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
|
---|---|---|---|---|---|---|---|---|---|
eabbca05635c3c70a72bba583a4c65f560cee105
|
wget.lua
|
wget.lua
|
--[[ @cond ___LICENSE___
-- Copyright (c) 2016 Koen Visscher, Paul Visscher and individual contributors.
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
--
-- @endcond
--]]
-- WGet
zpm.wget = {}
zpm.wget.downloadUrl = zpm.config.wget.downloadUrl
zpm.wget.dependenciesUrl = zpm.config.wget.dependenciesUrl
function zpm.wget.downloadWget( destination )
local zipFile = path.join( zpm.temp, "wget.zip" )
if not os.isfile( zipFile ) then
print( "wget not detected - start downloading" )
http.download( zpm.wget.downloadUrl, zipFile )
else
print( "wget archive detected - start exctracting" )
end
local zipTemp = path.join( zpm.temp, "wget-zip" )
zpm.assert( os.mkdir( zipTemp ), "The archive directory could not be made!" )
zip.extract( zipFile, zipTemp )
os.rename( path.join( zipTemp, "bin/wget.exe" ), destination )
print( "wget succesfully installed" )
end
function zpm.wget.downloadDependencies()
local eay32 = path.join( zpm.cache, "libeay32.dll" )
local iconv2 = path.join( zpm.cache, "libiconv2.dll" )
local intl3 = path.join( zpm.cache, "libintl3.dll" )
local ssl32 = path.join( zpm.cache, "libssl32.dll" )
local zipFile = path.join( zpm.temp, "dependencies.zip" )
if not ( os.isfile( eay32 ) and
os.isfile( iconv2 ) and
os.isfile( intl3 ) and
os.isfile( ssl32 ) ) then
print( "wget dependencies not detected - start downloading" )
http.download( zpm.wget.dependenciesUrl, zipFile )
else
print( "wget dependencies archive detected - start exctracting" )
end
local zipTemp = path.join( zpm.temp, "dependencies-zip" )
zpm.assert( os.mkdir( zipTemp ), "The archive directory could not be made!" )
zip.extract( zipFile, zipTemp )
os.rename( path.join( zipTemp, "bin/libeay32.dll" ), eay32 )
os.rename( path.join( zipTemp, "bin/libiconv2.dll" ), iconv2 )
os.rename( path.join( zipTemp, "bin/libintl3.dll" ), intl3 )
os.rename( path.join( zipTemp, "bin/libssl32.dll" ), ssl32 )
print( "wget dependencies succesfully installed" )
end
function zpm.wget.initialise()
local dest = path.join( zpm.cache, "wget.exe" )
if os.get() == "windows" then
if not os.isfile( dest ) then
print( "\nLoading wget..." )
zpm.wget.downloadWget( dest )
zpm.wget.downloadDependencies()
end
zpm.wget.location = dest
else
zpm.wget.location = "wget"
end
end
function zpm.wget.get( url, header )
if header == nil then
return os.outputof( zpm.wget.location .. " -nv -qO- " .. url .. " --no-check-certificate 2> nul" )
end
return os.outputof( zpm.wget.location .. " -nv -qO- " .. url .. " --no-check-certificate --header \"" .. header .. "\" 2> nul" )
end
function zpm.wget.download( destination, url, header )
if header == nil then
os.execute( zpm.wget.location .. " -N " .. url .. " -O " .. destination .. " --no-check-certificate 2> nul" )
else
os.execute( zpm.wget.location .. " -N " .. url .. " -O " .. destination .. " --no-check-certificate --header \"" .. header .. "\" 2> nul" )
end
end
|
--[[ @cond ___LICENSE___
-- Copyright (c) 2016 Koen Visscher, Paul Visscher and individual contributors.
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
--
-- @endcond
--]]
-- WGet
zpm.wget = {}
zpm.wget.downloadUrl = zpm.config.wget.downloadUrl
zpm.wget.dependenciesUrl = zpm.config.wget.dependenciesUrl
function zpm.wget.downloadWget( destination )
local zipFile = path.join( zpm.temp, "wget.zip" )
if not os.isfile( zipFile ) then
print( "wget not detected - start downloading" )
http.download( zpm.wget.downloadUrl, zipFile )
else
print( "wget archive detected - start exctracting" )
end
local zipTemp = path.join( zpm.temp, "wget-zip" )
zpm.assert( os.mkdir( zipTemp ), "The archive directory could not be made!" )
zip.extract( zipFile, zipTemp )
os.rename( path.join( zipTemp, "bin/wget.exe" ), destination )
print( "wget succesfully installed" )
end
function zpm.wget.downloadDependencies()
local eay32 = path.join( zpm.cache, "libeay32.dll" )
local iconv2 = path.join( zpm.cache, "libiconv2.dll" )
local intl3 = path.join( zpm.cache, "libintl3.dll" )
local ssl32 = path.join( zpm.cache, "libssl32.dll" )
local zipFile = path.join( zpm.temp, "dependencies.zip" )
if not ( os.isfile( eay32 ) and
os.isfile( iconv2 ) and
os.isfile( intl3 ) and
os.isfile( ssl32 ) ) then
print( "wget dependencies not detected - start downloading" )
http.download( zpm.wget.dependenciesUrl, zipFile )
else
print( "wget dependencies archive detected - start exctracting" )
end
local zipTemp = path.join( zpm.temp, "dependencies-zip" )
zpm.assert( os.mkdir( zipTemp ), "The archive directory could not be made!" )
zip.extract( zipFile, zipTemp )
os.rename( path.join( zipTemp, "bin/libeay32.dll" ), eay32 )
os.rename( path.join( zipTemp, "bin/libiconv2.dll" ), iconv2 )
os.rename( path.join( zipTemp, "bin/libintl3.dll" ), intl3 )
os.rename( path.join( zipTemp, "bin/libssl32.dll" ), ssl32 )
print( "wget dependencies succesfully installed" )
end
function zpm.wget.initialise()
local dest = path.join( zpm.cache, "wget.exe" )
if os.get() == "windows" then
if not os.isfile( dest ) then
print( "\nLoading wget..." )
zpm.wget.downloadWget( dest )
zpm.wget.downloadDependencies()
end
zpm.wget.location = dest
else
zpm.wget.location = "wget"
end
end
function zpm.wget.get( url, header )
if header == nil or header == "" then
return os.outputof( zpm.wget.location .. " -nv -qO- " .. url .. " --no-check-certificate 2> nul" )
end
return os.outputof( zpm.wget.location .. " -nv -qO- " .. url .. " --no-check-certificate --header \"" .. header .. "\" 2> nul" )
end
function zpm.wget.download( destination, url, header )
if header == nil or header == "" then
os.execute( zpm.wget.location .. " -N " .. url .. " -O " .. destination .. " --no-check-certificate 2> nul" )
else
os.execute( zpm.wget.location .. " -N " .. url .. " -O " .. destination .. " --no-check-certificate --header \"" .. header .. "\" 2> nul" )
end
end
|
Wget header fix
|
Wget header fix
|
Lua
|
mit
|
Zefiros-Software/ZPM
|
9d7066c345c68f3fab3eb2fb2d4e12b9f69de476
|
colorize/colorize.lua
|
colorize/colorize.lua
|
package.path = '../lualibs/?.lua;' .. package.path
require 'mapdef'
local colorbook = require 'colorbook'
local legend = require 'legend'
local openmaptiles = require 'openmaptiles'
-- možné prvky
local F_WATER = {waterway=ANY, landuse='reservoir'}
local F_BUILDING = {building=ANY}
local F_FOREST = {landuse='forest'}
local F_RAIL = {railway='rail'}
local F_TRAM = {railway='tram'}
local F_ROAD_MAJOR = {highway={major=true, primary=true, secondary=true, tertiary=true, trunk=true, primary_link=true, secondary_link=true, tertiary_link=true, trunk_link=true}}
local F_ROAD_MINOR = { highway={residential=true, service=true} }
local F_FOOTWAY = { highway={footway=true, pedestrian=true}}
local F_STEPS = { highway={steps=true}}
-- barvy (Solarized paleta)
local BASE03 = '#002b36'
local BASE02 = '#073642'
local BASE01 = '#586e75'
local BASE00 = '#657b83'
local BASE0 = '#839496'
local BASE1 = '#93a1a1'
local BASE2 = '#eee85d'
local BASE3 = '#fdf6d3'
local YELLOW = '#b58900'
local ORANGE = '#cb4b16'
local RED = '#dc322f'
local MAGENTA = '#d33682'
local VIOLET = '#6c71c4'
local BLUE = '#268bd2'
local CYAN = '#2aa198'
local GREEN = '#859900'
-- ...
-- samotný styl
stylesheet 'ColorIze'
by 'Severák'
background(BASE3)
-- plochy
area{
feat = F_WATER,
color = BLUE,
desc = 'vodní plochy'
}
area{
feat = F_FOREST,
color = GREEN,
desc = 'les'
}
area{
feat = F_BUILDING,
color = BASE00,
desc = 'budovy'
}
-- potoky
line{
feat = F_WATER,
color = BLUE,
width = 2,
desc = 'vodní toky'
}
-- silnice / okraje
line{
feat=F_FOOTWAY,
color = ORANGE,
dashing = {2, 2},
desc = 'pěšina'
}
line{
feat=F_ROAD_MINOR,
color = ORANGE,
width = 3,
desc = 'vedlejší silnice'
}
line{
feat=F_ROAD_MAJOR,
color = ORANGE,
width = 5,
desc = 'hlavní silnice'
}
-- silnice / výplň
line{
feat=F_ROAD_MAJOR,
color = BASE3,
width = 3
}
line{
feat=F_ROAD_MINOR,
color = BASE3,
width = 1
}
-- koleje
line{
feat = F_RAIL,
color = BASE03,
width = 3,
desc = 'železnice'
}
line{ -- čárkované koleje
feat = F_RAIL,
color = BASE3,
width = 1,
dashing = {4,4}
}
line{
feat = F_TRAM,
color = RED,
width = 2
}
-- názvy obcí -- name{...}
-- názvy silnic -- stretname{...}
-- generujeme zatím jen ColorBook CSS
colorbook.css 'map.css'
-- + legendu
legend.html()
-- + openmaptiles
openmaptiles.style()
print "OK"
|
package.path = '../lualibs/?.lua;' .. package.path
require 'mapdef'
local colorbook = require 'colorbook'
local legend = require 'legend'
local openmaptiles = require 'openmaptiles'
-- možné prvky
local F_WATER = {waterway=ANY, landuse='reservoir'}
local F_BUILDING = {building=ANY}
local F_FOREST = {landuse='forest'}
local F_RAIL = {railway='rail'}
local F_TRAM = {railway='tram', railway='transit'}
local F_ROAD_MAJOR = {highway={motorway=true, major=true, primary=true, secondary=true, tertiary=true, trunk=true, primary_link=true, secondary_link=true, tertiary_link=true, trunk_link=true}}
local F_ROAD_MINOR = { highway={minor=true, residential=true, service=true, path=true} }
local F_FOOTWAY = { highway={footway=true, pedestrian=true}}
local F_STEPS = { highway={steps=true}}
-- barvy (Solarized paleta)
local BASE03 = '#002b36'
local BASE02 = '#073642'
local BASE01 = '#586e75'
local BASE00 = '#657b83'
local BASE0 = '#839496'
local BASE1 = '#93a1a1'
local BASE2 = '#eee85d'
local BASE3 = '#fdf6d3'
local YELLOW = '#b58900'
local ORANGE = '#cb4b16'
local RED = '#dc322f'
local MAGENTA = '#d33682'
local VIOLET = '#6c71c4'
local BLUE = '#268bd2'
local CYAN = '#2aa198'
local GREEN = '#859900'
-- ...
-- samotný styl
stylesheet 'ColorIze'
by 'Severák'
background(BASE3)
-- plochy
area{
feat = F_WATER,
color = BLUE,
desc = 'vodní plochy'
}
area{
feat = F_FOREST,
color = GREEN,
desc = 'les'
}
area{
feat = F_BUILDING,
color = BASE00,
desc = 'budovy'
}
-- potoky
line{
feat = F_WATER,
color = BLUE,
width = 2,
desc = 'vodní toky'
}
-- silnice / okraje
line{
feat=F_FOOTWAY,
color = ORANGE,
dashing = {2, 2},
desc = 'pěšina'
}
line{
feat=F_ROAD_MINOR,
color = ORANGE,
width = 3,
desc = 'vedlejší silnice'
}
line{
feat=F_ROAD_MAJOR,
color = ORANGE,
width = 5,
desc = 'hlavní silnice'
}
-- silnice / výplň
line{
feat=F_ROAD_MAJOR,
color = BASE3,
width = 3
}
line{
feat=F_ROAD_MINOR,
color = BASE3,
width = 1
}
-- koleje
line{
feat = F_RAIL,
color = BASE03,
width = 3,
desc = 'železnice'
}
line{ -- čárkované koleje
feat = F_RAIL,
color = BASE3,
width = 1,
dashing = {4,4}
}
line{
feat = F_TRAM,
color = RED,
width = 2
}
-- názvy obcí -- name{...}
-- názvy silnic -- stretname{...}
-- generujeme zatím jen ColorBook CSS
colorbook.css 'map.css'
-- + legendu
legend.html()
-- + openmaptiles
openmaptiles.style()
print "OK"
|
nejake fixy pro hezci demo
|
nejake fixy pro hezci demo
|
Lua
|
mit
|
severak/mapstyles,severak/mapstyles
|
7848f9f8639b8083366067da2f4f7f5d0bdf2e22
|
mod_menu/mod_menu.lua
|
mod_menu/mod_menu.lua
|
--
-- ion/mod_menu/mod_menu.lua -- Menu opening helper routines.
--
-- Copyright (c) Tuomo Valkonen 2004-2005.
--
-- Ion is free software; you can redistribute it and/or modify it under
-- the terms of the GNU Lesser General Public License as published by
-- the Free Software Foundation; either version 2.1 of the License, or
-- (at your option) any later version.
--
-- This is a slight abuse of the _LOADED variable perhaps, but library-like
-- packages should handle checking if they're loaded instead of confusing
-- the user with require/include differences.
if _LOADED["mod_menu"] then return end
if not ioncore.load_module("mod_menu") then
return
end
local mod_menu=_G["mod_menu"]
local menudb=_G["ioncore"]
assert(mod_menu and menudb)
-- Menu commands {{{
local function menu_(reg, sub, menu_or_name, fn, check)
if check then
-- Check that no other menus are open in reg.
local l=reg:llist(2)
for i, r in l do
if obj_is(r, "WMenu") then
return
end
end
end
menu=menudb.evalmenu(menu_or_name, {reg, sub})
return fn(reg, function(e) e.func(reg, sub) end, menu)
end
--DOC
-- Display a menu in the lower-left corner of \var{mplex}.
-- The variable \var{menu_or_name} is either the name of a menu
-- defined with \fnref{mod_menu.defmenu} or directly a table similar
-- to ones passesd to this function. When this function is
-- called from a binding handler, \var{sub} should be set to
-- the second argument of to the binding handler (\var{_sub})
-- so that the menu handler will get the same parameters as the
-- binding handler. Extra options can be passed in the table
-- \var{param}. The initial entry can be specified as the field
-- \var{initial} as an integer starting from 1. Menus can be made
-- to use a bigger style by setting the field \var{big} to \code{true}.
function mod_menu.menu(mplex, sub, menu_or_name, param)
local function menu_stdmenu(m, s, menu)
return mod_menu.do_menu(m, s, menu, param)
end
return menu_(mplex, sub, menu_or_name, menu_stdmenu, true)
end
-- Compatibility
function mod_menu.bigmenu(mplex, sub, menu_or_name, initial)
local function menu_bigmenu(m, s, menu)
return mod_menu.do_menu(m, s, menu, {big=true, initial=initial})
end
return menu_(mplex, sub, menu_or_name, menu_bigmenu, true)
end
--DOC
-- This function is similar to \fnref{mod_menu.menu}, but input
-- is grabbed and \var{param.key} is used to cycle through the menu.
function mod_menu.grabmenu(mplex, sub, menu_or_name, param)
if type(param)=="string" then
param={key=param}
end
local function menu_grabmenu(m, s, menu)
return mod_menu.do_grabmenu(m, s, menu, param)
end
return menu_(mplex, sub, menu_or_name, menu_grabmenu, true)
end
-- Compatibility
function mod_menu.biggrabmenu(mplex, sub, menu_or_name, key, initial)
local function menu_biggrabmenu(m, s, menu)
return mod_menu.do_grabmenu(m, s, menu, true, key, initial or 0)
end
return menu_(mplex, sub, menu_or_name, menu_biggrabmenu, true, initial)
end
--DOC
-- This function displays a drop-down menu and should only
-- be called from a mouse press handler. The parameters are
-- similar to those of \fnref{mod_menu.menu}.
function mod_menu.pmenu(win, sub, menu_or_name)
return menu_(win, sub, menu_or_name, mod_menu.do_pmenu)
end
-- }}}
-- Mark ourselves loaded.
_LOADED["mod_menu"]=true
-- Load configuration file
dopath('cfg_menu', true)
|
--
-- ion/mod_menu/mod_menu.lua -- Menu opening helper routines.
--
-- Copyright (c) Tuomo Valkonen 2004-2005.
--
-- Ion is free software; you can redistribute it and/or modify it under
-- the terms of the GNU Lesser General Public License as published by
-- the Free Software Foundation; either version 2.1 of the License, or
-- (at your option) any later version.
--
-- This is a slight abuse of the _LOADED variable perhaps, but library-like
-- packages should handle checking if they're loaded instead of confusing
-- the user with require/include differences.
if _LOADED["mod_menu"] then return end
if not ioncore.load_module("mod_menu") then
return
end
local mod_menu=_G["mod_menu"]
local menudb=_G["ioncore"]
assert(mod_menu and menudb)
-- Menu commands {{{
local function menu_(reg, sub, menu_or_name, fn, check)
if check then
-- Check that no other menus are open in reg.
local l=reg:llist(2)
for i, r in l do
if obj_is(r, "WMenu") then
return
end
end
end
menu=menudb.evalmenu(menu_or_name, {reg, sub})
return fn(reg, function(e) e.func(reg, sub) end, menu)
end
--DOC
-- Display a menu in the lower-left corner of \var{mplex}.
-- The variable \var{menu_or_name} is either the name of a menu
-- defined with \fnref{mod_menu.defmenu} or directly a table similar
-- to ones passesd to this function. When this function is
-- called from a binding handler, \var{sub} should be set to
-- the second argument of to the binding handler (\var{_sub})
-- so that the menu handler will get the same parameters as the
-- binding handler. Extra options can be passed in the table
-- \var{param}. The initial entry can be specified as the field
-- \var{initial} as an integer starting from 1. Menus can be made
-- to use a bigger style by setting the field \var{big} to \code{true}.
function mod_menu.menu(mplex, sub, menu_or_name, param)
local function menu_stdmenu(m, s, menu)
return mod_menu.do_menu(m, s, menu, param)
end
return menu_(mplex, sub, menu_or_name, menu_stdmenu, true)
end
-- Compatibility
function mod_menu.bigmenu(mplex, sub, menu_or_name, initial)
local function menu_bigmenu(m, s, menu)
return mod_menu.do_menu(m, s, menu, {big=true, initial=initial})
end
return menu_(mplex, sub, menu_or_name, menu_bigmenu, true)
end
--DOC
-- This function is similar to \fnref{mod_menu.menu}, but input
-- is grabbed and the key given either directly as \var{param} or
-- as \var{param.key} is used to cycle through the menu.
function mod_menu.grabmenu(mplex, sub, menu_or_name, param)
if type(param)=="string" then
param={key=param}
end
local function menu_grabmenu(m, s, menu)
return mod_menu.do_grabmenu(m, s, menu, param)
end
return menu_(mplex, sub, menu_or_name, menu_grabmenu, true)
end
-- Compatibility
function mod_menu.biggrabmenu(mplex, sub, menu_or_name, key, initial)
local function menu_biggrabmenu(m, s, menu)
return mod_menu.do_grabmenu(m, s, menu, true, key, initial or 0)
end
return menu_(mplex, sub, menu_or_name, menu_biggrabmenu, true, initial)
end
--DOC
-- This function displays a drop-down menu and should only
-- be called from a mouse press handler. The parameters are
-- similar to those of \fnref{mod_menu.menu}.
function mod_menu.pmenu(win, sub, menu_or_name)
return menu_(win, sub, menu_or_name, mod_menu.do_pmenu)
end
-- }}}
-- Mark ourselves loaded.
_LOADED["mod_menu"]=true
-- Load configuration file
dopath('cfg_menu', true)
|
Fixed mod_menu.grabmenu documentation.
|
Fixed mod_menu.grabmenu documentation.
darcs-hash:20060101011729-4eba8-9cf60aba20d7cf444a33f209fb46632fd6d6ae9f.gz
|
Lua
|
lgpl-2.1
|
anoduck/notion,knixeur/notion,dkogan/notion,dkogan/notion,p5n/notion,anoduck/notion,p5n/notion,raboof/notion,raboof/notion,neg-serg/notion,anoduck/notion,knixeur/notion,dkogan/notion.xfttest,dkogan/notion,p5n/notion,knixeur/notion,neg-serg/notion,knixeur/notion,anoduck/notion,knixeur/notion,dkogan/notion,neg-serg/notion,dkogan/notion.xfttest,anoduck/notion,neg-serg/notion,raboof/notion,p5n/notion,dkogan/notion.xfttest,dkogan/notion.xfttest,p5n/notion,dkogan/notion,raboof/notion
|
d5c3bc8b437c5d7619bb26338db459b8f69f9fd8
|
nvim/lua/user/ui.lua
|
nvim/lua/user/ui.lua
|
local filereadable_key = 'filereadable'
local function file_exists(name)
local f = io.open(name, 'r')
return f ~= nil and io.close(f)
end
local function buf_get_var(bufnr, name, default)
local ok, value = pcall(vim.api.nvim_buf_get_var, bufnr, name)
if ok then return value end
return default
end
local function update_filereadable()
local path = vim.api.nvim_buf_get_name(0)
if path ~= '' then
vim.api.nvim_buf_set_var(0, filereadable_key, file_exists(path))
end
end
local function tabpage_get_win_normal(tabnr)
for _, winnr in ipairs(vim.api.nvim_tabpage_list_wins(tabnr)) do
local config = vim.api.nvim_win_get_config(winnr)
-- `relative` is empty for normal windows
if config.relative == '' then
return winnr
end
end
-- Fallback
return vim.api.nvim_tabpage_get_win(tabnr)
end
local function tabline()
local line = {}
local tab_list = vim.api.nvim_list_tabpages()
local current = vim.api.nvim_get_current_tabpage()
for _, tabnr in ipairs(tab_list) do
local winnr = tabpage_get_win_normal(tabnr)
local bufnr = vim.api.nvim_win_get_buf(winnr)
local path = vim.api.nvim_buf_get_name(bufnr)
local name = vim.fn.fnamemodify(path, ':t')
name = name ~= '' and name or '[No Name]'
local flags = {}
if vim.bo[bufnr].mod then
table.insert(flags, '+')
end
if not buf_get_var(bufnr, filereadable_key, true) then
table.insert(flags, '?')
end
local tab = {
'%', tabnr, 'T',
(tabnr == current and '%#TabLineSel#' or '%#TabLine#'),
' ', name,
(#flags > 0 and ' ' .. table.concat(flags, '') or ''),
' ',
}
table.insert(line, table.concat(tab, ''))
end
table.insert(line, '%#TabLineFill#')
return table.concat(line, '')
end
local function render_statusline(winnr, active)
local bufnr = vim.api.nvim_win_get_buf(winnr)
local path = vim.api.nvim_buf_get_name(bufnr)
local buftype = vim.bo[bufnr].buftype
local is_file = (buftype == '')
local l0 = {}
local l1 = {}
local r1 = {}
local r0 = {}
if active then
table.insert(l0, '%#StatusLineMode#▌%#StatusLineL0#')
else
table.insert(l0, '%#StatusLine#')
end
if active then
local filetype = vim.bo[bufnr].filetype
table.insert(l0, filetype == '' and 'plain' or filetype)
else
if is_file and path ~= '' then
local rel_path = vim.fn.fnamemodify(path, ':p:~:.')
table.insert(l0, rel_path)
elseif is_file then
table.insert(l0, '[No Name]')
else
table.insert(l0, buftype)
end
end
local flags = {}
if vim.bo[bufnr].readonly then
table.insert(flags, '!')
end
if vim.bo[bufnr].modified then
table.insert(flags, '+')
end
if not buf_get_var(bufnr, filereadable_key, true) then
table.insert(flags, '?')
end
if #flags > 0 then
table.insert(l0, table.concat(flags, ''))
end
if active and is_file then
local last_saved_time = buf_get_var(bufnr, 'auto_save_last_saved_time', 0)
if 0 < last_saved_time and last_saved_time >= os.time() - 60 then
table.insert(l1, os.date('✓ %X', last_saved_time))
end
end
if active then
local diagnostics = { E = 0, W = 0, I = 0, H = 0 }
local status = buf_get_var(bufnr, 'coc_diagnostic_info', nil)
if status then
diagnostics.E = diagnostics.E + (status.error or 0)
diagnostics.W = diagnostics.W + (status.warning or 0)
diagnostics.I = diagnostics.I + (status.information or 0)
diagnostics.H = diagnostics.H + (status.hint or 0)
end
if diagnostics.E > 0 then
local text = string.format('%%#StatusLineDiagnosticsError#%s %d%%*', '✗', diagnostics.E)
table.insert(l1, text)
end
if diagnostics.W > 0 then
local text = string.format('%%#StatusLineDiagnosticsWarning#%s %d%%*', '∆', diagnostics.W)
table.insert(l1, text)
end
if diagnostics.I > 0 then
local text = string.format('%%#StatusLineDiagnosticsInfo#%s %d%%*', '▸', diagnostics.I)
table.insert(l1, text)
end
if diagnostics.H > 0 then
local text = string.format('%%#StatusLineDiagnosticsHint#%s %d%%*', '▪︎', diagnostics.H)
table.insert(l1, text)
end
end
local coc_status = vim.g.coc_status or ''
if active and coc_status ~= '' then
table.insert(r1, string.sub(coc_status, 0, 60))
end
if active then
local encoding = vim.bo[bufnr].fileencoding
local format = vim.bo[bufnr].fileformat
table.insert(r0, encoding ~= '' and encoding or vim.o.encoding)
table.insert(r0, format)
table.insert(r0, '∙')
table.insert(r0, '%l:%c')
table.insert(r0, '∙')
table.insert(r0, '%p%%')
end
return table.concat({
table.concat(l0, ' '),
'%*',
table.concat(l1, ' '),
'%=',
table.concat(r1, ' '),
'%*',
table.concat(r0, ' '),
'%*',
}, ' ')
end
local function statusline()
local winnr = vim.g.statusline_winid
local active = winnr == vim.fn.win_getid()
if active then
require('candle').update_mode_highlight()
end
return render_statusline(winnr, active)
end
local function setup()
vim.o.tabline = [[%!v:lua.require'user.ui'.tabline()]]
vim.o.statusline = [[%!v:lua.require'user.ui'.statusline()]]
vim.api.nvim_exec([[
augroup user_ui_statusline
autocmd!
autocmd FocusGained,BufEnter,BufReadPost,BufWritePost * lua require'user.ui'.update_filereadable()
autocmd WinLeave,BufLeave * lua vim.wo.statusline=require'user.ui'.statusline()
autocmd BufWinEnter,WinEnter,BufEnter * set statusline<
autocmd VimResized * redrawstatus
augroup END
]], false)
end
return {
setup = setup,
statusline = statusline,
tabline = tabline,
update_filereadable = update_filereadable,
}
|
local filereadable_key = 'filereadable'
local function file_exists(name)
local f = io.open(name, 'r')
return f ~= nil and io.close(f)
end
local function buf_get_var(bufnr, name, default)
local ok, value = pcall(vim.api.nvim_buf_get_var, bufnr, name)
if ok then return value end
return default
end
local function update_filereadable()
local path = vim.api.nvim_buf_get_name(0)
if path ~= '' then
vim.api.nvim_buf_set_var(0, filereadable_key, file_exists(path))
end
end
local function tabline()
local line = {}
local tab_list = vim.api.nvim_list_tabpages()
local current = vim.api.nvim_get_current_tabpage()
for _, tabnr in ipairs(tab_list) do
local winnr = vim.api.nvim_tabpage_get_win(tabnr)
local bufnr = vim.api.nvim_win_get_buf(winnr)
local path = vim.api.nvim_buf_get_name(bufnr)
local name = vim.fn.fnamemodify(path, ':t')
name = name ~= '' and name or '[No Name]'
-- Work around flickering tab with https://github.com/Shougo/ddu-ui-ff
if string.match(name, '^ddu-') then
name = 'ddu'
end
local flags = {}
if vim.bo[bufnr].mod then
table.insert(flags, '+')
end
if not buf_get_var(bufnr, filereadable_key, true) then
table.insert(flags, '?')
end
local tab = {
'%', tabnr, 'T',
(tabnr == current and '%#TabLineSel#' or '%#TabLine#'),
' ', name,
(#flags > 0 and ' ' .. table.concat(flags, '') or ''),
' ',
}
table.insert(line, table.concat(tab, ''))
end
table.insert(line, '%#TabLineFill#')
return table.concat(line, '')
end
local function render_statusline(winnr, active)
local bufnr = vim.api.nvim_win_get_buf(winnr)
local path = vim.api.nvim_buf_get_name(bufnr)
local buftype = vim.bo[bufnr].buftype
local is_file = (buftype == '')
local l0 = {}
local l1 = {}
local r1 = {}
local r0 = {}
if active then
table.insert(l0, '%#StatusLineMode#▌%#StatusLineL0#')
else
table.insert(l0, '%#StatusLine#')
end
if active then
local filetype = vim.bo[bufnr].filetype
table.insert(l0, filetype == '' and 'plain' or filetype)
else
if is_file and path ~= '' then
local rel_path = vim.fn.fnamemodify(path, ':p:~:.')
table.insert(l0, rel_path)
elseif is_file then
table.insert(l0, '[No Name]')
else
table.insert(l0, buftype)
end
end
local flags = {}
if vim.bo[bufnr].readonly then
table.insert(flags, '!')
end
if vim.bo[bufnr].modified then
table.insert(flags, '+')
end
if not buf_get_var(bufnr, filereadable_key, true) then
table.insert(flags, '?')
end
if #flags > 0 then
table.insert(l0, table.concat(flags, ''))
end
if active and is_file then
local last_saved_time = buf_get_var(bufnr, 'auto_save_last_saved_time', 0)
if 0 < last_saved_time and last_saved_time >= os.time() - 60 then
table.insert(l1, os.date('✓ %X', last_saved_time))
end
end
if active then
local diagnostics = { E = 0, W = 0, I = 0, H = 0 }
local status = buf_get_var(bufnr, 'coc_diagnostic_info', nil)
if status then
diagnostics.E = diagnostics.E + (status.error or 0)
diagnostics.W = diagnostics.W + (status.warning or 0)
diagnostics.I = diagnostics.I + (status.information or 0)
diagnostics.H = diagnostics.H + (status.hint or 0)
end
if diagnostics.E > 0 then
local text = string.format('%%#StatusLineDiagnosticsError#%s %d%%*', '✗', diagnostics.E)
table.insert(l1, text)
end
if diagnostics.W > 0 then
local text = string.format('%%#StatusLineDiagnosticsWarning#%s %d%%*', '∆', diagnostics.W)
table.insert(l1, text)
end
if diagnostics.I > 0 then
local text = string.format('%%#StatusLineDiagnosticsInfo#%s %d%%*', '▸', diagnostics.I)
table.insert(l1, text)
end
if diagnostics.H > 0 then
local text = string.format('%%#StatusLineDiagnosticsHint#%s %d%%*', '▪︎', diagnostics.H)
table.insert(l1, text)
end
end
local coc_status = vim.g.coc_status or ''
if active and coc_status ~= '' then
table.insert(r1, string.sub(coc_status, 0, 60))
end
if active then
local encoding = vim.bo[bufnr].fileencoding
local format = vim.bo[bufnr].fileformat
table.insert(r0, encoding ~= '' and encoding or vim.o.encoding)
table.insert(r0, format)
table.insert(r0, '∙')
table.insert(r0, '%l:%c')
table.insert(r0, '∙')
table.insert(r0, '%p%%')
end
return table.concat({
table.concat(l0, ' '),
'%*',
table.concat(l1, ' '),
'%=',
table.concat(r1, ' '),
'%*',
table.concat(r0, ' '),
'%*',
}, ' ')
end
local function statusline()
local winnr = vim.g.statusline_winid
local active = winnr == vim.fn.win_getid()
if active then
require('candle').update_mode_highlight()
end
return render_statusline(winnr, active)
end
local function setup()
vim.o.tabline = [[%!v:lua.require'user.ui'.tabline()]]
vim.o.statusline = [[%!v:lua.require'user.ui'.statusline()]]
vim.api.nvim_exec([[
augroup user_ui_statusline
autocmd!
autocmd FocusGained,BufEnter,BufReadPost,BufWritePost * lua require'user.ui'.update_filereadable()
autocmd WinLeave,BufLeave * lua vim.wo.statusline=require'user.ui'.statusline()
autocmd BufWinEnter,WinEnter,BufEnter * set statusline<
autocmd VimResized * redrawstatus
augroup END
]], false)
end
return {
setup = setup,
statusline = statusline,
tabline = tabline,
update_filereadable = update_filereadable,
}
|
Revert "Fix tabline to ignore floating windows"
|
Revert "Fix tabline to ignore floating windows"
This reverts commit 7f6da0e9285b026b43f767c10e9ce28131b3c872.
|
Lua
|
mit
|
creasty/dotfiles,creasty/dotfiles,creasty/dotfiles,creasty/dotfiles,creasty/dotfiles,creasty/dotfiles,creasty/dotfiles,creasty/dotfiles
|
0cc865d05556a1b5ebacd2247e33353c87f025f3
|
wrap/lullbc/script/core/utils/util_func.lua
|
wrap/lullbc/script/core/utils/util_func.lua
|
--[[
@file util_func.lua
@brief The function util functions encapsulation.
--]]
local FuncTool = llbc.newclass('llbc.FuncTool')
-- constructor, do not call.
function FuncTool:ctor()
error('now allow to instantiate FuncTool instance')
end
-- Return a new partial function, function first N parameters already assigned.
-- @param[required] func - the will partial function.
-- @param[optional] ... - will assign arguments, must be greater than or equal to 1.
-- @returns function - the partial function.
function FuncTool.partial(func, ...)
local call_args = {...}
if #call_args < 1 then
error('partial arguments count could not be 0')
end
return function (...)
for _, v in pairs({...}) do
table.insert(call_args, #call_args + 1, v)
end
return func(table.unpack(call_args))
end
end
llbc.FuncTool = FuncTool
|
--[[
@file util_func.lua
@brief The function util functions encapsulation.
--]]
local table_unpack = table.unpack or unpack
local FuncTool = llbc.newclass('llbc.FuncTool')
-- constructor, do not call.
function FuncTool:ctor()
error('now allow to instantiate FuncTool instance')
end
-- Return a new partial function, function first N parameters already assigned.
-- @param[required] func - the will partial function.
-- @param[optional] ... - will assign arguments, must be greater than or equal to 1.
-- @returns function - the partial function.
function FuncTool.partial(func, ...)
local call_args = {...}
if #call_args < 1 then
error('partial arguments count could not be 0')
end
return function (...)
local args = {table_unpack(call_args)}
for k, v in ipairs({...}) do
table.insert(args, #args + 1, v)
end
return func(table_unpack(args))
end
end
llbc.FuncTool = FuncTool
|
fix lua partial() implemention error
|
fix lua partial() implemention error
|
Lua
|
mit
|
lailongwei/llbc,lailongwei/llbc,lailongwei/llbc,lailongwei/llbc,lailongwei/llbc
|
80ec6fd7d81ee4f854a6ab44da19a9f511305a34
|
test/curve_server.lua
|
test/curve_server.lua
|
--
-- echo server with curve
--
local zmq = require 'luazmq'
zmq.init()
local public_key = [[E>-TgoMAf+R*WZ]8[NQ-tV>c1vN{WryLVrFkS8>y]]
local secret_key = [[4{DUIc#[BilXOmYjg[c#]uTD3J4>EoJVl===jx3M]]
local address = 'tcp://*:10086'
local s = zmq.socket(zmq.REP)
s:set_curve_public_key(zmq.z85_decode(public_key))
s:set_curve_secret_key(zmq.z85_decode(secret_key))
s:set_curve_server(true)
s:set_accept_filter('127.0.0.1')
s:bind(address)
print('server start at ' .. address)
local num = 0
while true do
local str = s:recv()
num = num + 1
print(num, str)
s:send(str)
end
zmq.shutdown()
zmq.terminate()
|
--
-- echo server with curve
--
local zmq = require 'luazmq'
zmq.init()
local public_key = [[E>-TgoMAf+R*WZ]8[NQ-tV>c1vN{WryLVrFkS8>y]]
local secret_key = [[4{DUIc#[BilXOmYjg[c#]uTD3J4>EoJVl===jx3M]]
local address = 'tcp://*:10086'
local s = zmq.socket(zmq.REP)
s:set_curve_public_key(zmq.z85_decode(public_key))
s:set_curve_secret_key(zmq.z85_decode(secret_key))
s:set_curve_server(true)
s:set_accept_filter('127.0.0.1')
s:bind(address)
print('server start at ' .. address)
local num = 0
while true do
local str = s:recv()
num = num + 1
print(num, str)
s:send(str)
end
zmq.shutdown()
zmq.terminate()
|
tab fix
|
tab fix
|
Lua
|
apache-2.0
|
ichenq/lua-zmq
|
5fb0ee0b2ea94dca25a4216beea368c4fe5111c5
|
lib/luanode/__private_traverse.lua
|
lib/luanode/__private_traverse.lua
|
-------------------------------------------------------------------------------
-- This module implements a function that traverses all live objects.
-- You can implement your own function to pass as a parameter of traverse
-- and give you the information you want. As an example we have implemented
-- countreferences and findallpaths
--
-- Alexandra Barros - 2006.03.15
-------------------------------------------------------------------------------
-- Modifications by Ignacio Burgueño, mostly drop the use of 'module'
--
local _M = {
_NAME = "luanode.__private_traverse",
_PACKAGE = "luanode."
}
--module("traverse", package.seeall)
local List = {}
function List.new ()
return {first = 0, last = -1}
end
function List.push (list, value)
local last = list.last + 1
list.last = last
list[last] = value
end
function List.pop (list)
local first = list.first
if first > list.last then error("list is empty") end
local value = list[first]
list[first] = nil
list.first = first + 1
return value
end
function List.isempty (list)
return list.first > list.last
end
local edge -- forward declaration
local traverse = {}
function traverse.table(env, obj)
local f = env.funcs.table
if f then f(obj) end
for key, value in pairs(obj) do
edge(env, obj, key, "key", nil)
edge(env, obj, value, "value", key)
end
local mtable = debug.getmetatable(obj)
if mtable then edge(env, obj, mtable, "ismetatable", nil) end
end
function traverse.string(env, obj)
local f = env.funcs.string
if f then f(obj) end
end
function traverse.userdata(env, obj)
local f = env.funcs.userdata
if f then f(obj) end
local mtable = debug.getmetatable(obj)
if mtable then edge(env, obj, mtable, "ismetatable", nil) end
local fenv = debug.getfenv(obj)
if fenv then edge(env, obj, fenv, "environment", nil) end
end
traverse["function"] = function (env, obj)
local f = env.funcs.func
if f then f(obj) end
-- gets the upvalues
local i = 1
while true do
local n, v = debug.getupvalue(obj, i)
if not n then break end -- when there is no upvalues
edge(env, obj, n, "isname", nil)
edge(env, obj, v, "upvalue", n)
i = i + 1
end
local fenv = debug.getfenv(obj)
edge(env, obj, fenv, "environment", nil)
end
function traverse.thread(env, t)
local f = env.funcs.thread
if f then f(t) end
for i=1, math.huge do
local info = debug.getinfo(t, i, "f")
if not info then break end
for j=1, math.huge do
local n, v = debug.getlocal(t, i , j)
if not n then break end
print(n, v)
edge(env, nil, n, "isname", nil)
edge(env, nil, v, "local", n)
end
end
local fenv = debug.getfenv(t)
edge(env, t, fenv, "environment", nil)
end
-- 'how' is a string that identifies the content of 'to' and 'value':
-- if 'how' is "key", then 'to' is a key and 'name' is nil.
-- if 'how' is "value", then 'to' is an object and 'name' is the name of the
-- key.
edge = function (env, from, to, how, name)
local t = type(to)
if to and (t~="boolean") and (t~="number") and (t~="new") then
-- If the destination object has not been found yet
if not env.marked[to] then
env.marked[to] = true
List.push(env.list, to) -- puts on the list to be traversed
end
local f = env.funcs.edge
if f then f(from, to, how, name) end
end
end
-- Counts all references for a given object
function _M.countreferences(value)
local count = -1
local f = function(from, to, how, v)
if to == value then
count = count + 1
end
end
_M.traverse({edge=f}, {count, f})
return count
end
-- Main function
-- 'funcs' is a table that contains a funcation for every lua type and also the
-- function edge edge (traverseedge).
function _M.traverse(funcs, ignoreobjs)
-- The keys of the marked table are the objetcts (for example, table: 00442330).
-- The value of each key is true if the object has been found and false
-- otherwise.
local env = {marked = {}, list=List.new(), funcs=funcs}
if ignoreobjs then
for i=1, #ignoreobjs do
env.marked[ignoreobjs[i]] = true
end
end
env.marked["traverse"] = true
env.marked[_M.traverse] = true
env.marked[traverse] = true
env.marked[edge] = true
-- marks and inserts on the list
edge(env, nil, "_G", "isname", nil)
edge(env, nil, _G, "value", "_G")
-- traverses the active thread
-- inserts the local variables
-- interates over the function on the stack, starting from the one that
-- called traverse
for i=2, math.huge do
local info = debug.getinfo(i, "f")
if not info then break end
for j=1, math.huge do
local n, v = debug.getlocal(i, j)
if not n then break end
edge(env, nil, n, "isname", nil)
edge(env, nil, v, "local", n)
end
end
while not List.isempty(env.list) do
local obj = List.pop(env.list)
local t = type(obj)
--_M["traverse" .. t](env, obj)
traverse[t](env, obj)
end
end
return _M
|
-------------------------------------------------------------------------------
-- This module implements a function that traverses all live objects.
-- You can implement your own function to pass as a parameter of traverse
-- and give you the information you want. As an example we have implemented
-- countreferences and findallpaths
--
-- Alexandra Barros - 2006.03.15
-------------------------------------------------------------------------------
-- Modifications by Ignacio Burgueño, mostly drop the use of 'module'
--
local _M = {
_NAME = "luanode.__private_traverse",
_PACKAGE = "luanode."
}
--module("traverse", package.seeall)
local List = {}
function List.new ()
return {first = 0, last = -1}
end
function List.push (list, value)
local last = list.last + 1
list.last = last
list[last] = value
end
function List.pop (list)
local first = list.first
if first > list.last then error("list is empty") end
local value = list[first]
list[first] = nil
list.first = first + 1
return value
end
function List.isempty (list)
return list.first > list.last
end
local edge -- forward declaration
local traverse = {}
function traverse.table(env, obj)
local f = env.funcs.table
if f then f(obj) end
for key, value in pairs(obj) do
edge(env, obj, key, "key", nil)
edge(env, obj, value, "value", key)
end
local mtable = debug.getmetatable(obj)
if mtable then edge(env, obj, mtable, "ismetatable", nil) end
end
function traverse.string(env, obj)
local f = env.funcs.string
if f then f(obj) end
end
function traverse.userdata(env, obj)
local f = env.funcs.userdata
if f then f(obj) end
local mtable = debug.getmetatable(obj)
if mtable then edge(env, obj, mtable, "ismetatable", nil) end
local fenv = debug.getfenv(obj)
if fenv then edge(env, obj, fenv, "environment", nil) end
end
traverse["function"] = function (env, obj)
local f = env.funcs.func
if f then f(obj) end
-- gets the upvalues
local i = 1
while true do
local n, v = debug.getupvalue(obj, i)
if not n then break end -- when there is no upvalues
edge(env, obj, n, "isname", nil)
edge(env, obj, v, "upvalue", n)
i = i + 1
end
local fenv = debug.getfenv(obj)
edge(env, obj, fenv, "environment", nil)
end
function traverse.thread(env, t)
local f = env.funcs.thread
if f then f(t) end
for i=1, math.huge do
local info = debug.getinfo(t, i, "f")
if not info then break end
for j=1, math.huge do
local n, v = debug.getlocal(t, i , j)
if not n then break end
print(n, v)
edge(env, nil, n, "isname", nil)
edge(env, nil, v, "local", n)
end
end
local fenv = debug.getfenv(t)
edge(env, t, fenv, "environment", nil)
end
-- 'how' is a string that identifies the content of 'to' and 'value':
-- if 'how' is "key", then 'to' is a key and 'name' is nil.
-- if 'how' is "value", then 'to' is an object and 'name' is the name of the
-- key.
edge = function (env, from, to, how, name)
local t = type(to)
if to and (t~="boolean") and (t~="number") and (t~="new") then
-- If the destination object has not been found yet
if not env.marked[to] then
env.marked[to] = true
List.push(env.list, to) -- puts on the list to be traversed
end
local f = env.funcs.edge
if f then f(from, to, how, name) end
end
end
-- Counts all references for a given object
function _M.countreferences(value)
local count = -1
local f = function(from, to, how, v)
if to == value then
count = count + 1
end
end
_M.traverse({edge=f}, {count, f})
return count
end
-- Main function
-- 'funcs' is a table that contains a function for every lua type and also the
-- function edge edge (traverseedge).
function _M.traverse(funcs, ignoreobjs)
-- The keys of the marked table are the objects (for example, table: 00442330).
-- The value of each key is true if the object has been found and false
-- otherwise.
local env = {marked = {}, list=List.new(), funcs=funcs}
if ignoreobjs then
for i=1, #ignoreobjs do
env.marked[ignoreobjs[i]] = true
end
end
env.marked["traverse"] = true
env.marked[_M.traverse] = true
env.marked[traverse] = true
env.marked[edge] = true
-- marks and inserts on the list
edge(env, nil, "_G", "isname", nil)
edge(env, nil, _G, "value", "_G")
-- traverses the active thread
-- inserts the local variables
-- interates over the function on the stack, starting from the one that
-- called traverse
for i=2, math.huge do
local info = debug.getinfo(i, "f")
if not info then break end
for j=1, math.huge do
local n, v = debug.getlocal(i, j)
if not n then break end
edge(env, nil, n, "isname", nil)
edge(env, nil, v, "local", n)
end
end
while not List.isempty(env.list) do
local obj = List.pop(env.list)
local t = type(obj)
traverse[t](env, obj)
end
end
return _M
|
Fixes a couple typos.
|
Fixes a couple typos.
|
Lua
|
mit
|
ignacio/LuaNode,ignacio/LuaNode,ichramm/LuaNode,ichramm/LuaNode,ignacio/LuaNode,ichramm/LuaNode,ichramm/LuaNode,ignacio/LuaNode
|
89693c5719f8a3858c68aaf35c773aaba988b95f
|
spec/01-unit/009-responses_spec.lua
|
spec/01-unit/009-responses_spec.lua
|
local meta = require "kong.meta"
local responses = require "kong.tools.responses"
describe("Response helpers", function()
local old_ngx = _G.ngx
local snapshot
local stubbed_ngx
before_each(function()
snapshot = assert:snapshot()
stubbed_ngx = {
header = {},
say = function(...) return old_ngx.say(...) end,
exit = function(...) return old_ngx.exit(...) end,
log = function(...) return old_ngx.log(...) end,
}
_G.ngx = setmetatable(stubbed_ngx, {__index = old_ngx})
stub(stubbed_ngx, "say")
stub(stubbed_ngx, "exit")
stub(stubbed_ngx, "log")
end)
after_each(function()
snapshot:revert()
_G.ngx = old_ngx
end)
it("has a list of the main http status codes used in Kong", function()
assert.is_table(responses.status_codes)
end)
it("is callable via `send_HTTP_STATUS_CODE`", function()
for status_code_name, status_code in pairs(responses.status_codes) do
assert.has_no.errors(function()
responses["send_" .. status_code_name]()
end)
end
end)
it("sets the correct ngx values and call ngx.say and ngx.exit", function()
responses.send_HTTP_OK("OK")
assert.equal(ngx.status, responses.status_codes.HTTP_OK)
assert.equal(meta._NAME .. "/" .. meta._VERSION, ngx.header["Server"])
assert.stub(ngx.say).was.called() -- set custom content
assert.stub(ngx.exit).was.called() -- exit nginx (or continue to the next context if 200)
end)
it("send the content as a JSON string with a `message` property if given a string", function()
responses.send_HTTP_OK("OK")
assert.stub(ngx.say).was.called_with("{\"message\":\"OK\"}")
end)
it("sends the content as a JSON string if given a table", function()
responses.send_HTTP_OK({success = true})
assert.stub(ngx.say).was.called_with("{\"success\":true}")
end)
it("calls `ngx.exit` with the corresponding status_code", function()
for status_code_name, status_code in pairs(responses.status_codes) do
assert.has_no.errors(function()
responses["send_" .. status_code_name]()
assert.stub(ngx.exit).was.called_with(status_code)
end)
end
end)
it("calls `ngx.log` if and only if a 500 status code was given", function()
responses.send_HTTP_BAD_REQUEST()
assert.stub(ngx.log).was_not_called()
responses.send_HTTP_BAD_REQUEST("error")
assert.stub(ngx.log).was_not_called()
responses.send_HTTP_INTERNAL_SERVER_ERROR()
assert.stub(ngx.log).was_not_called()
responses.send_HTTP_INTERNAL_SERVER_ERROR("error")
assert.stub(ngx.log).was_called()
end)
it("don't call `ngx.log` if a 503 status code was given", function()
responses.send_HTTP_SERVICE_UNAVAILABLE()
assert.stub(ngx.log).was_not_called()
responses.send_HTTP_SERVICE_UNAVAILABLE()
assert.stub(ngx.log).was_not_called("error")
end)
describe("default content rules for some status codes", function()
it("should apply default content rules for some status codes", function()
responses.send_HTTP_NOT_FOUND()
assert.stub(ngx.say).was.called_with("{\"message\":\"Not found\"}")
responses.send_HTTP_NOT_FOUND("override")
assert.stub(ngx.say).was.called_with("{\"message\":\"override\"}")
end)
it("should apply default content rules for some status codes", function()
responses.send_HTTP_NO_CONTENT("some content")
assert.stub(ngx.say).was.not_called()
end)
it("should apply default content rules for some status codes", function()
responses.send_HTTP_INTERNAL_SERVER_ERROR()
assert.stub(ngx.say).was.called_with("{\"message\":\"An unexpected error occurred\"}")
responses.send_HTTP_INTERNAL_SERVER_ERROR("override")
assert.stub(ngx.say).was.called_with("{\"message\":\"An unexpected error occurred\"}")
end)
it("should apply default content rules for some status codes", function()
responses.send_HTTP_SERVICE_UNAVAILABLE()
assert.stub(ngx.say).was.called_with("{\"message\":\"Service unavailable\"}")
responses.send_HTTP_SERVICE_UNAVAILABLE("override")
assert.stub(ngx.say).was.called_with("{\"message\":\"override\"}")
end)
end)
describe("send()", function()
it("sends a custom status code", function()
responses.send(415, "Unsupported media type")
assert.stub(ngx.say).was.called_with("{\"message\":\"Unsupported media type\"}")
assert.stub(ngx.exit).was.called_with(415)
responses.send(415, "Unsupported media type")
assert.stub(ngx.say).was.called_with("{\"message\":\"Unsupported media type\"}")
assert.stub(ngx.exit).was.called_with(415)
responses.send(501)
assert.stub(ngx.exit).was.called_with(501)
end)
end)
describe("delayed response", function()
it("does not call ngx.say/ngx.exit if `ctx.delayed_response = true`", function()
ngx.ctx.delay_response = true
responses.send(401, "Unauthorized", { ["X-Hello"] = "world" })
assert.stub(ngx.say).was_not_called()
assert.stub(ngx.exit).was_not_called()
assert.not_equal("world", ngx.header["X-Hello"])
end)
it("flush_delayed_response() sends delayed response's status/header/body", function()
ngx.ctx.delay_response = true
responses.send(401, "Unauthorized", { ["X-Hello"] = "world" })
responses.flush_delayed_response(ngx.ctx)
assert.stub(ngx.say).was.called_with("{\"message\":\"Unauthorized\"}")
assert.stub(ngx.exit).was.called_with(401)
assert.equal("world", ngx.header["X-Hello"])
assert.is_false(ngx.ctx.delay_response)
end)
it("delayed response cannot be overriden", function()
ngx.ctx.delay_response = true
responses.send(401, "Unauthorized")
responses.send(200, "OK")
responses.flush_delayed_response(ngx.ctx)
assert.stub(ngx.say).was.called_with("{\"message\":\"Unauthorized\"}")
assert.stub(ngx.exit).was.called_with(401)
end)
it("flush_delayed_response() use custom callback if set", function()
local s = spy.new(function(ctx) end)
do
local old_type = _G.type
-- luacheck: ignore
_G.type = function(v)
if v == s then
return "function"
end
return old_type(v)
end
finally(function()
_G.type = old_type
end)
end
package.loaded["kong.tools.responses"] = nil
responses = require "kong.tools.responses"
ngx.ctx.delay_response = true
ngx.ctx.delayed_response_callback = s
responses.send(401, "Unauthorized", { ["X-Hello"] = "world" })
responses.flush_delayed_response(ngx.ctx)
assert.spy(s).was.called_with(ngx.ctx)
end)
end)
end)
|
local meta = require "kong.meta"
local responses = require "kong.tools.responses"
describe("Response helpers", function()
local old_ngx = _G.ngx
local snapshot
local stubbed_ngx
before_each(function()
snapshot = assert:snapshot()
stubbed_ngx = {
header = {},
say = function(...) return old_ngx.say(...) end,
exit = function(...) return old_ngx.exit(...) end,
log = function(...) return old_ngx.log(...) end,
}
_G.ngx = setmetatable(stubbed_ngx, {__index = old_ngx})
stub(stubbed_ngx, "say")
stub(stubbed_ngx, "exit")
stub(stubbed_ngx, "log")
end)
after_each(function()
snapshot:revert()
_G.ngx = old_ngx
end)
it("has a list of the main http status codes used in Kong", function()
assert.is_table(responses.status_codes)
end)
it("is callable via `send_HTTP_STATUS_CODE`", function()
for status_code_name, status_code in pairs(responses.status_codes) do
assert.has_no.errors(function()
responses["send_" .. status_code_name]()
end)
end
end)
it("sets the correct ngx values and call ngx.say and ngx.exit", function()
responses.send_HTTP_OK("OK")
assert.equal(ngx.status, responses.status_codes.HTTP_OK)
assert.equal(meta._NAME .. "/" .. meta._VERSION, ngx.header["Server"])
assert.stub(ngx.say).was.called() -- set custom content
assert.stub(ngx.exit).was.called() -- exit nginx (or continue to the next context if 200)
end)
it("send the content as a JSON string with a `message` property if given a string", function()
responses.send_HTTP_OK("OK")
assert.stub(ngx.say).was.called_with("{\"message\":\"OK\"}")
end)
it("sends the content as a JSON string if given a table", function()
responses.send_HTTP_OK({success = true})
assert.stub(ngx.say).was.called_with("{\"success\":true}")
end)
it("calls `ngx.exit` with the corresponding status_code", function()
for status_code_name, status_code in pairs(responses.status_codes) do
assert.has_no.errors(function()
responses["send_" .. status_code_name]()
assert.stub(ngx.exit).was.called_with(status_code)
end)
end
end)
it("calls `ngx.log` if and only if a 500 status code was given", function()
responses.send_HTTP_BAD_REQUEST()
assert.stub(ngx.log).was_not_called()
responses.send_HTTP_BAD_REQUEST("error")
assert.stub(ngx.log).was_not_called()
responses.send_HTTP_INTERNAL_SERVER_ERROR()
assert.stub(ngx.log).was_not_called()
responses.send_HTTP_INTERNAL_SERVER_ERROR("error")
assert.stub(ngx.log).was_called()
end)
it("don't call `ngx.log` if a 503 status code was given", function()
responses.send_HTTP_SERVICE_UNAVAILABLE()
assert.stub(ngx.log).was_not_called()
responses.send_HTTP_SERVICE_UNAVAILABLE()
assert.stub(ngx.log).was_not_called("error")
end)
describe("default content rules for some status codes", function()
it("should apply default content rules for some status codes", function()
responses.send_HTTP_NOT_FOUND()
assert.stub(ngx.say).was.called_with("{\"message\":\"Not found\"}")
responses.send_HTTP_NOT_FOUND("override")
assert.stub(ngx.say).was.called_with("{\"message\":\"override\"}")
end)
it("should apply default content rules for some status codes", function()
responses.send_HTTP_NO_CONTENT("some content")
assert.stub(ngx.say).was.not_called()
end)
it("should apply default content rules for some status codes", function()
responses.send_HTTP_INTERNAL_SERVER_ERROR()
assert.stub(ngx.say).was.called_with("{\"message\":\"An unexpected error occurred\"}")
responses.send_HTTP_INTERNAL_SERVER_ERROR("override")
assert.stub(ngx.say).was.called_with("{\"message\":\"An unexpected error occurred\"}")
end)
it("should apply default content rules for some status codes", function()
responses.send_HTTP_SERVICE_UNAVAILABLE()
assert.stub(ngx.say).was.called_with("{\"message\":\"Service unavailable\"}")
responses.send_HTTP_SERVICE_UNAVAILABLE("override")
assert.stub(ngx.say).was.called_with("{\"message\":\"override\"}")
end)
end)
describe("send()", function()
it("sends a custom status code", function()
responses.send(415, "Unsupported media type")
assert.stub(ngx.say).was.called_with("{\"message\":\"Unsupported media type\"}")
assert.stub(ngx.exit).was.called_with(415)
responses.send(415, "Unsupported media type")
assert.stub(ngx.say).was.called_with("{\"message\":\"Unsupported media type\"}")
assert.stub(ngx.exit).was.called_with(415)
responses.send(501)
assert.stub(ngx.exit).was.called_with(501)
end)
end)
describe("delayed response", function()
after_each(function()
ngx.ctx.delayed_response = nil
end)
it("yields and does not call ngx.say/ngx.exit if `ctx.delaye_response = true`", function()
ngx.ctx.delay_response = true
local co = coroutine.wrap(responses.send)
co(401, "Unauthorized", { ["X-Hello"] = "world" })
assert.stub(ngx.say).was_not_called()
assert.stub(ngx.exit).was_not_called()
assert.not_equal("world", ngx.header["X-Hello"])
end)
it("flush_delayed_response() sends delayed response's status/header/body", function()
ngx.ctx.delay_response = true
responses.send(401, "Unauthorized", { ["X-Hello"] = "world" })
responses.flush_delayed_response(ngx.ctx)
assert.stub(ngx.say).was.called_with("{\"message\":\"Unauthorized\"}")
assert.stub(ngx.exit).was.called_with(401)
assert.equal("world", ngx.header["X-Hello"])
assert.is_false(ngx.ctx.delay_response)
end)
it("delayed response cannot be overriden", function()
ngx.ctx.delay_response = true
responses.send(401, "Unauthorized")
responses.send(200, "OK")
responses.flush_delayed_response(ngx.ctx)
assert.stub(ngx.say).was.called_with("{\"message\":\"Unauthorized\"}")
assert.stub(ngx.exit).was.called_with(401)
end)
it("flush_delayed_response() use custom callback if set", function()
local s = spy.new(function(ctx) end)
do
local old_type = _G.type
-- luacheck: ignore
_G.type = function(v)
if v == s then
return "function"
end
return old_type(v)
end
finally(function()
_G.type = old_type
end)
end
package.loaded["kong.tools.responses"] = nil
responses = require "kong.tools.responses"
ngx.ctx.delay_response = true
ngx.ctx.delayed_response_callback = s
responses.send(401, "Unauthorized", { ["X-Hello"] = "world" })
responses.flush_delayed_response(ngx.ctx)
assert.spy(s).was.called_with(ngx.ctx)
end)
end)
end)
|
tests(responses) fix delay_response test failure
|
tests(responses) fix delay_response test failure
Ensure we run this test the same way we run our business logic: inside a
coroutine.
|
Lua
|
apache-2.0
|
Kong/kong,Mashape/kong,Kong/kong,Kong/kong,jebenexer/kong
|
6b35cd1908e4b3837fde9d2c93f60b4def99814c
|
entities/entities/projectile_molotov/init.lua
|
entities/entities/projectile_molotov/init.lua
|
AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include("shared.lua")
ENT.m_flDamage = 40
ENT.m_DmgRadius = 128
function ENT:Initialize()
self:SetMoveType(MOVETYPE_FLYGRAVITY)
self:SetMoveCollide(MOVECOLLIDE_FLY_BOUNCE)
self:SetSolid(SOLID_BBOX)
self:SetCollisionGroup(COLLISION_GROUP_PROJECTILE)
self:RemoveEffects(EF_NOINTERP)
self:SetModel("models/weapons/molotov3rd_zm.mdl")
self:SetGravity(1.0)
self:SetFriction(0.8)
self:SetSequence(1)
local fireTrail = ents.Create("env_fire_trail")
fireTrail:FollowBone(self, self:LookupBone("flame"))
fireTrail:Spawn()
fireTrail:Activate()
self:SetTrigger(true)
end
function ENT:Touch(pOther)
if (bit.band(pOther:GetSolidFlags(), FSOLID_TRIGGER) == 0 or bit.band(pOther:GetSolidFlags(), FSOLID_VOLUME_CONTENTS) == 0) and pOther:GetCollisionGroup() ~= COLLISION_GROUP_WEAPON then
return
end
self:Detonate()
end
function ENT:Detonate()
self:SetNoDraw(true)
self:AddSolidFlags(FSOLID_NOT_SOLID)
local trace = self:GetTouchTrace()
if trace.Fraction ~= 1.0 then
self:SetLocalPos(trace.HitPos + (trace.HitNormal * (self.m_flDamage - 24) * 0.6))
end
local contents = util.PointContents(self:GetPos())
if bit.band(contents, MASK_WATER) ~= 0 then
self:Remove()
return
end
local dmginfo = DamageInfo()
dmginfo:SetAttacker(self.Owner)
dmginfo:SetInflictor(self)
dmginfo:SetDamage(self.m_flDamage)
dmginfo:SetDamagePosition(trace.HitPos)
dmginfo:SetDamageType(DMG_BURN)
util.BlastDamageInfo(dmginfo, trace.HitPos, self.m_DmgRadius)
local effectdata = EffectData()
effectdata:SetOrigin(trace.HitPos)
util.Effect("HelicopterMegaBomb", effectdata)
util.Decal("Scorch", self:GetPos(), trace.HitPos - trace.HitNormal)
self:EmitSound("Grenade_Molotov.Detonate")
self:EmitSound("Grenade_Molotov.Detonate2")
local owner = self:GetOwner()
for _, v in pairs(ents.FindInSphere(trace.HitPos, self.m_DmgRadius)) do
if v:IsNPC() then
v:Ignite(100)
elseif v == owner then
v:Ignite(3)
end
end
for i = 1, 10 do
local fire = ents.Create("env_fire")
fire:SetPos(trace.HitPos + Vector(math.random(-80, 80), math.random(-80, 80), 0))
fire:SetKeyValue("health", 25)
fire:SetKeyValue("firesize", "60")
fire:SetKeyValue("fireattack", "2")
fire:SetKeyValue("damagescale", "4.0")
fire:SetKeyValue("StartDisabled", "0")
fire:SetKeyValue("firetype", "0" )
fire:SetKeyValue("spawnflags", "132")
fire:Spawn()
fire:Fire("StartFire", "", 0)
fire:SetOwner(owner)
if owner:IsPlayer() then
fire.OwnerTeam = owner:Team()
else
fire.OwnerTeam = TEAM_SURVIVOR
end
end
for i=1, 8 do
local sparks = ents.Create( "env_spark" )
sparks:SetPos( trace.HitPos + Vector( math.random( -40, 40 ), math.random( -40, 40 ), math.random( -40, 40 ) ) )
sparks:SetKeyValue( "MaxDelay", "0" )
sparks:SetKeyValue( "Magnitude", "2" )
sparks:SetKeyValue( "TrailLength", "3" )
sparks:SetKeyValue( "spawnflags", "0" )
sparks:Spawn()
sparks:Fire( "SparkOnce", "", 0 )
end
end
|
AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include("shared.lua")
ENT.m_flDamage = 40
ENT.m_DmgRadius = 128
function ENT:Initialize()
self:SetModel("models/weapons/molotov3rd_zm.mdl")
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self:SetCollisionGroup(COLLISION_GROUP_PROJECTILE)
self:GetPhysicsObject():Wake()
self:SetAngles(Angle(math.random(0, 360), math.random(0, 360), math.random(0, 360)))
self:SetGravity(1.0)
self:SetFriction(0.8)
self:SetSequence(1)
local fireTrail = ents.Create("env_fire_trail")
if IsValid(fireTrail) then
fireTrail:SetPos(self:GetPos())
fireTrail:SetParent(self)
fireTrail:Spawn()
fireTrail:Activate()
end
end
function ENT:Think()
if self.PhysicsData then
if self.HitWater then
self:Remove()
else
self:Detonate(self.PhysicsData.HitPos, self.PhysicsData.HitNormal)
end
end
end
function ENT:PhysicsCollide(data, phys)
self.PhysicsData = data
local contents = util.PointContents(self:GetPos())
if bit.band(contents, MASK_WATER) ~= 0 then
self.HitWater = true
end
self:NextThink(CurTime())
end
function ENT:Detonate(hitpos, hitnormal)
self:SetNoDraw(true)
self:AddSolidFlags(FSOLID_NOT_SOLID)
local contents = util.PointContents(self:GetPos())
if bit.band(contents, MASK_WATER) ~= 0 then
self:Remove()
return
end
local dmginfo = DamageInfo()
dmginfo:SetAttacker(self.Owner)
dmginfo:SetInflictor(self)
dmginfo:SetDamage(self.m_flDamage)
dmginfo:SetDamagePosition(hitpos)
dmginfo:SetDamageType(DMG_BURN)
util.BlastDamageInfo(dmginfo, hitpos, self.m_DmgRadius)
local effectdata = EffectData()
effectdata:SetOrigin(hitpos)
util.Effect("HelicopterMegaBomb", effectdata)
util.Decal("Scorch", self:GetPos(), hitpos - hitnormal)
self:EmitSound("Grenade_Molotov.Detonate")
self:EmitSound("Grenade_Molotov.Detonate2")
local owner = self:GetOwner()
for _, v in pairs(ents.FindInSphere(hitpos, self.m_DmgRadius)) do
if v:IsNPC() then
v:Ignite(100)
elseif v == owner then
v:Ignite(3)
end
end
for i = 1, 10 do
local fire = ents.Create("env_fire")
fire:SetPos(hitpos + Vector(math.random(-80, 80), math.random(-80, 80), 0))
fire:SetKeyValue("health", 25)
fire:SetKeyValue("firesize", "60")
fire:SetKeyValue("fireattack", "2")
fire:SetKeyValue("damagescale", "4.0")
fire:SetKeyValue("StartDisabled", "0")
fire:SetKeyValue("firetype", "0" )
fire:SetKeyValue("spawnflags", "132")
fire:Spawn()
fire:Fire("StartFire", "", 0)
fire:SetOwner(owner)
if owner:IsPlayer() then
fire.OwnerTeam = owner:Team()
else
fire.OwnerTeam = TEAM_SURVIVOR
end
end
for i=1, 8 do
local sparks = ents.Create( "env_spark" )
sparks:SetPos( hitpos + Vector( math.random( -40, 40 ), math.random( -40, 40 ), math.random( -40, 40 ) ) )
sparks:SetKeyValue( "MaxDelay", "0" )
sparks:SetKeyValue( "Magnitude", "2" )
sparks:SetKeyValue( "TrailLength", "3" )
sparks:SetKeyValue( "spawnflags", "0" )
sparks:Spawn()
sparks:Fire( "SparkOnce", "", 0 )
end
self:Remove()
end
|
Fixed Molotov projectile being broken
|
Fixed Molotov projectile being broken
|
Lua
|
apache-2.0
|
ForrestMarkX/glua-ZombieMaster
|
2f1eafcf061a78fbcbf66d8f9e6cc33208078bc2
|
examples/lib/write.lua
|
examples/lib/write.lua
|
-- Functions for printing to Termbox.
local write = {}
write.xdefault = 1
write.ydefault = 1
function write.line(str, ox, oy)
x = ox or write.xdefault
y = oy or write.ydefault
-- see gopher-lua issue #47
--str:gsub(".", function(char)
for i = 1, str:len() do char = str:sub(i,i)
if char == '\n' then
y = y + 1
x = ox or write.xdefault
else
termbox.set(x, y, char)
x = x + 1
end
end--)
termbox.flush()
write.xdefault = ox or write.xdefault
write.ydefault = y + 1
return y + 1
end
function write.lines(tab, x, y)
for i, v in ipairs(tab) do
y = write.line(v, x, y)
end
end
return write
|
-- Functions for printing to Termbox.
local write = {}
write.xdefault = 1
write.ydefault = 1
function write.line(str, ox, oy)
x = ox or write.xdefault
y = oy or write.ydefault
str:gsub(".", function(char)
if char == "\n" then
y = y + 1
x = ox or write.xdefault
else
termbox.set(x, y, char)
x = x + 1
end
end)
termbox.flush()
write.xdefault = ox or write.xdefault
write.ydefault = y + 1
return y + 1
end
function write.lines(tab, x, y)
for i, v in ipairs(tab) do
y = write.line(v, x, y)
end
end
return write
|
gopher-lua issue fixed
|
gopher-lua issue fixed
|
Lua
|
apache-2.0
|
ferbivore/luabox
|
97baa30328adc2cf81ed960e92ab24c485a59884
|
commands/update.lua
|
commands/update.lua
|
local log = require('log')
local updater = require('auto-updater')
local uv = require('uv')
local pathJoin = require('luvi').path.join
local exec = require('exec')
local prompt = require('prompt')(require('pretty-print'))
local miniz = require('miniz')
local binDir = pathJoin(uv.exepath(), "..")
local function updateLit()
return updater.check(require('../package'), uv.exepath())
end
local function updateLuvit()
local luvitPath = pathJoin(binDir, "luvit")
if uv.fs_stat(luvitPath) then
local bundle = require('luvi').makeBundle({"/usr/local/bin/luvit"})
local fs = {
readFile = bundle.readfile,
stat = bundle.stat,
}
return updater.check(require('pkg').query(fs, "."), luvitPath)
else
return updater.check({ name = "luvit/luvit" }, luvitPath)
end
end
local function updateLuvi()
local target = pathJoin(binDir, "luvi")
local new, old
local toupdate = require('luvi').version
if uv.fs_stat(target) then
local stdout = exec(target, "-v")
local version = stdout:match("luvi (v[^ \n]+)")
if version and version == toupdate then
log("luvi is up to date", version, "highlight")
return
end
log("found system luvi", version)
local res = prompt("Are you sure you wish to update " .. target .. " to luvi " .. toupdate .. "?", "Y/n")
if not res:match("[yY]") then
log("canceled update", version, "err")
return
end
log("updating luvi", toupdate)
new = target .. ".new"
old = target .. ".old"
else
log("installing luvi binary", target, "highlight")
old = nil
new = target
end
local fd = assert(uv.fs_open(new, "w", 511)) -- 0777
local source = uv.exepath()
local reader = miniz.new_reader(source)
local binSize
if reader then
-- If contains a zip, find where the zip starts
binSize = reader:get_offset()
else
-- Otherwise just read the file size
binSize = uv.fs_stat(source).size
end
local fd2 = assert(uv.fs_open(source, "r", 384)) -- 0600
assert(uv.fs_sendfile(fd, fd2, 0, binSize))
uv.fs_close(fd2)
uv.fs_close(fd)
if old then
log("replacing luvi binary", target, "highlight")
uv.fs_rename(target, old)
uv.fs_rename(new, target)
uv.fs_unlink(old)
log("luvi update complete", toupdate, "success")
else
log("luvi install complete", toupdate, "success")
end
end
local commands = {
luvi = updateLuvi,
luvit = updateLuvit,
lit = updateLit,
all = function ()
updateLit()
updateLuvit()
updateLuvi()
end
}
local cmd = commands[args[2] or "all"]
if not cmd then
error("Unknown update command: " .. args[2])
end
cmd()
|
local log = require('log')
local updater = require('auto-updater')
local uv = require('uv')
local pathJoin = require('luvi').path.join
local exec = require('exec')
local prompt = require('prompt')(require('pretty-print'))
local miniz = require('miniz')
local binDir = pathJoin(uv.exepath(), "..")
local function updateLit()
return updater.check(require('../package'), uv.exepath())
end
local function updateLuvit()
local luvitPath = pathJoin(binDir, "luvit")
if require('ffi').os == "Windows" then
luvitPath = luvitPath .. ".exe"
end
if uv.fs_stat(luvitPath) then
local bundle = require('luvi').makeBundle({"/usr/local/bin/luvit"})
local fs = {
readFile = bundle.readfile,
stat = bundle.stat,
}
return updater.check(require('pkg').query(fs, "."), luvitPath)
else
return updater.check({ name = "luvit/luvit" }, luvitPath)
end
end
local function updateLuvi()
local target = pathJoin(binDir, "luvi")
if require('ffi').os == "Windows" then
target = target .. ".exe"
end
local new, old
local toupdate = require('luvi').version
if uv.fs_stat(target) then
local stdout = exec(target, "-v")
local version = stdout:match("luvi (v[^ \n]+)")
if version and version == toupdate then
log("luvi is up to date", version, "highlight")
return
end
log("found system luvi", version)
local res = prompt("Are you sure you wish to update " .. target .. " to luvi " .. toupdate .. "?", "Y/n")
if not res:match("[yY]") then
log("canceled update", version, "err")
return
end
log("updating luvi", toupdate)
new = target .. ".new"
old = target .. ".old"
else
log("installing luvi binary", target, "highlight")
old = nil
new = target
end
local fd = assert(uv.fs_open(new, "w", 511)) -- 0777
local source = uv.exepath()
local reader = miniz.new_reader(source)
local binSize
if reader then
-- If contains a zip, find where the zip starts
binSize = reader:get_offset()
else
-- Otherwise just read the file size
binSize = uv.fs_stat(source).size
end
local fd2 = assert(uv.fs_open(source, "r", 384)) -- 0600
assert(uv.fs_sendfile(fd, fd2, 0, binSize))
uv.fs_close(fd2)
uv.fs_close(fd)
if old then
log("replacing luvi binary", target, "highlight")
uv.fs_rename(target, old)
uv.fs_rename(new, target)
uv.fs_unlink(old)
log("luvi update complete", toupdate, "success")
else
log("luvi install complete", toupdate, "success")
end
end
local commands = {
luvi = updateLuvi,
luvit = updateLuvit,
lit = updateLit,
all = function ()
updateLit()
updateLuvit()
updateLuvi()
end
}
local cmd = commands[args[2] or "all"]
if not cmd then
error("Unknown update command: " .. args[2])
end
cmd()
|
Fix update on Windows not targetting .exe files
|
Fix update on Windows not targetting .exe files
* Mirrors logic in libs/core.lua's realMake fn
|
Lua
|
apache-2.0
|
DBarney/lit,james2doyle/lit,kidaa/lit,luvit/lit,1yvT0s/lit,squeek502/lit,lduboeuf/lit,kaustavha/lit,zhaozg/lit
|
584a771c69206bc1d337d8fb19b9e6aec33b73da
|
mod_seclabels/mod_seclabels.lua
|
mod_seclabels/mod_seclabels.lua
|
local st = require "util.stanza";
local xmlns_label = "urn:xmpp:sec-label:0";
local xmlns_label_catalog = "urn:xmpp:sec-label:catalog:2";
local xmlns_label_catalog_old = "urn:xmpp:sec-label:catalog:0"; -- COMPAT
module:add_feature(xmlns_label);
module:add_feature(xmlns_label_catalog);
module:add_feature(xmlns_label_catalog_old);
module:hook("account-disco-info", function(event) -- COMPAT
local stanza = event.stanza;
stanza:tag('feature', {var=xmlns_label}):up();
stanza:tag('feature', {var=xmlns_label_catalog}):up();
end);
local default_labels = {
Classified = {
SECRET = { color = "black", bgcolor = "aqua", label = "THISISSECRET" };
PUBLIC = { label = "THISISPUBLIC" };
};
};
local catalog_name, catalog_desc, labels;
function get_conf()
catalog_name = module:get_option_string("security_catalog_name", "Default");
catalog_desc = module:get_option_string("security_catalog_desc", "My labels");
labels = module:get_option("security_labels", default_labels);
end
module:hook("config-reloaded",get_conf);
get_conf();
function handle_catalog_request(request)
local catalog_request = request.stanza.tags[1];
local reply = st.reply(request.stanza)
:tag("catalog", {
xmlns = catalog_request.attr.xmlns,
to = catalog_request.attr.to,
name = catalog_name,
desc = catalog_desc
});
local function add_labels(catalog, labels, selector)
for name, value in pairs(labels) do
if value.label then
if catalog_request.attr.xmlns == xmlns_label_catalog then
catalog:tag("item", {
selector = selector..name,
default = value.default and "true" or nil,
}):tag("securitylabel", { xmlns = xmlns_label })
else -- COMPAT
catalog:tag("securitylabel", {
xmlns = xmlns_label,
selector = selector..name,
default = value.default and "true" or nil,
})
end
if value.name or value.color or value.bgcolor then
catalog:tag("displaymarking", {
fgcolor = value.color,
bgcolor = value.bgcolor,
}):text(value.name or name):up();
end
if type(value.label) == "string" then
catalog:tag("label"):text(value.label):up();
elseif type(value.label) == "table" then
catalog:tag("label"):add_child(value.label):up();
end
catalog:up();
if catalog_request.attr.xmlns == xmlns_label_catalog then
catalog:up();
end
else
add_labels(catalog, value, (selector or "")..name.."|");
end
end
end
add_labels(reply, labels, "");
request.origin.send(reply);
return true;
end
module:hook("iq/host/"..xmlns_label_catalog..":catalog", handle_catalog_request);
module:hook("iq/self/"..xmlns_label_catalog..":catalog", handle_catalog_request); -- COMPAT
module:hook("iq/self/"..xmlns_label_catalog_old..":catalog", handle_catalog_request); -- COMPAT
|
local st = require "util.stanza";
local xmlns_label = "urn:xmpp:sec-label:0";
local xmlns_label_catalog = "urn:xmpp:sec-label:catalog:2";
local xmlns_label_catalog_old = "urn:xmpp:sec-label:catalog:0"; -- COMPAT
module:add_feature(xmlns_label);
module:add_feature(xmlns_label_catalog);
module:add_feature(xmlns_label_catalog_old);
module:hook("account-disco-info", function(event) -- COMPAT
local stanza = event.stanza;
stanza:tag('feature', {var=xmlns_label}):up();
stanza:tag('feature', {var=xmlns_label_catalog}):up();
end);
local default_labels = {
Classified = {
SECRET = { color = "black", bgcolor = "aqua", label = "THISISSECRET" };
PUBLIC = { label = "THISISPUBLIC" };
};
};
local catalog_name, catalog_desc, labels;
local function get_conf()
catalog_name = module:get_option_string("security_catalog_name", "Default");
catalog_desc = module:get_option_string("security_catalog_desc", "My labels");
labels = module:get_option("security_labels", default_labels);
end
module:hook_global("config-reloaded",get_conf);
get_conf();
function handle_catalog_request(request)
local catalog_request = request.stanza.tags[1];
local reply = st.reply(request.stanza)
:tag("catalog", {
xmlns = catalog_request.attr.xmlns,
to = catalog_request.attr.to,
name = catalog_name,
desc = catalog_desc
});
local function add_labels(catalog, labels, selector)
for name, value in pairs(labels) do
if value.label then
if catalog_request.attr.xmlns == xmlns_label_catalog then
catalog:tag("item", {
selector = selector..name,
default = value.default and "true" or nil,
}):tag("securitylabel", { xmlns = xmlns_label })
else -- COMPAT
catalog:tag("securitylabel", {
xmlns = xmlns_label,
selector = selector..name,
default = value.default and "true" or nil,
})
end
if value.name or value.color or value.bgcolor then
catalog:tag("displaymarking", {
fgcolor = value.color,
bgcolor = value.bgcolor,
}):text(value.name or name):up();
end
if type(value.label) == "string" then
catalog:tag("label"):text(value.label):up();
elseif type(value.label) == "table" then
catalog:tag("label"):add_child(value.label):up();
end
catalog:up();
if catalog_request.attr.xmlns == xmlns_label_catalog then
catalog:up();
end
else
add_labels(catalog, value, (selector or "")..name.."|");
end
end
end
-- TODO query remote servers
--[[ FIXME later
labels = module:fire_event("sec-label-catalog", {
to = catalog_request.attr.to,
request = request; -- or just origin?
labels = labels;
}) or labels;
--]]
add_labels(reply, labels, "");
request.origin.send(reply);
return true;
end
module:hook("iq/host/"..xmlns_label_catalog..":catalog", handle_catalog_request);
module:hook("iq/self/"..xmlns_label_catalog..":catalog", handle_catalog_request); -- COMPAT
module:hook("iq/self/"..xmlns_label_catalog_old..":catalog", handle_catalog_request); -- COMPAT
|
mod_seclabels: Fix config reloading
|
mod_seclabels: Fix config reloading
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
ce12db188673a4090baf25890dab81fec2067d9f
|
yahoovoices.lua
|
yahoovoices.lua
|
local url_count = 0
wget.callbacks.httploop_result = function(url, err, http_stat)
-- NEW for 2014: Slightly more verbose messages because people keep
-- complaining that it's not moving or not working
local status_code = http_stat["statcode"]
url_count = url_count + 1
io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \r")
io.stdout:flush()
if status_code >= 500 or
(status_code >= 400 and status_code ~= 404) then
io.stdout:write("\nYahoo! Server returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 5")
return wget.actions.CONTINUE
end
-- We're okay; sleep a bit (if we have to) and continue
local sleep_time = 0.1 * (math.random(75, 125) / 100.0)
if string.match(url["host"], "yimg%.com") then
-- We should be able to go fast on images since that's what a web browser does
sleep_time = 0
end
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
|
local url_count = 0
wget.callbacks.httploop_result = function(url, err, http_stat)
-- NEW for 2014: Slightly more verbose messages because people keep
-- complaining that it's not moving or not working
local status_code = http_stat["statcode"]
url_count = url_count + 1
io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \r")
io.stdout:flush()
if status_code >= 500 or
(status_code >= 400 and status_code ~= 404) then
io.stdout:write("\nYahoo! Server returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 5")
return wget.actions.CONTINUE
end
-- We're okay; sleep a bit (if we have to) and continue
local sleep_time = 0.1 * (math.random(75, 125) / 100.0)
if string.match(url["host"], "yimg%.com") then
-- We should be able to go fast on images since that's what a web browser does
sleep_time = 0
end
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
-- download URLs only once because wget is buggy
local downloaded_table = {}
wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason)
if verdict then
if downloaded_table[urlpos["url"]["url"]] then
return false
else
downloaded_table[urlpos["url"]["url"]] = true
return true
end
else
return verdict
end
end
|
yahoovoices.lua: Workaround wget bug to download only once
|
yahoovoices.lua: Workaround wget bug to download only once
|
Lua
|
unlicense
|
ArchiveTeam/yahoo-voices-grab,ArchiveTeam/yahoo-voices-grab
|
104e6e0d81a5c823205cbffbfd1f3d1575bb952f
|
IPyLua/dom_builder.lua
|
IPyLua/dom_builder.lua
|
local pyget = pyget
local dom_builder = {}
local element_mt = {
__tostring = function(self) return "<"..self.tag..">" end,
ipylua_show = function(self)
local tbl = { "<", self.tag }
for k,v in pairs(tbl) do
if type(k)~="number" and k~="tag" then
tbl[#tbl+1] = ('%s="%s"'):format(k,tostring(v))
end
end
tbl[#tbl+1] = ">"
for i=1,#self do
local data = pyget(self[i])
if data["image/png"] then
tbl[#tbl+1] = ('<img src="data:image/png;base64,%s">'):format(data["image/png"])
elseif data["text/html"] then
tbl[#tbl+1] = data["text/html"]
else
tbl[#tbl+1] = assert( data["text/plain"] )
end
end
tbl[#tbl+1] = "</"
tbl[#tbl+1] = self.tag
tbl[#tbl+1] = ">"
return { ["text/html"] = table.concat(tbl) }
end,
}
local function element(tag,params)
local t = {} for k,v in pairs(params or {}) do t[k] = v end
t.tag = tag
return setmetatable(t, element_mt)
end
setmetatable(dom_builder,{
__index = function(_,tag)
return function(params)
return element(tag,params)
end
end,
})
return dom_builder
|
local pyget = pyget
local dom_builder = {}
local element_mt = {
__tostring = function(self) return "<"..self.tag..">" end,
ipylua_show = function(self)
local tbl = { "<", self.tag }
for k,v in pairs(tbl) do
if type(k)~="number" and k~="tag" then
tbl[#tbl+1] = ('%s="%s"'):format(k,tostring(v))
end
end
tbl[#tbl+1] = ">"
for i=1,#self do
local data
local tt = type(self[i])
if tt == "string" or tt == "number" then
data = { ["text/html"] = self[i] }
else
data = pyget(self[i])
end
if data["image/png"] then
tbl[#tbl+1] = ('<img src="data:image/png;base64,%s">'):format(data["image/png"])
elseif data["text/html"] then
tbl[#tbl+1] = data["text/html"]
else
tbl[#tbl+1] = assert( data["text/plain"] )
end
end
tbl[#tbl+1] = "</"
tbl[#tbl+1] = self.tag
tbl[#tbl+1] = ">"
return { ["text/html"] = table.concat(tbl) }
end,
}
local function element(tag,params)
local t = {} for k,v in pairs(params or {}) do t[k] = v end
t.tag = tag
return setmetatable(t, element_mt)
end
setmetatable(dom_builder,{
__index = function(_,tag)
return function(params)
return element(tag,params)
end
end,
})
return dom_builder
|
Fixed problem in dom_builder
|
Fixed problem in dom_builder
|
Lua
|
mit
|
pakozm/IPyLua,pakozm/IPyLua
|
69e4b20e8c641d5e90029dbef68db92119143599
|
vrp/modules/hidden_transformer.lua
|
vrp/modules/hidden_transformer.lua
|
local lang = vRP.lang
local HiddenTransformer = class("HiddenTransformer", vRP.Extension)
-- PRIVATE METHODS
-- menu: hidden transformer informer
local function menu_informer(self)
local function m_buy(menu, id)
local user = menu.user
local itemtr = vRP.EXT.ItemTransformer.transformers["vRP:cfg_hidden:"..id]
local price = self.cfg.informer.infos[id]
if itemtr then
if user:tryPayment(price) then
vRP.EXT.Map.remote._setGPS(user.source, itemtr.cfg.x, itemtr.cfg.y) -- set gps marker
vRP.EXT.Base.remote._notify(user.source, lang.money.paid({price}))
vRP.EXT.Base.remote._notify(user.source, lang.itemtr.informer.bought())
else
vRP.EXT.Base.remote._notify(user.source, lang.money.not_enough())
end
end
end
vRP.EXT.GUI:registerMenuBuilder("hidden_transformer_informer", function(menu)
menu.title = lang.itemtr.informer.title()
menu.css.header_color = "rgba(0,255,125,0.75)"
-- add infos
for id,price in pairs(self.cfg.informer.infos) do
menu:addOption(id, m_buy, lang.itemtr.informer.description({price}), id)
end
end)
end
local function bind_informer(self, user)
if self.informer then
local x,y,z = table.unpack(self.informer)
-- add informer blip/marker/area
vRP.EXT.Map.remote._setNamedBlip(user.source,"vRP:informer",x,y,z,self.cfg.informer.blipid,self.cfg.informer.blipcolor,lang.itemtr.informer.title())
vRP.EXT.Map.remote._setNamedMarker(user.source,"vRP:informer",x,y,z-1,0.7,0.7,0.5,0,255,125,125,150)
user:setArea("vRP:informer",x,y,z,1,1.5,enter,leave)
end
end
-- METHODS
function HiddenTransformer:__construct()
vRP.Extension.__construct(self)
self.cfg = module("vrp", "cfg/hidden_transformers")
-- task: hidden placement
local function hidden_placement_task()
SetTimeout(300000, hidden_placement_task)
local sdata = vRP:getSData("vRP:hidden_transformers")
local hidden_transformers = {}
if sdata and string.len(sdata) > 0 then
hidden_transformers = msgpack.unpack(sdata)
end
for id, cfg_htr in pairs(self.cfg.hidden_transformers) do
-- init entry
local htr = hidden_transformers[id]
if not htr then
htr = {timestamp=os.time(), position=cfg_htr.positions[math.random(1,#cfg_htr.positions)]}
hidden_transformers[id] = htr
end
-- remove hidden transformer if needs respawn
if os.time()-htr.timestamp >= self.cfg.hidden_transformer_duration*60 then
htr.timestamp = os.time()
vRP.EXT.ItemTransformer:remove("vRP:cfg_hidden:"..id)
-- generate new position
htr.position = cfg_htr.positions[math.random(1, #cfg_htr.positions)]
end
-- spawn if unspawned
if not vRP.EXT.ItemTransformer.transformers["vRP:cfg_hidden:"..id] then
cfg_htr.def.x = htr.position[1]
cfg_htr.def.y = htr.position[2]
cfg_htr.def.z = htr.position[3]
vRP.EXT.ItemTransformer:set("vRP:cfg_hidden:"..id, cfg_htr.def)
end
end
vRP:setSData("vRP:hidden_transformers", msgpack.pack(hidden_transformers)) -- save hidden transformers
end
async(function()
hidden_placement_task()
end)
local function informer_placement_task()
SetTimeout(self.cfg.informer.interval*60000, informer_placement_task)
-- spawn informer
self:spawnInformer()
-- despawn informer after a while
SetTimeout(self.cfg.informer.duration*60000, function()
self:despawnInformer()
end)
end
SetTimeout(self.cfg.informer.interval*60000,informer_placement_task)
end
function HiddenTransformer:spawnInformer()
self:despawnInformer()
-- informer pos
self.informer = self.cfg.informer.positions[math.random(1, #self.cfg.informer.positions)]
for id, user in pairs(vRP.users) do
bind_informer(self, user)
end
end
function HiddenTransformer:despawnInformer()
if self.informer then
for id,user in pairs(vRP.users) do -- remove informer data for all users
vRP.EXT.Map.remote._removeNamedBlip(user.source,"vRP:informer")
vRP.EXT.Map.remote._removeNamedMarker(user.source,"vRP:informer")
user:removeArea("vRP:informer")
end
self.informer = nil
end
end
-- EVENT
HiddenTransformer.event = {}
function HiddenTransformer.event:playerSpawn(user, first_spawn)
if first_spawn then
bind_informer(self, user)
end
end
vRP:registerExtension(HiddenTransformer)
|
local lang = vRP.lang
local HiddenTransformer = class("HiddenTransformer", vRP.Extension)
-- PRIVATE METHODS
-- menu: hidden transformer informer
local function menu_informer(self)
local function m_buy(menu, id)
local user = menu.user
local itemtr = vRP.EXT.ItemTransformer.transformers["vRP:cfg_hidden:"..id]
local price = self.cfg.informer.infos[id]
if itemtr then
if user:tryPayment(price) then
vRP.EXT.Map.remote._setGPS(user.source, itemtr.cfg.x, itemtr.cfg.y) -- set gps marker
vRP.EXT.Base.remote._notify(user.source, lang.money.paid({price}))
vRP.EXT.Base.remote._notify(user.source, lang.itemtr.informer.bought())
else
vRP.EXT.Base.remote._notify(user.source, lang.money.not_enough())
end
end
end
vRP.EXT.GUI:registerMenuBuilder("hidden_transformer_informer", function(menu)
menu.title = lang.itemtr.informer.title()
menu.css.header_color = "rgba(0,255,125,0.75)"
-- add infos
for id,price in pairs(self.cfg.informer.infos) do
menu:addOption(id, m_buy, lang.itemtr.informer.description({price}), id)
end
end)
end
local function bind_informer(self, user)
if self.informer then
local x,y,z = table.unpack(self.informer)
local menu
local function enter(user)
menu = user:openMenu("hidden_transformer_informer")
end
local function leave(user)
if menu then
user:closeMenu(menu)
end
end
-- add informer blip/marker/area
vRP.EXT.Map.remote._setNamedBlip(user.source,"vRP:informer",x,y,z,self.cfg.informer.blipid,self.cfg.informer.blipcolor,lang.itemtr.informer.title())
vRP.EXT.Map.remote._setNamedMarker(user.source,"vRP:informer",x,y,z-1,0.7,0.7,0.5,0,255,125,125,150)
user:setArea("vRP:informer",x,y,z,1,1.5,enter,leave)
end
end
-- METHODS
function HiddenTransformer:__construct()
vRP.Extension.__construct(self)
self.cfg = module("vrp", "cfg/hidden_transformers")
-- task: hidden placement
local function hidden_placement_task()
SetTimeout(300000, hidden_placement_task)
local sdata = vRP:getSData("vRP:hidden_transformers")
local hidden_transformers = {}
if sdata and string.len(sdata) > 0 then
hidden_transformers = msgpack.unpack(sdata)
end
for id, cfg_htr in pairs(self.cfg.hidden_transformers) do
-- init entry
local htr = hidden_transformers[id]
if not htr then
htr = {timestamp=os.time(), position=cfg_htr.positions[math.random(1,#cfg_htr.positions)]}
hidden_transformers[id] = htr
end
-- remove hidden transformer if needs respawn
if os.time()-htr.timestamp >= self.cfg.hidden_transformer_duration*60 then
htr.timestamp = os.time()
vRP.EXT.ItemTransformer:remove("vRP:cfg_hidden:"..id)
-- generate new position
htr.position = cfg_htr.positions[math.random(1, #cfg_htr.positions)]
end
-- spawn if unspawned
if not vRP.EXT.ItemTransformer.transformers["vRP:cfg_hidden:"..id] then
cfg_htr.def.x = htr.position[1]
cfg_htr.def.y = htr.position[2]
cfg_htr.def.z = htr.position[3]
vRP.EXT.ItemTransformer:set("vRP:cfg_hidden:"..id, cfg_htr.def)
end
end
vRP:setSData("vRP:hidden_transformers", msgpack.pack(hidden_transformers)) -- save hidden transformers
end
async(function()
hidden_placement_task()
end)
local function informer_placement_task()
SetTimeout(self.cfg.informer.interval*60000, informer_placement_task)
-- spawn informer
self:spawnInformer()
-- despawn informer after a while
SetTimeout(self.cfg.informer.duration*60000, function()
self:despawnInformer()
end)
end
SetTimeout(self.cfg.informer.interval*60000,informer_placement_task)
end
function HiddenTransformer:spawnInformer()
self:despawnInformer()
-- informer pos
self.informer = self.cfg.informer.positions[math.random(1, #self.cfg.informer.positions)]
for id, user in pairs(vRP.users) do
bind_informer(self, user)
end
end
function HiddenTransformer:despawnInformer()
if self.informer then
for id,user in pairs(vRP.users) do -- remove informer data for all users
vRP.EXT.Map.remote._removeNamedBlip(user.source,"vRP:informer")
vRP.EXT.Map.remote._removeNamedMarker(user.source,"vRP:informer")
user:removeArea("vRP:informer")
end
self.informer = nil
end
end
-- EVENT
HiddenTransformer.event = {}
function HiddenTransformer.event:playerSpawn(user, first_spawn)
if first_spawn then
bind_informer(self, user)
end
end
vRP:registerExtension(HiddenTransformer)
|
Fix missing informer menu.
|
Fix missing informer menu.
|
Lua
|
mit
|
ImagicTheCat/vRP,ImagicTheCat/vRP
|
1ab9775adf3d5dd947b6f7f70a4df7e2704c037b
|
mock/gfx/MSpriteCopy.lua
|
mock/gfx/MSpriteCopy.lua
|
module 'mock'
CLASS: MSpriteCopy ( mock.GraphicsPropComponent )
:MODEL{
Field 'sourceSprite' :type( MSprite ) :set( 'setSourceSprite');
Field 'overrideFeatures' :boolean();
Field 'hiddenFeatures' :collection( 'string' ) :selection( 'getAvailFeatures' ) :getset( 'HiddenFeatures' );
-- Field 'copyScl' :boolean();
-- Field 'copyRot' :boolean();
-- Field 'copyLoc' :boolean();
-- Field 'flipX' :boolean() :onset( 'updateFlip' );
-- Field 'flipY' :boolean() :onset( 'updateFlip' );
}
registerComponent( 'MSpriteCopy', MSpriteCopy )
function MSpriteCopy:__init()
self.sourceSprite = false
self.flipX = false
self.flipY = false
self.overrideFeatures = false
self.deckInstance = MOAIGfxMaskedQuadListDeck2DInstance.new()
self.prop:setDeck( self.deckInstance )
end
function MSpriteCopy:onAttach( ent )
MSpriteCopy.__super.onAttach( self, ent )
self:setSourceSprite( self.sourceSprite )
end
function MSpriteCopy:setSourceSprite( sprite )
if self.sourceSprite == sprite then return end
self.sourceSprite = sprite
if not sprite then return end
local spriteData = sprite.spriteData
if not spriteData then return end
self.deckInstance:setSource( spriteData.frameDeck )
self.prop:setAttrLink( MOAIProp.ATTR_INDEX, sprite.prop, MOAIProp.ATTR_INDEX )
linkTransform( self.prop, sprite.prop )
self:updateFeatures()
end
function MSpriteCopy:getTargetData()
local source = self.sourceSprite
return source and source.spriteData
end
function MSpriteCopy:setHiddenFeatures( hiddenFeatures )
self.hiddenFeatures = hiddenFeatures or {}
--update hiddenFeatures
if self.sourceSprite then return self:updateFeatures() end
end
function MSpriteCopy:getHiddenFeatures()
return self.hiddenFeatures
end
function MSpriteCopy:updateFeatures()
local sprite = self.sourceSprite
if not sprite then return end
local data = sprite.spriteData
if not data then return end
local features = sprite.hiddenFeatures
if self.overrideFeatures then
features = self.hiddenFeatures
end
if not self.deckInstance then return end
local featureTable = data.features
if not featureTable then return end
local instance = self.deckInstance
for i = 0, 64 do --hide all
instance:setMask( i, false )
end
for i, featureName in ipairs( features ) do
local bit
if featureName == '__base__' then
bit = 0
else
bit = featureTable[ featureName ]
end
if bit then
instance:setMask( bit, true ) --show target feature
end
end
end
function MSpriteCopy:getAvailFeatures()
local result = {
{ '__base__', '__base__' }
}
local data = self:getTargetData()
if data then
for i, n in ipairs( data.featureNames ) do
result[ i+1 ] = { n, n }
end
end
return result
end
|
module 'mock'
CLASS: MSpriteCopy ( mock.GraphicsPropComponent )
:MODEL{
Field 'sourceSprite' :type( MSprite ) :set( 'setSourceSprite');
Field 'overrideFeatures' :boolean();
Field 'hiddenFeatures' :collection( 'string' ) :selection( 'getAvailFeatures' ) :getset( 'HiddenFeatures' );
-- Field 'copyScl' :boolean();
-- Field 'copyRot' :boolean();
-- Field 'copyLoc' :boolean();
-- Field 'flipX' :boolean() :onset( 'updateFlip' );
-- Field 'flipY' :boolean() :onset( 'updateFlip' );
}
registerComponent( 'MSpriteCopy', MSpriteCopy )
function MSpriteCopy:__init()
self.sourceSprite = false
self.linked = false
self.flipX = false
self.flipY = false
self.overrideFeatures = false
self.deckInstance = MOAIGfxMaskedQuadListDeck2DInstance.new()
self.prop:setDeck( self.deckInstance )
end
function MSpriteCopy:onAttach( ent )
MSpriteCopy.__super.onAttach( self, ent )
self:setSourceSprite( self.sourceSprite )
end
function MSpriteCopy:setSourceSprite( sprite )
self.sourceSprite = sprite
if not sprite then return end
local spriteData = sprite.spriteData
if not spriteData then return end
if self.sourceSprite == sprite and self.linked then return end
self.deckInstance:setSource( spriteData.frameDeck )
self.prop:setAttrLink( MOAIProp.ATTR_INDEX, sprite.prop, MOAIProp.ATTR_INDEX )
linkTransform( self.prop, sprite.prop )
self:updateFeatures()
self.linked = true
end
function MSpriteCopy:getTargetData()
local source = self.sourceSprite
return source and source.spriteData
end
function MSpriteCopy:setHiddenFeatures( hiddenFeatures )
self.hiddenFeatures = hiddenFeatures or {}
--update hiddenFeatures
if self.sourceSprite then return self:updateFeatures() end
end
function MSpriteCopy:getHiddenFeatures()
return self.hiddenFeatures
end
function MSpriteCopy:updateFeatures()
local sprite = self.sourceSprite
if not sprite then return end
local data = sprite.spriteData
if not data then return end
local features = sprite.hiddenFeatures
if self.overrideFeatures then
features = self.hiddenFeatures
end
if not self.deckInstance then return end
local featureTable = data.features
if not featureTable then return end
local instance = self.deckInstance
for i = 0, 64 do --hide all
instance:setMask( i, false )
end
for i, featureName in ipairs( features ) do
local bit
if featureName == '__base__' then
bit = 0
else
bit = featureTable[ featureName ]
end
if bit then
instance:setMask( bit, true ) --show target feature
end
end
end
function MSpriteCopy:getAvailFeatures()
local result = {
{ '__base__', '__base__' }
}
local data = self:getTargetData()
if data then
for i, n in ipairs( data.featureNames ) do
result[ i+1 ] = { n, n }
end
end
return result
end
|
fix MSpriteCopy
|
fix MSpriteCopy
|
Lua
|
mit
|
tommo/mock
|
79516cf0059ca8e1e0859e8f1beee34bfb5a57ee
|
mod_webpresence/mod_webpresence.lua
|
mod_webpresence/mod_webpresence.lua
|
module:depends("http");
local jid_split = require "util.jid".prepped_split;
local b64 = require "util.encodings".base64.encode;
local sha1 = require "util.hashes".sha1;
local stanza = require "util.stanza".stanza;
local json = require "util.json".encode_ordered;
local function require_resource(name)
local icon_path = module:get_option_string("presence_icons", "icons");
local f, err = module:load_resource(icon_path.."/"..name);
if f then
return f:read("*a");
end
module:log("warn", "Failed to open image file %s", icon_path..name);
return "";
end
local statuses = { online = {}, away = {}, xa = {}, dnd = {}, chat = {}, offline = {} };
local function handle_request(event, path)
local status, message;
local jid, type = path:match("([^/]+)/?(.*)$");
if jid then
local user, host = jid_split(jid);
if host and not user then
user, host = host, event.request.headers.host;
if host then host = host:gsub(":%d+$", ""); end
end
if user and host then
local user_sessions = hosts[host] and hosts[host].sessions[user];
if user_sessions then
status = user_sessions.top_resources[1];
if status and status.presence then
message = status.presence:child_with_name("status");
status = status.presence:child_with_name("show");
if not status then
status = "online";
else
status = status:get_text();
end
if message then
message = message:get_text();
end
end
end
end
end
status = status or "offline";
if type == "" then type = "image" end;
statuses[status].image = function()
return { status_code = 200, headers = { content_type = "image/png" },
body = require_resource("status_"..status..".png")
};
end;
statuses[status].html = function()
local jid_hash = sha1(jid, true);
return { status_code = 200, headers = { content_type = "text/html" },
body = [[<!DOCTYPE html>]]..
tostring(
stanza("html")
:tag("head")
:tag("title"):text("XMPP Status Page for "..jid):up():up()
:tag("body")
:tag("div", { id = jid_hash.."_status", class = "xmpp_status" })
:tag("img", { id = jid_hash.."_img", class = "xmpp_status_image xmpp_status_"..status,
src = "data:image/png;base64,"..b64(require_resource("status_"..status..".png")) }):up()
:tag("span", { id = jid_hash.."_status_name", class = "xmpp_status_name" })
:text("\194\160"..status):up()
:tag("span", { id = jid_hash.."_status_message", class = "xmpp_status_message" })
:text(message and "\194\160"..message.."" or "")
)
};
end;
statuses[status].text = function()
return { status_code = 200, headers = { content_type = "text/plain" },
body = status
};
end;
statuses[status].message = function()
return { status_code = 200, headers = { content_type = "text/plain" },
body = (message and message or "")
};
end;
statuses[status].json = function()
return { status_code = 200, headers = { content_type = "application/json" },
body = json({
jid = jid,
show = status,
status = (message and message or "null")
})
};
end;
statuses[status].xml = function()
return { status_code = 200, headers = { content_type = "application/xml" },
body = [[<?xml version="1.0" encoding="utf-8"?>]]..
tostring(
stanza("result")
:tag("jid"):text(jid):up()
:tag("show"):text(status):up()
:tag("status"):text(message)
)
};
end
return statuses[status][type]();
end
module:provides("http", {
default_path = "/status";
route = {
["GET /*"] = handle_request;
};
});
|
module:depends("http");
local jid_split = require "util.jid".prepped_split;
local b64 = require "util.encodings".base64.encode;
local sha1 = require "util.hashes".sha1;
local stanza = require "util.stanza".stanza;
local json = require "util.json".encode_ordered;
local function require_resource(name)
local icon_path = module:get_option_string("presence_icons", "icons");
local f, err = module:load_resource(icon_path.."/"..name);
if f then
return f:read("*a");
end
module:log("warn", "Failed to open image file %s", icon_path..name);
return "";
end
local statuses = { online = {}, away = {}, xa = {}, dnd = {}, chat = {}, offline = {} };
local function handle_request(event, path)
local status, message;
local jid, type = path:match("([^/]+)/?(.*)$");
if jid then
local user, host = jid_split(jid);
if host and not user then
user, host = host, event.request.headers.host;
if host then host = host:gsub(":%d+$", ""); end
end
if user and host then
local user_sessions = hosts[host] and hosts[host].sessions[user];
if user_sessions then
status = user_sessions.top_resources[1];
if status and status.presence then
message = status.presence:child_with_name("status");
status = status.presence:child_with_name("show");
if not status then
status = "online";
else
status = status:get_text();
end
if message then
message = message:get_text();
end
end
end
end
end
status = status or "offline";
statuses[status].image = function()
return { status_code = 200, headers = { content_type = "image/png" },
body = require_resource("status_"..status..".png")
};
end;
statuses[status].html = function()
local jid_hash = sha1(jid, true);
return { status_code = 200, headers = { content_type = "text/html" },
body = [[<!DOCTYPE html>]]..
tostring(
stanza("html")
:tag("head")
:tag("title"):text("XMPP Status Page for "..jid):up():up()
:tag("body")
:tag("div", { id = jid_hash.."_status", class = "xmpp_status" })
:tag("img", { id = jid_hash.."_img", class = "xmpp_status_image xmpp_status_"..status,
src = "data:image/png;base64,"..b64(require_resource("status_"..status..".png")) }):up()
:tag("span", { id = jid_hash.."_status_name", class = "xmpp_status_name" })
:text("\194\160"..status):up()
:tag("span", { id = jid_hash.."_status_message", class = "xmpp_status_message" })
:text(message and "\194\160"..message.."" or "")
)
};
end;
statuses[status].text = function()
return { status_code = 200, headers = { content_type = "text/plain" },
body = status
};
end;
statuses[status].message = function()
return { status_code = 200, headers = { content_type = "text/plain" },
body = (message and message or "")
};
end;
statuses[status].json = function()
return { status_code = 200, headers = { content_type = "application/json" },
body = json({
jid = jid,
show = status,
status = (message and message or "null")
})
};
end;
statuses[status].xml = function()
return { status_code = 200, headers = { content_type = "application/xml" },
body = [[<?xml version="1.0" encoding="utf-8"?>]]..
tostring(
stanza("result")
:tag("jid"):text(jid):up()
:tag("show"):text(status):up()
:tag("status"):text(message)
)
};
end
if ((type == "") or (not statuses[status][type])) then
type = "image"
end;
return statuses[status][type]();
end
module:provides("http", {
default_path = "/status";
route = {
["GET /*"] = handle_request;
};
});
|
mod_webpresence: fixed render-type handling (thanks to biszkopcik and Zash)
|
mod_webpresence: fixed render-type handling (thanks to biszkopcik and Zash)
|
Lua
|
mit
|
LanceJenkinZA/prosody-modules,Craige/prosody-modules,amenophis1er/prosody-modules,guilhem/prosody-modules,mmusial/prosody-modules,prosody-modules/import,Craige/prosody-modules,asdofindia/prosody-modules,joewalker/prosody-modules,olax/prosody-modules,vince06fr/prosody-modules,prosody-modules/import,guilhem/prosody-modules,cryptotoad/prosody-modules,LanceJenkinZA/prosody-modules,mardraze/prosody-modules,iamliqiang/prosody-modules,heysion/prosody-modules,softer/prosody-modules,vfedoroff/prosody-modules,softer/prosody-modules,apung/prosody-modules,mardraze/prosody-modules,mmusial/prosody-modules,vfedoroff/prosody-modules,brahmi2/prosody-modules,1st8/prosody-modules,syntafin/prosody-modules,either1/prosody-modules,prosody-modules/import,mardraze/prosody-modules,prosody-modules/import,heysion/prosody-modules,apung/prosody-modules,olax/prosody-modules,1st8/prosody-modules,asdofindia/prosody-modules,BurmistrovJ/prosody-modules,BurmistrovJ/prosody-modules,amenophis1er/prosody-modules,apung/prosody-modules,apung/prosody-modules,BurmistrovJ/prosody-modules,asdofindia/prosody-modules,obelisk21/prosody-modules,syntafin/prosody-modules,dhotson/prosody-modules,brahmi2/prosody-modules,guilhem/prosody-modules,joewalker/prosody-modules,stephen322/prosody-modules,amenophis1er/prosody-modules,cryptotoad/prosody-modules,joewalker/prosody-modules,amenophis1er/prosody-modules,softer/prosody-modules,mardraze/prosody-modules,mardraze/prosody-modules,syntafin/prosody-modules,softer/prosody-modules,stephen322/prosody-modules,brahmi2/prosody-modules,joewalker/prosody-modules,iamliqiang/prosody-modules,drdownload/prosody-modules,vince06fr/prosody-modules,vfedoroff/prosody-modules,NSAKEY/prosody-modules,jkprg/prosody-modules,heysion/prosody-modules,BurmistrovJ/prosody-modules,NSAKEY/prosody-modules,jkprg/prosody-modules,Craige/prosody-modules,guilhem/prosody-modules,either1/prosody-modules,crunchuser/prosody-modules,joewalker/prosody-modules,stephen322/prosody-modules,vfedoroff/prosody-modules,crunchuser/prosody-modules,obelisk21/prosody-modules,drdownload/prosody-modules,LanceJenkinZA/prosody-modules,BurmistrovJ/prosody-modules,olax/prosody-modules,stephen322/prosody-modules,iamliqiang/prosody-modules,dhotson/prosody-modules,apung/prosody-modules,vince06fr/prosody-modules,crunchuser/prosody-modules,dhotson/prosody-modules,guilhem/prosody-modules,asdofindia/prosody-modules,NSAKEY/prosody-modules,obelisk21/prosody-modules,cryptotoad/prosody-modules,NSAKEY/prosody-modules,jkprg/prosody-modules,either1/prosody-modules,vince06fr/prosody-modules,cryptotoad/prosody-modules,heysion/prosody-modules,brahmi2/prosody-modules,LanceJenkinZA/prosody-modules,jkprg/prosody-modules,obelisk21/prosody-modules,dhotson/prosody-modules,drdownload/prosody-modules,either1/prosody-modules,crunchuser/prosody-modules,dhotson/prosody-modules,NSAKEY/prosody-modules,1st8/prosody-modules,iamliqiang/prosody-modules,either1/prosody-modules,olax/prosody-modules,heysion/prosody-modules,mmusial/prosody-modules,iamliqiang/prosody-modules,vince06fr/prosody-modules,mmusial/prosody-modules,asdofindia/prosody-modules,drdownload/prosody-modules,amenophis1er/prosody-modules,crunchuser/prosody-modules,jkprg/prosody-modules,LanceJenkinZA/prosody-modules,prosody-modules/import,Craige/prosody-modules,olax/prosody-modules,drdownload/prosody-modules,1st8/prosody-modules,Craige/prosody-modules,vfedoroff/prosody-modules,stephen322/prosody-modules,cryptotoad/prosody-modules,syntafin/prosody-modules,obelisk21/prosody-modules,syntafin/prosody-modules,brahmi2/prosody-modules,softer/prosody-modules,mmusial/prosody-modules,1st8/prosody-modules
|
c0715a901bac3843fe5682353f7c572041ba562b
|
Modules/Utility/os.lua
|
Modules/Utility/os.lua
|
-- to use: local os = require(this_script)
-- Adds an os.date() function back to the Roblox os table!
-- @author Narrev
-- Abbreviated tables have been left in for now. Could be replaced with dayNames[wday + 1]:sub(1,3)
-- local timeZone = math.ceil( os.difftime(os.time(), tick()) / 3600)
-- timeZoneDiff = os.date("*t", os.time()).hour - os.date("*t").hour
local firstRequired = os.time()
return {
help = function(...) return
[[Note: Padding can be turned off by putting a '_' between '%' and the letter toggles padding
os.date("*t") returns a table with the following indices:
hour 14
min 36
wday 1
year 2003
yday 124
month 5
sec 33
day 4
String reference:
%a abbreviated weekday name (e.g., Wed)
%A full weekday name (e.g., Wednesday)
%b abbreviated month name (e.g., Sep)
%B full month name (e.g., September)
%c date and time (e.g., 09/16/98 23:48:10)
%d day of the month (16) [01-31]
%H hour, using a 24-hour clock (23) [00-23]
%I hour, using a 12-hour clock (11) [01-12]
%j day of year [01-365]
%M minute (48) [00-59]
%m month (09) [01-12]
%n New-line character ('\n')
%p either "am" or "pm" ('_' makes it uppercase)
%r 12-hour clock time * 02:55:02 pm
%R 24-hour HH:MM time, equivalent to %H:%M 14:55
%S second (10) [00-61]
%t Horizontal-tab character ('\t')
%T Basically %r but without seconds (HH:MM AM), equivalent to %I:%M %p 2:55 pm
%u ISO 8601 weekday as number with Monday as 1 (1-7) 4
%w weekday (3) [0-6 = Sunday-Saturday]
%x date (e.g., 09/16/98)
%X time (e.g., 23:48:10)
%Y full year (1998)
%y two-digit year (98) [00-99]
%% the character `%´]]
end;
date = function(optString, unix)
-- Precise!
local stringPassed = false
if not (optString == nil and unix == nil) then
if type(optString) == "string" then
if optString:find("*t") then
unix = optString:find("^!") and os.time() or unix
else
assert(optString:find("%%"), "Invalid string passed to os.date")
optString, unix = optString:find("^!") and optString:sub(2) or optString, optString:find("^!") and os.time() or unix
stringPassed = true
end
end
if type(optString) == "number" or optString:match("/Date%((%d+)") or optString:match("%d+\-%d+\-%d+T%d+:%d+:[%d%.]+.+") then
unix, optString = optString
end
if type(unix) == "string" then
if unix:match("/Date%((%d+)") then -- This is for a certain JSON compatibility. It works the same even if you don't need it
unix = unix:match("/Date%((%d+)") / 1000
elseif unix:match("%d+\-%d+\-%d+T%d+:%d+:[%d%.]+.+") then -- Untested MarketPlaceService compatibility
-- This part of the script is untested
local year, month, day, hour, minute, second = unix:match("(%d+)\-(%d+)\-(%d+)T(%d+):(%d+):([%d%.]+).+")
unix = os.time{year = year, month = month, day = day, hour = hour, minute = minute, second = second}
end
end
end
local unix = type(unix) == "number" and unix or tick()
local dayCount = function(yr) return (yr % 4 == 0 and (yr % 100 ~= 0 or yr % 400 == 0)) and 366 or 365 end
local year = 1970
local days = math.ceil(unix / 86400)
local wday = math.floor( (days + 3) % 7 ) -- Jan 1, 1970 was a thursday, so we add 3
local dayNames = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
local dayNamesAbbr = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}
local monthsAbbr = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}
local months, month = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
local suffixes = {"st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "st"}
local hours = math.floor(unix / 3600 % 24)
local minutes = math.floor(unix / 60 % 60)
local seconds = math.floor(unix % 60)
-- Calculate year and days into that year
while days > dayCount(year) do days = days - dayCount(year) year = year + 1 end
local yDay = days
-- Subtract amount of days from each month until we find what month we are in and what day in that month
for monthIndex, daysInMonth in ipairs{31,(dayCount(year) - 337),31,30,31,30,31,31,30,31,30,31} do
if days - daysInMonth <= 0 then
month = monthIndex
break
end
days = days - daysInMonth
end
-- string.format("%d/%d/%04d", month, days, year) same as "%x"
-- string.format("%02d:%02d:%02d %s", hours, minutes, seconds, period) same as "%r"
padded = function(num)
return string.format("%02d", num)
end
if optString == "*t" then
return {year = year, month = month, day = days, yday = yDay, wday = wday, hour = hours, min = minutes, sec = seconds}
elseif stringPassed then
local returner = optString
:gsub("%%c", "%%x %%X")
:gsub("%%_c", "%%_x %%_X")
:gsub("%%x", "%%m/%%d/%%y")
:gsub("%%_x", "%%_m/%%_d/%%y")
:gsub("%%X", "%%H:%%M:%%S")
:gsub("%%_X", "%%_H:%%M:%%S")
:gsub("%%T", "%%I:%%M %%p")
:gsub("%%_T", "%%_I:%%M %%p")
:gsub("%%r", "%%I:%%M:%%S %%p")
:gsub("%%_r", "%%_I:%%M:%%S %%p")
:gsub("%%R", "%%H:%%M")
:gsub("%%_R", "%%_H:%%M")
:gsub("%%a", dayNamesAbbr[wday + 1])
:gsub("%%A", dayNames[wday + 1])
:gsub("%%b", monthsAbbr[month])
:gsub("%%B", months[month])
:gsub("%%d", padded(days))
:gsub("%%_d", days)
:gsub("%%H", padded(hours))
:gsub("%%_H", hours)
:gsub("%%I", padded(hours > 12 and hours - 12 or hours == 0 and 12 or hours))
:gsub("%%_I", hours > 12 and hours - 12 or hours == 0 and 12 or hours)
:gsub("%%j", padded(yDay))
:gsub("%%_j", yDay)
:gsub("%%M", padded(minutes))
:gsub("%%_M", minutes)
:gsub("%%m", padded(month))
:gsub("%%_m", month)
:gsub("%%n","\n")
:gsub("%%p", hours >= 12 and "pm" or "am")
:gsub("%%_p", hours >= 12 and "PM" or "AM")
:gsub("%%S", padded(seconds))
:gsub("%%_S", seconds)
:gsub("%%t", "\t")
:gsub("%%u", wday == 0 and 7 or wday)
:gsub("%%w", wday)
:gsub("%%Y", year)
:gsub("%%y", padded(year % 100))
:gsub("%%_y", year % 100)
:gsub("%%%%", "%%")
return returner -- We declare returner and then return it because we don't want to return the second value of the last gsub function
end
return {year = year, month = month, day = days, yday = yDay, wday = wday, hour = hours, min = minutes, sec = seconds}
end;
time = function(...) return os.time(...) end;
difftime = function(...) return os.difftime(...) end;
clock = function(...) return os.difftime(os.time(), firstRequired) end;
}
|
-- to use: local os = require(this_script)
-- Adds an os.date() function back to the Roblox os table!
-- @author Narrev
-- Abbreviated tables have been left in for now. Could be replaced with dayNames[wday + 1]:sub(1,3)
-- local timeZone = math.ceil( os.difftime(os.time(), tick()) / 3600)
-- timeZoneDiff = os.date("*t", os.time()).hour - os.date("*t").hour
local firstRequired = os.time()
return {
help = function(...) return
[[Note: Padding can be turned off by putting a '_' between '%' and the letter toggles padding
os.date("*t") returns a table with the following indices:
hour 14
min 36
wday 1
year 2003
yday 124
month 5
sec 33
day 4
String reference:
%a abbreviated weekday name (e.g., Wed)
%A full weekday name (e.g., Wednesday)
%b abbreviated month name (e.g., Sep)
%B full month name (e.g., September)
%c date and time (e.g., 09/16/98 23:48:10)
%d day of the month (16) [01-31]
%H hour, using a 24-hour clock (23) [00-23]
%I hour, using a 12-hour clock (11) [01-12]
%j day of year [01-365]
%M minute (48) [00-59]
%m month (09) [01-12]
%n New-line character ('\n')
%p either "am" or "pm" ('_' makes it uppercase)
%r 12-hour clock time * 02:55:02 pm
%R 24-hour HH:MM time, equivalent to %H:%M 14:55
%S second (10) [00-61]
%t Horizontal-tab character ('\t')
%T Basically %r but without seconds (HH:MM AM), equivalent to %I:%M %p 2:55 pm
%u ISO 8601 weekday as number with Monday as 1 (1-7) 4
%w weekday (3) [0-6 = Sunday-Saturday]
%x date (e.g., 09/16/98)
%X time (e.g., 23:48:10)
%Y full year (1998)
%y two-digit year (98) [00-99]
%% the character `%´]]
end;
date = function(optString, unix)
local stringPassed = false
if not (optString == nil and unix == nil) then
if type(optString) == "number" or optString:match("/Date%((%d+)") or optString:match("%d+\-%d+\-%d+T%d+:%d+:[%d%.]+.+") then
-- if they didn't pass a non unix time
unix, optString = optString
elseif type(optString) == "string" then
assert(optString:find("*t") or optString:find("%%"), "Invalid string passed to os.date")
unix, optString = optString:find("^!") and os.time() or unix, optString:find("^!") and optString:sub(2) or optString
stringPassed = true
end
if type(unix) == "string" then
if unix:match("/Date%((%d+)") then -- This is for a certain JSON compatibility. It works the same even if you don't need it
unix = unix:match("/Date%((%d+)") / 1000
elseif unix:match("%d+\-%d+\-%d+T%d+:%d+:[%d%.]+.+") then -- Untested MarketPlaceService compatibility
-- This part of the script is untested
local year, month, day, hour, minute, second = unix:match("(%d+)\-(%d+)\-(%d+)T(%d+):(%d+):([%d%.]+).+")
unix = os.time{year = year, month = month, day = day, hour = hour, minute = minute, second = second}
end
end
end
local unix = type(unix) == "number" and unix or tick()
local dayCount = function(yr) return (yr % 4 == 0 and (yr % 100 ~= 0 or yr % 400 == 0)) and 366 or 365 end
local year = 1970
local days = math.ceil(unix / 86400)
local wday = math.floor( (days + 3) % 7 ) -- Jan 1, 1970 was a thursday, so we add 3
local dayNames = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
local dayNamesAbbr = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}
local monthsAbbr = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}
local months, month = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
local suffixes = {"st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "st"}
local hours = math.floor(unix / 3600 % 24)
local minutes = math.floor(unix / 60 % 60)
local seconds = math.floor(unix % 60)
-- Calculate year and days into that year
while days > dayCount(year) do days = days - dayCount(year) year = year + 1 end
local yDay = days
-- Subtract amount of days from each month until we find what month we are in and what day in that month
for monthIndex, daysInMonth in ipairs{31,(dayCount(year) - 337),31,30,31,30,31,31,30,31,30,31} do
if days - daysInMonth <= 0 then
month = monthIndex
break
end
days = days - daysInMonth
end
-- string.format("%d/%d/%04d", month, days, year) same as "%x"
-- string.format("%02d:%02d:%02d %s", hours, minutes, seconds, period) same as "%r"
padded = function(num)
return string.format("%02d", num)
end
if stringPassed then
local returner = optString
:gsub("%%c", "%%x %%X")
:gsub("%%_c", "%%_x %%_X")
:gsub("%%x", "%%m/%%d/%%y")
:gsub("%%_x", "%%_m/%%_d/%%y")
:gsub("%%X", "%%H:%%M:%%S")
:gsub("%%_X", "%%_H:%%M:%%S")
:gsub("%%T", "%%I:%%M %%p")
:gsub("%%_T", "%%_I:%%M %%p")
:gsub("%%r", "%%I:%%M:%%S %%p")
:gsub("%%_r", "%%_I:%%M:%%S %%p")
:gsub("%%R", "%%H:%%M")
:gsub("%%_R", "%%_H:%%M")
:gsub("%%a", dayNamesAbbr[wday + 1])
:gsub("%%A", dayNames[wday + 1])
:gsub("%%b", monthsAbbr[month])
:gsub("%%B", months[month])
:gsub("%%d", padded(days))
:gsub("%%_d", days)
:gsub("%%H", padded(hours))
:gsub("%%_H", hours)
:gsub("%%I", padded(hours > 12 and hours - 12 or hours == 0 and 12 or hours))
:gsub("%%_I", hours > 12 and hours - 12 or hours == 0 and 12 or hours)
:gsub("%%j", padded(yDay))
:gsub("%%_j", yDay)
:gsub("%%M", padded(minutes))
:gsub("%%_M", minutes)
:gsub("%%m", padded(month))
:gsub("%%_m", month)
:gsub("%%n","\n")
:gsub("%%p", hours >= 12 and "pm" or "am")
:gsub("%%_p", hours >= 12 and "PM" or "AM")
:gsub("%%S", padded(seconds))
:gsub("%%_S", seconds)
:gsub("%%t", "\t")
:gsub("%%u", wday == 0 and 7 or wday)
:gsub("%%w", wday)
:gsub("%%Y", year)
:gsub("%%y", padded(year % 100))
:gsub("%%_y", year % 100)
:gsub("%%%%", "%%")
return returner -- We declare returner and then return it because we don't want to return the second value of the last gsub function
end
return {year = year, month = month, day = days, yday = yDay, wday = wday, hour = hours, min = minutes, sec = seconds}
end;
time = function(...) return os.time(...) end;
difftime = function(...) return os.difftime(...) end;
clock = function(...) return os.difftime(os.time(), firstRequired) end;
}
|
Efficiency fixes
|
Efficiency fixes
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
8b89b1e55993bb8c9972afe61d159678ed303669
|
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[#newargs+1] = 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"})
|
nyagos.suffixes={}
local function _suffix(suffix,cmdline)
local suffix=string.lower(suffix)
if string.sub(suffix,1,1)=='.' then
suffix = string.sub(suffix,2)
end
if not nyagos.suffixes[suffix] then
local orgpathext = nyagos.getenv("PATHEXT")
local newext="."..suffix
if not string.find(";"..orgpathext..";",";"..newext..";",1,true) then
nyagos.setenv("PATHEXT",orgpathext..";"..newext)
end
end
nyagos.suffixes[suffix]=cmdline
end
suffix = setmetatable({},{
__call = function(t,k,v) _suffix(k,v) return end,
__newindex = function(t,k,v) _suffix(k,v) return end,
__index = function(t,k) return nyagos.suffixes[k] end
})
local org_filter=nyagos.argsfilter
nyagos.argsfilter = function(args)
if org_filter then
local args_ = org_filter(args)
if args_ then
args = args_
end
end
local path=nyagos.which(args[0])
if not path then
return
end
local m = string.match(path,"%.(%w+)$")
if not m then
return
end
local cmdline = nyagos.suffixes[ string.lower(m) ]
if not cmdline then
return
end
local newargs={}
if type(cmdline) == 'table' then
for i=1,#cmdline do
newargs[i-1]=cmdline[i]
end
elseif type(cmdline) == 'string' then
newargs[0] = cmdline
end
newargs[#newargs+1] = path
for i=1,#args do
newargs[#newargs+1] = args[i]
end
return newargs
end
nyagos.alias.suffix = function(args)
if #args < 2 then
print "Usage: suffix SUFFIX COMMAND"
else
local cmdline={}
for i=2,#args do
cmdline[#cmdline+1]=args[i]
end
suffix(args[1],cmdline)
end
end
suffix.pl="perl"
suffix.py="ipy"
suffix.rb="ruby"
suffix.lua="lua"
suffix.awk={"awk","-f"}
suffix.js={"cscript","//nologo"}
suffix.vbs={"cscript","//nologo"}
suffix.ps1={"powershell","-file"}
|
Change type of 'suffix' from function to virtual-table
|
Change type of 'suffix' from function to virtual-table
|
Lua
|
bsd-3-clause
|
nocd5/nyagos,kissthink/nyagos,kissthink/nyagos,hattya/nyagos,tsuyoshicho/nyagos,kissthink/nyagos,tyochiai/nyagos,hattya/nyagos,zetamatta/nyagos,hattya/nyagos
|
23ecf37a01cb3b0041b26b6ea9c12097fbca75df
|
luasrc/mch/router.lua
|
luasrc/mch/router.lua
|
#!/usr/bin/env lua
-- -*- lua -*-
-- Copyright 2012 Appwill Inc.
-- Author : KDr2
--
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
--
module('mch.router',package.seeall)
require 'mch.functional'
function map(route_table, uri, func_name)
local mod,fn = string.match(func_name,'^(.+)%.([^.]+)$')
mod=require(mod)
route_table[uri]=mod[fn]
end
function setup(app_name)
app_name='MOOCHINE_APP_' .. app_name
if not _G[app_name] then
_G[app_name]={}
end
local route_map={}
_G[app_name]['route_map']=route_map
_G[app_name]['map']=mch.functional.curry(map,route_map)
setfenv(2,_G[app_name])
end
|
#!/usr/bin/env lua
-- -*- lua -*-
-- Copyright 2012 Appwill Inc.
-- Author : KDr2
--
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
--
module('mch.router',package.seeall)
require 'mch.functional'
function map(route_table, uri, func_name)
local mod,fn = string.match(func_name,'^(.+)%.([^.]+)$')
mod=require(mod)
route_table[uri]=mod[fn]
end
function setup(app_name)
app_name='MOOCHINE_APP_' .. app_name
if not _G[app_name] then
_G[app_name]={}
end
if not _G[app_name]['route_map'] then
local route_map={}
_G[app_name]['route_map']=route_map
end
_G[app_name]['map']=mch.functional.curry(map,_G[app_name]['route_map'])
setfenv(2,_G[app_name])
end
|
bugfix
|
bugfix
|
Lua
|
apache-2.0
|
appwilldev/moochine,lilien1010/moochine,lilien1010/moochine,appwilldev/moochine,lilien1010/moochine
|
d0bd16dfaea66200d53b145fca9e70e0f9566b25
|
mock/common/ProtoSpawner.lua
|
mock/common/ProtoSpawner.lua
|
module 'mock'
local enumSpawnMethod = _ENUM_V {
'root',
'sibling',
'child',
'parent_sibling'
}
CLASS: ProtoSpawner ( Component )
:MODEL{
Field 'proto' :asset('proto');
Field 'spawnName' :string();
'----';
Field 'copyLoc' :boolean();
Field 'copyRot' :boolean();
Field 'copyScl' :boolean();
'----';
Field 'autoSpawn' :boolean();
Field 'destroyOnSpawn' :boolean();
Field 'spawnMethod' :enum( enumSpawnMethod )
-- Field 'spawnAsChild' :boolean();
}
:META{
category = 'spawner'
}
registerComponent( 'ProtoSpawner', ProtoSpawner )
registerEntityWithComponent( 'ProtoSpawner', ProtoSpawner )
function ProtoSpawner:__init()
self.proto = false
self.autoSpawn = true
self.destroyOnSpawn = true
self.spawnAsChild = false
self.copyLoc = true
self.copyScl = false
self.copyRot = false
self.spawnMethod = 'sibling'
self.spawnName = ''
end
function ProtoSpawner:onStart( ent )
if self.autoSpawn then
self:spawn()
end
end
function ProtoSpawner:spawnOne( ox, oy, oz )
local ent = self._entity
local instance
if self.proto then
instance = createProtoInstance( self.proto )
if instance then
instance:setName( self.spawnName )
local spawnMethod = self.spawnMethod
if spawnMethod == 'child' then
if self.copyLoc then instance:setLoc( 0,0,0 ) end
if self.copyRot then instance:setRot( 0,0,0 ) end
if self.copyScl then instance:setScl( 1,1,1 ) end
if ox then
instance:addLoc( ox, oy, oz )
end
ent:addChild( instance )
elseif spawnMethod == 'sibling' then
if self.copyLoc then instance:setLoc( ent:getLoc() ) end
if self.copyRot then instance:setRot( ent:getRot() ) end
if self.copyScl then instance:setScl( ent:getScl() ) end
if ox then
instance:addLoc( ox, oy, oz )
end
ent:addSibling( instance )
elseif spawnMethod == 'parent_sibling' then
ent:forceUpdate()
if ent.parent then
ent.parent:addSibling( instance )
else
ent:getScene():addEntity( instance )
end
if self.copyLoc then instance:setWorldLoc( ent:getWorldLoc() ) end
if self.copyRot then instance:setRot( ent:getRot() ) end
if self.copyScl then instance:setScl( ent:getScl() ) end
if ox then
instance:addLoc( ox, oy, oz )
end
elseif spawnMethod == 'root' then
ent:forceUpdate()
if self.copyLoc then instance:setLoc( ent:getWorldLoc() ) end
if self.copyRot then instance:setRot( ent:getRot() ) end
if self.copyScl then instance:setScl( ent:getScl() ) end
if ox then
instance:addLoc( ox, oy, oz )
end
instance:forceUpdate()
ent:getScene():addEntity( instance )
end
end
--FIXME:remove this non-generic code
if ent:isInstance( 'EWMapObject' ) then
instance:setFloor( ent:getFloor() )
end
end
return instance
end
function ProtoSpawner:spawn()
local result = { self:onSpawn() }
self:postSpawn()
return unpack( result )
end
function ProtoSpawner:onSpawn()
return self:spawnOne()
end
function ProtoSpawner:postSpawn()
if self.destroyOnSpawn then
self._entity:destroy()
end
end
--------------------------------------------------------------------
--EDITOR Support
function ProtoSpawner:onBuildGizmo()
local giz = mock_edit.IconGizmo( 'spawn.png' )
return giz
end
|
module 'mock'
local enumSpawnMethod = _ENUM_V {
'root',
'sibling',
'child',
'parent_sibling'
}
CLASS: ProtoSpawner ( Component )
:MODEL{
Field 'proto' :asset('proto');
Field 'spawnName' :string();
'----';
Field 'copyLoc' :boolean();
Field 'copyRot' :boolean();
Field 'copyScl' :boolean();
'----';
Field 'autoSpawn' :boolean();
Field 'destroyOnSpawn' :boolean();
Field 'spawnMethod' :enum( enumSpawnMethod )
-- Field 'spawnAsChild' :boolean();
}
:META{
category = 'spawner'
}
registerComponent( 'ProtoSpawner', ProtoSpawner )
registerEntityWithComponent( 'ProtoSpawner', ProtoSpawner )
function ProtoSpawner:__init()
self.proto = false
self.autoSpawn = true
self.destroyOnSpawn = true
self.spawnAsChild = false
self.copyLoc = true
self.copyScl = false
self.copyRot = false
self.spawnMethod = 'sibling'
self.spawnName = ''
end
function ProtoSpawner:onStart( ent )
if self.autoSpawn then
self:spawn()
end
end
function ProtoSpawner:spawnOne( ox, oy, oz )
local ent = self._entity
local instance
if self.proto then
instance = createProtoInstance( self.proto )
if instance then
instance:setName( self.spawnName )
local spawnMethod = self.spawnMethod
if spawnMethod == 'child' then
if self.copyLoc then instance:setLoc( 0,0,0 ) end
if self.copyRot then instance:setRot( 0,0,0 ) end
if self.copyScl then instance:setScl( 1,1,1 ) end
if ox then
instance:addLoc( ox, oy, oz )
end
ent:addChild( instance )
elseif spawnMethod == 'sibling' then
if self.copyLoc then instance:setLoc( ent:getLoc() ) end
if self.copyRot then instance:setRot( ent:getRot() ) end
if self.copyScl then instance:setScl( ent:getScl() ) end
if ox then
instance:addLoc( ox, oy, oz )
end
ent:addSibling( instance )
elseif spawnMethod == 'parent_sibling' then
ent:forceUpdate()
if ent.parent then
ent.parent:addSibling( instance )
if self.copyLoc then instance:setWorldLoc( ent:getWorldLoc() ) end
if self.copyRot then instance:setRot( ent:getRot() ) end
if self.copyScl then instance:setScl( ent:getScl() ) end
else
if self.copyLoc then instance:setLoc( ent:getWorldLoc() ) end
if self.copyRot then instance:setRot( ent:getRot() ) end
if self.copyScl then instance:setScl( ent:getScl() ) end
instance:forceUpdate()
ent:getScene():addEntity( instance )
end
if ox then
instance:addLoc( ox, oy, oz )
end
elseif spawnMethod == 'root' then
ent:forceUpdate()
if self.copyLoc then instance:setLoc( ent:getWorldLoc() ) end
if self.copyRot then instance:setRot( ent:getRot() ) end
if self.copyScl then instance:setScl( ent:getScl() ) end
if ox then
instance:addLoc( ox, oy, oz )
end
instance:forceUpdate()
ent:getScene():addEntity( instance )
end
end
--FIXME:remove this non-generic code
if ent:isInstance( 'EWMapObject' ) then
instance:setFloor( ent:getFloor() )
end
end
return instance
end
function ProtoSpawner:spawn()
local result = { self:onSpawn() }
self:postSpawn()
return unpack( result )
end
function ProtoSpawner:onSpawn()
return self:spawnOne()
end
function ProtoSpawner:postSpawn()
if self.destroyOnSpawn then
self._entity:destroy()
end
end
--------------------------------------------------------------------
--EDITOR Support
function ProtoSpawner:onBuildGizmo()
local giz = mock_edit.IconGizmo( 'spawn.png' )
return giz
end
|
fixed spawner bug
|
fixed spawner bug
|
Lua
|
mit
|
tommo/mock
|
24c1e0450d0d45ebc1e283a7b2676e53ef77d929
|
packages/nn/Sequential.lua
|
packages/nn/Sequential.lua
|
local Sequential, parent = torch.class('nn.Sequential', 'nn.Module')
function Sequential:__init()
self.modules = {}
end
function Sequential:add(module)
if #self.modules == 0 then
self.gradInput = module.gradInput
end
table.insert(self.modules, module)
self.output = module.output
return self
end
function Sequential:size()
return #self.modules
end
function Sequential:get(index)
return self.modules[index]
end
function Sequential:updateOutput(input)
local currentOutput = input
for i=1,#self.modules do
currentOutput = self.modules[i]:updateOutput(currentOutput)
end
self.output = currentOutput
return currentOutput
end
function Sequential:updateGradInput(input, gradOutput)
local currentGradOutput = gradOutput
local currentModule = self.modules[#self.modules]
for i=#self.modules-1,1,-1 do
local previousModule = self.modules[i]
currentGradOutput = currentModule:updateGradInput(previousModule.output, currentGradOutput)
currentModule = previousModule
end
currentGradOutput = currentModule:updateGradInput(input, currentGradOutput)
self.gradInput = currentGradOutput
return currentGradOutput
end
function Sequential:accGradParameters(input, gradOutput, scale)
scale = scale or 1
local currentGradOutput = gradOutput
local currentModule = self.modules[#self.modules]
for i=#self.modules-1,1,-1 do
local previousModule = self.modules[i]
currentModule:accGradParameters(previousModule.output, currentGradOutput, scale)
currentGradOutput = currentModule.gradInput
currentModule = previousModule
end
currentModule:accGradParameters(input, currentGradOutput, scale)
end
function Sequential:accUpdateGradParameters(input, gradOutput, lr)
local currentGradOutput = gradOutput
local currentModule = self.modules[#self.modules]
for i=#self.modules-1,1,-1 do
local previousModule = self.modules[i]
currentModule:accUpdateGradParameters(previousModule.output, currentGradOutput, lr)
currentGradOutput = currentModule.gradInput
currentModule = previousModule
end
currentModule:accUpdateGradParameters(input, currentGradOutput, lr)
end
function Sequential:zeroGradParameters()
for i=1,#self.modules do
self.modules[i]:zeroGradParameters()
end
end
function Sequential:updateParameters(learningRate)
for i=1,#self.modules do
self.modules[i]:updateParameters(learningRate)
end
end
function Sequential:share(mlp,...)
for i=1,#self.modules do
self.modules[i]:share(mlp.modules[i],...);
end
end
function Sequential:parameters()
local function tinsert(to, from)
if type(from) == 'table' then
for i=1,#from do
tinsert(to,from[i])
end
else
table.insert(to,from)
end
end
local w = {}
local gw = {}
for i=1,#self.modules do
local mw,mgw = self.modules[i]:parameters()
if mw then
tinsert(w,mw)
tinsert(gw,mgw)
end
end
return w,gw
end
function Sequential:__tostring__(dontexpand)
local tab = ' '
local line = '\n'
local next = ' -> '
local str = 'nn.Sequential'
if dontexpand then
return str
end
str = str .. ' {' .. line .. tab .. '[input'
for i=1,#self.modules do
str = str .. next .. '(' .. i .. ')'
end
str = str .. next .. 'output]'
for i=1,#self.modules do
str = str .. line .. tab .. '(' .. i .. '): ' .. tostring(self.modules[i], true)
end
str = str .. line .. '}'
return str
end
|
local Sequential, parent = torch.class('nn.Sequential', 'nn.Module')
function Sequential:__init()
self.modules = {}
end
function Sequential:add(module)
if #self.modules == 0 then
self.gradInput = module.gradInput
end
table.insert(self.modules, module)
self.output = module.output
return self
end
function Sequential:size()
return #self.modules
end
function Sequential:get(index)
return self.modules[index]
end
function Sequential:updateOutput(input)
local currentOutput = input
for i=1,#self.modules do
currentOutput = self.modules[i]:updateOutput(currentOutput)
end
self.output = currentOutput
return currentOutput
end
function Sequential:updateGradInput(input, gradOutput)
local currentGradOutput = gradOutput
local currentModule = self.modules[#self.modules]
for i=#self.modules-1,1,-1 do
local previousModule = self.modules[i]
currentGradOutput = currentModule:updateGradInput(previousModule.output, currentGradOutput)
currentModule = previousModule
end
currentGradOutput = currentModule:updateGradInput(input, currentGradOutput)
self.gradInput = currentGradOutput
return currentGradOutput
end
function Sequential:accGradParameters(input, gradOutput, scale)
scale = scale or 1
local currentGradOutput = gradOutput
local currentModule = self.modules[#self.modules]
for i=#self.modules-1,1,-1 do
local previousModule = self.modules[i]
currentModule:accGradParameters(previousModule.output, currentGradOutput, scale)
currentGradOutput = currentModule.gradInput
currentModule = previousModule
end
currentModule:accGradParameters(input, currentGradOutput, scale)
end
function Sequential:accUpdateGradParameters(input, gradOutput, lr)
local currentGradOutput = gradOutput
local currentModule = self.modules[#self.modules]
for i=#self.modules-1,1,-1 do
local previousModule = self.modules[i]
currentModule:accUpdateGradParameters(previousModule.output, currentGradOutput, lr)
currentGradOutput = currentModule.gradInput
currentModule = previousModule
end
currentModule:accUpdateGradParameters(input, currentGradOutput, lr)
end
function Sequential:zeroGradParameters()
for i=1,#self.modules do
self.modules[i]:zeroGradParameters()
end
end
function Sequential:updateParameters(learningRate)
for i=1,#self.modules do
self.modules[i]:updateParameters(learningRate)
end
end
function Sequential:share(mlp,...)
for i=1,#self.modules do
self.modules[i]:share(mlp.modules[i],...);
end
end
function Sequential:parameters()
local function tinsert(to, from)
if type(from) == 'table' then
for i=1,#from do
tinsert(to,from[i])
end
else
table.insert(to,from)
end
end
local w = {}
local gw = {}
for i=1,#self.modules do
local mw,mgw = self.modules[i]:parameters()
if mw then
tinsert(w,mw)
tinsert(gw,mgw)
end
end
return w,gw
end
function Sequential:__tostring__()
local tab = ' '
local line = '\n'
local next = ' -> '
local str = 'nn.Sequential'
str = str .. ' {' .. line .. tab .. '[input'
for i=1,#self.modules do
str = str .. next .. '(' .. i .. ')'
end
str = str .. next .. 'output]'
for i=1,#self.modules do
str = str .. line .. tab .. '(' .. i .. '): ' .. tostring(self.modules[i]):gsub(line, line .. tab)
end
str = str .. line .. '}'
return str
end
|
Fixed nested prints for Sequential
|
Fixed nested prints for Sequential
|
Lua
|
bsd-3-clause
|
soumith/TH,soumith/TH,soumith/TH,soumith/TH
|
de87bce7f9a507cf34165f3894420f00c36ef7d2
|
src/program/lwaftr/query/query.lua
|
src/program/lwaftr/query/query.lua
|
module(..., package.seeall)
local S = require("syscall")
local counter = require("core.counter")
local ffi = require("ffi")
local lib = require("core.lib")
local lwcounter = require("apps.lwaftr.lwcounter")
local lwtypes = require("apps.lwaftr.lwtypes")
local lwutil = require("apps.lwaftr.lwutil")
local shm = require("core.shm")
local top = require("program.top.top")
local select_snabb_instance = top.select_snabb_instance
local keys = lwutil.keys
-- Get the counter dir from the code.
local counters_dir = lwcounter.counters_dir
function show_usage (code)
print(require("program.lwaftr.query.README_inc"))
main.exit(code)
end
local function sort (t)
table.sort(t)
return t
end
local function is_counter_name (name)
return lwcounter.counter_names[name] ~= nil
end
local function pidof(maybe_pid)
if tonumber(maybe_pid) then return maybe_pid end
local name_id = maybe_pid
for _, pid in ipairs(shm.children("/")) do
if shm.exists(pid.."/nic/id") then
local lwaftr_id = shm.open("/"..pid.."/nic/id", lwtypes.lwaftr_id_type)
if ffi.string(lwaftr_id.value) == name_id then
return pid
end
end
end
end
function parse_args (raw_args)
local handlers = {}
function handlers.h() show_usage(0) end
function handlers.l ()
for _, name in ipairs(sort(lwcounter.counter_names)) do
print(name)
end
main.exit(0)
end
local args = lib.dogetopt(raw_args, handlers, "hl",
{ help="h", ["list-all"]="l" })
if #args > 2 then show_usage(1) end
if #args == 2 then
return args[1], args[2]
end
if #args == 1 then
local arg = args[1]
if is_counter_name(arg) then
return nil, arg
else
local pid = pidof(arg)
if not pid then
error(("Couldn't find PID for argument '%s'"):format(arg))
end
return pid, nil
end
end
return nil, nil
end
local function read_counters (tree, filter)
local ret = {}
local cnt, cnt_path, value
local max_width = 0
local counters_path = "/" .. tree .. "/" .. counters_dir
local counters = shm.children(counters_path)
for _, name in ipairs(counters) do
cnt_path = counters_path .. name
cnt = counter.open(cnt_path, 'readonly')
value = tonumber(counter.read(cnt))
if value ~= 0 then
name = name:gsub(".counter$", "")
if #name > max_width then max_width = #name end
ret[name] = value
end
end
return ret, max_width
end
local function skip_counter (name, filter)
return filter and not name:match(filter)
end
local function print_counter (name, value, max_width)
local nspaces = max_width - #name
print(("%s: %s%s"):format(name, (" "):rep(nspaces), lib.comma_value(value)))
end
function print_counters (tree, filter)
print("lwAFTR operational counters (non-zero)")
-- Open, read and print whatever counters are in that directory.
local counters, max_width = read_counters(tree, filter)
for _, name in ipairs(sort(keys(counters))) do
if not skip_counter(name, filter) then
local value = counters[name]
print_counter(name, value, max_width)
end
end
end
function run (raw_args)
local target_pid, counter_name = parse_args(raw_args)
local instance_tree = select_snabb_instance(target_pid)
print_counters(instance_tree, counter_name)
end
|
module(..., package.seeall)
local S = require("syscall")
local counter = require("core.counter")
local ffi = require("ffi")
local lib = require("core.lib")
local lwcounter = require("apps.lwaftr.lwcounter")
local lwtypes = require("apps.lwaftr.lwtypes")
local lwutil = require("apps.lwaftr.lwutil")
local shm = require("core.shm")
local top = require("program.top.top")
local select_snabb_instance = top.select_snabb_instance
local keys = lwutil.keys
-- Get the counter dir from the code.
local counters_dir = lwcounter.counters_dir
function show_usage (code)
print(require("program.lwaftr.query.README_inc"))
main.exit(code)
end
local function sort (t)
table.sort(t)
return t
end
local function is_counter_name (name)
return lwcounter.counter_names[name] ~= nil
end
local function pidof(maybe_pid)
if tonumber(maybe_pid) then return maybe_pid end
local name_id = maybe_pid
for _, pid in ipairs(shm.children("/")) do
local path = "/"..pid.."/nic/id"
if shm.exists(path) then
local lwaftr_id = shm.open(path, lwtypes.lwaftr_id_type)
if ffi.string(lwaftr_id.value) == name_id then
return pid
end
end
end
end
function parse_args (raw_args)
local handlers = {}
function handlers.h() show_usage(0) end
function handlers.l ()
for _, name in ipairs(sort(lwcounter.counter_names)) do
print(name)
end
main.exit(0)
end
local args = lib.dogetopt(raw_args, handlers, "hl",
{ help="h", ["list-all"]="l" })
if #args > 2 then show_usage(1) end
if #args == 2 then
return args[1], args[2]
end
if #args == 1 then
local arg = args[1]
if is_counter_name(arg) then
return nil, arg
else
local pid = pidof(arg)
if not pid then
error(("Couldn't find PID for argument '%s'"):format(arg))
end
return pid, nil
end
end
return nil, nil
end
local function read_counters (tree, filter)
local ret = {}
local cnt, cnt_path, value
local max_width = 0
local counters_path = "/" .. tree .. "/" .. counters_dir
local counters = shm.children(counters_path)
for _, name in ipairs(counters) do
cnt_path = counters_path .. name
cnt = counter.open(cnt_path, 'readonly')
value = tonumber(counter.read(cnt))
if value ~= 0 then
name = name:gsub(".counter$", "")
if #name > max_width then max_width = #name end
ret[name] = value
end
end
return ret, max_width
end
local function skip_counter (name, filter)
return filter and not name:match(filter)
end
local function print_counter (name, value, max_width)
local nspaces = max_width - #name
print(("%s: %s%s"):format(name, (" "):rep(nspaces), lib.comma_value(value)))
end
function print_counters (tree, filter)
print("lwAFTR operational counters (non-zero)")
-- Open, read and print whatever counters are in that directory.
local counters, max_width = read_counters(tree, filter)
for _, name in ipairs(sort(keys(counters))) do
if not skip_counter(name, filter) then
local value = counters[name]
print_counter(name, value, max_width)
end
end
end
function run (raw_args)
local target_pid, counter_name = parse_args(raw_args)
local instance_tree = select_snabb_instance(target_pid)
print_counters(instance_tree, counter_name)
end
|
Fix fetch lwAFTR instance by name
|
Fix fetch lwAFTR instance by name
|
Lua
|
apache-2.0
|
Igalia/snabbswitch,dpino/snabb,heryii/snabb,snabbco/snabb,eugeneia/snabbswitch,Igalia/snabbswitch,kbara/snabb,snabbco/snabb,SnabbCo/snabbswitch,eugeneia/snabb,dpino/snabbswitch,dpino/snabbswitch,dpino/snabb,eugeneia/snabb,alexandergall/snabbswitch,Igalia/snabb,eugeneia/snabb,kbara/snabb,kbara/snabb,dpino/snabbswitch,alexandergall/snabbswitch,mixflowtech/logsensor,snabbco/snabb,alexandergall/snabbswitch,Igalia/snabbswitch,dpino/snabb,alexandergall/snabbswitch,Igalia/snabb,kbara/snabb,dpino/snabb,eugeneia/snabbswitch,mixflowtech/logsensor,SnabbCo/snabbswitch,dpino/snabb,snabbco/snabb,kbara/snabb,snabbco/snabb,dpino/snabb,alexandergall/snabbswitch,heryii/snabb,eugeneia/snabbswitch,heryii/snabb,heryii/snabb,Igalia/snabb,Igalia/snabb,Igalia/snabb,Igalia/snabb,Igalia/snabb,snabbco/snabb,mixflowtech/logsensor,dpino/snabbswitch,dpino/snabb,SnabbCo/snabbswitch,snabbco/snabb,eugeneia/snabb,mixflowtech/logsensor,eugeneia/snabb,eugeneia/snabbswitch,alexandergall/snabbswitch,snabbco/snabb,eugeneia/snabb,Igalia/snabbswitch,alexandergall/snabbswitch,eugeneia/snabb,mixflowtech/logsensor,SnabbCo/snabbswitch,Igalia/snabb,alexandergall/snabbswitch,kbara/snabb,eugeneia/snabb,heryii/snabb,heryii/snabb,Igalia/snabbswitch
|
691a7645912f04af5c83aa6fbc8dfbc90753cc08
|
mod_webpresence/mod_webpresence.lua
|
mod_webpresence/mod_webpresence.lua
|
module:depends("http");
local jid_split = require "util.jid".prepped_split;
local function require_resource(name)
local icon_path = module:get_option_string("presence_icons", "icons");
local f, err = module:load_resource(icon_path.."/"..name);
if f then
return f:read("*a");
end
module:log("warn", "Failed to open image file %s", icon_path..name);
return "";
end
local statuses = { online = {}, away = {}, xa = {}, dnd = {}, chat = {}, offline = {} };
for status, _ in pairs(statuses) do
statuses[status].image = { status_code = 200, headers = { content_type = "image/png" },
body = require_resource("status_"..status..".png") };
statuses[status].text = { status_code = 200, headers = { content_type = "plain/text" },
body = status };
end
local function handle_request(event, path)
local status;
local jid, type = path:match("([^/]+)/?(.*)$");
if jid then
local user, host = jid_split(jid);
if host and not user then
user, host = host, event.request.headers.host;
if host then host = host:gsub(":%d+$", ""); end
end
if user and host then
local user_sessions = hosts[host] and hosts[host].sessions[user];
if user_sessions then
status = user_sessions.top_resources[1];
if status and status.presence then
status = status.presence:child_with_name("show");
if not status then
status = "online";
else
status = status:get_text();
end
end
end
end
end
status = status or "offline";
return (type and type == "text") and statuses[status].text or statuses[status].image;
end
module:provides("http", {
default_path = "/status";
route = {
["GET /*"] = handle_request;
};
});
|
module:depends("http");
local jid_split = require "util.jid".prepped_split;
local b64 = require "util.encodings".base64.encode;
local sha1 = require "util.hashes".sha1;
local function require_resource(name)
local icon_path = module:get_option_string("presence_icons", "icons");
local f, err = module:load_resource(icon_path.."/"..name);
if f then
return f:read("*a");
end
module:log("warn", "Failed to open image file %s", icon_path..name);
return "";
end
local statuses = { online = {}, away = {}, xa = {}, dnd = {}, chat = {}, offline = {} };
--[[for status, _ in pairs(statuses) do
statuses[status].image = { status_code = 200, headers = { content_type = "image/png" },
body = require_resource("status_"..status..".png") };
statuses[status].text = { status_code = 200, headers = { content_type = "text/plain" },
body = status };
end]]
local function handle_request(event, path)
local status, message;
local jid, type = path:match("([^/]+)/?(.*)$");
if jid then
local user, host = jid_split(jid);
if host and not user then
user, host = host, event.request.headers.host;
if host then host = host:gsub(":%d+$", ""); end
end
if user and host then
local user_sessions = hosts[host] and hosts[host].sessions[user];
if user_sessions then
status = user_sessions.top_resources[1];
if status and status.presence then
message = status.presence:child_with_name("status");
status = status.presence:child_with_name("show");
if not status then
status = "online";
else
status = status:get_text();
end
if message then
message = message:get_text();
end
end
end
end
end
status = status or "offline";
if type == "" then type = "image" end;
if type == "image" then
statuses[status].image = { status_code = 200, headers = { content_type = "image/png" },
body = require_resource("status_"..status..".png") };
elseif type == "html" then
statuses[status].html = { status_code = 200, headers = { content_type = "text/html" },
body = [[<div id="]]..sha1(jid,true)..[[_status" class="xmpp_status">]]..
[[<img id="]]..sha1(jid,true)..[[_img" class="xmpp_status_image" ]]..
[[src="data:image/png;base64,]]..
b64(require_resource("status_"..status..".png"))..[[">]]..
[[<span id="]]..sha1(jid,true)..[[_name" ]]..
[[class="xmpp_status_name">]]..status..[[</span>]]..
(message and [[<span id="]]..sha1(jid,true)..[[_message" ]]..
[[class="xmpp_status_message">]]..message..[[</span>]] or "")..
[[</div>]] };
elseif type == "text" then
statuses[status].text = { status_code = 200, headers = { content_type = "text/plain" },
body = status };
elseif type == "message" then
statuses[status].message = { status_code = 200, headers = { content_type = "text/plain" },
body = (message and message or "") };
end
return statuses[status][type];
end
module:provides("http", {
default_path = "/status";
route = {
["GET /*"] = handle_request;
};
});
|
mod_webpresence: fixed text notation, added html, added status message output
|
mod_webpresence: fixed text notation, added html, added status message output
|
Lua
|
mit
|
crunchuser/prosody-modules,guilhem/prosody-modules,drdownload/prosody-modules,1st8/prosody-modules,vince06fr/prosody-modules,amenophis1er/prosody-modules,softer/prosody-modules,stephen322/prosody-modules,brahmi2/prosody-modules,crunchuser/prosody-modules,syntafin/prosody-modules,softer/prosody-modules,jkprg/prosody-modules,vince06fr/prosody-modules,iamliqiang/prosody-modules,crunchuser/prosody-modules,crunchuser/prosody-modules,mardraze/prosody-modules,NSAKEY/prosody-modules,Craige/prosody-modules,1st8/prosody-modules,amenophis1er/prosody-modules,NSAKEY/prosody-modules,vfedoroff/prosody-modules,vince06fr/prosody-modules,joewalker/prosody-modules,joewalker/prosody-modules,apung/prosody-modules,brahmi2/prosody-modules,brahmi2/prosody-modules,cryptotoad/prosody-modules,dhotson/prosody-modules,guilhem/prosody-modules,jkprg/prosody-modules,syntafin/prosody-modules,drdownload/prosody-modules,LanceJenkinZA/prosody-modules,syntafin/prosody-modules,prosody-modules/import,LanceJenkinZA/prosody-modules,BurmistrovJ/prosody-modules,1st8/prosody-modules,amenophis1er/prosody-modules,heysion/prosody-modules,mardraze/prosody-modules,stephen322/prosody-modules,crunchuser/prosody-modules,1st8/prosody-modules,amenophis1er/prosody-modules,obelisk21/prosody-modules,brahmi2/prosody-modules,cryptotoad/prosody-modules,BurmistrovJ/prosody-modules,olax/prosody-modules,either1/prosody-modules,apung/prosody-modules,dhotson/prosody-modules,heysion/prosody-modules,syntafin/prosody-modules,brahmi2/prosody-modules,guilhem/prosody-modules,syntafin/prosody-modules,prosody-modules/import,cryptotoad/prosody-modules,mardraze/prosody-modules,either1/prosody-modules,NSAKEY/prosody-modules,prosody-modules/import,LanceJenkinZA/prosody-modules,drdownload/prosody-modules,obelisk21/prosody-modules,heysion/prosody-modules,NSAKEY/prosody-modules,BurmistrovJ/prosody-modules,jkprg/prosody-modules,prosody-modules/import,asdofindia/prosody-modules,cryptotoad/prosody-modules,mmusial/prosody-modules,drdownload/prosody-modules,iamliqiang/prosody-modules,olax/prosody-modules,iamliqiang/prosody-modules,asdofindia/prosody-modules,stephen322/prosody-modules,joewalker/prosody-modules,obelisk21/prosody-modules,iamliqiang/prosody-modules,Craige/prosody-modules,vince06fr/prosody-modules,either1/prosody-modules,amenophis1er/prosody-modules,either1/prosody-modules,apung/prosody-modules,obelisk21/prosody-modules,stephen322/prosody-modules,guilhem/prosody-modules,asdofindia/prosody-modules,obelisk21/prosody-modules,drdownload/prosody-modules,vfedoroff/prosody-modules,LanceJenkinZA/prosody-modules,Craige/prosody-modules,prosody-modules/import,asdofindia/prosody-modules,dhotson/prosody-modules,heysion/prosody-modules,BurmistrovJ/prosody-modules,heysion/prosody-modules,Craige/prosody-modules,mmusial/prosody-modules,mmusial/prosody-modules,Craige/prosody-modules,either1/prosody-modules,joewalker/prosody-modules,iamliqiang/prosody-modules,softer/prosody-modules,apung/prosody-modules,olax/prosody-modules,mmusial/prosody-modules,jkprg/prosody-modules,jkprg/prosody-modules,softer/prosody-modules,asdofindia/prosody-modules,LanceJenkinZA/prosody-modules,softer/prosody-modules,apung/prosody-modules,dhotson/prosody-modules,vfedoroff/prosody-modules,mardraze/prosody-modules,NSAKEY/prosody-modules,mmusial/prosody-modules,BurmistrovJ/prosody-modules,joewalker/prosody-modules,guilhem/prosody-modules,vfedoroff/prosody-modules,vince06fr/prosody-modules,olax/prosody-modules,vfedoroff/prosody-modules,mardraze/prosody-modules,stephen322/prosody-modules,cryptotoad/prosody-modules,dhotson/prosody-modules,1st8/prosody-modules,olax/prosody-modules
|
333c2c0ad937af1a69f812072fbaaaab16f310a1
|
premake5.lua
|
premake5.lua
|
-- Helper function to find compute API headers and libraries
function findLibraries()
local path = os.getenv("INTELOCLSDKROOT")
if (path) then
defines { "PLATFORM_INTEL" }
includedirs { "$(INTELOCLSDKROOT)/include" }
filter "platforms:x86"
if os.get() == "linux" then
libdirs { "$(INTELOCLSDKROOT)/lib" }
else
libdirs { "$(INTELOCLSDKROOT)/lib/x86" }
end
filter "platforms:x86_64"
if os.get() == "linux" then
libdirs { "$(INTELOCLSDKROOT)/lib64" }
else
libdirs { "$(INTELOCLSDKROOT)/lib/x64" }
end
filter {}
links {"OpenCL"}
return true
end
path = os.getenv("AMDAPPSDKROOT")
if (path) then
defines { "PLATFORM_AMD" }
includedirs { "$(AMDAPPSDKROOT)/include" }
filter "platforms:x86"
if os.get() == "linux" then
libdirs { "$(AMDAPPSDKROOT)/lib" }
else
libdirs { "$(AMDAPPSDKROOT)/lib/x86" }
end
filter "platforms:x86_64"
if os.get() == "linux" then
libdirs { "$(AMDAPPSDKROOT)/lib64" }
else
libdirs { "$(AMDAPPSDKROOT)/lib/x86_64" }
end
filter {}
links { "OpenCL" }
return true
end
path = os.getenv("CUDA_PATH")
if (path) then
defines { "PLATFORM_NVIDIA" }
includedirs { "$(CUDA_PATH)/include" }
filter "platforms:x86"
if os.get() == "linux" then
libdirs { "$(CUDA_PATH)/lib" }
else
libdirs { "$(CUDA_PATH)/lib/Win32" }
end
filter "platforms:x86_64"
if os.get() == "linux" then
libdirs { "$(CUDA_PATH)/lib64" }
else
libdirs { "$(CUDA_PATH)/lib/x64" }
end
filter {}
links { "OpenCL" }
if _OPTIONS["cuda"] then
defines { "PLATFORM_CUDA" }
links { "cuda" }
end
return true
end
return false
end
-- Command line arguments definition
newoption
{
trigger = "outdir",
value = "path",
description = "Specifies output directory for generated files"
}
newoption
{
trigger = "cuda",
description = "Enables usage of CUDA API in addition to OpenCL (Nvidia platform only)"
}
newoption
{
trigger = "tests",
description = "Enables compilation of supplied unit tests"
}
newoption
{
trigger = "disable-examples",
description = "Disables compilation of supplied examples"
}
-- Project configuration
workspace "KernelTuningToolkit"
local buildPath = "build"
if _OPTIONS["outdir"] then
buildPath = _OPTIONS["outdir"]
end
configurations { "Debug", "Release" }
platforms { "x86", "x86_64" }
location (buildPath)
language "C++"
flags { "C++14" }
filter "platforms:x86"
architecture "x86"
filter "platforms:x86_64"
architecture "x86_64"
filter "configurations:Debug"
defines { "DEBUG" }
symbols "On"
filter "configurations:Release"
defines { "NDEBUG" }
optimize "On"
filter {}
targetdir(buildPath .. "/%{cfg.platform}_%{cfg.buildcfg}")
objdir(buildPath .. "/%{cfg.platform}_%{cfg.buildcfg}/obj")
-- Library configuration
project "KernelTuningToolkit"
kind "SharedLib"
files { "source/**.h", "source/**.hpp", "source/**.cpp" }
includedirs { "source/**" }
defines { "KTT_LIBRARY" }
local libraries = findLibraries()
if not libraries then
printf("Warning: Compute API libraries were not found.")
end
-- Examples configuration
project "ExampleSimple"
if not _OPTIONS["disable-examples"] then
kind "ConsoleApp"
else
kind "None"
end
files { "examples/simple/*.cpp", "examples/simple/*.cl" }
includedirs { "include/**" }
links { "KernelTuningToolkit" }
project "ExampleOpenCLInfo"
if not _OPTIONS["disable-examples"] then
kind "ConsoleApp"
else
kind "None"
end
files { "examples/opencl_info/*.cpp" }
includedirs { "include/**" }
links { "KernelTuningToolkit" }
project "ExampleCoulombSum"
if not _OPTIONS["disable-examples"] then
kind "ConsoleApp"
else
kind "None"
end
files { "examples/coulomb_sum/*.cpp", "examples/coulomb_sum/*.cl" }
includedirs { "include/**" }
links { "KernelTuningToolkit" }
project "ExampleCoulombSum3D"
if not _OPTIONS["disable-examples"] then
kind "ConsoleApp"
else
kind "None"
end
files { "examples/coulomb_sum_3d/*.cpp", "examples/coulomb_sum_3d/*.cl" }
includedirs { "include/**" }
links { "KernelTuningToolkit" }
-- Unit tests configuration
project "Tests"
if _OPTIONS["tests"] then
kind "ConsoleApp"
else
kind "None"
end
files { "tests/**.hpp", "tests/**.cpp", "tests/**.cl", "source/**.h", "source/**.hpp", "source/**.cpp" }
includedirs { "tests/**", "source/**" }
defines { "KTT_TESTS", "DO_NOT_USE_WMAIN" }
findLibraries()
|
-- Helper function to find compute API headers and libraries
function findLibraries()
local path = os.getenv("INTELOCLSDKROOT")
if (path) then
defines { "PLATFORM_INTEL" }
includedirs { "$(INTELOCLSDKROOT)/include" }
filter "platforms:x86"
if os.get() == "linux" then
libdirs { "$(INTELOCLSDKROOT)/lib" }
else
libdirs { "$(INTELOCLSDKROOT)/lib/x86" }
end
filter "platforms:x86_64"
if os.get() == "linux" then
libdirs { "$(INTELOCLSDKROOT)/lib64" }
else
libdirs { "$(INTELOCLSDKROOT)/lib/x64" }
end
filter {}
links {"OpenCL"}
return true
end
path = os.getenv("AMDAPPSDKROOT")
if (path) then
defines { "PLATFORM_AMD" }
includedirs { "$(AMDAPPSDKROOT)/include" }
filter "platforms:x86"
if os.get() == "linux" then
libdirs { "$(AMDAPPSDKROOT)/lib" }
else
libdirs { "$(AMDAPPSDKROOT)/lib/x86" }
end
filter "platforms:x86_64"
if os.get() == "linux" then
libdirs { "$(AMDAPPSDKROOT)/lib64" }
else
libdirs { "$(AMDAPPSDKROOT)/lib/x86_64" }
end
filter {}
links { "OpenCL" }
return true
end
path = os.getenv("CUDA_PATH")
if (path) then
defines { "PLATFORM_NVIDIA" }
includedirs { "$(CUDA_PATH)/include" }
filter "platforms:x86"
if os.get() == "linux" then
libdirs { "$(CUDA_PATH)/lib" }
else
libdirs { "$(CUDA_PATH)/lib/Win32" }
end
filter "platforms:x86_64"
if os.get() == "linux" then
libdirs { "$(CUDA_PATH)/lib64" }
else
libdirs { "$(CUDA_PATH)/lib/x64" }
end
filter {}
links { "OpenCL" }
if _OPTIONS["cuda"] then
defines { "PLATFORM_CUDA" }
links { "cuda" }
end
return true
end
return false
end
-- Command line arguments definition
newoption
{
trigger = "outdir",
value = "path",
description = "Specifies output directory for generated files"
}
newoption
{
trigger = "cuda",
description = "Enables usage of CUDA API in addition to OpenCL (Nvidia platform only)"
}
newoption
{
trigger = "tests",
description = "Enables compilation of supplied unit tests"
}
newoption
{
trigger = "disable-examples",
description = "Disables compilation of supplied examples"
}
-- Project configuration
workspace "KernelTuningToolkit"
local buildPath = "build"
if _OPTIONS["outdir"] then
buildPath = _OPTIONS["outdir"]
end
configurations { "Debug", "Release" }
platforms { "x86", "x86_64" }
location (buildPath)
language "C++"
flags { "C++14" }
filter "platforms:x86"
architecture "x86"
filter "platforms:x86_64"
architecture "x86_64"
filter "configurations:Debug"
defines { "DEBUG" }
symbols "On"
filter "configurations:Release"
defines { "NDEBUG" }
optimize "On"
filter {}
targetdir(buildPath .. "/%{cfg.platform}_%{cfg.buildcfg}")
objdir(buildPath .. "/%{cfg.platform}_%{cfg.buildcfg}/obj")
-- Library configuration
project "KernelTuningToolkit"
kind "SharedLib"
files { "source/**.h", "source/**.hpp", "source/**.cpp" }
includedirs { "source/**" }
defines { "KTT_LIBRARY" }
local libraries = findLibraries()
if not libraries then
printf("Warning: Compute API libraries were not found.")
end
-- Examples configuration
if not _OPTIONS["disable-examples"] then
project "ExampleSimple"
kind "ConsoleApp"
files { "examples/simple/*.cpp", "examples/simple/*.cl" }
includedirs { "include/**" }
links { "KernelTuningToolkit" }
project "ExampleOpenCLInfo"
kind "ConsoleApp"
files { "examples/opencl_info/*.cpp" }
includedirs { "include/**" }
links { "KernelTuningToolkit" }
project "ExampleCoulombSum"
kind "ConsoleApp"
files { "examples/coulomb_sum/*.cpp", "examples/coulomb_sum/*.cl" }
includedirs { "include/**" }
links { "KernelTuningToolkit" }
project "ExampleCoulombSum3D"
kind "ConsoleApp"
files { "examples/coulomb_sum_3d/*.cpp", "examples/coulomb_sum_3d/*.cl" }
includedirs { "include/**" }
links { "KernelTuningToolkit" }
end -- _OPTIONS["disable-examples"]
-- Unit tests configuration
if _OPTIONS["tests"] then
project "Tests"
kind "ConsoleApp"
files { "tests/**.hpp", "tests/**.cpp", "tests/**.cl", "source/**.h", "source/**.hpp", "source/**.cpp" }
includedirs { "tests/**", "source/**" }
defines { "KTT_TESTS", "DO_NOT_USE_WMAIN" }
findLibraries()
end -- _OPTIONS["tests"]
|
Fixed Premake warnings when generating files for gmake
|
Fixed Premake warnings when generating files for gmake
|
Lua
|
mit
|
Fillo7/KTT,Fillo7/KTT
|
30f7400be367b722822897c496575d703b0439ce
|
OS/DiskOS/Libraries/diskHelpers.lua
|
OS/DiskOS/Libraries/diskHelpers.lua
|
function Sprite(id,x,y,r,sx,sy,sheet) (sheet or SpriteMap):draw(id,x,y,r,sx,sy) end
function SpriteGroup(id,x,y,w,h,sx,sy,sheet)
local sx,sy = math.floor(sx or 1), math.floor(sy or 1)
for spry = 1, h or 1 do for sprx = 1, w or 1 do
(sheet or SpriteMap):draw((id-1)+sprx+(spry*24-24),x+(sprx*sx*8-sx*8),y+(spry*sy*8-sy*8),0,sx,sy)
end end
end
--Flags API
function fget(id,n)
if type(id) ~= "number" then return error("SpriteId must be a number, provided: "..type(id)) end
if n and type(n) ~= "number" then return error("BitNumber must be a number, provided: "..type(n)) end
local id = math.floor(id)
local n = n; if n then n = math.floor(n) end
local flags = SheetFlagsData or string.char(0)
if type(flags) ~= "string" then return error("Corrupted SheetFlagsData") end
if id < 1 then return error("SpriteId is out of range ("..id..") expected [1,"..flags:len().."]") end
if id > flags:len() then return error("SpriteId is out of range ("..id..") expected [1,"..flags:len().."]") end
local flag = string.byte(flags:sub(id,id))
if n then
if n < 1 then return error("BitNumber is out of range ("..n..") expected [1,8]") end
if n > 8 then return error("BitNumber is out of range ("..n..") expected [1,8]") end
n = n-1
n = (n==0) and 1 or (2^n)
return bit.band(flag,n) == n
else
return flag
end
end
function fset(id,n,v)
if type(id) ~= "number" then return error("SpriteId must be a number, provided: "..type(id)) end
local id = math.floor(id)
local flags = SheetFlagsData or string.char(0)
if type(flags) ~= "string" then return error("Corrupted FlagsData") end
if id < 1 then return error("SpriteId is out of range ("..id..") expected [1,"..flags:len().."]") end
if id > flags:len() then return error("SpriteId is out of range ("..id..") expected [1,"..flags:len().."]") end
local flag = string.byte(flags:sub(id,id))
if type(v) == "boolean" then
if type(n) ~= "number" then return error("BitNumber must be a number, provided: "..type(n)) end
n = math.floor(n)
if n < 1 then return error("BitNumber is out of range ("..n..") expected [1,8]") end
if n > 8 then return error("BitNumber is out of range ("..n..") expected [1,8]") end
if type(v) ~= "boolean" and type(v) ~= "nil" then return error("BitValue must be a boolean") end
n = n-1
n = (n==0) and 1 or (2^n)
if v then
flag = bit.bor(flag,n)
else
n = bit.bnot(n)
flag = bit.band(flag,n)
end
SheetFlagsData = flags:sub(0,id-1)..string.char(flag)..flags:sub(id+1,-1)
else
if type(n) ~= "number" then return error("FlagValue must be a number") end
n = math.floor(n)
if n < 1 then return error("FlagValue is out of range ("..n..") expected [1,255]") end
if n > 255 then return error("FlagValue is out of range ("..n..") expected [1,255]") end
flag = string.char(n)
SheetFlagsData = flags:sub(0,id-1)..flag..flags:sub(id+1,-1)
end
end
--Enter the while true loop and pull events, including the call of calbacks in _G
function eventLoop()
while true do
local name, a, b, c, d, e, f = pullEvent()
if _G[name] and type(_G[name]) == "function" then
_G[name](a,b,c,d,e,f)
end
end
end
|
function Sprite(id,x,y,r,sx,sy,sheet) (sheet or SpriteMap):draw(id,x,y,r,sx,sy) end
function SpriteGroup(id,x,y,w,h,sx,sy,sheet)
local sx,sy = math.floor(sx or 1), math.floor(sy or 1)
for spry = 1, h or 1 do for sprx = 1, w or 1 do
(sheet or SpriteMap):draw((id-1)+sprx+(spry*24-24),x+(sprx*sx*8-sx*8),y+(spry*sy*8-sy*8),0,sx,sy)
end end
end
--Flags API
function fget(id,n)
if type(id) ~= "number" then return error("SpriteId must be a number, provided: "..type(id)) end
if n and type(n) ~= "number" then return error("BitNumber must be a number, provided: "..type(n)) end
local id = math.floor(id)
local n = n; if n then n = math.floor(n) end
local flags = SheetFlagsData or string.char(0)
if type(flags) ~= "string" or flags:len() == 0 then return error("Corrupted SheetFlagsData") end
if id < 1 then return error("SpriteId is out of range ("..id..") expected [1,"..flags:len().."]") end
if id > flags:len() then return error("SpriteId is out of range ("..id..") expected [1,"..flags:len().."]") end
local flag = string.byte(flags:sub(id,id))
if n then
if n < 1 then return error("BitNumber is out of range ("..n..") expected [1,8]") end
if n > 8 then return error("BitNumber is out of range ("..n..") expected [1,8]") end
n = n-1
n = (n==0) and 1 or (2^n)
return bit.band(flag,n) == n
else
return flag
end
end
function fset(id,n,v)
if type(id) ~= "number" then return error("SpriteId must be a number, provided: "..type(id)) end
local id = math.floor(id)
local flags = SheetFlagsData or string.char(0)
if type(flags) ~= "string" or flags:len() == 0 then return error("Corrupted FlagsData") end
if id < 1 then return error("SpriteId is out of range ("..id..") expected [1,"..flags:len().."]") end
if id > flags:len() then return error("SpriteId is out of range ("..id..") expected [1,"..flags:len().."]") end
local flag = string.byte(flags:sub(id,id))
if type(v) == "boolean" then
if type(n) ~= "number" then return error("BitNumber must be a number, provided: "..type(n)) end
n = math.floor(n)
if n < 1 then return error("BitNumber is out of range ("..n..") expected [1,8]") end
if n > 8 then return error("BitNumber is out of range ("..n..") expected [1,8]") end
if type(v) ~= "boolean" and type(v) ~= "nil" then return error("BitValue must be a boolean") end
n = n-1
n = (n==0) and 1 or (2^n)
if v then
flag = bit.bor(flag,n)
else
n = bit.bnot(n)
flag = bit.band(flag,n)
end
SheetFlagsData = flags:sub(0,id-1)..string.char(flag)..flags:sub(id+1,-1)
else
if type(n) ~= "number" then return error("FlagValue must be a number") end
n = math.floor(n)
if n < 1 then return error("FlagValue is out of range ("..n..") expected [1,255]") end
if n > 255 then return error("FlagValue is out of range ("..n..") expected [1,255]") end
flag = string.char(n)
SheetFlagsData = flags:sub(0,id-1)..flag..flags:sub(id+1,-1)
end
end
--Enter the while true loop and pull events, including the call of calbacks in _G
function eventLoop()
while true do
local name, a, b, c, d, e, f = pullEvent()
if _G[name] and type(_G[name]) == "function" then
_G[name](a,b,c,d,e,f)
end
end
end
|
Bugfix
|
Bugfix
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
8f32a3da1190b9ad2604dc5910393d336a1ea5fd
|
Typelist-alltypes.lua
|
Typelist-alltypes.lua
|
--[[
Modulo che crea l'elenco Pokémon per tipo
--]]
local g = {}
local data = require("Wikilib-data")
local tl = require('Typelist')
--[[
Sorting function for Entry:
Pokémon with two types are sorted first for
second type order, then for ndex
--]]
tl.FirstTypeEntry.__lt = function(a, b)
if (a.type2 == b.type2) then
return tl.FirstTypeEntry.super.__lt(a, b)
end
return table.search(data.typesOrder, a.type2)
< table.search(data.typesOrder, b.type2)
end
--[[
Funzione di interfaccia: ritorna l'elenco Pokémon
per tipo
--]]
g.typelist = function(frame)
local tables = {}
for k, type in ipairs(data.typesOrder) do
local typeName = type == 'coleot' and 'coleottero' or type
table.insert(tables, tl.makeTypeTable(typeName, tl.MonoTypeEntry))
table.insert(tables, tl.makeTypeTable(type, tl.FirstTypeEntry))
end
return table.concat(tables, '\n')
end
g.Typelist, g.TypeList, g.typeList = g.typelist,
g.typelist, g.typelist
print(g.typelist())
-- return g
|
--[[
Modulo che crea l'elenco Pokémon per tipo
--]]
local g = {}
local data = require("Wikilib-data")
local tl = require('Typelist')
--[[
Sorting function for Entry:
Pokémon with two types are sorted first for
second type order, then for ndex
--]]
tl.FirstTypeEntry.__lt = function(a, b)
if (a.type2 == b.type2) then
return tl.FirstTypeEntry.super.__lt(a, b)
end
return table.search(data.typesOrder, a.type2)
< table.search(data.typesOrder, b.type2)
end
--[[
Funzione di interfaccia: ritorna l'elenco Pokémon
per tipo
--]]
g.typelist = function(frame)
local tables = {}
for k, type in ipairs(data.typesOrder) do
local typeName = type == 'coleot' and 'coleottero' or type
table.insert(tables, tl.makeTypeTable(typeName, tl.MonoTypeEntry))
table.insert(tables, tl.makeTypeTable(type, tl.FirstTypeEntry, tl.Entry.makeHeader(typeName, 3, 'come tipo primario')))
end
return table.concat(tables, '\n')
end
g.Typelist, g.TypeList, g.typeList = g.typelist,
g.typelist, g.typelist
print(g.typelist())
-- return g
|
Fix in header level
|
Fix in header level
|
Lua
|
cc0-1.0
|
pokemoncentral/wiki-lua-modules
|
356b89e5defb7e7114321a1c3ef80c032789a477
|
project_files/cinematic_editor.lua
|
project_files/cinematic_editor.lua
|
fileToRender = "../project_files/testspheres.lua"
keyframeFile = "../project_files/cinematic_keyframes.kf"
function trafo(str)
local newcontent = str:gsub("mmCreateView%(.-%)", "")
newcontent = newcontent:gsub("mmCreateModule%(\"View.-%)", "")
newcontent = newcontent:gsub("mmCreateCall%(\"CallRenderView.-%)", "")
local viewname, viewclass, viewmoduleinst = str:match(
'%(%s*[\"\']([^\"\']+)[\"\']%s*,%s*[\"\']([^\"\']+)[\"\']%s*,%s*[\"\']([^\"\']+)[\"\']%s*%)')
print("viewname = " .. viewname)
print("viewclass = " .. viewclass)
print("viewmoduleinst = " .. viewmoduleinst)
newcontent = newcontent:gsub('mmCreateCall%([\"\']CallRender3D[\'\"],%s*[\'\"]'
.. '.-' .. viewmoduleinst .. '::rendering[\'\"],([^,]+)%)', 'mmCreateCall("CallRender3D", "::ReplacementRenderer1::renderer",%1)'
.. "\n" .. 'mmCreateCall("CallRender3D", "::ReplacementRenderer2::renderer",%1)')
return newcontent
end
local content = mmReadTextFile(fileToRender, trafo)
print("read: " .. content)
code = load(content)
code()
mmCreateView("testeditor", "GUIView", "::GUIView1")
mmCreateModule("SplitView", "::SplitView1")
mmSetParamValue("::SplitView1::split.orientation", "1")
mmSetParamValue("::SplitView1::split.pos", "0.65")
mmSetParamValue("::SplitView1::split.colour", "gray")
mmCreateModule("SplitView", "::SplitView2")
mmSetParamValue("::SplitView2::split.pos", "0.55")
mmSetParamValue("::SplitView2::split.colour", "gray")
mmCreateModule("KeyframeKeeper", "::KeyframeKeeper1")
mmSetParamValue("::KeyframeKeeper1::storage::01_filename", keyframeFile)
mmCreateModule("View2D", "::View2D1")
mmSetParamValue("::View2D1::backCol", "black")
mmSetParamValue("::View2D1::resetViewOnBBoxChange", "True")
mmCreateModule("View3D", "::View3D1")
mmSetParamValue("::View3D1::backCol", "black")
mmSetParamValue("::View3D1::bboxCol", "gray")
mmCreateModule("TimeLineRenderer", "::TimeLineRenderer1")
mmCreateModule("CinematicRenderer", "::CinematicRenderer1")
mmCreateModule("CinematicView", "::CinematicView1")
mmSetParamValue("::CinematicView1::backCol", "grey")
mmSetParamValue("::CinematicView1::bboxCol", "white")
mmSetParamValue("::CinematicView1::07_fps", "24")
mmSetParamValue("::CinematicView1::stereo::projection", "2")
mmCreateModule("ReplacementRenderer", "::ReplacementRenderer1")
mmSetParamValue("::ReplacementRenderer1::03_replacmentKeyAssign", "6")
mmSetParamValue("::ReplacementRenderer1::01_replacementRendering", "on")
mmCreateModule("ReplacementRenderer", "::ReplacementRenderer2")
mmSetParamValue("::ReplacementRenderer2::03_replacmentKeyAssign", "5")
mmSetParamValue("::ReplacementRenderer2::01_replacementRendering", "off")
mmCreateCall("CallRenderView", "::GUIView1::renderview", "::SplitView1::render")
mmCreateCall("CallRenderView", "::SplitView1::render1", "::SplitView2::render")
mmCreateCall("CallRenderView", "::SplitView1::render2", "::View2D1::render")
mmCreateCall("CallRenderView", "::SplitView2::render1", "::View3D1::render")
mmCreateCall("CallCinematicCamera", "::TimeLineRenderer1::getkeyframes", "::KeyframeKeeper1::scene3D")
mmCreateCall("CallRender3D", "::View3D1::rendering", "::CinematicRenderer1::rendering")
mmCreateCall("CallCinematicCamera", "::CinematicRenderer1::keyframeKeeper", "::KeyframeKeeper1::scene3D")
mmCreateCall("CallRender3D", "::CinematicRenderer1::renderer", "::ReplacementRenderer1::rendering")
mmCreateCall("CallRender2D", "::View2D1::rendering", "::TimeLineRenderer1::rendering")
mmCreateCall("CallRenderView", "::SplitView2::render2", "::CinematicView1::render")
mmCreateCall("CallCinematicCamera", "::CinematicView1::keyframeKeeper", "::KeyframeKeeper1::scene3D")
mmCreateCall("CallRender3D", "::CinematicView1::rendering", "::ReplacementRenderer2::rendering")
|
fileToRender = "../project_files/testspheres.lua"
keyframeFile = "../project_files/cinematic_keyframes.kf"
function trafo(str)
-- Break if SplitView or CinematicView occure anywhere in the project
local startpos, endpos, word = str:find("SplitView")
if not (startpos == nil) then
print( "lua ERROR: Cinematic Editor can not be used with projects containing \"SplitView\"." )
return ""
end
startpos, endpos, word = str:find("CinematicView")
if not (startpos == nil) then
print( "lua ERROR: Cinematic Editor can not be used with projects containing \"CinematicView\"." )
return ""
end
local viewclass, viewmoduleinst
startpos, endpos, word = str:find("mmCreateView%(.-,%s*[\"\']([^\"\']+)[\"\']%s*,.-%)")
if word == "GUIView" then
print( "lua INFO: Found \"GUIView\" as head view." )
startpos, endpos, word = str:find("mmCreateModule%(.-View.-%)")
local substring = str:sub(startpos, endpos)
viewclass, viewmoduleinst = substring:match(
'mmCreateModule%(%s*[\"\']([^\"\']+)[\"\']%s*,%s*[\"\']([^\"\']+)[\"\']%s*%)')
else
viewclass, viewmoduleinst = str:match(
'mmCreateView%(.-,%s*[\"\']([^\"\']+)[\"\']%s*,%s*[\"\']([^\"\']+)[\"\']%s*%)')
end
print("lua INFO: View Class = " .. viewclass)
print("lua INFO: View Module Instance = " .. viewmoduleinst)
local newcontent = str:gsub("mmCreateView%(.-%)", "")
newcontent = newcontent:gsub("mmCreateModule%(.-\"View.-%)", "")
newcontent = newcontent:gsub("mmCreateCall%(\"CallRenderView.-%)", "")
newcontent = newcontent:gsub('mmCreateCall%([\"\']CallRender3D[\'\"],%s*[\'\"]'
.. '.-' .. viewmoduleinst .. '::rendering[\'\"],([^,]+)%)', 'mmCreateCall("CallRender3D", "::ReplacementRenderer1::renderer",%1)'
.. "\n" .. 'mmCreateCall("CallRender3D", "::ReplacementRenderer2::renderer",%1)')
return newcontent
end
local content = mmReadTextFile(fileToRender, trafo)
print("lua INFO: Transformed Include Project File =\n" .. content .. "\n\n")
code = load(content)
code()
mmCreateView("testeditor", "GUIView", "::GUIView1")
mmCreateModule("SplitView", "::SplitView1")
mmSetParamValue("::SplitView1::split.orientation", "1")
mmSetParamValue("::SplitView1::split.pos", "0.65")
mmSetParamValue("::SplitView1::split.colour", "gray")
mmCreateModule("SplitView", "::SplitView2")
mmSetParamValue("::SplitView2::split.pos", "0.55")
mmSetParamValue("::SplitView2::split.colour", "gray")
mmCreateModule("KeyframeKeeper", "::KeyframeKeeper1")
mmSetParamValue("::KeyframeKeeper1::storage::01_filename", keyframeFile)
mmCreateModule("View2D", "::View2D1")
mmSetParamValue("::View2D1::backCol", "black")
mmSetParamValue("::View2D1::resetViewOnBBoxChange", "True")
mmCreateModule("View3D", "::View3D1")
mmSetParamValue("::View3D1::backCol", "black")
mmSetParamValue("::View3D1::bboxCol", "gray")
mmCreateModule("TimeLineRenderer", "::TimeLineRenderer1")
mmCreateModule("CinematicRenderer", "::CinematicRenderer1")
mmCreateModule("CinematicView", "::CinematicView1")
mmSetParamValue("::CinematicView1::backCol", "grey")
mmSetParamValue("::CinematicView1::bboxCol", "white")
mmSetParamValue("::CinematicView1::07_fps", "24")
mmSetParamValue("::CinematicView1::stereo::projection", "2")
mmCreateModule("ReplacementRenderer", "::ReplacementRenderer1")
mmSetParamValue("::ReplacementRenderer1::03_replacmentKeyAssign", "4")
mmSetParamValue("::ReplacementRenderer1::01_replacementRendering", "on")
mmCreateModule("ReplacementRenderer", "::ReplacementRenderer2")
mmSetParamValue("::ReplacementRenderer2::03_replacmentKeyAssign", "3")
mmSetParamValue("::ReplacementRenderer2::01_replacementRendering", "off")
mmCreateCall("CallRenderView", "::GUIView1::renderview", "::SplitView1::render")
mmCreateCall("CallRenderView", "::SplitView1::render1", "::SplitView2::render")
mmCreateCall("CallRenderView", "::SplitView1::render2", "::View2D1::render")
mmCreateCall("CallRenderView", "::SplitView2::render1", "::View3D1::render")
mmCreateCall("CallCinematicCamera", "::TimeLineRenderer1::getkeyframes", "::KeyframeKeeper1::scene3D")
mmCreateCall("CallRender3D", "::View3D1::rendering", "::CinematicRenderer1::rendering")
mmCreateCall("CallCinematicCamera", "::CinematicRenderer1::keyframeKeeper", "::KeyframeKeeper1::scene3D")
mmCreateCall("CallRender3D", "::CinematicRenderer1::renderer", "::ReplacementRenderer1::rendering")
mmCreateCall("CallRender2D", "::View2D1::rendering", "::TimeLineRenderer1::rendering")
mmCreateCall("CallRenderView", "::SplitView2::render2", "::CinematicView1::render")
mmCreateCall("CallCinematicCamera", "::CinematicView1::keyframeKeeper", "::KeyframeKeeper1::scene3D")
mmCreateCall("CallRender3D", "::CinematicView1::rendering", "::ReplacementRenderer2::rendering")
|
fixed cinematic_editor example file
|
fixed cinematic_editor example file
|
Lua
|
bsd-3-clause
|
UniStuttgart-VISUS/megamol,UniStuttgart-VISUS/megamol,UniStuttgart-VISUS/megamol,UniStuttgart-VISUS/megamol,UniStuttgart-VISUS/megamol
|
bb084aaab297e4acc6becf10a69f698c87f2cb25
|
scripts/tools/gcc.lua
|
scripts/tools/gcc.lua
|
-- Copyright 2010 Andreas Fredriksson
--
-- This file is part of Tundra.
--
-- Tundra is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- Tundra is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with Tundra. If not, see <http://www.gnu.org/licenses/>.
local env = ...
-- load the generic C toolset first
load_toolset("generic-cpp", env)
local native = require("tundra.native")
env:set_many {
["NATIVE_SUFFIXES"] = { ".c", ".cpp", ".cc", ".cxx", ".a", ".o" },
["OBJECTSUFFIX"] = ".o",
["LIBSUFFIX"] = ".a",
["CC"] = "gcc",
["C++"] = "g++",
["LIB"] = "ar",
["LD"] = "gcc",
["_OS_CCOPTS"] = "",
["CCOPTS"] = "-Wall",
["CCCOM"] = "$(CC) $(_OS_CCOPTS) -c $(CPPDEFS:p-D) $(CPPPATH:f:p-I) $(CCOPTS) $(CCOPTS_$(CURRENT_VARIANT:u)) -o $(@) $(<)",
["CXXCOM"] = "$(CCCOM)",
["PROGOPTS"] = "",
["PROGCOM"] = "$(LD) $(PROGOPTS) $(LIBS:p-l) -o $(@) $(<)",
["LIBOPTS"] = "",
["LIBCOM"] = "$(LIB) -r $(LIBOPTS) $(@) $(<)",
}
|
-- Copyright 2010 Andreas Fredriksson
--
-- This file is part of Tundra.
--
-- Tundra is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- Tundra is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with Tundra. If not, see <http://www.gnu.org/licenses/>.
local env = ...
-- load the generic C toolset first
load_toolset("generic-cpp", env)
local native = require("tundra.native")
env:set_many {
["NATIVE_SUFFIXES"] = { ".c", ".cpp", ".cc", ".cxx", ".a", ".o" },
["OBJECTSUFFIX"] = ".o",
["LIBSUFFIX"] = ".a",
["_GCC_BINPREFIX"] = "",
["CC"] = "$(_GCC_BINPREFIX)gcc",
["C++"] = "$(_GCC_BINPREFIX)g++",
["LIB"] = "$(_GCC_BINPREFIX)ar",
["LD"] = "$(_GCC_BINPREFIX)gcc",
["_OS_CCOPTS"] = "",
["CCOPTS"] = "-Wall",
["CCCOM"] = "$(CC) $(_OS_CCOPTS) -c $(CPPDEFS:p-D) $(CPPPATH:f:p-I) $(CCOPTS) $(CCOPTS_$(CURRENT_VARIANT:u)) -o $(@) $(<)",
["CXXCOM"] = "$(CCCOM)",
["PROGOPTS"] = "",
["PROGCOM"] = "$(LD) $(PROGOPTS) $(LIBS:p-l) -o $(@) $(<)",
["LIBOPTS"] = "",
["LIBCOM"] = "$(LIB) -r $(LIBOPTS) $(@) $(<)",
}
|
GCC: Support prefix to tools via (_GCC_BINPREFIX) as a convenience for cross compilation setups.
|
GCC: Support prefix to tools via (_GCC_BINPREFIX) as a convenience for cross compilation setups.
|
Lua
|
mit
|
bmharper/tundra,deplinenoise/tundra,deplinenoise/tundra,deplinenoise/tundra,bmharper/tundra,bmharper/tundra,bmharper/tundra
|
bb4ba9dc907433a940180045e8ab43f39eb06a71
|
github-contributions-widget/github-contributions-widget.lua
|
github-contributions-widget/github-contributions-widget.lua
|
-------------------------------------------------
-- Github Contributions Widget for Awesome Window Manager
-- Shows the contributions graph
-- More details could be found here:
-- https://github.com/streetturtle/awesome-wm-widgets/tree/master/github-contributions-widget
-- @author Pavel Makhov
-- @copyright 2020 Pavel Makhov
-------------------------------------------------
local awful = require("awful")
local wibox = require("wibox")
local beautiful = require("beautiful")
local GET_CONTRIBUTIONS_CMD = [[bash -c "curl -s https://github-contributions.now.sh/api/v1/%s | jq -r '[.contributions[] | select ( .date | strptime(\"%%Y-%%m-%%d\") | mktime < now)][:%s]| .[].color'"]]
-- in case github-contributions.now.sh stops working contributions can be scrapped from the github.com with the command below. Note that the order is reversed.
local GET_CONTRIBUTIONS_CMD_FALLBACK = [[bash -c "curl -s https://github.com/users/%s/contributions | grep -o '\" fill=\"\#[0-9a-fA-F]\{6\}\" da' | grep -o '\#[0-9a-fA-F]\{6\}'"]]
local github_contributions_widget = wibox.widget{
reflection = {
horizontal = true,
vertical = true,
},
widget = wibox.container.mirror
}
local function worker(args)
local args = args or {}
local username = args.username or 'streetturtle'
local days = args.days or 365
local empty_color = args.empty_color or beautiful.bg_normal
local with_border = args.with_border
local margin_top = args.margin_top or 1
if with_border == nil then with_border = true end
local function hex2rgb(hex)
if hex == '#ebedf0' then hex = empty_color end
hex = tostring(hex):gsub("#","")
return tonumber("0x" .. hex:sub(1, 2)),
tonumber("0x" .. hex:sub(3, 4)),
tonumber("0x" .. hex:sub(5, 6))
end
local function get_square(color)
local r, g, b = hex2rgb(color)
return wibox.widget{
fit = function(self, context, width, height)
return 3, 3
end,
draw = function(self, context, cr, width, height)
cr:set_source_rgb(r/255, g/255, b/255)
cr:rectangle(0, 0, with_border and 2 or 3, with_border and 2 or 3)
cr:fill()
end,
layout = wibox.widget.base.make_widget
}
end
local col = {layout = wibox.layout.fixed.vertical}
local row = {layout = wibox.layout.fixed.horizontal}
local a = 5 - os.date('%w')
for i = 0, a do
table.insert(col, get_square('#ebedf0'))
end
local update_widget = function(widget, stdout, _, _, _)
for colors in stdout:gmatch("[^\r\n]+") do
if a%7 == 0 then
table.insert(row, col)
col = {layout = wibox.layout.fixed.vertical}
end
table.insert(col, get_square(colors))
a = a + 1
end
github_contributions_widget:setup(
{
row,
top = margin_top,
layout = wibox.container.margin
}
)
end
awful.spawn.easy_async(string.format(GET_CONTRIBUTIONS_CMD, username, days),
function(stdout, stderr)
update_widget(github_contributions_widget, stdout)
end)
return github_contributions_widget
end
return setmetatable(github_contributions_widget, { __call = function(_, ...) return worker(...) end })
|
-------------------------------------------------
-- Github Contributions Widget for Awesome Window Manager
-- Shows the contributions graph
-- More details could be found here:
-- https://github.com/streetturtle/awesome-wm-widgets/tree/master/github-contributions-widget
-- @author Pavel Makhov
-- @copyright 2020 Pavel Makhov
-------------------------------------------------
local awful = require("awful")
local wibox = require("wibox")
local beautiful = require("beautiful")
local GET_CONTRIBUTIONS_CMD = [[bash -c "curl -s https://github-contributions.now.sh/api/v1/%s | jq -r '[.contributions[] | select ( .date | strptime(\"%%Y-%%m-%%d\") | mktime < now)][:%s]| .[].color'"]]
-- in case github-contributions.now.sh stops working contributions can be scrapped from the github.com with the command below. Note that the order is reversed.
local GET_CONTRIBUTIONS_CMD_FALLBACK = [[bash -c "curl -s https://github.com/users/%s/contributions | grep -o '\" fill=\"\#[0-9a-fA-F]\{6\}\" da' | grep -o '\#[0-9a-fA-F]\{6\}'"]]
local github_contributions_widget = wibox.widget{
reflection = {
horizontal = true,
vertical = true,
},
widget = wibox.container.mirror
}
local color_dict = {
color_calendar_graph_day_L4_bg = '#216e39',
color_calendar_graph_day_L3_bg = '#239a3b',
color_calendar_graph_day_L2_bg = '#7bc96f',
color_calendar_graph_day_L1_bg = '#c6e48b',
color_calendar_graph_day_bg = '#ebedf0',
}
local function worker(args)
local args = args or {}
local username = args.username or 'streetturtle'
local days = args.days or 365
local empty_color = args.empty_color or beautiful.bg_normal
local with_border = args.with_border
local margin_top = args.margin_top or 1
if with_border == nil then with_border = true end
local function hex2rgb(hex)
if hex == '#ebedf0' then hex = empty_color end
hex = tostring(hex):gsub("#","")
return tonumber("0x" .. hex:sub(1, 2)),
tonumber("0x" .. hex:sub(3, 4)),
tonumber("0x" .. hex:sub(5, 6))
end
local function get_square(color)
local r, g, b = hex2rgb(color)
return wibox.widget{
fit = function(self, context, width, height)
return 3, 3
end,
draw = function(self, context, cr, width, height)
cr:set_source_rgb(r/255, g/255, b/255)
cr:rectangle(0, 0, with_border and 2 or 3, with_border and 2 or 3)
cr:fill()
end,
layout = wibox.widget.base.make_widget
}
end
local col = {layout = wibox.layout.fixed.vertical}
local row = {layout = wibox.layout.fixed.horizontal}
local a = 6 - os.date('%w')
for i = 0, a do
table.insert(col, get_square('#ebedf0'))
end
local update_widget = function(widget, stdout, _, _, _)
for colors in stdout:gmatch("[^\r\n]+") do
if a%7 == 0 then
table.insert(row, col)
col = {layout = wibox.layout.fixed.vertical}
end
table.insert(col, get_square(color_dict[colors:match('var%(%-%-(.*)%)'):gsub('-', '_')]))
a = a + 1
end
github_contributions_widget:setup(
{
row,
top = margin_top,
layout = wibox.container.margin
}
)
end
awful.spawn.easy_async(string.format(GET_CONTRIBUTIONS_CMD, username, days),
function(stdout, stderr)
update_widget(github_contributions_widget, stdout)
end)
return github_contributions_widget
end
return setmetatable(github_contributions_widget, { __call = function(_, ...) return worker(...) end })
|
[github-contributions] quickfix of #203
|
[github-contributions] quickfix of #203
|
Lua
|
mit
|
streetturtle/awesome-wm-widgets,streetturtle/awesome-wm-widgets
|
8b508718f50a7ef9afad7188359251a534a16e8d
|
runTests.lua
|
runTests.lua
|
local Misc = require('misc')
local runSuiteOLD = function(suite)
for name, func in pairs(suite) do
-- io.write(' test \'' .. name .. '\'')
-- io.write(string.rep(' ', 30 - #name))
func()
-- io.write('[ok]\n')
-- local status, errmsg = pcall(func) -- TODO: use xpcall
-- if status == false then
-- io.write('[FAIL] : ', errmsg,'\n')
-- else
-- io.write('[ok]\n')
-- end
end
end
local runSuite = function(suite)
local badTests = {}
for name, func in pairs(suite) do
-- local status = pcall(func)
func()
if status == false then
table.insert(badTests, name)
end
end
if #badTests > 0 then
io.write('FAILS: ', Misc.dump(badTests), '\n')
end
end
local loadAndRunSuite = function(suiteName)
-- io.write('suite \'' .. suiteName .. '\'\n')
local suite = require(suiteName)
assert(suite ~= nil)
-- runSuite(suite)
runSuiteOLD(suite)
end
local runAllTestSuits = function(suits)
for _, suiteName in ipairs(suits) do
loadAndRunSuite(suiteName)
end
end
local main = function()
runAllTestSuits {
'testMisc',
'testLexerHelp',
'testLexer',
'testParser',
'testGenerator',
}
end
main()
|
local Misc = require('misc')
local runSuiteOLD = function(suite)
for name, func in pairs(suite) do
-- io.write(' test \'' .. name .. '\'')
-- io.write(string.rep(' ', 30 - #name))
func()
-- io.write('[ok]\n')
-- local status, errmsg = pcall(func) -- TODO: use xpcall
-- if status == false then
-- io.write('[FAIL] : ', errmsg,'\n')
-- else
-- io.write('[ok]\n')
-- end
end
end
local runSuite = function(suite)
local badTests = {}
for name, func in pairs(suite) do
-- local status = pcall(func)
func()
if status == false then
table.insert(badTests, name)
end
end
if #badTests > 0 then
io.write('FAILS: ', Misc.dump(badTests), '\n')
end
end
local loadAndRunSuite = function(suiteName)
-- io.write('suite \'' .. suiteName .. '\'\n')
local suite = require(suiteName)
assert(suite ~= nil)
-- runSuite(suite)
runSuiteOLD(suite)
end
local runAllTestSuits = function(suits)
for _, suiteName in ipairs(suits) do
loadAndRunSuite(suiteName)
end
end
local main = function()
runAllTestSuits {
'miscTest',
'lexerHelpTest',
'lexerTest',
'parserTest',
'generatorTest',
}
end
main()
|
Fixed filenames in runTests.lua
|
Fixed filenames in runTests.lua
|
Lua
|
mit
|
ozkriff/misery-lua
|
dcce8b8324c30c1d869f92610d97c48b41fbe856
|
lua/flowtracker2.lua
|
lua/flowtracker2.lua
|
local ffi = require "ffi"
local C = ffi.C
local memory = require "memory"
local flowtrackerlib = ffi.load("../build/flowtracker")
local hmap = require "hmap"
local lm = require "libmoon"
local log = require "log"
local pktLib = require "packet"
local eth = require "proto.ethernet"
local ip = require "proto.ip4"
local mod = {}
local flowtracker = {}
flowtracker.__index = flowtracker
function mod.new(args)
-- get size of stateType and round up to something
-- in C++: force template instantiation of several hashtable types (4,8,16,32,64,....?) bytes value?
-- get appropriate hashtables
-- Check parameters
for k,v in pairs(args) do
log:info("%s: %s", k, v)
end
if args.stateType == nil then
log:error("Module has no stateType")
end
local obj = setmetatable(args, flowtracker)
obj.table4 = hmap.createTable(ffi.sizeof(obj.stateType))
-- FIXME: ffi.new is garbage collected, can't be used here!
obj.defaultState = ffi.cast("void*", obj.defaultState or ffi.new(obj.stateType))
--lm.startTask("__FLOWTRACKER_SWAPPER", obj)
return obj
end
local function extractTuple(buf, tuple)
local ethPkt = pktLib.getEthernetPacket(buf)
if ethPkt.eth:getType() == eth.TYPE_IP then
-- actual L4 type doesn't matter
local parsedPkt = pktLib.getUdp4Packet(buf)
tuple.ip_dst = parsedPkt.ip4:getDst()
tuple.ip_src = parsedPkt.ip4:getSrc()
TTL = parsedPkt.ip4:getTTL()
if parsedPkt.ip4:getProtocol() == ip.PROTO_UDP then
tuple.port_dst = parsedPkt.udp:getDstPort()
tuple.port_src = parsedPkt.udp:getSrcPort()
tuple.proto = parsedPkt.ip4:getProtocol()
return true
elseif parsedPkt.ip4:getProtocol() == ip.PROTO_TCP then
-- port at the same position as UDP
tuple.port_dst = parsedPkt.udp:getDstPort()
tuple.port_src = parsedPkt.udp:getSrcPort()
tuple.proto = parsedPkt.ip4:getProtocol()
return true
elseif parsedPkt.ip4:getProtocol() == ip.PROTO_SCTP then
-- port at the same position as UDP
tuple.port_dst = parsedPkt.udp:getDstPort()
tuple.port_src = parsedPkt.udp:getSrcPort()
tuple.proto = parsedPkt.ip4:getProtocol()
return true
end
end
return false
end
function flowtracker:analyzer(userModule, queue)
userModule = loadfile(userModule)()
local handler4 = userModule.handleIp4Packet
assert(handler4)
local accessor = self.table4.newAccessor()
local bufs = memory.bufArray()
-- FIXME: would be nice to make this customizable as well?
local tuple = ffi.new("struct ipv4_5tuple")
while lm.running() do
local rx = queue:tryRecv(bufs)
for _, buf in ipairs(bufs) do
-- also handle IPv4/6/whatever
local success = extractTuple(buf, tuple)
if success then
-- copy-constructed
local isNew = self.table4:access(accessor, tuple)
local valuePtr = accessor:get()
if isNew then
C.memcpy(valuePtr, self.defaultState, ffi.sizeof(self.defaultState))
end
handler4(tuple, valuePtr, buf, isNew)
accessor:release()
end
end
bufs:free(rx)
end
accessor:free()
end
-- usual libmoon threading magic
__FLOWTRACKER_ANALYZER = flowtracker.analyzer
mod.analyzerTask = "__FLOWTRACKER_ANALYZER"
-- don't forget the usual magic in __serialize for thread-stuff
-- swapper goes here
return mod
|
local ffi = require "ffi"
local C = ffi.C
local memory = require "memory"
local flowtrackerlib = ffi.load("../build/flowtracker")
local hmap = require "hmap"
local lm = require "libmoon"
local log = require "log"
local pktLib = require "packet"
local eth = require "proto.ethernet"
local ip = require "proto.ip4"
local mod = {}
local flowtracker = {}
flowtracker.__index = flowtracker
function mod.new(args)
-- get size of stateType and round up to something
-- in C++: force template instantiation of several hashtable types (4,8,16,32,64,....?) bytes value?
-- get appropriate hashtables
-- Check parameters
for k, v in pairs(args) do
log:info("%s: %s", k, v)
end
if args.stateType == nil then
log:error("Module has no stateType")
end
local obj = setmetatable(args, flowtracker)
obj.table4 = hmap.createTable(ffi.sizeof(obj.stateType))
-- FIXME: ffi.new is garbage collected, can't be used here!
obj.defaultState = ffi.cast("void*", obj.defaultState or ffi.new(obj.stateType))
--lm.startTask("__FLOWTRACKER_SWAPPER", obj)
return obj
end
local function extractTuple(buf, tuple)
local ethPkt = pktLib.getEthernetPacket(buf)
if ethPkt.eth:getType() == eth.TYPE_IP then
-- actual L4 type doesn't matter
local parsedPkt = pktLib.getUdp4Packet(buf)
tuple.ip_dst = parsedPkt.ip4:getDst()
tuple.ip_src = parsedPkt.ip4:getSrc()
local TTL = parsedPkt.ip4:getTTL()
if parsedPkt.ip4:getProtocol() == ip.PROTO_UDP then
tuple.port_dst = parsedPkt.udp:getDstPort()
tuple.port_src = parsedPkt.udp:getSrcPort()
tuple.proto = parsedPkt.ip4:getProtocol()
return true
elseif parsedPkt.ip4:getProtocol() == ip.PROTO_TCP then
-- port at the same position as UDP
tuple.port_dst = parsedPkt.udp:getDstPort()
tuple.port_src = parsedPkt.udp:getSrcPort()
tuple.proto = parsedPkt.ip4:getProtocol()
return true
elseif parsedPkt.ip4:getProtocol() == ip.PROTO_SCTP then
-- port at the same position as UDP
tuple.port_dst = parsedPkt.udp:getDstPort()
tuple.port_src = parsedPkt.udp:getSrcPort()
tuple.proto = parsedPkt.ip4:getProtocol()
return true
end
end
return false
end
function flowtracker:analyzer(userModule, queue)
userModule = loadfile(userModule)()
local handler4 = userModule.handleIp4Packet
assert(handler4)
local accessor = self.table4.newAccessor()
local bufs = memory.bufArray()
-- FIXME: would be nice to make this customizable as well?
local tuple = ffi.new("struct ipv4_5tuple")
while lm.running() do
local rx = queue:tryRecv(bufs)
for _, buf in ipairs(bufs) do
-- also handle IPv4/6/whatever
local success = extractTuple(buf, tuple)
if success then
-- copy-constructed
local isNew = self.table4:access(accessor, tuple)
local valuePtr = accessor:get()
if isNew then
C.memcpy(valuePtr, self.defaultState, ffi.sizeof(self.defaultState))
end
handler4(tuple, valuePtr, buf, isNew)
accessor:release()
end
end
bufs:free(rx)
end
accessor:free()
end
-- usual libmoon threading magic
__FLOWTRACKER_ANALYZER = flowtracker.analyzer
mod.analyzerTask = "__FLOWTRACKER_ANALYZER"
-- don't forget the usual magic in __serialize for thread-stuff
-- swapper goes here
return mod
|
Fix formatting
|
Fix formatting
|
Lua
|
mit
|
emmericp/FlowScope
|
266dae7f16d92025adec4f02c1ff36218f40a942
|
lib/luvit/utils.lua
|
lib/luvit/utils.lua
|
--[[
Copyright 2012 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local table = require('table')
local utils = {}
local colors = {
black = "0;30",
red = "0;31",
green = "0;32",
yellow = "0;33",
blue = "0;34",
magenta = "0;35",
cyan = "0;36",
white = "0;37",
Bblack = "1;30",
Bred = "1;31",
Bgreen = "1;32",
Byellow = "1;33",
Bblue = "1;34",
Bmagenta = "1;35",
Bcyan = "1;36",
Bwhite = "1;37"
}
if not _G.useColors then
_G.useColors = true
end
function utils.color(color_name)
if _G.useColors then
return "\27[" .. (colors[color_name] or "0") .. "m"
else
return ""
end
end
function utils.colorize(color_name, string, reset_name)
return utils.color(color_name) .. string .. utils.color(reset_name)
end
local backslash, null, newline, carraige, tab, quote, quote2, obracket, cbracket
function utils.loadColors (n)
if n ~= nil then _G.useColors = n end
backslash = utils.colorize("Bgreen", "\\\\", "green")
null = utils.colorize("Bgreen", "\\0", "green")
newline = utils.colorize("Bgreen", "\\n", "green")
carraige = utils.colorize("Bgreen", "\\r", "green")
tab = utils.colorize("Bgreen", "\\t", "green")
quote = utils.colorize("Bgreen", '"', "green")
quote2 = utils.colorize("Bgreen", '"')
obracket = utils.colorize("white", '[')
cbracket = utils.colorize("white", ']')
end
utils.loadColors ()
function utils.dump(o, depth)
local t = type(o)
if t == 'string' then
return quote .. o:gsub("\\", backslash):gsub("%z", null):gsub("\n", newline):gsub("\r", carraige):gsub("\t", tab) .. quote2
end
if t == 'nil' then
return utils.colorize("Bblack", "nil")
end
if t == 'boolean' then
return utils.colorize("yellow", tostring(o))
end
if t == 'number' then
return utils.colorize("blue", tostring(o))
end
if t == 'userdata' then
return utils.colorize("magenta", tostring(o))
end
if t == 'thread' then
return utils.colorize("Bred", tostring(o))
end
if t == 'function' then
return utils.colorize("cyan", tostring(o))
end
if t == 'cdata' then
return utils.colorize("Bmagenta", tostring(o))
end
if t == 'table' then
if type(depth) == 'nil' then
depth = 0
end
if depth > 1 then
return utils.colorize("yellow", tostring(o))
end
local indent = (" "):rep(depth)
-- Check to see if this is an array
local is_array = true
local i = 1
for k,v in pairs(o) do
if not (k == i) then
is_array = false
end
i = i + 1
end
local first = true
local lines = {}
i = 1
local estimated = 0
for k,v in (is_array and ipairs or pairs)(o) do
local s
if is_array then
s = ""
else
if type(k) == "string" and k:find("^[%a_][%a%d_]*$") then
s = k .. ' = '
else
s = '[' .. utils.dump(k, 100) .. '] = '
end
end
s = s .. utils.dump(v, depth + 1)
lines[i] = s
estimated = estimated + #s
i = i + 1
end
if estimated > 200 then
return "{\n " .. indent .. table.concat(lines, ",\n " .. indent) .. "\n" .. indent .. "}"
else
return "{ " .. table.concat(lines, ", ") .. " }"
end
end
-- This doesn't happen right?
return tostring(o)
end
-- Replace print
function utils.print(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = tostring(arguments[i])
end
process.stdout:write(table.concat(arguments, "\t") .. "\n")
end
-- A nice global data dumper
function utils.prettyPrint(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = utils.dump(arguments[i])
end
process.stdout:write(table.concat(arguments, "\t") .. "\n")
end
-- Like p, but prints to stderr using blocking I/O for better debugging
function utils.debug(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = utils.dump(arguments[i])
end
process.stderr:write(table.concat(arguments, "\t") .. "\n")
end
function utils.bind(fun, self, ...)
local bind_args = {...}
return function(...)
local args = {...}
for i=#bind_args,1,-1 do
table.insert(args, 1, bind_args[i])
end
fun(self, unpack(args))
end
end
return utils
--print("nil", dump(nil))
--print("number", dump(42))
--print("boolean", dump(true), dump(false))
--print("string", dump("\"Hello\""), dump("world\nwith\r\nnewlines\r\t\n"))
--print("funct", dump(print))
--print("table", dump({
-- ["nil"] = nil,
-- ["8"] = 8,
-- ["number"] = 42,
-- ["boolean"] = true,
-- ["table"] = {age = 29, name="Tim"},
-- ["string"] = "Another String",
-- ["function"] = dump,
-- ["thread"] = coroutine.create(dump),
-- [print] = {{"deep"},{{"nesting"}},3,4,5},
-- [{1,2,3}] = {4,5,6}
--}))
|
--[[
Copyright 2012 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local table = require('table')
local utils = {}
local colors = {
black = "0;30",
red = "0;31",
green = "0;32",
yellow = "0;33",
blue = "0;34",
magenta = "0;35",
cyan = "0;36",
white = "0;37",
Bblack = "1;30",
Bred = "1;31",
Bgreen = "1;32",
Byellow = "1;33",
Bblue = "1;34",
Bmagenta = "1;35",
Bcyan = "1;36",
Bwhite = "1;37"
}
if utils._useColors == nil then
utils._useColors = true
end
function utils.color(color_name)
if utils._useColors then
return "\27[" .. (colors[color_name] or "0") .. "m"
else
return ""
end
end
function utils.colorize(color_name, string, reset_name)
return utils.color(color_name) .. string .. utils.color(reset_name)
end
local backslash, null, newline, carriage, tab, quote, quote2, obracket, cbracket
function utils.loadColors (n)
if n ~= nil then utils._useColors = n end
backslash = utils.colorize("Bgreen", "\\\\", "green")
null = utils.colorize("Bgreen", "\\0", "green")
newline = utils.colorize("Bgreen", "\\n", "green")
carriage = utils.colorize("Bgreen", "\\r", "green")
tab = utils.colorize("Bgreen", "\\t", "green")
quote = utils.colorize("Bgreen", '"', "green")
quote2 = utils.colorize("Bgreen", '"')
obracket = utils.colorize("white", '[')
cbracket = utils.colorize("white", ']')
end
utils.loadColors ()
function utils.dump(o, depth)
local t = type(o)
if t == 'string' then
return quote .. o:gsub("\\", backslash):gsub("%z", null):gsub("\n", newline):gsub("\r", carriage):gsub("\t", tab) .. quote2
end
if t == 'nil' then
return utils.colorize("Bblack", "nil")
end
if t == 'boolean' then
return utils.colorize("yellow", tostring(o))
end
if t == 'number' then
return utils.colorize("blue", tostring(o))
end
if t == 'userdata' then
return utils.colorize("magenta", tostring(o))
end
if t == 'thread' then
return utils.colorize("Bred", tostring(o))
end
if t == 'function' then
return utils.colorize("cyan", tostring(o))
end
if t == 'cdata' then
return utils.colorize("Bmagenta", tostring(o))
end
if t == 'table' then
if type(depth) == 'nil' then
depth = 0
end
if depth > 1 then
return utils.colorize("yellow", tostring(o))
end
local indent = (" "):rep(depth)
-- Check to see if this is an array
local is_array = true
local i = 1
for k,v in pairs(o) do
if not (k == i) then
is_array = false
end
i = i + 1
end
local first = true
local lines = {}
i = 1
local estimated = 0
for k,v in (is_array and ipairs or pairs)(o) do
local s
if is_array then
s = ""
else
if type(k) == "string" and k:find("^[%a_][%a%d_]*$") then
s = k .. ' = '
else
s = '[' .. utils.dump(k, 100) .. '] = '
end
end
s = s .. utils.dump(v, depth + 1)
lines[i] = s
estimated = estimated + #s
i = i + 1
end
if estimated > 200 then
return "{\n " .. indent .. table.concat(lines, ",\n " .. indent) .. "\n" .. indent .. "}"
else
return "{ " .. table.concat(lines, ", ") .. " }"
end
end
-- This doesn't happen right?
return tostring(o)
end
-- Replace print
function utils.print(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = tostring(arguments[i])
end
process.stdout:write(table.concat(arguments, "\t") .. "\n")
end
-- A nice global data dumper
function utils.prettyPrint(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = utils.dump(arguments[i])
end
process.stdout:write(table.concat(arguments, "\t") .. "\n")
end
-- Like p, but prints to stderr using blocking I/O for better debugging
function utils.debug(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = utils.dump(arguments[i])
end
process.stderr:write(table.concat(arguments, "\t") .. "\n")
end
function utils.bind(fun, self, ...)
local bind_args = {...}
return function(...)
local args = {...}
for i=#bind_args,1,-1 do
table.insert(args, 1, bind_args[i])
end
fun(self, unpack(args))
end
end
return utils
--print("nil", dump(nil))
--print("number", dump(42))
--print("boolean", dump(true), dump(false))
--print("string", dump("\"Hello\""), dump("world\nwith\r\nnewlines\r\t\n"))
--print("funct", dump(print))
--print("table", dump({
-- ["nil"] = nil,
-- ["8"] = 8,
-- ["number"] = 42,
-- ["boolean"] = true,
-- ["table"] = {age = 29, name="Tim"},
-- ["string"] = "Another String",
-- ["function"] = dump,
-- ["thread"] = coroutine.create(dump),
-- [print] = {{"deep"},{{"nesting"}},3,4,5},
-- [{1,2,3}] = {4,5,6}
--}))
|
Do not polute global namespace with useColors and fix typo
|
Do not polute global namespace with useColors and fix typo
|
Lua
|
apache-2.0
|
boundary/luvit,rjeli/luvit,sousoux/luvit,GabrielNicolasAvellaneda/luvit-upstream,zhaozg/luvit,boundary/luvit,DBarney/luvit,boundary/luvit,AndrewTsao/luvit,bsn069/luvit,zhaozg/luvit,GabrielNicolasAvellaneda/luvit-upstream,bsn069/luvit,sousoux/luvit,GabrielNicolasAvellaneda/luvit-upstream,rjeli/luvit,boundary/luvit,kaustavha/luvit,sousoux/luvit,boundary/luvit,connectFree/lev,sousoux/luvit,boundary/luvit,AndrewTsao/luvit,rjeli/luvit,kaustavha/luvit,luvit/luvit,luvit/luvit,sousoux/luvit,rjeli/luvit,bsn069/luvit,GabrielNicolasAvellaneda/luvit-upstream,sousoux/luvit,kaustavha/luvit,AndrewTsao/luvit,DBarney/luvit,DBarney/luvit,connectFree/lev,DBarney/luvit
|
d3af3982feef3dbd9fdd59b5ff1c1d0158ac74f1
|
spec/02-integration/06_error_handling_spec.lua
|
spec/02-integration/06_error_handling_spec.lua
|
local utils = require "spec.spec_utils"
local cassandra = require "cassandra"
describe("error handling", function()
local _hosts, _shm
setup(function()
_hosts, _shm = utils.ccm_start()
end)
describe("spawn_cluster()", function()
it("should return option errors", function()
local options = require "cassandra.options"
spy.on(options, "parse_cluster")
finally(function()
options.parse_cluster:revert()
end)
local ok, err = cassandra.spawn_cluster()
assert.False(ok)
assert.spy(options.parse_cluster).was.called()
assert.equal("shm is required for spawning a cluster/session", err)
ok, err = cassandra.spawn_cluster {}
assert.False(ok)
assert.equal("shm is required for spawning a cluster/session", err)
ok, err = cassandra.spawn_cluster {shm = ""}
assert.False(ok)
assert.equal("shm must be a valid string", err)
end)
it("should return an error when no contact_point is valid", function()
cassandra.set_log_level("QUIET")
finally(function()
cassandra.set_log_level("ERR")
end)
local contact_points = {"0.0.0.1", "0.0.0.2", "0.0.0.3"}
local ok, err = cassandra.spawn_cluster {
shm = "test",
contact_points = contact_points
}
assert.is_table(err)
assert.False(ok)
assert.equal("NoHostAvailableError", err.type)
end)
end)
describe("spawn_session()", function()
it("should return options errors", function()
local options = require "cassandra.options"
spy.on(options, "parse_session")
finally(function()
options.parse_session:revert()
end)
local session, err = cassandra.spawn_session()
assert.falsy(session)
assert.spy(options.parse_session).was.called()
assert.equal("shm is required for spawning a cluster/session", err)
end)
it("should error when spawning a session without contact_points not cluster", function()
local shm = "session_without_cluster_nor_contact_points"
local session, err = cassandra.spawn_session {
shm = shm
}
assert.is_table(err)
assert.falsy(session)
assert.equal("DriverError", err.type)
assert.equal("Options must contain contact_points to spawn session, or spawn a cluster in the init phase.", err.message)
end)
end)
describe("execute()", function()
local session
setup(function()
local err
session, err = cassandra.spawn_session {
shm = _shm,
contact_points = _hosts
}
assert.falsy(err)
end)
teardown(function()
session:shutdown()
end)
it("should handle CQL errors", function()
local res, err = session:execute("CAN I HAZ CQL")
assert.falsy(res)
assert.is_table(err)
assert.equal("ResponseError", err.type)
res, err = session:execute("SELECT * FROM system.local WHERE key = ?")
assert.falsy(res)
assert.is_table(err)
assert.equal("ResponseError", err.type)
end)
end)
describe("shm errors", function()
it("should trigger a cluster refresh if the hosts are not available anymore", function()
local shm = "test_shm_errors"
local cache = require "cassandra.cache"
local dict = cache.get_dict(shm)
assert.is_table(dict)
local ok, err = cassandra.spawn_cluster {
shm = shm,
contact_points = _hosts
}
assert.falsy(err)
assert.True(ok)
assert.is_table(cache.get_hosts(shm))
-- erase hosts from the cache
dict:delete("hosts")
assert.falsy(cache.get_hosts(shm))
-- attempt session create
local session, err = cassandra.spawn_session {
shm = shm,
contact_points = _hosts
}
assert.falsy(err)
-- attempt query
local rows, err = session:execute("SELECT * FROM system.local")
assert.falsy(err)
assert.is_table(rows)
assert.equal(1, #rows)
end)
end)
end)
|
local utils = require "spec.spec_utils"
local cassandra = require "cassandra"
describe("error handling", function()
local _hosts, _shm
setup(function()
_hosts, _shm = utils.ccm_start()
end)
describe("spawn_cluster()", function()
it("should return option errors", function()
local options = require "cassandra.options"
spy.on(options, "parse_cluster")
finally(function()
options.parse_cluster:revert()
end)
local ok, err = cassandra.spawn_cluster()
assert.False(ok)
assert.spy(options.parse_cluster).was.called()
assert.equal("shm is required for spawning a cluster/session", err)
ok, err = cassandra.spawn_cluster {}
assert.False(ok)
assert.equal("shm is required for spawning a cluster/session", err)
ok, err = cassandra.spawn_cluster {shm = ""}
assert.False(ok)
assert.equal("shm must be a valid string", err)
end)
it("should return an error when no contact_point is valid", function()
local contact_points = {"0.0.0.1", "0.0.0.2", "0.0.0.3"}
local ok, err = cassandra.spawn_cluster {
shm = "test",
contact_points = contact_points
}
assert.is_table(err)
assert.False(ok)
assert.equal("NoHostAvailableError", err.type)
end)
end)
describe("spawn_session()", function()
it("should return options errors", function()
local options = require "cassandra.options"
spy.on(options, "parse_session")
finally(function()
options.parse_session:revert()
end)
local session, err = cassandra.spawn_session()
assert.falsy(session)
assert.spy(options.parse_session).was.called()
assert.equal("shm is required for spawning a cluster/session", err)
end)
it("should error when spawning a session without contact_points not cluster", function()
local shm = "session_without_cluster_nor_contact_points"
local session, err = cassandra.spawn_session {
shm = shm
}
assert.is_table(err)
assert.falsy(session)
assert.equal("DriverError", err.type)
assert.equal("Options must contain contact_points to spawn session, or spawn a cluster in the init phase.", err.message)
end)
end)
describe("execute()", function()
local session
setup(function()
local err
session, err = cassandra.spawn_session {
shm = _shm,
contact_points = _hosts
}
assert.falsy(err)
end)
teardown(function()
session:shutdown()
end)
it("should handle CQL errors", function()
local res, err = session:execute("CAN I HAZ CQL")
assert.falsy(res)
assert.is_table(err)
assert.equal("ResponseError", err.type)
res, err = session:execute("SELECT * FROM system.local WHERE key = ?")
assert.falsy(res)
assert.is_table(err)
assert.equal("ResponseError", err.type)
end)
end)
describe("shm errors", function()
it("should trigger a cluster refresh if the hosts are not available anymore", function()
local shm = "test_shm_errors"
local cache = require "cassandra.cache"
local dict = cache.get_dict(shm)
assert.is_table(dict)
local ok, err = cassandra.spawn_cluster {
shm = shm,
contact_points = _hosts
}
assert.falsy(err)
assert.True(ok)
assert.is_table(cache.get_hosts(shm))
-- erase hosts from the cache
dict:delete("hosts")
assert.falsy(cache.get_hosts(shm))
-- attempt session create
local session, err = cassandra.spawn_session {
shm = shm,
contact_points = _hosts
}
assert.falsy(err)
-- attempt query
local rows, err = session:execute("SELECT * FROM system.local")
assert.falsy(err)
assert.is_table(rows)
assert.equal(1, #rows)
end)
end)
end)
|
fix(test) remove set_log_lvl call
|
fix(test) remove set_log_lvl call
|
Lua
|
mit
|
thibaultCha/lua-cassandra,thibaultCha/lua-cassandra
|
bad6c7ef3844bcc0ee17714ca412efcc8832eb4d
|
Main/Generators/Porg.lua
|
Main/Generators/Porg.lua
|
-- Physical Organizer. Creates unit targets for Elements.
require "Cpp/Common";
local UnitTarget = require "Macaroni.Model.Project.UnitTarget";
local TypeNames = Macaroni.Model.TypeNames;
-- Parses NodeSpace for a library.
-- Each element that does not have an For each element which deserves one
-- has a new Unit target created for it with the name of the element Node.
-- Later the units will be generated into C++ source with the Cpp plugin.
Generator =
{
findOrCreateTarget = function(self, path, element)
local t = self.defaultTarget:Unit(element.Node.FullName, true);
local fileName = element.Node:GetPrettyFullName("/")
t:SetHFileAsUnknownRelativePath(fileName .. ".h")
t:SetCppFileAsUnknownRelativePath(fileName .. ".cpp")
return t;
end,
parseElement = function(self, path, element)
if self:shouldHaveTarget(element) then
local newTarget = self:findOrCreateTarget(path, element)
element:SwitchOwner(newTarget);
end
end,
shouldHaveTarget = function(self, element)
if element.TypeName == "Extern" then
return false;
end
--if (element.Node.HFilePath ~= nil or (not element.RequiresCppFile)) then
if (element.Node.HFilePath ~= nil) then
return false;
end
-- If this element was adopted then it doesn't handle its own
-- unit no matter what.
if element.Node.AdoptedHome ~= nil then
return false;
end
-- Inner classes or typedefs owned by classes should be defined in
-- the class generators. Logically they are distinct, but physically
-- speaking its all one giant unit.
local parentNode = element.Node.Node;
if (parentNode ~= nil and parentNode.TypeName == TypeNames.Class) then
-- If this is nested in a class, lets forget about it.
return false;
end
return true;
end,
};
function Generate(libTarget, path)
local generator = Generator;
generator.defaultTarget = libTarget;
local elements = libTarget:CreateElementList();
for i=1, #elements do
local element = elements[i]
if (element:OwnedBy(libTarget)) then
generator:parseElement(path, element)
end
end
end
function GetMethod(name)
if name == "Generate" then
return
{
Describe = function(args)
args.output.WriteLine("Generate Targets for Nodes in "
.. tostring(args.target) .. ".");
end,
Install = function(args)
-- By default, Macaroni itself will copy all artifacts
-- and source to the destination directory "Source".
end,
Run = function(args)
Generate(args.target, args.path)
end
}
end
return nil;
end
|
-- Physical Organizer. Creates unit targets for Elements.
require "Cpp/Common";
local UnitTarget = require "Macaroni.Model.Project.UnitTarget";
local TypeNames = Macaroni.Model.TypeNames;
-- Parses NodeSpace for a library.
-- Each element that does not have an For each element which deserves one
-- has a new Unit target created for it with the name of the element Node.
-- Later the units will be generated into C++ source with the Cpp plugin.
Generator =
{
findOrCreateTarget = function(self, path, element)
local t = self.defaultTarget:Unit(element.Node.FullName, true);
local fileName = element.Node:GetPrettyFullName("/")
t:SetHFileAsUnknownRelativePath(fileName .. ".h")
t:SetCppFileAsUnknownRelativePath(fileName .. ".cpp")
return t;
end,
parseElement = function(self, path, element)
if self:shouldHaveTarget(element) then
local newTarget = self:findOrCreateTarget(path, element)
element:SwitchOwner(newTarget);
end
end,
shouldHaveTarget = function(self, element)
if element.TypeName ~= "Class" and element.TypeName ~= "Typedef"
and element.TypeName ~= "Enum" then
return false;
end
--if (element.Node.HFilePath ~= nil or (not element.RequiresCppFile)) then
if (element.Node.HFilePath ~= nil) then
return false;
end
-- If this element was adopted then it doesn't handle its own
-- unit no matter what.
if element.Node.AdoptedHome ~= nil then
return false;
end
-- Inner classes or typedefs owned by classes should be defined in
-- the class generators. Logically they are distinct, but physically
-- speaking its all one giant unit.
local parentNode = element.Node.Node;
if (parentNode ~= nil and parentNode.TypeName == TypeNames.Class) then
-- If this is nested in a class, lets forget about it.
return false;
end
return true;
end,
};
function Generate(libTarget, path)
local generator = Generator;
generator.defaultTarget = libTarget;
local elements = libTarget:CreateElementList();
for i=1, #elements do
local element = elements[i]
if (element:OwnedBy(libTarget)) then
generator:parseElement(path, element)
end
end
end
function GetMethod(name)
if name == "Generate" then
return
{
Describe = function(args)
args.output.WriteLine("Generate Targets for Nodes in "
.. tostring(args.target) .. ".");
end,
Install = function(args)
-- By default, Macaroni itself will copy all artifacts
-- and source to the destination directory "Source".
end,
Run = function(args)
Generate(args.target, args.path)
end
}
end
return nil;
end
|
Fix Porg's overzealous generation
|
Fix Porg's overzealous generation
Porg was generating stuff for namespaces which was dumb.
|
Lua
|
apache-2.0
|
TimSimpson/Macaroni,TimSimpson/Macaroni,TimSimpson/Macaroni,TimSimpson/Macaroni,TimSimpson/Macaroni
|
c4ccd2cdecc630a994ab73b49eaec79d9deeb7de
|
test_scripts/Polices/appID_Management/157_ATF_P_TC_Register_App_Interface_Without_Data_Consent_Assign_pre_DataConsent_Policies.lua
|
test_scripts/Polices/appID_Management/157_ATF_P_TC_Register_App_Interface_Without_Data_Consent_Assign_pre_DataConsent_Policies.lua
|
------------- --------------------------------------------------------------------------------
-- Requirement summary:
-- [RegisterAppInterface] Without data consent, assign "pre_DataConsent" policies
-- to the application which appID does not exist in LocalPT
--
-- Description:
-- SDL should assign "pre_DataConsent" permissions in case the application registers
-- (sends RegisterAppInterface request) with the appID that does not exist in Local Policy Table,
-- and Data Consent either has been denied or has not yet been asked for the device
-- this application registers from.
--
-- Preconditions:
-- 1. Register new app from unconsented device. -> PTU is not triggered.
--
-- Steps:
-- 1. Trigger PTU with user request from HMI
-- Expected result:
-- 1. sdl_snapshot is created.
-- 2. Application is added to policy and assigns pre_DataConsent group
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--[[ Required Shared libraries ]]
local commonFunctions = require("user_modules/shared_testcases/commonFunctions")
local commonSteps = require("user_modules/shared_testcases/commonSteps")
local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable')
local testCasesForPolicyTableSnapshot = require('user_modules/shared_testcases/testCasesForPolicyTableSnapshot')
--[[ General Precondition before ATF start ]]
commonSteps:DeleteLogsFileAndPolicyTable()
--[[ General Settings for configuration ]]
Test = require("connecttest")
require("user_modules/AppTypes")
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test:Preconfition_trigger_user_request_update_from_HMI()
testCasesForPolicyTable:trigger_user_request_update_from_HMI(self)
local app_permission = testCasesForPolicyTableSnapshot:get_data_from_PTS("app_policies."..config.application1.registerAppInterfaceParams.appID)
if(app_permission ~= "pre_DataConsent") then
self:FailTestCase("Assigned app permissions is not for pre_DataConsent, real: " ..app_permission)
end
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test.Postcondition_Stop()
StopSDL()
end
return Test
|
------------- --------------------------------------------------------------------------------
-- Requirement summary:
-- [RegisterAppInterface] Without data consent, assign "pre_DataConsent" policies
-- to the application which appID does not exist in LocalPT
--
-- Description:
-- SDL should assign "pre_DataConsent" permissions in case the application registers
-- (sends RegisterAppInterface request) with the appID that does not exist in Local Policy Table,
-- and Data Consent either has been denied or has not yet been asked for the device
-- this application registers from.
--
-- Preconditions:
-- 1. Register new app from unconsented device. -> PTU is not triggered.
--
-- Steps:
-- 1. Trigger PTU with user request from HMI
-- Expected result:
-- 1. sdl_snapshot is created.
-- 2. Application is added to policy and assigns pre_DataConsent group
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--[[ Required Shared libraries ]]
local commonFunctions = require("user_modules/shared_testcases/commonFunctions")
local commonSteps = require("user_modules/shared_testcases/commonSteps")
--[[ Local Functions ]]
local function get_permission_code(app_id)
local query = "select fg.name from app_group ag, functional_group fg where ag.functional_group_id = fg.id and application_id = '" .. app_id .. "'"
local result = commonFunctions:get_data_policy_sql(config.pathToSDL.."/storage/policy.sqlite", query)
return result[1]
end
--[[ General Precondition before ATF start ]]
commonFunctions:SDLForceStop()
commonSteps:DeleteLogsFileAndPolicyTable()
--[[ General Settings for configuration ]]
Test = require("connecttest")
require("user_modules/AppTypes")
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test:Preconfition_trigger_user_request_update_from_HMI()
local r_actual = get_permission_code("0000001")
local r_expected = get_permission_code("pre_DataConsent")
print("Actual: '" .. tostring(r_actual) .. "'")
print("Expected: '" .. tostring(r_expected) .. "'")
if r_actual ~= r_expected then
local msg = table.concat({"Assigned app permissions is not for pre_DataConsent, expected '", r_expected, "', actual '", r_actual, "'"})
self:FailTestCase(msg)
end
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test.Postcondition_Stop()
StopSDL()
end
return Test
|
Fix issues
|
Fix issues
|
Lua
|
bsd-3-clause
|
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
|
daadc09b3a82e492f2b91de941990506d97bdddc
|
src/module/kalmon.lua
|
src/module/kalmon.lua
|
-- This module adds some core functionality.
-- See https://github.com/kalmanolah/kalmon-ESP8266
-- See https://github.com/kalmanolah/kalmon-web
local obj = {}
obj._report_data = function()
return {
{ "/heartbeat", "ping" }
}
end
obj._command_handlers = function()
local handlers = {}
handlers['/info'] = function(evt)
return cjson.encode({
node = node.info(),
files = file.list(),
cfg = cfg.data,
})
end
-- handlers['/files/read'] = function(evt)
-- local content = nil
-- if file.open(evt.data.target, 'r') then
-- content = file.read()
-- file.close()
-- end
-- return content
-- end
-- handlers['/files/rename'] = function(evt)
-- file.rename(evt.data.source, evt.data.target)
-- end
-- handlers['/files/remove'] = function(evt)
-- file.remove(evt.data.target)
-- end
-- handlers['/files/create'] = function(evt)
-- file.open(evt.data.target, "w+")
-- file.write(evt.data.content)
-- file.close()
-- end
return handlers
end
return function(fnc, args)
if obj[fnc] then
return obj[fnc](args)
end
end
|
-- This module adds some core functionality.
-- See https://github.com/kalmanolah/kalmon-ESP8266
-- See https://github.com/kalmanolah/kalmon-web
local obj = {}
obj._report_data = function()
return {
{ "/heartbeat", "ping" }
}
end
obj._command_handlers = function()
local handlers = {}
handlers['/info'] = function(evt)
local files = {}
for f, s in pairs(file.list()) do
files[#files + 1] = {f, s}
end
return cjson.encode({
node = node.info(),
files = files,
cfg = cfg.data,
})
end
-- handlers['/files/read'] = function(evt)
-- local content = nil
-- if file.open(evt.data.target, 'r') then
-- content = file.read()
-- file.close()
-- end
-- return content
-- end
-- handlers['/files/rename'] = function(evt)
-- file.rename(evt.data.source, evt.data.target)
-- end
-- handlers['/files/remove'] = function(evt)
-- file.remove(evt.data.target)
-- end
-- handlers['/files/create'] = function(evt)
-- file.open(evt.data.target, "w+")
-- file.write(evt.data.content)
-- file.close()
-- end
return handlers
end
return function(fnc, args)
if obj[fnc] then
return obj[fnc](args)
end
end
|
bugfix
|
bugfix
Signed-off-by: Kalman Olah <[email protected]>
|
Lua
|
mit
|
kalmanolah/kalmon-ESP8266
|
c42b23242a52cff98943d90e97e695ecf4c6b936
|
Skins/ModernGadgets/@Resources/Scripts/SettingsBackups.lua
|
Skins/ModernGadgets/@Resources/Scripts/SettingsBackups.lua
|
-- MODERNGADGETS SETTINGS BACKUP SCRIPT
--
-- This script makes backups of the settings files every two hours, which
-- prevents them from being lost when updating the suite.
debug = false
function Initialize()
dofile(SKIN:GetVariable('scriptPath') .. 'Utilities.lua')
fileNames = { 'GlobalSettings.inc',
'CpuSettings.inc',
'NetworkSettings.inc',
'GpuSettings.inc',
'DisksSettings.inc',
'ProcessSettings.inc',
'ChronometerSettings.inc',
'GPU Variants\\GpuSettings1.inc',
'GPU Variants\\GpuSettings2.inc',
'GPU Variants\\GpuSettings3.inc' }
backupsPath = SKIN:GetVariable('SETTINGSPATH') .. 'ModernGadgetsSettings\\'
filesPath = SKIN:GetVariable('@') .. 'Settings\\'
cpuMeterPath = SKIN:GetVariable('cpuMeterPath')
networkMeterPath = SKIN:GetVariable('networkMeterPath')
gpuMeterPath = SKIN:GetVariable('gpuMeterPathBase')
disksMeterPath = SKIN:GetVariable('disksMeterPath')
end
function Update() end
function ImportBackup()
for i=1, 10 do
local bTable = ReadIni(backupsPath .. fileNames[i]) or {}
local sTable = ReadIni(filesPath .. fileNames[i])
CrossCheck(bTable, sTable, filesPath .. fileNames[i])
end
SKIN:Bang('!RefreshGroup', 'MgImportRefresh')
LogHelper('Imported settings backup', 'Notice')
SKIN:Bang('!Refresh')
end
function CrossCheck(bTable, sTable, filePath)
for i,v in pairs(bTable) do
if i == 'Variables' and type(v) == 'table' then
for a,b in pairs(v) do
if sTable[i][a] then
SKIN:Bang('!WriteKeyValue', i, a, b, filePath)
else
LogHelper('Key \'' .. a .. '\' does not exist in local', 'Debug')
end
end
end
end
end
function CheckForBackup()
local file = io.open(backupsPath .. fileNames[1])
if file == nil then
SKIN:Bang('!CommandMeasure', 'MeasureCreateBackup', 'Run')
SKIN:Bang('!Hide')
SKIN:Bang('!ShowMeterGroup', 'Essentials')
SKIN:Bang('!ShowMeterGroup', 'Welcome')
SKIN:Bang('!SetVariable', 'page', 'Welcome')
SKIN:Bang('!UpdateMeterGroup', 'Essentials')
SKIN:Bang('!Redraw')
SKIN:Bang('!EnableMeasure', 'MeasureMove')
SKIN:Bang('!UpdateMeasure', 'MeasureMove')
else
SKIN:Bang('!Hide')
SKIN:Bang('!ShowMeterGroup', 'Essentials')
SKIN:Bang('!ShowMeterGroup', 'ImportBackupPrompt')
SKIN:Bang('!SetVariable', 'page', 'Import')
SKIN:Bang('!UpdateMeterGroup', 'Essentials')
SKIN:Bang('!Redraw')
SKIN:Bang('!EnableMeasure', 'MeasureMove')
SKIN:Bang('!UpdateMeasure', 'MeasureMove')
file:close()
end
end
-- parses a INI formatted text file into a 'Table[Section][Key] = Value' table
function ReadIni(inputfile)
local file = io.open(inputfile, 'r')
if file == nil then return nil end
local tbl, num, section = {}, 0
for line in file:lines() do
num = num + 1
if not line:match('^%s-;') then
local key, command = line:match('^([^=]+)=(.+)')
if line:match('^%s-%[.+') then
section = line:match('^%s-%[([^%]]+)')
if section == '' or not section then
section = nil
LogHelper('Empty section name found in ' .. inputfile, 'Debug')
end
if not tbl[section] then tbl[section] = {} end
elseif key and command and section then
tbl[section][key:match('^%s*(%S*)%s*$')] = command:match('^%s*(.-)%s*$'):gsub('#(.-)#', '#\*%1\*#')
elseif #line > 0 and section and not key or command then
LogHelper(num .. ': Invalid property or value.', 'Debug')
end
end
end
file:close()
if not section then LogHelper('No sections found in ' .. inputfile, 'Debug') end
return tbl
end
|
-- MODERNGADGETS SETTINGS BACKUP SCRIPT
--
-- This script makes backups of the settings files every two hours, which
-- prevents them from being lost when updating the suite.
debug = false
function Initialize()
fileNames = { 'GlobalSettings.inc',
'CpuSettings.inc',
'NetworkSettings.inc',
'GpuSettings.inc',
'DisksSettings.inc',
'ProcessSettings.inc',
'ChronometerSettings.inc',
'GPU Variants\\GpuSettings1.inc',
'GPU Variants\\GpuSettings2.inc',
'GPU Variants\\GpuSettings3.inc' }
backupsPath = SKIN:GetVariable('SETTINGSPATH') .. 'ModernGadgetsSettings\\'
filesPath = SKIN:GetVariable('@') .. 'Settings\\'
cpuMeterPath = SKIN:GetVariable('cpuMeterPath')
networkMeterPath = SKIN:GetVariable('networkMeterPath')
gpuMeterPath = SKIN:GetVariable('gpuMeterPathBase')
disksMeterPath = SKIN:GetVariable('disksMeterPath')
end
function Update() end
function ImportBackup()
for i=1, 10 do
local bTable = ReadIni(backupsPath .. fileNames[i]) or {}
local sTable = ReadIni(filesPath .. fileNames[i])
CrossCheck(bTable, sTable, filesPath .. fileNames[i])
end
SKIN:Bang('!RefreshGroup', 'MgImportRefresh')
RmLog('Imported settings backup', 'Notice')
SKIN:Bang('!Refresh')
end
function CrossCheck(bTable, sTable, filePath)
for i,v in pairs(bTable) do
if i == 'Variables' and type(v) == 'table' then
for a,b in pairs(v) do
if sTable[i][a] then
SKIN:Bang('!WriteKeyValue', i, a, b, filePath)
else
RmLog('Key \'' .. a .. '\' does not exist in local')
end
end
end
end
end
function CheckForBackup()
local file = io.open(backupsPath .. fileNames[1])
if file == nil then
SKIN:Bang('!CommandMeasure', 'MeasureCreateBackup', 'Run')
SKIN:Bang('!Hide')
SKIN:Bang('!ShowMeterGroup', 'Essentials')
SKIN:Bang('!ShowMeterGroup', 'Welcome')
SKIN:Bang('!SetVariable', 'page', 'Welcome')
SKIN:Bang('!UpdateMeterGroup', 'Essentials')
SKIN:Bang('!Redraw')
SKIN:Bang('!EnableMeasure', 'MeasureMove')
SKIN:Bang('!UpdateMeasure', 'MeasureMove')
else
SKIN:Bang('!Hide')
SKIN:Bang('!ShowMeterGroup', 'Essentials')
SKIN:Bang('!ShowMeterGroup', 'ImportBackupPrompt')
SKIN:Bang('!SetVariable', 'page', 'Import')
SKIN:Bang('!UpdateMeterGroup', 'Essentials')
SKIN:Bang('!Redraw')
SKIN:Bang('!EnableMeasure', 'MeasureMove')
SKIN:Bang('!UpdateMeasure', 'MeasureMove')
file:close()
end
end
-- parses a INI formatted text file into a 'Table[Section][Key] = Value' table
function ReadIni(inputfile)
local file = io.open(inputfile, 'r')
if file == nil then return nil end
local tbl, num, section = {}, 0
for line in file:lines() do
num = num + 1
if not line:match('^%s-;') then
local key, command = line:match('^([^=]+)=(.+)')
if line:match('^%s-%[.+') then
section = line:match('^%s-%[([^%]]+)')
if section == '' or not section then
section = nil
RmLog('Empty section name found in ' .. inputfile)
end
if not tbl[section] then tbl[section] = {} end
elseif key and command and section then
tbl[section][key:match('^%s*(%S*)%s*$')] = command:match('^%s*(.-)%s*$'):gsub('#(.-)#', '#\*%1\*#')
elseif #line > 0 and section and not key or command then
RmLog(num .. ': Invalid property or value.')
end
end
end
file:close()
if not section then RmLog('No sections found in ' .. inputfile) end
return tbl
end
-- function to make logging messages less cluttered
function RmLog(message, type)
if type == nil then type = 'Debug' end
if debug == true then
SKIN:Bang("!Log", message, type)
elseif type ~= 'Debug' then
SKIN:Bang("!Log", message, type)
end
end
|
Fix settings backup script logging
|
Fix settings backup script logging
|
Lua
|
mit
|
raiguard/ModernGadgets,raiguard/ModernGadgets,raiguard/ModernGadgets,iamanai/ModernGadgets,iamanai/ModernGadgets
|
79fbb1637b6043a50d9601e6624287fc56c6f54c
|
lgi/override/Pango.lua
|
lgi/override/Pango.lua
|
------------------------------------------------------------------------------
--
-- LGI Pango override module.
--
-- Copyright (c) 2012 Pavel Holejsovsky
-- Licensed under the MIT license:
-- http://www.opensource.org/licenses/mit-license.php
--
------------------------------------------------------------------------------
local pairs, rawget = pairs, rawget
local table = require 'table'
local lgi = require 'lgi'
local Pango = lgi.Pango
local core = require 'lgi.core'
local ffi = require 'lgi.ffi'
local ti = ffi.types
local record = require 'lgi.record'
local component = require 'lgi.component'
-- Provide defines which are not present in the GIR
local _ = Pango.SCALE
for name, value in pairs {
SCALE_XX_SMALL = 1 / (1.2 * 1.2 * 1.2),
SCALE_X_SMALL = 1 / (1.2 * 1.2),
SCALE_SMALL = 1 / 1.2,
SCALE_MEDIUM = 1,
SCALE_LARGE = 1.2,
SCALE_X_LARGE = 1.2 * 1.2,
SCALE_XX_LARGE = 1.2 * 1.2 * 1.2,
} do
if not Pango[name] then
Pango._constant[name] = value
end
end
-- Because of https://bugzilla.gnome.org/show_bug.cgi?id=672133 Pango
-- enums are not gtype based on some platforms. If we detect non-gtype
-- enum, reload it using ffi and GEnumInfo machinery.
for _, enum in pairs {
'AttrType', 'Underline', 'BidiType', 'Direction', 'CoverageLevel',
'Style', 'Variant', 'Weight', 'Stretch', 'FontMask', 'Gravity',
'GravityHint', 'Alignment', 'WrapMode', 'EllipsizeMode', 'RenderPart',
'Script', 'TabAlign',
} do
if not Pango[enum]._gtype then
local gtype = ffi.load_gtype(
core.gi.Pango.resolve,
'pango_' .. enum:gsub('([%l%d])([%u])', '%1_%2'):lower()
.. '_get_type')
Pango._enum[enum] = ffi.load_enum(gtype, 'Pango.' .. enum)
end
end
local pango_layout_set_text = Pango.Layout.set_text
function Pango.Layout._method:set_text(text, len)
pango_layout_set_text(self, text, len or -1)
end
local pango_layout_set_markup = Pango.Layout.set_markup
function Pango.Layout._method:set_markup(text, len)
pango_layout_set_markup(self, text, len or -1)
end
-- Add attributes simulating logically missing properties in Pango classes.
for compound, attrs in pairs {
[Pango.Layout] = {
'attributes', 'font_description', 'width', 'height', 'wrap', 'context',
'is_wrapped', 'ellipsize', 'is_ellipsized', 'indent', 'spacing',
'justify', 'auto_dir', 'alignment', 'tabs', 'single_paragraph_mode',
'baseline', 'line_count', 'lines', 'log_attrs', 'character_count',
'text', 'markup',
},
[Pango.Context] = {
'base_dir', 'base_gravity', 'font_description', 'font_map', 'gravity',
'gravity_hint', 'language', 'matrix',
},
[Pango.FontMetrics] = {
'ascent', 'descent', 'approximate_char_width', 'approximate_digit_width',
'underline_thickness', 'underline_position',
'strikethrough_thinkess', 'strikethrough_position',
},
} do
compound._attribute = rawget(compound, '_attribute') or {}
for _, name in pairs(attrs) do
if not compound._property or not compound._property[name] then
compound._attribute[name] = {
get = compound['get_' .. name] or compound[name],
set = compound['set_' .. name],
}
end
end
end
-- Handling of poor-man's OO invented by Pango.Attribute related
-- pseudoclasses.
Pango.Attribute._free = core.gi.Pango.Attribute.methods.destroy
for name, def in pairs {
language_new = { Pango.Language },
family_new = { ti.utf8 },
style_new = { Pango.Style },
variant_new = { Pango.Variant },
stretch_new = { Pango.Stretch },
weight_new = { Pango.Weight },
size_new = { ti.int },
size_new_absolute = { ti.int },
desc_new = { Pango.FontDescription },
foreground_new = { ti.uint16, ti.uint16, ti.uint16 },
background_new = { ti.uint16, ti.uint16, ti.uint16 },
strikethrough_new = { ti.boolean },
strikethrough_color_new = { ti.uint16, ti.uint16, ti.uint16 },
underline_new = { Pango.Underline },
underline_color_new = { ti.uint16, ti.uint16, ti.uint16 },
shape_new = { Pango.Rectangle, Pango.Rectangle },
scale_new = { ti.double },
rise_new = { ti.int },
letter_spacing_new = { ti.int },
fallback_new = { ti.boolean },
gravity_new = { Pango.Gravity },
gravity_hint_new = { Pango.GravityHint },
} do
def.addr = core.gi.Pango.resolve['pango_attr_' .. name]
def.name = 'Pango.Attribute.' .. name
def.ret = { Pango.Attribute, xfer = true }
Pango.Attribute._method[name] = core.callable.new(def)
end
-- Adding Pango.Attribute into the Pango.AttrList takes ownership of
-- the record. Pfft, crappy API, wrap and handle.
for _, name in pairs { 'insert', 'insert_before', 'change' } do
local raw_method = Pango.AttrList[name]
Pango.AttrList._method[name] = function(list, attr)
-- Invoke original method first, then unown the attribute.
raw_method(list, attr)
core.record.set(attr, false)
end
end
|
------------------------------------------------------------------------------
--
-- LGI Pango override module.
--
-- Copyright (c) 2012 Pavel Holejsovsky
-- Licensed under the MIT license:
-- http://www.opensource.org/licenses/mit-license.php
--
------------------------------------------------------------------------------
local pairs, rawget = pairs, rawget
local table = require 'table'
local lgi = require 'lgi'
local Pango = lgi.Pango
local core = require 'lgi.core'
local gi = core.gi
local ffi = require 'lgi.ffi'
local ti = ffi.types
local record = require 'lgi.record'
local component = require 'lgi.component'
-- Provide defines which are not present in the GIR
local _ = Pango.SCALE
for name, value in pairs {
SCALE_XX_SMALL = 1 / (1.2 * 1.2 * 1.2),
SCALE_X_SMALL = 1 / (1.2 * 1.2),
SCALE_SMALL = 1 / 1.2,
SCALE_MEDIUM = 1,
SCALE_LARGE = 1.2,
SCALE_X_LARGE = 1.2 * 1.2,
SCALE_XX_LARGE = 1.2 * 1.2 * 1.2,
} do
if not Pango[name] then
Pango._constant[name] = value
end
end
-- Because of https://bugzilla.gnome.org/show_bug.cgi?id=672133 Pango
-- enums are not gtype based on some platforms. If we detect non-gtype
-- enum, reload it using ffi and GEnumInfo machinery.
for _, enum in pairs {
'AttrType', 'Underline', 'BidiType', 'Direction', 'CoverageLevel',
'Style', 'Variant', 'Weight', 'Stretch', 'FontMask', 'Gravity',
'GravityHint', 'Alignment', 'WrapMode', 'EllipsizeMode', 'RenderPart',
'Script', 'TabAlign',
} do
if not Pango[enum]._gtype then
local gtype = ffi.load_gtype(
core.gi.Pango.resolve,
'pango_' .. enum:gsub('([%l%d])([%u])', '%1_%2'):lower()
.. '_get_type')
Pango._enum[enum] = ffi.load_enum(gtype, 'Pango.' .. enum)
end
end
local pango_layout_set_text = Pango.Layout.set_text
function Pango.Layout._method:set_text(text, len)
pango_layout_set_text(self, text, len or -1)
end
local pango_layout_set_markup = Pango.Layout.set_markup
function Pango.Layout._method:set_markup(text, len)
pango_layout_set_markup(self, text, len or -1)
end
-- Add attributes simulating logically missing properties in Pango classes.
for compound, attrs in pairs {
[Pango.Layout] = {
'attributes', 'font_description', 'width', 'height', 'wrap', 'context',
'is_wrapped', 'ellipsize', 'is_ellipsized', 'indent', 'spacing',
'justify', 'auto_dir', 'alignment', 'tabs', 'single_paragraph_mode',
'baseline', 'line_count', 'lines', 'log_attrs', 'character_count',
'text', 'markup',
},
[Pango.Context] = {
'base_dir', 'base_gravity', 'font_description', 'font_map', 'gravity',
'gravity_hint', 'language', 'matrix',
},
[Pango.FontMetrics] = {
'ascent', 'descent', 'approximate_char_width', 'approximate_digit_width',
'underline_thickness', 'underline_position',
'strikethrough_thinkess', 'strikethrough_position',
},
} do
compound._attribute = rawget(compound, '_attribute') or {}
for _, name in pairs(attrs) do
if not compound._property or not compound._property[name] then
compound._attribute[name] = {
get = compound['get_' .. name] or compound[name],
set = compound['set_' .. name],
}
end
end
end
-- Handling of poor-man's OO invented by Pango.Attribute related
-- pseudoclasses.
Pango.Attribute._free = core.gi.Pango.Attribute.methods.destroy
for name, def in pairs {
language_new = { Pango.Language },
family_new = { ti.utf8 },
style_new = { Pango.Style },
variant_new = { Pango.Variant },
stretch_new = { Pango.Stretch },
weight_new = { Pango.Weight },
size_new = { ti.int },
size_new_absolute = { ti.int },
desc_new = { Pango.FontDescription },
foreground_new = { ti.uint16, ti.uint16, ti.uint16 },
background_new = { ti.uint16, ti.uint16, ti.uint16 },
strikethrough_new = { ti.boolean },
strikethrough_color_new = { ti.uint16, ti.uint16, ti.uint16 },
underline_new = { Pango.Underline },
underline_color_new = { ti.uint16, ti.uint16, ti.uint16 },
shape_new = { Pango.Rectangle, Pango.Rectangle },
scale_new = { ti.double },
rise_new = { ti.int },
letter_spacing_new = { ti.int },
fallback_new = { ti.boolean },
gravity_new = { Pango.Gravity },
gravity_hint_new = { Pango.GravityHint },
} do
def.addr = core.gi.Pango.resolve['pango_attr_' .. name]
def.name = 'Pango.Attribute.' .. name
def.ret = { Pango.Attribute, xfer = true }
Pango.Attribute._method[name] = core.callable.new(def)
end
-- Adding Pango.Attribute into the Pango.AttrList takes ownership of
-- the record. Pfft, crappy API, wrap and handle.
for _, name in pairs { 'insert', 'insert_before', 'change' } do
local raw_method = Pango.AttrList[name]
Pango.AttrList._method[name] = function(list, attr)
-- Invoke original method first, then unown the attribute.
raw_method(list, attr)
core.record.set(attr, false)
end
end
-- Pango.Layout:move_cursor_visually() is missing an (out) annotation
-- in older Pango releases. Work around this limitation by creating
-- custom ffi definition for this method.
if gi.Pango.Layout.methods.move_cursor_visually.args[6].direction ~= 'out' then
local _ = Pango.Layout.move_cursor_visually
Pango.Layout._method.move_cursor_visually = core.callable.new {
addr = core.gi.Pango.resolve.pango_layout_move_cursor_visually,
name = 'Pango.Layout.move_cursor_visually',
ret = ti.void,
gi.Pango.Layout.methods.new.return_type,
ti.boolean, ti.int, ti.int, ti.int,
{ ti.int, dir = 'out' }, { ti.int, dir = 'out' },
}
end
|
Pango: add override fixing Pango.Layout.move_cursor_visually()
|
Pango: add override fixing Pango.Layout.move_cursor_visually()
|
Lua
|
mit
|
pavouk/lgi,psychon/lgi,zevv/lgi
|
3e1b8e6bf535fb12f1ad3348473c64acd3647993
|
hop/hop.lua
|
hop/hop.lua
|
#!/usr/bin/env lua
-- Copyright 2011 The hop Authors.
--
-- 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.
json = require("json")
function startswith(given, lookup)
return string.sub(given, 1, string.len(lookup)) == lookup
end
function expanduser(p, i)
if string.sub(p, 1, 1) == '~' then
local home = os.getenv('HOME')
return home..string.sub(p,2)
else
return p
end
end
function removePrefix(str, pat)
for i = 1, #str do
local c = str:sub(i, i)
if (c ~= pat)
then
return str:sub(i)
end
end
end
function backtick(cmd, raw)
local f = assert(io.popen(cmd, 'r'))
local s = assert(f:read('*a'))
f:close()
if raw then return s end
s = string.gsub(s, '^%s+', '')
s = string.gsub(s, '%s+$', '')
s = string.gsub(s, '[\n\r]+', ' ')
return s
end
Hop = {}
Hop.getAllEntries = function()
local jsonEntries = json.decode(io.open(expanduser('~/.hop.json.db')):read('*all'))
return jsonEntries
end
Hop.search = function(request)
local possible = {}
local items = Hop.getAllEntries()
for k, v in pairs(items) do
if (startswith(k, request))
then
possible[k] = v
end
end
return possible
end
Hop.hop = function(request)
local results = Hop.search(request)
local value
local key
for k, p in pairs(results) do key = k; value = p break end
if not (value)
then
print ('No value for ' .. request)
return
end
print(key)
print(value)
if (startswith(value, '$server$'))
then
os.exit(254)
else
os.exit(255)
end
end
Hop.autocomplete = function(request)
local keys = {}
for k in pairs(Hop.search(request)) do table.insert(keys, k) end
print(table.concat(keys, '\n'))
end
Hop.dispatch = function(argv)
if not (argv[1]) then return end
if (startswith(argv[1], '-'))
then
local commandName = removePrefix(argv[1], '-')
if not (Hop[commandName])
then
print (backtick('hop-python-script ' .. table.concat(argv, ' ')))
return
else
if not (argv[2]) then return end
return Hop[commandName](argv[2])
end
end
return Hop.hop(argv[1])
end
Hop.dispatch(arg)
|
#!/usr/bin/env lua
-- Copyright 2011 The hop Authors.
--
-- 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.
json = require("json")
function startswith(given, lookup)
return string.sub(given, 1, string.len(lookup)) == lookup
end
function expanduser(p, i)
if string.sub(p, 1, 1) == '~' then
local home = os.getenv('HOME')
return home..string.sub(p,2)
else
return p
end
end
function removePrefix(str, pat)
for i = 1, #str do
local c = str:sub(i, i)
if (c ~= pat)
then
return str:sub(i)
end
end
end
function backtick(cmd, raw)
local f = assert(io.popen(cmd, 'r'))
local s = assert(f:read('*a'))
f:close()
if raw then return s end
s = string.gsub(s, '^%s+', '')
s = string.gsub(s, '%s+$', '')
s = string.gsub(s, '[\n\r]+', ' ')
return s
end
Hop = {}
Hop.getAllEntries = function()
local jsonEntries = json.decode(io.open(expanduser('~/.hop.json.db')):read('*all'))
return jsonEntries
end
Hop.search = function(request)
local possible = {}
local items = Hop.getAllEntries()
for k, v in pairs(items) do
if (startswith(k, request))
then
possible[k] = v
end
end
return possible
end
Hop.hop = function(request)
local results = Hop.search(request)
local value
local key
-- prefer an exact match if possible
if results[request] ~= nil
then
key = request
value = results[request]
else
for k, p in pairs(results) do key = k; value = p break end
end
if not (value)
then
print ('No value for ' .. request)
return
end
print(key)
print(value)
if (startswith(value, '$server$'))
then
os.exit(254)
else
os.exit(255)
end
end
Hop.autocomplete = function(request)
local keys = {}
for k in pairs(Hop.search(request)) do table.insert(keys, k) end
print(table.concat(keys, '\n'))
end
Hop.dispatch = function(argv)
if not (argv[1]) then return end
if (startswith(argv[1], '-'))
then
local commandName = removePrefix(argv[1], '-')
if not (Hop[commandName])
then
print (backtick('hop-python-script ' .. table.concat(argv, ' ')))
return
else
if not (argv[2]) then return end
return Hop[commandName](argv[2])
end
end
return Hop.hop(argv[1])
end
Hop.dispatch(arg)
|
fixed lua bug that caused e.g. `hop java` to sometimes hop to javascript even if java was a key
|
fixed lua bug that caused e.g. `hop java` to sometimes hop to javascript even if java was a key
|
Lua
|
apache-2.0
|
Cue/hop,Cue/hop
|
c99ba7bc3ba5c63922105a7c5dc0fb948bc3e29a
|
config/nvim/lua/plugins/gitsigns.lua
|
config/nvim/lua/plugins/gitsigns.lua
|
require("gitsigns").setup {
signs = {
add = {hl = "GitSignsAdd", text = "│", numhl = "GitSignsAddNr", linehl = "GitSignsAddLn"},
change = {hl = "GitSignsChange", text = "│", numhl = "GitSignsChangeNr", linehl = "GitSignsChangeLn"},
delete = {hl = "GitSignsDelete", text = "_", numhl = "GitSignsDeleteNr", linehl = "GitSignsDeleteLn"},
topdelete = {hl = "GitSignsDelete", text = "‾", numhl = "GitSignsDeleteNr", linehl = "GitSignsDeleteLn"},
changedelete = {hl = "GitSignsChange", text = "~", numhl = "GitSignsChangeNr", linehl = "GitSignsChangeLn"}
},
numhl = false,
linehl = false,
keymaps = {
-- Default keymap options
noremap = true,
["n ]c"] = {expr = true, '&diff ? \']c\' : \'<cmd>lua require"gitsigns.actions".next_hunk()<CR>\''},
["n [c"] = {expr = true, '&diff ? \'[c\' : \'<cmd>lua require"gitsigns.actions".prev_hunk()<CR>\''},
["n <leader>hs"] = '<cmd>lua require"gitsigns".stage_hunk()<CR>',
["v <leader>hs"] = '<cmd>lua require"gitsigns".stage_hunk({vim.fn.line("."), vim.fn.line("v")})<CR>',
["n <leader>hu"] = '<cmd>lua require"gitsigns".undo_stage_hunk()<CR>',
["n <leader>hr"] = '<cmd>lua require"gitsigns".reset_hunk()<CR>',
["v <leader>hr"] = '<cmd>lua require"gitsigns".reset_hunk({vim.fn.line("."), vim.fn.line("v")})<CR>',
["n <leader>hR"] = '<cmd>lua require"gitsigns".reset_buffer()<CR>',
["n <leader>hp"] = '<cmd>lua require"gitsigns".preview_hunk()<CR>',
["n <leader>hb"] = '<cmd>lua require"gitsigns".blame_line(true)<CR>',
-- Text objects
["o ih"] = ':<C-U>lua require"gitsigns.actions".select_hunk()<CR>',
["x ih"] = ':<C-U>lua require"gitsigns.actions".select_hunk()<CR>'
},
watch_index = {
interval = 1000,
follow_files = true
},
current_line_blame_opts = {
delay = 1000,
virtual_text_pos = "eol"
},
current_line_blame = false,
sign_priority = 6,
update_debounce = 100,
status_formatter = nil, -- Use default
word_diff = true,
use_internal_diff = true -- If luajit is present
}
|
require("gitsigns").setup {
signs = {
add = {hl = "GitSignsAdd", text = "│", numhl = "GitSignsAddNr", linehl = "GitSignsAddLn"},
change = {hl = "GitSignsChange", text = "│", numhl = "GitSignsChangeNr", linehl = "GitSignsChangeLn"},
delete = {hl = "GitSignsDelete", text = "_", numhl = "GitSignsDeleteNr", linehl = "GitSignsDeleteLn"},
topdelete = {hl = "GitSignsDelete", text = "‾", numhl = "GitSignsDeleteNr", linehl = "GitSignsDeleteLn"},
changedelete = {hl = "GitSignsChange", text = "~", numhl = "GitSignsChangeNr", linehl = "GitSignsChangeLn"}
},
numhl = false,
linehl = false,
keymaps = {
-- Default keymap options
noremap = true,
["n ]c"] = {expr = true, '&diff ? \']c\' : \'<cmd>lua require"gitsigns.actions".next_hunk()<CR>\''},
["n [c"] = {expr = true, '&diff ? \'[c\' : \'<cmd>lua require"gitsigns.actions".prev_hunk()<CR>\''},
["n <leader>hs"] = '<cmd>lua require"gitsigns".stage_hunk()<CR>',
["v <leader>hs"] = '<cmd>lua require"gitsigns".stage_hunk({vim.fn.line("."), vim.fn.line("v")})<CR>',
["n <leader>hu"] = '<cmd>lua require"gitsigns".undo_stage_hunk()<CR>',
["n <leader>hr"] = '<cmd>lua require"gitsigns".reset_hunk()<CR>',
["v <leader>hr"] = '<cmd>lua require"gitsigns".reset_hunk({vim.fn.line("."), vim.fn.line("v")})<CR>',
["n <leader>hR"] = '<cmd>lua require"gitsigns".reset_buffer()<CR>',
["n <leader>hp"] = '<cmd>lua require"gitsigns".preview_hunk()<CR>',
["n <leader>hb"] = '<cmd>lua require"gitsigns".blame_line(true)<CR>',
-- Text objects
["o ih"] = ':<C-U>lua require"gitsigns.actions".select_hunk()<CR>',
["x ih"] = ':<C-U>lua require"gitsigns.actions".select_hunk()<CR>'
},
watch_index = {
interval = 1000,
follow_files = true
},
current_line_blame_opts = {
delay = 1000,
virtual_text_pos = "eol"
},
current_line_blame = false,
sign_priority = 6,
update_debounce = 100,
status_formatter = nil, -- Use default
word_diff = true,
diff_opts = {
internal = true
}
}
|
fix(vim): replace deprecated gitsigns setting
|
fix(vim): replace deprecated gitsigns setting
use_internal_diff -> diff_opts.internal
|
Lua
|
mit
|
nicknisi/dotfiles,nicknisi/dotfiles,nicknisi/dotfiles
|
3142b7b5cade6235eda90fb13d3ef3be01b22834
|
grains/grains_test.lua
|
grains/grains_test.lua
|
local Grains = require('grains')
describe('Grains', function()
it('square 1', function()
assert.are.equals(Grains.square(1), 1)
end)
it('square 2', function()
assert.are.equals(Grains.square(2), 2)
end)
it('square 3', function()
assert.are.equals(Grains.square(3), 4)
end)
it('square 4', function()
assert.are.equals(Grains.square(4), 8)
end)
it('square 16', function()
assert.are.equals(Grains.square(16), 32768)
end)
it('square 32', function()
assert.are.equals(Grains.square(32), 2147483648)
end)
it('square 64', function()
assert.are.equals(Grains.square(64), 9223372036854775808)
end)
it('total', function()
assert.are.equals(Grains.total(), 18446744073709551615)
end)
end)
|
local Grains = require('grains')
describe('Grains', function()
it('square 1', function()
assert.are.equals(1, Grains.square(1))
end)
it('square 2', function()
assert.are.equals(2, Grains.square(2))
end)
it('square 3', function()
assert.are.equals(4, Grains.square(3))
end)
it('square 4', function()
assert.are.equals(8, Grains.square(4))
end)
it('square 16', function()
assert.are.equals(32768, Grains.square(16))
end)
it('square 32', function()
assert.are.equals(2147483648, Grains.square(32))
end)
it('square 64', function()
assert.are.equals(9223372036854775808, Grains.square(64))
end)
it('total', function()
assert.are.equals(18446744073709551615, Grains.total())
end)
end)
|
Fixed assertion argument order
|
Fixed assertion argument order
|
Lua
|
mit
|
exercism/xlua,ryanplusplus/xlua,fyrchik/xlua
|
b36e5305b31d8a862b05a8465e3597b207a42474
|
share/lua/website/imdb.lua
|
share/lua/website/imdb.lua
|
--
-- libquvi-scripts
-- Copyright (C) 2011 quvi project
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-- 02110-1301 USA
--
local IMDB = {} -- Utility functions unique to this script
-- Identify the script.
function ident(self)
package.path = self.script_dir .. '/?.lua'
local C = require 'quvi/const'
local r = {}
r.domain = 'imdb%.com'
r.formats = 'default|best'
local B = require 'quvi/bit'
r.categories = B.bit_or(C.proto_http, C.proto_rtmp)
local U = require 'quvi/util'
r.handles = U.handles(self.page_url,
{r.domain},
{"/video/.+"})
return r
end
-- Query available formats.
function query_formats(self)
local config = IMDB.get_config(self)
local formats = IMDB.iter_formats(config)
local t = {}
for _,v in pairs(formats) do
table.insert(t, IMDB.to_s(v))
end
table.sort(t)
self.formats = table.concat(t, "|")
return self
end
-- Parse media URL.
function parse(self)
self.host_id = 'imdb'
self.id = self.page_url:match('/video/%w+/(vi%d-)/')
local page = quvi.fetch(self.page_url)
self.title = page:match('<title>(.-) %- IMDb</title>')
--
-- Format codes (for most videos):
-- uff=1 - 480p RTMP
-- uff=2 - 480p HTTP
-- uff=3 - 720p HTTP
--
local formats = IMDB.iter_formats(page)
local U = require 'quvi/util'
local format = U.choose_format(self, formats,
IMDB.choose_best,
IMDB.choose_default,
IMDB.to_s)
or error("unable to choose format")
if not format.path then
error("no match: media url")
end
local url = 'http://www.imdb.com' .. format.path
local iframe = quvi.fetch(url, {fetch_type = 'config'})
local file = iframe:match('so%.addVariable%("file", "(.-)"%);')
file = U.unescape(file)
if file:match('^http.-') then
self.url = {file}
else
local path = iframe:match('so%.addVariable%("id", "(.-)"%);')
path = U.unescape(path)
self.url = {file .. path}
end
-- Optional: we can live without these
local thumb = iframe:match('so%.addVariable%("image", "(.-)"%);')
self.thumbnail_url = thumb or ''
return self
end
--
-- Utility functions
--
function IMDB.iter_formats(page)
local p = "case '(.-)' :.-url = '(.-)';"
local t = {}
for c,u in page:gfind(p) do
table.insert(t, {path=u, container=c})
--print(u,c)
end
-- First item is ad, so remove it
table.remove(t, 1)
return t
end
function IMDB.choose_best(t) -- Expect the last to be the 'best'
return t[#t]
end
function IMDB.choose_default(t) -- Expect the second to be the 'default'
return t[2]
end
function IMDB.to_s(t)
return t.container
end
-- vim: set ts=4 sw=4 tw=72 expandtab:
|
--
-- libquvi-scripts
-- Copyright (C) 2011 quvi project
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-- 02110-1301 USA
--
local IMDB = {} -- Utility functions unique to this script
-- Identify the script.
function ident(self)
package.path = self.script_dir .. '/?.lua'
local C = require 'quvi/const'
local r = {}
r.domain = 'imdb%.com'
r.formats = 'default|best'
local B = require 'quvi/bit'
r.categories = B.bit_or(C.proto_http, C.proto_rtmp)
local U = require 'quvi/util'
r.handles = U.handles(self.page_url,
{r.domain},
{"/video/.+"})
return r
end
-- Query available formats.
function query_formats(self)
local page = quvi.fetch(self.page_url)
local formats = IMDB.iter_formats(page)
local t = {}
for _,v in pairs(formats) do
table.insert(t, IMDB.to_s(v))
end
table.sort(t)
self.formats = table.concat(t, "|")
return self
end
-- Parse media URL.
function parse(self)
self.host_id = 'imdb'
self.id = self.page_url:match('/video/%w+/(vi%d-)/')
local page = quvi.fetch(self.page_url)
self.title = page:match('<title>(.-) %- IMDb</title>')
--
-- Format codes (for most videos):
-- uff=1 - 480p RTMP
-- uff=2 - 480p HTTP
-- uff=3 - 720p HTTP
--
local formats = IMDB.iter_formats(page)
local U = require 'quvi/util'
local format = U.choose_format(self, formats,
IMDB.choose_best,
IMDB.choose_default,
IMDB.to_s)
or error("unable to choose format")
if not format.path then
error("no match: media url")
end
local url = 'http://www.imdb.com' .. format.path
local iframe = quvi.fetch(url, {fetch_type = 'config'})
local file = iframe:match('so%.addVariable%("file", "(.-)"%);')
file = U.unescape(file)
if file:match('^http.-') then
self.url = {file}
else
local path = iframe:match('so%.addVariable%("id", "(.-)"%);')
path = U.unescape(path)
self.url = {file .. path}
end
-- Optional: we can live without these
local thumb = iframe:match('so%.addVariable%("image", "(.-)"%);')
self.thumbnail_url = thumb or ''
return self
end
--
-- Utility functions
--
function IMDB.iter_formats(page)
local p = "case '(.-)' :.-url = '(.-)';"
local t = {}
for c,u in page:gfind(p) do
table.insert(t, {path=u, container=c})
--print(u,c)
end
-- First item is ad, so remove it
table.remove(t, 1)
return t
end
function IMDB.choose_best(t) -- Expect the last to be the 'best'
return t[#t]
end
function IMDB.choose_default(t) -- Expect the second to be the 'default'
return t[2]
end
function IMDB.to_s(t)
return t.container
end
-- vim: set ts=4 sw=4 tw=72 expandtab:
|
FIX: imdb.lua:43: attempt to call field 'get_config' (nil)
|
FIX: imdb.lua:43: attempt to call field 'get_config' (nil)
|
Lua
|
agpl-3.0
|
legatvs/libquvi-scripts,DangerCove/libquvi-scripts,alech/libquvi-scripts,DangerCove/libquvi-scripts,hadess/libquvi-scripts-iplayer,alech/libquvi-scripts,legatvs/libquvi-scripts,hadess/libquvi-scripts-iplayer
|
d51581ad1f836d6682f7fad0d12ba08ad389eb18
|
toys/lstm-real-class/toy.lua
|
toys/lstm-real-class/toy.lua
|
-- Here I try modeling two criteria at once, one real and one a discrete version
-- of that. The main motivation is to try predicting multiple things at once.
require 'optim'
plutils = require 'pl.utils'
tablex = require 'pl.tablex'
lstm = require 'lstm'
inputs = {}
total_count = 0
train_points = 0
lines = plutils.readlines('noisy_inputs.txt')
for i,line in pairs(lines) do
local vals = plutils.split(line, ',')
inputs[i] = torch.Tensor(tablex.map(tonumber, vals))
total_count = total_count + 1
end
true_inputs = {}
total_count = 0
lines = plutils.readlines('true_inputs.txt')
for i,line in pairs(lines) do
local vals = plutils.split(line, ',')
true_inputs[i] = torch.Tensor(tablex.map(tonumber, vals))
total_count = total_count + 1
end
-- For this tests, I model the same thing but two ways. On the real line using
-- MSECriterion and as 10 discrete classes dividing the real line and using
-- CrossEntropyCriterion.
num_classes = 10
outputs = tablex.map(tonumber, plutils.readlines('outputs.txt'))
outputs = torch.Tensor(outputs)
output_range = outputs:max() - outputs:min() + 1e-08
output_classes = (outputs - outputs:min() + 1e-09):div(output_range/num_classes):ceil()
output_tuples = torch.cat(outputs, output_classes, 2)
-- Decide on the train/test split
test_frac = 0.3
m = torch.floor(total_count * test_frac)
n = total_count - m
-- Split the data into test and train
x_train = {}
x_test = {}
for i,input in pairs(inputs) do
if i <= n then
x_train[i] = input
train_points = train_points + input:size(1)
else
x_test[i-n] = input
end
end
y_train = output_tuples:narrow(1, 1, n)
y_test = output_tuples:narrow(1, n+1, m)
-- Normalize the inputs
norm_mean =
torch.Tensor(tablex.map(function(i) return i:sum() end, x_train)):sum() / train_points
norm_var = torch.Tensor(tablex.map(
function(i) return (i - norm_mean):pow(2):sum() end,
x_train)):sum() / train_points
norm_std = math.sqrt(norm_var)
x_train_n = tablex.map(function(z) return (z - norm_mean) / norm_std end, x_train)
x_test_n = tablex.map(function(z) return (z - norm_mean) / norm_std end, x_test)
x_true_n = tablex.map(function(z) return (z - norm_mean) / norm_std end, true_inputs)
function buildDataset(x, y)
local dataset = {}
local n = #x
function dataset:size()
return n
end
for i=1,dataset:size() do
dataset[i] = {x[i]:view(-1,1), y:narrow(1,i,1)}
end
return dataset
end
train_dataset = buildDataset(x_train_n, y_train)
test_dataset = buildDataset(x_test_n, y_test)
true_dataset = buildDataset(x_true_n, output_tuples)
n_h = 20
max_len = 4
net = {}
net.classes = num_classes
-- LSTM
x = nn.Identity()()
net.chain = lstm.MemoryChain(1, n_h, max_len)
lastHidden = nn.SelectTable(1)(net.chain(x))
net.chainMod = nn.gModule({x}, {lastHidden})
-- Prediction
chainOut = nn.Identity()()
predictReal = nn.Linear(n_h, 1)(chainOut)
predictClass = nn.LogSoftMax()(nn.Linear(n_h, num_classes)(chainOut))
predictions = nn.Identity()({predictReal, predictClass})
-- Takes the output from the LSTM chain and does multi-output prediction. Output
-- will be {1x1, 1xC}, where C is the number of classes.
net.predict = nn.gModule({chainOut}, {predictions})
-- Criterion
rC = nn.MSECriterion()
cC = nn.ClassNLLCriterion()
net.criterion = nn.ParallelCriterion():add(rC):add(cC)
-- Get access to net's parameters
net.predict.par_vec, net.predict.grad_par_vec = net.predict:getParameters()
trainer = {}
trainer.maxIteration = 25
trainer.learningRate = 0.01
function trainer:hookIteration(iter, err)
print("# current error = " .. err)
end
function trainer:train(net, dataset)
local iteration = 1
local lr = self.learningRate
local shuffledIndices = torch.randperm(dataset:size(), 'torch.LongTensor')
local chain = net.chain
local chainMod = net.chainMod
local predict = net.predict
local criterion = net.criterion
while true do
local currentError = 0
for t = 1,dataset:size() do
local example = dataset[shuffledIndices[t]]
net:forward(unpack(example))
net:backward(unpack(example))
-- Update parameters
chain.lstm_par_vec:add(chain.lstm_grad_par_vec:mul(-lr))
predict.par_vec:add(predict.grad_par_vec:mul(-lr))
currentError = currentError + criterion.output
end
currentError = currentError / dataset:size()
if self.hookIteration then
self.hookIteration(self, iteration, currentError)
end
iteration = iteration + 1
if self.maxIteration > 0 and iteration > self.maxIteration then
print("# Max iteration reached; training error = " .. currentError)
break
end
end
end
function net:forward(input, targets)
targets = self:splitTargets(targets)
self.chainMod:forward(input)
self.predict:forward(self.chainMod.output)
return self.criterion:forward(self.predict.output, targets)
end
function net:splitTargets(targets)
local targetReal = targets:select(2,1):view(-1,1)
local targetClass = targets:select(2,2)
return {targetReal, targetClass}
end
function net:backward(input, targets)
targets = self:splitTargets(targets)
self.chain:zeroGradParameters()
self.predict:zeroGradParameters()
self.criterion:backward(self.predict.output, targets)
self.predict:backward(self.chain.output, self.criterion.gradInput)
self.chainMod:backward(input, self.predict.gradInput)
end
function net:predictionError(dataset)
local err = 0
for i=1, dataset:size() do
self:forward(unpack(dataset[i]))
err = err + self.criterion.output
end
return err / dataset:size()
end
function net:classify(dataset)
local predicted_classes = torch.Tensor(dataset:size())
for i=1, dataset:size() do
local input, target = unpack(dataset[i])
net:forward(input, target)
local odds = net.predict.output[2]
_, cls = torch.max(nn.LogSoftMax():forward(odds), 2)
predicted_classes[i] = cls
end
return predicted_classes
end
function net:confusion(dataset)
if self.classes == nil then
error('not a classification net')
end
confusion = optim.ConfusionMatrix(torch.range(1,self.classes):totable())
local predictions = self:classify(dataset)
for i=1, dataset:size() do
local predicted = predictions[i]
local actual = dataset[i][2][{1,2}]
confusion:add(predicted, actual)
end
return confusion
end
-- Train the model
trainer:train(net, train_dataset)
-- See how it did
net:confusion(test)
-- END
|
-- Here I try modeling two criteria at once, one real and one a discrete version
-- of that. The main motivation is to try predicting multiple things at once.
require 'optim'
plutils = require 'pl.utils'
tablex = require 'pl.tablex'
lstm = require 'lstm'
inputs = {}
total_count = 0
train_points = 0
lines = plutils.readlines('noisy_inputs.txt')
for i,line in pairs(lines) do
local vals = plutils.split(line, ',')
inputs[i] = torch.Tensor(tablex.map(tonumber, vals))
total_count = total_count + 1
end
true_inputs = {}
total_count = 0
lines = plutils.readlines('true_inputs.txt')
for i,line in pairs(lines) do
local vals = plutils.split(line, ',')
true_inputs[i] = torch.Tensor(tablex.map(tonumber, vals))
total_count = total_count + 1
end
-- For this tests, I model the same thing but two ways. On the real line using
-- MSECriterion and as 10 discrete classes dividing the real line and using
-- CrossEntropyCriterion.
num_classes = 10
outputs = tablex.map(tonumber, plutils.readlines('outputs.txt'))
outputs = torch.Tensor(outputs)
output_range = outputs:max() - outputs:min() + 1e-08
output_classes = (outputs - outputs:min() + 1e-09):div(output_range/num_classes):ceil()
output_tuples = torch.cat(outputs, output_classes, 2)
-- Decide on the train/test split
test_frac = 0.3
m = torch.floor(total_count * test_frac)
n = total_count - m
-- Split the data into test and train
x_train = {}
x_test = {}
for i,input in pairs(inputs) do
if i <= n then
x_train[i] = input
train_points = train_points + input:size(1)
else
x_test[i-n] = input
end
end
y_train = output_tuples:narrow(1, 1, n)
y_test = output_tuples:narrow(1, n+1, m)
-- Normalize the inputs
norm_mean =
torch.Tensor(tablex.map(function(i) return i:sum() end, x_train)):sum() / train_points
norm_var = torch.Tensor(tablex.map(
function(i) return (i - norm_mean):pow(2):sum() end,
x_train)):sum() / train_points
norm_std = math.sqrt(norm_var)
x_train_n = tablex.map(function(z) return (z - norm_mean) / norm_std end, x_train)
x_test_n = tablex.map(function(z) return (z - norm_mean) / norm_std end, x_test)
x_true_n = tablex.map(function(z) return (z - norm_mean) / norm_std end, true_inputs)
function buildDataset(x, y)
local dataset = {}
local n = #x
function dataset:size()
return n
end
for i=1,dataset:size() do
dataset[i] = {x[i]:view(-1,1), y:narrow(1,i,1)}
end
return dataset
end
train_dataset = buildDataset(x_train_n, y_train)
test_dataset = buildDataset(x_test_n, y_test)
true_dataset = buildDataset(x_true_n, output_tuples)
n_h = 20
max_len = 4
-- Generic module
net = nn.Module.new()
net.classes = num_classes
-- LSTM
x = nn.Identity()()
net.chain = lstm.MemoryChain(1, n_h, max_len)
lastHidden = nn.SelectTable(1)(net.chain(x))
net.chainMod = nn.gModule({x}, {lastHidden})
-- Prediction
chainOut = nn.Identity()()
predictReal = nn.Linear(n_h, 1)(chainOut)
predictClass = nn.LogSoftMax()(nn.Linear(n_h, num_classes)(chainOut))
predictions = nn.Identity()({predictReal, predictClass})
-- Takes the output from the LSTM chain and does multi-output prediction. Output
-- will be {1x1, 1xC}, where C is the number of classes.
net.predict = nn.gModule({chainOut}, {predictions})
-- Criterion
rC = nn.MSECriterion()
cC = nn.ClassNLLCriterion()
net.criterion = nn.ParallelCriterion():add(rC):add(cC)
trainer = {}
trainer.maxIteration = 30
trainer.learningRate = 0.01
function trainer:hookIteration(iter, err)
print("# current error = " .. err)
end
function trainer:train(net, dataset, reset)
reset = reset or true
local iteration = 1
local lr = self.learningRate
local shuffledIndices = torch.randperm(dataset:size(), 'torch.LongTensor')
local chain = net.chain
local chainMod = net.chainMod
local predict = net.predict
local criterion = net.criterion
if reset then
net:reset()
end
while true do
local currentError = 0
for t = 1,dataset:size() do
local example = dataset[shuffledIndices[t]]
net:forward(example)
net:backward(unpack(example))
-- Update parameters
net.par_vec:add(net.grad_par_vec:mul(-lr))
currentError = currentError + criterion.output
end
currentError = currentError / dataset:size()
if self.hookIteration then
self.hookIteration(self, iteration, currentError)
end
iteration = iteration + 1
if self.maxIteration > 0 and iteration > self.maxIteration then
print("# Max iteration reached; training error = " .. currentError)
break
end
end
end
function net:parameters()
local chain_par, chain_grad_par = self.chain:parameters()
local predict_par, predict_grad_par = self.predict:parameters()
local par = {}
local grad_par = {}
local j = 1
for i=1, #chain_par do
par[j] = chain_par[i]
grad_par[j] = chain_grad_par[i]
j = j + 1
end
for i=1, #predict_par do
par[j] = predict_par[i]
grad_par[j] = predict_grad_par[i]
j = j + 1
end
return par, grad_par
end
function net:updateOutput(input_and_target)
local input, targets = unpack(input_and_target)
targets = self:splitTargets(targets)
self.chainMod:forward(input)
self.predict:forward(self.chainMod.output)
self.output = self.criterion:forward(self.predict.output, targets)
return self.output
end
function net:updateGradInput(input, targets)
targets = self:splitTargets(targets)
self:zeroGradParameters()
self.criterion:backward(self.predict.output, targets)
self.predict:backward(self.chain.output, self.criterion.gradInput)
self.chainMod:backward(input, self.predict.gradInput)
self.gradInput = self.chainMod.gradInput
return self.gradInput
end
function net:reset(radius)
radius = radius or 0.7
self:zeroGradParameters()
self.par_vec:uniform(-radius, radius)
end
function net:splitTargets(targets)
local targetReal = targets:select(2,1):view(-1,1)
local targetClass = targets:select(2,2)
return {targetReal, targetClass}
end
function net:predictionError(dataset)
local err = 0
for i=1, dataset:size() do
self:forward(dataset[i])
err = err + self.criterion.output
end
return err / dataset:size()
end
function net:classify(dataset)
local predicted_classes = torch.Tensor(dataset:size())
for i=1, dataset:size() do
net:forward(dataset[i])
local odds = net.predict.output[2]
_, cls = torch.max(nn.LogSoftMax():forward(odds), 2)
predicted_classes[i] = cls
end
return predicted_classes
end
function net:confusion(dataset)
if self.classes == nil then
error('not a classification net')
end
confusion = optim.ConfusionMatrix(torch.range(1,self.classes):totable())
local predictions = self:classify(dataset)
for i=1, dataset:size() do
local predicted = predictions[i]
local actual = dataset[i][2][{1,2}]
confusion:add(predicted, actual)
end
return confusion
end
-- Get access to net's parameters
net.par_vec, net.grad_par_vec = net:getParameters()
-- Train the model
trainer:train(net, train_dataset)
-- See how it did
net:confusion(test_dataset)
-- END
|
fixes to switch transpose input
|
fixes to switch transpose input
|
Lua
|
mit
|
kbullaughey/lstm-play,kbullaughey/lstm-play,kbullaughey/lstm-play
|
f362a2270446867baf232946727cb2b42b483d5d
|
benchmark/benchmark.lua
|
benchmark/benchmark.lua
|
-- lua-lru, LRU cache in Lua
-- Copyright (c) 2015 Boris Nagaev
-- See the LICENSE file for terms of use.
local lru
-- fix for resty.lrucache
ngx = {
now = os.clock
}
local impl = arg[1]
if impl then
lru = require(impl)
else
lru = {
new = function()
return {
set = function()
end
}
end
}
end
-- fix for Lua-LRU-Cache
if impl == 'LRUCache' then
lru.new0 = lru.new
function lru.new(max_size,expire)
return lru:new0(max_size,expire)
end
end
local cache = lru.new(1000)
for i = 1, 1000000 do
local key
for j = 1, 5 do
local x = math.random(1, 10000)
cache:set(x, x+1)
key = x
end
for j = 1, 5 do
local x = math.random(1, 1000)
cache:set(x, x+1)
end
assert(cache:get(key) == key+1)
end
|
-- lua-lru, LRU cache in Lua
-- Copyright (c) 2015 Boris Nagaev
-- See the LICENSE file for terms of use.
local lru
-- fix for resty.lrucache
ngx = {
now = os.clock
}
local impl = arg[1]
if impl then
lru = require(impl)
else
lru = {
new = function()
return {
set = function()
end,
get = function(_, x)
return x+1
end,
}
end
}
end
-- fix for Lua-LRU-Cache
if impl == 'LRUCache' then
lru.new0 = lru.new
function lru.new(max_size,expire)
return lru:new0(max_size,expire)
end
end
local cache = lru.new(1000)
for i = 1, 1000000 do
local key
for j = 1, 5 do
local x = math.random(1, 10000)
cache:set(x, x+1)
key = x
end
for j = 1, 5 do
local x = math.random(1, 1000)
cache:set(x, x+1)
end
assert(cache:get(key) == key+1)
end
|
benchmark: fix 'no cache' case
|
benchmark: fix 'no cache' case
|
Lua
|
mit
|
starius/lua-lru
|
ee2f4bd29a1a3bc432d448ca80c7184a676e0cca
|
utils.lua
|
utils.lua
|
-- UTILS
function trim(s)
local from = s:match"^%s*()"
return s:match"^%s*()" > #s and "" or s:match(".*%S", s:match"^%s*()")
end
function clone(t) -- shallow-copy a table
if type(t) ~= "table" then return t end
local meta = getmetatable(t)
local target = {}
for k, v in pairs(t) do target[k] = v end
setmetatable(target, meta)
return target
end
table.exact_length = function(tbl)
i = 0
for k,v in pairs(tbl) do
i = i + 1
end
return i
end
function isint(n)
return n == math.floor(n)
end
function isnan(n)
return n ~= n
end
table.collapse_to_string = function(tbl)
assert(type(tbl) == "table")
ret = ""
if(tbl == nil) then
ret = "No table provided"
elseif(table.exact_length(tbl) == 0) then
ret = "Empty table"
elseif (tbl[1] ~= nil) then
for _,v in pairs(tbl) do
if (ret ~= "") then
ret = ret .. ", "
end
ret = ret .. "'" .. v .."'"
end
else
for k,v in pairs(tbl) do
if (ret ~= "") then
ret = ret .. ", "
end
ret = ret .. "'" .. k .. "'=>'" .. v .. "'"
end
end
return ret
end
-- END UTILS
|
-- UTILS
function trim(s)
local from = s:match"^%s*()"
return s:match"^%s*()" > #s and "" or s:match(".*%S", s:match"^%s*()")
end
function clone(t) -- shallow-copy a table
if type(t) ~= "table" then return t end
local meta = getmetatable(t)
local target = {}
for k, v in pairs(t) do target[k] = v end
setmetatable(target, meta)
return target
end
table.exact_length = function(tbl)
if (type(tbl) ~= 'table') then
return 1
end
i = 0
for k,v in pairs(tbl) do
i = i + 1
end
return i
end
function isint(n)
return n == math.floor(n)
end
function isnan(n)
return n ~= n
end
table.collapse_to_string = function(tbl)
assert(type(tbl) == "table")
ret = ""
if(tbl == nil) then
ret = "No table provided"
elseif(table.exact_length(tbl) == 0) then
ret = "Empty table"
elseif (tbl[1] ~= nil) then
for _,v in pairs(tbl) do
if (ret ~= "") then
ret = ret .. ", "
end
ret = ret .. "'" .. v .."'"
end
else
for k,v in pairs(tbl) do
if (ret ~= "") then
ret = ret .. ", "
end
ret = ret .. "'" .. k .. "'=>'" .. v .. "'"
end
end
return ret
end
-- END UTILS
|
Table length fix
|
Table length fix
|
Lua
|
mit
|
AlexMili/torch-dataframe
|
e8e8c3b3a2f8257370b892307e2d0318030eacd7
|
game/scripts/vscripts/items/item_pocket_riki.lua
|
game/scripts/vscripts/items/item_pocket_riki.lua
|
--[[Author: YOLOSPAGHETTI
Date: February 4, 2016
Checks if Riki is behind his target
Borrows heavily from bristleback.lua]]
function CheckBackstab(params)
local attacker = params.attacker
local ability = params.ability
local stat_damage_multiplier = ability:GetSpecialValueFor("stat_damage") / 100
local statId = attacker:GetPrimaryAttribute()
local damage
if statId == 0 then
damage = attacker:GetStrength() * stat_damage_multiplier
elseif statId == 1 then
damage = attacker:GetAgility() * stat_damage_multiplier
else
damage = attacker:GetIntellect() * stat_damage_multiplier
end
local victim_angle = params.target:GetAnglesAsVector().y
local origin_difference = params.target:GetAbsOrigin() - attacker:GetAbsOrigin()
local origin_difference_radian = math.atan2(origin_difference.y, origin_difference.x)
origin_difference_radian = origin_difference_radian * 180
local attacker_angle = origin_difference_radian / math.pi
attacker_angle = attacker_angle + 180.0
local result_angle = attacker_angle - victim_angle
result_angle = math.abs(result_angle)
-- Check for the backstab angle.
if result_angle >= (180 - (ability:GetSpecialValueFor("backstab_angle") / 2)) and result_angle <= (180 + (ability:GetSpecialValueFor("backstab_angle") / 2)) then
EmitSoundOn(params.sound, params.target)
local particle = ParticleManager:CreateParticle(params.particle, PATTACH_ABSORIGIN_FOLLOW, params.target)
ParticleManager:SetParticleControlEnt(particle, 1, params.target, PATTACH_POINT_FOLLOW, "attach_hitloc", params.target:GetAbsOrigin(), true)
ApplyDamage({victim = params.target, attacker = attacker, damage = damage, damage_type = ability:GetAbilityDamageType(), ability = ability})
end
end
function ConsumeRiki(keys)
local caster = keys.caster
local ability = keys.ability
ability.RikiContainer:TrueKill(ability, ability.RikiContainer)
local buffsTime = ability.RikiContainer:GetRespawnTime()
local newItem = CreateItem("item_pocket_riki_consumed", caster, caster)
swap_to_item(caster, ability, newItem)
caster:RemoveModifierByName("modifier_item_pocket_riki_invisibility_fade")
caster:RemoveModifierByName("modifier_item_pocket_riki_permanent_invisibility")
caster:RemoveModifierByName("modifier_invisible")
newItem:ApplyDataDrivenModifier(caster, caster, "modifier_item_pocket_riki_consumed_str", {duration=buffsTime})
ModifyStacks(newItem, caster, caster, "modifier_item_pocket_riki_consumed_str", ability.RikiContainer:GetStrength(), true)
newItem:ApplyDataDrivenModifier(caster, caster, "modifier_item_pocket_riki_consumed_agi", {duration=buffsTime})
ModifyStacks(newItem, caster, caster, "modifier_item_pocket_riki_consumed_agi", ability.RikiContainer:GetAgility(), true)
newItem:ApplyDataDrivenModifier(caster, caster, "modifier_item_pocket_riki_consumed_int", {duration=buffsTime})
ModifyStacks(newItem, caster, caster, "modifier_item_pocket_riki_consumed_int", ability.RikiContainer:GetIntellect(), true)
Timers:CreateTimer(buffsTime, function()
UTIL_Remove(newItem)
caster:RemoveModifierByName("modifier_item_pocket_riki_consumed_invisibility_fade")
caster:RemoveModifierByName("modifier_item_pocket_riki_consumed_permanent_invisibility")
caster:RemoveModifierByName("modifier_invisible")
end)
end
function DropRiki(keys)
local caster = keys.caster
local ability = keys.ability
ability.RikiContainer:RemoveModifierByName("modifier_pocket_riki_hide")
UTIL_Remove(ability)
end
|
--[[Author: YOLOSPAGHETTI
Date: February 4, 2016
Checks if Riki is behind his target
Borrows heavily from bristleback.lua]]
function CheckBackstab(params)
local attacker = params.attacker
local ability = params.ability
local stat_damage_multiplier = ability:GetSpecialValueFor("stat_damage") / 100
local statId = attacker:GetPrimaryAttribute()
local damage
if statId == 0 then
damage = attacker:GetStrength() * stat_damage_multiplier
elseif statId == 1 then
damage = attacker:GetAgility() * stat_damage_multiplier
else
damage = attacker:GetIntellect() * stat_damage_multiplier
end
local victim_angle = params.target:GetAnglesAsVector().y
local origin_difference = params.target:GetAbsOrigin() - attacker:GetAbsOrigin()
local origin_difference_radian = math.atan2(origin_difference.y, origin_difference.x)
origin_difference_radian = origin_difference_radian * 180
local attacker_angle = origin_difference_radian / math.pi
attacker_angle = attacker_angle + 180.0
local result_angle = attacker_angle - victim_angle
result_angle = math.abs(result_angle)
-- Check for the backstab angle.
if result_angle >= (180 - (ability:GetSpecialValueFor("backstab_angle") / 2)) and result_angle <= (180 + (ability:GetSpecialValueFor("backstab_angle") / 2)) then
EmitSoundOn(params.sound, params.target)
local particle = ParticleManager:CreateParticle(params.particle, PATTACH_ABSORIGIN_FOLLOW, params.target)
ParticleManager:SetParticleControlEnt(particle, 1, params.target, PATTACH_POINT_FOLLOW, "attach_hitloc", params.target:GetAbsOrigin(), true)
ApplyDamage({victim = params.target, attacker = attacker, damage = damage, damage_type = ability:GetAbilityDamageType(), ability = ability})
end
end
function ConsumeRiki(keys)
local caster = keys.caster
local ability = keys.ability
local riki = ability.RikiContainer
local buffsTime = riki:CalculateRespawnTime()
local newItem = CreateItem("item_pocket_riki_consumed", caster, caster)
riki:TrueKill(ability, riki)
swap_to_item(caster, ability, newItem)
caster:RemoveModifierByName("modifier_item_pocket_riki_invisibility_fade")
caster:RemoveModifierByName("modifier_item_pocket_riki_permanent_invisibility")
caster:RemoveModifierByName("modifier_invisible")
newItem:ApplyDataDrivenModifier(caster, caster, "modifier_item_pocket_riki_consumed_str", {duration=buffsTime})
ModifyStacks(newItem, caster, caster, "modifier_item_pocket_riki_consumed_str", riki:GetStrength(), true)
newItem:ApplyDataDrivenModifier(caster, caster, "modifier_item_pocket_riki_consumed_agi", {duration=buffsTime})
ModifyStacks(newItem, caster, caster, "modifier_item_pocket_riki_consumed_agi", riki:GetAgility(), true)
newItem:ApplyDataDrivenModifier(caster, caster, "modifier_item_pocket_riki_consumed_int", {duration=buffsTime})
ModifyStacks(newItem, caster, caster, "modifier_item_pocket_riki_consumed_int", riki:GetIntellect(), true)
Timers:CreateTimer(buffsTime, function()
UTIL_Remove(newItem)
caster:RemoveModifierByName("modifier_item_pocket_riki_consumed_invisibility_fade")
caster:RemoveModifierByName("modifier_item_pocket_riki_consumed_permanent_invisibility")
caster:RemoveModifierByName("modifier_invisible")
end)
end
function DropRiki(keys)
local caster = keys.caster
local ability = keys.ability
ability.RikiContainer:RemoveModifierByName("modifier_pocket_riki_hide")
UTIL_Remove(ability)
end
|
Fixed consumed Pocked Riki gave attributes for too long
|
Fixed consumed Pocked Riki gave attributes for too long
|
Lua
|
mit
|
ark120202/aabs
|
9c11d08da2d061cbf05bb0721d0392c91bc0c79c
|
configure-controller.lua
|
configure-controller.lua
|
local Root = Discover.ControllerLocation() .. '/'
dofile(Root .. 'info.include.lua')
-- Setup
Discover.Version({Version = 1})
local Help = Discover.HelpMode()
local Guard = function(Action) -- Helps prevent filesystem changes in help mode
if not Help then Action() end
end
local Debug = false
local VariantDirectory = Root .. 'variant-release/'
TupConfig = nil
-- Start gathering info
local DebugFlag = Discover.Flag{Name = 'Debug', Description = 'Enables building a debug executable. The debug executable will be built in ' .. Root .. 'variant-debug/.'}
local Platform = Discover.Platform()
if DebugFlag.Present
then
Debug = true
VariantDirectory = Root .. 'variant-debug/'
end
if Platform.Family == 'windows'
then
VariantDirectory = Root
end
Tup = Discover.Program{Name = {'tup', 'tup-lua'}}
Guard(function()
if Platform.Family ~= 'windows'
then
Utility.MakeDirectory{Directory = VariantDirectory}
end
Utility.Call{Command = Tup.Location .. ' init', WorkingDirectory = Root}
local Error
TupConfig, Error = io.open(VariantDirectory .. 'tup.config', 'w')
if not TupConfig then error(Error) end
if Debug then TupConfig:write 'CONFIG_DEBUG=true\n' end
TupConfig:write('CONFIG_ROOT=' .. Root .. '\n')
TupConfig:write('CONFIG_VERSION=' .. Info.Version .. '\n')
TupConfig:write('CONFIG_CFLAGS=' .. (os.getenv 'CFLAGS' or '') .. '\n')
end)
if Debug
then
Guard(function()
TupConfig:write('CONFIG_DATADIRECTORY=' .. Root .. 'data/\n')
end)
else
if Platform.Family == 'windows'
then
Guard(function()
TupConfig:write('CONFIG_DATADIRECTORY=.\n')
end)
else
local InstallData = Discover.InstallDataDirectory{Project = 'inscribist'}
Guard(function()
TupConfig:write('CONFIG_DATADIRECTORY=' .. InstallData.Location .. '\n')
end)
end
end
Guard(function()
TupConfig:write('CONFIG_PLATFORM=')
if Platform.Family == 'windows'
then
TupConfig:write 'windows\n'
else
TupConfig:write 'linux\n'
end
end)
local Compiler = Discover.CXXCompiler{CXX11 = true}
Guard(function()
TupConfig:write('CONFIG_COMPILERNAME=' .. Compiler.Name .. '\n')
TupConfig:write('CONFIG_COMPILER=' .. Compiler.Path .. '\n')
end)
-- Locate libraries
local LinkDirectories = {}
local IncludeDirectories = {}
local LinkFlags = {}
local PackageLibBinaries = {}
local Libraries = {
{ Name = {'lua52', 'lua'}},
{ Name = {'bz2', 'bzip2'}},
{ Name = {'gtk-2.0', 'gtk-x11-2.0', 'gtk-win32-2.0-0'}},
{ Name = {'gdk-2.0', 'gdk-x11-2.0', 'gdk-win32-2.0-0'}},
{ Name = {'atk-1.0', 'atk-1.0-0'}},
{ Name = {'gio-2.0', 'gio-2.0-0'}},
{ Name = {'pangoft2-1.0', 'pangoft2-1.0-0'}},
{ Name = {'pangocairo-1.0', 'pangocairo-1.0-0'}},
{ Name = {'gdk_pixbuf-2.0', 'gdk_pixbuf-2.0-0'}},
{ Name = {'cairo', 'cairo-2'}},
{ Name = {'pango-1.0', 'pango-1.0-0'}},
{ Name = {'freetype', 'freetype6'}},
{ Name = {'fontconfig', 'fontconfig-1'}},
{ Name = {'gobject-2.0', 'gobject-2.0-0'}},
{ Name = {'glib-2.0', 'glib-2.0-0'}},
{ Name = {'intl'}, Windows = true},
{ Name = {'expat-1'}, Windows = true, NoLink = true},
{ Name = {'png14-14'}, Windows = true, NoLink = true},
{ Name = {'zlib1'}, Windows = true, NoLink = true},
{ Name = {'gmodule-2.0-0'}, Windows = true, NoLink = true},
{ Name = {'pangowin32-1.0-0'}, Windows = true, NoLink = true},
{ Name = {'gthread-2.0-0'}, Windows = true, NoLink = true},
{ Name = {'gcc_s_sjlj-1'}, Windows = true, NoLink = true},
{ Name = {'stdc++-6'}, Windows = true, NoLink = true}
}
function AddPackageLibBinary(LibraryInfo)
end
for Index, Library in ipairs(Libraries)
do
local LibraryInfo = Discover.CLibrary{Name = Library.Name}
Guard(function()
if (not Library.Windows or Platform.Family == 'windows') and not Library.NoLink
then
for DirectoryIndex, Directory in ipairs(LibraryInfo.IncludeDirectories) do
IncludeDirectories['-I"' .. Directory .. '"'] = true
end
for FilenameIndex, Filename in ipairs(LibraryInfo.Filenames) do
local ShortName = Filename:gsub('^lib', '')
ShortName = ShortName:gsub('%.so$', '')
ShortName = ShortName:gsub('%.so%..*', '')
ShortName = ShortName:gsub('%.dll$', '')
LinkFlags['-l' .. ShortName] = true
end
for DirectoryIndex, Directory in ipairs(LibraryInfo.LibraryDirectories) do
LinkDirectories['-L"' .. Directory .. '"'] = true
end
end
if Platform.Family == 'windows'
then
if #LibraryInfo.LibraryDirectories > 1 or #LibraryInfo.Filenames > 1
then
error('Was pkg-config used for library ' .. Library .. '? Too much information, can\'t determine library files for packaging.')
end
table.insert(PackageLibBinaries, LibraryInfo.LibraryDirectories[1] .. '/' .. LibraryInfo.Filenames[1])
end
end)
end
Guard(function()
TupConfig:write 'CONFIG_LIBDIRECTORIES='
for Flag, Discard in pairs(LinkDirectories) do TupConfig:write(Flag .. ' ') end
TupConfig:write '\n'
TupConfig:write 'CONFIG_INCLUDEDIRECTORIES='
for Flag, Discard in pairs(IncludeDirectories) do TupConfig:write(Flag .. ' ') end
TupConfig:write '\n'
TupConfig:write 'CONFIG_LINKFLAGS='
for Flag, Discard in pairs(LinkFlags) do TupConfig:write(Flag .. ' ') end
TupConfig:write '\n'
end)
Guard(function()
if Platform.Family == 'windows'
then
local PackageInclude, Error = io.open('packaging/windows/package.include.lua', 'w')
if not PackageInclude then error(Error) end
PackageInclude:write 'LibBinaries = {\n'
for Index, File in ipairs(PackageLibBinaries)
do
PackageInclude:write('\t\'' .. File .. '\',\n')
end
PackageInclude:write '}\n\n'
end
end)
|
local Root = Discover.ControllerLocation() .. '/'
dofile(Root .. 'info.include.lua')
-- Setup
Discover.Version({Version = 1})
local Help = Discover.HelpMode()
local Guard = function(Action) -- Helps prevent filesystem changes in help mode
if not Help then Action() end
end
local Debug = false
local VariantDirectory = Root .. 'variant-release/'
TupConfig = nil
-- Start gathering info
local DebugFlag = Discover.Flag{Name = 'Debug', Description = 'Enables building a debug executable. The debug executable will be built in ' .. Root .. 'variant-debug/.'}
local Platform = Discover.Platform()
if DebugFlag.Present
then
Debug = true
VariantDirectory = Root .. 'variant-debug/'
end
if Platform.Family == 'windows'
then
VariantDirectory = Root
end
Tup = Discover.Program{Name = {'tup', 'tup-lua'}}
Guard(function()
if Platform.Family ~= 'windows'
then
Utility.MakeDirectory{Directory = VariantDirectory}
end
Utility.Call{Command = Tup.Location .. ' init', WorkingDirectory = Root}
local Error
TupConfig, Error = io.open(VariantDirectory .. 'tup.config', 'w')
if not TupConfig then error(Error) end
if Debug then TupConfig:write 'CONFIG_DEBUG=true\n' end
TupConfig:write('CONFIG_ROOT=' .. Root .. '\n')
TupConfig:write('CONFIG_VERSION=' .. Info.Version .. '\n')
TupConfig:write('CONFIG_CFLAGS=' .. (os.getenv 'CFLAGS' or '') .. '\n')
end)
if Debug
then
Guard(function()
TupConfig:write('CONFIG_DATADIRECTORY=' .. Root .. 'data/\n')
end)
else
if Platform.Family ~= 'windows'
then
local InstallData = Discover.InstallDataDirectory{Project = 'inscribist'}
Guard(function()
TupConfig:write('CONFIG_DATADIRECTORY=' .. InstallData.Location .. '\n')
end)
end
end
Guard(function()
TupConfig:write('CONFIG_PLATFORM=')
if Platform.Family == 'windows'
then
TupConfig:write 'windows\n'
else
TupConfig:write 'linux\n'
end
end)
local Compiler = Discover.CXXCompiler{CXX11 = true}
Guard(function()
TupConfig:write('CONFIG_COMPILERNAME=' .. Compiler.Name .. '\n')
TupConfig:write('CONFIG_COMPILER=' .. Compiler.Path .. '\n')
end)
-- Locate libraries
local LinkDirectories = {}
local IncludeDirectories = {}
local LinkFlags = {}
local PackageLibBinaries = {}
local Libraries = {
{ Name = {'lua52', 'lua'}},
{ Name = {'bz2', 'bzip2'}},
{ Name = {'gtk-2.0', 'gtk-x11-2.0', 'gtk-win32-2.0-0'}},
{ Name = {'gdk-2.0', 'gdk-x11-2.0', 'gdk-win32-2.0-0'}},
{ Name = {'atk-1.0', 'atk-1.0-0'}},
{ Name = {'gio-2.0', 'gio-2.0-0'}},
{ Name = {'pangoft2-1.0', 'pangoft2-1.0-0'}},
{ Name = {'pangocairo-1.0', 'pangocairo-1.0-0'}},
{ Name = {'gdk_pixbuf-2.0', 'gdk_pixbuf-2.0-0'}},
{ Name = {'cairo', 'cairo-2'}},
{ Name = {'pango-1.0', 'pango-1.0-0'}},
{ Name = {'freetype', 'freetype6'}},
{ Name = {'fontconfig', 'fontconfig-1'}},
{ Name = {'gobject-2.0', 'gobject-2.0-0'}},
{ Name = {'glib-2.0', 'glib-2.0-0'}},
{ Name = {'intl'}, Windows = true},
{ Name = {'expat-1'}, Windows = true, NoLink = true},
{ Name = {'png14-14'}, Windows = true, NoLink = true},
{ Name = {'zlib1'}, Windows = true, NoLink = true},
{ Name = {'gmodule-2.0-0'}, Windows = true, NoLink = true},
{ Name = {'pangowin32-1.0-0'}, Windows = true, NoLink = true},
{ Name = {'gthread-2.0-0'}, Windows = true, NoLink = true},
{ Name = {'gcc_s_sjlj-1'}, Windows = true, NoLink = true},
{ Name = {'stdc++-6'}, Windows = true, NoLink = true}
}
function AddPackageLibBinary(LibraryInfo)
end
for Index, Library in ipairs(Libraries)
do
local LibraryInfo = Discover.CLibrary{Name = Library.Name}
Guard(function()
if (not Library.Windows or Platform.Family == 'windows') and not Library.NoLink
then
for DirectoryIndex, Directory in ipairs(LibraryInfo.IncludeDirectories) do
IncludeDirectories['-I"' .. Directory .. '"'] = true
end
for FilenameIndex, Filename in ipairs(LibraryInfo.Filenames) do
local ShortName = Filename:gsub('^lib', '')
ShortName = ShortName:gsub('%.so$', '')
ShortName = ShortName:gsub('%.so%..*', '')
ShortName = ShortName:gsub('%.dll$', '')
LinkFlags['-l' .. ShortName] = true
end
for DirectoryIndex, Directory in ipairs(LibraryInfo.LibraryDirectories) do
LinkDirectories['-L"' .. Directory .. '"'] = true
end
end
if Platform.Family == 'windows'
then
if #LibraryInfo.LibraryDirectories > 1 or #LibraryInfo.Filenames > 1
then
error('Was pkg-config used for library ' .. Library .. '? Too much information, can\'t determine library files for packaging.')
end
table.insert(PackageLibBinaries, LibraryInfo.LibraryDirectories[1] .. '/' .. LibraryInfo.Filenames[1])
end
end)
end
Guard(function()
TupConfig:write 'CONFIG_LIBDIRECTORIES='
for Flag, Discard in pairs(LinkDirectories) do TupConfig:write(Flag .. ' ') end
TupConfig:write '\n'
TupConfig:write 'CONFIG_INCLUDEDIRECTORIES='
for Flag, Discard in pairs(IncludeDirectories) do TupConfig:write(Flag .. ' ') end
TupConfig:write '\n'
TupConfig:write 'CONFIG_LINKFLAGS='
for Flag, Discard in pairs(LinkFlags) do TupConfig:write(Flag .. ' ') end
TupConfig:write '\n'
end)
Guard(function()
if Platform.Family == 'windows'
then
local PackageInclude, Error = io.open('packaging/windows/package.include.lua', 'w')
if not PackageInclude then error(Error) end
PackageInclude:write 'LibBinaries = {\n'
for Index, File in ipairs(PackageLibBinaries)
do
PackageInclude:write('\t\'' .. File .. '\',\n')
end
PackageInclude:write '}\n\n'
end
end)
|
Fixes to executable location determination.
|
Fixes to executable location determination.
|
Lua
|
bsd-3-clause
|
Rendaw/inscribist,Rendaw/inscribist
|
44e4327aef39d9cbf1e96cc8ff3b0d67643cb470
|
shared/maploader.lua
|
shared/maploader.lua
|
local Class = require "shared.middleclass"
local MapLoader = Class "MapLoader"
local sti = require "libs.sti"
local blocking = require "shared.blocking"
function MapLoader:initialize(mapName, spawnFunction)
local map = sti.new("maps/" .. mapName)
blocking.setMap(map)
local objects
for k, v in pairs(map.tilesets) do
if v.name == "objects" then
objects = v.tiles
break
end
end
for k, v in pairs(map.layers.Objects.objects) do
local tile = map.tiles[v.gid]
spawnFunction(tile, v.x + width/2, v.y + height/2)
end
end
return MapLoader
|
local Class = require "shared.middleclass"
local MapLoader = Class "MapLoader"
local sti = require "libs.sti"
local blocking = require "shared.blocking"
function MapLoader:initialize(mapName, spawnFunction)
local map = sti.new("maps/" .. mapName)
blocking.setMap(map)
local objects
for k, v in pairs(map.tilesets) do
if v.name == "objects" then
objects = v.tiles
break
end
end
for k, v in pairs(map.layers.Objects.objects) do
local tile = map.tiles[v.gid]
spawnFunction(tile, v.x + tile.width/2, v.y + tile.height/2)
end
self.map = map
end
return MapLoader
|
Fix: MapLoader width/height
|
Fix: MapLoader width/height
|
Lua
|
mit
|
ExcelF/project-navel
|
370a4c6873cd49733fef19fb58b05e09d635d1cd
|
src/lugate/request.lua
|
src/lugate/request.lua
|
----------------------
-- The lugate module.
-- Lugate is a lua module for building JSON-RPC 2.0 Gateway APIs just inside of your Nginx configuration file.
-- Lugate is meant to be used with [ngx\_http\_lua\_module](https://github.com/openresty/lua-nginx-module) together.
--
-- @classmod lugate.request
-- @author Ivan Zinovyev <[email protected]>
-- @license MIT
--- Request obeject
local Request = {}
--- Create new request
-- param[type=table] data Request data
-- param[type=table] lugate Lugate instance
-- return[type=table] New request instance
function Request:new(data, lugate)
assert(type(data) == "table", "Parameter 'data' is required and should be a table!")
assert(type(lugate) == "table", "Parameter 'lugate' is required and should be a table!")
local request = setmetatable({}, Request)
self.__index = self
request.lugate = lugate
request.data = data
return request
end
--- Check if request is valid JSON-RPC 2.0
-- @return[type=boolean]
function Request:is_valid()
if nil == self.valid then
self.valid = not self:is_empty()
and self.data.jsonrpc
and self.data.method
and true or false
end
return self.valid
end
--- Check if request is empty
-- @return[type=boolean]
function Request:is_empty()
return not next(self.data)
end
--- Check if request is a valid Lugate proxy call over JSON-RPC 2.0
-- @param[type=table] data Decoded request body
-- @return[type=boolean]
function Request:is_proxy_call()
if nil == self.proxy_call then
self.proxy_call = self:is_valid()
and self.data.params
and self.data.params.route
and true or false
end
return self.proxy_call
end
--- Get JSON-RPC version
-- @return[type=string]
function Request:get_jsonrpc()
return self.data.jsonrpc
end
--- Get method name
-- @return[type=string]
function Request:get_method()
return self.data.method
end
--- Get request params (search for nested params)
-- @return[type=table]
function Request:get_params()
return self:is_proxy_call() and self.data.params.params or self.data.params
end
--- Get request id
-- @return[type=int]
function Request:get_id()
return self.data.id
end
--- Get request route
-- @return[type=string]
function Request:get_route()
return self:is_proxy_call() and self.data.params.route or nil
end
--- Get request cache key
-- @return[type=string]
function Request:get_ttl()
return self.data.params and self.data.params.cache and self.data.params.cache.ttl or false
end
--- Get request cache key
-- @return[type=string]
function Request:get_key()
return self.data.params and self.data.params.cache and self.data.params.cache.key or false
end
--- Check if request is cachable
-- @return[type=boolean]
function Request:is_cachable()
return self:get_ttl() and self:get_key() and true or false
end
--- Get which uri is passing for request data
-- @return[type=string] Request uri
-- @return[type=string] Error
function Request:get_uri()
if self:is_proxy_call() then
for route, uri in pairs(self.lugate.routes) do
local uri, matches = string.gsub(self:get_route(), route, uri);
if matches >= 1 then
return uri, nil
end
end
end
return nil, 'Failed to bind the route'
end
--- Get request data table
-- @return[type=table]
function Request:get_data()
return {
jsonrpc = self:get_jsonrpc(),
id = self:get_id(),
method = self:get_method(),
params = self:get_params()
}
end
--- Get request body
-- @return[type=string] Json array
function Request:get_body()
return self.lugate.json.encode(self:get_data())
end
--- Build a request in format acceptable by nginx
-- @param[type=table] data Decoded requets body
-- @return[type=string] Uri
-- @return[type=string] Error message
function Request:get_ngx_request()
local uri, err = self:get_uri()
if uri then
return { self:get_uri(), { method = 8, body = self:get_body() } }, nil
end
return nil, err
end
return Request
|
----------------------
-- The lugate module.
-- Lugate is a lua module for building JSON-RPC 2.0 Gateway APIs just inside of your Nginx configuration file.
-- Lugate is meant to be used with [ngx\_http\_lua\_module](https://github.com/openresty/lua-nginx-module) together.
--
-- @classmod lugate.request
-- @author Ivan Zinovyev <[email protected]>
-- @license MIT
--- Request obeject
local Request = {}
--- Create new request
-- param[type=table] data Request data
-- param[type=table] lugate Lugate instance
-- return[type=table] New request instance
function Request:new(data, lugate)
assert(type(data) == "table", "Parameter 'data' is required and should be a table!")
assert(type(lugate) == "table", "Parameter 'lugate' is required and should be a table!")
local request = setmetatable({}, Request)
self.__index = self
request.lugate = lugate
request.data = data
return request
end
--- Check if request is valid JSON-RPC 2.0
-- @return[type=boolean]
function Request:is_valid()
if nil == self.valid then
self.valid = not self:is_empty()
and self.data.jsonrpc
and self.data.method
and true or false
end
return self.valid
end
--- Check if request is empty
-- @return[type=boolean]
function Request:is_empty()
return not next(self.data)
end
--- Check if request is a valid Lugate proxy call over JSON-RPC 2.0
-- @param[type=table] data Decoded request body
-- @return[type=boolean]
function Request:is_proxy_call()
if nil == self.proxy_call then
self.proxy_call = self:is_valid()
and self.data.params
and self.data.params.route
and true or false
end
return self.proxy_call
end
--- Get JSON-RPC version
-- @return[type=string]
function Request:get_jsonrpc()
return self.data.jsonrpc
end
--- Get method name
-- @return[type=string]
function Request:get_method()
return self.data.method
end
--- Get request params (search for nested params)
-- @return[type=table]
function Request:get_params()
return self:is_proxy_call() and self.data.params.params or self.data.params
end
--- Get request id
-- @return[type=int]
function Request:get_id()
return self.data.id
end
--- Get request route
-- @return[type=string]
function Request:get_route()
return self:is_proxy_call() and self.data.params.route or nil
end
--- Get request cache key
-- @return[type=string]
function Request:get_ttl()
return self.data.params and 'table' == type(self.data.params.cache) and self.data.params.cache.ttl or false
end
--- Get request cache key
-- @return[type=string]
function Request:get_key()
return self.data.params and 'table' == type(self.data.params.cache) and self.data.params.cache.key or false
end
--- Check if request is cachable
-- @return[type=boolean]
function Request:is_cachable()
return self:get_ttl() and self:get_key() and true or false
end
--- Get which uri is passing for request data
-- @return[type=string] Request uri
-- @return[type=string] Error
function Request:get_uri()
if self:is_proxy_call() then
for route, uri in pairs(self.lugate.routes) do
local uri, matches = string.gsub(self:get_route(), route, uri);
if matches >= 1 then
return uri, nil
end
end
end
return nil, 'Failed to bind the route'
end
--- Get request data table
-- @return[type=table]
function Request:get_data()
return {
jsonrpc = self:get_jsonrpc(),
id = self:get_id(),
method = self:get_method(),
params = self:get_params()
}
end
--- Get request body
-- @return[type=string] Json array
function Request:get_body()
return self.lugate.json.encode(self:get_data())
end
--- Build a request in format acceptable by nginx
-- @param[type=table] data Decoded requets body
-- @return[type=string] Uri
-- @return[type=string] Error message
function Request:get_ngx_request()
local uri, err = self:get_uri()
if uri then
return { self:get_uri(), { method = 8, body = self:get_body() } }, nil
end
return nil, err
end
return Request
|
Fix for params type
|
Fix for params type
|
Lua
|
mit
|
zinovyev/lugate,zinovyev/lugate
|
0dc79c5866fd3abf50770e050735e59d7c1f629b
|
lua/include/histogram.lua
|
lua/include/histogram.lua
|
local histogram = {}
histogram.__index = histogram
function histogram:create()
local histo = setmetatable({}, histogram)
histo.histo = {}
histo.dirty = true
return histo
end
histogram.new = histogram.create
setmetatable(histogram, { __call = histogram.create })
function histogram:update(k)
if not k then return end
self.histo[k] = (self.histo[k] or 0) +1
self.dirty = true
end
function histogram:calc()
self.sortedHisto = {}
self.sum = 0
self.numSamples = 0
for k, v in pairs(self.histo) do
table.insert(self.sortedHisto, { k = k, v = v })
self.numSamples = self.numSamples + v
self.sum = self.sum + k * v
end
self.avg = self.sum / self.numSamples
local stdDevSum = 0
for k, v in pairs(self.histo) do
stdDevSum = stdDevSum + v * (k - self.avg)^2
end
self.stdDev = (stdDevSum / (self.numSamples - 1)) ^ 0.5
table.sort(self.sortedHisto, function(e1, e2) return e1.k < e2.k end)
-- TODO: this is obviously not entirely correct for numbers not divisible by 4
-- however, it doesn't really matter for the number of samples we usually use
local quartSamples = self.numSamples / 4
self.quarts = {}
local idx = 0
for _, p in ipairs(self.sortedHisto) do
-- TODO: inefficient
for _ = 1, p.v do
if not self.quarts[1] and idx >= quartSamples then
self.quarts[1] = p.k
elseif not self.quarts[2] and idx >= quartSamples * 2 then
self.quarts[2] = p.k
elseif not self.quarts[3] and idx >= quartSamples * 3 then
self.quarts[3] = p.k
break
end
idx = idx + 1
end
end
self.dirty = false
end
function histogram:totals()
if self.dirty then self:calc() end
return self.numSamples, self.sum, self.avg
end
function histogram:avg()
if self.dirty then self:calc() end
return self.avg
end
function histogram:standardDeviation()
if self.dirty then self:calc() end
return self.stdDev
end
function histogram:quartiles()
if self.dirty then self:calc() end
return unpack(self.quarts)
end
function histogram:median()
if self.dirty then self:calc() end
return self.quarts[2]
end
function histogram:samples()
local i = 0
if self.dirty then self:calc() end
local n = #self.sortedHisto
return function()
if not self.dirty then
i = i + 1
if i <= n then return self.sortedHisto[i] end
end
end
end
-- FIXME: add support for different formats
function histogram:print()
if self.dirty then self:calc() end
printf("Samples: %d, Average: %.1f, StdDev: %.1f, Quartiles: %.1f/%.1f/%.1f", self.numSamples, self.avg, self.stdDev, unpack(self.quarts))
end
return histogram
|
local histogram = {}
histogram.__index = histogram
function histogram:create()
local histo = setmetatable({}, histogram)
histo.histo = {}
histo.dirty = true
return histo
end
histogram.new = histogram.create
setmetatable(histogram, { __call = histogram.create })
function histogram:update(k)
if not k then return end
self.histo[k] = (self.histo[k] or 0) +1
self.dirty = true
end
function histogram:calc()
self.sortedHisto = {}
self.sum = 0
self.numSamples = 0
for k, v in pairs(self.histo) do
table.insert(self.sortedHisto, { k = k, v = v })
self.numSamples = self.numSamples + v
self.sum = self.sum + k * v
end
self.avg = self.sum / self.numSamples
local stdDevSum = 0
for k, v in pairs(self.histo) do
stdDevSum = stdDevSum + v * (k - self.avg)^2
end
self.stdDev = (stdDevSum / (self.numSamples - 1)) ^ 0.5
table.sort(self.sortedHisto, function(e1, e2) return e1.k < e2.k end)
-- TODO: this is obviously not entirely correct for numbers not divisible by 4
-- however, it doesn't really matter for the number of samples we usually use
local quartSamples = self.numSamples / 4
self.quarts = {}
local idx = 0
for _, p in ipairs(self.sortedHisto) do
-- TODO: inefficient
for _ = 1, p.v do
if not self.quarts[1] and idx >= quartSamples then
self.quarts[1] = p.k
elseif not self.quarts[2] and idx >= quartSamples * 2 then
self.quarts[2] = p.k
elseif not self.quarts[3] and idx >= quartSamples * 3 then
self.quarts[3] = p.k
break
end
idx = idx + 1
end
end
for i = 1, 3 do
if not self.quarts[i] then
self.quarts[i] = 0/0
end
end
self.dirty = false
end
function histogram:totals()
if self.dirty then self:calc() end
return self.numSamples, self.sum, self.avg
end
function histogram:avg()
if self.dirty then self:calc() end
return self.avg
end
function histogram:standardDeviation()
if self.dirty then self:calc() end
return self.stdDev
end
function histogram:quartiles()
if self.dirty then self:calc() end
return unpack(self.quarts)
end
function histogram:median()
if self.dirty then self:calc() end
return self.quarts[2]
end
function histogram:samples()
local i = 0
if self.dirty then self:calc() end
local n = #self.sortedHisto
return function()
if not self.dirty then
i = i + 1
if i <= n then return self.sortedHisto[i] end
end
end
end
-- FIXME: add support for different formats
function histogram:print()
if self.dirty then self:calc() end
printf("Samples: %d, Average: %.1f, StdDev: %.1f, Quartiles: %.1f/%.1f/%.1f", self.numSamples, self.avg, self.stdDev, unpack(self.quarts))
end
return histogram
|
fix quartiles of empty histograms
|
fix quartiles of empty histograms
|
Lua
|
mit
|
emmericp/MoonGen,gallenmu/MoonGen,werpat/MoonGen,kidaa/MoonGen,wenhuizhang/MoonGen,pavel-odintsov/MoonGen,atheurer/MoonGen,gallenmu/MoonGen,werpat/MoonGen,slyon/MoonGen,atheurer/MoonGen,emmericp/MoonGen,schoenb/MoonGen,gallenmu/MoonGen,slyon/MoonGen,kidaa/MoonGen,duk3luk3/MoonGen,bmichalo/MoonGen,scholzd/MoonGen,scholzd/MoonGen,duk3luk3/MoonGen,bmichalo/MoonGen,werpat/MoonGen,emmericp/MoonGen,NetronomeMoongen/MoonGen,dschoeffm/MoonGen,bmichalo/MoonGen,slyon/MoonGen,duk3luk3/MoonGen,pavel-odintsov/MoonGen,schoenb/MoonGen,gallenmu/MoonGen,NetronomeMoongen/MoonGen,atheurer/MoonGen,gallenmu/MoonGen,wenhuizhang/MoonGen,wenhuizhang/MoonGen,gallenmu/MoonGen,dschoeffm/MoonGen,NetronomeMoongen/MoonGen,pavel-odintsov/MoonGen,gallenmu/MoonGen,schoenb/MoonGen,slyon/MoonGen,kidaa/MoonGen,scholzd/MoonGen,gallenmu/MoonGen,bmichalo/MoonGen,dschoeffm/MoonGen
|
cbad38152f8b3f27888fe1c5ff9c95acb25dc71e
|
tests/plugins/project/test.lua
|
tests/plugins/project/test.lua
|
import("detect.sdks.find_vstudio")
import("core.project.config")
import("core.platform.platform")
import("core.tool.toolchain")
function test_vsxmake(t)
if not is_subhost("windows") then
return t:skip("wrong host platform")
end
local projname = "testproj"
local tempdir = os.tmpfile()
os.mkdir(tempdir)
os.cd(tempdir)
-- create project
os.runv("xmake", {"create", projname})
os.cd(projname)
-- set config
local arch = os.getenv("platform") or "x86"
config.set("arch", arch, {readonly = true, force = true})
config.check()
platform.load(config.plat())
-- create sln & vcxproj
local vs = config.get("vs")
local vstype = "vsxmake" .. vs
os.execv("xmake", {"project", "-k", vstype, "-a", arch})
os.cd(vstype)
-- run msbuild
try
{
function ()
os.execv("msbuild", {"/P:XmakeDiagnosis=true", "/P:XmakeVerbose=true"}, {envs = toolchain.load("msvc"):runenvs()})
end,
catch
{
function ()
print("--- sln file ---")
io.cat(projname .. "_" .. vstype .. ".sln")
print("--- vcx file ---")
io.cat(projname .. "/" .. projname .. ".vcxproj")
print("--- filter file ---")
io.cat(projname .. "/" .. projname .. ".vcxproj.filters")
raise("msbuild failed")
end
}
}
-- clean up
os.cd(os.scriptdir())
os.tryrm(tempdir)
end
|
import("detect.sdks.find_vstudio")
import("core.project.config")
import("core.platform.platform")
import("core.tool.toolchain")
function test_vsxmake(t)
if not is_subhost("windows") then
return t:skip("wrong host platform")
end
local projname = "testproj"
local tempdir = os.tmpfile()
os.mkdir(tempdir)
os.cd(tempdir)
-- create project
os.runv("xmake", {"create", projname})
os.cd(projname)
-- set config
local arch = os.getenv("platform") or "x86"
config.set("arch", arch, {readonly = true, force = true})
config.check()
platform.load(config.plat())
-- create sln & vcxproj
local vs = config.get("vs")
local vstype = "vsxmake" .. vs
os.execv("xmake", {"project", "-k", vstype, "-a", arch})
os.cd(vstype)
-- run msbuild
try
{
function ()
local runenvs = toolchain.load("msvc"):runenvs()
os.addenv("PATH", runenvs.PATH)
os.execv("msbuild", {"/P:XmakeDiagnosis=true", "/P:XmakeVerbose=true"}, {envs = runenvs})
end,
catch
{
function ()
print("--- sln file ---")
io.cat(projname .. "_" .. vstype .. ".sln")
print("--- vcx file ---")
io.cat(projname .. "/" .. projname .. ".vcxproj")
print("--- filter file ---")
io.cat(projname .. "/" .. projname .. ".vcxproj.filters")
raise("msbuild failed")
end
}
}
-- clean up
os.cd(os.scriptdir())
os.tryrm(tempdir)
end
|
fix test for calling msbuild
|
fix test for calling msbuild
|
Lua
|
apache-2.0
|
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
|
4dfdf0127057bfe108a0204c04ccbe38ebf07d4b
|
src/logging/file.lua
|
src/logging/file.lua
|
-------------------------------------------------------------------------------
-- Saves logging information in a file
--
-- @author Thiago Costa Ponte ([email protected])
--
-- @copyright 2004-2007 Kepler Project
--
-- @release $Id: file.lua,v 1.5 2007-09-05 12:15:31 tomas Exp $
-------------------------------------------------------------------------------
require"logging"
function logging.file(filename, datePattern, logPattern)
if type(filename) ~= "string" then
filename = "lualogging.log"
end
filename = string.format(filename, os.date(datePattern))
local f = io.open(filename, "a")
if not f then
return nil, string.format("file `%s' could not be opened for writing", filename)
end
f:setvbuf ("line")
return logging.new( function(self, level, message)
local s = logging.prepareLogMsg(logPattern, os.date(), level, message)
f:write(s)
return true
end
)
end
|
-------------------------------------------------------------------------------
-- Saves logging information in a file
--
-- @author Thiago Costa Ponte ([email protected])
--
-- @copyright 2004-2007 Kepler Project
--
-- @release $Id: file.lua,v 1.6 2008-07-28 16:23:38 alessandrohc Exp $
-------------------------------------------------------------------------------
require"logging"
local lastFileNameDatePattern
local lastFileHandler
local openFileLogger = function (filename, datePattern)
local filename = string.format(filename, os.date(datePattern))
if (lastFileNameDatePattern ~= filename) then
local f = io.open(filename, "a")
if (f) then
f:setvbuf ("line")
lastFileNameDatePattern = filename
lastFileHandler = f
return f
else
return nil, string.format("file `%s' could not be opened for writing", filename)
end
else
return lastFileHandler
end
end
function logging.file(filename, datePattern, logPattern)
if type(filename) ~= "string" then
filename = "lualogging.log"
end
local f, msg = openFileLogger(filename, datePattern)
if not f then
return nil, msg
end
return logging.new( function(self, level, message)
local f, msg = openFileLogger(filename, datePattern)
if not f then
return nil, msg
end
local s = logging.prepareLogMsg(logPattern, os.date(), level, message)
f:write(s)
return true
end
)
end
|
Fix the problem cause when the logger in file use the datePattern, but not considered the change of the date.
|
Fix the problem cause when the logger in file use the datePattern, but not considered the change of the date.
|
Lua
|
mit
|
Neopallium/lualogging,mwchase/log4l,StoneDot/lualogging
|
cdcfdb718dc83e3ecb55492256886d68144cbbd1
|
OS/DiskOS/Programs/Disks/save.lua
|
OS/DiskOS/Programs/Disks/save.lua
|
local destination, flag, ctype, clvl = ...
flag, ctype, clvl = flag or "", ctype or "gzip", tonumber(clvl or "9")
local term = require("terminal")
local eapi = require("Editors")
local png = false
if destination and destination ~= "@clip" and destination ~= "-?" then
destination = term.resolve(destination)
if destination:sub(-4,-1) == ".png" then
png = true
elseif destination:sub(-5,-1) ~= ".lk12" then
destination = destination..".lk12"
end
elseif not destination then
destination = eapi.filePath
end
if (not destination) or destination == "-?" then
printUsage(
"save <file>","Saves the current loaded game",
"save <file>.png","Save in a png disk",
"save <file>.png -color [color]","Specify the color of the png disk",
"save @clip","Saves into the clipboard",
"save <file> -c","Saves with compression",
"save <file> -b","Saves in binary format",
"save","Saves on the last known file",
"save <image> --sheet","Saves the spritesheet as external .lk12 image",
"save <filename> --code","Saves the code as a .lua file"
)
return
end
if destination ~= "@clip" and string.lower(flag) == "--code" then destination = destination:sub(1,-6)..".lua" end
if destination ~= "@clip" and fs.exists(destination) and fs.isDirectory(destination) then return 1, "Destination must not be a directory" end
if destination ~= "@clip" and fs.isReadonly(destination) then
return 1, "Destination is readonly !"
end
local backup
if destination ~= "@clip" and fs.exists(destination) and (flag == "" or flag == "-c" or flag == "-b") then
backup = fs.read(destination)
end
if destination ~= "@clip" and fs.exists(destination) then
while true do
color(9) print("Are you sure you want to overwrite the destination file ? (Y/N)") color(6)
local input = TextUtils.textInput() print("")
if input then
input = input:lower()
if input == "y" or input == "yes" then
break --The user has accepted to overwrite the file.
elseif input == "n" or input == "no" then
return 1, "User declined to overwrite the destination file."
end
end
end
end
local sw, sh = screenSize()
if string.lower(flag) == "--sheet" then --Sheet export
local data = eapi.leditors[eapi.editors.sprite]:export(true)
if destination == "@clip" then clipboard(data) else fs.write(destination,data) end
color(11) print("Exported Spritesheet successfully")
return
elseif string.lower(flag) == "--map" then --TileMap export
local data = eapi.leditors[eapi.editors.tile]:export(true)
if destination == "@clip" then clipboard(data) else fs.write(destination,data) end
color(11) print("Exported Spritesheet successfully")
return
elseif string.lower(flag) == "--code" then --Lua code export
local data = eapi.leditors[eapi.editors.code]:export(true)
if destination == "@clip" then clipboard(data) else fs.write(destination,data) end
color(11) print("Exported Lua code successfully")
return
end
eapi.filePath = destination
local editorsData = (string.lower(flag) == "-b") and eapi:encode() or eapi:export()
local apiVersion = eapi.apiVersion
local diskData = ""
if string.lower(flag) == "-c" or png then
diskData = LK12Utils.encodeDiskGame(editorsData,ctype,clvl,apiVersion)
elseif string.lower(flag) == "-b" then
diskData = LK12Utils.encodeDiskGame(editorsData,"binary",false,apiVersion)
else
diskData = LK12Utils.encodeDiskGame(editorsData,false,false,apiVersion)
end
if string.lower(flag) == "-color" and png then
FDD.newDisk(select(3,...))
else
FDD.newDisk("Blue")
end
if destination == "@clip" then
clipboard(diskData)
elseif png then
local diskSize = #diskData
if diskSize > 64*1024 then
return 1, "Save too big to fit in a floppy disk ("..(math.floor(diskSize/102.4)*10).." kb/ 64 kb) !"
end
memset(RamUtils.FRAM, diskData)
fs.write(destination, FDD.exportDisk())
else
fs.write(destination,diskData)
end
if backup then
fs.write("C:/_backup.lk12", backup)
end
color(11) print(destination == "@clip" and "Saved to clipboard successfully" or "Saved successfully")
|
local destination, flag, ctype, clvl = ...
flag, ctype, clvl = flag or "", ctype or "gzip", tonumber(clvl or "9")
local term = require("terminal")
local eapi = require("Editors")
local png = false
if destination and destination ~= "@clip" and destination ~= "-?" then
destination = term.resolve(destination)
if destination:sub(-4,-1) == ".png" then
png = true
elseif destination:sub(-5,-1) ~= ".lk12" then
destination = destination..".lk12"
end
elseif not destination then
destination = eapi.filePath
end
if (not destination) or destination == "-?" then
printUsage(
"save <file>","Saves the current loaded game",
"save <file>.png","Save in a png disk",
"save <file>.png -color [color]","Specify the color of the png disk",
"save @clip","Saves into the clipboard",
"save <file> -c","Saves with compression",
"save <file> -b","Saves in binary format",
"save","Saves on the last known file",
"save <image> --sheet","Saves the spritesheet as external .lk12 image",
"save <filename> --code","Saves the code as a .lua file"
)
return
end
if destination ~= "@clip" and string.lower(flag) == "--code" then destination = destination:sub(1,-6)..".lua" end
if destination ~= "@clip" and fs.exists(destination) and fs.isDirectory(destination) then return 1, "Destination must not be a directory" end
if destination ~= "@clip" and fs.isReadonly(destination) then
return 1, "Destination is readonly !"
end
local backup
if destination ~= "@clip" and fs.exists(destination) and (flag == "" or flag == "-c" or flag == "-b") then
backup = fs.read(destination)
end
if destination ~= "@clip" and fs.exists(destination) then
while true do
color(9) print("Are you sure you want to overwrite the destination file ? (Y/N)") color(6)
local input = TextUtils.textInput() print("")
if input then
input = input:lower()
if input == "y" or input == "yes" then
break --The user has accepted to overwrite the file.
elseif input == "n" or input == "no" then
return 1, "User declined to overwrite the destination file."
end
end
end
end
local sw, sh = screenSize()
if string.lower(flag) == "--sheet" then --Sheet export
local data = eapi.leditors[eapi.editors.sprite]:export(true)
if destination == "@clip" then clipboard(data) else fs.write(destination,data) end
color(11) print("Exported Spritesheet successfully")
return
elseif string.lower(flag) == "--map" then --TileMap export
local data = eapi.leditors[eapi.editors.tile]:export(true)
if destination == "@clip" then clipboard(data) else fs.write(destination,data) end
color(11) print("Exported Spritesheet successfully")
return
elseif string.lower(flag) == "--code" then --Lua code export
local data = eapi.leditors[eapi.editors.code]:export(true)
if destination == "@clip" then clipboard(data) else fs.write(destination,data) end
color(11) print("Exported Lua code successfully")
return
end
eapi.filePath = destination
local editorsData = (string.lower(flag) == "-b") and eapi:encode() or eapi:export()
local apiVersion = eapi.apiVersion
local diskData = ""
if string.lower(flag) == "-c" or png then
diskData = LK12Utils.encodeDiskGame(editorsData,flag == "-color" and "gzip" or ctype,clvl,apiVersion)
elseif string.lower(flag) == "-b" then
diskData = LK12Utils.encodeDiskGame(editorsData,"binary",false,apiVersion)
else
diskData = LK12Utils.encodeDiskGame(editorsData,false,false,apiVersion)
end
if string.lower(flag) == "-color" and png then
FDD.newDisk(select(3,...))
else
FDD.newDisk("Blue")
end
if destination == "@clip" then
clipboard(diskData)
elseif png then
local diskSize = #diskData
if diskSize > 64*1024 then
return 1, "Save too big to fit in a floppy disk ("..(math.floor(diskSize/102.4)*10).." kb/ 64 kb) !"
end
memset(RamUtils.FRAM, diskData)
fs.write(destination, FDD.exportDisk())
else
fs.write(destination,diskData)
end
if backup then
fs.write("C:/_backup.lk12", backup)
end
color(11) print(destination == "@clip" and "Saved to clipboard successfully" or "Saved successfully")
|
Fix disk color flag
|
Fix disk color flag
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
b3694b0a83f6954e530d79a4609eb2c8f3775fc2
|
common/shared/common.lua
|
common/shared/common.lua
|
keyChars = { { 48, 57 }, { 65, 90 }, { 97, 122 } }
pedModels = {
female = {
white = { 12, 31, 38, 39, 40, 41, 53, 54, 55, 56, 64, 75, 77, 85, 86, 87, 88, 89, 90, 91, 92, 93, 129, 130, 131, 138, 140, 145, 150, 151, 152, 157, 172, 178, 192, 193, 194, 196, 197, 198, 199, 201, 205, 211, 214, 216, 224, 225, 226, 231, 232, 233, 237, 243, 246, 251, 257, 263 },
black = { 9, 10, 11, 12, 13, 40, 41, 63, 64, 69, 76, 91, 139, 148, 190, 195, 207, 215, 218, 219, 238, 243, 244, 245, 256 },
asian = { 38, 53, 54, 55, 56, 88, 141, 169, 178, 224, 225, 226, 263 }
},
male = {
white = { 23, 26, 27, 29, 30, 32, 33, 34, 35, 36, 37, 38, 43, 44, 45, 46, 47, 48, 50, 51, 52, 53, 58, 59, 60, 61, 62, 68, 70, 72, 73, 78, 81, 82, 94, 95, 96, 97, 98, 99, 100, 101, 108, 109, 110, 111, 112, 113, 114, 115, 116, 120, 121, 122, 124, 125, 126, 127, 128, 132, 133, 135, 137, 146, 147, 153, 154, 155, 158, 159, 160, 161, 162, 164, 165, 170, 171, 173, 174, 175, 177, 179, 181, 184, 186, 187, 188, 189, 200, 202, 204, 206, 209, 212, 213, 217, 223, 230, 234, 235, 236, 240, 241, 242, 247, 248, 250, 252, 254, 255, 258, 259, 261, 264 },
black = { 7, 14, 15, 16, 17, 18, 20, 21, 22, 24, 25, 28, 35, 36, 50, 51, 66, 67, 78, 79, 80, 83, 84, 102, 103, 104, 105, 106, 107, 134, 136, 142, 143, 144, 156, 163, 166, 168, 176, 180, 182, 183, 185, 220, 221, 222, 249, 253, 260, 262 },
asian = { 49, 57, 58, 59, 60, 117, 118, 120, 121, 122, 123, 170, 186, 187, 203, 210, 227, 228, 229 }
}
}
function nextIndex( table )
local index = 1
while ( true ) do
if ( not table[ index ] ) then
return index
else
index = index + 1
end
end
end
function findByValue( _table, value, multiple, strict )
local result = { }
for k, v in pairs( _table ) do
if ( type( v ) == "table" ) then
for _k, _v in pairs( v ) do
if ( _v == value ) and ( ( not strict ) or ( ( strict ) and ( type( _v ) == type( value ) ) ) ) then
if ( multiple ) then
table.insert( result, k )
else
return k
end
end
end
else
if ( v == value ) and ( ( not strict ) or ( ( strict ) and ( type( v ) == type( value ) ) ) ) then
if ( multiple ) then
table.insert( result, k )
else
return k
end
end
end
end
return result
end
function count( table )
local count = 0
for _ in pairs( table ) do
count = count + 1
end
return count
end
function isLeapYear( year )
return ( year % 4 == 0 ) and ( year % 100 ~= 0 or year % 400 == 0 )
end
function getDaysInMonth( month, year )
return month == 2 and isLeapYear( year ) and 29 or ( "\31\28\31\30\31\30\31\31\30\31\30\31" ):byte( month )
end
function getValidPedModelsByGenderAndColor( gender, color )
return pedModels[ gender ][ color ]
end
function getRandomString( length )
local buffer = ""
for i = 0, length do
math.randomseed( getTickCount( ) .. i .. i .. math.random( 123, 789 ) )
local chars = keyChars[ math.random( #keyChars ) ]
buffer = buffer .. string.char( math.random( chars[ 1 ], chars[ 2 ] ) )
end
return buffer
end
|
keyChars = { { 48, 57 }, { 65, 90 }, { 97, 122 } }
pedModels = {
female = {
white = { 12, 31, 38, 39, 40, 41, 53, 54, 55, 56, 64, 75, 77, 85, 87, 88, 89, 90, 91, 92, 93, 129, 130, 131, 138, 140, 145, 150, 151, 152, 157, 172, 178, 192, 193, 194, 196, 197, 198, 199, 201, 205, 211, 214, 216, 224, 225, 226, 231, 232, 233, 237, 243, 246, 251, 257, 263 },
black = { 9, 10, 11, 12, 13, 40, 41, 63, 64, 69, 76, 91, 139, 148, 190, 195, 207, 215, 218, 219, 238, 243, 244, 245, 256 },
asian = { 38, 53, 54, 55, 56, 88, 141, 169, 178, 224, 225, 226, 263 }
},
male = {
white = { 23, 26, 27, 29, 30, 32, 33, 34, 35, 36, 37, 38, 43, 44, 45, 46, 47, 48, 50, 51, 52, 53, 58, 59, 60, 61, 62, 68, 70, 72, 73, 78, 81, 82, 94, 95, 96, 97, 98, 99, 100, 101, 108, 109, 110, 111, 112, 113, 114, 115, 116, 120, 121, 122, 124, 125, 126, 127, 128, 132, 133, 135, 137, 146, 147, 153, 154, 155, 158, 159, 160, 161, 162, 164, 165, 170, 171, 173, 174, 175, 177, 179, 181, 184, 186, 187, 188, 189, 200, 202, 204, 206, 209, 212, 213, 217, 223, 230, 234, 235, 236, 240, 241, 242, 247, 248, 250, 252, 254, 255, 258, 259, 261, 264 },
black = { 7, 14, 15, 16, 17, 18, 20, 21, 22, 24, 25, 28, 35, 36, 50, 51, 66, 67, 78, 79, 80, 83, 84, 102, 103, 104, 105, 106, 107, 134, 136, 142, 143, 144, 156, 163, 166, 168, 176, 180, 182, 183, 185, 220, 221, 222, 249, 253, 260, 262 },
asian = { 49, 57, 58, 59, 60, 117, 118, 120, 121, 122, 123, 170, 186, 187, 203, 210, 227, 228, 229 }
}
}
function nextIndex( table )
local index = 1
while ( true ) do
if ( not table[ index ] ) then
return index
else
index = index + 1
end
end
end
function findByValue( _table, value, multiple, strict )
local result = { }
for k, v in pairs( _table ) do
if ( type( v ) == "table" ) then
for _k, _v in pairs( v ) do
if ( _v == value ) and ( ( not strict ) or ( ( strict ) and ( type( _v ) == type( value ) ) ) ) then
if ( multiple ) then
table.insert( result, k )
else
return k
end
end
end
else
if ( v == value ) and ( ( not strict ) or ( ( strict ) and ( type( v ) == type( value ) ) ) ) then
if ( multiple ) then
table.insert( result, k )
else
return k
end
end
end
end
return result
end
function count( table )
local count = 0
for _ in pairs( table ) do
count = count + 1
end
return count
end
function isLeapYear( year )
return ( year % 4 == 0 ) and ( year % 100 ~= 0 or year % 400 == 0 )
end
function getDaysInMonth( month, year )
return month == 2 and isLeapYear( year ) and 29 or ( "\31\28\31\30\31\30\31\31\30\31\30\31" ):byte( month )
end
function getValidPedModelsByGenderAndColor( gender, color )
local gender, color = gender:lower( ), color:lower( )
return pedModels[ gender ] and pedModels[ gender ][ color ] or { }
end
function getRandomString( length )
local buffer = ""
for i = 0, length do
math.randomseed( getTickCount( ) .. i .. i .. math.random( 123, 789 ) )
local chars = keyChars[ math.random( #keyChars ) ]
buffer = buffer .. string.char( math.random( chars[ 1 ], chars[ 2 ] ) )
end
return buffer
end
|
common: fixed skin table and fetcher
|
common: fixed skin table and fetcher
|
Lua
|
mit
|
smile-tmb/lua-mta-fairplay-roleplay
|
a706b2cc9c9f3e002e7bd56b75fba03a6b17251e
|
extension/script/backend/worker/breakpoint.lua
|
extension/script/backend/worker/breakpoint.lua
|
local rdebug = require 'remotedebug.visitor'
local fs = require 'backend.worker.filesystem'
local source = require 'backend.worker.source'
local evaluate = require 'backend.worker.evaluate'
local ev = require 'backend.event'
local hookmgr = require 'remotedebug.hookmgr'
local parser = require 'backend.worker.parser'
local currentactive = {}
local waitverify = {}
local info = {}
local m = {}
local enable = false
local function updateHook()
if enable then
if next(currentactive) == nil and next(waitverify) == nil then
enable = false
hookmgr.break_open(false)
end
else
if next(currentactive) ~= nil or next(waitverify) ~= nil then
enable = true
hookmgr.break_open(true)
end
end
end
local function hasActiveBreakpoint(bps, activeline)
for line in pairs(bps) do
if activeline[line] then
return true
end
end
return false
end
local function updateBreakpoint(bpkey, src, lineinfo, bps)
if next(bps) == nil then
currentactive[bpkey] = nil
for proto in pairs(src.protos) do
hookmgr.break_del(proto)
end
else
currentactive[bpkey] = bps
for proto, key in pairs(src.protos) do
if hasActiveBreakpoint(bps, lineinfo[key]) then
hookmgr.break_add(proto)
else
hookmgr.break_del(proto)
end
end
end
updateHook()
end
local function bpKey(src)
if src.sourceReference then
return src.sourceReference
end
return fs.path_native(fs.path_normalize(src.path))
end
local function valid(bp)
if bp.condition then
if not evaluate.verify(bp.condition) then
return false
end
end
if bp.hitCondition then
if not evaluate.verify('0 ' .. bp.hitCondition) then
return false
end
end
return true
end
local function verifyBreakpoint(src, lineinfo, breakpoints)
local bpkey = bpKey(src)
local curbp = currentactive[bpkey]
local hits = {}
if curbp then
for _, bp in ipairs(curbp) do
hits[bp.realLine] = bp.statHit
end
end
local res = {}
for _, bp in ipairs(breakpoints) do
if not valid(bp) then
goto continue
end
local activeline = lineinfo[bp.line]
if not activeline then
goto continue
end
bp.source = src
bp.realLine = bp.line
bp.line = activeline
res[bp.line] = bp
bp.statHit = hits[bp.realLine] or 0
if bp.logMessage then
local n = 0
bp.statLog = {}
bp.statLog[1] = bp.logMessage:gsub('%b{}', function(str)
n = n + 1
local key = ('{%d}'):format(n)
bp.statLog[key] = str:sub(2,-2)
return key
end)
bp.statLog[1] = bp.statLog[1] .. '\n'
end
ev.emit('breakpoint', 'changed', {
id = bp.id,
line = bp.line,
message = bp.message,
verified = true,
})
::continue::
end
updateBreakpoint(bpkey, src, lineinfo, res)
end
function m.find(src, currentline)
local currentBP = currentactive[bpKey(src)]
if not currentBP then
hookmgr.break_closeline()
return
end
return currentBP[currentline]
end
local function getLineInfo(src, content)
if src then
if not src.lineinfo then
if content then
src.lineinfo = parser(content)
elseif src.sourceReference then
src.lineinfo = parser(source.getCode(src.sourceReference))
end
end
return src.lineinfo
end
if content then
return parser(content)
end
end
function m.set_bp(clientsrc, breakpoints, content)
local src = source.c2s(clientsrc)
local lineinfo = getLineInfo(src, content)
if lineinfo then
if src then
verifyBreakpoint(src, lineinfo, breakpoints)
else
waitverify[bpKey(clientsrc)] = {
breakpoints = breakpoints,
lineinfo = lineinfo,
}
updateHook()
end
end
end
function m.exec(bp)
if bp.condition then
local ok, res = evaluate.eval(bp.condition)
if not ok or not res then
return false
end
end
bp.statHit = bp.statHit + 1
if bp.hitCondition then
local ok, res = evaluate.eval(bp.statHit .. ' ' .. bp.hitCondition)
if not ok or res ~= true then
return false
end
end
if bp.statLog then
local res = bp.statLog[1]:gsub('{%d+}', function(key)
local info = bp.statLog[key]
if not info then
return key
end
local ok, res = evaluate.eval(info)
if not ok then
return '{'..info..'}'
end
return tostring(res)
end)
rdebug.getinfo(1, "Sl", info)
local src = source.create(info.source)
if source.valid(src) then
ev.emit('output', 'stdout', res, src, info.currentline)
else
ev.emit('output', 'stdout', res)
end
return false
end
return true
end
function m.newproto(proto, src, key)
src.protos[proto] = key
local bpkey = bpKey(src)
local wv = waitverify[bpkey]
if wv then
waitverify[bpkey] = nil
verifyBreakpoint(src, wv.lineinfo, wv.breakpoints)
end
end
local funcs = {}
function m.set_funcbp(breakpoints)
funcs = {}
for _, bp in ipairs(breakpoints) do
if evaluate.verify(bp.name) then
funcs[#funcs+1] = bp.name
end
end
hookmgr.funcbp_open(#funcs > 0)
end
function m.hit_funcbp(func)
for _, funcstr in ipairs(funcs) do
local ok, res = evaluate.eval(funcstr, 1)
if ok and res == func then
return true
end
end
end
ev.on('terminated', function()
currentactive = {}
waitverify = {}
info = {}
m = {}
enable = false
hookmgr.break_open(false)
end)
return m
|
local rdebug = require 'remotedebug.visitor'
local fs = require 'backend.worker.filesystem'
local source = require 'backend.worker.source'
local evaluate = require 'backend.worker.evaluate'
local ev = require 'backend.event'
local hookmgr = require 'remotedebug.hookmgr'
local parser = require 'backend.worker.parser'
local currentactive = {}
local waitverify = {}
local info = {}
local m = {}
local enable = false
local function updateHook()
if enable then
if next(currentactive) == nil and next(waitverify) == nil then
enable = false
hookmgr.break_open(false)
end
else
if next(currentactive) ~= nil or next(waitverify) ~= nil then
enable = true
hookmgr.break_open(true)
end
end
end
local function hasActiveBreakpoint(bps, activeline)
for line in pairs(bps) do
if activeline[line] then
return true
end
end
return false
end
local function updateBreakpoint(bpkey, src, lineinfo, bps)
if next(bps) == nil then
currentactive[bpkey] = nil
for proto in pairs(src.protos) do
hookmgr.break_del(proto)
end
else
currentactive[bpkey] = bps
for proto, key in pairs(src.protos) do
if hasActiveBreakpoint(bps, lineinfo[key]) then
hookmgr.break_add(proto)
else
hookmgr.break_del(proto)
end
end
end
updateHook()
end
local function bpKey(src)
if src.sourceReference then
return src.sourceReference
end
return fs.path_native(fs.path_normalize(src.path))
end
local function valid(bp)
if bp.condition then
if not evaluate.verify(bp.condition) then
return false
end
end
if bp.hitCondition then
if not evaluate.verify('0 ' .. bp.hitCondition) then
return false
end
end
return true
end
local function verifyBreakpoint(src, lineinfo, breakpoints)
local bpkey = bpKey(src)
local curbp = currentactive[bpkey]
local hits = {}
if curbp then
for _, bp in ipairs(curbp) do
hits[bp.realLine] = bp.statHit
end
end
local res = {}
for _, bp in ipairs(breakpoints) do
if not valid(bp) then
goto continue
end
local activeline = lineinfo[bp.line]
if not activeline then
goto continue
end
bp.source = src
bp.realLine = bp.line
bp.line = activeline
res[bp.line] = bp
bp.statHit = hits[bp.realLine] or 0
if bp.logMessage then
local n = 0
bp.statLog = {}
bp.statLog[1] = bp.logMessage:gsub('%b{}', function(str)
n = n + 1
local key = ('{%d}'):format(n)
bp.statLog[key] = str:sub(2,-2)
return key
end)
bp.statLog[1] = bp.statLog[1] .. '\n'
end
ev.emit('breakpoint', 'changed', {
id = bp.id,
line = bp.line,
message = bp.message,
verified = true,
})
::continue::
end
updateBreakpoint(bpkey, src, lineinfo, res)
end
function m.find(src, currentline)
local currentBP = currentactive[bpKey(src)]
if not currentBP then
hookmgr.break_closeline()
return
end
return currentBP[currentline]
end
local function getLineInfo(src, content)
if src then
if not src.lineinfo then
if content then
src.lineinfo = parser(content)
elseif src.sourceReference then
src.lineinfo = parser(source.getCode(src.sourceReference))
end
end
return src.lineinfo
end
if content then
return parser(content)
end
end
function m.set_bp(clientsrc, breakpoints, content)
local src = source.c2s(clientsrc)
local lineinfo = getLineInfo(src, content)
if lineinfo then
if src then
verifyBreakpoint(src, lineinfo, breakpoints)
else
waitverify[bpKey(clientsrc)] = {
breakpoints = breakpoints,
lineinfo = lineinfo,
}
updateHook()
end
end
end
function m.exec(bp)
if bp.condition then
local ok, res = evaluate.eval(bp.condition)
if not ok or not res then
return false
end
end
bp.statHit = bp.statHit + 1
if bp.hitCondition then
local ok, res = evaluate.eval(bp.statHit .. ' ' .. bp.hitCondition)
if not ok or res ~= true then
return false
end
end
if bp.statLog then
local res = bp.statLog[1]:gsub('{%d+}', function(key)
local info = bp.statLog[key]
if not info then
return key
end
local ok, res = evaluate.eval(info)
if not ok then
return '{'..info..'}'
end
return tostring(res)
end)
rdebug.getinfo(1, "Sl", info)
local src = source.create(info.source)
if source.valid(src) then
ev.emit('output', 'stdout', res, src, info.currentline)
else
ev.emit('output', 'stdout', res)
end
return false
end
return true
end
function m.newproto(proto, src, key)
src.protos[proto] = key
local bpkey = bpKey(src)
local wv = waitverify[bpkey]
if wv then
waitverify[bpkey] = nil
src.lineinfo = wv.lineinfo
verifyBreakpoint(src, wv.lineinfo, wv.breakpoints)
return
end
local bps = currentactive[bpkey]
if bps and src.lineinfo then
updateBreakpoint(key, src, src.lineinfo, bps)
return
end
end
local funcs = {}
function m.set_funcbp(breakpoints)
funcs = {}
for _, bp in ipairs(breakpoints) do
if evaluate.verify(bp.name) then
funcs[#funcs+1] = bp.name
end
end
hookmgr.funcbp_open(#funcs > 0)
end
function m.hit_funcbp(func)
for _, funcstr in ipairs(funcs) do
local ok, res = evaluate.eval(funcstr, 1)
if ok and res == func then
return true
end
end
end
ev.on('terminated', function()
currentactive = {}
waitverify = {}
info = {}
m = {}
enable = false
hookmgr.break_open(false)
end)
return m
|
Fixes #100
|
Fixes #100
|
Lua
|
mit
|
actboy168/vscode-lua-debug,actboy168/vscode-lua-debug,actboy168/vscode-lua-debug
|
4ae43aee2c084e31aa1134a2c92d20f7681fdfcc
|
frontend/device/cervantes/device.lua
|
frontend/device/cervantes/device.lua
|
local Generic = require("device/generic/device")
local TimeVal = require("ui/timeval")
local logger = require("logger")
local function yes() return true end
local function getProductId()
local ntxinfo_pcb = io.popen("/usr/bin/ntxinfo /dev/mmcblk0 | grep pcb | cut -d ':' -f2", "r")
if not ntxinfo_pcb then return 0 end
local product_id = tonumber(ntxinfo_pcb:read()) or 0
ntxinfo_pcb:close()
return product_id
end
local Cervantes = Generic:new{
model = "Cervantes",
isCervantes = yes,
isAlwaysPortrait = yes,
isTouchDevice = yes,
touch_legacy = true, -- SingleTouch input events
touch_switch_xy = true,
touch_mirrored_x = true,
touch_probe_ev_epoch_time = true,
hasOTAUpdates = yes,
hasKeys = yes,
internal_storage_mount_point = "/mnt/public/",
}
-- Cervantes Touch
local CervantesTouch = Cervantes:new{
model = "Cervantes Touch",
display_dpi = 167,
}
-- Cervantes TouchLight / Fnac Touch Plus
local CervantesTouchLight = Cervantes:new{
model = "Cervantes TouchLight",
display_dpi = 167,
hasFrontlight = yes,
}
-- Cervantes 2013 / Fnac Touch Light
local Cervantes2013 = Cervantes:new{
model = "Cervantes 2013",
display_dpi = 212,
hasFrontlight = yes,
}
-- Cervantes 3 / Fnac Touch Light 2
local Cervantes3 = Cervantes:new{
model = "Cervantes 3",
display_dpi = 300,
hasFrontlight = yes,
}
-- Cervantes 4
local Cervantes4 = Cervantes:new{
model = "Cervantes 4",
display_dpi = 300,
hasFrontlight = yes,
hasNaturalLight = yes,
frontlight_settings = {
frontlight_white = "/sys/class/backlight/lm3630a_ledb",
frontlight_red = "/sys/class/backlight/lm3630a_leda",
},
}
-- input events
local probeEvEpochTime
-- this function will update itself after the first touch event
probeEvEpochTime = function(self, ev)
local now = TimeVal:now()
-- This check should work as long as main UI loop is not blocked for more
-- than 10 minute before handling the first touch event.
if ev.time.sec <= now.sec - 600 then
-- time is seconds since boot, force it to epoch
probeEvEpochTime = function(_, _ev)
_ev.time = TimeVal:now()
end
ev.time = now
else
-- time is already epoch time, no need to do anything
probeEvEpochTime = function(_, _) end
end
end
function Cervantes:initEventAdjustHooks()
if self.touch_switch_xy then
self.input:registerEventAdjustHook(self.input.adjustTouchSwitchXY)
end
if self.touch_mirrored_x then
self.input:registerEventAdjustHook(
self.input.adjustTouchMirrorX,
self.screen:getWidth()
)
end
if self.touch_probe_ev_epoch_time then
self.input:registerEventAdjustHook(function(_, ev)
probeEvEpochTime(_, ev)
end)
end
if self.touch_legacy then
self.input.handleTouchEv = self.input.handleTouchEvLegacy
end
end
function Cervantes:init()
self.screen = require("ffi/framebuffer_mxcfb"):new{device = self, debug = logger.dbg}
self.powerd = require("device/cervantes/powerd"):new{device = self}
self.input = require("device/input"):new{
device = self,
event_map = {
[61] = "Home",
[116] = "Power",
}
}
self.input.open("/dev/input/event0") -- Keys
self.input.open("/dev/input/event1") -- touchscreen
self.input.open("fake_events") -- usb events
self:initEventAdjustHooks()
Generic.init(self)
end
function Cervantes:setDateTime(year, month, day, hour, min, sec)
if hour == nil or min == nil then return true end
local command
if year and month and day then
command = string.format("date -s '%d-%d-%d %d:%d:%d'", year, month, day, hour, min, sec)
else
command = string.format("date -s '%d:%d'",hour, min)
end
if os.execute(command) == 0 then
os.execute('hwclock -u -w')
return true
else
return false
end
end
function Cervantes:saveSettings()
self.powerd:saveSettings()
end
-- wireless
function Cervantes:initNetworkManager(NetworkMgr)
function NetworkMgr:turnOffWifi(complete_callback)
logger.info("Cervantes: disabling WiFi")
os.execute("./disable-wifi.sh")
if complete_callback then
complete_callback()
end
end
function NetworkMgr:turnOnWifi(complete_callback)
logger.info("Cervantes: enabling WiFi")
os.execute("./enable-wifi.sh")
self:showNetworkMenu(complete_callback)
end
NetworkMgr:setWirelessBackend("wpa_supplicant", {ctrl_interface = "/var/run/wpa_supplicant/eth0"})
function NetworkMgr:obtainIP()
os.execute("./obtain-ip.sh")
end
function NetworkMgr:releaseIP()
os.execute("./release-ip.sh")
end
function NetworkMgr:restoreWifiAsync()
os.execute("./restore-wifi-async.sh")
end
function NetworkMgr:isWifiOn()
return 0 == os.execute("lsmod | grep -q 8189fs")
end
end
-- screensaver
function Cervantes:supportsScreensaver()
return true
end
function Cervantes:intoScreenSaver()
local Screensaver = require("ui/screensaver")
if self.screen_saver_mode == false then
Screensaver:show()
end
self.powerd:beforeSuspend()
self.screen_saver_mode = true
end
function Cervantes:outofScreenSaver()
if self.screen_saver_mode == true then
local Screensaver = require("ui/screensaver")
Screensaver:close()
local UIManager = require("ui/uimanager")
UIManager:nextTick(function() UIManager:setDirty("all", "full") end)
end
self.powerd:afterResume()
self.screen_saver_mode = false
end
-- power functions: suspend, resume, reboot, poweroff
function Cervantes:suspend()
os.execute("./suspend.sh")
end
function Cervantes:resume()
os.execute("./resume.sh")
end
function Cervantes:reboot()
os.execute("reboot")
end
function Cervantes:powerOff()
os.execute("halt")
end
-------------- device probe ------------
local product_id = getProductId()
if product_id == 22 then
return CervantesTouch
elseif product_id == 23 then
return CervantesTouchLight
elseif product_id == 33 then
return Cervantes2013
elseif product_id == 51 then
return Cervantes3
elseif product_id == 68 then
return Cervantes4
else
error("unrecognized Cervantes: board id " .. product_id)
end
|
local Generic = require("device/generic/device")
local TimeVal = require("ui/timeval")
local logger = require("logger")
local function yes() return true end
local function no() return false end
local function getProductId()
local ntxinfo_pcb = io.popen("/usr/bin/ntxinfo /dev/mmcblk0 | grep pcb | cut -d ':' -f2", "r")
if not ntxinfo_pcb then return 0 end
local product_id = tonumber(ntxinfo_pcb:read()) or 0
ntxinfo_pcb:close()
return product_id
end
local Cervantes = Generic:new{
model = "Cervantes",
isCervantes = yes,
isAlwaysPortrait = yes,
isTouchDevice = yes,
touch_legacy = true, -- SingleTouch input events
touch_switch_xy = true,
touch_mirrored_x = true,
touch_probe_ev_epoch_time = true,
hasNaturalLight = no,
hasOTAUpdates = yes,
hasKeys = yes,
internal_storage_mount_point = "/mnt/public/",
}
-- Cervantes Touch
local CervantesTouch = Cervantes:new{
model = "Cervantes Touch",
display_dpi = 167,
}
-- Cervantes TouchLight / Fnac Touch Plus
local CervantesTouchLight = Cervantes:new{
model = "Cervantes TouchLight",
display_dpi = 167,
hasFrontlight = yes,
}
-- Cervantes 2013 / Fnac Touch Light
local Cervantes2013 = Cervantes:new{
model = "Cervantes 2013",
display_dpi = 212,
hasFrontlight = yes,
}
-- Cervantes 3 / Fnac Touch Light 2
local Cervantes3 = Cervantes:new{
model = "Cervantes 3",
display_dpi = 300,
hasFrontlight = yes,
}
-- Cervantes 4
local Cervantes4 = Cervantes:new{
model = "Cervantes 4",
display_dpi = 300,
hasFrontlight = yes,
hasNaturalLight = yes,
frontlight_settings = {
frontlight_white = "/sys/class/backlight/lm3630a_ledb",
frontlight_red = "/sys/class/backlight/lm3630a_leda",
},
}
-- input events
local probeEvEpochTime
-- this function will update itself after the first touch event
probeEvEpochTime = function(self, ev)
local now = TimeVal:now()
-- This check should work as long as main UI loop is not blocked for more
-- than 10 minute before handling the first touch event.
if ev.time.sec <= now.sec - 600 then
-- time is seconds since boot, force it to epoch
probeEvEpochTime = function(_, _ev)
_ev.time = TimeVal:now()
end
ev.time = now
else
-- time is already epoch time, no need to do anything
probeEvEpochTime = function(_, _) end
end
end
function Cervantes:initEventAdjustHooks()
if self.touch_switch_xy then
self.input:registerEventAdjustHook(self.input.adjustTouchSwitchXY)
end
if self.touch_mirrored_x then
self.input:registerEventAdjustHook(
self.input.adjustTouchMirrorX,
self.screen:getWidth()
)
end
if self.touch_probe_ev_epoch_time then
self.input:registerEventAdjustHook(function(_, ev)
probeEvEpochTime(_, ev)
end)
end
if self.touch_legacy then
self.input.handleTouchEv = self.input.handleTouchEvLegacy
end
end
function Cervantes:init()
self.screen = require("ffi/framebuffer_mxcfb"):new{device = self, debug = logger.dbg}
self.powerd = require("device/cervantes/powerd"):new{device = self}
self.input = require("device/input"):new{
device = self,
event_map = {
[61] = "Home",
[116] = "Power",
}
}
self.input.open("/dev/input/event0") -- Keys
self.input.open("/dev/input/event1") -- touchscreen
self.input.open("fake_events") -- usb events
self:initEventAdjustHooks()
Generic.init(self)
end
function Cervantes:setDateTime(year, month, day, hour, min, sec)
if hour == nil or min == nil then return true end
local command
if year and month and day then
command = string.format("date -s '%d-%d-%d %d:%d:%d'", year, month, day, hour, min, sec)
else
command = string.format("date -s '%d:%d'",hour, min)
end
if os.execute(command) == 0 then
os.execute('hwclock -u -w')
return true
else
return false
end
end
function Cervantes:saveSettings()
self.powerd:saveSettings()
end
-- wireless
function Cervantes:initNetworkManager(NetworkMgr)
function NetworkMgr:turnOffWifi(complete_callback)
logger.info("Cervantes: disabling WiFi")
os.execute("./disable-wifi.sh")
if complete_callback then
complete_callback()
end
end
function NetworkMgr:turnOnWifi(complete_callback)
logger.info("Cervantes: enabling WiFi")
os.execute("./enable-wifi.sh")
self:showNetworkMenu(complete_callback)
end
NetworkMgr:setWirelessBackend("wpa_supplicant", {ctrl_interface = "/var/run/wpa_supplicant/eth0"})
function NetworkMgr:obtainIP()
os.execute("./obtain-ip.sh")
end
function NetworkMgr:releaseIP()
os.execute("./release-ip.sh")
end
function NetworkMgr:restoreWifiAsync()
os.execute("./restore-wifi-async.sh")
end
function NetworkMgr:isWifiOn()
return 0 == os.execute("lsmod | grep -q 8189fs")
end
end
-- screensaver
function Cervantes:supportsScreensaver()
return true
end
function Cervantes:intoScreenSaver()
local Screensaver = require("ui/screensaver")
if self.screen_saver_mode == false then
Screensaver:show()
end
self.powerd:beforeSuspend()
self.screen_saver_mode = true
end
function Cervantes:outofScreenSaver()
if self.screen_saver_mode == true then
local Screensaver = require("ui/screensaver")
Screensaver:close()
local UIManager = require("ui/uimanager")
UIManager:nextTick(function() UIManager:setDirty("all", "full") end)
end
self.powerd:afterResume()
self.screen_saver_mode = false
end
-- power functions: suspend, resume, reboot, poweroff
function Cervantes:suspend()
os.execute("./suspend.sh")
end
function Cervantes:resume()
os.execute("./resume.sh")
end
function Cervantes:reboot()
os.execute("reboot")
end
function Cervantes:powerOff()
os.execute("halt")
end
-------------- device probe ------------
local product_id = getProductId()
if product_id == 22 then
return CervantesTouch
elseif product_id == 23 then
return CervantesTouchLight
elseif product_id == 33 then
return Cervantes2013
elseif product_id == 51 then
return Cervantes3
elseif product_id == 68 then
return Cervantes4
else
error("unrecognized Cervantes: board id " .. product_id)
end
|
[fix, cervantes] Old Cervantes devices should return false for hasNaturalLights (#4320)
|
[fix, cervantes] Old Cervantes devices should return false for hasNaturalLights (#4320)
|
Lua
|
agpl-3.0
|
poire-z/koreader,Markismus/koreader,koreader/koreader,NiLuJe/koreader,mihailim/koreader,koreader/koreader,pazos/koreader,Hzj-jie/koreader,NiLuJe/koreader,Frenzie/koreader,Frenzie/koreader,mwoz123/koreader,poire-z/koreader,houqp/koreader
|
e97dbe130e9d62617381aa6785d6a4c72f99a1a8
|
xmake.lua
|
xmake.lua
|
-- lcui.css
set_project("lcui.css")
-- xmake minver
set_xmakever("2.1.6")
-- the debug mode
if is_mode("debug") then
-- enable the debug symbols
set_symbols("debug")
-- disable optimization
set_optimize("none")
end
-- the release mode
if is_mode("release") then
-- enable fastest optimization
set_optimize("fastest")
-- strip all symbols
set_strip("all")
end
target("LCUIEx")
set_kind("shared")
set_targetdir("dist/lib")
add_files("src/*.c")
add_files("src/ui/*.c")
add_files("src/ui/components/*.c")
add_includedirs("include", "../LCUI/include", "vendor/include", "vendor/lib")
if is_os("windows") then
add_linkdirs("vendor/lib")
add_links("LCUI")
end
on_load(function (target)
import("lib.detect.find_package")
target:add(find_package("LCUI"))
end)
includes("demo")
|
-- lcui.css
set_project("lcui.css")
-- xmake minver
set_xmakever("2.1.6")
-- the debug mode
if is_mode("debug") then
-- enable the debug symbols
set_symbols("debug")
-- disable optimization
set_optimize("none")
end
-- the release mode
if is_mode("release") then
-- enable fastest optimization
set_optimize("fastest")
-- strip all symbols
set_strip("all")
end
target("LCUIEx")
set_kind("shared")
set_targetdir("dist/lib")
add_files("src/*.c")
add_files("src/ui/*.c")
add_files("src/ui/components/*.c")
add_defines("LCUI_EXPORTS")
add_includedirs("include", "../LCUI/include", "vendor/include")
on_load(function (target)
import("lib.detect.find_package")
target:add(find_package("LCUI", {linkdirs = "vendor/lib"}))
end)
includes("demo")
|
fix link errors for msvc
|
fix link errors for msvc
|
Lua
|
mit
|
lc-ui/lcui.css,lc-ui/lcui.css,lc-ui/lcui.css
|
492d01cc097f117235d1532f744a532baed68d70
|
build/scripts/common_examples.lua
|
build/scripts/common_examples.lua
|
-- Configuration gnrale
configurations
{
-- "DebugStatic",
-- "ReleaseStatic",
"DebugDLL",
"ReleaseDLL"
}
language "C++"
location("../examples/build/" .. _ACTION)
debugdir "../examples/bin"
includedirs "../include"
libdirs "../lib"
if (_OPTIONS["x64"]) then
libdirs "../extlibs/lib/x64"
end
libdirs "../extlibs/lib/x86"
targetdir "../examples/bin"
configuration "Debug*"
defines "NAZARA_DEBUG"
flags "Symbols"
configuration "Release*"
flags { "EnableSSE2", "Optimize", "OptimizeSpeed", "NoFramePointer", "NoRTTI" }
configuration "*Static"
defines "NAZARA_STATIC"
configuration "codeblocks or codelite or gmake or xcode3*"
buildoptions "-std=c++11"
|
-- Configuration gnrale
configurations
{
-- "DebugStatic",
-- "ReleaseStatic",
"DebugDLL",
"ReleaseDLL"
}
language "C++"
location("../examples/build/" .. _ACTION)
debugdir "../examples/bin"
includedirs { "../include", "../extlibs/lib/include" }
libdirs "../lib"
if (_OPTIONS["x64"]) then
libdirs "../extlibs/lib/x64"
end
libdirs "../extlibs/lib/x86"
targetdir "../examples/bin"
configuration "Debug*"
defines "NAZARA_DEBUG"
flags "Symbols"
configuration "Release*"
flags { "EnableSSE2", "Optimize", "OptimizeSpeed", "NoFramePointer", "NoRTTI" }
configuration "*Static"
defines "NAZARA_STATIC"
configuration "codeblocks or codelite or gmake or xcode3*"
buildoptions "-std=c++11"
|
Fixed HardwareInfo OpenGL include
|
Fixed HardwareInfo OpenGL include
Former-commit-id: d45ca9ac45a883a5378d527ef3ffe6594dcd02f1
|
Lua
|
mit
|
DigitalPulseSoftware/NazaraEngine
|
63cedeb44dc66861f0e939c1da5adee92cc539eb
|
core/configmanager.lua
|
core/configmanager.lua
|
local _G = _G;
local setmetatable, loadfile, pcall, rawget, rawset, io =
setmetatable, loadfile, pcall, rawget, rawset, io;
module "configmanager"
local parsers = {};
local config = { ["*"] = { core = {} } };
local global_config = config["*"];
-- When host not found, use global
setmetatable(config, { __index = function () return global_config; end});
local host_mt = { __index = global_config };
-- When key not found in section, check key in global's section
function section_mt(section_name)
return { __index = function (t, k)
local section = rawget(global_config, section_name);
if not section then return nil; end
return section[k];
end };
end
function getconfig()
return config;
end
function get(host, section, key)
local sec = config[host][section];
if sec then
return sec[key];
end
return nil;
end
function set(host, section, key, value)
if host and section and key then
local hostconfig = rawget(config, host);
if not hostconfig then
hostconfig = rawset(config, host, setmetatable({}, host_mt))[host];
end
if not rawget(hostconfig, section) then
hostconfig[section] = setmetatable({}, section_mt(section));
end
hostconfig[section][key] = value;
return true;
end
return false;
end
function load(filename, format)
format = format or filename:match("%w+$");
if parsers[format] and parsers[format].load then
local f = io.open(filename);
if f then
local ok, err = parsers[format].load(f:read("*a"));
f:close();
return ok, err;
end
end
if not format then
return nil, "no parser specified";
else
return false, "no parser";
end
end
function save(filename, format)
end
function addparser(format, parser)
if format and parser then
parsers[format] = parser;
end
end
-- Built-in Lua parser
do
local loadstring, pcall, setmetatable = _G.loadstring, _G.pcall, _G.setmetatable;
local setfenv, rawget, tostring = _G.setfenv, _G.rawget, _G.tostring;
parsers.lua = {};
function parsers.lua.load(data)
local env;
env = setmetatable({ Host = true; host = true; }, { __index = function (t, k)
return rawget(_G, k) or
function (settings_table)
config[__currenthost or "*"][k] = settings_table;
end;
end,
__newindex = function (t, k, v)
set(env.__currenthost or "*", "core", k, v);
end});
function env.Host(name)
rawset(env, "__currenthost", name);
set(name or "*", "core", "defined", true);
end
env.host = env.Host;
local chunk, err = loadstring(data);
if not chunk then
return nil, err;
end
setfenv(chunk, env);
local ok, err = pcall(chunk);
if not ok then
return nil, err;
end
return true;
end
end
return _M;
|
local _G = _G;
local setmetatable, loadfile, pcall, rawget, rawset, io =
setmetatable, loadfile, pcall, rawget, rawset, io;
module "configmanager"
local parsers = {};
local config = { ["*"] = { core = {} } };
local global_config = config["*"];
-- When host not found, use global
setmetatable(config, { __index = function () return global_config; end});
local host_mt = { __index = global_config };
-- When key not found in section, check key in global's section
function section_mt(section_name)
return { __index = function (t, k)
local section = rawget(global_config, section_name);
if not section then return nil; end
return section[k];
end };
end
function getconfig()
return config;
end
function get(host, section, key)
local sec = config[host][section];
if sec then
return sec[key];
end
return nil;
end
function set(host, section, key, value)
if host and section and key then
local hostconfig = rawget(config, host);
if not hostconfig then
hostconfig = rawset(config, host, setmetatable({}, host_mt))[host];
end
if not rawget(hostconfig, section) then
hostconfig[section] = setmetatable({}, section_mt(section));
end
hostconfig[section][key] = value;
return true;
end
return false;
end
function load(filename, format)
format = format or filename:match("%w+$");
if parsers[format] and parsers[format].load then
local f, err = io.open(filename);
if f then
local ok, err = parsers[format].load(f:read("*a"));
f:close();
return ok, err;
end
return f, err;
end
if not format then
return nil, "no parser specified";
else
return nil, "no parser for "..(format);
end
end
function save(filename, format)
end
function addparser(format, parser)
if format and parser then
parsers[format] = parser;
end
end
-- Built-in Lua parser
do
local loadstring, pcall, setmetatable = _G.loadstring, _G.pcall, _G.setmetatable;
local setfenv, rawget, tostring = _G.setfenv, _G.rawget, _G.tostring;
parsers.lua = {};
function parsers.lua.load(data)
local env;
env = setmetatable({ Host = true; host = true; }, { __index = function (t, k)
return rawget(_G, k) or
function (settings_table)
config[__currenthost or "*"][k] = settings_table;
end;
end,
__newindex = function (t, k, v)
set(env.__currenthost or "*", "core", k, v);
end});
function env.Host(name)
rawset(env, "__currenthost", name);
set(name or "*", "core", "defined", true);
end
env.host = env.Host;
local chunk, err = loadstring(data);
if not chunk then
return nil, err;
end
setfenv(chunk, env);
local ok, err = pcall(chunk);
if not ok then
return nil, err;
end
return true;
end
end
return _M;
|
Fix for configmanager when config file can't be found
|
Fix for configmanager when config file can't be found
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
a10f158d7a047aa4b71fa95417cc0a415f53f3ff
|
core/configmanager.lua
|
core/configmanager.lua
|
-- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local _G = _G;
local setmetatable, loadfile, pcall, rawget, rawset, io, error, dofile, type, pairs, table, format =
setmetatable, loadfile, pcall, rawget, rawset, io, error, dofile, type, pairs, table, string.format;
local fire_event = prosody and prosody.events.fire_event or function () end;
local path_sep = package.config:sub(1,1);
module "configmanager"
local parsers = {};
local config_mt = { __index = function (t, k) return rawget(t, "*"); end};
local config = setmetatable({ ["*"] = { core = {} } }, config_mt);
-- When host not found, use global
local host_mt = { };
-- When key not found in section, check key in global's section
function section_mt(section_name)
return { __index = function (t, k)
local section = rawget(config["*"], section_name);
if not section then return nil; end
return section[k];
end
};
end
function getconfig()
return config;
end
function get(host, section, key)
local sec = config[host][section];
if sec then
return sec[key];
end
return nil;
end
local function set(config, host, section, key, value)
if host and section and key then
local hostconfig = rawget(config, host);
if not hostconfig then
hostconfig = rawset(config, host, setmetatable({}, host_mt))[host];
end
if not rawget(hostconfig, section) then
hostconfig[section] = setmetatable({}, section_mt(section));
end
hostconfig[section][key] = value;
return true;
end
return false;
end
function _M.set(host, section, key, value)
return set(config, host, section, key, value);
end
-- Helper function to resolve relative paths (needed by config)
do
local rel_path_start = ".."..path_sep;
function resolve_relative_path(parent_path, path)
if path then
local is_relative;
if path_sep == "/" and path:sub(1,1) ~= "/" then
is_relative = true;
elseif path_sep == "\\" and (path:sub(1,1) ~= "/" and path:sub(2,3) ~= ":\\") then
is_relative = true;
end
if is_relative then
return parent_path..path_sep..path;
end
end
return path;
end
end
function load(filename, format)
format = format or filename:match("%w+$");
if parsers[format] and parsers[format].load then
local f, err = io.open(filename);
if f then
local new_config, err = parsers[format].load(f:read("*a"), filename);
f:close();
if new_config then
setmetatable(new_config, config_mt);
config = new_config;
fire_event("config-reloaded", {
filename = filename,
format = format,
config = config
});
end
return not not new_config, "parser", err;
end
return f, "file", err;
end
if not format then
return nil, "file", "no parser specified";
else
return nil, "file", "no parser for "..(format);
end
end
function save(filename, format)
end
function addparser(format, parser)
if format and parser then
parsers[format] = parser;
end
end
-- _M needed to avoid name clash with local 'parsers'
function _M.parsers()
local p = {};
for format in pairs(parsers) do
table.insert(p, format);
end
return p;
end
-- Built-in Lua parser
do
local loadstring, pcall, setmetatable = _G.loadstring, _G.pcall, _G.setmetatable;
local setfenv, rawget, tostring = _G.setfenv, _G.rawget, _G.tostring;
parsers.lua = {};
function parsers.lua.load(data, filename)
local config = { ["*"] = { core = {} } };
local env;
-- The ' = true' are needed so as not to set off __newindex when we assign the functions below
env = setmetatable({
Host = true, host = true, VirtualHost = true,
Component = true, component = true,
Include = true, include = true, RunScript = true }, {
__index = function (t, k)
return rawget(_G, k) or
function (settings_table)
config[__currenthost or "*"][k] = settings_table;
end;
end,
__newindex = function (t, k, v)
set(config, env.__currenthost or "*", "core", k, v);
end
});
rawset(env, "__currenthost", "*") -- Default is global
function env.VirtualHost(name)
if rawget(config, name) and rawget(config[name].core, "component_module") then
error(format("Host %q clashes with previously defined %s Component %q, for services use a sub-domain like conference.%s",
name, config[name].core.component_module:gsub("^%a+$", { component = "external", muc = "MUC"}), name, name), 0);
end
rawset(env, "__currenthost", name);
-- Needs at least one setting to logically exist :)
set(config, name or "*", "core", "defined", true);
return function (config_options)
rawset(env, "__currenthost", "*"); -- Return to global scope
for option_name, option_value in pairs(config_options) do
set(config, name or "*", "core", option_name, option_value);
end
end;
end
env.Host, env.host = env.VirtualHost, env.VirtualHost;
function env.Component(name)
if rawget(config, name) and rawget(config[name].core, "defined") and not rawget(config[name].core, "component_module") then
error(format("Component %q clashes with previously defined Host %q, for services use a sub-domain like conference.%s",
name, name, name), 0);
end
set(config, name, "core", "component_module", "component");
-- Don't load the global modules by default
set(config, name, "core", "load_global_modules", false);
rawset(env, "__currenthost", name);
local function handle_config_options(config_options)
rawset(env, "__currenthost", "*"); -- Return to global scope
for option_name, option_value in pairs(config_options) do
set(config, name or "*", "core", option_name, option_value);
end
end
return function (module)
if type(module) == "string" then
set(config, name, "core", "component_module", module);
return handle_config_options;
end
return handle_config_options(module);
end
end
env.component = env.Component;
function env.Include(file)
local f, err = io.open(file);
if f then
local data = f:read("*a");
local file = resolve_relative_path(filename:gsub("[^"..path_sep.."]+$", ""), file);
local ok, err = parsers.lua.load(data, file);
if not ok then error(err:gsub("%[string.-%]", file), 0); end
end
if not f then error("Error loading included "..file..": "..err, 0); end
return f, err;
end
env.include = env.Include;
function env.RunScript(file)
return dofile(resolve_relative_path(filename:gsub("[^"..path_sep.."]+$", ""), file));
end
local chunk, err = loadstring(data, "@"..filename);
if not chunk then
return nil, err;
end
setfenv(chunk, env);
local ok, err = pcall(chunk);
if not ok then
return nil, err;
end
return config;
end
end
return _M;
|
-- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local _G = _G;
local setmetatable, loadfile, pcall, rawget, rawset, io, error, dofile, type, pairs, table, format =
setmetatable, loadfile, pcall, rawget, rawset, io, error, dofile, type, pairs, table, string.format;
local fire_event = prosody and prosody.events.fire_event or function () end;
local path_sep = package.config:sub(1,1);
module "configmanager"
local parsers = {};
local config_mt = { __index = function (t, k) return rawget(t, "*"); end};
local config = setmetatable({ ["*"] = { core = {} } }, config_mt);
-- When host not found, use global
local host_mt = { };
-- When key not found in section, check key in global's section
function section_mt(section_name)
return { __index = function (t, k)
local section = rawget(config["*"], section_name);
if not section then return nil; end
return section[k];
end
};
end
function getconfig()
return config;
end
function get(host, section, key)
local sec = config[host][section];
if sec then
return sec[key];
end
return nil;
end
local function set(config, host, section, key, value)
if host and section and key then
local hostconfig = rawget(config, host);
if not hostconfig then
hostconfig = rawset(config, host, setmetatable({}, host_mt))[host];
end
if not rawget(hostconfig, section) then
hostconfig[section] = setmetatable({}, section_mt(section));
end
hostconfig[section][key] = value;
return true;
end
return false;
end
function _M.set(host, section, key, value)
return set(config, host, section, key, value);
end
-- Helper function to resolve relative paths (needed by config)
do
local rel_path_start = ".."..path_sep;
function resolve_relative_path(parent_path, path)
if path then
local is_relative;
if path_sep == "/" and path:sub(1,1) ~= "/" then
is_relative = true;
elseif path_sep == "\\" and (path:sub(1,1) ~= "/" and path:sub(2,3) ~= ":\\") then
is_relative = true;
end
if is_relative then
return parent_path..path_sep..path;
end
end
return path;
end
end
function load(filename, format)
format = format or filename:match("%w+$");
if parsers[format] and parsers[format].load then
local f, err = io.open(filename);
if f then
local new_config = setmetatable({ ["*"] = { core = {} } }, config_mt);
local ok, err = parsers[format].load(f:read("*a"), filename, new_config);
f:close();
if ok then
config = new_config;
fire_event("config-reloaded", {
filename = filename,
format = format,
config = config
});
end
return not not new_config, "parser", err;
end
return f, "file", err;
end
if not format then
return nil, "file", "no parser specified";
else
return nil, "file", "no parser for "..(format);
end
end
function save(filename, format)
end
function addparser(format, parser)
if format and parser then
parsers[format] = parser;
end
end
-- _M needed to avoid name clash with local 'parsers'
function _M.parsers()
local p = {};
for format in pairs(parsers) do
table.insert(p, format);
end
return p;
end
-- Built-in Lua parser
do
local loadstring, pcall, setmetatable = _G.loadstring, _G.pcall, _G.setmetatable;
local setfenv, rawget, tostring = _G.setfenv, _G.rawget, _G.tostring;
parsers.lua = {};
function parsers.lua.load(data, filename, config)
local env;
-- The ' = true' are needed so as not to set off __newindex when we assign the functions below
env = setmetatable({
Host = true, host = true, VirtualHost = true,
Component = true, component = true,
Include = true, include = true, RunScript = true }, {
__index = function (t, k)
return rawget(_G, k) or
function (settings_table)
config[__currenthost or "*"][k] = settings_table;
end;
end,
__newindex = function (t, k, v)
set(config, env.__currenthost or "*", "core", k, v);
end
});
rawset(env, "__currenthost", "*") -- Default is global
function env.VirtualHost(name)
if rawget(config, name) and rawget(config[name].core, "component_module") then
error(format("Host %q clashes with previously defined %s Component %q, for services use a sub-domain like conference.%s",
name, config[name].core.component_module:gsub("^%a+$", { component = "external", muc = "MUC"}), name, name), 0);
end
rawset(env, "__currenthost", name);
-- Needs at least one setting to logically exist :)
set(config, name or "*", "core", "defined", true);
return function (config_options)
rawset(env, "__currenthost", "*"); -- Return to global scope
for option_name, option_value in pairs(config_options) do
set(config, name or "*", "core", option_name, option_value);
end
end;
end
env.Host, env.host = env.VirtualHost, env.VirtualHost;
function env.Component(name)
if rawget(config, name) and rawget(config[name].core, "defined") and not rawget(config[name].core, "component_module") then
error(format("Component %q clashes with previously defined Host %q, for services use a sub-domain like conference.%s",
name, name, name), 0);
end
set(config, name, "core", "component_module", "component");
-- Don't load the global modules by default
set(config, name, "core", "load_global_modules", false);
rawset(env, "__currenthost", name);
local function handle_config_options(config_options)
rawset(env, "__currenthost", "*"); -- Return to global scope
for option_name, option_value in pairs(config_options) do
set(config, name or "*", "core", option_name, option_value);
end
end
return function (module)
if type(module) == "string" then
set(config, name, "core", "component_module", module);
return handle_config_options;
end
return handle_config_options(module);
end
end
env.component = env.Component;
function env.Include(file)
local f, err = io.open(file);
if f then
local data = f:read("*a");
local file = resolve_relative_path(filename:gsub("[^"..path_sep.."]+$", ""), file);
local ret, err = parsers.lua.load(data, file, config);
if not ret then error(err:gsub("%[string.-%]", file), 0); end
end
if not f then error("Error loading included "..file..": "..err, 0); end
return f, err;
end
env.include = env.Include;
function env.RunScript(file)
return dofile(resolve_relative_path(filename:gsub("[^"..path_sep.."]+$", ""), file));
end
local chunk, err = loadstring(data, "@"..filename);
if not chunk then
return nil, err;
end
setfenv(chunk, env);
local ok, err = pcall(chunk);
if not ok then
return nil, err;
end
return true;
end
end
return _M;
|
configmanager: Change parser API again to pass a config table to insert settings to. Fixes Include(). (Thanks Zash/answerman)
|
configmanager: Change parser API again to pass a config table to insert settings to. Fixes Include(). (Thanks Zash/answerman)
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
2eade79021742a658b43f071913e1280b7f42937
|
tests/test-require.lua
|
tests/test-require.lua
|
require("helper")
_G.num_loaded = 0
local m1 = require("module1")
local m1_m2 = require("module1/module2")
local m2_m2 = require("module2/module2")
local rm1 = require("./modules/module1")
local rm1_m2 = require("./modules/module1/module2")
local rm2_m2 = require("./modules/module2/module2")
p(m1, m1_m2, m2_m2)
p(rm1, rm1_m2, rm2_m2)
p({num_loaded=num_loaded})
assert(num_loaded == 3, "There should be three modules loaded")
assert(m1 == rm1 and m1_m2 == rm1_m2 and m2_m2 == rm2_m2, "Modules are not caching correctly")
-- Test native addons
local vectors = {
require("vector"),
require("vector-renamed"),
}
assert(vectors[1] == vectors[2], "Symlinks should realpath and load real module and reuse cache")
-- Test to make sure dashes are allowed and the same file is cached no matter how it's found
local libluvits = {
require('lib-luvit'),
require('./modules/lib-luvit'),
}
assert(libluvits[1] == libluvits[3], "Module search and relative should share same cache")
|
require("helper")
_G.num_loaded = 0
local m1 = require("module1")
local m1_m2 = require("module1/module2")
local m2_m2 = require("module2/module2")
local rm1 = require("./modules/module1")
local rm1_m2 = require("./modules/module1/module2")
local rm2_m2 = require("./modules/module2/module2")
p(m1, m1_m2, m2_m2)
p(rm1, rm1_m2, rm2_m2)
p({num_loaded=num_loaded})
assert(num_loaded == 3, "There should be exactly three modules loaded, there was " .. num_loaded)
assert(m1 == rm1 and m1_m2 == rm1_m2 and m2_m2 == rm2_m2, "Modules are not caching correctly")
-- Test native addons
local vectors = {
require("vector"),
require("vector-renamed"),
}
assert(vectors[1] == vectors[2], "Symlinks should realpath and load real module and reuse cache")
-- Test to make sure dashes are allowed and the same file is cached no matter how it's found
local libluvits = {
require('lib-luvit'),
require('./modules/lib-luvit'),
}
assert(libluvits[1] == libluvits[2], "Module search and relative should share same cache")
|
Fix typo in test
|
Fix typo in test
|
Lua
|
apache-2.0
|
sousoux/luvit,boundary/luvit,sousoux/luvit,rjeli/luvit,bsn069/luvit,boundary/luvit,luvit/luvit,AndrewTsao/luvit,AndrewTsao/luvit,GabrielNicolasAvellaneda/luvit-upstream,kaustavha/luvit,boundary/luvit,GabrielNicolasAvellaneda/luvit-upstream,sousoux/luvit,zhaozg/luvit,AndrewTsao/luvit,sousoux/luvit,boundary/luvit,kaustavha/luvit,DBarney/luvit,GabrielNicolasAvellaneda/luvit-upstream,DBarney/luvit,GabrielNicolasAvellaneda/luvit-upstream,sousoux/luvit,DBarney/luvit,sousoux/luvit,rjeli/luvit,boundary/luvit,bsn069/luvit,boundary/luvit,rjeli/luvit,DBarney/luvit,connectFree/lev,bsn069/luvit,zhaozg/luvit,kaustavha/luvit,rjeli/luvit,connectFree/lev,luvit/luvit
|
28b72efd8f1efcd3f44271cc56e23f022410382c
|
Hydra/API/hydra_ipc.lua
|
Hydra/API/hydra_ipc.lua
|
--- === hydra.ipc ===
---
--- Interface with Hydra from the command line.
local function rawhandler(str)
local fn, err = load(str)
if fn then return fn() else return err end
end
--- hydra.ipc.handler(str) -> value
--- The default handler for IPC, called by hydra-cli. Default implementation evals the string and returns the result.
--- You may override this function if for some reason you want to implement special evaluation rules for executing remote commands.
--- The return value of this function is always turned into a string via tostring() and returned to hydra-cli.
--- If an error occurs, the error message is returned instead.
hydra.ipc.handler = rawhandler
function hydra.ipc._handler(raw, str)
local fn = hydra.ipc.handler
if raw then fn = rawhandler end
local ok, val = hydra.call(function() return fn(str) end)
return val
end
local function envstuff(prefix, dryrun)
prefix = prefix or "/usr/local"
local fn = os.execute
if dryrun then fn = print end
local hydradestdir = string.format("'%s/bin'", prefix)
local manpagedestdir = string.format("'%s/share/man/man1'", prefix)
return fn, hydradestdir, manpagedestdir
end
--- hydra.ipc.link(prefix = "/usr/local", dryrun = nil)
--- Symlinks ${prefix}/bin/hydra and ${prefix}/share/man/man1/hydra.1
--- If dryrun is true, prints the commands it would run.
function hydra.ipc.link(prefix, dryrun)
local fn, hydradestdir, manpagedestdir = envstuff(prefix, dryrun)
fn(string.format("mkdir -p %s", hydradestdir))
fn(string.format("mkdir -p %s", manpagedestdir))
fn(string.format('ln -s "%s"/hydra %s/hydra', hydra.resourcesdir, hydradestdir))
fn(string.format('ln -s "%s"/hydra.1 %s/hydra.1', hydra.resourcesdir, manpagedestdir))
print("Done. Now you can do these things:")
print([[$ hydra 'hydra.alert("hello world")']])
print([[$ man hydra]])
end
--- hydra.ipc.unlink(prefix = "/usr/local", dryrun = false)
--- Removes ${prefix}/bin/hydra and ${prefix}/share/man/man1/hydra.1
--- If dryrun is true, prints the commands it would run.
function hydra.ipc.unlink(prefix, dryrun)
local fn, hydradestdir, manpagedestdir = envstuff(prefix, dryrun)
fn(string.format('rm -f %s/hydra', hydradestdir))
fn(string.format('rm -f %s/hydra.1', manpagedestdir))
print("Done.")
end
|
--- === hydra.ipc ===
---
--- Interface with Hydra from the command line.
local function rawhandler(str)
local fn, err = load("return " .. str)
if not fn then fn, err = load(str) end
if fn then return fn() else return err end
end
--- hydra.ipc.handler(str) -> value
--- The default handler for IPC, called by hydra-cli. Default implementation evals the string and returns the result.
--- You may override this function if for some reason you want to implement special evaluation rules for executing remote commands.
--- The return value of this function is always turned into a string via tostring() and returned to hydra-cli.
--- If an error occurs, the error message is returned instead.
hydra.ipc.handler = rawhandler
function hydra.ipc._handler(raw, str)
local fn = hydra.ipc.handler
if raw then fn = rawhandler end
local ok, val = hydra.call(function() return fn(str) end)
return val
end
local function envstuff(prefix, dryrun)
prefix = prefix or "/usr/local"
local fn = os.execute
if dryrun then fn = print end
local hydradestdir = string.format("'%s/bin'", prefix)
local manpagedestdir = string.format("'%s/share/man/man1'", prefix)
return fn, hydradestdir, manpagedestdir
end
--- hydra.ipc.link(prefix = "/usr/local", dryrun = nil)
--- Symlinks ${prefix}/bin/hydra and ${prefix}/share/man/man1/hydra.1
--- If dryrun is true, prints the commands it would run.
function hydra.ipc.link(prefix, dryrun)
local fn, hydradestdir, manpagedestdir = envstuff(prefix, dryrun)
fn(string.format("mkdir -p %s", hydradestdir))
fn(string.format("mkdir -p %s", manpagedestdir))
fn(string.format('ln -s "%s"/hydra %s/hydra', hydra.resourcesdir, hydradestdir))
fn(string.format('ln -s "%s"/hydra.1 %s/hydra.1', hydra.resourcesdir, manpagedestdir))
print("Done. Now you can do these things:")
print([[$ hydra 'hydra.alert("hello world")']])
print([[$ man hydra]])
end
--- hydra.ipc.unlink(prefix = "/usr/local", dryrun = false)
--- Removes ${prefix}/bin/hydra and ${prefix}/share/man/man1/hydra.1
--- If dryrun is true, prints the commands it would run.
function hydra.ipc.unlink(prefix, dryrun)
local fn, hydradestdir, manpagedestdir = envstuff(prefix, dryrun)
fn(string.format('rm -f %s/hydra', hydradestdir))
fn(string.format('rm -f %s/hydra.1', manpagedestdir))
print("Done.")
end
|
Make hydra-cli first try the command with 'return ' prefixed; part of #273.
|
Make hydra-cli first try the command with 'return ' prefixed; part of #273.
|
Lua
|
mit
|
chrisjbray/hammerspoon,bradparks/hammerspoon,peterhajas/hammerspoon,joehanchoi/hammerspoon,knu/hammerspoon,knl/hammerspoon,junkblocker/hammerspoon,knu/hammerspoon,CommandPost/CommandPost-App,bradparks/hammerspoon,cmsj/hammerspoon,zzamboni/hammerspoon,TimVonsee/hammerspoon,heptal/hammerspoon,cmsj/hammerspoon,joehanchoi/hammerspoon,peterhajas/hammerspoon,joehanchoi/hammerspoon,heptal/hammerspoon,TimVonsee/hammerspoon,chrisjbray/hammerspoon,wsmith323/hammerspoon,trishume/hammerspoon,Stimim/hammerspoon,hypebeast/hammerspoon,wvierber/hammerspoon,ocurr/hammerspoon,Stimim/hammerspoon,cmsj/hammerspoon,junkblocker/hammerspoon,ocurr/hammerspoon,wvierber/hammerspoon,Stimim/hammerspoon,tmandry/hammerspoon,zzamboni/hammerspoon,kkamdooong/hammerspoon,bradparks/hammerspoon,lowne/hammerspoon,CommandPost/CommandPost-App,zzamboni/hammerspoon,dopcn/hammerspoon,hypebeast/hammerspoon,hypebeast/hammerspoon,Habbie/hammerspoon,Habbie/hammerspoon,kkamdooong/hammerspoon,wsmith323/hammerspoon,trishume/hammerspoon,cmsj/hammerspoon,peterhajas/hammerspoon,Habbie/hammerspoon,zzamboni/hammerspoon,kkamdooong/hammerspoon,CommandPost/CommandPost-App,ocurr/hammerspoon,chrisjbray/hammerspoon,junkblocker/hammerspoon,peterhajas/hammerspoon,Hammerspoon/hammerspoon,wvierber/hammerspoon,Hammerspoon/hammerspoon,asmagill/hammerspoon,dopcn/hammerspoon,latenitefilms/hammerspoon,emoses/hammerspoon,Hammerspoon/hammerspoon,nkgm/hammerspoon,chrisjbray/hammerspoon,TimVonsee/hammerspoon,knu/hammerspoon,asmagill/hammerspoon,bradparks/hammerspoon,latenitefilms/hammerspoon,ocurr/hammerspoon,heptal/hammerspoon,dopcn/hammerspoon,ocurr/hammerspoon,asmagill/hammerspoon,chrisjbray/hammerspoon,wvierber/hammerspoon,knl/hammerspoon,dopcn/hammerspoon,CommandPost/CommandPost-App,Stimim/hammerspoon,joehanchoi/hammerspoon,TimVonsee/hammerspoon,Habbie/hammerspoon,lowne/hammerspoon,joehanchoi/hammerspoon,emoses/hammerspoon,dopcn/hammerspoon,latenitefilms/hammerspoon,cmsj/hammerspoon,chrisjbray/hammerspoon,hypebeast/hammerspoon,lowne/hammerspoon,heptal/hammerspoon,asmagill/hammerspoon,wsmith323/hammerspoon,emoses/hammerspoon,knu/hammerspoon,nkgm/hammerspoon,tmandry/hammerspoon,CommandPost/CommandPost-App,Hammerspoon/hammerspoon,knu/hammerspoon,Habbie/hammerspoon,TimVonsee/hammerspoon,zzamboni/hammerspoon,CommandPost/CommandPost-App,knl/hammerspoon,knl/hammerspoon,lowne/hammerspoon,tmandry/hammerspoon,knu/hammerspoon,wvierber/hammerspoon,emoses/hammerspoon,wsmith323/hammerspoon,cmsj/hammerspoon,junkblocker/hammerspoon,kkamdooong/hammerspoon,Hammerspoon/hammerspoon,nkgm/hammerspoon,latenitefilms/hammerspoon,latenitefilms/hammerspoon,Habbie/hammerspoon,zzamboni/hammerspoon,Stimim/hammerspoon,nkgm/hammerspoon,kkamdooong/hammerspoon,Hammerspoon/hammerspoon,trishume/hammerspoon,nkgm/hammerspoon,latenitefilms/hammerspoon,lowne/hammerspoon,emoses/hammerspoon,heptal/hammerspoon,wsmith323/hammerspoon,asmagill/hammerspoon,hypebeast/hammerspoon,asmagill/hammerspoon,knl/hammerspoon,peterhajas/hammerspoon,bradparks/hammerspoon,junkblocker/hammerspoon
|
7777d34109601a47299a35ac827ae1033bf6cfb6
|
scripts/src/embed.lua
|
scripts/src/embed.lua
|
require "lmkbuild"
local add_files = lmkbuild.add_files
local error = error
local file_newer = lmkbuild.file_newer
local get_var = lmkbuild.get_var
local io = io
local ipairs = ipairs
local is_valid = lmkbuild.is_valid
local print = print
local resolve = lmkbuild.resolve
local rm = lmkbuild.rm
local set = lmk.set_local
local split = lmkbuild.split
local table = table
local tostring = tostring
local type = type
module (...)
function main (files)
local name = resolve ("$(embedName)")
if (not name) or (name == "") then name = resolve ("$(name)") end
local root = resolve ("$(embedRoot)")
if (not root) or (root == "") then root = name end
local ns = resolve ("$(embedNamespace)")
local useNs = (ns ~= "")
local export = get_var ("embedExport")
if export == nil then export = true
else export = export[#export] -- get_var returns a table so get the last element
end
local countFunc = "get_" .. root .. "_count"
local getFunc = "get_" .. root .. "_text"
local lengthFunc = "get_" .. root .. "_length"
local fileFunc = "get_" .. root .. "_file_name"
local macroName = name:gsub ("(%w)(%u%l)", "%1_%2"):gsub ("(%l)(%u)", "%1_%2"):upper ()
local macroHeader = macroName .. "_DOT_H"
local macroExport = macroName .. "_EXPORT"
local macroLink = macroName .. "_LINK_SYMBOL"
if not export then macroLink = "" end
local target = name .. ".h"
if file_newer (files, target) then
fout = io.open (target, "w")
if fout then
fout:write ("// WARNING: Auto Generated File. DO NOT EDIT.\n\n")
fout:write ("#ifndef " .. macroHeader .. "\n")
fout:write ("#define " .. macroHeader .. "\n\n")
if export then
fout:write ("#ifdef _WIN32\n")
fout:write ("# ifdef " .. macroExport .. "\n")
fout:write ("# define " .. macroLink .. " __declspec (dllexport)\n")
fout:write ("# else\n")
fout:write ("# define " .. macroLink .. " __declspec (dllimport)\n")
fout:write ("# endif\n")
fout:write ("#else\n")
fout:write ("# define " .. macroLink .. "\n")
fout:write ("#endif\n\n")
end
if useNs then
fout:write ("namespace " .. ns .. " {\n\n")
end
if macroLink ~= "" then macroLink = macroLink .. " " end
fout:write (macroLink .. "int\n")
fout:write (countFunc .. " ();\n\n")
fout:write (macroLink .. "const char*\n")
fout:write (getFunc .. " (const int Which);\n\n")
fout:write (macroLink .. "int\n")
fout:write (lengthFunc .. " (const int Which);\n\n")
fout:write (macroLink .. "const char*\n")
fout:write (fileFunc .. " (const int Which);\n\n")
if useNs then
fout:write ("};\n\n")
end
fout:write ("#endif // " .. macroHeader .. "\n")
io.close (fout)
end
end
add_files {target}
target = name .. ".cpp"
if file_newer (files, target) then
local fout = io.open (target, "w")
if fout then
local strLength = {}
local scope = ""
if useNs then scope = ns .. "::" end
fout:write ("// WARNING: Auto Generated File. DO NOT EDIT.\n\n")
if export then
fout:write ("#define " .. macroExport .. "\n")
end
fout:write ("#include <" .. name .. ".h>\n\n")
fout:write ("namespace {\n\n")
for index, inFile in ipairs (files) do
local count = 0
fout:write ("// " .. inFile .. "\n")
fout:write ("static const char text" .. index .. "[] = {\n")
local instr = nil
local fin = io.open (inFile, "r")
if fin then
instr = fin:read ("*all")
io.close (fin)
else error ("Unable to open file: " .. inFile .. " for embedding.")
end
if instr then
local length = instr:len ()
strLength[index] = length
for ix = 1, length do
local byte = instr:byte (ix)
if byte < 10 then fout:write (" ")
elseif byte < 100 then fout:write (" ")
end
fout:write (tostring (byte))
count = count + 1
if count > 17 then
count = 0
fout:write (",\n")
else
fout:write (", ")
end
end
else strLength[index] = 0;
end
fout:write (" 0\n};\n\n")
end
fout:write ("};\n\n\n")
fout:write ("int\n")
fout:write (scope .. countFunc .. " () { return " .. tostring (#files) ..
"; }\n\n\n")
fout:write ("const char *\n")
fout:write (scope .. getFunc .. " (const int Which) {\n\n")
fout:write (" switch (Which) {\n")
for index, inFile in ipairs (files) do
fout:write (" case " .. tostring (index - 1) .. ": return text" ..
tostring (index) .. "; break; // " .. inFile .. "\n")
end
fout:write (" default: return 0;\n")
fout:write (" }\n\n return 0;\n}\n\n\n")
fout:write ("int\n")
fout:write (scope .. lengthFunc .. " (const int Which) {\n\n")
fout:write (" switch (Which) {\n")
for index, inFile in ipairs (files) do
fout:write (" case " .. tostring (index - 1) .. ": return " ..
tostring (strLength[index]) .. "; break; // " .. inFile .. "\n")
end
fout:write (" default: return 0;\n")
fout:write (" }\n\n return 0;\n}\n\n\n")
fout:write ("const char *\n")
fout:write (scope .. fileFunc .. " (const int Which) {\n\n")
fout:write (" switch (Which) {\n")
for index, inFile in ipairs (files) do
fout:write (" case " .. tostring (index - 1) .. ': return "' ..
inFile .. '"; break;\n')
end
fout:write (" default: return 0;\n")
fout:write (" }\n\n return 0;\n}\n\n\n")
io.close (fout)
else error ("Unable to create file: " .. target)
end
end
add_files {target}
end
function test (files)
main (files)
end
function clean (files)
end
function clobber (files)
end
|
require "lmkbuild"
local add_files = lmkbuild.add_files
local error = error
local file_newer = lmkbuild.file_newer
local get_var = lmkbuild.get_var
local io = io
local ipairs = ipairs
local is_valid = lmkbuild.is_valid
local print = print
local resolve = lmkbuild.resolve
local rm = lmkbuild.rm
local set = lmk.set_local
local split = lmkbuild.split
local table = table
local tostring = tostring
local type = type
module (...)
function main (files)
local name = resolve ("$(embedName)")
if (not name) or (name == "") then name = resolve ("$(name)") end
local root = resolve ("$(embedRoot)")
if (not root) or (root == "") then root = name end
local ns = resolve ("$(embedNamespace)")
local useNs = (ns ~= "")
local export = get_var ("embedExport")
if export == nil then export = true
else export = export[#export] -- get_var returns a table so get the last element
end
local countFunc = "get_" .. root .. "_count"
local getFunc = "get_" .. root .. "_text"
local lengthFunc = "get_" .. root .. "_length"
local fileFunc = "get_" .. root .. "_file_name"
local macroName = name:gsub ("(%w)(%u%l)", "%1_%2"):gsub ("(%l)(%u)", "%1_%2"):upper ()
local macroHeader = macroName .. "_DOT_H"
local macroExport = macroName .. "_EXPORT"
local macroLink = macroName .. "_LINK_SYMBOL"
if not export then macroLink = "" end
local target = name .. ".h"
if file_newer (files, target) then
fout = io.open (target, "w")
if fout then
fout:write ("// WARNING: Auto Generated File. DO NOT EDIT.\n\n")
fout:write ("#ifndef " .. macroHeader .. "\n")
fout:write ("#define " .. macroHeader .. "\n\n")
if export then
fout:write ("#ifdef _WIN32\n")
fout:write ("# ifdef " .. macroExport .. "\n")
fout:write ("# define " .. macroLink .. " __declspec (dllexport)\n")
fout:write ("# else\n")
fout:write ("# define " .. macroLink .. " __declspec (dllimport)\n")
fout:write ("# endif\n")
fout:write ("#else\n")
fout:write ("# define " .. macroLink .. "\n")
fout:write ("#endif\n\n")
end
if useNs then
fout:write ("namespace " .. ns .. " {\n\n")
end
if macroLink ~= "" then macroLink = macroLink .. " " end
fout:write (macroLink .. "int\n")
fout:write (countFunc .. " ();\n\n")
fout:write (macroLink .. "const char*\n")
fout:write (getFunc .. " (const int Which);\n\n")
fout:write (macroLink .. "int\n")
fout:write (lengthFunc .. " (const int Which);\n\n")
fout:write (macroLink .. "const char*\n")
fout:write (fileFunc .. " (const int Which);\n\n")
if useNs then
fout:write ("};\n\n")
end
fout:write ("#endif // " .. macroHeader .. "\n")
io.close (fout)
end
end
if export then add_files {target} end
target = name .. ".cpp"
if file_newer (files, target) then
local fout = io.open (target, "w")
if fout then
local strLength = {}
local scope = ""
if useNs then scope = ns .. "::" end
fout:write ("// WARNING: Auto Generated File. DO NOT EDIT.\n\n")
if export then
fout:write ("#define " .. macroExport .. "\n")
end
if export then fout:write ("#include <" .. name .. ".h>\n\n")
else fout:write ('#include "' .. name .. '.h"\n\n')
end
fout:write ("namespace {\n\n")
for index, inFile in ipairs (files) do
local count = 0
fout:write ("// " .. inFile .. "\n")
fout:write ("static const char text" .. index .. "[] = {\n")
local instr = nil
local fin = io.open (inFile, "r")
if fin then
instr = fin:read ("*all")
io.close (fin)
else error ("Unable to open file: " .. inFile .. " for embedding.")
end
if instr then
local length = instr:len ()
strLength[index] = length
for ix = 1, length do
local byte = instr:byte (ix)
if byte < 10 then fout:write (" ")
elseif byte < 100 then fout:write (" ")
end
fout:write (tostring (byte))
count = count + 1
if count > 17 then
count = 0
fout:write (",\n")
else
fout:write (", ")
end
end
else strLength[index] = 0;
end
fout:write (" 0\n};\n\n")
end
fout:write ("};\n\n\n")
fout:write ("int\n")
fout:write (scope .. countFunc .. " () { return " .. tostring (#files) ..
"; }\n\n\n")
fout:write ("const char *\n")
fout:write (scope .. getFunc .. " (const int Which) {\n\n")
fout:write (" switch (Which) {\n")
for index, inFile in ipairs (files) do
fout:write (" case " .. tostring (index - 1) .. ": return text" ..
tostring (index) .. "; break; // " .. inFile .. "\n")
end
fout:write (" default: return 0;\n")
fout:write (" }\n\n return 0;\n}\n\n\n")
fout:write ("int\n")
fout:write (scope .. lengthFunc .. " (const int Which) {\n\n")
fout:write (" switch (Which) {\n")
for index, inFile in ipairs (files) do
fout:write (" case " .. tostring (index - 1) .. ": return " ..
tostring (strLength[index]) .. "; break; // " .. inFile .. "\n")
end
fout:write (" default: return 0;\n")
fout:write (" }\n\n return 0;\n}\n\n\n")
fout:write ("const char *\n")
fout:write (scope .. fileFunc .. " (const int Which) {\n\n")
fout:write (" switch (Which) {\n")
for index, inFile in ipairs (files) do
fout:write (" case " .. tostring (index - 1) .. ': return "' ..
inFile .. '"; break;\n')
end
fout:write (" default: return 0;\n")
fout:write (" }\n\n return 0;\n}\n\n\n")
io.close (fout)
else error ("Unable to create file: " .. target)
end
end
add_files {target}
end
function test (files)
main (files)
end
function clean (files)
end
function clobber (files)
end
|
Bugfix: embedding would incorrectly generate file that were not exported
|
Bugfix: embedding would incorrectly generate file that were not exported
|
Lua
|
mit
|
shillcock/lmk,dmzgroup/lmk
|
5761651f0c41c8e1a13c207c9876ef764d3267b9
|
monster/mon_27_wasps.lua
|
monster/mon_27_wasps.lua
|
require("monster.base.drop")
require("monster.base.lookat")
require("monster.base.quests")
require("base.messages");
module("monster.mon_27_wasps", package.seeall)
function ini(Monster)
init=true;
monster.base.quests.iniQuests();
killer={}; --A list that keeps track of who attacked the monster last
--Random Messages
msgs = base.messages.Messages();
msgs:addMessage("#me fliegt, ein hohes, weinerlich klingendes Gerusch machend umher.", "#me flies around, making a high pitched whining sound.");
msgs:addMessage("#me landet nur um wieder abheben zu knnen begleitet von einem kurzen Summen.", "#me lands, only to take off again with a short buzz.");
msgs:addMessage("#me peitscht, einen Landeplatz suchend durch die Luft.", "#me whips about in the air, searching for somewhere to land.");
msgs:addMessage("#me schwirrt drohend in keine bestimmte Richtung.", "#me angrily buzzes around in no particular direction.");
msgs:addMessage("Bzzz.", "Bzzz.");
msgs:addMessage("#me fliegt in wilden Kreisen und man kann das Gift an ihrem Stachel aufglnzen sehen.", "#me darts around, one can see venom dripping from its sting.");
msgs:addMessage("#me fhrt ihren spitzen Stachel aus.", "#me extends its sting.");
msgs:addMessage("Summ, summ.", "Buzz, buzz.");
msgs:addMessage("Bsss.", "Bsss.");
msgs:addMessage("#mes Flgel verbreiten ein hochfrequentes Summen, welches in den Ohren schmerzt.", "#me's wings exude a buzzing with high frequency, it hurts one's ears.");
end
function enemyNear(Monster,Enemy)
if init==nil then
ini(Monster);
end
if math.random(1,10) == 1 then
monster.base.drop.MonsterRandomTalk(Monster,msgs); --a random message is spoken once in a while
end
local MonID=Monster:getMonsterType();
if (MonID==278) then
world:gfx(9,Monster.pos);
end
return false
end
function enemyOnSight(Monster,Enemy)
if init==nil then
ini(Monster);
end
monster.base.drop.MonsterRandomTalk(Monster,msgs); --a random message is spoken once in a while
local MonID=Monster:getMonsterType();
if (MonID==278) then
world:gfx(9,Monster.pos);
end
if monster.base.drop.DefaultSlowdown( Monster ) then
return true
else
return false
end
end
function onAttacked(Monster,Enemy)
if init==nil then
ini(Monster);
end
monster.base.kills.setLastAttacker(Monster,Enemy)
killer[Monster.id]=Enemy.id; --Keeps track who attacked the monster last
end
function onCasted(Monster,Enemy)
if init==nil then
ini(Monster);
end
monster.base.kills.setLastAttacker(Monster,Enemy)
killer[Monster.id]=Enemy.id; --Keeps track who attacked the monster last
end
function onDeath(Monster)
monster.base.drop.ClearDropping();
local MonID=Monster:getMonsterType();
monster.base.drop.AddDropItem(2529,1,100,333,0,1); --honeycombs
if (MonID==278) then -- wasp of Fire!!!
-- VILARION: monster cannot suffer damage on death
-- which it will be Create Circle calls and subsequent
-- HitChar calls. This creates an infinite loop, since
-- onDeath is called by the damage routine
--CreateCircle( 1, 250,Monster.pos,3,false);
--CreateCircle( 9, 750,Monster.pos,2,true);
--CreateCircle(44,1000,Monster.pos,1,true);
--world:gfx(36,Monster.pos);
--world:makeSound(5,Monster.pos);
--HitChar(SourceItem.pos,3000,Monster.pos);
end
monster.base.drop.Dropping(Monster);
end
function CreateCircle(gfxid,Damage,CenterPos,Radius,setFlames)
local irad = math.ceil(Radius);
local dim = 2*(irad+1);
local x;
local y;
local map = {};
for x = -irad-1, irad do
map[x] = {};
for y = -irad-1, irad do
map[x][y] = (x+0.5)*(x+0.5)+(y+0.5)*(y+0.5)-irad*irad > 0
end;
end;
for x = -irad, irad do
for y = -irad, irad do
if not( map[x][y] and map[x-1][y] and map[x][y-1] and map[x-1][y-1] )
and( map[x][y] or map[x-1][y] or map[x][y-1] or map[x-1][y-1] ) then
HitPos=position( CenterPos.x + x, CenterPos.y + y, CenterPos.z );
world:gfx(gfxid,HitPos);
HitChar(HitPos,Damage,CenterPos);
if not SetNextTrap(HitPos,CenterPos) then
if setFlames then
if (math.random(1,5)==1) then
world:createItemFromId(359,1,HitPos,true,math.random(200,600),0);
end
end
end
end;
end;
end;
end;
function HitChar(Posi,Hitpoints,CenterPos)
if world:isCharacterOnField(Posi) then
local Character = world:getCharacterOnField(Posi);
if (Character:getType()==1) then
if (Character:getMonsterType() == 401) then
if not equapos(Posi,CenterPos) then
return
end
elseif (Character:getMonsterType() == 278) then
Character:increaseAttrib("hitpoints",-10000);
return
end
end
if equapos(Posi,CenterPos) then
Character:warp(position(Character.pos.x+math.random(-9,9),Character.pos.y+math.random(-9,9),Character.pos.z));
else
local Distance = Character:distanceMetricToPosition(CenterPos);
local Diffx = CenterPos.x - Character.pos.x;
local Diffy = CenterPos.y - Character.pos.y;
if (Distance == 1) then
Diffx = 6*Diffx;
Diffy = 6*Diffy;
elseif (Distance == 2) then
Diffx = 2*Diffx;
Diffy = 2*Diffy;
end
Character:warp(position(Character.pos.x-Diffx,Character.pos.y-Diffy,Character.pos.z));
end
base.common.TempInformNLS(Character,
"Getroffen von der Detonation wirst du davon geschleudert.",
"Hitted by the detonation, you get thrown away.");
Character:increaseAttrib("hitpoints",-Hitpoints);
end;
end;
function SetNextTrap(Posi,CenterPos)
if equapos(Posi,CenterPos) then
return false
end
if not world:isItemOnField(Posi) then
return false
end
TestItem = world:getItemOnField(Posi);
if (TestItem.data ~= 2) then
return false
end
if ((TestItem.id >= 377) and (TestItem.id <=381)) then
local tempmonster = world:createMonster(401,Posi,-50);
if isValidChar(tempmonster) then
tempmonster.fightpoints = tempmonster.fightpoints - 100;
return true
end
end
return false
end
|
require("monster.base.drop")
require("monster.base.lookat")
require("monster.base.quests")
require("base.messages");
module("monster.mon_27_wasps", package.seeall)
function ini(Monster)
init=true;
monster.base.quests.iniQuests();
killer={}; --A list that keeps track of who attacked the monster last
--Random Messages
msgs = base.messages.Messages();
msgs:addMessage("#me fliegt, ein hohes, weinerlich klingendes Gerusch machend umher.", "#me flies around, making a high pitched whining sound.");
msgs:addMessage("#me landet nur um wieder abheben zu knnen begleitet von einem kurzen Summen.", "#me lands, only to take off again with a short buzz.");
msgs:addMessage("#me peitscht, einen Landeplatz suchend durch die Luft.", "#me whips about in the air, searching for somewhere to land.");
msgs:addMessage("#me schwirrt drohend in keine bestimmte Richtung.", "#me angrily buzzes around in no particular direction.");
msgs:addMessage("Bzzz.", "Bzzz.");
msgs:addMessage("#me fliegt in wilden Kreisen und man kann das Gift an ihrem Stachel aufglnzen sehen.", "#me darts around, one can see venom dripping from its sting.");
msgs:addMessage("#me fhrt ihren spitzen Stachel aus.", "#me extends its sting.");
msgs:addMessage("Summ, summ.", "Buzz, buzz.");
msgs:addMessage("Bsss.", "Bsss.");
msgs:addMessage("#mes Flgel verbreiten ein hochfrequentes Summen, welches in den Ohren schmerzt.", "#me's wings exude a buzzing with high frequency, it hurts one's ears.");
end
function enemyNear(Monster,Enemy)
if init==nil then
ini(Monster);
end
if math.random(1,10) == 1 then
monster.base.drop.MonsterRandomTalk(Monster,msgs); --a random message is spoken once in a while
end
local MonID=Monster:getMonsterType();
if (MonID==278) then
world:gfx(9,Monster.pos);
end
return false
end
function enemyOnSight(Monster,Enemy)
if init==nil then
ini(Monster);
end
monster.base.drop.MonsterRandomTalk(Monster,msgs); --a random message is spoken once in a while
local MonID=Monster:getMonsterType();
if (MonID==278) then
world:gfx(9,Monster.pos);
end
if monster.base.drop.DefaultSlowdown( Monster ) then
return true
else
return false
end
end
function onAttacked(Monster,Enemy)
if init==nil then
ini(Monster);
end
monster.base.kills.setLastAttacker(Monster,Enemy)
killer[Monster.id]=Enemy.id; --Keeps track who attacked the monster last
end
function onCasted(Monster,Enemy)
if init==nil then
ini(Monster);
end
monster.base.kills.setLastAttacker(Monster,Enemy)
killer[Monster.id]=Enemy.id; --Keeps track who attacked the monster last
end
function onDeath(Monster)
monster.base.drop.ClearDropping();
local MonID=Monster:getMonsterType();
monster.base.drop.AddDropItem(2529,1,100,333,0,1); --honeycombs
if (MonID==278) then -- wasp of Fire!!!
CreateCircle( 1, 250,Monster.pos,3,false);
CreateCircle( 9, 750,Monster.pos,2,true);
CreateCircle(44,1000,Monster.pos,1,true);
world:gfx(36,Monster.pos);
world:makeSound(5,Monster.pos);
--HitChar(SourceItem.pos,3000,Monster.pos);
end
monster.base.drop.Dropping(Monster);
end
function CreateCircle(gfxid,Damage,CenterPos,Radius,setFlames)
local irad = math.ceil(Radius);
local dim = 2*(irad+1);
local x;
local y;
local map = {};
for x = -irad-1, irad do
map[x] = {};
for y = -irad-1, irad do
map[x][y] = (x+0.5)*(x+0.5)+(y+0.5)*(y+0.5)-irad*irad > 0
end;
end;
for x = -irad, irad do
for y = -irad, irad do
if not( map[x][y] and map[x-1][y] and map[x][y-1] and map[x-1][y-1] )
and( map[x][y] or map[x-1][y] or map[x][y-1] or map[x-1][y-1] ) then
HitPos=position( CenterPos.x + x, CenterPos.y + y, CenterPos.z );
world:gfx(gfxid,HitPos);
HitChar(HitPos,Damage,CenterPos);
if not SetNextTrap(HitPos,CenterPos) then
if setFlames then
if (math.random(1,5)==1) then
world:createItemFromId(359,1,HitPos,true,math.random(200,600),0);
end
end
end
end;
end;
end;
end;
function HitChar(Posi,Hitpoints,CenterPos)
if world:isCharacterOnField(Posi) then
local Character = world:getCharacterOnField(Posi);
if (Character:getType()==1) then
if (Character:getMonsterType() == 401) then
if not equapos(Posi,CenterPos) then
return
end
elseif (Character:getMonsterType() == 278) then
Character:increaseAttrib("hitpoints",-10000);
return
end
end
if equapos(Posi,CenterPos) then
Character:warp(position(Character.pos.x+math.random(-9,9),Character.pos.y+math.random(-9,9),Character.pos.z));
else
local Distance = Character:distanceMetricToPosition(CenterPos);
local Diffx = CenterPos.x - Character.pos.x;
local Diffy = CenterPos.y - Character.pos.y;
if (Distance == 1) then
Diffx = 6*Diffx;
Diffy = 6*Diffy;
elseif (Distance == 2) then
Diffx = 2*Diffx;
Diffy = 2*Diffy;
end
Character:warp(position(Character.pos.x-Diffx,Character.pos.y-Diffy,Character.pos.z));
end
base.common.TempInformNLS(Character,
"Getroffen von der Detonation wirst du davon geschleudert.",
"Hitted by the detonation, you get thrown away.");
Character:increaseAttrib("hitpoints",-Hitpoints);
end;
end;
function SetNextTrap(Posi,CenterPos)
if equapos(Posi,CenterPos) then
return false
end
if not world:isItemOnField(Posi) then
return false
end
TestItem = world:getItemOnField(Posi);
if (TestItem.data ~= 2) then
return false
end
if ((TestItem.id >= 377) and (TestItem.id <=381)) then
local tempmonster = world:createMonster(401,Posi,-50);
if isValidChar(tempmonster) then
tempmonster.fightpoints = tempmonster.fightpoints - 100;
return true
end
end
return false
end
|
fix infinite loop (fixed in server)
|
fix infinite loop (fixed in server)
|
Lua
|
agpl-3.0
|
KayMD/Illarion-Content,Baylamon/Illarion-Content,Illarion-eV/Illarion-Content,LaFamiglia/Illarion-Content,vilarion/Illarion-Content
|
712c3f1031b5bafce5a30211bff05e3924da3a0c
|
src/nodish/net/socket.lua
|
src/nodish/net/socket.lua
|
local S = require'syscall'
local emitter = require'nodish.emitter'
local ev = require'ev'
-- TODO: employ ljsyscall
local isip = function(ip)
local addrinfo,err = socket.dns.getaddrinfo(ip)
if err then
return false
end
return true
end
-- TODO: employ ljsyscall
local isipv6 = function(ip)
local addrinfo,err = socket.dns.getaddrinfo(ip)
if addrinfo then
assert(#addrinfo > 0)
if addrinfo[1].family == 'inet6' then
return true
end
end
return false
end
-- TODO: employ ljsyscall
local isipv4 = function(ip)
return isip(ip) and not isipv6(ip)
end
local new = function()
local self = emitter.new()
local sock
local loop = ev.Loop.default
local connecting = false
local connected = false
local closing = false
local watchers = {}
local on_error = function(err)
if err ~= 'closed' then
self:emit('error',err)
end
self:emit('close')
self:destroy()
end
local EAGAIN = S.c.E.AGAIN
local read_io = function()
assert(sock)
return ev.IO.new(function()
repeat
local data,err = sock:read()
if data then
if #data > 0 then
if watchers.timer then
watchers.timer:again(loop)
end
self:emit('data',data)
else
on_error('closed')
end
elseif err and err.errno ~= EAGAIN then
on_error(tostring(err))
end
until not sock
end,sock:getfd(),ev.READ)
end
local pending
local pos
local write_io = function()
assert(sock)
local pos = 1
local left
return ev.IO.new(function(loop,io)
local sent,err = sock:write(pending:sub(pos))
if err and err.errno ~= EAGAIN then
io:stop(loop)
on_error(tostring(err))
return
elseif sent == 0 then
io:stop(loop)
on_error('closed')
return
else
pos = pos + sent
if pos > #pending then
pos = 1
pending = nil
io:stop(loop)
self:emit('_drain')
self:emit('drain')
end
end
if watchers.timer then
watchers.timer:again(loop)
end
end,sock:getfd(),ev.WRITE)
end
local on_connect = function()
connecting = false
connected = true
watchers.read = read_io()
watchers.write = write_io()
self:resume()
self:emit('connect',self)
end
self.connect = function(_,port,ip)
ip = ip or '127.0.0.1'
-- if not isip(ip) then
-- on_error(err)
-- end
if sock and closing then
self:once('close',function(self)
self:_connect(port,ip)
end)
elseif not connecting then
self:_connect(port,ip)
end
end
self._connect = function(_,port,ip)
assert(not sock)
-- if isipv6(ip) then
-- sock = S.socket.tcp6()
-- else
-- sock = socket.tcp()
-- end
local addr = S.types.t.sockaddr_in(port,ip)
sock = S.socket('inet','stream')
sock:nonblock(true)
connecting = true
closing = false
local ok,err = sock:connect(addr)
if ok or err.errno == S.c.E.ALREADY then
on_connect()
elseif err.errno == S.c.E.INPROGRESS then
watchers.connect = ev.IO.new(function(loop,io)
local ok,err = sock:connect(addr)
if ok or err.errno == S.c.E.ISCONN then
io:stop(loop)
watchers.connect = nil
on_connect()
else
on_error(tostring(err))
end
end,sock:getfd(),ev.WRITE)
watchers.connect:start(loop)
else
on_error(tostring(err))
end
end
self._transfer = function(_,s)
sock = s
sock:nonblock(true)
on_connect()
end
self.write = function(_,data)
if pending then
pending = pending..data
else
pending = data
if connecting then
self:once('connect',function()
watchers.write:start(loop)
end)
elseif connected then
watchers.write:start(loop)
else
self:emit('error','wrong state')
self:emit('close')
self:destroy()
end
end
return self
end
self.fin = function(_,data)
if pending or data then
if data then
self:write(data)
end
self:once('_drain',function()
sock:shutdown(S.c.SHUT.RD)
end)
else
sock:shutdown(S.c.SHUT.RD)
end
return self
end
self.destroy = function()
for _,watcher in pairs(watchers) do
watcher:stop(loop)
end
if sock then
sock:close()
sock = nil
end
end
self.pause = function()
watchers.read:stop(loop)
end
self.resume = function()
watchers.read:start(loop)
end
self.address = function()
if sock then
local res = {sock:getsockname()}
if #res == 3 then
local res_obj = {
address = res[1],
port = tonumber(res[2]),
family = res[3] == 'inet' and 'ipv4' or 'ipv6',
}
return res_obj
end
return
end
end
self.set_timeout = function(_,msecs,callback)
if msecs > 0 and type(msecs) == 'number' then
if watchers.timer then
watchers.timer:stop(loop)
end
local secs = msecs / 1000
watchers.timer = ev.Timer.new(function()
self:emit('timeout')
end,secs,secs)
watchers.timer:start(loop)
if callback then
self:once('timeout',callback)
end
else
watchers.timer:stop(loop)
if callback then
self:remove_listener('timeout',callback)
end
end
end
self.set_keepalive = function(_,enable)
if sock then
sock:setsockopt(S.c.SO.KEEPALIVE,enable)
end
end
self.set_nodelay = function(_,enable)
if sock then
-- TODO: employ ljsiscall
-- sock:setoption('tcp-nodelay',enable)
end
end
return self
end
local connect = function(port,ip,cb)
local sock = new()
if type(ip) == 'function' then
cb = ip
end
sock:once('connect',cb)
sock:connect(port,ip)
return sock
end
return {
new = new,
connect = connect,
create_connection = connect,
}
|
local S = require'syscall'
local emitter = require'nodish.emitter'
local ev = require'ev'
-- TODO: employ ljsyscall
local isip = function(ip)
local addrinfo,err = socket.dns.getaddrinfo(ip)
if err then
return false
end
return true
end
-- TODO: employ ljsyscall
local isipv6 = function(ip)
local addrinfo,err = socket.dns.getaddrinfo(ip)
if addrinfo then
assert(#addrinfo > 0)
if addrinfo[1].family == 'inet6' then
return true
end
end
return false
end
-- TODO: employ ljsyscall
local isipv4 = function(ip)
return isip(ip) and not isipv6(ip)
end
local new = function()
local self = emitter.new()
local sock
local loop = ev.Loop.default
local connecting = false
local connected = false
local closing = false
local watchers = {}
local on_error = function(err)
if err ~= 'closed' then
self:emit('error',err)
end
self:emit('close')
self:destroy()
end
local EAGAIN = S.c.E.AGAIN
local read_io = function()
assert(sock)
return ev.IO.new(function()
repeat
local data,err = sock:read()
if data then
if #data > 0 then
if watchers.timer then
watchers.timer:again(loop)
end
self:emit('data',data)
else
on_error('closed')
end
elseif err and err.errno ~= EAGAIN then
on_error(tostring(err))
else
break
end
until not sock
end,sock:getfd(),ev.READ)
end
local pending
local pos
local write_io = function()
assert(sock)
local pos = 1
local left
return ev.IO.new(function(loop,io)
local sent,err = sock:write(pending:sub(pos))
if err and err.errno ~= EAGAIN then
io:stop(loop)
on_error(tostring(err))
return
elseif sent == 0 then
io:stop(loop)
on_error('closed')
return
else
pos = pos + sent
if pos > #pending then
pos = 1
pending = nil
io:stop(loop)
self:emit('_drain')
self:emit('drain')
end
end
if watchers.timer then
watchers.timer:again(loop)
end
end,sock:getfd(),ev.WRITE)
end
local on_connect = function()
connecting = false
connected = true
watchers.read = read_io()
watchers.write = write_io()
self:resume()
self:emit('connect',self)
end
self.connect = function(_,port,ip)
ip = ip or '127.0.0.1'
-- if not isip(ip) then
-- on_error(err)
-- end
if sock and closing then
self:once('close',function(self)
self:_connect(port,ip)
end)
elseif not connecting then
self:_connect(port,ip)
end
end
self._connect = function(_,port,ip)
assert(not sock)
-- if isipv6(ip) then
-- sock = S.socket.tcp6()
-- else
-- sock = socket.tcp()
-- end
local addr = S.types.t.sockaddr_in(port,ip)
sock = S.socket('inet','stream')
sock:nonblock(true)
connecting = true
closing = false
local ok,err = sock:connect(addr)
if ok or err.errno == S.c.E.ALREADY then
on_connect()
elseif err.errno == S.c.E.INPROGRESS then
watchers.connect = ev.IO.new(function(loop,io)
local ok,err = sock:connect(addr)
if ok or err.errno == S.c.E.ISCONN then
io:stop(loop)
watchers.connect = nil
on_connect()
else
on_error(tostring(err))
end
end,sock:getfd(),ev.WRITE)
watchers.connect:start(loop)
else
on_error(tostring(err))
end
end
self._transfer = function(_,s)
sock = s
sock:nonblock(true)
on_connect()
end
self.write = function(_,data)
if pending then
pending = pending..data
else
pending = data
if connecting then
self:once('connect',function()
watchers.write:start(loop)
end)
elseif connected then
watchers.write:start(loop)
else
self:emit('error','wrong state')
self:emit('close')
self:destroy()
end
end
return self
end
self.fin = function(_,data)
if pending or data then
if data then
self:write(data)
end
self:once('_drain',function()
sock:shutdown(S.c.SHUT.RD)
end)
else
sock:shutdown(S.c.SHUT.RD)
end
return self
end
self.destroy = function()
for _,watcher in pairs(watchers) do
watcher:stop(loop)
end
if sock then
sock:close()
sock = nil
end
end
self.pause = function()
watchers.read:stop(loop)
end
self.resume = function()
watchers.read:start(loop)
end
self.address = function()
if sock then
local res = {sock:getsockname()}
if #res == 3 then
local res_obj = {
address = res[1],
port = tonumber(res[2]),
family = res[3] == 'inet' and 'ipv4' or 'ipv6',
}
return res_obj
end
return
end
end
self.set_timeout = function(_,msecs,callback)
if msecs > 0 and type(msecs) == 'number' then
if watchers.timer then
watchers.timer:stop(loop)
end
local secs = msecs / 1000
watchers.timer = ev.Timer.new(function()
self:emit('timeout')
end,secs,secs)
watchers.timer:start(loop)
if callback then
self:once('timeout',callback)
end
else
watchers.timer:stop(loop)
if callback then
self:remove_listener('timeout',callback)
end
end
end
self.set_keepalive = function(_,enable)
if sock then
sock:setsockopt(S.c.SO.KEEPALIVE,enable)
end
end
self.set_nodelay = function(_,enable)
if sock then
-- TODO: employ ljsiscall
-- sock:setoption('tcp-nodelay',enable)
end
end
return self
end
local connect = function(port,ip,cb)
local sock = new()
if type(ip) == 'function' then
cb = ip
end
sock:once('connect',cb)
sock:connect(port,ip)
return sock
end
return {
new = new,
connect = connect,
create_connection = connect,
}
|
fix read loop
|
fix read loop
|
Lua
|
mit
|
lipp/nodish
|
e38e189b35cad922dea032d7faaa456858329edc
|
modules/luci-mod-freifunk/luasrc/model/cbi/freifunk/basics.lua
|
modules/luci-mod-freifunk/luasrc/model/cbi/freifunk/basics.lua
|
-- Copyright 2008 Steven Barth <[email protected]>
-- Copyright 2011 Manuel Munz <freifunk at somakoma de>
-- Licensed to the public under the Apache License 2.0.
local fs = require "nixio.fs"
local util = require "luci.util"
local uci = require "luci.model.uci".cursor()
local profiles = "/etc/config/profile_*"
m = Map("freifunk", translate ("Community"))
c = m:section(NamedSection, "community", "public", nil, translate("These are the basic settings for your local wireless community. These settings define the default values for the wizard and DO NOT affect the actual configuration of the router."))
community = c:option(ListValue, "name", translate ("Community"))
community.rmempty = false
local profile
for profile in fs.glob(profiles) do
local name = uci:get_first(profile, "community", "name") or "?"
community:value(string.gsub(profile, "/etc/config/profile_", ""), name)
end
n = Map("system", translate("Basic system settings"))
function n.on_after_commit(self)
luci.http.redirect(luci.dispatcher.build_url("admin", "freifunk", "basics"))
end
b = n:section(TypedSection, "system")
b.anonymous = true
hn = b:option(Value, "hostname", translate("Hostname"))
hn.rmempty = false
hn.datatype = "hostname"
loc = b:option(Value, "location", translate("Location"))
loc.rmempty = false
loc.datatype = "minlength(1)"
lat = b:option(Value, "latitude", translate("Latitude"), translate("e.g.") .. " 48.12345")
lat.datatype = "float"
lat.rmempty = false
lon = b:option(Value, "longitude", translate("Longitude"), translate("e.g.") .. " 10.12345")
lon.datatype = "float"
lon.rmempty = false
--[[
Opens an OpenStreetMap iframe or popup
Makes use of resources/OSMLatLon.htm and htdocs/resources/osm.js
]]--
local class = util.class
local ff = uci:get("freifunk", "community", "name") or ""
local co = "profile_" .. ff
local deflat = uci:get_first("system", "system", "latitude") or uci:get_first(co, "community", "latitude") or 52
local deflon = uci:get_first("system", "system", "longitude") or uci:get_first(co, "community", "longitude") or 10
local zoom = 12
if ( deflat == 52 and deflon == 10 ) then
zoom = 4
end
OpenStreetMapLonLat = luci.util.class(AbstractValue)
function OpenStreetMapLonLat.__init__(self, ...)
AbstractValue.__init__(self, ...)
self.template = "cbi/osmll_value"
self.latfield = nil
self.lonfield = nil
self.centerlat = ""
self.centerlon = ""
self.zoom = "0"
self.width = "100%" --popups will ignore the %-symbol, "100%" is interpreted as "100"
self.height = "600"
self.popup = false
self.displaytext="OpenStreetMap" --text on button, that loads and displays the OSMap
self.hidetext="X" -- text on button, that hides OSMap
end
osm = b:option(OpenStreetMapLonLat, "latlon", translate("Find your coordinates with OpenStreetMap"), translate("Select your location with a mouse click on the map. The map will only show up if you are connected to the Internet."))
osm.latfield = "latitude"
osm.lonfield = "longitude"
osm.centerlat = uci:get_first("system", "system", "latitude") or deflat
osm.centerlon = uci:get_first("system", "system", "longitude") or deflon
osm.zoom = zoom
osm.width = "100%"
osm.height = "600"
osm.popup = false
osm.displaytext=translate("Show OpenStreetMap")
osm.hidetext=translate("Hide OpenStreetMap")
return m, n
|
-- Copyright 2008 Steven Barth <[email protected]>
-- Copyright 2011 Manuel Munz <freifunk at somakoma de>
-- Licensed to the public under the Apache License 2.0.
local fs = require "nixio.fs"
local util = require "luci.util"
local uci = require "luci.model.uci".cursor()
local profiles = "/etc/config/profile_*"
m = Map("freifunk", translate ("Community"))
c = m:section(NamedSection, "community", "public", nil, translate("These are the basic settings for your local wireless community. These settings define the default values for the wizard and DO NOT affect the actual configuration of the router."))
community = c:option(ListValue, "name", translate ("Community"))
community.rmempty = false
local profile
for profile in fs.glob(profiles) do
local name = uci:get_first(string.gsub(profile, "/etc/config/", ""), "community", "name") or "?"
community:value(string.gsub(profile, "/etc/config/profile_", ""), name)
end
n = Map("system", translate("Basic system settings"))
function n.on_after_commit(self)
luci.http.redirect(luci.dispatcher.build_url("admin", "freifunk", "basics"))
end
b = n:section(TypedSection, "system")
b.anonymous = true
hn = b:option(Value, "hostname", translate("Hostname"))
hn.rmempty = false
hn.datatype = "hostname"
loc = b:option(Value, "location", translate("Location"))
loc.rmempty = false
loc.datatype = "minlength(1)"
lat = b:option(Value, "latitude", translate("Latitude"), translate("e.g.") .. " 48.12345")
lat.datatype = "float"
lat.rmempty = false
lon = b:option(Value, "longitude", translate("Longitude"), translate("e.g.") .. " 10.12345")
lon.datatype = "float"
lon.rmempty = false
--[[
Opens an OpenStreetMap iframe or popup
Makes use of resources/OSMLatLon.htm and htdocs/resources/osm.js
]]--
local class = util.class
local ff = uci:get("freifunk", "community", "name") or ""
local co = "profile_" .. ff
local deflat = uci:get_first("system", "system", "latitude") or uci:get_first(co, "community", "latitude") or 52
local deflon = uci:get_first("system", "system", "longitude") or uci:get_first(co, "community", "longitude") or 10
local zoom = 12
if ( deflat == 52 and deflon == 10 ) then
zoom = 4
end
OpenStreetMapLonLat = luci.util.class(AbstractValue)
function OpenStreetMapLonLat.__init__(self, ...)
AbstractValue.__init__(self, ...)
self.template = "cbi/osmll_value"
self.latfield = nil
self.lonfield = nil
self.centerlat = ""
self.centerlon = ""
self.zoom = "0"
self.width = "100%" --popups will ignore the %-symbol, "100%" is interpreted as "100"
self.height = "600"
self.popup = false
self.displaytext="OpenStreetMap" --text on button, that loads and displays the OSMap
self.hidetext="X" -- text on button, that hides OSMap
end
osm = b:option(OpenStreetMapLonLat, "latlon", translate("Find your coordinates with OpenStreetMap"), translate("Select your location with a mouse click on the map. The map will only show up if you are connected to the Internet."))
osm.latfield = "latitude"
osm.lonfield = "longitude"
osm.centerlat = uci:get_first("system", "system", "latitude") or deflat
osm.centerlon = uci:get_first("system", "system", "longitude") or deflon
osm.zoom = zoom
osm.width = "100%"
osm.height = "600"
osm.popup = false
osm.displaytext=translate("Show OpenStreetMap")
osm.hidetext=translate("Hide OpenStreetMap")
return m, n
|
luci-mod-freifunk: fix the list of community profiles
|
luci-mod-freifunk: fix the list of community profiles
Signed-off-by: pmelange <[email protected]>
|
Lua
|
apache-2.0
|
hnyman/luci,rogerpueyo/luci,artynet/luci,hnyman/luci,rogerpueyo/luci,Noltari/luci,tobiaswaldvogel/luci,openwrt-es/openwrt-luci,Noltari/luci,rogerpueyo/luci,openwrt/luci,rogerpueyo/luci,lbthomsen/openwrt-luci,Noltari/luci,nmav/luci,openwrt/luci,lbthomsen/openwrt-luci,openwrt-es/openwrt-luci,nmav/luci,nmav/luci,openwrt-es/openwrt-luci,lbthomsen/openwrt-luci,openwrt-es/openwrt-luci,artynet/luci,artynet/luci,tobiaswaldvogel/luci,openwrt/luci,openwrt-es/openwrt-luci,openwrt/luci,openwrt/luci,artynet/luci,tobiaswaldvogel/luci,tobiaswaldvogel/luci,rogerpueyo/luci,nmav/luci,artynet/luci,nmav/luci,hnyman/luci,hnyman/luci,lbthomsen/openwrt-luci,hnyman/luci,hnyman/luci,Noltari/luci,openwrt-es/openwrt-luci,artynet/luci,openwrt/luci,Noltari/luci,nmav/luci,rogerpueyo/luci,tobiaswaldvogel/luci,nmav/luci,Noltari/luci,tobiaswaldvogel/luci,rogerpueyo/luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,Noltari/luci,Noltari/luci,hnyman/luci,Noltari/luci,openwrt-es/openwrt-luci,artynet/luci,openwrt/luci,rogerpueyo/luci,hnyman/luci,openwrt/luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,artynet/luci,artynet/luci,nmav/luci,openwrt-es/openwrt-luci,nmav/luci
|
2f83c35322a342a064cad6a96080bd07992ac0a3
|
shared/entitymanager.lua
|
shared/entitymanager.lua
|
local Class = require "shared.middleclass"
local GameMath = require "shared.gamemath"
local Building = require "shared.building"
local Unit = require "shared.unit"
local EntityManager = Class "EntityManager"
function EntityManager:initialize(logicCore)
self.logicCore = logicCore
self.nextId = 1
self.entities = {}
self.drawLayer = {
buildings = {},
units = {},
}
end
function EntityManager:update(dt)
for id, entity in pairs(self.entities) do
entity:update(dt)
end
end
function EntityManager:draw(dt)
local buildings = self.drawLayer.buildings
local units = self.drawLayer.units
for i = 1, #buildings do
local current = buildings[i]
current:draw(dt)
end
for i = 1, #units do
local current = units[i]
current:draw(dt)
end
end
function EntityManager:spawnFromEntityStatic(entityStatic, player)
local entityClass = require(entityStatic.classSource)
local entity = entityClass:new(entityStatic, player)
self:add(entity)
return entity
end
function EntityManager:add(entity)
local id = self.nextId
self.nextId = id + 1
entity.id = id
self.entities[id] = entity
if entity:isInstanceOf(Building) then
table.insert(self.drawLayer.buildings, entity)
elseif entity:isInstanceOf(Unit) then
table.insert(self.drawLayer.units, entity)
end
end
function EntityManager:remove(id)
local entity = self.entities[id]
if self.entities[id] then
self.entities[id]:delete()
self.entities[id] = nil
end
if entity:isInstanceOf(Building) then
for i = 1, #self.drawLayer.buildings do
table.remove(self.drawLayer.buildings, i)
break
end
elseif entity:isInstanceOf(Unit) then
for i = 1, #self.drawLayer.units do
table.remove(self.drawLayer.units, i)
break
end
end
end
function EntityManager:entity(id)
return self.entities[id]
end
local function noOp()
return true
end
-- position: vector2
-- filter: [optional] filter function(entity)
function EntityManager:findClosestEntity(position, filter, radius)
radius = radius or math.huge
filter = filter or noOp
local entities = self.entities
local closestDist = math.huge
local closestEntity
for id, entity in pairs(entities) do
if filter(entity) then
local d = GameMath.Vector2.distance(entity.position, position)
if d < closestDist and d < radius then
closestEntity = entity
closestDist = d
end
end
end
return closestEntity, closestDist
end
function EntityManager:findAllEntities(filter)
local entities = {}
for id, entity in pairs(self.entities) do
if filter(entity) then
table.insert(entities, entity)
end
end
return entities
end
function EntityManager:clear()
for id, entity in pairs(self.entities) do
self:remove(id)
end
end
return EntityManager
|
local Class = require "shared.middleclass"
local GameMath = require "shared.gamemath"
local Building = require "shared.building"
local Unit = require "shared.unit"
local EntityManager = Class "EntityManager"
function EntityManager:initialize(logicCore)
self.logicCore = logicCore
self.nextId = 1
self.entities = {}
self.drawLayer = {
buildings = {},
units = {},
}
end
function EntityManager:update(dt)
for id, entity in pairs(self.entities) do
entity:update(dt)
end
end
function EntityManager:draw(dt)
local buildings = self.drawLayer.buildings
local units = self.drawLayer.units
for i = 1, #buildings do
local current = buildings[i]
current:draw(dt)
end
for i = 1, #units do
local current = units[i]
current:draw(dt)
end
end
function EntityManager:spawnFromEntityStatic(entityStatic, player)
local entityClass = require(entityStatic.classSource)
local entity = entityClass:new(entityStatic, player)
self:add(entity)
return entity
end
function EntityManager:add(entity)
local id = self.nextId
self.nextId = id + 1
entity.id = id
self.entities[id] = entity
if entity:isInstanceOf(Building) then
table.insert(self.drawLayer.buildings, entity)
elseif entity:isInstanceOf(Unit) then
table.insert(self.drawLayer.units, entity)
end
end
function EntityManager:remove(id)
local entity = self.entities[id]
if self.entities[id] then
self.entities[id]:delete()
self.entities[id] = nil
end
if entity:isInstanceOf(Building) then
for i, entity in pairs(self.drawLayer.buildings) do
if entity.id == id then
table.remove(self.drawLayer.buildings, i)
break
end
end
elseif entity:isInstanceOf(Unit) then
for i, entity in pairs(self.drawLayer.units) do
if entity.id == id then
table.remove(self.drawLayer.units, i)
break
end
end
end
end
function EntityManager:entity(id)
return self.entities[id]
end
local function noOp()
return true
end
-- position: vector2
-- filter: [optional] filter function(entity)
function EntityManager:findClosestEntity(position, filter, radius)
radius = radius or math.huge
filter = filter or noOp
local entities = self.entities
local closestDist = math.huge
local closestEntity
for id, entity in pairs(entities) do
if filter(entity) then
local d = GameMath.Vector2.distance(entity.position, position)
if d < closestDist and d < radius then
closestEntity = entity
closestDist = d
end
end
end
return closestEntity, closestDist
end
function EntityManager:findAllEntities(filter)
local entities = {}
for id, entity in pairs(self.entities) do
if filter(entity) then
table.insert(entities, entity)
end
end
return entities
end
function EntityManager:clear()
for id, entity in pairs(self.entities) do
self:remove(id)
end
end
return EntityManager
|
fixed entity removing from drawlayers
|
fixed entity removing from drawlayers
|
Lua
|
mit
|
ExcelF/project-navel
|
8ce816de7f316c443186e6b72204a343f2938744
|
test/testmongodb.lua
|
test/testmongodb.lua
|
local skynet = require "skynet"
local mongo = require "skynet.db.mongo"
local bson = require "bson"
local host, db_name = ...
function test_insert_without_index()
local db = mongo.client({host = host})
db[db_name].testdb:dropIndex("*")
db[db_name].testdb:drop()
local ret = db[db_name].testdb:safe_insert({test_key = 1});
assert(ret and ret.n == 1)
local ret = db[db_name].testdb:safe_insert({test_key = 1});
assert(ret and ret.n == 1)
end
function test_insert_with_index()
local db = mongo.client({host = host})
db[db_name].testdb:dropIndex("*")
db[db_name].testdb:drop()
db[db_name].testdb:ensureIndex({test_key = 1}, {unique = true, name = "test_key_index"})
local ret = db[db_name].testdb:safe_insert({test_key = 1})
assert(ret and ret.n == 1)
local ret = db[db_name].testdb:safe_insert({test_key = 1})
assert(ret and ret.n == 0)
end
function test_find_and_remove()
local db = mongo.client({host = host})
db[db_name].testdb:dropIndex("*")
db[db_name].testdb:drop()
db[db_name].testdb:ensureIndex({test_key = 1}, {test_key2 = -1}, {unique = true, name = "test_index"})
local ret = db[db_name].testdb:safe_insert({test_key = 1, test_key2 = 1})
assert(ret and ret.n == 1)
local ret = db[db_name].testdb:safe_insert({test_key = 1, test_key2 = 2})
assert(ret and ret.n == 1)
local ret = db[db_name].testdb:safe_insert({test_key = 2, test_key2 = 3})
assert(ret and ret.n == 1)
local ret = db[db_name].testdb:findOne({test_key2 = 1})
assert(ret and ret.test_key2 == 1)
local ret = db[db_name].testdb:find({test_key2 = {['$gt'] = 0}}):sort({test_key = 1}, {test_key2 = -1}):skip(1):limit(1)
assert(ret:count() == 3)
assert(ret:count(true) == 1)
if ret:hasNext() then
ret = ret:next()
end
assert(ret and ret.test_key2 == 1)
db[db_name].testdb:delete({test_key = 1})
db[db_name].testdb:delete({test_key = 2})
local ret = db[db_name].testdb:findOne({test_key = 1})
assert(ret == nil)
end
function test_expire_index()
local db = mongo.client({host = host})
db[db_name].testdb:dropIndex("*")
db[db_name].testdb:drop()
db[db_name].testdb:ensureIndex({test_key = 1}, {unique = true, name = "test_key_index", expireAfterSeconds = 1, })
db[db_name].testdb:ensureIndex({test_date = 1}, {expireAfterSeconds = 1, })
local ret = db[db_name].testdb:safe_insert({test_key = 1, test_date = bson.date(os.time())})
assert(ret and ret.n == 1)
local ret = db[db_name].testdb:findOne({test_key = 1})
assert(ret and ret.test_key == 1)
for i = 1, 1000 do
skynet.sleep(1);
local ret = db[db_name].testdb:findOne({test_key = 1})
if ret == nil then
return
end
end
assert(false, "test expire index failed");
end
skynet.start(function()
print("Test insert without index")
test_insert_without_index()
print("Test insert index")
test_insert_with_index()
print("Test find and remove")
test_find_and_remove()
print("Test expire index")
test_expire_index()
print("mongodb test finish.");
end)
|
local skynet = require "skynet"
local mongo = require "skynet.db.mongo"
local bson = require "bson"
local host, port, db_name, username, password = ...
local function _create_client()
return mongo.client(
{
host = host, port = port,
username = username, password = password,
authdb = db_name,
}
)
end
function test_insert_without_index()
local db = _create_client()
db[db_name].testdb:dropIndex("*")
db[db_name].testdb:drop()
local ok, err, ret = db[db_name].testdb:safe_insert({test_key = 1});
assert(ok and ret and ret.n == 1, err)
local ok, err, ret = db[db_name].testdb:safe_insert({test_key = 1});
assert(ok and ret and ret.n == 1, err)
end
function test_insert_with_index()
local db = _create_client()
db[db_name].testdb:dropIndex("*")
db[db_name].testdb:drop()
db[db_name].testdb:ensureIndex({test_key = 1}, {unique = true, name = "test_key_index"})
local ok, err, ret = db[db_name].testdb:safe_insert({test_key = 1})
assert(ok and ret and ret.n == 1)
local ok, err, ret = db[db_name].testdb:safe_insert({test_key = 1})
assert(ok == false and string.find(err, "duplicate key error"))
end
function test_find_and_remove()
local db = _create_client()
db[db_name].testdb:dropIndex("*")
db[db_name].testdb:drop()
db[db_name].testdb:ensureIndex({test_key = 1}, {test_key2 = -1}, {unique = true, name = "test_index"})
local ok, err, ret = db[db_name].testdb:safe_insert({test_key = 1, test_key2 = 1})
assert(ok and ret and ret.n == 1, err)
local ok, err, ret = db[db_name].testdb:safe_insert({test_key = 1, test_key2 = 2})
assert(ok and ret and ret.n == 1, err)
local ok, err, ret = db[db_name].testdb:safe_insert({test_key = 2, test_key2 = 3})
assert(ok and ret and ret.n == 1, err)
local ret = db[db_name].testdb:findOne({test_key2 = 1})
assert(ret and ret.test_key2 == 1, err)
local ret = db[db_name].testdb:find({test_key2 = {['$gt'] = 0}}):sort({test_key = 1}, {test_key2 = -1}):skip(1):limit(1)
assert(ret:count() == 3)
assert(ret:count(true) == 1)
if ret:hasNext() then
ret = ret:next()
end
assert(ret and ret.test_key2 == 1)
db[db_name].testdb:delete({test_key = 1})
db[db_name].testdb:delete({test_key = 2})
local ret = db[db_name].testdb:findOne({test_key = 1})
assert(ret == nil)
end
function test_expire_index()
local db = _create_client()
db[db_name].testdb:dropIndex("*")
db[db_name].testdb:drop()
db[db_name].testdb:ensureIndex({test_key = 1}, {unique = true, name = "test_key_index", expireAfterSeconds = 1, })
db[db_name].testdb:ensureIndex({test_date = 1}, {expireAfterSeconds = 1, })
local ok, err, ret = db[db_name].testdb:safe_insert({test_key = 1, test_date = bson.date(os.time())})
assert(ok and ret and ret.n == 1, err)
local ret = db[db_name].testdb:findOne({test_key = 1})
assert(ret and ret.test_key == 1)
for i = 1, 60 do
skynet.sleep(100);
print("check expire", i)
local ret = db[db_name].testdb:findOne({test_key = 1})
if ret == nil then
return
end
end
print("test expire index failed")
assert(false, "test expire index failed");
end
skynet.start(function()
print("Test insert without index")
test_insert_without_index()
print("Test insert index")
test_insert_with_index()
print("Test find and remove")
test_find_and_remove()
print("Test expire index")
test_expire_index()
print("mongodb test finish.");
end)
|
fix mongodb testcase
|
fix mongodb testcase
|
Lua
|
mit
|
sundream/skynet,hongling0/skynet,xjdrew/skynet,great90/skynet,korialuo/skynet,cloudwu/skynet,zhangshiqian1214/skynet,sundream/skynet,JiessieDawn/skynet,icetoggle/skynet,Ding8222/skynet,zhouxiaoxiaoxujian/skynet,zhouxiaoxiaoxujian/skynet,JiessieDawn/skynet,zhangshiqian1214/skynet,wangyi0226/skynet,bttscut/skynet,bttscut/skynet,jxlczjp77/skynet,zhouxiaoxiaoxujian/skynet,firedtoad/skynet,cloudwu/skynet,wangyi0226/skynet,pigparadise/skynet,hongling0/skynet,bttscut/skynet,icetoggle/skynet,sanikoyes/skynet,xcjmine/skynet,xcjmine/skynet,zhangshiqian1214/skynet,zhangshiqian1214/skynet,firedtoad/skynet,zhangshiqian1214/skynet,xcjmine/skynet,hongling0/skynet,great90/skynet,jxlczjp77/skynet,korialuo/skynet,zhangshiqian1214/skynet,bigrpg/skynet,sanikoyes/skynet,ag6ag/skynet,Ding8222/skynet,bigrpg/skynet,pigparadise/skynet,wangyi0226/skynet,icetoggle/skynet,sanikoyes/skynet,xjdrew/skynet,JiessieDawn/skynet,cloudwu/skynet,bigrpg/skynet,pigparadise/skynet,Ding8222/skynet,jxlczjp77/skynet,ag6ag/skynet,great90/skynet,korialuo/skynet,ag6ag/skynet,sundream/skynet,xjdrew/skynet,firedtoad/skynet
|
c90f9558870e038a44fad024060110039096a515
|
test/test_proxy.lua
|
test/test_proxy.lua
|
local function zversion(zmq)
local version = zmq.version()
return string.format("%d.%d.%d", version[1], version[2], version[3])
end
local function iszvereq(zmq, mi, ma, bu)
local version = zmq.version()
return (mi == version[1]) and (ma == version[2]) and (bu == version[3])
end
local HAS_RUNNER = not not lunit
local lunit = require "lunit"
local TEST_CASE = assert(lunit.TEST_CASE)
local skip = lunit.skip or function() end
local SKIP = function(msg) return function() return skip(msg) end end
local IS_LUA52 = _VERSION >= 'Lua 5.2'
local TEST_FFI = ("ffi" == os.getenv("LZMQ"))
local LZMQ = "lzmq" .. (TEST_FFI and ".ffi" or "")
local zmq = require (LZMQ)
local zthreads = require (LZMQ .. ".threads" )
local ztimer = require (LZMQ .. ".timer" )
local function wait(ms)
ztimer.sleep(ms or 100)
end
local include_thread = [[
local LZMQ = ]] .. ("%q"):format(LZMQ) .. [[
local zmq = require (LZMQ)
local zthreads = require (LZMQ .. ".threads" )
local ctx = zthreads.get_parent_ctx()
local function assert(name, ...)
if ... then return ... end
local err = tostring((select('2', ...)))
print(name .. " Fail! Error: `" .. err .. "`")
os.exit(1)
end
local function assert_equal(name, a, b, ...)
if a == b then return b, ... end
print(name .. " Fail! Expected `" .. tostring(a) .. "` got `" .. tostring(b) .. "`")
os.exit(1)
end
]]
local _ENV = TEST_CASE'proxy' if true then
if not zmq.proxy then test = SKIP"zmq_proxy does not support" else
local cli_endpoint = "inproc://client"
local srv_endpoint = "inproc://server"
local ctx, thread, pipe
function setup()
ctx = zmq:context()
end
function teardown()
ctx:shutdown() -- interrupt thread
if thread then thread:join() end -- close thread
ctx:destroy() -- close context
end
function test_capture()
thread, pipe = zthreads.fork(ctx, include_thread .. [[
local pipe, cli_endpoint, srv_endpoint = ...
local fe = assert('ROUTER:', ctx:socket{zmq.ROUTER, connect = cli_endpoint})
local be = assert('DEALER:', ctx:socket{zmq.DEALER, connect = srv_endpoint})
local ok, err = zmq.proxy(fe, be, pipe)
--]], cli_endpoint, srv_endpoint)
local cli = assert(ctx:socket{zmq.REQ, bind = cli_endpoint, rcvtimeo=1000})
local srv = assert(ctx:socket{zmq.REP, bind = srv_endpoint, rcvtimeo=1000})
thread:start()
assert(cli:send("hello"))
local msg = assert_table(pipe:recv_all())
assert_equal(3, #msg) -- id, empty, message
assert_equal('', msg[2])
assert_equal('hello', msg[3])
assert_equal('hello', srv:recv())
----------------------------
assert(srv:send("world"))
local msg = assert_table(pipe:recv_all())
assert_equal(3, #msg) -- id, empty, message
assert_equal('', msg[2])
assert_equal('world', msg[3])
assert_equal('world', cli:recv())
end
function test_basic()
thread, pipe = zthreads.run(ctx, include_thread .. [[
local cli_endpoint, srv_endpoint = ...
local fe = assert('ROUTER:', ctx:socket{zmq.ROUTER, connect = cli_endpoint})
local be = assert('DEALER:', ctx:socket{zmq.DEALER, connect = srv_endpoint})
local ok, err = zmq.proxy(fe, be)
--]], cli_endpoint, srv_endpoint)
local cli = assert(ctx:socket{zmq.REQ, bind = cli_endpoint, rcvtimeo=1000})
local srv = assert(ctx:socket{zmq.REP, bind = srv_endpoint, rcvtimeo=1000})
thread:start()
assert(cli:send("hello"))
assert_equal('hello', srv:recv())
----------------------------
assert(srv:send("world"))
assert_equal('world', cli:recv())
end
end
end
local _ENV = TEST_CASE'proxy_steerable' if true then
if not zmq.proxy_steerable then test = SKIP"zmq_proxy_steerable does not support" else
local cli_endpoint = "inproc://client"
local srv_endpoint = "inproc://server"
local ctx, thread, pipe
function setup()
ctx = zmq:context()
end
function teardown()
ctx:shutdown() -- interrupt thread
if thread then thread:join() end -- close thread
ctx:destroy() -- close context
end
function test_control()
thread, pipe = zthreads.fork(ctx, include_thread .. [[
local pipe, cli_endpoint, srv_endpoint = ...
local fe = assert('ROUTER:', ctx:socket{zmq.ROUTER, connect = cli_endpoint})
local be = assert('DEALER:', ctx:socket{zmq.DEALER, connect = srv_endpoint})
local ok, err = zmq.proxy_steerable(fe, be, nil, pipe)
--]], cli_endpoint, srv_endpoint)
local cli = assert(ctx:socket{zmq.REQ, bind = cli_endpoint, rcvtimeo=1000})
local srv = assert(ctx:socket{zmq.REP, bind = srv_endpoint, rcvtimeo=1000})
thread:start()
pipe:send("PAUSE")
assert(cli:send("hello"))
local _, err = assert_nil(srv:recv())
assert_equal('EAGAIN', err:mnemo())
pipe:send("RESUME")
assert_equal("hello", srv:recv())
end
function test_basic()
thread, pipe = zthreads.run(ctx, include_thread .. [[
local cli_endpoint, srv_endpoint = ...
local fe = assert('ROUTER:', ctx:socket{zmq.ROUTER, connect = cli_endpoint})
local be = assert('DEALER:', ctx:socket{zmq.DEALER, connect = srv_endpoint})
local ok, err = zmq.proxy(fe, be)
--]], cli_endpoint, srv_endpoint)
local cli = assert(ctx:socket{zmq.REQ, bind = cli_endpoint, rcvtimeo=1000})
local srv = assert(ctx:socket{zmq.REP, bind = srv_endpoint, rcvtimeo=1000})
thread:start()
assert(cli:send("hello"))
assert_equal('hello', srv:recv())
----------------------------
assert(srv:send("world"))
assert_equal('world', cli:recv())
end
end
end
if not HAS_RUNNER then lunit.run() end
|
local function zversion(zmq)
local version = zmq.version()
return string.format("%d.%d.%d", version[1], version[2], version[3])
end
local function iszvereq(zmq, mi, ma, bu)
local version = zmq.version()
return (mi == version[1]) and (ma == version[2]) and (bu == version[3])
end
local HAS_RUNNER = not not lunit
local lunit = require "lunit"
local TEST_CASE = assert(lunit.TEST_CASE)
local skip = lunit.skip or function() end
local SKIP = function(msg) return function() return skip(msg) end end
local IS_LUA52 = _VERSION >= 'Lua 5.2'
local TEST_FFI = ("ffi" == os.getenv("LZMQ"))
local LZMQ = "lzmq" .. (TEST_FFI and ".ffi" or "")
local zmq = require (LZMQ)
local zthreads = require (LZMQ .. ".threads" )
local ztimer = require (LZMQ .. ".timer" )
local function wait(ms)
ztimer.sleep(ms or 100)
end
local include_thread = [[
local LZMQ = ]] .. ("%q"):format(LZMQ) .. [[
local zmq = require (LZMQ)
local zthreads = require (LZMQ .. ".threads" )
local ctx = zthreads.get_parent_ctx()
local function assert(name, ...)
if ... then return ... end
local err = tostring((select('2', ...)))
print(name .. " Fail! Error: `" .. err .. "`")
os.exit(1)
end
local function assert_equal(name, a, b, ...)
if a == b then return b, ... end
print(name .. " Fail! Expected `" .. tostring(a) .. "` got `" .. tostring(b) .. "`")
os.exit(1)
end
]]
local _ENV = TEST_CASE'proxy' if true then
if not zmq.proxy then test = SKIP"zmq_proxy does not support" else
local cli_endpoint = "inproc://client"
local srv_endpoint = "inproc://server"
local ctx, thread, pipe
function setup()
ctx = zmq:context()
end
function teardown()
ctx:destroy(0) -- close context
if thread then thread:join() end -- close thread
end
function test_capture()
thread, pipe = zthreads.fork(ctx, include_thread .. [[
local pipe, cli_endpoint, srv_endpoint = ...
local fe = assert('ROUTER:', ctx:socket{zmq.ROUTER, connect = cli_endpoint})
local be = assert('DEALER:', ctx:socket{zmq.DEALER, connect = srv_endpoint})
local ok, err = zmq.proxy(fe, be, pipe)
ctx:destroy(0)
--]], cli_endpoint, srv_endpoint)
local cli = assert(ctx:socket{zmq.REQ, bind = cli_endpoint, rcvtimeo=1000})
local srv = assert(ctx:socket{zmq.REP, bind = srv_endpoint, rcvtimeo=1000})
thread:start()
assert(cli:send("hello"))
local msg = assert_table(pipe:recv_all())
assert_equal(3, #msg) -- id, empty, message
assert_equal('', msg[2])
assert_equal('hello', msg[3])
assert_equal('hello', srv:recv())
----------------------------
assert(srv:send("world"))
local msg = assert_table(pipe:recv_all())
assert_equal(3, #msg) -- id, empty, message
assert_equal('', msg[2])
assert_equal('world', msg[3])
assert_equal('world', cli:recv())
end
function test_basic()
thread, pipe = zthreads.run(ctx, include_thread .. [[
local cli_endpoint, srv_endpoint = ...
local fe = assert('ROUTER:', ctx:socket{zmq.ROUTER, connect = cli_endpoint})
local be = assert('DEALER:', ctx:socket{zmq.DEALER, connect = srv_endpoint})
local ok, err = zmq.proxy(fe, be)
ctx:destroy(0)
--]], cli_endpoint, srv_endpoint)
local cli = assert(ctx:socket{zmq.REQ, bind = cli_endpoint, rcvtimeo=1000})
local srv = assert(ctx:socket{zmq.REP, bind = srv_endpoint, rcvtimeo=1000})
thread:start()
assert(cli:send("hello"))
assert_equal('hello', srv:recv())
----------------------------
assert(srv:send("world"))
assert_equal('world', cli:recv())
end
end
end
local _ENV = TEST_CASE'proxy_steerable' if true then
if not zmq.proxy_steerable then test = SKIP"zmq_proxy_steerable does not support" else
local cli_endpoint = "inproc://client"
local srv_endpoint = "inproc://server"
local ctx, thread, pipe
function setup()
ctx = zmq:context()
end
function teardown()
ctx:destroy(0) -- close context
if thread then thread:join() end -- close thread
end
function test_control()
thread, pipe = zthreads.fork(ctx, include_thread .. [[
local pipe, cli_endpoint, srv_endpoint = ...
local fe = assert('ROUTER:', ctx:socket{zmq.ROUTER, connect = cli_endpoint})
local be = assert('DEALER:', ctx:socket{zmq.DEALER, connect = srv_endpoint})
local ok, err = zmq.proxy_steerable(fe, be, nil, pipe)
ctx:destroy(0)
--]], cli_endpoint, srv_endpoint)
local cli = assert(ctx:socket{zmq.REQ, bind = cli_endpoint, rcvtimeo=1000})
local srv = assert(ctx:socket{zmq.REP, bind = srv_endpoint, rcvtimeo=1000})
thread:start()
pipe:send("PAUSE")
assert(cli:send("hello"))
local _, err = assert_nil(srv:recv())
assert_equal('EAGAIN', err:mnemo())
pipe:send("RESUME")
assert_equal("hello", srv:recv())
end
function test_basic()
thread, pipe = zthreads.run(ctx, include_thread .. [[
local cli_endpoint, srv_endpoint = ...
local fe = assert('ROUTER:', ctx:socket{zmq.ROUTER, connect = cli_endpoint})
local be = assert('DEALER:', ctx:socket{zmq.DEALER, connect = srv_endpoint})
local ok, err = zmq.proxy(fe, be)
ctx:destroy(0)
--]], cli_endpoint, srv_endpoint)
local cli = assert(ctx:socket{zmq.REQ, bind = cli_endpoint, rcvtimeo=1000})
local srv = assert(ctx:socket{zmq.REP, bind = srv_endpoint, rcvtimeo=1000})
thread:start()
assert(cli:send("hello"))
assert_equal('hello', srv:recv())
----------------------------
assert(srv:send("world"))
assert_equal('world', cli:recv())
end
end
end
if not HAS_RUNNER then lunit.run() end
|
Fix. test_proxy work without `ctx:shutdown` method.
|
Fix. test_proxy work without `ctx:shutdown` method.
|
Lua
|
mit
|
zeromq/lzmq,zeromq/lzmq,zeromq/lzmq,moteus/lzmq,LuaDist/lzmq-ffi,LuaDist/lzmq,bsn069/lzmq,LuaDist/lzmq,bsn069/lzmq,moteus/lzmq,LuaDist/lzmq-ffi,moteus/lzmq
|
7e3c29b3a3241746cdb80698334d731d5d60c909
|
src_trunk/resources/realism-system/c_headbob.lua
|
src_trunk/resources/realism-system/c_headbob.lua
|
function bobHead()
local logged = getElementData(getLocalPlayer(), "loggedin")
if (logged==1) then
for key, value in ipairs(getElementsByType("player")) do
local rot = getPedCameraRotation(value)
local x, y, z = getElementPosition(value)
local vx = x + math.sin(math.rad(rot)) * 10
local vy = y + math.cos(math.rad(rot)) * 10
setPedLookAt(value, vx, vy, 10, 3000)
end
end
end
addEventHandler("onClientRender", getRootElement(), bobHead)
|
function bobHead()
local logged = getElementData(getLocalPlayer(), "loggedin")
if (logged==1) then
for key, value in ipairs(getElementsByType("player")) do
if value == getLocalPlayer() then
local scrWidth, scrHeight = guiGetScreenSize()
local sx = scrWidth/2
local sy = scrHeight/2
local x, y, z = getWorldFromScreenPosition(sx, sy, 10)
setPedLookAt(value, x, y, z, 3000)
else
local rot = getPedCameraRotation(value)
local x, y, z = getElementPosition(value)
local vx = x + math.sin(math.rad(rot)) * 10
local vy = y + math.cos(math.rad(rot)) * 10
setPedLookAt(value, vx, vy, z, 3000)
end
end
end
addEventHandler("onClientRender", getRootElement(), bobHead)
|
fixed 246 and made the local player headbob work like before
|
fixed 246 and made the local player headbob work like before
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@72 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
12eae1c93e73369950802e750ca97f2c3d80e51a
|
test/testwebsocket.lua
|
test/testwebsocket.lua
|
local skynet = require "skynet"
local httpd = require "http.httpd"
local websocket = require "websocket"
local socket = require "skynet.socket"
local sockethelper = require "http.sockethelper"
local handler = {}
function handler.on_open(ws)
skynet.error(string.format("Client connected: %s", ws.addr))
ws:writetext("Hello websocket !")
end
function handler.on_message(ws, msg, sz)
skynet.error("Received a message from client:\n"..msg)
end
function handler.on_error(ws, msg)
skynet.error("Error. Client may be force closed.")
ws:close()
end
function handler.on_close(ws, code, reason)
skynet.error(string.format("Client disconnected: %s", ws.addr))
-- do not need close.
-- ws:close
end
local function handle_socket(fd, addr)
-- limit request body size to 8192 (you can pass nil to unlimit)
local code, url, method, header, body = httpd.read_request(sockethelper.readfunc(fd), 8192)
if code then
if url == "/ws" then
local ws = websocket.new(fd, addr, header, handler)
ws:start()
end
end
end
skynet.start(function()
local fd = assert(socket.listen("127.0.0.1:8001"))
socket.start(fd , function(fd, addr)
socket.start(fd)
pcall(handle_socket, fd, addr)
end)
end)
|
local skynet = require "skynet"
local httpd = require "http.httpd"
local websocket = require "websocket"
local socket = require "skynet.socket"
local sockethelper = require "http.sockethelper"
local handler = {}
function handler.on_open(ws)
skynet.error(string.format("Client connected: %s", ws.addr))
ws:writetext("Hello websocket !")
end
function handler.on_message(ws, msg, sz)
skynet.error("Received a message from client:\n"..msg)
end
function handler.on_error(ws, msg)
skynet.error("Error. Client may be force closed.")
ws:close()
end
function handler.on_close(ws, code, reason)
skynet.error(string.format("Client disconnected: %s", ws.addr))
-- do not need close.
-- ws:close
end
local function check_origin(origin, host)
return true
end
local function respcb(ret)
end
local function handle_socket(fd, addr)
-- limit request body size to 8192 (you can pass nil to unlimit)
local code, url, method, header, body = httpd.read_request(sockethelper.readfunc(fd), 8192)
if code then
if url == "/ws" then
if (not websocket.upgrade(header, check_origin, function(resp) socket.write(fd, resp) end)) then
socket.close(fd)
return
end
local ws = websocket.new(fd, addr, handler, nil)
end
end
end
skynet.start(function()
local fd = assert(socket.listen("127.0.0.1:8001"))
socket.start(fd , function(fd, addr)
socket.start(fd)
pcall(handle_socket, fd, addr)
end)
end)
|
fix test/testwebsocket.lua
|
fix test/testwebsocket.lua
|
Lua
|
mit
|
korialuo/skynet,korialuo/skynet,korialuo/skynet
|
31e4e02ee8b3108f0af68618d487b58e45198656
|
lua/entities/gmod_wire_cam/init.lua
|
lua/entities/gmod_wire_cam/init.lua
|
AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include('shared.lua')
ENT.WireDebugName = "Camera"
function ENT:Initialize()
self.phys = self:GetPhysicsObject()
if not self.phys:IsValid() then self.phys = self end
self.IdealPos = self:GetPos()
self.IdealAng = self:GetAngles()
self.IdealVel = self.phys:GetVelocity()
end
--[[
function ENT:Think()
--if IsValid(self:GetParent()) then return end
self:SetPos(self.IdealPos)
self:SetAngles(self.IdealAng)
self.phys:SetVelocity(self.IdealVel)
self:SetColor(Color(0,0,0,0))
self:NextThink(CurTime()+0.1)
end
]]
function ENT:ReceiveInfo(iname, value)
self.IdealAng = self:GetAngles()
if iname == "X" then
self.IdealPos.x = value
self:SetPos(self.IdealPos)
elseif iname == "Y" then
self.IdealPos.y = value
self:SetPos(self.IdealPos)
elseif iname == "Z" then
self.IdealPos.z = value
self:SetPos(self.IdealPos)
elseif iname == "Position" then
self.IdealPos = value
self:SetPos(self.IdealPos)
elseif iname == "Pitch" then
self.IdealAng.p = value
--self:SetAngles(self.IdealAng)
elseif iname == "Yaw" then
self.IdealAng.y = value
--self:SetAngles(self.IdealAng)
elseif iname == "Roll" then
self.IdealAng.r = value
--self:SetAngles(self.IdealAng)
elseif iname == "Angle" then
self.IdealAng = value
--self:SetAngles(self.IdealAng)
elseif iname == "Direction" then
self.IdealAng = value:Angle()
--self:SetAngles(self.IdealAng)
elseif iname == "Velocity" then
self.IdealVel = value
self.phys:SetVelocity(self.IdealVel)
elseif iname == "Parent" then
if IsValid(value) then
self:SetParent(value)
else
self:SetParent(nil)
end
end
if self:GetAngles() ~= self.IdealAng then
local parent = self:GetParent()
self:SetParent(nil)
self:SetAngles(self.IdealAng)
self:SetParent(parent)
end
end
function ENT:OnRemove()
Wire_Remove(self)
end
function ENT:OnRestore()
Wire_Restored(self)
end
|
AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include('shared.lua')
ENT.WireDebugName = "Camera"
function ENT:Initialize()
self.phys = self:GetPhysicsObject()
if not self.phys:IsValid() then self.phys = self end
self.IdealPos = self:GetPos()
self.IdealAng = self:GetAngles()
self.IdealVel = self.phys:GetVelocity()
end
--[[
function ENT:Think()
--if IsValid(self:GetParent()) then return end
self:SetPos(self.IdealPos)
self:SetAngles(self.IdealAng)
self.phys:SetVelocity(self.IdealVel)
self:SetColor(Color(0,0,0,0))
self:NextThink(CurTime()+0.1)
end
]]
function ENT:ReceiveInfo(iname, value)
self.IdealAng = self:GetAngles()
if iname == "X" then
self.IdealPos.x = value
self:SetPos(self.IdealPos)
elseif iname == "Y" then
self.IdealPos.y = value
self:SetPos(self.IdealPos)
elseif iname == "Z" then
self.IdealPos.z = value
self:SetPos(self.IdealPos)
elseif iname == "Position" then
if not isvector(value) then
if istable(value) and #value == 3 then
value = Vector(unpack(value))
else
return
end
end
self.IdealPos = value
self:SetPos(self.IdealPos)
elseif iname == "Pitch" then
self.IdealAng.p = value
elseif iname == "Yaw" then
self.IdealAng.y = value
elseif iname == "Roll" then
self.IdealAng.r = value
elseif iname == "Angle" then
self.IdealAng = value
elseif iname == "Direction" then
if not isvector(value) then
if istable(value) and #value == 3 then
value = Vector(unpack(value))
else
return
end
end
self.IdealAng = value:Angle()
elseif iname == "Velocity" then
self.IdealVel = value
self.phys:SetVelocity(self.IdealVel)
elseif iname == "Parent" then
if IsValid(value) then
self:SetParent(value)
else
self:SetParent(nil)
end
end
if self:GetAngles() ~= self.IdealAng then
local parent = self:GetParent()
self:SetParent(nil)
self:SetAngles(self.IdealAng)
self:SetParent(parent)
end
end
function ENT:OnRemove()
Wire_Remove(self)
end
function ENT:OnRestore()
Wire_Restored(self)
end
|
Fixes #90 (sometimes table[3]s were passed in instead of vectors)
|
Fixes #90 (sometimes table[3]s were passed in instead of vectors)
|
Lua
|
apache-2.0
|
Grocel/wire,wiremod/wire,thegrb93/wire,garrysmodlua/wire,mitterdoo/wire,NezzKryptic/Wire,dvdvideo1234/wire,bigdogmat/wire,mms92/wire,rafradek/wire,CaptainPRICE/wire,sammyt291/wire,notcake/wire,immibis/wiremod,Python1320/wire,plinkopenguin/wiremod
|
490b138f494d2472305f6c932c7886912ed02edb
|
tests/httpredirect.lua
|
tests/httpredirect.lua
|
-- test redirecting http <-> https combinations
local copas = require("copas")
local http = require("copas.http")
local ltn12 = require("ltn12")
local dump_all_headers = false
local redirect
local function doreq(url)
local reqt = {
url = url,
redirect = redirect, --> allows https-> http redirect
target = {},
}
reqt.sink = ltn12.sink.table(reqt.target)
local result, code, headers, status = http.request(reqt)
print(string.rep("=",70))
print("Fetching:",url,"==>",code, status)
if dump_all_headers then
if headers then
print("HEADERS")
for k,v in pairs(headers) do print("",k,v) end
end
else
print(" at:", (headers or {}).location)
end
--print(string.rep("=",70))
return result, code, headers, status
end
copas.addthread(function()
local result, code, headers, status = doreq("https://goo.gl/UBCUc5") -- https --> https redirect
assert(tonumber(code)==200)
assert(headers.location == "https://github.com/brunoos/luasec")
print("https -> https redirect OK!")
copas.addthread(function()
local result, code, headers, status = doreq("http://goo.gl/UBCUc5") -- http --> https redirect
assert(tonumber(code)==200)
assert(headers.location == "https://github.com/brunoos/luasec")
print("http -> https redirect OK!")
copas.addthread(function()
local result, code, headers, status = doreq("http://goo.gl/tBfqNu") -- http --> http redirect
assert(tonumber(code)==200)
assert(headers.location == "http://www.thijsschreijer.nl/blog/")
print("http -> http redirect OK!")
copas.addthread(function()
local result, code, headers, status = doreq("https://goo.gl/tBfqNu") -- https --> http security test case
assert(result==nil and code == "Unallowed insecure redirect https to http")
print("https -> http redirect, while not allowed OK!:", code)
copas.addthread(function()
redirect = "all"
local result, code, headers, status = doreq("https://goo.gl/tBfqNu") -- https --> http security test case
assert(tonumber(code)==200)
assert(headers.location == "http://www.thijsschreijer.nl/blog/")
print("https -> http redirect, while allowed OK!")
end)
end)
end)
end)
end)
copas.loop()
|
-- test redirecting http <-> https combinations
local copas = require("copas")
local http = require("copas.http")
local ltn12 = require("ltn12")
local dump_all_headers = false
local redirect
local function doreq(url)
local reqt = {
url = url,
redirect = redirect, --> allows https-> http redirect
target = {},
}
reqt.sink = ltn12.sink.table(reqt.target)
local result, code, headers, status = http.request(reqt)
print(string.rep("=",70))
print("Fetching:",url,"==>",code, status)
if dump_all_headers then
if headers then
print("HEADERS")
for k,v in pairs(headers) do print("",k,v) end
end
else
print(" at:", (headers or {}).location)
end
--print(string.rep("=",70))
return result, code, headers, status
end
local done = false
copas.addthread(function()
local result, code, headers, status = doreq("https://goo.gl/UBCUc5") -- https --> https redirect
assert(tonumber(code)==200)
assert(headers.location == "https://github.com/brunoos/luasec")
print("https -> https redirect OK!")
copas.addthread(function()
local result, code, headers, status = doreq("http://goo.gl/UBCUc5") -- http --> https redirect
assert(tonumber(code)==200)
assert(headers.location == "https://github.com/brunoos/luasec")
print("http -> https redirect OK!")
copas.addthread(function()
local result, code, headers, status = doreq("http://goo.gl/tBfqNu") -- http --> http redirect
assert(tonumber(code)==200)
assert(headers.location == "http://www.thijsschreijer.nl/blog/")
print("http -> http redirect OK!")
copas.addthread(function()
local result, code, headers, status = doreq("https://goo.gl/tBfqNu") -- https --> http security test case
assert(result==nil and code == "Unallowed insecure redirect https to http")
print("https -> http redirect, while not allowed OK!:", code)
copas.addthread(function()
redirect = "all"
local result, code, headers, status = doreq("https://goo.gl/tBfqNu") -- https --> http security test case
assert(tonumber(code)==200)
assert(headers.location == "http://www.thijsschreijer.nl/blog/")
print("https -> http redirect, while allowed OK!")
done = true
end)
end)
end)
end)
end)
copas.loop()
if not done then
print("Some checks above failed")
os.exit(1)
end
|
Fix httpredirect test to os.exit(1) on fail
|
Fix httpredirect test to os.exit(1) on fail
|
Lua
|
mit
|
keplerproject/copas
|
694ad08f9b78a50b34994b2240bd85df7a790c58
|
plugins/mod_saslauth.lua
|
plugins/mod_saslauth.lua
|
-- Prosody IM
-- Copyright (C) 2008-2009 Matthew Wild
-- Copyright (C) 2008-2009 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local st = require "util.stanza";
local sm_bind_resource = require "core.sessionmanager".bind_resource;
local sm_make_authenticated = require "core.sessionmanager".make_authenticated;
local base64 = require "util.encodings".base64;
local datamanager_load = require "util.datamanager".load;
local usermanager_validate_credentials = require "core.usermanager".validate_credentials;
local usermanager_get_supported_methods = require "core.usermanager".get_supported_methods;
local usermanager_user_exists = require "core.usermanager".user_exists;
local usermanager_get_password = require "core.usermanager".get_password;
local t_concat, t_insert = table.concat, table.insert;
local tostring = tostring;
local jid_split = require "util.jid".split
local md5 = require "util.hashes".md5;
local config = require "core.configmanager";
local secure_auth_only = config.get(module:get_host(), "core", "require_encryption");
local log = module._log;
local xmlns_sasl ='urn:ietf:params:xml:ns:xmpp-sasl';
local xmlns_bind ='urn:ietf:params:xml:ns:xmpp-bind';
local xmlns_stanzas ='urn:ietf:params:xml:ns:xmpp-stanzas';
local new_sasl = require "util.sasl".new;
local function build_reply(status, ret, err_msg)
local reply = st.stanza(status, {xmlns = xmlns_sasl});
if status == "challenge" then
log("debug", "%s", ret or "");
reply:text(base64.encode(ret or ""));
elseif status == "failure" then
reply:tag(ret):up();
if err_msg then reply:tag("text"):text(err_msg); end
elseif status == "success" then
log("debug", "%s", ret or "");
reply:text(base64.encode(ret or ""));
else
module:log("error", "Unknown sasl status: %s", status);
end
return reply;
end
local function handle_status(session, status)
if status == "failure" then
session.sasl_handler = nil;
elseif status == "success" then
if not session.sasl_handler.username then -- TODO move this to sessionmanager
module:log("warn", "SASL succeeded but we didn't get a username!");
session.sasl_handler = nil;
session:reset_stream();
return;
end
sm_make_authenticated(session, session.sasl_handler.username);
session.sasl_handler = nil;
session:reset_stream();
end
end
local function credentials_callback(mechanism, ...)
if mechanism == "PLAIN" then
local username, hostname, password = arg[1], arg[2], arg[3];
local response = usermanager_validate_credentials(hostname, username, password, mechanism)
if response == nil then return false
else return response end
elseif mechanism == "DIGEST-MD5" then
function func(x) return x; end
local node, domain, realm, decoder = arg[1], arg[2], arg[3], arg[4];
local password = usermanager_get_password(node, domain)
if password then
if decoder then node, realm, password = decoder(node), decoder(realm), decoder(password); end
return func, md5(node..":"..realm..":"..password);
else
return func, nil;
end
end
end
local function sasl_handler(session, stanza)
if stanza.name == "auth" then
-- FIXME ignoring duplicates because ejabberd does
if config.get(session.host or "*", "core", "anonymous_login") then
if stanza.attr.mechanism ~= "ANONYMOUS" then
return session.send(build_reply("failure", "invalid-mechanism"));
end
elseif stanza.attr.mechanism == "ANONYMOUS" then
return session.send(build_reply("failure", "mechanism-too-weak"));
end
session.sasl_handler = new_sasl(stanza.attr.mechanism, session.host, credentials_callback);
if not session.sasl_handler then
return session.send(build_reply("failure", "invalid-mechanism"));
end
elseif not session.sasl_handler then
return; -- FIXME ignoring out of order stanzas because ejabberd does
end
local text = stanza[1];
if text then
text = base64.decode(text);
log("debug", "%s", text);
if not text then
session.sasl_handler = nil;
session.send(build_reply("failure", "incorrect-encoding"));
return;
end
end
local status, ret, err_msg = session.sasl_handler:feed(text);
handle_status(session, status);
local s = build_reply(status, ret, err_msg);
log("debug", "sasl reply: %s", tostring(s));
session.send(s);
end
module:add_handler("c2s_unauthed", "auth", xmlns_sasl, sasl_handler);
module:add_handler("c2s_unauthed", "abort", xmlns_sasl, sasl_handler);
module:add_handler("c2s_unauthed", "response", xmlns_sasl, sasl_handler);
local mechanisms_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-sasl' };
local bind_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-bind' };
local xmpp_session_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-session' };
module:add_event_hook("stream-features",
function (session, features)
if not session.username then
if secure_auth_only and not session.secure then
return;
end
features:tag("mechanisms", mechanisms_attr);
-- TODO: Provide PLAIN only if TLS is active, this is a SHOULD from the introduction of RFC 4616. This behavior could be overridden via configuration but will issuing a warning or so.
if config.get(session.host or "*", "core", "anonymous_login") then
features:tag("mechanism"):text("ANONYMOUS"):up();
else
mechanisms = usermanager_get_supported_methods(session.host or "*");
for k, v in pairs(mechanisms) do
features:tag("mechanism"):text(k):up();
end
end
features:up();
else
features:tag("bind", bind_attr):tag("required"):up():up();
features:tag("session", xmpp_session_attr):up();
end
end);
module:add_iq_handler("c2s", "urn:ietf:params:xml:ns:xmpp-bind",
function (session, stanza)
log("debug", "Client requesting a resource bind");
local resource;
if stanza.attr.type == "set" then
local bind = stanza.tags[1];
if bind and bind.attr.xmlns == xmlns_bind then
resource = bind:child_with_name("resource");
if resource then
resource = resource[1];
end
end
end
local success, err_type, err, err_msg = sm_bind_resource(session, resource);
if not success then
session.send(st.error_reply(stanza, err_type, err, err_msg));
else
session.send(st.reply(stanza)
:tag("bind", { xmlns = xmlns_bind})
:tag("jid"):text(session.full_jid));
end
end);
module:add_iq_handler("c2s", "urn:ietf:params:xml:ns:xmpp-session",
function (session, stanza)
log("debug", "Client requesting a session");
session.send(st.reply(stanza));
end);
|
-- Prosody IM
-- Copyright (C) 2008-2009 Matthew Wild
-- Copyright (C) 2008-2009 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local st = require "util.stanza";
local sm_bind_resource = require "core.sessionmanager".bind_resource;
local sm_make_authenticated = require "core.sessionmanager".make_authenticated;
local base64 = require "util.encodings".base64;
local datamanager_load = require "util.datamanager".load;
local usermanager_validate_credentials = require "core.usermanager".validate_credentials;
local usermanager_get_supported_methods = require "core.usermanager".get_supported_methods;
local usermanager_user_exists = require "core.usermanager".user_exists;
local usermanager_get_password = require "core.usermanager".get_password;
local t_concat, t_insert = table.concat, table.insert;
local tostring = tostring;
local jid_split = require "util.jid".split
local md5 = require "util.hashes".md5;
local config = require "core.configmanager";
local secure_auth_only = config.get(module:get_host(), "core", "require_encryption");
local log = module._log;
local xmlns_sasl ='urn:ietf:params:xml:ns:xmpp-sasl';
local xmlns_bind ='urn:ietf:params:xml:ns:xmpp-bind';
local xmlns_stanzas ='urn:ietf:params:xml:ns:xmpp-stanzas';
local new_sasl = require "util.sasl".new;
local function build_reply(status, ret, err_msg)
local reply = st.stanza(status, {xmlns = xmlns_sasl});
if status == "challenge" then
log("debug", "%s", ret or "");
reply:text(base64.encode(ret or ""));
elseif status == "failure" then
reply:tag(ret):up();
if err_msg then reply:tag("text"):text(err_msg); end
elseif status == "success" then
log("debug", "%s", ret or "");
reply:text(base64.encode(ret or ""));
else
module:log("error", "Unknown sasl status: %s", status);
end
return reply;
end
local function handle_status(session, status)
if status == "failure" then
session.sasl_handler = nil;
elseif status == "success" then
if not session.sasl_handler.username then -- TODO move this to sessionmanager
module:log("warn", "SASL succeeded but we didn't get a username!");
session.sasl_handler = nil;
session:reset_stream();
return;
end
sm_make_authenticated(session, session.sasl_handler.username);
session.sasl_handler = nil;
session:reset_stream();
end
end
local function credentials_callback(mechanism, ...)
if mechanism == "PLAIN" then
local username, hostname, password = ...;
local response = usermanager_validate_credentials(hostname, username, password, mechanism);
if response == nil then
return false;
else
return response;
end
elseif mechanism == "DIGEST-MD5" then
function func(x) return x; end
local node, domain, realm, decoder = ...;
local password = usermanager_get_password(node, domain);
if password then
if decoder then
node, realm, password = decoder(node), decoder(realm), decoder(password);
end
return func, md5(node..":"..realm..":"..password);
else
return func, nil;
end
end
end
local function sasl_handler(session, stanza)
if stanza.name == "auth" then
-- FIXME ignoring duplicates because ejabberd does
if config.get(session.host or "*", "core", "anonymous_login") then
if stanza.attr.mechanism ~= "ANONYMOUS" then
return session.send(build_reply("failure", "invalid-mechanism"));
end
elseif stanza.attr.mechanism == "ANONYMOUS" then
return session.send(build_reply("failure", "mechanism-too-weak"));
end
session.sasl_handler = new_sasl(stanza.attr.mechanism, session.host, credentials_callback);
if not session.sasl_handler then
return session.send(build_reply("failure", "invalid-mechanism"));
end
elseif not session.sasl_handler then
return; -- FIXME ignoring out of order stanzas because ejabberd does
end
local text = stanza[1];
if text then
text = base64.decode(text);
log("debug", "%s", text);
if not text then
session.sasl_handler = nil;
session.send(build_reply("failure", "incorrect-encoding"));
return;
end
end
local status, ret, err_msg = session.sasl_handler:feed(text);
handle_status(session, status);
local s = build_reply(status, ret, err_msg);
log("debug", "sasl reply: %s", tostring(s));
session.send(s);
end
module:add_handler("c2s_unauthed", "auth", xmlns_sasl, sasl_handler);
module:add_handler("c2s_unauthed", "abort", xmlns_sasl, sasl_handler);
module:add_handler("c2s_unauthed", "response", xmlns_sasl, sasl_handler);
local mechanisms_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-sasl' };
local bind_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-bind' };
local xmpp_session_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-session' };
module:add_event_hook("stream-features",
function (session, features)
if not session.username then
if secure_auth_only and not session.secure then
return;
end
features:tag("mechanisms", mechanisms_attr);
-- TODO: Provide PLAIN only if TLS is active, this is a SHOULD from the introduction of RFC 4616. This behavior could be overridden via configuration but will issuing a warning or so.
if config.get(session.host or "*", "core", "anonymous_login") then
features:tag("mechanism"):text("ANONYMOUS"):up();
else
mechanisms = usermanager_get_supported_methods(session.host or "*");
for k, v in pairs(mechanisms) do
features:tag("mechanism"):text(k):up();
end
end
features:up();
else
features:tag("bind", bind_attr):tag("required"):up():up();
features:tag("session", xmpp_session_attr):up();
end
end);
module:add_iq_handler("c2s", "urn:ietf:params:xml:ns:xmpp-bind",
function (session, stanza)
log("debug", "Client requesting a resource bind");
local resource;
if stanza.attr.type == "set" then
local bind = stanza.tags[1];
if bind and bind.attr.xmlns == xmlns_bind then
resource = bind:child_with_name("resource");
if resource then
resource = resource[1];
end
end
end
local success, err_type, err, err_msg = sm_bind_resource(session, resource);
if not success then
session.send(st.error_reply(stanza, err_type, err, err_msg));
else
session.send(st.reply(stanza)
:tag("bind", { xmlns = xmlns_bind})
:tag("jid"):text(session.full_jid));
end
end);
module:add_iq_handler("c2s", "urn:ietf:params:xml:ns:xmpp-session",
function (session, stanza)
log("debug", "Client requesting a session");
session.send(st.reply(stanza));
end);
|
mod_saslauth: Fix coding style and layout, and use of arg[] for vararg
|
mod_saslauth: Fix coding style and layout, and use of arg[] for vararg
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
5e16070ed6d9fed34ecb5f7a59ee5072f77f9a10
|
lua/lush_theme/jellybeans.lua
|
lua/lush_theme/jellybeans.lua
|
local lush = require('lush')
local hsl = lush.hsl
local jellybeans = require('lush_theme.jellybeans-nvim')
local nice_red = "#ff5656" -- A nicer red, also from https://git.io/Jfs2T
local mantis = "#70b950" -- From Jellybeans
local koromiko = "#ffb964" -- From Jellybeans
local spec = lush.extends({jellybeans}).with(function(injected_functions)
local sym = injected_functions.sym
return {
-- Darker background for entire window
Normal { fg = "#e8e8d3", bg = "#090909", },
-- Better colors for popup menus
Pmenu { bg = "#202020", fg = "#D6D6D6" },
CocMenuSel { bg = "#D6D6D6", fg = "#2B2B2B" },
-- Better colors for JSX tag attributes
sym("@tag.attribute.tsx") { fg = koromiko },
-- Better error color
CocErrorSign { fg = nice_red },
-- Git Signs
GitSignsAdd { fg = mantis },
GitSignsChange { fg = "#8fbfdc" },
GitSignsDelete { fg = nice_red },
-- Specs
Specs { bg = mantis, fg = "#000000" },
}
end)
return spec
|
local lush = require('lush')
local hsl = lush.hsl
local jellybeans = require('lush_theme.jellybeans-nvim')
local nice_red = "#ff5656" -- A nicer red, also from https://git.io/Jfs2T
local mantis = "#70b950" -- From Jellybeans
local koromiko = "#ffb964" -- From Jellybeans
local wewak = "#f0a0c0"
local morning_glory = "#8fbfdc"
local bayoux_blue = "#556779"
-- List of Treesitter symbols:
-- https://github.com/nvim-treesitter/nvim-treesitter/blob/master/CONTRIBUTING.md
local spec = lush.extends({jellybeans}).with(function(injected_functions)
local sym = injected_functions.sym
return {
-- Darker background for entire window
Normal { fg = "#e8e8d3", bg = "#090909", },
-- Better colors for popup menus
Pmenu { bg = "#202020", fg = "#D6D6D6" },
CocMenuSel { bg = "#D6D6D6", fg = "#2B2B2B" },
-- Fixes due to Jellybeans being out of date with latest Treesitter symbol
-- syntax
sym("@variable") { Normal },
sym("@namespace") { Normal },
sym("@tag.delimiter") { fg = bayoux_blue },
sym("@text.emphasis") { gui = "italic" },
sym("@text.underline") { gui = "underline" },
sym("@text.strike") { gui="strikethrough" },
sym("@text.uri") { fg = morning_glory },
-- My additions
-- Make JSX attributes easier to distinguish
sym("@tag.attribute.tsx") { fg = koromiko },
-- This used to be this color before an update, not sure why it changed
sym("@variable.builtin") { fg = "#7bc3a9" },
-- Better error color
CocErrorSign { fg = nice_red },
-- Git Signs
GitSignsAdd { fg = mantis },
GitSignsChange { fg = "#8fbfdc" },
GitSignsDelete { fg = nice_red },
-- Specs
Specs { bg = mantis, fg = "#000000" },
}
end)
return spec
|
fix: update many more colors for new treesitter syntax
|
fix: update many more colors for new treesitter syntax
|
Lua
|
mit
|
mutewinter/dot_vim,mutewinter/dot_vim
|
8a8e7c4e7c02157b23039670da4535eefb98ffa9
|
modules/admin-full/luasrc/model/cbi/admin_network/network.lua
|
modules/admin-full/luasrc/model/cbi/admin_network/network.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2008 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local fs = require "nixio.fs"
m = Map("network", translate("Interfaces"))
m:section(SimpleSection).template = "admin_network/iface_overview"
-- Show ATM bridge section if we have the capabilities
if fs.access("/usr/sbin/br2684ctl") then
atm = m:section(TypedSection, "atm-bridge", translate("ATM Bridges"),
translate("ATM bridges expose encapsulated ethernet in AAL5 " ..
"connections as virtual Linux network interfaces which can " ..
"be used in conjunction with DHCP or PPP to dial into the " ..
"provider network."))
atm.addremove = true
atm.anonymous = true
atm.create = function(self, section)
local sid = TypedSection.create(self, section)
local max_unit = -1
m.uci:foreach("network", "atm-bridge",
function(s)
local u = tonumber(s.unit)
if u ~= nil and u > max_unit then
max_unit = u
end
end)
m.uci:set("network", sid, "unit", max_unit + 1)
m.uci:set("network", sid, "atmdev", 0)
m.uci:set("network", sid, "encaps", "llc")
m.uci:set("network", sid, "payload", "bridged")
m.uci:set("network", sid, "vci", 35)
m.uci:set("network", sid, "vpi", 8)
return sid
end
atm:tab("general", translate("General Setup"))
atm:tab("advanced", translate("Advanced Settings"))
vci = atm:taboption("general", Value, "vci", translate("ATM Virtual Channel Identifier (VCI)"))
vpi = atm:taboption("general", Value, "vpi", translate("ATM Virtual Path Identifier (VPI)"))
encaps = atm:taboption("general", ListValue, "encaps", translate("Encapsulation mode"))
encaps:value("llc", translate("LLC"))
encaps:value("vc", translate("VC-Mux"))
atmdev = atm:taboption("advanced", Value, "atmdev", translate("ATM device number"))
unit = atm:taboption("advanced", Value, "unit", translate("Bridge unit number"))
payload = atm:taboption("advanced", ListValue, "payload", translate("Forwarding mode"))
payload:value("bridged", translate("bridged"))
payload:value("routed", translate("routed"))
else
m.pageaction = false
end
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2008 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local fs = require "nixio.fs"
m = Map("network", translate("Interfaces"))
m.pageaction = false
m:section(SimpleSection).template = "admin_network/iface_overview"
-- Show ATM bridge section if we have the capabilities
if fs.access("/usr/sbin/br2684ctl") then
atm = m:section(TypedSection, "atm-bridge", translate("ATM Bridges"),
translate("ATM bridges expose encapsulated ethernet in AAL5 " ..
"connections as virtual Linux network interfaces which can " ..
"be used in conjunction with DHCP or PPP to dial into the " ..
"provider network."))
atm.addremove = true
atm.anonymous = true
atm.create = function(self, section)
local sid = TypedSection.create(self, section)
local max_unit = -1
m.uci:foreach("network", "atm-bridge",
function(s)
local u = tonumber(s.unit)
if u ~= nil and u > max_unit then
max_unit = u
end
end)
m.uci:set("network", sid, "unit", max_unit + 1)
m.uci:set("network", sid, "atmdev", 0)
m.uci:set("network", sid, "encaps", "llc")
m.uci:set("network", sid, "payload", "bridged")
m.uci:set("network", sid, "vci", 35)
m.uci:set("network", sid, "vpi", 8)
return sid
end
atm:tab("general", translate("General Setup"))
atm:tab("advanced", translate("Advanced Settings"))
vci = atm:taboption("general", Value, "vci", translate("ATM Virtual Channel Identifier (VCI)"))
vpi = atm:taboption("general", Value, "vpi", translate("ATM Virtual Path Identifier (VPI)"))
encaps = atm:taboption("general", ListValue, "encaps", translate("Encapsulation mode"))
encaps:value("llc", translate("LLC"))
encaps:value("vc", translate("VC-Mux"))
atmdev = atm:taboption("advanced", Value, "atmdev", translate("ATM device number"))
unit = atm:taboption("advanced", Value, "unit", translate("Bridge unit number"))
payload = atm:taboption("advanced", ListValue, "payload", translate("Forwarding mode"))
payload:value("bridged", translate("bridged"))
payload:value("routed", translate("routed"))
m.pageaction = true
end
local network = require "luci.model.network"
if network:has_ipv6() then
local s = m:section(NamedSection, "globals", "globals", translate("Global network options"))
local o = s:option(Value, "ula_prefix", translate("IPv6 ULA-Prefix"))
o.datatype = "ip6addr"
o.rmempty = true
m.pageaction = true
end
return m
|
Add support for changing ULA prefix
|
Add support for changing ULA prefix
git-svn-id: b12fe9853c2c9793030bd743626f1e993aa2455c@9849 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
freifunk-gluon/luci,freifunk-gluon/luci,freifunk-gluon/luci,freifunk-gluon/luci,freifunk-gluon/luci,freifunk-gluon/luci,freifunk-gluon/luci,freifunk-gluon/luci
|
0bc87fe20e82fb986ab68a0c28c3d6c43ad3ea9b
|
xmake/modules/devel/debugger/run.lua
|
xmake/modules/devel/debugger/run.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-2020, TBOOX Open Source Group.
--
-- @author ruki
-- @file run.lua
--
-- imports
import("core.base.option")
import("core.project.config")
import("detect.tools.find_cudagdb")
import("detect.tools.find_cudamemcheck")
import("detect.tools.find_gdb")
import("detect.tools.find_lldb")
import("detect.tools.find_windbg")
import("detect.tools.find_x64dbg")
import("detect.tools.find_ollydbg")
import("detect.tools.find_devenv")
import("detect.tools.find_vsjitdebugger")
-- run gdb
function _run_gdb(program, argv)
-- find gdb
local gdb = find_gdb({program = config.get("debugger")})
if not gdb then
return false
end
-- patch arguments
argv = argv or {}
table.insert(argv, 1, program)
table.insert(argv, 1, "--args")
-- run it
os.execv(gdb, argv)
-- ok
return true
end
-- run cuda-gdb
function _run_cudagdb(program, argv)
-- find cudagdb
local gdb = find_cudagdb({program = config.get("debugger")})
if not gdb then
return false
end
-- patch arguments
argv = argv or {}
table.insert(argv, 1, program)
table.insert(argv, 1, "--args")
-- run it
os.execv(gdb, argv)
-- ok
return true
end
-- run lldb
function _run_lldb(program, argv)
-- find lldb
local lldb = find_lldb({program = config.get("debugger")})
if not lldb then
return false
end
-- attempt to split name, e.g. xcrun -sdk macosx lldb
local names = lldb:split("%s")
-- patch arguments
argv = argv or {}
table.insert(argv, 1, program)
for i = #names, 2, -1 do
table.insert(argv, 1, names[i])
end
-- run it
os.execv(names[1], argv)
-- ok
return true
end
-- run windbg
function _run_windbg(program, argv)
-- find windbg
local windbg = find_windbg({program = config.get("debugger")})
if not windbg then
return false
end
-- patch arguments
argv = argv or {}
table.insert(argv, 1, program)
-- run it
os.execv(windbg, argv)
-- ok
return true
end
-- run cuda-memcheck
function _run_cudamemcheck(program, argv)
-- find cudamemcheck
local cudamemcheck = find_cudamemcheck({program = config.get("debugger")})
if not cudamemcheck then
return false
end
-- patch arguments
argv = argv or {}
table.insert(argv, 1, program)
-- run it
os.execv(cudamemcheck, argv)
-- ok
return true
end
-- run x64dbg
function _run_x64dbg(program, argv)
-- find x64dbg
local x64dbg = find_x64dbg({program = config.get("debugger")})
if not x64dbg then
return false
end
-- patch arguments
argv = argv or {}
table.insert(argv, 1, program)
-- run it
os.execv(x64dbg, argv)
-- ok
return true
end
-- run ollydbg
function _run_ollydbg(program, argv)
-- find ollydbg
local ollydbg = find_ollydbg({program = config.get("debugger")})
if not ollydbg then
return false
end
-- patch arguments
argv = argv or {}
table.insert(argv, 1, program)
-- run it
os.execv(ollydbg, argv)
-- ok
return true
end
-- run vsjitdebugger
function _run_vsjitdebugger(program, argv)
-- find vsjitdebugger
local vsjitdebugger = find_vsjitdebugger({program = config.get("debugger")})
if not vsjitdebugger then
return false
end
-- patch arguments
argv = argv or {}
table.insert(argv, 1, program)
-- run it
os.execv(vsjitdebugger, argv)
-- ok
return true
end
-- run devenv
function _run_devenv(program, argv)
-- find devenv
local devenv = find_devenv({program = config.get("debugger")})
if not devenv then
return false
end
-- patch arguments
argv = argv or {}
table.insert(argv, 1, "/DebugExe")
table.insert(argv, 2, program)
-- run it
os.execv(devenv, argv)
-- ok
return true
end
-- run program with debugger
--
-- @param program the program name
-- @param argv the program rguments
--
-- @code
--
-- import("devel.debugger")
--
-- debugger.run("test")
-- debugger.run("echo", {"hello xmake!"})
--
-- @endcode
--
function main(program, argv)
-- init debuggers
local debuggers =
{
{"lldb" , _run_lldb}
, {"gdb" , _run_gdb}
, {"cudagdb" , _run_cudagdb}
, {"cudamemcheck", _run_cudamemcheck}
}
-- for windows target or on windows?
if (config.plat() or os.host()) == "windows" then
table.insert(debuggers, 1, {"windbg", _run_windbg})
table.insert(debuggers, 1, {"ollydbg", _run_ollydbg})
table.insert(debuggers, 1, {"x64dbg", _run_x64dbg})
table.insert(debuggers, 1, {"vsjitdebugger", _run_vsjitdebugger})
table.insert(debuggers, 1, {"devenv", _run_devenv})
end
-- get debugger from the configure
local debugger = config.get("debugger")
if debugger then
-- try exactmatch first
debugger = debugger:lower()
local debuggername = path.basename(debugger)
for _, _debugger in ipairs(debuggers) do
if debuggername:startswith(_debugger[1]) then
if _debugger[2](program, argv) then
return
end
end
end
for _, _debugger in ipairs(debuggers) do
if debugger:find(_debugger[1]) then
if _debugger[2](program, argv) then
return
end
end
end
else
-- run debugger
for _, _debugger in ipairs(debuggers) do
if _debugger[2](program, argv) then
return
end
end
end
-- no debugger
raise("debugger%s not found!", debugger and ("(" .. debugger .. ")") or "")
end
|
--!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-2020, TBOOX Open Source Group.
--
-- @author ruki
-- @file run.lua
--
-- imports
import("core.base.option")
import("core.project.config")
import("detect.tools.find_cudagdb")
import("detect.tools.find_cudamemcheck")
import("detect.tools.find_gdb")
import("detect.tools.find_lldb")
import("detect.tools.find_windbg")
import("detect.tools.find_x64dbg")
import("detect.tools.find_ollydbg")
import("detect.tools.find_devenv")
import("detect.tools.find_vsjitdebugger")
-- run gdb
function _run_gdb(program, argv)
-- find gdb
local gdb = find_gdb({program = config.get("debugger")})
if not gdb then
return false
end
-- patch arguments
argv = argv or {}
table.insert(argv, 1, program)
table.insert(argv, 1, "--args")
-- run it
os.execv(gdb, argv)
-- ok
return true
end
-- run cuda-gdb
function _run_cudagdb(program, argv)
-- find cudagdb
local gdb = find_cudagdb({program = config.get("debugger")})
if not gdb then
return false
end
-- patch arguments
argv = argv or {}
table.insert(argv, 1, program)
table.insert(argv, 1, "--args")
-- run it
os.execv(gdb, argv)
-- ok
return true
end
-- run lldb
function _run_lldb(program, argv)
-- find lldb
local lldb = find_lldb({program = config.get("debugger")})
if not lldb then
return false
end
-- attempt to split name, e.g. xcrun -sdk macosx lldb
local names = lldb:split("%s")
-- patch arguments
argv = argv or {}
table.insert(argv, 1, program)
table.insert(argv, 1, "-f")
for i = #names, 2, -1 do
table.insert(argv, 1, names[i])
end
-- run it
os.execv(names[1], argv)
-- ok
return true
end
-- run windbg
function _run_windbg(program, argv)
-- find windbg
local windbg = find_windbg({program = config.get("debugger")})
if not windbg then
return false
end
-- patch arguments
argv = argv or {}
table.insert(argv, 1, program)
-- run it
os.execv(windbg, argv)
-- ok
return true
end
-- run cuda-memcheck
function _run_cudamemcheck(program, argv)
-- find cudamemcheck
local cudamemcheck = find_cudamemcheck({program = config.get("debugger")})
if not cudamemcheck then
return false
end
-- patch arguments
argv = argv or {}
table.insert(argv, 1, program)
-- run it
os.execv(cudamemcheck, argv)
-- ok
return true
end
-- run x64dbg
function _run_x64dbg(program, argv)
-- find x64dbg
local x64dbg = find_x64dbg({program = config.get("debugger")})
if not x64dbg then
return false
end
-- patch arguments
argv = argv or {}
table.insert(argv, 1, program)
-- run it
os.execv(x64dbg, argv)
-- ok
return true
end
-- run ollydbg
function _run_ollydbg(program, argv)
-- find ollydbg
local ollydbg = find_ollydbg({program = config.get("debugger")})
if not ollydbg then
return false
end
-- patch arguments
argv = argv or {}
table.insert(argv, 1, program)
-- run it
os.execv(ollydbg, argv)
-- ok
return true
end
-- run vsjitdebugger
function _run_vsjitdebugger(program, argv)
-- find vsjitdebugger
local vsjitdebugger = find_vsjitdebugger({program = config.get("debugger")})
if not vsjitdebugger then
return false
end
-- patch arguments
argv = argv or {}
table.insert(argv, 1, program)
-- run it
os.execv(vsjitdebugger, argv)
-- ok
return true
end
-- run devenv
function _run_devenv(program, argv)
-- find devenv
local devenv = find_devenv({program = config.get("debugger")})
if not devenv then
return false
end
-- patch arguments
argv = argv or {}
table.insert(argv, 1, "/DebugExe")
table.insert(argv, 2, program)
-- run it
os.execv(devenv, argv)
-- ok
return true
end
-- run program with debugger
--
-- @param program the program name
-- @param argv the program rguments
--
-- @code
--
-- import("devel.debugger")
--
-- debugger.run("test")
-- debugger.run("echo", {"hello xmake!"})
--
-- @endcode
--
function main(program, argv)
-- init debuggers
local debuggers =
{
{"lldb" , _run_lldb}
, {"gdb" , _run_gdb}
, {"cudagdb" , _run_cudagdb}
, {"cudamemcheck", _run_cudamemcheck}
}
-- for windows target or on windows?
if (config.plat() or os.host()) == "windows" then
table.insert(debuggers, 1, {"windbg", _run_windbg})
table.insert(debuggers, 1, {"ollydbg", _run_ollydbg})
table.insert(debuggers, 1, {"x64dbg", _run_x64dbg})
table.insert(debuggers, 1, {"vsjitdebugger", _run_vsjitdebugger})
table.insert(debuggers, 1, {"devenv", _run_devenv})
end
-- get debugger from the configure
local debugger = config.get("debugger")
if debugger then
-- try exactmatch first
debugger = debugger:lower()
local debuggername = path.basename(debugger)
for _, _debugger in ipairs(debuggers) do
if debuggername:startswith(_debugger[1]) then
if _debugger[2](program, argv) then
return
end
end
end
for _, _debugger in ipairs(debuggers) do
if debugger:find(_debugger[1]) then
if _debugger[2](program, argv) then
return
end
end
end
else
-- run debugger
for _, _debugger in ipairs(debuggers) do
if _debugger[2](program, argv) then
return
end
end
end
-- no debugger
raise("debugger%s not found!", debugger and ("(" .. debugger .. ")") or "")
end
|
fix load program with args for lldb
|
fix load program with args for lldb
|
Lua
|
apache-2.0
|
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
|
fb7fdc5be200406aa30106401b71cb88129dbe40
|
.config/nvim/lua/config/telescope.lua
|
.config/nvim/lua/config/telescope.lua
|
local status_ok, p = pcall(require, "telescope")
if not status_ok then
return
end
local actions = require("telescope.actions")
p.setup({
defaults = {
sorting_strategy = "ascending",
vimgrep_arguments = {
"rg",
"--color=never",
"--no-heading",
"--with-filename",
"--line-number",
"--column",
"--smart-case",
"--hidden",
},
mappings = {
i = {
["<C-c>"] = { "<Esc>", type = "command" },
["<C-c><C-c>"] = actions.close,
},
n = {
["<C-n>"] = actions.move_selection_next,
["<C-p>"] = actions.move_selection_previous,
["<C-f>"] = actions.results_scrolling_up,
["<C-b>"] = actions.results_scrolling_down,
["q"] = actions.close,
["<C-c>"] = actions.close,
["y"] = function()
local selection = require("telescope.actions.state").get_selected_entry()
local path = vim.fn.fnamemodify(selection.path, ":p:t")
vim.fn.setreg("+", path)
vim.fn.setreg('"', path)
print("Copied: " .. path)
end,
["Y"] = function()
local selection = require("telescope.actions.state").get_selected_entry()
local path = vim.fn.fnamemodify(selection.path, ":.")
vim.fn.setreg("+", path)
vim.fn.setreg('"', path)
print("Copied: " .. path)
end,
["gy"] = function()
local selection = require("telescope.actions.state").get_selected_entry()
local path = selection.path
vim.fn.setreg("+", path)
vim.fn.setreg('"', path)
print("Copied: " .. path)
end,
},
},
},
extensions = {
coc = {
prefer_locations = true, -- always use Telescope locations to preview definitions/declarations/implementations etc
},
},
})
p.load_extension("coc")
local opts = { noremap = true, silent = true }
vim.api.nvim_set_keymap(
"n",
"<Leader><Leader>",
"<Cmd>lua require('telescope.builtin').buffers({ sort_mru = true, ignore_current_buffer = true })<CR>",
opts
)
vim.api.nvim_set_keymap(
"n",
"<Leader>f",
"<Cmd>lua require('telescope.builtin').git_files({ hidden = true, cwd='$PWD' })<CR>",
opts
)
vim.api.nvim_set_keymap(
"n",
"<Leader>F",
"<Cmd>lua require('telescope.builtin').find_files({ hidden = true, no_ignore = true, cwd='$PWD' })<CR>",
opts
)
vim.api.nvim_set_keymap("n", "<Leader>g", "<Cmd>lua require('telescope.builtin').live_grep({ cwd='$PWD' })<CR>", opts)
vim.api.nvim_set_keymap("n", "<Leader>G", "<Cmd>lua require('telescope.builtin').grep_string({ cwd='$PWD' })<CR>", opts)
vim.api.nvim_set_keymap("n", "<Leader>r", "<Cmd>Telescope resume<CR>", opts)
vim.api.nvim_set_keymap(
"n",
",g",
"<Cmd>lua require('telescope.builtin').live_grep({ cwd='$SCRAPBOOK_DIR' })<CR>",
opts
)
vim.api.nvim_set_keymap(
"n",
",G",
"<Cmd>lua require('telescope.builtin').grep_string({ cwd='$SCRAPBOOK_DIR' })<CR>",
opts
)
vim.api.nvim_set_keymap(
"n",
",f",
"<Cmd>lua require('telescope.builtin').find_files({ cwd='$SCRAPBOOK_DIR' })<CR>",
opts
)
vim.api.nvim_set_keymap(
"n",
",F",
"<Cmd>lua require('telescope.builtin').find_files({ hidden = true, no_ignore = true, cwd='$SCRAPBOOK_DIR' })<CR>",
opts
)
-- telescope-coc config
vim.api.nvim_set_keymap("n", "gd", "<Cmd>Telescope coc definitions<CR>", opts)
vim.api.nvim_set_keymap("n", "gD", "<Cmd>Telescope coc declarations<CR>", opts)
vim.api.nvim_set_keymap("n", "<Leader>d", "<Cmd>Telescope coc type_definitions<CR>", opts)
vim.api.nvim_set_keymap("n", "gi", "<Cmd>Telescope coc implementations<CR>", opts)
vim.api.nvim_set_keymap("n", "gr", "<Cmd>Telescope coc references<CR>", opts)
|
local status_ok, p = pcall(require, "telescope")
if not status_ok then
return
end
local actions = require("telescope.actions")
p.setup({
defaults = {
sorting_strategy = "ascending",
vimgrep_arguments = {
"rg",
"--color=never",
"--no-heading",
"--with-filename",
"--line-number",
"--column",
"--smart-case",
"--hidden",
},
mappings = {
i = {
["<C-c>"] = { "<Esc>", type = "command" },
["<C-c><C-c>"] = actions.close,
},
n = {
["<C-n>"] = actions.move_selection_next,
["<C-p>"] = actions.move_selection_previous,
["<C-f>"] = actions.results_scrolling_up,
["<C-b>"] = actions.results_scrolling_down,
["q"] = actions.close,
["<C-c>"] = actions.close,
["y"] = function()
local selection = require("telescope.actions.state").get_selected_entry()
local path = vim.fn.fnamemodify(selection.path, ":p:t")
vim.fn.setreg("+", path)
vim.fn.setreg('"', path)
print("Copied: " .. path)
end,
["Y"] = function()
local selection = require("telescope.actions.state").get_selected_entry()
local path = vim.fn.fnamemodify(selection.path, ":.")
vim.fn.setreg("+", path)
vim.fn.setreg('"', path)
print("Copied: " .. path)
end,
["gy"] = function()
local selection = require("telescope.actions.state").get_selected_entry()
local path = selection.path
vim.fn.setreg("+", path)
vim.fn.setreg('"', path)
print("Copied: " .. path)
end,
},
},
},
extensions = {
coc = {
prefer_locations = true, -- always use Telescope locations to preview definitions/declarations/implementations etc
},
},
})
p.load_extension("coc")
local opts = { noremap = true, silent = true }
local keymap = vim.api.nvim_set_keymap
keymap(
"n",
"<Leader><Leader>",
"<Cmd>lua require('telescope.builtin').buffers({ sort_mru = true, ignore_current_buffer = true })<CR>",
opts
)
keymap("n", "<Leader>f", "<Cmd>lua require('telescope.builtin').git_files({ hidden = true, cwd='$PWD' })<CR>", opts)
keymap(
"n",
"<Leader>F",
"<Cmd>lua require('telescope.builtin').find_files({ hidden = true, no_ignore = true, cwd='$PWD' })<CR>",
opts
)
keymap("n", "<Leader>g", "<Cmd>lua require('telescope.builtin').live_grep({ cwd='$PWD' })<CR>", opts)
keymap("n", "<Leader>G", "<Cmd>lua require('telescope.builtin').grep_string({ cwd='$PWD' })<CR>", opts)
keymap("n", "<Leader>r", "<Cmd>Telescope resume<CR>", opts)
keymap("n", ",g", "<Cmd>lua require('telescope.builtin').live_grep({ cwd='$SCRAPBOOK_DIR' })<CR>", opts)
keymap("n", ",G", "<Cmd>lua require('telescope.builtin').grep_string({ cwd='$SCRAPBOOK_DIR' })<CR>", opts)
keymap("n", ",f", "<Cmd>lua require('telescope.builtin').find_files({ cwd='$SCRAPBOOK_DIR' })<CR>", opts)
keymap(
"n",
",F",
"<Cmd>lua require('telescope.builtin').find_files({ hidden = true, no_ignore = true, cwd='$SCRAPBOOK_DIR' })<CR>",
opts
)
-- telescope-coc config
keymap("n", "gd", "<Cmd>Telescope coc definitions<CR>", opts)
keymap("n", "gD", "<Cmd>Telescope coc declarations<CR>", opts)
keymap("n", "<Leader>d", "<Cmd>Telescope coc type_definitions<CR>", opts)
keymap("n", "gi", "<Cmd>Telescope coc implementations<CR>", opts)
keymap("n", "gr", "<Cmd>Telescope coc references<CR>", opts)
-- Commands
keymap("n", "<Leader>;", "<Cmd>Telescope commands<CR>", opts)
keymap("n", "<Leader>:", "<Cmd>Telescope command_history<CR>", opts)
|
[nvim] Fix telescope config
|
[nvim] Fix telescope config
|
Lua
|
mit
|
masa0x80/dotfiles,masa0x80/dotfiles,masa0x80/dotfiles,masa0x80/dotfiles
|
7dc5ae985676dbf6a71ef29836e22dc079429917
|
lua/entities/gmod_wire_expression2/core/console.lua
|
lua/entities/gmod_wire_expression2/core/console.lua
|
/******************************************************************************\
Console support
\******************************************************************************/
E2Lib.RegisterExtension("console", true, "Lets E2 chips run concommands and retrieve convars")
local function tokenizeAndGetCommand(str)
-- Tokenize!
local tokens = {}
local curtoken = {}
local escaped = false
for i=1, #str do
local char = string.sub(str, i, i)
if escaped then
curtoken[#curtoken+1] = char
else
if string.match(char, "%w") then
curtoken[#curtoken + 1] = char
else
if #curtoken>0 then tokens[#tokens + 1] = table.concat(curtoken) curtoken = {} end
if char == "\"" then
escaped = not escaped
elseif char ~= " " then
tokens[#tokens + 1] = char
end
end
end
end
tokens[#tokens+1] = table.concat(curtoken)
-- Get table of commands used
local commands = {tokens[1] or ""}
for i=1, #tokens do
if tokens[i]==";" then
commands[#commands + 1] = tokens[i+1] or ""
end
end
return commands
end
local function validConCmd(self, command)
local ply = self.player
if not ply:IsValid() then return false end
if ply:GetInfoNum("wire_expression2_concmd", 0) == 0 then return false end
-- Validating the concmd length to ensure that it won't crash the server. 512 is the max
if #command >= 512 then return false end
local whitelistArr = string.Split((ply:GetInfo("wire_expression2_concmd_whitelist") or ""):Trim(), ",")
if #whitelistArr == 0 then return true end
local whitelist = {}
for k, v in pairs(whitelistArr) do whitelist[v] = true end
local commands = tokenizeAndGetCommand(command)
for _, command in pairs(commands) do
if not whitelist[command] then
return false
end
end
return true
end
__e2setcost(5)
e2function number concmd(string command)
if not validConCmd(self, command) then return 0 end
self.player:ConCommand(command:gsub("%%", "%%%%"))
return 1
end
e2function string convar(string cvar)
if not validConCmd(self, cvar) then return "" end
local ret = self.player:GetInfo(cvar)
if not ret then return "" end
return ret
end
e2function number convarnum(string cvar)
if not validConCmd(self, cvar) then return 0 end
local ret = self.player:GetInfoNum(cvar, 0)
if not ret then return 0 end
return ret
end
e2function number maxOfType(string typename)
if typename == "wire_holograms" then return GetConVarNumber("wire_holograms_max") or 0 end
return GetConVarNumber("sbox_max"..typename) or 0
end
e2function number playerDamage()
local ret = GetConVarNumber("sbox_plpldamage") or 0
return ret ~= 0 and 1 or 0
end
|
/******************************************************************************\
Console support
\******************************************************************************/
E2Lib.RegisterExtension("console", true, "Lets E2 chips run concommands and retrieve convars")
local function tokenizeAndGetCommand(str)
-- Tokenize!
local tokens = {}
local curtoken = {}
local escaped = false
for i=1, #str do
local char = string.sub(str, i, i)
if (escaped and char ~= "\"") or string.match(char, "%w") then
curtoken[#curtoken + 1] = char
else
if #curtoken>0 then tokens[#tokens + 1] = table.concat(curtoken) curtoken = {} end
if char == "\"" then
escaped = not escaped
elseif char ~= " " then
tokens[#tokens + 1] = char
end
end
end
tokens[#tokens+1] = table.concat(curtoken)
-- Get table of commands used
local commands = {tokens[1] or ""}
for i=1, #tokens do
if tokens[i]==";" then
commands[#commands + 1] = tokens[i+1] or ""
end
end
return commands
end
local function validConCmd(self, command)
local ply = self.player
if not ply:IsValid() then return false end
if ply:GetInfoNum("wire_expression2_concmd", 0) == 0 then return false end
-- Validating the concmd length to ensure that it won't crash the server. 512 is the max
if #command >= 512 then return false end
local whitelistArr = string.Split((ply:GetInfo("wire_expression2_concmd_whitelist") or ""):Trim(), ",")
if #whitelistArr == 0 then return true end
local whitelist = {}
for k, v in pairs(whitelistArr) do whitelist[v] = true end
local commands = tokenizeAndGetCommand(command)
for _, command in pairs(commands) do
if not whitelist[command] then
return false
end
end
return true
end
__e2setcost(5)
e2function number concmd(string command)
if not validConCmd(self, command) then return 0 end
self.player:ConCommand(command:gsub("%%", "%%%%"))
return 1
end
e2function string convar(string cvar)
if not validConCmd(self, cvar) then return "" end
local ret = self.player:GetInfo(cvar)
if not ret then return "" end
return ret
end
e2function number convarnum(string cvar)
if not validConCmd(self, cvar) then return 0 end
local ret = self.player:GetInfoNum(cvar, 0)
if not ret then return 0 end
return ret
end
e2function number maxOfType(string typename)
if typename == "wire_holograms" then return GetConVarNumber("wire_holograms_max") or 0 end
return GetConVarNumber("sbox_max"..typename) or 0
end
e2function number playerDamage()
local ret = GetConVarNumber("sbox_plpldamage") or 0
return ret ~= 0 and 1 or 0
end
|
Fixed escape mechanism
|
Fixed escape mechanism
|
Lua
|
apache-2.0
|
wiremod/wire,Grocel/wire,dvdvideo1234/wire,garrysmodlua/wire,sammyt291/wire,NezzKryptic/Wire
|
fb85680a6776989a2b1ea5bcb612efaaf39db29c
|
test_scripts/Polices/build_options/ATF_PTU_Trigger_IGN_cycles.lua
|
test_scripts/Polices/build_options/ATF_PTU_Trigger_IGN_cycles.lua
|
-- Requirement summary:
-- [PTU] Trigger: ignition cycles
--
-- Description:
-- When the amount of ignition cycles notified by HMI via BasicCommunication.OnIgnitionCycleOver gets equal to the value of
-- "exchange_after_x_ignition_cycles" field ("module_config" section) of policies database, SDL must trigger a PTU sequence
-- 1. Used preconditions:
-- SDL is built with "DEXTENDED_POLICY: ON" flag
-- the 1-st IGN cycle, PTU was succesfully applied. Policies DataBase contains "exchange_after_x_ignition_cycles" = 10
-- 2. Performed steps: Perform ignition_on/off 11 times
--
-- Expected result:
-- When amount of ignition cycles notified by HMI via BasicCommunication.OnIgnitionCycleOver gets equal to the value of "exchange_after_x_ignition_cycles"
-- field ("module_config" section) of policies database, SDL must trigger a PolicyTableUpdate sequence
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--[[ Required Shared libraries ]]
local commonFunctions = require ('user_modules/shared_testcases/commonFunctions')
local commonSteps = require('user_modules/shared_testcases/commonSteps')
local commonPreconditions = require('user_modules/shared_testcases/commonPreconditions')
--[[ Local Functions ]]
local function genpattern2str(name, value_type)
return "(%s*\"" .. name .. "\"%s*:%s*)".. value_type
end
local function modify_preloaded(pattern, value)
local preloaded_file = io.open(config.pathToSDL .. 'sdl_preloaded_pt.json', "r")
local content = preloaded_file:read("*a")
preloaded_file:close()
local res = string.gsub(content, pattern, "%1"..value, 1)
preloaded_file = io.open(config.pathToSDL .. 'sdl_preloaded_pt.json', "w+")
preloaded_file:write(res)
preloaded_file:close()
local check = string.find(res, value)
if ( check ~= nil) then
return true
end
return false
end
--[[ General Precondition before ATF start ]]
commonFunctions:SDLForceStop()
commonSteps:DeleteLogsFiles()
commonSteps:DeletePolicyTable()
--TODO(VVVakulenko): Should be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed
config.defaultProtocolVersion = 2
commonPreconditions:BackupFile("sdl_preloaded_pt.json")
local function Preconditions_set_exchange_after_x_ignition_cycles_to_10()
modify_preloaded(genpattern2str("exchange_after_x_ignition_cycles", "%d+"), "5")
end
Preconditions_set_exchange_after_x_ignition_cycles_to_10()
--[[ General Settings for configuration ]]
Test = require('connecttest')
require('user_modules/AppTypes')
local mobile_session = require('mobile_session')
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
for i = 1, 5 do
Test["Preconditions_perform_" .. tostring(i) .. "_IGN_OFF_ON"] = function() end
function Test:IGNITION_OFF()
StopSDL()
self.hmiConnection:SendNotification("BasicCommunication.OnIgnitionCycleOver")
EXPECT_HMINOTIFICATION("BasicCommunication.OnSDLClose")
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppUnregistered")
:Times(1)
end
function Test.Precondition_StartSDL()
StartSDL(config.pathToSDL, config.ExitOnCrash)
end
function Test:Precondition_InitHMI()
self:initHMI()
end
function Test:Precondition_InitHMI_onReady()
self:initHMI_onReady()
end
function Test:Precondition_Register_app()
self:connectMobile()
self.mobileSession = mobile_session.MobileSession(self, self.mobileConnection)
self.mobileSession:StartService(7)
:Do(function()
local correlationId = self.mobileSession:SendRPC("RegisterAppInterface", config.application1.registerAppInterfaceParams)
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered")
:Do(function(_,data)
self.HMIAppID = data.params.application.appID
end)
self.mobileSession:ExpectResponse(correlationId, { success = true, resultCode = "SUCCESS" })
self.mobileSession:ExpectNotification("OnHMIStatus", {hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE", systemContext = "MAIN"})
end)
end
end
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:TestStep_Check_PTU_triggered_on_IGNOFF()
self.hmiConnection:SendNotification("BasicCommunication.OnIgnitionCycleOver")
EXPECT_HMICALL("BasicCommunication.PolicyUpdate")
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATE_NEEDED"})
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test.Postcondition_Stop_SDL()
StopSDL()
end
function Test.Postcondition_RestoreFile()
commonPreconditions:RestoreFile("sdl_preloaded_pt.json")
end
return Test
|
-- Requirement summary:
-- [PTU] Trigger: ignition cycles
--
-- Description:
-- When the amount of ignition cycles notified by HMI via BasicCommunication.OnIgnitionCycleOver gets equal to the value of
-- "exchange_after_x_ignition_cycles" field ("module_config" section) of policies database, SDL must trigger a PTU sequence
-- 1. Used preconditions:
-- SDL is built with "DEXTENDED_POLICY: ON" flag
-- the 1-st IGN cycle, PTU was succesfully applied. Policies DataBase contains "exchange_after_x_ignition_cycles" = 10
-- 2. Performed steps: Perform ignition_on/off 11 times
--
-- Expected result:
-- When amount of ignition cycles notified by HMI via BasicCommunication.OnIgnitionCycleOver gets equal to the value of "exchange_after_x_ignition_cycles"
-- field ("module_config" section) of policies database, SDL must trigger a PolicyTableUpdate sequence
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--[[ Required Shared libraries ]]
local mobileSession = require("mobile_session")
local commonFunctions = require ('user_modules/shared_testcases/commonFunctions')
local commonSteps = require('user_modules/shared_testcases/commonSteps')
local commonPreconditions = require('user_modules/shared_testcases/commonPreconditions')
local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable')
--[[ Local Variables ]]
local exchnage_after = 5
local sdl_preloaded_pt = "sdl_preloaded_pt.json"
local ptu_file = "files/ptu.json"
--[[ Local Functions ]]
local function genpattern2str(name, value_type)
return "(%s*\"" .. name .. "\"%s*:%s*)".. value_type
end
local function modify_file(file_name, pattern, value)
local f = io.open(file_name, "r")
local content = f:read("*a")
f:close()
local res = string.gsub(content, pattern, "%1"..value, 1)
f = io.open(file_name, "w+")
f:write(res)
f:close()
local check = string.find(res, value)
if check ~= nil then
return true
end
return false
end
--[[ General Precondition before ATF start ]]
commonFunctions:SDLForceStop()
commonSteps:DeleteLogsFileAndPolicyTable()
config.defaultProtocolVersion = 2
-- Backup files
commonPreconditions:BackupFile(sdl_preloaded_pt)
os.execute("cp ".. ptu_file .. " " .. ptu_file .. ".BAK")
-- Update files
for _, v in pairs({config.pathToSDL .. sdl_preloaded_pt, ptu_file}) do
modify_file(v, genpattern2str("exchange_after_x_ignition_cycles", "%d+"), tostring(exchnage_after))
end
--[[ General Settings for configuration ]]
Test = require('connecttest')
require('user_modules/AppTypes')
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test:ActivateApp()
local requestId1 = self.hmiConnection:SendRequest("SDL.ActivateApp", { appID = self.applications[config.application1.registerAppInterfaceParams.appName] })
EXPECT_HMIRESPONSE(requestId1)
:Do(function(_, data1)
if data1.result.isSDLAllowed ~= true then
local requestId2 = self.hmiConnection:SendRequest("SDL.GetUserFriendlyMessage",
{ language = "EN-US", messageCodes = { "DataConsent" } })
EXPECT_HMIRESPONSE(requestId2)
:Do(function()
self.hmiConnection:SendNotification("SDL.OnAllowSDLFunctionality",
{ allowed = true, source = "GUI", device = { id = config.deviceMAC, name = "127.0.0.1" } })
EXPECT_HMICALL("BasicCommunication.ActivateApp")
:Do(function(_, data2)
self.hmiConnection:SendResponse(data2.id,"BasicCommunication.ActivateApp", "SUCCESS", { })
end)
:Times(1)
end)
end
end)
end
function Test:TestStep_SUCCEESS_Flow_EXTERNAL_PROPRIETARY()
testCasesForPolicyTable:flow_SUCCEESS_EXTERNAL_PROPRIETARY(self)
end
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
for i = 1, exchnage_after do
Test["Preconditions_perform_" .. tostring(i) .. "_IGN_OFF_ON"] = function() end
function Test:IGNITION_OFF()
self.hmiConnection:SendNotification("BasicCommunication.OnIgnitionCycleOver")
end
function Test.StopSDL()
StopSDL()
end
function Test.StartSDL()
StartSDL(config.pathToSDL, config.ExitOnCrash)
end
function Test:InitHMI()
self:initHMI()
end
function Test:InitHMI_onReady()
self:initHMI_onReady()
end
function Test:Register_app()
self:connectMobile()
self.mobileSession = mobileSession.MobileSession(self, self.mobileConnection)
self.mobileSession:StartService(7)
:Do(function()
local correlationId = self.mobileSession:SendRPC("RegisterAppInterface", config.application1.registerAppInterfaceParams)
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered")
self.mobileSession:ExpectResponse(correlationId, { success = true, resultCode = "SUCCESS" })
self.mobileSession:ExpectNotification("OnHMIStatus", { hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE", systemContext = "MAIN" })
end)
if i == exchnage_after then
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", { status = "UPDATE_NEEDED" })
:Times(AtLeast(1))
EXPECT_HMICALL("BasicCommunication.PolicyUpdate")
end
end
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test.Postcondition_Stop_SDL()
StopSDL()
end
function Test.Postcondition_RestoreFiles()
commonPreconditions:RestoreFile(sdl_preloaded_pt)
local ptu_file_bak = ptu_file..".BAK"
os.execute("cp -f " .. ptu_file_bak .. " " .. ptu_file)
os.execute("rm -f " .. ptu_file_bak)
end
return Test
|
Fix issues
|
Fix issues
|
Lua
|
bsd-3-clause
|
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
|
cdb39743e24d2fef994da492c40fb523deb056fa
|
luasrc/mch/response.lua
|
luasrc/mch/response.lua
|
#!/usr/bin/env lua
-- -*- lua -*-
-- Copyright 2012 Appwill Inc.
-- Author : KDr2
--
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
--
module('mch.response',package.seeall)
mchutil=require('mch.util')
ltp=require("ltp.template")
Response={ltp=ltp}
function Response:new()
local ret={
headers=ngx.header,
_cookies={},
_output={}
}
setmetatable(ret,self)
self.__index=self
return ret
end
function Response:write(content)
table.insert(self._output,content)
end
function Response:writeln(content)
table.insert(self._output,content)
table.insert(self._output,"\r\n")
end
function Response:redirect(url, status)
ngx.redirect(url, status)
end
function Response:_set_cookie(key, value, encrypt, duration, path)
if not key or key=="" or not value then
return
end
if not duration or duration<=0 then
duration=86400
end
if not path or path=="" then
path = "/"
end
if value and value~="" and encrypt==true then
value=ndk.set_var.set_encrypt_session(value)
value=ndk.set_var.set_encode_base64(value)
end
local expiretime=ngx.time()+duration
expiretime = ngx.cookie_time(expiretime)
return table.concat({key, "=", value, "; expires=", expiretime, "; path=", path})
end
function Response:set_cookie(key, value, encrypt, duration, path)
if not value then self._cookies[key]=nil end
local cookie=self:_set_cookie(key, value, encrypt, duration, path)
self._cookies[key]=cookie
ngx.header["Set-Cookie"]=self._cookies
end
--[[
LTP Template Support
--]]
ltp_templates_cache={}
function ltp_function(template)
ret=ltp_templates_cache[template]
if ret then return ret end
local tdata=mchutil.read_all(MOOCHINE_APP_PATH .. "/templates/" .. template)
local rfun = ltp.load_template(tdata, '<?lua','?>')
ltp_templates_cache[template]=rfun
return rfun
end
function Response:ltp(template,data)
local rfun=ltp_function(template)
local output = {}
local mt={__index=_G}
setmetatable(data,mt)
ltp.execute_template(rfun, data, output)
table.insert(self._output,output)
end
|
#!/usr/bin/env lua
-- -*- lua -*-
-- Copyright 2012 Appwill Inc.
-- Author : KDr2
--
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
--
module('mch.response',package.seeall)
mchutil=require('mch.util')
ltp=require("ltp.template")
Response={ltp=ltp}
function Response:new()
local ret={
headers=ngx.header,
_cookies={},
_output={}
}
setmetatable(ret,self)
self.__index=self
return ret
end
function Response:write(content)
table.insert(self._output,content)
end
function Response:writeln(content)
table.insert(self._output,content)
table.insert(self._output,"\r\n")
end
function Response:redirect(url, status)
ngx.redirect(url, status)
end
function Response:_set_cookie(key, value, encrypt, duration, path)
if not value then return nil end
if not key or key=="" or not value then
return
end
if not duration or duration<=0 then
duration=86400
end
if not path or path=="" then
path = "/"
end
if value and value~="" and encrypt==true then
value=ndk.set_var.set_encrypt_session(value)
value=ndk.set_var.set_encode_base64(value)
end
local expiretime=ngx.time()+duration
expiretime = ngx.cookie_time(expiretime)
return table.concat({key, "=", value, "; expires=", expiretime, "; path=", path})
end
function Response:set_cookie(key, value, encrypt, duration, path)
local cookie=self:_set_cookie(key, value, encrypt, duration, path)
self._cookies[key]=cookie
ngx.header["Set-Cookie"]=self._cookies
end
--[[
LTP Template Support
--]]
ltp_templates_cache={}
function ltp_function(template)
ret=ltp_templates_cache[template]
if ret then return ret end
local tdata=mchutil.read_all(MOOCHINE_APP_PATH .. "/templates/" .. template)
local rfun = ltp.load_template(tdata, '<?lua','?>')
ltp_templates_cache[template]=rfun
return rfun
end
function Response:ltp(template,data)
local rfun=ltp_function(template)
local output = {}
local mt={__index=_G}
setmetatable(data,mt)
ltp.execute_template(rfun, data, output)
table.insert(self._output,output)
end
|
fix multi set-cookie bug
|
fix multi set-cookie bug
|
Lua
|
apache-2.0
|
appwilldev/moochine,lilien1010/moochine,appwilldev/moochine,lilien1010/moochine,lilien1010/moochine
|
122fe9a9e243ca99e021f419ed5efcd7b9510570
|
plugins/mod_xmlrpc.lua
|
plugins/mod_xmlrpc.lua
|
-- Prosody IM
-- Copyright (C) 2008-2009 Matthew Wild
-- Copyright (C) 2008-2009 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
module.host = "*" -- Global module
local httpserver = require "net.httpserver";
local st = require "util.stanza";
local pcall = pcall;
local unpack = unpack;
local tostring = tostring;
local is_admin = require "core.usermanager".is_admin;
local jid_split = require "util.jid".split;
local jid_bare = require "util.jid".bare;
local b64_decode = require "util.encodings".base64.decode;
local get_method = require "core.objectmanager".get_object;
local validate_credentials = require "core.usermanager".validate_credentials;
local translate_request = require "util.xmlrpc".translate_request;
local create_response = require "util.xmlrpc".create_response;
local create_error_response = require "util.xmlrpc".create_error_response;
local entity_map = setmetatable({
["amp"] = "&";
["gt"] = ">";
["lt"] = "<";
["apos"] = "'";
["quot"] = "\"";
}, {__index = function(_, s)
if s:sub(1,1) == "#" then
if s:sub(2,2) == "x" then
return string.char(tonumber(s:sub(3), 16));
else
return string.char(tonumber(s:sub(2)));
end
end
end
});
local function xml_unescape(str)
return (str:gsub("&(.-);", entity_map));
end
local function parse_xml(xml)
local stanza = st.stanza("root");
local regexp = "<([^>]*)>([^<]*)";
for elem, text in xml:gmatch(regexp) do
--print("[<"..elem..">|"..text.."]");
if elem:sub(1,1) == "!" or elem:sub(1,1) == "?" then -- neglect comments and processing-instructions
elseif elem:sub(1,1) == "/" then -- end tag
elem = elem:sub(2);
stanza:up(); -- TODO check for start-end tag name match
elseif elem:sub(-1,-1) == "/" then -- empty tag
elem = elem:sub(1,-2);
stanza:tag(elem):up();
else -- start tag
stanza:tag(elem);
end
if #text ~= 0 then -- text
stanza:text(xml_unescape(text));
end
end
return stanza.tags[1];
end
local function handle_xmlrpc_request(jid, method, args)
local is_secure_call = (method:sub(1,7) == "secure/");
if not is_admin(jid) and not is_secure_call then
return create_error_response(401, "not authorized");
end
method = get_method(method);
if not method then return create_error_response(404, "method not found"); end
args = args or {};
if is_secure_call then table.insert(args, 1, jid); end
local success, result = pcall(method, unpack(args));
if success then
success, result = pcall(create_response, result or "nil");
if success then
return result;
end
return create_error_response(500, "Error in creating response: "..result);
end
return create_error_response(0, (result and result:gmatch("[^:]*:[^:]*: (.*)")()) or "nil");
end
local function handle_xmpp_request(origin, stanza)
local query = stanza.tags[1];
if query.name == "query" then
if #query.tags == 1 then
local success, method, args = pcall(translate_request, query.tags[1]);
if success then
local result = handle_xmlrpc_request(jid_bare(stanza.attr.from), method, args);
origin.send(st.reply(stanza):tag('query', {xmlns='jabber:iq:rpc'}):add_child(result));
else
origin.send(st.error_reply(stanza, "modify", "bad-request", method));
end
else origin.send(st.error_reply(stanza, "modify", "bad-request", "No content in XML-RPC request")); end
else origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); end
end
module:add_iq_handler({"c2s", "s2sin"}, "jabber:iq:rpc", handle_xmpp_request);
module:add_feature("jabber:iq:rpc");
-- TODO add <identity category='automation' type='rpc'/> to disco replies
local default_headers = { ['Content-Type'] = 'text/xml' };
local unauthorized_response = { status = '401 UNAUTHORIZED', headers = {['Content-Type']='text/html', ['WWW-Authenticate']='Basic realm="WallyWorld"'}; body = "<html><body>Authentication required</body></html>"; };
local function handle_http_request(method, body, request)
-- authenticate user
local username, password = b64_decode(request['authorization'] or ''):gmatch('([^:]*):(.*)')(); -- TODO digest auth
local node, host = jid_split(username);
if not validate_credentials(host, node, password) then
return unauthorized_response;
end
-- parse request
local stanza = body and parse_xml(body);
if (not stanza) or request.method ~= "POST" then
return "<html><body>You really don't look like an XML-RPC client to me... what do you want?</body></html>";
end
-- execute request
local success, method, args = pcall(translate_request, stanza);
if success then
return { headers = default_headers; body = tostring(handle_xmlrpc_request(node.."@"..host, method, args)) };
end
return "<html><body>Error parsing XML-RPC request: "..tostring(method).."</body></html>";
end
httpserver.new{ port = 9000, base = "xmlrpc", handler = handle_http_request }
|
-- Prosody IM
-- Copyright (C) 2008-2009 Matthew Wild
-- Copyright (C) 2008-2009 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
module.host = "*" -- Global module
local httpserver = require "net.httpserver";
local st = require "util.stanza";
local pcall = pcall;
local unpack = unpack;
local tostring = tostring;
local is_admin = require "core.usermanager".is_admin;
local jid_split = require "util.jid".split;
local jid_bare = require "util.jid".bare;
local b64_decode = require "util.encodings".base64.decode;
local get_method = require "core.objectmanager".get_object;
local validate_credentials = require "core.usermanager".validate_credentials;
local translate_request = require "util.xmlrpc".translate_request;
local create_response = require "util.xmlrpc".create_response;
local create_error_response = require "util.xmlrpc".create_error_response;
local entity_map = setmetatable({
["amp"] = "&";
["gt"] = ">";
["lt"] = "<";
["apos"] = "'";
["quot"] = "\"";
}, {__index = function(_, s)
if s:sub(1,1) == "#" then
if s:sub(2,2) == "x" then
return string.char(tonumber(s:sub(3), 16));
else
return string.char(tonumber(s:sub(2)));
end
end
end
});
local function xml_unescape(str)
return (str:gsub("&(.-);", entity_map));
end
local function parse_xml(xml)
local stanza = st.stanza("root");
local regexp = "<([^>]*)>([^<]*)";
for elem, text in xml:gmatch(regexp) do
--print("[<"..elem..">|"..text.."]");
if elem:sub(1,1) == "!" or elem:sub(1,1) == "?" then -- neglect comments and processing-instructions
elseif elem:sub(1,1) == "/" then -- end tag
elem = elem:sub(2);
stanza:up(); -- TODO check for start-end tag name match
elseif elem:sub(-1,-1) == "/" then -- empty tag
elem = elem:sub(1,-2);
stanza:tag(elem):up();
else -- start tag
stanza:tag(elem);
end
if #text ~= 0 then -- text
stanza:text(xml_unescape(text));
end
end
return stanza.tags[1];
end
local function handle_xmlrpc_request(jid, method, args)
local is_secure_call = (method:sub(1,7) == "secure/");
if not is_admin(jid) and not is_secure_call then
return create_error_response(401, "not authorized");
end
method = get_method(method);
if not method then return create_error_response(404, "method not found"); end
args = args or {};
if is_secure_call then table.insert(args, 1, jid); end
local success, result = pcall(method, unpack(args));
if success then
success, result = pcall(create_response, result or "nil");
if success then
return result;
end
return create_error_response(500, "Error in creating response: "..result);
end
return create_error_response(0, tostring(result):gsub("^[^:]+:%d+: ", ""));
end
local function handle_xmpp_request(origin, stanza)
local query = stanza.tags[1];
if query.name == "query" then
if #query.tags == 1 then
local success, method, args = pcall(translate_request, query.tags[1]);
if success then
local result = handle_xmlrpc_request(jid_bare(stanza.attr.from), method, args);
origin.send(st.reply(stanza):tag('query', {xmlns='jabber:iq:rpc'}):add_child(result));
else
origin.send(st.error_reply(stanza, "modify", "bad-request", method));
end
else origin.send(st.error_reply(stanza, "modify", "bad-request", "No content in XML-RPC request")); end
else origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); end
end
module:add_iq_handler({"c2s", "s2sin"}, "jabber:iq:rpc", handle_xmpp_request);
module:add_feature("jabber:iq:rpc");
-- TODO add <identity category='automation' type='rpc'/> to disco replies
local default_headers = { ['Content-Type'] = 'text/xml' };
local unauthorized_response = { status = '401 UNAUTHORIZED', headers = {['Content-Type']='text/html', ['WWW-Authenticate']='Basic realm="WallyWorld"'}; body = "<html><body>Authentication required</body></html>"; };
local function handle_http_request(method, body, request)
-- authenticate user
local username, password = b64_decode(request['authorization'] or ''):gmatch('([^:]*):(.*)')(); -- TODO digest auth
local node, host = jid_split(username);
if not validate_credentials(host, node, password) then
return unauthorized_response;
end
-- parse request
local stanza = body and parse_xml(body);
if (not stanza) or request.method ~= "POST" then
return "<html><body>You really don't look like an XML-RPC client to me... what do you want?</body></html>";
end
-- execute request
local success, method, args = pcall(translate_request, stanza);
if success then
return { headers = default_headers; body = tostring(handle_xmlrpc_request(node.."@"..host, method, args)) };
end
return "<html><body>Error parsing XML-RPC request: "..tostring(method).."</body></html>";
end
httpserver.new{ port = 9000, base = "xmlrpc", handler = handle_http_request }
|
mod_xmlrpc: Correct stripping of filename/line number prefix in RPC method error results
|
mod_xmlrpc: Correct stripping of filename/line number prefix in RPC method error results
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
1f570cb8e8cba545d0c80c27e6feede818786e0c
|
net/xmppclient_listener.lua
|
net/xmppclient_listener.lua
|
-- Prosody IM
-- Copyright (C) 2008-2009 Matthew Wild
-- Copyright (C) 2008-2009 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local logger = require "logger";
local log = logger.init("xmppclient_listener");
local lxp = require "lxp"
local init_xmlhandlers = require "core.xmlhandlers"
local sm_new_session = require "core.sessionmanager".new_session;
local connlisteners_register = require "net.connlisteners".register;
local t_insert = table.insert;
local t_concat = table.concat;
local t_concatall = function (t, sep) local tt = {}; for _, s in ipairs(t) do t_insert(tt, tostring(s)); end return t_concat(tt, sep); end
local m_random = math.random;
local format = string.format;
local sessionmanager = require "core.sessionmanager";
local sm_new_session, sm_destroy_session = sessionmanager.new_session, sessionmanager.destroy_session;
local sm_streamopened = sessionmanager.streamopened;
local sm_streamclosed = sessionmanager.streamclosed;
local st = require "util.stanza";
local config = require "core.configmanager";
local opt_keepalives = config.get("*", "core", "tcp_keepalives");
local stream_callbacks = { default_ns = "jabber:client",
streamopened = sm_streamopened, streamclosed = sm_streamclosed, handlestanza = core_process_stanza };
function stream_callbacks.error(session, error, data)
if error == "no-stream" then
session.log("debug", "Invalid opening stream header");
session:close("invalid-namespace");
elseif session.close then
(session.log or log)("debug", "Client XML parse error: %s", tostring(error));
session:close("xml-not-well-formed");
end
end
local function handleerr(err) log("error", "Traceback[c2s]: %s: %s", tostring(err), debug.traceback()); end
function stream_callbacks.handlestanza(a, b)
xpcall(function () core_process_stanza(a, b) end, handleerr);
end
local sessions = {};
local xmppclient = { default_port = 5222, default_mode = "*a" };
-- These are session methods --
local function session_reset_stream(session)
-- Reset stream
local parser = lxp.new(init_xmlhandlers(session, stream_callbacks), "\1");
session.parser = parser;
session.notopen = true;
function session.data(conn, data)
local ok, err = parser:parse(data);
if ok then return; end
log("debug", "Received invalid XML (%s) %d bytes: %s", tostring(err), #data, data:sub(1, 300):gsub("[\r\n]+", " "):gsub("[%z\1-\31]", "_"));
session:close("xml-not-well-formed");
end
return true;
end
local stream_xmlns_attr = {xmlns='urn:ietf:params:xml:ns:xmpp-streams'};
local default_stream_attr = { ["xmlns:stream"] = "http://etherx.jabber.org/streams", xmlns = stream_callbacks.default_ns, version = "1.0", id = "" };
local function session_close(session, reason)
local log = session.log or log;
if session.conn then
if session.notopen then
session.send("<?xml version='1.0'?>");
session.send(st.stanza("stream:stream", default_stream_attr):top_tag());
end
if reason then
if type(reason) == "string" then -- assume stream error
log("info", "Disconnecting client, <stream:error> is: %s", reason);
session.send(st.stanza("stream:error"):tag(reason, {xmlns = 'urn:ietf:params:xml:ns:xmpp-streams' }));
elseif type(reason) == "table" then
if reason.condition then
local stanza = st.stanza("stream:error"):tag(reason.condition, stream_xmlns_attr):up();
if reason.text then
stanza:tag("text", stream_xmlns_attr):text(reason.text):up();
end
if reason.extra then
stanza:add_child(reason.extra);
end
log("info", "Disconnecting client, <stream:error> is: %s", tostring(stanza));
session.send(stanza);
elseif reason.name then -- a stanza
log("info", "Disconnecting client, <stream:error> is: %s", tostring(reason));
session.send(reason);
end
end
end
session.send("</stream:stream>");
session.conn:close();
xmppclient.ondisconnect(session.conn, (reason and (reason.text or reason.condition)) or reason or "session closed");
end
end
-- End of session methods --
function xmppclient.onincoming(conn, data)
local session = sessions[conn];
if not session then
session = sm_new_session(conn);
sessions[conn] = session;
session.log("info", "Client connected");
-- Client is using legacy SSL (otherwise mod_tls sets this flag)
if conn:ssl() then
session.secure = true;
end
if opt_keepalives ~= nil then
conn:setoption("keepalive", opt_keepalives);
end
session.reset_stream = session_reset_stream;
session.close = session_close;
session_reset_stream(session); -- Initialise, ready for use
session.dispatch_stanza = stream_callbacks.handlestanza;
end
if data then
session.data(conn, data);
end
end
function xmppclient.ondisconnect(conn, err)
local session = sessions[conn];
if session then
(session.log or log)("info", "Client disconnected: %s", err);
sm_destroy_session(session, err);
sessions[conn] = nil;
session = nil;
end
end
connlisteners_register("xmppclient", xmppclient);
|
-- Prosody IM
-- Copyright (C) 2008-2009 Matthew Wild
-- Copyright (C) 2008-2009 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local logger = require "logger";
local log = logger.init("xmppclient_listener");
local lxp = require "lxp"
local init_xmlhandlers = require "core.xmlhandlers"
local sm_new_session = require "core.sessionmanager".new_session;
local connlisteners_register = require "net.connlisteners".register;
local t_insert = table.insert;
local t_concat = table.concat;
local t_concatall = function (t, sep) local tt = {}; for _, s in ipairs(t) do t_insert(tt, tostring(s)); end return t_concat(tt, sep); end
local m_random = math.random;
local format = string.format;
local sessionmanager = require "core.sessionmanager";
local sm_new_session, sm_destroy_session = sessionmanager.new_session, sessionmanager.destroy_session;
local sm_streamopened = sessionmanager.streamopened;
local sm_streamclosed = sessionmanager.streamclosed;
local st = require "util.stanza";
local config = require "core.configmanager";
local opt_keepalives = config.get("*", "core", "tcp_keepalives");
local stream_callbacks = { default_ns = "jabber:client",
streamopened = sm_streamopened, streamclosed = sm_streamclosed, handlestanza = core_process_stanza };
local xmlns_xmpp_streams = "urn:ietf:params:xml:ns:xmpp-streams";
function stream_callbacks.error(session, error, data)
if error == "no-stream" then
session.log("debug", "Invalid opening stream header");
session:close("invalid-namespace");
elseif error == "parse-error" then
(session.log or log)("debug", "Client XML parse error: %s", tostring(data));
session:close("xml-not-well-formed");
elseif error == "stream-error" then
local condition, text = "undefined-condition";
for child in data:children() do
if child.attr.xmlns == xmlns_xmpp_streams then
if child.name ~= "text" then
condition = child.name;
else
text = child:get_text();
end
if condition ~= "undefined-condition" and text then
break;
end
end
end
text = condition .. (text and (" ("..text..")") or "");
session.log("info", "Session closed by remote with error: %s", text);
session:close(nil, text);
end
end
local function handleerr(err) log("error", "Traceback[c2s]: %s: %s", tostring(err), debug.traceback()); end
function stream_callbacks.handlestanza(a, b)
xpcall(function () core_process_stanza(a, b) end, handleerr);
end
local sessions = {};
local xmppclient = { default_port = 5222, default_mode = "*a" };
-- These are session methods --
local function session_reset_stream(session)
-- Reset stream
local parser = lxp.new(init_xmlhandlers(session, stream_callbacks), "\1");
session.parser = parser;
session.notopen = true;
function session.data(conn, data)
local ok, err = parser:parse(data);
if ok then return; end
log("debug", "Received invalid XML (%s) %d bytes: %s", tostring(err), #data, data:sub(1, 300):gsub("[\r\n]+", " "):gsub("[%z\1-\31]", "_"));
session:close("xml-not-well-formed");
end
return true;
end
local stream_xmlns_attr = {xmlns='urn:ietf:params:xml:ns:xmpp-streams'};
local default_stream_attr = { ["xmlns:stream"] = "http://etherx.jabber.org/streams", xmlns = stream_callbacks.default_ns, version = "1.0", id = "" };
local function session_close(session, reason)
local log = session.log or log;
if session.conn then
if session.notopen then
session.send("<?xml version='1.0'?>");
session.send(st.stanza("stream:stream", default_stream_attr):top_tag());
end
if reason then
if type(reason) == "string" then -- assume stream error
log("info", "Disconnecting client, <stream:error> is: %s", reason);
session.send(st.stanza("stream:error"):tag(reason, {xmlns = 'urn:ietf:params:xml:ns:xmpp-streams' }));
elseif type(reason) == "table" then
if reason.condition then
local stanza = st.stanza("stream:error"):tag(reason.condition, stream_xmlns_attr):up();
if reason.text then
stanza:tag("text", stream_xmlns_attr):text(reason.text):up();
end
if reason.extra then
stanza:add_child(reason.extra);
end
log("info", "Disconnecting client, <stream:error> is: %s", tostring(stanza));
session.send(stanza);
elseif reason.name then -- a stanza
log("info", "Disconnecting client, <stream:error> is: %s", tostring(reason));
session.send(reason);
end
end
end
session.send("</stream:stream>");
session.conn:close();
xmppclient.ondisconnect(session.conn, (reason and (reason.text or reason.condition)) or reason or "session closed");
end
end
-- End of session methods --
function xmppclient.onincoming(conn, data)
local session = sessions[conn];
if not session then
session = sm_new_session(conn);
sessions[conn] = session;
session.log("info", "Client connected");
-- Client is using legacy SSL (otherwise mod_tls sets this flag)
if conn:ssl() then
session.secure = true;
end
if opt_keepalives ~= nil then
conn:setoption("keepalive", opt_keepalives);
end
session.reset_stream = session_reset_stream;
session.close = session_close;
session_reset_stream(session); -- Initialise, ready for use
session.dispatch_stanza = stream_callbacks.handlestanza;
end
if data then
session.data(conn, data);
end
end
function xmppclient.ondisconnect(conn, err)
local session = sessions[conn];
if session then
(session.log or log)("info", "Client disconnected: %s", err);
sm_destroy_session(session, err);
sessions[conn] = nil;
session = nil;
end
end
connlisteners_register("xmppclient", xmppclient);
|
net.xmppclient_listener: Fix to correctly handle stream errors from clients
|
net.xmppclient_listener: Fix to correctly handle stream errors from clients
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
d389abf769144ad55c0fc3259400d15df4c5896f
|
nvim/lua/plugin/lsp.lua
|
nvim/lua/plugin/lsp.lua
|
local ok, lspconfig = pcall(require, "lspconfig")
if not ok then
return
end
local mason = require('mason')
local mason_lspconfig = require('mason-lspconfig')
local util = require('lspconfig.util')
mason.setup()
mason_lspconfig.setup {
ensure_installed = {
'sumneko_lua',
},
}
local function on_attach(_, bufnr)
local function buf_set_keymap(...) vim.api.nvim_buf_set_keymap(bufnr, ...) end
local function buf_set_option(...) vim.api.nvim_buf_set_option(bufnr, ...) end
-- Enable completion triggered by <c-x><c-o>
buf_set_option('omnifunc', 'v:lua.vim.lsp.omnifunc')
-- Mappings.
local opts = { noremap=true, silent=true }
-- See `:help vim.lsp.*` for documentation on any of the below functions
buf_set_keymap('n', 'gD', '<cmd>lua vim.lsp.buf.declaration()<CR>', opts)
buf_set_keymap('n', 'gd', '<cmd>lua vim.lsp.buf.definition()<CR>', opts)
buf_set_keymap('n', 'K', '<cmd>lua vim.lsp.buf.hover()<CR>', opts)
buf_set_keymap('n', 'gi', '<cmd>lua vim.lsp.buf.implementation()<CR>', opts)
buf_set_keymap('n', '<C-k>', '<cmd>lua vim.lsp.buf.signature_help()<CR>', opts)
buf_set_keymap('n', '<space>wa', '<cmd>lua vim.lsp.buf.add_workspace_folder()<CR>', opts)
buf_set_keymap('n', '<space>wr', '<cmd>lua vim.lsp.buf.remove_workspace_folder()<CR>', opts)
buf_set_keymap('n', '<space>wl', '<cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<CR>', opts)
buf_set_keymap('n', '<space>D', '<cmd>lua vim.lsp.buf.type_definition()<CR>', opts)
buf_set_keymap('n', '<space>rn', '<cmd>lua vim.lsp.buf.rename()<CR>', opts)
buf_set_keymap('n', '<space>ca', '<cmd>lua vim.lsp.buf.code_action()<CR>', opts)
buf_set_keymap('n', 'gr', '<cmd>lua vim.lsp.buf.references()<CR>', opts)
buf_set_keymap('n', '<space>e', '<cmd>lua vim.diagnostic.open_float()<CR>', opts)
buf_set_keymap('n', '[d', '<cmd>lua vim.diagnostic.goto_prev()<CR>', opts)
buf_set_keymap('n', ']d', '<cmd>lua vim.diagnostic.goto_next()<CR>', opts)
buf_set_keymap('n', '<space>q', '<cmd>lua vim.diagnostic.setloclist()<CR>', opts)
buf_set_keymap('n', '<space>f', '<cmd>lua vim.lsp.buf.formatting()<CR>', opts)
require('lsp_signature').on_attach()
end
util.on_setup = util.add_hook_after(util.on_setup, function(config)
if config.on_attach then
config.on_attach = util.add_hook_after(config.on_attach, on_attach)
else
config.on_attach = on_attach
end
local capabilities = require('cmp_nvim_lsp').update_capabilities(vim.lsp.protocol.make_client_capabilities())
config.capabilities = vim.tbl_deep_extend("force", capabilities, config.capabilities or {})
end)
mason_lspconfig.setup_handlers {
function(server_name)
lspconfig[server_name].setup()
end,
["sumneko_lua"] = function()
lspconfig.sumneko_lua.setup {
settings = {
Lua = {
diagnostics = {
globals = { "vim" },
},
},
},
}
end,
}
|
local ok, lspconfig = pcall(require, "lspconfig")
if not ok then
return
end
local mason = require('mason')
local mason_lspconfig = require('mason-lspconfig')
local util = require('lspconfig.util')
mason.setup()
mason_lspconfig.setup {
ensure_installed = {
'sumneko_lua',
},
}
local function on_attach(_, bufnr)
local function buf_set_keymap(...) vim.api.nvim_buf_set_keymap(bufnr, ...) end
local function buf_set_option(...) vim.api.nvim_buf_set_option(bufnr, ...) end
-- Enable completion triggered by <c-x><c-o>
buf_set_option('omnifunc', 'v:lua.vim.lsp.omnifunc')
-- Mappings.
local opts = { noremap=true, silent=true }
-- See `:help vim.lsp.*` for documentation on any of the below functions
buf_set_keymap('n', 'gD', '<cmd>lua vim.lsp.buf.declaration()<CR>', opts)
buf_set_keymap('n', 'gd', '<cmd>lua vim.lsp.buf.definition()<CR>', opts)
buf_set_keymap('n', 'K', '<cmd>lua vim.lsp.buf.hover()<CR>', opts)
buf_set_keymap('n', 'gi', '<cmd>lua vim.lsp.buf.implementation()<CR>', opts)
buf_set_keymap('n', '<C-k>', '<cmd>lua vim.lsp.buf.signature_help()<CR>', opts)
buf_set_keymap('n', '<space>wa', '<cmd>lua vim.lsp.buf.add_workspace_folder()<CR>', opts)
buf_set_keymap('n', '<space>wr', '<cmd>lua vim.lsp.buf.remove_workspace_folder()<CR>', opts)
buf_set_keymap('n', '<space>wl', '<cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<CR>', opts)
buf_set_keymap('n', '<space>D', '<cmd>lua vim.lsp.buf.type_definition()<CR>', opts)
buf_set_keymap('n', '<space>rn', '<cmd>lua vim.lsp.buf.rename()<CR>', opts)
buf_set_keymap('n', '<space>ca', '<cmd>lua vim.lsp.buf.code_action()<CR>', opts)
buf_set_keymap('n', 'gr', '<cmd>lua vim.lsp.buf.references()<CR>', opts)
buf_set_keymap('n', '<space>e', '<cmd>lua vim.diagnostic.open_float()<CR>', opts)
buf_set_keymap('n', '[d', '<cmd>lua vim.diagnostic.goto_prev()<CR>', opts)
buf_set_keymap('n', ']d', '<cmd>lua vim.diagnostic.goto_next()<CR>', opts)
buf_set_keymap('n', '<space>q', '<cmd>lua vim.diagnostic.setloclist()<CR>', opts)
buf_set_keymap('n', '<space>f', '<cmd>lua vim.lsp.buf.formatting()<CR>', opts)
require('lsp_signature').on_attach()
end
util.on_setup = util.add_hook_after(util.on_setup, function(config)
if config.on_attach then
config.on_attach = util.add_hook_after(config.on_attach, on_attach)
else
config.on_attach = on_attach
end
local capabilities = require('cmp_nvim_lsp').update_capabilities(vim.lsp.protocol.make_client_capabilities())
config.capabilities = vim.tbl_deep_extend("force", capabilities, config.capabilities or {})
end)
for _, server in ipairs(mason_lspconfig.get_installed_servers()) do
lspconfig[server].setup {
settings = {
Lua = {
diagnostics = {
globals = { "vim" },
},
},
},
}
end
|
Use lspconfig server getter instead of handler
|
Use lspconfig server getter instead of handler
The handler seems to have some bug that complains when I install a
server that isn't hardcoded.
|
Lua
|
mit
|
MrPickles/dotfiles
|
71f6cdef3a0b1975451c784a6cd5bac505d934bb
|
App/NevermoreEngine.lua
|
App/NevermoreEngine.lua
|
--- Nevermore module loader.
-- Used to simply resource loading and networking so a more unified server / client codebased can be used
-- @module Nevermore
local DEBUG_MODE = false -- Set to true to help identify what libraries have circular dependencies
local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ServerScriptService = game:GetService("ServerScriptService")
assert(script:IsA("ModuleScript"), "Invalid script type. For NevermoreEngine to work correctly, it should be a ModuleScript named \"NevermoreEngine\" parented to ReplicatedStorage")
assert(script.Name == "NevermoreEngine", "Invalid script name. For NevermoreEngine to work correctly, it should be a ModuleScript named \"NevermoreEngine\" parented to ReplicatedStorage")
assert(script.Parent == ReplicatedStorage, "Invalid parent. For NevermoreEngine to work correctly, it should be a ModuleScript named \"NevermoreEngine\" parented to ReplicatedStorage")
--- Handles yielded operations by caching the retrieval process
local function _handleRetrieving(Retrieving, Function, Argument)
assert(type(Retrieving) == "table", "Error: Retrieving must be a table")
assert(type(Function) == "function", "Error: Function must be a function")
local Signal = Instance.new("BindableEvent")
local Result
Retrieving[Argument] = function()
if Result ~= nil and Result then
return Result
end
Signal.Event:Wait()
return Result
end
Result = Function(Argument)
assert(Result ~= nil, "Result cannot be nil")
Retrieving[Argument] = nil
Signal:Fire()
Signal:Destroy()
return Result
end
--- Caches single argument, single output only
local function _asyncCache(Function)
assert(type(Function) == "function", "Error: Function must be a userdata")
local Cache = {}
local Retrieving = {}
return function(Argument)
assert(Argument ~= nil, "Error: ARgument ")
if Cache[Argument] ~= nil then
return Cache[Argument]
elseif Retrieving[Argument] then
return Retrieving[Argument]()
else
Cache[Argument] = _handleRetrieving(Retrieving, Function, Argument)
return Cache[Argument]
end
end
end
--- Retrieves an instance from a parent
local function _retrieve(Parent, ClassName)
assert(type(ClassName) == "string", "Error: ClassName must be a string")
assert(typeof(Parent) == "Instance", ("Error: Parent must be an Instance, got '%s'"):format(typeof(Parent)))
return RunService:IsServer() and function(Name)
local Item = Parent:FindFirstChild(Name)
if not Item then
Item = Instance.new(ClassName)
Item.Archivable = false
Item.Name = Name
Item.Parent = Parent
end
return Item
end or function(Name)
local Resource = Parent:WaitForChild(Name, 5)
if Resource then
return Resource
end
warn(("Warning: No '%s' found, be sure to require '%s' on the server. Yielding for '%s'"):format(tostring(Name), tostring(Name), ClassName))
return Parent:WaitForChild(Name)
end
end
local function _getRepository(GetSubFolder)
if RunService:IsServer() then
local RepositoryFolder = ServerScriptService:FindFirstChild("Nevermore")
if not RepositoryFolder then
warn("Warning: No repository of Nevermore modules found (Expected in ServerScriptService with name \"Nevermore\"). Library retrieval will fail.")
RepositoryFolder = Instance.new("Folder")
RepositoryFolder.Name = "Nevermore"
end
return RepositoryFolder
else
return GetSubFolder("Modules")
end
end
local function _getLibraryCache(RepositoryFolder)
local LibraryCache = {}
for _, Child in pairs(RepositoryFolder:GetDescendants()) do
if Child:IsA("ModuleScript") and not Child:FindFirstAncestorOfClass("ModuleScript") then
if LibraryCache[Child.Name] then
error(("Error: Duplicate name of '%s' already exists"):format(Child.Name))
end
LibraryCache[Child.Name] = Child
end
end
return LibraryCache
end
local function _replicateRepository(ReplicationFolder, LibraryCache)
for Name, Library in pairs(LibraryCache) do
if not Name:lower():find("server") then
Library.Parent = ReplicationFolder
end
end
end
local function _debugLoading(Function)
local Count = 0
local RequestDepth = 0
return function(Module, ...)
Count = Count + 1
local LibraryID = Count
if DEBUG_MODE then
print(("\t"):rep(RequestDepth), LibraryID, "Loading: ", Module)
RequestDepth = RequestDepth + 1
end
local Result = Function(Module, ...)
if DEBUG_MODE then
RequestDepth = RequestDepth - 1
print(("\t"):rep(RequestDepth), LibraryID, "Done loading: ", Module)
end
return Result
end
end
local function _getLibraryLoader(LibraryCache)
--- Loads a library from Nevermore's library cache
-- @param Module The name of the library or a module
-- @return The library's value
return function(Module)
if typeof(Module) == "Instance" and Module:IsA("ModuleScript") then
return require(Module)
elseif type(Module) == "string" then
local ModuleScript = LibraryCache[Module] or error("Error: Library '" .. Module .. "' does not exist.", 2)
return require(ModuleScript)
else
error(("Error: Module must be a string or ModuleScript, got '%s'"):format(typeof(Module)))
end
end
end
local ResourceFolder = _retrieve(ReplicatedStorage, "Folder")("NevermoreResources")
local GetSubFolder = _retrieve(ResourceFolder, "Folder")
local RepositoryFolder = _getRepository(GetSubFolder)
local LibraryCache = _getLibraryCache(RepositoryFolder)
if RunService:IsServer() and not RunService:IsClient() then -- Don't move in SoloTestMode
_replicateRepository(GetSubFolder("Modules"), LibraryCache)
end
local Nevermore = {}
--- Load a library through Nevermore
-- @function LoadLibrary
-- @tparam Variant LibraryName Can either be a ModuleScript or string
-- @treturn Variant Library
Nevermore.LoadLibrary = _asyncCache(_debugLoading(_getLibraryLoader(LibraryCache)))
--- Get a remote event
-- @function GetRemoteEvent
-- @tparam string RemoteEventName
-- @treturn RemoteEvent RemoteEvent
Nevermore.GetRemoteEvent = _asyncCache(_retrieve(GetSubFolder("RemoteEvents"), "RemoteEvent"))
--- Get a remote function
-- @function GetRemoteFunction
-- @tparam string RemoteFunctionName
-- @treturn RemoteFunction RemoteFunction
Nevermore.GetRemoteFunction = _asyncCache(_retrieve(GetSubFolder("RemoteFunctions"), "RemoteFunction"))
setmetatable(Nevermore, {
__call = function(self, ...)
return self.LoadLibrary(...)
end;
__index = function(self, Index)
error(("'%s is not a valid member of Nevermore"):format(tostring(Index)))
end;
})
return Nevermore
|
--- Nevermore module loader.
-- Used to simply resource loading and networking so a more unified server / client codebased can be used
-- @module Nevermore
local DEBUG_MODE = false -- Set to true to help identify what libraries have circular dependencies
local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ServerScriptService = game:GetService("ServerScriptService")
assert(script:IsA("ModuleScript"), "Invalid script type. For NevermoreEngine to work correctly, it should be " ..
"a ModuleScript named \"NevermoreEngine\" parented to ReplicatedStorage")
assert(script.Name == "NevermoreEngine", "Invalid script name. For NevermoreEngine to work correctly, it should be " ..
"a ModuleScript named \"NevermoreEngine\" parented to ReplicatedStorage")
assert(script.Parent == ReplicatedStorage, "Invalid parent. For NevermoreEngine to work correctly, it should be " ..
"a ModuleScript named \"NevermoreEngine\" parented to ReplicatedStorage")
--- Handles yielded operations by caching the retrieval process
local function _handleRetrieving(Retrieving, Function, Argument)
assert(type(Retrieving) == "table", "Error: Retrieving must be a table")
assert(type(Function) == "function", "Error: Function must be a function")
local Signal = Instance.new("BindableEvent")
local Result
Retrieving[Argument] = function()
if Result ~= nil and Result then
return Result
end
Signal.Event:Wait()
return Result
end
Result = Function(Argument)
assert(Result ~= nil, "Result cannot be nil")
Retrieving[Argument] = nil
Signal:Fire()
Signal:Destroy()
return Result
end
--- Caches single argument, single output only
local function _asyncCache(Function)
assert(type(Function) == "function", "Error: Function must be a userdata")
local Cache = {}
local Retrieving = {}
return function(Argument)
assert(Argument ~= nil, "Error: ARgument ")
if Cache[Argument] ~= nil then
return Cache[Argument]
elseif Retrieving[Argument] then
return Retrieving[Argument]()
else
Cache[Argument] = _handleRetrieving(Retrieving, Function, Argument)
return Cache[Argument]
end
end
end
--- Retrieves an instance from a parent
local function _retrieve(Parent, ClassName)
assert(type(ClassName) == "string", "Error: ClassName must be a string")
assert(typeof(Parent) == "Instance", ("Error: Parent must be an Instance, got '%s'"):format(typeof(Parent)))
return RunService:IsServer() and function(Name)
local Item = Parent:FindFirstChild(Name)
if not Item then
Item = Instance.new(ClassName)
Item.Archivable = false
Item.Name = Name
Item.Parent = Parent
end
return Item
end or function(Name)
local Resource = Parent:WaitForChild(Name, 5)
if Resource then
return Resource
end
warn(("Warning: No '%s' found, be sure to require '%s' on the server. Yielding for '%s'")
:format(tostring(Name), tostring(Name), ClassName))
return Parent:WaitForChild(Name)
end
end
local function _getRepository(GetSubFolder)
if RunService:IsServer() then
local RepositoryFolder = ServerScriptService:FindFirstChild("Nevermore")
if not RepositoryFolder then
warn("Warning: No repository of Nevermore modules found (Expected in ServerScriptService with name \"Nevermore\")" ..
". Library retrieval will fail.")
RepositoryFolder = Instance.new("Folder")
RepositoryFolder.Name = "Nevermore"
end
return RepositoryFolder
else
return GetSubFolder("Modules")
end
end
local function _getLibraryCache(RepositoryFolder)
local LibraryCache = {}
for _, Child in pairs(RepositoryFolder:GetDescendants()) do
if Child:IsA("ModuleScript") and not Child:FindFirstAncestorOfClass("ModuleScript") then
if LibraryCache[Child.Name] then
warn(("Warning: Duplicate name of '%s' already exists! Using first found!"):format(Child.Name))
end
LibraryCache[Child.Name] = Child
end
end
return LibraryCache
end
local function _replicateRepository(ReplicationFolder, LibraryCache)
for Name, Library in pairs(LibraryCache) do
if not Name:lower():find("server") then
Library.Parent = ReplicationFolder
end
end
end
local function _debugLoading(Function)
local Count = 0
local RequestDepth = 0
return function(Module, ...)
Count = Count + 1
local LibraryID = Count
if DEBUG_MODE then
print(("\t"):rep(RequestDepth), LibraryID, "Loading: ", Module)
RequestDepth = RequestDepth + 1
end
local Result = Function(Module, ...)
if DEBUG_MODE then
RequestDepth = RequestDepth - 1
print(("\t"):rep(RequestDepth), LibraryID, "Done loading: ", Module)
end
return Result
end
end
local function _getLibraryLoader(LibraryCache)
--- Loads a library from Nevermore's library cache
-- @param Module The name of the library or a module
-- @return The library's value
return function(Module)
if typeof(Module) == "Instance" and Module:IsA("ModuleScript") then
return require(Module)
elseif type(Module) == "string" then
local ModuleScript = LibraryCache[Module] or error("Error: Library '" .. Module .. "' does not exist.", 2)
return require(ModuleScript)
else
error(("Error: Module must be a string or ModuleScript, got '%s'"):format(typeof(Module)))
end
end
end
local ResourceFolder = _retrieve(ReplicatedStorage, "Folder")("NevermoreResources")
local GetSubFolder = _retrieve(ResourceFolder, "Folder")
local RepositoryFolder = _getRepository(GetSubFolder)
local LibraryCache = _getLibraryCache(RepositoryFolder)
if RunService:IsServer() and not RunService:IsClient() then -- Don't move in SoloTestMode
_replicateRepository(GetSubFolder("Modules"), LibraryCache)
end
local Nevermore = {}
--- Load a library through Nevermore
-- @function LoadLibrary
-- @tparam Variant LibraryName Can either be a ModuleScript or string
-- @treturn Variant Library
Nevermore.LoadLibrary = _asyncCache(_debugLoading(_getLibraryLoader(LibraryCache)))
--- Get a remote event
-- @function GetRemoteEvent
-- @tparam string RemoteEventName
-- @treturn RemoteEvent RemoteEvent
Nevermore.GetRemoteEvent = _asyncCache(_retrieve(GetSubFolder("RemoteEvents"), "RemoteEvent"))
--- Get a remote function
-- @function GetRemoteFunction
-- @tparam string RemoteFunctionName
-- @treturn RemoteFunction RemoteFunction
Nevermore.GetRemoteFunction = _asyncCache(_retrieve(GetSubFolder("RemoteFunctions"), "RemoteFunction"))
setmetatable(Nevermore, {
__call = function(self, ...)
return self.LoadLibrary(...)
end;
__index = function(self, Index)
error(("'%s is not a valid member of Nevermore"):format(tostring(Index)))
end;
})
return Nevermore
|
Fix formatting issues with NevermoreEngine
|
Fix formatting issues with NevermoreEngine
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
a41d3db1455677741d04b298cb4f2b4ece5f629a
|
core/sessionmanager.lua
|
core/sessionmanager.lua
|
local tonumber, tostring = tonumber, tostring;
local ipairs, pairs, print= ipairs, pairs, print;
local collectgarbage = collectgarbage;
local m_random = import("math", "random");
local format = import("string", "format");
local hosts = hosts;
local sessions = sessions;
local modulemanager = require "core.modulemanager";
local log = require "util.logger".init("sessionmanager");
local error = error;
local uuid_generate = require "util.uuid".uuid_generate;
local newproxy = newproxy;
local getmetatable = getmetatable;
module "sessionmanager"
function new_session(conn)
local session = { conn = conn, notopen = true, priority = 0, type = "c2s_unauthed" };
if true then
session.trace = newproxy(true);
getmetatable(session.trace).__gc = function () print("Session got collected") end;
end
local w = conn.write;
session.send = function (t) w(tostring(t)); end
return session;
end
function destroy_session(session)
if not (session and session.disconnect) then return; end
log("debug", "Destroying session...");
session.disconnect();
if session.username then
if session.resource then
hosts[session.host].sessions[session.username].sessions[session.resource] = nil;
end
local nomore = true;
for res, ssn in pairs(hosts[session.host].sessions[session.username]) do
nomore = false;
end
if nomore then
hosts[session.host].sessions[session.username] = nil;
end
end
session.conn = nil;
session.disconnect = nil;
for k in pairs(session) do
if k ~= "trace" then
session[k] = nil;
end
end
collectgarbage("collect");
collectgarbage("collect");
collectgarbage("collect");
collectgarbage("collect");
collectgarbage("collect");
end
function send_to_session(session, data)
log("debug", "Sending: %s", tostring(data));
session.conn.write(tostring(data));
end
function make_authenticated(session, username)
session.username = username;
session.resource = resource;
if session.type == "c2s_unauthed" then
session.type = "c2s";
end
return true;
end
function bind_resource(session, resource)
if not session.username then return false, "auth"; end
if session.resource then return false, "constraint"; end -- We don't support binding multiple resources
resource = resource or uuid_generate();
--FIXME: Randomly-generated resources must be unique per-user, and never conflict with existing
if not hosts[session.host].sessions[session.username] then
hosts[session.host].sessions[session.username] = { sessions = {} };
else
if hosts[session.host].sessions[session.username].sessions[resource] then
-- Resource conflict
return false, "conflict";
end
end
session.resource = resource;
session.full_jid = session.username .. '@' .. session.host .. '/' .. resource;
hosts[session.host].sessions[session.username].sessions[resource] = session;
return true;
end
function streamopened(session, attr)
local send = session.send;
session.host = attr.to or error("Client failed to specify destination hostname");
session.version = tonumber(attr.version) or 0;
session.streamid = m_random(1000000, 99999999);
print(session, session.host, "Client opened stream");
send("<?xml version='1.0'?>");
send(format("<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' id='%s' from='%s' version='1.0'>", session.streamid, session.host));
local features = {};
modulemanager.fire_event("stream-features", session, features);
send("<stream:features>");
for _, feature in ipairs(features) do
send_to_session(session, tostring(feature));
end
send("</stream:features>");
log("info", "Stream opened successfully");
session.notopen = nil;
end
return _M;
|
local tonumber, tostring = tonumber, tostring;
local ipairs, pairs, print= ipairs, pairs, print;
local collectgarbage = collectgarbage;
local m_random = import("math", "random");
local format = import("string", "format");
local hosts = hosts;
local sessions = sessions;
local modulemanager = require "core.modulemanager";
local log = require "util.logger".init("sessionmanager");
local error = error;
local uuid_generate = require "util.uuid".uuid_generate;
local newproxy = newproxy;
local getmetatable = getmetatable;
module "sessionmanager"
function new_session(conn)
local session = { conn = conn, notopen = true, priority = 0, type = "c2s_unauthed" };
if true then
session.trace = newproxy(true);
getmetatable(session.trace).__gc = function () print("Session got collected") end;
end
local w = conn.write;
session.send = function (t) w(tostring(t)); end
return session;
end
function destroy_session(session)
if not (session and session.disconnect) then return; end
log("debug", "Destroying session...");
session.disconnect();
if session.username then
if session.resource then
hosts[session.host].sessions[session.username].sessions[session.resource] = nil;
end
local nomore = true;
for res, ssn in pairs(hosts[session.host].sessions[session.username]) do
nomore = false;
end
if nomore then
hosts[session.host].sessions[session.username] = nil;
end
end
session.conn = nil;
session.disconnect = nil;
for k in pairs(session) do
if k ~= "trace" then
session[k] = nil;
end
end
collectgarbage("collect");
collectgarbage("collect");
collectgarbage("collect");
collectgarbage("collect");
collectgarbage("collect");
end
function send_to_session(session, data)
log("debug", "Sending: %s", tostring(data));
session.conn.write(tostring(data));
end
function make_authenticated(session, username)
session.username = username;
if session.type == "c2s_unauthed" then
session.type = "c2s";
end
return true;
end
function bind_resource(session, resource)
if not session.username then return false, "auth"; end
if session.resource then return false, "constraint"; end -- We don't support binding multiple resources
resource = resource or uuid_generate();
--FIXME: Randomly-generated resources must be unique per-user, and never conflict with existing
if not hosts[session.host].sessions[session.username] then
hosts[session.host].sessions[session.username] = { sessions = {} };
else
if hosts[session.host].sessions[session.username].sessions[resource] then
-- Resource conflict
return false, "conflict";
end
end
session.resource = resource;
session.full_jid = session.username .. '@' .. session.host .. '/' .. resource;
hosts[session.host].sessions[session.username].sessions[resource] = session;
return true;
end
function streamopened(session, attr)
local send = session.send;
session.host = attr.to or error("Client failed to specify destination hostname");
session.version = tonumber(attr.version) or 0;
session.streamid = m_random(1000000, 99999999);
print(session, session.host, "Client opened stream");
send("<?xml version='1.0'?>");
send(format("<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' id='%s' from='%s' version='1.0'>", session.streamid, session.host));
local features = {};
modulemanager.fire_event("stream-features", session, features);
send("<stream:features>");
for _, feature in ipairs(features) do
send_to_session(session, tostring(feature));
end
send("</stream:features>");
log("info", "Stream opened successfully");
session.notopen = nil;
end
return _M;
|
Fix setting resource before we even know what it is
|
Fix setting resource before we even know what it is
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
a3a72ec955e2666e17f97b2063513c1e177c412b
|
Modules/Server/DataStore/DataStore.lua
|
Modules/Server/DataStore/DataStore.lua
|
--- Wraps the datastore object to provide async cached loading and saving
-- @classmod DataStore
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local DataStoreStage = require("DataStoreStage")
local DataStorePromises = require("DataStorePromises")
local Promise = require("Promise")
local Maid = require("Maid")
local Signal = require("Signal")
local DataStore = setmetatable({}, DataStoreStage)
DataStore.ClassName = "DataStore"
DataStore.__index = DataStore
function DataStore.new(robloxDataStore, key)
local self = setmetatable(DataStoreStage.new(), DataStore)
self._key = key or error("No key")
self._robloxDataStore = robloxDataStore or error("No robloxDataStore")
self.Saving = Signal.new() -- :Fire(promise)
return self
end
function DataStore:DidLoadFail()
if not self._loadPromise then
return false
end
if self._loadPromise:IsRejected() then
return true
end
return false
end
function DataStore:PromiseLoadSuccessful()
return self._maid:GivePromise(self:_promiseLoad()):Then(function()
return true
end):Catch(function()
return false
end)
end
-- Saves all stored data
function DataStore:Save()
if self:DidLoadFail() then
warn("[DataStore] - Not saving, failed to load")
return Promise.rejected("Load not successful, not saving")
end
if not self:HasWritableData() then
-- Nothing to save, don't update anything
print("[DataStore.Save] - Not saving, nothing staged")
return Promise.fulfilled(nil)
end
return self:_saveData(self:GetNewWriter())
end
-- Loads data. This returns the originally loaded data.
function DataStore:Load(name, defaultValue)
return self:_promiseLoad()
:Then(function(data)
if data[name] == nil then
return defaultValue
else
return data[name]
end
end)
end
function DataStore:_saveData(writer)
local maid = Maid.new()
local promise;
promise = DataStorePromises.UpdateAsync(self._robloxDataStore, self._key, function(data)
if promise:IsRejected() then
-- Cancel if we're already overwritten
return nil
end
data = data or {}
writer:WriteMerge(data)
return data
end):Catch(function(err)
warn("[DataStore] - Failed to UpdateAsync data", err)
end)
maid:GivePromise(promise)
self._maid._saveMaid = maid
self.Saving:Fire(promise)
return promise
end
function DataStore:_promiseLoad()
if self._loadPromise then
return self._loadPromise
end
self._loadPromise = DataStorePromises.GetAsync(self._robloxDataStore, self._key):Then(function(data)
if data == nil then
return {}
elseif type(data) == "table" then
return data
else
return Promise.rejected("Failed to load data. Wrong type '" .. type(data) .. "'")
end
end):Catch(function(err)
warn("[DataStore] - Failed to GetAsync data", err)
end)
self._maid:GivePromise(self._loadPromise)
return self._loadPromise
end
return DataStore
|
--- Wraps the datastore object to provide async cached loading and saving
-- @classmod DataStore
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local DataStoreStage = require("DataStoreStage")
local DataStorePromises = require("DataStorePromises")
local Promise = require("Promise")
local Maid = require("Maid")
local Signal = require("Signal")
local DataStore = setmetatable({}, DataStoreStage)
DataStore.ClassName = "DataStore"
DataStore.__index = DataStore
function DataStore.new(robloxDataStore, key)
local self = setmetatable(DataStoreStage.new(), DataStore)
self._key = key or error("No key")
self._robloxDataStore = robloxDataStore or error("No robloxDataStore")
self.Saving = Signal.new() -- :Fire(promise)
return self
end
function DataStore:DidLoadFail()
if not self._loadPromise then
return false
end
if self._loadPromise:IsRejected() then
return true
end
return false
end
function DataStore:PromiseLoadSuccessful()
return self._maid:GivePromise(self:_promiseLoad()):Then(function()
return true
end):Catch(function()
return false
end)
end
-- Saves all stored data
function DataStore:Save()
if self:DidLoadFail() then
warn("[DataStore] - Not saving, failed to load")
return Promise.rejected("Load not successful, not saving")
end
if not self:HasWritableData() then
-- Nothing to save, don't update anything
print("[DataStore.Save] - Not saving, nothing staged")
return Promise.fulfilled(nil)
end
return self:_saveData(self:GetNewWriter())
end
-- Loads data. This returns the originally loaded data.
function DataStore:Load(name, defaultValue)
return self:_promiseLoad()
:Then(function(data)
if data[name] == nil then
return defaultValue
else
return data[name]
end
end)
end
function DataStore:_saveData(writer)
local maid = Maid.new()
local promise
promise = maid:GivePromise(DataStorePromises.UpdateAsync(self._robloxDataStore, self._key, function(data)
if promise:IsRejected() then
-- Cancel if we're already overwritten
return nil
end
data = data or {}
writer:WriteMerge(data)
return data
end):Catch(function(err)
-- Might be caused by Maid rejecting state
warn("[DataStore] - Failed to UpdateAsync data", err)
return Promise.rejected(err)
end))
self._maid._saveMaid = maid
self.Saving:Fire(promise)
return promise
end
function DataStore:_promiseLoad()
if self._loadPromise then
return self._loadPromise
end
self._loadPromise = DataStorePromises.GetAsync(self._robloxDataStore, self._key):Then(function(data)
if data == nil then
return {}
elseif type(data) == "table" then
return data
else
return Promise.rejected("Failed to load data. Wrong type '" .. type(data) .. "'")
end
end):Catch(function(err)
warn("[DataStore] - Failed to GetAsync data", err)
end)
self._maid:GivePromise(self._loadPromise)
return self._loadPromise
end
return DataStore
|
Fix loader state returns
|
Fix loader state returns
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
9425cf4d6b7384c0bde9784de60a0526869c9f86
|
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
|
1st8/prosody-modules,olax/prosody-modules,stephen322/prosody-modules,NSAKEY/prosody-modules,either1/prosody-modules,guilhem/prosody-modules,mmusial/prosody-modules,mmusial/prosody-modules,mardraze/prosody-modules,LanceJenkinZA/prosody-modules,BurmistrovJ/prosody-modules,Craige/prosody-modules,BurmistrovJ/prosody-modules,stephen322/prosody-modules,jkprg/prosody-modules,iamliqiang/prosody-modules,asdofindia/prosody-modules,vince06fr/prosody-modules,either1/prosody-modules,BurmistrovJ/prosody-modules,vince06fr/prosody-modules,cryptotoad/prosody-modules,dhotson/prosody-modules,prosody-modules/import,dhotson/prosody-modules,amenophis1er/prosody-modules,brahmi2/prosody-modules,1st8/prosody-modules,vince06fr/prosody-modules,joewalker/prosody-modules,NSAKEY/prosody-modules,either1/prosody-modules,syntafin/prosody-modules,amenophis1er/prosody-modules,vfedoroff/prosody-modules,softer/prosody-modules,NSAKEY/prosody-modules,brahmi2/prosody-modules,LanceJenkinZA/prosody-modules,Craige/prosody-modules,1st8/prosody-modules,asdofindia/prosody-modules,guilhem/prosody-modules,amenophis1er/prosody-modules,syntafin/prosody-modules,jkprg/prosody-modules,guilhem/prosody-modules,syntafin/prosody-modules,drdownload/prosody-modules,brahmi2/prosody-modules,jkprg/prosody-modules,apung/prosody-modules,dhotson/prosody-modules,vfedoroff/prosody-modules,drdownload/prosody-modules,joewalker/prosody-modules,LanceJenkinZA/prosody-modules,prosody-modules/import,guilhem/prosody-modules,amenophis1er/prosody-modules,NSAKEY/prosody-modules,obelisk21/prosody-modules,vince06fr/prosody-modules,softer/prosody-modules,prosody-modules/import,asdofindia/prosody-modules,olax/prosody-modules,either1/prosody-modules,crunchuser/prosody-modules,iamliqiang/prosody-modules,asdofindia/prosody-modules,softer/prosody-modules,mmusial/prosody-modules,LanceJenkinZA/prosody-modules,apung/prosody-modules,stephen322/prosody-modules,obelisk21/prosody-modules,heysion/prosody-modules,iamliqiang/prosody-modules,dhotson/prosody-modules,amenophis1er/prosody-modules,olax/prosody-modules,Craige/prosody-modules,syntafin/prosody-modules,prosody-modules/import,1st8/prosody-modules,dhotson/prosody-modules,drdownload/prosody-modules,cryptotoad/prosody-modules,cryptotoad/prosody-modules,brahmi2/prosody-modules,Craige/prosody-modules,iamliqiang/prosody-modules,brahmi2/prosody-modules,stephen322/prosody-modules,BurmistrovJ/prosody-modules,heysion/prosody-modules,crunchuser/prosody-modules,softer/prosody-modules,mardraze/prosody-modules,drdownload/prosody-modules,cryptotoad/prosody-modules,mardraze/prosody-modules,apung/prosody-modules,iamliqiang/prosody-modules,jkprg/prosody-modules,jkprg/prosody-modules,obelisk21/prosody-modules,prosody-modules/import,cryptotoad/prosody-modules,syntafin/prosody-modules,mmusial/prosody-modules,Craige/prosody-modules,olax/prosody-modules,vfedoroff/prosody-modules,softer/prosody-modules,olax/prosody-modules,obelisk21/prosody-modules,crunchuser/prosody-modules,NSAKEY/prosody-modules,mardraze/prosody-modules,heysion/prosody-modules,guilhem/prosody-modules,apung/prosody-modules,stephen322/prosody-modules,crunchuser/prosody-modules,BurmistrovJ/prosody-modules,either1/prosody-modules,LanceJenkinZA/prosody-modules,obelisk21/prosody-modules,joewalker/prosody-modules,heysion/prosody-modules,vfedoroff/prosody-modules,mmusial/prosody-modules,joewalker/prosody-modules,vfedoroff/prosody-modules,1st8/prosody-modules,crunchuser/prosody-modules,mardraze/prosody-modules,asdofindia/prosody-modules,apung/prosody-modules,vince06fr/prosody-modules,drdownload/prosody-modules,heysion/prosody-modules,joewalker/prosody-modules
|
2f6180fdc635cae1b5b3c7435a8d87620f38bfca
|
testserver/base/keys.lua
|
testserver/base/keys.lua
|
require("base.doors")
module("base.keys", package.seeall)
--[[
LockDoor
Lock a door. This function checks if that item is a closed on that can be
locked.
It does not check if the player has a fitting key.
@param ItemStruct - the item that is the closed door that shall be locked
@return boolean - true in case the door got locked, false if anything went
wrong
]]
function LockDoor(Door)
if base.doors.CheckClosedDoor(Door.id) then
if (Door.quality == 233 and Door:getData("lockData") ~= nil) then
Door.quality = 333;
world:changeItem(Door);
world:makeSound(19, Door.pos);
return true;
end;
end;
return false;
end;
--[[
UnlockDoor
Unlock a door. This function checks if the item is a closed locked door and
unlocks it.
It does not check if the player has a fitting key.
@param ItemStruct - the item that is the closed door that shall be unlocked
@return boolean - true in case the door got locked, false if anything went
wrong
]]
function UnlockDoor(Door)
if base.doors.CheckClosedDoor(Door.id) then
if (Door.quality ~= 233 and Door:getData("lockData") ~= nil) then
Door.quality = 233;
world:changeItem(Door);
world:makeSound(20, Door.pos);
return true;
end;
end;
return false;
end;
--[[
CheckKey
Check if a key fits into a door. This function does not check if the item is
really a key. It assumes that it is one and checks the lock that is encoded
in the data value.
How ever it checks if the door item is a opened or a closed door.
@param ItemStruct - the item that is the key for a door
@param ItemStruct - the item that is the door that shall be checked
@return boolean - true in case the key item would fit to the door, false if
it does not fit
]]
function CheckKey(Key, Door)
if base.doors.CheckClosedDoor(Door.id) or base.doors.CheckOpenDoor(Door.id) then
if (Key:getData("lockData") == Door:getData("lockData") and Door:getData("lockData") ~= nil) then
return true;
else
return false;
end;
else
return false;
end;
end;
|
require("base.doors")
module("base.keys", package.seeall)
--[[
LockDoor
Lock a door. This function checks if that item is a closed on that can be
locked.
It does not check if the player has a fitting key.
@param ItemStruct - the item that is the closed door that shall be locked
@return boolean - true in case the door got locked, false if anything went
wrong
]]
function LockDoor(Door)
if base.doors.CheckClosedDoor(Door.id) then
if (Door.quality == 233 and Door:getData("lockData") ~= nil) then
Door.quality = 333;
world:changeItem(Door);
world:makeSound(19, Door.pos);
return true;
else
return false;
end;
else
return false;
end;
return false;
end;
--[[
UnlockDoor
Unlock a door. This function checks if the item is a closed locked door and
unlocks it.
It does not check if the player has a fitting key.
@param ItemStruct - the item that is the closed door that shall be unlocked
@return boolean - true in case the door got locked, false if anything went
wrong
]]
function UnlockDoor(Door)
if base.doors.CheckClosedDoor(Door.id) then
if (Door.quality ~= 233 and Door:getData("lockData") ~= nil) then
Door.quality = 233;
world:changeItem(Door);
world:makeSound(20, Door.pos);
return true;
else
return false;
end;
else
return false;
end;
return false;
end;
--[[
CheckKey
Check if a key fits into a door. This function does not check if the item is
really a key. It assumes that it is one and checks the lock that is encoded
in the data value.
How ever it checks if the door item is a opened or a closed door.
@param ItemStruct - the item that is the key for a door
@param ItemStruct - the item that is the door that shall be checked
@return boolean - true in case the key item would fit to the door, false if
it does not fit
]]
function CheckKey(Key, Door)
if base.doors.CheckClosedDoor(Door.id) or base.doors.CheckOpenDoor(Door.id) then
if (Key:getData("lockData") == Door:getData("lockData") and Door:getData("lockData") ~= nil) then
return true;
else
return false;
end;
else
return false;
end;
end;
|
fixed unlocking of doors
|
fixed unlocking of doors
|
Lua
|
agpl-3.0
|
KayMD/Illarion-Content,Illarion-eV/Illarion-Content,LaFamiglia/Illarion-Content,Baylamon/Illarion-Content,vilarion/Illarion-Content
|
31b95fcae2db7d151a0f486da7d7151bc2731a12
|
mod_storage_gdbm/mod_storage_gdbm.lua
|
mod_storage_gdbm/mod_storage_gdbm.lua
|
-- mod_storage_gdbm
-- Copyright (C) 2014-2015 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 st = require"util.stanza";
local uuid = require"util.uuid".generate;
local serialization = require"util.serialization";
local serialize = serialization.serialize;
local deserialize = serialization.deserialize;
local g_set, g_get, g_del = gdbm.replace, gdbm.fetch, gdbm.delete;
local g_first, g_next = gdbm.firstkey, gdbm.nextkey;
local t_remove = table.remove;
local empty = {};
local function id(v) return v; end
local function is_stanza(s)
return getmetatable(s) == st.stanza_mt;
end
local function t(c, a, b)
if c then return a; end return b;
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)
if type(value) == "table" and next(value) == nil then
value = nil;
end
if value ~= nil then
value = serialize(value);
end
local ok, err = (value and g_set or g_del)(self._db, user or "@", value);
if not ok then return nil, err; end
return true;
end
function keyval:get(user)
local data, err = g_get(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(key, value);
if not ok then return nil, err; end
ok, err = self:set(username, meta);
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 = t(r, -1, 1);
local s = meta[t(r, query.before, query.after)];
local limit = query.limit;
if s then
s = s + d;
else
s = t(r, #meta, 1)
end
local e = t(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-2015 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 st = require"util.stanza";
local uuid = require"util.uuid".generate;
local serialization = require"util.serialization";
local serialize = serialization.serialize;
local deserialize = serialization.deserialize;
local g_set, g_get, g_del = gdbm.replace, gdbm.fetch, gdbm.delete;
local g_first, g_next = gdbm.firstkey, gdbm.nextkey;
local t_remove = table.remove;
local empty = {};
local function id(v) return v; end
local function is_stanza(s)
return getmetatable(s) == st.stanza_mt;
end
local function t(c, a, b)
if c then return a; end return b;
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)
if type(value) == "table" and next(value) == nil then
value = nil;
end
if value ~= nil then
value = serialize(value);
end
local ok, err = (value and g_set or g_del)(self._db, user or "@", value);
if not ok then return nil, err; end
return true;
end
function keyval:get(user)
local data, err = g_get(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 prefix = (username or "@") .. "#";
local ok, err = self:set(prefix..key, value);
if not ok then return nil, err; end
ok, err = self:set(username, meta);
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 prefix = (username or "@") .. "#";
local r = query.reverse;
local d = t(r, -1, 1);
local s = meta[t(r, query.before, query.after)];
local limit = query.limit;
if s then
s = s + d;
else
s = t(r, #meta, 1)
end
local e = t(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(prefix..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: Prefix archive item keys with username to prevent collisions
|
mod_storage_gdbm: Prefix archive item keys with username to prevent collisions
|
Lua
|
mit
|
either1/prosody-modules,mardraze/prosody-modules,NSAKEY/prosody-modules,drdownload/prosody-modules,joewalker/prosody-modules,guilhem/prosody-modules,jkprg/prosody-modules,Craige/prosody-modules,heysion/prosody-modules,stephen322/prosody-modules,cryptotoad/prosody-modules,guilhem/prosody-modules,joewalker/prosody-modules,apung/prosody-modules,mmusial/prosody-modules,LanceJenkinZA/prosody-modules,stephen322/prosody-modules,softer/prosody-modules,BurmistrovJ/prosody-modules,heysion/prosody-modules,obelisk21/prosody-modules,stephen322/prosody-modules,either1/prosody-modules,guilhem/prosody-modules,cryptotoad/prosody-modules,asdofindia/prosody-modules,heysion/prosody-modules,brahmi2/prosody-modules,mmusial/prosody-modules,LanceJenkinZA/prosody-modules,prosody-modules/import,BurmistrovJ/prosody-modules,amenophis1er/prosody-modules,jkprg/prosody-modules,syntafin/prosody-modules,brahmi2/prosody-modules,syntafin/prosody-modules,mardraze/prosody-modules,drdownload/prosody-modules,prosody-modules/import,prosody-modules/import,heysion/prosody-modules,obelisk21/prosody-modules,asdofindia/prosody-modules,mmusial/prosody-modules,olax/prosody-modules,jkprg/prosody-modules,iamliqiang/prosody-modules,prosody-modules/import,NSAKEY/prosody-modules,iamliqiang/prosody-modules,vince06fr/prosody-modules,heysion/prosody-modules,apung/prosody-modules,olax/prosody-modules,softer/prosody-modules,dhotson/prosody-modules,crunchuser/prosody-modules,drdownload/prosody-modules,Craige/prosody-modules,Craige/prosody-modules,vince06fr/prosody-modules,softer/prosody-modules,mmusial/prosody-modules,crunchuser/prosody-modules,asdofindia/prosody-modules,Craige/prosody-modules,BurmistrovJ/prosody-modules,guilhem/prosody-modules,brahmi2/prosody-modules,prosody-modules/import,LanceJenkinZA/prosody-modules,vfedoroff/prosody-modules,either1/prosody-modules,dhotson/prosody-modules,mardraze/prosody-modules,mardraze/prosody-modules,syntafin/prosody-modules,amenophis1er/prosody-modules,apung/prosody-modules,softer/prosody-modules,obelisk21/prosody-modules,Craige/prosody-modules,drdownload/prosody-modules,crunchuser/prosody-modules,mardraze/prosody-modules,vfedoroff/prosody-modules,jkprg/prosody-modules,vfedoroff/prosody-modules,obelisk21/prosody-modules,cryptotoad/prosody-modules,jkprg/prosody-modules,stephen322/prosody-modules,dhotson/prosody-modules,stephen322/prosody-modules,either1/prosody-modules,syntafin/prosody-modules,amenophis1er/prosody-modules,1st8/prosody-modules,1st8/prosody-modules,dhotson/prosody-modules,obelisk21/prosody-modules,NSAKEY/prosody-modules,joewalker/prosody-modules,dhotson/prosody-modules,apung/prosody-modules,vince06fr/prosody-modules,brahmi2/prosody-modules,BurmistrovJ/prosody-modules,vfedoroff/prosody-modules,joewalker/prosody-modules,LanceJenkinZA/prosody-modules,crunchuser/prosody-modules,amenophis1er/prosody-modules,softer/prosody-modules,asdofindia/prosody-modules,either1/prosody-modules,vince06fr/prosody-modules,apung/prosody-modules,olax/prosody-modules,NSAKEY/prosody-modules,1st8/prosody-modules,guilhem/prosody-modules,BurmistrovJ/prosody-modules,iamliqiang/prosody-modules,amenophis1er/prosody-modules,iamliqiang/prosody-modules,1st8/prosody-modules,1st8/prosody-modules,joewalker/prosody-modules,LanceJenkinZA/prosody-modules,brahmi2/prosody-modules,NSAKEY/prosody-modules,syntafin/prosody-modules,crunchuser/prosody-modules,cryptotoad/prosody-modules,drdownload/prosody-modules,olax/prosody-modules,vfedoroff/prosody-modules,mmusial/prosody-modules,vince06fr/prosody-modules,cryptotoad/prosody-modules,olax/prosody-modules,iamliqiang/prosody-modules,asdofindia/prosody-modules
|
89b40cb5bcbfd70f58e4a9ca7f4c69b09864f931
|
main.lua
|
main.lua
|
io.stdout:setvbuf("no")
love.graphics.setDefaultFilter("nearest")
api = require("api") --I STILL WANT IT AS A GLOBAL !
local utf8 = require("utf8")
local debugrun = false
function love.mousepressed(x,y,button,istouch)
local x,y = _ScreenToLiko(x,y) if x < 0 or x > 192 or y < 0 or y > 128 then return end
_auto_mpress(x,y,button,istouch)
end
function love.mousemoved(x,y,dx,dy,istouch)
local x, y = _ScreenToLiko(x,y) if x < 0 or x > 192 or y < 0 or y > 128 then return end
_auto_mmove(x,y,dx,dy,istouch)
end
function love.mousereleased(x,y,button,istouch)
local x, y = _ScreenToLiko(x,y) if x < 0 or x > 192 or y < 0 or y > 128 then return end
_auto_mrelease(x,y,button,istouch)
end
function love.wheelmoved(x,y)
_auto_mmove(x,y,0,0,false,true) --Mouse button 0 is the wheel
end
function love.touchpressed(id,x,y,dx,dy,pressure)
local x, y = _ScreenToLiko(x,y) if x < 0 or x > 192 or y < 0 or y > 128 then return end
_auto_tpress(id,x,y,pressure)
end
function love.touchmoved(id,x,y,dx,dy,pressure)
local x, y = _ScreenToLiko(x,y) if x < 0 or x > 192 or y < 0 or y > 128 then return end
_auto_tmove(id,x,y,pressure)
end
function love.touchreleased(id,x,y,dx,dy,pressure)
local x, y = _ScreenToLiko(x,y) if x < 0 or x > 192 or y < 0 or y > 128 then return end
_auto_trelease(id,x,y,pressure)
end
function love.keypressed(key,scancode,isrepeat)
_auto_kpress(key,scancode,isrepeat)
end
function love.keyreleased(key,scancode)
_auto_krelease(key,scancode)
end
function love.textinput(text)
local text_escaped = text:gsub("[%(%)%.%%%+%-%*%?%[%]%^%$]", "%%%1")
if #text == 1 and _FontChars:find(text_escaped) then
_auto_tinput(text)
end
end
--Internal Callbacks--
function love.load()
--love.keyboard.setTextInput(true)
if not love.filesystem.exists("/data/") then love.filesystem.createDirectory("/data/") end
if not love.filesystem.exists("/data/demos/") then
love.filesystem.createDirectory("/data/demos/")
for k, demo in ipairs(love.filesystem.getDirectoryItems("/demos/")) do
api.fs.write("/demos/"..demo,love.filesystem.read("/demos/"..demo))
end
end
api.loadDefaultCursors()
_ScreenCanvas = love.graphics.newCanvas(192,128)
_ScreenCanvas:setFilter("nearest")
love.graphics.clear(0,0,0,255)
love.graphics.setCanvas(_ScreenCanvas)
love.graphics.clear(0,0,0,255)
love.graphics.translate(_ScreenTX,_ScreenTY)
love.resize(love.graphics.getDimensions())
love.graphics.setLineStyle("rough")
love.graphics.setLineJoin("miter")
love.graphics.setFont(_Font)
api.clear() --Clear the canvas for the first time
api.stroke(1)
if debugrun then
require("debugrun")
else
require("autorun")
end
_auto_init()
end
function love.resize(w,h)
_ScreenWidth, _ScreenHeight = w, h
local TSX, TSY = w/192, h/128 --TestScaleX, TestScaleY
if TSX < TSY then
_ScreenScaleX, _ScreenScaleY, _ScreenScale = w/192, w/192, w/192
_ScreenX, _ScreenY = 0, (_ScreenHeight-128*_ScreenScaleY)/2
else
_ScreenScaleX, _ScreenScaleY, _ScreenScale = h/128, h/128, h/128
_ScreenX, _ScreenY = (_ScreenWidth-192*_ScreenScaleX)/2, 0
end
api.clearCursorsCache()
_ShouldDraw = true
end
function love.update(dt)
local mx, my = _ScreenToLiko(love.mouse.getPosition())
love.window.setTitle(_ScreenTitle.." FPS: "..love.timer.getFPS().." ShouldDraw: "..(_ForceDraw and "FORCE" or (_ShouldDraw and "Yes" or "No")).." MX, MY: "..mx..","..my)
_auto_update(dt)
end
function love.visible(v)
_ForceDraw = not v
_ShouldDraw = v
end
function love.focus(f)
_ForceDraw = not f
_ShouldDraw = f
end
function love.run()
if love.math then
love.math.setRandomSeed(os.time())
end
if love.load then love.load(arg) end
-- We don't want the first frame's dt to include time taken by love.load.
if love.timer then love.timer.step() end
local dt = 0
-- Main loop time.
while true do
-- Process events.
if love.event then
love.event.pump()
for name, a,b,c,d,e,f in love.event.poll() do
if name == "quit" then
if not love.quit or not love.quit() then
return a
end
end
love.handlers[name](a,b,c,d,e,f)
end
end
-- Update dt, as we'll be passing it to update
if love.timer then
love.timer.step()
dt = love.timer.getDelta()
end
-- Call update and draw
if love.update then love.update(dt) end -- will pass 0 if love.timer is disabled
if love.graphics and love.graphics.isActive() and (_ShouldDraw or _ForceDraw) then
love.graphics.setCanvas()
love.graphics.origin()
love.graphics.setColor(255,255,255)
love.graphics.draw(_ScreenCanvas, _ScreenX,_ScreenY, 0, _ScreenScaleX,_ScreenScaleY)
--love.graphics.api.points(1,1,_ScreenWidth,_ScreenHeight)
love.graphics.present()
love.graphics.setCanvas(_ScreenCanvas)
love.graphics.translate(_ScreenTX,_ScreenTY)
_ShouldDraw = false
end
if love.timer then love.timer.sleep(0.001) end
end
end
|
io.stdout:setvbuf("no")
love.graphics.setDefaultFilter("nearest")
api = require("api") --I STILL WANT IT AS A GLOBAL !
local utf8 = require("utf8")
local debugrun = false
function love.mousepressed(x,y,button,istouch)
local x,y = _ScreenToLiko(x,y) if x < 0 or x > 192 or y < 0 or y > 128 then return end
_auto_mpress(x,y,button,istouch)
end
function love.mousemoved(x,y,dx,dy,istouch)
local x, y = _ScreenToLiko(x,y) if x < 0 or x > 192 or y < 0 or y > 128 then return end
_auto_mmove(x,y,dx,dy,istouch)
end
function love.mousereleased(x,y,button,istouch)
local x, y = _ScreenToLiko(x,y) if x < 0 or x > 192 or y < 0 or y > 128 then return end
_auto_mrelease(x,y,button,istouch)
end
function love.wheelmoved(x,y)
_auto_mmove(x,y,0,0,false,true) --Mouse button 0 is the wheel
end
function love.touchpressed(id,x,y,dx,dy,pressure)
local x, y = _ScreenToLiko(x,y) if x < 0 or x > 192 or y < 0 or y > 128 then return end
_auto_tpress(id,x,y,pressure)
end
function love.touchmoved(id,x,y,dx,dy,pressure)
local x, y = _ScreenToLiko(x,y) if x < 0 or x > 192 or y < 0 or y > 128 then return end
_auto_tmove(id,x,y,pressure)
end
function love.touchreleased(id,x,y,dx,dy,pressure)
local x, y = _ScreenToLiko(x,y) if x < 0 or x > 192 or y < 0 or y > 128 then return end
_auto_trelease(id,x,y,pressure)
end
function love.keypressed(key,scancode,isrepeat)
_auto_kpress(key,scancode,isrepeat)
end
function love.keyreleased(key,scancode)
_auto_krelease(key,scancode)
end
function love.textinput(text)
local text_escaped = text:gsub("[%(%)%.%%%+%-%*%?%[%]%^%$]", "%%%1")
if #text == 1 and _FontChars:find(text_escaped) then
_auto_tinput(text)
end
end
--Internal Callbacks--
function love.load()
--love.keyboard.setTextInput(true)
if not love.filesystem.exists("/data/") then love.filesystem.createDirectory("/data/") end
if not love.filesystem.exists("/data/demos/") then
love.filesystem.createDirectory("/data/demos/")
for k, demo in ipairs(love.filesystem.getDirectoryItems("/demos/")) do
api.fs.write("/demos/"..demo,love.filesystem.read("/demos/"..demo))
end
end
api.loadDefaultCursors()
_ScreenCanvas = love.graphics.newCanvas(192,128)
_ScreenCanvas:setFilter("nearest")
love.graphics.clear(0,0,0,255)
love.graphics.setCanvas(_ScreenCanvas)
love.graphics.clear(0,0,0,255)
love.graphics.translate(_ScreenTX,_ScreenTY)
love.resize(love.graphics.getDimensions())
love.graphics.setLineStyle("rough")
love.graphics.setLineJoin("miter")
love.graphics.setFont(_Font)
api.clear() --Clear the canvas for the first time
api.stroke(1)
if debugrun then
require("debugrun")
else
require("autorun")
end
_auto_init()
end
function love.resize(w,h)
_ScreenWidth, _ScreenHeight = w, h
local TSX, TSY = w/192, h/128 --TestScaleX, TestScaleY
if TSX < TSY then
_ScreenScaleX, _ScreenScaleY, _ScreenScale = w/192, w/192, w/192
_ScreenX, _ScreenY = 0, (_ScreenHeight-128*_ScreenScaleY)/2
else
_ScreenScaleX, _ScreenScaleY, _ScreenScale = h/128, h/128, h/128
_ScreenX, _ScreenY = (_ScreenWidth-192*_ScreenScaleX)/2, 0
end
api.clearCursorsCache()
_ShouldDraw = true
end
function love.update(dt)
local mx, my = _ScreenToLiko(love.mouse.getPosition())
love.window.setTitle(_ScreenTitle.." FPS: "..love.timer.getFPS().." ShouldDraw: "..(_ForceDraw and "FORCE" or (_ShouldDraw and "Yes" or "No")).." MX, MY: "..mx..","..my)
_auto_update(dt)
end
function love.visible(v)
_ForceDraw = not v
_ShouldDraw = v
end
function love.focus(f)
_ForceDraw = not f
_ShouldDraw = f
end
function love.run()
if love.math then
love.math.setRandomSeed(os.time())
end
if love.load then love.load(arg) end
-- We don't want the first frame's dt to include time taken by love.load.
if love.timer then love.timer.step() end
local dt = 0
-- Main loop time.
while true do
-- Process events.
if love.event then
love.event.pump()
for name, a,b,c,d,e,f in love.event.poll() do
if name == "quit" then
if not love.quit or not love.quit() then
return a
end
end
love.handlers[name](a,b,c,d,e,f)
end
end
-- Update dt, as we'll be passing it to update
if love.timer then
love.timer.step()
dt = love.timer.getDelta()
end
-- Call update and draw
if love.update then love.update(dt) end -- will pass 0 if love.timer is disabled
if love.graphics and love.graphics.isActive() and (_ShouldDraw or _ForceDraw) then
love.graphics.setCanvas()
love.graphics.origin()
love.graphics.clear(0,0,0,255)
love.graphics.setColor(255,255,255)
love.graphics.draw(_ScreenCanvas, _ScreenX,_ScreenY, 0, _ScreenScaleX,_ScreenScaleY)
--love.graphics.api.points(1,1,_ScreenWidth,_ScreenHeight)
love.graphics.present()
love.graphics.setCanvas(_ScreenCanvas)
love.graphics.translate(_ScreenTX,_ScreenTY)
_ShouldDraw = false
end
if love.timer then love.timer.sleep(0.001) end
end
end
|
screen rendering fix
|
screen rendering fix
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
0b57414998b5404f93209f5b06141911cc9af503
|
xmake/plugins/project/xmake.lua
|
xmake/plugins/project/xmake.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 xmake.lua
--
-- define task
task("project")
-- set category
set_category("plugin")
-- on run
on_run("main")
-- set menu
set_menu {
-- usage
usage = "xmake project [options] [target]"
-- description
, description = "Generate the project file."
-- options
, options =
{
{'k', "kind", "kv", "makefile", "Set the project kind."
, " - makefile"
, " - compile_flags"
, " - compile_commands (clang compilation database with json format)"
, " - vs2002, vs2003, vs2005, vs2008"
, " - vs2010, vs2012, vs2013, vs2015, vs2017, vs2019"
, " - vsxmake2010 ~ vsmake2019" }
, {'m', "modes", "kv", nil, "Set the project modes."
, " e.g. "
, " - xmake project -k vs2015 -m \"release" .. path.envsep() .. "debug\"" }
, {'a', "archs", "kv", nil, "Set the project archs."
, " e.g. "
, " - xmake project -k vs2015 -a \"x86" .. path.envsep() .. "x64\"" }
, {nil, "outputdir", "v", ".", "Set the output directory." }
}
}
|
--!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 xmake.lua
--
-- define task
task("project")
-- set category
set_category("plugin")
-- on run
on_run("main")
-- set menu
set_menu {
-- usage
usage = "xmake project [options] [target]"
-- description
, description = "Generate the project file."
-- options
, options =
{
{'k', "kind", "kv", "makefile", "Set the project kind."
, " - makefile"
, " - compile_flags"
, " - compile_commands (clang compilation database with json format)"
, " - vs (auto detect), vs2002, vs2003, vs2005, vs2008"
, " - vs2010, vs2012, vs2013, vs2015, vs2017, vs2019"
, " - vsxmake (auto detect), vsxmake2010 ~ vsxmake2019" }
, {'m', "modes", "kv", nil, "Set the project modes."
, " e.g. "
, " - xmake project -k vs2015 -m \"release" .. path.envsep() .. "debug\"" }
, {'a', "archs", "kv", nil, "Set the project archs."
, " e.g. "
, " - xmake project -k vs2015 -a \"x86" .. path.envsep() .. "x64\"" }
, {nil, "outputdir", "v", ".", "Set the output directory." }
}
}
|
Fix typo
|
Fix typo
|
Lua
|
apache-2.0
|
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
|
0886c8886240bbf7b6c760c2cab9310c7d49192e
|
spec/unit/statics_spec.lua
|
spec/unit/statics_spec.lua
|
local spec_helper = require "spec.spec_helpers"
local constants = require "kong.constants"
local stringy = require "stringy"
local IO = require "kong.tools.io"
local fs = require "luarocks.fs"
describe("Static files", function()
describe("Constants", function()
it("version set in constants should match the one in the rockspec", function()
local rockspec_path
for _, filename in ipairs(fs.list_dir(".")) do
if stringy.endswith(filename, "rockspec") then
rockspec_path = filename
break
end
end
if not rockspec_path then
error("Can't find the rockspec file")
end
local file_content = IO.read_file(rockspec_path)
local res = file_content:match("\"+[0-9.-]+[a-z]*[0-9-]*\"+")
local extracted_version = res:sub(2, res:len() - 1)
assert.are.same(constants.VERSION, extracted_version)
end)
end)
describe("Configuration", function()
it("should parse a correct configuration", function()
local configuration = IO.read_file(spec_helper.DEFAULT_CONF_FILE)
assert.are.same([[
# Available plugins on this server
plugins_available:
- keyauth
- basicauth
- ratelimiting
- tcplog
- udplog
- filelog
- request_transformer
nginx_working_dir: /usr/local/kong/
proxy_port: 8000
admin_api_port: 8001
# Specify the DAO to use
database: cassandra
# Databases configuration
databases_available:
cassandra:
properties:
hosts: "localhost"
port: 9042
timeout: 1000
keyspace: kong
keepalive: 60000
# Sends anonymous error reports
send_anonymous_reports: true
nginx_plus_status: false
# Cassandra cache configuration
cache:
expiration: 5 # in seconds
nginx: |
worker_processes auto;
error_log logs/error.log info;
daemon on;
# Set "worker_rlimit_nofile" to a high value
# worker_rlimit_nofile 65536;
env KONG_CONF;
events {
# Set "worker_connections" to a high value
worker_connections 1024;
}
http {
resolver 8.8.8.8;
charset UTF-8;
access_log logs/access.log;
access_log on;
# Timeouts
keepalive_timeout 60s;
client_header_timeout 60s;
client_body_timeout 60s;
send_timeout 60s;
# Proxy Settings
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
proxy_ssl_server_name on;
# IP Address
real_ip_header X-Forwarded-For;
set_real_ip_from 0.0.0.0/0;
real_ip_recursive on;
# Other Settings
client_max_body_size 128m;
underscores_in_headers on;
reset_timedout_connection on;
tcp_nopush on;
################################################
# The following code is required to run Kong #
# Please be careful if you'd like to change it #
################################################
# Lua Settings
lua_package_path ';;';
lua_code_cache on;
lua_max_running_timers 4096;
lua_max_pending_timers 16384;
lua_shared_dict cache 512m;
lua_socket_log_errors off;
init_by_lua '
kong = require "kong"
local status, err = pcall(kong.init)
if not status then
ngx.log(ngx.ERR, "Startup error: "..err)
os.exit(1)
end
';
server {
listen {{proxy_port}};
location / {
default_type 'text/plain';
# This property will be used later by proxy_pass
set $backend_url nil;
# Authenticate the user and load the API info
access_by_lua 'kong.exec_plugins_access()';
# Proxy the request
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass $backend_url;
# Add additional response headers
header_filter_by_lua 'kong.exec_plugins_header_filter()';
# Change the response body
body_filter_by_lua 'kong.exec_plugins_body_filter()';
# Log the request
log_by_lua 'kong.exec_plugins_log()';
}
location /robots.txt {
return 200 'User-agent: *\nDisallow: /';
}
error_page 500 /500.html;
location = /500.html {
internal;
content_by_lua '
local utils = require "kong.tools.utils"
utils.show_error(ngx.status, "Oops, an unexpected error occurred!")
';
}
}
server {
listen {{admin_api_port}};
location / {
default_type application/json;
content_by_lua 'require("lapis").serve("kong.api.app")';
}
location /robots.txt {
return 200 'User-agent: *\nDisallow: /';
}
# Do not remove, additional configuration placeholder for some plugins
# {{additional_configuration}}
}
}
]], configuration)
end)
end)
end)
|
local spec_helper = require "spec.spec_helpers"
local constants = require "kong.constants"
local stringy = require "stringy"
local IO = require "kong.tools.io"
local fs = require "luarocks.fs"
describe("Static files", function()
describe("Constants", function()
it("version set in constants should match the one in the rockspec", function()
local rockspec_path
for _, filename in ipairs(fs.list_dir(".")) do
if stringy.endswith(filename, "rockspec") then
rockspec_path = filename
break
end
end
if not rockspec_path then
error("Can't find the rockspec file")
end
local file_content = IO.read_file(rockspec_path)
local res = file_content:match("\"+[0-9.-]+[a-z]*[0-9-]*\"+")
local extracted_version = res:sub(2, res:len() - 1)
assert.are.same(constants.VERSION, extracted_version)
end)
end)
describe("Configuration", function()
it("should parse a correct configuration", function()
local configuration = IO.read_file(spec_helper.DEFAULT_CONF_FILE)
assert.are.same([[
# Available plugins on this server
plugins_available:
- keyauth
- basicauth
- ratelimiting
- tcplog
- udplog
- filelog
- request_transformer
nginx_working_dir: /usr/local/kong/
proxy_port: 8000
admin_api_port: 8001
# Specify the DAO to use
database: cassandra
# Databases configuration
databases_available:
cassandra:
properties:
hosts: "localhost"
port: 9042
timeout: 1000
keyspace: kong
keepalive: 60000
# Sends anonymous error reports
send_anonymous_reports: true
nginx_plus_status: false
# Cassandra cache configuration
cache:
expiration: 5 # in seconds
# Nginx configuration
nginx: |
worker_processes auto;
error_log logs/error.log info;
daemon on;
worker_rlimit_nofile {{auto_worker_rlimit_nofile}};
env KONG_CONF;
events {
worker_connections {{auto_worker_connections}};
multi_accept on;
}
http {
resolver 8.8.8.8;
charset UTF-8;
access_log logs/access.log;
access_log on;
# Timeouts
keepalive_timeout 60s;
client_header_timeout 60s;
client_body_timeout 60s;
send_timeout 60s;
# Proxy Settings
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
proxy_ssl_server_name on;
# IP Address
real_ip_header X-Forwarded-For;
set_real_ip_from 0.0.0.0/0;
real_ip_recursive on;
# Other Settings
client_max_body_size 128m;
underscores_in_headers on;
reset_timedout_connection on;
tcp_nopush on;
################################################
# The following code is required to run Kong #
# Please be careful if you'd like to change it #
################################################
# Lua Settings
lua_package_path ';;';
lua_code_cache on;
lua_max_running_timers 4096;
lua_max_pending_timers 16384;
lua_shared_dict cache 512m;
lua_socket_log_errors off;
init_by_lua '
kong = require "kong"
local status, err = pcall(kong.init)
if not status then
ngx.log(ngx.ERR, "Startup error: "..err)
os.exit(1)
end
';
server {
listen {{proxy_port}};
location / {
default_type 'text/plain';
# This property will be used later by proxy_pass
set $backend_url nil;
# Authenticate the user and load the API info
access_by_lua 'kong.exec_plugins_access()';
# Proxy the request
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass $backend_url;
# Add additional response headers
header_filter_by_lua 'kong.exec_plugins_header_filter()';
# Change the response body
body_filter_by_lua 'kong.exec_plugins_body_filter()';
# Log the request
log_by_lua 'kong.exec_plugins_log()';
}
location /robots.txt {
return 200 'User-agent: *\nDisallow: /';
}
error_page 500 /500.html;
location = /500.html {
internal;
content_by_lua '
local utils = require "kong.tools.utils"
utils.show_error(ngx.status, "Oops, an unexpected error occurred!")
';
}
}
server {
listen {{admin_api_port}};
location / {
default_type application/json;
content_by_lua 'require("lapis").serve("kong.api.app")';
}
location /robots.txt {
return 200 'User-agent: *\nDisallow: /';
}
# Do not remove, additional configuration placeholder for some plugins
# {{additional_configuration}}
}
}
]], configuration)
end)
end)
end)
|
fixing test
|
fixing test
|
Lua
|
mit
|
ChristopherBiscardi/kong,puug/kong,sbuettner/kong,paritoshmmmec/kong,vmercierfr/kong,skynet/kong,bbalu/kong,ropik/kong,Skyscanner/kong,chourobin/kong,peterayeni/kong,AnsonSmith/kong,wakermahmud/kong
|
f0716ecd6e807799c8e16bea72d6ea98ec803d1b
|
modules/luci-mod-admin-full/luasrc/model/cbi/admin_network/network.lua
|
modules/luci-mod-admin-full/luasrc/model/cbi/admin_network/network.lua
|
-- Copyright 2008 Steven Barth <[email protected]>
-- Copyright 2008 Jo-Philipp Wich <[email protected]>
-- Licensed to the public under the Apache License 2.0.
local fs = require "nixio.fs"
local json = require "luci.jsonc"
m = Map("network", translate("Interfaces"))
m.pageaction = false
m:section(SimpleSection).template = "admin_network/iface_overview"
if fs.access("/etc/init.d/dsl_control") then
local ok, boarddata = pcall(json.parse, fs.readfile("/etc/board.json"))
local modemtype = (ok == true)
and (type(boarddata) == "table")
and (type(boarddata.dsl) == "table")
and (type(boarddata.dsl.modem) == "table")
and boarddata.dsl.modem.type
dsl = m:section(TypedSection, "dsl", translate("DSL"))
dsl.anonymous = true
annex = dsl:option(ListValue, "annex", translate("Annex"))
annex:value("a", translate("Annex A + L + M (all)"))
annex:value("b", translate("Annex B (all)"))
annex:value("j", translate("Annex J (all)"))
annex:value("m", translate("Annex M (all)"))
annex:value("bdmt", translate("Annex B G.992.1"))
annex:value("b2", translate("Annex B G.992.3"))
annex:value("b2p", translate("Annex B G.992.5"))
annex:value("at1", translate("ANSI T1.413"))
annex:value("admt", translate("Annex A G.992.1"))
annex:value("alite", translate("Annex A G.992.2"))
annex:value("a2", translate("Annex A G.992.3"))
annex:value("a2p", translate("Annex A G.992.5"))
annex:value("l", translate("Annex L G.992.3 POTS 1"))
annex:value("m2", translate("Annex M G.992.3"))
annex:value("m2p", translate("Annex M G.992.5"))
tone = dsl:option(ListValue, "tone", translate("Tone"))
tone:value("", translate("auto"))
tone:value("a", translate("A43C + J43 + A43"))
tone:value("av", translate("A43C + J43 + A43 + V43"))
tone:value("b", translate("B43 + B43C"))
tone:value("bv", translate("B43 + B43C + V43"))
if modemtype == "vdsl" then
xfer_mode = dsl:option(ListValue, "xfer_mode", translate("Encapsulation mode"))
xfer_mode:value("", translate("auto"))
xfer_mode:value("atm", translate("ATM (Asynchronous Transfer Mode)"))
xfer_mode:value("ptm", translate("PTM/EFM (Packet Transfer Mode)"))
line_mode = dsl:option(ListValue, "line_mode", translate("DSL line mode"))
line_mode:value("", translate("auto"))
line_mode:value("adsl", translate("ADSL"))
line_mode:value("vdsl", translate("VDSL"))
end
firmware = dsl:option(Value, "firmware", translate("Firmware File"))
m.pageaction = true
end
-- Show ATM bridge section if we have the capabilities
if fs.access("/usr/sbin/br2684ctl") then
atm = m:section(TypedSection, "atm-bridge", translate("ATM Bridges"),
translate("ATM bridges expose encapsulated ethernet in AAL5 " ..
"connections as virtual Linux network interfaces which can " ..
"be used in conjunction with DHCP or PPP to dial into the " ..
"provider network."))
atm.addremove = true
atm.anonymous = true
atm.create = function(self, section)
local sid = TypedSection.create(self, section)
local max_unit = -1
m.uci:foreach("network", "atm-bridge",
function(s)
local u = tonumber(s.unit)
if u ~= nil and u > max_unit then
max_unit = u
end
end)
m.uci:set("network", sid, "unit", max_unit + 1)
m.uci:set("network", sid, "atmdev", 0)
m.uci:set("network", sid, "encaps", "llc")
m.uci:set("network", sid, "payload", "bridged")
m.uci:set("network", sid, "vci", 35)
m.uci:set("network", sid, "vpi", 8)
return sid
end
atm:tab("general", translate("General Setup"))
atm:tab("advanced", translate("Advanced Settings"))
vci = atm:taboption("general", Value, "vci", translate("ATM Virtual Channel Identifier (VCI)"))
vpi = atm:taboption("general", Value, "vpi", translate("ATM Virtual Path Identifier (VPI)"))
encaps = atm:taboption("general", ListValue, "encaps", translate("Encapsulation mode"))
encaps:value("llc", translate("LLC"))
encaps:value("vc", translate("VC-Mux"))
atmdev = atm:taboption("advanced", Value, "atmdev", translate("ATM device number"))
unit = atm:taboption("advanced", Value, "unit", translate("Bridge unit number"))
payload = atm:taboption("advanced", ListValue, "payload", translate("Forwarding mode"))
payload:value("bridged", translate("bridged"))
payload:value("routed", translate("routed"))
m.pageaction = true
end
local network = require "luci.model.network"
if network:has_ipv6() then
local s = m:section(NamedSection, "globals", "globals", translate("Global network options"))
local o = s:option(Value, "ula_prefix", translate("IPv6 ULA-Prefix"))
o.datatype = "ip6addr"
o.rmempty = true
m.pageaction = true
end
return m
|
-- Copyright 2008 Steven Barth <[email protected]>
-- Copyright 2008 Jo-Philipp Wich <[email protected]>
-- Licensed to the public under the Apache License 2.0.
local fs = require "nixio.fs"
local json = require "luci.jsonc"
m = Map("network", translate("Interfaces"))
m.pageaction = false
m:section(SimpleSection).template = "admin_network/iface_overview"
if fs.access("/etc/init.d/dsl_control") then
local ok, boarddata = pcall(json.parse, fs.readfile("/etc/board.json"))
local modemtype = (ok == true)
and (type(boarddata) == "table")
and (type(boarddata.dsl) == "table")
and (type(boarddata.dsl.modem) == "table")
and boarddata.dsl.modem.type
dsl = m:section(TypedSection, "dsl", translate("DSL"))
dsl.anonymous = true
annex = dsl:option(ListValue, "annex", translate("Annex"))
annex:value("a", translate("Annex A + L + M (all)"))
annex:value("b", translate("Annex B (all)"))
annex:value("j", translate("Annex J (all)"))
annex:value("m", translate("Annex M (all)"))
annex:value("bdmt", translate("Annex B G.992.1"))
annex:value("b2", translate("Annex B G.992.3"))
annex:value("b2p", translate("Annex B G.992.5"))
annex:value("at1", translate("ANSI T1.413"))
annex:value("admt", translate("Annex A G.992.1"))
annex:value("alite", translate("Annex A G.992.2"))
annex:value("a2", translate("Annex A G.992.3"))
annex:value("a2p", translate("Annex A G.992.5"))
annex:value("l", translate("Annex L G.992.3 POTS 1"))
annex:value("m2", translate("Annex M G.992.3"))
annex:value("m2p", translate("Annex M G.992.5"))
tone = dsl:option(ListValue, "tone", translate("Tone"))
tone:value("", translate("auto"))
tone:value("a", translate("A43C + J43 + A43"))
tone:value("av", translate("A43C + J43 + A43 + V43"))
tone:value("b", translate("B43 + B43C"))
tone:value("bv", translate("B43 + B43C + V43"))
if modemtype == "vdsl" then
xfer_mode = dsl:option(ListValue, "xfer_mode", translate("Encapsulation mode"))
xfer_mode:value("", translate("auto"))
xfer_mode:value("atm", translate("ATM (Asynchronous Transfer Mode)"))
xfer_mode:value("ptm", translate("PTM/EFM (Packet Transfer Mode)"))
line_mode = dsl:option(ListValue, "line_mode", translate("DSL line mode"))
line_mode:value("", translate("auto"))
line_mode:value("adsl", translate("ADSL"))
line_mode:value("vdsl", translate("VDSL"))
ds_snr = dsl:option(ListValue, "ds_snr_offset", translate("Downstream SNR offset"))
ds_snr:depends("line_mode", "adsl")
for i = -50, 50, 5 do
ds_snr:value(i, translate("%.1f dB" %{ i / 10} ))
end
end
firmware = dsl:option(Value, "firmware", translate("Firmware File"))
m.pageaction = true
end
-- Show ATM bridge section if we have the capabilities
if fs.access("/usr/sbin/br2684ctl") then
atm = m:section(TypedSection, "atm-bridge", translate("ATM Bridges"),
translate("ATM bridges expose encapsulated ethernet in AAL5 " ..
"connections as virtual Linux network interfaces which can " ..
"be used in conjunction with DHCP or PPP to dial into the " ..
"provider network."))
atm.addremove = true
atm.anonymous = true
atm.create = function(self, section)
local sid = TypedSection.create(self, section)
local max_unit = -1
m.uci:foreach("network", "atm-bridge",
function(s)
local u = tonumber(s.unit)
if u ~= nil and u > max_unit then
max_unit = u
end
end)
m.uci:set("network", sid, "unit", max_unit + 1)
m.uci:set("network", sid, "atmdev", 0)
m.uci:set("network", sid, "encaps", "llc")
m.uci:set("network", sid, "payload", "bridged")
m.uci:set("network", sid, "vci", 35)
m.uci:set("network", sid, "vpi", 8)
return sid
end
atm:tab("general", translate("General Setup"))
atm:tab("advanced", translate("Advanced Settings"))
vci = atm:taboption("general", Value, "vci", translate("ATM Virtual Channel Identifier (VCI)"))
vpi = atm:taboption("general", Value, "vpi", translate("ATM Virtual Path Identifier (VPI)"))
encaps = atm:taboption("general", ListValue, "encaps", translate("Encapsulation mode"))
encaps:value("llc", translate("LLC"))
encaps:value("vc", translate("VC-Mux"))
atmdev = atm:taboption("advanced", Value, "atmdev", translate("ATM device number"))
unit = atm:taboption("advanced", Value, "unit", translate("Bridge unit number"))
payload = atm:taboption("advanced", ListValue, "payload", translate("Forwarding mode"))
payload:value("bridged", translate("bridged"))
payload:value("routed", translate("routed"))
m.pageaction = true
end
local network = require "luci.model.network"
if network:has_ipv6() then
local s = m:section(NamedSection, "globals", "globals", translate("Global network options"))
local o = s:option(Value, "ula_prefix", translate("IPv6 ULA-Prefix"))
o.datatype = "ip6addr"
o.rmempty = true
m.pageaction = true
end
return m
|
luci-mod-admin-full: add SNR tweak option to DSL
|
luci-mod-admin-full: add SNR tweak option to DSL
Reported-by: Andrea Merello <[email protected]>
[rebase onto master, fix indentation, commit subject, depend on adsl mode]
Signed-off-by: Jo-Philipp Wich <[email protected]>
|
Lua
|
apache-2.0
|
openwrt/luci,artynet/luci,openwrt-es/openwrt-luci,wongsyrone/luci-1,Noltari/luci,tobiaswaldvogel/luci,artynet/luci,Noltari/luci,hnyman/luci,chris5560/openwrt-luci,chris5560/openwrt-luci,nmav/luci,chris5560/openwrt-luci,tobiaswaldvogel/luci,openwrt/luci,wongsyrone/luci-1,remakeelectric/luci,openwrt/luci,wongsyrone/luci-1,hnyman/luci,tobiaswaldvogel/luci,tobiaswaldvogel/luci,Wedmer/luci,wongsyrone/luci-1,kuoruan/lede-luci,rogerpueyo/luci,nmav/luci,openwrt/luci,kuoruan/lede-luci,kuoruan/luci,remakeelectric/luci,wongsyrone/luci-1,kuoruan/luci,openwrt-es/openwrt-luci,981213/luci-1,openwrt-es/openwrt-luci,tobiaswaldvogel/luci,nmav/luci,nmav/luci,rogerpueyo/luci,hnyman/luci,kuoruan/lede-luci,nmav/luci,remakeelectric/luci,Noltari/luci,kuoruan/luci,rogerpueyo/luci,nmav/luci,artynet/luci,Wedmer/luci,openwrt-es/openwrt-luci,Noltari/luci,rogerpueyo/luci,Wedmer/luci,981213/luci-1,kuoruan/luci,hnyman/luci,Noltari/luci,Wedmer/luci,Noltari/luci,kuoruan/lede-luci,tobiaswaldvogel/luci,wongsyrone/luci-1,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,nmav/luci,Wedmer/luci,rogerpueyo/luci,artynet/luci,981213/luci-1,tobiaswaldvogel/luci,openwrt/luci,Noltari/luci,hnyman/luci,openwrt/luci,981213/luci-1,Wedmer/luci,Noltari/luci,remakeelectric/luci,remakeelectric/luci,nmav/luci,nmav/luci,kuoruan/luci,Wedmer/luci,remakeelectric/luci,hnyman/luci,kuoruan/lede-luci,kuoruan/lede-luci,chris5560/openwrt-luci,kuoruan/lede-luci,openwrt/luci,artynet/luci,981213/luci-1,tobiaswaldvogel/luci,openwrt/luci,remakeelectric/luci,lbthomsen/openwrt-luci,wongsyrone/luci-1,artynet/luci,kuoruan/lede-luci,wongsyrone/luci-1,lbthomsen/openwrt-luci,chris5560/openwrt-luci,Noltari/luci,kuoruan/luci,kuoruan/luci,lbthomsen/openwrt-luci,chris5560/openwrt-luci,chris5560/openwrt-luci,981213/luci-1,chris5560/openwrt-luci,Wedmer/luci,hnyman/luci,lbthomsen/openwrt-luci,rogerpueyo/luci,remakeelectric/luci,hnyman/luci,artynet/luci,981213/luci-1,rogerpueyo/luci,artynet/luci,lbthomsen/openwrt-luci,artynet/luci,openwrt-es/openwrt-luci,openwrt-es/openwrt-luci,kuoruan/luci,openwrt-es/openwrt-luci,rogerpueyo/luci,openwrt-es/openwrt-luci
|
02e6bcfa10efadb9996d15bec9016c7443ea6fc3
|
lua/framework/mouse.lua
|
lua/framework/mouse.lua
|
--=========== Copyright © 2018, Planimeter, All rights reserved. =============--
--
-- Purpose:
--
--============================================================================--
local ffi = require( "ffi" )
local SDL = require( "sdl" )
module( "framework.mouse" )
function getPosition()
local x = ffi.new( "int[1]" )
local y = ffi.new( "int[1]" )
SDL.SDL_GetMouseState( x, y )
return x[0], y[0]
end
function getSystemCursor( id )
if ( id == "arrow" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_ARROW
elseif ( id == "ibeam" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_IBEAM
elseif ( id == "wait" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_WAIT
elseif ( id == "crosshair" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_CROSSHAIR
elseif ( id == "waitarrow" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_WAITARROW
elseif ( id == "sizenwse" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_SIZENWSE
elseif ( id == "sizenesw" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_SIZENESW
elseif ( id == "sizewe" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_SIZEWE
elseif ( id == "sizens" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_SIZENS
elseif ( id == "sizeall" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_SIZEALL
elseif ( id == "no" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_NO
elseif ( id == "hand" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_HAND
end
return SDL.SDL_CreateSystemCursor( id )
end
function setCursor( cursor )
SDL.SDL_SetCursor( cursor )
end
function setVisible( visible )
SDL.SDL_ShowCursor( visible and SDL.SDL_ENABLE or SDL.SDL_DISABLE )
end
|
--=========== Copyright © 2018, Planimeter, All rights reserved. =============--
--
-- Purpose:
--
--============================================================================--
local ffi = require( "ffi" )
local SDL = require( "sdl" )
module( "framework.mouse" )
function getPosition()
local x = ffi.new( "int[1]" )
local y = ffi.new( "int[1]" )
SDL.SDL_GetMouseState( x, y )
return x[0], y[0]
end
function getSystemCursor( id )
if ( id == "arrow" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_ARROW
elseif ( id == "ibeam" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_IBEAM
elseif ( id == "wait" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_WAIT
elseif ( id == "crosshair" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_CROSSHAIR
elseif ( id == "waitarrow" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_WAITARROW
elseif ( id == "sizenwse" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_SIZENWSE
elseif ( id == "sizenesw" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_SIZENESW
elseif ( id == "sizewe" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_SIZEWE
elseif ( id == "sizens" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_SIZENS
elseif ( id == "sizeall" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_SIZEALL
elseif ( id == "no" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_NO
elseif ( id == "hand" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_HAND
end
return SDL.SDL_CreateSystemCursor( id )
end
function setCursor( cursor )
SDL.SDL_SetCursor( cursor )
if ( cursor ) then
else
SDL.SDL_SetCursor( SDL.SDL_GetDefaultCursor() )
end
end
function setVisible( visible )
SDL.SDL_ShowCursor( visible and SDL.SDL_ENABLE or SDL.SDL_DISABLE )
end
|
Fix `setCursor()` not setting default cursor
|
Fix `setCursor()` not setting default cursor
|
Lua
|
mit
|
Planimeter/lgameframework,Planimeter/lgameframework,Planimeter/lgameframework
|
86333dc5d889aa95556abba4ec92a81a6b521089
|
util/ip.lua
|
util/ip.lua
|
-- Prosody IM
-- Copyright (C) 2008-2011 Florian Zeitz
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local ip_methods = {};
local ip_mt = { __index = function (ip, key) return (ip_methods[key])(ip); end,
__tostring = function (ip) return ip.addr; end,
__eq = function (ipA, ipB) return ipA.addr == ipB.addr; end};
local hex2bits = { ["0"] = "0000", ["1"] = "0001", ["2"] = "0010", ["3"] = "0011", ["4"] = "0100", ["5"] = "0101", ["6"] = "0110", ["7"] = "0111", ["8"] = "1000", ["9"] = "1001", ["A"] = "1010", ["B"] = "1011", ["C"] = "1100", ["D"] = "1101", ["E"] = "1110", ["F"] = "1111" };
local function new_ip(ipStr, proto)
if not proto then
local sep = ipStr:match("^%x+(.)");
if sep == ":" then proto = "IPv6"
elseif sep == "." then proto = "IPv4"
end
if not proto then
return nil, "invalid address";
end
elseif proto ~= "IPv4" and proto ~= "IPv6" then
return nil, "invalid protocol";
end
if proto == "IPv6" and ipStr:find('.', 1, true) then
local changed;
ipStr, changed = ipStr:gsub(":(%d+)%.(%d+)%.(%d+)%.(%d+)$", function(a,b,c,d)
return (":%04X:%04X"):format(a*256+b,c*256+d);
end);
if changed ~= 1 then return nil, "invalid-address"; end
end
return setmetatable({ addr = ipStr, proto = proto }, ip_mt);
end
local function toBits(ip)
local result = "";
local fields = {};
if ip.proto == "IPv4" then
ip = ip.toV4mapped;
end
ip = (ip.addr):upper();
ip:gsub("([^:]*):?", function (c) fields[#fields + 1] = c end);
if not ip:match(":$") then fields[#fields] = nil; end
for i, field in ipairs(fields) do
if field:len() == 0 and i ~= 1 and i ~= #fields then
for i = 1, 16 * (9 - #fields) do
result = result .. "0";
end
else
for i = 1, 4 - field:len() do
result = result .. "0000";
end
for i = 1, field:len() do
result = result .. hex2bits[field:sub(i,i)];
end
end
end
return result;
end
local function commonPrefixLength(ipA, ipB)
ipA, ipB = toBits(ipA), toBits(ipB);
for i = 1, 128 do
if ipA:sub(i,i) ~= ipB:sub(i,i) then
return i-1;
end
end
return 128;
end
local function v4scope(ip)
local fields = {};
ip:gsub("([^.]*).?", function (c) fields[#fields + 1] = tonumber(c) end);
-- Loopback:
if fields[1] == 127 then
return 0x2;
-- Link-local unicast:
elseif fields[1] == 169 and fields[2] == 254 then
return 0x2;
-- Global unicast:
else
return 0xE;
end
end
local function v6scope(ip)
-- Loopback:
if ip:match("^[0:]*1$") then
return 0x2;
-- Link-local unicast:
elseif ip:match("^[Ff][Ee][89ABab]") then
return 0x2;
-- Site-local unicast:
elseif ip:match("^[Ff][Ee][CcDdEeFf]") then
return 0x5;
-- Multicast:
elseif ip:match("^[Ff][Ff]") then
return tonumber("0x"..ip:sub(4,4));
-- Global unicast:
else
return 0xE;
end
end
local function label(ip)
if commonPrefixLength(ip, new_ip("::1", "IPv6")) == 128 then
return 0;
elseif commonPrefixLength(ip, new_ip("2002::", "IPv6")) >= 16 then
return 2;
elseif commonPrefixLength(ip, new_ip("2001::", "IPv6")) >= 32 then
return 5;
elseif commonPrefixLength(ip, new_ip("fc00::", "IPv6")) >= 7 then
return 13;
elseif commonPrefixLength(ip, new_ip("fec0::", "IPv6")) >= 10 then
return 11;
elseif commonPrefixLength(ip, new_ip("3ffe::", "IPv6")) >= 16 then
return 12;
elseif commonPrefixLength(ip, new_ip("::", "IPv6")) >= 96 then
return 3;
elseif commonPrefixLength(ip, new_ip("::ffff:0:0", "IPv6")) >= 96 then
return 4;
else
return 1;
end
end
local function precedence(ip)
if commonPrefixLength(ip, new_ip("::1", "IPv6")) == 128 then
return 50;
elseif commonPrefixLength(ip, new_ip("2002::", "IPv6")) >= 16 then
return 30;
elseif commonPrefixLength(ip, new_ip("2001::", "IPv6")) >= 32 then
return 5;
elseif commonPrefixLength(ip, new_ip("fc00::", "IPv6")) >= 7 then
return 3;
elseif commonPrefixLength(ip, new_ip("fec0::", "IPv6")) >= 10 then
return 1;
elseif commonPrefixLength(ip, new_ip("3ffe::", "IPv6")) >= 16 then
return 1;
elseif commonPrefixLength(ip, new_ip("::", "IPv6")) >= 96 then
return 1;
elseif commonPrefixLength(ip, new_ip("::ffff:0:0", "IPv6")) >= 96 then
return 35;
else
return 40;
end
end
local function toV4mapped(ip)
local fields = {};
local ret = "::ffff:";
ip:gsub("([^.]*).?", function (c) fields[#fields + 1] = tonumber(c) end);
ret = ret .. ("%02x"):format(fields[1]);
ret = ret .. ("%02x"):format(fields[2]);
ret = ret .. ":"
ret = ret .. ("%02x"):format(fields[3]);
ret = ret .. ("%02x"):format(fields[4]);
return new_ip(ret, "IPv6");
end
function ip_methods:toV4mapped()
if self.proto ~= "IPv4" then return nil, "No IPv4 address" end
local value = toV4mapped(self.addr);
self.toV4mapped = value;
return value;
end
function ip_methods:label()
local value;
if self.proto == "IPv4" then
value = label(self.toV4mapped);
else
value = label(self);
end
self.label = value;
return value;
end
function ip_methods:precedence()
local value;
if self.proto == "IPv4" then
value = precedence(self.toV4mapped);
else
value = precedence(self);
end
self.precedence = value;
return value;
end
function ip_methods:scope()
local value;
if self.proto == "IPv4" then
value = v4scope(self.addr);
else
value = v6scope(self.addr);
end
self.scope = value;
return value;
end
function ip_methods:private()
local private = self.scope ~= 0xE;
if not private and self.proto == "IPv4" then
local ip = self.addr;
local fields = {};
ip:gsub("([^.]*).?", function (c) fields[#fields + 1] = tonumber(c) end);
if fields[1] == 127 or fields[1] == 10 or (fields[1] == 192 and fields[2] == 168)
or (fields[1] == 172 and (fields[2] >= 16 or fields[2] <= 32)) then
private = true;
end
end
self.private = private;
return private;
end
local function parse_cidr(cidr)
local bits;
local ip_len = cidr:find("/", 1, true);
if ip_len then
bits = tonumber(cidr:sub(ip_len+1, -1));
cidr = cidr:sub(1, ip_len-1);
end
return new_ip(cidr), bits;
end
local function match(ipA, ipB, bits)
local common_bits = commonPrefixLength(ipA, ipB);
if not bits then
return ipA == ipB;
end
if bits and ipB.proto == "IPv4" then
common_bits = common_bits - 96; -- v6 mapped addresses always share these bits
end
return common_bits >= bits;
end
return {new_ip = new_ip,
commonPrefixLength = commonPrefixLength,
parse_cidr = parse_cidr,
match=match};
|
-- Prosody IM
-- Copyright (C) 2008-2011 Florian Zeitz
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local ip_methods = {};
local ip_mt = { __index = function (ip, key) return (ip_methods[key])(ip); end,
__tostring = function (ip) return ip.addr; end,
__eq = function (ipA, ipB) return ipA.addr == ipB.addr; end};
local hex2bits = { ["0"] = "0000", ["1"] = "0001", ["2"] = "0010", ["3"] = "0011", ["4"] = "0100", ["5"] = "0101", ["6"] = "0110", ["7"] = "0111", ["8"] = "1000", ["9"] = "1001", ["A"] = "1010", ["B"] = "1011", ["C"] = "1100", ["D"] = "1101", ["E"] = "1110", ["F"] = "1111" };
local function new_ip(ipStr, proto)
if not proto then
local sep = ipStr:match("^%x+(.)");
if sep == ":" or (not(sep) and ipStr:sub(1,1) == ":") then
proto = "IPv6"
elseif sep == "." then
proto = "IPv4"
end
if not proto then
return nil, "invalid address";
end
elseif proto ~= "IPv4" and proto ~= "IPv6" then
return nil, "invalid protocol";
end
if proto == "IPv6" and ipStr:find('.', 1, true) then
local changed;
ipStr, changed = ipStr:gsub(":(%d+)%.(%d+)%.(%d+)%.(%d+)$", function(a,b,c,d)
return (":%04X:%04X"):format(a*256+b,c*256+d);
end);
if changed ~= 1 then return nil, "invalid-address"; end
end
return setmetatable({ addr = ipStr, proto = proto }, ip_mt);
end
local function toBits(ip)
local result = "";
local fields = {};
if ip.proto == "IPv4" then
ip = ip.toV4mapped;
end
ip = (ip.addr):upper();
ip:gsub("([^:]*):?", function (c) fields[#fields + 1] = c end);
if not ip:match(":$") then fields[#fields] = nil; end
for i, field in ipairs(fields) do
if field:len() == 0 and i ~= 1 and i ~= #fields then
for i = 1, 16 * (9 - #fields) do
result = result .. "0";
end
else
for i = 1, 4 - field:len() do
result = result .. "0000";
end
for i = 1, field:len() do
result = result .. hex2bits[field:sub(i,i)];
end
end
end
return result;
end
local function commonPrefixLength(ipA, ipB)
ipA, ipB = toBits(ipA), toBits(ipB);
for i = 1, 128 do
if ipA:sub(i,i) ~= ipB:sub(i,i) then
return i-1;
end
end
return 128;
end
local function v4scope(ip)
local fields = {};
ip:gsub("([^.]*).?", function (c) fields[#fields + 1] = tonumber(c) end);
-- Loopback:
if fields[1] == 127 then
return 0x2;
-- Link-local unicast:
elseif fields[1] == 169 and fields[2] == 254 then
return 0x2;
-- Global unicast:
else
return 0xE;
end
end
local function v6scope(ip)
-- Loopback:
if ip:match("^[0:]*1$") then
return 0x2;
-- Link-local unicast:
elseif ip:match("^[Ff][Ee][89ABab]") then
return 0x2;
-- Site-local unicast:
elseif ip:match("^[Ff][Ee][CcDdEeFf]") then
return 0x5;
-- Multicast:
elseif ip:match("^[Ff][Ff]") then
return tonumber("0x"..ip:sub(4,4));
-- Global unicast:
else
return 0xE;
end
end
local function label(ip)
if commonPrefixLength(ip, new_ip("::1", "IPv6")) == 128 then
return 0;
elseif commonPrefixLength(ip, new_ip("2002::", "IPv6")) >= 16 then
return 2;
elseif commonPrefixLength(ip, new_ip("2001::", "IPv6")) >= 32 then
return 5;
elseif commonPrefixLength(ip, new_ip("fc00::", "IPv6")) >= 7 then
return 13;
elseif commonPrefixLength(ip, new_ip("fec0::", "IPv6")) >= 10 then
return 11;
elseif commonPrefixLength(ip, new_ip("3ffe::", "IPv6")) >= 16 then
return 12;
elseif commonPrefixLength(ip, new_ip("::", "IPv6")) >= 96 then
return 3;
elseif commonPrefixLength(ip, new_ip("::ffff:0:0", "IPv6")) >= 96 then
return 4;
else
return 1;
end
end
local function precedence(ip)
if commonPrefixLength(ip, new_ip("::1", "IPv6")) == 128 then
return 50;
elseif commonPrefixLength(ip, new_ip("2002::", "IPv6")) >= 16 then
return 30;
elseif commonPrefixLength(ip, new_ip("2001::", "IPv6")) >= 32 then
return 5;
elseif commonPrefixLength(ip, new_ip("fc00::", "IPv6")) >= 7 then
return 3;
elseif commonPrefixLength(ip, new_ip("fec0::", "IPv6")) >= 10 then
return 1;
elseif commonPrefixLength(ip, new_ip("3ffe::", "IPv6")) >= 16 then
return 1;
elseif commonPrefixLength(ip, new_ip("::", "IPv6")) >= 96 then
return 1;
elseif commonPrefixLength(ip, new_ip("::ffff:0:0", "IPv6")) >= 96 then
return 35;
else
return 40;
end
end
local function toV4mapped(ip)
local fields = {};
local ret = "::ffff:";
ip:gsub("([^.]*).?", function (c) fields[#fields + 1] = tonumber(c) end);
ret = ret .. ("%02x"):format(fields[1]);
ret = ret .. ("%02x"):format(fields[2]);
ret = ret .. ":"
ret = ret .. ("%02x"):format(fields[3]);
ret = ret .. ("%02x"):format(fields[4]);
return new_ip(ret, "IPv6");
end
function ip_methods:toV4mapped()
if self.proto ~= "IPv4" then return nil, "No IPv4 address" end
local value = toV4mapped(self.addr);
self.toV4mapped = value;
return value;
end
function ip_methods:label()
local value;
if self.proto == "IPv4" then
value = label(self.toV4mapped);
else
value = label(self);
end
self.label = value;
return value;
end
function ip_methods:precedence()
local value;
if self.proto == "IPv4" then
value = precedence(self.toV4mapped);
else
value = precedence(self);
end
self.precedence = value;
return value;
end
function ip_methods:scope()
local value;
if self.proto == "IPv4" then
value = v4scope(self.addr);
else
value = v6scope(self.addr);
end
self.scope = value;
return value;
end
function ip_methods:private()
local private = self.scope ~= 0xE;
if not private and self.proto == "IPv4" then
local ip = self.addr;
local fields = {};
ip:gsub("([^.]*).?", function (c) fields[#fields + 1] = tonumber(c) end);
if fields[1] == 127 or fields[1] == 10 or (fields[1] == 192 and fields[2] == 168)
or (fields[1] == 172 and (fields[2] >= 16 or fields[2] <= 32)) then
private = true;
end
end
self.private = private;
return private;
end
local function parse_cidr(cidr)
local bits;
local ip_len = cidr:find("/", 1, true);
if ip_len then
bits = tonumber(cidr:sub(ip_len+1, -1));
cidr = cidr:sub(1, ip_len-1);
end
return new_ip(cidr), bits;
end
local function match(ipA, ipB, bits)
local common_bits = commonPrefixLength(ipA, ipB);
if not bits then
return ipA == ipB;
end
if bits and ipB.proto == "IPv4" then
common_bits = common_bits - 96; -- v6 mapped addresses always share these bits
end
return common_bits >= bits;
end
return {new_ip = new_ip,
commonPrefixLength = commonPrefixLength,
parse_cidr = parse_cidr,
match=match};
|
util.ip: Fix protocol detection of IPv6 addresses beginning with :
|
util.ip: Fix protocol detection of IPv6 addresses beginning with :
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
33ef7758382619324052da77717dbc1183136fa7
|
nvim/lua/config/cmp.lua
|
nvim/lua/config/cmp.lua
|
local M = {}
function M.setup()
local has_words_before = function()
local line, col = unpack(vim.api.nvim_win_get_cursor(0))
return col ~= 0 and vim.api.nvim_buf_get_lines(0, line - 1, line, true)[1]:sub(col, col):match "%s" == nil
end
local luasnip = require "luasnip"
local cmp = require "cmp"
cmp.setup {
completion = { completeopt = "menu,menuone,noinsert", keyword_length = 1 },
experimental = { native_menu = false, ghost_text = false },
snippet = {
expand = function(args)
require("luasnip").lsp_expand(args.body)
end,
},
formatting = {
format = function(entry, vim_item)
vim_item.menu = ({
buffer = "[Buffer]",
luasnip = "[Snip]",
nvim_lua = "[Lua]",
treesitter = "[Treesitter]",
})[entry.source.name]
return vim_item
end,
},
mapping = {
["<C-k>"] = cmp.mapping(cmp.mapping.select_prev_item(), { "i", "c" }),
["<C-j>"] = cmp.mapping(cmp.mapping.select_next_item(), { "i", "c" }),
["<C-b>"] = cmp.mapping(cmp.mapping.scroll_docs(-4), { "i", "c" }),
["<C-f>"] = cmp.mapping(cmp.mapping.scroll_docs(4), { "i", "c" }),
["<C-Space>"] = cmp.mapping(cmp.mapping.complete(), { "i", "c" }),
["<C-e>"] = cmp.mapping { i = cmp.mapping.close(), c = cmp.mapping.close() },
["<CR>"] = cmp.mapping {
i = cmp.mapping.confirm { behavior = cmp.ConfirmBehavior.Replace, select = false },
c = function(fallback)
if cmp.visible() then
cmp.confirm { behavior = cmp.ConfirmBehavior.Replace, select = false }
else
fallback()
end
end,
},
["<Tab>"] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_next_item()
elseif luasnip.expand_or_jumpable() then
luasnip.expand_or_jump()
elseif has_words_before() then
cmp.complete()
else
fallback()
end
end, {
"i",
"s",
"c",
}),
["<S-Tab>"] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_prev_item()
elseif luasnip.jumpable(-1) then
luasnip.jump(-1)
else
fallback()
end
end, {
"i",
"s",
"c",
}),
},
sources = {
{ name = "treesitter" },
{ name = "buffer" },
{ name = "luasnip" },
{ name = "nvim_lua" },
{ name = "path" },
{ name = "spell" },
{ name = "emoji" },
{ name = "calc" },
},
documentation = {
border = { "╭", "─", "╮", "│", "╯", "─", "╰", "│" },
winhighlight = "NormalFloat:NormalFloat,FloatBorder:TelescopeBorder",
},
}
-- Use buffer source for `/`
cmp.setup.cmdline("/", {
sources = {
{ name = "buffer" },
},
})
-- Use cmdline & path source for ':'
cmp.setup.cmdline(":", {
sources = cmp.config.sources({
{ name = "path" },
}, {
{ name = "cmdline" },
}),
})
end
return M
|
local M = {}
function M.setup()
local has_words_before = function()
local line, col = unpack(vim.api.nvim_win_get_cursor(0))
return col ~= 0 and vim.api.nvim_buf_get_lines(0, line - 1, line, true)[1]:sub(col, col):match "%s" == nil
end
local luasnip = require "luasnip"
local cmp = require "cmp"
cmp.setup {
completion = { completeopt = "menu,menuone,noinsert", keyword_length = 1 },
experimental = { native_menu = false, ghost_text = false },
snippet = {
expand = function(args)
require("luasnip").lsp_expand(args.body)
end,
},
formatting = {
format = function(entry, vim_item)
vim_item.menu = ({
buffer = "[Buffer]",
luasnip = "[Snip]",
nvim_lua = "[Lua]",
treesitter = "[Treesitter]",
})[entry.source.name]
return vim_item
end,
},
mapping = {
["<C-k>"] = cmp.mapping(cmp.mapping.select_prev_item(), { "i", "c" }),
["<C-j>"] = cmp.mapping(cmp.mapping.select_next_item(), { "i", "c" }),
["<C-b>"] = cmp.mapping(cmp.mapping.scroll_docs(-4), { "i", "c" }),
["<C-f>"] = cmp.mapping(cmp.mapping.scroll_docs(4), { "i", "c" }),
["<C-Space>"] = cmp.mapping(cmp.mapping.complete(), { "i", "c" }),
["<C-e>"] = cmp.mapping { i = cmp.mapping.close(), c = cmp.mapping.close() },
["<CR>"] = cmp.mapping {
i = cmp.mapping.confirm { behavior = cmp.ConfirmBehavior.Replace, select = false },
c = function(fallback)
if cmp.visible() then
cmp.confirm { behavior = cmp.ConfirmBehavior.Replace, select = false }
else
fallback()
end
end,
},
["<Tab>"] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_next_item()
elseif luasnip.expand_or_jumpable() then
luasnip.expand_or_jump()
elseif has_words_before() then
cmp.complete()
else
fallback()
end
end, {
"i",
"s",
"c",
}),
["<S-Tab>"] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_prev_item()
elseif luasnip.jumpable(-1) then
luasnip.jump(-1)
else
fallback()
end
end, {
"i",
"s",
"c",
}),
},
sources = {
{ name = "treesitter" },
{ name = "buffer" },
{ name = "luasnip" },
{ name = "nvim_lua" },
{ name = "path" },
{ name = "spell" },
{ name = "emoji" },
{ name = "calc" },
},
window = {
documentation = cmp.config.window.bordered(),
},
}
-- Use buffer source for `/`
cmp.setup.cmdline("/", {
sources = {
{ name = "buffer" },
},
})
-- Use cmdline & path source for ':'
cmp.setup.cmdline(":", {
sources = cmp.config.sources({
{ name = "path" },
}, {
{ name = "cmdline" },
}),
})
end
return M
|
fix cmp config
|
fix cmp config
|
Lua
|
mit
|
jvansan/dotfiles
|
2dd12f5d051de407f65ea4e288a184985566be6f
|
lua/framework/graphics/framebuffer.lua
|
lua/framework/graphics/framebuffer.lua
|
--=========== Copyright © 2018, Planimeter, All rights reserved. =============--
--
-- Purpose:
--
--============================================================================--
require( "class" )
require( "framework.graphics.image" )
local GL = require( "opengl" )
local ffi = require( "ffi" )
local kazmath = require( "kazmath" )
local image = framework.graphics.image
class( "framework.graphics.framebuffer" )
local framebuffer = framework.graphics.framebuffer
function framebuffer:framebuffer( width, height )
if ( not width and not height ) then
width, height = framework.graphics.getSize()
end
self.width = width
self.height = height
self.framebuffer = ffi.new( "GLuint[1]" )
GL.glGenFramebuffers( 1, self.framebuffer )
framework.graphics.setFramebuffer( self )
self.texture = ffi.new( "GLuint[1]" )
GL.glGenTextures( 1, self.texture )
GL.glBindTexture( GL.GL_TEXTURE_2D, self.texture[0] )
GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_BASE_LEVEL, 0 )
GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAX_LEVEL, 0 )
GL.glTexImage2D(
GL.GL_TEXTURE_2D,
0,
GL.GL_RGBA,
width,
height,
0,
GL.GL_RGBA,
GL.GL_UNSIGNED_BYTE,
nil
)
GL.glFramebufferTexture2D(
GL.GL_FRAMEBUFFER,
GL.GL_COLOR_ATTACHMENT0,
GL.GL_TEXTURE_2D,
self.texture[0],
0
)
framework.graphics.clear()
framework.graphics.setFramebuffer()
setproxy( self )
end
function framebuffer:draw( x, y, r, sx, sy, ox, oy, kx, ky )
framework.graphics.setMatrixMode( "projection" )
framework.graphics.push()
local mat4 = framework.graphics.getTransformation()
local width, height = framework.graphics.getSize()
kazmath.kmMat4OrthographicProjection(
mat4, 0, width, 0, height, -1.0, 1.0
)
image.draw( self, x, y, r, sx, sy, ox, oy, kx, ky )
framework.graphics.pop()
framework.graphics.setMatrixMode( "model" )
end
function framebuffer:__gc()
GL.glDeleteTextures( 1, self.texture )
GL.glDeleteFramebuffers( 1, self.framebuffer )
end
|
--=========== Copyright © 2018, Planimeter, All rights reserved. =============--
--
-- Purpose:
--
--============================================================================--
require( "class" )
require( "framework.graphics.image" )
local GL = require( "opengl" )
local ffi = require( "ffi" )
local kazmath = require( "kazmath" )
local image = framework.graphics.image
class( "framework.graphics.framebuffer" )
local framebuffer = framework.graphics.framebuffer
function framebuffer:framebuffer( width, height )
if ( not width and not height ) then
width, height = framework.graphics.getSize()
end
self.width = width
self.height = height
self.framebuffer = ffi.new( "GLuint[1]" )
GL.glGenFramebuffers( 1, self.framebuffer )
framework.graphics.setFramebuffer( self )
self.texture = ffi.new( "GLuint[1]" )
GL.glGenTextures( 1, self.texture )
GL.glBindTexture( GL.GL_TEXTURE_2D, self.texture[0] )
GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_BASE_LEVEL, 0 )
GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAX_LEVEL, 0 )
GL.glTexImage2D(
GL.GL_TEXTURE_2D,
0,
GL.GL_RGBA,
width,
height,
0,
GL.GL_RGBA,
GL.GL_UNSIGNED_BYTE,
nil
)
GL.glFramebufferTexture2D(
GL.GL_FRAMEBUFFER,
GL.GL_COLOR_ATTACHMENT0,
GL.GL_TEXTURE_2D,
self.texture[0],
0
)
framework.graphics.clear()
framework.graphics.setFramebuffer()
setproxy( self )
end
function framebuffer:draw( x, y, r, sx, sy, ox, oy, kx, ky )
local mode = framework.graphics.getMatrixMode()
framework.graphics.setMatrixMode( "projection" )
framework.graphics.push()
local mat4 = framework.graphics.getTransformation()
local width, height = framework.graphics.getSize()
kazmath.kmMat4OrthographicProjection(
mat4, 0, width, 0, height, -1.0, 1.0
)
image.draw( self, x, y, r, sx, sy, ox, oy, kx, ky )
framework.graphics.pop()
framework.graphics.setMatrixMode( mode )
end
function framebuffer:__gc()
GL.glDeleteTextures( 1, self.texture )
GL.glDeleteFramebuffers( 1, self.framebuffer )
end
|
Fix `framebuffer:draw()` not restoring original matrix mode
|
Fix `framebuffer:draw()` not restoring original matrix mode
|
Lua
|
mit
|
Planimeter/lgameframework,Planimeter/lgameframework,Planimeter/lgameframework
|
1e58c78c72ac2b78707f9927c032fbdb31086f95
|
util.lua
|
util.lua
|
local computer = require("computer")
local event = require("event")
local function trunc(num, numDecimalPlaces)
local mult = 10^(numDecimalPlaces or 0)
return math.floor(num * mult) / mult
end
local function needsCharging(threshold, distanceFromCharger)
distanceFromCharger = distanceFromCharger or 0
local percentCharge = (computer.energy() / computer.maxEnergy())
-- require additional 1% charge per 25 blocks distance to charger
print(percentCharge)
print((distanceFromCharger / 25) / 100)
print(threshold)
if (percentCharge - ((distanceFromCharger / 25) / 100)) <= threshold then
return true
end
return false
end
local function waitUntilCharge(threshold, maxWaitSeconds)
maxWaitSeconds = maxWaitSeconds or 300
while maxWaitSeconds > 0 do
local percentCharge = (computer.energy() / computer.maxEnergy())
if (percentCharge >= threshold) then
return true
end
maxWaitSeconds = maxWaitSeconds - 1
event.pull(1, "_chargewait")
end
local percentCharge = (computer.energy() / computer.maxEnergy())
return percentCharge >= threshold
end
return {
trunc = trunc,
needsCharging = needsCharging,
waitUntilCharge = waitUntilCharge
}
|
local computer = require("computer")
local event = require("event")
local function trunc(num, numDecimalPlaces)
local mult = 10^(numDecimalPlaces or 0)
return math.floor(num * mult) / mult
end
local function needsCharging(threshold, distanceFromCharger)
distanceFromCharger = distanceFromCharger or 0
local percentCharge = (computer.energy() / computer.maxEnergy())
-- require additional 1% charge per 25 blocks distance to charger
if (percentCharge - ((distanceFromCharger / 25) / 100)) <= threshold then
return true
end
return false
end
local function waitUntilCharge(threshold, maxWaitSeconds)
maxWaitSeconds = maxWaitSeconds or 300
while maxWaitSeconds > 0 do
local percentCharge = (computer.energy() / computer.maxEnergy())
if (percentCharge >= threshold) then
return true
end
maxWaitSeconds = maxWaitSeconds - 1
event.pull(1, "_chargewait")
end
local percentCharge = (computer.energy() / computer.maxEnergy())
return percentCharge >= threshold
end
return {
trunc = trunc,
needsCharging = needsCharging,
waitUntilCharge = waitUntilCharge
}
|
fixed
|
fixed
|
Lua
|
apache-2.0
|
InfinitiesLoop/oclib
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.