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
|
|---|---|---|---|---|---|---|---|---|---|
a92f296892a7c836e23e84a1a69930dbb0660335
|
deployment_scripts/puppet/modules/lma_collector/files/plugins/decoders/rabbitmq.lua
|
deployment_scripts/puppet/modules/lma_collector/files/plugins/decoders/rabbitmq.lua
|
-- Copyright 2015 Mirantis, Inc.
--
-- 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 dt = require "date_time"
local l = require 'lpeg'
l.locale(l)
local patt = require 'patterns'
local utils = require 'lma_utils'
local msg = {
Timestamp = nil,
Type = 'log',
Hostname = nil,
Payload = nil,
Pid = nil,
Fields = nil,
Severity = nil,
}
-- RabbitMQ message logs are formatted like this:
-- =ERROR REPORT==== 2-Jan-2015::09:17:22 ===
-- Blabla
-- Blabla
--
local message = l.Cg(patt.Message / utils.chomp, "Message")
local severity = l.Cg(patt.SeverityLabel, "SeverityLabel")
local day = l.R"13" * l.R"09" + l.R"19"
local datetime = l.Cg(day, "day") * patt.dash * dt.date_mabbr * patt.dash * dt.date_fullyear *
"::" * dt.rfc3339_partial_time
local timestamp = l.Cg(l.Ct(datetime)/ dt.time_to_ns, "Timestamp")
local grammar = l.Ct("=" * severity * " REPORT==== " * timestamp * " ===" * l.P'\n' * message)
function process_message ()
local log = read_message("Payload")
local m = grammar:match(log)
if not m then
return -1
end
msg.Timestamp = m.Timestamp
msg.Payload = m.Message
msg.Severity = utils.label_to_severity_map[m.SeverityLabel] or 5
msg.Fields = {}
msg.Fields.severity_label = m.SeverityLabel
msg.Fields.programname = 'rabbitmq'
utils.inject_tags(msg)
inject_message(msg)
return 0
end
|
-- Copyright 2015 Mirantis, Inc.
--
-- 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 dt = require "date_time"
local l = require 'lpeg'
l.locale(l)
local patt = require 'patterns'
local utils = require 'lma_utils'
local msg = {
Timestamp = nil,
Type = 'log',
Hostname = nil,
Payload = nil,
Pid = nil,
Fields = nil,
Severity = nil,
}
-- RabbitMQ message logs are formatted like this:
-- =ERROR REPORT==== 2-Jan-2015::09:17:22 ===
-- Blabla
-- Blabla
--
local message = l.Cg(patt.Message / utils.chomp, "Message")
-- The token before 'REPORT' isn't standardized so it can be a valid severity
-- level as 'INFO' or 'ERROR' but also 'CRASH' or 'SUPERVISOR'.
local severity = l.Cg(l.R"AZ"^1, "SeverityLabel")
local day = l.R"13" * l.R"09" + l.R"19"
local datetime = l.Cg(day, "day") * patt.dash * dt.date_mabbr * patt.dash * dt.date_fullyear *
"::" * dt.rfc3339_partial_time
local timestamp = l.Cg(l.Ct(datetime)/ dt.time_to_ns, "Timestamp")
local grammar = l.Ct("=" * severity * " REPORT==== " * timestamp * " ===" * l.P'\n' * message)
function process_message ()
local log = read_message("Payload")
local m = grammar:match(log)
if not m then
return -1
end
msg.Timestamp = m.Timestamp
msg.Payload = m.Message
if utils.label_to_severity_map[m.SeverityLabel] then
msg.Severity = utils.label_to_severity_map[m.SeverityLabel]
elseif m.SeverityLabel == 'CRASH' then
msg.Severity = 2 -- CRITICAL
else
msg.Severity = 5 -- NOTICE
end
msg.Fields = {}
msg.Fields.severity_label = utils.severity_to_label_map[msg.Severity]
msg.Fields.programname = 'rabbitmq'
utils.inject_tags(msg)
inject_message(msg)
return 0
end
|
Fix parsing errors for RabbitMQ logs
|
Fix parsing errors for RabbitMQ logs
RabbitMQ logs aren't following good logging guidelines and in
particular, the severity level isn't always mapping the Syslog levels.
This change updates the Lua decoder to cope with these logs.
Change-Id: I4823d0775a5db51ffd1a2e9afe851833c02b420e
|
Lua
|
apache-2.0
|
stackforge/fuel-plugin-lma-collector,stackforge/fuel-plugin-lma-collector,stackforge/fuel-plugin-lma-collector,stackforge/fuel-plugin-lma-collector,stackforge/fuel-plugin-lma-collector
|
2d4cdce2c82b81c8ba05315644168a70d85a0ad4
|
luapress/util.lua
|
luapress/util.lua
|
-- Luapress
-- File: luapress/util.lua
-- Desc: internal Luapress utilities!
local os = os
local io = io
local print = print
local pairs = pairs
local error = error
local table = table
local string = string
local lfs = require('lfs')
local markdown = require('luapress.lib.markdown')
local template = require('luapress.template')
-- Writes a header/footer wrapped HTML file depending on the modification time
local function write_html(destination, object, object_type, templates, config)
-- Check modification time on post & destination files
local attributes = lfs.attributes(destination)
if not config.cache or not attributes or object.time > attributes.modification then
local output = template:process(templates.header, templates[object_type], templates.footer)
-- Write the file
f, err = io.open(destination, 'w')
if not f then error(err) end
local result, err = f:write(output)
if not result then error(err) end
f:close()
if config.print then print('\t' .. object.title) end
end
end
-- Returns the destination file given our config
local function ensure_destination(directory, object_type, link, config)
if config.link_dirs then
lfs.mkdir(directory .. '/build/' .. object_type .. '/' .. link)
return 'build/' .. object_type .. '/' .. link .. '/index.html'
end
return 'build/' .. object_type .. '/' .. link
end
-- Builds link list based on the currently active page
local function page_links(pages, active, config)
local output = ''
for k, page in pairs(pages) do
if not page.hidden then
if page.link == active then
output = output .. '<li class="active"><a href="' .. config.url .. '/pages/' .. active .. '">' .. page.title .. '</a></li>\n'
else
output = output .. '<li><a href="' .. config.url .. '/pages/' .. page.link .. '">' .. page.title .. '</a></li>\n'
end
end
end
return output
end
-- Load markdown files in a directory
local function load_markdowns(directory, config)
local outs = {}
for file in lfs.dir(directory) do
if file:sub(-3) == '.md' then
local title = file:sub(0, -4)
file = directory .. '/' .. file
local attributes = lfs.attributes(file)
-- Work out title
local link = title:gsub(' ', '_'):gsub('[^_aA-zZ0-9]', '')
if not config.link_dirs then link = link .. '.html' end
-- Get basic attributes
local out = {
link = link,
title = title,
content = '',
time = attributes.modification
}
-- Now read the file
local f, err = io.open(file, 'r')
if not f then error(err) end
local s, err = f:read('*a')
if not s then error(err) end
-- Set $=key's
s = s:gsub('%$=url', config.url)
-- Get $key=value's
for k, v, c, d in s:gmatch('%$([%w]+)=(.-)\n') do
out[k] = v
s = s:gsub('%$[%w]+=.-\n', '')
end
-- Excerpt
local start, _ = s:find('--MORE--')
if start then
-- Extract the excerpt
out.excerpt = markdown(s:sub(0, start - 1))
-- Replace the --MORE--
s = s:gsub('%-%-MORE%-%-', '<a id="more"> </a>')
end
out.content = markdown(s)
-- Date set?
if out.date then
local _, _, d, m, y = out.date:find('(%d+)%/(%d+)%/(%d+)')
out.time = os.time({day = d, month = m, year = y})
end
-- Insert to outs
table.insert(outs, out)
if config.print then print('\t' .. out.title) end
end
end
return outs
end
-- Loads lhtml templates in a directory
local function load_templates(directory)
local templates = {}
for file in lfs.dir(directory) do
if file:sub(-5) == 'lhtml' then
local tmpl_name = file:sub(0, -7)
file = directory .. '/' .. file
local f, err = io.open(file, 'r')
if not f then error(err) end
local s, err = f:read('*a')
if not s then error(err) end
f:close()
templates[tmpl_name] = s
end
end
-- RSS template
templates.rss = {
time = 0,
content = [[
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title><?=self:get('title') ?></title>
<link><?=self:get('url') ?></link>
<? for k, post in pairs(self:get('posts')) do ?>
<item>
<title><?=post.title ?></title>
<description><?=post.excerpt ?></description>
<link><?=self:get('url') ?>/posts/<?=post.link ?></link>
<guid><?=self:get('url') ?>/posts/<?=post.link ?></guid>
</item>
<? end ?>
</channel>
</rss>
]]}
return templates
end
-- Recursively duplicates a directory
local function copy_dir(directory, destination)
for file in lfs.dir(directory) do
if file ~= '.' and file ~= '..' then
local attributes = lfs.attributes(directory .. file) or {}
-- Directory?
if attributes.mode and attributes.mode == 'directory' then
-- Ensure destination directory
if not io.open(destination .. file, 'r') then
lfs.mkdir(destination .. file)
end
copy_dir(directory .. file .. '/', destination .. file .. '/')
end
-- File?
if attributes.mode and attributes.mode == 'file' then
local dest_attributes = lfs.attributes(destination .. file)
if not dest_attributes or attributes.modification > dest_attributes.modification then
-- Open current file
local f, err = io.open(directory .. file, 'r')
if not f then error(err) end
-- Read file
local s, err = f:read('*a')
if not s then error(err) end
f:close()
-- Open new file for creation
local f, err = io.open(destination .. file, 'w')
-- Write contents
local result, err = f:write(s)
if not result then error(err) end
f:close()
print('\t' .. destination .. file)
end
end
end
end
end
-- Export
return {
copy_dir = copy_dir,
load_templates = load_templates,
load_markdowns = load_markdowns,
page_links = page_links,
ensure_destination = ensure_destination,
write_html = write_html
}
|
-- Luapress
-- File: luapress/util.lua
-- Desc: internal Luapress utilities!
local os = os
local io = io
local print = print
local pairs = pairs
local error = error
local table = table
local string = string
local lfs = require('lfs')
local markdown = require('luapress.lib.markdown')
local template = require('luapress.template')
-- Writes a header/footer wrapped HTML file depending on the modification time
local function write_html(destination, object, object_type, templates, config)
-- Check modification time on post & destination files
local attributes = lfs.attributes(destination)
if not config.cache or not attributes or object.time > attributes.modification then
local output = template:process(templates.header, templates[object_type], templates.footer)
-- Write the file
f, err = io.open(destination, 'w')
if not f then error(err) end
local result, err = f:write(output)
if not result then error(err) end
f:close()
if config.print then print('\t' .. object.title) end
end
end
-- Returns the destination file given our config
local function ensure_destination(directory, object_type, link, config)
if config.link_dirs then
lfs.mkdir(directory .. '/build/' .. object_type .. '/' .. link)
return 'build/' .. object_type .. '/' .. link .. '/index.html'
end
return 'build/' .. object_type .. '/' .. link
end
-- Builds link list based on the currently active page
local function page_links(pages, active, config)
local output = ''
for k, page in pairs(pages) do
if not page.hidden then
if page.link == active then
output = output .. '<li class="active"><a href="' .. config.url .. '/pages/' .. active .. '">' .. page.title .. '</a></li>\n'
else
output = output .. '<li><a href="' .. config.url .. '/pages/' .. page.link .. '">' .. page.title .. '</a></li>\n'
end
end
end
return output
end
-- Load markdown files in a directory
local function load_markdowns(directory, config)
local outs = {}
for file in lfs.dir(directory) do
if file:sub(-3) == '.md' then
local title = file:sub(0, -4)
file = directory .. '/' .. file
local attributes = lfs.attributes(file)
-- Work out title
local link = title:gsub(' ', '_'):gsub('[^_aA-zZ0-9]', '')
if not config.link_dirs then link = link .. '.html' end
-- Get basic attributes
local out = {
link = link,
title = title,
content = '',
time = attributes.modification
}
-- Now read the file
local f, err = io.open(file, 'r')
if not f then error(err) end
local s, err = f:read('*a')
if not s then error(err) end
-- Set $=key's
s = s:gsub('%$=url', config.url)
-- Get $key=value's
for k, v, c, d in s:gmatch('%$([%w]+)=(.-)\n') do
out[k] = v
s = s:gsub('%$[%w]+=.-\n', '')
end
-- Excerpt
local start, _ = s:find('--MORE--')
if start then
-- Extract the excerpt
out.excerpt = markdown(s:sub(0, start - 1))
-- Replace the --MORE--
s = s:gsub('%-%-MORE%-%-', '<a id="more"> </a>')
end
out.content = markdown(s)
-- Date set?
if out.date then
local _, _, d, m, y = out.date:find('(%d+)%/(%d+)%/(%d+)')
out.time = os.time({day = d, month = m, year = y})
end
-- Insert to outs
table.insert(outs, out)
if config.print then print('\t' .. out.title) end
end
end
return outs
end
-- Loads lhtml templates in a directory
local function load_templates(directory)
local templates = {}
for file in lfs.dir(directory) do
if file:sub(-5) == 'lhtml' then
local tmpl_name = file:sub(0, -7)
file = directory .. '/' .. file
local f, err = io.open(file, 'r')
if not f then error(err) end
local s, err = f:read('*a')
if not s then error(err) end
f:close()
templates[tmpl_name] = s
end
end
-- RSS template
templates.rss = {
time = 0,
content = [[
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title><?=self:get('title') ?></title>
<link><?=self:get('url') ?></link>
<? for k, post in pairs(self:get('posts')) do ?>
<item>
<title><?=post.title ?></title>
<description><? if post.excerpt then ?><?=post.excerpt ?><? else ?><?=post.content ?><? end ?></description>
<link><?=self:get('url') ?>/posts/<?=post.link ?></link>
<guid><?=self:get('url') ?>/posts/<?=post.link ?></guid>
</item>
<? end ?>
</channel>
</rss>
]]}
return templates
end
-- Recursively duplicates a directory
local function copy_dir(directory, destination)
for file in lfs.dir(directory) do
if file ~= '.' and file ~= '..' then
local attributes = lfs.attributes(directory .. file) or {}
-- Directory?
if attributes.mode and attributes.mode == 'directory' then
-- Ensure destination directory
if not io.open(destination .. file, 'r') then
lfs.mkdir(destination .. file)
end
copy_dir(directory .. file .. '/', destination .. file .. '/')
end
-- File?
if attributes.mode and attributes.mode == 'file' then
local dest_attributes = lfs.attributes(destination .. file)
if not dest_attributes or attributes.modification > dest_attributes.modification then
-- Open current file
local f, err = io.open(directory .. file, 'r')
if not f then error(err) end
-- Read file
local s, err = f:read('*a')
if not s then error(err) end
f:close()
-- Open new file for creation
local f, err = io.open(destination .. file, 'w')
-- Write contents
local result, err = f:write(s)
if not result then error(err) end
f:close()
print('\t' .. destination .. file)
end
end
end
end
end
-- Export
return {
copy_dir = copy_dir,
load_templates = load_templates,
load_markdowns = load_markdowns,
page_links = page_links,
ensure_destination = ensure_destination,
write_html = write_html
}
|
Fix RSS template
|
Fix RSS template
|
Lua
|
mit
|
w-oertl/Luapress,Fizzadar/Luapress,w-oertl/Luapress,Fizzadar/Luapress
|
93d41a0fdbcc687805ebc1247dd806e5af5545c0
|
nyagos.d/suffix.lua
|
nyagos.d/suffix.lua
|
nyagos.suffixes={}
function suffix(suffix,cmdline)
local suffix=string.lower(suffix)
if string.sub(suffix,1,1)=='.' then
suffix = string.sub(suffix,2)
end
if not nyagos.suffixes[suffix] then
local orgpathext = nyagos.getenv("PATHEXT")
local newext="."..suffix
if not string.find(";"..orgpathext..";",";"..newext..";",1,true) then
nyagos.setenv("PATHEXT",orgpathext..";"..newext)
end
end
nyagos.suffixes[suffix]=cmdline
end
local org_filter=nyagos.argsfilter
nyagos.argsfilter = function(args)
if org_filter then
local args_ = org_filter(args)
if args_ then
args = args_
end
end
local path=nyagos.which(args[0])
if not path then
return
end
local m = string.match(path,"%.(%w+)$")
if not m then
return
end
local cmdline = nyagos.suffixes[ string.lower(m) ]
if not cmdline then
return
end
local newargs={}
for i=1,#cmdline do
newargs[i-1]=cmdline[i]
end
newargs[#cmdline] = path
for i=1,#args do
newargs[#cmdline+i] = args[i]
end
return newargs
end
alias{
suffix=function(args)
if #args < 2 then
print "Usage: suffix SUFFIX COMMAND"
else
suffix(args[1],args[2])
end
end
}
suffix(".pl",{"perl"})
suffix(".py",{"ipy"})
suffix(".rb",{"ruby"})
suffix(".lua",{"lua"})
suffix(".awk",{"awk","-f"})
suffix(".js",{"cscript","//nologo"})
suffix(".vbs",{"cscript","//nologo"})
suffix(".ps1",{"powershell","-file"})
|
nyagos.suffixes={}
function suffix(suffix,cmdline)
local suffix=string.lower(suffix)
if string.sub(suffix,1,1)=='.' then
suffix = string.sub(suffix,2)
end
if not nyagos.suffixes[suffix] then
local orgpathext = nyagos.getenv("PATHEXT")
local newext="."..suffix
if not string.find(";"..orgpathext..";",";"..newext..";",1,true) then
nyagos.setenv("PATHEXT",orgpathext..";"..newext)
end
end
nyagos.suffixes[suffix]=cmdline
end
local org_filter=nyagos.argsfilter
nyagos.argsfilter = function(args)
if org_filter then
local args_ = org_filter(args)
if args_ then
args = args_
end
end
local path=nyagos.which(args[0])
if not path then
return
end
local m = string.match(path,"%.(%w+)$")
if not m then
return
end
local cmdline = nyagos.suffixes[ string.lower(m) ]
if not cmdline then
return
end
local newargs={}
for i=1,#cmdline do
newargs[i-1]=cmdline[i]
end
newargs[#cmdline] = path
for i=1,#args do
newargs[#newargs+i] = args[i]
end
return newargs
end
alias{
suffix=function(args)
if #args < 2 then
print "Usage: suffix SUFFIX COMMAND"
else
local cmdline={}
for i=2,#args do
cmdline[#cmdline+1]=args[i]
end
suffix(args[1],cmdline)
end
end
}
suffix(".pl",{"perl"})
suffix(".py",{"ipy"})
suffix(".rb",{"ruby"})
suffix(".lua",{"lua"})
suffix(".awk",{"awk","-f"})
suffix(".js",{"cscript","//nologo"})
suffix(".vbs",{"cscript","//nologo"})
suffix(".ps1",{"powershell","-file"})
|
Fix built-in command suffix
|
Fix built-in command suffix
|
Lua
|
bsd-3-clause
|
tsuyoshicho/nyagos,kissthink/nyagos,kissthink/nyagos,tyochiai/nyagos,hattya/nyagos,zetamatta/nyagos,hattya/nyagos,nocd5/nyagos,hattya/nyagos,kissthink/nyagos
|
679d474d14257574b1fbe6613cf872161ce25c5f
|
MMOCoreORB/bin/scripts/screenplays/dungeon/death_watch_bunker/conversations/deathWatchBobaFettConvoHandler.lua
|
MMOCoreORB/bin/scripts/screenplays/dungeon/death_watch_bunker/conversations/deathWatchBobaFettConvoHandler.lua
|
local ObjectManager = require("managers.object.object_manager")
deathWatchBobaFettConvoHandler = Object:new { }
function deathWatchBobaFettConvoHandler:runScreenHandlers(conversationTemplate, conversingPlayer, conversingNPC, selectedOption, conversationScreen)
local screen = LuaConversationScreen(conversationScreen)
local screenID = screen:getScreenID()
if (screenID == "dont_give_opinions") then
CreatureObject(conversingPlayer):setScreenPlayState(1, "death_watch_bunker")
end
return conversationScreen
end
function deathWatchBobaFettConvoHandler:getInitialScreen(pPlayer, pNpc, pConversationTemplate)
local convoTemplate = LuaConversationTemplate(pConversationTemplate)
local pGhost = CreatureObject(pPlayer):getPlayerObject()
if (pGhost == nil) then
return convoTemplate:getScreen("intro")
end
if (PlayerObject(pGhost):hasScreenPlayState(1, "death_watch_bunker")) then
return convoTemplate:getScreen("back_again")
else
return convoTemplate:getScreen("intro")
end
end
function deathWatchBobaFettConvoHandler:getNextConversationScreen(pConversationTemplate, pPlayer, selectedOption, pConversingNpc)
local pConversationSession = CreatureObject(pPlayer):getConversationSession()
local pLastConversationScreen = nil
if (pConversationSession ~= nil) then
local conversationSession = LuaConversationSession(pConversationSession)
pLastConversationScreen = conversationSession:getLastConversationScreen()
end
local conversationTemplate = LuaConversationTemplate(pConversationTemplate)
if (pLastConversationScreen ~= nil) then
local lastConversationScreen = LuaConversationScreen(pLastConversationScreen)
local optionLink = lastConversationScreen:getOptionLink(selectedOption)
return conversationTemplate:getScreen(optionLink)
end
return self:getInitialScreen(pPlayer, pConversingNpc, pConversationTemplate)
end
|
local ObjectManager = require("managers.object.object_manager")
deathWatchBobaFettConvoHandler = Object:new { }
function deathWatchBobaFettConvoHandler:runScreenHandlers(conversationTemplate, conversingPlayer, conversingNPC, selectedOption, conversationScreen)
local screen = LuaConversationScreen(conversationScreen)
local screenID = screen:getScreenID()
if (screenID == "dont_give_opinions") then
CreatureObject(conversingPlayer):setScreenPlayState(1, "death_watch_bunker")
end
return conversationScreen
end
function deathWatchBobaFettConvoHandler:getInitialScreen(pPlayer, pNpc, pConversationTemplate)
local convoTemplate = LuaConversationTemplate(pConversationTemplate)
if (CreatureObject(pPlayer):hasScreenPlayState(1, "death_watch_bunker")) then
return convoTemplate:getScreen("back_again")
else
return convoTemplate:getScreen("intro")
end
end
function deathWatchBobaFettConvoHandler:getNextConversationScreen(pConversationTemplate, pPlayer, selectedOption, pConversingNpc)
local pConversationSession = CreatureObject(pPlayer):getConversationSession()
local pLastConversationScreen = nil
if (pConversationSession ~= nil) then
local conversationSession = LuaConversationSession(pConversationSession)
pLastConversationScreen = conversationSession:getLastConversationScreen()
end
local conversationTemplate = LuaConversationTemplate(pConversationTemplate)
if (pLastConversationScreen ~= nil) then
local lastConversationScreen = LuaConversationScreen(pLastConversationScreen)
local optionLink = lastConversationScreen:getOptionLink(selectedOption)
return conversationTemplate:getScreen(optionLink)
end
return self:getInitialScreen(pPlayer, pConversingNpc, pConversationTemplate)
end
|
[fixed] Bug in Boba Fett convo handler
|
[fixed] Bug in Boba Fett convo handler
Change-Id: I8bbd30ac6d01618de25f99c605e99c9d0a3f9118
|
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
|
1489b71b18f0f7565079f93cc1f15b76313adea8
|
nvim/lua/config/lspconfig.lua
|
nvim/lua/config/lspconfig.lua
|
-- NOTE: see https://github.com/neovim/nvim-lspconfig/blob/master/CONFIG.md
-- see also https://github.com/williamboman/nvim-lsp-installer
-- keymaps
local on_attach = function(client, bufnr)
local function buf_set_option(...)
vim.api.nvim_buf_set_option(bufnr, ...)
end
buf_set_option('omnifunc', 'v:lua.vim.lsp.omnifunc')
-- Mappings.
local opts = { noremap = true, silent = true }
vim.keymap.set('n', 'gD', '<Cmd>lua vim.lsp.buf.declaration()<CR>', opts)
vim.keymap.set('n', 'gd', '<Cmd>lua vim.lsp.buf.definition()<CR>', opts)
vim.keymap.set('n', 'gk', '<Cmd>lua vim.lsp.buf.hover()<CR>', opts)
vim.keymap.set('n', 'gi', '<cmd>lua vim.lsp.buf.implementation()<CR>', opts)
vim.keymap.set('n', '<C-k>', '<cmd>lua vim.lsp.buf.signature_help()<CR>', opts)
vim.keymap.set('n', '<space>wa', '<cmd>lua vim.lsp.buf.add_workspace_folder()<CR>', opts)
vim.keymap.set('n', '<space>wr', '<cmd>lua vim.lsp.buf.remove_workspace_folder()<CR>', opts)
vim.keymap.set('n', '<space>wl', '<cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<CR>', opts)
vim.keymap.set('n', '<space>D', '<cmd>lua vim.lsp.buf.type_definition()<CR>', opts)
vim.keymap.set('n', '<space>rn', '<cmd>lua vim.lsp.buf.rename()<CR>', opts)
vim.keymap.set('n', 'gr', '<cmd>lua vim.lsp.buf.references()<CR>', opts)
vim.keymap.set('n', '<space>e', '<cmd>lua vim.lsp.diagnostic.show_line_diagnostics()<CR>', opts)
vim.keymap.set('n', '[d', '<cmd>lua vim.lsp.diagnostic.goto_prev()<CR>', opts)
vim.keymap.set('n', ']d', '<cmd>lua vim.lsp.diagnostic.goto_next()<CR>', opts)
vim.keymap.set('n', '<space>q', '<cmd>lua vim.lsp.diagnostic.set_loclist()<CR>', opts)
-- Set some keybinds conditional on server capabilities
if client.resolved_capabilities.document_formatting then
vim.keymap.set('n', '<space>f', '<cmd>lua vim.lsp.buf.formatting()<CR>', opts)
elseif client.resolved_capabilities.document_range_formatting then
vim.keymap.set('n', '<space>f', '<cmd>lua vim.lsp.buf.range_formatting()<CR>', opts)
end
-- Set autocommands conditional on server_capabilities
if client.resolved_capabilities.document_highlight then
local lspDocumentHighlight = vim.api.nvim_create_augroup('lsp_document_highlight', { clear = false })
vim.api.nvim_create_autocmd('CursorHold', {
command = 'lua vim.lsp.buf.document_highlight()',
group = lspDocumentHighlight,
})
vim.api.nvim_create_autocmd('CursorMoved', {
command = 'lua vim.lsp.buf.clear_references()',
group = lspDocumentHighlight,
})
end
end
-- config that activates keymaps and enables snippet support
local function make_config()
local capabilities = vim.lsp.protocol.make_client_capabilities()
capabilities.textDocument.completion.completionItem.snippetSupport = true
capabilities.textDocument.foldingRange = {
dynamicRegistration = false,
lineFoldingOnly = true,
}
return {
-- enable snippet support
capabilities = capabilities,
-- map buffer local keybindings when the language server attaches
on_attach = on_attach,
}
end
local opts = make_config()
local lspconfig = require('lspconfig')
local function on_attach(client)
client.resolved_capabilities.document_formatting = false
client.resolved_capabilities.document_range_formatting = false
end
lspconfig.eslint.setup(opts)
lspconfig.tsserver.setup(opts)
lspconfig.stylelint_lsp.setup(opts)
vim.cmd([[ do User LspAttachBuffers ]])
|
-- NOTE: see https://github.com/neovim/nvim-lspconfig/blob/master/CONFIG.md
-- see also https://github.com/williamboman/nvim-lsp-installer
-- keymaps
local on_attach = function(client, bufnr)
local function buf_set_option(...)
vim.api.nvim_buf_set_option(bufnr, ...)
end
buf_set_option('omnifunc', 'v:lua.vim.lsp.omnifunc')
-- Mappings.
local opts = { noremap = true, silent = true }
vim.keymap.set('n', 'gD', '<Cmd>lua vim.lsp.buf.declaration()<CR>', opts)
vim.keymap.set('n', 'gd', '<Cmd>lua vim.lsp.buf.definition()<CR>', opts)
vim.keymap.set('n', 'gk', '<Cmd>lua vim.lsp.buf.hover()<CR>', opts)
vim.keymap.set('n', 'gi', '<cmd>lua vim.lsp.buf.implementation()<CR>', opts)
vim.keymap.set('n', '<C-k>', '<cmd>lua vim.lsp.buf.signature_help()<CR>', opts)
vim.keymap.set('n', '<space>wa', '<cmd>lua vim.lsp.buf.add_workspace_folder()<CR>', opts)
vim.keymap.set('n', '<space>wr', '<cmd>lua vim.lsp.buf.remove_workspace_folder()<CR>', opts)
vim.keymap.set('n', '<space>wl', '<cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<CR>', opts)
vim.keymap.set('n', '<space>D', '<cmd>lua vim.lsp.buf.type_definition()<CR>', opts)
vim.keymap.set('n', '<space>rn', '<cmd>lua vim.lsp.buf.rename()<CR>', opts)
vim.keymap.set('n', 'gr', '<cmd>lua vim.lsp.buf.references()<CR>', opts)
vim.keymap.set('n', '<space>e', '<cmd>lua vim.lsp.diagnostic.show_line_diagnostics()<CR>', opts)
vim.keymap.set('n', '[d', '<cmd>lua vim.lsp.diagnostic.goto_prev()<CR>', opts)
vim.keymap.set('n', ']d', '<cmd>lua vim.lsp.diagnostic.goto_next()<CR>', opts)
vim.keymap.set('n', '<space>q', '<cmd>lua vim.lsp.diagnostic.set_loclist()<CR>', opts)
-- Set some keybinds conditional on server capabilities
if client.resolved_capabilities.document_formatting then
vim.keymap.set('n', '<space>f', '<cmd>lua vim.lsp.buf.formatting()<CR>', opts)
elseif client.resolved_capabilities.document_range_formatting then
vim.keymap.set('n', '<space>f', '<cmd>lua vim.lsp.buf.range_formatting()<CR>', opts)
end
-- Set autocommands conditional on server_capabilities
if client.resolved_capabilities.document_highlight then
local lspDocumentHighlight = vim.api.nvim_create_augroup('lsp_document_highlight', { clear = false })
vim.api.nvim_create_autocmd('CursorHold', {
command = 'lua vim.lsp.buf.document_highlight()',
group = lspDocumentHighlight,
})
vim.api.nvim_create_autocmd('CursorMoved', {
command = 'lua vim.lsp.buf.clear_references()',
group = lspDocumentHighlight,
})
end
end
-- this is to avoid LSP formatting conflicts with null-ls... see https://github.com/jose-elias-alvarez/null-ls.nvim/wiki/Avoiding-LSP-formatting-conflicts
local function nullls_on_attach(client, bufnr, lang)
if lang == 'eslint' or lang == 'tsserver' or lang == 'stylelint_lsp' or lang == 'sumneko_lua' then
client.resolved_capabilities.document_formatting = false
client.resolved_capabilities.document_range_formatting = false
end
return on_attach(client, bufnr)
end
-- config that activates keymaps and enables snippet support
local function make_config(lang)
local capabilities = vim.lsp.protocol.make_client_capabilities()
capabilities.textDocument.completion.completionItem.snippetSupport = true
capabilities.textDocument.foldingRange = {
dynamicRegistration = false,
lineFoldingOnly = true,
}
local settings = {}
-- TODO: not sure how to just use luacheck for diagnostics instead... I'm still figuring out the latest with null-ls vs lspconfig vs nvim-lsp-installer
if lang == 'sumneko_lua' then
settings = {
Lua = {
diagnostics = {
globals = { 'vim' },
},
},
}
end
return {
-- enable snippet support
capabilities = capabilities,
settings = settings,
-- map buffer local keybindings when the language server attaches
on_attach = function(client, bufnr)
return nullls_on_attach(client, bufnr, lang)
end,
}
end
local lspconfig = require('lspconfig')
local servers = {
'sumneko_lua',
'eslint',
'tsserver',
'stylelint_lsp',
}
for _, server in pairs(servers) do
lspconfig[server].setup(make_config(server))
end
vim.cmd([[ do User LspAttachBuffers ]])
|
fix: issues with null-ls and nvim-lsp-installer
|
fix: issues with null-ls and nvim-lsp-installer
I'm still working my way through this... I'm beginning to wonder if
null-ls can handle most/all of the LSP things I'd want if I can
configure it as expected... but I'm not sure yet.
|
Lua
|
mit
|
drmohundro/dotfiles
|
d016334dc8ddfeb11fca3e34f3d693cb69212274
|
MMOCoreORB/bin/scripts/object/draft_schematic/clothing/clothing_belt_field_05_quest.lua
|
MMOCoreORB/bin/scripts/object/draft_schematic/clothing/clothing_belt_field_05_quest.lua
|
--Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_draft_schematic_clothing_clothing_belt_field_05_quest = object_draft_schematic_clothing_shared_clothing_belt_field_05_quest:new {
templateType = DRAFTSCHEMATIC,
customObjectName = "Demolitionist\'s Belt",
craftingToolTab = 8, -- (See DraftSchemticImplementation.h)
complexity = 16,
size = 1,
xpType = "crafting_clothing_general",
xp = 285,
assemblySkill = "clothing_assembly",
experimentingSkill = "clothing_experimentation",
customizationSkill = "clothing_customization",
customizationOptions = {2, 1},
customizationStringNames = {"/private/index_color_1", "/private/index_color_2"},
customizationDefaults = {0, 0},
ingredientTemplateNames = {"craft_clothing_ingredients_n", "craft_clothing_ingredients_n", "craft_clothing_ingredients_n"},
ingredientTitleNames = {"shell", "binding_and_reinforcement", "hardware"},
ingredientSlotType = {0, 0, 0},
resourceTypes = {"petrochem_inert", "metal", "iron"},
resourceQuantities = {50, 25, 35},
contribution = {100, 100, 100},
targetTemplate = "object/tangible/wearables/belt/belt_s05_quest.iff",
additionalTemplates = {
},
skillMods = {
{"grenade_assembly", 5},
{"grenade_experimentation", 5},
{"thrown_accuracy", 5},
},
}
ObjectTemplates:addTemplate(object_draft_schematic_clothing_clothing_belt_field_05_quest, "object/draft_schematic/clothing/clothing_belt_field_05_quest.iff")
|
--Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_draft_schematic_clothing_clothing_belt_field_05_quest = object_draft_schematic_clothing_shared_clothing_belt_field_05_quest:new {
templateType = DRAFTSCHEMATIC,
customObjectName = "Demolitionist\'s Belt",
craftingToolTab = 8, -- (See DraftSchemticImplementation.h)
complexity = 16,
size = 1,
xpType = "crafting_clothing_general",
xp = 285,
assemblySkill = "clothing_assembly",
experimentingSkill = "clothing_experimentation",
customizationSkill = "clothing_customization",
customizationOptions = {2, 1},
customizationStringNames = {"/private/index_color_1", "/private/index_color_2"},
customizationDefaults = {0, 0},
ingredientTemplateNames = {"craft_clothing_ingredients_n", "craft_clothing_ingredients_n", "craft_clothing_ingredients_n", "craft_clothing_ingredients_n", "craft_clothing_ingredients_n", "craft_clothing_ingredients_n"},
ingredientTitleNames = {"shell", "binding_and_reinforcement", "hardware", "grenade_fasteners", "explosives", "clasps"},
ingredientSlotType = {0, 0, 0, 0, 1, 1},
resourceTypes = {"petrochem_inert", "metal", "iron", "metal_nonferrous", "object/tangible/component/munition/shared_warhead_medium.iff", "object/tangible/component/clothing/shared_clasp_heavy_duty.iff"},
resourceQuantities = {50, 25, 35, 6, 6, 1},
contribution = {100, 100, 100, 100, 100, 100},
targetTemplate = "object/tangible/wearables/belt/belt_s05_quest.iff",
additionalTemplates = {
},
skillMods = {
{"grenade_assembly", 5},
{"grenade_experimentation", 5},
{"thrown_accuracy", 5},
},
}
ObjectTemplates:addTemplate(object_draft_schematic_clothing_clothing_belt_field_05_quest, "object/draft_schematic/clothing/clothing_belt_field_05_quest.iff")
|
(Unstable) [Fixed] Ingredient's for Demolitionist's Belt
|
(Unstable) [Fixed] Ingredient's for Demolitionist's Belt
git-svn-id: e4cf3396f21da4a5d638eecf7e3b4dd52b27f938@6016 c3d1530f-68f5-4bd0-87dc-8ef779617e40
|
Lua
|
agpl-3.0
|
lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo
|
d51cf644e0c9b5f9cc11e929b374e9b76a5233b1
|
Hydra/sample_config.lua
|
Hydra/sample_config.lua
|
hydra.alert("Hydra sample config loaded", 1.5)
-- save the time when updates are checked
function checkforupdates()
updates.check()
settings.set('lastcheckedupdates', os.time())
end
-- show a helpful menu
menu.show(function()
local updatetitles = {[true] = "Install Update", [false] = "Check for Update..."}
local updatefns = {[true] = updates.install, [false] = checkforupdates}
local hasupdate = (updates.newversion ~= nil)
return {
{title = "Reload Config", fn = hydra.reload},
{title = "-"},
{title = "About", fn = hydra.showabout},
{title = updatetitles[hasupdate], fn = updatefns[hasupdate]},
{title = "Quit Hydra", fn = os.exit},
}
end)
-- move the window to the right a bit, and make it a little shorter
hotkey.new({"cmd", "ctrl", "alt"}, "J", function()
local win = window.focusedwindow()
local frame = win:frame()
frame.x = frame.x + 10
frame.h = frame.h - 10
win:setframe(frame)
end):enable()
-- open a repl
hotkey.bind({"cmd", "ctrl", "alt"}, "R", hydra.repl())
-- show available updates
local function showupdate()
os.execute('open https://github.com/sdegutis/Hydra/releases')
end
-- what to do when an udpate is checked
function updates.available(available)
if available then
notify.show("Hydra update available", "", "Click here to see the changelog and maybe even install it", "showupdate")
else
hydra.alert("No update available.")
end
end
-- Uncomment this if you want Hydra to make sure it launches at login
-- autolaunch.set(true)
-- check for updates every week
timer.new(timer.weeks(1), checkforupdates):start()
notify.register("showupdate", showupdate)
-- if this is your first time running Hydra, you're launching it more than a week later, check now
local lastcheckedupdates = settings.get('lastcheckedupdates')
if lastcheckedupdates == nil or lastcheckedupdates <= os.time() - timer.days(7) then
checkforupdates()
end
|
hydra.alert("Hydra sample config loaded", 1.5)
-- open a repl
hotkey.bind({"cmd", "ctrl", "alt"}, "R", hydra.repl)
-- save the time when updates are checked
function checkforupdates()
updates.check()
settings.set('lastcheckedupdates', os.time())
end
-- show a helpful menu
menu.show(function()
local updatetitles = {[true] = "Install Update", [false] = "Check for Update..."}
local updatefns = {[true] = updates.install, [false] = checkforupdates}
local hasupdate = (updates.newversion ~= nil)
return {
{title = "Reload Config", fn = hydra.reload},
{title = "-"},
{title = "About", fn = hydra.showabout},
{title = updatetitles[hasupdate], fn = updatefns[hasupdate]},
{title = "Quit Hydra", fn = os.exit},
}
end)
-- move the window to the right a bit, and make it a little shorter
hotkey.new({"cmd", "ctrl", "alt"}, "J", function()
local win = window.focusedwindow()
local frame = win:frame()
frame.x = frame.x + 10
frame.h = frame.h - 10
win:setframe(frame)
end):enable()
-- show available updates
local function showupdate()
os.execute('open https://github.com/sdegutis/Hydra/releases')
end
-- what to do when an udpate is checked
function updates.available(available)
if available then
notify.show("Hydra update available", "", "Click here to see the changelog and maybe even install it", "showupdate")
else
hydra.alert("No update available.")
end
end
-- Uncomment this if you want Hydra to make sure it launches at login
-- autolaunch.set(true)
-- check for updates every week
timer.new(timer.weeks(1), checkforupdates):start()
notify.register("showupdate", showupdate)
-- if this is your first time running Hydra, you're launching it more than a week later, check now
local lastcheckedupdates = settings.get('lastcheckedupdates')
if lastcheckedupdates == nil or lastcheckedupdates <= os.time() - timer.days(7) then
checkforupdates()
end
|
Move the REPL higher in the sample config, and fix it.
|
Move the REPL higher in the sample config, and fix it.
|
Lua
|
mit
|
wsmith323/hammerspoon,lowne/hammerspoon,chrisjbray/hammerspoon,TimVonsee/hammerspoon,Stimim/hammerspoon,hypebeast/hammerspoon,wsmith323/hammerspoon,bradparks/hammerspoon,peterhajas/hammerspoon,trishume/hammerspoon,Hammerspoon/hammerspoon,junkblocker/hammerspoon,lowne/hammerspoon,TimVonsee/hammerspoon,wvierber/hammerspoon,TimVonsee/hammerspoon,Stimim/hammerspoon,knl/hammerspoon,junkblocker/hammerspoon,knl/hammerspoon,emoses/hammerspoon,zzamboni/hammerspoon,latenitefilms/hammerspoon,asmagill/hammerspoon,Habbie/hammerspoon,joehanchoi/hammerspoon,tmandry/hammerspoon,wsmith323/hammerspoon,kkamdooong/hammerspoon,TimVonsee/hammerspoon,joehanchoi/hammerspoon,dopcn/hammerspoon,Hammerspoon/hammerspoon,Stimim/hammerspoon,chrisjbray/hammerspoon,chrisjbray/hammerspoon,lowne/hammerspoon,tmandry/hammerspoon,chrisjbray/hammerspoon,asmagill/hammerspoon,asmagill/hammerspoon,trishume/hammerspoon,Hammerspoon/hammerspoon,bradparks/hammerspoon,heptal/hammerspoon,asmagill/hammerspoon,peterhajas/hammerspoon,wvierber/hammerspoon,nkgm/hammerspoon,Hammerspoon/hammerspoon,heptal/hammerspoon,CommandPost/CommandPost-App,asmagill/hammerspoon,knl/hammerspoon,Habbie/hammerspoon,peterhajas/hammerspoon,dopcn/hammerspoon,junkblocker/hammerspoon,CommandPost/CommandPost-App,Hammerspoon/hammerspoon,joehanchoi/hammerspoon,chrisjbray/hammerspoon,hypebeast/hammerspoon,zzamboni/hammerspoon,peterhajas/hammerspoon,latenitefilms/hammerspoon,emoses/hammerspoon,knu/hammerspoon,CommandPost/CommandPost-App,ocurr/hammerspoon,CommandPost/CommandPost-App,TimVonsee/hammerspoon,dopcn/hammerspoon,junkblocker/hammerspoon,joehanchoi/hammerspoon,knl/hammerspoon,bradparks/hammerspoon,nkgm/hammerspoon,latenitefilms/hammerspoon,cmsj/hammerspoon,ocurr/hammerspoon,latenitefilms/hammerspoon,wvierber/hammerspoon,joehanchoi/hammerspoon,knu/hammerspoon,wsmith323/hammerspoon,kkamdooong/hammerspoon,lowne/hammerspoon,bradparks/hammerspoon,ocurr/hammerspoon,cmsj/hammerspoon,CommandPost/CommandPost-App,nkgm/hammerspoon,knu/hammerspoon,cmsj/hammerspoon,cmsj/hammerspoon,junkblocker/hammerspoon,emoses/hammerspoon,hypebeast/hammerspoon,cmsj/hammerspoon,emoses/hammerspoon,trishume/hammerspoon,Habbie/hammerspoon,Habbie/hammerspoon,kkamdooong/hammerspoon,knl/hammerspoon,lowne/hammerspoon,knu/hammerspoon,chrisjbray/hammerspoon,kkamdooong/hammerspoon,wvierber/hammerspoon,ocurr/hammerspoon,heptal/hammerspoon,bradparks/hammerspoon,wsmith323/hammerspoon,zzamboni/hammerspoon,heptal/hammerspoon,tmandry/hammerspoon,Habbie/hammerspoon,hypebeast/hammerspoon,Habbie/hammerspoon,nkgm/hammerspoon,Stimim/hammerspoon,Hammerspoon/hammerspoon,latenitefilms/hammerspoon,CommandPost/CommandPost-App,asmagill/hammerspoon,zzamboni/hammerspoon,peterhajas/hammerspoon,ocurr/hammerspoon,heptal/hammerspoon,hypebeast/hammerspoon,nkgm/hammerspoon,emoses/hammerspoon,zzamboni/hammerspoon,dopcn/hammerspoon,Stimim/hammerspoon,latenitefilms/hammerspoon,kkamdooong/hammerspoon,dopcn/hammerspoon,knu/hammerspoon,knu/hammerspoon,cmsj/hammerspoon,wvierber/hammerspoon,zzamboni/hammerspoon
|
a801ef55cfff3552f2f5c54c09d85172a90c4bb8
|
src/plugins/lua/multimap.lua
|
src/plugins/lua/multimap.lua
|
-- Multimap is rspamd module designed to define and operate with different maps
local rules = {}
function split(str, delim, maxNb)
-- Eliminate bad cases...
if string.find(str, delim) == nil then
return { str }
end
if maxNb == nil or maxNb < 1 then
maxNb = 0 -- No limit
end
local result = {}
local pat = "(.-)" .. delim .. "()"
local nb = 0
local lastPos
for part, pos in string.gfind(str, pat) do
nb = nb + 1
result[nb] = part
lastPos = pos
if nb == maxNb then break end
end
-- Handle the last field
if nb ~= maxNb then
result[nb + 1] = string.sub(str, lastPos)
end
return result
end
function rbl_cb(task, to_resolve, results, err)
if results then
local _,_,o4,o3,o2,o1,in_rbl = string.find(to_resolve, '(%d+)%.(%d+)%.(%d+)%.(%d+)%.(.+)')
-- Get corresponding rule by rbl name
for _,rule in ipairs(rules) do
if rule['map'] == in_rbl then
task:insert_result(rule['symbol'], 1, rule['map'])
return
end
end
end
end
function check_multimap(task)
for _,rule in ipairs(rules) do
if rule['type'] == 'ip' then
local ip = task:get_from_ip_num()
if rule['ips']:get_key(ip) then
task:insert_result(rule['symbol'], 1)
end
elseif rule['type'] == 'header' then
local headers = task:get_message():get_header(rule['header'])
if headers then
for _,hv in ipairs(headers) do
if rule['pattern'] then
-- extract a part from header
local _,_,ext = string.find(hv, rule['pattern'])
if ext then
if rule['hash']:get_key(ext) then
task:insert_result(rule['symbol'], 1)
end
end
else
if rule['hash']:get_key(hv) then
task:insert_result(rule['symbol'], 1)
end
end
end
end
elseif rule['type'] == 'dnsbl' then
local ip = task:get_from_ip()
if ip then
local _,_,o1,o2,o3,o4 = string.find(ip, '(%d+)%.(%d+)%.(%d+)%.(%d+)')
local rbl_str = o4 .. '.' .. o3 .. '.' .. o2 .. '.' .. o1 .. '.' .. rule['map']
task:resolve_dns_a(rbl_str, 'rbl_cb')
end
end
end
end
function add_rule(params)
local newrule = {
type = 'ip',
header = nil,
pattern = nil,
map = nil,
symbol = nil
}
for _,param in ipairs(params) do
local _,_,name,value = string.find(param, '(%w+)%s*=%s*(.+)')
if not name or not value then
rspamd_logger:err('invalid rule: '..param)
return 0
end
if name == 'type' then
if value == 'ip' then
newrule['type'] = 'ip'
elseif value == 'dnsbl' then
newrule['type'] = 'dnsbl'
elseif value == 'header' then
newrule['type'] = 'header'
else
rspamd_logger:err('invalid rule type: '.. value)
return 0
end
elseif name == 'header' then
newrule['header'] = value
elseif name == 'pattern' then
newrule['pattern'] = value
elseif name == 'map' then
newrule['map'] = value
elseif name == 'symbol' then
newrule['symbol'] = value
else
rspamd_logger:err('invalid rule option: '.. name)
return 0
end
end
if not newrule['symbol'] or not newrule['map'] or not newrule['symbol'] then
rspamd_logger:err('incomplete rule')
return 0
end
if newrule['type'] == 'ip' then
newrule['ips'] = rspamd_config:add_radix_map (newrule['map'])
elseif newrule['type'] == 'header' then
newrule['hash'] = rspamd_config:add_hash_map (newrule['map'])
end
table.insert(rules, newrule)
return 1
end
local opts = rspamd_config:get_all_opt('multimap')
if opts then
local strrules = opts['rule']
if strrules then
for _,value in ipairs(strrules) do
local params = split(value, ',')
if not add_rule (params) then
rspamd_logger:err('cannot add rule: "'..value..'"')
end
end
end
end
if table.maxn(rules) > 0 then
-- add fake symbol to check all maps inside a single callback
rspamd_config:register_symbol('MULTIMAP', 1.0, 'check_multimap')
end
|
-- Multimap is rspamd module designed to define and operate with different maps
local rules = {}
function split(str, delim, maxNb)
-- Eliminate bad cases...
if string.find(str, delim) == nil then
return { str }
end
if maxNb == nil or maxNb < 1 then
maxNb = 0 -- No limit
end
local result = {}
local pat = "(.-)" .. delim .. "()"
local nb = 0
local lastPos
for part, pos in string.gfind(str, pat) do
nb = nb + 1
result[nb] = part
lastPos = pos
if nb == maxNb then break end
end
-- Handle the last field
if nb ~= maxNb then
result[nb + 1] = string.sub(str, lastPos)
end
return result
end
function rbl_cb(task, to_resolve, results, err)
if results then
local _,_,o4,o3,o2,o1,in_rbl = string.find(to_resolve, '(%d+)%.(%d+)%.(%d+)%.(%d+)%.(.+)')
-- Get corresponding rule by rbl name
for _,rule in ipairs(rules) do
if rule['map'] == in_rbl then
task:insert_result(rule['symbol'], 1, rule['map'])
return
end
end
end
end
function check_multimap(task)
for _,rule in ipairs(rules) do
if rule['type'] == 'ip' then
local ip = task:get_from_ip_num()
if rule['ips']:get_key(ip) then
task:insert_result(rule['symbol'], 1)
end
elseif rule['type'] == 'header' then
local headers = task:get_message():get_header(rule['header'])
if headers then
for _,hv in ipairs(headers) do
if rule['pattern'] then
-- extract a part from header
local _,_,ext = string.find(hv, rule['pattern'])
if ext then
if rule['hash']:get_key(ext) then
task:insert_result(rule['symbol'], 1)
end
end
else
if rule['hash']:get_key(hv) then
task:insert_result(rule['symbol'], 1)
end
end
end
end
elseif rule['type'] == 'dnsbl' then
local ip = task:get_from_ip()
if ip then
local _,_,o1,o2,o3,o4 = string.find(ip, '(%d+)%.(%d+)%.(%d+)%.(%d+)')
local rbl_str = o4 .. '.' .. o3 .. '.' .. o2 .. '.' .. o1 .. '.' .. rule['map']
task:resolve_dns_a(rbl_str, 'rbl_cb')
end
end
end
end
function add_rule(params)
local newrule = {
type = 'ip',
header = nil,
pattern = nil,
map = nil,
symbol = nil
}
for _,param in ipairs(params) do
local _,_,name,value = string.find(param, '(%w+)%s*=%s*(.+)')
if not name or not value then
rspamd_logger:err('invalid rule: '..param)
return 0
end
if name == 'type' then
if value == 'ip' then
newrule['type'] = 'ip'
elseif value == 'dnsbl' then
newrule['type'] = 'dnsbl'
elseif value == 'header' then
newrule['type'] = 'header'
else
rspamd_logger:err('invalid rule type: '.. value)
return 0
end
elseif name == 'header' then
newrule['header'] = value
elseif name == 'pattern' then
newrule['pattern'] = value
elseif name == 'map' then
newrule['map'] = value
elseif name == 'symbol' then
newrule['symbol'] = value
else
rspamd_logger:err('invalid rule option: '.. name)
return 0
end
end
if not newrule['symbol'] or not newrule['map'] or not newrule['symbol'] then
rspamd_logger:err('incomplete rule')
return 0
end
if newrule['type'] == 'ip' then
newrule['ips'] = rspamd_config:add_radix_map (newrule['map'])
elseif newrule['type'] == 'header' then
newrule['hash'] = rspamd_config:add_hash_map (newrule['map'])
end
table.insert(rules, newrule)
return 1
end
local opts = rspamd_config:get_all_opt('multimap')
if opts then
local strrules = opts['rule']
if strrules then
if type(strrules) == 'array' then
for _,value in ipairs(strrules) do
local params = split(value, ',')
if not add_rule (params) then
rspamd_logger:err('cannot add rule: "'..value..'"')
end
end
elseif type(strrules) == 'string' then
local params = split(strrules, ',')
if not add_rule (params) then
rspamd_logger:err('cannot add rule: "'..strrules..'"')
end
end
end
end
if table.maxn(rules) > 0 then
-- add fake symbol to check all maps inside a single callback
rspamd_config:register_symbol('MULTIMAP', 1.0, 'check_multimap')
end
|
Fix multimap module if there is only one rule for it.
|
Fix multimap module if there is only one rule for it.
|
Lua
|
apache-2.0
|
andrejzverev/rspamd,minaevmike/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,minaevmike/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,amohanta/rspamd,minaevmike/rspamd,amohanta/rspamd,awhitesong/rspamd,andrejzverev/rspamd,minaevmike/rspamd,amohanta/rspamd,andrejzverev/rspamd,amohanta/rspamd,awhitesong/rspamd,dark-al/rspamd,andrejzverev/rspamd,awhitesong/rspamd,minaevmike/rspamd,andrejzverev/rspamd,dark-al/rspamd,AlexeySa/rspamd,minaevmike/rspamd,dark-al/rspamd,AlexeySa/rspamd,dark-al/rspamd,minaevmike/rspamd,minaevmike/rspamd,awhitesong/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,dark-al/rspamd,amohanta/rspamd,minaevmike/rspamd
|
a201220ec1736c3db1cb94190b3e7fd6faffee24
|
src/api-umbrella/utils/elasticsearch.lua
|
src/api-umbrella/utils/elasticsearch.lua
|
local http = require "resty.http"
local is_empty = require("pl.types").is_empty
local json_decode = require("cjson").decode
local json_encode = require "api-umbrella.utils.json_encode"
local server = config["elasticsearch"]["_first_server"]
local _M = {}
function _M.query(path, options)
local httpc = http.new()
if not options then
options = {}
end
options["path"] = path
if not options["headers"] then
options["headers"] = {}
end
if server["userinfo"] and not options["headers"]["Authorization"] then
options["headers"]["Authorization"] = "Basic " .. ngx.encode_base64(server["userinfo"])
end
if options["body"] and type(options["body"]) == "table" then
options["body"] = json_encode(options["body"])
if not options["headers"]["Content-Type"] then
options["headers"]["Content-Type"] = "application/json"
end
end
local connect_ok, connect_err = httpc:connect(server["host"], server["port"])
if connect_err then
httpc:close()
return nil, "elasticsearch connect error: " .. (connect_err or "")
end
local res, err = httpc:request(options)
if err then
httpc:close()
return nil, "elasticsearch request error: " .. (err or "")
end
local body, body_err = res:read_body()
if body_err then
httpc:close()
return nil, "elasticsearch read body error: " .. (body_err or "")
end
local keepalive_ok, keepalive_err = httpc:set_keepalive()
if not keepalive_ok then
httpc:close()
return nil, "elasticsearch keepalive error: " .. (keepalive_err or "")
end
if res.status >= 400 and res.status ~= 404 then
return nil, "Unsuccessful response: " .. (body or "")
else
if res.headers["Content-Type"] and string.sub(res.headers["Content-Type"], 1, 16) == "application/json" and not is_empty(body) then
res["body_json"] = json_decode(body)
end
return res
end
end
return _M
|
local http = require "resty.http"
local is_empty = require("pl.types").is_empty
local json_decode = require("cjson").decode
local json_encode = require "api-umbrella.utils.json_encode"
local server = config["elasticsearch"]["_first_server"]
local _M = {}
function _M.query(path, options)
local httpc = http.new()
if not options then
options = {}
end
options["path"] = path
if not options["headers"] then
options["headers"] = {}
end
if server["userinfo"] and not options["headers"]["Authorization"] then
options["headers"]["Authorization"] = "Basic " .. ngx.encode_base64(server["userinfo"])
end
if options["body"] and type(options["body"]) == "table" then
options["body"] = json_encode(options["body"])
if not options["headers"]["Content-Type"] then
options["headers"]["Content-Type"] = "application/json"
end
end
local connect_ok, connect_err = httpc:connect(server["host"], server["port"])
if not connect_ok then
httpc:close()
return nil, "elasticsearch connect error: " .. (connect_err or "")
end
if server["scheme"] == "https" then
local ssl_ok, ssl_err = httpc:ssl_handshake(nil, server["host"], true)
if not ssl_ok then
httpc:close()
return nil, "elasticsearch ssl handshake error: " .. (ssl_err or "")
end
end
local res, err = httpc:request(options)
if err then
httpc:close()
return nil, "elasticsearch request error: " .. (err or "")
end
local body, body_err = res:read_body()
if body_err then
httpc:close()
return nil, "elasticsearch read body error: " .. (body_err or "")
end
res["body"] = body
local keepalive_ok, keepalive_err = httpc:set_keepalive()
if not keepalive_ok then
httpc:close()
return nil, "elasticsearch keepalive error: " .. (keepalive_err or "")
end
if res.status >= 400 and res.status ~= 404 then
return nil, "Unsuccessful response: " .. (body or "")
else
if res.headers["Content-Type"] and string.sub(res.headers["Content-Type"], 1, 16) == "application/json" and not is_empty(body) then
res["body_json"] = json_decode(body)
end
return res
end
end
return _M
|
Fix elasticsearch connections over SSL.
|
Fix elasticsearch connections over SSL.
|
Lua
|
mit
|
NREL/api-umbrella,NREL/api-umbrella,NREL/api-umbrella,NREL/api-umbrella
|
94417bcafc1454cad27dda535a69b7d0a5eb8942
|
mods/mobs/npc.lua
|
mods/mobs/npc.lua
|
-- Npc by TenPlus1
mobs.npc_drops = { "farming:meat", "farming:donut", "farming:bread", "default:apple", "default:sapling", "default:junglesapling",
"shields:shield_enhanced_wood", "3d_armor:chestplate_cactus", "3d_armor:boots_bronze",
"default:sword_steel", "default:sword_gold", "default:pick_steel", "default:shovel_steel",
"default:bronze_ingot", "bucket:bucket_water" }
mobs.npc_max_hp = 20
mobs:register_mob("mobs:npc", {
-- animal, monster, npc
type = "npc",
-- aggressive, deals 6 damage to player/monster when hit
passive = false,
damage = 6, -- 4 damages if tamed
attack_type = "dogfight",
attacks_monsters = true,
-- health & armor
hp_min = 20, hp_max = 20, armor = 100,
-- textures and model
collisionbox = {-0.35,-1.0,-0.35, 0.35,0.8,0.35},
visual = "mesh",
mesh = "character.b3d",
drawtype = "front",
textures = {
{"mobs_npc.png"},
},
visual_size = {x=1, y=1},
-- sounds
makes_footstep_sound = true,
sounds = {},
-- speed and jump
walk_velocity = 3,
run_velocity = 3,
jump = true,
-- drops wood and chance of apples when dead
drops = {
{name = "default:wood",
chance = 1, min = 1, max = 3},
{name = "default:apple",
chance = 2, min = 1, max = 2},
{name = "default:axe_stone",
chance = 3, min = 1, max = 1},
{name = "maptools:silver_coin",
chance = 10, min = 1, max = 1,},
},
-- damaged by
water_damage = 0,
lava_damage = 2,
light_damage = 0,
-- follow diamond
follow = "default:diamond",
view_range = 16,
-- set owner and order
owner = "",
order = "follow",
-- model animation
animation = {
speed_normal = 30, speed_run = 30,
stand_start = 0, stand_end = 79,
walk_start = 168, walk_end = 187,
run_start = 168, run_end = 187,
punch_start = 200, punch_end = 219,
},
-- right clicking with "cooked meat" or "bread" will give npc more health
on_rightclick = function(self, clicker)
local item = clicker:get_wielded_item()
local name = clicker:get_player_name()
if not name then return end
-- heal npc
if item:get_name() == "mobs:meat"
or item:get_name() == "farming:bread" then
-- feed and add health
local hp = self.object:get_hp()
-- return if full health
if hp >= self.hp_max then
minetest.chat_send_player(name, "NPC at full health.")
return
end
hp = hp + 4 -- add restorative value
-- new health shouldn't exceed self.hp_max
if hp > self.hp_max then hp = self.hp_max end
self.object:set_hp(hp)
-- take item
if not minetest.setting_getbool("creative_mode") then
item:take_item()
clicker:set_wielded_item(item)
end
-- right clicking with gold lump drops random item from mobs.npc_drops
elseif item:get_name() == "default:gold_lump" then
if not minetest.setting_getbool("creative_mode") then
item:take_item()
clicker:set_wielded_item(item)
end
local pos = self.object:getpos()
pos.y = pos.y + 0.5
minetest.add_item(pos, {name = mobs.npc_drops[math.random(1,#mobs.npc_drops)]})
elseif item:get_name() == "default:diamond" then
self.diamond_count = (self.diamond_count or 0) + 1
if not minetest.setting_getbool("creative_mode") then
item:take_item()
end
-- pick up npc
elseif item:get_name() == "mobs:magic_lasso"
and clicker:is_player()
and clicker:get_inventory()
and self.child == false
and clicker:get_inventory():room_for_item("main", "mobs:npc") then
-- pick up if owner
if self.owner == name then
clicker:get_inventory():add_item("main", "mobs:npc")
self.object:remove()
item:add_wear(3000) -- 22 uses
clicker:set_wielded_item(item)
-- cannot pick up if not tamed
elseif not self.owner or self.owner == "" then
minetest.chat_send_player(name, "Not tamed!")
-- cannot pick up if not tamed
elseif self.owner ~= name then
minetest.chat_send_player(name, "Not owner!")
end
if self.diamond_count < 4 then return end
else
-- if owner switch between follow and stand
if self.owner and self.owner == clicker:get_player_name() then
self.damages = 4
if self.order == "follow" then
self.order = "stand"
else
self.order = "follow"
end
else
self.owner = clicker:get_player_name()
end
end
end,
})
-- spawning enable for now
mobs:register_spawn("mobs:npc", {"default:dirt_with_grass"}, 20, -1, 20000, 1, 31000)
-- register spawn egg
mobs:register_egg("mobs:npc", "Npc", "default_brick.png", 1)
|
-- Npc by TenPlus1
mobs.npc_drops = { "farming:meat", "farming:donut", "farming:bread", "default:apple", "default:sapling", "default:junglesapling",
"shields:shield_enhanced_wood", "3d_armor:chestplate_cactus", "3d_armor:boots_bronze",
"default:sword_steel", "default:sword_gold", "default:pick_steel", "default:shovel_steel",
"default:bronze_ingot", "bucket:bucket_water" }
mobs.npc_max_hp = 20
mobs:register_mob("mobs:npc", {
-- animal, monster, npc
type = "npc",
-- aggressive, deals 6 damage to player/monster when hit
passive = false,
damage = 6, -- 4 damages if tamed
attack_type = "dogfight",
attacks_monsters = true,
-- health & armor
hp_min = 20, hp_max = 20, armor = 100,
-- textures and model
collisionbox = {-0.35,-1.0,-0.35, 0.35,0.8,0.35},
visual = "mesh",
mesh = "character.b3d",
drawtype = "front",
textures = {
{"mobs_npc.png"},
},
visual_size = {x=1, y=1},
-- sounds
makes_footstep_sound = true,
sounds = {},
-- speed and jump
walk_velocity = 3,
run_velocity = 3,
jump = true,
-- drops wood and chance of apples when dead
drops = {
{name = "default:wood",
chance = 1, min = 1, max = 3},
{name = "default:apple",
chance = 2, min = 1, max = 2},
{name = "default:axe_stone",
chance = 3, min = 1, max = 1},
{name = "maptools:silver_coin",
chance = 10, min = 1, max = 1,},
},
-- damaged by
water_damage = 0,
lava_damage = 2,
light_damage = 0,
-- follow diamond
follow = "default:diamond",
view_range = 16,
-- set owner and order
owner = "",
order = "follow",
-- model animation
animation = {
speed_normal = 30, speed_run = 30,
stand_start = 0, stand_end = 79,
walk_start = 168, walk_end = 187,
run_start = 168, run_end = 187,
punch_start = 200, punch_end = 219,
},
-- right clicking with "cooked meat" or "bread" will give npc more health
on_rightclick = function(self, clicker)
local item = clicker:get_wielded_item()
local name = clicker:get_player_name()
if not name then return end
-- heal npc
if item:get_name() == "mobs:meat"
or item:get_name() == "farming:bread" then
-- feed and add health
local hp = self.object:get_hp()
-- return if full health
if hp >= self.hp_max then
minetest.chat_send_player(name, "NPC at full health.")
return
end
hp = hp + 4 -- add restorative value
-- new health shouldn't exceed self.hp_max
if hp > self.hp_max then hp = self.hp_max end
self.object:set_hp(hp)
-- take item
if not minetest.setting_getbool("creative_mode") then
item:take_item()
clicker:set_wielded_item(item)
end
-- right clicking with gold lump drops random item from mobs.npc_drops
elseif item:get_name() == "default:gold_lump" then
if not minetest.setting_getbool("creative_mode") then
item:take_item()
clicker:set_wielded_item(item)
end
local pos = self.object:getpos()
pos.y = pos.y + 0.5
minetest.add_item(pos, {name = mobs.npc_drops[math.random(1,#mobs.npc_drops)]})
elseif item:get_name() == "default:diamond" then
self.diamond_count = (self.diamond_count or 0) + 1
if not minetest.setting_getbool("creative_mode") then
item:take_item()
end
if self.diamond_count < 4 then return end
-- if owner switch between follow and stand
if self.owner and self.owner == clicker:get_player_name() then
self.damages = 4
if self.order == "follow" then
self.order = "stand"
else
self.order = "follow"
end
else
self.owner = clicker:get_player_name()
end
-- pick up npc
elseif item:get_name() == "mobs:magic_lasso"
and clicker:is_player()
and clicker:get_inventory()
and self.child == false
and clicker:get_inventory():room_for_item("main", "mobs:npc") then
-- pick up if owner
if self.owner == name then
clicker:get_inventory():add_item("main", "mobs:npc")
self.object:remove()
item:add_wear(3000) -- 22 uses
clicker:set_wielded_item(item)
-- cannot pick up if not tamed
elseif not self.owner or self.owner == "" then
minetest.chat_send_player(name, "Not tamed!")
-- cannot pick up if not tamed
elseif self.owner ~= name then
minetest.chat_send_player(name, "Not owner!")
end
end
end,
})
-- spawning enable for now
mobs:register_spawn("mobs:npc", {"default:dirt_with_grass"}, 20, -1, 20000, 1, 31000)
-- register spawn egg
mobs:register_egg("mobs:npc", "Npc", "default_brick.png", 1)
|
Fixed NPC taming - Moved code wrongly placed after a merge (last May 22). Solves part of #94
|
Fixed NPC taming
- Moved code wrongly placed after a merge (last May 22). Solves part of #94
|
Lua
|
unlicense
|
sys4-fr/server-minetestforfun,MinetestForFun/server-minetestforfun,Coethium/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Coethium/server-minetestforfun,paly2/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,MinetestForFun/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Coethium/server-minetestforfun
|
703774516e84f00dfbea58584bb2d5e913f25fda
|
luasrc/tests/testMultipleRequire.lua
|
luasrc/tests/testMultipleRequire.lua
|
require "totem"
local myTests = {}
local tester = totem.Tester()
function myTests.test_beta()
local N = 10000
local oneRequire = torch.Tensor(N)
local multipleRequire = torch.Tensor(N)
-- Call N in one go
require 'randomkit'
state = torch.getRNGState()
randomkit.gauss(oneRequire)
-- call N with require between each another
torch.setRNGState(state)
local multipleRequire = torch.Tensor(N)
for i=1,N do
require 'randomkit'
multipleRequire[i] = randomkit.gauss()
end
-- The streams should be the same
tester:assertTensorEq(oneRequire, multipleRequire, 1e-16, 'Multiple require changed the stream')
end
tester:add(myTests)
return tester:run()
|
require "totem"
local myTests = {}
local tester = totem.Tester()
function myTests.test_beta()
local N = 10000
local oneRequire = torch.Tensor(N)
local multipleRequire = torch.Tensor(N)
-- Call N in one go
require 'randomkit'
local ignored = torch.rand(1)
local state = torch.getRNGState()
randomkit.gauss(oneRequire)
-- call N with require between each another
torch.setRNGState(state)
local multipleRequire = torch.Tensor(N)
for i=1,N do
require 'randomkit'
multipleRequire[i] = randomkit.gauss()
end
-- The streams should be the same
tester:assertTensorEq(oneRequire, multipleRequire, 1e-16, 'Multiple require changed the stream')
end
tester:add(myTests)
return tester:run()
|
Fix test with serial dependency.
|
Fix test with serial dependency.
- torch.rand() must be called before torch.getRNGState() to ensure the
state is defined.
- Added a 'local' keyword.
|
Lua
|
bsd-3-clause
|
fastturtle/torch-randomkit,deepmind/torch-randomkit,fastturtle/torch-randomkit,deepmind/torch-randomkit
|
0ee0a869ee36d31c9399f9e6c122e2ae0e86cbb9
|
BtEvaluator/SensorManager.lua
|
BtEvaluator/SensorManager.lua
|
--- .
-- @module SensorManager
WG.SensorManager = WG.SensorManager or (function()
local Utils = VFS.Include(LUAUI_DIRNAME .. "Widgets/BtUtils/root.lua", nil, VFS.RAW_FIRST)
local Logger = Utils.Debug.Logger
local globalData = {} -- table that is persistent among all sensors (and all groups) and can be used to store persistent data
local System = Utils.Debug.clone(loadstring("return _G")().System)
setmetatable(System, {
-- enumerate all tables from Utils or other sources beside System that should be available in sensors
__index = {
Global = globalData,
Logger = Logger,
System = System,
}
})
local getGameFrame = Spring.GetGameFrame;
local SENSOR_DIRNAME = LUAUI_DIRNAME .. "Widgets/BtSensors/"
local sensors = {}
local sensorEnvironmentMetatable = {
__metatable = false,
__index = System
};
local smInstance = {}
local SensorManager = {}
function SensorManager.loadSensor(name)
local file = SENSOR_DIRNAME .. name .. ".lua"
if(not VFS.FileExists(file))then
return nil
end
local sensorCode = "--[[" .. name .. "]] " .. VFS.LoadFile(file)
local sensorFunction, msg = loadstring(sensorCode)
if(not sensorFunction)then
Logger.error("sensors", "Failed to compile sensor '", name, "' due to error: ", msg)
return nil
end
local function sensorConstructor(groupSensorManager, group)
group.length = #group
local sensorEnvironment = setmetatable({
units = group,
Sensors = groupSensorManager,
}, sensorEnvironmentMetatable)
setfenv(sensorFunction, sensorEnvironment)
local success, evaluator = pcall(sensorFunction)
if(not success)then
Logger.error("sensors", "Creation of sensor '", name ,"' instance failed: ", evaluator)
return nil
end
local info = {}
if(sensorEnvironment.getInfo)then
info = sensorEnvironment.getInfo()
end
info.period = info.period or 0
local lastExecutionFrame = nil
local lastResult = nil
local lastPeriod = 0
return function(...)
local currentFrame = getGameFrame()
if(lastExecutionFrame == nil or currentFrame - lastExecutionFrame > lastPeriod)then
local success, lastResult, period = pcall(evaluator, ...)
if(not success)then
Logger.error("sensors", "Evaluation of sensor '", name ,"' failed: ", lastResult[2])
return
end
lastPeriod = period or info.period
lastExecutionFrame = currentFrame
end
return unpack(lastResult)
end
end
return sensorConstructor
end
function SensorManager.forGroup(group)
local manager = group[smInstance];
if(not manager)then
manager = setmetatable({
Reload = function(self)
local keys = {}
for k, _ in pairs(self) do
if(k ~= "Reload")then
table.insert(keys, k)
end
end
for _, k in ipairs(keys) do
rawset(self, k, nil)
end
SensorManager.reload()
end
}, {
__index = function(self, key)
local sensorConstructor = sensors[key]
if(not sensorConstructor)then
sensorConstructor = SensorManager.loadSensor(key)
if(not sensorConstructor)then
return nil
end
sensors[key] = sensorConstructor
end
local sensor = sensorConstructor(manager, group);
if(not sensor)then
sensors[key] = nil
return nil
end
rawset(self, key, sensor)
return sensor
end,
})
group[smInstance] = manager
end
return manager
end
function SensorManager.getAvailableSensors()
local sensorFiles = Utils.dirList(SENSOR_DIRNAME, "*.lua")
for i, v in ipairs(sensorFiles) do
sensorFiles[i] = v:sub(1, v:len() - 4)
end
return sensorFiles
end
function SensorManager.reload()
globalData = {}
getmetatable(System).__index.Global = globalData
sensors = {}
managerForGroup = {}
end
return SensorManager
end)()
return WG.SensorManager
|
--- .
-- @module SensorManager
WG.SensorManager = WG.SensorManager or (function()
local Utils = VFS.Include(LUAUI_DIRNAME .. "Widgets/BtUtils/root.lua", nil, VFS.RAW_FIRST)
local Logger = Utils.Debug.Logger
local globalData = {} -- table that is persistent among all sensors (and all groups) and can be used to store persistent data
local System = Utils.Debug.clone(loadstring("return _G")().System)
setmetatable(System, {
-- enumerate all tables from Utils or other sources beside System that should be available in sensors
__index = {
Global = globalData,
Logger = Logger,
System = System,
}
})
local getGameFrame = Spring.GetGameFrame;
local SENSOR_DIRNAME = LUAUI_DIRNAME .. "Widgets/BtSensors/"
local sensors = {}
local sensorEnvironmentMetatable = {
__metatable = false,
__index = System
};
local smInstance = {}
local SensorManager = {}
function SensorManager.loadSensor(name)
local file = SENSOR_DIRNAME .. name .. ".lua"
if(not VFS.FileExists(file))then
return nil
end
local sensorCode = "--[[" .. name .. "]] " .. VFS.LoadFile(file)
local sensorFunction, msg = loadstring(sensorCode)
if(not sensorFunction)then
Logger.error("sensors", "Failed to compile sensor '", name, "' due to error: ", msg)
return nil
end
local function sensorConstructor(groupSensorManager, group)
group.length = #group
local sensorEnvironment = setmetatable({
units = group,
Sensors = groupSensorManager,
}, sensorEnvironmentMetatable)
setfenv(sensorFunction, sensorEnvironment)
local success, evaluator = pcall(sensorFunction)
if(not success)then
Logger.error("sensors", "Creation of sensor '", name ,"' instance failed: ", evaluator)
return nil
end
local info = {}
if(sensorEnvironment.getInfo)then
info = sensorEnvironment.getInfo()
end
info.period = info.period or 0
local lastExecutionFrame = nil
local lastResult = nil
local lastPeriod = 0
return function(...)
local currentFrame = getGameFrame()
if(lastExecutionFrame == nil or currentFrame - lastExecutionFrame > lastPeriod)then
local success, result, period = pcall(evaluator, ...)
if(not success)then
Logger.error("sensors", "Evaluation of sensor '", name ,"' failed: ", lastResult[2])
return
end
lastResult = result
lastPeriod = period or info.period
lastExecutionFrame = currentFrame
end
return lastResult
end
end
return sensorConstructor
end
function SensorManager.forGroup(group)
local manager = group[smInstance];
if(not manager)then
manager = setmetatable({
Reload = function(self)
local keys = {}
for k, _ in pairs(self) do
if(k ~= "Reload")then
table.insert(keys, k)
end
end
for _, k in ipairs(keys) do
rawset(self, k, nil)
end
SensorManager.reload()
end
}, {
__index = function(self, key)
local sensorConstructor = sensors[key]
if(not sensorConstructor)then
sensorConstructor = SensorManager.loadSensor(key)
if(not sensorConstructor)then
return nil
end
sensors[key] = sensorConstructor
end
local sensor = sensorConstructor(manager, group);
if(not sensor)then
sensors[key] = nil
return nil
end
rawset(self, key, sensor)
return sensor
end,
})
group[smInstance] = manager
end
return manager
end
function SensorManager.getAvailableSensors()
local sensorFiles = Utils.dirList(SENSOR_DIRNAME, "*.lua")
for i, v in ipairs(sensorFiles) do
sensorFiles[i] = v:sub(1, v:len() - 4)
end
return sensorFiles
end
function SensorManager.reload()
globalData = {}
getmetatable(System).__index.Global = globalData
sensors = {}
managerForGroup = {}
end
return SensorManager
end)()
return WG.SensorManager
|
Fix of sensors return value refactor
|
Fix of sensors return value refactor
|
Lua
|
mit
|
MartinFrancu/BETS
|
7fc2b38bc54bcd96bd5a8da4a207ad84c4ec904f
|
mod_lastlog/mod_lastlog.lua
|
mod_lastlog/mod_lastlog.lua
|
local datamanager = require "util.datamanager";
local time = os.time;
local log_ip = module:get_option_boolean("lastlog_ip_address", false);
local host = module.host;
module:hook("authentication-success", function(event)
local session = event.session;
if session.username then
datamanager.store(session.username, host, "lastlog", {
event = "login";
timestamp = time(),
ip = log_ip and session.ip or nil,
});
end
end);
module:hook("resource-unbind", function(event)
local session = event.session;
if session.username then
datamanager.store(session.username, host, "lastlog", {
event = "logout";
timestamp = time(),
ip = log_ip and session.ip or nil,
});
end
end);
function module.command(arg)
local user, host = require "util.jid".prepped_split(table.remove(arg, 1));
local lastlog = datamanager.load(user, host, "lastlog") or {};
print("Last login: "..(lastlog and os.date("%Y-%m-%d %H:%m:%s", datamanager.load(user, host, "lastlog").time) or "<unknown>"));
if lastlog.ip then
print("IP address: "..lastlog.ip);
end
return 0;
end
|
local datamanager = require "util.datamanager";
local time = os.time;
local log_ip = module:get_option_boolean("lastlog_ip_address", false);
local host = module.host;
module:hook("authentication-success", function(event)
local session = event.session;
if session.username then
datamanager.store(session.username, host, "lastlog", {
event = "login";
timestamp = time(),
ip = log_ip and session.ip or nil,
});
end
end);
module:hook("resource-unbind", function(event)
local session = event.session;
if session.username then
datamanager.store(session.username, host, "lastlog", {
event = "logout";
timestamp = time(),
ip = log_ip and session.ip or nil,
});
end
end);
function module.command(arg)
local user, host = require "util.jid".prepped_split(table.remove(arg, 1));
require"core.storagemanager".initialize_host(host);
local lastlog = assert(datamanager.load(user, host, "lastlog"));
if lastlog then
print(("Last %s: %s"):format(lastlog.event or "login",
lastlog.timestamp and os.date("%Y-%m-%d %H:%M:%S", lastlog.timestamp) or "<unknown>"));
if lastlog.ip then
print("IP address: "..lastlog.ip);
end
else
print("No record found");
end
return 0;
end
|
mod_lastlog: Fix command
|
mod_lastlog: Fix command
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
b8c7b4af5af07ac6f7eb62dd136116d3366f17c7
|
testserver/npc/base/talk.lua
|
testserver/npc/base/talk.lua
|
--- Base NPC script for talking NPCs
--
-- This script offers all functions needed to get NPCs to talk.
--
-- Author: Martin Karing
require("base.common")
require("base.messages")
require("base.class")
require("npc.base.basic")
require("npc.base.responses")
module("npc.base.talk", package.seeall)
talkNPC = base.class.class(function(self, rootNPC)
if (rootNPC == nil or not rootNPC:is_a(npc.base.basic.baseNPC)) then
return;
end;
self["_parent"] = rootNPC;
self["_entry"] = nil;
self["_cycleText"] = nil;
self["_state"] = 0;
self["_saidNumber"] = nil;
self["_nextCycleText"] = -1;
end);
function talkNPC:addCycleText(germanText, englishText)
if (self._cycleText == nil) then
self._cycleText = base.messages.Messages();
self._parent:addCycle(self);
end;
self._cycleText:addMessage(germanText, englishText);
end;
function talkNPC:addTalkingEntry(newEntry)
if (newEntry == nil or not newEntry:is_a(talkNPCEntry)) then
return;
end;
if (self._entry == nil) then
self._parent:addRecvText(self);
self._entry = {};
end;
newEntry:setParent(self);
table.insert(self._entry, newEntry);
end;
function talkNPC:receiveText(npcChar, texttype, player, text)
local result = false;
table.foreach(self._entry, function(_, entry)
if entry:checkEntry(npcChar, texttype, player, text) then
entry:execute(npcChar, player);
result = true;
return true;
end;
end);
return result;
end;
function talkNPC:nextCycle(npcChar, counter)
if (counter >= self._nextCycleText) then
self._nextCycleText = math.random(1200, 3600); --2 to 6 minutes
local german, english = self._cycleText:getRandomMessage();
do
local textType, text = _get_text_and_talktype(german);
npcChar:talkLanguage(textType, Player.german, text);
end;
do
local textType, text = _get_text_and_talktype(english);
npcChar:talkLanguage(textType, Player.english, text);
end;
else
self._nextCycleText = self._nextCycleText - counter;
end;
return self._nextCycleText;
end;
talkNPCEntry = base.class.class(function(self)
self["_trigger"] = {};
self["_conditions"] = {};
self["_responses"] = {};
self["_responseProcessors"] = {};
self["_responsesCount"] = 0;
self["_consequences"] = {};
self["_parent"] = nil;
end);
function talkNPCEntry:addTrigger(text)
if (text == nil or type(text) ~= "string") then
return;
end;
text = string.lower(text);
text = string.gsub(text,'([ ]+)',' .*'); -- replace all spaces by " .*"
table.insert(self._trigger, text);
end;
function talkNPCEntry:setParent(npc)
local updateFkt = function(_, value)
value:setNPC(npc);
end;
table.foreach(self._conditions, updateFkt);
table.foreach(self._consequences, updateFkt);
self._parent = npc;
end;
function talkNPCEntry:addCondition(condition)
if (condition == nil or not condition:is_a(npc.base.condition.condition.condition)) then
return;
end;
table.insert(self._conditions, condition);
if (self._parent ~= nil) then
condition:setNPC(self._parent);
end;
end;
function talkNPCEntry:addResponse(text)
if (text == nil or type(text) ~= "string") then
return;
end;
table.insert(self._responses, text);
self._responsesCount = self._responsesCount + 1;
for _, processor in pairs(npc.base.responses.processorList) do
if processor:check(text) then
if (self._responseProcessors[self._responsesCount] == nil) then
self._responseProcessors[self._responsesCount] = {};
end;
table.insert(self._responseProcessors[self._responsesCount], processor)
end;
end;
end;
function talkNPCEntry:addConsequence(consequence)
if (consequence == nil or not consequence:is_a(npc.base.consequence.consequence.consequence)) then
return;
end;
table.insert(self._consequences, consequence);
if (self._parent ~= nil) then
consequence:setNPC(self._parent);
end;
end;
function talkNPCEntry:checkEntry(npcChar, texttype, player, text)
for _1, pattern in pairs(self._trigger) do
local a, _2, number = string.find(text, pattern);
self._saidNumber = number;
if (a ~= nil) then
local conditionsResult = true;
for _3, condition in pairs(self._conditions) do
if not condition:check(npcChar, texttype, player) then
conditionsResult = false;
break;
end;
end;
if conditionsResult then
return true;
end;
end;
end;
end;
function talkNPCEntry:execute(npcChar, player)
if (self._responsesCount > 0) then
local selectedResponse = math.random(1, self._responsesCount);
local responseText = self._responses[selectedResponse];
local responseProcessors = self._responseProcessors[selectedResponse];
if (responseProcessors ~= nil) then
for _, processor in pairs(responseProcessors) do
responseText = processor:process(player, self._parent, npcChar, responseText);
end;
end;
local textType, text = _get_text_and_talktype(responseText);
npcChar:talk(textType, text);
end;
table.foreach(self._consequences, function(_, consequence)
if consequence then
consequence:perform(npcChar, player);
end;
end);
end;
function _get_text_and_talktype(text)
if (string.find(text, "[#/]w") == 1) then
return Character.whisper, string.gsub(responseText, "[#/]w%s*", "", 1);
elseif (string.find(text, "[#/]s") == 1) then
return Character.yell, string.gsub(responseText, "[#/]s%s*", "", 1);
elseif (string.find(text, "[#/]o") == 1) then
return Character.whisper, responseText;
else
return Character.say, responseText;
end;
end;
function _set_value(value)
if (type(value) == "function") then
return value, 2;
elseif (value == "%NUMBER") then
return nil, 1;
else
return tonumber(value), 0;
end;
end;
function _get_value(npc, value, type)
if (type == 2) then
return value(npc._saidNumber);
elseif (type == 1) then
return npc._saidNumber;
elseif (type == 0) then
return value;
else
return 0;
end;
end;
|
--- Base NPC script for talking NPCs
--
-- This script offers all functions needed to get NPCs to talk.
--
-- Author: Martin Karing
require("base.common")
require("base.messages")
require("base.class")
require("npc.base.basic")
require("npc.base.responses")
module("npc.base.talk", package.seeall)
talkNPC = base.class.class(function(self, rootNPC)
if (rootNPC == nil or not rootNPC:is_a(npc.base.basic.baseNPC)) then
return;
end;
self["_parent"] = rootNPC;
self["_entry"] = nil;
self["_cycleText"] = nil;
self["_state"] = 0;
self["_saidNumber"] = nil;
self["_nextCycleText"] = -1;
end);
function talkNPC:addCycleText(germanText, englishText)
if (self._cycleText == nil) then
self._cycleText = base.messages.Messages();
self._parent:addCycle(self);
end;
self._cycleText:addMessage(germanText, englishText);
end;
function talkNPC:addTalkingEntry(newEntry)
if (newEntry == nil or not newEntry:is_a(talkNPCEntry)) then
return;
end;
if (self._entry == nil) then
self._parent:addRecvText(self);
self._entry = {};
end;
newEntry:setParent(self);
table.insert(self._entry, newEntry);
end;
function talkNPC:receiveText(npcChar, texttype, player, text)
local result = false;
table.foreach(self._entry, function(_, entry)
if entry:checkEntry(npcChar, texttype, player, text) then
entry:execute(npcChar, player);
result = true;
return true;
end;
end);
return result;
end;
function talkNPC:nextCycle(npcChar, counter)
if (counter >= self._nextCycleText) then
self._nextCycleText = math.random(1200, 3600); --2 to 6 minutes
local german, english = self._cycleText:getRandomMessage();
do
local textType, text = _get_text_and_talktype(german);
npcChar:talkLanguage(textType, Player.german, text);
end;
do
local textType, text = _get_text_and_talktype(english);
npcChar:talkLanguage(textType, Player.english, text);
end;
else
self._nextCycleText = self._nextCycleText - counter;
end;
return self._nextCycleText;
end;
talkNPCEntry = base.class.class(function(self)
self["_trigger"] = {};
self["_conditions"] = {};
self["_responses"] = {};
self["_responseProcessors"] = {};
self["_responsesCount"] = 0;
self["_consequences"] = {};
self["_parent"] = nil;
end);
function talkNPCEntry:addTrigger(text)
if (text == nil or type(text) ~= "string") then
return;
end;
text = string.lower(text);
text = string.gsub(text,'([ ]+)',' .*'); -- replace all spaces by " .*"
table.insert(self._trigger, text);
end;
function talkNPCEntry:setParent(npc)
local updateFkt = function(_, value)
value:setNPC(npc);
end;
table.foreach(self._conditions, updateFkt);
table.foreach(self._consequences, updateFkt);
self._parent = npc;
end;
function talkNPCEntry:addCondition(condition)
if (condition == nil or not condition:is_a(npc.base.condition.condition.condition)) then
return;
end;
table.insert(self._conditions, condition);
if (self._parent ~= nil) then
condition:setNPC(self._parent);
end;
end;
function talkNPCEntry:addResponse(text)
if (text == nil or type(text) ~= "string") then
return;
end;
table.insert(self._responses, text);
self._responsesCount = self._responsesCount + 1;
for _, processor in pairs(npc.base.responses.processorList) do
if processor:check(text) then
if (self._responseProcessors[self._responsesCount] == nil) then
self._responseProcessors[self._responsesCount] = {};
end;
table.insert(self._responseProcessors[self._responsesCount], processor)
end;
end;
end;
function talkNPCEntry:addConsequence(consequence)
if (consequence == nil or not consequence:is_a(npc.base.consequence.consequence.consequence)) then
return;
end;
table.insert(self._consequences, consequence);
if (self._parent ~= nil) then
consequence:setNPC(self._parent);
end;
end;
function talkNPCEntry:checkEntry(npcChar, texttype, player, text)
for _1, pattern in pairs(self._trigger) do
local a, _2, number = string.find(text, pattern);
self._saidNumber = number;
if (a ~= nil) then
local conditionsResult = true;
for _3, condition in pairs(self._conditions) do
if not condition:check(npcChar, texttype, player) then
conditionsResult = false;
break;
end;
end;
if conditionsResult then
return true;
end;
end;
end;
end;
function talkNPCEntry:execute(npcChar, player)
if (self._responsesCount > 0) then
local selectedResponse = math.random(1, self._responsesCount);
local responseText = self._responses[selectedResponse];
local responseProcessors = self._responseProcessors[selectedResponse];
if (responseProcessors ~= nil) then
for _, processor in pairs(responseProcessors) do
responseText = processor:process(player, self._parent, npcChar, responseText);
end;
end;
local textType, text = _get_text_and_talktype(responseText);
npcChar:talk(textType, text);
end;
table.foreach(self._consequences, function(_, consequence)
if consequence then
consequence:perform(npcChar, player);
end;
end);
end;
function _get_text_and_talktype(text)
if (string.find(text, "[#/]w") == 1) then
return Character.whisper, string.gsub(text, "[#/]w%s*", "", 1);
elseif (string.find(text, "[#/]s") == 1) then
return Character.yell, string.gsub(text, "[#/]s%s*", "", 1);
elseif (string.find(text, "[#/]o") == 1) then
return Character.whisper, text;
else
return Character.say, text;
end;
end;
function _set_value(value)
if (type(value) == "function") then
return value, 2;
elseif (value == "%NUMBER") then
return nil, 1;
else
return tonumber(value), 0;
end;
end;
function _get_value(npc, value, type)
if (type == 2) then
return value(npc._saidNumber);
elseif (type == 1) then
return npc._saidNumber;
elseif (type == 0) then
return value;
else
return 0;
end;
end;
|
Fixed bug in easyNPC talking
|
Fixed bug in easyNPC talking
|
Lua
|
agpl-3.0
|
Baylamon/Illarion-Content,vilarion/Illarion-Content,KayMD/Illarion-Content,LaFamiglia/Illarion-Content,Illarion-eV/Illarion-Content
|
bb16266f3c5b923741e064e84973a09eb02378e8
|
MMOCoreORB/bin/scripts/mobile/lair/dathomir_reptilian_ancient_flyer_flock_neutral_none.lua
|
MMOCoreORB/bin/scripts/mobile/lair/dathomir_reptilian_ancient_flyer_flock_neutral_none.lua
|
dathomir_reptilian_ancient_flyer_flock_neutral_none = Lair:new {
mobiles = {{"ancient_reptilian_flier", 0}},
spawnLimit = 15,
buildingsVeryEasy = {"object/tangible/lair/reptilian_flyer/lair_reptilian_flyer_mountain.iff"},
buildingsEasy = {"object/tangible/lair/reptilian_flyer/lair_reptilian_flyer_mountain.iff"},
buildingsMedium = {"object/tangible/lair/reptilian_flyer/lair_reptilian_flyer_mountain.iff"},
buildingsHard = {"object/tangible/lair/reptilian_flyer/lair_reptilian_flyer_mountain.iff"},
buildingsVeryHard = {"object/tangible/lair/reptilian_flyer/lair_reptilian_flyer_mountain.iff"},
}
addLairTemplate("dathomir_reptilian_ancient_flyer_flock_neutral_none", dathomir_reptilian_ancient_flyer_flock_neutral_none)
|
dathomir_reptilian_ancient_flyer_flock_neutral_none = Lair:new {
mobiles = {{"ancient_reptilian_flier", 0}},
spawnLimit = 15,
buildingsVeryEasy = {"object/tangible/lair/base/poi_all_lair_rocks_large_fog_green.iff"},
buildingsEasy = {"object/tangible/lair/base/poi_all_lair_rocks_large_fog_green.iff"},
buildingsMedium = {"object/tangible/lair/base/poi_all_lair_rocks_large_fog_green.iff"},
buildingsHard = {"object/tangible/lair/base/poi_all_lair_rocks_large_fog_green.iff"},
buildingsVeryHard = {"object/tangible/lair/base/poi_all_lair_rocks_large_fog_green.iff"},
}
addLairTemplate("dathomir_reptilian_ancient_flyer_flock_neutral_none", dathomir_reptilian_ancient_flyer_flock_neutral_none)
|
[fixed] ancient reptilian flier lair. Mantis #4706
|
[fixed] ancient reptilian flier lair. Mantis #4706
Change-Id: Ic33b8f041a28e282d9541fa9ae9c39fa58cc9482
|
Lua
|
agpl-3.0
|
lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo
|
cdd169fc777c6cd2c0335969d02064844aa104bc
|
xmake/platforms/linux/load.lua
|
xmake/platforms/linux/load.lua
|
--!A cross-platform build utility based on Lua
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2018, TBOOX Open Source Group.
--
-- @author ruki
-- @file load.lua
--
-- imports
import("core.project.config")
-- load it
function main()
-- cross toolchains?
if config.get("cross") or config.get("toolchains") or config.get("sdk") then
-- init linkdirs and includedirs
local sdkdir = config.get("sdk")
if sdkdir then
_g.includedirs = {path.join(sdkdir, "include")}
_g.linkdirs = {path.join(sdkdir, "lib")}
end
-- ok
return _g
end
-- init flags for architecture
local archflags = nil
local arch = config.get("arch")
if arch then
if arch == "x86_64" then archflags = "-m64"
elseif arch == "i386" then archflags = "-m32"
end
end
-- init flags for c/c++
_g.cxflags = { archflags, "-I/usr/local/include", "-I/usr/include" }
_g.ldflags = { archflags, "-L/usr/local/lib", "-L/usr/lib" }
_g.shflags = { archflags, "-L/usr/local/lib", "-L/usr/lib" }
-- init flags for objc/c++ (with _g.ldflags and _g.shflags)
_g.mxflags = { archflags }
-- init flags for asm (with _g.ldflags and _g.shflags)
_g.asflags = { archflags }
-- init flags for golang
_g["gc-ldflags"] = {}
-- init flags for dlang
local dc_archs = { i386 = "-m32", x86_64 = "-m64" }
_g.dcflags = { dc_archs[arch] or "" }
_g["dc-shflags"] = { dc_archs[arch] or "" }
_g["dc-ldflags"] = { dc_archs[arch] or "" }
-- init flags for rust
_g["rc-shflags"] = {}
_g["rc-ldflags"] = {}
-- init flags for cuda
local cu_archs = { i386 = "-m32 -Xcompiler -arch -Xcompiler -m32", x86_64 = "-m64 -Xcompiler -arch -Xcompiler -m64" }
_g.cuflags = {cu_archs[arch] or ""}
_g["cu-shflags"] = {cu_archs[arch] or ""}
_g["cu-ldflags"] = {cu_archs[arch] or ""}
local cuda_dir = config.get("cuda_dir")
if cuda_dir then
table.insert(_g.cuflags, "-I" .. os.args(path.join(cuda_dir, "include")))
table.insert(_g["cu-ldflags"], "-L" .. os.args(path.join(cuda_dir, "lib")))
table.insert(_g["cu-shflags"], "-L" .. os.args(path.join(cuda_dir, "lib")))
table.insert(_g["cu-ldflags"], "-Wl,-rpath=" .. os.args(path.join(cuda_dir, "lib")))
end
-- ok
return _g
end
|
--!A cross-platform build utility based on Lua
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2018, TBOOX Open Source Group.
--
-- @author ruki
-- @file load.lua
--
-- imports
import("core.project.config")
-- load it
function main()
-- cross toolchains?
if config.get("cross") or config.get("toolchains") or config.get("sdk") then
-- init linkdirs and includedirs
local sdkdir = config.get("sdk")
if sdkdir then
_g.includedirs = {path.join(sdkdir, "include")}
_g.linkdirs = {path.join(sdkdir, "lib")}
end
-- ok
return _g
end
-- init flags for architecture
local archflags = nil
local arch = config.get("arch")
if arch then
if arch == "x86_64" then archflags = "-m64"
elseif arch == "i386" then archflags = "-m32"
end
end
-- init flags for c/c++
_g.cxflags = { archflags, "-I/usr/local/include", "-I/usr/include" }
_g.ldflags = { archflags, "-L/usr/local/lib", "-L/usr/lib" }
_g.shflags = { archflags, "-L/usr/local/lib", "-L/usr/lib" }
-- init flags for objc/c++ (with _g.ldflags and _g.shflags)
_g.mxflags = { archflags }
-- init flags for asm (with _g.ldflags and _g.shflags)
_g.asflags = { archflags }
-- init flags for golang
_g["gc-ldflags"] = {}
-- init flags for dlang
local dc_archs = { i386 = "-m32", x86_64 = "-m64" }
_g.dcflags = { dc_archs[arch] or "" }
_g["dc-shflags"] = { dc_archs[arch] or "" }
_g["dc-ldflags"] = { dc_archs[arch] or "" }
-- init flags for rust
_g["rc-shflags"] = {}
_g["rc-ldflags"] = {}
-- init flags for cuda
local cu_archs = { i386 = "-m32 -Xcompiler -m32", x86_64 = "-m64 -Xcompiler -m64" }
_g.cuflags = {cu_archs[arch] or ""}
_g["cu-shflags"] = {cu_archs[arch] or ""}
_g["cu-ldflags"] = {cu_archs[arch] or ""}
local cuda_dir = config.get("cuda_dir")
if cuda_dir then
table.insert(_g.cuflags, "-I" .. os.args(path.join(cuda_dir, "include")))
table.insert(_g["cu-ldflags"], "-L" .. os.args(path.join(cuda_dir, "lib")))
table.insert(_g["cu-shflags"], "-L" .. os.args(path.join(cuda_dir, "lib")))
table.insert(_g["cu-ldflags"], "-Xlinker -rpath=" .. os.args(path.join(cuda_dir, "lib")))
end
-- ok
return _g
end
|
fix compiler errors for linux cuda
|
fix compiler errors for linux cuda
|
Lua
|
apache-2.0
|
tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake
|
4ba2aac15223b704c3a7e9e818e2f97bea7a7ad6
|
scripts/cycle.lua
|
scripts/cycle.lua
|
require "const"
local function calculate_orientation (self, ori)
local FrameTime = dmz.time.frame_time ()
local result = dmz.matrix.new ()
local dir = ori:transform (const.Forward)
dir:set_y (0)
if not dir:is_zero () then
dir = dir:normalize ()
local heading = const.Forward:get_angle (dir)
local cross = const.Forward:cross (dir)
if cross:get_y () < 0 then heading = dmz.math.TwoPi - heading end
local remainder = math.fmod (heading, dmz.math.HalfPi)
if remainder > (dmz.math.HalfPi / 2) then
heading = heading + dmz.math.HalfPi - remainder
else
heading = heading - remainder
end
if dmz.math.is_zero (self.turn) then self.lastTurn = FrameTime - 0.8
elseif (FrameTime - self.lastTurn) > 0.75 then
if self.turn > 0.1 then
heading = heading - dmz.math.HalfPi
self.lastTurn = FrameTime
elseif self.turn < -0.1 then
heading = heading + dmz.math.HalfPi
self.lastTurn = FrameTime
else self.lastTurn = FrameTime - 0.6
end
end
result:from_axis_and_angle (const.Up, heading)
end
return result
end
local function set_throttle (self, hil)
if not hil then hil = dmz.object.hil () end
if hil then
local throttle = 1
if (self.speed < self.NormalSpeed) and (self.MinSpeed > 0) then
throttle = throttle -
(((self.NormalSpeed - self.speed) / (self.NormalSpeed - self.MinSpeed)) * 0.4)
elseif self.speed > self.NormalSpeed then
throttle = throttle +
(((self.speed - self.NormalSpeed) / (self.MaxSpeed - self.NormalSpeed)) * 0.6)
end
dmz.object.scalar (hil, self.throttleHandle, throttle)
end
end
local function update_time_slice (self, time)
local hil = dmz.object.hil ()
if hil and self.active > 0 then
local state = dmz.object.state (hil)
if state and state:contains (const.EngineOn) then
local pos = dmz.object.position (hil)
local vel = dmz.object.velocity (hil)
local ori = dmz.object.orientation (hil)
if not pos then pos = dmz.vector.new () end
if not vel then vel = dmz.vector.new () end
if not ori then ori = dmz.matrix.new () end
ori = calculate_orientation (self, ori)
local dir = ori:transform (dmz.vector.forward ())
if self.accel > 0.1 then
self.speed = self.speed + (self.Deceleration * time)
if self.speed < self.MinSpeed then self.speed = self.MinSpeed end
elseif self.accel < -0.1 then
self.speed = self.speed + (self.Acceleration * time)
if self.speed > self.MaxSpeed then self.speed = self.MaxSpeed end
end
set_throttle (self, hil)
vel = dir * (self.speed)
local origPos = pos
pos = pos + (vel * time)
local passed =
((self.speed > 0) and const.test_move (self, hil, origPos, pos, ori) or true)
dmz.object.position (hil, nil, (passed and pos or origPos))
dmz.object.velocity (hil, nil, (passed and vel or {0, 0, 0}))
dmz.object.orientation (hil, nil, ori)
end
end
end
local function receive_input_event (self, event)
if event.state then
if event.state.active then self.active = self.active + 1
else self.active = self.active - 1 end
if self.active == 1 then self.timeSlice:start (self.handle)
elseif self.active == 0 then
self.timeSlice:stop (self.handle)
local hil = dmz.object.hil ()
if hil then dmz.object.scalar (hil, self.throttleHandle, 0) end
end
end
if event.axis then
--print ("axis: " .. event.axis.which .. " value: " .. event.axis.value)
local value = 0
if not dmz.math.is_zero (event.axis.value, 0.1) then
if event.axis.value > 0 then value = 1
else value = -1
end
end
if event.axis.which == 2 then --self.speed = value * self.moveSpeed
elseif event.axis.which == 1 then self.turn = value
elseif event.axis.which == 6 then --self.strafe = value * self.moveSpeed
elseif event.axis.which == 7 then self.accel = value
end
end
if event.button then
--print ("button: " .. event.button.which .. " value: " .. tostring (event.button.value))
end
end
local function start (self)
self.handle = self.timeSlice:create (update_time_slice, self, self.name)
self.inputObs:init_channels (
self.config,
dmz.input.Axis + dmz.input.Button + dmz.input.ChannelState,
receive_input_event,
self);
if self.handle and self.active == 0 then self.timeSlice:stop (self.handle) end
end
local function stop (self)
if self.handle and self.timeSlice then self.timeSlice:destroy (self.handle) end
self.inputObs:release_all ()
end
function new (config, name)
local self = {
throttleHandle = dmz.handle.new (
config:to_string ("throttle.name", "throttle")),
Acceleration = config:to_number ("speed.acceleration", 10),
Deceleration = config:to_number ("speed.deceleration", -10),
MinSpeed = config:to_number ("speed.min", 25),
NormalSpeed = config:to_number ("speed.normal", 45),
MaxSpeed = config:to_number ("speed.max", 55),
turn = 0,
speed = 0,
accel = 0,
lastTurn = dmz.time.frame_time (),
start_plugin = start,
stop_plugin = stop,
name = name,
log = dmz.log.new ("lua." .. name),
timeSlice = dmz.time_slice.new (),
inputObs = dmz.input_observer.new (),
active = 0,
config = config,
}
self.speed = self.NormalSpeed
if self.MinSpeed > self.MaxSpeed then
self.log:warn ("Max Speed is less than Minimum Speed")
self.MaxSpeed = self.MinSpeed
end
if self.Acceleration < 0 then self.Acceleration = -self.Acceleration end
if self.Deceleration > 0 then self.Deceleration = -self.Deceleration end
self.log:info ("Creating plugin: " .. name)
return self
end
|
require "const"
local function calculate_orientation (self, ori)
local FrameTime = dmz.time.frame_time ()
local result = dmz.matrix.new ()
local dir = ori:transform (const.Forward)
dir:set_y (0)
if not dir:is_zero () then
dir = dir:normalize ()
local heading = const.Forward:get_angle (dir)
local cross = const.Forward:cross (dir)
if cross:get_y () < 0 then heading = dmz.math.TwoPi - heading end
local remainder = math.fmod (heading, dmz.math.HalfPi)
if remainder > (dmz.math.HalfPi / 2) then
heading = heading + dmz.math.HalfPi - remainder
else
heading = heading - remainder
end
if dmz.math.is_zero (self.turn) then self.lastTurn = FrameTime - 0.8
elseif (FrameTime - self.lastTurn) > 0.75 then
if self.turn > 0.1 then
heading = heading - dmz.math.HalfPi
self.lastTurn = FrameTime
elseif self.turn < -0.1 then
heading = heading + dmz.math.HalfPi
self.lastTurn = FrameTime
else self.lastTurn = FrameTime - 0.6
end
end
result:from_axis_and_angle (const.Up, heading)
end
return result
end
local function set_throttle (self, hil)
if not hil then hil = dmz.object.hil () end
if hil then
local throttle = 1
if (self.speed < self.NormalSpeed) and (self.MinSpeed > 0) then
throttle = throttle -
(((self.NormalSpeed - self.speed) / (self.NormalSpeed - self.MinSpeed)) * 0.4)
elseif self.speed > self.NormalSpeed then
throttle = throttle +
(((self.speed - self.NormalSpeed) / (self.MaxSpeed - self.NormalSpeed)) * 0.6)
end
dmz.object.scalar (hil, self.throttleHandle, throttle)
end
end
local function update_time_slice (self, time)
local hil = dmz.object.hil ()
if hil and self.active > 0 then
local state = dmz.object.state (hil)
if state and state:contains (const.EngineOn) then
self.wasAlive = true
local pos = dmz.object.position (hil)
local vel = dmz.object.velocity (hil)
local ori = dmz.object.orientation (hil)
if not pos then pos = dmz.vector.new () end
if not vel then vel = dmz.vector.new () end
if not ori then ori = dmz.matrix.new () end
ori = calculate_orientation (self, ori)
local dir = ori:transform (dmz.vector.forward ())
if self.accel > 0.1 then
self.speed = self.speed + (self.Deceleration * time)
if self.speed < self.MinSpeed then self.speed = self.MinSpeed end
elseif self.accel < -0.1 then
self.speed = self.speed + (self.Acceleration * time)
if self.speed > self.MaxSpeed then self.speed = self.MaxSpeed end
end
set_throttle (self, hil)
vel = dir * (self.speed)
local origPos = pos
pos = pos + (vel * time)
local passed =
((self.speed > 0) and const.test_move (self, hil, origPos, pos, ori) or true)
dmz.object.position (hil, nil, (passed and pos or origPos))
dmz.object.velocity (hil, nil, (passed and vel or {0, 0, 0}))
dmz.object.orientation (hil, nil, ori)
elseif self.wasAlive and state and state:contains (const.Dead) then
self.wasAlive = nil
local ori = dmz.object.orientation (hil)
if not ori then ori = dmz.matrix.new () end
local dir = ori:transform (dmz.vector.forward ())
self.speed = self.NormalSpeed
dmz.object.velocity (hil, nil, dir * self.speed)
end
end
end
local function receive_input_event (self, event)
if event.state then
if event.state.active then self.active = self.active + 1
else self.active = self.active - 1 end
if self.active == 1 then self.timeSlice:start (self.handle)
elseif self.active == 0 then
self.timeSlice:stop (self.handle)
local hil = dmz.object.hil ()
if hil then dmz.object.scalar (hil, self.throttleHandle, 0) end
end
end
if event.axis then
--print ("axis: " .. event.axis.which .. " value: " .. event.axis.value)
local value = 0
if not dmz.math.is_zero (event.axis.value, 0.1) then
if event.axis.value > 0 then value = 1
else value = -1
end
end
if event.axis.which == 2 then --self.speed = value * self.moveSpeed
elseif event.axis.which == 1 then self.turn = value
elseif event.axis.which == 6 then --self.strafe = value * self.moveSpeed
elseif event.axis.which == 7 then self.accel = value
end
end
if event.button then
--print ("button: " .. event.button.which .. " value: " .. tostring (event.button.value))
end
end
local function start (self)
self.handle = self.timeSlice:create (update_time_slice, self, self.name)
self.inputObs:init_channels (
self.config,
dmz.input.Axis + dmz.input.Button + dmz.input.ChannelState,
receive_input_event,
self);
if self.handle and self.active == 0 then self.timeSlice:stop (self.handle) end
end
local function stop (self)
if self.handle and self.timeSlice then self.timeSlice:destroy (self.handle) end
self.inputObs:release_all ()
end
function new (config, name)
local self = {
throttleHandle = dmz.handle.new (
config:to_string ("throttle.name", "throttle")),
Acceleration = config:to_number ("speed.acceleration", 10),
Deceleration = config:to_number ("speed.deceleration", -10),
MinSpeed = config:to_number ("speed.min", 25),
NormalSpeed = config:to_number ("speed.normal", 45),
MaxSpeed = config:to_number ("speed.max", 55),
turn = 0,
speed = 0,
accel = 0,
lastTurn = dmz.time.frame_time (),
start_plugin = start,
stop_plugin = stop,
name = name,
log = dmz.log.new ("lua." .. name),
timeSlice = dmz.time_slice.new (),
inputObs = dmz.input_observer.new (),
active = 0,
config = config,
}
self.speed = self.NormalSpeed
if self.MinSpeed > self.MaxSpeed then
self.log:warn ("Max Speed is less than Minimum Speed")
self.MaxSpeed = self.MinSpeed
end
if self.Acceleration < 0 then self.Acceleration = -self.Acceleration end
if self.Deceleration > 0 then self.Deceleration = -self.Deceleration end
self.log:info ("Creating plugin: " .. name)
return self
end
|
Bugfix: fixes #12 Cycle speed is now reset when game restarts.
|
Bugfix: fixes #12 Cycle speed is now reset when game restarts.
Signed-off-by: DMZ Develoment <64b2b6d12bfe4baae7dad3d018f8cbf6b0e7a044@dmzdev.org>
|
Lua
|
mit
|
dmzgroup/cycles,shillcock/cycles,shillcock/cycles,dmzgroup/cycles,dmzgroup/cycles,shillcock/cycles,shillcock/cycles,dmzgroup/cycles
|
ff700cb87ab9fe12b8fa81f32fcb266a818f4be0
|
annc-monitor.lua
|
annc-monitor.lua
|
-- Displays announcements in the DFHack console
if active == nil then active = false end
if next_annc_id == nil then next_annc_id = 0 end
if timeout_interval == nil then timeout_interval = 2 end
function set_timeout()
dfhack.timeout(timeout_interval, 'frames', check_announcements)
end
function log(s, color)
dfhack.color(color)
print(s)
dfhack.color(COLOR_RESET)
end
function check_announcements()
local annc_total = #df.global.world.status.reports
if annc_total > next_annc_id then
for i = next_annc_id, annc_total - 1 do
local annc = df.global.world.status.reports[i]
local color = annc.color + (annc.bright and 8 or 0)
log(annc.text, color)
end
next_annc_id = annc_total
end
if active then set_timeout() end
end
function usage()
print [[
Usage:
annc-monitor start: Begin monitoring
annc-monitor stop: End monitoring
annc-monitor interval NUMBER: Set poll interval (frames)
]]
end
args = {...}
if #args >= 1 then
if args[1] == 'start' then
active = true
set_timeout()
elseif args[1] == 'stop' then
active = false
elseif args[1] == 'interval' then
local n = tonumber(args[2])
if n == nil or n < 1 or n ~= math.floor(n) then
qerror('"' .. args[2] .. '" is not an integer!')
end
timeout_interval = n
else
usage()
end
else
usage()
end
dfhack.onStateChange.annc_monitor = function(state)
if state == SC_WORLD_LOADED then
next_annc_id = 0
end
end
|
-- Displays announcements in the DFHack console
if world_loaded == nil then
world_loaded = false
enabled = false
next_annc_id = 0
timeout_interval = 2
end
function set_timeout()
dfhack.timeout(timeout_interval, 'frames', check_announcements)
end
function log(s, color)
dfhack.color(color)
print(s)
dfhack.color(COLOR_RESET)
end
function check_announcements()
if world_loaded then
local annc_total = #df.global.world.status.reports
if annc_total > next_annc_id then
for i = next_annc_id, annc_total - 1 do
local annc = df.global.world.status.reports[i]
local color = annc.color + (annc.bright and 8 or 0)
log(annc.text, color)
end
next_annc_id = annc_total
end
end
if enabled then set_timeout() end
end
function usage()
print [[
Usage:
annc-monitor start: Begin monitoring
annc-monitor stop: End monitoring
annc-monitor interval NUMBER: Set poll interval (frames)
]]
end
args = {...}
if #args >= 1 then
if args[1] == 'start' then
enabled = true
set_timeout()
elseif args[1] == 'stop' then
enabled = false
elseif args[1] == 'interval' then
local n = tonumber(args[2])
if n == nil or n < 1 or n ~= math.floor(n) then
qerror('"' .. args[2] .. '" is not an integer!')
end
timeout_interval = n
else
usage()
end
else
usage()
end
dfhack.onStateChange.annc_monitor = function(state)
if state == SC_WORLD_LOADED then
world_loaded = true
next_annc_id = #df.global.world.status.reports
elseif state == SC_WORLD_UNLOADED then
world_loaded = false
end
end
|
Fix handling of existing announcements
|
Fix handling of existing announcements
|
Lua
|
unlicense
|
lethosor/dfhack-scripts,PeridexisErrant/lethosor-scripts,DFHack/lethosor-scripts
|
5d93eac689f02af3dc98064e106e2d914cf6427b
|
npc/base/talk.lua
|
npc/base/talk.lua
|
--- Base NPC script for talking NPCs
--
-- This script offers all functions needed to get NPCs to talk.
--
-- Author: Martin Karing
-- $Id$
require("base.common")
require("base.messages")
require("base.class")
require("npc.base.basic")
module("npc.base.talk", package.seeall)
talkNPC = base.class.class(function(self, rootNPC)
if (rootNPC == nil or not rootNPC:is_a(npc.base.basic.baseNPC)) then
return;
end;
self["_parent"] = rootNPC;
self["_entry"] = nil;
self["_cycleText"] = nil;
self["_state"] = 0;
self["_saidNumber"] = nil;
self["_nextCycleText"] = -1;
end);
function talkNPC:addCycleText(germanText, englishText)
if (self._cycleText == nil) then
self._cycleText = base.messages.Messages();
self._parent:addCycle(self);
end;
self._cycleText:addMessage(germanText, englishText);
end;
function talkNPC:addTalkingEntry(newEntry)
if (newEntry == nil or not newEntry:is_a(talkNPCEntry)) then
return;
end;
if (self._entry == nil) then
self._parent:addRecvText(self);
self._entry = {};
end;
table.insert(self._entry, newEntry);
end;
function talkNPC:receiveText(player, text)
for _, entry in pairs(self._entry) do
if entry:checkEntry(player, text) then
entry:execute(player);
return true;
end;
end;
return false;
end;
function talkNPC:nextCycle(counter)
if (counter >= self._nextCycleText) then
self._nextCycleText = math.random(900, 3000);
local german, english = self._cycleText:getRandomMessage();
thisNPC:talkLanguage(CCharacter.say, CPlayer.german, german);
thisNPC:talkLanguage(CCharacter.say, CPlayer.english, english);
else
self._nextCycleText = self._nextCycleText - counter;
end;
return self._nextCycleText;
end;
talkNPCEntry = base.class.class(function(self)
self["_trigger"] = {};
self["_conditions"] = {};
self["_responses"] = {};
self["_responsesCount"] = 0;
self["_consequences"] = {};
end);
function talkNPCEntry:addTrigger(text)
if (text == nil or type(text) ~= "string") then
return;
end;
text = string.lower(text);
table.insert(self._trigger, text);
end;
function talkNPCEntry:addCondition(condition)
if (condition == nil or not condition:is_a(npc.base.condition.condition.condition)) then
return;
end;
condition:setNPC(self)
table.insert(self._conditions, condition);
end;
function talkNPCEntry:addResponse(text)
if (text == nil or type(text) ~= "string") then
return;
end;
table.insert(self._responses, text);
self._responsesCount = self._responsesCount + 1;
end;
function talkNPCEntry:addConsequence(consequence)
if (consequence == nil or not consequence:is_a(npc.base.consequence.consequence.consequence)) then
return;
end;
consequence:setNPC(self)
table.insert(self._consequences, consequence);
end;
function talkNPCEntry:checkEntry(player, text)
for _1, pattern in pairs(self._trigger) do
local a, _2, number = string.find(text, pattern);
self._saidNumber = number;
if (a ~= nil) then
local conditionsResult = true;
for _3, condition in pairs(self._conditions) do
if not condition:check(player) then
conditionsResult = false;
break;
end;
end;
if conditionsResult then
return true;
end;
end;
end;
end;
function talkNPCEntry:execute(player)
if (self._responsesCount > 0) then
local selectedResponse = math.random(1, self._responsesCount);
thisNPC:talk(CCharacter.say, self._responses[selectedResponse]);
end;
for _, consequence in pairs(self._consequences) do
consequence:perform(player);
end;
end;
function _set_value(value)
if (type(value) == "function") then
return value, 2;
elseif (value == "%NUMBER") then
return nil, 1;
else
return tonumber(value), 0;
end;
end;
function _get_value(npc, value, type)
if (type == 2) then
return value(npc._saidNumber);
elseif (type == 1) then
return npc._saidNumber;
elseif (type == 0) then
return value;
else
return 0;
end;
end;
|
--- Base NPC script for talking NPCs
--
-- This script offers all functions needed to get NPCs to talk.
--
-- Author: Martin Karing
-- $Id$
require("base.common")
require("base.messages")
require("base.class")
require("npc.base.basic")
module("npc.base.talk", package.seeall)
talkNPC = base.class.class(function(self, rootNPC)
if (rootNPC == nil or not rootNPC:is_a(npc.base.basic.baseNPC)) then
return;
end;
self["_parent"] = rootNPC;
self["_entry"] = nil;
self["_cycleText"] = nil;
self["_state"] = 0;
self["_saidNumber"] = nil;
self["_nextCycleText"] = -1;
end);
function talkNPC:addCycleText(germanText, englishText)
if (self._cycleText == nil) then
self._cycleText = base.messages.Messages();
self._parent:addCycle(self);
end;
self._cycleText:addMessage(germanText, englishText);
end;
function talkNPC:addTalkingEntry(newEntry)
if (newEntry == nil or not newEntry:is_a(talkNPCEntry)) then
return;
end;
if (self._entry == nil) then
self._parent:addRecvText(self);
self._entry = {};
end;
newEntry:setParent(self);
table.insert(self._entry, newEntry);
end;
function talkNPC:receiveText(player, text)
local result = false;
table.foreach(self._entry, function(_, entry)
if entry:checkEntry(player, text) then
entry:execute(player);
result = true;
return true;
end;
end);
return result;
end;
function talkNPC:nextCycle(counter)
if (counter >= self._nextCycleText) then
self._nextCycleText = math.random(900, 3000);
local german, english = self._cycleText:getRandomMessage();
thisNPC:talkLanguage(CCharacter.say, CPlayer.german, german);
thisNPC:talkLanguage(CCharacter.say, CPlayer.english, english);
else
self._nextCycleText = self._nextCycleText - counter;
end;
return self._nextCycleText;
end;
talkNPCEntry = base.class.class(function(self)
self["_trigger"] = {};
self["_conditions"] = {};
self["_responses"] = {};
self["_responsesCount"] = 0;
self["_consequences"] = {};
self["_parent"] = nil;
end);
function talkNPCEntry:addTrigger(text)
if (text == nil or type(text) ~= "string") then
return;
end;
text = string.lower(text);
table.insert(self._trigger, text);
end;
function talkNPCEntry:setParent(npc)
local updateFkt = function(_, value)
value:setNPC(npc);
end;
table.foreach(self._conditions, updateFkt);
table.foreach(self._consequences, updateFkt);
self._parent = npc;
end;
function talkNPCEntry:addCondition(condition)
if (condition == nil or not condition:is_a(npc.base.condition.condition.condition)) then
return;
end;
if (self._parent ~= nil) then
condition:setNPC(self._parent);
end;
table.insert(self._conditions, condition);
end;
function talkNPCEntry:addResponse(text)
if (text == nil or type(text) ~= "string") then
return;
end;
table.insert(self._responses, text);
self._responsesCount = self._responsesCount + 1;
end;
function talkNPCEntry:addConsequence(consequence)
if (consequence == nil or not consequence:is_a(npc.base.consequence.consequence.consequence)) then
return;
end;
if (self._parent ~= nil) then
consequence:setNPC(self._parent);
end;
table.insert(self._consequences, consequence);
end;
function talkNPCEntry:checkEntry(player, text)
for _1, pattern in pairs(self._trigger) do
local a, _2, number = string.find(text, pattern);
self._saidNumber = number;
if (a ~= nil) then
local conditionsResult = true;
for _3, condition in pairs(self._conditions) do
if not condition:check(player) then
conditionsResult = false;
break;
end;
end;
if conditionsResult then
return true;
end;
end;
end;
end;
function talkNPCEntry:execute(player)
if (self._responsesCount > 0) then
local selectedResponse = math.random(1, self._responsesCount);
thisNPC:talk(CCharacter.say, self._responses[selectedResponse]);
end;
table.foreach(self._consequences, function(_, consequence)
consequence:perform(player);
end);
end;
function _set_value(value)
if (type(value) == "function") then
return value, 2;
elseif (value == "%NUMBER") then
return nil, 1;
else
return tonumber(value), 0;
end;
end;
function _get_value(npc, value, type)
if (type == 2) then
return value(npc._saidNumber);
elseif (type == 1) then
return npc._saidNumber;
elseif (type == 0) then
return value;
else
return 0;
end;
end;
|
Fixed the bug that is likely the reason for all NPCs not working
|
Fixed the bug that is likely the reason for all NPCs not working
|
Lua
|
agpl-3.0
|
vilarion/Illarion-Content,LaFamiglia/Illarion-Content,KayMD/Illarion-Content,Baylamon/Illarion-Content,Illarion-eV/Illarion-Content
|
9d1144b21d7a681b9989b9edb03de571b34e089a
|
mods/homedecor_modpack/fake_fire/init.lua
|
mods/homedecor_modpack/fake_fire/init.lua
|
screwdriver = screwdriver or {}
local function start_smoke(pos, node, clicker, chimney)
local this_spawner_meta = minetest.get_meta(pos)
local id = this_spawner_meta:get_int("smoky")
local s_handle = this_spawner_meta:get_int("sound")
local above = minetest.get_node({x=pos.x, y=pos.y+1, z=pos.z}).name
if id ~= 0 then
if s_handle then
minetest.after(0, function(s_handle)
minetest.sound_stop(s_handle)
end, s_handle)
end
minetest.delete_particlespawner(id)
this_spawner_meta:set_int("smoky", nil)
this_spawner_meta:set_int("sound", nil)
return
end
if above == "air" and (not id or id == 0) then
id = minetest.add_particlespawner({
amount = 4, time = 0, collisiondetection = true,
minpos = {x=pos.x-0.25, y=pos.y+0.4, z=pos.z-0.25},
maxpos = {x=pos.x+0.25, y=pos.y+5, z=pos.z+0.25},
minvel = {x=-0.2, y=0.3, z=-0.2}, maxvel = {x=0.2, y=1, z=0.2},
minacc = {x=0,y=0,z=0}, maxacc = {x=0,y=0.5,z=0},
minexptime = 1, maxexptime = 3,
minsize = 4, maxsize = 8,
texture = "smoke_particle.png",
})
if chimney == 1 then
s_handle = nil
this_spawner_meta:set_int("smoky", id)
this_spawner_meta:set_int("sound", nil)
else
s_handle = minetest.sound_play("fire_small", {
pos = pos,
max_hear_distance = 5,
loop = true
})
this_spawner_meta:set_int("smoky", id)
this_spawner_meta:set_int("sound", s_handle)
end
return end
end
local function stop_smoke(pos)
local this_spawner_meta = minetest.get_meta(pos)
local id = this_spawner_meta:get_int("smoky")
local s_handle = this_spawner_meta:get_int("sound")
if id ~= 0 then
minetest.delete_particlespawner(id)
end
if s_handle then
minetest.after(0, function(s_handle)
minetest.sound_stop(s_handle)
end, s_handle)
end
this_spawner_meta:set_int("smoky", nil)
this_spawner_meta:set_int("sound", nil)
end
-- FLAME TYPES
local flame_types = {"fake", "ice"}
for _, f in ipairs(flame_types) do
minetest.register_node("fake_fire:"..f.."_fire", {
inventory_image = f.."_fire_inv.png",
description = f.." fire",
drawtype = "plantlike",
paramtype = "light",
paramtype2 = "facedir",
groups = {dig_immediate=3, not_in_creative_inventory=1},
sunlight_propagates = true,
buildable_to = true,
walkable = false,
light_source = 14,
waving = 1,
tiles = {
{name=f.."_fire_animated.png", animation={type="vertical_frames",
aspect_w=16, aspect_h=16, length=1.5}},
},
on_rightclick = function (pos, node, clicker)
start_smoke(pos, node, clicker)
end,
on_destruct = function (pos)
stop_smoke(pos)
minetest.sound_play("fire_extinguish", {
pos = pos, max_hear_distance = 5
})
end,
drop = ""
})
end
minetest.register_node("fake_fire:fancy_fire", {
inventory_image = "fancy_fire_inv.png",
description = "Fancy Fire",
drawtype = "mesh",
mesh = "fancy_fire.obj",
paramtype = "light",
paramtype2 = "facedir",
groups = {dig_immediate=3},
sunlight_propagates = true,
light_source = 14,
walkable = false,
damage_per_second = 4,
on_rotate = screwdriver.rotate_simple,
tiles = {
{name="fake_fire_animated.png",
animation={type='vertical_frames', aspect_w=16, aspect_h=16, length=1}}, {name='fake_fire_logs.png'}},
on_rightclick = function (pos, node, clicker)
start_smoke(pos, node, clicker)
end,
on_destruct = function (pos)
stop_smoke(pos)
minetest.sound_play("fire_extinguish", {
pos = pos, max_hear_distance = 5
})
end,
drop = {
max_items = 3,
items = {
{
items = { "default:torch", "default:torch", "building_blocks:sticks" },
rarity = 1,
}
}
}
})
-- EMBERS
minetest.register_node("fake_fire:embers", {
description = "Glowing Embers",
tiles = {
{name="embers_animated.png", animation={type="vertical_frames",
aspect_w=16, aspect_h=16, length=2}},
},
light_source = 9,
groups = {crumbly=3},
paramtype = "light",
sounds = default.node_sound_dirt_defaults(),
})
-- CHIMNEYS
local materials = {"stone", "sandstone"}
for _, m in ipairs(materials) do
minetest.register_node("fake_fire:chimney_top_"..m, {
description = "Chimney Top - "..m,
tiles = {"default_"..m..".png^chimney_top.png", "default_"..m..".png"},
groups = {snappy=3},
paramtype = "light",
sounds = default.node_sound_stone_defaults(),
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {-0.5, -0.5, -0.5, 0.5, 0, 0.5},
},
on_rightclick = function (pos, node, clicker)
local chimney = 1
start_smoke(pos, node, clicker, chimney)
end,
on_destruct = function (pos)
stop_smoke(pos)
end
})
minetest.register_craft({
type = "shapeless",
output = 'fake_fire:chimney_top_'..m,
recipe = {"default:torch", "stairs:slab_"..m}
})
end
-- FLINT and STEEL
minetest.register_tool("fake_fire:flint_and_steel", {
description = "Flint and steel",
inventory_image = "flint_and_steel.png",
liquids_pointable = false,
stack_max = 1,
tool_capabilities = {
full_punch_interval = 1.0,
max_drop_level=0,
groupcaps={flamable = {uses=65, maxlevel=1}}
},
on_use = function(itemstack, user, pointed_thing)
if pointed_thing.type == "node" and minetest.get_node(pointed_thing.above).name == "air" then
if not minetest.is_protected(pointed_thing.above, user:get_player_name()) then
if string.find(minetest.get_node(pointed_thing.under).name, "ice") then
minetest.set_node(pointed_thing.above, {name="fake_fire:ice_fire"})
else
minetest.set_node(pointed_thing.above, {name="fake_fire:fake_fire"})
end
else
minetest.chat_send_player(user:get_player_name(), "This area is protected!")
end
else
return
end
itemstack:add_wear(65535/65)
return itemstack
end
})
-- CRAFTS
minetest.register_craft({
type = "shapeless",
output = 'fake_fire:flint_and_steel',
recipe = {
{ "", "default:obsidian_shard", "" },
{ "", "default:steel_ingot", "" }, -- Modif MFF (modified recipe)
{ "", "default:steel_ingot", "" }
},
})
minetest.register_craft({
type = "shapeless",
output = 'fake_fire:embers',
recipe = {"default:torch", "group:wood", "default:torch"}
})
minetest.register_craft({
type = "shapeless",
output = 'fake_fire:fancy_fire',
recipe = {"default:torch", "building_blocks:sticks", "default:torch" }
})
-- ALIASES
minetest.register_alias("fake_fire:smokeless_fire", "fake_fire:fake_fire")
minetest.register_alias("fake_fire:smokeless_ice_fire", "fake_fire:ice_fire")
minetest.register_alias("fake_fire:smokeless_chimney_top_stone", "fake_fire:chimney_top_stone")
minetest.register_alias("fake_fire:smokeless_chimney_top_sandstone", "fake_fire:chimney_top_sandstone")
minetest.register_alias("fake_fire:flint", "fake_fire:flint_and_steel")
|
screwdriver = screwdriver or {}
local function start_smoke(pos, node, clicker, chimney)
local this_spawner_meta = minetest.get_meta(pos)
local id = this_spawner_meta:get_int("smoky")
local s_handle = this_spawner_meta:get_int("sound")
local above = minetest.get_node({x=pos.x, y=pos.y+1, z=pos.z}).name
if id ~= 0 then
if s_handle then
minetest.after(0, function(s_handle)
minetest.sound_stop(s_handle)
end, s_handle)
end
minetest.delete_particlespawner(id)
this_spawner_meta:set_int("smoky", nil)
this_spawner_meta:set_int("sound", nil)
return
end
if above == "air" and (not id or id == 0) then
id = minetest.add_particlespawner({
amount = 4, time = 0, collisiondetection = true,
minpos = {x=pos.x-0.25, y=pos.y+0.4, z=pos.z-0.25},
maxpos = {x=pos.x+0.25, y=pos.y+5, z=pos.z+0.25},
minvel = {x=-0.2, y=0.3, z=-0.2}, maxvel = {x=0.2, y=1, z=0.2},
minacc = {x=0,y=0,z=0}, maxacc = {x=0,y=0.5,z=0},
minexptime = 1, maxexptime = 3,
minsize = 4, maxsize = 8,
texture = "smoke_particle.png",
})
if chimney == 1 then
s_handle = nil
this_spawner_meta:set_int("smoky", id)
this_spawner_meta:set_int("sound", nil)
else
s_handle = minetest.sound_play("fire_small", {
pos = pos,
max_hear_distance = 5,
loop = true
})
this_spawner_meta:set_int("smoky", id)
this_spawner_meta:set_int("sound", s_handle)
end
return end
end
local function stop_smoke(pos)
local this_spawner_meta = minetest.get_meta(pos)
local id = this_spawner_meta:get_int("smoky")
local s_handle = this_spawner_meta:get_int("sound")
if id ~= 0 then
minetest.delete_particlespawner(id)
end
if s_handle then
minetest.after(0, function(s_handle)
minetest.sound_stop(s_handle)
end, s_handle)
end
this_spawner_meta:set_int("smoky", nil)
this_spawner_meta:set_int("sound", nil)
end
-- FLAME TYPES
local flame_types = {"fake", "ice"}
for _, f in ipairs(flame_types) do
minetest.register_node("fake_fire:"..f.."_fire", {
inventory_image = f.."_fire_inv.png",
description = f.." fire",
drawtype = "plantlike",
paramtype = "light",
paramtype2 = "facedir",
groups = {dig_immediate=3, not_in_creative_inventory=1},
sunlight_propagates = true,
buildable_to = true,
walkable = false,
light_source = 14,
waving = 1,
tiles = {
{name=f.."_fire_animated.png", animation={type="vertical_frames",
aspect_w=16, aspect_h=16, length=1.5}},
},
on_rightclick = function (pos, node, clicker)
start_smoke(pos, node, clicker)
end,
on_destruct = function (pos)
stop_smoke(pos)
minetest.sound_play("fire_extinguish", {
pos = pos, max_hear_distance = 5
})
end,
drop = ""
})
end
minetest.register_node("fake_fire:fancy_fire", {
inventory_image = "fancy_fire_inv.png",
description = "Fancy Fire",
drawtype = "mesh",
mesh = "fancy_fire.obj",
paramtype = "light",
paramtype2 = "facedir",
groups = {dig_immediate=3},
sunlight_propagates = true,
light_source = 14,
walkable = false,
damage_per_second = 4,
on_rotate = screwdriver.rotate_simple,
tiles = {
{name="fake_fire_animated.png",
animation={type='vertical_frames', aspect_w=16, aspect_h=16, length=1}}, {name='fake_fire_logs.png'}},
on_rightclick = function (pos, node, clicker)
start_smoke(pos, node, clicker)
end,
on_destruct = function (pos)
stop_smoke(pos)
minetest.sound_play("fire_extinguish", {
pos = pos, max_hear_distance = 5
})
end,
drop = {
max_items = 3,
items = {
{
items = { "default:torch", "default:torch", "building_blocks:sticks" },
rarity = 1,
}
}
}
})
-- EMBERS
minetest.register_node("fake_fire:embers", {
description = "Glowing Embers",
tiles = {
{name="embers_animated.png", animation={type="vertical_frames",
aspect_w=16, aspect_h=16, length=2}},
},
light_source = 9,
groups = {crumbly=3},
paramtype = "light",
sounds = default.node_sound_dirt_defaults(),
})
-- CHIMNEYS
local materials = {"stone", "sandstone"}
for _, m in ipairs(materials) do
minetest.register_node("fake_fire:chimney_top_"..m, {
description = "Chimney Top - "..m,
tiles = {"default_"..m..".png^chimney_top.png", "default_"..m..".png"},
groups = {snappy=3},
paramtype = "light",
sounds = default.node_sound_stone_defaults(),
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {-0.5, -0.5, -0.5, 0.5, 0, 0.5},
},
on_rightclick = function (pos, node, clicker)
local chimney = 1
start_smoke(pos, node, clicker, chimney)
end,
on_destruct = function (pos)
stop_smoke(pos)
end
})
minetest.register_craft({
type = "shapeless",
output = 'fake_fire:chimney_top_'..m,
recipe = {"default:torch", "stairs:slab_"..m}
})
end
-- FLINT and STEEL
minetest.register_tool("fake_fire:flint_and_steel", {
description = "Flint and steel",
inventory_image = "flint_and_steel.png",
liquids_pointable = false,
stack_max = 1,
tool_capabilities = {
full_punch_interval = 1.0,
max_drop_level=0,
groupcaps={flamable = {uses=65, maxlevel=1}}
},
on_use = function(itemstack, user, pointed_thing)
if pointed_thing.type == "node" and minetest.get_node(pointed_thing.above).name == "air" then
if not minetest.is_protected(pointed_thing.above, user:get_player_name()) then
if string.find(minetest.get_node(pointed_thing.under).name, "ice") then
minetest.set_node(pointed_thing.above, {name="fake_fire:ice_fire"})
else
minetest.set_node(pointed_thing.above, {name="fake_fire:fake_fire"})
end
else
minetest.chat_send_player(user:get_player_name(), "This area is protected!")
end
else
return
end
itemstack:add_wear(65535/65)
return itemstack
end
})
-- CRAFTS
minetest.register_craft({
type = "shapeless",
output = 'fake_fire:flint_and_steel',
recipe = {"default:obsidian_shard", "default:steel_ingot", "default:steel_ingot"}
-- /MFF (Mg|06/23/2015)
})
minetest.register_craft({
type = "shapeless",
output = 'fake_fire:embers',
recipe = {"default:torch", "group:wood", "default:torch"}
})
minetest.register_craft({
type = "shapeless",
output = 'fake_fire:fancy_fire',
recipe = {"default:torch", "building_blocks:sticks", "default:torch" }
})
-- ALIASES
minetest.register_alias("fake_fire:smokeless_fire", "fake_fire:fake_fire")
minetest.register_alias("fake_fire:smokeless_ice_fire", "fake_fire:ice_fire")
minetest.register_alias("fake_fire:smokeless_chimney_top_stone", "fake_fire:chimney_top_stone")
minetest.register_alias("fake_fire:smokeless_chimney_top_sandstone", "fake_fire:chimney_top_sandstone")
minetest.register_alias("fake_fire:flint", "fake_fire:flint_and_steel")
|
Fixed flint_and_steel's shapeless craft recipe
|
Fixed flint_and_steel's shapeless craft recipe
|
Lua
|
unlicense
|
Coethium/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,crabman77/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,Coethium/server-minetestforfun,crabman77/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Coethium/server-minetestforfun,Ombridride/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun
|
327d69623ab75aafda177f8f1cbc5455b9a7e5e9
|
assets/scripts/engine/SceneLoader/SceneLoader.lua
|
assets/scripts/engine/SceneLoader/SceneLoader.lua
|
-- Lua Script to load scene files
require 'yaml'
require 'strict'
--result = yaml.load("lua: rocks\npeppers: [ habanero, chipotle, jalapeno ]\n")
--LuaDebug.Log(result.lua)
--LuaDebug.Log(result.peppers[1])
gameObjectMap = {}
function GetString(path)
local file = io.open(path, 'r')
local text = file:read('*a')
return text;
end
function LoadRenderer(go, gameObjectNode)
local renderer = go.renderer;
local posNode = gameObjectNode.RenderInfo.localPosition
local rotNode = gameObjectNode.RenderInfo.localRotation
local sclNode = gameObjectNode.RenderInfo.localScale
renderer.localPosition = Vec3f(posNode[1], posNode[2], posNode[3])
renderer.localRotation = Quatf(rotNode[1], rotNode[2], rotNode[3], rotNode[4])
renderer.localScale = Vec3f(sclNode[1], sclNode[2], sclNode[3])
end
function LoadComponent(componentNode, go)
local type = componentNode.type
if not type then
LuaDebug.Log('Component node has no type key. Skipping...')
return nil
end
if not _G[type] then
LuaDebug.Log('No component type ' .. type .. ' registered. Skipping...')
return nil
end
local comp = _G[type]()
-- First pass to set ids
for key, value in pairs(componentNode) do
if key == 'id' then
GameComponent.setId(comp, value)
end
end
-- Second pass to set fields that may depend on ids
for key, value in pairs(componentNode) do
if key ~= 'type' and key ~= 'id' then -- Ignore type and id field
local convertedValue = ConvertValue(key, value, comp, go)
comp[key] = convertedValue;
end
end
if not CheckRequiredProperties(comp, type) then
LuaDebug.Log('Component node does not define all required properties. Skipping...')
return nil
end
return comp
end
function LoadScene(path)
local scene = {gameObjects = {}}
local source = GetString(path)
local result = yaml.load(source)
for key, gameObjectNode in pairs(result.GameObjects) do
local go = GameObject()
local name = gameObjectNode["name"]
if name then
go:setId(name)
end
LoadRenderer(go, gameObjectNode)
for key, componentNode in pairs(gameObjectNode.Components) do
local comp = LoadComponent(componentNode, go)
if (comp) then
go:addComponent(comp)
end
end
AddGameObject(go)
end
end
function AddGameObject(go)
app_registerGameObject(go)
gameObjectMap[go:getId()] = go
end
function RemoveGameObject(go)
gameObjectMap[go:getId()] = nil
app_destroyGameObject(go)
end
function RegisterJob(job)
app_registerJob(job)
end
function CancelJob(job)
app_cancelJob(job)
end
|
-- Lua Script to load scene files
require 'yaml'
require 'strict'
--result = yaml.load("lua: rocks\npeppers: [ habanero, chipotle, jalapeno ]\n")
--LuaDebug.Log(result.lua)
--LuaDebug.Log(result.peppers[1])
gameObjectMap = {}
function GetString(path)
local file = io.open(path, 'r')
local text = file:read('*a')
return text;
end
function LoadRenderer(go, gameObjectNode)
local transform = go.renderer.transform;
local posNode = gameObjectNode.RenderInfo.localPosition
local rotNode = gameObjectNode.RenderInfo.localRotation
local sclNode = gameObjectNode.RenderInfo.localScale
transform.localPosition = Vec3f(posNode[1], posNode[2], posNode[3])
-- Disabled for now because LuaBind doesn't like it for some reason
--transform.localRotation = Quatf(rotNode[1], rotNode[2], rotNode[3], rotNode[4])
transform.localScale = Vec3f(sclNode[1], sclNode[2], sclNode[3])
end
function LoadComponent(componentNode, go)
local type = componentNode.type
if not type then
LuaDebug.Log('Component node has no type key. Skipping...')
return nil
end
if not _G[type] then
LuaDebug.Log('No component type ' .. type .. ' registered. Skipping...')
return nil
end
local comp = _G[type]()
-- First pass to set ids
for key, value in pairs(componentNode) do
if key == 'id' then
GameComponent.setId(comp, value)
end
end
-- Second pass to set fields that may depend on ids
for key, value in pairs(componentNode) do
if key ~= 'type' and key ~= 'id' then -- Ignore type and id field
local convertedValue = ConvertValue(key, value, comp, go)
comp[key] = convertedValue;
end
end
if not CheckRequiredProperties(comp, type) then
LuaDebug.Log('Component node does not define all required properties. Skipping...')
return nil
end
return comp
end
function LoadScene(path)
local scene = {gameObjects = {}}
local source = GetString(path)
local result = yaml.load(source)
for key, gameObjectNode in pairs(result.GameObjects) do
local go = GameObject()
local name = gameObjectNode["name"]
if name then
go:setId(name)
end
LoadRenderer(go, gameObjectNode)
for key, componentNode in pairs(gameObjectNode.Components) do
local comp = LoadComponent(componentNode, go)
if (comp) then
go:addComponent(comp)
end
end
AddGameObject(go)
end
end
function AddGameObject(go)
app_registerGameObject(go)
gameObjectMap[go:getId()] = go
end
function RemoveGameObject(go)
gameObjectMap[go:getId()] = nil
app_destroyGameObject(go)
end
function RegisterJob(job)
app_registerJob(job)
end
function CancelJob(job)
app_cancelJob(job)
end
|
Fixed a bug where the Position, Rotation and Scale was not set from the scene file properly.
|
Fixed a bug where the Position, Rotation and Scale was not set from the scene file properly.
|
Lua
|
mit
|
NoxHarmonium/spacestationkeeper,NoxHarmonium/spacestationkeeper
|
ccfe7fe3c5ddd9b991d308702d8474d1a568fced
|
lib/switchboard_modules/lua_script_debugger/premade_scripts/benchmarking_tests/speed_test-dac.lua
|
lib/switchboard_modules/lua_script_debugger/premade_scripts/benchmarking_tests/speed_test-dac.lua
|
print("Benchmarking Test: Set DAC0 to 2.5V, then 0V as fast as possible.")
--This example will output a waveform at ~13kHz to ~15kHz on DAC0
--Note: Most commonly users should throttle their code execution using the functions:
--"LJ.IntervalConfig(0, 1000)", and "if LJ.CheckInterval(0) then" ...
--The throttle setting can correspond roughly with the length of the Lua script.
--A rule of thumb for deciding a throttle setting is Throttle = (3*NumLinesCode) + 20
ThrottleSetting = 36 --Default throttle setting is 10 instructions
LJ.setLuaThrottle(ThrottleSetting)
ThrottleSetting = LJ.getLuaThrottle()
print ("Current Lua Throttle Setting: ", ThrottleSetting)
Print_interval_ms = 2000
c = 0
LJ.IntervalConfig(0, Print_interval_ms)
while true do
MB.W(1000, 3, 2.5) --write 2.5V to DAC0. Address is 1000, type is 3
MB.W(1000, 3, 0.0) --write 0.0V to DAC0. Address is 1000, type is 3
c = c + 1
if LJ.CheckInterval(0) then
c = c / (Print_interval_ms / 1000)
print ("Frequency in Hz: ", c)
c = 0
end
end
|
--[[
Name: speed_test-dac.lua
Desc: This example will output a waveform at ~13kHz to ~15kHz on DAC0
Note: In most cases, users should throttle their code execution using the
functions: "interval_config(0, 1000)", and "if check_interval(0)"
--]]
-- Assign functions locally for faster processing
local modbus_read = MB.R
local modbus_write = MB.W
local set_lua_throttle = LJ.setLuaThrottle
local get_lua_throttle = LJ.getLuaThrottle
local interval_config = LJ.IntervalConfig
local check_interval = LJ.CheckInterval
print("Benchmarking Test: Set DAC0 to 2.5V, then 0V as fast as possible.")
-- The throttle setting can correspond roughly with the length of the Lua
-- script. A rule of thumb for deciding a throttle setting is
-- Throttle = (3*NumLinesCode)+20. The default throttle setting is 10 instructions
local throttle = 36
set_lua_throttle(throttle)
throttle = get_lua_throttle()
print ("Current Lua Throttle Setting: ", throttle)
-- Use a 2000ms interval
local interval = 2000
local numwrites = 0
interval_config(0, interval)
while true do
-- Write 2.5V to DAC0. Address is 1000, type is 3 (FLOAT32)
modbus_write(1000, 3, 2.5)
-- Write 0.0V to DAC0. Address is 1000, type is 3 (FLOAT32)
modbus_write(1000, 3, 0.0)
numwrites = numwrites + 1
if check_interval(0) then
-- Convert the number of writes per interval to a frequency
numwrites = numwrites / (interval / 1000)
print ("Frequency in Hz: ", numwrites)
numwrites = 0
end
end
|
Fixed up formatting of the dac speed test
|
Fixed up formatting of the dac speed test
|
Lua
|
mit
|
chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager
|
235b06552d27fa9cd51f83340517115560c1aef4
|
vrp/lib/utils.lua
|
vrp/lib/utils.lua
|
local modules = {}
function module(rsc, path) -- load a LUA resource file as module
if path == nil then -- shortcut for vrp, can omit the resource parameter
path = rsc
rsc = "vrp"
end
local key = rsc..path
if modules[key] then -- cached module
return table.unpack(modules[key])
else
local f,err = load(LoadResourceFile(rsc, path..".lua"))
if f then
local ar = {pcall(f)}
if ar[1] then
table.remove(ar,1)
modules[key] = ar
return table.unpack(ar)
else
modules[key] = nil
print("[vRP] error loading module "..rsc.."/"..path..":"..ar[2])
end
else
print("[vRP] error parsing module "..rsc.."/"..path..":"..err)
end
end
end
-- generate a task metatable (helper to return delayed values with timeout)
--- dparams: default params in case of timeout or empty cbr()
--- timeout: milliseconds, default 5000
function Task(callback, dparams, timeout)
if timeout == nil then timeout = 5000 end
local r = {}
r.done = false
local finish = function(params)
if not r.done then
if params == nil then params = dparams or {} end
r.done = true
callback(table.unpack(params))
end
end
setmetatable(r, {__call = function(t,params) finish(params) end })
SetTimeout(timeout, function() finish(dparams) end)
return r
end
function parseInt(v)
-- return cast(int,tonumber(v))
return math.floor(tonumber(v))
end
function parseDouble(v)
-- return cast(double,tonumber(v))
return tonumber(v)
end
-- will remove chars not allowed/disabled by strchars
-- if allow_policy is true, will allow all strchars, if false, will allow everything except the strchars
local sanitize_tmp = {}
function sanitizeString(str, strchars, allow_policy)
local r = ""
-- get/prepare index table
local chars = sanitize_tmp[strchars]
if chars == nil then
chars = {}
local size = string.len(strchars)
for i=1,size do
local char = string.sub(strchars,i,i)
chars[char] = true
end
sanitize_tmp[strchars] = chars
end
-- sanitize
size = string.len(str)
for i=1,size do
local char = string.sub(str,i,i)
if (allow_policy and chars[char]) or (not allow_policy and not chars[char]) then
r = r..char
end
end
return r
end
function splitString(str, sep)
if sep == nil then sep = "%s" end
local t={}
local i=1
for str in string.gmatch(str, "([^"..sep.."]+)") do
t[i] = str
i = i + 1
end
return t
end
function joinStrings(list, sep)
if sep == nil then sep = "" end
local str = ""
local count = 0
local size = #list
for k,v in pairs(list) do
count = count+1
str = str..v
if count < size then str = str..sep end
end
return str
end
|
local modules = {}
function module(rsc, path) -- load a LUA resource file as module
if path == nil then -- shortcut for vrp, can omit the resource parameter
path = rsc
rsc = "vrp"
end
local key = rsc..path
if modules[key] then -- cached module
return table.unpack(modules[key])
else
local f,err = load(LoadResourceFile(rsc, path..".lua"))
if f then
local ar = {pcall(f)}
if ar[1] then
table.remove(ar,1)
modules[key] = ar
return table.unpack(ar)
else
modules[key] = nil
print("[vRP] error loading module "..rsc.."/"..path..":"..ar[2])
end
else
print("[vRP] error parsing module "..rsc.."/"..path..":"..err)
end
end
end
-- generate a task metatable (helper to return delayed values with timeout)
--- dparams: default params in case of timeout or empty cbr()
--- timeout: milliseconds, default 5000
function Task(callback, dparams, timeout)
if timeout == nil then timeout = 5000 end
local r = {}
r.done = false
local finish = function(params)
if not r.done then
if params == nil then params = dparams or {} end
r.done = true
callback(table.unpack(params))
end
end
setmetatable(r, {__call = function(t,params) finish(params) end })
SetTimeout(timeout, function() finish(dparams) end)
return r
end
function parseInt(v)
-- return cast(int,tonumber(v))
return math.floor(tonumber(v))
end
function parseDouble(v)
-- return cast(double,tonumber(v))
return tonumber(v)
end
function parseFloat(v)
return parseDouble(v)
end
-- will remove chars not allowed/disabled by strchars
-- if allow_policy is true, will allow all strchars, if false, will allow everything except the strchars
local sanitize_tmp = {}
function sanitizeString(str, strchars, allow_policy)
local r = ""
-- get/prepare index table
local chars = sanitize_tmp[strchars]
if chars == nil then
chars = {}
local size = string.len(strchars)
for i=1,size do
local char = string.sub(strchars,i,i)
chars[char] = true
end
sanitize_tmp[strchars] = chars
end
-- sanitize
size = string.len(str)
for i=1,size do
local char = string.sub(str,i,i)
if (allow_policy and chars[char]) or (not allow_policy and not chars[char]) then
r = r..char
end
end
return r
end
function splitString(str, sep)
if sep == nil then sep = "%s" end
local t={}
local i=1
for str in string.gmatch(str, "([^"..sep.."]+)") do
t[i] = str
i = i + 1
end
return t
end
function joinStrings(list, sep)
if sep == nil then sep = "" end
local str = ""
local count = 0
local size = #list
for k,v in pairs(list) do
count = count+1
str = str..v
if count < size then str = str..sep end
end
return str
end
|
Fix gunshop issue.
|
Fix gunshop issue.
|
Lua
|
mit
|
ImagicTheCat/vRP,ImagicTheCat/vRP
|
8ea166a2e636a7ea3d69e668c8262fa4b3d4510c
|
nvim/lua/config/telescope.lua
|
nvim/lua/config/telescope.lua
|
local actions = require('telescope.actions')
require('telescope').setup({
defaults = {
mappings = {
i = {
-- default key binding is <C-c> but I keep forgetting and I hit <esc> twice...
['<esc>'] = actions.close,
},
},
},
pickers = {
oldfiles = {
theme = 'ivy',
},
buffers = {
sort_lastused = true,
},
},
extensions = {
fzf = {
fuzzy = true,
override_generic_sorter = true,
override_file_sorter = true,
case_mode = 'smart_case',
},
},
})
require('telescope').load_extension('fzf')
|
local actions = require('telescope.actions')
require('telescope').setup({
defaults = {
mappings = {
i = {
-- default key binding is <C-c> but I keep forgetting and I hit <esc> twice...
['<esc>'] = actions.close,
},
},
},
pickers = {
oldfiles = {
theme = 'ivy',
},
buffers = {
sort_lastused = true,
sort_mru = true,
initial_mode = 'normal',
},
},
extensions = {
fzf = {
fuzzy = true,
override_generic_sorter = true,
override_file_sorter = true,
case_mode = 'smart_case',
},
},
})
require('telescope').load_extension('fzf')
|
fix: use mru and normal mode for buffers
|
fix: use mru and normal mode for buffers
I still have muscle memory with bufexplorer so this feels more natural
to me.
|
Lua
|
mit
|
drmohundro/dotfiles
|
6e2af68c410c3a1b6abd472464b0f97ba93de55a
|
modules/admin-mini/luasrc/model/cbi/mini/wifi.lua
|
modules/admin-mini/luasrc/model/cbi/mini/wifi.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
m = Map("wireless", translate("wifi"), translate("a_w_devices1"))
s = m:section(TypedSection, "wifi-device", translate("devices"))
en = s:option(Flag, "disabled", translate("enable"))
en.enabled = "0"
en.disabled = "1"
mode = s:option(ListValue, "mode", translate("mode"))
mode:value("", "standard")
mode:value("11b", "802.11b")
mode:value("11g", "802.11g")
mode:value("11a", "802.11a")
mode:value("11bg", "802.11b+g")
mode.rmempty = true
s:option(Value, "channel", translate("a_w_channel"))
s = m:section(TypedSection, "wifi-iface", translate("m_n_local"))
s.anonymous = true
s:option(Value, "ssid", translate("a_w_netid")).maxlength = 32
local devs = {}
luci.model.uci.foreach("wireless", "wifi-device",
function (section)
table.insert(devs, section[".name"])
end)
if #devs > 1 then
device = s:option(DummyValue, "device", translate("device"))
else
s.defaults.device = devs[1]
end
mode = s:option(ListValue, "mode", translate("mode"))
mode:value("ap", translate("m_w_ap"))
mode:value("adhoc", translate("m_w_adhoc"))
mode:value("sta", translate("m_w_client"))
function mode.write(self, section, value)
if value == "sta" then
-- ToDo: Move this away
if not luci.model.uci.get("network", "wan") then
luci.model.uci.set("network", "wan", "interface")
luci.model.uci.set("network", "wan", "proto", "none")
end
luci.model.uci.set("network", "wan", "type", "bridge")
luci.model.uci.save("network")
self.map:set(section, "network", "wan")
else
self.map:set(section, "network", "lan")
end
return ListValue.write(self, section, value)
end
encr = s:option(ListValue, "encryption", translate("encryption"))
encr:value("none", "keine")
encr:value("wep", "WEP")
encr:value("psk", "WPA-PSK")
encr:value("wpa", "WPA-Radius")
encr:value("psk2", "WPA2-PSK")
encr:value("wpa2", "WPA2-Radius")
key = s:option(Value, "key", translate("key"))
key:depends("encryption", "wep")
key:depends("encryption", "psk")
key:depends("encryption", "wpa")
key:depends("encryption", "psk2")
key:depends("encryption", "wpa2")
key.rmempty = true
server = s:option(Value, "server", translate("a_w_radiussrv"))
server:depends("encryption", "wpa")
server:depends("encryption", "wpa2")
server.rmempty = true
port = s:option(Value, "port", translate("a_w_radiusport"))
port:depends("encryption", "wpa")
port:depends("encryption", "wpa2")
port.rmempty = true
iso = s:option(Flag, "isolate", translate("a_w_apisolation"), translate("a_w_apisolation1"))
iso.rmempty = true
iso:depends("mode", "ap")
hide = s:option(Flag, "hidden", translate("a_w_hideessid"))
hide.rmempty = true
hide:depends("mode", "ap")
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
m = Map("wireless", translate("wifi"), translate("a_w_devices1"))
s = m:section(TypedSection, "wifi-device", translate("devices"))
en = s:option(Flag, "disabled", translate("enable"))
en.enabled = "0"
en.disabled = "1"
mode = s:option(ListValue, "mode", translate("mode"))
mode:value("", "standard")
mode:value("11b", "802.11b")
mode:value("11g", "802.11g")
mode:value("11a", "802.11a")
mode:value("11bg", "802.11b+g")
mode.rmempty = true
s:option(Value, "channel", translate("a_w_channel"))
s = m:section(TypedSection, "wifi-iface", translate("m_n_local"))
s.anonymous = true
s:option(Value, "ssid", translate("a_w_netid")).maxlength = 32
local devs = {}
luci.model.uci.foreach("wireless", "wifi-device",
function (section)
table.insert(devs, section[".name"])
end)
if #devs > 1 then
device = s:option(DummyValue, "device", translate("device"))
else
s.defaults.device = devs[1]
end
mode = s:option(ListValue, "mode", translate("mode"))
mode:value("ap", translate("m_w_ap"))
mode:value("adhoc", translate("m_w_adhoc"))
mode:value("sta", translate("m_w_client"))
function mode.write(self, section, value)
if value == "sta" then
-- ToDo: Move this away
if not luci.model.uci.get("network", "wan") then
luci.model.uci.set("network", "wan", "proto", "none")
luci.model.uci.set("network", "wan", "ifname", " ")
end
luci.model.uci.set("network", "wan", "_ifname", luci.model.uci.get("network", "wan", "ifname") or " ")
luci.model.uci.set("network", "wan", "ifname", " ")
luci.model.uci.save("network")
luci.model.uci.unload("network")
self.map:set(section, "network", "wan")
else
if luci.model.uci.get("network", "wan", "_ifname") then
luci.model.uci.set("network", "wan", "ifname", luci.model.uci.get("network", "wan", "_ifname"))
end
self.map:set(section, "network", "lan")
end
return ListValue.write(self, section, value)
end
encr = s:option(ListValue, "encryption", translate("encryption"))
encr:value("none", "keine")
encr:value("wep", "WEP")
encr:value("psk", "WPA-PSK")
encr:value("wpa", "WPA-Radius")
encr:value("psk2", "WPA2-PSK")
encr:value("wpa2", "WPA2-Radius")
key = s:option(Value, "key", translate("key"))
key:depends("encryption", "wep")
key:depends("encryption", "psk")
key:depends("encryption", "wpa")
key:depends("encryption", "psk2")
key:depends("encryption", "wpa2")
key.rmempty = true
server = s:option(Value, "server", translate("a_w_radiussrv"))
server:depends("encryption", "wpa")
server:depends("encryption", "wpa2")
server.rmempty = true
port = s:option(Value, "port", translate("a_w_radiusport"))
port:depends("encryption", "wpa")
port:depends("encryption", "wpa2")
port.rmempty = true
iso = s:option(Flag, "isolate", translate("a_w_apisolation"), translate("a_w_apisolation1"))
iso.rmempty = true
iso:depends("mode", "ap")
hide = s:option(Flag, "hidden", translate("a_w_hideessid"))
hide.rmempty = true
hide:depends("mode", "ap")
return m
|
modules/admin-mini: Fixed WLAN client mode
|
modules/admin-mini: Fixed WLAN client mode
|
Lua
|
apache-2.0
|
deepak78/luci,8devices/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci
|
853d1ac167f8acdedf1d0752811d3e586846f30f
|
premake5.lua
|
premake5.lua
|
--
-- Premake script (http://premake.github.io)
--
solution 'luazmq'
configurations {'Debug', 'Release'}
targetdir 'bin'
filter 'configurations:Debug'
defines 'DEBUG'
symbols 'On'
filter 'configurations:Release'
defines 'NDEBUG'
symbols 'On'
optimize 'On'
filter 'action:vs*'
defines
{
'WIN32',
'_WIN32_WINNT=0x0600',
'_CRT_SECURE_NO_WARNINGS',
'NOMINMAX',
'snprintf=_snprintf',
'inline=__inline',
}
filter 'system:windows'
defines 'LUA_BUILD_AS_DLL'
filter 'system:linux'
defines 'LUA_USE_LINUX'
project 'lua5.3'
targetname 'lua5.3'
language 'C'
kind 'SharedLib'
location 'build'
includedirs 'deps/lua/src'
files
{
'deps/lua/src/*.h',
'deps/lua/src/*.c',
}
removefiles
{
'deps/lua/src/lua.c',
'deps/lua/src/luac.c',
}
project 'luazmq'
targetname 'luazmq'
language 'C'
kind 'SharedLib'
location 'build'
defines 'LUA_LIB'
includedirs
{
'deps/lua/src',
'deps/zmq/include'
}
files 'src/*.c'
links 'lua5.3'
filter 'system:linux'
links {'m', 'zmq', 'sodium'}
filter 'system:windows'
libdirs 'deps/zmq/lib'
links {'libzmq'}
|
--
-- Premake script (http://premake.github.io)
--
solution 'luazmq'
configurations {'Debug', 'Release'}
targetdir 'bin'
filter 'configurations:Debug'
defines 'DEBUG'
symbols 'On'
filter 'configurations:Release'
defines 'NDEBUG'
symbols 'On'
optimize 'On'
filter 'action:vs*'
defines
{
'WIN32',
'_WIN32_WINNT=0x0600',
'_CRT_SECURE_NO_WARNINGS',
'NOMINMAX',
'snprintf=_snprintf',
'inline=__inline',
}
filter 'system:windows'
defines 'LUA_BUILD_AS_DLL'
filter 'system:linux'
defines 'LUA_USE_LINUX'
project 'lua5.3'
targetname 'lua5.3'
language 'C'
kind 'SharedLib'
location 'build'
includedirs 'deps/lua/src'
files
{
'deps/lua/src/*.h',
'deps/lua/src/*.c',
}
removefiles
{
'deps/lua/src/lua.c',
'deps/lua/src/luac.c',
}
project 'luazmq'
targetname 'luazmq'
language 'C'
kind 'SharedLib'
location 'build'
defines 'LUA_LIB'
includedirs
{
'deps/lua/src',
'deps/zmq/include'
}
files 'src/*.c'
links 'lua5.3'
filter 'system:linux'
links {'m', 'zmq', 'sodium'}
filter 'system:windows'
libdirs 'deps/zmq/lib'
links {'libzmq'}
|
Fix tab space
|
Fix tab space
|
Lua
|
apache-2.0
|
ichenq/lua-zmq
|
0da2fb629e72efd794fc396cbab34661e0ca43b7
|
floor.lua
|
floor.lua
|
--[[
@file floor.lua
@brief OpenComputersのロボットに床を作らせる
@detail
燃料は考慮しない, 貼るブロックはロボットのインベントリ内のものを使う,
robotの下にブロックを配置する
貼り終えたら元の位置,向きに戻る
robotの必要最低限の構成
:Hardware
case(tier1↑)
eeprom
cpu(tier1↑)
memory(tier1↑)
HDD(tier1↑)
screen(tier1↑)
graphic card
keyboard
Inventory Upgrade
:SoftWare
luaBIOS(eeprom)
OpenOS
@args1 (width : number, nil) 横の長さ (defalt:4)
@args2 (height : number, nil) 縦の長さ (defalt:4)
@options
-e
ロボットのツールスロットにextracell2のblockcontainerがあるものとして
robotのインベントリ内の資材ではなく,これを用いることで床貼りを行う
-f
ブロックを配置する場所に既にブロックがあった場合置き換えを行う
-r
指定された場合元の位置に戻る
@author iesika
@date 2017/9/12~
--]]
local component = require ("component")
local sides = require("sides")
local shell = require("shell")
local robot = require("robot")
local args, options = shell.parse(...)
local width = tonumber(args[1]) or 4
local height = tonumber(args[2]) or 4
local function selectNotEmptySlot()
if robot.count() > 0 then
return true
end
for i = 1, robot.inventorySize() do
if robot.count(i) > 0 then
robot.select(i)
return true
end
end
return false
end
local function prompt(message)
io.write(message .. " [Y/n] ")
local result = io.read()
return result and (result == "" or result:lower() == "y")
end
--メイン
if component.isAvailable("piston") then
if(prompt("use piston upgrade?")) then
goto PISTON
end
goto NORMAL
end
--ピストンを使わない設置
::NORMAL::
for i = 1, width do
for j = 1, height do
if options.f and component.robot.detect(sides.down) then
component.robot.swing(sides.down)
end
selectNotEmptySlot()
if options["e"] then
robot.useDown()
else
robot.placeDown()
end
if j == height then--奥までいったらUターンする
component.robot.turn(i%2 == 1)
repeat until component.robot.move(sides.forward)
component.robot.turn(i%2 == 1)
else
repeat until component.robot.move(sides.forward)
end
end
end
--元の位置に戻る
if options["r"] then
if width%2 == 0 then
robot.turnLeft()
else
for i = 1, height - 1 do
repeat until component.robot.move(sides.forward)
end
robot.turnRight()
end
for i = 1, width do
repeat until component.robot.move(sides.forward)
end
robot.turnRight()
end
goto END
--ピストンを使う設置
::PISTON::
repeat until robot.back()
repeat until robot.down()
for i = 1, width do
selectNotEmptySlot()
for j = 1, height do
if options["e"] then
robot.use()
else
robot.place()
end
if j ~= height then
component.piston.push()
end
end
if i == height and options["r"] then
--元の位置に戻る
robot.turnLeft()
for k = 1, width - 1 do
repeat until robot.forward()
end
robot.turnRight()
else
robot.turnRight()
repeat until robot.forward()
robot.turnLeft()
end
end
::END::
|
--[[
@file floor.lua
@brief OpenComputersのロボットに床を作らせる
@detail
燃料は考慮しない, 貼るブロックはロボットのインベントリ内のものを使う,
robotの下からブロックを配置する
貼り終えたら元の位置,向きに戻る
robotの必要最低限の構成
:Hardware
case(tier1↑)
eeprom
cpu(tier1↑)
memory(tier1↑)
HDD(tier1↑)
screen(tier1↑)
graphic card
keyboard
Inventory Upgrade
:SoftWare
luaBIOS(eeprom)
OpenOS
@args1 (width : number, nil) 横の長さ (defalt:4)
@args2 (height : number, nil) 縦の長さ (defalt:4)
@options
-e
ロボットのツールスロットにextracell2のblockcontainerがあるものとして
robotのインベントリ内の資材ではなく,これを用いることで床貼りを行う
-f
ブロックを配置する場所に既にブロックがあった場合置き換えを行う
(ピストンアップグレードを使う時は無意味)
-r
指定された場合元の位置に戻る
@author iesika
@date 2017/9/12~
--]]
local component = require ("component")
local sides = require("sides")
local shell = require("shell")
local robot = require("robot")
local args, options = shell.parse(...)
local width = tonumber(args[1]) or 4
local height = tonumber(args[2]) or 4
local function selectNotEmptySlot()
if robot.count() > 0 then
return true
end
for i = 1, robot.inventorySize() do
if robot.count(i) > 0 then
robot.select(i)
return true
end
end
return false
end
local function prompt(message)
io.write(message .. " [Y/n] ")
local result = io.read()
return result and (result == "" or result:lower() == "y")
end
--メイン
if component.isAvailable("piston") then
if(prompt("use piston upgrade?")) then
goto PISTON
end
goto NORMAL
end
--ピストンを使わない設置
::NORMAL::
for i = 1, width do
for j = 1, height do
if options.f and component.robot.detect(sides.down) then
component.robot.swing(sides.down)
end
selectNotEmptySlot()
if options["e"] then
robot.useDown()
else
robot.placeDown()
end
if j == height then--奥までいったらUターンする
component.robot.turn(i%2 == 1)
repeat until component.robot.move(sides.forward)
component.robot.turn(i%2 == 1)
else
repeat until component.robot.move(sides.forward)
end
end
end
--元の位置に戻る
if options["r"] then
if width%2 == 0 then
robot.turnLeft()
else
for i = 1, height - 1 do
repeat until component.robot.move(sides.forward)
end
robot.turnRight()
end
for i = 1, width do
repeat until component.robot.move(sides.forward)
end
robot.turnRight()
end
goto END
--ピストンを使う設置
::PISTON::
repeat until robot.back()
repeat until robot.down()
for i = 1, width do
selectNotEmptySlot()
for j = 1, height do
if options["e"] then
robot.use()
else
robot.place()
end
if j ~= height then
component.piston.push()
end
end
if i == height then
if options["r"] then
--元の位置に戻る
robot.turnLeft()
for k = 1, width - 1 do
repeat until robot.forward()
end
robot.turnRight()
end
else
robot.turnRight()
repeat until robot.forward()
robot.turnLeft()
end
end
::END::
|
fix option r
|
fix option r
|
Lua
|
mit
|
iesika/iesika-OCPrograms
|
7c12ce0cbb393eb7192f00cc6850be1ac5f9a37b
|
game/dota_addons/castle_defenders/scripts/vscripts/addon_game_mode.lua
|
game/dota_addons/castle_defenders/scripts/vscripts/addon_game_mode.lua
|
-- This is the entry-point to your game mode and should be used primarily to precache models/particles/sounds/etc
require('internal/util')
require('gamemode')
function Precache( context )
--[[
This function is used to precache resources/units/items/abilities that will be needed
for sure in your game and that will not be precached by hero selection. When a hero
is selected from the hero selection screen, the game will precache that hero's assets,
any equipped cosmetics, and perform the data-driven precaching defined in that hero's
precache{} block, as well as the precache{} block for any equipped abilities.
See GameMode:PostLoadPrecache() in gamemode.lua for more information
]]
print ("[BAREBONES] Performing pre-load precache")
-- Particles can be precached individually or by folder
-- It it likely that precaching a single particle system will precache all of its children, but this may not be guaranteed
PrecacheUnitByNameSync("creep_wave_1", context)
PrecacheUnitByNameSync("creep_wave_2", context)
PrecacheUnitByNameSync("creep_wave_3", context)
PrecacheUnitByNameSync("creep_wave_4", context)
PrecacheUnitByNameSync("creep_wave_5", context)
PrecacheUnitByNameSync("creep_wave_6", context)
PrecacheUnitByNameSync("creep_wave_7", context)
PrecacheUnitByNameSync("creep_wave_8", context)
PrecacheUnitByNameSync("creep_wave_9", context)
PrecacheUnitByNameSync("creep_wave_10", context)
PrecacheUnitByNameSync("boss_wave_1", context)
end
-- Create the game mode when we activate
function Activate()
GameRules.GameMode = GameMode()
GameRules.GameMode:InitGameMode()
end
|
-- This is the entry-point to your game mode and should be used primarily to precache models/particles/sounds/etc
require('internal/util')
require('gamemode')
function Precache( context )
--[[
This function is used to precache resources/units/items/abilities that will be needed
for sure in your game and that will not be precached by hero selection. When a hero
is selected from the hero selection screen, the game will precache that hero's assets,
any equipped cosmetics, and perform the data-driven precaching defined in that hero's
precache{} block, as well as the precache{} block for any equipped abilities.
See GameMode:PostLoadPrecache() in gamemode.lua for more information
]]
print ("[BAREBONES] Performing pre-load precache")
-- Particles can be precached individually or by folder
-- It it likely that precaching a single particle system will precache all of its children, but this may not be guaranteed
PrecacheUnitByNameSync("easy_creep_wave_1", context)
PrecacheUnitByNameSync("easy_creep_wave_2", context)
PrecacheUnitByNameSync("easy_creep_wave_3", context)
PrecacheUnitByNameSync("easy_creep_wave_4", context)
PrecacheUnitByNameSync("easy_creep_wave_5", context)
PrecacheUnitByNameSync("easy_creep_wave_6", context)
PrecacheUnitByNameSync("easy_creep_wave_7", context)
PrecacheUnitByNameSync("easy_creep_wave_8", context)
PrecacheUnitByNameSync("easy_creep_wave_9", context)
PrecacheUnitByNameSync("easy_creep_wave_10", context)
PrecacheUnitByNameSync("medium_creep_wave_1", context)
PrecacheUnitByNameSync("medium_creep_wave_2", context)
PrecacheUnitByNameSync("medium_creep_wave_3", context)
PrecacheUnitByNameSync("medium_creep_wave_4", context)
PrecacheUnitByNameSync("medium_creep_wave_5", context)
PrecacheUnitByNameSync("medium_creep_wave_6", context)
PrecacheUnitByNameSync("medium_creep_wave_7", context)
PrecacheUnitByNameSync("medium_creep_wave_8", context)
PrecacheUnitByNameSync("medium_creep_wave_9", context)
PrecacheUnitByNameSync("medium_creep_wave_10", context)
PrecacheUnitByNameSync("boss_wave_1", context)
PrecacheUnitByNameSync("boss_wave_2", context)
PrecacheUnitByNameSync("boss_wave_3", context)
end
-- Create the game mode when we activate
function Activate()
GameRules.GameMode = GameMode()
GameRules.GameMode:InitGameMode()
end
|
Added Precache for easy and medium creep wave 1 >> 10. bug: First wave, crab and tidehunter spawn. After first boss come out, second wave spawn (game logic should be boss wave out, second save stop spawn (spawn after boss die)) second save, only slark(no other model like sc said (brothers model)
|
Added Precache for easy and medium creep wave 1 >> 10.
bug: First wave, crab and tidehunter spawn.
After first boss come out, second wave spawn (game logic should be boss wave out, second save stop spawn (spawn after boss die))
second save, only slark(no other model like sc said (brothers model)
|
Lua
|
apache-2.0
|
soonyee91/castle_defenders
|
51f277c1e3c56e5be976528e9a207753d5af56eb
|
lua/starfall/libs_sh/color.lua
|
lua/starfall/libs_sh/color.lua
|
SF.Color = {}
--- Color type
--@shared
local color_methods, color_metatable = SF.Typedef( "Color" )
local wrap, unwrap = SF.CreateWrapper( color_metatable, true, false, debug.getregistry().Color )
SF.Color.Methods = color_methods
SF.Color.Metatable = color_metatable
SF.Color.Wrap = wrap
SF.Color.Unwrap = unwrap
--- Same as the Gmod Color type
-- @name SF.DefaultEnvironment.Color
-- @class function
-- @param r - Red
-- @param g - Green
-- @param b - Blue
-- @param a - Alpha
-- @return New color
SF.DefaultEnvironment.Color = function ( ... )
return wrap( Color( ... ) )
end
-- Lookup table.
-- Index 1->4 have associative rgba for use in __index. Saves lots of checks
-- String based indexing returns string, just a pass through.
-- Think of rgb as a template for members of Color that are expected.
local rgb = { [ 1 ] = "r", [ 2 ] = "g", [ 3 ] = "b", [ 4 ] = "a", r = "r", g = "g", b = "b", a = "a" }
--- __newindex metamethod
function color_metatable.__newindex ( t, k, v )
if rgb[ k ] then
rawset( SF.UnwrapObject( t ), rgb[ k ], v )
else
rawset( t, k, v )
end
end
--- __index metamethod
function color_metatable.__index ( t, k )
if rgb[ k ] then
return rawget( SF.UnwrapObject( t ), rgb[ k ] )
else
return rawget( t, k )
end
end
--- __tostring metamethod
function color_metatable:__tostring ()
return unwrap( self ):__tostring()
end
--- __concat metamethod
function color_metatable.__concat ( ... )
local t = { ... }
return tostring( t[ 1 ] ) .. tostring( t[ 2 ] )
end
--- __eq metamethod
function color_metatable:__eq ( c )
SF.CheckType( self, color_metatable )
SF.CheckType( c, color_metatable )
return unwrap( self ):__eq( unwrap( c ) )
end
--- Converts the color from RGB to HSV.
--@shared
--@return A triplet of numbers representing HSV.
function color_methods:toHSV ()
return ColorToHSV( unwrap( self ) )
end
|
SF.Color = {}
--- Color type
--@shared
local color_methods, color_metatable = SF.Typedef( "Color" )
local wrap, unwrap = SF.CreateWrapper( color_metatable, true, false, debug.getregistry().Color )
SF.Color.Methods = color_methods
SF.Color.Metatable = color_metatable
SF.Color.Wrap = wrap
SF.Color.Unwrap = unwrap
--- Same as the Gmod Color type
-- @name SF.DefaultEnvironment.Color
-- @class function
-- @param r - Red
-- @param g - Green
-- @param b - Blue
-- @param a - Alpha
-- @return New color
SF.DefaultEnvironment.Color = function ( ... )
return wrap( Color( ... ) )
end
-- Lookup table.
-- Index 1->4 have associative rgba for use in __index. Saves lots of checks
-- String based indexing returns string, just a pass through.
-- Think of rgb as a template for members of Color that are expected.
local rgb = { [ 1 ] = "r", [ 2 ] = "g", [ 3 ] = "b", [ 4 ] = "a", r = "r", g = "g", b = "b", a = "a" }
--- __newindex metamethod
function color_metatable.__newindex ( t, k, v )
if rgb[ k ] then
rawset( SF.UnwrapObject( t ), rgb[ k ], v )
else
rawset( t, k, v )
end
end
local _p = color_metatable.__index
--- __index metamethod
function color_metatable.__index ( t, k )
if rgb[ k ] then
return rawget( SF.UnwrapObject( t ), rgb[ k ] )
else
return _p[ k ]
end
end
--- __tostring metamethod
function color_metatable:__tostring ()
return unwrap( self ):__tostring()
end
--- __concat metamethod
function color_metatable.__concat ( ... )
local t = { ... }
return tostring( t[ 1 ] ) .. tostring( t[ 2 ] )
end
--- __eq metamethod
function color_metatable:__eq ( c )
SF.CheckType( self, color_metatable )
SF.CheckType( c, color_metatable )
return unwrap( self ):__eq( unwrap( c ) )
end
--- Converts the color from RGB to HSV.
--@shared
--@return A triplet of numbers representing HSV.
function color_methods:toHSV ()
return ColorToHSV( unwrap( self ) )
end
|
Fixed Color indexing
|
Fixed Color indexing
Fixes issue #311
|
Lua
|
bsd-3-clause
|
Jazzelhawk/Starfall,INPStarfall/Starfall,Ingenious-Gaming/Starfall,Xandaros/Starfall,Jazzelhawk/Starfall,Xandaros/Starfall,Ingenious-Gaming/Starfall,INPStarfall/Starfall
|
c4aa481e00910cf9165d55fb71d8eddf70d00eff
|
scripts/genie.lua
|
scripts/genie.lua
|
local BASE_DIR = path.getabsolute("..")
local EXTERN_DIR = path.join(BASE_DIR, "extern")
local OVR_DIR = path.join(EXTERN_DIR, "LibOVR")
local use_ovr = false
solution "lua-bgfx" do
uuid "8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942"
configurations { "Debug", "Release" }
platforms { "Native", "x32", "x64" }
startproject "lua-bgfx"
targetdir(path.join(BASE_DIR, "bin"))
objdir(path.join(BASE_DIR, "obj"))
configuration { "Debug" }
flags { "Symbols" }
configuration {}
end
if os.get() == "windows" then
SDL_DIR = path.join(EXTERN_DIR, "sdl")
project "SDL2" do
uuid "3ABE8B7C-26F5-8C0D-CFE1-7210BBF7080F"
targetname "SDL2"
kind "SharedLib"
language "C++"
local headers = os.matchfiles(path.join(SDL_DIR, "include") .. "/*.h")
local dir = path.join(BASE_DIR, "scripts/include")
os.mkdir(dir)
os.mkdir(path.join(dir, "SDL2"))
for _, header in pairs(headers) do
local file = path.getname(header)
local folder = path.join(dir, "SDL2")
local path = path.join(folder, file)
os.copyfile(header, path)
end
local SDL_SRC = path.join(SDL_DIR, "src")
includedirs {
path.join(SDL_DIR, "include")
}
-- common files
files {
path.join(SDL_SRC, "*.c"),
path.join(SDL_SRC, "atomic/*.c"),
path.join(SDL_SRC, "audio/*.c"),
path.join(SDL_SRC, "audio/dummy/*.c"),
path.join(SDL_SRC, "audio/disk/*.c"),
path.join(SDL_SRC, "core/*.c"),
path.join(SDL_SRC, "cpuinfo/*.c"),
path.join(SDL_SRC, "dynapi/*.c"),
path.join(SDL_SRC, "events/*.c"),
path.join(SDL_SRC, "file/*.c"),
path.join(SDL_SRC, "filesystem/dummy/*.c"),
path.join(SDL_SRC, "haptic/*.c"),
path.join(SDL_SRC, "haptic/dummy/*.c"),
path.join(SDL_SRC, "joystick/*.c"),
path.join(SDL_SRC, "joystick/dummy/*.c"),
path.join(SDL_SRC, "libm/*.c"),
path.join(SDL_SRC, "loadso/*.c"),
path.join(SDL_SRC, "main/*.c"),
path.join(SDL_SRC, "power/*.c"),
path.join(SDL_SRC, "render/*.c"),
path.join(SDL_SRC, "stdlib/*.c"),
path.join(SDL_SRC, "thread/*.c"),
path.join(SDL_SRC, "timer/*.c"),
path.join(SDL_SRC, "timer/dummy/*.c"),
path.join(SDL_SRC, "video/*.c"),
path.join(SDL_SRC, "video/dummy/*.c")
}
configuration { "windows", "vs*" }
files {
path.join(SDL_SRC, "audio/directsound/*.c"),
-- this is, apparently, possible.
path.join(SDL_SRC, "audio/pulseaudio/*.c"),
path.join(SDL_SRC, "audio/xaudio2/*.c"),
path.join(SDL_SRC, "audio/winmm/*.c"),
path.join(SDL_SRC, "core/windows/*.c"),
path.join(SDL_SRC, "filesystem/windows/*.c"),
path.join(SDL_SRC, "haptic/windows/*.c"),
path.join(SDL_SRC, "joystick/windows/*.c"),
path.join(SDL_SRC, "loadso/windows/*.c"),
path.join(SDL_SRC, "power/windows/*.c"),
path.join(SDL_SRC, "render/direct3d/*.c"),
path.join(SDL_SRC, "render/direct3d11/*.c"),
path.join(SDL_SRC, "render/opengl/*.c"),
path.join(SDL_SRC, "render/opengles/*.c"),
path.join(SDL_SRC, "render/opengles2/*.c"),
path.join(SDL_SRC, "render/software/*.c"),
path.join(SDL_SRC, "thread/generic/SDL_syscond.c"),
path.join(SDL_SRC, "thread/windows/*.c"),
path.join(SDL_SRC, "timer/windows/*.c"),
path.join(SDL_SRC, "video/windows/*.c")
}
links {
"version",
"imm32",
"dxguid",
"xinput",
"winmm"
}
end
end
local function link_ovr()
-- 32-bit
configuration {"vs2013"}
libdirs { path.join(OVR_DIR, "Lib/Windows/Win32/Release/VS2013") }
configuration {"vs2015"}
libdirs { path.join(OVR_DIR, "Lib/Windows/Win32/Release/VS2015") }
-- 64-bit
-- configuration {"vs2013", "x64"}
-- libdirs { path.join(OVR_DIR, "Lib/Windows/x64/Release/VS2013") }
-- configuration {"vs2015", "x64"}
-- libdirs { path.join(OVR_DIR, "Lib/Windows/x64/Release/VS2015") }
configuration {"vs*"}
includedirs { path.join(OVR_DIR, "Include") }
links { "LibOVR" }
end
project "BGFX" do
uuid "EC77827C-D8AE-830D-819B-69106DB1FF0E"
targetname "bgfx_s"
kind "StaticLib"
language "C++"
local BX_DIR = path.join(EXTERN_DIR, "bx/include")
local BGFX_DIR = path.join(EXTERN_DIR, "bgfx")
local BGFX_SRC_DIR = path.join(BGFX_DIR, "src")
includedirs {
path.join(BGFX_DIR, "include"),
path.join(BGFX_DIR, "3rdparty/khronos"),
path.join(BGFX_DIR, "3rdparty"),
BGFX_SRC_DIR,
BX_DIR
}
files {
path.join(BGFX_SRC_DIR, "amalgamated.cpp"),
}
configuration {"vs*"}
if use_ovr and os.isdir(OVR_DIR) then
defines {
"BGFX_CONFIG_USE_OVR=1",
"BGFX_CONFIG_MULTITHREADED=0"
}
link_ovr()
end
configuration {"vs*"}
defines { "_CRT_SECURE_NO_WARNINGS" }
links {
"psapi"
}
includedirs {
path.join(BGFX_DIR, "3rdparty/dxsdk/include"),
path.join(BX_DIR, "compat/msvc")
}
configuration {"gmake"}
buildoptions {
"-fpic",
"-mstackrealign"
}
end
project "lua-bgfx" do
uuid "BB11813B-A7DE-DB46-D0F7-C9EEBC2311D5"
targetprefix ""
targetname "bgfx"
kind "SharedLib"
language "C++"
files {
path.join(BASE_DIR, "wrap_bgfx.cpp")
}
links {
"BGFX"
}
includedirs {
path.join(EXTERN_DIR, "bgfx/include"),
path.join(EXTERN_DIR, "bx/include")
}
configuration {"vs*"}
defines { "_CRT_SECURE_NO_WARNINGS" }
includedirs {
path.join(EXTERN_DIR, "luajit/src"),
path.join(BASE_DIR, "scripts/include"),
EXTERN_DIR
}
libdirs {
path.join(EXTERN_DIR, "luajit/src"),
}
links {
"version",
"imm32",
"dxguid",
"xinput",
"winmm",
"SDL2",
"lua51",
"psapi"
}
if use_ovr and os.isdir(OVR_DIR) then
link_ovr()
end
configuration {"linux"}
includedirs {
"/usr/include/luajit-2.0"
}
links {
"luajit-5.1",
"GL",
"SDL2"
}
linkoptions {
"-pthread"
}
configuration {"gmake"}
buildoptions {
"-std=c++11",
"-fno-strict-aliasing",
"-Wall",
"-Wextra",
"-mstackrealign"
}
end
|
local BASE_DIR = path.getabsolute("..")
local EXTERN_DIR = path.join(BASE_DIR, "extern")
local OVR_DIR = path.join(EXTERN_DIR, "LibOVR")
local use_ovr = false
solution "lua-bgfx" do
uuid "8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942"
configurations { "Debug", "Release" }
platforms { "Native", "x32", "x64" }
startproject "lua-bgfx"
targetdir(path.join(BASE_DIR, "bin"))
objdir(path.join(BASE_DIR, "obj"))
configuration { "Debug" }
flags { "Symbols" }
configuration {}
end
if os.get() == "windows" then
SDL_DIR = path.join(EXTERN_DIR, "sdl")
project "SDL2" do
uuid "3ABE8B7C-26F5-8C0D-CFE1-7210BBF7080F"
targetname "SDL2"
kind "SharedLib"
language "C++"
local headers = os.matchfiles(path.join(SDL_DIR, "include") .. "/*.h")
local dir = path.join(BASE_DIR, "scripts/include")
os.mkdir(dir)
os.mkdir(path.join(dir, "SDL2"))
for _, header in pairs(headers) do
local file = path.getname(header)
local folder = path.join(dir, "SDL2")
local path = path.join(folder, file)
os.copyfile(header, path)
end
local SDL_SRC = path.join(SDL_DIR, "src")
includedirs {
path.join(SDL_DIR, "include")
}
-- common files
files {
path.join(SDL_SRC, "*.c"),
path.join(SDL_SRC, "atomic/*.c"),
path.join(SDL_SRC, "audio/*.c"),
path.join(SDL_SRC, "audio/dummy/*.c"),
path.join(SDL_SRC, "audio/disk/*.c"),
path.join(SDL_SRC, "core/*.c"),
path.join(SDL_SRC, "cpuinfo/*.c"),
path.join(SDL_SRC, "dynapi/*.c"),
path.join(SDL_SRC, "events/*.c"),
path.join(SDL_SRC, "file/*.c"),
path.join(SDL_SRC, "filesystem/dummy/*.c"),
path.join(SDL_SRC, "haptic/*.c"),
path.join(SDL_SRC, "haptic/dummy/*.c"),
path.join(SDL_SRC, "joystick/*.c"),
path.join(SDL_SRC, "joystick/dummy/*.c"),
path.join(SDL_SRC, "libm/*.c"),
path.join(SDL_SRC, "loadso/*.c"),
path.join(SDL_SRC, "main/*.c"),
path.join(SDL_SRC, "power/*.c"),
path.join(SDL_SRC, "render/*.c"),
path.join(SDL_SRC, "stdlib/*.c"),
path.join(SDL_SRC, "thread/*.c"),
path.join(SDL_SRC, "timer/*.c"),
path.join(SDL_SRC, "timer/dummy/*.c"),
path.join(SDL_SRC, "video/*.c"),
path.join(SDL_SRC, "video/dummy/*.c")
}
configuration { "windows", "vs*" }
files {
path.join(SDL_SRC, "audio/directsound/*.c"),
-- this is, apparently, possible.
path.join(SDL_SRC, "audio/pulseaudio/*.c"),
path.join(SDL_SRC, "audio/xaudio2/*.c"),
path.join(SDL_SRC, "audio/winmm/*.c"),
path.join(SDL_SRC, "core/windows/*.c"),
path.join(SDL_SRC, "filesystem/windows/*.c"),
path.join(SDL_SRC, "haptic/windows/*.c"),
path.join(SDL_SRC, "joystick/windows/*.c"),
path.join(SDL_SRC, "loadso/windows/*.c"),
path.join(SDL_SRC, "power/windows/*.c"),
path.join(SDL_SRC, "render/direct3d/*.c"),
path.join(SDL_SRC, "render/direct3d11/*.c"),
path.join(SDL_SRC, "render/opengl/*.c"),
path.join(SDL_SRC, "render/opengles/*.c"),
path.join(SDL_SRC, "render/opengles2/*.c"),
path.join(SDL_SRC, "render/software/*.c"),
path.join(SDL_SRC, "thread/generic/SDL_syscond.c"),
path.join(SDL_SRC, "thread/windows/*.c"),
path.join(SDL_SRC, "timer/windows/*.c"),
path.join(SDL_SRC, "video/windows/*.c")
}
links {
"version",
"imm32",
"dxguid",
"xinput",
"winmm"
}
end
end
local function link_ovr()
-- 32-bit
configuration {"vs2013"}
libdirs { path.join(OVR_DIR, "Lib/Windows/Win32/Release/VS2013") }
configuration {"vs2015"}
libdirs { path.join(OVR_DIR, "Lib/Windows/Win32/Release/VS2015") }
-- 64-bit
-- configuration {"vs2013", "x64"}
-- libdirs { path.join(OVR_DIR, "Lib/Windows/x64/Release/VS2013") }
-- configuration {"vs2015", "x64"}
-- libdirs { path.join(OVR_DIR, "Lib/Windows/x64/Release/VS2015") }
configuration {"vs*"}
includedirs { path.join(OVR_DIR, "Include") }
links { "LibOVR" }
end
project "BGFX" do
uuid "EC77827C-D8AE-830D-819B-69106DB1FF0E"
targetname "bgfx_s"
kind "StaticLib"
language "C++"
local BX_DIR = path.join(EXTERN_DIR, "bx/include")
local BGFX_DIR = path.join(EXTERN_DIR, "bgfx")
local BGFX_SRC_DIR = path.join(BGFX_DIR, "src")
includedirs {
path.join(BGFX_DIR, "include"),
path.join(BGFX_DIR, "3rdparty/khronos"),
path.join(BGFX_DIR, "3rdparty"),
BGFX_SRC_DIR,
BX_DIR
}
files {
path.join(BGFX_SRC_DIR, "amalgamated.cpp"),
}
configuration {"vs*"}
if use_ovr and os.isdir(OVR_DIR) then
defines {
"BGFX_CONFIG_USE_OVR=1",
"BGFX_CONFIG_MULTITHREADED=0"
}
link_ovr()
end
configuration {"vs*"}
defines { "_CRT_SECURE_NO_WARNINGS" }
links {
"psapi"
}
includedirs {
path.join(BGFX_DIR, "3rdparty/dxsdk/include"),
path.join(BX_DIR, "compat/msvc")
}
configuration {"gmake"}
buildoptions {
"-std=c++11",
"-fno-strict-aliasing",
"-fpic",
"-mstackrealign"
}
end
project "lua-bgfx" do
uuid "BB11813B-A7DE-DB46-D0F7-C9EEBC2311D5"
targetprefix ""
targetname "bgfx"
kind "SharedLib"
language "C++"
files {
path.join(BASE_DIR, "wrap_bgfx.cpp")
}
links {
"BGFX"
}
includedirs {
path.join(EXTERN_DIR, "bgfx/include"),
path.join(EXTERN_DIR, "bx/include")
}
configuration {"vs*"}
defines { "_CRT_SECURE_NO_WARNINGS" }
includedirs {
path.join(EXTERN_DIR, "luajit/src"),
path.join(BASE_DIR, "scripts/include"),
EXTERN_DIR
}
libdirs {
path.join(EXTERN_DIR, "luajit/src"),
}
links {
"version",
"imm32",
"dxguid",
"xinput",
"winmm",
"SDL2",
"lua51",
"psapi"
}
if use_ovr and os.isdir(OVR_DIR) then
link_ovr()
end
configuration {"linux"}
includedirs {
"/usr/include/luajit-2.0"
}
links {
"luajit-5.1",
"GL",
"SDL2"
}
linkoptions {
"-pthread"
}
configuration {"gmake"}
buildoptions {
"-std=c++11",
"-fno-strict-aliasing",
"-Wall",
"-Wextra",
"-mstackrealign"
}
end
|
fix build against new bgfx
|
fix build against new bgfx
|
Lua
|
mit
|
excessive/lua-bgfx,excessive/lua-bgfx
|
a8de6bf219be25eb38536be0fb94ff9ea3908a58
|
src/Lua/Searches/expectimax.lua
|
src/Lua/Searches/expectimax.lua
|
local currentState = State.new(nil)
currentState.Tiles = {
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0
}
math.randomseed(os.time())
currentState.Tiles[math.random(#currentState.Tiles)] = math.random(2)*2
currentState:Print()
function Max_Value(state)
local val = -math.huge
for k, successor in pairs(state.Tree) do
if (val<successor.Heuristic) then
val = successor.Heuristic
end
end
return val
end
function Exp_Value(state) -- when looking at
local val = 0
local probability = 1/(#state.Tree)
for k, successor in pairs(state.Tree) do
val = val+probability*successor.Heuristic
end
return val
end
function Expectimax(state)
state:Branch()
decisions = {}
if (state.MoveCount>0) then
for a, b in pairs(state.Tree) do
b:Spawn()
if (#b.Tree~=0) then
for c, d in pairs(b.Tree) do
d:Branch()
if (d.MoveCount>0) then
for e, f in pairs(d.Tree) do
f:Spawn()
if (#f.Tree~=0) then
for g, h in pairs(f.Tree) do
h:Branch()
if (h.MoveCount>0) then
for i, j in pairs(h.Tree) do
local heuristic = Heuristics.Emptiness(j)*2 + Heuristics.Monotonicity(j)--Heuristics.Score(j)
j.Heuristic = heuristic
end
h.Heuristic = Max_Value(h)
else
local heuristic = Heuristics.Emptiness(h)*2 + Heuristics.Monotonicity(h)--Heuristics.Score(j)
h.Heuristic = heuristic
end
end
f.Heuristic = Exp_Value(f)
else
local heuristic = Heuristics.Emptiness(f)*2 + Heuristics.Monotonicity(f)--Heuristics.Score(j)
f.Heuristic = heuristic
end
end
d.Heuristic = Max_Value(d)
else
local heuristic = Heuristics.Emptiness(d)*2 + Heuristics.Monotonicity(d)--Heuristics.Score(j)
d.Heuristic = heuristic
end
end
b.Heuristic = Exp_Value(b)
else
local heuristic = Heuristics.Emptiness(b)*2 + Heuristics.Monotonicity(b)--Heuristics.Score(j)
b.Heuristic = heuristic
end
end
state.Heuristic = Max_Value(state)
else
local heuristic = Heuristics.Emptiness(state)*2 + Heuristics.Monotonicity(state)--Heuristics.Score(j)
state.Heuristic = heuristic
end
local max_currentState = -math.huge
local choice_currentState = nil
for a, b in pairs(currentState.Tree) do
if (max_currentState<b.Heuristic) then
max_currentState = b.Heuristic
choice_currentState = a
end
end
return choice_currentState
end
while (true) do
clear()
print("Current Score: "..Heuristics.Score(currentState))
currentState:Print()
local direction = Expectimax(currentState)
currentState = currentState.Tree[direction]
print("Moved to...")
if (currentState==nil) then
print("Nothing; there are no more moves/the program knows it will fail shortly")
wait(2.5)
break
end
currentState:Print()
print("Spawning...")
currentState.Tree = {}
currentState:Spawn()
if (#currentState.Tree)~=0 then
currentState = currentState.Tree[math.random(#currentState.Tree)]
currentState:Print()
else
currentState:Print()
break
end
end
print()
|
local currentState = State.new(nil)
currentState.Tiles = {
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0
}
math.randomseed(os.time())
currentState.Tiles[math.random(#currentState.Tiles)] = math.random(2)*2
currentState:Print()
function Max_Value(state)
local val = -math.huge
for k, successor in pairs(state.Tree) do
if (val<successor.Heuristic) then
val = successor.Heuristic
end
end
return val
end
function Exp_Value(state) -- when looking at
local val = 0
local probability = 1/(#state.Tree)
for k, successor in pairs(state.Tree) do
val = val+probability*successor.Heuristic
end
return val
end
function Expectimax(state)
state:Branch()
decisions = {}
if (state.MoveCount>0) then
for a, b in pairs(state.Tree) do
b:Spawn()
if (#b.Tree~=0) then
for c, d in pairs(b.Tree) do
d:Branch()
if (d.MoveCount>0) then
for e, f in pairs(d.Tree) do
f:Spawn()
if (#f.Tree~=0) then
for g, h in pairs(f.Tree) do
h:Branch()
if (h.MoveCount>0) then
for i, j in pairs(h.Tree) do
local heuristic = Heuristics.Emptiness(j)*2 + Heuristics.Monotonicity(j)--Heuristics.Score(j)
j.Heuristic = heuristic
end
h.Heuristic = Max_Value(h)
else
local heuristic = Heuristics.Emptiness(h)*2 + Heuristics.Monotonicity(h)--Heuristics.Score(j)
h.Heuristic = heuristic
end
h.Tree = nil
end
f.Heuristic = Exp_Value(f)
else
local heuristic = Heuristics.Emptiness(f)*2 + Heuristics.Monotonicity(f)--Heuristics.Score(j)
f.Heuristic = heuristic
end
f.Tree = nil
end
d.Heuristic = Max_Value(d)
else
local heuristic = Heuristics.Emptiness(d)*2 + Heuristics.Monotonicity(d)--Heuristics.Score(j)
d.Heuristic = heuristic
end
d.Tree = nil
end
b.Heuristic = Exp_Value(b)
else
local heuristic = Heuristics.Emptiness(b)*2 + Heuristics.Monotonicity(b)--Heuristics.Score(j)
b.Heuristic = heuristic
end
b.Tree = nil
end
state.Heuristic = Max_Value(state)
else
local heuristic = Heuristics.Emptiness(state)*2 + Heuristics.Monotonicity(state)--Heuristics.Score(j)
state.Heuristic = heuristic
end
local max_currentState = -math.huge
local choice_currentState = nil
for a, b in pairs(currentState.Tree) do
if (max_currentState<b.Heuristic) then
max_currentState = b.Heuristic
choice_currentState = a
end
end
return choice_currentState
end
while (true) do
clear()
print("Current Score: "..Heuristics.Score(currentState))
currentState:Print()
local direction = Expectimax(currentState)
currentState = currentState.Tree[direction]
currentState.Tree = nil
print("Moved to...")
if (currentState==nil) then
print("Nothing; there are no more moves/the program knows it will fail shortly")
wait(2.5)
break
end
currentState:Print()
print("Spawning...")
currentState.Tree = {}
currentState:Spawn()
if (#currentState.Tree)~=0 then
currentState = currentState.Tree[math.random(#currentState.Tree)]
currentState:Print()
else
currentState:Print()
break
end
end
print()
|
Fixed memory leak
|
Fixed memory leak
|
Lua
|
mit
|
ioltuszyk/Slider,ioltuszyk/Slider
|
6bc7fc33d890c744e563990f9a76110ea177a91c
|
src/ubus.lua
|
src/ubus.lua
|
#!/usr/bin/lua
-- WANT_JSON
local Ansible = require("ansible")
local ubus = require("ubus")
local json = require("dkjson")
function list(module)
check_parameters(module, {"path"})
local path = module:get_params()['path']
local conn = module:ubus_connect()
local list = {}
local namespaces = conn:objects()
if not namespaces then
module:fail_json({msg="Failed to enumerate ubus"})
end
for _, n in ipairs(namespaces) do
if not path or Ansible.contains(n, path) then
local signatures = conn:signatures(n)
if not signatures then
module:fail_json({msg="Failed to enumerate ubus"})
end
list[n] = signatures
end
end
conn:close()
module:exit_json({msg="Gathered local signatures", signatures=list})
end
function call(module)
check_parameters(module, {"path", "method", "message"})
local p = module:get_params()
local path = p["path"]
if 1 ~= #path then
module:fail_json({msg="Call only allows one path element, but zero or 2+ were given"})
else
path = path[1]
end
local conn = module:ubus_connect()
local res = module:ubus_call(conn, path, p['method'], p['message'])
conn:close()
module:exit_json({msg=string.format("Called %s.%s(%s)", path, p['method'], json.encode(p['message'])), result=res, changed=true})
end
function send(module)
-- - send <type> [<message>] Send an event
check_parameters(module, {"type", "message"})
local p = module:get_params()
local conn = module:ubus_connect()
local res, status = conn:send(p["type"], p["message"])
if not res then
module:fail_json({msg="Failed to send event", status=status})
end
conn:close()
module:exit_json({msg="Event sent successfully", result=res, changed=true})
end
function facts(module)
check_parameters(module, {})
local conn = module:ubus_connect()
local facts = {}
local namespaces = conn:objects()
for _,n in ipairs(namespaces) do
if "network.device" == n
or 1 == string.find(n, "network.interface.")
or "network.wireless" == n then
facts[n] = module:ubus_call(conn, n, "status", {})
elseif "service" == n then
-- list {}
facts[n] = module:ubus_call(conn, n, "list", {})
elseif "system" == n then
-- board {}
-- info {}
local f = {}
f["board"] = module:ubus_call(conn, n, "board", {})
f["info"] = module:ubus_call(conn, n, "info", {})
facts[n] = f
elseif "uci" == n then
-- configs {}
-- foreach configs...
local f = {}
f["configs"] = module:ubus_call(conn, n, "configs", {})
f["state"] = {}
for _,conf in ipairs(f["configs"]) do
-- TODO: transform unnamed sections to their anonymous names
f["state"]["conf"] = module:ubus_call( conn, n, "state", {config=conf})
end
facts[n] = f
end
end
conn:close()
module:exit_json({msg="All available facts gathered", ansible_facts=facts})
end
function check_parameters(module, valid)
local p = module:get_params()
local i = 0
for k,_ in pairs(p) do
-- not a buildin command and not a valid entry
if 1 ~= string.find(k, "_ansible")
and k ~= "socket"
and k ~= "timeout"
and k ~= "command" then
i = i+1
if((not Ansible.contains(k, valid))) then
module:fail_json({msg=string.format("Parameter %q invalid for command %s", k, p['command'])})
end
end
end
return i
end
function main(arg)
-- module models the ubus cli tools structure
-- Usage: ubus [<options>] <command> [arguments...]
-- Options:
-- -s <socket>: Set the unix domain socket to connect to
-- -t <timeout>: Set the timeout (in seconds) for a command to complete
-- -S: Use simplified output (for scripts)
-- -v: More verbose output
--
-- Commands:
-- - list [<path>] List objects
-- - call <path> <method> [<message>] Call an object method
-- - send <type> [<message>] Send an event
local module = Ansible.new({
command = { aliases = {"cmd"}, required=true , choices={"list", "call", "send", "facts"}},
path = { type="list" },
method = { type="str" },
type = { type="str" },
message = { type="jsonarg" },
socket = { type="path" },
timeout = { type="int"}
})
module:parse(arg[1])
local p = module:get_params()
local dispatcher = {
list = list,
call = call,
send = send,
facts = facts
}
dispatcher[p['command']](module)
end
main(arg)
|
#!/usr/bin/lua
-- WANT_JSON
local Ansible = require("ansible")
local ubus = require("ubus")
local json = require("dkjson")
function list(module)
check_parameters(module, {"path"})
local path = module:get_params()['path']
local conn = module:ubus_connect()
local list = {}
local namespaces = conn:objects()
if not namespaces then
module:fail_json({msg="Failed to enumerate ubus"})
end
for _, n in ipairs(namespaces) do
if not path or Ansible.contains(n, path) then
local signatures = conn:signatures(n)
if not signatures then
module:fail_json({msg="Failed to enumerate ubus"})
end
list[n] = signatures
end
end
conn:close()
module:exit_json({msg="Gathered local signatures", signatures=list})
end
function call(module)
check_parameters(module, {"path", "method", "message"})
local p = module:get_params()
local path = p["path"]
if 1 ~= #path then
module:fail_json({msg="Call only allows one path element, but zero or 2+ were given"})
else
path = path[1]
end
local conn = module:ubus_connect()
local res = module:ubus_call(conn, path, p['method'], p['message'])
conn:close()
module:exit_json({msg=string.format("Called %s.%s(%s)", path, p['method'], json.encode(p['message'])), result=res, changed=true})
end
function send(module)
-- - send <type> [<message>] Send an event
check_parameters(module, {"type", "message"})
local p = module:get_params()
local conn = module:ubus_connect()
local res, status = conn:send(p["type"], p["message"])
if not res then
module:fail_json({msg="Failed to send event", status=status})
end
conn:close()
module:exit_json({msg="Event sent successfully", result=res, changed=true})
end
function facts(module)
check_parameters(module, {})
local conn = module:ubus_connect()
local facts = {}
local namespaces = conn:objects()
for _,n in ipairs(namespaces) do
if "network.device" == n
or 1 == string.find(n, "network.interface.")
or "network.wireless" == n then
facts[n] = module:ubus_call(conn, n, "status", {})
elseif "service" == n then
-- list {}
facts[n] = module:ubus_call(conn, n, "list", {})
elseif "system" == n then
-- board {}
-- info {}
local f = {}
f["board"] = module:ubus_call(conn, n, "board", {})
f["info"] = module:ubus_call(conn, n, "info", {})
facts[n] = f
elseif "uci" == n then
-- configs {}
-- foreach configs...
local f = {}
local configs = module:ubus_call(conn, n, "configs", {})['configs']
f["configs"] = configs
f["state"] = {}
for _,conf in ipairs(configs) do
-- TODO: transform unnamed sections to their anonymous names
f["state"][conf] = module:ubus_call( conn, n, "state", {config=conf})['values']
end
facts[n] = f
end
end
conn:close()
module:exit_json({msg="All available facts gathered", ansible_facts=facts})
end
function check_parameters(module, valid)
local p = module:get_params()
local i = 0
for k,_ in pairs(p) do
-- not a buildin command and not a valid entry
if 1 ~= string.find(k, "_ansible")
and k ~= "socket"
and k ~= "timeout"
and k ~= "command" then
i = i+1
if((not Ansible.contains(k, valid))) then
module:fail_json({msg=string.format("Parameter %q invalid for command %s", k, p['command'])})
end
end
end
return i
end
function main(arg)
-- module models the ubus cli tools structure
-- Usage: ubus [<options>] <command> [arguments...]
-- Options:
-- -s <socket>: Set the unix domain socket to connect to
-- -t <timeout>: Set the timeout (in seconds) for a command to complete
-- -S: Use simplified output (for scripts)
-- -v: More verbose output
--
-- Commands:
-- - list [<path>] List objects
-- - call <path> <method> [<message>] Call an object method
-- - send <type> [<message>] Send an event
local module = Ansible.new({
command = { aliases = {"cmd"}, required=true , choices={"list", "call", "send", "facts"}},
path = { type="list" },
method = { type="str" },
type = { type="str" },
message = { type="jsonarg" },
socket = { type="path" },
timeout = { type="int"}
})
module:parse(arg[1])
local p = module:get_params()
local dispatcher = {
list = list,
call = call,
send = send,
facts = facts
}
dispatcher[p['command']](module)
end
main(arg)
|
fix uci facts collection
|
fix uci facts collection
|
Lua
|
agpl-3.0
|
noctux/philote,noctux/philote
|
0cf237c87d8dfc9e10c435927939b104240532eb
|
src/cosy/daemon-handler.lua
|
src/cosy/daemon-handler.lua
|
local Configuration = require "cosy.configuration"
local I18n = require "cosy.i18n"
local Library = require "cosy.library"
local Value = require "cosy.value"
Configuration.load {
"cosy.daemon",
"cosy.server",
}
local i18n = I18n.load {
"cosy.daemon",
"cosy.server",
}
i18n._locale = Configuration.locale._
local libraries = {}
return function (message)
local decoded, request = pcall (Value.decode, message)
if not decoded or type (request) ~= "table" then
return Value.expression ({
success = false,
error = i18n {
_ = i18n ["message:invalid"],
},
})
end
local server = request.server
local lib = libraries [server]
if not lib then
lib = Library.connect (server)
if not lib then
return {
success = false,
error = {
_ = i18n ["server:unreachable"] % {},
},
}
end
libraries [server] = lib
end
local method = lib [request.operation]
local result, err = method (request.parameters, request.try_only)
if result then
result = {
success = true,
response = result,
}
else
result = {
success = false,
error = err,
}
end
return Value.expression (result)
end
|
local Configuration = require "cosy.configuration"
local I18n = require "cosy.i18n"
local Library = require "cosy.library"
local Value = require "cosy.value"
Configuration.load {
"cosy.daemon",
"cosy.server",
}
local i18n = I18n.load {
"cosy.daemon",
"cosy.server",
}
i18n._locale = Configuration.locale._
local libraries = {}
return function (message)
local decoded, request = pcall (Value.decode, message)
if not decoded or type (request) ~= "table" then
return Value.expression (i18n {
success = false,
error = i18n {
_ = i18n ["message:invalid"] % {},
},
})
end
local server = request.server
local lib = libraries [server]
if not lib then
lib = Library.connect (server)
if not lib then
return Value.expression (i18n {
success = false,
error = {
_ = i18n ["server:unreachable"] % {},
},
})
end
libraries [server] = lib
end
local method = lib [request.operation]
local result, err = method (request.parameters, request.try_only)
if result then
result = {
success = true,
response = result,
}
else
result = {
success = false,
error = err,
}
end
return Value.expression (result)
end
|
Fix error messages.
|
Fix error messages.
|
Lua
|
mit
|
CosyVerif/library,CosyVerif/library,CosyVerif/library
|
d549ad79e19f9c9201e63b7cfcbdf56c243bc893
|
build/premake5.lua
|
build/premake5.lua
|
function SetTarget( _configuration, _platform, _basepath )
local platformname = _platform
local archname = _platform
if _platform == "x32" then
platformname = "Win32"
archname = "x86"
end
local strtarget = string.format( "%s/bin/%s_%s/", _basepath, _configuration, platformname )
local strobj = string.format( "%s/intermediate/%s_%s", _basepath, _configuration, platformname )
configuration {_configuration, _platform}
targetdir( strtarget )
objdir( strobj )
end
function SetLibs( _configuration, _platform, _basepath )
local platformname = _platform
local archname = _platform
if _platform == "x32" then
platformname = "Win32"
archname = "x86"
end
local strGlew = string.format( "%s/3rdparty/glew-1.13.0/lib/%s/%s", _basepath, _configuration, platformname )
local strSdl2 = string.format( "%s/3rdparty/SDL2-2.0.3/lib/%s/%s", _basepath, platformname, _configuration )
local strImgui = string.format( "%s/3rdparty/imgui/bin/%s-%s-Dll", _basepath, platformname, _configuration )
configuration {_configuration, _platform}
--libdirs { "../../3rdparty\SDL2-2.0.3/lib/x64\$(Configuration);..\..\3rdparty\glew-1.10.0\lib\release\x64;..\..\3rdparty\tinyxml2\tinyxml2\bin\$(Platform)-$(Configuration)-Dll;..\..\3rdparty\imgui\bin\$(Platform)-$(Configuration)-Dll;$(LibraryPath)
libdirs { strGlew, strSdl2, strImgui }
end
--------------------------------------------------------
workspace "fracstar"
configurations { "Debug", "Release" }
configuration "macosx"
platforms { "native" }
configuration "windows"
platforms { "x32", "x64" }
--location "src"
---------------------------------------------------------
project "bigball"
kind "StaticLib"
language "C++"
files { "../../engine/src/**.h", "../../engine/src/**.cpp" }
includedirs { "../../3rdparty/SDL2-2.0.3/include", "../../3rdparty/glew-1.13.0/include", "../../3rdparty/jsmn", "../../3rdparty/imgui", "../../3rdparty" }
defines { "_CRT_SECURE_NO_WARNINGS" }
local targetpath = "../../engine"
configuration "windows"
SetTarget( "Debug", "x32", targetpath )
SetTarget( "Debug", "x64", targetpath )
SetTarget( "Release", "x32", targetpath )
SetTarget( "Release", "x64", targetpath )
configuration "macosx"
SetTarget( "Debug", "native", targetpath )
SetTarget( "Release", "native", targetpath )
---------------------------------------------------------
project "fracstar"
kind "ConsoleApp"
language "C++"
files { "../src/**.h", "../src/**.cpp" }
--removefiles { "3rdparty/**", "mars**" }
targetname "fracstar"
defines { "_CRT_SECURE_NO_WARNINGS", "_WINDOWS", "_USRDLL" }
flags { "NoPCH", "NoNativeWChar", "NoEditAndContinue" }
includedirs { "../../engine/src/", "../../3rdparty", "../../3rdparty/SDL2-2.0.3/include", "../../3rdparty/glew-1.13.0/include", "../../3rdparty/jsmn", "../../3rdparty/imgui", "../../3rdparty/eigen3" }
links { "bigball" } --"user32", "gdi32" }
local targetpath = ".."
local libpath = "../.."
configuration "windows"
SetTarget( "Debug", "x32", targetpath )
SetTarget( "Debug", "x64", targetpath )
SetTarget( "Release", "x32", targetpath )
SetTarget( "Release", "x64", targetpath )
SetLibs( "Debug", "x32", libpath )
SetLibs( "Debug", "x64", libpath )
SetLibs( "Release", "x32", libpath )
SetLibs( "Release", "x64", libpath )
configuration "macosx"
SetTarget( "Debug", "native", targetpath )
SetTarget( "Release", "native", targetpath )
SetLibs( "Debug", "native", libpath )
SetLibs( "Release", "native", libpath )
configuration "Debug"
defines { "_DEBUG" }
flags { "Symbols", "MultiProcessorCompile" }
configuration "Release"
defines { "NDEBUG" }
flags { "Optimize", "Symbols", "MultiProcessorCompile" }
optimize "On"
configuration "macosx"
linkoptions { "-std=c++11" } --, "-stdlib=libc++" }
buildoptions { "-std=c++11" } --, "-stdlib=libc++" }
|
function SetTarget( _configuration, _platform, _basepath )
local platformname = _platform
local archname = _platform
if _platform == "x32" then
platformname = "Win32"
archname = "x86"
end
local strtarget = string.format( "%s/bin/%s_%s/", _basepath, _configuration, platformname )
local strobj = string.format( "%s/intermediate/%s_%s", _basepath, _configuration, platformname )
configuration {_configuration, _platform}
targetdir( strtarget )
objdir( strobj )
end
function SetLibs( _configuration, _platform, _basepath )
local platformname = _platform
local archname = _platform
if _platform == "x32" then
platformname = "Win32"
archname = "x86"
end
local strGlew = string.format( "%s/3rdparty/glew-1.13.0/lib/release/%s", _basepath, platformname )
local strSdl2 = string.format( "%s/3rdparty/SDL2-2.0.3/lib/%s/%s", _basepath, platformname, _configuration )
local strImgui = string.format( "%s/3rdparty/imgui/bin/%s_%s", _basepath, platformname, _configuration )
configuration {_configuration, _platform}
libdirs { strGlew, strSdl2, strImgui }
end
--------------------------------------------------------
workspace "fracstar"
configurations { "Debug", "Release" }
configuration "macosx"
platforms { "native" }
configuration "windows"
platforms { "x32", "x64" }
--location "src"
---------------------------------------------------------
project "bigball"
kind "StaticLib"
language "C++"
files { "../../engine/src/**.h", "../../engine/src/**.cpp" }
includedirs { "../../3rdparty/SDL2-2.0.3/include", "../../3rdparty/glew-1.13.0/include", "../../3rdparty/zlib-1.2.8", "../../3rdparty/jsmn", "../../3rdparty/imgui", "../../3rdparty" }
defines { "_CRT_SECURE_NO_WARNINGS" }
local targetpath = "../../engine"
configuration "windows"
SetTarget( "Debug", "x32", targetpath )
SetTarget( "Debug", "x64", targetpath )
SetTarget( "Release", "x32", targetpath )
SetTarget( "Release", "x64", targetpath )
configuration "macosx"
SetTarget( "Debug", "native", targetpath )
SetTarget( "Release", "native", targetpath )
configuration "Debug"
defines { "_DEBUG" }
flags { "Symbols", "MultiProcessorCompile" }
configuration "Release"
defines { "NDEBUG" }
flags { "Optimize", "Symbols", "MultiProcessorCompile" }
optimize "On"
---------------------------------------------------------
project "fracstar"
kind "ConsoleApp"
language "C++"
files { "../src/**.h", "../src/**.cpp" }
--removefiles { "3rdparty/**", "mars**" }
targetname "fracstar"
defines { "_CRT_SECURE_NO_WARNINGS", "_WINDOWS", "_USRDLL" }
flags { "NoPCH", "NoNativeWChar", "NoEditAndContinue" }
includedirs { "../../engine/src/", "../../3rdparty", "../../3rdparty/SDL2-2.0.3/include", "../../3rdparty/glew-1.13.0/include", "../../3rdparty/zlib-1.2.8", "../../3rdparty/jsmn", "../../3rdparty/imgui", "../../3rdparty/eigen3" }
links { "bigball", "glew32", "sdl2", "imgui" } --"user32", "gdi32" }
local targetpath = ".."
local libpath = "../.."
configuration "windows"
SetTarget( "Debug", "x32", targetpath )
SetTarget( "Debug", "x64", targetpath )
SetTarget( "Release", "x32", targetpath )
SetTarget( "Release", "x64", targetpath )
SetLibs( "Debug", "x32", libpath )
SetLibs( "Debug", "x64", libpath )
SetLibs( "Release", "x32", libpath )
SetLibs( "Release", "x64", libpath )
configuration "macosx"
SetTarget( "Debug", "native", targetpath )
SetTarget( "Release", "native", targetpath )
SetLibs( "Debug", "native", libpath )
SetLibs( "Release", "native", libpath )
configuration "Debug"
defines { "_DEBUG" }
flags { "Symbols", "MultiProcessorCompile" }
configuration "Release"
defines { "NDEBUG" }
flags { "Optimize", "Symbols", "MultiProcessorCompile" }
optimize "On"
configuration "macosx"
linkoptions { "-std=c++11" } --, "-stdlib=libc++" }
buildoptions { "-std=c++11" } --, "-stdlib=libc++" }
|
various fixes to premake conf
|
various fixes to premake conf
|
Lua
|
mit
|
nsweb/fracstar,nsweb/fracstar
|
27f97cdee060e445994ddcfe52912a9581f7b130
|
irc/handlers.lua
|
irc/handlers.lua
|
local pairs = pairs
local error = error
local tonumber = tonumber
local table = table
module "irc"
handlers = {}
handlers["PING"] = function(o, prefix, query)
o:send("PONG :%s", query)
end
handlers["001"] = function(o, prefix, me)
o.authed = true
o.nick = me
end
handlers["PRIVMSG"] = function(o, prefix, channel, message)
o:invoke("OnChat", parsePrefix(prefix), channel, message)
end
handlers["NOTICE"] = function(o, prefix, channel, message)
o:invoke("OnNotice", parsePrefix(prefix), channel, message)
end
handlers["JOIN"] = function(o, prefix, channel)
local user = parsePrefix(prefix)
if o.track_users then
if user.nick == o.nick then
o.channels[channel] = {users = {}}
else
o.channels[channel].users[user.nick] = user
end
end
o:invoke("OnJoin", user, channel)
end
handlers["PART"] = function(o, prefix, channel, reason)
local user = parsePrefix(prefix)
if o.track_users then
if user.nick == o.nick then
o.channels[channel] = nil
else
o.channels[channel].users[user.nick] = nil
end
end
o:invoke("OnPart", user, channel, reason)
end
handlers["QUIT"] = function(o, prefix, msg)
local user = parsePrefix(prefix)
if o.track_users then
for channel, v in pairs(o.channels) do
v.users[user.nick] = nil
end
end
o:invoke("OnQuit", user, msg)
end
handlers["NICK"] = function(o, prefix, newnick)
local user = parsePrefix(prefix)
if o.track_users then
for channel, v in pairs(o.channels) do
local users = v.users
local oldinfo = users[user.nick]
if oldinfo then
users[newnick] = oldinfo
users[newnick].nick = newnick
if users[newnick].fullhost then
users[newnick].fullhost = users[newnick].nick.."!"..users[newnick].username.."@"..users[newnick].host
end
users[user.nick] = nil
o:invoke("NickChange", user, newnick, channel)
end
end
else
o:invoke("NickChange", user, newnick)
end
if user.nick == o.nick then
o.nick = newnick
end
end
local function needNewNick(o, prefix, target, badnick)
local newnick = o.nickGenerator(badnick)
o:send("NICK %s", newnick)
end
-- ERR_ERRONEUSNICKNAME (Misspelt but remains for historical reasons)
handlers["432"] = needNewNick
-- ERR_NICKNAMEINUSE
handlers["433"] = needNewNick
--WHO list
handlers["352"] = function(o, prefix, me, channel, name1, host, serv, name, access1 ,something, something2)
if o.track_users then
local user = {nick=name, host=host, username=name1, serv=serv, access=parseAccess(access1), fullhost=name.."!"..name1.."@"..host}
--print(user.nick,user.host,user.ID,user.serv,user.access)
o.channels[channel].users[user.nick] = user
end
end
--NAMES list
handlers["353"] = function(o, prefix, me, chanType, channel, names)
if o.track_users then
o.channels[channel] = o.channels[channel] or {users = {}, type = chanType}
local users = o.channels[channel].users
for nick in names:gmatch("(%S+)") do
local access, name = parseNick(nick)
users[name] = {access = access}
end
end
end
--end of NAMES
handlers["366"] = function(o, prefix, me, channel, msg)
if o.track_users then
o:invoke("NameList", channel, msg)
end
end
--no topic
handlers["331"] = function(o, prefix, me, channel)
o:invoke("OnTopic", channel, nil)
end
--new topic
handlers["TOPIC"] = function(o, prefix, channel, topic)
o:invoke("OnTopic", channel, topic)
end
handlers["332"] = function(o, prefix, me, channel, topic)
o:invoke("OnTopic", channel, topic)
end
--topic creation info
handlers["333"] = function(o, prefix, me, channel, nick, time)
o:invoke("OnTopicInfo", channel, nick, tonumber(time))
end
handlers["KICK"] = function(o, prefix, channel, kicked, reason)
o:invoke("OnKick", channel, kicked, parsePrefix(prefix), reason)
end
--RPL_UMODEIS
--To answer a query about a client's own mode, RPL_UMODEIS is sent back
handlers["221"] = function(o, prefix, user, modes)
o:invoke("OnUserMode", modes)
end
--RPL_CHANNELMODEIS
--The result from common irc servers differs from that defined by the rfc
handlers["324"] = function(o, prefix, user, channel, modes)
o:invoke("OnChannelMode", channel, modes)
end
handlers["MODE"] = function(o, prefix, target, modes, ...)
if o.track_users and target ~= o.nick then
local add = true
local optList = {...}
for c in modes:gmatch(".") do
if c == "+" then add = true
elseif c == "-" then add = false
elseif c == "o" then
local user = table.remove(optList, 1)
o.channels[target].users[user].access.op = add
elseif c == "h" then
local user = table.remove(optList, 1)
o.channels[target].users[user].access.halfop = add
elseif c == "v" then
local user = table.remove(optList, 1)
o.channels[target].users[user].access.voice = add
end
end
end
o:invoke("OnModeChange", parsePrefix(prefix), target, modes, ...)
end
handlers["ERROR"] = function(o, prefix, message)
o:invoke("OnDisconnect", message, true)
o:shutdown()
error(message, 3)
end
|
local pairs = pairs
local error = error
local tonumber = tonumber
local table = table
module "irc"
handlers = {}
handlers["PING"] = function(o, prefix, query)
o:send("PONG :%s", query)
end
handlers["001"] = function(o, prefix, me)
o.authed = true
o.nick = me
end
handlers["PRIVMSG"] = function(o, prefix, channel, message)
o:invoke("OnChat", parsePrefix(prefix), channel, message)
end
handlers["NOTICE"] = function(o, prefix, channel, message)
o:invoke("OnNotice", parsePrefix(prefix), channel, message)
end
handlers["JOIN"] = function(o, prefix, channel)
local user = parsePrefix(prefix)
if o.track_users then
if user.nick == o.nick then
o.channels[channel] = {users = {}}
else
o.channels[channel].users[user.nick] = user
end
end
o:invoke("OnJoin", user, channel)
end
handlers["PART"] = function(o, prefix, channel, reason)
local user = parsePrefix(prefix)
if o.track_users then
if user.nick == o.nick then
o.channels[channel] = nil
else
o.channels[channel].users[user.nick] = nil
end
end
o:invoke("OnPart", user, channel, reason)
end
handlers["QUIT"] = function(o, prefix, msg)
local user = parsePrefix(prefix)
if o.track_users then
for channel, v in pairs(o.channels) do
v.users[user.nick] = nil
end
end
o:invoke("OnQuit", user, msg)
end
handlers["NICK"] = function(o, prefix, newnick)
local user = parsePrefix(prefix)
if o.track_users then
for channel, v in pairs(o.channels) do
local users = v.users
local oldinfo = users[user.nick]
if oldinfo then
users[newnick] = oldinfo
users[newnick].nick = newnick
if users[newnick].fullhost then
users[newnick].fullhost = users[newnick].nick.."!"..users[newnick].username.."@"..users[newnick].host
end
users[user.nick] = nil
o:invoke("NickChange", user, newnick, channel)
end
end
else
o:invoke("NickChange", user, newnick)
end
if user.nick == o.nick then
o.nick = newnick
end
end
local function needNewNick(o, prefix, target, badnick)
local newnick = o.nickGenerator(badnick)
o:send("NICK %s", newnick)
end
-- ERR_ERRONEUSNICKNAME (Misspelt but remains for historical reasons)
handlers["432"] = needNewNick
-- ERR_NICKNAMEINUSE
handlers["433"] = needNewNick
--WHO list
handlers["352"] = function(o, prefix, me, channel, name1, host, serv, name, access1 ,something, something2)
if o.track_users then
local user = {nick=name, host=host, username=name1, serv=serv, access=parseAccess(access1), fullhost=name.."!"..name1.."@"..host}
--print(user.nick,user.host,user.ID,user.serv,user.access)
o.channels[channel].users[user.nick] = user
end
end
--NAMES list
handlers["353"] = function(o, prefix, me, chanType, channel, names)
if o.track_users then
o.channels[channel] = o.channels[channel] or {users = {}, type = chanType}
local users = o.channels[channel].users
for nick in names:gmatch("(%S+)") do
local access, name = parseNick(nick)
users[name] = {access = access}
end
end
end
--end of NAMES
handlers["366"] = function(o, prefix, me, channel, msg)
if o.track_users then
o:invoke("NameList", channel, msg)
end
end
--no topic
handlers["331"] = function(o, prefix, me, channel)
o:invoke("OnTopic", channel, nil)
end
--new topic
handlers["TOPIC"] = function(o, prefix, channel, topic)
o:invoke("OnTopic", channel, topic)
end
handlers["332"] = function(o, prefix, me, channel, topic)
o:invoke("OnTopic", channel, topic)
end
--topic creation info
handlers["333"] = function(o, prefix, me, channel, nick, time)
o:invoke("OnTopicInfo", channel, nick, tonumber(time))
end
handlers["KICK"] = function(o, prefix, channel, kicked, reason)
o:invoke("OnKick", channel, kicked, parsePrefix(prefix), reason)
end
--RPL_UMODEIS
--To answer a query about a client's own mode, RPL_UMODEIS is sent back
handlers["221"] = function(o, prefix, user, modes)
o:invoke("OnUserMode", modes)
end
--RPL_CHANNELMODEIS
--The result from common irc servers differs from that defined by the rfc
handlers["324"] = function(o, prefix, user, channel, modes)
o:invoke("OnChannelMode", channel, modes)
end
handlers["MODE"] = function(o, prefix, target, modes, ...)
if o.track_users and target ~= o.nick then
local add = true
local optList = {...}
for c in modes:gmatch(".") do
if c == "+" then add = true
elseif c == "-" then add = false
elseif c == "o" then
local user = table.remove(optList, 1)
if user and o.channels[target].users[user] then o.channels[target].users[user].access.op = add end
elseif c == "h" then
local user = table.remove(optList, 1)
if user then o.channels[target].users[user].access.halfop = add end
elseif c == "v" then
local user = table.remove(optList, 1)
if user then o.channels[target].users[user].access.voice = add end
elseif c == "b" or c == "q" then
table.remove(optList, 1)
end
end
end
o:invoke("OnModeChange", parsePrefix(prefix), target, modes, ...)
end
handlers["ERROR"] = function(o, prefix, message)
o:invoke("OnDisconnect", message, true)
o:shutdown()
error(message, 3)
end
|
fix possible crash when modes are set
|
fix possible crash when modes are set
|
Lua
|
mit
|
GLolol/Crackbot,wolfy1339/WolfyBot,wolfy1339/WolfyBot,Brilliant-Minds/BMNBot-2,wolfy1339/WolfyBot,cracker64/Crackbot,cracker64/Crackbot,Brilliant-Minds/BMNBot-2,GLolol/Crackbot
|
37b5f9462e207df9e5f62ee5c2b89df9603f2bb5
|
classes/cabook.lua
|
classes/cabook.lua
|
local book = require("classes/book")
local plain = require("classes/plain")
local cabook = pl.class(book)
cabook._name = "cabook"
function cabook:_init (options)
book._init(self, options)
self:loadPackage("color")
self:loadPackage("ifattop")
self:loadPackage("leaders")
self:loadPackage("raiselower")
self:loadPackage("rebox");
self:loadPackage("rules")
self:loadPackage("image")
self:loadPackage("date")
self:loadPackage("textcase")
self:loadPackage("frametricks")
self:loadPackage("inputfilter")
self:loadPackage("linespacing")
if self.options.verseindex then
self:loadPackage("verseindex")
end
self:loadPackage("imprint")
self:loadPackage("covers")
self:registerPostinit(function (class)
-- CaSILE books sometimes have sections, sometimes don't.
-- Initialize some sectioning levels to work either way
SILE.scratch.counters["sectioning"] = {
value = { 0, 0 },
display = { "ORDINAL", "STRING" }
}
require("hyphenation_exceptions")
SILE.settings:set("typesetter.underfulltolerance", SILE.length("6ex"))
SILE.settings:set("typesetter.overfulltolerance", SILE.length("0.2ex"))
SILE.call("footnote:separator", {}, function ()
SILE.call("rebox", { width = "6em", height = "2ex" }, function ()
SILE.call("hrule", { width = "5em", height = "0.2pt" })
end)
SILE.call("medskip")
end)
SILE.call("cabook:font:serif", { size = "11.5pt" })
SILE.settings:set("linespacing.method", "fit-font")
SILE.settings:set("linespacing.fit-font.extra-space", SILE.length("0.6ex plus 0.2ex minus 0.2ex"))
SILE.settings:set("linebreak.hyphenPenalty", 300)
SILE.scratch.insertions.classes.footnote.interInsertionSkip = SILE.length("0.7ex plus 0 minus 0")
SILE.scratch.last_was_ref = false
class:registerPostinit(function ()
SILE.typesetter:registerPageEndHook(function ()
SILE.scratch.last_was_ref = false
end)
end)
end)
return self
end
function cabook:declareSettings ()
book.declareSettings(self)
-- require("classes.cabook-settings")()
end
function cabook:declareOptions ()
book.declareOptions(self)
local binding, crop, background, verseindex, layout
self:declareOption("binding", function (_, value)
if value then binding = value end
return binding
end)
self:declareOption("crop", function (_, value)
if value then crop = SU.cast("boolean", value) end
return crop
end)
self:declareOption("background", function (_, value)
if value then background = SU.cast("boolean", value) end
return background
end)
self:declareOption("verseindex", function (_, value)
if value then verseindex = SU.cast("boolean", value) end
return verseindex
end)
-- SU.error("ga cl 2.5")
self:declareOption("layout", function (_, value)
if value then
layout = value
self:registerPostinit(function (_)
require("layouts."..layout)(self)
end)
end
return layout
end)
end
function cabook:setOptions (options)
options.binding = options.binding or "print" -- print, paperback, hardcover, coil, stapled
options.crop = options.crop or true
options.background = options.background or true
options.verseindex = options.verseindex or false
options.layout = options.layout or "a4"
book.setOptions(self, options)
end
function cabook:registerCommands ()
book.registerCommands(self)
-- SILE's loadPackage assumes a "packages" path, this just side steps that naming requirement
self:initPackage(require("classes.commands"))
self:initPackage(require("classes.inline-styles"))
self:initPackage(require("classes.block-styles"))
end
function cabook:endPage ()
self:moveTocNodes()
if self.moveTovNodes then self:moveTovNodes() end
if not SILE.scratch.headers.skipthispage then
SILE.settings:pushState()
SILE.settings:reset()
if self:oddPage() then
SILE.call("output-right-running-head")
else
SILE.call("output-left-running-head")
end
SILE.settings:popState()
end
SILE.scratch.headers.skipthispage = false
local ret = plain.endPage(self)
if self.options.crop then self:outputCropMarks() end
return ret
end
function cabook:finish ()
if self.moveTovNodes then
self:writeTov()
SILE.call("tableofverses")
end
return book.finish(self)
end
return cabook
|
local book = require("classes/book")
local plain = require("classes/plain")
local cabook = pl.class(book)
cabook._name = "cabook"
function cabook:_init (options)
book._init(self, options)
self:loadPackage("color")
self:loadPackage("ifattop")
self:loadPackage("leaders")
self:loadPackage("raiselower")
self:loadPackage("rebox");
self:loadPackage("rules")
self:loadPackage("image")
self:loadPackage("date")
self:loadPackage("textcase")
self:loadPackage("frametricks")
self:loadPackage("inputfilter")
self:loadPackage("linespacing")
if self.options.verseindex then
self:loadPackage("verseindex")
end
self:loadPackage("imprint")
self:loadPackage("covers")
self:registerPostinit(function (_)
-- CaSILE books sometimes have sections, sometimes don't.
-- Initialize some sectioning levels to work either way
SILE.scratch.counters["sectioning"] = {
value = { 0, 0 },
display = { "ORDINAL", "STRING" }
}
require("hyphenation_exceptions")
SILE.settings:set("typesetter.underfulltolerance", SILE.length("6ex"))
SILE.settings:set("typesetter.overfulltolerance", SILE.length("0.2ex"))
SILE.call("footnote:separator", {}, function ()
SILE.call("rebox", { width = "6em", height = "2ex" }, function ()
SILE.call("hrule", { width = "5em", height = "0.2pt" })
end)
SILE.call("medskip")
end)
SILE.call("cabook:font:serif", { size = "11.5pt" })
SILE.settings:set("linespacing.method", "fit-font")
SILE.settings:set("linespacing.fit-font.extra-space", SILE.length("0.6ex plus 0.2ex minus 0.2ex"))
SILE.settings:set("linebreak.hyphenPenalty", 300)
SILE.scratch.insertions.classes.footnote.interInsertionSkip = SILE.length("0.7ex plus 0 minus 0")
SILE.scratch.last_was_ref = false
SILE.typesetter:registerPageEndHook(function ()
SILE.scratch.last_was_ref = false
end)
end)
end
function cabook:declareSettings ()
book.declareSettings(self)
-- require("classes.cabook-settings")()
end
function cabook:declareOptions ()
book.declareOptions(self)
local binding, crop, background, verseindex, layout
self:declareOption("binding", function (_, value)
if value then binding = value end
return binding
end)
self:declareOption("crop", function (_, value)
if value then crop = SU.cast("boolean", value) end
return crop
end)
self:declareOption("background", function (_, value)
if value then background = SU.cast("boolean", value) end
return background
end)
self:declareOption("verseindex", function (_, value)
if value then verseindex = SU.cast("boolean", value) end
return verseindex
end)
-- SU.error("ga cl 2.5")
self:declareOption("layout", function (_, value)
if value then
layout = value
self:registerPostinit(function (_)
require("layouts."..layout)(self)
end)
end
return layout
end)
end
function cabook:setOptions (options)
options.binding = options.binding or "print" -- print, paperback, hardcover, coil, stapled
options.crop = options.crop or true
options.background = options.background or true
options.verseindex = options.verseindex or false
options.layout = options.layout or "a4"
book.setOptions(self, options)
end
function cabook:registerCommands ()
book.registerCommands(self)
-- SILE's loadPackage assumes a "packages" path, this just side steps that naming requirement
self:initPackage(require("classes.commands"))
self:initPackage(require("classes.inline-styles"))
self:initPackage(require("classes.block-styles"))
end
function cabook:endPage ()
self:moveTocNodes()
if self.moveTovNodes then self:moveTovNodes() end
if not SILE.scratch.headers.skipthispage then
SILE.settings:pushState()
SILE.settings:reset()
if self:oddPage() then
SILE.call("output-right-running-head")
else
SILE.call("output-left-running-head")
end
SILE.settings:popState()
end
SILE.scratch.headers.skipthispage = false
local ret = plain.endPage(self)
if self.options.crop then self:outputCropMarks() end
return ret
end
function cabook:finish ()
if self.moveTovNodes then
self:writeTov()
SILE.call("tableofverses")
end
return book.finish(self)
end
return cabook
|
fix(classes): Setup cabook class to be minimally v0.14.x compliant
|
fix(classes): Setup cabook class to be minimally v0.14.x compliant
|
Lua
|
agpl-3.0
|
alerque/casile,alerque/casile,alerque/casile,alerque/casile,alerque/casile
|
38deeb5cbab19386f12db5064d731f6168fa79ea
|
lua/starfall/libs_sh/time.lua
|
lua/starfall/libs_sh/time.lua
|
-------------------------------------------------------------------------------
-- Time library
-------------------------------------------------------------------------------
local timer = timer
--- Deals with time and timers.
-- @shared
local time_library, _ = SF.Libraries.Register("time")
-- ------------------------- Time ------------------------- --
--- Same as GLua's CurTime()
function time_library.curTime()
return CurTime()
end
--- Same as GLua's RealTime()
function time_library.realTime()
return RealTime()
end
--- Same as GLua's SysTime()
function time_library.sysTime()
return SysTime()
end
-- ------------------------- Timers ------------------------- --
local function timercb(instance, tname, realname, func)
if not instance.error then
instance:runFunction(func)
else
timerx.remove(realname)
end
end
local function mangle_timer_name(instance, name)
return string.format("sftimer_%s_%s",tostring(instance),name)
end
--- Creates a timer
-- @param name The timer name
-- @param delay The time, in seconds, to set the timer to.
-- @param reps The repititions of the tiemr. 0 = infinte, nil = 1
-- @param func The function to call when the tiemr is fired
-- @param ... Arguments to func
function time_library.timer(name, delay, reps, func, ...)
SF.CheckType(name,"string")
SF.CheckType(delay,"number")
reps = SF.CheckType(reps,"number",0,1)
SF.CheckType(func,"function")
local instance = SF.instance
local timername = mangle_timer_name(instance,name)
timerx.create(timername, delay, reps, timercb, instance, name, timername, func)
instance.data.timers[name] = true
end
--- Creates a simple timer, has no name, can't be stopped, paused, or destroyed.
-- @param delay the time, in second, to set the timer to
-- @param func the function to call when the timer is fired
-- @param ... Arguments passed to the function
function time_library.stimer( delay, func, ... )
SF.CheckType( delay, "number" )
SF.CheckType( func, "function" )
timerx.simple( delay, simplecb, SF.instance, func, {...} )
end
--- Removes a timer
-- @param name Timer name
function time_library.destroyTimer(name)
SF.CheckType(name,"string")
local instance = SF.instance
local timername = mangle_timer_name(instance,name)
if timerx.exists(timername) then timerx.remove(timername) end
instance.data.timers[name] = nil
end
local function init(instance)
instance.data.timers = {}
end
local function deinit(instance)
if instance.data.timers ~= nil then
for name,_ in pairs(instance.data.timers) do
local realname = mangle_timer_name(instance,name)
timerx.remove(realname)
end
end
instance.data.timers = nil
end
SF.Libraries.AddHook("initialize",init)
SF.Libraries.AddHook("deinitialize",deinit)
|
-------------------------------------------------------------------------------
-- Time library
-------------------------------------------------------------------------------
local timer = timer
--- Deals with time and timers.
-- @shared
local time_library, _ = SF.Libraries.Register("time")
-- ------------------------- Time ------------------------- --
--- Same as GLua's CurTime()
function time_library.curTime()
return CurTime()
end
--- Same as GLua's RealTime()
function time_library.realTime()
return RealTime()
end
--- Same as GLua's SysTime()
function time_library.sysTime()
return SysTime()
end
-- ------------------------- Timers ------------------------- --
local function timercb(instance, tname, realname, func)
if not instance.error then
instance:runFunction(func)
else
timerx.remove(realname)
end
end
local function mangle_timer_name(instance, name)
return string.format("sftimer_%s_%s",tostring(instance),name)
end
--- Creates a timer
-- @param name The timer name
-- @param delay The time, in seconds, to set the timer to.
-- @param reps The repititions of the tiemr. 0 = infinte, nil = 1
-- @param func The function to call when the tiemr is fired
-- @param ... Arguments to func
function time_library.timer(name, delay, reps, func, ...)
SF.CheckType(name,"string")
SF.CheckType(delay,"number")
reps = SF.CheckType(reps,"number",0,1)
SF.CheckType(func,"function")
local instance = SF.instance
local timername = mangle_timer_name(instance,name)
timerx.create(timername, delay, reps, timercb, instance, name, timername, func)
instance.data.timers[name] = true
end
--- Creates a simple timer, has no name, can't be stopped, paused, or destroyed.
-- @param delay the time, in second, to set the timer to
-- @param func the function to call when the timer is fired
-- @param ... Arguments passed to the function
function time_library.stimer( delay, func, ... )
SF.CheckType( delay, "number" )
SF.CheckType( func, "function" )
timerx.simple( delay, simplecb, SF.instance, func, {...} )
end
--- Removes a timer
-- @param name Timer name
function time_library.destroyTimer(name)
SF.CheckType(name,"string")
local instance = SF.instance
local timername = mangle_timer_name(instance,name)
if timerx.exists(timername) then timerx.remove(timername) end
instance.data.timers[name] = nil
end
--- Returns time between frames on client and ticks on server. Same thing as G.FrameTime in GLua
function time_library.frameTime()
return FrameTime()
end
SF.Libraries.AddHook("initialize",function(instance)
instance.data.timers = {}
end)
SF.Libraries.AddHook("deinitialize",function(instance)
if instance.data.timers ~= nil then
for name,_ in pairs(instance.data.timers) do
local realname = mangle_timer_name(instance,name)
timerx.remove(realname)
end
end
instance.data.timers = nil
end)
|
Added time.frameTime(). Fixes #96
|
Added time.frameTime(). Fixes #96
|
Lua
|
bsd-3-clause
|
INPStarfall/Starfall,Jazzelhawk/Starfall,Ingenious-Gaming/Starfall,Jazzelhawk/Starfall,Ingenious-Gaming/Starfall,Xandaros/Starfall,INPStarfall/Starfall,Xandaros/Starfall
|
8af3698386050fcdf489ac04a9df7df865a778c9
|
database/redis.lua
|
database/redis.lua
|
-- Copyright (C) Dejiang Zhu (doujiang24)
local redis = require "resty.redis"
local corehelper = require "system.helper.core"
local log_error = corehelper.log_error
local log_debug = corehelper.log_debug
local setmetatable = setmetatable
local unpack = unpack
local get_instance = get_instance
local insert = table.insert
local select = select
local _M = { _VERSION = '0.01' }
local commands = {
'subscribe', 'psubscribe', 'unsubscribe', 'punsubscribe',
}
local mt = { __index = _M }
function _M.connect(self, config)
local red = setmetatable({ conn = redis:new(), config = config }, mt);
local conn = red.conn
local host = config.host
local port = config.port
local timeout = config.timeout
conn:set_timeout(timeout)
local ok, err = conn:connect(host, port)
if not ok then
log_error("failed to connect redis: ", err)
return
end
if config.password then
local res, err = red:auth(config.password)
if not res then
log_error("failed to authenticate: ", err)
return
end
end
return red
end
function close(self)
local conn = self.conn
local ok, err = conn:close()
if not ok then
log_error("failed to close redis: ", err)
end
end
_M.close = close
function _M.keepalive(self)
local conn, config = self.conn, self.config
if not config.idle_timeout or not config.max_keepalive then
log_error("not set idle_timeout and max_keepalive in config; turn to close")
return close(self)
end
local ok, err = conn:set_keepalive(config.idle_timeout, config.max_keepalive)
if not ok then
log_error("failed to set redis keepalive: ", err)
end
end
function _M.commit_pipeline(self)
local conn, ret = self.conn, {}
local results, err = conn:commit_pipeline()
if not results then
log_error("failed to commit the pipelined requests: ", err)
return ret
end
for i, res in ipairs(results) do
if type(res) == "table" then
if not res[1] then
log_error("failed to run command: ", i, "; err:", res[2])
insert(ret, false)
else
insert(ret, res[1])
end
else
insert(ret, res)
end
end
return ret
end
for i = 1, #commands do
local cmd = commands[i]
_M[cmd] =
function (self, ...)
local conn = self.conn
local res, err = conn[cmd](conn, ...)
if not res then
log_error("failed to query pubsub command redis, error:", err, "operater:", cmd, ...)
end
local nch = select("#", ...)
if 1 == nch then
return res, err
end
local results = { res }
for i = 1, nch - 1 do
local res, err = conn:read_reply()
if not res then
log_error("failed to read_reply for pubsub command redis, error:", err, "operater:", cmd, ...)
end
results[#results + 1] = res
end
return results, err
end
end
local class_mt = {
__index = function (table, key)
return function (self, ...)
local conn = self.conn
local res, err = conn[key](conn, ...)
if not res and err then
local args = { ... }
if "read_reply" == key and "timeout" == err then
--log_debug("failed to query redis, error:", err, "operater:", key, unpack(args))
else
log_error("failed to query redis, error:", err, "operater:", key, unpack(args))
end
return false, err
end
return res
end
end
}
setmetatable(_M, class_mt)
return _M
|
-- Copyright (C) Dejiang Zhu (doujiang24)
local redis = require "resty.redis"
local corehelper = require "system.helper.core"
local log_error = corehelper.log_error
local log_debug = corehelper.log_debug
local setmetatable = setmetatable
local unpack = unpack
local get_instance = get_instance
local insert = table.insert
local select = select
local _M = { _VERSION = '0.01' }
local mt = { __index = _M }
function _M.connect(self, config)
local red = setmetatable({ conn = redis:new(), config = config }, mt);
local conn = red.conn
local host = config.host
local port = config.port
local timeout = config.timeout
conn:set_timeout(timeout)
local ok, err = conn:connect(host, port)
if not ok then
log_error("failed to connect redis: ", err)
return
end
if config.password then
local res, err = red:auth(config.password)
if not res then
log_error("failed to authenticate: ", err)
return
end
end
return red
end
function close(self)
local conn = self.conn
local ok, err = conn:close()
if not ok then
log_error("failed to close redis: ", err)
end
end
_M.close = close
function _M.keepalive(self)
local conn, config = self.conn, self.config
if not config.idle_timeout or not config.max_keepalive then
log_error("not set idle_timeout and max_keepalive in config; turn to close")
return close(self)
end
local ok, err = conn:set_keepalive(config.idle_timeout, config.max_keepalive)
if not ok then
log_error("failed to set redis keepalive: ", err)
end
end
function _M.commit_pipeline(self)
local conn, ret = self.conn, {}
local results, err = conn:commit_pipeline()
if not results then
log_error("failed to commit the pipelined requests: ", err)
return ret
end
for i, res in ipairs(results) do
if type(res) == "table" then
if not res[1] then
log_error("failed to run command: ", i, "; err:", res[2])
insert(ret, false)
else
insert(ret, res[1])
end
else
insert(ret, res)
end
end
return ret
end
local class_mt = {
__index = function (table, key)
return function (self, ...)
local conn = self.conn
local res, err = conn[key](conn, ...)
log_debug(key, ...)
if not res and err then
if "read_reply" == key and "timeout" == err then
--log_debug("failed to query redis, error:", err, "operater:", key, unpack(args))
else
log_error("failed to query redis, error:", err, "operater:", key, ...)
end
return false, err
end
return res
end
end
}
setmetatable(_M, class_mt)
return _M
|
bugfix: no need to fix for pubsub; since lua-resty-redis has apply my patch
|
bugfix: no need to fix for pubsub; since lua-resty-redis
has apply my patch
|
Lua
|
mit
|
doujiang24/durap-system
|
d8560584341077212a3c990dfcdb24523d58bb1c
|
demo/xmake.lua
|
demo/xmake.lua
|
target("demo")
set_kind("binary")
set_default(false)
set_targetdir("app/")
add_deps("LCUIEx")
add_files("src/*.c")
add_files("src/ui/views/*.c")
add_files("src/ui/helpers/*.c")
add_includedirs("include", "../include", "../../LCUI/include", "../vendor/include")
before_build(function (target)
os.cp("dist/lib/" .. target.filename("*", "shared"), "app/")
os.trycp("dist/assets/*", "app/assets")
end)
if is_mode("release") then
set_symbols("hidden")
end
if not is_os("windows") then
add_rpathdirs("/usr/local/lib")
end
|
target("demo")
set_kind("binary")
set_default(false)
set_targetdir("app/")
add_deps("LCUIEx")
add_files("src/*.c")
add_files("src/ui/views/*.c")
add_files("src/ui/helpers/*.c")
add_includedirs("include", "../include", "../../LCUI/include", "../vendor/include")
before_build(function (target)
if val("plat") == "windows" then
os.cp("dist/lib/" .. target.filename("*", "shared"), "$(scriptdir)/app/")
os.cp("vendor/lib/" .. target.filename("*", "shared"), "$(scriptdir)/app/")
end
os.trycp("dist/assets/*", "$(scriptdir)/app/assets")
end)
if is_mode("release") then
set_symbols("hidden")
end
if not is_os("windows") then
add_rpathdirs("/usr/local/lib")
end
|
fix load dll on windows
|
fix load dll on windows
|
Lua
|
mit
|
lc-ui/lcui.css,lc-ui/lcui.css,lc-ui/lcui.css
|
e2540b68db76d29cbfe1385c5fcdd8bcfd00fe06
|
src/builtin/tactic.lua
|
src/builtin/tactic.lua
|
-- Define macros for simplifying Tactic creation
local unary_combinator = function (name, fn) tactic_macro(name, { macro_arg.Tactic }, function (env, t) return fn(t) end) end
local nary_combinator = function (name, fn) tactic_macro(name, { macro_arg.Tactics }, function (env, ts) return fn(unpack(ts)) end) end
local const_tactic = function (name, fn) tactic_macro(name, {}, function (env) return fn() end) end
unary_combinator("Repeat", Repeat)
unary_combinator("Try", Try)
nary_combinator("Then", Then)
nary_combinator("OrElse", OrElse)
const_tactic("exact", assumption_tac)
const_tactic("trivial", trivial_tac)
const_tactic("absurd", absurd_tac)
const_tactic("conj_hyp", conj_hyp_tac)
const_tactic("disj_hyp", disj_hyp_tac)
const_tactic("unfold_all", unfold_tac)
const_tactic("beta", beta_tac)
tactic_macro("apply", { macro_arg.Expr }, function (env, e) return apply_tac(e) end)
tactic_macro("unfold", { macro_arg.Id }, function (env, id) return unfold_tac(id) end)
tactic_macro("simp", { macro_arg.Ids },
function (env, ids)
return simp_tac(ids)
end
)
|
-- Define macros for simplifying Tactic creation
local unary_combinator = function (name, fn) tactic_macro(name, { macro_arg.Tactic }, function (env, t) return fn(t) end) end
local nary_combinator = function (name, fn) tactic_macro(name, { macro_arg.Tactics }, function (env, ts) return fn(unpack(ts)) end) end
local const_tactic = function (name, fn) tactic_macro(name, {}, function (env) return fn() end) end
unary_combinator("Repeat", Repeat)
unary_combinator("Try", Try)
nary_combinator("Then", Then)
nary_combinator("OrElse", OrElse)
const_tactic("exact", assumption_tac)
const_tactic("trivial", trivial_tac)
const_tactic("absurd", absurd_tac)
const_tactic("conj_hyp", conj_hyp_tac)
const_tactic("disj_hyp", disj_hyp_tac)
const_tactic("unfold_all", unfold_tac)
const_tactic("beta", beta_tac)
tactic_macro("apply", { macro_arg.Expr }, function (env, e) return apply_tac(e) end)
tactic_macro("unfold", { macro_arg.Id }, function (env, id) return unfold_tac(id) end)
tactic_macro("simp", { macro_arg.Ids },
function (env, ids)
if #ids == 0 then
ids[1] = "default"
end
return simp_tac(ids)
end
)
|
fix(src/builtin/tactic): add default rule set if none is provided
|
fix(src/builtin/tactic): add default rule set if none is provided
Signed-off-by: Leonardo de Moura <7610bae85f2b530654cc716772f1fe653373e892@microsoft.com>
|
Lua
|
apache-2.0
|
leanprover-community/lean,avigad/lean,Kha/lean,Kha/lean,soonhokong/travis_test,rlewis1988/lean,fgdorais/lean,fpvandoorn/lean2,eigengrau/lean,soonhokong/lean-osx,UlrikBuchholtz/lean,johoelzl/lean,leanprover/lean,fpvandoorn/lean2,avigad/lean,digama0/lean,soonhokong/lean,sp3ctum/lean,rlewis1988/lean,dselsam/lean,johoelzl/lean,leanprover/lean,c-cube/lean,digama0/lean,leanprover-community/lean,UlrikBuchholtz/lean,leodemoura/lean,soonhokong/lean-osx,UlrikBuchholtz/lean,c-cube/lean,htzh/lean,leanprover-community/lean,javra/lean,sp3ctum/lean,dselsam/lean,eigengrau/lean,sp3ctum/lean,fpvandoorn/lean,avigad/lean,c-cube/lean,fpvandoorn/lean2,soonhokong/lean-osx,dselsam/lean,digama0/lean,rlewis1988/lean,avigad/lean,leanprover-community/lean,dselsam/lean,levnach/lean,levnach/lean,fpvandoorn/lean2,rlewis1988/lean,leanprover/lean,dselsam/lean,johoelzl/lean,levnach/lean,UlrikBuchholtz/lean,soonhokong/lean-windows,soonhokong/lean-windows,fpvandoorn/lean,Kha/lean,leodemoura/lean,soonhokong/lean,johoelzl/lean,codyroux/lean0.1,eigengrau/lean,javra/lean,c-cube/lean,avigad/lean,javra/lean,avigad/lean,soonhokong/travis_test,digama0/lean,fgdorais/lean,eigengrau/lean,johoelzl/lean,leodemoura/lean,leanprover/lean,levnach/lean,fpvandoorn/lean,javra/lean,htzh/lean,soonhokong/travis_test,fgdorais/lean,rlewis1988/lean,fgdorais/lean,fpvandoorn/lean2,leodemoura/lean,leodemoura/lean,leodemoura/lean,rlewis1988/lean,leanprover/lean,soonhokong/lean,sp3ctum/lean,codyroux/lean0.1,codyroux/lean0.1,htzh/lean,soonhokong/lean-osx,soonhokong/lean-windows,eigengrau/lean,soonhokong/lean-osx,dselsam/lean,leanprover/lean,Kha/lean,soonhokong/travis_test,digama0/lean,leanprover-community/lean,leanprover-community/lean,htzh/lean,fgdorais/lean,c-cube/lean,soonhokong/lean-windows,Kha/lean,soonhokong/lean,UlrikBuchholtz/lean,fpvandoorn/lean,fpvandoorn/lean,sp3ctum/lean,javra/lean,digama0/lean,fpvandoorn/lean,johoelzl/lean,htzh/lean,soonhokong/lean,soonhokong/lean-windows,fgdorais/lean,levnach/lean,codyroux/lean0.1,Kha/lean
|
d7632b6e5af6c481a2d45919d5a3952eb9b5a38e
|
triggerfield/galmair_guard_rules.lua
|
triggerfield/galmair_guard_rules.lua
|
--[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
-- Quest: As a Galmair Guard (155)
local common = require("base.common")
local M = {}
function M.MoveToField(char)
if char:getType() ~= Character.player then
return
end
if char.pos == position (368 , 255, 0) or char.pos == position (367 , 255, 0) and char:getQuestProgress(155) == 1 then -- doing quest to read the rules of Galmair
char:setQuestProgress(155, 2)
common.InformNLS(char,"[Queststatus] Auf den Statuen hier steht irgendetwas. Egal ob du den Text liest oder nicht, allein der Fakt, dass du sie gefunden hast, wird den Ork zufrieden stellen. Geh zurck zu Boumaug.", "[Quest status] The statues around you have writing on them. Whether or not you read the text, finding the statues will satisfy the orc. Return to Boumaug.")
end
end
return M
|
--[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
-- Quest: As a Galmair Guard (155)
local common = require("base.common")
local M = {}
function M.MoveToField(char)
if char:getType() ~= Character.player then
return
end
if char.pos == position (368 , 255, 0)and char:getQuestProgress(155) == 1 or char.pos == position (367 , 255, 0) and char:getQuestProgress(155) == 1 then -- doing quest to read the rules of Galmair
char:setQuestProgress(155, 2)
common.InformNLS(char,"[Queststatus] Auf den Statuen hier steht irgendetwas. Egal ob du den Text liest oder nicht, allein der Fakt, dass du sie gefunden hast, wird den Ork zufrieden stellen. Geh zurck zu Boumaug.", "[Quest status] The statues around you have writing on them. Whether or not you read the text, finding the statues will satisfy the orc. Return to Boumaug.")
end
end
return M
|
fix bug allowing perpetual quest
|
fix bug allowing perpetual quest
|
Lua
|
agpl-3.0
|
vilarion/Illarion-Content,KayMD/Illarion-Content,Baylamon/Illarion-Content,Illarion-eV/Illarion-Content
|
66c21609870294075d707d9331f9c16b529fa952
|
mod_websocket/mod_websocket.lua
|
mod_websocket/mod_websocket.lua
|
-- Prosody IM
-- Copyright (C) 2012 Florian Zeitz
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
module:set_global();
local add_filter = require "util.filters".add_filter;
local sha1 = require "util.hashes".sha1;
local base64 = require "util.encodings".base64.encode;
local softreq = require "util.dependencies".softreq;
local portmanager = require "core.portmanager";
local bit = softreq"bit" or softreq"bit32" or module:log("error", "No bit module found. Either LuaJIT 2 or Lua 5.2 is required");
local band = bit.band;
local bxor = bit.bxor;
local cross_domain = module:get_option("cross_domain_websocket");
if cross_domain then
if cross_domain == true then
cross_domain = "*";
elseif type(cross_domain) == "table" then
cross_domain = table.concat(cross_domain, ", ");
end
if type(cross_domain) ~= "string" then
cross_domain = nil;
end
end
module:depends("c2s")
local sessions = module:shared("c2s/sessions");
local c2s_listener = portmanager.get_service("c2s").listener;
-- Websocket helpers
local function parse_frame(frame)
local result = {};
local pos = 1;
local length_bytes = 0;
local counter = 0;
local tmp_byte;
if #frame < 2 then return; end
tmp_byte = string.byte(frame, pos);
result.FIN = band(tmp_byte, 0x80) > 0;
result.RSV1 = band(tmp_byte, 0x40) > 0;
result.RSV2 = band(tmp_byte, 0x20) > 0;
result.RSV3 = band(tmp_byte, 0x10) > 0;
result.opcode = band(tmp_byte, 0x0F);
pos = pos + 1;
tmp_byte = string.byte(frame, pos);
result.MASK = band(tmp_byte, 0x80) > 0;
result.length = band(tmp_byte, 0x7F);
if result.length == 126 then
length_bytes = 2;
result.length = 0;
elseif result.length == 127 then
length_bytes = 8;
result.length = 0;
end
if #frame < (2 + length_bytes) then return; end
for i = 1, length_bytes do
pos = pos + 1;
result.length = result.length * 256 + string.byte(frame, pos);
end
if #frame < (2 + length_bytes + (result.MASK and 4 or 0) + result.length) then return; end
if result.MASK then
result.key = {string.byte(frame, pos+1), string.byte(frame, pos+2),
string.byte(frame, pos+3), string.byte(frame, pos+4)}
pos = pos + 5;
result.data = "";
for i = pos, pos + result.length - 1 do
result.data = result.data .. string.char(bxor(result.key[counter+1], string.byte(frame, i)));
counter = (counter + 1) % 4;
end
else
result.data = frame:sub(pos + 1, pos + result.length);
end
return result, 2 + length_bytes + (result.MASK and 4 or 0) + result.length;
end
local function build_frame(desc)
local length;
local result = "";
local data = desc.data or "";
result = result .. string.char(0x80 * (desc.FIN and 1 or 0) + desc.opcode);
length = #data;
if length <= 125 then -- 7-bit length
result = result .. string.char(length);
elseif length <= 0xFFFF then -- 2-byte length
result = result .. string.char(126);
result = result .. string.char(length/0x100) .. string.char(length%0x100);
else -- 8-byte length
result = result .. string.char(127);
for i = 7, 0, -1 do
result = result .. string.char(( length / (2^(8*i)) ) % 0x100);
end
end
result = result .. data;
return result;
end
--- Filter stuff
function handle_request(event, path)
local request, response = event.request, event.response;
local conn = response.conn;
if not request.headers.sec_websocket_key then
response.headers.content_type = "text/html";
return [[<!DOCTYPE html><html><head><title>Websocket</title></head><body>
<p>It works! Now point your WebSocket client to this URL to connect to Prosody.</p>
</body></html>]];
end
local wants_xmpp = false;
(request.headers.sec_websocket_protocol or ""):gsub("([^,]*),?", function (proto)
if proto == "xmpp" then wants_xmpp = true; end
end);
if not wants_xmpp then
return 501;
end
local function websocket_close(code, message)
local data = string.char(code/0x100) .. string.char(code%0x100) .. message;
conn:write(build_frame({opcode = 0x8, FIN = true, data = data}));
conn:close();
end
local dataBuffer;
local function handle_frame(frame)
module:log("debug", "Websocket received: %s (%i bytes)", frame.data, #frame.data);
-- Error cases
if frame.RSV1 or frame.RSV2 or frame.RSV3 then -- Reserved bits non zero
websocket_close(1002, "Reserved bits not zero");
return false;
end
if frame.opcode >= 0x8 and frame.length > 125 then -- Control frame with too much payload
websocket_close(1002, "Payload too large");
return false;
end
if frame.opcode >= 0x8 and not frame.FIN then -- Fragmented control frame
websocket_close(1002, "Fragmented control frame");
return false;
end
if (frame.opcode > 0x2 and frame.opcode < 0x8) or (frame.opcode > 0xA) then
websocket_close(1002, "Reserved opcode");
return false;
end
if frame.opcode == 0x0 and not dataBuffer then
websocket_close(1002, "Unexpected continuation frame");
return false;
end
if (frame.opcode == 0x1 or frame.opcode == 0x2) and dataBuffer then
websocket_close(1002, "Continuation frame expected");
return false;
end
-- Valid cases
if frame.opcode == 0x0 then -- Continuation frame
dataBuffer = dataBuffer .. frame.data;
elseif frame.opcode == 0x1 then -- Text frame
dataBuffer = frame.data;
elseif frame.opcode == 0x2 then -- Binary frame
websocket_close(1003, "Only text frames are supported");
return;
elseif frame.opcode == 0x8 then -- Close request
websocket_close(1000, "Goodbye");
return;
elseif frame.opcode == 0x9 then -- Ping frame
frame.opcode = 0xA;
conn:write(build_frame(frame));
return "";
else
log("warn", "Received frame with unsupported opcode %i", frame.opcode);
return "";
end
if frame.FIN then
data = dataBuffer;
dataBuffer = nil;
return data;
end
return "";
end
conn:setlistener(c2s_listener);
c2s_listener.onconnect(conn);
local frameBuffer = "";
add_filter(sessions[conn], "bytes/in", function(data)
local cache = "";
frameBuffer = frameBuffer .. data;
local frame, length = parse_frame(frameBuffer);
while frame do
frameBuffer = frameBuffer:sub(length + 1);
local result = handle_frame(frame);
if not result then return; end
cache = cache .. result;
frame, length = parse_frame(frameBuffer);
end
return cache;
end);
add_filter(sessions[conn], "bytes/out", function(data)
return build_frame({ FIN = true, opcode = 0x01, data = tostring(data)});
end);
response.status = "101 Switching Protocols";
response.headers.upgrade = "websocket";
response.headers.connection = "Upgrade";
response.headers.sec_webSocket_accept = base64(sha1(request.headers.sec_websocket_key .. "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"));
response.headers.sec_webSocket_protocol = "xmpp";
response.headers.access_control_allow_origin = cross_domain;
return "";
end
function module.add_host(module)
module:depends("http");
module:provides("http", {
name = "xmpp-websocket";
route = {
["GET"] = handle_request;
["GET /"] = handle_request;
};
});
end
|
-- Prosody IM
-- Copyright (C) 2012 Florian Zeitz
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
module:set_global();
local add_filter = require "util.filters".add_filter;
local sha1 = require "util.hashes".sha1;
local base64 = require "util.encodings".base64.encode;
local softreq = require "util.dependencies".softreq;
local portmanager = require "core.portmanager";
local bit;
pcall(function() bit = require"bit"; end);
bit = bit or softreq"bit32"
if not bit then module:log("error", "No bit module found. Either LuaJIT 2, lua-bitop or Lua 5.2 is required"); end
local band = bit.band;
local bxor = bit.bxor;
local cross_domain = module:get_option("cross_domain_websocket");
if cross_domain then
if cross_domain == true then
cross_domain = "*";
elseif type(cross_domain) == "table" then
cross_domain = table.concat(cross_domain, ", ");
end
if type(cross_domain) ~= "string" then
cross_domain = nil;
end
end
module:depends("c2s")
local sessions = module:shared("c2s/sessions");
local c2s_listener = portmanager.get_service("c2s").listener;
-- Websocket helpers
local function parse_frame(frame)
local result = {};
local pos = 1;
local length_bytes = 0;
local counter = 0;
local tmp_byte;
if #frame < 2 then return; end
tmp_byte = string.byte(frame, pos);
result.FIN = band(tmp_byte, 0x80) > 0;
result.RSV1 = band(tmp_byte, 0x40) > 0;
result.RSV2 = band(tmp_byte, 0x20) > 0;
result.RSV3 = band(tmp_byte, 0x10) > 0;
result.opcode = band(tmp_byte, 0x0F);
pos = pos + 1;
tmp_byte = string.byte(frame, pos);
result.MASK = band(tmp_byte, 0x80) > 0;
result.length = band(tmp_byte, 0x7F);
if result.length == 126 then
length_bytes = 2;
result.length = 0;
elseif result.length == 127 then
length_bytes = 8;
result.length = 0;
end
if #frame < (2 + length_bytes) then return; end
for i = 1, length_bytes do
pos = pos + 1;
result.length = result.length * 256 + string.byte(frame, pos);
end
if #frame < (2 + length_bytes + (result.MASK and 4 or 0) + result.length) then return; end
if result.MASK then
result.key = {string.byte(frame, pos+1), string.byte(frame, pos+2),
string.byte(frame, pos+3), string.byte(frame, pos+4)}
pos = pos + 5;
result.data = "";
for i = pos, pos + result.length - 1 do
result.data = result.data .. string.char(bxor(result.key[counter+1], string.byte(frame, i)));
counter = (counter + 1) % 4;
end
else
result.data = frame:sub(pos + 1, pos + result.length);
end
return result, 2 + length_bytes + (result.MASK and 4 or 0) + result.length;
end
local function build_frame(desc)
local length;
local result = "";
local data = desc.data or "";
result = result .. string.char(0x80 * (desc.FIN and 1 or 0) + desc.opcode);
length = #data;
if length <= 125 then -- 7-bit length
result = result .. string.char(length);
elseif length <= 0xFFFF then -- 2-byte length
result = result .. string.char(126);
result = result .. string.char(length/0x100) .. string.char(length%0x100);
else -- 8-byte length
result = result .. string.char(127);
for i = 7, 0, -1 do
result = result .. string.char(( length / (2^(8*i)) ) % 0x100);
end
end
result = result .. data;
return result;
end
--- Filter stuff
function handle_request(event, path)
local request, response = event.request, event.response;
local conn = response.conn;
if not request.headers.sec_websocket_key then
response.headers.content_type = "text/html";
return [[<!DOCTYPE html><html><head><title>Websocket</title></head><body>
<p>It works! Now point your WebSocket client to this URL to connect to Prosody.</p>
</body></html>]];
end
local wants_xmpp = false;
(request.headers.sec_websocket_protocol or ""):gsub("([^,]*),?", function (proto)
if proto == "xmpp" then wants_xmpp = true; end
end);
if not wants_xmpp then
return 501;
end
local function websocket_close(code, message)
local data = string.char(code/0x100) .. string.char(code%0x100) .. message;
conn:write(build_frame({opcode = 0x8, FIN = true, data = data}));
conn:close();
end
local dataBuffer;
local function handle_frame(frame)
module:log("debug", "Websocket received: %s (%i bytes)", frame.data, #frame.data);
-- Error cases
if frame.RSV1 or frame.RSV2 or frame.RSV3 then -- Reserved bits non zero
websocket_close(1002, "Reserved bits not zero");
return false;
end
if frame.opcode >= 0x8 and frame.length > 125 then -- Control frame with too much payload
websocket_close(1002, "Payload too large");
return false;
end
if frame.opcode >= 0x8 and not frame.FIN then -- Fragmented control frame
websocket_close(1002, "Fragmented control frame");
return false;
end
if (frame.opcode > 0x2 and frame.opcode < 0x8) or (frame.opcode > 0xA) then
websocket_close(1002, "Reserved opcode");
return false;
end
if frame.opcode == 0x0 and not dataBuffer then
websocket_close(1002, "Unexpected continuation frame");
return false;
end
if (frame.opcode == 0x1 or frame.opcode == 0x2) and dataBuffer then
websocket_close(1002, "Continuation frame expected");
return false;
end
-- Valid cases
if frame.opcode == 0x0 then -- Continuation frame
dataBuffer = dataBuffer .. frame.data;
elseif frame.opcode == 0x1 then -- Text frame
dataBuffer = frame.data;
elseif frame.opcode == 0x2 then -- Binary frame
websocket_close(1003, "Only text frames are supported");
return;
elseif frame.opcode == 0x8 then -- Close request
websocket_close(1000, "Goodbye");
return;
elseif frame.opcode == 0x9 then -- Ping frame
frame.opcode = 0xA;
conn:write(build_frame(frame));
return "";
else
log("warn", "Received frame with unsupported opcode %i", frame.opcode);
return "";
end
if frame.FIN then
data = dataBuffer;
dataBuffer = nil;
return data;
end
return "";
end
conn:setlistener(c2s_listener);
c2s_listener.onconnect(conn);
local frameBuffer = "";
add_filter(sessions[conn], "bytes/in", function(data)
local cache = "";
frameBuffer = frameBuffer .. data;
local frame, length = parse_frame(frameBuffer);
while frame do
frameBuffer = frameBuffer:sub(length + 1);
local result = handle_frame(frame);
if not result then return; end
cache = cache .. result;
frame, length = parse_frame(frameBuffer);
end
return cache;
end);
add_filter(sessions[conn], "bytes/out", function(data)
return build_frame({ FIN = true, opcode = 0x01, data = tostring(data)});
end);
response.status = "101 Switching Protocols";
response.headers.upgrade = "websocket";
response.headers.connection = "Upgrade";
response.headers.sec_webSocket_accept = base64(sha1(request.headers.sec_websocket_key .. "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"));
response.headers.sec_webSocket_protocol = "xmpp";
response.headers.access_control_allow_origin = cross_domain;
return "";
end
function module.add_host(module)
module:depends("http");
module:provides("http", {
name = "xmpp-websocket";
route = {
["GET"] = handle_request;
["GET /"] = handle_request;
};
});
end
|
mod_websocket: Fix require to work with lua-bitop (Thanks István and Zash)
|
mod_websocket: Fix require to work with lua-bitop (Thanks István and Zash)
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
9725e96257b10f5a0b577ff1e142b5fc1ae4adf5
|
xmake.lua
|
xmake.lua
|
-- version
set_version("1.5.1")
-- set warning all as error
set_warnings("all", "error")
-- set language: c99, c++11
set_languages("c99", "cxx11")
-- add defines to config.h
add_defines_h("$(prefix)_OS_$(OS)")
-- add undefines to config.h
add_undefines_h("$(prefix)_TRACE_INFO_ONLY")
add_undefines_h("$(prefix)_EXCEPTION_ENABLE")
add_undefines_h("$(prefix)_MEMORY_UNALIGNED_ACCESS_ENABLE")
-- add defines for c files
add_defines("_GNU_SOURCE=1", "_REENTRANT")
-- disable some compiler errors
add_cxflags("-Wno-error=deprecated-declarations")
add_mxflags("-Wno-error=deprecated-declarations")
-- the debug mode
if modes("debug") then
-- enable the debug symbols
set_symbols("debug")
-- disable optimization
set_optimize("none")
-- add defines for debug
add_defines("__tb_debug__")
-- attempt to enable some checkers for pc
if archs("i386", "x86_64") then
add_cxflags("-fsanitize=address", "-ftrapv")
add_mxflags("-fsanitize=address", "-ftrapv")
add_ldflags("-fsanitize=address")
end
end
-- the release or profile modes
if modes("release", "profile") then
-- the release mode
if modes("release") then
-- set the symbols visibility: hidden
set_symbols("hidden")
-- strip all symbols
set_strip("all")
-- fomit the frame pointer
add_cxflags("-fomit-frame-pointer")
add_mxflags("-fomit-frame-pointer")
-- the profile mode
else
-- enable the debug symbols
set_symbols("debug")
end
-- for pc
if archs("i386", "x86_64") then
-- enable fastest optimization
set_optimize("fastest")
-- for embed
else
-- enable smallest optimization
set_optimize("smallest")
end
-- attempt to add vector extensions
add_vectorexts("sse2", "sse3", "ssse3", "mmx")
end
-- for embed
if not archs("i386", "x86_64") then
-- add defines for small
add_defines("__tb_small__")
-- add defines to config.h
add_defines_h("$(prefix)_SMALL")
end
-- for the windows platform (msvc)
if plats("windows") then
-- add some defines only for windows
add_defines("NOCRYPT", "NOGDI")
-- the release mode
if modes("release") then
-- link libcmt.lib
add_cxflags("-MT")
-- the debug mode
elseif modes("debug") then
-- enable some checkers
add_cxflags("-Gs", "-RTC1")
-- link libcmtd.lib
add_cxflags("-MTd")
end
-- no msvcrt.lib
add_ldflags("-nodefaultlib:\"msvcrt.lib\"")
end
-- add option: demo
add_option("demo")
set_option_enable(true)
set_option_showmenu(true)
set_option_category("option")
set_option_description("Enable or disable the demo module")
-- add packages
add_pkgdirs("pkg")
-- add projects
add_subdirs("src/tbox")
if options("demo") then add_subdirs("src/demo") end
|
-- version
set_version("1.5.1")
-- set warning all as error
set_warnings("all", "error")
-- set language: c99, c++11
set_languages("c99", "cxx11")
-- add defines to config.h
add_defines_h("$(prefix)_OS_$(OS)")
-- add undefines to config.h
add_undefines_h("$(prefix)_TRACE_INFO_ONLY")
add_undefines_h("$(prefix)_EXCEPTION_ENABLE")
add_undefines_h("$(prefix)_MEMORY_UNALIGNED_ACCESS_ENABLE")
-- add defines for c files
add_defines("_GNU_SOURCE=1", "_REENTRANT")
-- disable some compiler errors
add_cxflags("-Wno-error=deprecated-declarations", "-fno-strict-aliasing")
add_mxflags("-Wno-error=deprecated-declarations", "-fno-strict-aliasing")
-- the debug mode
if modes("debug") then
-- enable the debug symbols
set_symbols("debug")
-- disable optimization
set_optimize("none")
-- add defines for debug
add_defines("__tb_debug__")
-- attempt to enable some checkers for pc
if archs("i386", "x86_64") then
add_cxflags("-fsanitize=address", "-ftrapv")
add_mxflags("-fsanitize=address", "-ftrapv")
add_ldflags("-fsanitize=address")
end
end
-- the release or profile modes
if modes("release", "profile") then
-- the release mode
if modes("release") then
-- set the symbols visibility: hidden
set_symbols("hidden")
-- strip all symbols
set_strip("all")
-- fomit the frame pointer
add_cxflags("-fomit-frame-pointer")
add_mxflags("-fomit-frame-pointer")
-- the profile mode
else
-- enable the debug symbols
set_symbols("debug")
end
-- for pc
if archs("i386", "x86_64") then
-- enable fastest optimization
set_optimize("fastest")
-- for embed
else
-- enable smallest optimization
set_optimize("smallest")
end
-- attempt to add vector extensions
add_vectorexts("sse2", "sse3", "ssse3", "mmx")
end
-- for embed
if not archs("i386", "x86_64") then
-- add defines for small
add_defines("__tb_small__")
-- add defines to config.h
add_defines_h("$(prefix)_SMALL")
end
-- for the windows platform (msvc)
if plats("windows") then
-- add some defines only for windows
add_defines("NOCRYPT", "NOGDI")
-- the release mode
if modes("release") then
-- link libcmt.lib
add_cxflags("-MT")
-- the debug mode
elseif modes("debug") then
-- enable some checkers
add_cxflags("-Gs", "-RTC1")
-- link libcmtd.lib
add_cxflags("-MTd")
end
-- no msvcrt.lib
add_ldflags("-nodefaultlib:\"msvcrt.lib\"")
end
-- add option: demo
add_option("demo")
set_option_enable(true)
set_option_showmenu(true)
set_option_category("option")
set_option_description("Enable or disable the demo module")
-- add packages
add_pkgdirs("pkg")
-- add projects
add_subdirs("src/tbox")
if options("demo") then add_subdirs("src/demo") end
|
fix strict-aliasing error for gcc
|
fix strict-aliasing error for gcc
|
Lua
|
apache-2.0
|
tboox/tbox,tboox/tbox,waruqi/tbox,waruqi/tbox
|
3490d048863b84de46f5c7c19422301f9a834602
|
entity/player.lua
|
entity/player.lua
|
local Player = {}
Player.__index = Player
local PULL_LENGTH2 = 300 * 300;
local PULL_FORCE = 300;
local PLAYER_FORCE = 5000;
local PLAYER_DAMPENING = 10;
local PLAYER_DENSITY = 10;
local PLAYER_HITPOINTS = 100;
local BALL_DAMAGE = 10;
local radius = 16;
Player.category = 1;
Player.mask = -1;
function Player.create(def, game)
local joysticks = love.joystick.getJoysticks()
local player = {
game = game,
joystick = joysticks[tonumber(def.no)],
no = def.no,
hitpoints = PLAYER_HITPOINTS
}
setmetatable(player, Player)
player.body = love.physics.newBody(game.world, def.x, def.y, "dynamic")
player.body:setLinearDamping(PLAYER_DAMPENING)
local fixture = love.physics.newFixture(player.body, love.physics.newCircleShape(radius), PLAYER_DENSITY) fixture:setFilterData( Player.category, Player.mask, 0 )
table.insert(game.players, player)
game.entities["player_" .. def.no] = EntityTypes.HitPoints.create({player = player}, game);
return player
end
function Player:collisionBegin(other, collision)
if other.type == "Ball" then
self.hitpoints = self.hitpoints - BALL_DAMAGE
end
end
function Player:control()
if self.joystick == nil then
return 0, 0, 0
end
x = self.joystick:getGamepadAxis('leftx')
y = self.joystick:getGamepadAxis('lefty')
tl = self.joystick:getGamepadAxis('triggerleft')
if vector.len2(x,y) < 0.2 then
x = 0
y = 0
end
if tl < 0.1 then
tl = 0
end
return x, y, tl
end
function Player:update(dt)
local jx, jy, jpull = self:control()
self.body:applyForce(vector.mul(PLAYER_FORCE, jx, jy));
local x, y = self.body:getPosition();
if jpull > 0 then
for k, ball in pairs(self.game.balls) do
local ballX, ballY = ball.body:getPosition();
local diffX, diffY = vector.sub(x,y, ballX, ballY);
local len2 = vector.len2(diffX, diffY);
if len2 < PULL_LENGTH2 then
ball.body:applyForce(vector.mul(jpull * PULL_FORCE * (1 - len2 / PULL_LENGTH2) / math.sqrt(len2), diffX, diffY))
end
end
end
end
function Player:draw()
if self.no == 1 then
love.graphics.setColor(255, 50, 50, self.hitpoints*255/100)
elseif self.no == 2 then
love.graphics.setColor(50, 50, 255, self.hitpoints*255/100)
else
love.graphics.setColor(255, 255, 255, self.hitpoints*255/100)
end
love.graphics.circle('fill', self.body:getX(), self.body:getY(), radius)
<<<<<<< HEAD
love.graphics.setColor(255,255,255)
=======
love.graphics.setColor(255, 255, 255, 255)
>>>>>>> 33171d27d91ddf03ce20f3f17c95819e20286982
end
return Player
|
local Player = {}
Player.__index = Player
local PULL_LENGTH2 = 300 * 300;
local PULL_FORCE = 600;
local PLAYER_FORCE = 5000;
local PLAYER_DAMPENING = 10;
local PLAYER_DENSITY = 10;
local PLAYER_HITPOINTS = 100;
local BALL_DAMAGE = 10;
local radius = 16;
Player.category = 1;
Player.mask = -1;
function Player.create(def, game)
local joysticks = love.joystick.getJoysticks()
local player = {
game = game,
joystick = joysticks[tonumber(def.no)],
no = def.no,
hitpoints = PLAYER_HITPOINTS
}
setmetatable(player, Player)
player.body = love.physics.newBody(game.world, def.x, def.y, "dynamic")
player.body:setLinearDamping(PLAYER_DAMPENING)
player.body:setUserData(player)
local fixture = love.physics.newFixture(player.body, love.physics.newCircleShape(radius), PLAYER_DENSITY) fixture:setFilterData( Player.category, Player.mask, 0 )
table.insert(game.players, player)
game.entities["player_" .. def.no] = EntityTypes.HitPoints.create({player = player}, game);
return player
end
function Player:collisionBegin(other, collision)
if other.type == "Ball" then
self.hitpoints = self.hitpoints - BALL_DAMAGE
end
end
function Player:control()
if self.joystick == nil then
return 0, 0, 0
end
x = self.joystick:getGamepadAxis('leftx')
y = self.joystick:getGamepadAxis('lefty')
tl = self.joystick:getGamepadAxis('triggerleft')
if vector.len2(x,y) < 0.2 then
x = 0
y = 0
end
if tl < 0.1 then
tl = 0
end
return x, y, tl
end
function Player:update(dt)
local jx, jy, jpull = self:control()
self.body:applyForce(vector.mul(PLAYER_FORCE, jx, jy));
local x, y = self.body:getPosition();
if jpull > 0 then
for k, ball in pairs(self.game.balls) do
local ballX, ballY = ball.body:getPosition();
local diffX, diffY = vector.sub(x,y, ballX, ballY);
local len2 = vector.len2(diffX, diffY);
if len2 < PULL_LENGTH2 then
ball.body:applyForce(vector.mul(jpull * PULL_FORCE * (1 - len2 / PULL_LENGTH2) / math.sqrt(len2), diffX, diffY))
end
end
end
end
function Player:draw()
if self.no == 1 then
love.graphics.setColor(255, 50, 50, self.hitpoints*255/100)
elseif self.no == 2 then
love.graphics.setColor(50, 50, 255, self.hitpoints*255/100)
else
love.graphics.setColor(255, 255, 255, self.hitpoints*255/100)
end
love.graphics.circle('fill', self.body:getX(), self.body:getY(), radius)
love.graphics.setColor(255,255,255)
end
return Player
|
Fixed stuff
|
Fixed stuff
|
Lua
|
mit
|
GuiSim/pixel
|
ecd590f04481136a42d6064d400713017e854f17
|
src/cli/db.lua
|
src/cli/db.lua
|
#!/usr/bin/env lua
local Faker = require "kong.tools.faker"
local Migrations = require "kong.tools.migrations"
local constants = require "kong.constants"
local cutils = require "kong.cli.utils"
local IO = require "kong.tools.io"
local lapp = require("lapp")
local args = lapp(string.format([[
Migrations, seeding of the DB.
Usage: kong db <command> [options]
Commands:
<command> (string) where <command> is one of:
migrations, migrations:up, migrations:down, migrations:reset, seed, drop
Options:
-c,--config (default %s) configuration file
-r,--random <seed>: flag to also insert random entities
-n,--number (default 1000) <seed>: number of random entities to insert if --random
]], constants.CLI.GLOBAL_KONG_CONF))
-- $ kong db
if args.command == "db" then
lapp.quit("Missing required <command>.")
end
local config_path = cutils.get_kong_config_path(args.config)
local _, dao_factory = IO.load_configuration_and_dao(config_path)
local migrations = Migrations(dao_factory, cutils.get_luarocks_install_dir())
if args.command == "migrations" then
local migrations, err = dao_factory:get_migrations()
if err then
cutils.logger:error_exit(err)
end
cutils.logger:log(string.format(
"Executed migrations for %s on keyspace: %s:\n%s",
cutils.colors.yellow(dao_factory.type),
cutils.colors.yellow(dao_factory._properties.keyspace),
table.concat(migrations, ", ")
))
elseif args.command == "migrations:up" then
cutils.logger:log(string.format(
"Migrating %s keyspace: %s",
cutils.colors.yellow(dao_factory.type),
cutils.colors.yellow(dao_factory._properties.keyspace))
)
migrations:migrate(function(migration, err)
if err then
cutils.logger:error_exit(err)
elseif migration then
cutils.logger:success("Migrated up to: "..cutils.colors.yellow(migration.name))
else
cutils.logger:success("Schema already up to date")
end
end)
elseif args.command == "migrations:down" then
cutils.logger:log(string.format(
"Rolling back %s keyspace: %s",
cutils.colors.yellow(dao_factory.type),
cutils.colors.yellow(dao_factory._properties.keyspace)
))
migrations:rollback(function(migration, err)
if err then
cutils.logger:error_exit(err)
elseif migration then
cutils.logger:success("Rollbacked to: "..cutils.colors.yellow(migration.name))
else
cutils.logger:success("No migration to rollback")
end
end)
elseif args.command == "migrations:reset" then
cutils.logger:log(string.format(
"Reseting %s keyspace: %s",
cutils.colors.yellow(dao_factory.type),
cutils.colors.yellow(dao_factory._properties.keyspace))
)
migrations:reset(function(migration, err)
if err then
cutils.logger:error_exit(err)
elseif migration then
cutils.logger:success("Rollbacked: "..cutils.colors.yellow(migration.name))
else
cutils.logger:success("Schema reseted")
end
end)
elseif args.command == "seed" then
-- Drop if exists
local err = dao_factory:drop()
if err then
cutils.logger:error_exit(err)
end
local err = dao_factory:prepare()
if err then
cutils.logger:error(err)
end
local faker = Faker(dao_factory)
faker:seed(args.random and args.number or nil)
cutils.logger:success("Populated")
elseif args.command == "drop" then
local err = dao_factory:drop()
if err then
cutils.logger:error_exit(err)
end
cutils.logger:success("Dropped")
else
lapp.quit("Invalid command: "..args.command)
end
|
#!/usr/bin/env lua
local Faker = require "kong.tools.faker"
local Migrations = require "kong.tools.migrations"
local constants = require "kong.constants"
local cutils = require "kong.cli.utils"
local IO = require "kong.tools.io"
local lapp = require("lapp")
local args = lapp(string.format([[
Migrations, seeding of the DB.
Usage: kong db <command> [options]
Commands:
<command> (string) where <command> is one of:
migrations, migrations:up, migrations:down, migrations:reset, seed, drop
Options:
-c,--config (default %s) configuration file
-r,--random <seed>: flag to also insert random entities
-n,--number (default 1000) <seed>: number of random entities to insert if --random
]], constants.CLI.GLOBAL_KONG_CONF))
-- $ kong db
if args.command == "db" then
lapp.quit("Missing required <command>.")
end
local config_path = cutils.get_kong_config_path(args.config)
local _, dao_factory = IO.load_configuration_and_dao(config_path)
local migrations = Migrations(dao_factory, cutils.get_luarocks_install_dir())
if args.command == "migrations" then
local migrations, err = dao_factory:get_migrations()
if err then
cutils.logger:error_exit(err)
elseif migrations then
cutils.logger:log(string.format(
"Executed migrations for %s on keyspace: %s:\n%s",
cutils.colors.yellow(dao_factory.type),
cutils.colors.yellow(dao_factory._properties.keyspace),
table.concat(migrations, ", ")
))
else
cutils.logger:log(string.format(
"No migrations have been run yet for %s on keyspace: %s",
cutils.colors.yellow(dao_factory.type),
cutils.colors.yellow(dao_factory._properties.keyspace)
))
end
elseif args.command == "migrations:up" then
cutils.logger:log(string.format(
"Migrating %s keyspace: %s",
cutils.colors.yellow(dao_factory.type),
cutils.colors.yellow(dao_factory._properties.keyspace))
)
migrations:migrate(function(migration, err)
if err then
cutils.logger:error_exit(err)
elseif migration then
cutils.logger:success("Migrated up to: "..cutils.colors.yellow(migration.name))
else
cutils.logger:success("Schema already up to date")
end
end)
elseif args.command == "migrations:down" then
cutils.logger:log(string.format(
"Rolling back %s keyspace: %s",
cutils.colors.yellow(dao_factory.type),
cutils.colors.yellow(dao_factory._properties.keyspace)
))
migrations:rollback(function(migration, err)
if err then
cutils.logger:error_exit(err)
elseif migration then
cutils.logger:success("Rollbacked to: "..cutils.colors.yellow(migration.name))
else
cutils.logger:success("No migration to rollback")
end
end)
elseif args.command == "migrations:reset" then
cutils.logger:log(string.format(
"Reseting %s keyspace: %s",
cutils.colors.yellow(dao_factory.type),
cutils.colors.yellow(dao_factory._properties.keyspace))
)
migrations:reset(function(migration, err)
if err then
cutils.logger:error_exit(err)
elseif migration then
cutils.logger:success("Rollbacked: "..cutils.colors.yellow(migration.name))
else
cutils.logger:success("Schema reseted")
end
end)
elseif args.command == "seed" then
-- Drop if exists
local err = dao_factory:drop()
if err then
cutils.logger:error_exit(err)
end
local err = dao_factory:prepare()
if err then
cutils.logger:error(err)
end
local faker = Faker(dao_factory)
faker:seed(args.random and args.number or nil)
cutils.logger:success("Populated")
elseif args.command == "drop" then
local err = dao_factory:drop()
if err then
cutils.logger:error_exit(err)
end
cutils.logger:success("Dropped")
else
lapp.quit("Invalid command: "..args.command)
end
|
fix: migrations list when 0 migraitons run. Fix #104
|
fix: migrations list when 0 migraitons run. Fix #104
|
Lua
|
apache-2.0
|
Kong/kong,shiprabehera/kong,ind9/kong,vzaramel/kong,xvaara/kong,streamdataio/kong,beauli/kong,salazar/kong,rafael/kong,isdom/kong,isdom/kong,ind9/kong,akh00/kong,rafael/kong,icyxp/kong,ejoncas/kong,jebenexer/kong,kyroskoh/kong,streamdataio/kong,ejoncas/kong,Kong/kong,li-wl/kong,Vermeille/kong,Kong/kong,ajayk/kong,vzaramel/kong,kyroskoh/kong,Mashape/kong,jerizm/kong,smanolache/kong,ccyphers/kong
|
20dd1f895710403b6b887b77a78ecdd7a969ea4f
|
core/ext/key_commands_std.lua
|
core/ext/key_commands_std.lua
|
-- Copyright 2007-2008 Mitchell Foral mitchell<att>caladbolg.net. See LICENSE.
---
-- Defines the key commands used by the Textadept key command manager.
-- For non-ascii keys, see textadept.keys for string aliases.
-- This set of key commands is pretty standard among other text editors.
module('textadept.key_commands_std', package.seeall)
--[[
C: B D H J K L R U
A: A B C D E F G H J K L M N P Q R S T U V W X Y Z
CS: A B C D F G H J K L M N O Q R T U V X Y Z
SA: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
CA: A B C D E F G H J K L M N O Q R S T U V W X Y Z
CSA: A B C D E F G H J K L M N O P Q R S T U V W X Y Z
]]--
---
-- Global container that holds all key commands.
-- @class table
-- @name keys
_G.keys = {}
local keys = keys
keys.clear_sequence = 'esc'
local b, v = 'buffer', 'view'
local t = textadept
keys.ct = {} -- Textadept command chain
keys.ct.e = {} -- Enclose in... chain
keys.ct.s = {} -- Select in... chain
keys.ct.v = {} -- Buffer view chain
-- File
keys.cn = { t.new_buffer }
keys.co = { t.io.open }
-- TODO: { 'reload', b }
keys.cs = { 'save', b }
keys.css = { 'save_as', b }
keys.cw = { 'close', b }
keys.csw = { t.io.close_all }
-- TODO: { t.io.load_session } after prompting with open dialog
-- TODO: { t.io.save_session } after prompting with save dialog
-- TODO: quit
-- Edit
local m_editing = _m.textadept.editing
-- Undo is cz.
-- Redo is cy.
-- Cut is cx.
-- Copy is cc.
-- Paste is cv.
-- Delete is delete.
-- Select All is ca.
keys.ce = { m_editing.match_brace }
keys.cse = { m_editing.match_brace, 'select' }
keys['c\n'] = { m_editing.autocomplete_word, '%w_' }
keys.cq = { m_editing.block_comment }
-- TODO: { m_editing.current_word, 'delete' }
-- TODO: { m_editing.transpose_chars }
-- TODO: { m_editing.squeeze }
-- TODO: { m_editing.move_line, 'up' }
-- TODO: { m_editing.move_line, 'down' }
-- TODO: { m_editing.convert_indentation }
-- TODO: { m_editing.smart_cutcopy }
-- TODO: { m_editing.smart_cutcopy, 'copy' }
-- TODO: { m_editing.smart_paste }
-- TODO: { m_editing.smart_paste, 'cycle' }
-- TODO: { m_editing.smart_paste, 'reverse' }
-- TODO: { m_editing.ruby_exec }
-- TODO: { m_editing.lua_exec }
keys.ct.e.t = { m_editing.enclose, 'tag' }
keys.ct.e.st = { m_editing.enclose, 'single_tag' }
keys.ct.e['"'] = { m_editing.enclose, 'dbl_quotes' }
keys.ct.e["'"] = { m_editing.enclose, 'sng_quotes' }
keys.ct.e['('] = { m_editing.enclose, 'parens' }
keys.ct.e['['] = { m_editing.enclose, 'brackets' }
keys.ct.e['{'] = { m_editing.enclose, 'braces' }
keys.ct.e.c = { m_editing.enclose, 'chars' }
keys.ct.e.g = { m_editing.grow_selection, 1 }
keys.ct.s.e = { m_editing.select_enclosed }
keys.ct.s.t = { m_editing.select_enclosed, 'tags' }
keys.ct.s['"'] = { m_editing.select_enclosed, 'dbl_quotes' }
keys.ct.s["'"] = { m_editing.select_enclosed, 'sng_quotes' }
keys.ct.s['('] = { m_editing.select_enclosed, 'parens' }
keys.ct.s['['] = { m_editing.select_enclosed, 'brackets' }
keys.ct.s['{'] = { m_editing.select_enclosed, 'braces' }
keys.ct.s.w = { m_editing.current_word, 'select' }
keys.ct.s.l = { m_editing.select_line }
keys.ct.s.p = { m_editing.select_paragraph }
keys.ct.s.b = { m_editing.select_indented_block }
keys.ct.s.s = { m_editing.select_scope }
-- Search
keys.cf = { t.find.focus } -- find/replace
-- Find Next is an when find pane is focused.
-- Find Prev is ap when find pane is focused.
-- Replace is ar when find pane is focused.
keys.cg = { m_editing.goto_line }
-- Tools
keys['f2'] = { t.command_entry.focus }
-- Snippets
local m_snippets = _m.textadept.lsnippets
keys.ci = { m_snippets.insert }
keys.csi = { m_snippets.prev }
keys.cai = { m_snippets.cancel_current }
keys.casi = { m_snippets.list }
keys.ai = { m_snippets.show_style }
-- Multiple Line Editing
local m_mlines = _m.textadept.mlines
keys.cm = {}
keys.cm.a = { m_mlines.add }
keys.cm.sa = { m_mlines.add_multiple }
keys.cm.r = { m_mlines.remove }
keys.cm.sr = { m_mlines.remove_multiple }
keys.cm.u = { m_mlines.update }
keys.cm.c = { m_mlines.clear }
-- Buffers
keys['c\t'] = { 'goto_buffer', v, 1, false }
keys['cs\t'] = { 'goto_buffer', v, -1, false }
local function toggle_setting(setting)
local state = buffer[setting]
if type(state) == 'boolean' then
buffer[setting] = not state
elseif type(state) == 'number' then
buffer[setting] = buffer[setting] == 0 and 1 or 0
end
t.events.update_ui() -- for updating statusbar
end
keys.ct.v.e = { toggle_setting, 'view_eol' }
keys.ct.v.w = { toggle_setting, 'wrap_mode' }
keys.ct.v.i = { toggle_setting, 'indentation_guides' }
keys.ct.v['\t'] = { toggle_setting, 'use_tabs' }
keys.ct.v[' '] = { toggle_setting, 'view_ws' }
keys['f5'] = { 'colourise', b, 0, -1 }
-- Views
keys['ca\t'] = { t.goto_view, 1, false }
keys['csa\t'] = { t.goto_view, -1, false }
keys.ct.ss = { 'split', v } -- vertical
keys.ct.s = { 'split', v, false } -- horizontal
keys.ct.w = { function() view:unsplit() return true end }
keys.ct.sw = { function() while view:unsplit() do end end }
-- TODO: { function() view.size = view.size + 10 end }
-- TODO: { function() view.size = view.size - 10 end }
-- Project Manager
local function pm_activate(text) t.pm.entry_text = text t.pm.activate() end
keys.csp = { function() if t.pm.width > 0 then t.pm.toggle_visible() end end }
keys.cp = { function()
if t.pm.width == 0 then t.pm.toggle_visible() end
t.pm.focus()
end }
keys.cap = {
c = { pm_activate, 'ctags' },
b = { pm_activate, 'buffers' },
f = { pm_activate, '/' },
-- TODO: { pm_activate, 'macros' }
m = { pm_activate, 'modules' },
}
-- Miscellaneous not in standard menu.
-- Recent files.
local RECENT_FILES = 1
t.events.add_handler('user_list_selection',
function(type, text) if type == RECENT_FILES then t.io.open(text) end end)
keys.ao = { function()
local buffer = buffer
local list = ''
local sep = buffer.auto_c_separator
buffer.auto_c_separator = ('|'):byte()
for _, filename in ipairs(t.io.recent_files) do
list = filename..'|'..list
end
buffer:user_list_show( RECENT_FILES, list:sub(1, -2) )
buffer.auto_c_separator = sep
end }
|
-- Copyright 2007-2008 Mitchell Foral mitchell<att>caladbolg.net. See LICENSE.
---
-- Defines the key commands used by the Textadept key command manager.
-- For non-ascii keys, see textadept.keys for string aliases.
-- This set of key commands is pretty standard among other text editors.
module('textadept.key_commands_std', package.seeall)
--[[
C: B D H J K L R U
A: A B C D E F G H J K L M N P Q R S T U V W X Y Z
CS: A B C D F G H J K L M N O Q R T U V X Y Z
SA: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
CA: A B C D E F G H J K L M N O Q R S T U V W X Y Z
CSA: A B C D E F G H J K L M N O P Q R S T U V W X Y Z
]]--
---
-- Global container that holds all key commands.
-- @class table
-- @name keys
_G.keys = {}
local keys = keys
keys.clear_sequence = 'esc'
local b, v = 'buffer', 'view'
local t = textadept
keys.ct = {} -- Textadept command chain
-- File
keys.cn = { t.new_buffer }
keys.co = { t.io.open }
-- TODO: { 'reload', b }
keys.cs = { 'save', b }
keys.css = { 'save_as', b }
keys.cw = { 'close', b }
keys.csw = { t.io.close_all }
-- TODO: { t.io.load_session } after prompting with open dialog
-- TODO: { t.io.save_session } after prompting with save dialog
-- TODO: quit
-- Edit
local m_editing = _m.textadept.editing
-- Undo is cz.
-- Redo is cy.
-- Cut is cx.
-- Copy is cc.
-- Paste is cv.
-- Delete is delete.
-- Select All is ca.
keys.ce = { m_editing.match_brace }
keys.cse = { m_editing.match_brace, 'select' }
keys['c\n'] = { m_editing.autocomplete_word, '%w_' }
keys.cq = { m_editing.block_comment }
-- TODO: { m_editing.current_word, 'delete' }
-- TODO: { m_editing.transpose_chars }
-- TODO: { m_editing.squeeze }
-- TODO: { m_editing.move_line, 'up' }
-- TODO: { m_editing.move_line, 'down' }
-- TODO: { m_editing.convert_indentation }
-- TODO: { m_editing.smart_cutcopy }
-- TODO: { m_editing.smart_cutcopy, 'copy' }
-- TODO: { m_editing.smart_paste }
-- TODO: { m_editing.smart_paste, 'cycle' }
-- TODO: { m_editing.smart_paste, 'reverse' }
-- TODO: { m_editing.ruby_exec }
-- TODO: { m_editing.lua_exec }
keys.ac = { -- enClose in...
t = { m_editing.enclose, 'tag' },
st = { m_editing.enclose, 'single_tag' },
['"'] = { m_editing.enclose, 'dbl_quotes' },
["'"] = { m_editing.enclose, 'sng_quotes' },
['('] = { m_editing.enclose, 'parens' },
['['] = { m_editing.enclose, 'brackets' },
['{'] = { m_editing.enclose, 'braces' },
c = { m_editing.enclose, 'chars' },
}
keys.as = { -- select in...
e = { m_editing.select_enclosed },
t = { m_editing.select_enclosed, 'tags' },
['"'] = { m_editing.select_enclosed, 'dbl_quotes' },
["'"] = { m_editing.select_enclosed, 'sng_quotes' },
['('] = { m_editing.select_enclosed, 'parens' },
['['] = { m_editing.select_enclosed, 'brackets' },
['{'] = { m_editing.select_enclosed, 'braces' },
w = { m_editing.current_word, 'select' },
l = { m_editing.select_line },
p = { m_editing.select_paragraph },
b = { m_editing.select_indented_block },
s = { m_editing.select_scope },
g = { m_editing.grow_selection, 1 },
}
-- Search
keys.cf = { t.find.focus } -- find/replace
-- Find Next is an when find pane is focused.
-- Find Prev is ap when find pane is focused.
-- Replace is ar when find pane is focused.
keys.cg = { m_editing.goto_line }
-- Tools
keys['f2'] = { t.command_entry.focus }
-- Snippets
local m_snippets = _m.textadept.lsnippets
keys.ci = { m_snippets.insert }
keys.csi = { m_snippets.prev }
keys.cai = { m_snippets.cancel_current }
keys.casi = { m_snippets.list }
keys.ai = { m_snippets.show_style }
-- Multiple Line Editing
local m_mlines = _m.textadept.mlines
keys.cm = {}
keys.cm.a = { m_mlines.add }
keys.cm.sa = { m_mlines.add_multiple }
keys.cm.r = { m_mlines.remove }
keys.cm.sr = { m_mlines.remove_multiple }
keys.cm.u = { m_mlines.update }
keys.cm.c = { m_mlines.clear }
-- Buffers
keys['c\t'] = { 'goto_buffer', v, 1, false }
keys['ca\t'] = { 'goto_buffer', v, -1, false }
local function toggle_setting(setting)
local state = buffer[setting]
if type(state) == 'boolean' then
buffer[setting] = not state
elseif type(state) == 'number' then
buffer[setting] = buffer[setting] == 0 and 1 or 0
end
t.events.update_ui() -- for updating statusbar
end
keys.ct.v = {
e = { toggle_setting, 'view_eol' },
w = { toggle_setting, 'wrap_mode' },
i = { toggle_setting, 'indentation_guides' },
['\t'] = { toggle_setting, 'use_tabs' },
[' '] = { toggle_setting, 'view_ws' },
}
keys['f5'] = { 'colourise', b, 0, -1 }
-- Views
keys.cv = {
n = { t.goto_view, 1, false },
p = { t.goto_view, -1, false },
ss = { 'split', v }, -- vertical
s = { 'split', v, false }, -- horizontal
w = { function() view:unsplit() return true end },
sw = { function() while view:unsplit() do end end },
-- TODO: { function() view.size = view.size + 10 end }
-- TODO: { function() view.size = view.size - 10 end }
}
-- Project Manager
local function pm_activate(text) t.pm.entry_text = text t.pm.activate() end
keys.csp = { function() if t.pm.width > 0 then t.pm.toggle_visible() end end }
keys.cp = { function()
if t.pm.width == 0 then t.pm.toggle_visible() end
t.pm.focus()
end }
keys.cap = {
c = { pm_activate, 'ctags' },
b = { pm_activate, 'buffers' },
f = { pm_activate, '/' },
-- TODO: { pm_activate, 'macros' }
m = { pm_activate, 'modules' },
}
-- Miscellaneous not in standard menu.
-- Recent files.
local RECENT_FILES = 1
t.events.add_handler('user_list_selection',
function(type, text) if type == RECENT_FILES then t.io.open(text) end end)
keys.ao = { function()
local buffer = buffer
local list = ''
local sep = buffer.auto_c_separator
buffer.auto_c_separator = ('|'):byte()
for _, filename in ipairs(t.io.recent_files) do
list = filename..'|'..list
end
buffer:user_list_show( RECENT_FILES, list:sub(1, -2) )
buffer.auto_c_separator = sep
end }
|
Fixed some conflicting key commands; core/ext/key_commands_std.lua
|
Fixed some conflicting key commands; core/ext/key_commands_std.lua
|
Lua
|
mit
|
jozadaquebatista/textadept,jozadaquebatista/textadept
|
ebed90e5a6f358e375a8efd0c57c29f4dca59331
|
core/src/lua-cjson/xmake.lua
|
core/src/lua-cjson/xmake.lua
|
target("lua-cjson")
set_kind("static")
set_warnings("all")
add_deps("luajit")
if is_plat("windows") then
set_languages("c89")
end
add_files("lua-cjson/*.c|fpconv.c")
-- Use internal strtod() / g_fmt() code for performance and disable multi-thread
add_defines("NDEBUG", "USE_INTERNAL_FPCONV")
if is_plat("windows") then
-- Windows sprintf()/strtod() handle NaN/inf differently. Not supported.
add_defines("DISABLE_INVALID_NUMBERS")
add_defines("strncasecmp=_strnicmp")
end
|
target("lua-cjson")
set_kind("static")
set_warnings("all")
add_deps("luajit")
if is_plat("windows") then
set_languages("c89")
end
add_files("lua-cjson/*.c|fpconv.c")
-- Use internal strtod() / g_fmt() code for performance and disable multi-thread
add_defines("NDEBUG", "USE_INTERNAL_FPCONV")
if is_plat("windows") then
-- Windows sprintf()/strtod() handle NaN/inf differently. Not supported.
add_defines("DISABLE_INVALID_NUMBERS")
add_defines("strncasecmp=_strnicmp")
add_defines("inline=__inline")
end
|
fix compile errors for vs2013
|
fix compile errors for vs2013
|
Lua
|
apache-2.0
|
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
|
6f74268546ae4eee537c5acc21aa4c8fa03be55f
|
otouto/plugins/pokemon-go.lua
|
otouto/plugins/pokemon-go.lua
|
-- For some reason you can't have an é in variable names. :(
local pokemon_go = {}
local utilities = require('otouto.utilities')
pokemon_go.command = 'pokego <team>'
function pokemon_go:init(config)
pokemon_go.triggers = utilities.triggers(self.info.username, config.cmd_pat)
:t('pokego', true):t('pokégo', true)
:t('pokemongo', true):t('pokémongo', true).table
pokemon_go.doc = [[```
]]..config.cmd_pat..[[pokego <team>
Set your Pokémon Go team for statistical purposes. The team must be valid, and can be referred to by name or color (or the first letter of either). Giving no team name will show statistics.
```]]
local db = self.database.pokemon_go
if not db then
self.database.pokemon_go = {}
db = self.database.pokemon_go
end
if not db.membership then
db.membership = {}
end
end
local team_ref = {
mystic = "Mystic",
m = "Mystic",
valor = "Valor",
v = "Valor",
instinct = "Instinct",
i = "Instinct",
blue = "Mystic",
b = "Mystic",
red = "Valor",
r = "Valor",
yellow = "Instinct",
y = "Instinct"
}
function pokemon_go:action(msg, config)
local output
local input = utilities.input(msg.text_lower)
if input then
local team = team_ref[input]
if not team then
output = 'Invalid team.'
else
local id_str = tostring(msg.from.id)
local db = self.database.pokemon_go
local db_membership = db.membership
if not db_membership[team] then
db_membership[team] = utilities.new_set()
end
for t, set in pairs(db_membership) do
if t ~= team then
set:remove(id_str)
else
set:add(id_str)
end
end
output = 'Your team is now '..team..'.'
end
else
local db = self.database.pokemon_go
local db_membership = db.membership
local output_temp = {'Membership:'}
for t, set in pairs(db_membership) do
table.insert(output_temp, t..': '..#set)
end
output = table.concat(output_temp, '\n')
end
utilities.send_reply(self, msg, output)
end
return pokemon_go
|
-- For some reason you can't have an é in variable names. :(
local pokemon_go = {}
local utilities = require('otouto.utilities')
pokemon_go.command = 'pokego <team>'
function pokemon_go:init(config)
pokemon_go.triggers = utilities.triggers(self.info.username, config.cmd_pat)
:t('pokego', true):t('pokégo', true)
:t('pokemongo', true):t('pokémongo', true).table
pokemon_go.doc = [[```
]]..config.cmd_pat..[[pokego <team>
Set your Pokémon Go team for statistical purposes. The team must be valid, and can be referred to by name or color (or the first letter of either). Giving no team name will show statistics.
```]]
local db = self.database.pokemon_go
if not db then
self.database.pokemon_go = {}
db = self.database.pokemon_go
end
if not db.membership then
db.membership = {}
end
for _, set in pairs(db.membership) do
setmetatable(set, utilities.set_meta)
end
end
local team_ref = {
mystic = "Mystic",
m = "Mystic",
valor = "Valor",
v = "Valor",
instinct = "Instinct",
i = "Instinct",
blue = "Mystic",
b = "Mystic",
red = "Valor",
r = "Valor",
yellow = "Instinct",
y = "Instinct"
}
function pokemon_go:action(msg, config)
local output
local input = utilities.input(msg.text_lower)
if input then
local team = team_ref[input]
if not team then
output = 'Invalid team.'
else
local id_str = tostring(msg.from.id)
local db = self.database.pokemon_go
local db_membership = db.membership
if not db_membership[team] then
db_membership[team] = utilities.new_set()
end
for t, set in pairs(db_membership) do
if t ~= team then
set:remove(id_str)
else
set:add(id_str)
end
end
output = 'Your team is now '..team..'.'
end
else
local db = self.database.pokemon_go
local db_membership = db.membership
local output_temp = {'Membership:'}
for t, set in pairs(db_membership) do
table.insert(output_temp, t..': '..#set)
end
output = table.concat(output_temp, '\n')
end
utilities.send_reply(self, msg, output)
end
return pokemon_go
|
Fix your database serialization, Drew
|
Fix your database serialization, Drew
|
Lua
|
agpl-3.0
|
bb010g/otouto,Brawl345/Brawlbot-v2,topkecleon/otouto,barreeeiroo/BarrePolice
|
bd525446571232ebbd39f7428b27ef07cd8df258
|
core/gui.lua
|
core/gui.lua
|
-- Copyright 2007-2010 Mitchell mitchell<att>caladbolg.net. See LICENSE.
local gui = _G.gui
-- LuaDoc is in core/.gui.lua.
function gui.check_focused_buffer(buffer)
if type(buffer) ~= 'table' or not buffer.doc_pointer then
error(locale.ERR_BUFFER_EXPECTED, 2)
elseif gui.focused_doc_pointer ~= buffer.doc_pointer then
error(locale.ERR_BUFFER_NOT_FOCUSED, 2)
end
end
-- LuaDoc is in core/.gui.lua.
function gui._print(buffer_type, ...)
local function safe_print(...)
local message = table.concat({...}, '\t')
local message_buffer, message_buffer_index
local message_view, message_view_index
for index, buffer in ipairs(_BUFFERS) do
if buffer._type == buffer_type then
message_buffer, message_buffer_index = buffer, index
for jndex, view in ipairs(_VIEWS) do
if view.doc_pointer == message_buffer.doc_pointer then
message_view, message_view_index = view, jndex
break
end
end
break
end
end
if not message_view then
local _, message_view = view:split(false) -- horizontal split
if not message_buffer then
message_buffer = new_buffer()
message_buffer._type = buffer_type
events.emit('file_opened')
else
message_view:goto_buffer(message_buffer_index, true)
end
else
gui.goto_view(message_view_index, true)
end
message_buffer:append_text(message..'\n')
message_buffer:set_save_point()
end
pcall(safe_print, ...) -- prevent endless loops if this errors
end
-- LuaDoc is in core/.gui.lua.
function gui.print(...) gui._print(locale.MESSAGE_BUFFER, ...) end
-- LuaDoc is in core/.gui.lua.
function gui.switch_buffer()
local items = {}
for _, buffer in ipairs(_BUFFERS) do
local filename = buffer.filename or buffer._type or locale.UNTITLED
local dirty = buffer.dirty and '*' or ''
items[#items + 1] = dirty..filename:match('[^/\\]+$')
items[#items + 1] = filename
end
local out =
gui.dialog('filteredlist',
'--title', locale.SWITCH_BUFFERS,
'--button1', 'gtk-ok',
'--button2', 'gtk-cancel',
'--no-newline',
'--columns', 'Name', 'File',
'--items', items)
local i = tonumber(out:match('%-?%d+$'))
if i and i >= 0 then view:goto_buffer(i + 1, true) end
end
|
-- Copyright 2007-2010 Mitchell mitchell<att>caladbolg.net. See LICENSE.
local gui = _G.gui
-- LuaDoc is in core/.gui.lua.
function gui.check_focused_buffer(buffer)
if type(buffer) ~= 'table' or not buffer.doc_pointer then
error(locale.ERR_BUFFER_EXPECTED, 2)
elseif gui.focused_doc_pointer ~= buffer.doc_pointer then
error(locale.ERR_BUFFER_NOT_FOCUSED, 2)
end
end
-- LuaDoc is in core/.gui.lua.
function gui._print(buffer_type, ...)
local function safe_print(...)
local message = table.concat({...}, '\t')
local message_buffer, message_buffer_index
local message_view, message_view_index
for index, buffer in ipairs(_BUFFERS) do
if buffer._type == buffer_type then
message_buffer, message_buffer_index = buffer, index
for jndex, view in ipairs(_VIEWS) do
if view.doc_pointer == message_buffer.doc_pointer then
message_view, message_view_index = view, jndex
break
end
end
break
end
end
if not message_view then
local _, message_view = view:split(false) -- horizontal split
if not message_buffer then
message_buffer = new_buffer()
message_buffer._type = buffer_type
events.emit('file_opened')
else
message_view:goto_buffer(message_buffer_index, true)
end
else
gui.goto_view(message_view_index, true)
end
message_buffer:append_text(message..'\n')
message_buffer:set_save_point()
end
pcall(safe_print, ...) -- prevent endless loops if this errors
end
-- LuaDoc is in core/.gui.lua.
function gui.print(...) gui._print(locale.MESSAGE_BUFFER, ...) end
-- LuaDoc is in core/.gui.lua.
function gui.switch_buffer()
local items = {}
for _, buffer in ipairs(_BUFFERS) do
local filename = buffer.filename or buffer._type or locale.UNTITLED
local dirty = buffer.dirty and '*' or ''
items[#items + 1] = dirty..filename:match('[^/\\]+$')
items[#items + 1] = filename
end
local response =
gui.dialog('filteredlist',
'--title', locale.SWITCH_BUFFERS,
'--button1', 'gtk-ok',
'--button2', 'gtk-cancel',
'--no-newline',
'--columns', 'Name', 'File',
'--items', items)
local ok, i = response:match('(%-?%d+)\n(%d+)$')
if ok and ok ~= '2' then view:goto_buffer(tonumber(i) + 1, true) end
end
|
Fix switch buffers dialog bug when cancelling; core/gui.lua
|
Fix switch buffers dialog bug when cancelling; core/gui.lua
|
Lua
|
mit
|
jozadaquebatista/textadept,jozadaquebatista/textadept
|
f2264da43cd521bd64e687c91bc7b94c3e28e7b3
|
applications/luci-app-adblock/luasrc/model/cbi/adblock/overview_tab.lua
|
applications/luci-app-adblock/luasrc/model/cbi/adblock/overview_tab.lua
|
-- Copyright 2016 Hannu Nyman
-- Copyright 2017 Dirk Brenken (dev@brenken.org)
-- This is free software, licensed under the Apache License, Version 2.0
local sys = require("luci.sys")
local util = require("luci.util")
local data = util.ubus("service", "get_data", "name", "adblock") or { }
local dnsFile1 = sys.exec("find '/tmp/dnsmasq.d' -maxdepth 1 -type f -name 'adb_list*' -print")
local dnsFile2 = sys.exec("find '/var/lib/unbound' -maxdepth 1 -type f -name 'adb_list*' -print")
m = Map("adblock", translate("Adblock"),
translate("Configuration of the adblock package to block ad/abuse domains by using DNS. ")
.. translate("For further information ")
.. [[<a href="https://github.com/openwrt/packages/blob/master/net/adblock/files/README.md" target="_blank">]]
.. translate("see online documentation")
.. [[</a>]]
.. translate("."))
-- Main adblock options
s = m:section(NamedSection, "global", "adblock")
o1 = s:option(Flag, "adb_enabled", translate("Enable adblock"))
o1.rmempty = false
o1.default = 0
if data.adblock ~= nil and (dnsFile1 ~= "" or dnsFile2 ~= "") then
btn = s:option( Button, "_btn", translate("Suspend adblock"))
btn.inputstyle = "reset"
function btn.write()
luci.sys.call("/etc/init.d/adblock suspend")
end
else
btn = s:option( Button, "_btn", translate("Resume adblock"))
btn.inputstyle = "apply"
function btn.write()
luci.sys.call("/etc/init.d/adblock resume")
end
end
o2 = s:option(Flag, "adb_debug", translate("Enable verbose debug logging"))
o2.default = o2.disabled
o2.rmempty = false
o3 = s:option(Value, "adb_iface", translate("Restrict interface reload trigger to certain interface(s)"),
translate("Space separated list of interfaces that trigger a reload action. "..
"To disable reload trigger at all set it to 'false'."))
o3.rmempty =false
-- Runtime information
ds = s:option(DummyValue, "_dummy", translate("Runtime information"))
ds.template = "cbi/nullsection"
dv1 = s:option(DummyValue, "adblock_version", translate("Adblock version"))
if data.adblock ~= nil then
dv1.value = data.adblock.adblock.adblock_version or "?"
else
dv1.value = "?"
end
dv1.template = "adblock/runtime"
dv2 = s:option(DummyValue, "status", translate("Status"))
if dnsFile1 ~= "" or dnsFile2 ~= "" then
dv2.value = "active"
else
dv2.value = "suspended"
end
dv2.template = "adblock/runtime"
dv3 = s:option(DummyValue, "dns_backend", translate("DNS backend"))
if data.adblock ~= nil then
dv3.value = data.adblock.adblock.dns_backend or "?"
else
dv3.value = "?"
end
dv3.template = "adblock/runtime"
dv4 = s:option(DummyValue, "blocked_domains", translate("Blocked domains (overall)"))
if data.adblock ~= nil then
dv4.value = data.adblock.adblock.blocked_domains or "?"
else
dv4.value = "?"
end
dv4.template = "adblock/runtime"
dv5 = s:option(DummyValue, "last_rundate", translate("Last rundate"))
if data.adblock ~= nil then
dv5.value = data.adblock.adblock.last_rundate or "?"
else
dv5.value = "?"
end
dv5.template = "adblock/runtime"
-- Blocklist options
bl = m:section(TypedSection, "source", translate("Blocklist sources"),
translate("Available blocklist sources. ")
.. translate("Note that list URLs and Shallalist category selections are configurable in the 'Advanced' section."))
bl.template = "cbi/tblsection"
name = bl:option(Flag, "enabled", translate("Enabled"))
name.rmempty = false
des = bl:option(DummyValue, "adb_src_desc", translate("Description"))
-- Backup options
s = m:section(NamedSection, "global", "adblock", translate("Backup options"))
o4 = s:option(Flag, "adb_backup", translate("Enable blocklist backup"))
o4.rmempty = false
o4.default = 0
o5 = s:option(Value, "adb_backupdir", translate("Backup directory"))
o5.rmempty = false
o5.datatype = "directory"
return m
|
-- Copyright 2016 Hannu Nyman
-- Copyright 2017 Dirk Brenken (dev@brenken.org)
-- This is free software, licensed under the Apache License, Version 2.0
local sys = require("luci.sys")
local util = require("luci.util")
local data = util.ubus("service", "get_data", "name", "adblock") or { }
local dnsFile1 = sys.exec("find '/tmp/dnsmasq.d' -maxdepth 1 -type f -name 'adb_list*' -print 2>/dev/null")
local dnsFile2 = sys.exec("find '/var/lib/unbound' -maxdepth 1 -type f -name 'adb_list*' -print 2>/dev/null")
m = Map("adblock", translate("Adblock"),
translate("Configuration of the adblock package to block ad/abuse domains by using DNS. ")
.. translate("For further information ")
.. [[<a href="https://github.com/openwrt/packages/blob/master/net/adblock/files/README.md" target="_blank">]]
.. translate("see online documentation")
.. [[</a>]]
.. translate("."))
-- Main adblock options
s = m:section(NamedSection, "global", "adblock")
o1 = s:option(Flag, "adb_enabled", translate("Enable adblock"))
o1.rmempty = false
o1.default = 0
btn = s:option(Button, "", translate("Suspend / Resume adblock"))
if data.adblock == nil then
btn.inputtitle = "n/a"
btn.inputstyle = nil
btn.disabled = true
elseif dnsFile1 ~= "" or dnsFile2 ~= "" then
btn.inputtitle = "Suspend adblock"
btn.inputstyle = "reset"
btn.disabled = false
function btn.write()
luci.sys.call("/etc/init.d/adblock suspend >/dev/null 2>&1")
end
else
btn.inputtitle = "Resume adblock"
btn.inputstyle = "apply"
btn.disabled = false
function btn.write()
luci.sys.call("/etc/init.d/adblock resume >/dev/null 2>&1")
end
end
o2 = s:option(Flag, "adb_debug", translate("Enable verbose debug logging"))
o2.default = o2.disabled
o2.rmempty = false
o3 = s:option(Value, "adb_iface", translate("Restrict interface reload trigger to certain interface(s)"),
translate("Space separated list of interfaces that trigger a reload action. "..
"To disable reload trigger at all set it to 'false'."))
o3.rmempty =false
-- Runtime information
ds = s:option(DummyValue, "_dummy", translate("Runtime information"))
ds.template = "cbi/nullsection"
dv1 = s:option(DummyValue, "adblock_version", translate("Adblock version"))
dv1.template = "adblock/runtime"
if data.adblock ~= nil then
dv1.value = data.adblock.adblock.adblock_version or "n/a"
else
dv1.value = "n/a"
end
dv2 = s:option(DummyValue, "status", translate("Status"))
dv2.template = "adblock/runtime"
if data.adblock == nil then
dv2.value = "n/a"
elseif dnsFile1 ~= "" or dnsFile2 ~= "" then
dv2.value = "active"
else
dv2.value = "suspended"
end
dv3 = s:option(DummyValue, "dns_backend", translate("DNS backend"))
dv3.template = "adblock/runtime"
if data.adblock ~= nil then
dv3.value = data.adblock.adblock.dns_backend or "n/a"
else
dv3.value = "n/a"
end
dv4 = s:option(DummyValue, "blocked_domains", translate("Blocked domains (overall)"))
dv4.template = "adblock/runtime"
if data.adblock ~= nil then
dv4.value = data.adblock.adblock.blocked_domains or "n/a"
else
dv4.value = "n/a"
end
dv5 = s:option(DummyValue, "last_rundate", translate("Last rundate"))
dv5.template = "adblock/runtime"
if data.adblock ~= nil then
dv5.value = data.adblock.adblock.last_rundate or "n/a"
else
dv5.value = "n/a"
end
-- Blocklist options
bl = m:section(TypedSection, "source", translate("Blocklist sources"),
translate("Available blocklist sources. ")
.. translate("Note that list URLs and Shallalist category selections are configurable in the 'Advanced' section."))
bl.template = "cbi/tblsection"
name = bl:option(Flag, "enabled", translate("Enabled"))
name.rmempty = false
des = bl:option(DummyValue, "adb_src_desc", translate("Description"))
-- Backup options
s = m:section(NamedSection, "global", "adblock", translate("Backup options"))
o4 = s:option(Flag, "adb_backup", translate("Enable blocklist backup"))
o4.rmempty = false
o4.default = 0
o5 = s:option(Value, "adb_backupdir", translate("Backup directory"))
o5.rmempty = false
o5.datatype = "directory"
return m
|
luci-app-adblock: small fixes in overview tab
|
luci-app-adblock: small fixes in overview tab
* mute stderr in syscalls
* better suspend/resume button handling
Signed-off-by: Dirk Brenken <34c6fceca75e456f25e7e99531e2425c6c1de443@brenken.org>
|
Lua
|
apache-2.0
|
kuoruan/luci,981213/luci-1,openwrt-es/openwrt-luci,kuoruan/lede-luci,chris5560/openwrt-luci,aa65535/luci,artynet/luci,taiha/luci,Wedmer/luci,taiha/luci,shangjiyu/luci-with-extra,kuoruan/luci,lbthomsen/openwrt-luci,shangjiyu/luci-with-extra,remakeelectric/luci,Noltari/luci,shangjiyu/luci-with-extra,rogerpueyo/luci,shangjiyu/luci-with-extra,tobiaswaldvogel/luci,remakeelectric/luci,rogerpueyo/luci,rogerpueyo/luci,openwrt/luci,kuoruan/luci,openwrt-es/openwrt-luci,hnyman/luci,rogerpueyo/luci,kuoruan/luci,LuttyYang/luci,LuttyYang/luci,kuoruan/luci,wongsyrone/luci-1,Noltari/luci,oneru/luci,Wedmer/luci,shangjiyu/luci-with-extra,wongsyrone/luci-1,oneru/luci,rogerpueyo/luci,Noltari/luci,oneru/luci,shangjiyu/luci-with-extra,LuttyYang/luci,openwrt-es/openwrt-luci,LuttyYang/luci,tobiaswaldvogel/luci,remakeelectric/luci,lbthomsen/openwrt-luci,981213/luci-1,taiha/luci,wongsyrone/luci-1,kuoruan/lede-luci,nmav/luci,Wedmer/luci,oneru/luci,openwrt-es/openwrt-luci,kuoruan/lede-luci,chris5560/openwrt-luci,aa65535/luci,artynet/luci,Noltari/luci,chris5560/openwrt-luci,shangjiyu/luci-with-extra,nmav/luci,openwrt/luci,taiha/luci,kuoruan/lede-luci,lbthomsen/openwrt-luci,LuttyYang/luci,Noltari/luci,981213/luci-1,Wedmer/luci,Wedmer/luci,kuoruan/luci,nmav/luci,wongsyrone/luci-1,openwrt-es/openwrt-luci,aa65535/luci,chris5560/openwrt-luci,taiha/luci,tobiaswaldvogel/luci,oneru/luci,nmav/luci,artynet/luci,nmav/luci,hnyman/luci,chris5560/openwrt-luci,lbthomsen/openwrt-luci,artynet/luci,LuttyYang/luci,Noltari/luci,Wedmer/luci,remakeelectric/luci,aa65535/luci,artynet/luci,Wedmer/luci,Noltari/luci,tobiaswaldvogel/luci,chris5560/openwrt-luci,rogerpueyo/luci,kuoruan/lede-luci,artynet/luci,hnyman/luci,remakeelectric/luci,nmav/luci,lbthomsen/openwrt-luci,oneru/luci,openwrt/luci,hnyman/luci,taiha/luci,wongsyrone/luci-1,chris5560/openwrt-luci,lbthomsen/openwrt-luci,openwrt-es/openwrt-luci,openwrt/luci,artynet/luci,rogerpueyo/luci,hnyman/luci,oneru/luci,remakeelectric/luci,aa65535/luci,tobiaswaldvogel/luci,kuoruan/luci,aa65535/luci,taiha/luci,oneru/luci,hnyman/luci,kuoruan/luci,kuoruan/lede-luci,hnyman/luci,openwrt-es/openwrt-luci,taiha/luci,aa65535/luci,Wedmer/luci,openwrt/luci,wongsyrone/luci-1,nmav/luci,981213/luci-1,aa65535/luci,LuttyYang/luci,openwrt/luci,981213/luci-1,981213/luci-1,artynet/luci,hnyman/luci,tobiaswaldvogel/luci,openwrt-es/openwrt-luci,rogerpueyo/luci,Noltari/luci,openwrt/luci,artynet/luci,kuoruan/lede-luci,kuoruan/lede-luci,Noltari/luci,tobiaswaldvogel/luci,981213/luci-1,shangjiyu/luci-with-extra,nmav/luci,openwrt/luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,LuttyYang/luci,remakeelectric/luci,wongsyrone/luci-1,wongsyrone/luci-1,lbthomsen/openwrt-luci,nmav/luci,chris5560/openwrt-luci,remakeelectric/luci
|
0ec2de4572348feff705d187eaf398eda8d80cfe
|
util/print-network-table.lua
|
util/print-network-table.lua
|
#!/usr/bin/env th
require 'torch'
require 'nn'
require 'dpnn'
torch.setdefaulttensortype('torch.FloatTensor')
local cmd = torch.CmdLine()
cmd:text()
cmd:text('Print network table.')
cmd:text()
cmd:text('Options:')
cmd:option('-modelDef', '/home/bamos/repos/openface/models/openface/nn4.small2.def.lua', 'Path to model definition.')
cmd:option('-imgDim', 96, 'Image dimension. nn1=224, nn4=96')
cmd:option('-embSize', 128)
cmd:text()
opt = cmd:parse(arg or {})
paths.dofile(opt.modelDef)
local net = createModel()
local img = torch.randn(1, 3, opt.imgDim, opt.imgDim)
net:forward(img)
-- for i,module in ipairs(net:listModules()) do
for i=1,#net.modules do
local module = net.modules[i]
local out = torch.typename(module) .. ": "
for j, sz in ipairs(torch.totable(module.output:size())) do
-- print(sz)
out = out .. sz .. ', '
end
out = string.sub(out, 1, -3)
print(out)
end
|
#!/usr/bin/env th
require 'torch'
require 'nn'
require 'dpnn'
torch.setdefaulttensortype('torch.FloatTensor')
local cmd = torch.CmdLine()
cmd:text()
cmd:text('Print network table.')
cmd:text()
cmd:text('Options:')
cmd:option('-modelDef', '/home/bamos/repos/openface/models/openface/nn4.small2.def.lua', 'Path to model definition.')
cmd:option('-imgDim', 96, 'Image dimension. nn1=224, nn4=96')
cmd:option('-embSize', 128)
cmd:text()
opt = cmd:parse(arg or {})
paths.dofile(opt.modelDef)
local net = createModel()
local img = torch.randn(1, 3, opt.imgDim, opt.imgDim)
net:forward(img)
for i=1,#net.modules do
local module = net.modules[i]
local out = torch.typename(module) .. ": "
for _, sz in ipairs(torch.totable(module.output:size())) do
out = out .. sz .. ', '
end
out = string.sub(out, 1, -3)
print(out)
end
|
Fix luacheck warning.
|
Fix luacheck warning.
|
Lua
|
apache-2.0
|
Alexx-G/openface,francisleunggie/openface,nmabhi/Webface,cmusatyalab/openface,nmabhi/Webface,xinfang/face-recognize,francisleunggie/openface,nmabhi/Webface,xinfang/face-recognize,Alexx-G/openface,nmabhi/Webface,Alexx-G/openface,cmusatyalab/openface,nhzandi/openface,nhzandi/openface,francisleunggie/openface,xinfang/face-recognize,nhzandi/openface,Alexx-G/openface,cmusatyalab/openface
|
044f59c38cdf54a42b5d9cdaf6670d8281d3d294
|
mod_post_msg/mod_post_msg.lua
|
mod_post_msg/mod_post_msg.lua
|
module:depends"http"
local jid_split = require "util.jid".split;
local jid_prep = require "util.jid".prep;
local msg = require "util.stanza".message;
local test_password = require "core.usermanager".test_password;
local b64_decode = require "util.encodings".base64.decode;
local formdecode = require "net.http".formdecode;
local xml = require"util.xml";
local function require_valid_user(f)
return function(event, path)
local request = event.request;
local response = event.response;
local headers = request.headers;
if not headers.authorization then
response.headers.www_authenticate = ("Basic realm=%q"):format(module.host.."/"..module.name);
return 401
end
local from_jid, password = b64_decode(headers.authorization:match"[^ ]*$"):match"([^:]*):(.*)";
from_jid = jid_prep(from_jid);
if from_jid and password then
local user, host = jid_split(from_jid);
local ok, err = test_password(user, host, password);
if ok and user and host then
module:log("debug", "Authed as %s", from_jid);
return f(event, path, from_jid);
elseif err then
module:log("debug", "User failed authentication: %s", err);
end
end
return 401
end
end
local function handle_post(event, path, authed_user)
local request = event.request;
local response = event.response;
local headers = request.headers;
local body_type = headers.content_type;
local to = jid_prep(path);
local message;
if body_type == "text/plain" then
if to and request.body then
message = msg({ to = to, from = authed_user, type = "chat"},request.body);
end
elseif body_type == "application/x-www-form-urlencoded" then
local post_body = formdecode(request.body);
message = msg({ to = post_body.to or to, from = authed_user,
type = post_body.type or "chat"}, post_body.body);
if post_body.html then
local html, err = xml.parse(post_body.html);
if not html then
module:log("warn", "mod_post_msg: invalid XML: %s", err);
return 400;
end
message:tag("html", {xmlns="http://jabber.org/protocol/xhtml-im"}):add_child(html):up();
end
else
return 415;
end
if message and message.attr.to then
module:log("debug", "Sending %s", tostring(message));
module:send(message);
return 201;
end
return 422;
end
module:provides("http", {
default_path = "/msg";
route = {
["POST /*"] = require_valid_user(handle_post);
OPTIONS = function(e)
local headers = e.response.headers;
headers.allow = "POST";
headers.accept = "application/x-www-form-urlencoded, text/plain";
return 200;
end;
}
});
|
module:depends"http"
local jid_split = require "util.jid".split;
local jid_prep = require "util.jid".prep;
local msg = require "util.stanza".message;
local test_password = require "core.usermanager".test_password;
local b64_decode = require "util.encodings".base64.decode;
local formdecode = require "net.http".formdecode;
local xml = require"util.xml";
local function require_valid_user(f)
return function(event, path)
local request = event.request;
local response = event.response;
local headers = request.headers;
if not headers.authorization then
response.headers.www_authenticate = ("Basic realm=%q"):format(module.host.."/"..module.name);
return 401
end
local from_jid, password = b64_decode(headers.authorization:match"[^ ]*$"):match"([^:]*):(.*)";
from_jid = jid_prep(from_jid);
if from_jid and password then
local user, host = jid_split(from_jid);
local ok, err = test_password(user, host, password);
if ok and user and host then
module:log("debug", "Authed as %s", from_jid);
return f(event, path, from_jid);
elseif err then
module:log("debug", "User failed authentication: %s", err);
end
end
return 401
end
end
local function handle_post(event, path, authed_user)
local request = event.request;
local response = event.response;
local headers = request.headers;
local body_type = headers.content_type;
local to = jid_prep(path);
local message;
if body_type == "text/plain" then
if to and request.body then
message = msg({ to = to, from = authed_user, type = "chat"},request.body);
end
elseif body_type == "application/x-www-form-urlencoded" then
local post_body = formdecode(request.body);
message = msg({ to = post_body.to or to, from = authed_user,
type = post_body.type or "chat"}, post_body.body);
if post_body.html then
local html, err = xml.parse(post_body.html);
if not html then
module:log("warn", "mod_post_msg: invalid XML: %s", err);
return 400;
end
message:tag("html", {xmlns="http://jabber.org/protocol/xhtml-im"}):add_child(html):up();
end
else
return 415;
end
if message and message.attr.to then
module:log("debug", "Sending %s", tostring(message));
module:send(message);
return 201;
end
return 422;
end
module:provides("http", {
default_path = "/msg";
route = {
["POST /*"] = require_valid_user(handle_post);
OPTIONS = function(e)
local headers = e.response.headers;
headers.allow = "POST";
headers.accept = "application/x-www-form-urlencoded, text/plain";
return 200;
end;
}
});
|
mod_post_msg: Fix indentation
|
mod_post_msg: Fix indentation
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
4b4bc0dde2bbe33547593d393e4fbba94686aa39
|
profiles/examples/postgis.lua
|
profiles/examples/postgis.lua
|
-- This example shows how to query external data stored in PostGIS when processing ways.
-- This profile assumes that OSM data has been imported to PostGIS using imposm to a db
-- with the name 'imposm', the default user and no password. It assumes areas with
-- landusage=* was imported to the table osm_landusages, containting the columns type and area.
-- Seee http://imposm.org/ for more info on imposm.
-- Other tools for importing OSM data to PostGIS include osm2pgsql and osmosis.
-- It uses the PostGIS function ST_DWithin() to find areas tagged with landuse=industrial
-- that are within 100 meters of the way.
-- It then slows down the routing depending on the number and size of the industrial area.
-- The end result is that routes will tend to avoid industrial area. Passing through
-- industrial areas is still possible, it's just slower, and thus avoided if a reasonable
-- alternative is found.
-- We use the osm id as the key when querying PostGIS. Be sure to add an index to the colunn
-- containing the osm id (osm_id in this case), otherwise you will suffer form very
-- bad performance. You should also have spatial indexes on the relevant gemoetry columns.
-- More info about using SQL form LUA can be found at http://www.keplerproject.org/luasql/
-- Happy routing!
-- Open PostGIS connection
lua_sql = require "luasql.postgres" -- we will connect to a postgresql database
sql_env = assert( lua_sql.postgres() )
sql_con = assert( sql_env:connect("imposm") ) -- you can add db user/password here if needed
print("PostGIS connection opened")
-- these settings are read directly by osrm
take_minimum_of_speeds = true
obey_oneway = true
obey_bollards = true
use_restrictions = true
ignore_areas = true -- future feature
traffic_signal_penalty = 7 -- seconds
u_turn_penalty = 20
-- nodes processing, called from OSRM
function node_function(node)
return 1
end
-- ways processing, called from OSRM
function way_function (way)
-- only route on ways with highway=*
local highway = way.tags:Find("highway")
if (not highway or highway=='') then
return 0
end
-- Query PostGIS for industrial areas close to the way, then group by way and sum the areas.
-- We take the square root of the area to get a estimate of the length of the side of the area,
-- and thus a rough guess of how far we might be travelling along the area.
local sql_query = " " ..
"SELECT SUM(SQRT(area.area)) AS val " ..
"FROM osm_ways way " ..
"LEFT JOIN osm_landusages area ON ST_DWithin(way.geometry, area.geometry, 100) " ..
"WHERE area.type IN ('industrial') AND way.osm_id=" .. way.id .. " " ..
"GROUP BY way.id"
local cursor = assert( sql_con:execute(sql_query) ) -- execute querty
local row = cursor:fetch( {}, "a" ) -- fetch first (and only) row
way.forward_speed = 20.0 -- default speed
if row then
local val = tonumber(row.val) -- read 'val' from row
if val > 10 then
way.forward_speed = way.forward_speed / math.log10( val ) -- reduce speed by amount of industry close by
end
end
cursor:close() -- done with this query
-- set other required info for this way
way.name = way.tags:Find("name")
way.direction = Way.bidirectional
way.type = 1
return 1
end
|
-- This example shows how to query external data stored in PostGIS when processing ways.
-- This profile assumes that OSM data has been imported to PostGIS using imposm to a db
-- with the name 'imposm', the default user and no password. It assumes areas with
-- landusage=* was imported to the table osm_landusages, containting the columns type and area.
-- Seee http://imposm.org/ for more info on imposm.
-- Other tools for importing OSM data to PostGIS include osm2pgsql and osmosis.
-- It uses the PostGIS function ST_DWithin() to find areas tagged with landuse=industrial
-- that are within 100 meters of the way.
-- It then slows down the routing depending on the number and size of the industrial area.
-- The end result is that routes will tend to avoid industrial area. Passing through
-- industrial areas is still possible, it's just slower, and thus avoided if a reasonable
-- alternative is found.
-- We use the osm id as the key when querying PostGIS. Be sure to add an index to the colunn
-- containing the osm id (osm_id in this case), otherwise you will suffer form very
-- bad performance. You should also have spatial indexes on the relevant gemoetry columns.
-- More info about using SQL form LUA can be found at http://www.keplerproject.org/luasql/
-- Happy routing!
-- Open PostGIS connection
lua_sql = require "luasql.postgres" -- we will connect to a postgresql database
sql_env = assert( lua_sql.postgres() )
sql_con = assert( sql_env:connect("imposm") ) -- you can add db user/password here if needed
print("PostGIS connection opened")
-- these settings are read directly by osrm
take_minimum_of_speeds = true
obey_oneway = true
obey_bollards = true
use_restrictions = true
ignore_areas = true -- future feature
traffic_signal_penalty = 7 -- seconds
u_turn_penalty = 20
-- nodes processing, called from OSRM
function node_function(node)
return 1
end
-- ways processing, called from OSRM
function way_function (way, result)
-- only route on ways with highway=*
local highway = way.tags:Find("highway")
if (not highway or highway=='') then
return 0
end
-- Query PostGIS for industrial areas close to the way, then group by way and sum the areas.
-- We take the square root of the area to get a estimate of the length of the side of the area,
-- and thus a rough guess of how far we might be travelling along the area.
local sql_query = " " ..
"SELECT SUM(SQRT(area.area)) AS val " ..
"FROM osm_ways way " ..
"LEFT JOIN osm_landusages area ON ST_DWithin(way.geometry, area.geometry, 100) " ..
"WHERE area.type IN ('industrial') AND way.osm_id=" .. way.id .. " " ..
"GROUP BY way.id"
local cursor = assert( sql_con:execute(sql_query) ) -- execute querty
local row = cursor:fetch( {}, "a" ) -- fetch first (and only) row
result.forward_speed = 20.0 -- default speed
result.forward_mode = 1
if row then
local val = tonumber(row.val) -- read 'val' from row
if val > 10 then
-- reduce speed by amount of industry close by
result.forward_speed = way.forward_speed / math.log10( val )
end
end
cursor:close() -- done with this query
-- set other required info for this way
result.name = way.get_value_by_key("name")
return 1
end
|
Fix postgis lua example
|
Fix postgis lua example
Fixes #1573.
|
Lua
|
bsd-2-clause
|
arnekaiser/osrm-backend,hydrays/osrm-backend,deniskoronchik/osrm-backend,beemogmbh/osrm-backend,felixguendling/osrm-backend,hydrays/osrm-backend,neilbu/osrm-backend,frodrigo/osrm-backend,hydrays/osrm-backend,KnockSoftware/osrm-backend,bjtaylor1/osrm-backend,arnekaiser/osrm-backend,neilbu/osrm-backend,Project-OSRM/osrm-backend,Conggge/osrm-backend,felixguendling/osrm-backend,frodrigo/osrm-backend,beemogmbh/osrm-backend,yuryleb/osrm-backend,KnockSoftware/osrm-backend,duizendnegen/osrm-backend,duizendnegen/osrm-backend,deniskoronchik/osrm-backend,KnockSoftware/osrm-backend,yuryleb/osrm-backend,hydrays/osrm-backend,raymond0/osrm-backend,duizendnegen/osrm-backend,oxidase/osrm-backend,raymond0/osrm-backend,felixguendling/osrm-backend,oxidase/osrm-backend,Project-OSRM/osrm-backend,oxidase/osrm-backend,deniskoronchik/osrm-backend,arnekaiser/osrm-backend,Project-OSRM/osrm-backend,neilbu/osrm-backend,frodrigo/osrm-backend,Conggge/osrm-backend,yuryleb/osrm-backend,Project-OSRM/osrm-backend,frodrigo/osrm-backend,bjtaylor1/osrm-backend,bjtaylor1/osrm-backend,bjtaylor1/osrm-backend,beemogmbh/osrm-backend,deniskoronchik/osrm-backend,neilbu/osrm-backend,beemogmbh/osrm-backend,duizendnegen/osrm-backend,oxidase/osrm-backend,raymond0/osrm-backend,KnockSoftware/osrm-backend,raymond0/osrm-backend,Conggge/osrm-backend,Conggge/osrm-backend,arnekaiser/osrm-backend,yuryleb/osrm-backend
|
488857a3ddb2919b8fee88142b650db377a1c773
|
server.lua
|
server.lua
|
-- https://github.com/szym/display
-- Copyright (c) 2015, Szymon Jakubczak (MIT License)
-- Forwards any data POSTed to /events to an event-stream at /events.
-- Serves files from /static otherwise.
local turbo = require('turbo')
local subscribers = {}
function postEvent(data)
for k, v in pairs(subscribers) do
k:sendEvent(data)
end
end
local EventHandler = class('EventHandler', turbo.web.RequestHandler)
function EventHandler:sendEvent(data)
self:write('data: ')
self:write(data)
self:write('\n\n')
coroutine.yield(self:flush())
end
function EventHandler:get()
self:set_async(true)
self:set_chunked_write()
self:set_header('Content-Type', 'text/event-stream')
self:set_header('Cache-Control', 'no-cache')
self:set_header('Connection', 'keep-alive')
self:set_status(200)
self:flush()
subscribers[self] = self
end
function EventHandler:on_finish()
subscribers[self] = nil
end
function EventHandler:post()
self:set_async(true)
postEvent(self.request.body)
self:set_status(200)
self:finish()
end
local scriptname = debug.getinfo(1, 'S').source:sub(2)
local staticdir = scriptname:gsub('server.lua$', 'static/')
app = turbo.web.Application:new({
{'/events', EventHandler},
{'/$', turbo.web.StaticFileHandler, staticdir .. 'index.html'},
{'/(.*)$', turbo.web.StaticFileHandler, staticdir}
})
local port = tonumber(arg[1]) or 8000
local hostname = arg[2] or 'localhost'
app:listen(port)
print('Listening on http://' .. hostname .. ':' .. port)
turbo.ioloop.instance():start()
|
-- https://github.com/szym/display
-- Copyright (c) 2015, Szymon Jakubczak (MIT License)
-- Forwards any data POSTed to /events to an event-stream at /events.
-- Serves files from /static otherwise.
local turbo = require('turbo')
local subscribers = {}
function postEvent(data)
for k, v in pairs(subscribers) do
k:sendEvent(data)
end
end
local EventHandler = class('EventHandler', turbo.web.RequestHandler)
function EventHandler:sendEvent(data)
self:write('data: ')
self:write(data)
self:write('\n\n')
coroutine.yield(self:flush())
end
function EventHandler:get()
self:set_async(true)
self:set_chunked_write()
self:set_header('Content-Type', 'text/event-stream')
self:set_header('Cache-Control', 'no-cache')
self:set_header('Connection', 'keep-alive')
self:set_status(200)
self:flush()
subscribers[self] = self
end
function EventHandler:on_finish()
subscribers[self] = nil
end
function EventHandler:post()
self:set_async(true)
postEvent(self.request.body)
self:set_status(200)
self:finish()
end
local scriptname = debug.getinfo(1, 'S').source:sub(2)
local staticdir = scriptname:gsub('server.lua$', 'static/')
app = turbo.web.Application:new({
{'/events', EventHandler},
{'/$', turbo.web.StaticFileHandler, staticdir .. 'index.html'},
{'/(.*)$', turbo.web.StaticFileHandler, staticdir}
})
local port = tonumber(arg[1]) or 8000
local hostname = arg[2] or '127.0.0.1'
app:listen(port, hostname, { max_body_size=(20 * 1024 * 1024) })
print('Listening on http://' .. hostname .. ':' .. port)
turbo.ioloop.instance():start()
|
Work around max_buffer_size bug in TurboLua.
|
Work around max_buffer_size bug in TurboLua.
Also, default to localhost listening.
|
Lua
|
mit
|
szym/display,szym/display,szym/display,szym/display,soumith/display,soumith/display,soumith/display,soumith/display
|
c0c3d8f6b471e17d05ef26d903448b99bc4ea1c2
|
spec/plugins/logging_spec.lua
|
spec/plugins/logging_spec.lua
|
local IO = require "kong.tools.io"
local utils = require "kong.tools.utils"
local cjson = require "cjson"
local stringy = require "stringy"
local spec_helper = require "spec.spec_helpers"
local http_client = require "kong.tools.http_client"
local STUB_GET_URL = spec_helper.STUB_GET_URL
local TCP_PORT = 20777
local UDP_PORT = 20778
local HTTP_PORT = 20779
local HTTP_DELAY_PORT = 20780
local FILE_LOG_PATH = spec_helper.get_env().configuration.nginx_working_dir.."/file_log_spec_output.log"
local function create_mock_bin()
local res, status = http_client.post("http://mockbin.org/bin/create", '{ "status": 200, "statusText": "OK", "httpVersion": "HTTP/1.1", "headers": [], "cookies": [], "content": { "mimeType" : "application/json" }, "redirectURL": "", "headersSize": 0, "bodySize": 0 }', { ["content-type"] = "application/json" })
assert.are.equal(201, status)
return res:sub(2, res:len() - 1)
end
local mock_bin = create_mock_bin()
describe("Logging Plugins", function()
setup(function()
spec_helper.prepare_db()
spec_helper.insert_fixtures {
api = {
{ name = "tests tcp logging", public_dns = "tcp_logging.com", target_url = "http://mockbin.com" },
{ name = "tests tcp logging2", public_dns = "tcp_logging2.com", target_url = "http://localhost:"..HTTP_DELAY_PORT },
{ name = "tests udp logging", public_dns = "udp_logging.com", target_url = "http://mockbin.com" },
{ name = "tests http logging", public_dns = "http_logging.com", target_url = "http://mockbin.com" },
{ name = "tests https logging", public_dns = "https_logging.com", target_url = "http://mockbin.com" },
{ name = "tests file logging", public_dns = "file_logging.com", target_url = "http://mockbin.com" }
},
plugin_configuration = {
{ name = "tcplog", value = { host = "127.0.0.1", port = TCP_PORT }, __api = 1 },
{ name = "tcplog", value = { host = "127.0.0.1", port = TCP_PORT }, __api = 2 },
{ name = "udplog", value = { host = "127.0.0.1", port = UDP_PORT }, __api = 3 },
{ name = "httplog", value = { http_endpoint = "http://localhost:"..HTTP_PORT.."/" }, __api = 4 },
{ name = "httplog", value = { http_endpoint = "https://mockbin.org/bin/"..mock_bin }, __api = 5 },
{ name = "filelog", value = { path = FILE_LOG_PATH }, __api = 6 }
}
}
spec_helper.start_kong()
end)
teardown(function()
spec_helper.stop_kong()
end)
it("should log to TCP", function()
local thread = spec_helper.start_tcp_server(TCP_PORT) -- Starting the mock TCP server
-- Making the request
local _, status = http_client.get(STUB_GET_URL, nil, { host = "tcp_logging.com" })
assert.are.equal(200, status)
-- Getting back the TCP server input
local ok, res = thread:join()
assert.truthy(ok)
assert.truthy(res)
-- Making sure it's alright
local log_message = cjson.decode(res)
assert.are.same("127.0.0.1", log_message.client_ip)
end)
it("should log proper latencies", function()
local http_thread = spec_helper.start_http_server(HTTP_DELAY_PORT) -- Starting the mock TCP server
local tcp_thread = spec_helper.start_tcp_server(TCP_PORT) -- Starting the mock TCP server
-- Making the request
local _, status = http_client.get(spec_helper.PROXY_URL.."/delay", nil, { host = "tcp_logging2.com" })
assert.are.equal(200, status)
-- Getting back the TCP server input
local ok, res = tcp_thread:join()
assert.truthy(ok)
assert.truthy(res)
-- Making sure it's alright
local log_message = cjson.decode(res)
assert.truthy(log_message.latencies.proxy < 3000)
assert.truthy(log_message.latencies.kong < 100)
assert.truthy(log_message.latencies.request >= log_message.latencies.kong + log_message.latencies.proxy)
http_thread:join()
end)
it("should log to UDP", function()
local thread = spec_helper.start_udp_server(UDP_PORT) -- Starting the mock TCP server
-- Making the request
local _, status = http_client.get(STUB_GET_URL, nil, { host = "udp_logging.com" })
assert.are.equal(200, status)
-- Getting back the TCP server input
local ok, res = thread:join()
assert.truthy(ok)
assert.truthy(res)
-- Making sure it's alright
local log_message = cjson.decode(res)
assert.are.same("127.0.0.1", log_message.client_ip)
end)
it("should log to HTTP", function()
local thread = spec_helper.start_http_server(HTTP_PORT) -- Starting the mock TCP server
-- Making the request
local _, status = http_client.get(STUB_GET_URL, nil, { host = "http_logging.com" })
assert.are.equal(200, status)
-- Getting back the TCP server input
local ok, res = thread:join()
assert.truthy(ok)
assert.truthy(res)
-- Making sure it's alright
assert.are.same("POST / HTTP/1.1", res[1])
local log_message = cjson.decode(res[7])
assert.are.same("127.0.0.1", log_message.client_ip)
end)
it("should log to HTTPs", function()
-- Making the request
local _, status = http_client.get(STUB_GET_URL, nil, { host = "https_logging.com" })
assert.are.equal(200, status)
local total_time = 0
local res, status, body
repeat
assert.truthy(total_time <= 10) -- Fail after 10 seconds
res, status = http_client.get("http://mockbin.org/bin/"..mock_bin.."/log", nil, { accept = "application/json" })
assert.are.equal(200, status)
body = cjson.decode(res)
local wait = 1
os.execute("sleep "..tostring(wait))
total_time = total_time + wait
until(#body.log.entries > 0)
assert.are.equal(1, #body.log.entries)
local log_message = cjson.decode(body.log.entries[1].request.postData.text)
-- Making sure it's alright
assert.are.same("127.0.0.1", log_message.client_ip)
end)
it("should log to file", function()
os.remove(FILE_LOG_PATH)
local uuid = utils.random_string()
-- Making the request
local _, status = http_client.get(STUB_GET_URL, nil,
{ host = "file_logging.com", file_log_uuid = uuid }
)
assert.are.equal(200, status)
while not (IO.file_exists(FILE_LOG_PATH) and IO.file_size(FILE_LOG_PATH) > 0) do
-- Wait for the file to be created, and for the log to be appended
end
local file_log = IO.read_file(FILE_LOG_PATH)
local log_message = cjson.decode(stringy.strip(file_log))
assert.are.same("127.0.0.1", log_message.client_ip)
assert.are.same(uuid, log_message.request.headers.file_log_uuid)
end)
end)
|
local IO = require "kong.tools.io"
local utils = require "kong.tools.utils"
local cjson = require "cjson"
local stringy = require "stringy"
local spec_helper = require "spec.spec_helpers"
local http_client = require "kong.tools.http_client"
local STUB_GET_URL = spec_helper.STUB_GET_URL
local TCP_PORT = 20777
local UDP_PORT = 20778
local HTTP_PORT = 20779
local HTTP_DELAY_PORT = 20780
local FILE_LOG_PATH = spec_helper.get_env().configuration.nginx_working_dir.."/file_log_spec_output.log"
local function create_mock_bin()
local res, status = http_client.post("http://mockbin.org/bin/create", '{ "status": 200, "statusText": "OK", "httpVersion": "HTTP/1.1", "headers": [], "cookies": [], "content": { "mimeType" : "application/json" }, "redirectURL": "", "headersSize": 0, "bodySize": 0 }', { ["content-type"] = "application/json" })
assert.are.equal(201, status)
return res:sub(2, res:len() - 1)
end
local mock_bin = create_mock_bin()
describe("Logging Plugins", function()
setup(function()
spec_helper.prepare_db()
spec_helper.insert_fixtures {
api = {
{ name = "tests tcp logging", public_dns = "tcp_logging.com", target_url = "http://mockbin.com" },
{ name = "tests tcp logging2", public_dns = "tcp_logging2.com", target_url = "http://localhost:"..HTTP_DELAY_PORT },
{ name = "tests udp logging", public_dns = "udp_logging.com", target_url = "http://mockbin.com" },
{ name = "tests http logging", public_dns = "http_logging.com", target_url = "http://mockbin.com" },
{ name = "tests https logging", public_dns = "https_logging.com", target_url = "http://mockbin.com" },
{ name = "tests file logging", public_dns = "file_logging.com", target_url = "http://mockbin.com" }
},
plugin_configuration = {
{ name = "tcplog", value = { host = "127.0.0.1", port = TCP_PORT }, __api = 1 },
{ name = "tcplog", value = { host = "127.0.0.1", port = TCP_PORT }, __api = 2 },
{ name = "udplog", value = { host = "127.0.0.1", port = UDP_PORT }, __api = 3 },
{ name = "httplog", value = { http_endpoint = "http://localhost:"..HTTP_PORT.."/" }, __api = 4 },
{ name = "httplog", value = { http_endpoint = "https://mockbin.org/bin/"..mock_bin }, __api = 5 },
{ name = "filelog", value = { path = FILE_LOG_PATH }, __api = 6 }
}
}
spec_helper.start_kong()
end)
teardown(function()
spec_helper.stop_kong()
end)
it("should log to TCP", function()
local thread = spec_helper.start_tcp_server(TCP_PORT) -- Starting the mock TCP server
-- Making the request
local _, status = http_client.get(STUB_GET_URL, nil, { host = "tcp_logging.com" })
assert.are.equal(200, status)
-- Getting back the TCP server input
local ok, res = thread:join()
assert.truthy(ok)
assert.truthy(res)
-- Making sure it's alright
local log_message = cjson.decode(res)
assert.are.same("127.0.0.1", log_message.client_ip)
end)
it("should log proper latencies", function()
local http_thread = spec_helper.start_http_server(HTTP_DELAY_PORT) -- Starting the mock TCP server
local tcp_thread = spec_helper.start_tcp_server(TCP_PORT) -- Starting the mock TCP server
-- Making the request
local _, status = http_client.get(spec_helper.PROXY_URL.."/delay", nil, { host = "tcp_logging2.com" })
assert.are.equal(200, status)
-- Getting back the TCP server input
local ok, res = tcp_thread:join()
assert.truthy(ok)
assert.truthy(res)
-- Making sure it's alright
local log_message = cjson.decode(res)
assert.truthy(log_message.latencies.proxy < 3000)
assert.truthy(log_message.latencies.kong < 500) -- Travis can be very slow, hopefully not slower than half a second
assert.truthy(log_message.latencies.request >= log_message.latencies.kong + log_message.latencies.proxy)
http_thread:join()
end)
it("should log to UDP", function()
local thread = spec_helper.start_udp_server(UDP_PORT) -- Starting the mock TCP server
-- Making the request
local _, status = http_client.get(STUB_GET_URL, nil, { host = "udp_logging.com" })
assert.are.equal(200, status)
-- Getting back the TCP server input
local ok, res = thread:join()
assert.truthy(ok)
assert.truthy(res)
-- Making sure it's alright
local log_message = cjson.decode(res)
assert.are.same("127.0.0.1", log_message.client_ip)
end)
it("should log to HTTP", function()
local thread = spec_helper.start_http_server(HTTP_PORT) -- Starting the mock TCP server
-- Making the request
local _, status = http_client.get(STUB_GET_URL, nil, { host = "http_logging.com" })
assert.are.equal(200, status)
-- Getting back the TCP server input
local ok, res = thread:join()
assert.truthy(ok)
assert.truthy(res)
-- Making sure it's alright
assert.are.same("POST / HTTP/1.1", res[1])
local log_message = cjson.decode(res[7])
assert.are.same("127.0.0.1", log_message.client_ip)
end)
it("should log to HTTPs", function()
-- Making the request
local _, status = http_client.get(STUB_GET_URL, nil, { host = "https_logging.com" })
assert.are.equal(200, status)
local total_time = 0
local res, status, body
repeat
assert.truthy(total_time <= 10) -- Fail after 10 seconds
res, status = http_client.get("http://mockbin.org/bin/"..mock_bin.."/log", nil, { accept = "application/json" })
assert.are.equal(200, status)
body = cjson.decode(res)
local wait = 1
os.execute("sleep "..tostring(wait))
total_time = total_time + wait
until(#body.log.entries > 0)
assert.are.equal(1, #body.log.entries)
local log_message = cjson.decode(body.log.entries[1].request.postData.text)
-- Making sure it's alright
assert.are.same("127.0.0.1", log_message.client_ip)
end)
it("should log to file", function()
os.remove(FILE_LOG_PATH)
local uuid = utils.random_string()
-- Making the request
local _, status = http_client.get(STUB_GET_URL, nil,
{ host = "file_logging.com", file_log_uuid = uuid }
)
assert.are.equal(200, status)
while not (IO.file_exists(FILE_LOG_PATH) and IO.file_size(FILE_LOG_PATH) > 0) do
-- Wait for the file to be created, and for the log to be appended
end
local file_log = IO.read_file(FILE_LOG_PATH)
local log_message = cjson.decode(stringy.strip(file_log))
assert.are.same("127.0.0.1", log_message.client_ip)
assert.are.same(uuid, log_message.request.headers.file_log_uuid)
end)
end)
|
fixing logging spec
|
fixing logging spec
|
Lua
|
apache-2.0
|
peterayeni/kong,paritoshmmmec/kong,bbalu/kong,sbuettner/kong,Skyscanner/kong,vmercierfr/kong,chourobin/kong,ChristopherBiscardi/kong,skynet/kong,wakermahmud/kong,AnsonSmith/kong
|
d853a52528a7f56a702d964e6c36d8528b02fe8c
|
OS/DiskOS/APIS/RamUtils.lua
|
OS/DiskOS/APIS/RamUtils.lua
|
--RAM Utilities.
--Variabes.
local sw,sh = screenSize()
--Localized Lua Library
local unpack = unpack
local floor, ceil, min = math.floor, math.ceil, math.min
local strChar, strByte = string.char, string.byte
local lshift, rshift, bor, band = bit.lshift, bit.rshift, bit.bor, bit.band
--The API
local RamUtils = {}
RamUtils.VRAM = 0 --The start address of the VRAM
RamUtils.LIMG = RamUtils.VRAM + (sw/2)*sh --The start address of the LabelImage.
RamUtils.FRAM = RamUtils.LIMG + (sw/2)*sh --The start address of the Floppy RAM.
RamUtils.Null = strChar(0) --The null character
--==Images==--
--Encode an image into binary.
function RamUtils.imgToBin(img,getTable)
if image:typeOf("GPU.image") then image = image:data() end --Convert the image to imagedata.
local bin = {}
local imgW, imgH = img:size()
local flag = true
img:map(function(x,y,c)
x = x + y*imgW + 1
local byte = bin[floor(x/2)] or 0
if flag then
byte = byte + lshift(c,4)
else
byte = byte + c
end
bin[floor(x/2)] = byte
flag = not flag
end)
if getTable then return bin end
return strChar(unpack(bin))
end
--Load an image from binary.
function RamUtils.binToImage(img,bin)
local colors, cid = {}, 1
for i=1,bin:len() do
local byte = strByte(bin,i)
local left = band(byte,0xF0)
colors[cid] = rshift(left,4)
colors[cid+1] = band(byte,0x0F)
cid = cid + 2
end
cid = 1
imgdata:map(function(x,y,c)
local c = colors[cid] or 0
cid = cid + 1
return c
end)
end
--==Maps==--
--Encode a map into binary.
function RamUtils.mapToBin(map,getTable)
local bin = {}
local tid = 1
map:map(function(x,y,tile)
bin[tid] = min(tile,255)
tid = tid + 1
end)
if getTable then return bin end
return strChar(unpack(bin))
end
--Load a map from binary.
function RamUtils.binToMap(map,bin)
local len, id = bin:len(), 0
map:map(function(x,y,tile)
id = id + 1
return (id <= len and strByte(bin,id) or 0)
end)
end
--==Code==--
--Encode code into binary.
function RamUtils.codeToBin(code)
return math.compress(code,"gzip",9)
end
--Load code from binary.
function RamUtils.binToCode(bin)
return math.decompress(bin,"gzip",9)
end
--==Extra==--
--Encode a number into binary
function RamUtils.numToBin(num,length,getTable)
local bytes = {}
for bnum=1,length do
bytes[bnum] = band(num,255)
num = rshift(num,8)
end
if getTable then return bytes end
return strChar(unpack(bytes))
end
--Load a number from binar
function RamUtils.binToNum(bin)
local number = 0
for i=1,bin:len() do
local byte = strByte(bin,i)
byte = lshift(byte,(i-1)*8)
number = bor(number,byte)
end
return number
end
--Calculate the length of the number in bytes
function RamUtils.numLength(num)
local length = 0
while num > 0 do
num = rshift(num,8)
length = length + 1
end
return length
end
--Create a binary iterator for a string
function RamUtils.binIter(bin)
local counter = 0
return function()
counter = counter + 1
return strByte(bin,counter)
end, function()
return counter
end
end
--Make the ramutils a global
_G["RamUtils"] = RamUtils
|
--RAM Utilities.
--Variabes.
local sw,sh = screenSize()
--Localized Lua Library
local unpack = unpack
local floor, ceil, min = math.floor, math.ceil, math.min
local strChar, strByte = string.char, string.byte
local lshift, rshift, bor, band = bit.lshift, bit.rshift, bit.bor, bit.band
--The API
local RamUtils = {}
RamUtils.VRAM = 0 --The start address of the VRAM
RamUtils.LIMG = RamUtils.VRAM + (sw/2)*sh --The start address of the LabelImage.
RamUtils.FRAM = RamUtils.LIMG + (sw/2)*sh --The start address of the Floppy RAM.
RamUtils.Null = strChar(0) --The null character
--==Images==--
--Encode an image into binary.
function RamUtils.imgToBin(img,getTable)
if img:typeOf("GPU.image") then img = img:data() end --Convert the image to imagedata.
local bin = {}
local imgW, imgH = img:size()
local flag = true
img:map(function(x,y,c)
x = x + y*imgW + 1
local byte = bin[floor(x/2)] or 0
if flag then
byte = byte + lshift(c,4)
else
byte = byte + c
end
bin[floor(x/2)] = byte
flag = not flag
end)
if getTable then return bin end
for k,v in pairs(bin) do
bin[k] = strChar(v)
end
return table.concat(bin)
end
--Load an image from binary.
function RamUtils.binToImage(img,bin)
local colors, cid = {}, 1
for i=1,bin:len() do
local byte = strByte(bin,i)
local left = band(byte,0xF0)
colors[cid] = rshift(left,4)
colors[cid+1] = band(byte,0x0F)
cid = cid + 2
end
cid = 1
imgdata:map(function(x,y,c)
local c = colors[cid] or 0
cid = cid + 1
return c
end)
end
--==Maps==--
--Encode a map into binary.
function RamUtils.mapToBin(map,getTable)
local bin = {}
local tid = 1
map:map(function(x,y,tile)
bin[tid] = min(tile,255)
tid = tid + 1
end)
if getTable then return bin end
for k,v in pairs(bin) do
bin[k] = strChar(v)
end
return table.concat(bin)
end
--Load a map from binary.
function RamUtils.binToMap(map,bin)
local len, id = bin:len(), 0
map:map(function(x,y,tile)
id = id + 1
return (id <= len and strByte(bin,id) or 0)
end)
end
--==Code==--
--Encode code into binary.
function RamUtils.codeToBin(code)
return math.compress(code,"gzip",9)
end
--Load code from binary.
function RamUtils.binToCode(bin)
return math.decompress(bin,"gzip",9)
end
--==Extra==--
--Encode a number into binary
function RamUtils.numToBin(num,length,getTable)
local bytes = {}
for bnum=1,length do
bytes[bnum] = band(num,255)
num = rshift(num,8)
end
if getTable then return bytes end
return strChar(unpack(bytes))
end
--Load a number from binar
function RamUtils.binToNum(bin)
local number = 0
for i=1,bin:len() do
local byte = strByte(bin,i)
byte = lshift(byte,(i-1)*8)
number = bor(number,byte)
end
return number
end
--Calculate the length of the number in bytes
function RamUtils.numLength(num)
local length = 0
while num > 0 do
num = rshift(num,8)
length = length + 1
end
return length
end
--Create a binary iterator for a string
function RamUtils.binIter(bin)
local counter = 0
return function()
counter = counter + 1
return strByte(bin,counter)
end, function()
return counter
end
end
--Make the ramutils a global
_G["RamUtils"] = RamUtils
|
Bugfixes in RamUtils.imgToBin + RamUtils.mapToBin
|
Bugfixes in RamUtils.imgToBin + RamUtils.mapToBin
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
6bec98b05129fdee91f3153ac3e426c12b183d89
|
world/Plugins/Docker/docker.lua
|
world/Plugins/Docker/docker.lua
|
-- local PLUGIN = nil
Ground = 63
DContainer = {displayed = false, x = 0, z = 0, name="",id="",imageRepo="",imageTag=""}
CONTAINER_START_X = 0
CONTAINER_OFFSET_X = -6
CONTAINER_START_Z = 4
Containers = {}
SignsToUpdate = {}
function startContainer(id,name,imageRepo,imageTag)
x = 0
for i=0, table.getn(Containers)
do
if Containers[i] == nil
then
container = DContainer
container:init(x,CONTAINER_START_Z)
container:display()
Containers[i] = container
return
end
x = x + CONTAINER_OFFSET_X
end
container = DContainer
container:init(x,CONTAINER_START_Z)
container:display()
container.id = id
container.name = name
container.imageRepo = imageRepo
container.imageTag = imageTag
table.insert(Containers, container)
end
function DContainer:init(x,z)
self.x = x
self.z = z
self.displayed = false
end
function DContainer:display()
if self.displayed == false
then
self.displayed = true
cRoot:Get():GetDefaultWorld():SetBlock(self.x,Ground + 1,self.z - 1,E_BLOCK_SIGN_POST,8)
local c = self
sign = {}
sign.x = self.x
sign.y = Ground + 1
sign.z = self.z - 1
sign.line1 = self.id
sign.line2 = self.name
sign.line3 = self.imageRepo
sign.line4 = self.imageTag
table.insert(SignsToUpdate,sign)
cRoot:Get():GetDefaultWorld():ScheduleTask(20,
function(World)
for i=1,table.getn(SignsToUpdate) do
local sign = SignsToUpdate[i]
LOG("update sign: " .. sign.line1)
cRoot:Get():GetDefaultWorld():SetSignLines(self.x,Ground + 1,self.z - 1,sign.line1,sign.line2,sign.line3,sign.line4)
end
SignsToUpdate = {}
end
)
for px=self.x, self.x+3
do
for pz=self.z, self.z+4
do
cRoot:Get():GetDefaultWorld():SetBlock(px,Ground + 1,pz,E_BLOCK_WOOL,E_META_WOOL_LIGHTBLUE)
end
end
for py = Ground+2, Ground+3
do
cRoot:Get():GetDefaultWorld():SetBlock(self.x,py,self.z,E_BLOCK_WOOL,E_META_WOOL_LIGHTBLUE)
cRoot:Get():GetDefaultWorld():SetBlock(self.x+3,py,self.z,E_BLOCK_WOOL,E_META_WOOL_LIGHTBLUE)
cRoot:Get():GetDefaultWorld():SetBlock(self.x,py,self.z+1,E_BLOCK_WOOL,E_META_WOOL_BLUE)
cRoot:Get():GetDefaultWorld():SetBlock(self.x+3,py,self.z+1,E_BLOCK_WOOL,E_META_WOOL_BLUE)
cRoot:Get():GetDefaultWorld():SetBlock(self.x,py,self.z+2,E_BLOCK_WOOL,E_META_WOOL_LIGHTBLUE)
cRoot:Get():GetDefaultWorld():SetBlock(self.x+3,py,self.z+2,E_BLOCK_WOOL,E_META_WOOL_LIGHTBLUE)
cRoot:Get():GetDefaultWorld():SetBlock(self.x,py,self.z+3,E_BLOCK_WOOL,E_META_WOOL_BLUE)
cRoot:Get():GetDefaultWorld():SetBlock(self.x+3,py,self.z+3,E_BLOCK_WOOL,E_META_WOOL_BLUE)
cRoot:Get():GetDefaultWorld():SetBlock(self.x,py,self.z+4,E_BLOCK_WOOL,E_META_WOOL_LIGHTBLUE)
cRoot:Get():GetDefaultWorld():SetBlock(self.x+3,py,self.z+4,E_BLOCK_WOOL,E_META_WOOL_LIGHTBLUE)
cRoot:Get():GetDefaultWorld():SetBlock(self.x+1,py,self.z+4,E_BLOCK_WOOL,E_META_WOOL_LIGHTBLUE)
cRoot:Get():GetDefaultWorld():SetBlock(self.x+2,py,self.z+4,E_BLOCK_WOOL,E_META_WOOL_LIGHTBLUE)
end
for px=self.x, self.x+3
do
for pz=self.z, self.z+4
do
cRoot:Get():GetDefaultWorld():SetBlock(px,Ground + 4,pz,E_BLOCK_WOOL,E_META_WOOL_LIGHTBLUE)
end
end
end
end
function Initialize(Plugin)
Plugin:SetName("Docker")
Plugin:SetVersion(1)
-- Hooks
cPluginManager:AddHook(cPluginManager.HOOK_WORLD_STARTED, WorldStarted);
-- PLUGIN = Plugin -- NOTE: only needed if you want OnDisable() to use GetName() or something like that
-- Command Bindings
Plugin:AddWebTab("Docker",HandleRequest_Docker)
LOG("Initialised " .. Plugin:GetName() .. " v." .. Plugin:GetVersion())
return true
end
function WorldStarted()
y = Ground
for x=-40,40
do
for z=-40,40
do
cRoot:Get():GetDefaultWorld():SetBlock(x,y,z,E_BLOCK_WOOL,E_META_WOOL_WHITE)
end
end
end
function HandleRequest_Docker(Request)
content = "[dockerclient]"
if Request.PostParams["action"] ~= nil then
action = Request.PostParams["action"]
if action == "generateGround"
then
WorldStarted()
end
if action == "startContainer"
then
name = Request.PostParams["name"]
imageRepo = Request.PostParams["imageRepo"]
imageTag = Request.PostParams["imageTag"]
id = Request.PostParams["id"]
startContainer(id,name,imageRepo,imageTag)
end
content = content .. "{action:\"" .. action .. "\"}"
else
content = content .. "{error:\"action requested\"}"
end
content = content .. "[/dockerclient]"
return content
end
-- function OnDisable()
-- LOG(PLUGIN:GetName() .. " is shutting down...")
-- end
|
-- local PLUGIN = nil
Ground = 63
DContainer = {displayed = false, x = 0, z = 0, name="",id="",imageRepo="",imageTag=""}
CONTAINER_START_X = 0
CONTAINER_OFFSET_X = -6
CONTAINER_START_Z = 4
Containers = {}
SignsToUpdate = {}
function updateSigns(World)
for i=1,table.getn(SignsToUpdate)
do
sign = SignsToUpdate[i]
LOG("update sign: " .. sign.line1 .. ", " .. sign.line2 .. ", " .. sign.line3 .. ", " .. sign.line4)
cRoot:Get():GetDefaultWorld():SetSignLines(sign.x,sign.y,sign.z,sign.line1,sign.line2,sign.line3,sign.line4)
end
SignsToUpdate = {}
end
function startContainer(id,name,imageRepo,imageTag)
x = 0
for i=0, table.getn(Containers)
do
if Containers[i] == nil
then
container = DContainer
container:init(x,CONTAINER_START_Z)
container:setInfos(id,name,imageRepo,imageTag)
container:display()
Containers[i] = container
return
end
x = x + CONTAINER_OFFSET_X
end
container = DContainer
container:init(x,CONTAINER_START_Z)
container:setInfos(id,name,imageRepo,imageTag)
container:display()
table.insert(Containers, container)
end
function DContainer:init(x,z)
self.x = x
self.z = z
self.displayed = false
end
function DContainer:setInfos(id,name,imageRepo,imageTag)
self.id = id
self.name = name
self.imageRepo = imageRepo
self.imageTag = imageTag
end
function DContainer:display()
if self.displayed == false
then
self.displayed = true
cRoot:Get():GetDefaultWorld():SetBlock(self.x,Ground + 1,self.z - 1,E_BLOCK_SIGN_POST,8)
sign = {}
sign.x = self.x
sign.y = Ground + 1
sign.z = self.z - 1
sign.line1 = self.id
sign.line2 = self.name
sign.line3 = self.imageRepo
sign.line4 = self.imageTag
LOG("schedule update sign: x:" .. tostring(sign.x) .. ", " .. sign.line1 .. ", " .. sign.line2 .. ", " .. sign.line3 .. ", " .. sign.line4)
table.insert(SignsToUpdate,sign)
cRoot:Get():GetDefaultWorld():ScheduleTask(20,updateSigns)
-- function(World)
-- for i=1,table.getn(SignsToUpdate) do
-- local sign = SignsToUpdate[i]
-- LOG("update sign: " .. sign.line1)
-- cRoot:Get():GetDefaultWorld():SetSignLines(self.x,Ground + 1,self.z - 1,sign.line1,sign.line2,sign.line3,sign.line4)
-- end
-- SignsToUpdate = {}
-- end
-- )
for px=self.x, self.x+3
do
for pz=self.z, self.z+4
do
cRoot:Get():GetDefaultWorld():SetBlock(px,Ground + 1,pz,E_BLOCK_WOOL,E_META_WOOL_LIGHTBLUE)
end
end
for py = Ground+2, Ground+3
do
cRoot:Get():GetDefaultWorld():SetBlock(self.x,py,self.z,E_BLOCK_WOOL,E_META_WOOL_LIGHTBLUE)
cRoot:Get():GetDefaultWorld():SetBlock(self.x+3,py,self.z,E_BLOCK_WOOL,E_META_WOOL_LIGHTBLUE)
cRoot:Get():GetDefaultWorld():SetBlock(self.x,py,self.z+1,E_BLOCK_WOOL,E_META_WOOL_BLUE)
cRoot:Get():GetDefaultWorld():SetBlock(self.x+3,py,self.z+1,E_BLOCK_WOOL,E_META_WOOL_BLUE)
cRoot:Get():GetDefaultWorld():SetBlock(self.x,py,self.z+2,E_BLOCK_WOOL,E_META_WOOL_LIGHTBLUE)
cRoot:Get():GetDefaultWorld():SetBlock(self.x+3,py,self.z+2,E_BLOCK_WOOL,E_META_WOOL_LIGHTBLUE)
cRoot:Get():GetDefaultWorld():SetBlock(self.x,py,self.z+3,E_BLOCK_WOOL,E_META_WOOL_BLUE)
cRoot:Get():GetDefaultWorld():SetBlock(self.x+3,py,self.z+3,E_BLOCK_WOOL,E_META_WOOL_BLUE)
cRoot:Get():GetDefaultWorld():SetBlock(self.x,py,self.z+4,E_BLOCK_WOOL,E_META_WOOL_LIGHTBLUE)
cRoot:Get():GetDefaultWorld():SetBlock(self.x+3,py,self.z+4,E_BLOCK_WOOL,E_META_WOOL_LIGHTBLUE)
cRoot:Get():GetDefaultWorld():SetBlock(self.x+1,py,self.z+4,E_BLOCK_WOOL,E_META_WOOL_LIGHTBLUE)
cRoot:Get():GetDefaultWorld():SetBlock(self.x+2,py,self.z+4,E_BLOCK_WOOL,E_META_WOOL_LIGHTBLUE)
end
for px=self.x, self.x+3
do
for pz=self.z, self.z+4
do
cRoot:Get():GetDefaultWorld():SetBlock(px,Ground + 4,pz,E_BLOCK_WOOL,E_META_WOOL_LIGHTBLUE)
end
end
end
end
function Initialize(Plugin)
Plugin:SetName("Docker")
Plugin:SetVersion(1)
-- Hooks
cPluginManager:AddHook(cPluginManager.HOOK_WORLD_STARTED, WorldStarted);
-- PLUGIN = Plugin -- NOTE: only needed if you want OnDisable() to use GetName() or something like that
-- Command Bindings
Plugin:AddWebTab("Docker",HandleRequest_Docker)
LOG("Initialised " .. Plugin:GetName() .. " v." .. Plugin:GetVersion())
return true
end
function WorldStarted()
y = Ground
for x=-40,40
do
for z=-40,40
do
cRoot:Get():GetDefaultWorld():SetBlock(x,y,z,E_BLOCK_WOOL,E_META_WOOL_WHITE)
end
end
end
function HandleRequest_Docker(Request)
content = "[dockerclient]"
if Request.PostParams["action"] ~= nil then
action = Request.PostParams["action"]
if action == "generateGround"
then
WorldStarted()
end
if action == "startContainer"
then
name = Request.PostParams["name"]
imageRepo = Request.PostParams["imageRepo"]
imageTag = Request.PostParams["imageTag"]
id = Request.PostParams["id"]
startContainer(id,name,imageRepo,imageTag)
end
content = content .. "{action:\"" .. action .. "\"}"
else
content = content .. "{error:\"action requested\"}"
end
content = content .. "[/dockerclient]"
return content
end
-- function OnDisable()
-- LOG(PLUGIN:GetName() .. " is shutting down...")
-- end
|
Fixed signs update
|
Fixed signs update
|
Lua
|
apache-2.0
|
stevesloka/kubecraft,johnmccabe/dockercraft,nyasukun/openstackcraft,gdevillele/dockercraft,docker/dockercraft,nyasukun/openstackcraft,johnmccabe/dockercraft,johnmccabe/dockercraft,nyasukun/openstackcraft,stevesloka/kubecraft,gdevillele/dockercraft,stevesloka/kubecraft,gdevillele/dockercraft,docker/dockercraft
|
9b09c2c39bf7f67cfbd57b3068d9c75a411129f8
|
mod_storage_gdbm/mod_storage_gdbm.lua
|
mod_storage_gdbm/mod_storage_gdbm.lua
|
-- mod_storage_gdbm
-- Copyright (C) 2014 Kim Alvefur
--
-- This file is MIT/X11 licensed.
--
-- Depends on lgdbm:
-- http://webserver2.tecgraf.puc-rio.br/~lhf/ftp/lua/#lgdbm
local gdbm = require"gdbm";
local path = require"util.paths";
local lfs = require"lfs";
local uuid = require"util.uuid".generate;
local serialization = require"util.serialization";
local st = require"util.stanza";
local serialize = serialization.serialize;
local deserialize = serialization.deserialize;
local function id(v) return v; end
local function is_stanza(s)
return getmetatable(s) == st.stanza_mt;
end
local function ifelse(cond, iftrue, iffalse)
if cond then return iftrue; end return iffalse;
end
local base_path = path.resolve_relative_path(prosody.paths.data, module.host);
lfs.mkdir(base_path);
local cache = {};
local keyval = {};
local keyval_mt = { __index = keyval, suffix = ".db" };
function keyval:set(user, value)
local ok, err = gdbm.replace(self._db, user or "@", serialize(value));
if not ok then return nil, err; end
return true;
end
function keyval:get(user)
local data, err = gdbm.fetch(self._db, user or "@");
if not data then return nil, err; end
return deserialize(data);
end
local archive = {};
local archive_mt = { __index = archive, suffix = ".adb" };
archive.get = keyval.get;
archive.set = keyval.set;
function archive:append(username, key, when, with, value)
key = key or uuid();
local meta = self:get(username);
if not meta then
meta = {};
end
local i = meta[key] or #meta+1;
local type;
if is_stanza(value) then
type, value = "stanza", st.preserialize(value);
end
meta[i] = { key = key, when = when, with = with, type = type };
meta[key] = i;
local ok, err = self:set(username, meta);
if not ok then return nil, err; end
ok, err = self:set(key, value);
if not ok then return nil, err; end
return key;
end
local deserialize = {
stanza = st.deserialize;
};
function archive:find(username, query)
local meta = self:get(username);
local r = query.reverse;
local d = r and -1 or 1;
local s = meta[ifelse(r, query.before, query.after)];
local limit = query.limit;
if s then
s = s + d;
else
s = ifelse(r, #meta, 1)
end
local e = ifelse(r, 1, #meta);
local c = 0;
return function ()
if limit and c >= limit then return end
local item, value;
for i = s, e, d do
item = meta[i];
if (not query.with or item.with == query.with)
and (not query.start or item.when >= query.start)
and (not query["end"] or item.when <= query["end"]) then
s = i + d; c = c + 1;
value = self:get(item.key);
return item.key, (deserialize[item.type] or id)(value), item.when, item.with;
end
end
end
end
local drivers = {
keyval = keyval_mt;
archive = archive_mt;
}
function open(_, store, typ)
typ = typ or "keyval";
local driver_mt = drivers[typ];
if not driver_mt then
return nil, "unsupported-store";
end
local db_path = path.join(base_path, store) .. driver_mt.suffix;
local db = cache[db_path];
if not db then
db = assert(gdbm.open(db_path, "c"));
cache[db_path] = db;
end
return setmetatable({ _db = db; _path = db_path; store = store, typ = type }, driver_mt);
end
function module.unload()
for path, db in pairs(cache) do
gdbm.sync(db);
gdbm.close(db);
end
end
module:provides"storage";
|
-- mod_storage_gdbm
-- Copyright (C) 2014 Kim Alvefur
--
-- This file is MIT/X11 licensed.
--
-- Depends on lgdbm:
-- http://webserver2.tecgraf.puc-rio.br/~lhf/ftp/lua/#lgdbm
local gdbm = require"gdbm";
local path = require"util.paths";
local lfs = require"lfs";
local uuid = require"util.uuid".generate;
local serialization = require"util.serialization";
local st = require"util.stanza";
local serialize = serialization.serialize;
local deserialize = serialization.deserialize;
local empty = {};
local function id(v) return v; end
local function is_stanza(s)
return getmetatable(s) == st.stanza_mt;
end
local function ifelse(cond, iftrue, iffalse)
if cond then return iftrue; end return iffalse;
end
local base_path = path.resolve_relative_path(prosody.paths.data, module.host);
lfs.mkdir(base_path);
local cache = {};
local keyval = {};
local keyval_mt = { __index = keyval, suffix = ".db" };
function keyval:set(user, value)
local ok, err = gdbm.replace(self._db, user or "@", serialize(value));
if not ok then return nil, err; end
return true;
end
function keyval:get(user)
local data, err = gdbm.fetch(self._db, user or "@");
if not data then return nil, err; end
return deserialize(data);
end
local archive = {};
local archive_mt = { __index = archive, suffix = ".adb" };
archive.get = keyval.get;
archive.set = keyval.set;
function archive:append(username, key, when, with, value)
key = key or uuid();
local meta = self:get(username);
if not meta then
meta = {};
end
local i = meta[key] or #meta+1;
local type;
if is_stanza(value) then
type, value = "stanza", st.preserialize(value);
end
meta[i] = { key = key, when = when, with = with, type = type };
meta[key] = i;
local ok, err = self:set(username, meta);
if not ok then return nil, err; end
ok, err = self:set(key, value);
if not ok then return nil, err; end
return key;
end
local deserialize = {
stanza = st.deserialize;
};
function archive:find(username, query)
query = query or empty_query;
local meta = self:get(username) or empty;
local r = query.reverse;
local d = r and -1 or 1;
local s = meta[ifelse(r, query.before, query.after)];
local limit = query.limit;
if s then
s = s + d;
else
s = ifelse(r, #meta, 1)
end
local e = ifelse(r, 1, #meta);
local c = 0;
return function ()
if limit and c >= limit then return end
local item, value;
for i = s, e, d do
item = meta[i];
if (not query.with or item.with == query.with)
and (not query.start or item.when >= query.start)
and (not query["end"] or item.when <= query["end"]) then
s = i + d; c = c + 1;
value = self:get(item.key);
return item.key, (deserialize[item.type] or id)(value), item.when, item.with;
end
end
end
end
local drivers = {
keyval = keyval_mt;
archive = archive_mt;
}
function open(_, store, typ)
typ = typ or "keyval";
local driver_mt = drivers[typ];
if not driver_mt then
return nil, "unsupported-store";
end
local db_path = path.join(base_path, store) .. driver_mt.suffix;
local db = cache[db_path];
if not db then
db = assert(gdbm.open(db_path, "c"));
cache[db_path] = db;
end
return setmetatable({ _db = db; _path = db_path; store = store, typ = type }, driver_mt);
end
function module.unload()
for path, db in pairs(cache) do
gdbm.sync(db);
gdbm.close(db);
end
end
module:provides"storage";
|
mod_storage_gdbm: Fix traceback if query is nil or no metadata exists
|
mod_storage_gdbm: Fix traceback if query is nil or no metadata exists
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
9e711e51488636636a601b09ac3ad8953877a779
|
fusion/stdlib/functional.lua
|
fusion/stdlib/functional.lua
|
--- Module for "functional" iterators and functions.
-- @module fusion.stdlib.functional
local unpack = unpack or table.unpack -- luacheck: ignore 113
--- Return an iterator over a value if possible or the value passed.
-- Possible value types can be strings and any object with __pairs or __ipairs
-- metadata.
-- @tparam table input Table to iterate over (can also be iterator function)
-- @tparam function iterator Table iterator to use (`pairs()` by default)
-- @treturn function
local function iter(input, iterator)
if type(input) == "function" then
return input
elseif type(input) == "string" then
return input:gmatch(".")
else
if not iterator then
return iter(input, pairs)
end
return iterator(input)
end
end
--- Make an iterator (or 'generator') from a function.
-- @tparam function fn
-- @treturn function Wrapped coroutine
local function mk_gen(fn)
return function(...)
local a = {...}
return coroutine.wrap(function()
return fn(unpack(a))
end)
end
end
--- Apply a function to one or more input streams, and return the values.
-- @function map
-- @tparam function fn
-- @tparam iter input
-- @treturn iter Initialized iterator
-- @usage print(x in map(((v)-> v ^ 2), 1::10)); -- squares
local function map(fn, input, ...)
local _args = {...}
for i, v in ipairs(_args) do
_args[i] = iter(v)
end
for k, v in iter(input) do
local t0 = {}
for i, _v in ipairs(_args) do -- luacheck: ignore 213
table.insert(t0, _v())
end
input[k] = fn(v, unpack(t0))
coroutine.yield(k, fn(v, unpack(t0)))
end
end
--- Return values in an input stream if an applied function returns true.
-- @function filter
-- @tparam function fn
-- @tparam iter input Iterable object
-- @treturn iter Initialized iterator
-- @usage print(x in filter(((v)-> v % 2 == 0), 1::10)); -- odds
local function filter(fn, input)
for k, v in iter(input) do -- luacheck: ignore 213
if fn(k, v) then
coroutine.yield(k, v)
end
end
end
--- Return a value from a function applied to all values of an input stream.
-- @function reduce
-- @tparam function fn
-- @tparam iter input Iterable object
-- @param init Initial value (will use first value of stream if not supplied)
-- @usage print(reduce(((x, y)-> x > y), {5, 2, 7, 9, 1})); -- math.max()
local function reduce(fn, input, init)
for k, v in iter(input) do -- luacheck: ignore 213
if init == nil then
init = v
else
init = assert(fn(init, v))
end
end
return init
end
--- Does the same thing as `reduce`, but operates on ordered sequences.
-- This function should only be used on numeric tables or indexable streams.
-- Use `foldl()` or `foldr()` for convenience instead of this function unless
-- you need control over the exact sequence.
-- @function fold
-- @tparam number start
-- @tparam number stop
-- @tparam number step
-- @tparam function fn
-- @param input Numerically indexable object
-- @param init Initial value (will use first value in input if not supplied)
-- @see reduce
local function fold(start, stop, step, fn, input, init)
for i=start, stop, step do
if not init then
init = input[i]
else
init = assert(fn(init, input[i]))
end
end
return init
end
--- Fold starting from the first value of input to the last value of input.
-- @function foldl
-- @tparam function fn
-- @param input Numerically indexable object
-- @param init Initial value (will use first value in input if not supplied)
-- @see fold, foldr, reduce
local function foldl(fn, input, init)
return fold(1, #input, 1, fn, input, init)
end
--- Fold starting from the last value of input to the first value of input.
-- @function foldr
-- @tparam function fn
-- @param input Numerically indexable object
-- @param init Initial value (will use last value in input if not supplied)
-- @see fold, foldl, reduce
local function foldr(fn, input, init)
return fold(#input, 1, -1, fn, input, init)
end
--- Return the boolean form of a value. False and nil return false, otherwise
-- true is returned.
-- @param val Value to convert to boolean value (optionally nil)
-- @treturn boolean
local function truthy(val)
return not not val
end
--- Return true if any returned value from an input stream are truthy,
-- otherwise false.
-- @function any
-- @tparam function fn
-- @tparam iter input
-- @treturn boolean
-- @usage print(any({nil, true, false})); -- true
local function any(fn, input)
if not fn or not input then
return any(input, truthy)
end
for k, v in iter(input) do -- luacheck: ignore 213
if v and fn(v) or fn(k) then
return true
end
end
return false
end
--- Return true if all returned values from an input stream are truthy.
-- @function all
-- @tparam function fn
-- @tparam iter input
-- @treturn boolean
-- @usage print(all(chain(1::50, {false}))); -- false
local function all(fn, input)
if not fn then
return all(input, truthy)
end
for k, v in pairs(input) do -- luacheck: ignore 213
if not fn(v) then
return false
end
end
return true
end
--- Return a sum of all values in a stream.
-- @function sum
-- @tparam iter input
-- @tparam boolean negative optional; returns a difference instead if true
-- @treturn number
-- @usage print(sum(1::50));
local function sum(input, negative)
if negative then
return reduce(function(a, b) return a + b end, input)
else
return reduce(function(a, b) return a - b end, input)
end
end
return {
_iter = iter;
_mk_gen = mk_gen;
all = all;
any = any;
filter = mk_gen(filter);
foldl = foldl;
foldr = foldr;
map = mk_gen(map);
reduce = reduce;
sum = sum;
}
|
--- Module for "functional" iterators and functions.
-- @module fusion.stdlib.functional
local unpack = unpack or table.unpack -- luacheck: ignore 113
--- Return an iterator over a value if possible or the value passed.
-- Possible value types can be strings and any object with __pairs or __ipairs
-- metadata.
-- @tparam table input Table to iterate over (can also be iterator function)
-- @tparam function iterator Table iterator to use (`pairs()` by default)
-- @treturn function
local function iter(input, iterator)
if type(input) == "function" then
return input
elseif type(input) == "string" then
return input:gmatch(".")
else
if not iterator then
return iter(input, pairs)
end
return iterator(input)
end
end
--- Make an iterator (or 'generator') from a function.
-- @tparam function fn
-- @treturn function Wrapped coroutine
local function mk_gen(fn)
return function(...)
local a = {...}
return coroutine.wrap(function()
return fn(unpack(a))
end)
end
end
--- Apply a function to one or more input streams, and return the values.
-- @function map
-- @tparam function fn
-- @tparam iter input
-- @treturn iter Initialized iterator
-- @usage print(x in map(((v)-> v ^ 2), 1::10)); -- squares
local function map(fn, input, ...)
local _args = {...}
for i, v in ipairs(_args) do
_args[i] = iter(v)
end
for k, v in iter(input) do
local t0 = {}
for i, _v in ipairs(_args) do -- luacheck: ignore 213
table.insert(t0, _v())
end
input[k] = fn(v, unpack(t0))
coroutine.yield(k, fn(v, unpack(t0)))
end
end
--- Return values in an input stream if an applied function returns true.
-- @function filter
-- @tparam function fn
-- @tparam iter input Iterable object
-- @treturn iter Initialized iterator
-- @usage print(x in filter(((v)-> v % 2 == 0), 1::10)); -- odds
local function filter(fn, input)
for k, v in iter(input) do -- luacheck: ignore 213
if fn(k, v) then
coroutine.yield(k, v)
end
end
end
--- Return a value from a function applied to all values of an input stream.
-- @function reduce
-- @tparam function fn
-- @tparam iter input Iterable object
-- @param init Initial value (will use first value of stream if not supplied)
-- @usage print(reduce(((x, y)-> x > y), {5, 2, 7, 9, 1})); -- math.max()
local function reduce(fn, input, init)
for k, v in iter(input) do -- luacheck: ignore 213
if init == nil then
init = v
else
init = assert(fn(init, v))
end
end
return init
end
--- Does the same thing as `reduce`, but operates on ordered sequences.
-- This function should only be used on numeric tables or indexable streams.
-- Use `foldl()` or `foldr()` for convenience instead of this function unless
-- you need control over the exact sequence.
-- @function fold
-- @tparam number start
-- @tparam number stop
-- @tparam number step
-- @tparam function fn
-- @param input Numerically indexable object
-- @param init Initial value (will use first value in input if not supplied)
-- @see reduce
local function fold(start, stop, step, fn, input, init)
for i=start, stop, step do
if not init then
init = input[i]
else
init = assert(fn(init, input[i]))
end
end
return init
end
--- Fold starting from the first value of input to the last value of input.
-- @function foldl
-- @tparam function fn
-- @param input Numerically indexable object
-- @param init Initial value (will use first value in input if not supplied)
-- @see fold, foldr, reduce
local function foldl(fn, input, init)
return fold(1, #input, 1, fn, input, init)
end
--- Fold starting from the last value of input to the first value of input.
-- @function foldr
-- @tparam function fn
-- @param input Numerically indexable object
-- @param init Initial value (will use last value in input if not supplied)
-- @see fold, foldl, reduce
local function foldr(fn, input, init)
return fold(#input, 1, -1, fn, input, init)
end
--- Return the boolean form of a value. False and nil return false, otherwise
-- true is returned.
-- @param val Value to convert to boolean value (optionally nil)
-- @treturn boolean
local function truthy(val)
return not not val
end
--- Return true if any returned value from an input stream are truthy,
-- otherwise false.
-- @function any
-- @tparam function fn
-- @tparam iter input
-- @treturn boolean
-- @usage print(any({nil, true, false})); -- true
local function any(fn, input)
if not fn or not input then
return any(truthy, fn or input)
end
for k, v in iter(input) do -- luacheck: ignore 213
if v ~= nil and fn(v) then
return true
elseif v == nil and fn(k) then
return true
end
end
return false
end
--- Return true if all returned values from an input stream are truthy.
-- @function all
-- @tparam function fn
-- @tparam iter input
-- @treturn boolean
-- @usage print(all(chain(1::50, {false}))); -- false
local function all(fn, input)
if not fn or not input then
return all(truthy, fn or input)
end
for k, v in iter(input) do -- luacheck: ignore 213
if v ~= nil and not fn(v) then
return false
elseif v == nil and not fn(k) then
return false
end
end
return true
end
--- Return a sum of all values in a stream.
-- @function sum
-- @tparam iter input
-- @tparam boolean negative optional; returns a difference instead if true
-- @treturn number
-- @usage print(sum(1::50));
local function sum(input, negative)
if negative then
return reduce(function(a, b) return a - b end, input)
else
return reduce(function(a, b) return a + b end, input)
end
end
return {
_iter = iter;
_mk_gen = mk_gen;
all = all;
any = any;
filter = mk_gen(filter);
foldl = foldl;
foldr = foldr;
map = mk_gen(map);
reduce = reduce;
sum = sum;
}
|
functional: fix logic error with sum(), any(), and all()
|
functional: fix logic error with sum(), any(), and all()
|
Lua
|
mit
|
RyanSquared/FusionScript
|
4c6a891c04c3bab5deac158869e76b17651bfe6c
|
mod_register_url/mod_register_url.lua
|
mod_register_url/mod_register_url.lua
|
-- Registration Redirect module for Prosody
--
-- Redirects IP addresses not in the whitelist to a web page to complete the registration.
local st = require "util.stanza";
function reg_redirect(event)
local ip_wl = module:get_option("registration_whitelist") or { "127.0.0.1" };
local url = module:get_option("registration_url");
local no_wl = module:get_option("no_registration_whitelist") or false;
if type(no_wl) ~= boolean then no_wl = false end
local test_ip = false;
if not no_wl then
for i,ip in ipairs(ip_wl) do
if event.origin.ip == ip then test_ip = true; end
break;
end
end
if not test_ip and url ~= nil or no_wl and url ~= nil then
local reply = st.reply(event.stanza);
reply:tag("query", {xmlns = "jabber:iq:register"})
:tag("instructions"):text("Please visit "..url.." to register an account on this server."):up()
:tag("x", {xmlns = "jabber:x:oob"}):up()
:tag("url"):text(url):up();
event.origin.send(reply);
return true;
end
end
module:hook("stanza/iq/jabber:iq:register:query", reg_redirect, 10);
|
-- Registration Redirect module for Prosody
--
-- Redirects IP addresses not in the whitelist to a web page to complete the registration.
local st = require "util.stanza";
function reg_redirect(event)
local ip_wl = module:get_option("registration_whitelist") or { "127.0.0.1" };
local url = module:get_option("registration_url");
local no_wl = module:get_option_boolean("no_registration_whitelist", false);
local test_ip = false;
if not no_wl then
for i,ip in ipairs(ip_wl) do
if event.origin.ip == ip then test_ip = true; end
break;
end
end
if not test_ip and url ~= nil or no_wl and url ~= nil then
local reply = st.reply(event.stanza);
reply:tag("query", {xmlns = "jabber:iq:register"})
:tag("instructions"):text("Please visit "..url.." to register an account on this server."):up()
:tag("x", {xmlns = "jabber:x:oob"}):up()
:tag("url"):text(url):up();
event.origin.send(reply);
return true;
end
end
module:hook("stanza/iq/jabber:iq:register:query", reg_redirect, 10);
|
mod_register_url: minor fix.
|
mod_register_url: minor fix.
|
Lua
|
mit
|
prosody-modules/import,drdownload/prosody-modules,softer/prosody-modules,iamliqiang/prosody-modules,mmusial/prosody-modules,olax/prosody-modules,NSAKEY/prosody-modules,syntafin/prosody-modules,NSAKEY/prosody-modules,olax/prosody-modules,amenophis1er/prosody-modules,vince06fr/prosody-modules,drdownload/prosody-modules,either1/prosody-modules,joewalker/prosody-modules,dhotson/prosody-modules,Craige/prosody-modules,vince06fr/prosody-modules,prosody-modules/import,NSAKEY/prosody-modules,BurmistrovJ/prosody-modules,1st8/prosody-modules,cryptotoad/prosody-modules,drdownload/prosody-modules,mmusial/prosody-modules,mardraze/prosody-modules,stephen322/prosody-modules,mardraze/prosody-modules,syntafin/prosody-modules,brahmi2/prosody-modules,BurmistrovJ/prosody-modules,mardraze/prosody-modules,BurmistrovJ/prosody-modules,olax/prosody-modules,mmusial/prosody-modules,jkprg/prosody-modules,obelisk21/prosody-modules,apung/prosody-modules,obelisk21/prosody-modules,jkprg/prosody-modules,LanceJenkinZA/prosody-modules,drdownload/prosody-modules,brahmi2/prosody-modules,mardraze/prosody-modules,asdofindia/prosody-modules,jkprg/prosody-modules,LanceJenkinZA/prosody-modules,cryptotoad/prosody-modules,asdofindia/prosody-modules,asdofindia/prosody-modules,obelisk21/prosody-modules,apung/prosody-modules,joewalker/prosody-modules,BurmistrovJ/prosody-modules,dhotson/prosody-modules,Craige/prosody-modules,1st8/prosody-modules,asdofindia/prosody-modules,heysion/prosody-modules,softer/prosody-modules,heysion/prosody-modules,apung/prosody-modules,obelisk21/prosody-modules,drdownload/prosody-modules,guilhem/prosody-modules,olax/prosody-modules,prosody-modules/import,heysion/prosody-modules,softer/prosody-modules,amenophis1er/prosody-modules,brahmi2/prosody-modules,apung/prosody-modules,BurmistrovJ/prosody-modules,NSAKEY/prosody-modules,apung/prosody-modules,joewalker/prosody-modules,Craige/prosody-modules,amenophis1er/prosody-modules,stephen322/prosody-modules,mmusial/prosody-modules,either1/prosody-modules,vfedoroff/prosody-modules,iamliqiang/prosody-modules,softer/prosody-modules,cryptotoad/prosody-modules,1st8/prosody-modules,mmusial/prosody-modules,vince06fr/prosody-modules,vince06fr/prosody-modules,iamliqiang/prosody-modules,crunchuser/prosody-modules,jkprg/prosody-modules,vince06fr/prosody-modules,vfedoroff/prosody-modules,Craige/prosody-modules,dhotson/prosody-modules,vfedoroff/prosody-modules,vfedoroff/prosody-modules,dhotson/prosody-modules,LanceJenkinZA/prosody-modules,heysion/prosody-modules,NSAKEY/prosody-modules,guilhem/prosody-modules,mardraze/prosody-modules,syntafin/prosody-modules,amenophis1er/prosody-modules,jkprg/prosody-modules,1st8/prosody-modules,stephen322/prosody-modules,Craige/prosody-modules,softer/prosody-modules,prosody-modules/import,either1/prosody-modules,asdofindia/prosody-modules,syntafin/prosody-modules,either1/prosody-modules,guilhem/prosody-modules,syntafin/prosody-modules,brahmi2/prosody-modules,stephen322/prosody-modules,brahmi2/prosody-modules,guilhem/prosody-modules,crunchuser/prosody-modules,1st8/prosody-modules,prosody-modules/import,guilhem/prosody-modules,crunchuser/prosody-modules,amenophis1er/prosody-modules,crunchuser/prosody-modules,iamliqiang/prosody-modules,heysion/prosody-modules,joewalker/prosody-modules,vfedoroff/prosody-modules,cryptotoad/prosody-modules,stephen322/prosody-modules,crunchuser/prosody-modules,olax/prosody-modules,cryptotoad/prosody-modules,LanceJenkinZA/prosody-modules,joewalker/prosody-modules,iamliqiang/prosody-modules,obelisk21/prosody-modules,dhotson/prosody-modules,either1/prosody-modules,LanceJenkinZA/prosody-modules
|
703465cb6ad521389b8c64052bcf24f45ec92aec
|
states/game.lua
|
states/game.lua
|
local Scene = require 'entities.scene'
local Dynamo = require 'entities.scenes.dynamo'
local Sprite = require 'entities.sprite'
local Bit = require 'bit'
local game = {}
function game:init()
self.dynamo = Dynamo:new()
self.scene = Scene:new()
self.catalogs = {
art = require 'catalogs.art',
}
self.isoSprite = love.graphics.newImage(self.catalogs.art.iso_tile)
self.shipBitmask = love.image.newImageData(self.catalogs.art.ship_bitmask)
-- Map (r, g, b) -> unique int
local function getColorHash(r, g, b)
return Bit.bor(Bit.lshift(r, 32), Bit.lshift(g, 16), b)
end
self.grid = {}
self.rooms = {}
self.enemies = {}
for x = 1, self.shipBitmask:getWidth() do
self.grid[x] = {}
self.rooms[x] = {}
self.enemies[x] = {}
for y = 1, self.shipBitmask:getHeight() do
local r, g, b, a = self.shipBitmask:getPixel(x - 1, y - 1)
self.grid[x][y] = 0
self.rooms[x][y] = 0
self.enemies[x][y] = 0
if not (r == 0 and g == 0 and b == 0 and a == 0) then
self.grid[x][y] = 1
self.rooms[x][y] = getColorHash(r, g, b)
end
end
end
self.gridX = love.graphics.getWidth()/2
self.gridY = love.graphics.getHeight()/2
self.gridWidth = #self.grid[1] -- tiles
self.gridHeight = #self.grid -- tiles
self.tileWidth = self.isoSprite:getWidth() -- pixels
self.tileHeight = self.isoSprite:getHeight() -- pixels
self.tileDepth = self.tileHeight / 2
self.scene:add{
hoverX = nil,
hoverY = nil,
update = function(self, dt)
local mx, my = love.mouse.getPosition()
local gx, gy, gw, gh = game:getGridBoundingBox()
local translatedX = gx - game.gridX + gw/2
local translatedY = gy - game.gridY + gh/2
mx = -translatedX - mx
my = -translatedY - my
mx = mx + game.tileWidth / 2
my = my + game.tileHeight
self.hoverX, self.hoverY = game:screenToGrid(-mx, -my)
end,
mousepressed = function(self, mx, my)
if game.enemies[self.hoverX] and game.enemies[self.hoverX][self.hoverY] then
game.enemies[self.hoverX][self.hoverY] = 0
end
end,
draw = function(self)
love.graphics.print(self.hoverX .. ', ' .. self.hoverY, 10, 10)
love.graphics.push()
local gx, gy, gw, gh = game:getGridBoundingBox()
local translatedX = gx - game.gridX + gw/2
local translatedY = gy - game.gridY + gh/2
love.graphics.translate(-translatedX, -translatedY)
for x = 1, game.gridWidth do
for y = 1, game.gridHeight do
local roomNumber = game.rooms[x][y]
if x == self.hoverX and y == self.hoverY then
love.graphics.setColor(255, 0, 0)
elseif game.enemies[x][y] > 0 then
love.graphics.setColor(0, 255, 0)
elseif roomNumber > 0 then
love.graphics.setColor(255, 128, 255)
else
love.graphics.setColor(255, 255, 255)
end
tx, ty = game:gridToScreen(x, y)
local cellValue = game.grid[x][y]
if cellValue == 1 then
love.graphics.draw(game.isoSprite, tx, ty)
end
end
end
-- Grid bounding box
love.graphics.rectangle('line', gx, gy, gw, gh)
love.graphics.pop()
end,
}
-- Every so often add a new enemy
Timer.every(1, function()
local ex, ey
local enemy
local notAnEmptySpace
-- Locate empty square
repeat
ex = love.math.random(self.gridWidth)
ey = love.math.random(self.gridHeight)
enemy = self.enemies[ex][ey]
notAnEmptySpace = self.grid[ex][ey] > 0
until (enemy == 0 and notAnEmptySpace)
self.enemies[ex][ey] = 1
end)
end
function game:enter()
end
function game:update(dt)
self.scene:update(dt)
self.dynamo:update(dt)
end
function game:keypressed(key, code)
self.scene:keypressed(key, code)
self.dynamo:keypressed(key, code)
end
function game:keyreleased(key, code)
self.scene:keyreleased(key, code)
self.dynamo:keyreleased(key, code)
end
function game:mousepressed(x, y, mbutton)
self.scene:mousepressed(x, y, mbutton)
self.dynamo:mousepressed(x, y, mbutton)
end
function game:mousereleased(x, y, mbutton)
self.scene:mousereleased(x, y, mbutton)
self.dynamo:mousereleased(x, y, mbutton)
end
function game:mousemoved(x, y, dx, dy, istouch)
self.scene:mousemoved(x, y, dx, dy, istouch)
self.dynamo:mousemoved(x, y, dx, dy, istouch)
end
function game:draw()
self.scene:draw()
self.dynamo:draw()
end
function game:screenToGrid(sx, sy)
local gx = ((sx / (self.tileWidth / 2)) + (sy / (self.tileDepth / 2))) / 2 + 1
local gy = ((sy / (self.tileDepth / 2)) - (sx / (self.tileWidth / 2))) / 2 + 1
return Lume.round(gx), Lume.round(gy)
end
function game:gridToScreen(gx, gy)
local x = (gx - gy) * game.tileWidth / 2
local y = (gx + gy) * game.tileDepth / 2
return x, y
end
function game:getGridBoundingBox()
local xFudge = 0
local yFudge = 4
local w = self.gridWidth * self.tileWidth + xFudge
local h = self.gridHeight * self.tileDepth + yFudge
local x = -w/2 + self.tileWidth/2 - xFudge * 2
local y = self.tileHeight - yFudge * 2
return x, y, w, h
end
return game
|
local Scene = require 'entities.scene'
local Dynamo = require 'entities.scenes.dynamo'
local Sprite = require 'entities.sprite'
local Bit = require 'bit'
local game = {}
function game:init()
self.dynamo = Dynamo:new()
self.scene = Scene:new()
self.catalogs = {
art = require 'catalogs.art',
}
self.isoSprite = love.graphics.newImage(self.catalogs.art.iso_tile)
self.shipBitmask = love.image.newImageData(self.catalogs.art.ship_bitmask)
-- Map (r, g, b) -> unique int
local function getColorHash(r, g, b)
return Bit.bor(Bit.lshift(r, 32), Bit.lshift(g, 16), b)
end
self.grid = {}
self.rooms = {}
self.enemies = {}
for x = 1, self.shipBitmask:getWidth() do
self.grid[x] = {}
self.rooms[x] = {}
self.enemies[x] = {}
for y = 1, self.shipBitmask:getHeight() do
local r, g, b, a = self.shipBitmask:getPixel(x - 1, y - 1)
self.grid[x][y] = 0
self.rooms[x][y] = 0
self.enemies[x][y] = 0
if not (r == 0 and g == 0 and b == 0 and a == 0) then
self.grid[x][y] = 1
self.rooms[x][y] = getColorHash(r, g, b)
end
end
end
self.gridX = love.graphics.getWidth()/2
self.gridY = love.graphics.getHeight()/2
self.gridWidth = #self.grid[1] -- tiles
self.gridHeight = #self.grid -- tiles
self.tileWidth = self.isoSprite:getWidth() -- pixels
self.tileHeight = self.isoSprite:getHeight() -- pixels
self.tileDepth = self.tileHeight / 2
self.scene:add{
hoverX = nil,
hoverY = nil,
update = function(self, dt)
local mx, my = love.mouse.getPosition()
local gx, gy, gw, gh = game:getGridBoundingBox()
local translatedX = gx - game.gridX + gw/2
local translatedY = gy - game.gridY + gh/2
mx = -translatedX - mx
my = -translatedY - my
mx = mx + game.tileWidth / 2
my = my + game.tileHeight
self.hoverX, self.hoverY = game:screenToGrid(-mx, -my)
end,
mousepressed = function(self, mx, my)
if game.enemies[self.hoverX] and game.enemies[self.hoverX][self.hoverY] then
game.enemies[self.hoverX][self.hoverY] = 0
end
end,
draw = function(self)
love.graphics.print(self.hoverX .. ', ' .. self.hoverY, 10, 10)
love.graphics.push()
local gx, gy, gw, gh = game:getGridBoundingBox()
local translatedX = gx - game.gridX + gw/2
local translatedY = gy - game.gridY + gh/2
love.graphics.translate(-translatedX, -translatedY)
for x = 1, game.gridWidth do
for y = 1, game.gridHeight do
local roomNumber = game.rooms[x][y]
if x == self.hoverX and y == self.hoverY then
love.graphics.setColor(255, 0, 0)
elseif game.enemies[x][y] > 0 then
love.graphics.setColor(0, 255, 0)
elseif roomNumber > 0 then
love.graphics.setColor(255, 128, 255)
else
love.graphics.setColor(255, 255, 255)
end
tx, ty = game:gridToScreen(x, y)
local cellValue = game.grid[x][y]
if cellValue == 1 then
love.graphics.draw(game.isoSprite, tx, ty)
end
end
end
-- Grid bounding box
love.graphics.rectangle('line', gx, gy, gw, gh)
love.graphics.pop()
end,
}
-- Every so often add a new enemy
Timer.every(1, function()
local ex, ey
local enemy
local notAnEmptySpace
local tries = 0
local maxTries = 25
-- Locate empty square
repeat
tries = tries + 1
ex = love.math.random(self.gridWidth)
ey = love.math.random(self.gridHeight)
enemy = self.enemies[ex][ey]
notAnEmptySpace = self.grid[ex][ey] > 0
until ((enemy == 0 and notAnEmptySpace) or tries >= maxTries)
self.enemies[ex][ey] = 1
end)
end
function game:enter()
end
function game:update(dt)
self.scene:update(dt)
self.dynamo:update(dt)
end
function game:keypressed(key, code)
self.scene:keypressed(key, code)
self.dynamo:keypressed(key, code)
end
function game:keyreleased(key, code)
self.scene:keyreleased(key, code)
self.dynamo:keyreleased(key, code)
end
function game:mousepressed(x, y, mbutton)
self.scene:mousepressed(x, y, mbutton)
self.dynamo:mousepressed(x, y, mbutton)
end
function game:mousereleased(x, y, mbutton)
self.scene:mousereleased(x, y, mbutton)
self.dynamo:mousereleased(x, y, mbutton)
end
function game:mousemoved(x, y, dx, dy, istouch)
self.scene:mousemoved(x, y, dx, dy, istouch)
self.dynamo:mousemoved(x, y, dx, dy, istouch)
end
function game:draw()
self.scene:draw()
self.dynamo:draw()
end
function game:screenToGrid(sx, sy)
local gx = ((sx / (self.tileWidth / 2)) + (sy / (self.tileDepth / 2))) / 2 + 1
local gy = ((sy / (self.tileDepth / 2)) - (sx / (self.tileWidth / 2))) / 2 + 1
return Lume.round(gx), Lume.round(gy)
end
function game:gridToScreen(gx, gy)
local x = (gx - gy) * game.tileWidth / 2
local y = (gx + gy) * game.tileDepth / 2
return x, y
end
function game:getGridBoundingBox()
local xFudge = 0
local yFudge = 4
local w = self.gridWidth * self.tileWidth + xFudge
local h = self.gridHeight * self.tileDepth + yFudge
local x = -w/2 + self.tileWidth/2 - xFudge * 2
local y = self.tileHeight - yFudge * 2
return x, y, w, h
end
return game
|
Fix game freeze when ship is filled
|
Fix game freeze when ship is filled
|
Lua
|
mit
|
Nuthen/ludum-dare-39
|
136a73e503dfc92c2d9dc350854708b02ff88548
|
test/integration/integration_spec.lua
|
test/integration/integration_spec.lua
|
describe('integration', function()
local port = '7070'
local url = 'http://localhost:' .. port
local executeCommand = function(command)
local handle = io.popen(command .. ' -s ' .. url)
local result = handle:read('*a')
handle:close()
return result
end
it('should return correct headers', function()
local result = executeCommand('curl --head')
assert.match('HTTP/1%.1 200 OK', result)
assert.match('Content%-Type: text/html', result)
assert.match('Content%-Length: 16', result)
end)
it('should return correct body', function()
assert.match('Hello, Pegasus', executeCommand('curl'))
end)
end)
|
describe('integration', function()
local port = '7070'
local url = 'http://localhost:' .. port
local executeCommand = function(command)
local handle = io.popen(command .. ' -s ' .. url)
local result = handle:read('*a')
handle:close()
return result
end
it('should return correct headers', function()
local result = executeCommand('curl --head')
assert.truthy(string.find(result, 'HTTP/1.1 200 OK'))
assert.truthy(string.find(result, 'Content%-Type: text/html'))
assert.truthy(string.find(result, 'Content%-Length: 16'))
end)
it('should return correct body', function()
assert.truthy(string.find(executeCommand('curl'), 'Hello, Pegasus'))
end)
end)
|
fix problem with integration tests
|
fix problem with integration tests
|
Lua
|
mit
|
EvandroLG/pegasus.lua
|
3e89e853ba2e65800e3e127d4a195fb6b412c012
|
task/train.lua
|
task/train.lua
|
local image = require 'image'
local nn = require 'nn'
local optim = require 'optim'
local tnt = require 'torchnet'
local function parse_args(args)
local op = xlua.OptionParser("dataset_creator.lua -c|--csv=CSV -d|--dir=DIR"
.. "[-p|--pattern ptrn] OUTPUT_FILE")
op:option{
"--train",
dest = "train_path",
help = "a file containing training data",
req = true,
}
op:option{
"--test",
dest = "test_path",
help = "a file containing testing data",
req = true,
}
op:option{
"--optim",
default = "adam",
dest = "optim",
help = "optimization method: sgd | adam | adadelta | adagrad | adamax",
}
op:option{
"--batch-size",
default = 100,
dest = "batch_size",
help = "the batch size to use for training",
}
op:option{
"--act",
default = "ReLU",
dest = "act",
help = "activation function: ReLU | ELU | Tanh | Sigmoid",
}
op:option{
"--layers",
dest = "layers",
default = "100,100",
help = "comma separated hidden layer sizes",
}
op:option{
"--batchnorm",
action = "store_true",
default = false,
dest = "batchnorm",
help = "batch normalization",
}
op:option{
"--dropout",
default = 0,
dest = "dropout",
help = "use dropout with specified probability",
}
op:option{
"--dropconnect",
dest = "dropconnect",
default = 0,
help = "use dropconnect with specified probability",
}
op:option{
"--weight-init",
default = "xavier",
dest = "weight_init",
help = "weight initialization mode: heuristic | xavier | xavier_caffe | kaiming",
}
op:option{
"--visualize",
action = "store_true",
dest = "visualize",
help = "visualize the first hidden layer's weights",
}
local opts, args = op:parse()
if not paths.filep(opts.train_path) then
op:fail("The training dataset file must exist!")
elseif not paths.filep(opts.test_path) then
op:fail("The testing dataset file must exit!")
end
opts.dropout = tonumber(opts.dropout)
opts.dropconnect = tonumber(opts.dropconnect)
opts.layers = loadstring("return {" .. opts.layers .. "}")()
return opts, args
end
local function create_net(opts)
local net = nn.Sequential()
if opts.dropconnect > 0 then
require 'dropconnect'
end
for i = 2, #opts.layers do
local nprev = opts.layers[i-1]
local ncurr = opts.layers[i]
if opts.dropout > 0 then
net:add(nn.Dropout(opts.dropout))
end
if opts.dropconnect == 0 then
net:add(nn.Linear(nprev, ncurr))
else
net:add(nn.LinearDropconnect(nprev, ncurr, opts.dropconnect))
end
if i < #opts.layers then
net:add(nn[opts.act]())
if opts.batchnorm then
net:add(nn.BatchNormalization(ncurr))
end
else
net:add(nn.Sigmoid())
end
end
net = require('weight-init')(net, opts.weight_init)
return net
end
local opts, args = parse_args(_G.arg)
local train_dataset = torch.load(opts.train_path)
local test_dataset = torch.load(opts.test_path)
table.insert(opts.layers, 1, train_dataset:get(1).input:nElement())
table.insert(opts.layers, train_dataset:get(1).target:nElement())
local net = create_net(opts)
print(net)
local criterion = nn.BCECriterion()
local engine = tnt.OptimEngine()
local apmeter = tnt.APMeter()
local avgloss = tnt.AverageValueMeter()
engine.hooks.onStartEpoch = function(state)
avgloss:reset()
apmeter:reset()
end
engine.hooks.onForwardCriterion = function(state)
avgloss:add(state.criterion.output)
apmeter:add(state.network.output, state.sample.target)
if state.training then
local str = string.format('avg. loss: %2.10f, precision per class:', avgloss:value())
local val = apmeter:value()
for i = 1, val:nElement() do
str = str .. string.format(' %7.3f%%', val[i] * 100)
end
print(str)
end
end
engine.hooks.onEndEpoch = function(state)
state.iterator:exec('resample') -- call :resample() on the underlying dataset
if opts.visualize then
local parameters
for _, module in ipairs(net.modules) do
if module.__typename == "nn.Linear"
or module.__typename == "nn.LinearDropconnect" then
parameters = module.weight:view(opts.layers[2], 64, 64)
break
end
end
_G.visualize_window = image.display{
image = parameters,
zoom = 2,
win = visualize_window
}
end
end
-- train the model:
engine:train{
network = net,
iterator = train_dataset:shuffle():batch(opts.batch_size):iterator(),
criterion = criterion,
optimMethod = optim[opts.optim],
maxepoch = 100,
}
-- measure test loss and error:
avgloss:reset()
apmeter:reset()
engine:test{
network = net,
iterator = test_dataset:batch(100):iterator(),
criterion = criterion,
}
print(string.format('avg. loss: %2.10f', avgloss:value()))
print(apmeter:value())
-- for data in test_dataset:iterator()() do
-- w = image.display{image=data.input:view(1, 64, 64), win = w}
-- local a = net:forward(data.input):squeeze()
-- local b = data.target
-- a = torch.cat(a, a:ge(0.5):double(), 2)
-- print(torch.cat(a, b, 2):t())
-- io.read()
-- end
|
local image = require 'image'
local nn = require 'nn'
local optim = require 'optim'
local tnt = require 'torchnet'
local function parse_args(args)
local op = xlua.OptionParser("dataset_creator.lua -c|--csv=CSV -d|--dir=DIR"
.. "[-p|--pattern ptrn] OUTPUT_FILE")
op:option{
"--train",
dest = "train_path",
help = "a file containing training data",
req = true,
}
op:option{
"--test",
dest = "test_path",
help = "a file containing testing data",
req = true,
}
op:option{
"--optim",
default = "adam",
dest = "optim",
help = "optimization method: sgd | adam | adadelta | adagrad | adamax",
}
op:option{
"--batch-size",
default = 100,
dest = "batch_size",
help = "the batch size to use for training",
}
op:option{
"--act",
default = "ReLU",
dest = "act",
help = "activation function: ReLU | ELU | Tanh | Sigmoid",
}
op:option{
"--layers",
dest = "layers",
default = "100,100",
help = "comma separated hidden layer sizes",
}
op:option{
"--batchnorm",
action = "store_true",
default = false,
dest = "batchnorm",
help = "batch normalization",
}
op:option{
"--dropout",
default = 0,
dest = "dropout",
help = "use dropout with specified probability",
}
op:option{
"--dropconnect",
dest = "dropconnect",
default = 0,
help = "use dropconnect with specified probability",
}
op:option{
"--weight-init",
default = "xavier",
dest = "weight_init",
help = "weight initialization mode: heuristic | xavier | xavier_caffe | kaiming",
}
op:option{
"--visualize",
action = "store_true",
dest = "visualize",
help = "visualize the first hidden layer's weights",
}
local opts, args = op:parse()
if not paths.filep(opts.train_path) then
op:fail("The training dataset file must exist!")
elseif not paths.filep(opts.test_path) then
op:fail("The testing dataset file must exit!")
end
opts.dropout = tonumber(opts.dropout)
opts.dropconnect = tonumber(opts.dropconnect)
opts.layers = loadstring("return {" .. opts.layers .. "}")()
return opts, args
end
local function create_net(opts)
local net = nn.Sequential()
if opts.dropconnect > 0 then
require 'dropconnect'
end
for i = 2, #opts.layers do
local nprev = opts.layers[i-1]
local ncurr = opts.layers[i]
if opts.dropout > 0 then
net:add(nn.Dropout(opts.dropout))
end
if opts.dropconnect == 0 then
net:add(nn.Linear(nprev, ncurr))
else
net:add(nn.LinearDropconnect(nprev, ncurr, opts.dropconnect))
end
if opts.batchnorm then
net:add(nn.BatchNormalization(ncurr))
end
if i < #opts.layers then
net:add(nn[opts.act]())
else
net:add(nn.Sigmoid())
end
end
net = require('weight-init')(net, opts.weight_init)
return net
end
local opts, args = parse_args(_G.arg)
local train_dataset = torch.load(opts.train_path)
local test_dataset = torch.load(opts.test_path)
table.insert(opts.layers, 1, train_dataset:get(1).input:nElement())
table.insert(opts.layers, train_dataset:get(1).target:nElement())
local net = create_net(opts)
print(net)
local criterion = nn.BCECriterion()
local engine = tnt.OptimEngine()
local apmeter = tnt.APMeter()
local avgloss = tnt.AverageValueMeter()
engine.hooks.onStartEpoch = function(state)
avgloss:reset()
apmeter:reset()
end
engine.hooks.onForwardCriterion = function(state)
avgloss:add(state.criterion.output)
apmeter:add(state.network.output, state.sample.target)
if state.training then
local str = string.format('avg. loss: %2.10f, precision per class:', avgloss:value())
local val = apmeter:value()
for i = 1, val:nElement() do
str = str .. string.format(' %7.3f%%', val[i] * 100)
end
print(str)
end
end
engine.hooks.onEndEpoch = function(state)
state.iterator:exec('resample') -- call :resample() on the underlying dataset
if opts.visualize then
local parameters
for _, module in ipairs(net.modules) do
if module.__typename == "nn.Linear"
or module.__typename == "nn.LinearDropconnect" then
parameters = module.weight:view(opts.layers[2], 64, 64)
break
end
end
_G.visualize_window = image.display{
image = parameters,
zoom = 2,
win = visualize_window
}
end
end
-- train the model:
engine:train{
network = net,
iterator = train_dataset:shuffle():batch(opts.batch_size):iterator(),
criterion = criterion,
optimMethod = optim[opts.optim],
maxepoch = 100,
}
-- measure test loss and error:
avgloss:reset()
apmeter:reset()
engine:test{
network = net,
iterator = test_dataset:batch(100):iterator(),
criterion = criterion,
}
print(string.format('avg. loss: %2.10f', avgloss:value()))
print(apmeter:value())
-- for data in test_dataset:iterator()() do
-- w = image.display{image=data.input:view(1, 64, 64), win = w}
-- local a = net:forward(data.input):squeeze()
-- local b = data.target
-- a = torch.cat(a, a:ge(0.5):double(), 2)
-- print(torch.cat(a, b, 2):t())
-- io.read()
-- end
|
Fix BatchNorm layer ordering + adding the last one
|
Fix BatchNorm layer ordering + adding the last one
|
Lua
|
mit
|
MatejNikl/incremental_learning
|
59805bebcbddd8567a40eebb0117303359249a72
|
mock/component/InputListener.lua
|
mock/component/InputListener.lua
|
module 'mock'
--[[
each InputScript will hold a listener to responding input sensor
filter [ mouse, keyboard, touch, joystick ]
]]
function installInputListener( self, option )
option = option or {}
local inputDevice = option['device'] or mock.getDefaultInputDevice()
local refuseMockUpInput = option['no_mockup'] == true
----link callbacks
local mouseCallback = false
local keyboardCallback = false
local touchCallback = false
local joystickCallback = false
local sensors = option['sensors'] or false
if not sensors or table.index( sensors, 'mouse' ) then
----MouseEvent
local onMouseEvent = self.onMouseEvent
local onMouseDown = self.onMouseDown
local onMouseUp = self.onMouseUp
local onMouseMove = self.onMouseMove
local onMouseEnter = self.onMouseEnter
local onMouseLeave = self.onMouseLeave
local onScroll = self.onScroll
if
onMouseDown or onMouseUp or onMouseMove or onScroll or
onMouseLeave or onMouseEnter or
onMouseEvent
then
mouseCallback = function( ev, x, y, btn, mock )
if mock and refuseMockUpInput then return end
if ev == 'move' then
if onMouseMove then onMouseMove( self, x, y, mock ) end
elseif ev == 'down' then
if onMouseDown then onMouseDown( self, btn, x, y, mock ) end
elseif ev == 'up' then
if onMouseUp then onMouseUp ( self, btn, x, y, mock ) end
elseif ev == 'scroll' then
if onScroll then onScroll ( self, x, y, mock ) end
elseif ev == 'enter' then
if onMouseEnter then onMouseEnter ( self, mock ) end
elseif ev == 'leave' then
if onMouseLeave then onMouseLeave ( self, mock ) end
end
if onMouseEvent then
return onMouseEvent( self, ev, x, y, btn, mock )
end
end
inputDevice:addMouseListener( mouseCallback )
end
end
if not sensors or table.index( sensors, 'touch' ) then
----TouchEvent
local onTouchEvent = self.onTouchEvent
local onTouchDown = self.onTouchDown
local onTouchUp = self.onTouchUp
local onTouchMove = self.onTouchMove
local onTouchCancel = self.onTouchCancel
if onTouchDown or onTouchUp or onTouchMove or onTouchEvent then
touchCallback = function( ev, id, x, y, mock )
if mock and refuseMockUpInput then return end
if ev == 'move' then
if onTouchMove then onTouchMove( self, id, x, y, mock ) end
elseif ev == 'down' then
if onTouchDown then onTouchDown( self, id, x, y, mock ) end
elseif ev == 'up' then
if onTouchUp then onTouchUp ( self, id, x, y, mock ) end
elseif ev == 'cancel' then
if onTouchCancel then onTouchCancel( self ) end
end
if onTouchEvent then
return onTouchEvent( self, ev, id, x, y, mock )
end
end
inputDevice:addTouchListener( touchCallback )
end
end
----KeyEvent
if not sensors or table.index( sensors, 'keyboard' ) then
local onKeyEvent = self.onKeyEvent
local onKeyDown = self.onKeyDown
local onKeyUp = self.onKeyUp
if onKeyDown or onKeyUp or onKeyEvent then
keyboardCallback = function( key, down, mock )
if mock and refuseMockUpInput then return end
if down then
if onKeyDown then onKeyDown( self, key, mock ) end
else
if onKeyUp then onKeyUp ( self, key, mock ) end
end
if onKeyEvent then
return onKeyEvent( self, key, down, mock )
end
end
inputDevice:addKeyboardListener( keyboardCallback )
end
end
---JOYSTICK EVNET
if not sensors or table.index( sensors, 'joystick' ) then
local onJoyButtonDown = self.onJoyButtonDown
local onJoyButtonUp = self.onJoyButtonUp
local onJoyAxisMove = self.onJoyAxisMove
if onJoyButtonDown or onJoyButtonUp or onJoyAxisMove then
joystickCallback = function( ev, joyId, btnId, axisId, value, mock )
if mock and refuseMockUpInput then return end
if ev == 'down' then
if onJoyButtonDown then onJoyButtonDown( self, joyId, btnId, mock ) end
elseif ev == 'up' then
if onJoyButtonUp then onJoyButtonUp( self, joyId, btnId, mock ) end
elseif ev == 'axis' then
if onJoyAxisMove then onJoyAxisMove( self, joyId, axisId, value ) end
end
end
inputDevice:addJoystickListener( joystickCallback )
end
end
self.__inputListenerData = {
mouseCallback = mouseCallback,
keyboardCallback = keyboardCallback,
touchCallback = touchCallback,
joystickCallback = joystickCallback,
inputDevice = inputDevice
}
end
function uninstallInputListener( self )
local data = self.__inputListenerData
if not data then return end
local inputDevice = data.inputDevice
if data.mouseCallback then
inputDevice:removeMouseListener( data.mouseCallback )
end
if data.keyboardCallback then
inputDevice:removeKeyboardListener( data.keyboardCallback )
end
if data.touchCallback then
inputDevice:removeTouchListener( data.touchCallback )
end
if data.joystickCallback then
inputDevice:removeJoystickListener( data.joystickCallback )
end
end
--[[
input event format:
KeyDown ( keyname )
KeyUp ( keyname )
MouseMove ( x, y )
MouseDown ( btn, x, y )
MouseUp ( btn, x, y )
RawMouseMove ( id, x, y ) ---many mouse (??)
RawMouseDown ( id, btn, x, y ) ---many mouse (??)
RawMouseUp ( id, btn, x, y ) ---many mouse (??)
TouchDown ( id, x, y )
TouchUp ( id, x, y )
TouchMove ( id, x, y )
TouchCancel ( )
JoystickMove( id, x, y )
JoystickDown( btn )
JoystickUp ( btn )
LEVEL: get from service
COMPASS: get from service
]]
|
module 'mock'
--[[
each InputScript will hold a listener to responding input sensor
filter [ mouse, keyboard, touch, joystick ]
]]
function installInputListener( self, option )
option = option or {}
local inputDevice = option['device'] or mock.getDefaultInputDevice()
local refuseMockUpInput = option['no_mockup'] == true
----link callbacks
local mouseCallback = false
local keyboardCallback = false
local touchCallback = false
local joystickCallback = false
local sensors = option['sensors'] or false
if not sensors or table.index( sensors, 'mouse' ) then
----MouseEvent
local onMouseEvent = self.onMouseEvent
local onMouseDown = self.onMouseDown
local onMouseUp = self.onMouseUp
local onMouseMove = self.onMouseMove
local onMouseEnter = self.onMouseEnter
local onMouseLeave = self.onMouseLeave
local onScroll = self.onScroll
if
onMouseDown or onMouseUp or onMouseMove or onScroll or
onMouseLeave or onMouseEnter or
onMouseEvent
then
mouseCallback = function( ev, x, y, btn, mock )
if mock and refuseMockUpInput then return end
if ev == 'move' then
if onMouseMove then onMouseMove( self, x, y, mock ) end
elseif ev == 'down' then
if onMouseDown then onMouseDown( self, btn, x, y, mock ) end
elseif ev == 'up' then
if onMouseUp then onMouseUp ( self, btn, x, y, mock ) end
elseif ev == 'scroll' then
if onScroll then onScroll ( self, x, y, mock ) end
elseif ev == 'enter' then
if onMouseEnter then onMouseEnter ( self, mock ) end
elseif ev == 'leave' then
if onMouseLeave then onMouseLeave ( self, mock ) end
end
if onMouseEvent then
return onMouseEvent( self, ev, x, y, btn, mock )
end
end
inputDevice:addMouseListener( mouseCallback )
end
end
if not sensors or table.index( sensors, 'touch' ) then
----TouchEvent
local onTouchEvent = self.onTouchEvent
local onTouchDown = self.onTouchDown
local onTouchUp = self.onTouchUp
local onTouchMove = self.onTouchMove
local onTouchCancel = self.onTouchCancel
if onTouchDown or onTouchUp or onTouchMove or onTouchEvent then
touchCallback = function( ev, id, x, y, mock )
if mock and refuseMockUpInput then return end
if ev == 'move' then
if onTouchMove then onTouchMove( self, id, x, y, mock ) end
elseif ev == 'down' then
if onTouchDown then onTouchDown( self, id, x, y, mock ) end
elseif ev == 'up' then
if onTouchUp then onTouchUp ( self, id, x, y, mock ) end
elseif ev == 'cancel' then
if onTouchCancel then onTouchCancel( self ) end
end
if onTouchEvent then
return onTouchEvent( self, ev, id, x, y, mock )
end
end
inputDevice:addTouchListener( touchCallback )
end
end
----KeyEvent
if not sensors or table.index( sensors, 'keyboard' ) then
local onKeyEvent = self.onKeyEvent
local onKeyDown = self.onKeyDown
local onKeyUp = self.onKeyUp
if onKeyDown or onKeyUp or onKeyEvent then
keyboardCallback = function( key, down, mock )
if mock and refuseMockUpInput then return end
if down then
if onKeyDown then onKeyDown( self, key, mock ) end
else
if onKeyUp then onKeyUp ( self, key, mock ) end
end
if onKeyEvent then
return onKeyEvent( self, key, down, mock )
end
end
inputDevice:addKeyboardListener( keyboardCallback )
end
end
---JOYSTICK EVNET
if not sensors or table.index( sensors, 'joystick' ) then
local onJoyButtonDown = self.onJoyButtonDown
local onJoyButtonUp = self.onJoyButtonUp
local onJoyAxisMove = self.onJoyAxisMove
if onJoyButtonDown or onJoyButtonUp or onJoyAxisMove then
joystickCallback = function( ev, joyId, btnId, axisId, value, mock )
print( ev, joyid, btnId, axisId, value )
if mock and refuseMockUpInput then return end
if ev == 'down' then
if onJoyButtonDown then onJoyButtonDown( self, joyId, btnId, mock ) end
elseif ev == 'up' then
if onJoyButtonUp then onJoyButtonUp( self, joyId, btnId, mock ) end
elseif ev == 'axis' then
if onJoyAxisMove then onJoyAxisMove( self, joyId, axisId, value ) end
end
end
inputDevice:addJoystickListener( joystickCallback )
end
end
self.__inputListenerData = {
mouseCallback = mouseCallback,
keyboardCallback = keyboardCallback,
touchCallback = touchCallback,
joystickCallback = joystickCallback,
inputDevice = inputDevice
}
end
function uninstallInputListener( self )
local data = self.__inputListenerData
if not data then return end
local inputDevice = data.inputDevice
if data.mouseCallback then
inputDevice:removeMouseListener( data.mouseCallback )
end
if data.keyboardCallback then
inputDevice:removeKeyboardListener( data.keyboardCallback )
end
if data.touchCallback then
inputDevice:removeTouchListener( data.touchCallback )
end
if data.joystickCallback then
inputDevice:removeJoystickListener( data.joystickCallback )
end
end
--[[
input event format:
KeyDown ( keyname )
KeyUp ( keyname )
MouseMove ( x, y )
MouseDown ( btn, x, y )
MouseUp ( btn, x, y )
RawMouseMove ( id, x, y ) ---many mouse (??)
RawMouseDown ( id, btn, x, y ) ---many mouse (??)
RawMouseUp ( id, btn, x, y ) ---many mouse (??)
TouchDown ( id, x, y )
TouchUp ( id, x, y )
TouchMove ( id, x, y )
TouchCancel ( )
JoystickMove( id, x, y )
JoystickDown( btn )
JoystickUp ( btn )
LEVEL: get from service
COMPASS: get from service
]]
|
[mock]adding joystick support for osx host; [yaka]fix item using in meow store
|
[mock]adding joystick support for osx host; [yaka]fix item using in meow store
|
Lua
|
mit
|
tommo/mock
|
c35797f6aeae0ab019a059e2955f0e990b65bd0c
|
SpatialMatching.lua
|
SpatialMatching.lua
|
local SpatialMatching, parent = torch.class('nn.SpatialMatching', 'nn.Module')
function SpatialMatching:__init(maxw, maxh, full_output)
-- If full_output is false, output is computed on elements of the first input
-- for which all the possible corresponding elements exist in the second input
-- In addition, if full_output is set to false, the pixel (1,1) of the first input
-- is supposed to correspond to the pixel (maxh/2, maxw/2) of the second one
-- If align_inputs is set, input[2] is assumed to be large enough
-- (that is input[1]:size(1) <= inputs[1]:size(1) - maxh + 1, same for w)
-- TODO full_output == true and align_inputs == false is probably useless
parent.__init(self)
self.maxw = maxw or 11
self.maxh = maxh or 11
full_output = full_output or true
if full_output then self.full_output = 1 else self.full_output = 0 end
end
function SpatialMatching:updateOutput(input)
-- input is a table of 2 inputs, each one being KxHxW
-- if not full_output, the 1st one is KxH1xW1 where H1 <= H-maxh+1, W1 <= W-maxw+1
self.output:resize(input[1]:size(2), input[1]:size(3), self.maxh, self.maxw)
input[1].nn.SpatialMatching_updateOutput(self, input[1], input[2])
return self.output
end
function SpatialMatching:updateGradInput(input, gradOutput)
-- TODO this is probably the wrong way
self.gradInput1 = torch.Tensor(input[1]:size()):zero()
self.gradInput2 = torch.Tensor(input[2]:size()):zero()
input[1].nn.SpatialMatching_updateGradInput(self, input[1], input[2], gradOutput)
self.gradInput = {self.gradInput1, self.gradInput2}
return self.gradInput
end
|
local SpatialMatching, parent = torch.class('nn.SpatialMatching', 'nn.Module')
function SpatialMatching:__init(maxw, maxh, full_output)
-- If full_output is false, output is computed on elements of the first input
-- for which all the possible corresponding elements exist in the second input
-- In addition, if full_output is set to false, the pixel (1,1) of the first input
-- is supposed to correspond to the pixel (maxh/2, maxw/2) of the second one
-- If align_inputs is set, input[2] is assumed to be large enough
-- (that is input[1]:size(1) <= inputs[1]:size(1) - maxh + 1, same for w)
-- TODO full_output == true and align_inputs == false is probably useless
parent.__init(self)
self.maxw = maxw or 11
self.maxh = maxh or 11
if full_output == nil then
full_output = false
end
if full_output then self.full_output = 1 else self.full_output = 0 end
end
function SpatialMatching:updateOutput(input)
-- input is a table of 2 inputs, each one being KxHxW
-- if not full_output, the 1st one is KxH1xW1 where H1 <= H-maxh+1, W1 <= W-maxw+1
self.output:resize(input[1]:size(2), input[1]:size(3), self.maxh, self.maxw)
input[1].nn.SpatialMatching_updateOutput(self, input[1], input[2])
return self.output
end
function SpatialMatching:updateGradInput(input, gradOutput)
-- TODO this is probably the wrong way
self.gradInput1 = torch.Tensor(input[1]:size()):zero()
self.gradInput2 = torch.Tensor(input[2]:size()):zero()
input[1].nn.SpatialMatching_updateGradInput(self, input[1], input[2], gradOutput)
self.gradInput = {self.gradInput1, self.gradInput2}
return self.gradInput
end
|
Fix bug in SpatialMatching
|
Fix bug in SpatialMatching
|
Lua
|
mit
|
clementfarabet/lua---nnx
|
970882fff2c6d7f45b61c5b690d6e0f8068ebc86
|
modules/dokpro.lua
|
modules/dokpro.lua
|
local htmlparser = require'htmlparser'
local trim = function(s)
if not s then return nil end
return s:match('^()%s*$') and '' or s:match('^%s*(.*%S)')
end
local wordClass = {
f = 'substantiv',
m = 'substantiv',
n = 'substantiv',
a = 'adjektiv',
v = 'verb',
}
local removeDuplicates = function(tbl)
local done = {}
local out = {}
for i=1, #tbl do
local v = tbl[i]
if(not done[v]) then
done[v] = true
table.insert(out, v)
end
end
return out
end
local parseData = function(data)
if(data:match('ordboksdatabasene')) then
return nil, 'Service down. :('
end
-- This page is a typical example of someone using XHTML+CSS+JS, while still
-- coding like they used to back in 1998.
data = data:gsub('\r', ''):match('<div id="kolonne_enkel"[^>]+>(.-)<div id="slutt">'):gsub(' ', '')
local words = {}
data = data:match('(<span class="oppslagsord b".->.-)</td>')
if(data) then
local doc = htmlparser.parsestr(data)
local word = doc[1][1]
-- Workaround for mis matched word (partial match)
if type(word) == "table" then
word = doc[1][1][1]
end
-- First entry
local entry = {
lookup = {},
meaning = {},
examples = {},
}
local addentry = function(lookup)
entry = {
lookup = {},
meaning = {},
examples = {},
}
table.insert(entry.lookup, lookup)
table.insert(words, entry)
end
local add = function(item)
if not item then return end
table.insert(entry.meaning, item)
end
-- Here be dragons. This is why we can't have nice things
for _, w in pairs(doc) do
if _ ~= '_tag' then
if type(w) == "string" then
add(w)
elseif type(w) == "table" then
if w['_attr'] and w['_attr'].class == 'oppsgramordklasse' then
local class = wordClass[w[1]:sub(1, 1)] or w[1]
add(ivar2.util.underline(class))
elseif w['_attr'] and w['_attr'].class == 'oppslagsord b' then
local lookup = {}
for _, t in pairs(w) do
if type(t) == "string" and t ~= "span" then
table.insert(lookup, t)
elseif type(t[1]) == "string" and t[1] ~= "span" then
table.insert(lookup, t[1])
end
end
addentry(table.concat(lookup))
-- Extract definitions
elseif w['_attr'] ~= nil and w['_attr']['class'] == 'utvidet' then
for _, t in pairs(w) do
if type(t) == "string" and t ~= "span" then
-- Utvidet + kompakt leads to dupes.
-- add(t)
elseif type(w) == "table" then
if t['_attr'] ~= nil and t['_attr']['class'] == 'tydingC kompakt' then
for _, f in pairs(t) do
if type(f) == "string" and f ~= 'span' then
add(f)
elseif type(f[1]) == "string" and trim(f[1]) ~= "" then
add(string.format("[%s]", ivar2.util.bold(f[1])))
end
end
end
end
end
elseif type(w[1]) == "string" then
if w[1] ~= word then
add(w[1])
end
end
end
end
end
-- Remove duplicate entries (such as word classes)
entry.meaning = removeDuplicates(entry.meaning)
for _,entry in pairs(words) do
entry.meaning = trim(table.concat(entry.meaning))
end
end
return words
end
local handleInput = function(self, source, destination, word, ordbok)
if not ordbok then ordbok = 'bokmaal' end
local query = ivar2.util.urlEncode(word)
ivar2.util.simplehttp(
"http://ordbok.uib.no/perl/ordbok.cgi?ordbok="..ordbok.."&"..ordbok.."=+&OPP=" .. query,
function(data)
local words, err = parseData(data)
local out = {}
if(words) then
for i=1, #words do
local word = words[i]
local lookup = table.concat(word.lookup, ', ')
local definition = word.meaning
if(word.examples[1]) then
if(definition and #definition < 35) then
definition = definition .. ' ' .. word.examples[1]
else
definition = word.examples[1]
end
end
if(definition) then
local message = string.format('\002[%s]\002: %s', lookup, definition)
table.insert(out, message)
end
end
end
if(#out > 0) then
self:Msg('privmsg', destination, source, '%s', table.concat(out, ', '))
else
self:Msg('privmsg', destination, source, '%s: %s', source.nick, err or 'Du suger, prøv igjen.')
end
end
)
end
return {
PRIVMSG = {
['^%pdokpro (.+)$'] = handleInput,
['^%pordbok (.+)$'] = handleInput,
['^%pbokmål (.+)$'] = handleInput,
['^%pnynorsk (.+)$'] = function(self, source, destination, word)
handleInput(self, source, destination, word, 'nynorsk')
end
},
}
|
local htmlparser = require'htmlparser'
local trim = function(s)
if not s then return nil end
return s:match('^()%s*$') and '' or s:match('^%s*(.*%S)')
end
local wordClass = {
f = 'substantiv',
m = 'substantiv',
n = 'substantiv',
a = 'adjektiv',
v = 'verb',
}
local removeDuplicates = function(tbl)
local done = {}
local out = {}
for i=1, #tbl do
local v = tbl[i]
if(not done[v]) then
done[v] = true
table.insert(out, v)
end
end
return out
end
local parseData = function(data)
if(data:match('ordboksdatabasene')) then
return nil, 'Service down. :('
end
-- This page is a typical example of someone using XHTML+CSS+JS, while still
-- coding like they used to back in 1998.
data = data:gsub('\r', ''):match('<div id="kolonne_enkel"[^>]+>(.-)<div id="slutt">'):gsub(' ', '')
local words = {}
data = data:match('(<span class="oppslagsord b".->.-)</td>')
if(data) then
local doc = htmlparser.parsestr(data)
local word = doc[1][1]
-- Workaround for mis matched word (partial match)
if type(word) == "table" then
word = doc[1][1][1]
end
-- First entry
local entry = {
lookup = {},
meaning = {},
examples = {},
}
local addentry = function(lookup)
entry = {
lookup = {},
meaning = {},
examples = {},
}
table.insert(entry.lookup, lookup)
table.insert(words, entry)
end
local add = function(item)
if not item then return end
table.insert(entry.meaning, item)
end
-- Here be dragons. This is why we can't have nice things
for _, w in pairs(doc) do
if _ ~= '_tag' then
if type(w) == "string" then
add(w)
elseif type(w) == "table" then
if w['_attr'] and w['_attr'].class == 'oppsgramordklasse' then
-- replace with friendly version:
-- local class = wordClass[w[1]:sub(1, 1)] or w[1]
local class = w[1]
add(ivar2.util.underline(class))
elseif w['_attr'] and w['_attr'].class == 'oppslagsord b' then
local lookup = {}
for _, t in pairs(w) do
if type(t) == "string" and t ~= "span" then
table.insert(lookup, t)
elseif type(t[1]) == "string" and t[1] ~= "span" then
table.insert(lookup, t[1])
end
end
addentry(table.concat(lookup))
-- Extract definitions
elseif w['_attr'] ~= nil and w['_attr']['class'] == 'utvidet' then
for _, t in pairs(w) do
if type(t) == "string" and t ~= "span" then
-- Utvidet + kompakt leads to dupes.
-- add(t)
elseif type(w) == "table" then
if t['_attr'] ~= nil and t['_attr']['class'] == 'tydingC kompakt' then
for _, f in pairs(t) do
if type(f) == "string" and f ~= 'span' then
add(f)
elseif type(f[1]) == "string" and trim(f[1]) ~= "" then
add(string.format("[%s]", ivar2.util.bold(f[1])))
end
end
end
end
end
elseif type(w[1]) == "string" then
if w[1] ~= word then
add(w[1])
end
end
end
end
end
-- Remove duplicate entries (such as word classes)
entry.meaning = removeDuplicates(entry.meaning)
for _, e in pairs(words) do
e.meaning = trim(table.concat(e.meaning))
end
end
return words
end
local handleInput = function(self, source, destination, l_word, ordbok)
if not ordbok then ordbok = 'bokmaal' end
local query = ivar2.util.urlEncode(l_word)
ivar2.util.simplehttp(
"http://ordbok.uib.no/perl/ordbok.cgi?ordbok="..ordbok.."&"..ordbok.."=+&OPP=" .. query,
function(data)
local words, err = parseData(data)
local out = {}
if(words) then
for i=1, #words do
local word = words[i]
local lookup = table.concat(word.lookup, ', ')
local definition = word.meaning
if(word.examples[1]) then
if(definition and #definition < 35) then
definition = definition .. ' ' .. word.examples[1]
else
definition = word.examples[1]
end
end
if(definition) then
local message = string.format('\002[%s]\002: %s', lookup, definition)
table.insert(out, message)
end
end
end
if(#out > 0) then
self:Msg('privmsg', destination, source, '%s', table.concat(out, ', '))
else
self:Msg('privmsg', destination, source, '%s: %s', source.nick, err or 'Du suger, prøv igjen.')
end
end
)
end
return {
PRIVMSG = {
['^%pdokpro (.+)$'] = handleInput,
['^%pordbok (.+)$'] = handleInput,
['^%pbokmål (.+)$'] = handleInput,
['^%pnynorsk (.+)$'] = function(self, source, destination, word)
handleInput(self, source, destination, word, 'nynorsk')
end
},
}
|
dokpro: fixes
|
dokpro: fixes
|
Lua
|
mit
|
torhve/ivar2,torhve/ivar2,torhve/ivar2
|
11d5ce43802b0e92b321aeb1d37d2f7ecc4ab0d8
|
himan-scripts/CB-TCU-cloud.lua
|
himan-scripts/CB-TCU-cloud.lua
|
--Round to natural number
function round(n)
return n % 1 >= 0.5 and math.ceil(n) or math.floor(n)
end
--Main program
--
local MU = level(HPLevelType.kMaximumThetaE,0)
local HL = level(HPLevelType.kHeightLayer,500,0)
local HG = level(HPLevelType.kHeight,0)
EL500 = luatool:FetchWithType(current_time, HL, param("EL-HPA"), current_forecast_type)
LCL500 = luatool:FetchWithType(current_time, HL, param("LCL-HPA"), current_forecast_type)
LFC500 = luatool:FetchWithType(current_time, HL, param("LFC-HPA"), current_forecast_type)
CAPE500 = luatool:FetchWithType(current_time, HL, param("CAPE-JKG"), current_forecast_type)
CIN500 = luatool:FetchWithType(current_time, HL, param("CIN-JKG"), current_forecast_type)
LCLmu = luatool:FetchWithType(current_time, MU, param("LCL-HPA"), current_forecast_type)
LFCmu = luatool:FetchWithType(current_time, MU, param("LFC-HPA"), current_forecast_type)
ELmu = luatool:FetchWithType(current_time, MU, param("EL-HPA"), current_forecast_type)
CINmu = luatool:FetchWithType(current_time, MU, param("CIN-JKG"), current_forecast_type)
CAPEmu = luatool:FetchWithType(current_time, MU, param("CAPE-JKG"), current_forecast_type)
NL = luatool:FetchWithType(current_time, HG, param("NL-PRCNT"), current_forecast_type)
NM = luatool:FetchWithType(current_time, HG, param("NM-PRCNT"), current_forecast_type)
if not NL then
NL = luatool:FetchWithType(current_time, HG, param("NL-0TO1"), current_forecast_type)
end
if not NM then
NM = luatool:FetchWithType(current_time, HG, param("NM-0TO1"), current_forecast_type)
end
RR = luatool:FetchWithType(current_time, HG, param("RRR-KGM2"), current_forecast_type)
CBlimit = 9 --required vertical thickness [degrees C] to consider a CB (tweak this..!)
TCUlimit = 6 --required vertical thickness [degrees C] to consider a TCU (tweak this..!)
CBtopLim = 263.15 --required top T [K] to consider a CB (tweakable!)
--Max height [FL] to check for top
TopLim = 650
--Denominator to calculate overshooting top based on CAPE, +1000ft/350J/kg (tweak this!)
overshoot = 35
hitool:SetHeightUnit(HPParameterUnit.kHPa)
Ttop = hitool:VerticalValueGrid(param("T-K"),EL500)
Tbase = hitool:VerticalValueGrid(param("T-K"),LCL500)
TtopMU = hitool:VerticalValueGrid(param("T-K"),ELmu)
--LFC probably better than LCL for elev conv. base
TbaseMU = hitool:VerticalValueGrid(param("T-K"),LFCmu)
local i = 0
local res = {}
local Missing = missing
for i=1, #EL500 do
res[i] = Missing
--TCU
if ((Tbase[i]-Ttop[i]>TCUlimit) and (NL[i]>0) and (CIN500[i]>-1)) then
res[i] = FlightLevel_(EL500[i]*100)
--Limit top value
if (res[i] <= TopLim) then
--Add for overshooting top based on CAPE, +1000ft/350J/kg (tweak this!)
res[i] = -(res[i] + CAPE500[i]/overshoot)
else
--Add for overshooting top based on CAPE, +1000ft/350J/kg (tweak this!)
res[i] = Missing
end
end
--CB
if ((Ttop[i]<CBtopLim) and (Tbase[i]-Ttop[i]>CBlimit) and (RR[i]>0)) then
res[i] = FlightLevel_(EL500[i]*100)
--Limit top value
if (res[i] <= TopLim) then
--Add for overshooting top based on CAPE, +1000ft/350J/kg (tweak this!)
res[i] = res[i] + CAPE500[i]/overshoot
else
res[i] = Missing
end
end
--If no TOP from above, check also with MU values, for elev. conv. only from blw 3,5km
if (not res[i]==res[i] and (LFCmu[i]<LCL500[i]) and (LFCmu[i]>650)) then
-- TCU
if ((TbaseMU[i]-TtopMU[i]>TCUlimit) and ((NL[i]>0) or (NM[i]>0)) and (CINmu[i]>-1)) then
res[i] = FlightLevel_(ELmu[i]*100)
--Limit top value
if (res[i] <= TopLim) then
--Add for overshooting top based on CAPE, +1000ft/350J/kg (tweak this!)
res[i] = -(res[i] + CAPEmu[i]/overshoot)
else
res[i] = Missing
end
end
--CB
if ((TtopMU[i]<CBtopLim) and (TbaseMU[i]-TtopMU[i]>CBlimit) and (RR[i]>0)) then
res[i] = FlightLevel_(ELmu[i]*100)
--Limit top value
if (res[i] <= TopLim) then
--Add for overshooting top based on CAPE, +1000ft/350J/kg (tweak this!)
res[i] = res[i] + CAPEmu[i]/overshoot
else
res[i] = Missing
end
end
end
res[i] = round(res[i]/10)*10;
end
p = param("CBTCU-FL")
result:SetValues(res)
result:SetParam(p)
luatool:WriteToFile(result)
|
--Round to natural number
function round(n)
return n % 1 >= 0.5 and math.ceil(n) or math.floor(n)
end
--Main program
--
local MU = level(HPLevelType.kMaximumThetaE,0)
local HL = level(HPLevelType.kHeightLayer,500,0)
local HG = level(HPLevelType.kHeight,0)
EL500 = luatool:FetchWithType(current_time, HL, param("EL-HPA"), current_forecast_type)
LCL500 = luatool:FetchWithType(current_time, HL, param("LCL-HPA"), current_forecast_type)
LFC500 = luatool:FetchWithType(current_time, HL, param("LFC-HPA"), current_forecast_type)
CAPE500 = luatool:FetchWithType(current_time, HL, param("CAPE-JKG"), current_forecast_type)
CIN500 = luatool:FetchWithType(current_time, HL, param("CIN-JKG"), current_forecast_type)
LCLmu = luatool:FetchWithType(current_time, MU, param("LCL-HPA"), current_forecast_type)
LFCmu = luatool:FetchWithType(current_time, MU, param("LFC-HPA"), current_forecast_type)
LFCmu_metric = luatool:FetchWithType(current_time, MU, param("LFC-M"), current_forecast_type)
ELmu = luatool:FetchWithType(current_time, MU, param("EL-HPA"), current_forecast_type)
CINmu = luatool:FetchWithType(current_time, MU, param("CIN-JKG"), current_forecast_type)
CAPEmu = luatool:FetchWithType(current_time, MU, param("CAPE-JKG"), current_forecast_type)
Ttop = luatool:FetchWithType(current_time, HL, param("EL-K"), current_forecast_type)
Tbase = luatool:FetchWithType(current_time, HL, param("LCL-K"), current_forecast_type)
TtopMU = luatool:FetchWithType(current_time, MU, param("EL-K"), current_forecast_type)
--LFC probably better than LCL for elev conv. base
TbaseMU = luatool:FetchWithType(current_time, MU, param("LFC-K"), current_forecast_type)
NL = luatool:FetchWithType(current_time, HG, param("NL-PRCNT"), current_forecast_type)
NM = luatool:FetchWithType(current_time, HG, param("NM-PRCNT"), current_forecast_type)
if not NL then
NL = luatool:FetchWithType(current_time, HG, param("NL-0TO1"), current_forecast_type)
end
if not NM then
NM = luatool:FetchWithType(current_time, HG, param("NM-0TO1"), current_forecast_type)
end
RR = luatool:FetchWithType(current_time, HG, param("RRR-KGM2"), current_forecast_type)
CBlimit = 9 --required vertical thickness [degrees C] to consider a CB (tweak this..!)
TCUlimit = 6 --required vertical thickness [degrees C] to consider a TCU (tweak this..!)
CBtopLim = 263.15 --required top T [K] to consider a CB (tweakable!)
--Max height [FL] to check for top
TopLim = 650
--Denominator to calculate overshooting top based on CAPE, +1000ft/350J/kg (tweak this!)
overshoot = 35
local i = 0
local res = {}
local Missing = missing
for i=1, #EL500 do
res[i] = Missing
--TCU
if ((Tbase[i]-Ttop[i]>TCUlimit) and (NL[i]>0) and (CIN500[i]>-1)) then
res[i] = FlightLevel_(EL500[i]*100)
--Limit top value
if (res[i] <= TopLim) then
--Add for overshooting top based on CAPE, +1000ft/350J/kg (tweak this!)
res[i] = -(res[i] + CAPE500[i]/overshoot)
else
--Add for overshooting top based on CAPE, +1000ft/350J/kg (tweak this!)
res[i] = Missing
end
end
--CB
if ((Ttop[i]<CBtopLim) and (Tbase[i]-Ttop[i]>CBlimit) and (RR[i]>0)) then
res[i] = FlightLevel_(EL500[i]*100)
--Limit top value
if (res[i] <= TopLim) then
--Add for overshooting top based on CAPE, +1000ft/350J/kg (tweak this!)
res[i] = res[i] + CAPE500[i]/overshoot
else
res[i] = Missing
end
end
--If no TOP from above, check also with MU values, for elev. conv. only from blw 3,5km
if (not res[i]==res[i] and (LFCmu[i]>LCL500[i]) and (LFCmu_metric[i]>650)) then
-- TCU
if ((TbaseMU[i]-TtopMU[i]>TCUlimit) and ((NL[i]>0) or (NM[i]>0)) and (CINmu[i]>-1)) then
res[i] = FlightLevel_(ELmu[i]*100)
--Limit top value
if (res[i] <= TopLim) then
--Add for overshooting top based on CAPE, +1000ft/350J/kg (tweak this!)
res[i] = -(res[i] + CAPEmu[i]/overshoot)
else
res[i] = Missing
end
end
--CB
if ((TtopMU[i]<CBtopLim) and (TbaseMU[i]-TtopMU[i]>CBlimit) and (RR[i]>0)) then
res[i] = FlightLevel_(ELmu[i]*100)
--Limit top value
if (res[i] <= TopLim) then
--Add for overshooting top based on CAPE, +1000ft/350J/kg (tweak this!)
res[i] = res[i] + CAPEmu[i]/overshoot
else
res[i] = Missing
end
end
end
res[i] = round(res[i]/10)*10;
end
p = param("CBTCU-FL")
result:SetValues(res)
result:SetParam(p)
luatool:WriteToFile(result)
|
CB-TCU bugfix
|
CB-TCU bugfix
|
Lua
|
mit
|
fmidev/himan,fmidev/himan,fmidev/himan
|
fb1c495a4c976fdd24f4b7df7b7b4a120acf7e94
|
modules/corelib/ui/tooltip.lua
|
modules/corelib/ui/tooltip.lua
|
-- @docclass
g_tooltip = {}
-- private variables
local toolTipLabel
local currentHoveredWidget
-- private functions
local function moveToolTip(tooltip)
if not tooltip:isVisible() or tooltip:getOpacity() < 0.1 then return end
local pos = g_window.getMousePosition()
pos.y = pos.y + 1
local xdif = g_window.getSize().width - (pos.x + tooltip:getWidth())
if xdif < 2 then
pos.x = pos.x - tooltip:getWidth() - 3
else
pos.x = pos.x + 10
end
tooltip:setPosition(pos)
end
local function onWidgetHoverChange(widget, hovered)
if hovered then
if widget.tooltip and not g_mouse.isPressed() then
g_tooltip.display(widget.tooltip)
currentHoveredWidget = widget
end
else
if widget == currentHoveredWidget then
g_tooltip.hide()
currentHoveredWidget = nil
end
end
end
local function onWidgetStyleApply(widget, styleName, styleNode)
if styleNode.tooltip then
widget.tooltip = styleNode.tooltip
end
end
-- public functions
function g_tooltip.init()
connect(UIWidget, { onStyleApply = onWidgetStyleApply,
onHoverChange = onWidgetHoverChange})
addEvent(function()
toolTipLabel = g_ui.createWidget('UILabel', rootWidget)
toolTipLabel:setId('toolTip')
toolTipLabel:setBackgroundColor('#111111cc')
toolTipLabel:setTextAlign(AlignCenter)
toolTipLabel:hide()
toolTipLabel.onMouseMove = moveToolTip
end)
end
function g_tooltip.terminate()
disconnect(UIWidget, { onStyleApply = onWidgetStyleApply,
onHoverChange = onWidgetHoverChange })
currentHoveredWidget = nil
toolTipLabel:destroy()
toolTipLabel = nil
g_tooltip = nil
end
function g_tooltip.display(text)
if text == nil then return end
if not toolTipLabel then return end
toolTipLabel:setText(text)
toolTipLabel:resizeToText()
toolTipLabel:resize(toolTipLabel:getWidth() + 4, toolTipLabel:getHeight() + 4)
toolTipLabel:show()
toolTipLabel:raise()
toolTipLabel:enable()
g_effects.fadeIn(toolTipLabel, 100)
moveToolTip(toolTipLabel)
end
function g_tooltip.hide()
g_effects.fadeOut(toolTipLabel, 100)
end
-- @docclass UIWidget @{
-- UIWidget extensions
function UIWidget:setTooltip(text)
self.tooltip = text
end
function UIWidget:removeTooltip()
self.tooltip = nil
end
function UIWidget:getTooltip()
return self.tooltip
end
-- @}
g_tooltip.init()
connect(g_app, { onTerminate = g_tooltip.terminate })
|
-- @docclass
g_tooltip = {}
-- private variables
local toolTipLabel
local currentHoveredWidget
-- private functions
local function moveToolTip(first)
if not first and (not toolTipLabel:isVisible() or toolTipLabel:getOpacity() < 0.1) then return end
local pos = g_window.getMousePosition()
pos.y = pos.y + 1
local xdif = g_window.getSize().width - (pos.x + toolTipLabel:getWidth())
if xdif < 2 then
pos.x = pos.x - toolTipLabel:getWidth() - 3
else
pos.x = pos.x + 10
end
toolTipLabel:setPosition(pos)
end
local function onWidgetHoverChange(widget, hovered)
if hovered then
if widget.tooltip and not g_mouse.isPressed() then
g_tooltip.display(widget.tooltip)
currentHoveredWidget = widget
end
else
if widget == currentHoveredWidget then
g_tooltip.hide()
currentHoveredWidget = nil
end
end
end
local function onWidgetStyleApply(widget, styleName, styleNode)
if styleNode.tooltip then
widget.tooltip = styleNode.tooltip
end
end
-- public functions
function g_tooltip.init()
connect(UIWidget, { onStyleApply = onWidgetStyleApply,
onHoverChange = onWidgetHoverChange})
addEvent(function()
toolTipLabel = g_ui.createWidget('UILabel', rootWidget)
toolTipLabel:setId('toolTip')
toolTipLabel:setBackgroundColor('#111111cc')
toolTipLabel:setTextAlign(AlignCenter)
toolTipLabel:hide()
toolTipLabel.onMouseMove = function() moveToolTip() end
end)
end
function g_tooltip.terminate()
disconnect(UIWidget, { onStyleApply = onWidgetStyleApply,
onHoverChange = onWidgetHoverChange })
currentHoveredWidget = nil
toolTipLabel:destroy()
toolTipLabel = nil
g_tooltip = nil
end
function g_tooltip.display(text)
if text == nil then return end
if not toolTipLabel then return end
toolTipLabel:setText(text)
toolTipLabel:resizeToText()
toolTipLabel:resize(toolTipLabel:getWidth() + 4, toolTipLabel:getHeight() + 4)
toolTipLabel:show()
toolTipLabel:raise()
toolTipLabel:enable()
g_effects.fadeIn(toolTipLabel, 100)
moveToolTip(true)
end
function g_tooltip.hide()
g_effects.fadeOut(toolTipLabel, 100)
end
-- @docclass UIWidget @{
-- UIWidget extensions
function UIWidget:setTooltip(text)
self.tooltip = text
end
function UIWidget:removeTooltip()
self.tooltip = nil
end
function UIWidget:getTooltip()
return self.tooltip
end
-- @}
g_tooltip.init()
connect(g_app, { onTerminate = g_tooltip.terminate })
|
Fix minor tooltip bug
|
Fix minor tooltip bug
|
Lua
|
mit
|
kwketh/otclient,EvilHero90/otclient,dreamsxin/otclient,dreamsxin/otclient,gpedro/otclient,EvilHero90/otclient,Cavitt/otclient_mapgen,Cavitt/otclient_mapgen,gpedro/otclient,gpedro/otclient,Radseq/otclient,Radseq/otclient,kwketh/otclient,dreamsxin/otclient
|
00f865b217bef67624845e0593e70c3d3e3da848
|
scripts/genie.lua
|
scripts/genie.lua
|
solution "UtilsCollection"
location (path.join("../.project/", _ACTION))
language "C++"
configurations { "Debug", "Release" }
platforms { "x32", "x64" }
objdir ("../.build/".._ACTION)
defines { "_CRT_SECURE_NO_WARNINGS" }
project "ResourceEmbedder"
uuid "fecff87e-9cc0-4134-a2b5-6ef0e73969b4"
kind "ConsoleApp"
targetdir "../.output/"
files {
"../ResourceEmbedder/**.cpp",
"../ResourceEmbedder/**.h",
"../externals/lz4/lib/lz4.c",
"../externals/lz4/lib/lz4.h",
"../externals/lz4/lib/lz4hc.c",
"../externals/lz4/lib/lz4hc.h",
"../externals/zstd/lib/zstd.h",
"../externals/zstd/lib/common/**.c",
"../externals/zstd/lib/common/**.h",
"../externals/zstd/lib/compress/**.c",
"../externals/zstd/lib/compress/**.h"
}
includedirs {
"../externals/lz4/lib",
"../externals/zstd/lib/",
"../externals/zstd/lib/common",
"../externals/zstd/lib/compress"
}
platforms{}
configuration "Debug"
targetsuffix "_d"
flags { "Symbols" }
configuration "Release"
flags { "Optimize" }
project "U8toX"
uuid "83220d0c-8a77-4acb-af45-aedaad4df6b5"
kind "ConsoleApp"
targetdir "../.output/"
files {
"../u8tox/**.cpp",
"../u8tox/**.h"
}
platforms{}
configuration "Debug"
targetsuffix "_d"
flags { "Symbols" }
configuration "Release"
flags { "Optimize" }
project "BooleanExpression"
uuid "16b264fc-24cc-487b-840d-24070a7d461b"
kind "ConsoleApp"
targetdir "../.output/"
files {
"../BooleanExpression/**.cpp",
"../BooleanExpression/**.h"
}
platforms{}
configuration "Debug"
targetsuffix "_d"
flags { "Symbols" }
configuration "Release"
flags { "Optimize" }
project "StringUtils"
uuid "618ee57a-e754-46cf-9f9b-7923e531d970"
kind "ConsoleApp"
targetdir "../.output/"
files {
"../StringUtils/**.cpp",
"../StringUtils/**.h"
}
platforms{}
configuration "Debug"
targetsuffix "_d"
flags { "Symbols" }
configuration "Release"
flags { "Optimize" }
|
solution "UtilsCollection"
location (path.join("../.project/", _ACTION))
language "C++"
configurations { "Debug", "Release" }
platforms { "x32", "x64" }
objdir ("../.build/".._ACTION)
defines { "_CRT_SECURE_NO_WARNINGS" }
project "ResourceEmbedder"
uuid "fecff87e-9cc0-4134-a2b5-6ef0e73969b4"
kind "ConsoleApp"
targetdir "../.output/"
files {
"../ResourceEmbedder/**.cpp",
"../ResourceEmbedder/**.h",
"../externals/lz4/lib/lz4.c",
"../externals/lz4/lib/lz4.h",
"../externals/lz4/lib/lz4hc.c",
"../externals/lz4/lib/lz4hc.h",
"../externals/zstd/lib/zstd.h",
"../externals/zstd/lib/common/**.c",
"../externals/zstd/lib/common/**.h",
"../externals/zstd/lib/compress/**.c",
"../externals/zstd/lib/compress/**.h"
}
includedirs {
"../externals/lz4/lib",
"../externals/zstd/lib/",
"../externals/zstd/lib/common",
"../externals/zstd/lib/compress"
}
platforms{}
configuration "Debug"
targetsuffix "_d"
platforms "x64"
targetsuffix "_x64_d"
platforms{}
flags { "Symbols" }
configuration "Release"
platforms "x64"
targetsuffix "_x64"
platforms{}
flags { "Optimize" }
project "U8toX"
uuid "83220d0c-8a77-4acb-af45-aedaad4df6b5"
kind "ConsoleApp"
targetdir "../.output/"
files {
"../u8tox/**.cpp",
"../u8tox/**.h"
}
platforms{}
configuration "Debug"
targetsuffix "_d"
platforms "x64"
targetsuffix "_x64_d"
flags { "Symbols" }
configuration "Release"
platforms "x64"
targetsuffix "_x64"
platforms{}
flags { "Optimize" }
project "BooleanExpression"
uuid "16b264fc-24cc-487b-840d-24070a7d461b"
kind "ConsoleApp"
targetdir "../.output/"
files {
"../BooleanExpression/**.cpp",
"../BooleanExpression/**.h"
}
platforms{}
configuration "Debug"
targetsuffix "_d"
platforms "x64"
targetsuffix "_x64_d"
flags { "Symbols" }
configuration "Release"
platforms "x64"
targetsuffix "_x64"
platforms{}
flags { "Optimize" }
project "StringUtils"
uuid "618ee57a-e754-46cf-9f9b-7923e531d970"
kind "StaticLib"
targetdir "../.output/"
files {
"../StringUtils/**.cpp",
"../StringUtils/**.h"
}
platforms{}
configuration "Debug"
targetsuffix "_d"
platforms "x64"
targetsuffix "_x64_d"
flags { "Symbols" }
configuration "Release"
platforms "x64"
targetsuffix "_x64"
platforms{}
flags { "Optimize" }
|
Add prefix "_64" in filename to 64 bits build
|
Add prefix "_64" in filename to 64 bits build
|
Lua
|
mit
|
thennequin/UtilsCollection,thennequin/UtilsCollection
|
a1564096ec639e7541fd0e0fdc80fd5b267df4b1
|
pud/ui/Tooltip.lua
|
pud/ui/Tooltip.lua
|
local Class = require 'lib.hump.class'
local Frame = getClass 'pud.ui.Frame'
local Text = getClass 'pud.ui.Text'
local Bar = getClass 'pud.ui.Bar'
-- Tooltip
--
local Tooltip = Class{name='Tooltip',
inherits=Frame,
function(self, ...)
Frame.construct(self, ...)
self:setDepth(5)
self._margin = 0
self._show = false
end
}
-- destructor
function Tooltip:destroy()
self:clear()
self._margin = nil
Frame.destroy(self)
end
-- clear the tooltip
function Tooltip:clear()
if self._header1 then
self._header1:destroy()
self._header1 = nil
end
if self._header2 then
self._header2:destroy()
self._header2 = nil
end
if self._icon then
self._icon:destroy()
self._icon = nil
end
if self._lines then
local numLines = #self._lines
for i=1,numLines do
self._lines[i]:destroy()
self._lines[i] = nil
end
self._lines = nil
end
end
-- XXX
-- subclass for entities
-- query entity for icon, name, family, kind, and loop through a list of properties
-- then build tooltip based on these
-- so this class need methods for building the tooltip
--[[
all tooltips have this basic structure:
-------------------------------
| ICON TEXT (usually Name) | }
| TEXT or BLANK SPACE | }- This whole header area is optional
| BLANK SPACE | }
| TEXT or BAR |
| TEXT or BAR or BLANK SPACE |
| TEXT or BAR or BLANK SPACE |
| TEXT or BAR or BLANK SPACE |
| ... |
| TEXT or BAR |
-------------------------------
]]--
-- set icon
function Tooltip:setIcon(icon)
verifyClass('pud.ui.Frame', icon)
if self._icon then self._icon:destroy() end
self._icon = icon
self._icon:becomeChild(self, self._depth)
self:_adjustLayout()
self:_drawFB()
end
-- set header line 1
function Tooltip:setHeader1(text)
verifyClass('pud.ui.Text', text)
if self._header1 then self._header1:destroy() end
self._header1 = text
self._header1:becomeChild(self, self._depth)
self:_adjustLayout()
self:_drawFB()
end
-- set header line 2
function Tooltip:setHeader2(text)
verifyClass('pud.ui.Text', text)
if self._header2 then self._header2:destroy() end
self._header2 = text
self._header2:becomeChild(self, self._depth)
self:_adjustLayout()
self:_drawFB()
end
-- add a Text
function Tooltip:addText(text)
verifyClass('pud.ui.Text', text)
self:_addLine(text)
end
-- add a Bar
function Tooltip:addBar(bar)
verifyClass('pud.ui.Bar', bar)
self:_addLine(bar)
end
-- add a blank space
function Tooltip:addSpace()
local spacing = self:_getSpacing()
if spacing then
local space = Frame(0, 0, 0, spacing)
self:_addLine(space)
end
end
-- add a line to the tooltip
function Tooltip:_addLine(frame)
verifyClass('pud.ui.Frame', frame)
self._lines = self._lines or {}
self._lines[#self._lines + 1] = frame
frame:becomeChild(self, self._depth)
self:_adjustLayout()
self:_drawFB()
end
-- set the margin between the frame edge and the contents
function Tooltip:setMargin(margin)
verify('number', margin)
self._margin = margin
self:_adjustLayout()
self:_drawFB()
end
function Tooltip:_adjustLayout()
local numLines = self._lines and #self._lines or 0
if self._icon or self._header1 or self._header2 or numLines > 0 then
local x, y = self._margin, self._margin
local width, height = 0, 0
local spacing = self:_getSpacing()
if spacing then
local headerW, headerH, iconH = 0, 0, 0
if self._icon then
self._icon:setPosition(x, y)
iconH = self._icon:getHeight()
width = self._icon:getWidth() + spacing
x = width
end
if self._header1 then
self._header1:setPosition(x, y)
headerW = self._header1:getWidth()
headerH = headerH + spacing
y = y + spacing
end
if self._header2 then
self._header2:setPosition(x, y)
local h2width = self._header2:getWidth()
headerW = headerW > h2width and headerW or h2width
headerH = headerH + spacing
y = y + spacing
end
width = width + headerW
height = height + (headerH > iconH and headerH or iconH)
if numLines > 0 then
-- set some blank space if any headers exist
if self._icon or self._header1 or self._header2 then
height = height + spacing
y = y + spacing
end
x = self._margin
for i=1,numLines do
local line = self._lines[i]
line:setPosition(x, y)
local lineWidth = line:getWidth()
width = width > lineWidth and width or lineWidth
height = height + spacing
y = y + spacing
end -- for i=1,num
end -- if self._lines
width = width + self._margin*2
height = height + self._margin*2 -- XXX: might have an extra spacing
self:setSize(width, height)
self._ffb, self._bfb = nil, nil
end -- if spacing
end -- if self._icon or self._header1 or ...
end
function Tooltip:_getSpacing()
local spacing
local normalStyle = self:getNormalStyle()
if normalStyle then
local font = normalStyle:getFont()
if font then spacing = font:getHeight() end
end
if nil == spacing then warning('Please set Tooltip normal font style.') end
return spacing
end
-- draw in the foreground layer
-- draws over any foreground set in the Style. Usually, you just don't want to
-- set a foreground in the Style.
function Tooltip:_drawForeground()
Frame._drawForeground(self)
if self._icon then self._icon:draw() end
if self._header1 then self._header1:draw() end
if self._header2 then self._header2:draw() end
local numLines = self._lines and #self._lines or 0
if numLines > 0 then
for i=1,numLines do
local line = self._lines[i]
line:draw()
end
end
end
-- the class
return Tooltip
|
local Class = require 'lib.hump.class'
local Frame = getClass 'pud.ui.Frame'
local Text = getClass 'pud.ui.Text'
local Bar = getClass 'pud.ui.Bar'
-- Tooltip
--
local Tooltip = Class{name='Tooltip',
inherits=Frame,
function(self, ...)
Frame.construct(self, ...)
self._margin = 0
self:setDepth(5)
self:hide()
end
}
-- destructor
function Tooltip:destroy()
self:clear()
self._margin = nil
Frame.destroy(self)
end
-- clear the tooltip
function Tooltip:clear()
if self._header1 then
self._header1:destroy()
self._header1 = nil
end
if self._header2 then
self._header2:destroy()
self._header2 = nil
end
if self._icon then
self._icon:destroy()
self._icon = nil
end
if self._lines then
local numLines = #self._lines
for i=1,numLines do
self._lines[i]:destroy()
self._lines[i] = nil
end
self._lines = nil
end
end
-- XXX
-- subclass for entities
-- query entity for icon, name, family, kind, and loop through a list of properties
-- then build tooltip based on these
-- so this class need methods for building the tooltip
--[[
all tooltips have this basic structure:
-------------------------------
| ICON TEXT (usually Name) | }
| TEXT or BLANK SPACE | }- This whole header area is optional
| BLANK SPACE | }
| TEXT or BAR |
| TEXT or BAR or BLANK SPACE |
| TEXT or BAR or BLANK SPACE |
| TEXT or BAR or BLANK SPACE |
| ... |
| TEXT or BAR |
-------------------------------
]]--
-- set icon
function Tooltip:setIcon(icon)
verifyClass('pud.ui.Frame', icon)
if self._icon then self._icon:destroy() end
self._icon = icon
self._icon:becomeChild(self, self._depth)
self:_adjustLayout()
self:_drawFB()
end
-- set header line 1
function Tooltip:setHeader1(text)
verifyClass('pud.ui.Text', text)
if self._header1 then self._header1:destroy() end
self._header1 = text
self._header1:becomeChild(self, self._depth)
self:_adjustLayout()
self:_drawFB()
end
-- set header line 2
function Tooltip:setHeader2(text)
verifyClass('pud.ui.Text', text)
if self._header2 then self._header2:destroy() end
self._header2 = text
self._header2:becomeChild(self, self._depth)
self:_adjustLayout()
self:_drawFB()
end
-- add a Text
function Tooltip:addText(text)
verifyClass('pud.ui.Text', text)
self:_addLine(text)
end
-- add a Bar
function Tooltip:addBar(bar)
verifyClass('pud.ui.Bar', bar)
self:_addLine(bar)
end
-- add a blank space
function Tooltip:addSpace(size)
if nil == size then
size = self._lines and self._lines[1]:getHeight() or self._margin
end
verify('number', size)
local space = Frame(0, 0, 0, size)
self:_addLine(space)
end
-- add a line to the tooltip
function Tooltip:_addLine(frame)
verifyClass('pud.ui.Frame', frame)
self._lines = self._lines or {}
self._lines[#self._lines + 1] = frame
frame:becomeChild(self, self._depth)
self:_adjustLayout()
self:_drawFB()
end
-- set the margin between the frame edge and the contents
function Tooltip:setMargin(margin)
verify('number', margin)
self._margin = margin
self:_adjustLayout()
self:_drawFB()
end
function Tooltip:_adjustLayout()
local numLines = self._lines and #self._lines or 0
if self._icon or self._header1 or self._header2 or numLines > 0 then
local x, y = self._margin, self._margin
local width, height = 0, 0
local headerW, headerH, iconH = 0, 0, 0
if self._icon then
self._icon:setPosition(x, y)
iconH = self._icon:getHeight()
width = self._icon:getWidth() + self._margin
x = x + width
end
if self._header1 then
self._header1:setPosition(x, y)
headerW = self._header1:getWidth()
headerH = self._header1:getHeight()
y = y + headerH
end
if self._header2 then
self._header2:setPosition(x, y)
local h2width, h2height = self._header2:getSize()
headerW = headerW > h2width and headerW or h2width
headerH = headerH + h2height
y = y + h2height
end
width = width + headerW
height = height + (headerH > iconH and headerH or iconH)
if numLines > 0 then
-- set some blank space if any headers exist
if self._icon or self._header1 or self._header2 then
local blankspace = self._lines[1]:getHeight()
height = height + blankspace
y = self._margin + height
end
x = self._margin
for i=1,numLines do
local line = self._lines[i]
line:setPosition(x, y)
local lineWidth, lineHeight = line:getSize()
width = width > lineWidth and width or lineWidth
height = height + lineHeight
y = y + lineHeight
end -- for i=1,num
end -- if self._lines
width = width + self._margin*2
height = height + self._margin*2
self:setSize(width, height)
self._ffb, self._bfb = nil, nil
end -- if self._icon or self._header1 or ...
end
-- draw in the foreground layer
-- draws over any foreground set in the Style. Usually, you just don't want to
-- set a foreground in the Style.
function Tooltip:_drawForeground()
Frame._drawForeground(self)
if self._icon then self._icon:draw() end
if self._header1 then self._header1:draw() end
if self._header2 then self._header2:draw() end
local numLines = self._lines and #self._lines or 0
if numLines > 0 then
for i=1,numLines do
local line = self._lines[i]
line:draw()
end
end
end
-- the class
return Tooltip
|
fix tooltip spacing and margins to use element sizes
|
fix tooltip spacing and margins to use element sizes
|
Lua
|
mit
|
scottcs/wyx
|
e74603f51b1ebe8b30b11aef3df709ae678ad28f
|
httplib.lua
|
httplib.lua
|
local utils=require("utils")
local M = {
proxy=nil,
proxyport=nil,
M_GET="GET",
M_POST="POST",
M_PUT="PUT"
}
function M.geturl(arg)
local addr=arg.host
local path=arg.path
if path==nil then path="/" end
local resp=""
local method = M.M_GET
if arg.method ~= nil then method=arg.method end
local request = {
method.." "..path.." HTTP/1.1",
"Host: "..addr,
"Connection: close",
"Accept: */*" }
if arg.headers ~= nil then
for k,v in pairs(arg.headers) do
table.insert(request, v )
end
end
if (method==M.M_POST or method==M.M_PUT) and (arg.data~=nil) then
--request = request .. arg.data
table.insert(request, "Content-Length: "..string.len(arg.data) )
table.insert(request, "")
table.insert(request, arg.data)
else
table.insert(request, "")
end
conn=net.createConnection(net.TCP, 0)
conn:on("receive", function(conn, payload)
s, err = pcall(function() resp = resp..payload end)
if not s then
print("Error: "..err)
conn:close()
end
end )
conn:on("connection", function(c)
local s = utils.join(request, "\r\n");
--for i,s in pairs(request) do
-- print ("sending "..s)
--end
conn:send(s)
end)
conn:on("disconnection", function(c)
if arg.cb ~= nil then pcall( function() arg.cb(resp) end) end
end)
local realaddr = M.proxy~=nil and M.proxy or addr
local realport = M.proxyport~=nil and M.proxport or 80
conn:connect(realport, realaddr)
end
return M
|
local utils=require("utils")
local M = {
proxy=nil,
proxyport=nil,
M_GET="GET",
M_POST="POST",
M_PUT="PUT"
}
-- Build and return a table of the http response data
function M.parseHttpResponse (req)
local res = {}
res.headers = {}
local first = nil
local key, v, strt_ndx, end_ndx
local trim = utils.trim
local decode = utils.decodeUrl
local split = utils.split
--print("parsing string '"..req.."'")
for str in string.gmatch (req, "([^\n]+)") do
-- First line in the method and path
if (first == nil) then
first = 1
str = decode(str)
parts = split(str, " ")
res.code = tonumber(trim( parts[2] ) )
res.codetext = trim(parts[3])
res.request = req
res.httpVer = trim(parts[1])
else -- Process remaining ":" headers
strt_ndx, end_ndx = string.find (str, "([^:]+)")
if (end_ndx ~= nil) then
v = utils.trim (string.sub (str, end_ndx + 2))
key = utils.trim (string.sub (str, strt_ndx, end_ndx))
res.headers[key] = v
end
end
end
return res
end
function M.geturl(arg)
local addr=arg.host
local path=arg.path
local finished = false
if path==nil then path="/" end
local resp=""
local method = M.M_GET
if arg.method ~= nil then method=arg.method end
local request = {
method.." "..path.." HTTP/1.1",
"Host: "..addr,
"Connection: close",
"Accept: */*" }
if arg.headers ~= nil then
for k,v in pairs(arg.headers) do
table.insert(request, v )
end
end
if (method==M.M_POST or method==M.M_PUT) and (arg.data~=nil) then
--request = request .. arg.data
table.insert(request, "Content-Length: "..string.len(arg.data) )
table.insert(request, "")
table.insert(request, arg.data)
else
table.insert(request, "\r\n")
end
conn=net.createConnection(net.TCP, 0)
conn:on("receive", function(conn, payload)
local s, err = pcall(function() resp = resp..payload end)
if not s then
print("Error: "..err)
conn:close()
end
end )
conn:on("connection", function(c)
local s = utils.join(request, "\r\n")
--print ("Sending "..s)
conn:send(s)
end)
conn:on("disconnection", function(c)
local res=M.parseHttpResponse(resp)
if arg.cb ~= nil then
local s,err = pcall( function() arg.cb(res) end)
if not s then
print("Callback error: "..err)
conn:close()
end
end
end)
local realaddr = M.proxy~=nil and M.proxy or addr
local realport = M.proxyport~=nil and M.proxyport or 80
--print("Connecting to "..realaddr..":"..realport)
conn:connect(realport, realaddr)
if arg.blocking ~= nil and arg.blocking then
while not finished do
tmr.delay(500000)
end
end
end
return M
|
httplib parses server response fixed bug in table concatenation fixed bug in proxy port
|
httplib parses server response
fixed bug in table concatenation
fixed bug in proxy port
|
Lua
|
lgpl-2.1
|
positron96/esp8266-bootconfig
|
097cc43514fc1ede75cdc86a170613b302f8dcd1
|
src/lua/utils.lua
|
src/lua/utils.lua
|
-- functions used by different modules
function split(str, delim)
local ret = {}
local last_end = 1
local s, e = str:find(delim, 1)
while s do
if s ~= 1 then
cap = str:sub(last_end, e-1)
table.insert(ret, cap)
end
last_end = e+1
s, e = str:find(delim, last_end)
end
if last_end <= #str then
cap = str:sub(last_end)
table.insert(ret, cap)
end
return ret
end
function get_file_directory(str)
splitpath=split(str,"/")
local newpath = ""
if #splitpath > 1 then
for i = 1,#splitpath-1 do
newpath = newpath .. splitpath[i] .. "/"
end
end
return newpath
end
|
-- functions used by different modules
function split(str, delim)
local ret = {}
local last_end = 1
local s, e = str:find(delim, 1)
while s do
cap = str:sub(last_end, e-1)
table.insert(ret, cap)
last_end = e+1
s, e = str:find(delim, last_end)
end
if last_end <= #str then
cap = str:sub(last_end)
table.insert(ret, cap)
end
return ret
end
function get_file_directory(str)
local splitpath = split(str, "/")
local newpath = ""
if #splitpath > 1 then
for i = 1,#splitpath-1 do
newpath = newpath .. splitpath[i] .. "/"
end
end
return newpath
end
|
Fix path splitting for absolute path
|
Fix path splitting for absolute path
The absolute path was not split correctly and generated a relative path.
|
Lua
|
mpl-2.0
|
nabilbendafi/haka,lcheylus/haka,lcheylus/haka,haka-security/haka,nabilbendafi/haka,LubyRuffy/haka,haka-security/haka,Wingless-Archangel/haka,lcheylus/haka,nabilbendafi/haka,Wingless-Archangel/haka,haka-security/haka,LubyRuffy/haka
|
efe11b2a4260b39792435f0846a26ff952b10ee3
|
testbed/units.lua
|
testbed/units.lua
|
require "tundra.syntax.glob"
-- Used to generate the moc cpp files as needed for .h that uses Q_OBJECT
DefRule {
Name = "MocGeneration",
Pass = "GenerateSources",
Command = "$(QT5)/bin/moc $(<) -o $(@)",
Blueprint = {
Source = { Required = true, Type = "string", Help = "Input filename", },
OutName = { Required = true, Type = "string", Help = "Output filename", },
},
Setup = function (env, data)
return {
InputFiles = { data.Source },
OutputFiles = { "$(OBJECTDIR)/_generated/" .. data.OutName },
}
end,
}
-- Example 6502 emulator
Program {
Name = "Fake6502",
Env = {
CCOPTS = {
{ "-Wno-conversion", "-Wno-pedantic"; Config = "macosx-*-*" },
},
},
Sources = {
Glob {
Dir = "examples/Fake6502",
Extensions = { ".c", ".cpp", ".m" },
},
},
}
-- Core Lib
StaticLibrary {
Name = "core",
Env = {
CXXOPTS = {
{
"-Wno-global-constructors",
"-Wno-exit-time-destructors" ; Config = "macosx-clang-*" },
},
CPPPATH = { "src/frontend", "API" }
},
Sources = {
Glob {
Dir = "src/frontend/core",
Extensions = { ".c", ".cpp", ".m" },
},
},
}
---------- Plugins -----------------
SharedLibrary {
Name = "LLDBPlugin",
Env = {
CPPPATH = {
"API",
"plugins/lldb",
"plugins/lldb/Frameworks/LLDB.Framework/Headers",
},
CXXOPTS = {
{
"-std=c++11",
"-Wno-padded",
--"-Wno-documentation",
"-Wno-unused-parameter",
"-Wno-missing-prototypes",
"-Wno-unused-member-function",
"-Wno-c++98-compat-pedantic" ; Config = "macosx-clang-*" },
},
SHLIBOPTS = {
{ "-Fplugins/lldb/Frameworks", "-lstdc++"; Config = "macosx-clang-*" },
},
CXXCOM = { "-stdlib=libc++"; Config = "macosx-clang-*" },
},
Sources = {
Glob {
Dir = "plugins/lldb",
Extensions = { ".c", ".cpp", ".m" },
},
},
Frameworks = { "LLDB" },
}
------------------------------------
Program {
Name = "prodbg-qt5",
Env = {
CPPPATH = {
".",
"API",
"src/frontend",
"$(QT5)/include/QtWidgets",
"$(QT5)/include/QtGui",
"$(QT5)/include/QtCore",
"$(QT5)/include",
},
PROGOPTS = {
{ "/SUBSYSTEM:WINDOWS", "/DEBUG"; Config = { "win32-*-*", "win64-*-*" } },
},
CPPDEFS = {
{ "PRODBG_MAC", Config = "macosx-*-*" },
{ "PRODBG_WIN"; Config = { "win32-*-*", "win64-*-*" } },
},
CXXOPTS = {
{
--"-mmacosx-version-min=10.7",
"-std=gnu0x",
"-std=c++11",
"-stdlib=libc++",
"-Wno-padded",
<<<<<<< HEAD
"-Wno-c++98-compat",
"-Wno-c++98-compat-pedantic",
=======
"-Wno-extra-semi",
>>>>>>> WIP hex editor widget
"-Wno-global-constructors",
"-Wno-long-long",
"-Wno-unreachable-code",
"-Wno-float-equal",
"-Wno-disabled-macro-expansion",
"-Wno-conversion",
"-Wno-weak-vtables",
"-Wno-undefined-reinterpret-cast", -- needed for Qt signals :(
"-Wno-sign-conversion" ; Config = "macosx-clang-*" },
},
PROGCOM = {
-- hacky hacky
{ "-F$(QT5)/lib", "-lstdc++", "-rpath tundra-output$(SEP)macosx-clang-debug-default"; Config = "macosx-clang-*" },
},
},
Sources = {
FGlob {
Dir = "src/frontend/Qt5",
Extensions = { ".c", ".cpp", ".m" },
Filters = {
{ Pattern = "macosx"; Config = "macosx-*-*" },
{ Pattern = "windows"; Config = { "win32-*-*", "win64-*-*" } },
},
},
MocGeneration {
Source = "src/frontend/Qt5/Qt5CodeEditor.h",
OutName = "Qt5CodeEditor_moc.cpp"
},
MocGeneration {
Source = "src/frontend/Qt5/Qt5MainWindow.h",
OutName = "Qt5MainWindow_moc.cpp"
},
MocGeneration {
Source = "src/frontend/Qt5/Qt5HexEditWindow.h",
OutName = "Qt5HexEditWindow_moc.cpp"
},
MocGeneration {
Source = "src/frontend/Qt5/Qt5HexEditInternal.h",
OutName = "Qt5HexEditInternal_moc.cpp"
},
MocGeneration {
Source = "src/frontend/Qt5/Qt5HexEditWidget.h",
OutName = "Qt5HexEditWidget_moc.cpp"
},
},
Depends = { "core" },
Libs = { { "wsock32.lib", "kernel32.lib", "user32.lib", "gdi32.lib", "Comdlg32.lib", "Advapi32.lib" ; Config = "win32-*-*" } },
Frameworks = { "Cocoa", "QtWidgets", "QtGui", "QtCore", "QtConcurrent" },
}
Default "LLDBPlugin"
Default "Fake6502"
Default "prodbg-qt5"
|
require "tundra.syntax.glob"
-- Used to generate the moc cpp files as needed for .h that uses Q_OBJECT
DefRule {
Name = "MocGeneration",
Pass = "GenerateSources",
Command = "$(QT5)/bin/moc $(<) -o $(@)",
Blueprint = {
Source = { Required = true, Type = "string", Help = "Input filename", },
OutName = { Required = true, Type = "string", Help = "Output filename", },
},
Setup = function (env, data)
return {
InputFiles = { data.Source },
OutputFiles = { "$(OBJECTDIR)/_generated/" .. data.OutName },
}
end,
}
-- Example 6502 emulator
Program {
Name = "Fake6502",
Env = {
CCOPTS = {
{ "-Wno-conversion", "-Wno-pedantic"; Config = "macosx-*-*" },
},
},
Sources = {
Glob {
Dir = "examples/Fake6502",
Extensions = { ".c", ".cpp", ".m" },
},
},
}
-- Core Lib
StaticLibrary {
Name = "core",
Env = {
CXXOPTS = {
{
"-Wno-global-constructors",
"-Wno-exit-time-destructors" ; Config = "macosx-clang-*" },
},
CPPPATH = { "src/frontend", "API" }
},
Sources = {
Glob {
Dir = "src/frontend/core",
Extensions = { ".c", ".cpp", ".m" },
},
},
}
---------- Plugins -----------------
SharedLibrary {
Name = "LLDBPlugin",
Env = {
CPPPATH = {
"API",
"plugins/lldb",
"plugins/lldb/Frameworks/LLDB.Framework/Headers",
},
CXXOPTS = {
{
"-std=c++11",
"-Wno-padded",
"-Wno-documentation",
"-Wno-unused-parameter",
"-Wno-missing-prototypes",
"-Wno-unused-member-function",
"-Wno-c++98-compat-pedantic" ; Config = "macosx-clang-*" },
},
SHLIBOPTS = {
{ "-Fplugins/lldb/Frameworks", "-lstdc++"; Config = "macosx-clang-*" },
},
CXXCOM = { "-stdlib=libc++"; Config = "macosx-clang-*" },
},
Sources = {
Glob {
Dir = "plugins/lldb",
Extensions = { ".c", ".cpp", ".m" },
},
},
Frameworks = { "LLDB" },
}
------------------------------------
Program {
Name = "prodbg-qt5",
Env = {
CPPPATH = {
".",
"API",
"src/frontend",
"$(QT5)/include/QtWidgets",
"$(QT5)/include/QtGui",
"$(QT5)/include/QtCore",
"$(QT5)/include",
},
PROGOPTS = {
{ "/SUBSYSTEM:WINDOWS", "/DEBUG"; Config = { "win32-*-*", "win64-*-*" } },
},
CPPDEFS = {
{ "PRODBG_MAC", Config = "macosx-*-*" },
{ "PRODBG_WIN"; Config = { "win32-*-*", "win64-*-*" } },
},
CXXOPTS = {
{
--"-mmacosx-version-min=10.7",
"-std=gnu0x",
"-std=c++11",
"-stdlib=libc++",
"-Wno-padded",
"-Wno-c++98-compat",
"-Wno-c++98-compat-pedantic",
"-Wno-global-constructors",
"-Wno-long-long",
"-Wno-unreachable-code",
"-Wno-float-equal",
"-Wno-disabled-macro-expansion",
"-Wno-conversion",
"-Wno-weak-vtables",
"-Wno-extra-semi",
"-Wno-undefined-reinterpret-cast", -- needed for Qt signals :(
"-Wno-sign-conversion" ; Config = "macosx-clang-*" },
},
PROGCOM = {
-- hacky hacky
{ "-F$(QT5)/lib", "-lstdc++", "-rpath tundra-output$(SEP)macosx-clang-debug-default"; Config = "macosx-clang-*" },
},
},
Sources = {
FGlob {
Dir = "src/frontend/Qt5",
Extensions = { ".c", ".cpp", ".m" },
Filters = {
{ Pattern = "macosx"; Config = "macosx-*-*" },
{ Pattern = "windows"; Config = { "win32-*-*", "win64-*-*" } },
},
},
MocGeneration {
Source = "src/frontend/Qt5/Qt5CodeEditor.h",
OutName = "Qt5CodeEditor_moc.cpp"
},
MocGeneration {
Source = "src/frontend/Qt5/Qt5MainWindow.h",
OutName = "Qt5MainWindow_moc.cpp"
},
MocGeneration {
Source = "src/frontend/Qt5/Qt5HexEditWindow.h",
OutName = "Qt5HexEditWindow_moc.cpp"
},
MocGeneration {
Source = "src/frontend/Qt5/Qt5HexEditInternal.h",
OutName = "Qt5HexEditInternal_moc.cpp"
},
MocGeneration {
Source = "src/frontend/Qt5/Qt5HexEditWidget.h",
OutName = "Qt5HexEditWidget_moc.cpp"
},
},
Depends = { "core" },
Libs = { { "wsock32.lib", "kernel32.lib", "user32.lib", "gdi32.lib", "Comdlg32.lib", "Advapi32.lib" ; Config = "win32-*-*" } },
Frameworks = { "Cocoa", "QtWidgets", "QtGui", "QtCore", "QtConcurrent" },
}
Default "LLDBPlugin"
Default "Fake6502"
Default "prodbg-qt5"
|
Fix bad merge of units.lua
|
Fix bad merge of units.lua
|
Lua
|
mit
|
emoon/ProDBG,kondrak/ProDBG,ashemedai/ProDBG,v3n/ProDBG,SlNPacifist/ProDBG,emoon/ProDBG,kondrak/ProDBG,ashemedai/ProDBG,RobertoMalatesta/ProDBG,RobertoMalatesta/ProDBG,SlNPacifist/ProDBG,RobertoMalatesta/ProDBG,SlNPacifist/ProDBG,v3n/ProDBG,kondrak/ProDBG,ashemedai/ProDBG,emoon/ProDBG,RobertoMalatesta/ProDBG,emoon/ProDBG,v3n/ProDBG,ashemedai/ProDBG,SlNPacifist/ProDBG,ashemedai/ProDBG,kondrak/ProDBG,v3n/ProDBG,v3n/ProDBG,SlNPacifist/ProDBG,emoon/ProDBG,kondrak/ProDBG,v3n/ProDBG,SlNPacifist/ProDBG,RobertoMalatesta/ProDBG,kondrak/ProDBG,ashemedai/ProDBG,emoon/ProDBG
|
62cd2078d541bc8addcec9e0499cc8776dad9c51
|
onmt/modules/DBiEncoder.lua
|
onmt/modules/DBiEncoder.lua
|
--[[ DBiEncoder is a deep bidirectional Sequencer used for the source language.
--]]
local DBiEncoder, parent = torch.class('onmt.DBiEncoder', 'nn.Container')
local options = {}
function DBiEncoder.declareOpts(cmd)
onmt.BiEncoder.declareOpts(cmd)
cmd:setCmdLineOptions(options)
end
--[[ Create a deep bidirectional encoder - each layers reconnect before starting another bidirectional layer
Parameters:
* `args` - global arguments
* `input` - input neural network.
]]
function DBiEncoder:__init(args, input)
parent.__init(self)
self.args = onmt.utils.ExtendedCmdLine.getModuleOpts(args, options)
self.args.layers = args.layers
self.args.dropout = args.dropout
local dropout_input = args.dropout_input
self.layers = {}
args.layers = 1
args.brnn_merge = 'sum'
for _= 1, self.args.layers do
table.insert(self.layers, onmt.BiEncoder(args, input))
local identity = nn.Identity()
identity.inputSize = args.rnn_size
input = identity
self:add(self.layers[#self.layers])
-- trick to force a dropout on each layer L > 1
if #self.layers == 1 and args.dropout > 0 then
args.dropout_input = true
end
end
args.layers = self.args.layers
self.args.numEffectiveLayers = self.layers[1].args.numEffectiveLayers * self.args.layers
self.args.hiddenSize = args.rnn_size
args.dropout_input = dropout_input
self:resetPreallocation()
end
--[[ Return a new DBiEncoder using the serialized data `pretrained`. ]]
function DBiEncoder.load(pretrained)
local self = torch.factory('onmt.DBiEncoder')()
parent.__init(self)
self.layers = {}
for i=1, #pretrained.layers do
self.layers[i] = onmt.BiEncoder.load(pretrained.layers[i])
end
self.args = pretrained.args
self:resetPreallocation()
return self
end
--[[ Return data to serialize. ]]
function DBiEncoder:serialize()
local layersData = {}
for i = 1, #self.layers do
table.insert(layersData, self.layers[i]:serialize())
end
return {
name = 'DBiEncoder',
layers = layersData,
args = self.args
}
end
function DBiEncoder:resetPreallocation()
-- Prototype for preallocated full context vector.
self.contextProto = torch.Tensor()
-- Prototype for preallocated full hidden states tensors.
self.stateProto = torch.Tensor()
-- Prototype for preallocated gradient context
self.gradContextProto = torch.Tensor()
end
function DBiEncoder:maskPadding()
self.layers[1]:maskPadding()
end
function DBiEncoder:forward(batch)
if self.statesProto == nil then
self.statesProto = onmt.utils.Tensor.initTensorTable(self.args.numEffectiveLayers,
self.stateProto,
{ batch.size, self.args.hiddenSize })
end
local states = onmt.utils.Tensor.reuseTensorTable(self.statesProto, { batch.size, self.args.hiddenSize })
local context = onmt.utils.Tensor.reuseTensor(self.contextProto,
{ batch.size, batch.sourceLength, self.args.hiddenSize })
local stateIdx = 1
self.inputs = { batch }
self.lranges = {}
for i = 1,#self.layers do
local layerStates, layerContext = self.layers[i]:forward(self.inputs[i])
if i ~= #self.layers then
table.insert(self.inputs, onmt.data.BatchTensor.new(layerContext))
else
context:copy(layerContext)
end
table.insert(self.lranges, {stateIdx, #layerStates})
for j = 1,#layerStates do
states[stateIdx]:copy(layerStates[j])
stateIdx = stateIdx + 1
end
end
return states, context
end
function DBiEncoder:backward(batch, gradStatesOutput, gradContextOutput)
local gradInputs
for i = #self.layers, 1, -1 do
local lrange_gradStatesOutput
if gradStatesOutput then
lrange_gradStatesOutput = gradStatesOutput[{}]
end
gradInputs = self.layers[i]:backward(self.inputs[i], lrange_gradStatesOutput, gradContextOutput)
if i ~= 1 then
gradContextOutput = onmt.utils.Tensor.reuseTensor(self.gradContextProto,
{ batch.size, #gradInputs, self.args.hiddenSize })
for t = 1, #gradInputs do
gradContextOutput[{{},t,{}}]:copy(gradInputs[t])
end
end
end
return gradInputs
end
|
--[[ DBiEncoder is a deep bidirectional Sequencer used for the source language.
--]]
local DBiEncoder, parent = torch.class('onmt.DBiEncoder', 'nn.Container')
local options = {}
function DBiEncoder.declareOpts(cmd)
onmt.BiEncoder.declareOpts(cmd)
cmd:setCmdLineOptions(options)
end
--[[ Create a deep bidirectional encoder - each layers reconnect before starting another bidirectional layer
Parameters:
* `args` - global arguments
* `input` - input neural network.
]]
function DBiEncoder:__init(args, input)
parent.__init(self)
self.args = onmt.utils.ExtendedCmdLine.getModuleOpts(args, options)
self.args.layers = args.layers
self.args.dropout = args.dropout
local dropout_input = args.dropout_input
self.layers = {}
args.layers = 1
args.brnn_merge = 'sum'
for _= 1, self.args.layers do
table.insert(self.layers, onmt.BiEncoder(args, input))
local identity = nn.Identity()
identity.inputSize = args.rnn_size
input = identity
self:add(self.layers[#self.layers])
-- trick to force a dropout on each layer L > 1
if #self.layers == 1 and args.dropout > 0 then
args.dropout_input = true
end
end
args.layers = self.args.layers
self.args.numEffectiveLayers = self.layers[1].args.numEffectiveLayers * self.args.layers
self.args.hiddenSize = args.rnn_size
args.dropout_input = dropout_input
self:resetPreallocation()
end
--[[ Return a new DBiEncoder using the serialized data `pretrained`. ]]
function DBiEncoder.load(pretrained)
local self = torch.factory('onmt.DBiEncoder')()
parent.__init(self)
self.layers = {}
for i=1, #pretrained.layers do
self.layers[i] = onmt.BiEncoder.load(pretrained.layers[i])
end
self.args = pretrained.args
self:resetPreallocation()
return self
end
--[[ Return data to serialize. ]]
function DBiEncoder:serialize()
local layersData = {}
for i = 1, #self.layers do
table.insert(layersData, self.layers[i]:serialize())
end
return {
name = 'DBiEncoder',
layers = layersData,
args = self.args
}
end
function DBiEncoder:resetPreallocation()
-- Prototype for preallocated full context vector.
self.contextProto = torch.Tensor()
-- Prototype for preallocated full hidden states tensors.
self.stateProto = torch.Tensor()
-- Prototype for preallocated gradient context
self.gradContextProto = torch.Tensor()
end
function DBiEncoder:maskPadding()
for _, layer in ipairs(self.layers) do
layer:maskPadding()
end
end
function DBiEncoder:forward(batch)
if self.statesProto == nil then
self.statesProto = onmt.utils.Tensor.initTensorTable(self.args.numEffectiveLayers,
self.stateProto,
{ batch.size, self.args.hiddenSize })
end
local states = onmt.utils.Tensor.reuseTensorTable(self.statesProto, { batch.size, self.args.hiddenSize })
local context = onmt.utils.Tensor.reuseTensor(self.contextProto,
{ batch.size, batch.sourceLength, self.args.hiddenSize })
local stateIdx = 1
self.inputs = { batch }
self.lranges = {}
for i = 1,#self.layers do
local layerStates, layerContext = self.layers[i]:forward(self.inputs[i])
if i ~= #self.layers then
table.insert(self.inputs, onmt.data.BatchTensor.new(layerContext, batch.sourceSize))
else
context:copy(layerContext)
end
table.insert(self.lranges, {stateIdx, #layerStates})
for j = 1,#layerStates do
states[stateIdx]:copy(layerStates[j])
stateIdx = stateIdx + 1
end
end
return states, context
end
function DBiEncoder:backward(batch, gradStatesOutput, gradContextOutput)
local gradInputs
for i = #self.layers, 1, -1 do
local lrange_gradStatesOutput
if gradStatesOutput then
lrange_gradStatesOutput = gradStatesOutput[{}]
end
gradInputs = self.layers[i]:backward(self.inputs[i], lrange_gradStatesOutput, gradContextOutput)
if i ~= 1 then
gradContextOutput = onmt.utils.Tensor.reuseTensor(self.gradContextProto,
{ batch.size, #gradInputs, self.args.hiddenSize })
for t = 1, #gradInputs do
gradContextOutput[{{},t,{}}]:copy(gradInputs[t])
end
end
end
return gradInputs
end
|
Fix DBiEncoder padding masking
|
Fix DBiEncoder padding masking
|
Lua
|
mit
|
monsieurzhang/OpenNMT,jsenellart/OpenNMT,da03/OpenNMT,da03/OpenNMT,jsenellart-systran/OpenNMT,jungikim/OpenNMT,jungikim/OpenNMT,OpenNMT/OpenNMT,jsenellart-systran/OpenNMT,da03/OpenNMT,monsieurzhang/OpenNMT,OpenNMT/OpenNMT,jsenellart/OpenNMT,monsieurzhang/OpenNMT,jsenellart-systran/OpenNMT,OpenNMT/OpenNMT,jsenellart/OpenNMT,jungikim/OpenNMT
|
dcf768b496b272ae2a21735abc26312eef12efc9
|
CCLib/src/java/lang/native/HashMap.lua
|
CCLib/src/java/lang/native/HashMap.lua
|
natives["java.util.HashMap"] = natives["java.util.HashMap"] or {}
local tables = {}
natives["java.util.HashMap"]["putHash(Ljava/lang/Object;ILjava/lang/Object;)Ljava/lang/Object;"] = function(this, key, hash, value)
tables[this] = tables[this] or {}
local bucket = tables[this][hash]
local previous = nil
if not bucket then
bucket = {{key, value}}
elseif #bucket == 1 then
local jKeyEquals = findMethod(key[1], "equals(Ljava/lang/Object;)Z")[1]
local ret, exception = jKeyEquals(key, bucket[1][1])
if exception then return nil, exception end
if ret == 1 then
bucket[1][2] = value
else
table.insert(bucket, {key, value})
end
else
local jKeyEquals = findMethod(key[1], "equals(Ljava/lang/Object;)Z")[1]
local found = false
for _, j in pairs(bucket) do
local ret, exception = jKeyEquals(key, j[1])
if exception then return nil, exception end
if ret == 1 then
found = true
previous = j[2]
j[2] = value
end
end
if not found then
table.insert(bucket, {key, value})
end
end
end
natives["java.util.HashMap"]["getHash(Ljava/lang/Object;I)Ljava/lang/Object;"] = function(this, key, hash)
if tables[this] == nil then
return nil
end
local bucket = tables[this][hash]
if not bucket then
return nil
elseif #bucket == 1 then
return bucket[1][2]
else
local jKeyEquals = findMethod(key[1], "equals(Ljava/lang/Object;)Z")[1]
for _, i in pairs(bucket) do
local ret, exc = jKeyEquals(key, i[1])
if exc then return nil, exc end
if ret == 1 then
return i[2]
end
end
end
end
|
natives["java.util.HashMap"] = natives["java.util.HashMap"] or {}
local tables = {}
natives["java.util.HashMap"]["putHash(Ljava/lang/Object;ILjava/lang/Object;)Ljava/lang/Object;"] = function(this, key, hash, value)
tables[this] = tables[this] or {}
local bucket = tables[this][hash]
local previous = nil
if not bucket then
bucket = {{key, value}}
elseif #bucket == 1 then
local jKeyEquals = findMethod(key[1], "equals(Ljava/lang/Object;)Z")[1]
local ret, exception = jKeyEquals(key, bucket[1][1])
if exception then return nil, exception end
if ret == 1 then
bucket[1][2] = value
else
table.insert(bucket, {key, value})
end
else
local jKeyEquals = findMethod(key[1], "equals(Ljava/lang/Object;)Z")[1]
local found = false
for _, j in pairs(bucket) do
local ret, exception = jKeyEquals(key, j[1])
if exception then return nil, exception end
if ret == 1 then
found = true
previous = j[2]
j[2] = value
end
end
if not found then
table.insert(bucket, {key, value})
end
end
tables[this][hash] = bucket
end
natives["java.util.HashMap"]["getHash(Ljava/lang/Object;I)Ljava/lang/Object;"] = function(this, key, hash)
if tables[this] == nil then
return nil
end
local bucket = tables[this][hash]
if not bucket then
return nil
elseif #bucket == 1 then
return bucket[1][2]
else
local jKeyEquals = findMethod(key[1], "equals(Ljava/lang/Object;)Z")[1]
for _, i in pairs(bucket) do
local ret, exc = jKeyEquals(key, i[1])
if exc then return nil, exc end
if ret == 1 then
return i[2]
end
end
end
end
|
Fixed saving of changed buckets. Broken by pervious commit
|
Fixed saving of changed buckets. Broken by pervious commit
|
Lua
|
mit
|
Team-CC-Corp/JVML-JIT,apemanzilla/JVML-JIT
|
b9174f708bc8af38343cf709daa819550fbac32e
|
spec/parser.lua
|
spec/parser.lua
|
describe('Test the parser', function()
local ini = require 'ini'
it('basic test', function()
assert.same({'a_key', 'this is the value for this set'}, ini.parse('a_key = this is the value for this set'))
assert.same({'this_is_a_section_test'}, ini.parse('[this_is_a_section_test]'))
assert.same({';',' this is a comment test'},ini.parse('; this is a comment test'))
end)
it('section', function()
assert.same({'section_test'}, ini.parse('[section_test]'))
assert.same({'section_test1'}, ini.parse('[section_test1]')) -- test digit
assert.same({'s1ection_test'}, ini.parse('[s1ection_test]')) -- test digit
assert.same({'section_test'}, ini.parse('[ section_test ] ')) -- test space
assert.is_nil(ini.parse('[test_section'))
-- assert.is_nil(ini.parse('test_section]'))
assert.is_nil(ini.parse('[1my_section_test]')) -- fail because starts with a digit
end)
it('Multi-lines string',function()
local t = ini.parse[[
; this is a comment
[opengl]
fullscreen = true
window = 200,200
]]
assert.same(t,{
';',
' this is a comment',
'opengl',
'fullscreen',
'true',
'window',
'200,200'
})
end)
end)
describe('Pattern tests', function()
local lpeg = require 'lpeg'
local P = lpeg.P
local C = lpeg.C
local Ct = lpeg.Ct
local space = lpeg.space
local digit = lpeg.digit
local alpha = lpeg.alpha
local _alpha = P('_') + alpha -- match one alpha or underscore character
it('alpha', function()
assert.equals(_alpha:match('a'), 2)
assert.equals(_alpha:match('A'), 2)
assert.equals(_alpha:match('abc'), 2)
assert.equals(_alpha:match('_'), 2)
-- Must fail
assert.is_nil(_alpha:match(' '))
assert.is_nil(_alpha:match('1'))
end)
local key = C(_alpha^1 * (_alpha + digit)^0) * space^0
it('key', function()
assert.equals('_', key:match('_'))
assert.equals('a', key:match('a'))
assert.equals('_aA', key:match('_aA'))
assert.equals('_Aa', key:match('_Aa'))
assert.equals('_1', key:match('_1'))
assert.equals('mykey', key:match('mykey'))
assert.equals('my_key', key:match('my_key'))
assert.equals('_my_key', key:match('_my_key'))
assert.equals('mykey_', key:match('mykey_'))
assert.equals('my_key_1', key:match('my_key_1'))
assert.equals('mykey1', key:match('mykey1'))
assert.equals('m1ykey', key:match('m1ykey'))
assert.equals('_1mykey', key:match('_1mykey'))
assert.equals('my_key', key:match('my_key ')) -- trailing space
assert.equals('my', key:match('my key ')) -- TODO should succeed?
-- Must fail
assert.is_nil(key:match(''))
assert.is_nil(key:match(' '))
assert.is_nil(key:match('1'))
assert.is_nil(key:match('[my_key]'))
end)
-- it('set', function()
-- local s = spy.new(function(s) return key:match(s) end)
-- s('name = value')
-- print(key:match('name = value'))
-- assert.spy(s).returned_with('name')
-- end)
local section = P'['^1 * space^0 * key * space^0 * P']'^1 * space^0
it('section', function()
assert.equals(section:match('[section_test]'), 'section_test')
assert.equals(section:match('[_section_test]'), '_section_test')
assert.equals(section:match('[ _section_test ] '), '_section_test')
assert.equals(section:match('[_1section_test]'), '_1section_test')
assert.equals(section:match('[section_test1]'), 'section_test1')
assert.equals(section:match('[section1_test]'), 'section1_test')
end)
end)
|
describe('Test the parser', function()
local ini = require 'ini'
it('basic test', function()
assert.same({'a_key', 'this is the value for this set'}, ini.parse('a_key = this is the value for this set'))
assert.same({'this_is_a_section_test'}, ini.parse('[this_is_a_section_test]'))
assert.same({';',' this is a comment test'},ini.parse('; this is a comment test'))
end)
it('section', function()
assert.same({'section_test'}, ini.parse('[section_test]'))
assert.same({'section_test1'}, ini.parse('[section_test1]')) -- test digit
assert.same({'s1ection_test'}, ini.parse('[s1ection_test]')) -- test digit
assert.same({'section_test'}, ini.parse('[ section_test ] ')) -- test space
assert.is_nil(ini.parse('[test_section'))
-- assert.is_nil(ini.parse('test_section]'))
assert.is_nil(ini.parse('[1my_section_test]')) -- fail because starts with a digit
end)
it('Multi-lines string',function()
assert.same({
';',
' this is a comment',
'opengl',
'fullscreen',
'true',
'window',
'200,200'
}, ini.parse[[
; this is a comment
[opengl]
fullscreen = true
window = 200,200
]])
end)
end)
describe('Pattern tests', function()
local lpeg = require 'lpeg'
local P = lpeg.P
local C = lpeg.C
local Ct = lpeg.Ct
local space = lpeg.space
local digit = lpeg.digit
local alpha = lpeg.alpha
local _alpha = P('_') + alpha -- match one alpha or underscore character
it('alpha', function()
assert.equals(_alpha:match('a'), 2)
assert.equals(_alpha:match('A'), 2)
assert.equals(_alpha:match('abc'), 2)
assert.equals(_alpha:match('_'), 2)
-- Must fail
assert.is_nil(_alpha:match(' '))
assert.is_nil(_alpha:match('1'))
end)
local key = C(_alpha^1 * (_alpha + digit)^0) * space^0
it('key', function()
assert.equals('_', key:match('_'))
assert.equals('a', key:match('a'))
assert.equals('_aA', key:match('_aA'))
assert.equals('_Aa', key:match('_Aa'))
assert.equals('_1', key:match('_1'))
assert.equals('mykey', key:match('mykey'))
assert.equals('my_key', key:match('my_key'))
assert.equals('_my_key', key:match('_my_key'))
assert.equals('mykey_', key:match('mykey_'))
assert.equals('my_key_1', key:match('my_key_1'))
assert.equals('mykey1', key:match('mykey1'))
assert.equals('m1ykey', key:match('m1ykey'))
assert.equals('_1mykey', key:match('_1mykey'))
assert.equals('my_key', key:match('my_key ')) -- trailing space
assert.equals('my', key:match('my key ')) -- TODO should succeed?
-- Must fail
assert.is_nil(key:match(''))
assert.is_nil(key:match(' '))
assert.is_nil(key:match('1'))
assert.is_nil(key:match('[my_key]'))
end)
-- it('set', function()
-- local s = spy.new(function(s) return key:match(s) end)
-- s('name = value')
-- print(key:match('name = value'))
-- assert.spy(s).returned_with('name')
-- end)
local section = P'['^1 * space^0 * key * space^0 * P']'^1 * space^0
it('section', function()
assert.equals(section:match('[section_test]'), 'section_test')
assert.equals(section:match('[_section_test]'), '_section_test')
assert.equals(section:match('[ _section_test ] '), '_section_test')
assert.equals(section:match('[_1section_test]'), '_1section_test')
assert.equals(section:match('[section_test1]'), 'section_test1')
assert.equals(section:match('[section1_test]'), 'section1_test')
end)
end)
|
Fix inverted expeted and passed value
|
Fix inverted expeted and passed value
|
Lua
|
mit
|
lzubiaur/ini.lua
|
bc313ec8d6d8d7d70b6e85a9546c937c0dd18d24
|
state/loadmenu.lua
|
state/loadmenu.lua
|
--[[--
LOAD MENU STATE
----
Display the load menu.
--]]--
local st = RunState.new()
local mt = {__tostring = function() return 'RunState.loadmenu' end}
setmetatable(st, mt)
local InputCommandEvent = getClass 'wyx.event.InputCommandEvent'
local LoadMenuUI = getClass 'wyx.ui.LoadMenuUI'
function st:init() end
function st:enter(prevState, world)
InputEvents:register(self, InputCommandEvent)
if Console then Console:hide() end
self._ui = LoadMenuUI(UI.LoadMenu)
self._world = world
end
function st:leave()
InputEvents:unregisterAll(self)
self._world = nil
if self._ui then
self._ui:destroy()
self._ui = nil
end
end
function st:destroy() end
function st:update(dt)
UISystem:update(dt)
end
function st:draw()
UISystem:draw()
if Console then Console:draw() end
end
function st:InputCommandEvent(e)
local cmd = e:getCommand()
--local args = e:getCommandArgs()
local continue = false
-- commands that work regardless of console visibility
switch(cmd) {
CONSOLE_TOGGLE = function() Console:toggle() end,
default = function() continue = true end,
}
if not continue then return end
-- commands that only work when console is visible
if Console:isVisible() then
switch(cmd) {
CONSOLE_HIDE = function() Console:hide() end,
CONSOLE_PAGEUP = function() Console:pageup() end,
CONSOLE_PAGEDOWN = function() Console:pagedown() end,
CONSOLE_TOP = function() Console:top() end,
CONSOLE_BOTTOM = function() Console:bottom() end,
CONSOLE_CLEAR = function() Console:clear() end,
}
else
switch(cmd) {
-- run state
EXIT_MENU = function()
RunState.switch(State.menu)
end,
DELETE_GAME = function()
if self._ui then
local file, wyx = self._ui:getSelectedFile()
if file then
if not love.filesystem.remove(file) then
warning('Could not remove file: %q', file)
end
end
if wyx then
if love.filesystem.remove(wyx) then
self._ui:destroy()
self._ui = LoadMenuUI(UI.LoadMenu)
else
warning('Could not remove file: %q', wyx)
end
end
end
end,
LOAD_GAME = function()
if self._ui then
local file, wyx = self._ui:getSelectedFile()
if file then
self._world.FILENAME = file
self._world.WYXNAME = wyx
RunState.switch(State.loadgame, self._world)
else
warning('Could not load file: %q', file)
end
end
end,
}
end
end
return st
|
--[[--
LOAD MENU STATE
----
Display the load menu.
--]]--
local st = RunState.new()
local mt = {__tostring = function() return 'RunState.loadmenu' end}
setmetatable(st, mt)
local InputCommandEvent = getClass 'wyx.event.InputCommandEvent'
local LoadMenuUI = getClass 'wyx.ui.LoadMenuUI'
function st:init() end
function st:enter(prevState, world)
InputEvents:register(self, InputCommandEvent)
if Console then Console:hide() end
self._ui = LoadMenuUI(UI.LoadMenu)
self._world = world
end
function st:leave()
InputEvents:unregisterAll(self)
self._world = nil
if self._ui then
self._ui:destroy()
self._ui = nil
end
end
function st:destroy() end
function st:update(dt)
UISystem:update(dt)
end
function st:draw()
UISystem:draw()
if Console then Console:draw() end
end
function st:InputCommandEvent(e)
local cmd = e:getCommand()
--local args = e:getCommandArgs()
local continue = false
-- commands that work regardless of console visibility
switch(cmd) {
CONSOLE_TOGGLE = function() Console:toggle() end,
default = function() continue = true end,
}
if not continue then return end
-- commands that only work when console is visible
if Console:isVisible() then
switch(cmd) {
CONSOLE_HIDE = function() Console:hide() end,
CONSOLE_PAGEUP = function() Console:pageup() end,
CONSOLE_PAGEDOWN = function() Console:pagedown() end,
CONSOLE_TOP = function() Console:top() end,
CONSOLE_BOTTOM = function() Console:bottom() end,
CONSOLE_CLEAR = function() Console:clear() end,
}
else
switch(cmd) {
-- run state
EXIT_MENU = function()
RunState.switch(State.menu)
end,
DELETE_GAME = function()
if self._ui then
local file, wyx = self._ui:getSelectedFile()
if file then
if not love.filesystem.remove(file) then
warning('Could not remove file: %q', file)
end
end
if wyx then
if love.filesystem.remove(wyx) then
self._ui:destroy()
self._ui = LoadMenuUI(UI.LoadMenu)
else
warning('Could not remove file: %q', wyx)
end
end
end
end,
LOAD_GAME = function()
if self._ui then
local file, wyx = self._ui:getSelectedFile()
if file then
self._world.FILENAME = file
self._world.WYXNAME = wyx
RunState.switch(State.loadgame, self._world)
end
end
end,
}
end
end
return st
|
fix load button crash when no file selected
|
fix load button crash when no file selected
|
Lua
|
mit
|
scottcs/wyx
|
8e82d024ca0136b6b849910fd48c18a3de42eb16
|
share/lua/sd/appletrailers.lua
|
share/lua/sd/appletrailers.lua
|
--[[
$Id$
Copyright © 2010 VideoLAN and AUTHORS
Authors: Ilkka Ollakka <ileoo at videolan dot org >
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
function descriptor()
return { title="Apple Trailers" }
end
function find( haystack, needle )
local _,_,r = string.find( haystack, needle )
return r
end
function main()
fd = vlc.stream( "http://trailers.apple.com/trailers/home/feeds/just_hd.json" )
if not fd then return nil end
options = {":http-user-agent=QuickTime/7.2 vlc edition",":demux=avformat,ffmpeg",":play-and-pause"}
line = fd:readline()
while line ~= nil
do
if string.match( line, "title" ) then
title = vlc.strings.resolve_xml_special_chars( find( line, "title\":\"(.-)\""))
art = find( line, "poster\":\"(.-)\"")
url = find( line, "url\":\"(.-)\"")
playlist = vlc.stream( "http://trailers.apple.com"..url.."includes/playlists/web.inc" )
if not playlist then
vlc.msg.info("Didn't get playlist...")
end
node = vlc.sd.add_node( {title=title,arturl=art} )
playlistline = playlist:readline()
description =""
if not playlistline then vlc.msg.info("Empty playlists-file") end
while playlistline ~= nil
do
if string.match( playlistline, "class=\".-first" ) then
description = find( playlistline, "h%d.->(.-)</h%d")
end
if string.match( playlistline, "class=\"hd\".-\.mov") then
for urlline,resolution in string.gmatch(playlistline, "class=\"hd\".-href=\"(.-.mov)\".-(%d+.-p)") do
urlline = string.gsub( urlline, "_"..resolution, "_h"..resolution )
node:add_subitem( {path = urlline,
title=title.." "..description.." ("..resolution..")",
options=options, arturl=art })
end
end
playlistline = playlist:readline()
end
end
line = fd:readline()
end
end
|
--[[
$Id$
Copyright © 2010 VideoLAN and AUTHORS
Authors: Ilkka Ollakka <ileoo at videolan dot org >
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
function descriptor()
return { title="Apple Trailers" }
end
function find( haystack, needle )
local _,_,r = string.find( haystack, needle )
return r
end
function main()
fd = vlc.stream( "http://trailers.apple.com/trailers/home/feeds/just_hd.json" )
if not fd then return nil end
options = {":http-user-agent=QuickTime/7.2 vlc edition",":demux=avformat,ffmpeg",":play-and-pause"}
line = fd:readline()
while line ~= nil
do
if string.match( line, "title" ) then
title = vlc.strings.resolve_xml_special_chars( find( line, "title\":\"(.-)\""))
art = find( line, "poster\":\"(.-)\"")
art = "http://trailers.apple.com"..art
url = find( line, "url\":\"(.-)\"")
playlist = vlc.stream( "http://trailers.apple.com"..url.."includes/playlists/web.inc" )
if not playlist then
vlc.msg.info("Didn't get playlist...")
end
node = vlc.sd.add_node( {title=title,arturl=art} )
playlistline = playlist:readline()
description =""
if not playlistline then vlc.msg.info("Empty playlists-file") end
while playlistline ~= nil
do
if string.match( playlistline, "class=\".-first" ) then
description = find( playlistline, "h%d.->(.-)</h%d")
end
if string.match( playlistline, "class=\"hd\".-\.mov") then
for urlline,resolution in string.gmatch(playlistline, "class=\"hd\".-href=\"(.-.mov)\".-(%d+.-p)") do
urlline = string.gsub( urlline, "_"..resolution, "_h"..resolution )
node:add_subitem( {path = urlline,
title=title.." "..description.." ("..resolution..")",
options=options, arturl=art })
end
end
playlistline = playlist:readline()
end
end
line = fd:readline()
end
end
|
appletrailers: fix arturl, seems that appletrailers-page changed littlebit
|
appletrailers: fix arturl, seems that appletrailers-page changed littlebit
|
Lua
|
lgpl-2.1
|
vlc-mirror/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,xkfz007/vlc,xkfz007/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.2,xkfz007/vlc,xkfz007/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc,jomanmuk/vlc-2.2,krichter722/vlc,jomanmuk/vlc-2.2,krichter722/vlc,vlc-mirror/vlc,krichter722/vlc,jomanmuk/vlc-2.1,krichter722/vlc,jomanmuk/vlc-2.1,xkfz007/vlc,shyamalschandra/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,shyamalschandra/vlc,krichter722/vlc,jomanmuk/vlc-2.2,xkfz007/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,krichter722/vlc,xkfz007/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,shyamalschandra/vlc,vlc-mirror/vlc-2.1,shyamalschandra/vlc,krichter722/vlc,vlc-mirror/vlc-2.1,shyamalschandra/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1
|
cff7314fc5934961c4b5d5a385ff309884acc035
|
defaut/Guerrier.lua
|
defaut/Guerrier.lua
|
Ovale.defaut["WARRIOR"] =
[[
#Spells
Define(BATTLESHOUT 6673)
SpellAddBuff(BATTLESHOUT BATTLESHOUT=120)
Define(BATTLESTANCE 2457)
Define(BERSERKERRAGE 18499)
Define(BERSERKERSTANCE 2458)
Define(BLADESTORM 46924)
Define(BLOODTHIRST 23881)
SpellInfo(BLOODTHIRST cd=3)
Define(CHARGE 100)
Define(CLEAVE 845)
SpellInfo(CLEAVE cd=3)
Define(COLOSSSUSSMASH 86346)
SpellInfo(COLOSSSUSSMASH cd=20)
Define(COMMANDINGSHOUT 469)
SpellAddBuff(COMMANDINGSHOUT cd=60 COMMANDINGSHOUT=120)
Define(CONCUSSIONBLOW 12809)
Define(DEADLYCALM 85730)
Define(DEATHWISH 12292)
SpellInfo(DEATHWISH cd=180)
Define(DEFENSIVESTANCE 71)
Define(DEMOSHOUT 1160)
SpellAddTargetDebuff(DEMOSHOUT DEMOSHOUT=45)
Define(DEVASTATE 20243)
SpellAddTargetDebuff(DEVASTATE SUNDERARMOR=30)
Define(EXECUTE 5308)
Define(HEROICLEAP 6544)
Define(HEROICSTRIKE 78)
SpellInfo(HEROICSTRIKE cd=3)
Define(HEROICTHROW 57755)
Define(HEROICFURY 60970)
Define(INTERCEPT 20252)
Define(INTERVENE 3411)
Define(LASTSTAND 12975)
Define(MORTALSTRIKE 12294)
SpellInfo(MORTALSTRIKE cd=4.5)
Define(OVERPOWER 7384)
SpellInfo(OVERPOWER cd=1)
Define(PUMMEL 6552)
Define(RAGINGBLOW 85288)
SpellInfo(RAGINGBLOW cd=6)
Define(RECKLESSNESS 1719)
Define(REND 772)
SpellAddTargetDebuff(REND REND=15)
Define(RETALIATION 20230)
Define(REVENGE 6572)
SpellInfo(REVENGE cd=5)
Define(SHATTERINGTHROW 64382)
Define(SHIELDBASH 72)
Define(SHIELDBLOCK 2565)
Define(SHIELDWALL 871)
Define(SHIELDSLAM 23922)
SpellInfo(SHIELDSLAM cd=6)
Define(SHOCKWAVE 46968)
Define(SLAM 1464)
SpellAddBuff(SLAM BLOODSURGE=-1)
Define(STRIKE 88161)
SpellInfo(STRIKE cd=3)
Define(SUNDERARMOR 7386)
SpellAddTargetDebuff(SUNDERARMOR SUNDERARMOR=30)
Define(SWEEPINGSTRIKES 12328)
Define(THUNDERCLAP 6343)
SpellAddTargetDebuff(THUNDERCLAP THUNDERCLAP=30)
Define(VICTORYRUSH 34428)
Define(WHIRLWIND 1680)
SpellInfo(WHIRLWIND cd=8)
#Buffs
Define(BLOODSURGE 46916)
Define(TASTEFORBLOOD 56636)
Define(ENRAGE 14202)
Define(EXECUTIONER 90806)
#Talents
Define(SLAMTALENT 2233)
Define(SUDDENDEATH 52437)
AddCheckBox(multi L(AOE))
AddCheckBox(demo SpellName(DEMOSHOUT))
AddCheckBox(sunder SpellName(SUNDERARMOR) default)
AddListItem(shout none L(None))
AddListItem(shout battle SpellName(BATTLESHOUT))
AddListItem(shout command SpellName(COMMANDINGSHOUT))
ScoreSpells(DEADLYCALM COLOSSUSSMASH RAGINGBLOW OVERPOWER VICTORYRUSH BLOODTHIRST SLAM REND MORTALSTRIKE EXECUTE SHIELDSLAM REVENGE
DEVASTATE)
AddIcon help=main mastery=1
{
if List(shout command) and {Mana(less 20) or BuffExpires(stamina 3)} Spell(COMMANDINGSHOUT nored=1)
if List(shout battle) and {Mana(less 20) or BuffExpires(strengthagility 3)} Spell(BATTLESHOUT nored=1)
if TargetClassification(worldboss) and CheckBoxOn(demo) and TargetDebuffExpires(lowerphysicaldamage 2) Spell(DEMOSHOUT nored=1)
if TargetDebuffExpires(SUNDERARMOR 2 stacks=3) and CheckBoxOn(sunder) and TargetDebuffExpires(lowerarmor 2) Spell(SUNDERARMOR nored=1)
if Mana(less 20) Spell(DEADLYCALM)
if TargetDebuffExpires(REND) Spell(REND)
if CheckBoxOn(multi) Spell(BLADESTORM)
Spell(COLOSSUSSMASH)
Spell(MORTALSTRIKE)
Spell(OVERPOWER usable=1)
if TargetLifePercent(less 20) Spell(EXECUTE)
Spell(SLAM)
}
AddIcon help=main mastery=2
{
if List(shout command) and {Mana(less 20) or BuffExpires(stamina 3)} Spell(COMMANDINGSHOUT nored=1)
if List(shout battle) and {Mana(less 20) or BuffExpires(strengthagility 3)} Spell(BATTLESHOUT nored=1)
if TargetClassification(worldboss) and CheckBoxOn(demo) and TargetDebuffExpires(lowerphysicaldamage 2) Spell(DEMOSHOUT nored=1)
if TargetDebuffExpires(SUNDERARMOR 2 stacks=3) and CheckBoxOn(sunder) and TargetDebuffExpires(lowerarmor 2) Spell(SUNDERARMOR nored=1)
if CheckBoxOn(multi) Spell(WHIRLWIND)
Spell(COLOSSUSSMASH)
if TargetLifePercent(less 20) and BuffExpires(EXECUTIONER 0 stacks=5) Spell(EXECUTE)
Spell(BLOODTHIRST)
Spell(RAGINGBLOW usable=1)
Spell(VICTORYRUSH usable=1)
if TargetLifePercent(less 20) and BuffExpires(EXECUTIONER 3) Spell(EXECUTE)
if BuffPresent(BLOODSURGE) Spell(SLAM)
if TargetLifePercent(less 20) Spell(EXECUTE)
if BuffExpires(DEATHWISH) and BuffExpires(RECKLESSNESS) and BuffExpires(ENRAGE) Spell(BERSERKERRAGE)
}
AddIcon help=main mastery=3
{
if List(shout command) and {Mana(less 20) or BuffExpires(stamina 3)} Spell(COMMANDINGSHOUT nored=1)
if List(shout battle) and {Mana(less 20) or BuffExpires(strengthagility 3)} Spell(BATTLESHOUT nored=1)
if TargetClassification(worldboss) and CheckBoxOn(demo) and TargetDebuffExpires(lowerphysicaldamage 2) Spell(DEMOSHOUT nored=1)
if CheckBoxOn(multi)
{
if TargetDebuffExpires(REND mine=1) Spell(REND)
Spell(THUNDERCLAP)
Spell(SHOCKWAVE)
}
Spell(SHIELDSLAM)
Spell(REVENGE usable=1)
if TargetDebuffExpires(meleeslow) Spell(THUNDERCLAP)
Spell(VICTORYRUSH usable=1)
Spell(DEVASTATE)
}
AddIcon help=offgcd
{
if Mana(more 60) and CheckBoxOn(multi) Spell(CLEAVE)
if Mana(more 60) and CheckBoxOff(multi) Spell(HEROICSTRIKE)
}
AddIcon help=cd mastery=1
{
Item(Trinket0Slot usable=1)
Item(Trinket1Slot usable=1)
}
AddIcon help=cd mastery=2
{
Spell(DEATHWISH)
Spell(RECKLESSNESS)
Item(Trinket0Slot usable=1)
Item(Trinket1Slot usable=1)
}
AddIcon help=cd mastery=3
{
Spell(SHIELDBLOCK)
Spell(SHIELDWALL)
Spell(LASTSTAND)
Item(Trinket0Slot usable=1)
Item(Trinket1Slot usable=1)
}
]]
|
Ovale.defaut["WARRIOR"] =
[[
#Spells
Define(BATTLESHOUT 6673)
SpellAddBuff(BATTLESHOUT BATTLESHOUT=120)
Define(BATTLESTANCE 2457)
Define(BERSERKERRAGE 18499)
Define(BERSERKERSTANCE 2458)
Define(BLADESTORM 46924)
Define(BLOODTHIRST 23881)
SpellInfo(BLOODTHIRST cd=3)
Define(CHARGE 100)
Define(CLEAVE 845)
SpellInfo(CLEAVE cd=3)
Define(COLOSSSUSSMASH 86346)
SpellInfo(COLOSSSUSSMASH cd=20)
Define(COMMANDINGSHOUT 469)
SpellAddBuff(COMMANDINGSHOUT cd=60 COMMANDINGSHOUT=120)
Define(CONCUSSIONBLOW 12809)
Define(DEADLYCALM 85730)
Define(DEATHWISH 12292)
SpellInfo(DEATHWISH cd=180)
Define(DEFENSIVESTANCE 71)
Define(DEMOSHOUT 1160)
SpellAddTargetDebuff(DEMOSHOUT DEMOSHOUT=45)
Define(DEVASTATE 20243)
SpellAddTargetDebuff(DEVASTATE SUNDERARMORDEBUFF=30)
Define(EXECUTE 5308)
Define(HEROICLEAP 6544)
Define(HEROICSTRIKE 78)
SpellInfo(HEROICSTRIKE cd=3)
Define(HEROICTHROW 57755)
Define(HEROICFURY 60970)
Define(INTERCEPT 20252)
Define(INTERVENE 3411)
Define(LASTSTAND 12975)
Define(MORTALSTRIKE 12294)
SpellInfo(MORTALSTRIKE cd=4.5)
Define(OVERPOWER 7384)
SpellInfo(OVERPOWER cd=1)
Define(PUMMEL 6552)
Define(RAGINGBLOW 85288)
SpellInfo(RAGINGBLOW cd=6)
Define(RECKLESSNESS 1719)
Define(REND 772)
SpellAddTargetDebuff(REND REND=15)
Define(RETALIATION 20230)
Define(REVENGE 6572)
SpellInfo(REVENGE cd=5)
Define(SHATTERINGTHROW 64382)
Define(SHIELDBASH 72)
Define(SHIELDBLOCK 2565)
Define(SHIELDWALL 871)
Define(SHIELDSLAM 23922)
SpellInfo(SHIELDSLAM cd=6)
Define(SHOCKWAVE 46968)
Define(SLAM 1464)
SpellAddBuff(SLAM BLOODSURGE=-1)
Define(STRIKE 88161)
SpellInfo(STRIKE cd=3)
Define(SUNDERARMOR 7386)
SpellAddTargetDebuff(SUNDERARMOR SUNDERARMORDEBUFF=30)
Define(SWEEPINGSTRIKES 12328)
Define(THUNDERCLAP 6343)
SpellAddTargetDebuff(THUNDERCLAP THUNDERCLAP=30)
Define(VICTORYRUSH 34428)
Define(WHIRLWIND 1680)
SpellInfo(WHIRLWIND cd=8)
#Buffs
Define(BLOODSURGE 46916)
Define(TASTEFORBLOOD 56636)
Define(ENRAGE 14202)
Define(EXECUTIONER 90806)
Define(SUNDERARMORDEBUFF 58567)
#Talents
Define(SLAMTALENT 2233)
Define(SUDDENDEATH 52437)
AddCheckBox(multi L(AOE))
AddCheckBox(demo SpellName(DEMOSHOUT))
AddCheckBox(sunder SpellName(SUNDERARMOR) default)
AddListItem(shout none L(None))
AddListItem(shout battle SpellName(BATTLESHOUT))
AddListItem(shout command SpellName(COMMANDINGSHOUT))
ScoreSpells(DEADLYCALM COLOSSUSSMASH RAGINGBLOW OVERPOWER VICTORYRUSH BLOODTHIRST SLAM REND MORTALSTRIKE EXECUTE SHIELDSLAM REVENGE
DEVASTATE)
AddIcon help=main mastery=1
{
if List(shout command) and {Mana(less 20) or BuffExpires(stamina 3)} Spell(COMMANDINGSHOUT nored=1)
if List(shout battle) and {Mana(less 20) or BuffExpires(strengthagility 3)} Spell(BATTLESHOUT nored=1)
if TargetClassification(worldboss) and CheckBoxOn(demo) and TargetDebuffExpires(lowerphysicaldamage 2) Spell(DEMOSHOUT nored=1)
if TargetDebuffExpires(SUNDERARMORDEBUFF 2 stacks=3) and CheckBoxOn(sunder) and TargetDebuffExpires(lowerarmor 2) Spell(SUNDERARMOR nored=1)
if Mana(less 20) Spell(DEADLYCALM)
if TargetDebuffExpires(REND) Spell(REND)
if CheckBoxOn(multi) Spell(BLADESTORM)
Spell(COLOSSUSSMASH)
Spell(MORTALSTRIKE)
Spell(OVERPOWER usable=1)
if TargetLifePercent(less 20) Spell(EXECUTE)
Spell(SLAM)
}
AddIcon help=main mastery=2
{
if List(shout command) and {Mana(less 20) or BuffExpires(stamina 3)} Spell(COMMANDINGSHOUT nored=1)
if List(shout battle) and {Mana(less 20) or BuffExpires(strengthagility 3)} Spell(BATTLESHOUT nored=1)
if TargetClassification(worldboss) and CheckBoxOn(demo) and TargetDebuffExpires(lowerphysicaldamage 2) Spell(DEMOSHOUT nored=1)
if TargetDebuffExpires(SUNDERARMORDEBUFF 2 stacks=3) and CheckBoxOn(sunder) and TargetDebuffExpires(lowerarmor 2) Spell(SUNDERARMOR nored=1)
if CheckBoxOn(multi) Spell(WHIRLWIND)
Spell(COLOSSUSSMASH)
if TargetLifePercent(less 20) and BuffExpires(EXECUTIONER 0 stacks=5) Spell(EXECUTE)
Spell(BLOODTHIRST)
Spell(RAGINGBLOW usable=1)
Spell(VICTORYRUSH usable=1)
if TargetLifePercent(less 20) and BuffExpires(EXECUTIONER 3) Spell(EXECUTE)
if BuffPresent(BLOODSURGE) Spell(SLAM)
if TargetLifePercent(less 20) Spell(EXECUTE)
if BuffExpires(DEATHWISH) and BuffExpires(RECKLESSNESS) and BuffExpires(ENRAGE) Spell(BERSERKERRAGE)
}
AddIcon help=main mastery=3
{
if List(shout command) and {Mana(less 20) or BuffExpires(stamina 3)} Spell(COMMANDINGSHOUT nored=1)
if List(shout battle) and {Mana(less 20) or BuffExpires(strengthagility 3)} Spell(BATTLESHOUT nored=1)
if TargetClassification(worldboss) and CheckBoxOn(demo) and TargetDebuffExpires(lowerphysicaldamage 2) Spell(DEMOSHOUT nored=1)
if CheckBoxOn(multi)
{
if TargetDebuffExpires(REND mine=1) Spell(REND)
Spell(THUNDERCLAP)
Spell(SHOCKWAVE)
}
Spell(SHIELDSLAM)
Spell(REVENGE usable=1)
if TargetDebuffExpires(meleeslow) Spell(THUNDERCLAP)
Spell(VICTORYRUSH usable=1)
Spell(DEVASTATE)
}
AddIcon help=offgcd
{
if Mana(more 60) and CheckBoxOn(multi) Spell(CLEAVE)
if Mana(more 60) and CheckBoxOff(multi) Spell(HEROICSTRIKE)
}
AddIcon help=cd mastery=1
{
Item(Trinket0Slot usable=1)
Item(Trinket1Slot usable=1)
}
AddIcon help=cd mastery=2
{
Spell(DEATHWISH)
Spell(RECKLESSNESS)
Item(Trinket0Slot usable=1)
Item(Trinket1Slot usable=1)
}
AddIcon help=cd mastery=3
{
Spell(SHIELDBLOCK)
Spell(SHIELDWALL)
Spell(LASTSTAND)
Item(Trinket0Slot usable=1)
Item(Trinket1Slot usable=1)
}
]]
|
warrior: sunder armor fix
|
warrior: sunder armor fix
git-svn-id: b2bb544abab4b09d60f88077ac82407cb244c9c9@278 d5049fe3-3747-40f7-a4b5-f36d6801af5f
|
Lua
|
mit
|
eXhausted/Ovale,eXhausted/Ovale,ultijlam/ovale,ultijlam/ovale,ultijlam/ovale,eXhausted/Ovale,Xeltor/ovale
|
b5d9a838d0c8cb4df83bf606eb56c69b64c75002
|
src/loader/src/LoaderUtils.lua
|
src/loader/src/LoaderUtils.lua
|
---
-- @module LoaderUtils
-- @author Quenty
local loader = script.Parent
local BounceTemplateUtils = require(script.Parent.BounceTemplateUtils)
local GroupInfoUtils = require(script.Parent.GroupInfoUtils)
local PackageInfoUtils = require(script.Parent.PackageInfoUtils)
local ScriptInfoUtils = require(script.Parent.ScriptInfoUtils)
local Utils = require(script.Parent.Utils)
local LoaderUtils = {}
LoaderUtils.Utils = Utils -- TODO: Remove this
LoaderUtils.ContextTypes = Utils.readonly({
CLIENT = "client";
SERVER = "server";
})
LoaderUtils.IncludeBehavior = Utils.readonly({
NO_INCLUDE = "noInclude";
INCLUDE_ONLY = "includeOnly";
INCLUDE_SHARED = "includeShared";
})
function LoaderUtils.toWallyFormat(instance)
assert(typeof(instance) == "Instance", "Bad instance")
local topLevelPackages = {}
LoaderUtils.discoverTopLevelPackages(topLevelPackages, instance)
local packageInfoList = {}
for _, folder in pairs(topLevelPackages) do
local packageInfo = PackageInfoUtils.getOrCreatePackageInfo(folder, {}, "")
table.insert(packageInfoList, packageInfo)
end
PackageInfoUtils.fillDependencySet(packageInfoList)
local clientGroupList = GroupInfoUtils.groupPackageInfos(packageInfoList,
ScriptInfoUtils.ModuleReplicationTypes.CLIENT)
local serverGroupList = GroupInfoUtils.groupPackageInfos(packageInfoList,
ScriptInfoUtils.ModuleReplicationTypes.SERVER)
local sharedGroupList = GroupInfoUtils.groupPackageInfos(packageInfoList,
ScriptInfoUtils.ModuleReplicationTypes.SHARED)
local publishSet = LoaderUtils.getPublishPackageInfoSet(packageInfoList)
local clientFolder = Instance.new("Folder")
clientFolder.Name = "Packages"
local sharedFolder = Instance.new("Folder")
sharedFolder.Name = "SharedPackages"
local serverFolder = Instance.new("Folder")
serverFolder.Name = "Packages"
LoaderUtils.reifyGroupList(clientGroupList, publishSet, clientFolder, ScriptInfoUtils.ModuleReplicationTypes.CLIENT)
LoaderUtils.reifyGroupList(serverGroupList, publishSet, serverFolder, ScriptInfoUtils.ModuleReplicationTypes.SERVER)
LoaderUtils.reifyGroupList(sharedGroupList, publishSet, sharedFolder, ScriptInfoUtils.ModuleReplicationTypes.SHARED)
return clientFolder, serverFolder, sharedFolder
end
function LoaderUtils.isPackage(folder)
assert(typeof(folder) == "Instance", "Bad instance")
for _, item in pairs(folder:GetChildren()) do
if item:IsA("Folder") then
if item.Name == "Server"
or item.Name == "Client"
or item.Name == "Shared"
or item.Name == ScriptInfoUtils.DEPENDENCY_FOLDER_NAME then
return true
end
end
end
return false
end
function LoaderUtils.discoverTopLevelPackages(packages, instance)
assert(type(packages) == "table", "Bad packages")
assert(typeof(instance) == "Instance", "Bad instance")
if LoaderUtils.isPackage(instance) then
table.insert(packages, instance)
else
-- Loop through all folders
for _, item in pairs(instance:GetChildren()) do
if item:IsA("Folder") then
LoaderUtils.discoverTopLevelPackages(packages, item)
elseif item:IsA("ModuleScript") then
table.insert(packages, item)
end
end
end
end
function LoaderUtils.reifyGroupList(groupInfoList, publishSet, parent, replicationMode)
assert(type(groupInfoList) == "table", "Bad groupInfoList")
assert(type(publishSet) == "table", "Bad publishSet")
assert(typeof(parent) == "Instance", "Bad parent")
assert(type(replicationMode) == "string", "Bad replicationMode")
local folder = Instance.new("Folder")
folder.Name = "_Index"
for _, groupInfo in pairs(groupInfoList) do
LoaderUtils.reifyGroup(groupInfo, publishSet, folder, replicationMode)
end
-- Publish
for packageInfo, _ in pairs(publishSet) do
for scriptName, scriptInfo in pairs(packageInfo.scriptInfoLookup[replicationMode]) do
local link = BounceTemplateUtils.create(scriptInfo.instance, scriptName)
link.Parent = parent
end
end
folder.Parent = parent
end
function LoaderUtils.getPublishPackageInfoSet(packageInfoList)
local packageInfoSet = {}
for _, packageInfo in pairs(packageInfoList) do
packageInfoSet[packageInfo] = true
-- First level declared dependencies too (assuming we're importing just one item)
for dependentPackageInfo, _ in pairs(packageInfo.explicitDependencySet) do
packageInfoSet[dependentPackageInfo] = true
end
end
return packageInfoSet
end
function LoaderUtils.reifyGroup(groupInfo, publishSet, parent, replicationMode)
assert(type(groupInfo) == "table", "Bad groupInfo")
assert(type(publishSet) == "table", "Bad publishSet")
assert(typeof(parent) == "Instance", "Bad parent")
assert(type(replicationMode) == "string", "Bad replicationMode")
local folder = Instance.new("Folder")
folder.Name = assert(next(groupInfo.packageSet).fullName, "Bad package fullName")
for scriptName, scriptInfo in pairs(groupInfo.packageScriptInfoMap) do
assert(scriptInfo.name == scriptName, "Bad scriptInfo.name")
if scriptInfo.replicationMode == replicationMode then
if scriptInfo.instance == loader and loader.Parent == game:GetService("ReplicatedStorage") then
-- Hack to prevent reparenting of loader in legacy mode
local link = BounceTemplateUtils.create(scriptInfo.instance, scriptName)
link.Parent = folder
else
scriptInfo.instance.Name = scriptName
scriptInfo.instance.Parent = folder
end
else
local link = BounceTemplateUtils.create(scriptInfo.instance, scriptName)
link.Parent = folder
end
end
-- Link all of the other dependencies
for scriptName, scriptInfo in pairs(groupInfo.scriptInfoMap) do
assert(scriptInfo.name == scriptName, "Bad scriptInfo.name")
if not groupInfo.packageScriptInfoMap[scriptName] then
local link = BounceTemplateUtils.create(scriptInfo.instance, scriptName)
link.Parent = folder
end
end
folder.Parent = parent
end
return LoaderUtils
|
---
-- @module LoaderUtils
-- @author Quenty
local loader = script.Parent
local BounceTemplateUtils = require(script.Parent.BounceTemplateUtils)
local GroupInfoUtils = require(script.Parent.GroupInfoUtils)
local PackageInfoUtils = require(script.Parent.PackageInfoUtils)
local ScriptInfoUtils = require(script.Parent.ScriptInfoUtils)
local Utils = require(script.Parent.Utils)
local LoaderUtils = {}
LoaderUtils.Utils = Utils -- TODO: Remove this
LoaderUtils.ContextTypes = Utils.readonly({
CLIENT = "client";
SERVER = "server";
})
LoaderUtils.IncludeBehavior = Utils.readonly({
NO_INCLUDE = "noInclude";
INCLUDE_ONLY = "includeOnly";
INCLUDE_SHARED = "includeShared";
})
function LoaderUtils.toWallyFormat(instance)
assert(typeof(instance) == "Instance", "Bad instance")
local topLevelPackages = {}
LoaderUtils.discoverTopLevelPackages(topLevelPackages, instance)
LoaderUtils.injectLoader(topLevelPackages)
local packageInfoList = {}
for _, folder in pairs(topLevelPackages) do
local packageInfo = PackageInfoUtils.getOrCreatePackageInfo(folder, {}, "")
table.insert(packageInfoList, packageInfo)
end
PackageInfoUtils.fillDependencySet(packageInfoList)
local clientGroupList = GroupInfoUtils.groupPackageInfos(packageInfoList,
ScriptInfoUtils.ModuleReplicationTypes.CLIENT)
local serverGroupList = GroupInfoUtils.groupPackageInfos(packageInfoList,
ScriptInfoUtils.ModuleReplicationTypes.SERVER)
local sharedGroupList = GroupInfoUtils.groupPackageInfos(packageInfoList,
ScriptInfoUtils.ModuleReplicationTypes.SHARED)
local publishSet = LoaderUtils.getPublishPackageInfoSet(packageInfoList)
local clientFolder = Instance.new("Folder")
clientFolder.Name = "Packages"
local sharedFolder = Instance.new("Folder")
sharedFolder.Name = "SharedPackages"
local serverFolder = Instance.new("Folder")
serverFolder.Name = "Packages"
LoaderUtils.reifyGroupList(clientGroupList, publishSet, clientFolder, ScriptInfoUtils.ModuleReplicationTypes.CLIENT)
LoaderUtils.reifyGroupList(serverGroupList, publishSet, serverFolder, ScriptInfoUtils.ModuleReplicationTypes.SERVER)
LoaderUtils.reifyGroupList(sharedGroupList, publishSet, sharedFolder, ScriptInfoUtils.ModuleReplicationTypes.SHARED)
return clientFolder, serverFolder, sharedFolder
end
function LoaderUtils.isPackage(folder)
assert(typeof(folder) == "Instance", "Bad instance")
for _, item in pairs(folder:GetChildren()) do
if item:IsA("Folder") then
if item.Name == "Server"
or item.Name == "Client"
or item.Name == "Shared"
or item.Name == ScriptInfoUtils.DEPENDENCY_FOLDER_NAME then
return true
end
end
end
return false
end
function LoaderUtils.injectLoader(topLevelPackages)
for _, item in pairs(topLevelPackages) do
if item == loader then
return
end
end
-- We need the loader injected!
table.insert(topLevelPackages, loader)
end
function LoaderUtils.discoverTopLevelPackages(packages, instance)
assert(type(packages) == "table", "Bad packages")
assert(typeof(instance) == "Instance", "Bad instance")
if LoaderUtils.isPackage(instance) then
table.insert(packages, instance)
else
-- Loop through all folders
for _, item in pairs(instance:GetChildren()) do
if item:IsA("Folder") then
LoaderUtils.discoverTopLevelPackages(packages, item)
elseif item:IsA("ModuleScript") then
table.insert(packages, item)
end
end
end
end
function LoaderUtils.reifyGroupList(groupInfoList, publishSet, parent, replicationMode)
assert(type(groupInfoList) == "table", "Bad groupInfoList")
assert(type(publishSet) == "table", "Bad publishSet")
assert(typeof(parent) == "Instance", "Bad parent")
assert(type(replicationMode) == "string", "Bad replicationMode")
local folder = Instance.new("Folder")
folder.Name = "_Index"
for _, groupInfo in pairs(groupInfoList) do
LoaderUtils.reifyGroup(groupInfo, publishSet, folder, replicationMode)
end
-- Publish
for packageInfo, _ in pairs(publishSet) do
for scriptName, scriptInfo in pairs(packageInfo.scriptInfoLookup[replicationMode]) do
local link = BounceTemplateUtils.create(scriptInfo.instance, scriptName)
link.Parent = parent
end
end
folder.Parent = parent
end
function LoaderUtils.getPublishPackageInfoSet(packageInfoList)
local packageInfoSet = {}
for _, packageInfo in pairs(packageInfoList) do
packageInfoSet[packageInfo] = true
-- First level declared dependencies too (assuming we're importing just one item)
for dependentPackageInfo, _ in pairs(packageInfo.explicitDependencySet) do
packageInfoSet[dependentPackageInfo] = true
end
end
return packageInfoSet
end
function LoaderUtils.reifyGroup(groupInfo, publishSet, parent, replicationMode)
assert(type(groupInfo) == "table", "Bad groupInfo")
assert(type(publishSet) == "table", "Bad publishSet")
assert(typeof(parent) == "Instance", "Bad parent")
assert(type(replicationMode) == "string", "Bad replicationMode")
local folder = Instance.new("Folder")
folder.Name = assert(next(groupInfo.packageSet).fullName, "Bad package fullName")
for scriptName, scriptInfo in pairs(groupInfo.packageScriptInfoMap) do
assert(scriptInfo.name == scriptName, "Bad scriptInfo.name")
if scriptInfo.replicationMode == replicationMode then
if scriptInfo.instance == loader and loader.Parent == game:GetService("ReplicatedStorage") then
-- Hack to prevent reparenting of loader in legacy mode
local link = BounceTemplateUtils.create(scriptInfo.instance, scriptName)
link.Parent = folder
else
scriptInfo.instance.Name = scriptName
scriptInfo.instance.Parent = folder
end
else
local link = BounceTemplateUtils.create(scriptInfo.instance, scriptName)
link.Parent = folder
end
end
-- Link all of the other dependencies
for scriptName, scriptInfo in pairs(groupInfo.scriptInfoMap) do
assert(scriptInfo.name == scriptName, "Bad scriptInfo.name")
if not groupInfo.packageScriptInfoMap[scriptName] then
local link = BounceTemplateUtils.create(scriptInfo.instance, scriptName)
link.Parent = folder
end
end
folder.Parent = parent
end
return LoaderUtils
|
fix: Ensure loader injects itself
|
fix: Ensure loader injects itself
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
a9e96868ef8302fc7f4743b32cc1d362f5f6d473
|
hostinfo/init.lua
|
hostinfo/init.lua
|
--[[
Copyright 2014 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local fs = require('fs')
local json = require('json')
local los = require('los')
local async = require('async')
local path = require('path')
local HostInfo = require('./base').HostInfo
local classes = require('./all')
local uv = require('uv')
local function create_class_info()
local map = {}
local types = {}
for x, klass in pairs(classes) do
if klass.Info then klass = klass.Info end
map[klass.getType()] = klass
table.insert(types, klass.getType())
end
return {map = map, types = types}
end
local CLASS_INFO = create_class_info()
local HOST_INFO_MAP = CLASS_INFO.map
local HOST_INFO_TYPES = CLASS_INFO.types
--[[ NilInfo ]]--
local NilInfo = HostInfo:extend()
function NilInfo:initialize()
HostInfo.initialize(self)
self._error = 'Agent does not support this Host Info type'
end
--[[ Factory ]]--
local function create(infoType)
local klass = HOST_INFO_MAP[infoType]
if klass then
if klass.Info then
return klass.Info:new()
else
return klass:new()
end
end
return NilInfo:new()
end
-- [[ Types ]]--
local function getTypes()
return HOST_INFO_TYPES
end
-- [[ Suite of debug util functions ]] --
local function debugInfo(infoType, callback)
if not callback then
callback = function()
print('Running hostinfo of type: ' .. infoType)
end
end
local klass = create(infoType)
klass:run(function(err)
local data = '{"Debug":{"InfoType":"' .. infoType .. '", "OS":"' .. los.type() .. '"}}\n\n'
if err then
data = data .. json.stringify({error = err})
else
data = data .. json.stringify(klass:serialize(), {indent = 2})
end
callback(data)
end)
end
local function debugInfoAll(callback)
local data = ''
async.forEachLimit(HOST_INFO_TYPES, 5, function(infoType, cb)
debugInfo(infoType, function(debugData)
data = data .. debugData
cb()
end)
end, function()
callback(data)
end)
end
local function debugInfoToFile(infoType, fileName, callback)
debugInfo(infoType, function(debugData)
fs.writeFile(fileName, debugData, callback)
end)
end
local function debugInfoAllToFile(fileName, callback)
debugInfoAll(function(data)
fs.writeFile(fileName, data, callback)
end)
end
local function debugInfoAllToFolder(folderName, callback)
fs.mkdirSync(folderName)
async.forEachLimit(HOST_INFO_TYPES, 5, function(infoType, cb)
debugInfo(infoType, function(debugData)
fs.writeFile(path.join(folderName, infoType .. '.json'), debugData, cb)
end)
end, function()
callback()
end)
end
local function debugInfoAllTime(callback)
local data = {}
async.forEachLimit(HOST_INFO_TYPES, 5, function(infoType, cb)
local start = uv.hrtime()
debugInfo(infoType, function(_)
local endTime = uv.hrtime() - start
data[infoType] = endTime / 10000
cb()
end)
end, function()
callback(json.stringify(data, {indent = 2}))
end)
end
local function debugInfoAllSize(callback)
local folderName = 'tempDebug'
local data = {}
data.hostinfos = {}
local totalSize = 0
debugInfoAllToFolder(folderName, function()
local files = fs.readdirSync(folderName)
async.forEachLimit(files, 5, function(file, cb)
local size = fs.statSync(path.join(folderName, file))['size']
totalSize = totalSize + size
data.hostinfos[file:sub(0, -6)] = size
cb()
end, function()
fs.unlinkSync(folderName)
data.total_size = totalSize
callback(json.stringify(data, {indent = 2}))
end)
end)
end
--[[ Exports ]]--
local exports = {}
exports.create = create
exports.classes = classes
exports.getTypes = getTypes
exports.debugInfo = debugInfo
exports.debugInfoToFile = debugInfoToFile
exports.debugInfoAll = debugInfoAll
exports.debugInfoAllToFile = debugInfoAllToFile
exports.debugInfoAllToFolder = debugInfoAllToFolder
exports.debugInfoAllTime = debugInfoAllTime
exports.debugInfoAllSize = debugInfoAllSize
return exports
|
--[[
Copyright 2014 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local fs = require('fs')
local json = require('json')
local los = require('los')
local async = require('async')
local path = require('path')
local HostInfo = require('./base').HostInfo
local classes = require('./all')
local uv = require('uv')
local function create_class_info()
local map = {}
local types = {}
for _, klass in pairs(classes) do
if klass.Info then klass = klass.Info end
map[klass.getType()] = klass
-- We'll only populate the types array with ones that work on this OS
local os = los.type()
local supportedOSs = klass.getPlatforms()
-- if getPlatform isnt defined we assume it works everywhere, only hostinfo nil does this
if not supportedOSs then
table.insert(types, klass.getType())
else
table.foreach(supportedOSs, function(_, v)
if v == os then table.insert(types, klass.getType()) end
end)
end
end
return {map = map, types = types}
end
local CLASS_INFO = create_class_info()
local HOST_INFO_MAP = CLASS_INFO.map
local HOST_INFO_TYPES = CLASS_INFO.types
--[[ NilInfo ]]--
local NilInfo = HostInfo:extend()
function NilInfo:initialize()
HostInfo.initialize(self)
self._error = 'Agent does not support this Host Info type'
end
--[[ Factory ]]--
local function create(infoType)
local klass = HOST_INFO_MAP[infoType]
if klass then
if klass.Info then
return klass.Info:new()
else
return klass:new()
end
end
return NilInfo:new()
end
-- [[ Types ]]--
local function getTypes()
return HOST_INFO_TYPES
end
-- [[ Suite of debug util functions ]] --
local function debugInfo(infoType, callback)
if not callback then
callback = function()
print('Running hostinfo of type: ' .. infoType)
end
end
local klass = create(infoType)
klass:run(function(err)
local data = '{"Debug":{"InfoType":"' .. infoType .. '", "OS":"' .. los.type() .. '"}}\n\n'
if err then
data = data .. json.stringify({error = err})
else
data = data .. json.stringify(klass:serialize(), {indent = 2})
end
callback(data)
end)
end
local function debugInfoAll(callback)
local data = ''
async.forEachLimit(HOST_INFO_TYPES, 5, function(infoType, cb)
debugInfo(infoType, function(debugData)
data = data .. debugData
cb()
end)
end, function()
callback(data)
end)
end
local function debugInfoToFile(infoType, fileName, callback)
debugInfo(infoType, function(debugData)
fs.writeFile(fileName, debugData, callback)
end)
end
local function debugInfoAllToFile(fileName, callback)
debugInfoAll(function(data)
fs.writeFile(fileName, data, callback)
end)
end
local function debugInfoAllToFolder(folderName, callback)
fs.mkdirSync(folderName)
async.forEachLimit(HOST_INFO_TYPES, 5, function(infoType, cb)
debugInfo(infoType, function(debugData)
fs.writeFile(path.join(folderName, infoType .. '.json'), debugData, cb)
end)
end, function()
callback()
end)
end
local function debugInfoAllTime(callback)
local data = {}
async.forEachLimit(HOST_INFO_TYPES, 5, function(infoType, cb)
local start = uv.hrtime()
debugInfo(infoType, function(_)
local endTime = uv.hrtime() - start
data[infoType] = endTime / 10000
cb()
end)
end, function()
callback(json.stringify(data, {indent = 2}))
end)
end
local function debugInfoAllSize(callback)
local folderName = 'tempDebug'
local data = {}
data.hostinfos = {}
local totalSize = 0
debugInfoAllToFolder(folderName, function()
local files = fs.readdirSync(folderName)
async.forEachLimit(files, 5, function(file, cb)
local size = fs.statSync(path.join(folderName, file))['size']
totalSize = totalSize + size
data.hostinfos[file:sub(0, -6)] = size
cb()
end, function()
fs.unlinkSync(folderName)
data.total_size = totalSize
callback(json.stringify(data, {indent = 2}))
end)
end)
end
--[[ Exports ]]--
local exports = {}
exports.create = create
exports.classes = classes
exports.getTypes = getTypes
exports.debugInfo = debugInfo
exports.debugInfoToFile = debugInfoToFile
exports.debugInfoAll = debugInfoAll
exports.debugInfoAllToFile = debugInfoAllToFile
exports.debugInfoAllToFolder = debugInfoAllToFolder
exports.debugInfoAllTime = debugInfoAllTime
exports.debugInfoAllSize = debugInfoAllSize
return exports
|
fix(hostinfo/init): Only populate the HOST_INFO_TYPES array with types valid on the host OS. This is sent down to ele for get types. Solves issue #583
|
fix(hostinfo/init): Only populate the HOST_INFO_TYPES array with types valid on the host OS. This is sent down to ele for get types. Solves issue #583
|
Lua
|
apache-2.0
|
virgo-agent-toolkit/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent
|
dc22370cf1092ed7043d1cc1cda3ab0ec34bc91c
|
frontend/ui/geometry.lua
|
frontend/ui/geometry.lua
|
--[[
2D Geometry utilities
all of these apply to full rectangles { x = ..., y = ..., w = ..., h = ... }
some behaviour is defined for points { x = ..., y = ... }
some behaviour is defined for dimensions { w = ..., h = ... }
just use it on simple tables that have x, y and/or w, h
or define your own types using this as a metatable
]]--
Geom = {
x = 0,
y = 0,
w = 0,
h = 0
}
function Geom:new(o)
local o = o or {}
setmetatable(o, self)
self.__index = self
return o
end
function Geom:copy()
local n = Geom:new()
n.x = self.x
n.y = self.y
n.w = self.w
n.h = self.h
return n
end
function Geom:__tostring()
return self.w.."x"..self.h.."+"..self.x.."+"..self.y
end
--[[
offset rectangle or point by relative values
]]--
function Geom:offsetBy(dx, dy)
self.x = self.x + dx
self.y = self.y + dy
return self
end
--[[
offset rectangle or point to certain coordinates
]]--
function Geom:offsetTo(x, y)
self.x = x
self.y = y
return self
end
--[[
scale rectangle (grow to bottom and to the right) or dimension
if a single factor is given, it is applied to both width and height
]]--
function Geom:scaleBy(zx, zy)
self.w = self.w * zx
self.h = self.h * (zy or zx)
return self
end
--[[
this method also takes care of x and y
]]--
function Geom:transformByScale(zx, zy)
self.x = self.x * zx
self.y = self.y * (zx or zy)
self:scaleBy(zx, zy)
end
--[[
enlarges or shrinks dimensions or rectangles
note that for rectangles the offset stays the same
]]--
function Geom:changeSizeBy(dw, dh)
self.w = self.w + dw
self.h = self.h + dh
return self
end
--[[
return the outer rectangle that contains both us and a given rectangle
works for rectangles, dimensions and points
]]--
function Geom:combine(rect_b)
local combined = Geom:new(self)
if combined.x > rect_b.x then
combined.x = rect_b.x
end
if combined.y > rect_b.y then
combined.y = rect_b.y
end
if self.x + self.w > rect_b.x + rect_b.w then
combined.w = self.x + self.w - combined.x
else
combined.w = rect_b.x + rect_b.w - combined.x
end
if self.y + self.h > rect_b.y + rect_b.h then
combined.h = self.y + self.h - combined.y
else
combined.h = rect_b.y + rect_b.h - combined.y
end
return combined
end
--[[
returns a rectangle for the part that we and a given rectangle share
TODO: what happens if there is no rectangle shared? currently behaviour is undefined.
]]--
function Geom:intersect(rect_b)
local intersected = Geom:new(self)
if self.x < rect_b.x then
intersected.x = rect_b.x
end
if self.y < rect_b.y then
intersected.y = rect_b.y
end
if self.x + self.w < rect_b.x + rect_b.w then
intersected.w = self.x + self.w - intersected.x
else
intersected.w = rect_b.x + rect_b.w - intersected.x
end
if self.y + self.h < rect_b.y + rect_b.h then
intersected.h = self.y + self.h - intersected.y
else
intersected.h = rect_b.y + rect_b.h - intersected.y
end
return intersected
end
--[[
return true if self does not share any area with rect_b
]]--
function Geom:notIntersectWith(rect_b)
if (self.x >= (rect_b.x + rect_b.w))
or (self.y >= (rect_b.y + rect_b.h))
or (rect_b.x >= (self.x + self.w))
or (rect_b.y >= (self.y + self.h)) then
return true
end
return false
end
--[[
set size of dimension or rectangle to size of given dimension/rectangle
]]--
function Geom:setSizeTo(rect_b)
self.w = rect_b.w
self.h = rect_b.h
return self
end
--[[
check whether rect_b is within current rectangle
works for dimensions, too
for points, it is basically an equality check
]]--
function Geom:contains(rect_b)
if self.x <= rect_b.x
and self.y <= rect_b.y
and self.x + self.w >= rect_b.x + rect_b.w
and self.y + self.h >= rect_b.y + rect_b.h
then
return true
end
return false
end
--[[
check for equality
works for rectangles, points, dimensions
]]--
function Geom:__eq(rect_b)
if self.x == rect_b.x
and self.y == rect_b.y
and self:equalSize(rect_b)
then
return true
end
return false
end
--[[
check size of dimension/rectangle for equality
]]--
function Geom:equalSize(rect_b)
if self.w == rect_b.w
and self.h == rect_b.h
then
return true
end
return false
end
--[[
check if our size is smaller than the size of the given dimension/rectangle
]]--
function Geom:__lt(rect_b)
DEBUG("lt:",self,rect_b)
if self.w < rect_b.w and self.h < rect_b.h then
DEBUG("lt+")
return true
end
DEBUG("lt-")
return false
end
--[[
check if our size is smaller or equal the size of the given dimension/rectangle
]]--
function Geom:__le(rect_b)
if self.w <= rect_b.w and self.h <= rect_b.h then
return true
end
return false
end
--[[
offset the current rectangle by dx, dy while fitting it into the space
of a given rectangle
this can also be called with dx=0 and dy=0, which will fit the current
rectangle into the given rectangle
]]--
function Geom:offsetWithin(rect_b, dx, dy)
-- check size constraints and shrink us when we're too big
if self.w > rect_b.w then
self.w = rect_b.w
end
if self.h > rect_b.h then
self.h = rect_b.h
end
-- offset
self.x = self.x + dx
self.y = self.y + dy
-- check offsets
if self.x < rect_b.x then
self.x = rect_b.x
end
if self.y < rect_b.y then
self.y = rect_b.y
end
if self.x + self.w > rect_b.x + rect_b.w then
self.x = rect_b.x + rect_b.w - self.w
end
if self.y + self.h > rect_b.y + rect_b.h then
self.y = rect_b.y + rect_b.h - self.h
end
end
--[[
return the Euclidean distance between two geoms
]]--
function Geom:distance(geom)
return math.sqrt(math.pow(self.x - geom.x, 2) + math.pow(self.y - geom.y, 2))
end
|
--[[
2D Geometry utilities
all of these apply to full rectangles { x = ..., y = ..., w = ..., h = ... }
some behaviour is defined for points { x = ..., y = ... }
some behaviour is defined for dimensions { w = ..., h = ... }
just use it on simple tables that have x, y and/or w, h
or define your own types using this as a metatable
]]--
Geom = {
x = 0,
y = 0,
w = 0,
h = 0
}
function Geom:new(o)
local o = o or {}
setmetatable(o, self)
self.__index = self
return o
end
function Geom:copy()
local n = Geom:new()
n.x = self.x
n.y = self.y
n.w = self.w
n.h = self.h
return n
end
function Geom:__tostring()
return self.w.."x"..self.h.."+"..self.x.."+"..self.y
end
--[[
offset rectangle or point by relative values
]]--
function Geom:offsetBy(dx, dy)
self.x = self.x + dx
self.y = self.y + dy
return self
end
--[[
offset rectangle or point to certain coordinates
]]--
function Geom:offsetTo(x, y)
self.x = x
self.y = y
return self
end
--[[
scale rectangle (grow to bottom and to the right) or dimension
if a single factor is given, it is applied to both width and height
]]--
function Geom:scaleBy(zx, zy)
self.w = self.w * zx
self.h = self.h * (zy or zx)
return self
end
--[[
this method also takes care of x and y
]]--
function Geom:transformByScale(zx, zy)
self.x = self.x * zx
self.y = self.y * (zx or zy)
self:scaleBy(zx, zy)
end
--[[
enlarges or shrinks dimensions or rectangles
note that for rectangles the offset stays the same
]]--
function Geom:changeSizeBy(dw, dh)
self.w = self.w + dw
self.h = self.h + dh
return self
end
--[[
return the outer rectangle that contains both us and a given rectangle
works for rectangles, dimensions and points
]]--
function Geom:combine(rect_b)
local combined = Geom:new(self)
if combined.x > rect_b.x then
combined.x = rect_b.x
end
if combined.y > rect_b.y then
combined.y = rect_b.y
end
if self.x + self.w > rect_b.x + rect_b.w then
combined.w = self.x + self.w - combined.x
else
combined.w = rect_b.x + rect_b.w - combined.x
end
if self.y + self.h > rect_b.y + rect_b.h then
combined.h = self.y + self.h - combined.y
else
combined.h = rect_b.y + rect_b.h - combined.y
end
return combined
end
--[[
returns a rectangle for the part that we and a given rectangle share
TODO: what happens if there is no rectangle shared? currently behaviour is undefined.
]]--
function Geom:intersect(rect_b)
-- make a copy of self
local intersected = self:copy()
if self.x < rect_b.x then
intersected.x = rect_b.x
end
if self.y < rect_b.y then
intersected.y = rect_b.y
end
if self.x + self.w < rect_b.x + rect_b.w then
intersected.w = self.x + self.w - intersected.x
else
intersected.w = rect_b.x + rect_b.w - intersected.x
end
if self.y + self.h < rect_b.y + rect_b.h then
intersected.h = self.y + self.h - intersected.y
else
intersected.h = rect_b.y + rect_b.h - intersected.y
end
return intersected
end
--[[
return true if self does not share any area with rect_b
]]--
function Geom:notIntersectWith(rect_b)
if (self.x >= (rect_b.x + rect_b.w))
or (self.y >= (rect_b.y + rect_b.h))
or (rect_b.x >= (self.x + self.w))
or (rect_b.y >= (self.y + self.h)) then
return true
end
return false
end
--[[
set size of dimension or rectangle to size of given dimension/rectangle
]]--
function Geom:setSizeTo(rect_b)
self.w = rect_b.w
self.h = rect_b.h
return self
end
--[[
check whether rect_b is within current rectangle
works for dimensions, too
for points, it is basically an equality check
]]--
function Geom:contains(rect_b)
if self.x <= rect_b.x
and self.y <= rect_b.y
and self.x + self.w >= rect_b.x + rect_b.w
and self.y + self.h >= rect_b.y + rect_b.h
then
return true
end
return false
end
--[[
check for equality
works for rectangles, points, dimensions
]]--
function Geom:__eq(rect_b)
if self.x == rect_b.x
and self.y == rect_b.y
and self:equalSize(rect_b)
then
return true
end
return false
end
--[[
check size of dimension/rectangle for equality
]]--
function Geom:equalSize(rect_b)
if self.w == rect_b.w
and self.h == rect_b.h
then
return true
end
return false
end
--[[
check if our size is smaller than the size of the given dimension/rectangle
]]--
function Geom:__lt(rect_b)
DEBUG("lt:",self,rect_b)
if self.w < rect_b.w and self.h < rect_b.h then
DEBUG("lt+")
return true
end
DEBUG("lt-")
return false
end
--[[
check if our size is smaller or equal the size of the given dimension/rectangle
]]--
function Geom:__le(rect_b)
if self.w <= rect_b.w and self.h <= rect_b.h then
return true
end
return false
end
--[[
offset the current rectangle by dx, dy while fitting it into the space
of a given rectangle
this can also be called with dx=0 and dy=0, which will fit the current
rectangle into the given rectangle
]]--
function Geom:offsetWithin(rect_b, dx, dy)
-- check size constraints and shrink us when we're too big
if self.w > rect_b.w then
self.w = rect_b.w
end
if self.h > rect_b.h then
self.h = rect_b.h
end
-- offset
self.x = self.x + dx
self.y = self.y + dy
-- check offsets
if self.x < rect_b.x then
self.x = rect_b.x
end
if self.y < rect_b.y then
self.y = rect_b.y
end
if self.x + self.w > rect_b.x + rect_b.w then
self.x = rect_b.x + rect_b.w - self.w
end
if self.y + self.h > rect_b.y + rect_b.h then
self.y = rect_b.y + rect_b.h - self.h
end
end
function Geom:shrinkInside(rect_b, dx, dy)
self:offsetBy(dx, dy)
return self:intersect(rect_b)
end
--[[
return the Euclidean distance between two geoms
]]--
function Geom:distance(geom)
return math.sqrt(math.pow(self.x - geom.x, 2) + math.pow(self.y - geom.y, 2))
end
|
bugfix: intersected geom should be initiated with a fresh copy of self
|
bugfix: intersected geom should be initiated with a fresh copy of self
|
Lua
|
agpl-3.0
|
Hzj-jie/koreader,NiLuJe/koreader-base,apletnev/koreader-base,houqp/koreader-base,koreader/koreader-base,houqp/koreader-base,frankyifei/koreader-base,apletnev/koreader-base,robert00s/koreader,Frenzie/koreader-base,NiLuJe/koreader-base,Frenzie/koreader-base,chrox/koreader,ashang/koreader,NiLuJe/koreader,koreader/koreader,koreader/koreader-base,NiLuJe/koreader-base,frankyifei/koreader-base,Markismus/koreader,mwoz123/koreader,pazos/koreader,apletnev/koreader,Frenzie/koreader,NiLuJe/koreader,ashhher3/koreader,Hzj-jie/koreader-base,koreader/koreader-base,NickSavage/koreader,poire-z/koreader,NiLuJe/koreader-base,apletnev/koreader-base,Frenzie/koreader-base,houqp/koreader-base,koreader/koreader,lgeek/koreader,Hzj-jie/koreader-base,koreader/koreader-base,frankyifei/koreader,Hzj-jie/koreader-base,Frenzie/koreader-base,noname007/koreader,frankyifei/koreader-base,Frenzie/koreader,apletnev/koreader-base,houqp/koreader,frankyifei/koreader-base,poire-z/koreader,chihyang/koreader,mihailim/koreader,Hzj-jie/koreader-base,houqp/koreader-base
|
af0ab62bac717a76b883531ba257e52d5c41322c
|
util/dataforms.lua
|
util/dataforms.lua
|
module "dataforms"
local xmlns_forms = 'jabber:x:data';
local form_t = {};
local form_mt = { __index = form_t };
function new(layout)
return setmetatable(layout, form_mt);
end
local form_x_attr = { xmlns = xmlns_forms };
function form_t.form(layout, data)
local form = st.tag("x", form_x_attr);
for n, field in ipairs(layout) do
local field_type = field.type;
-- Add field tag
form:tag("field", { type = field_type, var = field.name });
local value = data[field.name];
-- Add value, depending on type
if field_type == "hidden" then
if type(value) == "table" then
-- Assume an XML snippet
form:add_child(value);
elseif value then
form:text(tostring(value));
end
elseif field_type == "boolean" then
form:text((value and "1") or "0");
elseif field_type == "fixed" then
elseif field_type == "jid-multi" then
for _, jid in ipairs(value) do
form:tag("value"):text(jid):up();
end
elseif field_type == "jid-single" then
form:tag("value"):text(value):up();
end
-- Jump back up to list of fields
form:up();
end
return form;
end
function form_t.data(layout, stanza)
end
--[[
Layout:
{
title = "MUC Configuration",
instructions = [[Use this form to configure options for this MUC room.]],
{ name = "FORM_TYPE", type = "hidden", required = true };
{ name = "field-name", type = "field-type", required = false };
}
--]]
|
local setmetatable = setmetatable;
local pairs, ipairs = pairs, ipairs;
local st = require "util.stanza";
module "dataforms"
local xmlns_forms = 'jabber:x:data';
local form_t = {};
local form_mt = { __index = form_t };
function new(layout)
return setmetatable(layout, form_mt);
end
local form_x_attr = { xmlns = xmlns_forms };
function form_t.form(layout, data)
local form = st.stanza("x", form_x_attr);
if layout.title then
form:tag("title"):text(layout.title):up();
end
if layout.instructions then
form:tag("instructions"):text(layout.instructions):up();
end
for n, field in ipairs(layout) do
local field_type = field.type or "text-single";
-- Add field tag
form:tag("field", { type = field_type, var = field.name, label = field.label });
local value = data[field.name];
-- Add value, depending on type
if field_type == "hidden" then
if type(value) == "table" then
-- Assume an XML snippet
form:add_child(value);
elseif value then
form:text(tostring(value));
end
elseif field_type == "boolean" then
form:tag("value"):text((value and "1") or "0");
elseif field_type == "fixed" then
elseif field_type == "jid-multi" then
for _, jid in ipairs(value) do
form:tag("value"):text(jid):up();
end
elseif field_type == "jid-single" then
form:tag("value"):text(value):up();
elseif field_type == "text-single" or field_type == "text-private" then
form:tag("value"):text(value):up();
elseif field_type == "text-multi" then
-- Split into multiple <value> tags, one for each line
for line in value:gmatch("([^\r\n]+)\r?\n*") do
form:tag("value"):text(line):up();
end
end
-- Jump back up to list of fields
form:up();
end
return form;
end
function form_t.data(layout, stanza)
end
return _M;
--[=[
Layout:
{
title = "MUC Configuration",
instructions = [[Use this form to configure options for this MUC room.]],
{ name = "FORM_TYPE", type = "hidden", required = true };
{ name = "field-name", type = "field-type", required = false };
}
--]=]
|
util.dataforms: Fixed to actually work, mostly
|
util.dataforms: Fixed to actually work, mostly
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
bcf740199b94d728e9852279d53a3fb5c3042751
|
src/http/adapters/nginx/base.lua
|
src/http/adapters/nginx/base.lua
|
local mixin = require 'core.mixin'
local Request = require 'http.request'
local ResponseWriter = require 'http.response'
local json_decode
do
local json = require 'core.encoding.json'
json_decode = json.decode
end
mixin(ResponseWriter, {
get_status_code = function(self)
return self.ngx.status
end,
set_status_code = function(self, code)
self.ngx.status = code
end,
flush = function(self)
self.ngx.flush()
end
})
mixin(Request, {
parse_query = function(self)
local query = self.ngx.req.get_uri_args()
self.query = query
return query
end,
parse_headers = function(self)
local headers = self.ngx.req.get_headers()
self.headers = headers
return headers
end,
parse_body = function(self)
local body
local r = self.ngx.req
r.read_body()
local headers = r.get_headers()
local content_type = headers['content-type']
if content_type == 'application/json' then
body = r.get_body_data()
local c = body:sub(1, 1)
if c ~= '{' and c ~= '[' then
return nil
end
body = json_decode(body)
else
body = r.get_post_args()
end
self.body = body
return body
end,
server_parts = function(self)
local var = self.ngx.var
return var.scheme, var.host, var.server_port
end
})
return {
ResponseWriter = ResponseWriter,
Request = Request
}
|
local mixin = require 'core.mixin'
local Request = require 'http.request'
local ResponseWriter = require 'http.response'
local json_decode
do
local json = require 'core.encoding.json'
json_decode = json.decode
end
mixin(ResponseWriter, {
get_status_code = function(self)
return self.ngx.status
end,
set_status_code = function(self, code)
self.ngx.status = code
end,
flush = function(self)
self.ngx.flush()
end
})
mixin(Request, {
parse_query = function(self)
local query = self.ngx.req.get_uri_args()
self.query = query
return query
end,
parse_headers = function(self)
local headers = self.ngx.req.get_headers()
self.headers = headers
return headers
end,
parse_body = function(self)
local body
local r = self.ngx.req
r.read_body()
local headers = r.get_headers()
local t = headers['content-type']
if t and t:find('application/json', 1, true) then
body = r.get_body_data()
local c = body:sub(1, 1)
if c ~= '{' and c ~= '[' then
return nil
end
body = json_decode(body)
else
body = r.get_post_args()
end
self.body = body
return body
end,
server_parts = function(self)
local var = self.ngx.var
return var.scheme, var.host, var.server_port
end
})
return {
ResponseWriter = ResponseWriter,
Request = Request
}
|
Fixed json content type check in parse body of nginx request adapter.
|
Fixed json content type check in parse body of nginx request adapter.
|
Lua
|
mit
|
akornatskyy/lucid
|
d65f4bb1ca63f045cca64d48d233e5ca2a7b9625
|
test/dev-app/controllers/test.lua
|
test/dev-app/controllers/test.lua
|
local session = require "sailor.session"
local validation = require "valua"
local form = require "sailor.form"
local test = {}
function test.index(page)
local stringVariable = 'this variable is being passed from a controller to a view!'
local anotherVar = 2342 -- this one too! \o/
page:write("Here we are testing basic functionalities, such as LP parsing and V-C communication.")
page:render('index',{stringVariable = stringVariable,anotherVar = anotherVar})
end
--This will be recovered once I reorganize the mailer module
--[[
function test.mailer(page)
local message = "Hello!"
if page.POST['email'] then
local sent, err = mail.send_message("<"..page.POST['email']..">","This is the subject!","This is the body!")
if err then
message = err
else
message = "The email was sent!"
end
end
page:render('mailer',{msg = message})
end]]
function test.models(page)
--Testing Models
--[[
I'm using 'User' model for testing under a mysql db.
If you want to check it out, you must import the sql files under /sql
]]
local User = sailor.model("user")
local u = User:new()
u.username = "maria"
u.password = "12345678"
local res,errs = u:validate()
if not res then
page:write("failed test!<br/>")
else
page:write("passed test!<br/>")
end
if u:save() then
page:write("saved! "..u.id.."<br/>")
end
-- FIND() IS NOT YET ESCAPED, DONT USE IT UNLESS YOU WROTE THE 'WHERE' STRING YOURSELF
local u2 = User:find("username ='francisco'")
if u2 then
page:write(u2.id.." - "..u2.username.."<br/>")
end
local users = User:find_all()
for _, user in pairs(users) do
page:write(user.id.." - "..user.username.."<br/>")
end
u.username = "catarina"
if u:save() then
page:write("saved! "..u.id.."<br/>")
end
local users = User:find_all()
for _, user in pairs(users) do
page:write(user.id.." - "..user.username.."<br/>")
end
page:write("Finding user with id 1:<br/>")
local some_user = User:find_by_id(1)
if some_user then
page:write(some_user.id.." - "..some_user.username.."<br/>")
end
page:write("Finding user with id 47:<br/>")
local some_user = User:find_by_id(47)
if some_user then
page:write(some_user.id.." - "..some_user.username.."<br/>")
else
page:write("User not found!")
end
end
function test.modelval(page)
local User = sailor.model("user")
local u = User:new()
u.username = ""
u.password = "12345"
local res,err = u:validate()
page:print(table.concat(err,'<br/>'), '<br/>')
u.username = "Lala"
u.password = "12345"
local res,err = u:validate()
page:print("<br/>",unpack(err))
u.username = "Lala"
u.password = "12345678"
local res,err = u:validate()
page:print("<br/>",unpack(err or {}))
end
function test.form(page)
local User = sailor.model("user")
local u = User:new()
u.username = "test"
if next(page.POST) then
u:get_post(page.POST)
end
page:render('form',{user=u,form = form})
end
function test.redirect(page)
return page:redirect('test',{hey="blah",hue = 2})
end
function test.include(page)
page:render('include')
end
function test.error(page)
page:render('error')
end
function test.newsession(page)
session.open(page.r)
session.save({username = "john lennon"})
if session.data then
for k,v in pairs(session.data) do
page:write(v)
end
end
end
function test.opensession(page)
session.open(page.r)
if session.data then
for k,v in pairs(session.data) do
page:write(v)
end
end
end
function test.destroysession(page)
session.destroy(page.r)
end
function test.login(page)
local access = require "sailor.access"
if access.is_guest() then
page:print("Logging in...<br/>")
local _,err = access.login("demo","demo")
page:print(err or "Logged in.")
else
page:print("You are already logged in.")
end
end
function test.runat_client(page)
page:render('runat_client')
end
function test.runat_both(page)
page:render('runat_both')
end
function test.client_module(page)
page:render('client_module')
end
function test.client_module_js(page)
page:render('client_module_js')
end
function test.realtime(page)
page:render('realtime')
end
function test.upload(page)
page:inspect(page.POST)
if page.POST.datafile then
file = io.open ('/Users/ecdalcol/Desktop/tuxedo/test' , 'w')
io.output(file)
io.write(page.POST.datafile)
io.close(file)
end
page:render('upload')
end
return test
|
local session = require "sailor.session"
local validation = require "valua"
local form = require "sailor.form"
local sailor = require "sailor"
local test = {}
function test.index(page)
local stringVariable = 'this variable is being passed from a controller to a view!'
local anotherVar = 2342 -- this one too! \o/
page:write("Here we are testing basic functionalities, such as LP parsing and V-C communication.")
page:render('index',{stringVariable = stringVariable,anotherVar = anotherVar})
end
--This will be recovered once I reorganize the mailer module
--[[
function test.mailer(page)
local message = "Hello!"
if page.POST['email'] then
local sent, err = mail.send_message("<"..page.POST['email']..">","This is the subject!","This is the body!")
if err then
message = err
else
message = "The email was sent!"
end
end
page:render('mailer',{msg = message})
end]]
function test.models(page)
--Testing Models
--[[
I'm using 'User' model for testing under a mysql db.
If you want to check it out, you must import the sql files under /sql
]]
local User = sailor.model("user")
local u = User:new()
u.username = "maria"
u.password = "12345678"
local res,errs = u:validate()
if not res then
page:write("failed test!<br/>")
else
page:write("passed test!<br/>")
end
if u:save() then
page:write("saved! "..u.id.."<br/>")
end
-- FIND() IS NOT YET ESCAPED, DONT USE IT UNLESS YOU WROTE THE 'WHERE' STRING YOURSELF
local u2 = User:find("username ='francisco'")
if u2 then
page:write(u2.id.." - "..u2.username.."<br/>")
end
local users = User:find_all()
for _, user in pairs(users) do
page:write(user.id.." - "..user.username.."<br/>")
end
u.username = "catarina"
if u:save() then
page:write("saved! "..u.id.."<br/>")
end
local users = User:find_all()
for _, user in pairs(users) do
page:write(user.id.." - "..user.username.."<br/>")
end
page:write("Finding user with id 1:<br/>")
local some_user = User:find_by_id(1)
if some_user then
page:write(some_user.id.." - "..some_user.username.."<br/>")
end
page:write("Finding user with id 47:<br/>")
local some_user = User:find_by_id(47)
if some_user then
page:write(some_user.id.." - "..some_user.username.."<br/>")
else
page:write("User not found!")
end
end
function test.modelval(page)
page.theme = nil
local User = sailor.model("user")
local u = User:new()
u.username = ""
u.password = "12345"
local res,err = u:validate()
page:write(table.concat(err,'<br/>'), '<br/>')
u.username = "Lala"
u.password = "12345"
local res,err = u:validate()
page:print("<br/>",unpack(err))
u.username = "Lala"
u.password = "12345678"
local res,err = u:validate()
page:print("<br/>",unpack(err or {}))
end
function test.form(page)
local User = sailor.model("user")
local u = User:new()
u.username = "test"
if next(page.POST) then
u:get_post(page.POST)
end
page:render('form',{user=u,form = form})
end
function test.redirect(page)
return page:redirect('test',{hey="blah",hue = 2})
end
function test.include(page)
page:render('include')
end
function test.error(page)
page:render('error')
end
function test.newsession(page)
session.open(page.r)
session.save({username = "john lennon"})
if session.data then
for k,v in pairs(session.data) do
page:write(v)
end
end
end
function test.opensession(page)
session.open(page.r)
if session.data then
for k,v in pairs(session.data) do
page:write(v)
end
end
end
function test.destroysession(page)
session.destroy(page.r)
end
function test.login(page)
local access = require "sailor.access"
if access.is_guest() then
page:print("Logging in...<br/>")
local _,err = access.login("demo","demo")
page:print(err or "Logged in.")
else
page:print("You are already logged in.")
end
end
function test.runat_client(page)
page:render('runat_client')
end
function test.runat_both(page)
page:render('runat_both')
end
function test.client_module(page)
page:render('client_module')
end
function test.client_module_js(page)
page:render('client_module_js')
end
function test.realtime(page)
page:render('realtime')
end
function test.upload(page)
page:inspect(page.POST)
if page.POST.datafile then
file = io.open ('/Users/ecdalcol/Desktop/tuxedo/test' , 'w')
io.output(file)
io.write(page.POST.datafile)
io.close(file)
end
page:render('upload')
end
return test
|
Fixing require of sailor
|
Fixing require of sailor
|
Lua
|
mit
|
mpeterv/sailor,noname007/sailor,jeary/sailor,sailorproject/sailor,felipedaragon/sailor,ignacio/sailor,Etiene/sailor,mpeterv/sailor,Etiene/sailor,felipedaragon/sailor,ignacio/sailor
|
ad66c0bc257bea3476e279d815f36b9eb231a887
|
projects/premake5.lua
|
projects/premake5.lua
|
newoption({
trigger = "gmcommon",
description = "Sets the path to the garrysmod_common (https://bitbucket.org/danielga/garrysmod_common) directory",
value = "path to garrysmod_common dir"
})
local gmcommon = _OPTIONS.gmcommon or os.getenv("GARRYSMOD_COMMON")
if gmcommon == nil then
error("you didn't provide a path to your garrysmod_common (https://bitbucket.org/danielga/garrysmod_common) directory")
end
include(gmcommon)
local LUASEC_FOLDER = "../luasec"
local OPENSSL_FOLDER = os.get() .. "/OpenSSL"
CreateSolution("ssl.core")
CreateProject(SERVERSIDE, SOURCES_MANUAL)
AddFiles("main.cpp")
IncludeLuaShared()
links({"luasocket", "core", "context", "x509"})
filter("system:windows")
libdirs(OPENSSL_FOLDER .. "/lib")
links({"ws2_32", "libeay32", "ssleay32"})
filter("system:not windows")
linkoptions("-Wl,-Bstatic")
pkg_config({"--cflags", "--libs", "openssl"})
CreateProject(CLIENTSIDE, SOURCES_MANUAL)
AddFiles("main.cpp")
IncludeLuaShared()
links({"luasocket", "core", "context", "x509"})
filter("system:windows")
libdirs(OPENSSL_FOLDER .. "/lib")
links({"ws2_32", "libeay32", "ssleay32"})
filter("system:not windows")
linkoptions("-Wl,-Bstatic")
pkg_config({"--cflags", "--libs", "openssl"})
project("luasocket")
kind("StaticLib")
warnings("Off")
includedirs(LUASEC_FOLDER .. "/src/luasocket")
files({
LUASEC_FOLDER .. "/src/luasocket/buffer.c",
LUASEC_FOLDER .. "/src/luasocket/io.c",
LUASEC_FOLDER .. "/src/luasocket/timeout.c"
})
vpaths({["Source files"] = LUASEC_FOLDER .. "/src/luasocket/**.c"})
IncludeLuaShared()
filter("system:windows")
files(LUASEC_FOLDER .. "/src/luasocket/wsocket.c")
filter("system:not windows")
files(LUASEC_FOLDER .. "/src/luasocket/usocket.c")
project("core")
kind("StaticLib")
warnings("Off")
includedirs(LUASEC_FOLDER .. "/src")
files(LUASEC_FOLDER .. "/src/ssl.c")
vpaths({["Source files"] = LUASEC_FOLDER .. "/src/**.c"})
IncludeLuaShared()
links("luasocket")
filter("system:windows")
includedirs(OPENSSL_FOLDER .. "/include")
project("context")
kind("StaticLib")
warnings("Off")
includedirs(LUASEC_FOLDER .. "/src")
files(LUASEC_FOLDER .. "/src/context.c")
vpaths({["Source files"] = LUASEC_FOLDER .. "/src/**.c"})
IncludeLuaShared()
filter("system:windows")
includedirs(OPENSSL_FOLDER .. "/include")
project("x509")
kind("StaticLib")
warnings("Off")
includedirs(LUASEC_FOLDER .. "/src")
files(LUASEC_FOLDER .. "/src/x509.c")
vpaths({["Source files"] = LUASEC_FOLDER .. "/src/**.c"})
IncludeLuaShared()
filter("system:windows")
includedirs(OPENSSL_FOLDER .. "/include")
|
newoption({
trigger = "gmcommon",
description = "Sets the path to the garrysmod_common (https://bitbucket.org/danielga/garrysmod_common) directory",
value = "path to garrysmod_common dir"
})
local gmcommon = _OPTIONS.gmcommon or os.getenv("GARRYSMOD_COMMON")
if gmcommon == nil then
error("you didn't provide a path to your garrysmod_common (https://bitbucket.org/danielga/garrysmod_common) directory")
end
include(gmcommon)
local LUASEC_FOLDER = "../luasec"
local OPENSSL_FOLDER = os.get() .. "/OpenSSL"
CreateSolution("ssl.core")
CreateProject(SERVERSIDE, SOURCES_MANUAL)
AddFiles("main.cpp")
IncludeLuaShared()
links({"x509", "context", "core", "luasocket"})
filter("system:windows")
libdirs(OPENSSL_FOLDER .. "/lib")
links({"ws2_32", "libeay32", "ssleay32"})
filter("system:not windows")
linkoptions("-Wl,-Bstatic")
pkg_config({"--cflags", "--libs", "openssl"})
CreateProject(CLIENTSIDE, SOURCES_MANUAL)
AddFiles("main.cpp")
IncludeLuaShared()
links({"x509", "context", "core", "luasocket"})
filter("system:windows")
libdirs(OPENSSL_FOLDER .. "/lib")
links({"ws2_32", "libeay32", "ssleay32"})
filter("system:not windows")
linkoptions("-Wl,-Bstatic")
pkg_config({"--cflags", "--libs", "openssl"})
project("luasocket")
kind("StaticLib")
warnings("Off")
includedirs(LUASEC_FOLDER .. "/src/luasocket")
files({
LUASEC_FOLDER .. "/src/luasocket/buffer.c",
LUASEC_FOLDER .. "/src/luasocket/io.c",
LUASEC_FOLDER .. "/src/luasocket/timeout.c"
})
vpaths({["Source files"] = LUASEC_FOLDER .. "/src/luasocket/**.c"})
IncludeLuaShared()
filter("system:windows")
files(LUASEC_FOLDER .. "/src/luasocket/wsocket.c")
filter("system:not windows")
files(LUASEC_FOLDER .. "/src/luasocket/usocket.c")
project("core")
kind("StaticLib")
warnings("Off")
includedirs(LUASEC_FOLDER .. "/src")
files(LUASEC_FOLDER .. "/src/ssl.c")
vpaths({["Source files"] = LUASEC_FOLDER .. "/src/**.c"})
IncludeLuaShared()
filter("system:windows")
includedirs(OPENSSL_FOLDER .. "/include")
project("context")
kind("StaticLib")
warnings("Off")
includedirs(LUASEC_FOLDER .. "/src")
files(LUASEC_FOLDER .. "/src/context.c")
vpaths({["Source files"] = LUASEC_FOLDER .. "/src/**.c"})
IncludeLuaShared()
filter("system:windows")
includedirs(OPENSSL_FOLDER .. "/include")
project("x509")
kind("StaticLib")
warnings("Off")
includedirs(LUASEC_FOLDER .. "/src")
files(LUASEC_FOLDER .. "/src/x509.c")
vpaths({["Source files"] = LUASEC_FOLDER .. "/src/**.c"})
IncludeLuaShared()
filter("system:windows")
includedirs(OPENSSL_FOLDER .. "/include")
|
Further testing of fixes.
|
Further testing of fixes.
This time, reordered links according to luasec makefile.
|
Lua
|
bsd-3-clause
|
danielga/gmod_luasec
|
4a6c8223a06325e0286ca4d7f79e954565d77828
|
xmake/core/main.lua
|
xmake/core/main.lua
|
--!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2019, TBOOX Open Source Group.
--
-- @author ruki
-- @file main.lua
--
-- define module: main
local main = main or {}
-- load modules
local os = require("base/os")
local log = require("base/log")
local path = require("base/path")
local utils = require("base/utils")
local option = require("base/option")
local global = require("base/global")
local deprecated = require("base/deprecated")
local privilege = require("base/privilege")
local task = require("base/task")
local colors = require("base/colors")
local theme = require("theme/theme")
local project = require("project/project")
local history = require("project/history")
--local profiler = require("base/profiler")
-- init the option menu
local menu =
{
-- title
title = "${bright}xmake v" .. _VERSION .. ", A cross-platform build utility based on Lua${clear}"
-- copyright
, copyright = "Copyright (C) 2015-2019 Ruki Wang, ${underline}tboox.org${clear}, ${underline}xmake.io${clear}\nCopyright (C) 2005-2015 Mike Pall, ${underline}luajit.org${clear}"
-- the tasks: xmake [task]
, function ()
local tasks = task.tasks() or {}
local ok, protasks_or_errors = pcall(project.tasks)
if ok then
table.join2(tasks, protasks_or_errors)
else
utils.cprint("${dim}%s", protasks_or_errors)
end
return task.menu(tasks)
end
}
-- show help and version info
function main._show_help()
-- show help
if option.get("help") then
-- print menu
option.show_menu(option.taskname())
-- ok
return true
-- show version
elseif option.get("version") then
-- show title
if menu.title then
utils.cprint(menu.title)
end
-- show copyright
if menu.copyright then
utils.cprint(menu.copyright)
end
-- show logo
option.show_logo()
-- ok
return true
end
end
-- find the root project file
function main._find_root(projectfile)
-- make all parent directories
local dirs = {}
local dir = path.directory(projectfile)
while os.isdir(dir) do
table.insert(dirs, 1, dir)
local parentdir = path.directory(dir)
if parentdir and parentdir ~= dir and parentdir ~= '.' then
dir = parentdir
else
break
end
end
-- find the first `xmake.lua` from it's parent directory
for _, dir in ipairs(dirs) do
local file = path.join(dir, "xmake.lua")
if os.isfile(file) then
return file
end
end
return projectfile
end
-- the init function for main
function main._init()
-- get project directory from the argument option
local opt_projectdir = option.find(xmake._ARGV, "project", "P")
-- get project file from the argument option
local opt_projectfile = option.find(xmake._ARGV, "file", "F")
-- init the project directory
local projectdir = opt_projectdir or xmake._PROJECT_DIR
if projectdir and not path.is_absolute(projectdir) then
projectdir = path.absolute(projectdir)
elseif projectdir then
projectdir = path.translate(projectdir)
end
xmake._PROJECT_DIR = projectdir
assert(projectdir)
-- init the xmake.lua file path
local projectfile = opt_projectfile or xmake._PROJECT_FILE
if projectfile and not path.is_absolute(projectfile) then
projectfile = path.absolute(projectfile, projectdir)
end
xmake._PROJECT_FILE = projectfile
assert(projectfile)
-- find the root project file
if not os.isfile(projectfile) or (not opt_projectdir and not opt_projectfile) then
projectfile = main._find_root(projectfile)
end
-- update and enter project
xmake._PROJECT_DIR = path.directory(projectfile)
xmake._PROJECT_FILE = projectfile
-- enter the project directory
if os.isdir(os.projectdir()) then
os.cd(os.projectdir())
end
-- add the directory of the program file (xmake) to $PATH environment
local programfile = os.programfile()
if programfile and os.isfile(programfile) then
os.addenv("PATH", path.directory(programfile))
else
os.addenv("PATH", os.programdir())
end
end
-- the main entry function
function main.entry()
-- init
main._init()
-- init option
local ok, errors = option.init(menu)
if not ok then
utils.error(errors)
return -1
end
-- check run command as root
if not option.get("root") and (not os.getenv("XMAKE_ROOT") or os.getenv("XMAKE_ROOT") ~= 'y') then
if os.isroot() then
if not privilege.store() or os.isroot() then
utils.error([[Running xmake as root is extremely dangerous and no longer supported.
As xmake does not drop privileges on installation you would be giving all
build scripts full access to your system.
Or you can add `--root` option or XMAKE_ROOT=y to allow run as root temporarily.
]])
return -1
end
end
end
-- start profiling
-- profiler:start()
-- load global configuration
ok, errors = global.load()
if not ok then
utils.error(errors)
return -1
end
-- load theme
local theme_inst, errors = theme.load(global.get("theme") or "default")
if not theme_inst then
utils.error(errors)
return -1
end
colors.theme_set(theme_inst)
-- show help?
if main._show_help() then
return 0
end
-- save command lines to history
if os.isfile(os.projectfile()) then
history("local.history"):save("cmdlines", option.cmdline())
end
-- get task instance
local taskname = option.taskname() or "build"
local taskinst = project.task(taskname) or task.task(taskname)
if not taskinst then
utils.error("do unknown task(%s)!", taskname)
return -1
end
-- run task
ok, errors = taskinst:run()
if not ok then
utils.error(errors)
return -1
end
-- dump deprecated entries
deprecated.dump()
-- stop profiling
-- profiler:stop()
-- close log
log:close()
-- ok
return 0
end
-- return module: main
return main
|
--!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2019, TBOOX Open Source Group.
--
-- @author ruki
-- @file main.lua
--
-- define module: main
local main = main or {}
-- load modules
local os = require("base/os")
local log = require("base/log")
local path = require("base/path")
local utils = require("base/utils")
local option = require("base/option")
local global = require("base/global")
local deprecated = require("base/deprecated")
local privilege = require("base/privilege")
local task = require("base/task")
local colors = require("base/colors")
local theme = require("theme/theme")
local project = require("project/project")
local history = require("project/history")
--local profiler = require("base/profiler")
-- init the option menu
local menu =
{
-- title
title = "${bright}xmake v" .. _VERSION .. ", A cross-platform build utility based on Lua${clear}"
-- copyright
, copyright = "Copyright (C) 2015-2019 Ruki Wang, ${underline}tboox.org${clear}, ${underline}xmake.io${clear}\nCopyright (C) 2005-2015 Mike Pall, ${underline}luajit.org${clear}"
-- the tasks: xmake [task]
, function ()
local tasks = task.tasks() or {}
local ok, protasks_or_errors = pcall(project.tasks)
if ok then
table.join2(tasks, protasks_or_errors)
else
utils.cprint("${dim}%s", protasks_or_errors)
end
return task.menu(tasks)
end
}
-- show help and version info
function main._show_help()
-- show help
if option.get("help") then
-- print menu
option.show_menu(option.taskname())
-- ok
return true
-- show version
elseif option.get("version") then
-- show title
if menu.title then
utils.cprint(menu.title)
end
-- show copyright
if menu.copyright then
utils.cprint(menu.copyright)
end
-- show logo
option.show_logo()
-- ok
return true
end
end
-- find the root project file
function main._find_root(projectfile)
-- make all parent directories
local dirs = {}
local dir = path.directory(projectfile)
while os.isdir(dir) do
table.insert(dirs, 1, dir)
local parentdir = path.directory(dir)
if parentdir and parentdir ~= dir and parentdir ~= '.' then
dir = parentdir
else
break
end
end
-- find the first `xmake.lua` from it's parent directory
for _, dir in ipairs(dirs) do
local file = path.join(dir, "xmake.lua")
if os.isfile(file) then
return file
end
end
return projectfile
end
-- the init function for main
function main._init()
-- get project directory from the argument option
local opt_projectdir = option.find(xmake._ARGV, "project", "P")
-- get project file from the argument option
local opt_projectfile = option.find(xmake._ARGV, "file", "F")
-- init the project directory
local projectdir = opt_projectdir or xmake._PROJECT_DIR
if projectdir and not path.is_absolute(projectdir) then
projectdir = path.absolute(projectdir)
elseif projectdir then
projectdir = path.translate(projectdir)
end
xmake._PROJECT_DIR = projectdir
assert(projectdir)
-- init the xmake.lua file path
local projectfile = opt_projectfile or xmake._PROJECT_FILE
if projectfile and not path.is_absolute(projectfile) then
projectfile = path.absolute(projectfile, projectdir)
end
xmake._PROJECT_FILE = projectfile
assert(projectfile)
-- find the root project file
if not os.isfile(projectfile) or (not opt_projectdir and not opt_projectfile) then
projectfile = main._find_root(projectfile)
end
-- update and enter project
xmake._PROJECT_DIR = path.directory(projectfile)
xmake._PROJECT_FILE = projectfile
-- enter the project directory
if os.isdir(os.projectdir()) then
os.cd(os.projectdir())
end
-- add the directory of the program file (xmake) to $PATH environment
local programfile = os.programfile()
if programfile and os.isfile(programfile) then
os.addenv("PATH", path.directory(programfile))
else
os.addenv("PATH", os.programdir())
end
end
-- the main entry function
function main.entry()
-- init
main._init()
-- load global configuration
local ok, errors = global.load()
if not ok then
utils.error(errors)
return -1
end
-- load theme
local theme_inst, errors = theme.load(global.get("theme") or "default")
if not theme_inst then
utils.error(errors)
return -1
end
colors.theme_set(theme_inst)
-- init option
ok, errors = option.init(menu)
if not ok then
utils.error(errors)
return -1
end
-- check run command as root
if not option.get("root") and (not os.getenv("XMAKE_ROOT") or os.getenv("XMAKE_ROOT") ~= 'y') then
if os.isroot() then
if not privilege.store() or os.isroot() then
utils.error([[Running xmake as root is extremely dangerous and no longer supported.
As xmake does not drop privileges on installation you would be giving all
build scripts full access to your system.
Or you can add `--root` option or XMAKE_ROOT=y to allow run as root temporarily.
]])
return -1
end
end
end
-- start profiling
-- profiler:start()
-- show help?
if main._show_help() then
return 0
end
-- save command lines to history
if os.isfile(os.projectfile()) then
history("local.history"):save("cmdlines", option.cmdline())
end
-- get task instance
local taskname = option.taskname() or "build"
local taskinst = project.task(taskname) or task.task(taskname)
if not taskinst then
utils.error("do unknown task(%s)!", taskname)
return -1
end
-- run task
ok, errors = taskinst:run()
if not ok then
utils.error(errors)
return -1
end
-- dump deprecated entries
deprecated.dump()
-- stop profiling
-- profiler:stop()
-- close log
log:close()
-- ok
return 0
end
-- return module: main
return main
|
fix show help with theme
|
fix show help with theme
|
Lua
|
apache-2.0
|
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
|
a8c18287863826467f2fdc6666f89b63b7b9e391
|
lualib/skynet/sharetable.lua
|
lualib/skynet/sharetable.lua
|
local skynet = require "skynet"
local service = require "skynet.service"
local core = require "skynet.sharetable.core"
local function sharetable_service()
local skynet = require "skynet"
local core = require "skynet.sharetable.core"
local matrix = {} -- all the matrix
local files = {} -- filename : matrix
local clients = {}
local sharetable = {}
local function close_matrix(m)
if m == nil then
return
end
local ptr = m:getptr()
local ref = matrix[ptr]
if ref == nil or ref.count == 0 then
matrix[ptr] = nil
m:close()
end
end
function sharetable.loadfile(source, filename, ...)
close_matrix(files[filename])
local m = core.matrix("@" .. filename, ...)
files[filename] = m
skynet.ret()
end
function sharetable.loadstring(source, filename, datasource, ...)
close_matrix(files[filename])
local m = core.matrix(datasource, ...)
files[filename] = m
skynet.ret()
end
local function loadtable(filename, ptr, len)
close_matrix(files[filename])
local m = core.matrix([[
local unpack, ptr, len = ...
return unpack(ptr, len)
]], skynet.unpack, ptr, len)
files[filename] = m
end
function sharetable.loadtable(source, filename, ptr, len)
local ok, err = pcall(loadtable, filename, ptr, len)
skynet.trash(ptr, len)
assert(ok, err)
skynet.ret()
end
local function query_file(source, filename)
local m = files[filename]
local ptr = m:getptr()
local ref = matrix[ptr]
if ref == nil then
ref = {
filename = filename,
count = 0,
matrix = m,
refs = {},
}
matrix[ptr] = ref
end
if ref.refs[source] == nil then
ref.refs[source] = true
local list = clients[source]
if not list then
clients[source] = { ptr }
else
table.insert(list, ptr)
end
ref.count = ref.count + 1
end
return ptr
end
function sharetable.query(source, filename)
local m = files[filename]
if m == nil then
skynet.ret()
end
local ptr = query_file(source, filename)
skynet.ret(skynet.pack(ptr))
end
function sharetable.close(source)
local list = clients[source]
if list then
for _, ptr in ipairs(list) do
local ref = matrix[ptr]
if ref and ref.refs[source] then
ref.refs[source] = nil
ref.count = ref.count - 1
if ref.count == 0 then
if files[ref.filename] ~= ref.matrix then
-- It's a history version
skynet.error(string.format("Delete a version (%s) of %s", ptr, ref.filename))
ref.matrix:close()
matrix[ptr] = nil
end
end
end
end
clients[source] = nil
end
-- no return
end
skynet.dispatch("lua", function(_,source,cmd,...)
sharetable[cmd](source,...)
end)
skynet.info_func(function()
local info = {}
for filename, m in pairs(files) do
info[filename] = {
current = m:getptr(),
size = m:size(),
}
end
local function address(refs)
local keys = {}
for addr in pairs(refs) do
table.insert(keys, skynet.address(addr))
end
table.sort(keys)
return table.concat(keys, ",")
end
for ptr, copy in pairs(matrix) do
local v = info[copy.filename]
local h = v.history
if h == nil then
h = {}
v.history = h
end
table.insert(h, string.format("%s [%d]: (%s)", copy.matrix:getptr(), copy.matrix:size(), address(copy.refs)))
end
for _, v in pairs(info) do
if v.history then
v.history = table.concat(v.history, "\n\t")
end
end
return info
end)
end
local function load_service(t, key)
if key == "address" then
t.address = service.new("sharetable", sharetable_service)
return t.address
else
return nil
end
end
local function report_close(t)
local addr = rawget(t, "address")
if addr then
skynet.send(addr, "lua", "close")
end
end
local sharetable = setmetatable ( {} , {
__index = load_service,
__gc = report_close,
})
function sharetable.loadfile(filename, ...)
skynet.call(sharetable.address, "lua", "loadfile", filename, ...)
end
function sharetable.loadstring(filename, source, ...)
skynet.call(sharetable.address, "lua", "loadstring", filename, source, ...)
end
function sharetable.loadtable(filename, tbl)
assert(type(tbl) == "table")
skynet.call(sharetable.address, "lua", "loadtable", filename, skynet.pack(tbl))
end
function sharetable.query(filename)
local newptr = skynet.call(sharetable.address, "lua", "query", filename)
return core.clone(newptr)
end
return sharetable
|
local skynet = require "skynet"
local service = require "skynet.service"
local core = require "skynet.sharetable.core"
local function sharetable_service()
local skynet = require "skynet"
local core = require "skynet.sharetable.core"
local matrix = {} -- all the matrix
local files = {} -- filename : matrix
local clients = {}
local sharetable = {}
local function close_matrix(m)
if m == nil then
return
end
local ptr = m:getptr()
local ref = matrix[ptr]
if ref == nil or ref.count == 0 then
matrix[ptr] = nil
m:close()
end
end
function sharetable.loadfile(source, filename, ...)
close_matrix(files[filename])
local m = core.matrix("@" .. filename, ...)
files[filename] = m
skynet.ret()
end
function sharetable.loadstring(source, filename, datasource, ...)
close_matrix(files[filename])
local m = core.matrix(datasource, ...)
files[filename] = m
skynet.ret()
end
local function loadtable(filename, ptr, len)
close_matrix(files[filename])
local m = core.matrix([[
local unpack, ptr, len = ...
return unpack(ptr, len)
]], skynet.unpack, ptr, len)
files[filename] = m
end
function sharetable.loadtable(source, filename, ptr, len)
local ok, err = pcall(loadtable, filename, ptr, len)
skynet.trash(ptr, len)
assert(ok, err)
skynet.ret()
end
local function query_file(source, filename)
local m = files[filename]
local ptr = m:getptr()
local ref = matrix[ptr]
if ref == nil then
ref = {
filename = filename,
count = 0,
matrix = m,
refs = {},
}
matrix[ptr] = ref
end
if ref.refs[source] == nil then
ref.refs[source] = true
local list = clients[source]
if not list then
clients[source] = { ptr }
else
table.insert(list, ptr)
end
ref.count = ref.count + 1
end
return ptr
end
function sharetable.query(source, filename)
local m = files[filename]
if m == nil then
skynet.ret()
return
end
local ptr = query_file(source, filename)
skynet.ret(skynet.pack(ptr))
end
function sharetable.close(source)
local list = clients[source]
if list then
for _, ptr in ipairs(list) do
local ref = matrix[ptr]
if ref and ref.refs[source] then
ref.refs[source] = nil
ref.count = ref.count - 1
if ref.count == 0 then
if files[ref.filename] ~= ref.matrix then
-- It's a history version
skynet.error(string.format("Delete a version (%s) of %s", ptr, ref.filename))
ref.matrix:close()
matrix[ptr] = nil
end
end
end
end
clients[source] = nil
end
-- no return
end
skynet.dispatch("lua", function(_,source,cmd,...)
sharetable[cmd](source,...)
end)
skynet.info_func(function()
local info = {}
for filename, m in pairs(files) do
info[filename] = {
current = m:getptr(),
size = m:size(),
}
end
local function address(refs)
local keys = {}
for addr in pairs(refs) do
table.insert(keys, skynet.address(addr))
end
table.sort(keys)
return table.concat(keys, ",")
end
for ptr, copy in pairs(matrix) do
local v = info[copy.filename]
local h = v.history
if h == nil then
h = {}
v.history = h
end
table.insert(h, string.format("%s [%d]: (%s)", copy.matrix:getptr(), copy.matrix:size(), address(copy.refs)))
end
for _, v in pairs(info) do
if v.history then
v.history = table.concat(v.history, "\n\t")
end
end
return info
end)
end
local function load_service(t, key)
if key == "address" then
t.address = service.new("sharetable", sharetable_service)
return t.address
else
return nil
end
end
local function report_close(t)
local addr = rawget(t, "address")
if addr then
skynet.send(addr, "lua", "close")
end
end
local sharetable = setmetatable ( {} , {
__index = load_service,
__gc = report_close,
})
function sharetable.loadfile(filename, ...)
skynet.call(sharetable.address, "lua", "loadfile", filename, ...)
end
function sharetable.loadstring(filename, source, ...)
skynet.call(sharetable.address, "lua", "loadstring", filename, source, ...)
end
function sharetable.loadtable(filename, tbl)
assert(type(tbl) == "table")
skynet.call(sharetable.address, "lua", "loadtable", filename, skynet.pack(tbl))
end
function sharetable.query(filename)
local newptr = skynet.call(sharetable.address, "lua", "query", filename)
if newptr then
return core.clone(newptr)
end
end
return sharetable
|
fix #1011
|
fix #1011
|
Lua
|
mit
|
xcjmine/skynet,xcjmine/skynet,icetoggle/skynet,cloudwu/skynet,xjdrew/skynet,hongling0/skynet,cloudwu/skynet,wangyi0226/skynet,JiessieDawn/skynet,ag6ag/skynet,pigparadise/skynet,sanikoyes/skynet,xcjmine/skynet,icetoggle/skynet,pigparadise/skynet,jxlczjp77/skynet,icetoggle/skynet,jxlczjp77/skynet,JiessieDawn/skynet,hongling0/skynet,wangyi0226/skynet,cloudwu/skynet,korialuo/skynet,xjdrew/skynet,JiessieDawn/skynet,ag6ag/skynet,hongling0/skynet,pigparadise/skynet,korialuo/skynet,wangyi0226/skynet,bigrpg/skynet,korialuo/skynet,sanikoyes/skynet,bigrpg/skynet,jxlczjp77/skynet,xjdrew/skynet,bigrpg/skynet,sanikoyes/skynet,ag6ag/skynet
|
da0fe31443df586198c1265d08deb5458017e664
|
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.5, -0.35, -0.5, 0.5, 0.15, 0.5},
visual = "mesh",
mesh = "boats_boat.obj",
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)
local pos = clicker:getpos()
pos = {x = pos.x, y = pos.y + 0.2, z = pos.z}
minetest.after(0.1, function()
clicker:setpos(pos)
end)
elseif not self.driver then
local attach = clicker:get_attach()
if attach and attach:get_luaentity() then
local luaentity = attach:get_luaentity()
if luaentity.driver then
luaentity.driver = nil
end
clicker:set_detach()
end
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)
if not puncher or not puncher:is_player() or self.removed then
return
end
if self.driver and puncher == self.driver then
self.driver = nil
puncher:set_detach()
default.player_attached[puncher:get_player_name()] = false
end
if not self.driver then
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
local inv = puncher:get_inventory()
if inv:room_for_item("main", "boats:boat") then
inv:add_item("main", "boats:boat")
else
minetest.add_item(self.object:getpos(), "boats:boat")
end
end
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
elseif ctrl.down then
self.v = self.v - 0.1
end
if ctrl.left then
if self.v < 0 then
self.object:setyaw(yaw - (1 + dtime) * 0.03)
else
self.object:setyaw(yaw + (1 + dtime) * 0.03)
end
elseif ctrl.right then
if self.v < 0 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
self.object:setpos(self.object:getpos())
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) > 5 then
self.v = 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}
end
new_velo = get_velocity(self.v, self.object:getyaw(),
self.object:getvelocity().y)
self.object:setpos(self.object:getpos())
else
p.y = p.y + 1
if is_water(p) then
local y = self.object:getvelocity().y
if y >= 5 then
y = 5
elseif y < 0 then
new_acce = {x = 0, y = 20, z = 0}
else
new_acce = {x = 0, y = 5, z = 0}
end
new_velo = get_velocity(self.v, self.object:getyaw(), y)
self.object:setpos(self.object:getpos())
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)
self.object:setpos(self.object:getpos())
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 = "boats_inventory.png",
wield_image = "boats_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,
-- Warning: Do not change the position of the collisionbox top surface,
-- lowering it causes the boat to fall through the world if underwater
collisionbox = {-0.5, -0.35, -0.5, 0.5, 0.3, 0.5},
visual = "mesh",
mesh = "boats_boat.obj",
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)
local pos = clicker:getpos()
pos = {x = pos.x, y = pos.y + 0.2, z = pos.z}
minetest.after(0.1, function()
clicker:setpos(pos)
end)
elseif not self.driver then
local attach = clicker:get_attach()
if attach and attach:get_luaentity() then
local luaentity = attach:get_luaentity()
if luaentity.driver then
luaentity.driver = nil
end
clicker:set_detach()
end
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)
if not puncher or not puncher:is_player() or self.removed then
return
end
if self.driver and puncher == self.driver then
self.driver = nil
puncher:set_detach()
default.player_attached[puncher:get_player_name()] = false
end
if not self.driver then
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
local inv = puncher:get_inventory()
if inv:room_for_item("main", "boats:boat") then
inv:add_item("main", "boats:boat")
else
minetest.add_item(self.object:getpos(), "boats:boat")
end
end
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
elseif ctrl.down then
self.v = self.v - 0.1
end
if ctrl.left then
if self.v < 0 then
self.object:setyaw(yaw - (1 + dtime) * 0.03)
else
self.object:setyaw(yaw + (1 + dtime) * 0.03)
end
elseif ctrl.right then
if self.v < 0 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
self.object:setpos(self.object:getpos())
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) > 5 then
self.v = 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}
end
new_velo = get_velocity(self.v, self.object:getyaw(),
self.object:getvelocity().y)
self.object:setpos(self.object:getpos())
else
p.y = p.y + 1
if is_water(p) then
local y = self.object:getvelocity().y
if y >= 5 then
y = 5
elseif y < 0 then
new_acce = {x = 0, y = 20, z = 0}
else
new_acce = {x = 0, y = 5, z = 0}
end
new_velo = get_velocity(self.v, self.object:getyaw(), y)
self.object:setpos(self.object:getpos())
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)
self.object:setpos(self.object:getpos())
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 = "boats_inventory.png",
wield_image = "boats_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"},
},
})
|
Boats: Raise collisionbox top surface to fix boat behaviour
|
Boats: Raise collisionbox top surface to fix boat behaviour
Lowering the top surface to be level with the boat top somehow
causes the boat to fall through world if underwater. Revert to
previous position that is needed for correct behaviour
|
Lua
|
lgpl-2.1
|
evrooije/beerarchy,evrooije/beerarchy,evrooije/beerarchy
|
f868b9d4be8987adc3b5dc43c69ff33d36d49c62
|
modules/hmi_connection.lua
|
modules/hmi_connection.lua
|
local json = require("json")
local module = { mt = { __index = { } } }
function module.mt.__index:Connect()
self.connection:Connect()
end
local resultCodes =
{
SUCCESS = 0,
UNSUPPORTED_REQUEST = 1,
UNSUPPORTED_RESOURCE = 2,
DISALLOWED = 3,
REJECTED = 4,
ABORTED = 5,
IGNORED = 6,
RETRY = 7,
IN_USE = 8,
DATA_NOT_AVAILABLE = 9,
TIMED_OUT = 10,
INVALID_DATA = 11,
CHAR_LIMIT_EXCEEDED = 12,
INVALID_ID = 13,
DUPLICATE_NAME = 14,
APPLICATION_NOT_REGISTERED = 15,
WRONG_LANGUAGE = 16,
OUT_OF_MEMORY = 17,
TOO_MANY_PENDING_REQUESTS = 18,
NO_APPS_REGISTERED = 19,
NO_DEVICES_CONNECTED = 20,
WARNINGS = 21,
GENERIC_ERROR = 22,
USER_DISALLOWED = 23,
TRUNCATED_DATA = 24,
SAVED = 25
}
function module.mt.__index:Send(text)
xmlReporter.AddMessage("hmi_connection","Send",{["json"] = tostring(text)})
self.connection:Send(text)
end
function module.mt.__index:SendRequest(methodName, params)
data = {}
self.requestId = self.requestId + 1
data.jsonrpc = "2.0"
data.id = self.requestId
data.method = methodName
data.params = params
local text = json.encode(data)
self:Send(text)
xmlReporter.AddMessage("hmi_connection",{["RequestId"] = tostring(self.requestId),["Type"] = "SendRequest"},{ ["methodName"] = methodName,["params"]=params } )
return self.requestId
end
function module.mt.__index:SendNotification(methodName, params)
xmlReporter.AddMessage("hmi_connection","SendNotification",{ ["methodName"] = methodName, ["params"] = params } )
local data = {}
data.method = methodName
data.jsonrpc = "2.0"
data.params = params
local text = json.encode(data)
self:Send(text)
end
function module.mt.__index:SendResponse(id, methodName, code, params)
xmlReporter.AddMessage("hmi_connection","SendResponse",{ ["id"] = id, ["methodName"] = tostring(methodName), ["code"] = code , ["params"] = params} )
local data = {}
self.requestId = self.requestId + 1
data.jsonrpc = "2.0"
data.id = id
data.result = {
method = methodName,
code = resultCodes[code]
}
for k, v in pairs(params) do
data.result[k] = v
end
local text = json.encode(data)
self:Send(text)
end
function module.mt.__index:SendError(id, methodName, code, errorMessage)
xmlReporter.AddMessage("hmi_connection","SendError",{["id"] = id, ["methodName"] = methodName, ["code"] = code,["errorMessage"] = errorMessage } )
local data = {}
data.error = {}
data.error.data = {}
data.id = id
data.jsonrpc = "2.0"
data.error.data.method = methodName
data.error.code = resultCodes[code]
data.error.message = errorMessage
local text = json.encode(data)
self:Send(text)
end
function module.mt.__index:OnInputData(func)
self.connection:OnInputData(function(_, data)
func(self, data)
end)
end
function module.mt.__index:OnConnected(func)
self.connection:OnConnected(function() func(self) end)
end
function module.mt.__index:OnDisconnected(func)
self.connection:OnDisconnected(function() func(self) end)
end
function module.mt.__index:Close()
self.connection:Close()
end
function module.Connection(connection)
local res = { }
res.connection = connection
res.requestId = 0
setmetatable(res, module.mt)
return res
end
return module
|
local json = require("json")
local module = { mt = { __index = { } } }
function module.mt.__index:Connect()
self.connection:Connect()
end
local resultCodes =
{
SUCCESS = 0,
UNSUPPORTED_REQUEST = 1,
UNSUPPORTED_RESOURCE = 2,
DISALLOWED = 3,
REJECTED = 4,
ABORTED = 5,
IGNORED = 6,
RETRY = 7,
IN_USE = 8,
DATA_NOT_AVAILABLE = 9,
TIMED_OUT = 10,
INVALID_DATA = 11,
CHAR_LIMIT_EXCEEDED = 12,
INVALID_ID = 13,
DUPLICATE_NAME = 14,
APPLICATION_NOT_REGISTERED = 15,
WRONG_LANGUAGE = 16,
OUT_OF_MEMORY = 17,
TOO_MANY_PENDING_REQUESTS = 18,
NO_APPS_REGISTERED = 19,
NO_DEVICES_CONNECTED = 20,
WARNINGS = 21,
GENERIC_ERROR = 22,
USER_DISALLOWED = 23,
TRUNCATED_DATA = 24,
SAVED = 25
}
function module.mt.__index:Send(text)
xmlReporter.AddMessage("hmi_connection","Send",{["json"] = tostring(text)})
self.connection:Send(text)
end
function module.mt.__index:SendRequest(methodName, params)
data = {}
self.requestId = self.requestId + 1
data.jsonrpc = "2.0"
data.id = self.requestId
data.method = methodName
data.params = params
local text = json.encode(data)
self:Send(text)
xmlReporter.AddMessage("hmi_connection",{["RequestId"] = tostring(self.requestId),["Type"] = "SendRequest"},{ ["methodName"] = methodName,["params"]=params } )
return self.requestId
end
function module.mt.__index:SendNotification(methodName, params)
xmlReporter.AddMessage("hmi_connection","SendNotification",{ ["methodName"] = methodName, ["params"] = params } )
local data = {}
data.method = methodName
data.jsonrpc = "2.0"
data.params = params
local text = json.encode(data)
self:Send(text)
end
function module.mt.__index:SendResponse(id, methodName, code, params)
xmlReporter.AddMessage("hmi_connection","SendResponse",{ ["id"] = id, ["methodName"] = tostring(methodName), ["code"] = code , ["params"] = params} )
local data = {}
self.requestId = self.requestId + 1
data.jsonrpc = "2.0"
data.id = id
data.result = {
method = methodName,
code = resultCodes[code]
}
if params ~= nil then
for k, v in pairs(params) do
data.result[k] = v
end
end
local text = json.encode(data)
self:Send(text)
end
function module.mt.__index:SendError(id, methodName, code, errorMessage)
xmlReporter.AddMessage("hmi_connection","SendError",{["id"] = id, ["methodName"] = methodName, ["code"] = code,["errorMessage"] = errorMessage } )
local data = {}
data.error = {}
data.error.data = {}
data.id = id
data.jsonrpc = "2.0"
data.error.data.method = methodName
data.error.code = resultCodes[code]
data.error.message = errorMessage
local text = json.encode(data)
self:Send(text)
end
function module.mt.__index:OnInputData(func)
self.connection:OnInputData(function(_, data)
func(self, data)
end)
end
function module.mt.__index:OnConnected(func)
self.connection:OnConnected(function() func(self) end)
end
function module.mt.__index:OnDisconnected(func)
self.connection:OnDisconnected(function() func(self) end)
end
function module.mt.__index:Close()
self.connection:Close()
end
function module.Connection(connection)
local res = { }
res.connection = connection
res.requestId = 0
setmetatable(res, module.mt)
return res
end
return module
|
Fix SendResponse in case params come nil
|
Fix SendResponse in case params come nil
If params value is nil then it should be skipped
|
Lua
|
bsd-3-clause
|
aderiabin/sdl_atf,aderiabin/sdl_atf,aderiabin/sdl_atf
|
f26e62dcc00cc340ffd3cc0b4cb4f676c63b53e5
|
pairwise/src/lua/example.lua
|
pairwise/src/lua/example.lua
|
-- This is an example of how an "all pairs" run could be achieved with
-- Lua script.
-- The pairwise executable automatically looks for a coroutine named
-- "pair_generator" in any Lua script, so by so naming the coroutine
-- you don't need to specify a different function name.
-- You can define arbitrary globals that you then reference in
-- functions/coroutines.
feature_count=4
function pair_generator( N )
for i = 0,(N-1) do
for j = i+1,(N-1) do
coroutine.yield (i,j)
end
end
-- Just "fall off the end"; no need to "return" anything else.
end
-- Lua has special syntax for iterating arrays similar to the items(),
-- keys() and values() methods on Python's dict type.
function cross_product( N )
local L = {3,5,7,11}
local R = {2,4,6,8}
for i,l in ipairs(L) do
for j,r in ipairs(R) do
coroutine.yield( l, r )
end
end
end
function one_versus_all()
fixed = 3
for i = 0,(feature_count-1) do
if i ~= fixed then
coroutine.yield (3,i)
end
end
end
-- A 2-arg mathematical function
function f(x,y)
return ( x^2 * math.sin(y) ) / (1-x)
end
|
-- This is an example of how an "all pairs" run could be achieved with
-- Lua script.
-- The pairwise executable automatically looks for a coroutine named
-- "pair_generator" in any Lua script, so by so naming the coroutine
-- you don't need to specify a different function name.
-- The 'pairwise' executable looks for a function named pair_generator
-- by default, but you can tell it to look for a different function
-- with the --coroutine/-c option.
function pair_generator( matrix_row_count )
for i = 0,(matrix_row_count-1) do
for j = i+1,(matrix_row_count-1) do
coroutine.yield (i,j)
end
end
-- Just "fall off the end"; no need to "return" anything else.
end
-- Lua has special syntax for iterating arrays similar to the items(),
-- keys() and values() methods on Python's dict type.
function cross_product( matrix_row_count )
local L = {3,5,7,11}
local R = {2,4,6,8}
for i,l in ipairs(L) do
for j,r in ipairs(R) do
coroutine.yield( l, r )
end
end
end
-- You can define arbitrary globals that you then reference in
-- functions/coroutines.
FIXED = 3
function one_versus_all( matrix_row_count )
for i = 0,(matrix_row_count-1) do
if i ~= FIXED then
coroutine.yield (FIXED,i)
end
end
end
-- A 2-arg mathematical function (irrelevant to pairwise. part of
-- testing).
function f(x,y)
return ( x^2 * math.sin(y) ) / (1-x)
end
|
fixed one_versus_all Lua example
|
fixed one_versus_all Lua example
|
Lua
|
mit
|
IlyaLab/kramtools,IlyaLab/kramtools,IlyaLab/kramtools,IlyaLab/kramtools,IlyaLab/kramtools,IlyaLab/kramtools
|
84949253a57b43d510f572903c85cc06171205c7
|
src/premake4.lua
|
src/premake4.lua
|
-- Procedurally Generated Transitional Audio Build --
target_dir = path.getabsolute("../bin/") .. "/"
local sdks_dir = (path.getabsolute("../../SDKs/") .. "/")
local ogg_dir = (sdks_dir .. "libogg-1.3.2/")
local vorbis_dir = (sdks_dir .. "libvorbis-1.3.4/")
local oalwrapper_dir = (sdks_dir .. "OALWrapper/")
local oalsoft_dir = (sdks_dir .. "openal-soft-1.15.1/")
local sdl2_dir = (sdks_dir .. "SDL2-2.0.3/")
local proto_dir = (sdks_dir .. "protobuf-2.5.0/")
-- A solution contains projects, and defines the available configurations
solution "pgta_engine"
location "build"
startproject "pgta_engine"
platforms { "x64", "x32" }
configurations { "Debug", "Release" }
flags { "Symbols" }
filter { "action:vs*" }
flags
{
"StaticRuntime", "NoMinimalRebuild", "NoEditAndContinue", "MultiProcessorCompile"
}
defines
{
"_CRT_SECURE_NO_WARNINGS",
"_SCL_SECURE_NO_WARNINGS",
"_CRT_NONSTDC_NO_DEPRECATE",
"SDL_MAIN_HANDLED"
}
filter {}
filter { "platforms:x32" }
targetsuffix "_x32"
filter { "platforms:x64" }
targetsuffix "_x64"
filter {}
filter { "Release" }
flags { "LinkTimeOptimization" }
optimize "Full"
filter {}
-- A project defines one build target
project "pgta_engine"
kind "ConsoleApp"
targetdir "../bin"
language "C++"
files
{
"pgta_engine/**.h",
"pgta_engine/**.cpp",
"pgta_engine/**.cc"
}
filter { "Debug" }
defines { "DEBUG", "_DEBUG" }
filter { "Release" }
defines { "NDEBUG" }
filter {}
filter { "system:macosx" }
buildoptions
{
"-std=c++11"
}
includedirs
{
path.getabsolute("../../OALWrapper/include/"),
"/usr/local/include/SDL2/"
}
libdirs
{
path.getabsolute("../../OALWrapper/build/")
}
links
{
"OALWrapper", "ogg", "vorbisfile", "OpenAL", "SDLmain", "SDL", "SDL2"
}
filter {}
-- include libogg
dofile (ogg_dir .. "premake5_include.lua")
-- include libvorbis
dofile (vorbis_dir .. "premake5_include.lua")
-- include OALWrapper
dofile (oalwrapper_dir .. "premake5_include.lua")
-- include openal-soft
copy_oal_dll = true
dofile (oalsoft_dir .. "premake5_include.lua")
-- include sdl2
copy_sdl_dll = true
dofile (sdl2_dir .. "premake5_include.lua")
-- include protobuf
dofile (proto_dir .. "premake5_include.lua")
|
-- Procedurally Generated Transitional Audio Build --
target_dir = path.getabsolute("../bin/") .. "/"
local sdks_dir = (path.getabsolute("../../SDKs/") .. "/")
local ogg_dir = (sdks_dir .. "libogg-1.3.2/")
local vorbis_dir = (sdks_dir .. "libvorbis-1.3.4/")
local oalwrapper_dir = (sdks_dir .. "OALWrapper/")
local oalsoft_dir = (sdks_dir .. "openal-soft-1.15.1/")
local sdl2_dir = (sdks_dir .. "SDL2-2.0.3/")
local proto_dir = (sdks_dir .. "protobuf-2.5.0/")
-- A solution contains projects, and defines the available configurations
solution "pgta_engine"
location "build"
startproject "pgta_engine"
platforms { "x64", "x32" }
configurations { "Debug", "Release" }
flags { "Symbols" }
filter { "action:vs*" }
flags
{
"StaticRuntime", "NoMinimalRebuild", "NoEditAndContinue", "MultiProcessorCompile"
}
defines
{
"_CRT_SECURE_NO_WARNINGS",
"_SCL_SECURE_NO_WARNINGS",
"_CRT_NONSTDC_NO_DEPRECATE",
"SDL_MAIN_HANDLED"
}
filter {}
filter { "platforms:x32" }
targetsuffix "_x32"
filter { "platforms:x64" }
targetsuffix "_x64"
filter {}
filter { "Release" }
flags { "LinkTimeOptimization" }
optimize "Full"
filter {}
-- A project defines one build target
project "pgta_engine"
kind "ConsoleApp"
targetdir "../bin"
language "C++"
files
{
"pgta_engine/**.h",
"pgta_engine/**.cpp",
"pgta_engine/**.cc"
}
filter { "Debug" }
defines { "DEBUG", "_DEBUG" }
filter { "Release" }
defines { "NDEBUG" }
filter {}
filter { "system:macosx" }
buildoptions
{
"-I/System/Library/Frameworks/OpenAL.framework/Headers",
"-std=c++11"
}
includedirs
{
path.getabsolute("../../OALWrapper/include/"),
"/usr/local/include/SDL2/"
}
libdirs
{
path.getabsolute("../../OALWrapper/build/")
}
links
{
"OALWrapper", "ogg", "vorbisfile", "OpenAL", "SDLmain", "SDL", "SDL2", "protobuf"
}
linkoptions
{
"-framework OpenAL"
}
filter {}
if (os.get() ~= "macosx") then
-- include libogg
dofile (ogg_dir .. "premake5_include.lua")
-- include libvorbis
dofile (vorbis_dir .. "premake5_include.lua")
-- include OALWrapper
dofile (oalwrapper_dir .. "premake5_include.lua")
-- include openal-soft
copy_oal_dll = true
dofile (oalsoft_dir .. "premake5_include.lua")
-- include sdl2
copy_sdl_dll = true
dofile (sdl2_dir .. "premake5_include.lua")
-- include protobuf
dofile (proto_dir .. "premake5_include.lua")
end
|
Fixed premake script for OSX.
|
Fixed premake script for OSX.
|
Lua
|
mit
|
PGTA/PGTA,PGTA/PGTA,PGTA/PGTA
|
d7b87e6a3e955d335c1ad9d7581a1fe3bb6e3538
|
tests/sample.lua
|
tests/sample.lua
|
local cutil = require "cutil"
function filter_spec_chars(s)
local ss = {}
for k = 1, #s do
local c = string.byte(s,k)
if not c then break end
if c<192 then
if (c>=48 and c<=57) or (c>= 65 and c<=90) or (c>=97 and c<=122) then
table.insert(ss, string.char(c))
end
elseif c<224 then
k = k + 1
elseif c<240 then
if c>=228 and c<=233 then
local c1 = string.byte(s,k+1)
local c2 = string.byte(s,k+2)
if c1 and c2 then
local a1,a2,a3,a4 = 128,191,128,191
if c == 228 then a1 = 184
elseif c == 233 then a2,a4 = 190,c1 ~= 190 and 191 or 165
end
if c1>=a1 and c1<=a2 and c2>=a3 and c2<=a4 then
table.insert(ss, string.char(c,c1,c2))
end
end
end
k = k + 2
elseif c<248 then
k = k + 3
elseif c<252 then
k = k + 4
elseif c<254 then
k = k + 5
end
end
return table.concat(ss)
end
ss = '$s%sfoo"a"你好xiao银仔y、,。~!@#¥%……&×(){}|:“《》?y、,。~!@#¥%……&×(){}|:“《》?"foo%%23333|'
print("lua version: ", filter_spec_chars(ss))
print("cutil version: ", cutil.filter_spec_chars(ss))
print("efficiency comparison: ")
t = os.clock()
for k = 1,100000 do
filter_spec_chars(ss)
end
t1 = os.clock()
print("test lua version: ", t1-t) -- 5.20
t = os.clock()
for k = 1,100000 do
cutil.filter_spec_chars(ss)
end
t1 = os.clock()
print("test cutil version: ", t1-t) -- 0.05
|
local cutil = require "cutil"
function filter_spec_chars(s)
local ss = {}
local k = 1
while true do
if k > #s then break end
local c = string.byte(s,k)
if not c then break end
if c<192 then
if (c>=48 and c<=57) or (c>= 65 and c<=90) or (c>=97 and c<=122) then
table.insert(ss, string.char(c))
end
k = k + 1
elseif c<224 then
k = k + 2
elseif c<240 then
if c>=228 and c<=233 then
local c1 = string.byte(s,k+1)
local c2 = string.byte(s,k+2)
if c1 and c2 then
local a1,a2,a3,a4 = 128,191,128,191
if c == 228 then a1 = 184
elseif c == 233 then a2,a4 = 190,c1 ~= 190 and 191 or 165
end
if c1>=a1 and c1<=a2 and c2>=a3 and c2<=a4 then
table.insert(ss, string.char(c,c1,c2))
end
end
end
k = k + 3
elseif c<248 then
k = k + 4
elseif c<252 then
k = k + 5
elseif c<254 then
k = k + 6
end
end
return table.concat(ss)
end
ss = '$s%sfoo"a"你好xiao银仔y、,。~!@#¥%……&×(){}|:“《》?y、,。~!@#¥%……&×(){}|:“《》?"foo%%23333|'
print("lua version: ", filter_spec_chars(ss))
print("cutil version: ", cutil.filter_spec_chars(ss))
print("efficiency comparison: ")
t = os.clock()
for k = 1,100000 do
filter_spec_chars(ss)
end
t1 = os.clock()
print("test lua version: ", t1-t) -- 5.20
t = os.clock()
for k = 1,100000 do
cutil.filter_spec_chars(ss)
end
t1 = os.clock()
print("test cutil version: ", t1-t) -- 0.05
|
bugfix
|
bugfix
temporary variables ( k ) do not work
|
Lua
|
mit
|
chenweiqi/lua-cutil
|
fa40d4c925f47780de0d032c6acf5c1df0abb1c8
|
conf/srv_router.lua
|
conf/srv_router.lua
|
local resolver = require "resty.dns.resolver"
function abort(reason, code)
ngx.status = code
ngx.say(reason)
return code
end
function log(msg)
ngx.log(ngx.ERR, msg, "\n")
end
-- log("Checking if it's in the " .. #domains .." known domains")
-- for k,domain in pairs(domains) do
-- log(" - " .. domain)
-- end
function service_name(reqdomain)
for k,domain in pairs(domains) do
--log("matching " .. reqdomain .. " with " .. domain)
if string.match(reqdomain, domain) then
--log("matched!")
pattern = "%.?" .. domain -- includes separation dot if present
--log("pattern: " .. pattern)
upstream = string.gsub(reqdomain,pattern,"")
-- strip the port from the host header
upstream = string.gsub(upstream,":%d+","")
if upstream == "" then
return "home"
end
-- return leftmost zone (in case further subdomains exists)
return string.match(upstream,"[^\\.]*$")
else
log("no match :(")
end
end
return "unknown"
end
--log("Service should be in " .. service_name(ngx.var.http_host))
-- TODO remove domain from host
-- TODO handle root of the domain
local query_subdomain = service_name(ngx.var.http_host) .. "." .. ngx.var.target_domain
local nameserver = {ngx.var.ns_ip, ngx.var.ns_port}
local dns, err = resolver:new{
nameservers = {nameserver}, retrans = 2, timeout = 250
}
if not dns then
log("failed to instantiate the resolver: " .. err)
return abort("DNS error", 500)
end
log("Querying " .. query_subdomain)
local records, err = dns:query(query_subdomain, {qtype = dns.TYPE_SRV})
if not records then
log("failed to query the DNS server: " .. err)
return abort("Internal routing error", 500)
end
if records.errcode then
-- error code meanings available in http://bit.ly/1ppRk24
if records.errcode == 3 then
return abort("Not found", 404)
else
log("DNS error #" .. records.errcode .. ": " .. records.errstr)
return abort("DNS error", 500)
end
end
if records[1].port then
-- resolve the target to an IP
local target_ip = dns:query(records[1].target)[1].address
-- pass the target ip to avoid resolver errors
ngx.var.target = target_ip .. ":" .. records[1].port
else
log("DNS answer didn't include a port")
return abort("Unknown destination port", 500)
end
|
local resolver = require "resty.dns.resolver"
function abort(reason, code)
ngx.status = code
ngx.say(reason)
return code
end
function log(msg)
ngx.log(ngx.ERR, msg, "\n")
end
-- log("Checking if it's in the " .. #domains .." known domains")
-- for k,domain in pairs(domains) do
-- log(" - " .. domain)
-- end
function service_name(reqdomain)
for k,domain in pairs(domains) do
--log("matching " .. reqdomain .. " with " .. domain)
if string.match(reqdomain, domain) then
--log("matched!")
pattern = "%.?" .. domain -- includes separation dot if present
--log("pattern: " .. pattern)
upstream = string.gsub(reqdomain,pattern,"")
-- strip the port from the host header
upstream = string.gsub(upstream,":%d+","")
if upstream == "" then
return "home"
end
return upstream
else
log("no match :(")
end
end
return "unknown"
end
--log("Service should be in " .. service_name(ngx.var.http_host))
-- TODO remove domain from host
-- TODO handle root of the domain
local query_subdomain = service_name(ngx.var.http_host) .. "." .. ngx.var.target_domain
local nameserver = {ngx.var.ns_ip, ngx.var.ns_port}
local dns, err = resolver:new{
nameservers = {nameserver}, retrans = 2, timeout = 250
}
if not dns then
log("failed to instantiate the resolver: " .. err)
return abort("DNS error", 500)
end
log("Querying " .. query_subdomain)
local records, err = dns:query(query_subdomain, {qtype = dns.TYPE_SRV})
if not records then
log("failed to query the DNS server: " .. err)
return abort("Internal routing error", 500)
end
if records.errcode then
-- error code meanings available in http://bit.ly/1ppRk24
if records.errcode == 3 then
return abort("Not found", 404)
else
log("DNS error #" .. records.errcode .. ": " .. records.errstr)
return abort("DNS error", 500)
end
end
if records[1].port then
-- resolve the target to an IP
local target_ip = dns:query(records[1].target)[1].address
-- pass the target ip to avoid resolver errors
ngx.var.target = target_ip .. ":" .. records[1].port
else
log("DNS answer didn't include a port")
return abort("Unknown destination port", 500)
end
|
Fix vlipco/srv-router#4
|
Fix vlipco/srv-router#4
|
Lua
|
mit
|
bankofse/proxy
|
25bc09033220b7cfdef98ceca596ed0b1285eaa7
|
vrp/lib/utils.lua
|
vrp/lib/utils.lua
|
-- https://github.com/ImagicTheCat/vRP
-- MIT license (see LICENSE or vrp/vRPShared.lua)
-- This file define global tools required by vRP and vRP extensions.
-- side detection
SERVER = IsDuplicityVersion()
CLIENT = not SERVER
local modules = {}
-- load a lua resource file as module (for a specific side)
-- rsc: resource name
-- path: lua file path without extension
function module(rsc, path)
if path == nil then -- shortcut for vrp, can omit the resource parameter
path = rsc
rsc = "vrp"
end
local key = rsc..path
local module = modules[key]
if module then -- cached module
return module
else
local code = LoadResourceFile(rsc, path..".lua")
if code then
local f, err = load(code, rsc.."/"..path..".lua")
if f then
local ok, res = xpcall(f, debug.traceback)
if ok then
modules[key] = res
return res
else
error("error loading module "..rsc.."/"..path..": "..res)
end
else
error("error parsing module "..rsc.."/"..path..": "..err)
end
else
error("resource file "..rsc.."/"..path..".lua not found")
end
end
end
-- Luaoop class
local Luaoop = module("vrp", "lib/Luaoop")
class = Luaoop.class
-- Luaseq like for FiveM
local function wait(self)
local r = Citizen.Await(self.p)
if not r then
if self.r then
r = self.r
else
error("async wait(): Citizen.Await returned (nil) before the areturn call.")
end
end
return table.unpack(r, 1, r.n)
end
local function areturn(self, ...)
self.r = table.pack(...)
self.p:resolve(self.r)
end
-- create an async returner or a thread (Citizen.CreateThreadNow)
-- func: if passed, will create a thread, otherwise will return an async returner
function async(func)
if func then
Citizen.CreateThreadNow(func)
else
return setmetatable({ wait = wait, p = promise.new() }, { __call = areturn })
end
end
local function hex_conv(c)
return string.format('%02X', string.byte(c))
end
-- convert Lua string to hexadecimal
function tohex(str)
return string.gsub(str, '.', hex_conv)
end
-- basic deep clone function (doesn't handle circular references)
function clone(t)
if type(t) == "table" then
local new = {}
for k,v in pairs(t) do
new[k] = clone(v)
end
return new
else
return t
end
end
function parseInt(v)
local n = tonumber(v)
if n == nil then
return 0
else
return math.floor(n)
end
end
-- will remove chars not allowed/disabled by strchars
-- allow_policy: if true, will allow all strchars, if false, will allow everything except the strchars
local sanitize_tmp = {}
function sanitizeString(str, strchars, allow_policy)
local r = ""
-- get/prepare index table
local chars = sanitize_tmp[strchars]
if chars == nil then
chars = {}
local size = string.len(strchars)
for i=1,size do
local char = string.sub(strchars,i,i)
chars[char] = true
end
sanitize_tmp[strchars] = chars
end
-- sanitize
size = string.len(str)
for i=1,size do
local char = string.sub(str,i,i)
if (allow_policy and chars[char]) or (not allow_policy and not chars[char]) then
r = r..char
end
end
return r
end
function splitString(str, sep)
if sep == nil then sep = "%s" end
local t={}
local i=1
for str in string.gmatch(str, "([^"..sep.."]+)") do
t[i] = str
i = i + 1
end
return t
end
|
-- https://github.com/ImagicTheCat/vRP
-- MIT license (see LICENSE or vrp/vRPShared.lua)
-- This file define global tools required by vRP and vRP extensions.
-- side detection
SERVER = IsDuplicityVersion()
CLIENT = not SERVER
local modules = {}
-- load a lua resource file as module (for a specific side)
-- rsc: resource name
-- path: lua file path without extension
function module(rsc, path)
if not path then -- shortcut for vrp, can omit the resource parameter
path = rsc
rsc = "vrp"
end
local key = rsc.."/"..path
local rets = modules[key]
if rets then -- cached module
return table.unpack(rets, 2, rets.n)
else
local code = LoadResourceFile(rsc, path..".lua")
if code then
local f, err = load(code, rsc.."/"..path..".lua")
if f then
local rets = table.pack(xpcall(f, debug.traceback))
if rets[1] then
modules[key] = rets
return table.unpack(rets, 2, rets.n)
else
error("error loading module "..rsc.."/"..path..": "..res)
end
else
error("error parsing module "..rsc.."/"..path..": "..err)
end
else
error("resource file "..rsc.."/"..path..".lua not found")
end
end
end
-- Luaoop class
local Luaoop = module("vrp", "lib/Luaoop")
class = Luaoop.class
-- Luaseq like for FiveM
local function wait(self)
local r = Citizen.Await(self.p)
if not r then
if self.r then
r = self.r
else
error("async wait(): Citizen.Await returned (nil) before the areturn call.")
end
end
return table.unpack(r, 1, r.n)
end
local function areturn(self, ...)
self.r = table.pack(...)
self.p:resolve(self.r)
end
-- create an async returner or a thread (Citizen.CreateThreadNow)
-- func: if passed, will create a thread, otherwise will return an async returner
function async(func)
if func then
Citizen.CreateThreadNow(func)
else
return setmetatable({ wait = wait, p = promise.new() }, { __call = areturn })
end
end
local function hex_conv(c)
return string.format('%02X', string.byte(c))
end
-- convert Lua string to hexadecimal
function tohex(str)
return string.gsub(str, '.', hex_conv)
end
-- basic deep clone function (doesn't handle circular references)
function clone(t)
if type(t) == "table" then
local new = {}
for k,v in pairs(t) do
new[k] = clone(v)
end
return new
else
return t
end
end
function parseInt(v)
local n = tonumber(v)
if n == nil then
return 0
else
return math.floor(n)
end
end
-- will remove chars not allowed/disabled by strchars
-- allow_policy: if true, will allow all strchars, if false, will allow everything except the strchars
local sanitize_tmp = {}
function sanitizeString(str, strchars, allow_policy)
local r = ""
-- get/prepare index table
local chars = sanitize_tmp[strchars]
if chars == nil then
chars = {}
local size = string.len(strchars)
for i=1,size do
local char = string.sub(strchars,i,i)
chars[char] = true
end
sanitize_tmp[strchars] = chars
end
-- sanitize
size = string.len(str)
for i=1,size do
local char = string.sub(str,i,i)
if (allow_policy and chars[char]) or (not allow_policy and not chars[char]) then
r = r..char
end
end
return r
end
function splitString(str, sep)
if sep == nil then sep = "%s" end
local t={}
local i=1
for str in string.gmatch(str, "([^"..sep.."]+)") do
t[i] = str
i = i + 1
end
return t
end
|
Improve/fix module function.
|
Improve/fix module function.
|
Lua
|
mit
|
ImagicTheCat/vRP,ImagicTheCat/vRP
|
2f47f94d1a79c15ee14ff77dcd8df609544353ed
|
src/plugins/core/preferences/panels/menubar.lua
|
src/plugins/core/preferences/panels/menubar.lua
|
--- === plugins.core.preferences.panels.menubar ===
---
--- Menubar Preferences Panel
--------------------------------------------------------------------------------
--
-- EXTENSIONS:
--
--------------------------------------------------------------------------------
local require = require
--------------------------------------------------------------------------------
-- Hammerspoon Extensions:
--------------------------------------------------------------------------------
local image = require("hs.image")
--------------------------------------------------------------------------------
-- CommandPost Extensions:
--------------------------------------------------------------------------------
local commands = require("cp.commands")
local config = require("cp.config")
local i18n = require("cp.i18n")
local tools = require("cp.tools")
local ui = require("cp.web.ui")
--------------------------------------------------------------------------------
--
-- CONSTANTS:
--
--------------------------------------------------------------------------------
local APPEARANCE_HEADING = 100
local SECTIONS_HEADING = 200
--------------------------------------------------------------------------------
--
-- THE MODULE:
--
--------------------------------------------------------------------------------
local mod = {}
--- plugins.core.preferences.panels.menubar.lastGroup <cp.prop: string>
--- Field
--- Last group used in the Preferences Drop Down.
mod.lastGroup = config.prop("menubarPreferencesLastGroup", nil)
--- plugins.core.preferences.panels.menubar.showSectionHeadingsInMenubar <cp.prop: boolean>
--- Field
--- Show section headings in menubar.
mod.showSectionHeadingsInMenubar = config.prop("showSectionHeadingsInMenubar", true)
--------------------------------------------------------------------------------
--
-- THE PLUGIN:
--
--------------------------------------------------------------------------------
local plugin = {
id = "core.preferences.panels.menubar",
group = "core",
dependencies = {
["core.preferences.manager"] = "prefsMgr",
["core.menu.manager"] = "menuMgr",
}
}
--------------------------------------------------------------------------------
-- INITIALISE PLUGIN:
--------------------------------------------------------------------------------
function plugin.init(deps)
local panel = deps.prefsMgr.addPanel({
priority = 2020,
id = "menubar",
label = i18n("menubarPanelLabel"),
image = image.imageFromPath(tools.iconFallback("/System/Library/PreferencePanes/DesktopScreenEffectsPref.prefPane/Contents/Resources/DesktopScreenEffectsPref.icns", "/System/Library/PreferencePanes/Appearance.prefPane/Contents/Resources/GeneralPrefsIcons.icns")),
tooltip = i18n("menubarPanelTooltip"),
height = 380,
})
--------------------------------------------------------------------------------
-- Setup Menubar Preferences Panel:
--------------------------------------------------------------------------------
panel
:addHeading(APPEARANCE_HEADING, i18n("appearance"))
:addCheckbox(APPEARANCE_HEADING + 1,
{
label = i18n("displayThisMenuAsIcon"),
onchange = function(_, params) deps.menuMgr.displayMenubarAsIcon(params.checked) end,
checked = deps.menuMgr.displayMenubarAsIcon,
}
)
:addCheckbox(APPEARANCE_HEADING + 2,
{
label = i18n("showSectionHeadingsInMenubar"),
onchange = function(_, params) mod.showSectionHeadingsInMenubar(params.checked) end,
checked = mod.showSectionHeadingsInMenubar,
}
)
:addHeading(APPEARANCE_HEADING + 3, i18n("shared") .. " " .. i18n("sections"))
return panel
end
return plugin
|
--- === plugins.core.preferences.panels.menubar ===
---
--- Menubar Preferences Panel
--------------------------------------------------------------------------------
--
-- EXTENSIONS:
--
--------------------------------------------------------------------------------
local require = require
--------------------------------------------------------------------------------
-- Hammerspoon Extensions:
--------------------------------------------------------------------------------
local image = require("hs.image")
--------------------------------------------------------------------------------
-- CommandPost Extensions:
--------------------------------------------------------------------------------
local config = require("cp.config")
local i18n = require("cp.i18n")
local tools = require("cp.tools")
--------------------------------------------------------------------------------
--
-- CONSTANTS:
--
--------------------------------------------------------------------------------
local APPEARANCE_HEADING = 100
local SECTIONS_HEADING = 200
--------------------------------------------------------------------------------
--
-- THE MODULE:
--
--------------------------------------------------------------------------------
local mod = {}
--- plugins.core.preferences.panels.menubar.lastGroup <cp.prop: string>
--- Field
--- Last group used in the Preferences Drop Down.
mod.lastGroup = config.prop("menubarPreferencesLastGroup", nil)
--- plugins.core.preferences.panels.menubar.showSectionHeadingsInMenubar <cp.prop: boolean>
--- Field
--- Show section headings in menubar.
mod.showSectionHeadingsInMenubar = config.prop("showSectionHeadingsInMenubar", true)
--------------------------------------------------------------------------------
--
-- THE PLUGIN:
--
--------------------------------------------------------------------------------
local plugin = {
id = "core.preferences.panels.menubar",
group = "core",
dependencies = {
["core.preferences.manager"] = "prefsMgr",
["core.menu.manager"] = "menuMgr",
}
}
--------------------------------------------------------------------------------
-- INITIALISE PLUGIN:
--------------------------------------------------------------------------------
function plugin.init(deps)
local panel = deps.prefsMgr.addPanel({
priority = 2020,
id = "menubar",
label = i18n("menubarPanelLabel"),
image = image.imageFromPath(tools.iconFallback("/System/Library/PreferencePanes/DesktopScreenEffectsPref.prefPane/Contents/Resources/DesktopScreenEffectsPref.icns", "/System/Library/PreferencePanes/Appearance.prefPane/Contents/Resources/GeneralPrefsIcons.icns")),
tooltip = i18n("menubarPanelTooltip"),
height = 380,
})
--------------------------------------------------------------------------------
-- Setup Menubar Preferences Panel:
--------------------------------------------------------------------------------
panel
:addHeading(APPEARANCE_HEADING, i18n("appearance"))
:addCheckbox(APPEARANCE_HEADING + 1,
{
label = i18n("displayThisMenuAsIcon"),
onchange = function(_, params) deps.menuMgr.displayMenubarAsIcon(params.checked) end,
checked = deps.menuMgr.displayMenubarAsIcon,
}
)
:addCheckbox(APPEARANCE_HEADING + 2,
{
label = i18n("showSectionHeadingsInMenubar"),
onchange = function(_, params) mod.showSectionHeadingsInMenubar(params.checked) end,
checked = mod.showSectionHeadingsInMenubar,
}
)
:addHeading(APPEARANCE_HEADING + 3, i18n("shared") .. " " .. i18n("sections"))
return panel
end
return plugin
|
#650
|
#650
- Fixed @stickler-ci issues
|
Lua
|
mit
|
fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost
|
dbaddabf2b40ce2ff35066a75ea264c439c7cd44
|
lunamark/reader/html.lua
|
lunamark/reader/html.lua
|
local htmlparser = require("lunamark.htmlparser")
local entities = require("lunamark.entities")
local function lookup_attr(node, name)
if node.attr then
for _,x in ipairs(t) do
if x.name == name then
return convert_entities(x.value)
end
end
end
end
local function convert_entities(s)
return s:gsub("&#[Xx](%x+);", entities.hex_entity):gsub("&#(%d+);", entities.dec_entity):gsub("&(%a+);", entities.char_entity)
end
local function handle_nodes(writer, nodes, preserve_space)
local output = {}
local firstblock = true
local function preblockspace()
if firstblock then
firstblock = false
else
table.insert(output, writer.interblocksep)
end
end
local i = 1
while nodes[i] do
local node = nodes[i]
if type(node) == "string" then -- text node
local contents
if preserve_space then
contents = writer.string(convert_entities(node))
else
local s = convert_entities(node)
contents = s:gsub("%s+", writer.space)
end
table.insert(output, contents)
elseif node.tag and node.child then -- tag with contents
local tag = node.tag
local contents = handle_nodes(writer, node.child,
preserve_space or tag == "pre" or tag == "code")
if tag == "p" then
preblockspace()
table.insert(output, writer.paragraph(contents))
elseif tag == "blockquote" then
preblockspace()
table.insert(output, writer.blockquote(contents))
elseif tag == "li" then
table.insert(output, writer.listitem(contents))
elseif tag == "ul" then
preblockspace()
table.insert(output, writer.bulletlist(contents))
elseif tag == "ol" then
preblockspace()
table.insert(output, writer.orderedlist(contents))
elseif tag == "pre" then
preblockspace()
table.insert(output, writer.verbatim(contents))
elseif tag:match("^h[123456]$") then
local lev = tonumber(tag:sub(2,2))
preblockspace()
local bodynodes = {}
while nodes[i+1] do
local nd = nodes[i+1]
if nd.tag and nd.tag:match("^h[123456]$") and
tonumber(nd.tag:sub(2,2)) <= lev then
break
else
table.insert(bodynodes,nd)
end
i = i + 1
end
local body = handle_nodes(writer, bodynodes, preserve_space)
table.insert(output, writer.section(contents, lev, body))
elseif tag == "a" then
local src = lookup_attr(node, "href") or ""
local tit = lookup_attr(node, "title")
table.insert(output, writer.link(contents,src,tit))
elseif tag == "em" or tag == "i" then
table.insert(output, writer.emphasis(contents))
elseif tag == "strong" or tag == "b" then
table.insert(output, writer.strong(contents))
elseif tag == "code" then
table.insert(output, writer.code(contents))
else --skip unknown tag
table.insert(output, contents)
end
elseif node.tag then -- self-closing tag
local tag = node.tag
if tag == "hr" then
preblockspace()
table.insert(output, writer.hrule)
elseif tag == "br" then
preblockspace()
table.insert(output, writer.linebreak)
elseif tag == "img" then
local alt = lookup_attr(node, "alt") or ""
local src = lookup_attr(node, "src") or ""
local tit = lookup_attr(node, "title")
table.insert(output, writer.image(alt,src,tit))
else
-- skip
end
else -- comment or xmlheader
-- skip
end
i = i + 1
end
return table.concat(output)
end
local function html(writer, options)
local function convert(inp)
local parser = htmlparser.new(inp)
local parsed = parser:parse()
return handle_nodes(writer, parsed)
end
return convert
end
return html
|
local htmlparser = require("lunamark.htmlparser")
local entities = require("lunamark.entities")
local function convert_entities(s)
return s:gsub("&#[Xx](%x+);", entities.hex_entity):gsub("&#(%d+);", entities.dec_entity):gsub("&(%a+);", entities.char_entity)
end
local function lookup_attr(node, name)
if node.attrs then
for _,x in ipairs(node.attrs) do
if x.name == name then
return convert_entities(x.value or "")
end
end
end
end
local function handle_nodes(writer, nodes, preserve_space)
local output = {}
local firstblock = true
local function preblockspace()
if firstblock then
firstblock = false
else
table.insert(output, writer.interblocksep)
end
end
local i = 1
while nodes[i] do
local node = nodes[i]
if type(node) == "string" then -- text node
local contents
if preserve_space then
contents = writer.string(convert_entities(node))
else
local s = convert_entities(node)
contents = s:gsub("%s+", writer.space)
end
table.insert(output, contents)
elseif node.tag and node.child then -- tag with contents
local tag = node.tag
local contents = handle_nodes(writer, node.child,
preserve_space or tag == "pre" or tag == "code")
if tag == "p" then
preblockspace()
table.insert(output, writer.paragraph(contents))
elseif tag == "blockquote" then
preblockspace()
table.insert(output, writer.blockquote(contents))
elseif tag == "li" then
table.insert(output, writer.listitem(contents))
elseif tag == "ul" then
preblockspace()
table.insert(output, writer.bulletlist(contents))
elseif tag == "ol" then
preblockspace()
table.insert(output, writer.orderedlist(contents))
elseif tag == "pre" then
preblockspace()
table.insert(output, writer.verbatim(contents))
elseif tag:match("^h[123456]$") then
local lev = tonumber(tag:sub(2,2))
preblockspace()
local bodynodes = {}
while nodes[i+1] do
local nd = nodes[i+1]
if nd.tag and nd.tag:match("^h[123456]$") and
tonumber(nd.tag:sub(2,2)) <= lev then
break
else
table.insert(bodynodes,nd)
end
i = i + 1
end
local body = handle_nodes(writer, bodynodes, preserve_space)
table.insert(output, writer.section(contents, lev, body))
elseif tag == "a" then
local src = lookup_attr(node, "href") or ""
local tit = lookup_attr(node, "title")
table.insert(output, writer.link(contents,src,tit))
elseif tag == "em" or tag == "i" then
table.insert(output, writer.emphasis(contents))
elseif tag == "strong" or tag == "b" then
table.insert(output, writer.strong(contents))
elseif tag == "code" then
table.insert(output, writer.code(contents))
else --skip unknown tag
table.insert(output, contents)
end
elseif node.tag then -- self-closing tag
local tag = node.tag
if tag == "hr" then
preblockspace()
table.insert(output, writer.hrule)
elseif tag == "br" then
preblockspace()
table.insert(output, writer.linebreak)
elseif tag == "img" then
local alt = lookup_attr(node, "alt") or ""
local src = lookup_attr(node, "src") or ""
local tit = lookup_attr(node, "title")
table.insert(output, writer.image(alt,src,tit))
else
-- skip
end
else -- comment or xmlheader
-- skip
end
i = i + 1
end
return table.concat(output)
end
local function html(writer, options)
local function convert(inp)
local parser = htmlparser.new(inp)
local parsed = parser:parse()
return handle_nodes(writer, parsed)
end
return convert
end
return html
|
Fixed lookup_attr in html reader.
|
Fixed lookup_attr in html reader.
|
Lua
|
mit
|
tst2005/lunamark,tst2005/lunamark,jgm/lunamark,jgm/lunamark,simoncozens/lunamark,tst2005/lunamark,simoncozens/lunamark,simoncozens/lunamark,jgm/lunamark
|
792fdac116094300841f85fbce55636d874eae7e
|
module/util/groupids.lua
|
module/util/groupids.lua
|
--[[!
\file
\brief Es un módulo que permite crear grupos de ids y comprobar si una id
está en alguno de estos grupos. Los grupos pueden agruparse paara formar grupos
más complejos, con operadores de negación y or.
]]
loadModule("util/class");
loadModule("util/math/range");
loadModule("util/checkutils");
loadModule("util/stringutils");
--[[!
Esta clase representa un conjunto de IDs arbitrarias.
]]
groupIds = class();
--[[!
Inicializador.
@param ... Es un conjunto de rangos de ids e ids que compondrán al grupo
inicialmente.
@note Si se indican tablas como argumentos deberán ser instancias de la clase
range. Por el contrario, deben ser números.
]]
function groupIds:init(...)
self.ranges = {};
for _, ids in ipairs({...}) do
if type(ids) == "table" then
self:addRangeIds(ids);
else
self:addId(ids);
end;
end;
end;
--[[!
Convierte una cadena de caracteres en un grupo de IDs.
@param str Es la cadena de caracteres donde se especifican las IDs o bien rangos de IDs
separados por comas o por punto y coma
@param symbols Por defecto es una tabla vacía. Es una tabla con grupos de IDs. Los índices son símbolos representativos
de estos grupos (pueden especificarse en la cadena de caracteres a analizar y serán interpretados como el grupo de IDs que representan) y los
valores son los grupos de IDs.
\code
local group = groupIds.fromString("3, 4, 5,3,10,20,30, 70-80, -1);
\endcode
]]
function groupIds.fromString(str, symbols)
-- tokenizar la cadena de caracteres.
local tokens = {};
for token in wpairs(str, ",; ") do tokens[#tokens+1] = token; end;
local group = groupIds();
-- analizar cada token
for _, token in ipairs(tokens) do
if token:match("%d+-%d+") then
local lowerBound, upperBound = token:match("(%d+)-(%d+)");
lowerBound, upperBound = tonumber(lowerBound), tonumber(upperBound);
group:addRangeIds(range(lowerBound, upperBound));
elseif token:match("%d+") then
local id = tonumber(token:match("(%d+)"));
group:addId(id);
else
localizedAssert(symbols and symbols[token], "Failed to parse group IDs; " .. token .. " is not a valid ID our group of IDs", 2);
group = group + symbols[token];
end;
end;
return group;
end;
--[[!
Añade un rango de IDs al conjunto.
]]
function groupIds:addRangeIds(rangeIds)
if #self.ranges > 0 then
-- buscar el primer rango que interseccione con el nuevo rango.
local i = 1;
while (i < #self.ranges) and (not rangeIds:intersectsWith(self.ranges[i]:translate(1, 1))) do
i = i + 1;
end;
if rangeIds:intersectsWith(self.ranges[i]:translate(1, 1)) then
if i < #self.ranges then
-- buscar el primer rango después del rango i que no intersecciona
-- con el nuevo rango.
local j = i;
while ((j+1) < #self.ranges) and rangeIds:intersectsWith(self.ranges[j+1]:translate(1, 1)) do
j = j + 1;
end;
if not rangeIds:intersectsWith(self.ranges[j+1]:translate(1, 1)) then
-- Reemplazamos rangos desde el i+1ésimo hasta el jésimo por un
-- nuevo rango.
local aux = rangeIds:getWrapper(self.ranges[i]):getWrapper(self.ranges[j]);
for k=j,i+1,-1 do
table.remove(self.ranges, k);
end;
self.ranges[i] = aux;
else
-- no hay ningún rango después del rango iésimo que no
-- interseccione con el nuevo rango.
local aux = rangeIds:getWrapper(self.ranges[i]):getWrapper(self.ranges[#self.ranges]);
-- eliminamos todos los rangos a partir del iesimo.
for k=j+1,i+1,-1 do
table.remove(self.ranges, k);
end;
-- insertamos el nuevo rango..
self.ranges[i] = aux;
end;
else
local aux = self.ranges[i];
self.ranges[i] = rangeIds:getWrapper(aux);
end;
else
-- no intersecciona con ningún rango, insertar el nuevo rango
-- después del rango cuyo límite superior es inferior al límite
-- inferior del nuevo rango...
-- buscar ese rango...
if #self.ranges > 1 then
if rangeIds:getUpperBound() < self.ranges[1]:getLowerBound() then
-- añadir al principio.
table.insert(self.ranges, 1, rangeIds);
else
i = 1;
while ((i+1) < #self.ranges) and (rangeIds:getUpperBound() > self.ranges[i+1]:getLowerBound()) do
i = i + 1;
end;
if rangeIds:getUpperBound() < self.ranges[i+1]:getLowerBound() then
table.insert(self.ranges, i+1, rangeIds);
else
table.insert(self.ranges, rangeIds);
end;
end;
else
if rangeIds:getUpperBound() < self.ranges[1]:getLowerBound() then
table.insert(self.ranges, 1, rangeIds);
else
table.insert(self.ranges, rangeIds);
end;
end;
end;
else
table.insert(self.ranges, rangeIds);
end;
end;
--[[!
Añade una id al conjunto.
]]
function groupIds:addId(id)
self:addRangeIds(range(id, id));
end;
--[[!
@return Devuelve todas las IDs que pertenecen a este grupo en una tabla.
@note Las IDs están situadas en la tabla de forma creciente.
]]
function groupIds:getAllIds()
local aux = {};
for _,r in ipairs(self.ranges) do
for i=r:getLowerBound(),r:getUpperBound(),1 do
aux[#aux+1] = i;
end;
end;
return aux;
end;
--[[!
@return Devuelve un valor booleano indicando si una ID está en este conjunto
o no.
]]
function groupIds:isInside(x)
if #self.ranges > 0 then
if #self.ranges > 1 then
-- buscar el rango previo al rango cuyo límite inferior es
-- superior al valor.
if self.ranges[1]:getLowerBound() > x then
return false;
end;
local i = 1;
while ((i+1) < #self.ranges) and (x >= self.ranges[i+1]:getLowerBound()) do
i = i + 1;
end;
if x < self.ranges[i+1]:getLowerBound() then
return x <= self.ranges[i]:getUpperBound();
else
return x <= self.ranges[i+1]:getUpperBound();
end;
end;
return self.ranges[1]:isInside(x);
end;
return false;
end;
--[[!
@return Devuelve not self:isInside(x)
]]
function groupIds:isOutside(x)
return not self:isInside(x);
end;
--[[!
Es un alias de groupIds.isInside
]]
groupIds.has = groupIds.isInside;
--[[!
@return Devuelve un conjunto de IDs que contiene las IDs de dos conjuntos.
(Operación or)
]]
function groupIds.__add(a, b)
local aux = a:clone();
for _, range in ipairs(b.ranges) do
aux:addRangeIds(range);
end;
return aux;
end;
--[[!
@return Devuelve una representación en forma de cadena de caracteres
de este grupo.
]]
function groupIds.__tostring(g)
return "[" .. table.concat(g:getAllIds(), ",") .. "]";
end;
-- Es un grupo que no contiene ninguna ID
groupIds.empty = groupIds();
|
--[[!
\file
\brief Es un módulo que permite crear grupos de ids y comprobar si una id
está en alguno de estos grupos. Los grupos pueden agruparse paara formar grupos
más complejos, con operadores de negación y or.
]]
loadModule("util/class");
loadModule("util/math/range");
loadModule("util/checkutils");
loadModule("util/stringutils");
loadModule("util/tableutils");
--[[!
Esta clase representa un conjunto de IDs arbitrarias.
]]
groupIds = class();
--[[!
Inicializador.
@param ... Es un conjunto de rangos de ids e ids que compondrán al grupo
inicialmente.
@note Si se indican tablas como argumentos deberán ser instancias de la clase
range. Por el contrario, deben ser números.
]]
function groupIds:init(...)
self.ranges = {};
for _, ids in ipairs({...}) do
if type(ids) == "table" then
self:addRangeIds(ids);
else
self:addId(ids);
end;
end;
end;
--[[!
@return Devuelve una copia de este grupo de IDs
]]
function groupIds:clone()
local aux = {};
aux.ranges = table.shallow_copy(self.ranges);
return setmetatable(aux, groupIds);
end;
--[[!
Convierte una cadena de caracteres en un grupo de IDs.
@param str Es la cadena de caracteres donde se especifican las IDs o bien rangos de IDs
separados por comas o por punto y coma
@param symbols Por defecto es una tabla vacía. Es una tabla con grupos de IDs. Los índices son símbolos representativos
de estos grupos (pueden especificarse en la cadena de caracteres a analizar y serán interpretados como el grupo de IDs que representan) y los
valores son los grupos de IDs.
\code
local group = groupIds.fromString("3, 4, 5,3,10,20,30, 70-80, -1);
\endcode
]]
function groupIds.fromString(str, symbols)
-- tokenizar la cadena de caracteres.
local tokens = {};
for token in wpairs(str, ",; ") do tokens[#tokens+1] = token; end;
local group = groupIds();
-- analizar cada token
for _, token in ipairs(tokens) do
if token:match("%d+-%d+") then
local lowerBound, upperBound = token:match("(%d+)-(%d+)");
lowerBound, upperBound = tonumber(lowerBound), tonumber(upperBound);
group:addRangeIds(range(lowerBound, upperBound));
elseif token:match("%d+") then
local id = tonumber(token:match("(%d+)"));
group:addId(id);
else
localizedAssert(symbols and symbols[token], "Failed to parse group IDs; " .. token .. " is not a valid ID our group of IDs", 2);
group = group + symbols[token];
end;
end;
return group;
end;
--[[!
Añade un rango de IDs al conjunto.
]]
function groupIds:addRangeIds(rangeIds)
if #self.ranges > 0 then
-- buscar el primer rango que interseccione con el nuevo rango.
local i = 1;
while (i < #self.ranges) and (not rangeIds:intersectsWith(self.ranges[i]:translate(1, 1))) do
i = i + 1;
end;
if rangeIds:intersectsWith(self.ranges[i]:translate(1, 1)) then
if i < #self.ranges then
-- buscar el primer rango después del rango i que no intersecciona
-- con el nuevo rango.
local j = i;
while ((j+1) < #self.ranges) and rangeIds:intersectsWith(self.ranges[j+1]:translate(1, 1)) do
j = j + 1;
end;
if not rangeIds:intersectsWith(self.ranges[j+1]:translate(1, 1)) then
-- Reemplazamos rangos desde el i+1ésimo hasta el jésimo por un
-- nuevo rango.
local aux = rangeIds:getWrapper(self.ranges[i]):getWrapper(self.ranges[j]);
for k=j,i+1,-1 do
table.remove(self.ranges, k);
end;
self.ranges[i] = aux;
else
-- no hay ningún rango después del rango iésimo que no
-- interseccione con el nuevo rango.
local aux = rangeIds:getWrapper(self.ranges[i]):getWrapper(self.ranges[#self.ranges]);
-- eliminamos todos los rangos a partir del iesimo.
for k=j+1,i+1,-1 do
table.remove(self.ranges, k);
end;
-- insertamos el nuevo rango..
self.ranges[i] = aux;
end;
else
local aux = self.ranges[i];
self.ranges[i] = rangeIds:getWrapper(aux);
end;
else
-- no intersecciona con ningún rango, insertar el nuevo rango
-- después del rango cuyo límite superior es inferior al límite
-- inferior del nuevo rango...
-- buscar ese rango...
if #self.ranges > 1 then
if rangeIds:getUpperBound() < self.ranges[1]:getLowerBound() then
-- añadir al principio.
table.insert(self.ranges, 1, rangeIds);
else
i = 1;
while ((i+1) < #self.ranges) and (rangeIds:getUpperBound() > self.ranges[i+1]:getLowerBound()) do
i = i + 1;
end;
if rangeIds:getUpperBound() < self.ranges[i+1]:getLowerBound() then
table.insert(self.ranges, i+1, rangeIds);
else
table.insert(self.ranges, rangeIds);
end;
end;
else
if rangeIds:getUpperBound() < self.ranges[1]:getLowerBound() then
table.insert(self.ranges, 1, rangeIds);
else
table.insert(self.ranges, rangeIds);
end;
end;
end;
else
table.insert(self.ranges, rangeIds);
end;
end;
--[[!
Añade una id al conjunto.
]]
function groupIds:addId(id)
self:addRangeIds(range(id, id));
end;
--[[!
@return Devuelve todas las IDs que pertenecen a este grupo en una tabla.
@note Las IDs están situadas en la tabla de forma creciente.
]]
function groupIds:getAllIds()
local aux = {};
for _,r in ipairs(self.ranges) do
for i=r:getLowerBound(),r:getUpperBound(),1 do
aux[#aux+1] = i;
end;
end;
return aux;
end;
--[[!
@return Devuelve un valor booleano indicando si una ID está en este conjunto
o no.
]]
function groupIds:isInside(x)
if #self.ranges > 0 then
if #self.ranges > 1 then
-- buscar el rango previo al rango cuyo límite inferior es
-- superior al valor.
if self.ranges[1]:getLowerBound() > x then
return false;
end;
local i = 1;
while ((i+1) < #self.ranges) and (x >= self.ranges[i+1]:getLowerBound()) do
i = i + 1;
end;
if x < self.ranges[i+1]:getLowerBound() then
return x <= self.ranges[i]:getUpperBound();
else
return x <= self.ranges[i+1]:getUpperBound();
end;
end;
return self.ranges[1]:isInside(x);
end;
return false;
end;
--[[!
@return Devuelve not self:isInside(x)
]]
function groupIds:isOutside(x)
return not self:isInside(x);
end;
--[[!
Es un alias de groupIds.isInside
]]
groupIds.has = groupIds.isInside;
--[[!
@return Devuelve un conjunto de IDs que contiene las IDs de dos conjuntos.
(Operación or)
]]
function groupIds.__add(a, b)
local aux = a:clone();
for _, range in ipairs(b.ranges) do
aux:addRangeIds(range);
end;
return aux;
end;
--[[!
@return Devuelve una representación en forma de cadena de caracteres
de este grupo.
]]
function groupIds.__tostring(g)
return "[" .. table.concat(g:getAllIds(), ",") .. "]";
end;
-- Es un grupo que no contiene ninguna ID
groupIds.empty = groupIds();
|
Arreglado bug en el módulo util/groupids
|
Arreglado bug en el módulo util/groupids
|
Lua
|
mit
|
morfeo642/mta_plr_server
|
e473ad9d8e3f043ed28b13e8b77ea3e2a1b4a581
|
src/lua-factory/sources/grl-lastfm-cover.lua
|
src/lua-factory/sources/grl-lastfm-cover.lua
|
--[[
* Copyright (C) 2015 Bastien Nocera.
*
* Contact: Bastien Nocera <hadess@hadess.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; version 2.1 of
* the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
--]]
---------------------------
-- Source initialization --
---------------------------
source = {
id = "grl-lastfm-cover",
name = "Last.fm Cover",
description = "a source for music covers",
goa_account_provider = 'lastfm',
goa_account_feature = 'music',
supported_keys = { 'thumbnail' },
supported_media = { 'audio' },
resolve_keys = {
["type"] = "audio",
required = { "artist", "album" },
},
tags = { 'music', 'net:internet', 'net:plaintext' },
}
------------------
-- Source utils --
------------------
LASTFM_SEARCH_ALBUM = 'http://ws.audioscrobbler.com/2.0/?method=album.getInfo&api_key=%s&artist=%s&album=%s'
---------------------------------
-- Handlers of Grilo functions --
---------------------------------
function grl_source_resolve(media, options, callback)
local url
local artist, title
if not media or not media.artist or not media.album
or #media.artist == 0 or #media.album == 0 then
callback()
return
end
-- Prepare artist and title strings to the url
artist = grl.encode(media.artist)
album = grl.encode(media.album)
url = string.format(LASTFM_SEARCH_ALBUM, grl.goa_consumer_key(), artist, album)
local userdata = {callback = callback, media = media}
grl.fetch(url, fetch_page_cb, userdata)
end
---------------
-- Utilities --
---------------
function fetch_page_cb(result, userdata)
if not result then
userdata.callback()
return
end
userdata.media.thumbnail = {}
local image_sizes = { "mega", "extralarge", "large", "medium", "small" }
for _, size in pairs(image_sizes) do
local url
url = string.match(result, '<image size="' .. size .. '">(.-)</image>')
if url ~= nil and url ~= '' then
grl.debug ('Image size ' .. size .. ' = ' .. url)
table.insert(userdata.media.thumbnail, url)
end
end
if #userdata.media.thumbnail == 0 then
userdata.callback()
else
userdata.callback(userdata.media, 0)
end
end
|
--[[
* Copyright (C) 2015 Bastien Nocera.
*
* Contact: Bastien Nocera <hadess@hadess.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; version 2.1 of
* the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
--]]
---------------------------
-- Source initialization --
---------------------------
source = {
id = "grl-lastfm-cover",
name = "Last.fm Cover",
description = "a source for music covers",
goa_account_provider = 'lastfm',
goa_account_feature = 'music',
supported_keys = { 'thumbnail' },
supported_media = { 'audio' },
resolve_keys = {
["type"] = "audio",
required = { "artist", "album" },
},
tags = { 'music', 'net:internet', 'net:plaintext' },
}
------------------
-- Source utils --
------------------
LASTFM_SEARCH_ALBUM = 'http://ws.audioscrobbler.com/2.0/?method=album.getInfo&api_key=%s&artist=%s&album=%s'
---------------------------------
-- Handlers of Grilo functions --
---------------------------------
function grl_source_resolve()
local url, req
local artist, title
req = grl.get_media_keys()
if not req or not req.artist or not req.album
or #req.artist == 0 or #req.album == 0 then
grl.callback()
return
end
-- Prepare artist and title strings to the url
artist = grl.encode(req.artist)
album = grl.encode(req.album)
url = string.format(LASTFM_SEARCH_ALBUM, grl.goa_consumer_key(), artist, album)
grl.fetch(url, fetch_page_cb)
end
---------------
-- Utilities --
---------------
function fetch_page_cb(result)
if not result then
grl.callback()
return
end
local media = {}
media.thumbnail = {}
local image_sizes = { "mega", "extralarge", "large", "medium", "small" }
for _, size in pairs(image_sizes) do
local url
url = string.match(result, '<image size="' .. size .. '">(.-)</image>')
if url ~= nil and url ~= '' then
grl.debug ('Image size ' .. size .. ' = ' .. url)
table.insert(media.thumbnail, url)
end
end
if #media.thumbnail == 0 then
grl.callback()
else
grl.callback(media, 0)
end
end
|
Revert "lua-factory: port grl-lastfm-cover.lua to the new lua system"
|
Revert "lua-factory: port grl-lastfm-cover.lua to the new lua system"
This reverts commit fbb244ee962ddcf483dc4c6adec30de6c2616436.
But keeps grl.fetch callback as function instead of string
https://bugzilla.gnome.org/show_bug.cgi?id=763046
|
Lua
|
lgpl-2.1
|
GNOME/grilo-plugins,jasuarez/grilo-plugins,MikePetullo/grilo-plugins,MikePetullo/grilo-plugins,jasuarez/grilo-plugins,GNOME/grilo-plugins,grilofw/grilo-plugins,grilofw/grilo-plugins,MikePetullo/grilo-plugins
|
9b35d6ace8284d29439ed56617efb5e07e61145b
|
packages/color-fonts.lua
|
packages/color-fonts.lua
|
local ot = SILE.require("core/opentype-parser")
SILE.shapers.harfbuzzWithColor = pl.class({
_base = SILE.shapers.harfbuzz,
shapeToken = function (self, str, options)
if not options.family then return {} end
local face = SILE.font.cache(options, SILE.shaper.getFace)
local font = ot.parseFont(face)
local items = self._base.shapeToken(self, str, options)
if font.colr and font.cpal then
local newItems = {}
for i = 1, #items do
local layers = font.colr[items[i].gid]
if layers then
for j = 1, #layers do
local item = items[i]
local layer = layers[j]
local width = 0
local text = ""
if j == #layers then
width = item.width
text = item.text
end
-- XXX: handle multiple palette, add a font option?
local color = font.cpal[1][layer.paletteIndex]
local newItem = {
gid = layer.gid,
glyphAdvance = item.glyphAdvance,
width = width,
height= item.height,
depth = item.depth,
index = item.index,
text = text,
color = color,
}
newItems[#newItems+1] = newItem
end
else
newItems[#newItems+1] = items[i]
end
end
return newItems
end
return items
end,
createNnodes = function (self, token, options)
local items, _ = self:shapeToken(token, options)
if #items < 1 then return {} end
local lang = options.language
SILE.languageSupport.loadLanguage(lang)
local nodeMaker = SILE.nodeMakers[lang] or SILE.nodeMakers.unicode
local run = { [1] = { slice = {}, color = items[1].color, chunk = "" } }
for i = 1, #items do
if items[i].color ~= run[#run].color then
run[#run+1] = { slice = {}, chunk = "", color = items[i].color }
if i <#items then
run[#run].color = items[i].color
end
end
run[#run].chunk = run[#run].chunk .. items[i].text
run[#run].slice[#(run[#run].slice)+1] = items[i]
end
local nodes = {}
for i=1, #run do
options = pl.tablex.deepcopy(options)
if run[i].color then
nodes[#nodes+1] = SILE.nodefactory.hbox({
outputYourself = function () SILE.outputter:pushColor(run[i].color) end
})
end
for node in nodeMaker(options):iterator(run[i].slice, run[i].chunk) do
nodes[#nodes+1] = node
end
if run[i].color then
nodes[#nodes+1] = SILE.nodefactory.hbox({
outputYourself = function () SILE.outputter:popColor() end
})
end
end
return nodes
end
})
SILE.shaper = SILE.shapers.harfbuzzWithColor()
return {
documentation = [[
\begin{document}
The \code{color-fonts} package adds support for fonts with a \code{COLR}
OpenType table. This package is automatically loaded when such a font is
detected.
\end{document}
]]
}
|
local ot = SILE.require("core/opentype-parser")
SILE.shapers.harfbuzzWithColor = pl.class({
_base = SILE.shapers.harfbuzz,
shapeToken = function (self, str, options)
if not options.family then return {} end
local face = SILE.font.cache(options, SILE.shaper.getFace)
local font = ot.parseFont(face)
local items = self._base.shapeToken(self, str, options)
if font.colr and font.cpal then
local newItems = {}
for i = 1, #items do
local layers = font.colr[items[i].gid]
if layers then
for j = 1, #layers do
local item = items[i]
local layer = layers[j]
local width = 0
local height = 0
local text = ""
if j == #layers then
width = item.width
height = item.height
text = item.text
end
-- XXX: handle multiple palette, add a font option?
local color = font.cpal[1][layer.paletteIndex]
local newItem = {
gid = layer.gid,
glyphAdvance = item.glyphAdvance,
width = width,
height = height,
depth = item.depth,
index = item.index,
text = text,
color = color,
}
newItems[#newItems+1] = newItem
end
else
newItems[#newItems+1] = items[i]
end
end
return newItems
end
return items
end,
createNnodes = function (self, token, options)
local items, _ = self:shapeToken(token, options)
if #items < 1 then return {} end
local lang = options.language
SILE.languageSupport.loadLanguage(lang)
local nodeMaker = SILE.nodeMakers[lang] or SILE.nodeMakers.unicode
local run = { [1] = { slice = {}, color = items[1].color, chunk = "" } }
for i = 1, #items do
if items[i].color ~= run[#run].color then
run[#run+1] = { slice = {}, chunk = "", color = items[i].color }
if i <#items then
run[#run].color = items[i].color
end
end
run[#run].chunk = run[#run].chunk .. items[i].text
run[#run].slice[#(run[#run].slice)+1] = items[i]
end
local nodes = {}
for i=1, #run do
options = pl.tablex.deepcopy(options)
if run[i].color then
nodes[#nodes+1] = SILE.nodefactory.hbox({
outputYourself = function () SILE.outputter:pushColor(run[i].color) end
})
end
for node in nodeMaker(options):iterator(run[i].slice, run[i].chunk) do
nodes[#nodes+1] = node
end
if run[i].color then
nodes[#nodes+1] = SILE.nodefactory.hbox({
outputYourself = function () SILE.outputter:popColor() end
})
end
end
return nodes
end
})
SILE.shaper = SILE.shapers.harfbuzzWithColor()
return {
documentation = [[
\begin{document}
The \code{color-fonts} package adds support for fonts with a \code{COLR}
OpenType table. This package is automatically loaded when such a font is
detected.
\end{document}
]]
}
|
fix(packages): Correctly handle color fonts on TTB pages
|
fix(packages): Correctly handle color fonts on TTB pages
I'm not sure if top-to-bottom was even supported way back in 2015, but
@khaledhosny didn't take it into account when implementing
`color-fonts.lua`.
This closes #1171.
|
Lua
|
mit
|
alerque/sile,alerque/sile,alerque/sile,alerque/sile
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.