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
683b0381bf1ff2f2782fcebbd755c476520b2737
frontend/apps/reader/modules/readerwikipedia.lua
frontend/apps/reader/modules/readerwikipedia.lua
local ReaderDictionary = require("apps/reader/modules/readerdictionary") local Translator = require("ui/translator") local Wikipedia = require("ui/wikipedia") local DEBUG = require("dbg") local _ = require("gettext") -- Wikipedia as a special dictionary local ReaderWikipedia = ReaderDictionary:extend{ -- identify itself wiki = true, no_page = _("No wiki page found."), } -- the super "class" ReaderDictionary has already registers a menu entry -- we should override the init function in ReaderWikipedia function ReaderWikipedia:init() end function ReaderWikipedia:onLookupWikipedia(word, box) -- detect language of the text local ok, lang = pcall(Translator.detect, Translator, word) if not ok then return end -- convert "zh-CN" and "zh-TW" to "zh" lang = lang:match("(.*)-") or lang -- strip punctuation characters around selected word word = string.gsub(word, "^%p+", '') word = string.gsub(word, "%p+$", '') -- seems lower case phrase has higher hit rate word = string.lower(word) local results = {} local pages ok, pages = pcall(Wikipedia.wikintro, Wikipedia, word, lang) if ok and pages then for pageid, page in pairs(pages) do local result = { dict = _("Wikipedia"), word = page.title, definition = page.extract or self.no_page, } table.insert(results, result) end DEBUG("lookup result:", word, results) self:showDict(word, results, box) else DEBUG("error:", pages) -- dummy results results = { { dict = _("Wikipedia"), word = word, definition = self.no_page, } } DEBUG("dummy result table:", word, results) self:showDict(word, results, box) end end -- override onSaveSettings in ReaderDictionary function ReaderWikipedia:onSaveSettings() end return ReaderWikipedia
local ReaderDictionary = require("apps/reader/modules/readerdictionary") local Translator = require("ui/translator") local Wikipedia = require("ui/wikipedia") local DEBUG = require("dbg") local _ = require("gettext") -- Wikipedia as a special dictionary local ReaderWikipedia = ReaderDictionary:extend{ -- identify itself wiki = true, no_page = _("No wiki page found."), } -- the super "class" ReaderDictionary has already registers a menu entry -- we should override the init function in ReaderWikipedia function ReaderWikipedia:init() end function ReaderWikipedia:onLookupWikipedia(word, box) -- set language from book properties local lang = self.view.document:getProps().language if lang == nil then -- or set laguage from KOReader settings lang = G_reader_settings:readSetting("language") if lang == nil then -- or detect language local ok_translator ok_translator, lang = pcall(Translator.detect, Translator, word) if not ok_translator then return end end end -- convert "zh-CN" and "zh-TW" to "zh" lang = lang:match("(.*)-") or lang -- strip punctuation characters around selected word word = string.gsub(word, "^%p+", '') word = string.gsub(word, "%p+$", '') -- seems lower case phrase has higher hit rate word = string.lower(word) local results = {} local ok, pages = pcall(Wikipedia.wikintro, Wikipedia, word, lang) if ok and pages then for pageid, page in pairs(pages) do local result = { dict = _("Wikipedia"), word = page.title, definition = page.extract or self.no_page, } table.insert(results, result) end DEBUG("lookup result:", word, results) self:showDict(word, results, box) else DEBUG("error:", pages) -- dummy results results = { { dict = _("Wikipedia"), word = word, definition = self.no_page, } } DEBUG("dummy result table:", word, results) self:showDict(word, results, box) end end -- override onSaveSettings in ReaderDictionary function ReaderWikipedia:onSaveSettings() end return ReaderWikipedia
Patch for wikipedia language (#2304)
Patch for wikipedia language (#2304) * smarter language detection for wikipedia new order: * check language for document * check global language setting * check language for lookup phrase Fix: https://github.com/koreader/koreader/issues/1844
Lua
agpl-3.0
mwoz123/koreader,houqp/koreader,NiLuJe/koreader,pazos/koreader,Hzj-jie/koreader,NickSavage/koreader,koreader/koreader,robert00s/koreader,Frenzie/koreader,poire-z/koreader,Frenzie/koreader,lgeek/koreader,NiLuJe/koreader,poire-z/koreader,Markismus/koreader,koreader/koreader,mihailim/koreader,apletnev/koreader
8b8d83c993ed8b37bf971ca31b30be01bca87264
resty/test/doubles/in_mem_kv_store.lua
resty/test/doubles/in_mem_kv_store.lua
local _M = {} local mt = { __index = _M } local setmetatable = setmetatable local cjson = require("cjson") function _M:connect(addr, port) self.kv_store = {} self.addr = addr self.port = port end function _M:new(fail) self.fail = fail return setmetatable(self, mt) end function _M:set_fail(fail) self.fail = fail end function _M:select(index) if self.fail == 4 then return nil, {} end if self.kv_store[index] == nil then self.kv_store[index] = {} end self.index = index return {}, nil end function _M:hmset(prefix_key,upstream_name,upstream,ttl_name,ttl) if self.kv_store[self.index] == nil then self.kv_store[self.index] = {} end self.kv_store[self.index][prefix_key] = {} self.kv_store[self.index][prefix_key][upstream_name] = upstream self.kv_store[self.index][prefix_key][ttl_name] = ttl; return {},nil end function _M:hmget(prefix_key,upstream_name,ttl_name) return {self.kv_store[self.index][prefix_key][upstream_name],self.kv_store[self.index][prefix_key][ttl_name]} end function _M:hdel(prefix_key,name) if self.fail == 5 then return nil, {} end if self.fail == 6 then self.fail = 5 end self.kv_store[self.index][prefix_key][name] = nil if next(self.kv_store[self.index][prefix_key]) == nil then self.kv_store[self.index][prefix_key] = nil end return {},nil end function _M:set_timeout(time) self.timeout = time end function _M:flushdb() if self.fail == 1 then return nil, {} end self.kv_store[self.index] = nil return {},nil end function _M:multi() if self.fail == 2 then return nil, {} else return {},nil end end function _M:exec() if self.fail == 3 then return nil, {} else return {},nil end end return _M
local _M = {} local mt = { __index = _M } local setmetatable = setmetatable function _M:connect(addr, port) self.kv_store = {} self.addr = addr self.port = port end function _M:new(fail) self.fail = fail return setmetatable(self, mt) end function _M:set_fail(fail) self.fail = fail end function _M:select(index) if self.fail == 4 then return nil, {} end if self.kv_store[index] == nil then self.kv_store[index] = {} end self.index = index return {}, nil end function _M:hmset(prefix_key,upstream_name,upstream,ttl_name,ttl) if self.kv_store[self.index] == nil then self.kv_store[self.index] = {} end self.kv_store[self.index][prefix_key] = {} self.kv_store[self.index][prefix_key][upstream_name] = upstream self.kv_store[self.index][prefix_key][ttl_name] = ttl; return {},nil end function _M:hmget(prefix_key,upstream_name,ttl_name) return {self.kv_store[self.index][prefix_key][upstream_name],self.kv_store[self.index][prefix_key][ttl_name]} end function _M:hdel(prefix_key,name) if self.fail == 5 then return nil, {} end if self.fail == 6 then self.fail = 5 end self.kv_store[self.index][prefix_key][name] = nil if next(self.kv_store[self.index][prefix_key]) == nil then self.kv_store[self.index][prefix_key] = nil end return {},nil end function _M:set_timeout(time) self.timeout = time end function _M:flushdb() if self.fail == 1 then return nil, {} end self.kv_store[self.index] = nil return {},nil end function _M:multi() if self.fail == 2 then return nil, {} else return {},nil end end function _M:exec() if self.fail == 3 then return nil, {} else return {},nil end end return _M
Fix linter check error
Fix linter check error
Lua
apache-2.0
dhiaayachi/dynx,dhiaayachi/dynx
723bbc92382387d1b53a339aaa97c84c32f1f2cf
updateSunriseSunset.lua
updateSunriseSunset.lua
--[[ %% autostart %% properties %% globals --]] -- Script to turn off lights when no more motion is detected -- Remi Bergsma [email protected] -- Inspired by posts on the Fibaro forum http://forum.fibaro.com -- Note: This script needs a virtual device (id=90 in example) with two buttons. One to set the sun to 'Risen' and one to 'Set'. They should update the global var 'Sun'. -- The file Sun.vfib contains the export of this device. -- local vars local sunriseHour = fibaro:getValue(1,'sunriseHour') local sunsetHour = fibaro:getValue(1,'sunsetHour') local BeforeSunset = 0 local AfterSunrise = 0 local debug = 1 if debug ==1 then fibaro:debug("Today, sunrise is at " .. sunriseHour .. " and sunset at " .. sunsetHour) end while true do if (os.date("%H:%M", os.time()+BeforeSunset*60) >= sunsetHour) or (os.date("%H:%M", os.time()-AfterSunrise*60) < sunriseHour) then -- sun is set if (fibaro:getGlobalValue("Sun") ~= "Set") then fibaro:call(90, "pressButton", "2") if debug ==1 then fibaro:debug("Changed sunset var to Set") end end else -- sun is risen if (fibaro:getGlobalValue("Sun") ~= "Risen") then fibaro:call(90, "pressButton", "1") if debug ==1 then fibaro:debug("Changed sunset var to Risen") end end end -- running once a minute is enough fibaro:sleep(60000) end
--[[ %% autostart %% properties %% globals --]] -- Script to set sun to set/risen -- Remi Bergsma [email protected] -- Inspired by posts on the Fibaro forum http://forum.fibaro.com -- Note: This script needs a virtual device (id=90 in example) with two buttons. One to set the sun to 'Risen' and one to 'Set'. They should update the global var 'Sun'. -- The file Sun.vfib contains the export of this device. -- local vars local sunriseHour = fibaro:getValue(1,'sunriseHour') local sunsetHour = fibaro:getValue(1,'sunsetHour') local BeforeSunset = 0 local AfterSunrise = 0 local debug = 0 while true do sunriseHour = fibaro:getValue(1,'sunriseHour') sunsetHour = fibaro:getValue(1,'sunsetHour') if debug ==1 then fibaro:debug("Today, sunrise is at " .. sunriseHour .. " and sunset at " .. sunsetHour) end if (os.date("%H:%M", os.time()+BeforeSunset*60) >= sunsetHour) or (os.date("%H:%M", os.time()-AfterSunrise*60) < sunriseHour) then -- sun is set if (fibaro:getGlobalValue("Sun") ~= "Set") then fibaro:call(90, "pressButton", "2") if debug ==1 then fibaro:debug("Changed sunset var to Set") end end else -- sun is risen if (fibaro:getGlobalValue("Sun") ~= "Risen") then fibaro:call(90, "pressButton", "1") if debug ==1 then fibaro:debug("Changed sunset var to Risen") end end end -- running once a minute is enough fibaro:sleep(60000) end
fix bug that wouldn't refresh the set/rise times
fix bug that wouldn't refresh the set/rise times
Lua
apache-2.0
remibergsma/fibaro-hc2-scenes
d45f34eadd01b314ecc0ead373e15175b1148261
init.lua
init.lua
-- -- init.lua -- -- This is the initialization file of SSOwat. It is called once at the Nginx -- server's start. -- Consequently, all the variables declared (along with libraries and -- translations) in this file will be *persistent* from one HTTP request to -- another. -- -- Remove prepending '@' & trailing 'init.lua' script_path = string.sub(debug.getinfo(1).source, 2, -9) -- Include local libs in package.path package.path = package.path .. ";"..script_path.."?.lua" -- Load libraries local json = require "json" local lualdap = require "lualdap" local math = require "math" local lustache = require "lustache" local lfs = require "lfs" local socket = require "socket" local config = require "config" -- Persistent shared table flashs = {} i18n = {} -- convert a string to a hex function tohex(str) return (str:gsub('.', function (c) return string.format('%02X', string.byte(c)) end)) end -- Efficient function to get a random string function random_string() local random_bytes = io.open("/dev/urandom"):read(64); return tohex(random_bytes); end -- Load translations in the "i18n" above table local locale_dir = script_path.."portal/locales/" for file in lfs.dir(locale_dir) do if string.sub(file, -4) == "json" then local lang = string.sub(file, 1, 2) local locale_file = io.open(locale_dir..file, "r") i18n[lang] = json.decode(locale_file:read("*all")) end end -- Path of the configuration conf_path = "/etc/ssowat/conf.json" -- You should see that in your Nginx error logs by default ngx.log(ngx.INFO, "SSOwat ready")
-- -- init.lua -- -- This is the initialization file of SSOwat. It is called once at the Nginx -- server's start. -- Consequently, all the variables declared (along with libraries and -- translations) in this file will be *persistent* from one HTTP request to -- another. -- -- Remove prepending '@' & trailing 'init.lua' script_path = string.sub(debug.getinfo(1).source, 2, -9) -- Include local libs in package.path package.path = package.path .. ";"..script_path.."?.lua" -- Load libraries local json = require "json" local lualdap = require "lualdap" local math = require "math" local lfs = require "lfs" local socket = require "socket" local config = require "config" lustache = require "lustache" -- Persistent shared table flashs = {} i18n = {} -- convert a string to a hex function tohex(str) return (str:gsub('.', function (c) return string.format('%02X', string.byte(c)) end)) end -- Efficient function to get a random string function random_string() local random_bytes = io.open("/dev/urandom"):read(64); return tohex(random_bytes); end -- Load translations in the "i18n" above table local locale_dir = script_path.."portal/locales/" for file in lfs.dir(locale_dir) do if string.sub(file, -4) == "json" then local lang = string.sub(file, 1, 2) local locale_file = io.open(locale_dir..file, "r") i18n[lang] = json.decode(locale_file:read("*all")) end end -- Path of the configuration conf_path = "/etc/ssowat/conf.json" -- You should see that in your Nginx error logs by default ngx.log(ngx.INFO, "SSOwat ready")
bugfix scope
bugfix scope "local lustache" was causing a scope error in some setups.
Lua
agpl-3.0
YunoHost/SSOwat,Kloadut/SSOwat,Kloadut/SSOwat,YunoHost/SSOwat
c94367e065c2adec79d69d82f8b40647803ef117
modules/admin-full/luasrc/model/cbi/admin_system/admin.lua
modules/admin-full/luasrc/model/cbi/admin_system/admin.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Copyright 2011 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local fs = require "nixio.fs" m = Map("system", translate("Router Password"), translate("Changes the administrator password for accessing the device")) s = m:section(TypedSection, "_dummy", "") s.addremove = false s.anonymous = true pw1 = s:option(Value, "pw1", translate("Password")) pw1.password = true pw2 = s:option(Value, "pw2", translate("Confirmation")) pw2.password = true function s.cfgsections() return { "_pass" } end function m.on_commit(map) local v1 = pw1:formvalue("_pass") local v2 = pw2:formvalue("_pass") if v1 and v2 and #v1 > 0 and #v2 > 0 then if v1 == v2 then if luci.sys.user.setpasswd("root", v1) == 0 then m.message = translate("Password successfully changed!") else m.message = translate("Unknown Error, password not changed!") end else m.message = translate("Given password confirmation did not match, password not changed!") end end end m2 = Map("dropbear", translate("SSH Access"), translate("Dropbear offers <abbr title=\"Secure Shell\">SSH</abbr> network shell access and an integrated <abbr title=\"Secure Copy\">SCP</abbr> server")) s = m2:section(TypedSection, "dropbear", translate("Dropbear Instance")) s.anonymous = true s.addremove = true ni = s:option(Value, "Interface", translate("Interface"), translate("Listen only on the given interface or, if unspecified, on all")) ni.template = "cbi/network_netlist" ni.nocreate = true ni.unspecified = true pt = s:option(Value, "Port", translate("Port"), translate("Specifies the listening port of this <em>Dropbear</em> instance")) pt.datatype = "port" pt.default = 22 pa = s:option(Flag, "PasswordAuth", translate("Password authentication"), translate("Allow <abbr title=\"Secure Shell\">SSH</abbr> password authentication")) pa.enabled = "on" pa.disabled = "off" pa.default = pa.enabled pa.rmempty = false ra = s:option(Flag, "RootPasswordAuth", translate("Allow root logins with password"), translate("Allow the <em>root</em> user to login with password")) ra.enabled = "on" ra.disabled = "off" ra.default = ra.enabled gp = s:option(Flag, "GatewayPorts", translate("Gateway ports"), translate("Allow remote hosts to connect to local SSH forwarded ports")) gp.enabled = "on" gp.disabled = "off" gp.default = gp.disabled s2 = m2:section(TypedSection, "_dummy", translate("SSH-Keys"), translate("Here you can paste public SSH-Keys (one per line) for SSH public-key authentication.")) s2.addremove = false s2.anonymous = true s2.template = "cbi/tblsection" function s2.cfgsections() return { "_keys" } end keys = s2:option(TextValue, "_data", "") keys.wrap = "off" keys.rows = 3 keys.rmempty = false function keys.cfgvalue() return fs.readfile("/etc/dropbear/authorized_keys") or "" end function keys.write(self, section, value) if value then fs.writefile("/etc/dropbear/authorized_keys", value:gsub("\r\n", "\n")) end end return m, m2
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Copyright 2011 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local fs = require "nixio.fs" m = Map("system", translate("Router Password"), translate("Changes the administrator password for accessing the device")) s = m:section(TypedSection, "_dummy", "") s.addremove = false s.anonymous = true pw1 = s:option(Value, "pw1", translate("Password")) pw1.password = true pw2 = s:option(Value, "pw2", translate("Confirmation")) pw2.password = true function s.cfgsections() return { "_pass" } end function m.on_commit(map) local v1 = pw1:formvalue("_pass") local v2 = pw2:formvalue("_pass") if v1 and v2 and #v1 > 0 and #v2 > 0 then if v1 == v2 then if luci.sys.user.setpasswd("root", v1) == 0 then m.message = translate("Password successfully changed!") else m.message = translate("Unknown Error, password not changed!") end else m.message = translate("Given password confirmation did not match, password not changed!") end end end if fs.access("/etc/config/dropbear") then m2 = Map("dropbear", translate("SSH Access"), translate("Dropbear offers <abbr title=\"Secure Shell\">SSH</abbr> network shell access and an integrated <abbr title=\"Secure Copy\">SCP</abbr> server")) s = m2:section(TypedSection, "dropbear", translate("Dropbear Instance")) s.anonymous = true s.addremove = true ni = s:option(Value, "Interface", translate("Interface"), translate("Listen only on the given interface or, if unspecified, on all")) ni.template = "cbi/network_netlist" ni.nocreate = true ni.unspecified = true pt = s:option(Value, "Port", translate("Port"), translate("Specifies the listening port of this <em>Dropbear</em> instance")) pt.datatype = "port" pt.default = 22 pa = s:option(Flag, "PasswordAuth", translate("Password authentication"), translate("Allow <abbr title=\"Secure Shell\">SSH</abbr> password authentication")) pa.enabled = "on" pa.disabled = "off" pa.default = pa.enabled pa.rmempty = false ra = s:option(Flag, "RootPasswordAuth", translate("Allow root logins with password"), translate("Allow the <em>root</em> user to login with password")) ra.enabled = "on" ra.disabled = "off" ra.default = ra.enabled gp = s:option(Flag, "GatewayPorts", translate("Gateway ports"), translate("Allow remote hosts to connect to local SSH forwarded ports")) gp.enabled = "on" gp.disabled = "off" gp.default = gp.disabled s2 = m2:section(TypedSection, "_dummy", translate("SSH-Keys"), translate("Here you can paste public SSH-Keys (one per line) for SSH public-key authentication.")) s2.addremove = false s2.anonymous = true s2.template = "cbi/tblsection" function s2.cfgsections() return { "_keys" } end keys = s2:option(TextValue, "_data", "") keys.wrap = "off" keys.rows = 3 keys.rmempty = false function keys.cfgvalue() return fs.readfile("/etc/dropbear/authorized_keys") or "" end function keys.write(self, section, value) if value then fs.writefile("/etc/dropbear/authorized_keys", value:gsub("\r\n", "\n")) end end end return m, m2
modules/admin-full: fix System -> Administration menu if dropbear is not installed
modules/admin-full: fix System -> Administration menu if dropbear is not installed git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@8070 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci
9bec37ad9e622b65bdc892945fac6b482020f3fb
src/hs/just/init.lua
src/hs/just/init.lua
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- J U S T L I B R A R Y -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- Module created by David Peterson (https://github.com/randomeizer). -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- This module provides functions to help with performing tasks which may be -- delayed, up to a finite number of loops. -- -------------------------------------------------------------------------------- -- THE MODULE: -------------------------------------------------------------------------------- local just = {} local timer = require("hs.timer") --- hs.fcpxhacks.modules.just.doWhile(actionFn, period, loops) -> UI --- Function --- Performs an 'action' function, looping while the result of the function evaluates to 'true'. --- It will halt after 'loops' repetitions if the result is never 'false'. --- --- Parameters: --- * actionFn - a fuction which is called on each loop. It should return a 'truthy' value. --- * `timeout` - (optional) the number of seconds after which we will give up. Defaults to 1 second. --- * `frequency` - (optional) the number of loops to perform before giving up. Defaults to 1 millisecond. --- --- Returns: --- * The last return value of the action function. --- function just.doWhile(actionFn, timeout, frequency) timeout = timeout or 1.0 frequency = frequency or 0.001 local loops, extra = math.modf(timeout / frequency) if extra > 0 then loops = loops + 1 end local period = frequency * 1000000 local count = 0 local result = true while count <= loops and result do if count > 0 then timer.usleep(period) end result = actionFn() count = count + 1 end return result end --- hs.fcpxhacks.modules.just.doUntil(actionFn, period, loops) -> result --- Function --- Performs an `action` function, looping until the result of the function evaluates to `true` (or a non-nil value). --- It will halt after the `timeout` (default) --- --- Parameters: --- * `actionFn` - a fuction which is called on each loop. It should return a 'truthy' value. --- * `timeout` - (optional) the number of seconds after which we will give up. Defaults to 1 second. --- * `frequency` - (optional) the number of loops to perform before giving up. Defaults to 1 millisecond. --- --- Returns: --- * The last return value of the action function. --- function just.doUntil(actionFn, timeout, frequency) timeout = timeout or 1.0 frequency = frequency or 0.001 local loops, extra = math.modf(timeout / frequency) if extra > 0 then loops = loops + 1 end local period = frequency * 1000000 local count = 0 local result = nil while count <= loops and not result do if count > 0 then timer.usleep(period) end result = actionFn() count = count + 1 end return result end --- hs.fcpxhacks.modules.just.wait(integer) -> nil --- Function --- Pauses the application for the specified number of seconds. --- --- Parameters: --- * periodInSeconds - the number of seconds to pause for. --- --- Returns: --- * N/A --- function just.wait(periodInSeconds) timer.usleep(periodInSeconds * 1000000) end return just
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- J U S T L I B R A R Y -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- Module created by David Peterson (https://github.com/randomeizer). -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- This module provides functions to help with performing tasks which may be -- delayed, up to a finite number of loops. -- -------------------------------------------------------------------------------- -- THE MODULE: -------------------------------------------------------------------------------- local just = {} local timer = require("hs.timer") --- hs.just.doWhile(actionFn, period, loops) -> UI --- Function --- Performs an 'action' function, looping while the result of the function evaluates to 'true'. --- It will halt after 'loops' repetitions if the result is never 'false'. --- --- Parameters: --- * actionFn - a fuction which is called on each loop. It should return a 'truthy' value. --- * `timeout` - (optional) the number of seconds after which we will give up. Defaults to 1 second. --- * `frequency` - (optional) the number of loops to perform before giving up. Defaults to 1 millisecond. --- --- Returns: --- * The last return value of the action function. --- function just.doWhile(actionFn, timeout, frequency) timeout = timeout or 1.0 frequency = frequency or 0.001 local period = frequency * 1000000 local stopTime = timer.secondsSinceEpoch() + timeout local result = true while result and timer.secondsSinceEpoch() < stopTime do result = actionFn() timer.usleep(period) end return result end --- hs.just.doUntil(actionFn, period, loops) -> result --- Function --- Performs an `action` function, looping until the result of the function evaluates to `true` (or a non-nil value). --- It will halt after the `timeout` (default) --- --- Parameters: --- * `actionFn` - a fuction which is called on each loop. It should return a 'truthy' value. --- * `timeout` - (optional) the number of seconds after which we will give up. Defaults to 1 second. --- * `frequency` - (optional) the number of loops to perform before giving up. Defaults to 1 millisecond. --- --- Returns: --- * The last return value of the action function. --- function just.doUntil(actionFn, timeout, frequency) timeout = timeout or 1.0 frequency = frequency or 0.001 local period = frequency * 1000000 local stopTime = timer.secondsSinceEpoch() + timeout local result = false while not result and timer.secondsSinceEpoch() < stopTime do result = actionFn() timer.usleep(period) end return result end --- hs.just.wait(integer) -> nil --- Function --- Pauses the application for the specified number of seconds. --- --- Parameters: --- * periodInSeconds - the number of seconds to pause for. --- --- Returns: --- * N/A --- function just.wait(periodInSeconds) timer.usleep(periodInSeconds * 1000000) end return just
#168 * Fixed timeout for just.doUntil/doWhile
#168 * Fixed timeout for just.doUntil/doWhile
Lua
mit
cailyoung/CommandPost,CommandPost/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost,cailyoung/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost,cailyoung/CommandPost
5a95dc751ca8eadb9c75cfa4fec1dfb75682bd45
asset/src/scenes/TestViewController.lua
asset/src/scenes/TestViewController.lua
local TestViewController = class("TestViewController", function() return mw.ViewController:create() end) function TestViewController:viewDidLoad() log("Test GameScene parameters...") log("NUMBER: %d", self:scene():getNumberParameter("NUMBER")) log("STRING: %s", self:scene():getStringParameter("STRING")) log("BOOLEAN: %s", tostring(self:scene():getBooleanParameter("BOOLEAN"))) log("REF: %s", GetType(self:scene():getRefParameter("REF"))) log("Test ZipData and GifSprite...") local zipData = mw.ZipData:createWithExistingFile("res/GIF/pokemon_gif5.rc", "7ujm,lp-") zipData:beginUnzip() local data1 = zipData:getCompressedFileData("487_o.gif") local data2 = zipData:getCompressedFileData("493.gif") zipData:endUnzip() local gif1 = mw.GifSprite:createWithRawData(data1) local gif2 = mw.GifSprite:createWithRawData(data2) local pDict = mw.Dictionary:create() pDict:setObjectForKey("GIF1", gif1) pDict:setObjectForKey("GIF2", gif2) local keys = pDict:allKeys() for i, key in ipairs(keys) do local sp = pDict:objectForKey(key) tolua.cast(sp, "mw.GifSprite") sp:setPosition(Device:width() * (0.25 + (i - 1) * 0.5), Device:height() * 0.5) self:view():addChild(sp) end local svg = mw.SvgSprite:createWithFile("tiger.svg") svg:setPosition(Device:cx(), Device:cy()) svg:setVectorScale(0.5) self:view():addChild(svg) bindable(svg):addComponent("framework.components.ui.longtouch"):exportMethods() svg:setDelegate(self) log("Test Sqlite DB...") local db = mw.SqliteDb:openDb("res/icon.jpg") local t = db:executeQuery("select * from [pet_info] where [id] = '493'"); table.dump(t) log("Test some utils...") local reachabilityStrMap = { [0] = "No network.", [1] = "Wifi", [2] = "WWAN", } log("NetStatus: %s", reachabilityStrMap[mw.SystemHelper:getInstance():checkNetStatus()]) log("UUID: %s", mw.UUIDGenerator:getInstance():generateUUID()) log("Test protobuf...") local pb = protobuf pb.register_file("res/addressbook.pb") local code = pb.encode("tutorial.Person", { name = "Winder", id = 18, phone = { { number = "021-55555555" }, { number = "13311122244", type = "WORK" } } }) log("DECODING...") local data = pb.decode("tutorial.Person", code) log("ID: %d", data.id) log("NAME: %s", data.name) log("PHONE: ") for _, v in ipairs(data.phone) do log("\t%s\t%s", v.number, v.type) end end function TestViewController:viewDidUnload() end function TestViewController:onLongTouchBegan(target, loc, ts) print("TestViewController:onLongTouchBegan", target, loc, ts) self._beginPos = target:convertToNodeSpace(loc) end function TestViewController:onLongTouchPressed(target, loc, ts) print("TestViewController:onLongTouchPressed", target, loc, ts) local vec = cc.pSub(target:convertToNodeSpace(loc), self._beginPos) target:setPosition(cc.pAdd(cc.p(target:getPosition()), vec)) end function TestViewController:onLongTouchEnded(target, loc, ts) print("TestViewController:onLongTouchEnded", target, loc, ts) self._beginPos = nil end function TestViewController:onClick(target) print("TestViewController:onClick", target) end return TestViewController
local TestViewController = class("TestViewController", function() return mw.ViewController:create() end) function TestViewController:viewDidLoad() log("Test GameScene parameters...") log("NUMBER: %d", self:scene():getNumberParameter("NUMBER")) log("STRING: %s", self:scene():getStringParameter("STRING")) log("BOOLEAN: %s", tostring(self:scene():getBooleanParameter("BOOLEAN"))) log("REF: %s", GetType(self:scene():getRefParameter("REF"))) log("Test ZipData and GifSprite...") local zipData = mw.ZipData:createWithExistingFile("res/GIF/pokemon_gif5.rc", "7ujm,lp-") zipData:beginUnzip() local data1 = zipData:getCompressedFileData("487_o.gif") local data2 = zipData:getCompressedFileData("493.gif") zipData:endUnzip() local gif1 = mw.GifSprite:createWithRawData(data1) local gif2 = mw.GifSprite:createWithRawData(data2) local pDict = mw.Dictionary:create() pDict:setObjectForKey("GIF1", gif1) pDict:setObjectForKey("GIF2", gif2) local keys = pDict:allKeys() for i, key in ipairs(keys) do local sp = pDict:objectForKey(key) tolua.cast(sp, "mw.GifSprite") sp:setPosition(Device:width() * (0.25 + (i - 1) * 0.5), Device:height() * 0.5) self:view():addChild(sp) end local svg = mw.SvgSprite:createWithFile("tiger.svg") svg:setPosition(Device:cx(), Device:cy()) svg:setVectorScale(0.5) self:view():addChild(svg) bindable(svg):addComponent("framework.components.ui.longtouch"):exportMethods() svg:setDelegate(self) log("Test Sqlite DB...") local db = mw.SqliteDb:openDb("res/icon.jpg") local t = db:executeQuery("select * from [pet_info] where [id] = '493'"); table.dump(t) log("Test some utils...") local reachabilityStrMap = { [0] = "No network.", [1] = "Wifi", [2] = "WWAN", } log("NetStatus: %s", reachabilityStrMap[mw.SystemHelper:getInstance():checkNetStatus()]) log("UUID: %s", mw.UUIDGenerator:getInstance():generateUUID()) log("Test protobuf...") local pb = protobuf pb.register_file(cc.FileUtils:getInstance():fullPathForFilename("res/addressbook.pb")) local code = pb.encode("tutorial.Person", { name = "Winder", id = 18, phone = { { number = "021-55555555" }, { number = "13311122244", type = "WORK" } } }) log("DECODING...") local data = pb.decode("tutorial.Person", code) log("ID: %d", data.id) log("NAME: %s", data.name) log("PHONE: ") for _, v in ipairs(data.phone) do log("\t%s\t%s", v.number, v.type) end end function TestViewController:viewDidUnload() end function TestViewController:onLongTouchBegan(target, loc, ts) print("TestViewController:onLongTouchBegan", target, loc, ts) self._beginPos = target:convertToNodeSpace(loc) end function TestViewController:onLongTouchPressed(target, loc, ts) print("TestViewController:onLongTouchPressed", target, loc, ts) local vec = cc.pSub(target:convertToNodeSpace(loc), self._beginPos) target:setPosition(cc.pAdd(cc.p(target:getPosition()), vec)) end function TestViewController:onLongTouchEnded(target, loc, ts) print("TestViewController:onLongTouchEnded", target, loc, ts) self._beginPos = nil end function TestViewController:onClick(target) print("TestViewController:onClick", target) end return TestViewController
fix pb to absolute path
fix pb to absolute path
Lua
apache-2.0
wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua
b6f5941649046f0f1df2420e01d2249786a294cf
lgi/override/Gst.lua
lgi/override/Gst.lua
------------------------------------------------------------------------------ -- -- LGI Gst override module. -- -- Copyright (c) 2010, 2011, 2012 Pavel Holejsovsky -- Licensed under the MIT license: -- http://www.opensource.org/licenses/mit-license.php -- ------------------------------------------------------------------------------ local ipairs = ipairs local lgi = require 'lgi' local gi = require('lgi.core').gi local GLib = lgi.GLib local Gst = lgi.Gst -- GstObject has special ref_sink mechanism, make sure that lgi core -- is aware of it, otherwise refcounting is screwed. Gst.Object._refsink = gi.Gst.Object.methods.ref_sink -- Gst.Element; GstElement uses ugly macro accessors instead of proper -- GObject properties, so add attributes for assorted Gst.Element -- properties. Gst.Element._attribute = {} for _, name in ipairs { 'name', 'parent', 'bus', 'clock', 'base_time', 'start_time', 'factory', 'index', 'state' } do Gst.Element._attribute[name] = { get = Gst.Element['get_' .. name], set = Gst.Element['set_' .. name], } end function Gst.Element._method:link_many(...) local target = self for _, source in ipairs {...} do if not target:link(source) then return false end target = source end return true end -- Gst.Bin adjustments function Gst.Bus._method:add_watch(callback) return self:add_watch_full(GLib.PRIORITY_DEFAULT, callback) end function Gst.Bin._method:add_many(...) local args = {...} for i = 1, #args do self:add(args[i]) end end -- Gst.TagList adjustments if not Gst.TagList.copy_value then Gst.TagList._method.copy_value = Gst.tag_list_copy_value end function Gst.TagList:get(tag) local gvalue = self:copy_value(tag) return gvalue and gvalue.value end -- Load additional Gst modules. local GstInterfaces = lgi.require('GstInterfaces', Gst._version) -- Initialize gstreamer. Gst.init()
------------------------------------------------------------------------------ -- -- LGI Gst override module. -- -- Copyright (c) 2010, 2011, 2012 Pavel Holejsovsky -- Licensed under the MIT license: -- http://www.opensource.org/licenses/mit-license.php -- ------------------------------------------------------------------------------ local ipairs = ipairs local os = require 'os' local lgi = require 'lgi' local gi = require('lgi.core').gi local GLib = lgi.GLib local Gst = lgi.Gst -- GstObject has special ref_sink mechanism, make sure that lgi core -- is aware of it, otherwise refcounting is screwed. Gst.Object._refsink = gi.Gst.Object.methods.ref_sink -- Gst.Element; GstElement uses ugly macro accessors instead of proper -- GObject properties, so add attributes for assorted Gst.Element -- properties. Gst.Element._attribute = {} for _, name in ipairs { 'name', 'parent', 'bus', 'clock', 'base_time', 'start_time', 'factory', 'index', 'state' } do Gst.Element._attribute[name] = { get = Gst.Element['get_' .. name], set = Gst.Element['set_' .. name], } end function Gst.Element._method:link_many(...) local target = self for _, source in ipairs {...} do if not target:link(source) then return false end target = source end return true end -- Gst.Bin adjustments function Gst.Bus._method:add_watch(callback) return self:add_watch_full(GLib.PRIORITY_DEFAULT, callback) end function Gst.Bin._method:add_many(...) local args = {...} for i = 1, #args do self:add(args[i]) end end -- Gst.TagList adjustments if not Gst.TagList.copy_value then Gst.TagList._method.copy_value = Gst.tag_list_copy_value end function Gst.TagList:get(tag) local gvalue = self:copy_value(tag) return gvalue and gvalue.value end -- Load additional Gst modules. local GstInterfaces = lgi.require('GstInterfaces', Gst._version) -- Initialize gstreamer. Gst.init() -- Undo unfortunate gstreamer's setlocale(LC_ALL, ""), which breaks -- Lua's tonumber() implementation for some locales (e.g. pl_PL, pt_BR -- and probably many others). os.setlocale ('C', 'numeric')
Fix gstreamer automatically calling setlocale()
Fix gstreamer automatically calling setlocale() Continuation of previous setlocale() fix. https://github.com/pavouk/lgi/issues/19
Lua
mit
pavouk/lgi,zevv/lgi,psychon/lgi
5cda0b71d7219f5bbe060ceef2a708ae05b78ff4
lib/image_loader.lua
lib/image_loader.lua
local gm = require 'graphicsmagick' local ffi = require 'ffi' local iproc = require 'iproc' require 'pl' local image_loader = {} local clip_eps8 = (1.0 / 255.0) * 0.5 - (1.0e-7 * (1.0 / 255.0) * 0.5) local clip_eps16 = (1.0 / 65535.0) * 0.5 - (1.0e-7 * (1.0 / 65535.0) * 0.5) local background_color = 0.5 function image_loader.encode_png(rgb, depth) depth = depth or 8 rgb = iproc.byte2float(rgb) if depth < 16 then rgb = rgb:clone():add(clip_eps8) rgb[torch.lt(rgb, 0.0)] = 0.0 rgb[torch.gt(rgb, 1.0)] = 1.0 else rgb = rgb:clone():add(clip_eps16) rgb[torch.lt(rgb, 0.0)] = 0.0 rgb[torch.gt(rgb, 1.0)] = 1.0 end local im if rgb:size(1) == 4 then -- RGBA im = gm.Image(rgb, "RGBA", "DHW") elseif rgb:size(1) == 3 then -- RGB im = gm.Image(rgb, "RGB", "DHW") elseif rgb:size(1) == 1 then -- Y im = gm.Image(rgb, "I", "DHW") -- im:colorspace("GRAY") -- it does not work end return im:depth(depth):format("PNG"):toString(9) end function image_loader.save_png(filename, rgb, depth) depth = depth or 8 local blob = image_loader.encode_png(rgb, depth) local fp = io.open(filename, "wb") if not fp then error("IO error: " .. filename) end fp:write(blob) fp:close() return true end function image_loader.decode_float(blob) local load_image = function() local im = gm.Image() local alpha = nil local gamma_lcd = 0.454545 im:fromBlob(blob, #blob) if im:colorspace() == "CMYK" then im:colorspace("RGB") end local gamma = math.floor(im:gamma() * 1000000) / 1000000 if gamma ~= 0 and gamma ~= gamma_lcd then im:gammaCorrection(gamma / gamma_lcd) end -- FIXME: How to detect that a image has an alpha channel? if blob:sub(1, 4) == "\x89PNG" or blob:sub(1, 3) == "GIF" then -- split alpha channel im = im:toTensor('float', 'RGBA', 'DHW') local sum_alpha = (im[4] - 1.0):sum() if sum_alpha < 0 then alpha = im[4]:reshape(1, im:size(2), im:size(3)) -- drop full transparent background local mask = torch.le(alpha, 0.0) im[1][mask] = background_color im[2][mask] = background_color im[3][mask] = background_color end local new_im = torch.FloatTensor(3, im:size(2), im:size(3)) new_im[1]:copy(im[1]) new_im[2]:copy(im[2]) new_im[3]:copy(im[3]) im = new_im else im = im:toTensor('float', 'RGB', 'DHW') end return {im, alpha, blob} end local state, ret = pcall(load_image) if state then return ret[1], ret[2], ret[3] else return nil, nil, nil end end function image_loader.decode_byte(blob) local im, alpha im, alpha, blob = image_loader.decode_float(blob) if im then im = iproc.float2byte(im) -- hmm, alpha does not convert here return im, alpha, blob else return nil, nil, nil end end function image_loader.load_float(file) local fp = io.open(file, "rb") if not fp then error(file .. ": failed to load image") end local buff = fp:read("*a") fp:close() return image_loader.decode_float(buff) end function image_loader.load_byte(file) local fp = io.open(file, "rb") if not fp then error(file .. ": failed to load image") end local buff = fp:read("*a") fp:close() return image_loader.decode_byte(buff) end local function test() torch.setdefaulttensortype("torch.FloatTensor") local a = image_loader.load_float("../images/lena.png") local blob = image_loader.encode_png(a) local b = image_loader.decode_float(blob) assert((b - a):abs():sum() == 0) a = image_loader.load_byte("../images/lena.png") blob = image_loader.encode_png(a) b = image_loader.decode_byte(blob) assert((b:float() - a:float()):abs():sum() == 0) end --test() return image_loader
local gm = require 'graphicsmagick' local ffi = require 'ffi' local iproc = require 'iproc' require 'pl' local image_loader = {} local clip_eps8 = (1.0 / 255.0) * 0.5 - (1.0e-7 * (1.0 / 255.0) * 0.5) local clip_eps16 = (1.0 / 65535.0) * 0.5 - (1.0e-7 * (1.0 / 65535.0) * 0.5) local background_color = 0.5 function image_loader.encode_png(rgb, depth) depth = depth or 8 rgb = iproc.byte2float(rgb) if depth < 16 then rgb = rgb:clone():add(clip_eps8) rgb[torch.lt(rgb, 0.0)] = 0.0 rgb[torch.gt(rgb, 1.0)] = 1.0 rgb = rgb:mul(255):long():float():div(255) else rgb = rgb:clone():add(clip_eps16) rgb[torch.lt(rgb, 0.0)] = 0.0 rgb[torch.gt(rgb, 1.0)] = 1.0 rgb = rgb:mul(65535):long():float():div(65535) end local im if rgb:size(1) == 4 then -- RGBA im = gm.Image(rgb, "RGBA", "DHW") elseif rgb:size(1) == 3 then -- RGB im = gm.Image(rgb, "RGB", "DHW") elseif rgb:size(1) == 1 then -- Y im = gm.Image(rgb, "I", "DHW") -- im:colorspace("GRAY") -- it does not work end return im:depth(depth):format("PNG"):toString(9) end function image_loader.save_png(filename, rgb, depth) depth = depth or 8 local blob = image_loader.encode_png(rgb, depth) local fp = io.open(filename, "wb") if not fp then error("IO error: " .. filename) end fp:write(blob) fp:close() return true end function image_loader.decode_float(blob) local load_image = function() local im = gm.Image() local alpha = nil local gamma_lcd = 0.454545 im:fromBlob(blob, #blob) if im:colorspace() == "CMYK" then im:colorspace("RGB") end local gamma = math.floor(im:gamma() * 1000000) / 1000000 if gamma ~= 0 and gamma ~= gamma_lcd then im:gammaCorrection(gamma / gamma_lcd) end -- FIXME: How to detect that a image has an alpha channel? if blob:sub(1, 4) == "\x89PNG" or blob:sub(1, 3) == "GIF" then -- split alpha channel im = im:toTensor('float', 'RGBA', 'DHW') local sum_alpha = (im[4] - 1.0):sum() if sum_alpha < 0 then alpha = im[4]:reshape(1, im:size(2), im:size(3)) -- drop full transparent background local mask = torch.le(alpha, 0.0) im[1][mask] = background_color im[2][mask] = background_color im[3][mask] = background_color end local new_im = torch.FloatTensor(3, im:size(2), im:size(3)) new_im[1]:copy(im[1]) new_im[2]:copy(im[2]) new_im[3]:copy(im[3]) im = new_im else im = im:toTensor('float', 'RGB', 'DHW') end return {im, alpha, blob} end local state, ret = pcall(load_image) if state then return ret[1], ret[2], ret[3] else return nil, nil, nil end end function image_loader.decode_byte(blob) local im, alpha im, alpha, blob = image_loader.decode_float(blob) if im then im = iproc.float2byte(im) -- hmm, alpha does not convert here return im, alpha, blob else return nil, nil, nil end end function image_loader.load_float(file) local fp = io.open(file, "rb") if not fp then error(file .. ": failed to load image") end local buff = fp:read("*a") fp:close() return image_loader.decode_float(buff) end function image_loader.load_byte(file) local fp = io.open(file, "rb") if not fp then error(file .. ": failed to load image") end local buff = fp:read("*a") fp:close() return image_loader.decode_byte(buff) end local function test() torch.setdefaulttensortype("torch.FloatTensor") local a = image_loader.load_float("../images/lena.png") local blob = image_loader.encode_png(a) local b = image_loader.decode_float(blob) assert((b - a):abs():sum() == 0) a = image_loader.load_byte("../images/lena.png") blob = image_loader.encode_png(a) b = image_loader.decode_byte(blob) assert((b:float() - a:float()):abs():sum() == 0) end --test() return image_loader
Fix weird value in alpha channel
Fix weird value in alpha channel
Lua
mit
nagadomi/waifu2x,Spitfire1900/upscaler,vitaliylag/waifu2x,nagadomi/waifu2x,zyhkz/waifu2x,vitaliylag/waifu2x,Spitfire1900/upscaler,nagadomi/waifu2x,nagadomi/waifu2x,zyhkz/waifu2x,higankanshi/waifu2x,zyhkz/waifu2x,nagadomi/waifu2x,zyhkz/waifu2x,higankanshi/waifu2x,higankanshi/waifu2x,vitaliylag/waifu2x
3196c8aeff17f326e8b731a4a08c98303a1ab504
game/scripts/vscripts/custom_events.lua
game/scripts/vscripts/custom_events.lua
Events:Register("activate", function () CustomGameEventManager:RegisterListener("custom_chat_send_message", Dynamic_Wrap(GameMode, "CustomChatSendMessage")) CustomGameEventManager:RegisterListener("metamorphosis_elixir_cast", Dynamic_Wrap(GameMode, "MetamorphosisElixirCast")) CustomGameEventManager:RegisterListener("modifier_clicked_purge", Dynamic_Wrap(GameMode, "ModifierClickedPurge")) CustomGameEventManager:RegisterListener("options_vote", Dynamic_Wrap(Options, "OnVote")) CustomGameEventManager:RegisterListener("team_select_host_set_player_team", Dynamic_Wrap(GameMode, "TeamSelectHostSetPlayerTeam")) CustomGameEventManager:RegisterListener("set_help_disabled", Dynamic_Wrap(GameMode, "SetHelpDisabled")) CustomGameEventManager:RegisterListener("on_ads_clicked", Dynamic_Wrap(GameMode, "OnAdsClicked")) end) function GameMode:MetamorphosisElixirCast(data) local hero = PlayerResource:GetSelectedHeroEntity(data.PlayerID) local elixirItem = FindItemInInventoryByName(hero, "item_metamorphosis_elixir", false) local newHeroName = tostring(data.hero) if IsValidEntity(hero) and hero:GetFullName() ~= newHeroName and HeroSelection:IsHeroPickAvaliable(newHeroName) and (elixirItem or hero.ForcedHeroChange) and (hero.ForcedHeroChange or Options:IsEquals("EnableRatingAffection", false) or PlayerResource:GetPlayerStat(data.PlayerID, "ChangedHeroAmount") == 0) then if not Duel:IsDuelOngoing() then if HeroSelection:ChangeHero(data.PlayerID, newHeroName, true, elixirItem and elixirItem:GetSpecialValueFor("transformation_time") or 0, elixirItem) then PlayerResource:ModifyPlayerStat(data.PlayerID, "ChangedHeroAmount", 1) end else Containers:DisplayError(data.PlayerID, "#arena_hud_error_cant_change_hero") end end end function GameMode:ModifierClickedPurge(data) if data.PlayerID and data.unit and data.modifier then local ent = EntIndexToHScript(data.unit) if IsValidEntity(ent) and ent:IsAlive() and ent:GetPlayerOwner() == PlayerResource:GetPlayer(data.PlayerID) and table.contains(ONCLICK_PURGABLE_MODIFIERS, data.modifier) and not ent:IsStunned() and not ent:IsChanneling() then ent:RemoveModifierByName(data.modifier) end end end function GameMode:TeamSelectHostSetPlayerTeam(data) if GameRules:PlayerHasCustomGameHostPrivileges(PlayerResource:GetPlayer(data.PlayerID)) and data.player then if data.team then PlayerResource:SetCustomTeamAssignment(tonumber(data.player), tonumber(data.team)) end if data.player2 then local team = PlayerResource:GetCustomTeamAssignment(data.player) local team2 = PlayerResource:GetCustomTeamAssignment(data.player2) PlayerResource:SetCustomTeamAssignment(tonumber(data.player2), DOTA_TEAM_NOTEAM) PlayerResource:SetCustomTeamAssignment(tonumber(data.player), team2) PlayerResource:SetCustomTeamAssignment(tonumber(data.player2), team) end end end function GameMode:SetHelpDisabled(data) local player = data.player or -1 if PlayerResource:IsValidPlayerID(player) then PlayerResource:SetDisableHelpForPlayerID(data.PlayerID, player, tonumber(data.disabled) == 1) end end function GameMode:OnAdsClicked(data) local playerId = data.PlayerID local key = data.source == "loading_screen" and "adsClickedLoading" or "adsClicked" if not PLAYER_DATA[playerId][key] then PLAYER_DATA[playerId][key] = true end end
Events:Register("activate", function () CustomGameEventManager:RegisterListener("metamorphosis_elixir_cast", Dynamic_Wrap(GameMode, "MetamorphosisElixirCast")) CustomGameEventManager:RegisterListener("modifier_clicked_purge", Dynamic_Wrap(GameMode, "ModifierClickedPurge")) CustomGameEventManager:RegisterListener("options_vote", Dynamic_Wrap(Options, "OnVote")) CustomGameEventManager:RegisterListener("team_select_host_set_player_team", Dynamic_Wrap(GameMode, "TeamSelectHostSetPlayerTeam")) CustomGameEventManager:RegisterListener("set_help_disabled", Dynamic_Wrap(GameMode, "SetHelpDisabled")) CustomGameEventManager:RegisterListener("on_ads_clicked", Dynamic_Wrap(GameMode, "OnAdsClicked")) end) function GameMode:MetamorphosisElixirCast(data) local hero = PlayerResource:GetSelectedHeroEntity(data.PlayerID) local elixirItem = FindItemInInventoryByName(hero, "item_metamorphosis_elixir", false) local newHeroName = tostring(data.hero) if IsValidEntity(hero) and hero:GetFullName() ~= newHeroName and HeroSelection:IsHeroPickAvaliable(newHeroName) and (elixirItem or hero.ForcedHeroChange) and (hero.ForcedHeroChange or Options:IsEquals("EnableRatingAffection", false) or PlayerResource:GetPlayerStat(data.PlayerID, "ChangedHeroAmount") == 0) then if not Duel:IsDuelOngoing() then if HeroSelection:ChangeHero(data.PlayerID, newHeroName, true, elixirItem and elixirItem:GetSpecialValueFor("transformation_time") or 0, elixirItem) then PlayerResource:ModifyPlayerStat(data.PlayerID, "ChangedHeroAmount", 1) end else Containers:DisplayError(data.PlayerID, "#arena_hud_error_cant_change_hero") end end end function GameMode:ModifierClickedPurge(data) if data.PlayerID and data.unit and data.modifier then local ent = EntIndexToHScript(data.unit) if IsValidEntity(ent) and ent:IsAlive() and ent:GetPlayerOwner() == PlayerResource:GetPlayer(data.PlayerID) and table.contains(ONCLICK_PURGABLE_MODIFIERS, data.modifier) and not ent:IsStunned() and not ent:IsChanneling() then ent:RemoveModifierByName(data.modifier) end end end function GameMode:TeamSelectHostSetPlayerTeam(data) if GameRules:PlayerHasCustomGameHostPrivileges(PlayerResource:GetPlayer(data.PlayerID)) and data.player then if data.team then PlayerResource:SetCustomTeamAssignment(tonumber(data.player), tonumber(data.team)) end if data.player2 then local team = PlayerResource:GetCustomTeamAssignment(data.player) local team2 = PlayerResource:GetCustomTeamAssignment(data.player2) PlayerResource:SetCustomTeamAssignment(tonumber(data.player2), DOTA_TEAM_NOTEAM) PlayerResource:SetCustomTeamAssignment(tonumber(data.player), team2) PlayerResource:SetCustomTeamAssignment(tonumber(data.player2), team) end end end function GameMode:SetHelpDisabled(data) local player = data.player or -1 if PlayerResource:IsValidPlayerID(player) then PlayerResource:SetDisableHelpForPlayerID(data.PlayerID, player, tonumber(data.disabled) == 1) end end function GameMode:OnAdsClicked(data) local playerId = data.PlayerID local key = data.source == "loading_screen" and "adsClickedLoading" or "adsClicked" if not PLAYER_DATA[playerId][key] then PLAYER_DATA[playerId][key] = true end end
fix(chat): remove old event listener that throws errors now
fix(chat): remove old event listener that throws errors now
Lua
mit
ark120202/aabs
d57273aee05538861daddb17f96137ce76b90c94
asset/src/framework/mvc/model.lua
asset/src/framework/mvc/model.lua
--[[ Description: Model base Author: M.Wan Date: 04/29/2014 ]] local ModelBase = class("ModelBase") --[[ When you define your model, you must not forget to use _defineScheme method to define your model properties unless you know what you are doing. Scheme indicates the basic properties of the model. And when you set the scheme property of the model, you should use "self:_setProperties({prop = value})" instead of "self._prop = value". e.g. local MyModel = class("MyModel", ModelBase) function MyModel:ctor(id) self.super.ctor(self, id) self:_defineScheme({ age = "number", name = "string", }) end function MyModel:getAge() return self._age end function MyModel:getName() return self._name end function MyModel:grow() self:_setProperties({ age = self._age + 1 }) end function MyModel:changeName(newName) self:_setProperties({ name = newName }) end ]] function ModelBase:ctor(id) assert(type(id) ~= "string", "Invalid model id, id must be string type.") self._id = id self._scheme = { id = "string", } end function ModelBase:getId() return self._id end function ModelBase:_defineScheme(scheme) if type(scheme) ~= "table" then scheme = {} end for propName, propType in pairs(scheme) do if type(propType) == "string" then self._scheme[propName] = propType end end end function ModelBase:_setProperties(props) if type(props) ~= "table" then return end for propName, propValue in pairs(props) do local propType = self._scheme[propName] if propType and GetType(propValue) == propType then self["_" .. propName] = propValue elseif propType == nil then log("The property %s doesn't exist in your model scheme.", propName) else log("Wrong type of the property %s. The value type is %s, but it should be %s.", propName, GetType(propValue), propType) end end end return ModelBase
--[[ Description: Model base Author: M.Wan Date: 04/29/2014 ]] local ModelBase = class("ModelBase") --[[ When you define your model, you must not forget to use _defineScheme method to define your model properties unless you know what you are doing. Scheme indicates the basic properties of the model. And when you set the scheme property of the model, you should use "self:_setProperties({prop = value})" instead of "self._prop = value". e.g. local MyModel = class("MyModel", ModelBase) function MyModel:ctor(id) self.super.ctor(self, id) self:_defineScheme({ age = "number", name = "string", }) end function MyModel:getAge() return self._age end function MyModel:getName() return self._name end function MyModel:grow() self:_setProperties({ age = self._age + 1 }) end function MyModel:changeName(newName) self:_setProperties({ name = newName }) end ]] function ModelBase:ctor(id) assert(type(id) ~= "string", "Invalid model id, id must be string type.") self._id = id self._scheme = { id = "string", } end function ModelBase:getId() return self._id end function ModelBase:_defineScheme(scheme) if type(scheme) ~= "table" then scheme = {} end self._scheme = { id = "string" } for propName, propType in pairs(scheme) do if type(propType) == "string" then self._scheme[propName] = propType end end end function ModelBase:_setProperties(props) if type(props) ~= "table" then return end for propName, propValue in pairs(props) do local propType = self._scheme[propName] if propType and GetType(propValue) == propType then self["_" .. propName] = propValue elseif propType == nil then log("The property %s doesn't exist in your model scheme.", propName) else log("Wrong type of the property %s. The value type is %s, but it should be %s.", propName, GetType(propValue), propType) end end end return ModelBase
fix model scheme problem
fix model scheme problem
Lua
apache-2.0
wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua
0e4759f01c31758a01b011222201a85dd34c47b8
pb/proto/parser.lua
pb/proto/parser.lua
-- Copyright (c) 2010-2011 by Robert G. Jakabosky <[email protected]> -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. local lower = string.lower local tremove = table.remove local tsort = table.sort local assert = assert local pack = string.match(...,"[-_a-zA-Z0-9.]*[.]") or '' local lp = require"lpeg" local scanner = require(pack .. "scanner") local grammar = require(pack .. "grammar") -- field tag sort function. local function sort_tags(f1, f2) return f1.tag < f2.tag end -- create sub-table if it doesn't exists local function create(tab, sub_tab) if not tab[sub_tab] then tab[sub_tab] = {} end return tab[sub_tab] end local Cap = function(...) return ... end local function node_type(node) return node['.type'] end local function make_node(node_type, node) node = node or {} node['.type'] = node_type return node end local function CapNode(ntype, ...) local fields = {...} local fcount = #fields return function(...) local node = make_node(ntype, {...}) local idx = 0 -- process named fields for i=1,fcount do local name = fields[i] local val = tremove(node, 1) node[name] = val end return node end end local captures = { [1] = function(...) local types = {} local proto = { types = types, ... } local tcount = 0 for i=1,#proto do local sub = proto[i] local sub_type = node_type(sub) proto[i] = nil if sub_type == 'option' then create(proto, 'options') proto.options[sub.name] = sub.value elseif sub_type == 'package' then proto.package = sub.name elseif sub_type == 'import' then local imports = create(proto, 'imports') imports[#imports + 1] = sub elseif sub_type == 'service' then create(proto, 'services') proto.services[sub.name] = sub else -- map 'name' -> type types[sub.name] = sub -- add types to array tcount = tcount + 1 types[tcount] = sub end end return proto end, Package = CapNode("package", "name" ), Import = CapNode("import", "file" ), Option = CapNode("option", "name", "value" ), Message = function(name, body) local node = make_node('message', body) node.name = name return node end, MessageBody = function(...) local fields = {} local body = { fields = fields, ... } local types local tcount = 0 local fcount = 0 -- process sub-nodes for i=1,#body do -- remove sub-node local sub = body[i] local sub_type = node_type(sub) body[i] = nil if sub_type == 'field' then -- map 'name' -> field fields[sub.name] = sub -- map order -> field fcount = fcount + 1 fields[fcount] = sub elseif sub_type == 'extensions' then local list = create(body, 'extensions') local idx = #list -- append extensions for i=1,#sub do local range = sub[i] idx = idx + 1 list[idx] = range end else if tcount == 0 then types = create(body, 'types') end -- map 'name' -> sub-type types[sub.name] = sub -- add sub-types to array tcount = tcount + 1 types[tcount] = sub end end -- sort fields by tag tsort(fields, sort_tags) return body end, Group = function(rule, name, tag, body) local group_ftype = 'group_' .. name local group = make_node('group', body) group.name = group_ftype group.tag = tag local field = make_node('field',{ rule = rule, ftype = group_ftype, name = name, tag = tag, is_group = true, }) return group, field end, Enum = function(name, ...) local node = make_node('enum', {...}) local options local values = {} node.name = name node.values = values for i=1,#node do -- remove next sub-node. local sub = node[i] local sub_type = node_type(sub) node[i] = nil -- option/enum_field if sub_type == 'option' then if not options then options = {} -- Enum has options end options[sub.name] = sub.value else -- map 'name' -> value values[sub[1]] = sub[2] -- map value -> 'name' values[sub[2]] = sub[1] end end node.options = options return node end, EnumField = function(...) return {...} end, Field = function(rule, ftype, name, tag, options) local field = make_node('field', { rule = rule, ftype = ftype, name = name, tag = tag, options = options, }) -- process common options. if options then field.default = options.default field.is_deprecated = options.deprecated field.is_packed = options.packed if field.is_packed then assert(field.rule == 'repeated', "Only 'repeated' fields can be packed.") end end return field end, FieldOptions = function(...) local options = {...} for i=1,#options,2 do -- remove next option from list local name = options[i] options[i] = nil local value = options[i+1] options[i+1] = nil -- set option. options[name] = value end return options end, Extensions = CapNode("extensions" ), Extension = function(first, last) if not last then -- single value. return first end -- range return {first, last} end, Service = CapNode("service", "name" ), rpc = CapNode("rpc", "name", "request", "response" ), Name = Cap, GroupName = Cap, ID = Cap, Constant = Cap, IntLit = tonumber, SNumLit = tonumber, StrLit = function(quoted) assert(quoted:sub(1,1) == '"') return quoted:sub(2,-2) end, BoolLit = function(bool) bool = lower(bool) return (bool == 'true') end, FieldRule = Cap, Type = Cap, } local ast_patt = lp.P(grammar.apply({}, captures)) * (scanner.EOF + scanner.error"invalid character") module(...) function parse(contents) return ast_patt:match(contents) end
-- Copyright (c) 2010-2011 by Robert G. Jakabosky <[email protected]> -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. local lower = string.lower local tremove = table.remove local tsort = table.sort local assert = assert local pack = string.match(...,"[-_a-zA-Z0-9.]*[.]") or '' local lp = require"lpeg" local scanner = require(pack .. "scanner") local grammar = require(pack .. "grammar") -- field tag sort function. local function sort_tags(f1, f2) return f1.tag < f2.tag end -- create sub-table if it doesn't exists local function create(tab, sub_tab) if not tab[sub_tab] then tab[sub_tab] = {} end return tab[sub_tab] end local Cap = function(...) return ... end local function node_type(node) return node['.type'] end local function make_node(node_type, node) node = node or {} node['.type'] = node_type return node end local function CapNode(ntype, ...) local fields = {...} local fcount = #fields return function(...) local node = make_node(ntype, {...}) local idx = 0 -- process named fields for i=1,fcount do local name = fields[i] local val = tremove(node, 1) node[name] = val end return node end end local captures = { [1] = function(...) local types = {} local proto = { types = types, ... } local tcount = 0 for i=1,#proto do local sub = proto[i] local sub_type = node_type(sub) proto[i] = nil if sub_type == 'option' then create(proto, 'options') proto.options[sub.name] = sub.value elseif sub_type == 'package' then proto.package = sub.name elseif sub_type == 'import' then local imports = create(proto, 'imports') imports[#imports + 1] = sub elseif sub_type == 'service' then create(proto, 'services') proto.services[sub.name] = sub else -- map 'name' -> type types[sub.name] = sub -- add types to array tcount = tcount + 1 types[tcount] = sub end end return proto end, Package = CapNode("package", "name" ), Import = CapNode("import", "file" ), Option = CapNode("option", "name", "value" ), Message = function(name, body) local node = make_node('message', body) node.name = name return node end, MessageBody = function(...) local fields = {} local body = { fields = fields, ... } local types local tcount = 0 local fcount = 0 -- check for empty message. if #body == 1 then if type(body[1]) == 'string' then body[1] = nil end end -- process sub-nodes for i=1,#body do -- remove sub-node local sub = body[i] local sub_type = node_type(sub) body[i] = nil if sub_type == 'field' then -- map 'name' -> field fields[sub.name] = sub -- map order -> field fcount = fcount + 1 fields[fcount] = sub elseif sub_type == 'extensions' then local list = create(body, 'extensions') local idx = #list -- append extensions for i=1,#sub do local range = sub[i] idx = idx + 1 list[idx] = range end else if tcount == 0 then types = create(body, 'types') end -- map 'name' -> sub-type types[sub.name] = sub -- add sub-types to array tcount = tcount + 1 types[tcount] = sub end end -- sort fields by tag tsort(fields, sort_tags) return body end, Group = function(rule, name, tag, body) local group_ftype = 'group_' .. name local group = make_node('group', body) group.name = group_ftype group.tag = tag local field = make_node('field',{ rule = rule, ftype = group_ftype, name = name, tag = tag, is_group = true, }) return group, field end, Enum = function(name, ...) local node = make_node('enum', {...}) local options local values = {} node.name = name node.values = values for i=1,#node do -- remove next sub-node. local sub = node[i] local sub_type = node_type(sub) node[i] = nil -- option/enum_field if sub_type == 'option' then if not options then options = {} -- Enum has options end options[sub.name] = sub.value else -- map 'name' -> value values[sub[1]] = sub[2] -- map value -> 'name' values[sub[2]] = sub[1] end end node.options = options return node end, EnumField = function(...) return {...} end, Field = function(rule, ftype, name, tag, options) local field = make_node('field', { rule = rule, ftype = ftype, name = name, tag = tag, options = options, }) -- process common options. if options then field.default = options.default field.is_deprecated = options.deprecated field.is_packed = options.packed if field.is_packed then assert(field.rule == 'repeated', "Only 'repeated' fields can be packed.") end end return field end, FieldOptions = function(...) local options = {...} for i=1,#options,2 do -- remove next option from list local name = options[i] options[i] = nil local value = options[i+1] options[i+1] = nil -- set option. options[name] = value end return options end, Extensions = CapNode("extensions" ), Extension = function(first, last) if not last then -- single value. return first end -- range return {first, last} end, Service = CapNode("service", "name" ), rpc = CapNode("rpc", "name", "request", "response" ), Name = Cap, GroupName = Cap, ID = Cap, Constant = Cap, IntLit = tonumber, SNumLit = tonumber, StrLit = function(quoted) assert(quoted:sub(1,1) == '"') return quoted:sub(2,-2) end, BoolLit = function(bool) bool = lower(bool) return (bool == 'true') end, FieldRule = Cap, Type = Cap, } local ast_patt = lp.P(grammar.apply({}, captures)) * (scanner.EOF + scanner.error"invalid character") module(...) function parse(contents) return ast_patt:match(contents) end
Fix bug parsing empty MessageBody.
Fix bug parsing empty MessageBody.
Lua
mit
GabrielNicolasAvellaneda/lua-pb,tgregory/lua-pb
8df5d51b0650ab81680753efe9e126cab4063149
packages/lime-system/files/usr/lib/lua/lime/proto/bmx6.lua
packages/lime-system/files/usr/lib/lua/lime/proto/bmx6.lua
#!/usr/bin/lua bmx6 = {} function bmx6.setup_interface(interface, ifname) local real_ifname = ifname:gsub("^@lm_", "") x:set("bmx6", interface, "dev") x:set("bmx6", interface, "dev", real_ifname) x:save("bmx6") x:set("network", interface, "interface") x:set("network", interface, "ifname", ifname) x:set("network", interface, "proto", "none") x:set("network", interface, "auto", "1") x:save("network") end function bmx6.clean() print("Clearing bmx6 config...") fs.writefile("/etc/config/bmx6", "") end function bmx6.init() -- TODO end function bmx6.configure(v4, v6) bmx6.clean() x:set("bmx6", "general", "bmx6") x:set("bmx6", "general", "dbgMuteTimeout", "1000000") x:set("bmx6", "main", "tunDev") x:set("bmx6", "main", "tunDev", "main") x:set("bmx6", "main", "tun4Address", v4) x:set("bmx6", "main", "tun6Address", v6) -- Enable bmx6 uci config plugin x:set("bmx6", "config", "plugin") x:set("bmx6", "config", "plugin", "bmx6_config.so") -- Enable JSON plugin to get bmx6 information in json format x:set("bmx6", "json", "plugin") x:set("bmx6", "json", "plugin", "bmx6_json.so") -- Disable ThrowRules because they are broken in IPv6 with current Linux Kernel x:set("bmx6", "ipVersion", "ipVersion") x:set("bmx6", "ipVersion", "ipVersion", "6") -- Search for mesh node's IP x:set("bmx6", "nodes", "tunOut") x:set("bmx6", "nodes", "tunOut", "nodes") x:set("bmx6", "nodes", "network", "172.16.0.0/12") -- Search for clouds x:set("bmx6", "clouds", "tunOut") x:set("bmx6", "clouds", "tunOut", "clouds") x:set("bmx6", "clouds", "network", "10.0.0.0/8") -- Search for internet in the mesh cloud x:set("bmx6", "inet4", "tunOut") x:set("bmx6", "inet4", "tunOut", "inet4") x:set("bmx6", "inet4", "network", "0.0.0.0/0") x:set("bmx6", "inet4", "maxPrefixLen", "0") -- Search for internet IPv6 gateways in the mesh cloud x:set("bmx6", "inet6", "tunOut") x:set("bmx6", "inet6", "tunOut", "inet6") x:set("bmx6", "inet6", "network", "::/0") x:set("bmx6", "inet6", "maxPrefixLen", "0") -- Search for other mesh cloud announcements x:set("bmx6", "ula", "tunOut") x:set("bmx6", "ula", "tunOut", "ula") x:set("bmx6", "ula", "network", "fddf:ca00::/24") x:set("bmx6", "ula", "minPrefixLen", "48") -- Search for other mesh cloud announcements that have public ipv6 x:set("bmx6", "publicv6", "tunOut") x:set("bmx6", "publicv6", "tunOut", "publicv6") x:set("bmx6", "publicv6", "network", "2000::/3") x:set("bmx6", "publicv6", "maxPrefixLen", "64") x:save("bmx6") end function bmx6.apply() os.execute("killall bmx6 ; sleep 2 ; killall -9 bmx6") os.execute("bmx6") end return bmx6
#!/usr/bin/lua bmx6 = {} function bmx6.setup_interface(interface, ifname) local real_ifname = ifname:gsub("^@lm_", "") x:set("bmx6", interface, "dev") x:set("bmx6", interface, "dev", real_ifname) x:save("bmx6") x:set("network", interface, "interface") x:set("network", interface, "ifname", ifname) x:set("network", interface, "proto", "none") x:set("network", interface, "auto", "1") x:set("network", interface, "mtu", "1350") x:save("network") end function bmx6.clean() print("Clearing bmx6 config...") fs.writefile("/etc/config/bmx6", "") end function bmx6.init() -- TODO end function bmx6.configure(v4, v6) bmx6.clean() x:set("bmx6", "general", "bmx6") x:set("bmx6", "general", "dbgMuteTimeout", "1000000") x:set("bmx6", "main", "tunDev") x:set("bmx6", "main", "tunDev", "main") x:set("bmx6", "main", "tun4Address", v4) x:set("bmx6", "main", "tun6Address", v6) -- Enable bmx6 uci config plugin x:set("bmx6", "config", "plugin") x:set("bmx6", "config", "plugin", "bmx6_config.so") -- Enable JSON plugin to get bmx6 information in json format x:set("bmx6", "json", "plugin") x:set("bmx6", "json", "plugin", "bmx6_json.so") -- Disable ThrowRules because they are broken in IPv6 with current Linux Kernel x:set("bmx6", "ipVersion", "ipVersion") x:set("bmx6", "ipVersion", "ipVersion", "6") -- Search for mesh node's IP x:set("bmx6", "nodes", "tunOut") x:set("bmx6", "nodes", "tunOut", "nodes") x:set("bmx6", "nodes", "network", "172.16.0.0/12") -- Search for clouds x:set("bmx6", "clouds", "tunOut") x:set("bmx6", "clouds", "tunOut", "clouds") x:set("bmx6", "clouds", "network", "10.0.0.0/8") -- Search for internet in the mesh cloud x:set("bmx6", "inet4", "tunOut") x:set("bmx6", "inet4", "tunOut", "inet4") x:set("bmx6", "inet4", "network", "0.0.0.0/0") x:set("bmx6", "inet4", "maxPrefixLen", "0") -- Search for internet IPv6 gateways in the mesh cloud x:set("bmx6", "inet6", "tunOut") x:set("bmx6", "inet6", "tunOut", "inet6") x:set("bmx6", "inet6", "network", "::/0") x:set("bmx6", "inet6", "maxPrefixLen", "0") -- Search for other mesh cloud announcements x:set("bmx6", "ula", "tunOut") x:set("bmx6", "ula", "tunOut", "ula") x:set("bmx6", "ula", "network", "fddf:ca00::/24") x:set("bmx6", "ula", "minPrefixLen", "48") -- Search for other mesh cloud announcements that have public ipv6 x:set("bmx6", "publicv6", "tunOut") x:set("bmx6", "publicv6", "tunOut", "publicv6") x:set("bmx6", "publicv6", "network", "2000::/3") x:set("bmx6", "publicv6", "maxPrefixLen", "64") x:save("bmx6") end function bmx6.apply() os.execute("killall bmx6 ; sleep 2 ; killall -9 bmx6") os.execute("bmx6") end return bmx6
set mtu=1350 on bmx6 interfaces as a workaround until Axel fixes PMTUD of (a)symmetric ip6_tunnels
set mtu=1350 on bmx6 interfaces as a workaround until Axel fixes PMTUD of (a)symmetric ip6_tunnels
Lua
agpl-3.0
p4u/lime-packages,p4u/lime-packages,p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages,p4u/lime-packages,libremesh/lime-packages
9f50d2c72358cc4687a49c07bce087469f1be699
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 ( v == value ) and ( type( v ) == type( value ) ) then if ( multiple ) then table.insert( result, v ) else return v 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, 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
common: fixed findByValue not working with tables
common: fixed findByValue not working with tables
Lua
mit
smile-tmb/lua-mta-fairplay-roleplay
89f85d51a10e80332a21db55abc2614cbd033c2e
Samples/AntTweakBar/assets/MengerSponge.lua
Samples/AntTweakBar/assets/MengerSponge.lua
function GetShaderPath( ShaderName ) local ProcessedShaderPath = "" if Constants.DeviceType == "D3D11" or Constants.DeviceType == "D3D12" then ProcessedShaderPath = "shaders\\" .. ShaderName .. "_DX.hlsl" else ProcessedShaderPath = "shaders\\" .. ShaderName .. "_GL.glsl" end return ProcessedShaderPath end MainVS = Shader.Create{ FilePath = GetShaderPath("MainVS" ), UseCombinedTextureSamplers = true, Desc = { ShaderType = "SHADER_TYPE_VERTEX" } } MainPS = Shader.Create{ FilePath = GetShaderPath("MainPS" ), UseCombinedTextureSamplers = true, Desc = { ShaderType = "SHADER_TYPE_PIXEL" } } PSO = PipelineState.Create { Name = "Menger Sponge PSO", GraphicsPipeline = { DepthStencilDesc = { DepthEnable = true }, RasterizerDesc = { CullMode = "CULL_MODE_NONE" }, BlendDesc = { IndependentBlendEnable = false, RenderTargets = { {BlendEnable = false} } }, InputLayout = { { InputIndex = 0, NumComponents = 3, ValueType = "VT_FLOAT32"}, { InputIndex = 1, NumComponents = 3, ValueType = "VT_FLOAT32"}, { InputIndex = 2, NumComponents = 4, ValueType = "VT_UINT8", IsNormalized = true} }, PrimitiveTopology = "PRIMITIVE_TOPOLOGY_TRIANGLE_LIST", pVS = MainVS, pPS = MainPS, RTVFormats = extBackBufferFormat, DSVFormat = extDepthBufferFormat } } ResMapping = ResourceMapping.Create{ {Name = "Constants", pObject = extConstantBuffer} } MainVS:BindResources(ResMapping) MainPS:BindResources(ResMapping) SRB = PSO:CreateShaderResourceBinding(true) DrawAttrs = DrawAttribs.Create{ IsIndexed = true, IndexType = "VT_UINT32", Flags = "DRAW_FLAG_VERIFY_STATES" } function SetNumIndices(NumIndices) DrawAttrs.NumIndices = NumIndices end function Draw() Context.SetPipelineState(PSO) SRB:BindResources({"SHADER_TYPE_VERTEX", "SHADER_TYPE_PIXEL"}, ResMapping, {"BIND_SHADER_RESOURCES_KEEP_EXISTING", "BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED"}) Context.CommitShaderResources(SRB, "RESOURCE_STATE_TRANSITION_MODE_TRANSITION") Context.SetVertexBuffers(extSpongeVB, "RESOURCE_STATE_TRANSITION_MODE_TRANSITION", "SET_VERTEX_BUFFERS_FLAG_RESET") Context.SetIndexBuffer(extSpongeIB, "RESOURCE_STATE_TRANSITION_MODE_TRANSITION") Context.Draw(DrawAttrs) end
function GetShaderPath( ShaderName ) local ProcessedShaderPath = "" if Constants.DeviceType == "D3D11" or Constants.DeviceType == "D3D12" then ProcessedShaderPath = "shaders\\" .. ShaderName .. "_DX.hlsl" else ProcessedShaderPath = "shaders\\" .. ShaderName .. "_GL.glsl" end return ProcessedShaderPath end MainVS = Shader.Create{ FilePath = GetShaderPath("MainVS" ), UseCombinedTextureSamplers = true, Desc = { ShaderType = "SHADER_TYPE_VERTEX" } } MainPS = Shader.Create{ FilePath = GetShaderPath("MainPS" ), UseCombinedTextureSamplers = true, Desc = { ShaderType = "SHADER_TYPE_PIXEL" } } PSO = PipelineState.Create { Name = "Menger Sponge PSO", GraphicsPipeline = { DepthStencilDesc = { DepthEnable = true }, RasterizerDesc = { CullMode = "CULL_MODE_NONE" }, BlendDesc = { IndependentBlendEnable = false, RenderTargets = { {BlendEnable = false} } }, InputLayout = { { InputIndex = 0, NumComponents = 3, ValueType = "VT_FLOAT32"}, { InputIndex = 1, NumComponents = 3, ValueType = "VT_FLOAT32"}, { InputIndex = 2, NumComponents = 4, ValueType = "VT_UINT8", IsNormalized = true} }, PrimitiveTopology = "PRIMITIVE_TOPOLOGY_TRIANGLE_LIST", pVS = MainVS, pPS = MainPS, RTVFormats = extBackBufferFormat, DSVFormat = extDepthBufferFormat } } ResMapping = ResourceMapping.Create{ {Name = "Constants", pObject = extConstantBuffer} } PSO:BindStaticResources(ResMapping) SRB = PSO:CreateShaderResourceBinding(true) DrawAttrs = DrawAttribs.Create{ IsIndexed = true, IndexType = "VT_UINT32", Flags = "DRAW_FLAG_VERIFY_STATES" } function SetNumIndices(NumIndices) DrawAttrs.NumIndices = NumIndices end function Draw() Context.SetPipelineState(PSO) SRB:BindResources({"SHADER_TYPE_VERTEX", "SHADER_TYPE_PIXEL"}, ResMapping, {"BIND_SHADER_RESOURCES_KEEP_EXISTING", "BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED"}) Context.CommitShaderResources(SRB, "RESOURCE_STATE_TRANSITION_MODE_TRANSITION") Context.SetVertexBuffers(extSpongeVB, "RESOURCE_STATE_TRANSITION_MODE_TRANSITION", "SET_VERTEX_BUFFERS_FLAG_RESET") Context.SetIndexBuffer(extSpongeIB, "RESOURCE_STATE_TRANSITION_MODE_TRANSITION") Context.Draw(DrawAttrs) end
Fixed MengerSponge sample
Fixed MengerSponge sample
Lua
apache-2.0
DiligentGraphics/DiligentSamples,DiligentGraphics/DiligentSamples,DiligentGraphics/DiligentSamples,DiligentGraphics/DiligentSamples,DiligentGraphics/DiligentSamples,DiligentGraphics/DiligentSamples
628617b1c884182cde499af489eb6bdfc63cdd37
conky/mpd.lua
conky/mpd.lua
local curl = require 'cURL' function file_exists(name) local f=io.open(name,"r") if f~=nil then io.close(f) return true else return false end end function lines_from(file) if not file_exists(file) then return {} end lines = {} for line in io.lines(file) do lines[#lines + 1] = line end return lines end -- -- Read env file -- local lines = lines_from('/home/marcel/.dotfiles/conky/env') local config = {} for i, line in pairs(lines) do local key, val = line:match("([^=]+)=(.+)") config[key] = val end local c = curl.easy_init() c:setopt_url(config.URL) local spacer = ' ' function conky_main() if conky_window == nil then return end -- If mpd running, show that if conky_parse('$mpd_status') == 'Playing' then return conky_parse([[ ${image /home/marcel/.config/mpd/cover -s 300x300 -n -f 5} ${voffset 300}$alignc${scroll 24 1 $mpd_smart} ${voffset 10}${mpd_bar 4,300}]]) end local result = '' c:perform({writefunction = function(str) result = str end}) if not (result == '') then local id = string.sub(result, 0, 11) result = string.sub(result, 12) local thumbname = '/tmp/conkythumbnails/' .. id .. '.jpg' if not file_exists(thumbname) then os.execute('mkdir -p /tmp/conkythumbnails') f = assert(io.open(thumbname, 'w')) local c = curl.easy_init() :setopt_url('https://i.ytimg.com/vi/' .. id .. '/maxresdefault.jpg') :perform({ writefunction = function(str) f:write(str) end }) f:close() end local title = '' while string.len(result) > 50 do local i = string.find(string.sub(result, 0, 50), "[ /][^ /]*$") title = title .. '${alignc}' .. string.sub(result, 0, i) .. '\n' result = string.sub(result, i + 1) end title = title .. '${alignc}' .. result return conky_parse([[ ${image ]] .. thumbname .. [[ -s 426x240 -n -f 5} ]] .. spacer .. [[ ${voffset 220} ]] .. title) end -- Well shit return conky_parse('$mpd_status') end
local curl = require 'cURL' -- Checks if file exists function file_exists(name) local f=io.open(name,"r") if f~=nil then io.close(f) return true else return false end end -- Read file into table of lines function lines_from(file) if not file_exists(file) then return {} end lines = {} for line in io.lines(file) do lines[#lines + 1] = line end return lines end -- -- Read env file -- key=value formatted file -- You should include `URL=url_to_your_apollo_server` or don't call the apollo function -- -- Read lines into table local lines = lines_from('/home/marcel/.dotfiles/conky/env') -- Create config var local config = {} -- Parse file line by line for i, line in pairs(lines) do local key, val = line:match("([^=]+)=(.+)") config[key] = val end -- Set up curl local c = curl.easy_init() c:setopt_url(config.URL) -- Super good code. Don't even worry about it. local spacer = ' ' -- -- Apollo -- https://github.com/iambecomeroot/apollo -- Use this only if you have an apollo server -- local function apollo() local result = '' -- Curl apollo server c:perform({writefunction = function(str) result = str end}) -- If this returns a `Cannot GET whatever` error, return false if string.sub(result, 0, 10) == 'Cannot GET' then return false end -- If response blank, return false if result == '' then return false end -- Get youtube video id from result local id = string.sub(result, 0, 11) result = string.sub(result, 12) -- Get path to thumbnail local thumbname = '/tmp/conkythumbnails/' .. id .. '.jpg' -- If thumbnail not saved, download it if not file_exists(thumbname) then -- Make sure directory exists os.execute('mkdir -p /tmp/conkythumbnails') -- Open file for writing f = assert(io.open(thumbname, 'w')) -- Curl thumbnail into file local c = curl.easy_init() :setopt_url('https://i.ytimg.com/vi/' .. id .. '/maxresdefault.jpg') :perform({ writefunction = function(str) f:write(str) end }) -- Close file f:close() end -- Split long titles into lines local title = '' while string.len(result) > 50 do local i = string.find(string.sub(result, 0, 50), "[ /][^ /]*$") title = title .. '${alignc}' .. string.sub(result, 0, i) .. '\n' result = string.sub(result, i + 1) end title = title .. '${alignc}' .. result -- Return conky text return conky_parse([[ ${image ]] .. thumbname .. [[ -s 426x240 -n -f 5} ]] .. spacer .. [[ ${voffset 220} ]] .. title) end -- -- Main function -- Called by conky -- function conky_main() if conky_window == nil then return end -- If mpd running, show that if conky_parse('$mpd_status') == 'Playing' then return conky_parse([[ ${image /home/marcel/.config/mpd/cover -s 300x300 -n -f 5} ${voffset 300}${alignc}${font Fira Sans:style=bold}${mpd_artist}${font} ${alignc}${mpd_title} ${voffset 10}${mpd_bar 4,300}]]) end -- If apollo running, show that local apollo_res = apollo() if apollo_res then return apollo_res end -- Fall back to mpd status -- Usually paused if you get to this point return conky_parse('$mpd_status') end
- Fixed bug where if lua couldn't curl everything would fuck up - Added comments
- Fixed bug where if lua couldn't curl everything would fuck up - Added comments
Lua
mit
Iambecomeroot/dotfiles,Iambecomeroot/dotfiles,Iambecomeroot/dotfiles
ea9154eb439c7a06a6dec6f163b5f5015ac908af
scen_edit/utils/table.lua
scen_edit/utils/table.lua
Table = Table or {} function Table:Merge(table2) for k, v in pairs(table2) do if type(v) == 'table' then local sv = type(self[k]) if sv == 'table' or sv == 'nil' then if sv == 'nil' then self[k] = {} end Table.Merge(self[k], v) end elseif self[k] == nil then self[k] = v end end return self end -- Concatenates one or more array tables into a -- new table and returns it function Table.Concat(...) local ret = {} local tables = {...} for _, tbl in ipairs(tables) do for _, element in ipairs(tbl) do table.insert(ret, element) end end return ret end function Table.IsEmpty(t) for _ in pairs(t) do return false end return true end function Table.GetSize(t) local i = 0 for _ in pairs(t) do i = i + 1 end return i end -- FIXME -- FIXME: Cleanup everything below -- FIXME function SB.CreateNameMapping(origArray) local newArray = {} for i = 1, #origArray do local item = origArray[i] newArray[item.name] = item end return newArray end function SB.GroupByField(tbl, field) local newArray = {} for _, item in pairs(tbl) do local fieldValue = item[field] if newArray[fieldValue] then table.insert(newArray[fieldValue], item) else newArray[fieldValue] = { item } end end return newArray end function GetKeys(tbl) local keys = {} for k, _ in pairs(tbl) do table.insert(keys, k) end return keys end function GetValues(tbl) local values = {} for _, v in pairs(tbl) do table.insert(values, v) end return values end function GetField(origArray, field) local newArray = {} for k, v in pairs(origArray) do table.insert(newArray, v[field]) end return newArray end function GetIndex(table, value) assert(value ~= nil, "GetIndex called with nil value.") for i = 1, #table do if table[i] == value then return i end end end -- basically does origTable = newTableValues but instead uses the old table reference function SetTableValues(origTable, newTable) for k in pairs(origTable) do origTable[k] = nil end for k in pairs(newTable) do origTable[k] = newTable[k] end end function Table.SortByAttr(t, attrName) assert(attrName ~= nil, "Sort attribute name is nil") local sortedTable = {} for k, v in pairs(t) do table.insert(sortedTable, v) end table.sort(sortedTable, function(a, b) return a[attrName] < b[attrName] end ) return sortedTable end function Table.Compare(v1, v2) local v1Type, v2Type = type(v1), type(v2) if v1Type ~= v2Type then return false elseif v1Type ~= "table" then return v1 == v2 else local kCount1 = 0 for k, v in pairs(v1) do kCount1 = kCount1 + 1 if not Table.Compare(v, v2[k]) then return false end end local kCount2 = 0 for k, v in pairs(v2) do kCount2 = kCount2 + 1 end if kCount1 ~= kCount2 then return false end return true end end function Table.ShallowCopy(t) local ret = {} for k, v in pairs(t) do ret[k] = v end return ret end function Table.Contains(t, value) for _, v in pairs(t) do if v == value then return true end end return false end -- very simple (and probably inefficient) implementation of unique() function Table.Unique(t) -- Use values as keys in a new table (to guarantee uniqueness) local valueKeys = {} for _, v in pairs(t) do valueKeys[v] = true end -- convert it back to a normal array-like table local values = {} for k, _ in pairs(valueKeys) do table.insert(values, k) end return values end
Table = Table or {} function Table:Merge(table2) for k, v in pairs(table2) do if type(v) == 'table' then local sv = type(self[k]) if sv == 'table' or sv == 'nil' then if sv == 'nil' then self[k] = {} end Table.Merge(self[k], v) end elseif self[k] == nil then self[k] = v end end return self end -- Concatenates one or more array tables into a -- new table and returns it function Table.Concat(...) local ret = {} local tables = {...} for _, tbl in ipairs(tables) do for _, element in ipairs(tbl) do table.insert(ret, element) end end return ret end -- This function is a workaround for the # operator which fails with associative -- arrays. function Table.IsEmpty(t) -- luacheck: ignore for _ in pairs(t) do return false end return true end function Table.GetSize(t) local i = 0 for _ in pairs(t) do i = i + 1 end return i end -- FIXME -- FIXME: Cleanup everything below -- FIXME function SB.CreateNameMapping(origArray) local newArray = {} for i = 1, #origArray do local item = origArray[i] newArray[item.name] = item end return newArray end function SB.GroupByField(tbl, field) local newArray = {} for _, item in pairs(tbl) do local fieldValue = item[field] if newArray[fieldValue] then table.insert(newArray[fieldValue], item) else newArray[fieldValue] = { item } end end return newArray end function GetKeys(tbl) local keys = {} for k, _ in pairs(tbl) do table.insert(keys, k) end return keys end function GetValues(tbl) local values = {} for _, v in pairs(tbl) do table.insert(values, v) end return values end function GetField(origArray, field) local newArray = {} for k, v in pairs(origArray) do table.insert(newArray, v[field]) end return newArray end function GetIndex(table, value) assert(value ~= nil, "GetIndex called with nil value.") for i = 1, #table do if table[i] == value then return i end end end -- basically does origTable = newTableValues but instead uses the old table reference function SetTableValues(origTable, newTable) for k in pairs(origTable) do origTable[k] = nil end for k in pairs(newTable) do origTable[k] = newTable[k] end end function Table.SortByAttr(t, attrName) assert(attrName ~= nil, "Sort attribute name is nil") local sortedTable = {} for k, v in pairs(t) do table.insert(sortedTable, v) end table.sort(sortedTable, function(a, b) return a[attrName] < b[attrName] end ) return sortedTable end function Table.Compare(v1, v2) local v1Type, v2Type = type(v1), type(v2) if v1Type ~= v2Type then return false elseif v1Type ~= "table" then return v1 == v2 else local kCount1 = 0 for k, v in pairs(v1) do kCount1 = kCount1 + 1 if not Table.Compare(v, v2[k]) then return false end end local kCount2 = 0 for k, v in pairs(v2) do kCount2 = kCount2 + 1 end if kCount1 ~= kCount2 then return false end return true end end function Table.ShallowCopy(t) local ret = {} for k, v in pairs(t) do ret[k] = v end return ret end function Table.Contains(t, value) for _, v in pairs(t) do if v == value then return true end end return false end -- very simple (and probably inefficient) implementation of unique() function Table.Unique(t) -- Use values as keys in a new table (to guarantee uniqueness) local valueKeys = {} for _, v in pairs(t) do valueKeys[v] = true end -- convert it back to a normal array-like table local values = {} for k, _ in pairs(valueKeys) do table.insert(values, k) end return values end
fix travis
fix travis
Lua
mit
Spring-SpringBoard/SpringBoard-Core,Spring-SpringBoard/SpringBoard-Core
74c73ae408187517515fec389c104e67a3ca46ad
protocols/core/luasrc/model/cbi/admin_network/proto_dhcp.lua
protocols/core/luasrc/model/cbi/admin_network/proto_dhcp.lua
--[[ LuCI - Lua Configuration Interface Copyright 2011 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local map, section, net = ... local ifc = net:get_interface() local hostname, accept_ra, send_rs local bcast, no_gw, no_dns, dns, metric, clientid, vendorclass hostname = section:taboption("general", Value, "hostname", translate("Hostname to send when requesting DHCP")) hostname.placeholder = luci.sys.hostname() hostname.datatype = "hostname" if luci.model.network:has_ipv6() then accept_ra = s:taboption("general", Flag, "accept_ra", translate("Accept router advertisements")) accept_ra.default = accept_ra.enabled send_rs = s:taboption("general", Flag, "send_rs", translate("Send router solicitations")) send_rs.default = send_rs.disabled send_rs:depends("accept_ra", "") end bcast = section:taboption("advanced", Flag, "broadcast", translate("Use broadcast flag"), translate("Required for certain ISPs, e.g. Charter with DOCSIS 3")) bcast.default = bcast.disabled no_gw = section:taboption("advanced", Flag, "gateway", translate("Use default gateway"), translate("If unchecked, no default route is configured")) no_gw.default = no_gw.enabled function no_gw.cfgvalue(...) return Flag.cfgvalue(...) == "0.0.0.0" and "0" or "1" end function no_gw.write(self, section, value) if value == "1" then m:set(section, "gateway", nil) else m:set(section, "gateway", "0.0.0.0") end end no_dns = section:taboption("advanced", Flag, "_no_dns", translate("Use DNS servers advertised by peer"), translate("If unchecked, the advertised DNS server addresses are ignored")) no_dns.default = no_dns.enabled function no_dns.cfgvalue(self, section) local addr for addr in luci.util.imatch(m:get(section, "dns")) do return self.disabled end return self.enabled end function no_dns.remove(self, section) return m:del(section, "dns") end function no_dns.write() end dns = section:taboption("advanced", DynamicList, "dns", translate("Use custom DNS servers")) dns:depends("_no_dns", "") dns.datatype = "ipaddr" dns.cast = "string" metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger" metric:depends("gateway", "1") clientid = section:taboption("advanced", Value, "clientid", translate("Client ID to send when requesting DHCP")) vendorclass = section:taboption("advanced", Value, "vendorid", translate("Vendor Class to send when requesting DHCP")) macaddr = section:taboption("advanced", Value, "macaddr", translate("Override MAC address")) macaddr.placeholder = ifc and ifc:mac() or "00:00:00:00:00:00" macaddr.datatype = "macaddr" mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU")) mtu.placeholder = "1500" mtu.datatype = "max(1500)"
--[[ LuCI - Lua Configuration Interface Copyright 2011-2012 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local map, section, net = ... local ifc = net:get_interface() local hostname, accept_ra, send_rs local bcast, no_gw, peerdns, dns, metric, clientid, vendorclass hostname = section:taboption("general", Value, "hostname", translate("Hostname to send when requesting DHCP")) hostname.placeholder = luci.sys.hostname() hostname.datatype = "hostname" if luci.model.network:has_ipv6() then accept_ra = s:taboption("general", Flag, "accept_ra", translate("Accept router advertisements")) accept_ra.default = accept_ra.enabled send_rs = s:taboption("general", Flag, "send_rs", translate("Send router solicitations")) send_rs.default = send_rs.disabled send_rs:depends("accept_ra", "") end bcast = section:taboption("advanced", Flag, "broadcast", translate("Use broadcast flag"), translate("Required for certain ISPs, e.g. Charter with DOCSIS 3")) bcast.default = bcast.disabled no_gw = section:taboption("advanced", Flag, "gateway", translate("Use default gateway"), translate("If unchecked, no default route is configured")) no_gw.default = no_gw.enabled function no_gw.cfgvalue(...) return Flag.cfgvalue(...) == "0.0.0.0" and "0" or "1" end function no_gw.write(self, section, value) if value == "1" then m:set(section, "gateway", nil) else m:set(section, "gateway", "0.0.0.0") end end peerdns = section:taboption("advanced", Flag, "peerdns", translate("Use DNS servers advertised by peer"), translate("If unchecked, the advertised DNS server addresses are ignored")) peerdns.default = peerdns.enabled dns = section:taboption("advanced", DynamicList, "dns", translate("Use custom DNS servers")) dns:depends("peerdns", "") dns.datatype = "ipaddr" dns.cast = "string" metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger" metric:depends("gateway", "1") clientid = section:taboption("advanced", Value, "clientid", translate("Client ID to send when requesting DHCP")) vendorclass = section:taboption("advanced", Value, "vendorid", translate("Vendor Class to send when requesting DHCP")) macaddr = section:taboption("advanced", Value, "macaddr", translate("Override MAC address")) macaddr.placeholder = ifc and ifc:mac() or "00:00:00:00:00:00" macaddr.datatype = "macaddr" mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU")) mtu.placeholder = "1500" mtu.datatype = "max(1500)"
protocols/core: fix peerdns option for dhcp proto
protocols/core: fix peerdns option for dhcp proto git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@8695 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci
ea813066d9b196b4f2ae375f0c70297e3c77679b
_Out/Server/NFDataCfg/ScriptModule/script_init.lua
_Out/Server/NFDataCfg/ScriptModule/script_init.lua
--package.path = '../../NFDataCfg/Script/?.lua;' pLuaScriptModule = nil; pPluginManager = nil; function init_script_system(xPluginManager,xLuaScriptModule) pPluginManager = xPluginManager; pLuaScriptModule = xLuaScriptModule; io.write("\nHello Lua pPluginManager:" .. tostring(pPluginManager) .. " pLuaScriptModule:" .. tostring(pLuaScriptModule) .."\n\n"); io.write(); end function load_script_file(name) for key, value in pairs(name) do if type(value) == "table" then local tblObject = nil; for k, v in pairs(value) do if package.loaded[v] then else local object = require(v); if nil == object then io.write("load_script_file " .. v .. " failed\n"); else io.write("load_script_file " .. v .. " successed\n"); end end end end end end function reload_script_file( name ) if package.loaded[name] then package.loaded[name] = nil end load_script_file( name ) end function reload_script_table( name ) io.write("----Begin reload lua list----\n"); for key, value in pairs(name) do if type(value) == "table" then local tblObject = nil; for k, v in pairs(value) do reload_script_file(tostring(value)) end end end io.write("----End reload lua list----\n"); end function register_module(tbl, name) if ScriptList then for key, value in pairs(ScriptList) do local tblObject = nil; if type(value) == "table" then for k, v in pairs(value) do if v == name then tblObject = tbl; end end end if tblObject ~= nil then io.write("----register_module successed----\n"); ScriptList[key].tbl = tblObject; end end end if ScriptReloadList then for key, value in pairs(ScriptReloadList) do local tblObject = nil; if type(value) == "table" then for k, v in pairs(value) do if v == name then tblObject = tbl; end end end if tblObject ~= nil then io.write("----register_module successed----\n"); ScriptReloadList[key].tbl = tblObject; end end end end
--package.path = '../../NFDataCfg/Script/?.lua;' pLuaScriptModule = nil; pPluginManager = nil; function init_script_system(xPluginManager,xLuaScriptModule) pPluginManager = xPluginManager; pLuaScriptModule = xLuaScriptModule; io.write("\nHello Lua pPluginManager:" .. tostring(pPluginManager) .. " pLuaScriptModule:" .. tostring(pLuaScriptModule) .."\n\n"); io.write(); end function load_script_file(name) for key, value in pairs(name) do if type(value) == "table" then local tblObject = nil; for k, v in pairs(value) do if package.loaded[v] then else local object = require(v); if nil == object then io.write("load_script_file " .. v .. " failed\n"); else io.write("load_script_file " .. v .. " successed\n"); end end end end end end function reload_script_file( name ) if package.loaded[name] then package.loaded[name] = nil end local object = require(name); if nil == object then io.write(" reload_script_file " .. name .. " failed\n"); else io.write(" reload_script_file " .. name .. " successed\n"); end end function reload_script_table( name ) io.write("----Begin reload lua list----\n"); for key, value in pairs(name) do if type(value) == "table" then local tblObject = nil; for k, v in pairs(value) do io.write("reload script : " .. tostring(v) .. "\n"); reload_script_file(v) end end end io.write("----End reload lua list----\n"); end function register_module(tbl, name) if ScriptList then for key, value in pairs(ScriptList) do local tblObject = nil; if type(value) == "table" then for k, v in pairs(value) do if v == name then tblObject = tbl; end end end if tblObject ~= nil then ScriptList[key].tbl = tblObject; end end end if ScriptReloadList then for key, value in pairs(ScriptReloadList) do local tblObject = nil; if type(value) == "table" then for k, v in pairs(value) do if v == name then tblObject = tbl; end end end if tblObject ~= nil then ScriptReloadList[key].tbl = tblObject; end end end end
fixed ScriptModule
fixed ScriptModule
Lua
apache-2.0
lightningkay/NoahGameFrame,lightningkay/NoahGameFrame,lightningkay/NoahGameFrame,lightningkay/NoahGameFrame,lightningkay/NoahGameFrame,lightningkay/NoahGameFrame,lightningkay/NoahGameFrame
f6bc5b55dbae6e9eb053dc300198fd17788bdd72
kong/plugins/requestsizelimiting/access.lua
kong/plugins/requestsizelimiting/access.lua
local stringy = require "stringy" local response = require "kong.tools.responses" local _M = {} local CONTENT_LENGHT = "content-length" local function check_size(length, allowed_size) local allowed_bytes_size = allowed_size * 100000 if length > allowed_bytes_size then local headers = ngx.req.get_headers() if headers.expect and stringy.strip(headers.expect:lower()) == "100-continue" then return response.send(417, "Request size limit exceeded") else return response.send(413, "Request size limit exceeded") end end end -- Request size limiting, rejects request if payload size is greater than allowed size -- -- All methods must respect: -- @param `conf` Configuration table -- @return `response` contains response code and error message function _M.execute(conf) local headers = ngx.req.get_headers() if headers[CONTENT_LENGHT] then check_size(tonumber(headers[CONTENT_LENGHT]), conf.allowed_payload_size) else -- not very good idea ngx.req.read_body() local data = ngx.req.get_body_data() if data then check_size(string.len(data), conf.allowed_payload_size) end end end return _M
local stringy = require "stringy" local response = require "kong.tools.responses" local _M = {} local CONTENT_LENGTH = "content-length" local function check_size(length, allowed_size) local allowed_bytes_size = allowed_size * 100000 if length > allowed_bytes_size then local headers = ngx.req.get_headers() if headers.expect and stringy.strip(headers.expect:lower()) == "100-continue" then return response.send(417, "Request size limit exceeded") else return response.send(413, "Request size limit exceeded") end end end -- Request size limiting, rejects request if payload size is greater than allowed size -- -- All methods must respect: -- @param `conf` Configuration table -- @return `response` contains response code and error message function _M.execute(conf) local headers = ngx.req.get_headers() if headers[CONTENT_LENGTH] then check_size(tonumber(headers[CONTENT_LENGTH]), conf.allowed_payload_size) else -- If the request body is too big, this could consume too much memory (to check) ngx.req.read_body() local data = ngx.req.get_body_data() if data then check_size(string.len(data), conf.allowed_payload_size) end end end return _M
updated comment and fixed a typo
updated comment and fixed a typo Former-commit-id: d4e35da22f456da0c06b007e1b523496f8b34adc
Lua
apache-2.0
beauli/kong,ajayk/kong,streamdataio/kong,rafael/kong,Kong/kong,xvaara/kong,vzaramel/kong,akh00/kong,icyxp/kong,isdom/kong,kyroskoh/kong,ejoncas/kong,streamdataio/kong,ccyphers/kong,Kong/kong,Vermeille/kong,vzaramel/kong,ind9/kong,Mashape/kong,rafael/kong,salazar/kong,jerizm/kong,ejoncas/kong,isdom/kong,shiprabehera/kong,ind9/kong,kyroskoh/kong,jebenexer/kong,smanolache/kong,Kong/kong,li-wl/kong
d59dcbeff95fd9ff1d691aea2df0a3014ea4bccb
genie.lua
genie.lua
local THISDIR = os.getcwd() local CLANG_PATH local MSYS_BASE_PATH = "C:/msys64" local MINGW_BASE_PATH = MSYS_BASE_PATH .. "/mingw64" local MSYS_BIN_PATH = MSYS_BASE_PATH .. "/usr/bin" if os.is("linux") then CLANG_PATH = THISDIR .. "/clang/bin:/usr/local/bin:/usr/bin" elseif os.is("windows") then CLANG_PATH = MINGW_BASE_PATH .. "/bin" else error("unsupported os") end local function flatten(t) local result = {} local function iterate(t) for _,k in pairs(t) do if type(k) == "table" then iterate(k) elseif k ~= nil and k ~= "" then table.insert(result, k) end end end iterate(t) return result end local function pkg_config(cmd) local args = os.outputof(cmd) --print(cmd, "=>", args) return flatten(string.explode(args, "[ \n]+")) end local function finddir(name, searchpath) searchpath = searchpath or CLANG_PATH local path = os.pathsearch(name, searchpath) assert(path, name .. " not found in path " .. searchpath) return path .. "/" .. name end local function dllpath(name, searchpath) searchpath = searchpath or CLANG_PATH assert(os.is("windows")) name = name .. ".dll" local path = os.pathsearch(name, searchpath) assert(path, name .. " not found in path " .. searchpath) return path .. "/" .. name end local function toolpath(name, searchpath) searchpath = searchpath or CLANG_PATH if os.is("windows") then name = name .. ".exe" end local path = os.pathsearch(name, searchpath) assert(path, name .. " not found in path " .. searchpath) return path .. "/" .. name end local function print_list(l) for k,v in pairs(l) do print(k,v) end end local CLANG_CXX = toolpath("clang++", CLANG_PATH) local LLVM_CONFIG = toolpath("llvm-config", CLANG_PATH) local LLVM_LDFLAGS = pkg_config(LLVM_CONFIG .. " --ldflags") local LLVM_CXXFLAGS = pkg_config(LLVM_CONFIG .. " --cxxflags") local LLVM_LIBS = pkg_config(LLVM_CONFIG .. " --libs engine passes option objcarcopts coverage support lto coroutines") premake.gcc.cxx = CLANG_CXX if os.is("windows") then local CLANG_CC = toolpath("clang", CLANG_PATH) premake.gcc.cc = CLANG_CC end premake.gcc.llvm = true solution "scopes" location "build" configurations { "debug", "release" } platforms { "native", "x64" } project "scopes" kind "ConsoleApp" language "C++" files { "scopes.cpp", "external/linenoise-ng/src/linenoise.cpp", "external/linenoise-ng/src/ConvertUTF.cpp", "external/linenoise-ng/src/wcwidth.cpp" } includedirs { "external/linenoise-ng/include", "libffi/include", } libdirs { --"bin", --"build/src/nanovg/build", --"build/src/tess2/Build", --"build/src/stk/src", --"build/src/nativefiledialog/src", } targetdir "bin" defines { "SCOPES_CPP_IMPL", "SCOPES_MAIN_CPP_IMPL", } buildoptions_cpp { "-std=c++11", "-fno-rtti", "-fno-exceptions", "-ferror-limit=1", "-pedantic", "-Wall", "-Wno-keyword-macro", } buildoptions_cpp(LLVM_CXXFLAGS) links { "clangFrontend", "clangDriver", "clangSerialization", "clangCodeGen", "clangParse", "clangSema", "clangAnalysis", "clangEdit", "clangAST", "clangLex", "clangBasic" } configuration { "linux" } defines { "_GLIBCXX_USE_CXX11_ABI=0", } links { "pthread", "m", "tinfo", "dl", "z", } linkoptions { --"-Wl,--whole-archive", --"-l...", --"-Wl,--no-whole-archive", --"-Wl,--export-dynamic", --"-rdynamic", THISDIR .. "/libffi/.libs/libffi.a", } linkoptions(LLVM_LDFLAGS) linkoptions { "-Wl,--whole-archive" } linkoptions(LLVM_LIBS) linkoptions { "-Wl,--no-whole-archive" } postbuildcommands { "cp -v " .. THISDIR .. "/bin/scopes " .. THISDIR } configuration { "windows" } buildoptions_cpp { "-Wno-unknown-warning-option", "-Wno-unused-variable", "-Wno-unused-function", } includedirs { "win32", MINGW_BASE_PATH .. "/lib/libffi-3.2.1/include" } files { "win32/mman.c", "win32/realpath.c", "win32/dlfcn.c", } defines { "SCOPES_WIN32", } buildoptions_c { "-Wno-shift-count-overflow" } links { "ffi", "ole32", "uuid", "version", "psapi" } linkoptions { "-Wl,--allow-multiple-definition" } linkoptions(LLVM_LDFLAGS) linkoptions { "-Wl,--whole-archive", "-Wl,--export-all-symbols" } linkoptions(LLVM_LIBS) linkoptions { "-Wl,--no-whole-archive" } local CP = toolpath("cp", MSYS_BIN_PATH) postbuildcommands { CP .. " -v " .. THISDIR .. "/bin/scopes " .. THISDIR, CP .. " -v " .. dllpath("libffi-6") .. " " .. THISDIR, CP .. " -v " .. dllpath("libgcc_s_seh-1") .. " " .. THISDIR, CP .. " -v " .. dllpath("libstdc++-6") .. " " .. THISDIR, CP .. " -v " .. dllpath("libwinpthread-1") .. " " .. THISDIR, CP .. " -v " .. dllpath("LLVM") .. " " .. THISDIR, } configuration "debug" defines { "SCOPES_DEBUG" } flags { "Symbols" } buildoptions { "-O0" } configuration "release" defines { "NDEBUG" } flags { "Optimize" }
local THISDIR = os.getcwd() local CLANG_PATH local MSYS_BASE_PATH = "C:/msys64" local MINGW_BASE_PATH = MSYS_BASE_PATH .. "/mingw64" local MSYS_BIN_PATH = MSYS_BASE_PATH .. "/usr/bin" if os.is("linux") then CLANG_PATH = THISDIR .. "/clang/bin:/usr/local/bin:/usr/bin" elseif os.is("windows") then CLANG_PATH = MINGW_BASE_PATH .. "/bin" else error("unsupported os") end local function flatten(t) local result = {} local function iterate(t) for _,k in pairs(t) do if type(k) == "table" then iterate(k) elseif k ~= nil and k ~= "" then table.insert(result, k) end end end iterate(t) return result end local function pkg_config(cmd) local args = os.outputof(cmd) --print(cmd, "=>", args) return flatten(string.explode(args, "[ \n]+")) end local function finddir(name, searchpath) searchpath = searchpath or CLANG_PATH local path = os.pathsearch(name, searchpath) assert(path, name .. " not found in path " .. searchpath) return path .. "/" .. name end local function dllpath(name, searchpath) searchpath = searchpath or CLANG_PATH assert(os.is("windows")) name = name .. ".dll" local path = os.pathsearch(name, searchpath) assert(path, name .. " not found in path " .. searchpath) return path .. "/" .. name end local function toolpath(name, searchpath) searchpath = searchpath or CLANG_PATH if os.is("windows") then name = name .. ".exe" end local path = os.pathsearch(name, searchpath) assert(path, name .. " not found in path " .. searchpath) return path .. "/" .. name end local function print_list(l) for k,v in pairs(l) do print(k,v) end end local CLANG_CXX = toolpath("clang++", CLANG_PATH) local LLVM_CONFIG = toolpath("llvm-config", CLANG_PATH) local LLVM_LDFLAGS = pkg_config(LLVM_CONFIG .. " --ldflags") local LLVM_CXXFLAGS = pkg_config(LLVM_CONFIG .. " --cxxflags") local LLVM_LIBS = pkg_config(LLVM_CONFIG .. " --libs engine passes option objcarcopts coverage support lto coroutines") premake.gcc.cxx = CLANG_CXX if os.is("windows") then local CLANG_CC = toolpath("clang", CLANG_PATH) premake.gcc.cc = CLANG_CC end premake.gcc.llvm = true solution "scopes" location "build" configurations { "debug", "release" } platforms { "native", "x64" } project "scopes" kind "ConsoleApp" language "C++" files { "scopes.cpp", "external/linenoise-ng/src/linenoise.cpp", "external/linenoise-ng/src/ConvertUTF.cpp", "external/linenoise-ng/src/wcwidth.cpp" } includedirs { "external/linenoise-ng/include", "libffi/include", } libdirs { --"bin", --"build/src/nanovg/build", --"build/src/tess2/Build", --"build/src/stk/src", --"build/src/nativefiledialog/src", } targetdir "bin" defines { "SCOPES_CPP_IMPL", "SCOPES_MAIN_CPP_IMPL", } buildoptions_cpp { "-std=c++11", "-fno-rtti", "-fno-exceptions", "-ferror-limit=1", "-pedantic", "-Wall", "-Wno-keyword-macro", } buildoptions_cpp(LLVM_CXXFLAGS) links { "clangFrontend", "clangDriver", "clangSerialization", "clangCodeGen", "clangParse", "clangSema", "clangAnalysis", "clangEdit", "clangAST", "clangLex", "clangBasic" } configuration { "linux" } defines { "_GLIBCXX_USE_CXX11_ABI=0", } links { "pthread", "m", "tinfo", "dl", "z", } linkoptions { --"-Wl,--whole-archive", --"-l...", --"-Wl,--no-whole-archive", --"-Wl,--export-dynamic", --"-rdynamic", THISDIR .. "/libffi/.libs/libffi.a", } linkoptions(LLVM_LDFLAGS) linkoptions { "-Wl,--whole-archive" } linkoptions(LLVM_LIBS) linkoptions { "-Wl,--no-whole-archive" } postbuildcommands { "cp -v " .. THISDIR .. "/bin/scopes " .. THISDIR } configuration { "windows" } buildoptions_cpp { "-Wno-unknown-warning-option", "-Wno-unused-variable", "-Wno-unused-function", } includedirs { "win32", MINGW_BASE_PATH .. "/lib/libffi-3.2.1/include" } files { "win32/mman.c", "win32/realpath.c", "win32/dlfcn.c", } defines { "SCOPES_WIN32", } buildoptions_c { "-Wno-shift-count-overflow" } links { "ffi", "ole32", "uuid", "version", "psapi" } linkoptions { "-Wl,--allow-multiple-definition" } linkoptions(LLVM_LDFLAGS) linkoptions { "-Wl,--whole-archive", "-Wl,--export-all-symbols" } linkoptions(LLVM_LIBS) linkoptions { "-Wl,--no-whole-archive" } if os.is("windows") then local CP = toolpath("cp", MSYS_BIN_PATH) postbuildcommands { CP .. " -v " .. THISDIR .. "/bin/scopes " .. THISDIR, CP .. " -v " .. dllpath("libffi-6") .. " " .. THISDIR, CP .. " -v " .. dllpath("libgcc_s_seh-1") .. " " .. THISDIR, CP .. " -v " .. dllpath("libstdc++-6") .. " " .. THISDIR, CP .. " -v " .. dllpath("libwinpthread-1") .. " " .. THISDIR, CP .. " -v " .. dllpath("LLVM") .. " " .. THISDIR, } end configuration "debug" defines { "SCOPES_DEBUG" } flags { "Symbols" } buildoptions { "-O0" } configuration "release" defines { "NDEBUG" } flags { "Optimize" }
* fixed error in build script
* fixed error in build script
Lua
mit
duangle/bangra,duangle/bangra,duangle/bangra,duangle/bangra
76fdc8369567f91b4dc034f5987a9da2e58b651c
mod_adhoc_cmd_admin/mod_adhoc_cmd_admin.lua
mod_adhoc_cmd_admin/mod_adhoc_cmd_admin.lua
-- Copyright (C) 2009 Florian Zeitz -- -- This file is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local st, jid, uuid = require "util.stanza", require "util.jid", require "util.uuid"; local dataforms_new = require "util.dataforms".new; local usermanager_user_exists = require "core.usermanager".user_exists; local usermanager_create_user = require "core.usermanager".create_user; local is_admin = require "core.usermanager".is_admin; local admins = set.new(config.get(module:get_host(), "core", "admins")); local sessions = {}; local add_user_layout = { title= "Adding a User"; instructions = "Fill out this form to add a user."; { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/admin" }; { name = "accountjid", type = "jid-single", required = true, label = "The Jabber ID for the account to be added" }; { name = "password", type = "text-private", label = "The password for this account" }; { name = "password-verify", type = "text-private", label = "Retype password" }; }; dataforms_new(add_user_layout) function add_user_command_handler(item, origin, stanza) if not is_admin(stanza.attr.from) then module:log("warn", "Non-admin %s tried to add a user", tostring(jid.bare(stanza.attr.from))); origin.send(st.error_reply(stanza, "auth", "forbidden", "You don't have permission to add a user"):up() :tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", status="canceled"}) :tag("note", {type="error"}):text("You don't have permission to add a user")); return true; end if stanza.tags[1].attr.sessionid and sessions[stanza.tags[1].attr.sessionid] then if stanza.tags[1].attr.action == "cancel" then origin.send(st.reply(stanza):tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", sessionid=stanza.tags[1].attr.sessionid, status="canceled"})); sessions[stanza.tags[1].attr.sessionid] = nil; return true; end for _, tag in ipairs(stanza.tags[1].tags) do if tag.name == "x" and tag.attr.xmlns == "jabber:x:data" then form = tag; break; end end local fields = add_user_layout:data(form); local username, host, resource = jid.split(fields.accountjid); if (fields.password == fields["password-verify"]) and username and host and host == stanza.attr.to then if usermanager_user_exists(username, host) then origin.send(st.error_reply(stanza, "cancel", "conflict", "Account already exists"):up() :tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", status="canceled"}) :tag("note", {type="error"}):text("Account already exists")); sessions[stanza.tags[1].attr.sessionid] = nil; return true; else if usermanager_create_user(username, fields.password, host) then origin.send(st.reply(stanza):tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", sessionid=stanza.tags[1].attr.sessionid, status="completed"}) :tag("note", {type="info"}):text("Account successfully created")); sessions[stanza.tags[1].attr.sessionid] = nil; module:log("debug", "Created new account " .. username.."@"..host); return true; else origin.send(st.error_reply(stanza, "wait", "internal-server-error", "Failed to write data to disk"):up() :tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", status="canceled"}) :tag("note", {type="error"}):text("Failed to write data to disk")); sessions[stanza.tags[1].attr.sessionid] = nil; return true; end end else module:log("debug", fields.accountjid .. " " .. fields.password .. " " .. fields["password-verify"]); origin.send(st.error_reply(stanza, "cancel", "conflict", "Invalid data.\nPasswords missmatch, or empy username"):up() :tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", status="canceled"}) :tag("note", {type="error"}):text("Invalid data.\nPasswords missmatch, or empy username")); sessions[stanza.tags[1].attr.sessionid] = nil; return true; end else local sessionid=uuid.generate(); sessions[sessionid] = "executing"; origin.send(st.reply(stanza):tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", sessionid=sessionid, status="executing"}):add_child(add_user_layout:form())); end return true; end local descriptor = { name="Add User", node="http://jabber.org/protocol/admin#add-user", handler=add_user_command_handler }; function module.unload() module:remove_item("adhoc", descriptor); end module:add_item ("adhoc", descriptor);
-- Copyright (C) 2009 Florian Zeitz -- -- This file is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local st, jid, uuid = require "util.stanza", require "util.jid", require "util.uuid"; local dataforms_new = require "util.dataforms".new; local usermanager_user_exists = require "core.usermanager".user_exists; local usermanager_create_user = require "core.usermanager".create_user; local is_admin = require "core.usermanager".is_admin; local admins = set.new(config.get(module:get_host(), "core", "admins")); local sessions = {}; local add_user_layout = dataforms_new{ title= "Adding a User"; instructions = "Fill out this form to add a user."; { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/admin" }; { name = "accountjid", type = "jid-single", required = true, label = "The Jabber ID for the account to be added" }; { name = "password", type = "text-private", label = "The password for this account" }; { name = "password-verify", type = "text-private", label = "Retype password" }; }; function add_user_command_handler(item, origin, stanza) if not is_admin(stanza.attr.from) then module:log("warn", "Non-admin %s tried to add a user", tostring(jid.bare(stanza.attr.from))); origin.send(st.error_reply(stanza, "auth", "forbidden", "You don't have permission to add a user"):up() :tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", status="canceled"}) :tag("note", {type="error"}):text("You don't have permission to add a user")); return true; end if stanza.tags[1].attr.sessionid and sessions[stanza.tags[1].attr.sessionid] then if stanza.tags[1].attr.action == "cancel" then origin.send(st.reply(stanza):tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", sessionid=stanza.tags[1].attr.sessionid, status="canceled"})); sessions[stanza.tags[1].attr.sessionid] = nil; return true; end form = stanza.tags[1]:find_child_with_ns("jabber:x:data"); local fields = add_user_layout:data(form); local username, host, resource = jid.split(fields.accountjid); if (fields.password == fields["password-verify"]) and username and host and host == stanza.attr.to then if usermanager_user_exists(username, host) then origin.send(st.error_reply(stanza, "cancel", "conflict", "Account already exists"):up() :tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", status="canceled"}) :tag("note", {type="error"}):text("Account already exists")); sessions[stanza.tags[1].attr.sessionid] = nil; return true; else if usermanager_create_user(username, fields.password, host) then origin.send(st.reply(stanza):tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", sessionid=stanza.tags[1].attr.sessionid, status="completed"}) :tag("note", {type="info"}):text("Account successfully created")); sessions[stanza.tags[1].attr.sessionid] = nil; module:log("debug", "Created new account " .. username.."@"..host); return true; else origin.send(st.error_reply(stanza, "wait", "internal-server-error", "Failed to write data to disk"):up() :tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", status="canceled"}) :tag("note", {type="error"}):text("Failed to write data to disk")); sessions[stanza.tags[1].attr.sessionid] = nil; return true; end end else module:log("debug", fields.accountjid .. " " .. fields.password .. " " .. fields["password-verify"]); origin.send(st.error_reply(stanza, "cancel", "conflict", "Invalid data.\nPassword mismatch, or empty username"):up() :tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", status="canceled"}) :tag("note", {type="error"}):text("Invalid data.\nPassword mismatch, or empty username")); sessions[stanza.tags[1].attr.sessionid] = nil; return true; end else local sessionid=uuid.generate(); sessions[sessionid] = "executing"; origin.send(st.reply(stanza):tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", sessionid=sessionid, status="executing"}):add_child(add_user_layout:form())); end return true; end local descriptor = { name="Add User", node="http://jabber.org/protocol/admin#add-user", handler=add_user_command_handler }; function module.unload() module:remove_item("adhoc", descriptor); end module:add_item ("adhoc", descriptor);
mod_adhoc_cmd_admin: Fixed style, some typos, and got down to <100LOC. Perhaps we need util.adhoc?
mod_adhoc_cmd_admin: Fixed style, some typos, and got down to <100LOC. Perhaps we need util.adhoc?
Lua
mit
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
c4f963ab9402700a874467723559dbc069b4c214
tools/rest_translation_server.lua
tools/rest_translation_server.lua
#!/usr/bin/env lua --[[ This requires the restserver-xavante rock to run. run server (this file) th tools/rest_translation_server.lua -model ../Recipes/baseline-1M-enfr/exp/model-baseline-1M-enfr_epoch13_3.44.t7 -gpuid 1 query the server curl -v -H "Content-Type: application/json" -X POST -d '{ "src" : "international migration" }' http://127.0.0.1:8080/translator/translate ]] require('onmt.init') local separators = require('tools.utils.separators') local tokenizer = require('tools.utils.tokenizer') local cmd = onmt.utils.ExtendedCmdLine.new('rest_translation_server.lua') local options = { {'-host', '127.0.0.1', [[Host to run the server on]]}, {'-port', '8080', [[Port to run the server on]]} } onmt.translate.Translator.declareOpts(cmd) cmd:text("") cmd:text("**Other options**") cmd:text("") onmt.utils.Cuda.declareOpts(cmd) onmt.utils.Logger.declareOpts(cmd) cmd:option('-mode', 'conservative', [[Define how aggressive should the tokenization be - 'aggressive' only keeps sequences of letters/numbers, 'conservative' allows mix of alphanumeric as in: '2,000', 'E65', 'soft-landing']]) cmd:option('-joiner_annotate', true, [[Include joiner annotation using 'joiner' character]]) cmd:option('-joiner', separators.joiner_marker, [[Character used to annotate joiners]]) cmd:option('-joiner_new', false, [[in joiner_annotate mode, 'joiner' is an independent token]]) cmd:option('-case_feature', true, [[Generate case feature]]) cmd:option('-bpe_model', '', [[Apply Byte Pair Encoding if the BPE model path is given]]) cmd:option('-nparallel', 1, [[Number of parallel thread to run the tokenization]]) cmd:option('-batchsize', 1000, [[Size of each parallel batch - you should not change except if low memory]]) local opt = cmd:parse(arg) local function translateMessage(translator, lines) local batch = {} -- We need to tokenize the input line before translation local srcTokens = {} local bpe local srcTokenized = {} local res local err local tokens local BPE = require ('tools.utils.BPE') if opt.bpe_model ~= '' then bpe = BPE.new(opt.bpe_model, opt.joiner_annotate, opt.joiner_new) end res, err = pcall(function() tokens = tokenizer.tokenize(opt, lines.src, bpe) end) -- it can generate an exception if there are utf-8 issues in the text if not res then if string.find(err, "interrupted") then error("interrupted") else error("unicode error in line " .. err) end end table.insert(srcTokenized, table.concat(tokens, ' ')) -- Extract from the line. for word in srcTokenized[1]:gmatch'([^%s]+)' do table.insert(srcTokens, word) end -- Currently just a single batch. table.insert(batch, translator:buildInput(srcTokens)) -- Translate local results = translator:translate(batch) -- Return the nbest translations for each in the batch. local translations = {} local ret = {} for i = 1, translator.opt.n_best do local srcSent = translator:buildOutput(batch[1]) local predSent = translator:buildOutput(results[1].preds[i]) local oline res, err = pcall(function() oline = tokenizer.detokenize(predSent, opt) end) -- table.insert(output, oline) if not res then if string.find(err,"interrupted") then error("interrupted") else error("unicode error in line ".. err) end end local attnTable = {} for j = 1, #results[1].preds[i].attention do table.insert(attnTable, results[1].preds[i].attention[j]:totable()) end table.insert(ret, { tgt = oline, attn = attnTable, src = srcSent, n_best = i, pred_score = results[1].preds[i].score }) end table.insert(translations, ret) return translations end local restserver = require("restserver") local server = restserver:new():port(opt.port) local translator server:add_resource("translator", { { method = "POST", path = "/translate", consumes = "application/json", produces = "application/json", input_schema = { src = { type = "string" }, }, handler = function(req) print("receiving request: ") print(req) local translate = translateMessage(translator, req) print("sending response: ") print(translate) return restserver.response():status(200):entity(translate) end, }, }) local function main() _G.logger = onmt.utils.Logger.new(opt.log_file, opt.disable_logs, opt.log_level) _G.logger:info("Loading model") translator = onmt.translate.Translator.new(opt) -- This loads the restserver.xavante plugin server:enable("restserver.xavante"):start() end main()
#!/usr/bin/env lua --[[ This requires the restserver-xavante rock to run. run server (this file) th tools/rest_translation_server.lua -model ../Recipes/baseline-1M-enfr/exp/model-baseline-1M-enfr_epoch13_3.44.t7 -gpuid 1 query the server curl -v -H "Content-Type: application/json" -X POST -d '{ "src" : "international migration" }' http://127.0.0.1:8080/translator/translate ]] require('onmt.init') local separators = require('tools.utils.separators') local tokenizer = require('tools.utils.tokenizer') local cmd = onmt.utils.ExtendedCmdLine.new('rest_translation_server.lua') local options = { {'-host', '127.0.0.1', [[Host to run the server on]]}, {'-port', '8080', [[Port to run the server on]]} } cmd:setCmdLineOptions(options, 'Server') onmt.translate.Translator.declareOpts(cmd) cmd:text("") cmd:text("**Other options**") cmd:text("") onmt.utils.Cuda.declareOpts(cmd) onmt.utils.Logger.declareOpts(cmd) cmd:option('-mode', 'conservative', [[Define how aggressive should the tokenization be - 'aggressive' only keeps sequences of letters/numbers, 'conservative' allows mix of alphanumeric as in: '2,000', 'E65', 'soft-landing']]) cmd:option('-joiner_annotate', false, [[Include joiner annotation using 'joiner' character]]) cmd:option('-joiner', separators.joiner_marker, [[Character used to annotate joiners]]) cmd:option('-joiner_new', false, [[in joiner_annotate mode, 'joiner' is an independent token]]) cmd:option('-case_feature', false, [[Generate case feature]]) cmd:option('-bpe_model', '', [[Apply Byte Pair Encoding if the BPE model path is given]]) cmd:option('-nparallel', 1, [[Number of parallel thread to run the tokenization]]) cmd:option('-batchsize', 1000, [[Size of each parallel batch - you should not change except if low memory]]) local opt = cmd:parse(arg) local function translateMessage(translator, lines) local batch = {} -- We need to tokenize the input line before translation local srcTokens = {} local bpe local srcTokenized = {} local res local err local tokens local BPE = require ('tools.utils.BPE') if opt.bpe_model ~= '' then bpe = BPE.new(opt.bpe_model, opt.joiner_annotate, opt.joiner_new) end res, err = pcall(function() tokens = tokenizer.tokenize(opt, lines.src, bpe) end) -- it can generate an exception if there are utf-8 issues in the text if not res then if string.find(err, "interrupted") then error("interrupted") else error("unicode error in line " .. err) end end table.insert(srcTokenized, table.concat(tokens, ' ')) -- Extract from the line. for word in srcTokenized[1]:gmatch'([^%s]+)' do table.insert(srcTokens, word) end -- Currently just a single batch. table.insert(batch, translator:buildInput(srcTokens)) -- Translate local results = translator:translate(batch) -- Return the nbest translations for each in the batch. local translations = {} local ret = {} for i = 1, translator.opt.n_best do local srcSent = translator:buildOutput(batch[1]) local predSent = translator:buildOutput(results[1].preds[i]) local oline res, err = pcall(function() oline = tokenizer.detokenize(predSent, opt) end) -- table.insert(output, oline) if not res then if string.find(err,"interrupted") then error("interrupted") else error("unicode error in line ".. err) end end local attnTable = {} for j = 1, #results[1].preds[i].attention do table.insert(attnTable, results[1].preds[i].attention[j]:totable()) end table.insert(ret, { tgt = oline, attn = attnTable, src = srcSent, n_best = i, pred_score = results[1].preds[i].score }) end table.insert(translations, ret) return translations end local restserver = require("restserver") local server = restserver:new():port(opt.port) local translator server:add_resource("translator", { { method = "POST", path = "/translate", consumes = "application/json", produces = "application/json", input_schema = { src = { type = "string" }, }, handler = function(req) print("receiving request: ") print(req) local translate = translateMessage(translator, req) print("sending response: ") print(translate) return restserver.response():status(200):entity(translate) end, }, }) local function main() _G.logger = onmt.utils.Logger.new(opt.log_file, opt.disable_logs, opt.log_level) _G.logger:info("Loading model") translator = onmt.translate.Translator.new(opt) -- This loads the restserver.xavante plugin server:enable("restserver.xavante"):start() end main()
small fix
small fix
Lua
mit
jungikim/OpenNMT,OpenNMT/OpenNMT,jsenellart/OpenNMT,jsenellart/OpenNMT,OpenNMT/OpenNMT,OpenNMT/OpenNMT,jsenellart-systran/OpenNMT,monsieurzhang/OpenNMT,jungikim/OpenNMT,da03/OpenNMT,jsenellart-systran/OpenNMT,jungikim/OpenNMT,jsenellart/OpenNMT,jsenellart-systran/OpenNMT,monsieurzhang/OpenNMT,da03/OpenNMT,monsieurzhang/OpenNMT,da03/OpenNMT
0c07743b33b1203e059a3195bdcc54f1692d60f6
MMOCoreORB/bin/scripts/skills/playerSkills/nonCombat/medic.lua
MMOCoreORB/bin/scripts/skills/playerSkills/nonCombat/medic.lua
--Copyright (C) 2007 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version --which carries forward this exception. HealSelfSkill = { skillname = "healdamage", effect = "clienteffect/healing_healdamage.cef", animation = "heal_self", mindCost = -50, range = 6.0 } AddHealDamageTargetSkill(HealSelfSkill); HealSelfSkill = { skillname = "healwound", effect = "clienteffect/healing_healwound.cef", animation = "heal_self", mindCost = -50, range = 6.0 } AddHealWoundTargetSkill(HealSelfSkill); FirstAidSkill = { skillname = "firstaid", effect = "clienteffect/healing_healdamage.cef", animation = "heal_self", speed = 5.0, range = 6.0 } AddFirstAidTargetSkill(FirstAidSkill); TendDamageSkill = { skillname = "tenddamage", effect = "clienteffect/healing_healdamage.cef", animation = "heal_self", mindCost = 30; mindCostWound = 5; healthHealed = 50; actionHealed = 50; tendDamage = 1; speed = 5.0, range = 6.0 } AddTendHealTargetSkill(TendDamageSkill); TendWoundSkill = { skillname = "tendwound", effect = "clienteffect/healing_healwound.cef", animation = "heal_self", mindCost = 30; mindCostWound = 10; woundPool = 1; woundHealed = 25; tendWound = 1; speed = 5.0, range = 6.0 } AddTendHealTargetSkill(TendWoundSkill); DiagnoseTargetSkill = { skillname = "diagnose", effect = "clienteffect/healing_healenhance.cef", animation = "heal_self", mindCost = 0, range = 6.0, speed = 0 } AddDiagnoseTargetSkill(DiagnoseTargetSkill);
--Copyright (C) 2007 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version --which carries forward this exception. HealSelfSkill = { skillname = "healdamage", effect = "clienteffect/healing_healdamage.cef", animation = "heal_self", mindCost = -50, range = 6.0 } AddHealDamageTargetSkill(HealSelfSkill); HealSelfSkill = { skillname = "healwound", effect = "clienteffect/healing_healwound.cef", animation = "heal_self", mindCost = -50, range = 6.0 } AddHealWoundTargetSkill(HealSelfSkill); FirstAidSkill = { skillname = "firstaid", effect = "clienteffect/healing_healdamage.cef", animation = "heal_self", speed = 5.0, range = 6.0 } AddFirstAidTargetSkill(FirstAidSkill); TendDamageSkill = { skillname = "tenddamage", effect = "clienteffect/healing_healdamage.cef", animation = "heal_self", mindCost = 30, mindWoundCost = 5, healthHealed = 50, actionHealed = 50, tendDamage = 1, speed = 5.0, range = 6.0 } AddTendHealTargetSkill(TendDamageSkill); TendWoundSkill = { skillname = "tendwound", effect = "clienteffect/healing_healwound.cef", animation = "heal_self", mindCost = 30, mindWoundCost = 10, woundPool = 1, woundHealed = 25, tendWound = 1, speed = 5.0, range = 6.0 } AddTendHealTargetSkill(TendWoundSkill); DiagnoseTargetSkill = { skillname = "diagnose", effect = "clienteffect/healing_healenhance.cef", animation = "heal_self", mindCost = 0, range = 6.0, speed = 0 } AddDiagnoseTargetSkill(DiagnoseTargetSkill);
Thanks to Anakis for this fix. -Adds wound cost to tendwound and tenddamage medic skills.
Thanks to Anakis for this fix. -Adds wound cost to tendwound and tenddamage medic skills. git-svn-id: c34995188cc7e843f8a799edec2d9d4b36f36456@846 c3d1530f-68f5-4bd0-87dc-8ef779617e40
Lua
agpl-3.0
Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo
489a1a962ce07b7f742c0934009d4566bbe3c0b8
src/jet/socket.lua
src/jet/socket.lua
local ev = require'ev' local socket = require'socket' local cjson = require'cjson' require'pack' -- blends pack/unpack into string table local print = print local pairs = pairs local tinsert = table.insert local tconcat = table.concat local ipairs = ipairs local assert = assert local spack = string.pack local sunpack = string.unpack local error = error local log = print local pcall = pcall local type = type module('jet.socket') local wrap_sync = function(sock) assert(sock) local wrapped = {} sock:setoption('tcp-nodelay',true) wrapped.send = function(_,message_object) local json_message = cjson.encode(message_object) sock:send(spack('>I',#json_message)) sock:send(json_message) end wrapped.receive = function(_) local bin_len = sock:receive(4) local _,len = bin_len:unpack('>I') local json_message = sock:receive(len) return cjson.decode(json_message) end return wrapped end local wrap = function(sock,args) assert(sock) args = args or {} -- set non blocking sock:settimeout(0) -- send message asap sock:setoption('tcp-nodelay',true) -- enable keep alive for detecting broken connections sock:setoption('keepalive',true) local on_message = args.on_message or function() end local on_close = args.on_close or function() end local on_error = args.on_error or function() end local encode = not args.dont_encode local decode = not args.dont_decode local loop = args.loop or ev.Loop.default local send_buffer = '' local wrapped = {} local send_pos local send_message = function(loop,write_io) local sent,err,sent_so_far = sock:send(send_buffer,send_pos) if sent then -- log('sent',#send_buffer,send_buffer:sub(5)) assert(sent==#send_buffer) send_buffer = '' write_io:stop(loop) elseif err == 'timeout' then log('sent timeout',send_pos) send_pos = sent_so_far elseif err == 'closed' then -- log('sent closed',pos) write_io:stop(loop) on_close(wrapped) sock:close() else log('sent error',err) write_io:stop(loop) on_close(wrapped) sock:close() log('unknown error:'..err) end end local fd = sock:getfd() assert(fd > -1) local send_io = ev.IO.new(send_message,fd,ev.WRITE) -- sends asynchronous the supplied message object -- -- the message format is 32bit big endian integer -- denoting the size of the JSON following wrapped.send = function(_,message) -- log('sending',cjson.encode(message)) if encode then message = cjson.encode(message) end -- assert(cjson.decode(message) ~= cjson.null) send_buffer = send_buffer..spack('>I',#message)..message send_pos = 0 if not send_io:is_active() then -- log('strting io') send_io:start(loop) end end wrapped.close = function() wrapped.read_io():stop(loop) send_io:stop(loop) sock:shutdown() sock:close() end wrapped.on_message = function(_,f) assert(type(f) == 'function') on_message = f end wrapped.on_close = function(_,f) assert(type(f) == 'function') on_close = f end wrapped.on_error = function(_,f) assert(type(f) == 'function') on_error = f end local read_io wrapped.read_io = function() if not read_io then local len local len_bin local json_message local _ local receive_message = function(loop,read_io) while true do if not len_bin or #len_bin < 4 then local err,sub len_bin,err,sub = sock:receive(4,len_bin) if len_bin then _,len = sunpack(len_bin,'>I') elseif err == 'timeout' then len_bin = sub return elseif err == 'closed' then read_io:stop(loop) on_close(wrapped) sock:close() return else log('WTF?!',err) read_io:stop(loop) on_error(wrapped,err) sock:close() end end if len then if len > 1000000 then local err = 'message too big:'..len..'bytes' print('jet.socket error',err) on_error(wrapped,err) read_io:stop(loop) sock:close() return end json_message,err,sub = sock:receive(len,json_message) if json_message then -- log('recv',len,json_message) if decode then local ok,message = pcall(cjson.decode,json_message) if ok then on_message(wrapped,message) else on_message(wrapped,nil,message) end else on_message(wrapped,json_message) end len = nil len_bin = nil json_message = nil elseif err == 'timeout' then json_message = sub return elseif err == 'closed' then read_io:stop(loop) on_close(wrapped) sock:close() return else read_io:stop(loop) on_error(wrapped,err) sock:close() return end end end end local fd = sock:getfd() assert(fd > -1) read_io = ev.IO.new(receive_message,fd,ev.READ) end return read_io end return wrapped end local mod = { wrap = wrap, wrap_sync = wrap_sync } return mod
local ev = require'ev' local socket = require'socket' local cjson = require'cjson' require'pack'-- blends pack/unpack into string table local print = print local pairs = pairs local tinsert = table.insert local tconcat = table.concat local ipairs = ipairs local assert = assert local spack = string.pack local sunpack = string.unpack local error = error local log = print local pcall = pcall local type = type module('jet.socket') local wrap_sync = function(sock) assert(sock) local wrapped = {} sock:setoption('tcp-nodelay',true) wrapped.send = function(_,message_object) local json_message = cjson.encode(message_object) sock:send(spack('>I',#json_message)) sock:send(json_message) end wrapped.receive = function(_) local bin_len = sock:receive(4) local _,len = bin_len:unpack('>I') local json_message = sock:receive(len) return cjson.decode(json_message) end return wrapped end local wrap = function(sock,args) assert(sock) args = args or {} -- set non blocking sock:settimeout(0) -- send message asap sock:setoption('tcp-nodelay',true) -- enable keep alive for detecting broken connections sock:setoption('keepalive',true) local on_message = args.on_message or function() end local on_close = args.on_close or function() end local on_error = args.on_error or function() end local encode = not args.dont_encode local decode = not args.dont_decode local loop = args.loop or ev.Loop.default local send_buffer = '' local wrapped = {} local send_pos local send_message = function(loop,write_io) local sent,err,sent_so_far = sock:send(send_buffer,send_pos) if not sent and err ~= 'timeout' then write_io:stop(loop) if err == 'closed' then on_close(wrapped) else log('sent error',err) on_error(wrapped,err) end sock:close() send_buffer = '' elseif sent then send_pos = nil send_buffer = '' write_io:stop(loop) else send_pos = sent_so_far + 1 end end local fd = sock:getfd() assert(fd > -1) local send_io = ev.IO.new(send_message,fd,ev.WRITE) -- sends asynchronous the supplied message object -- -- the message format is 32bit big endian integer -- denoting the size of the JSON following wrapped.send = function(_,message) if encode then message = cjson.encode(message) end send_buffer = send_buffer..spack('>I',#message)..message if not send_io:is_active() then send_io:start(loop) end end wrapped.close = function() wrapped.read_io():stop(loop) send_io:stop(loop) sock:shutdown() sock:close() end wrapped.on_message = function(_,f) assert(type(f) == 'function') on_message = f end wrapped.on_close = function(_,f) assert(type(f) == 'function') on_close = f end wrapped.on_error = function(_,f) assert(type(f) == 'function') on_error = f end local read_io wrapped.read_io = function() if not read_io then local len local len_bin local json_message local _ local receive_message = function(loop,read_io) while true do if not len_bin or #len_bin < 4 then local err,sub len_bin,err,sub = sock:receive(4,len_bin) if len_bin then _,len = sunpack(len_bin,'>I') elseif err == 'timeout' then len_bin = sub return elseif err == 'closed' then read_io:stop(loop) on_close(wrapped) sock:close() return else log('WTF?!',err) read_io:stop(loop) on_error(wrapped,err) sock:close() end end if len then if len > 1000000 then local err = 'message too big:'..len..'bytes' print('jet.socket error',err) on_error(wrapped,err) read_io:stop(loop) sock:close() return end json_message,err,sub = sock:receive(len,json_message) if json_message then if decode then local ok,message = pcall(cjson.decode,json_message) if ok then on_message(wrapped,message) else on_message(wrapped,nil,message) end else on_message(wrapped,json_message) end len = nil len_bin = nil json_message = nil elseif err == 'timeout' then json_message = sub return elseif err == 'closed' then read_io:stop(loop) on_close(wrapped) sock:close() return else read_io:stop(loop) on_error(wrapped,err) sock:close() return end end end end local fd = sock:getfd() assert(fd > -1) read_io = ev.IO.new(receive_message,fd,ev.READ) end return read_io end return wrapped end local mod = { wrap = wrap, wrap_sync = wrap_sync } return mod
bugfix async send
bugfix async send
Lua
mit
lipp/lua-jet
762337214ea1f5a06e44a090281328469c7d0633
src/nodes/wall.lua
src/nodes/wall.lua
local Wall = {} Wall.__index = Wall function Wall.new(node, collider) local wall = {} setmetatable(wall, Wall) wall.bb = collider:addRectangle(node.x, node.y, node.width, node.height) wall.bb.node = wall collider:setPassive(wall.bb) return wall end function Wall:collide(player, dt, mtv_x, mtv_y) if mtv_x ~= 0 then player.velocity.x = 0 player.position.x = player.position.x + mtv_x end if mtv_y ~= 0 then player.velocity.y = 0 player.position.y = player.position.y + mtv_y end end return Wall
local Wall = {} Wall.__index = Wall function Wall.new(node, collider) local wall = {} setmetatable(wall, Wall) wall.bb = collider:addRectangle(node.x, node.y, node.width, node.height) wall.bb.node = wall wall.node = node collider:setPassive(wall.bb) return wall end function Wall:collide(player, dt, mtv_x, mtv_y) if mtv_x ~= 0 then player.velocity.x = 0 player.position.x = player.position.x + mtv_x end if mtv_y > 0 then player.velocity.y = 0 player.position.y = player.position.y + mtv_y end if mtv_y < 0 then player.velocity.y = 0 player.position.y = self.node.y - player.height player.jumping = false end end return Wall
Bug fix so you can stand on a wall
Bug fix so you can stand on a wall
Lua
mit
hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua
b05886f70b0ce394ece1bf31d74940d8c7ac09df
interface/flowparse.lua
interface/flowparse.lua
local log = require "log" local function parse_devices(s, devnum, name) local result = {} for num in string.gmatch(s, "([^,]+)") do if num ~= "" then local n = tonumber(num) if not n or n < 0 or n >= devnum then log:error("Invalid device number %q for flow %q.", num, name) else table.insert(result, n) end end end return result end local fmt = "[<file>/]<name>:[<tx-list>]:[<rx-list>]:[<option-list>]:[<overwrites>]" return function(s, devnum) local name, tx, rx, optstring, overwrites = string.match(s, "^([^:]+)" .. (":?([^:]*)"):rep(3) .. ":?(.*)$") if not name or name == "" then log:fatal("Invalid parameter: %q.\nExpected format: '%s'." .. "\nAll lists are ',' seperated. Trailing ':' can be omitted.", s, fmt) return end local file file, name = string.match(name, "(.*)/([^/]+)") local options = {} for opt in string.gmatch(optstring, "([^,]+)") do if opt ~= "" then local k, v = string.match(opt, "^([^=]+)=([^=]+)$") if not k then k, v = opt, true end options[k] = v end end return { name = name, file = file, tx = parse_devices(tx, devnum, name), rx = parse_devices(rx, devnum, name), options = options, overwrites = overwrites } end
local log = require "log" local function parse_devices(s, devnum, name) local result = {} for num in string.gmatch(s, "([^,]+)") do if num ~= "" then local n = tonumber(num) if not n or n < 0 or n >= devnum then log:error("Invalid device number %q for flow %q.", num, name) else table.insert(result, n) end end end return result end local fmt = "[<file>/]<name>:[<tx-list>]:[<rx-list>]:[<option-list>]:[<overwrites>]" return function(s, devnum) local name, tx, rx, optstring, overwrites = string.match(s, "^([^:]+)" .. (":?([^:]*)"):rep(3) .. ":?(.*)$") if not name or name == "" then log:fatal("Invalid parameter: %q.\nExpected format: '%s'." .. "\nAll lists are ',' seperated. Trailing ':' can be omitted.", s, fmt) return end local file, _name file, _name = string.match(name, "(.*)/([^/]+)") name = _name or name local options = {} for opt in string.gmatch(optstring, "([^,]+)") do if opt ~= "" then local k, v = string.match(opt, "^([^=]+)=([^=]+)$") if not k then k, v = opt, true end options[k] = v end end return { name = name, file = file, tx = parse_devices(tx, devnum, name), rx = parse_devices(rx, devnum, name), options = options, overwrites = overwrites } end
Fix flowparse when no file is specified.
Fix flowparse when no file is specified.
Lua
mit
gallenmu/MoonGen,scholzd/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,emmericp/MoonGen,emmericp/MoonGen,dschoeffm/MoonGen,emmericp/MoonGen,scholzd/MoonGen,gallenmu/MoonGen,dschoeffm/MoonGen,dschoeffm/MoonGen,scholzd/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen
1d1079ec6aadb4892b4d902d91a9618629af2927
middleware/yo-api/yo.lua
middleware/yo-api/yo.lua
-- split function to split a string by a delimiter function split(s, delimiter) result = {} for match in (s..delimiter):gmatch("(.-)"..delimiter) do table.insert(result, match) end return result end return function(request, next_middleware) local response local apiToken = 'YO_API_TOKEN' request.headers['Content-Type']='application/json' -- endpoint to send an individual yo is called if request.uri == '/yo/' then local body = request.body local yoUsername = split(body,'=')[2] console.log(yoUsername) request.body = '{"username":"'.. string.upper(yoUsername) .. '","api_token":"'..apiToken..'"}' -- endpoint to Yo all is called elseif request.uri =='/yoall/' then request.body ='{"api_token":"'..apiToken..'"}' -- callback url is called elseif request.uri == '/' then send.mail('[email protected]','New Yo subscriber', 'NEW Yo SUBSCRIBER '..request.args.username) send.notification({msg="new subscriber " .. request.args.username, level='info'}) end console.log(request.body) return next_middleware() end
-- split function to split a string by a delimiter local function split(s, delimiter) local result = {} for match in (s..delimiter):gmatch("(.-)"..delimiter) do table.insert(result, match) end return result end return function(request, next_middleware) local apiToken = 'YO_API_TOKEN' request.headers['Content-Type'] = 'application/json' -- endpoint to send an individual yo is called if request.uri == '/yo/' then local body = request.body local yoUsername = split(body,'=')[2] console.log(yoUsername) request.body = '{"username":"'.. string.upper(yoUsername) .. '","api_token":"' .. apiToken .. '"}' -- endpoint to Yo all is called elseif request.uri =='/yoall/' then request.body = '{"api_token":"' .. apiToken .. '"}' -- callback url is called elseif request.uri == '/' then send.mail('[email protected]','New Yo subscriber', 'NEW Yo SUBSCRIBER ' .. request.args.username) send.notification({msg="new subscriber " .. request.args.username, level='info'}) end console.log(request.body) return next_middleware() end
fix luacheck messages in yo
fix luacheck messages in yo
Lua
mit
APItools/middleware
bd23f322696394bdb9c0f73f07c168c5f402293d
src/ffluci/model/cbi/admin_wifi/networks.lua
src/ffluci/model/cbi/admin_wifi/networks.lua
-- ToDo: Translate, Add descriptions and help texts m = Map("wireless", "Netze") s = m:section(TypedSection, "wifi-iface") s.addremove = true s.anonymous = true s:option(Value, "ssid", "Netzkennung (ESSID)").maxlength = 32 device = s:option(ListValue, "device", "Gerät") for k, v in pairs(ffluci.model.uci.show("wireless").wireless) do if v[".type"] == "wifi-device" then device:value(k) end end network = s:option(ListValue, "network", "Netzwerk") network:value("") for k, v in pairs(ffluci.model.uci.show("network").network) do if v[".type"] == "interface" then network:value(k) end end mode = s:option(ListValue, "mode", "Modus") mode:value("ap", "Access Point") mode:value("adhoc", "Ad-Hoc") mode:value("sta", "Client") mode:value("wds", "WDS") s:option(Value, "bssid", "BSSID").optional = true s:option(Value, "txpower", "Sendeleistung", "dbm").rmempty = true encr = s:option(ListValue, "encryption", "Verschlüsselung") encr:value("none", "keine") encr:value("wep", "WEP") encr:value("psk", "WPA-PSK") encr:value("wpa", "WPA-Radius") encr:value("psk2", "WPA2-PSK") encr:value("wpa2", "WPA2-Radius") key = s:option(Value, "key", "Schlüssel") key:depends("encryption", "wep") key:depends("encryption", "psk") key:depends("encryption", "wpa") key:depends("encryption", "psk2") key:depends("encryption", "wpa2") key.rmempty = true server = s:option(Value, "server", "Radius-Server") server:depends("encryption", "wpa") server:depends("encryption", "wpa2") server.rmempty = true port = s:option(Value, "port", "Radius-Port") port:depends("encryption", "wpa") port:depends("encryption", "wpa2") port.rmempty = true s:option(Flag, "isolate", "AP-Isolation", "Unterbindet Client-Client-Verkehr").optional = true s:option(Flag, "hidden", "ESSID verstecken").optional = true return m
-- ToDo: Translate, Add descriptions and help texts m = Map("wireless", "Netze") s = m:section(TypedSection, "wifi-iface") s.addremove = true s.anonymous = true s:option(Value, "ssid", "Netzkennung (ESSID)").maxlength = 32 device = s:option(ListValue, "device", "Gerät") local d = ffluci.model.uci.show("wireless").wireless if d then for k, v in pairs(d) do if v[".type"] == "wifi-device" then device:value(k) end end end network = s:option(ListValue, "network", "Netzwerk") network:value("") for k, v in pairs(ffluci.model.uci.show("network").network) do if v[".type"] == "interface" then network:value(k) end end mode = s:option(ListValue, "mode", "Modus") mode:value("ap", "Access Point") mode:value("adhoc", "Ad-Hoc") mode:value("sta", "Client") mode:value("wds", "WDS") s:option(Value, "bssid", "BSSID").optional = true s:option(Value, "txpower", "Sendeleistung", "dbm").rmempty = true encr = s:option(ListValue, "encryption", "Verschlüsselung") encr:value("none", "keine") encr:value("wep", "WEP") encr:value("psk", "WPA-PSK") encr:value("wpa", "WPA-Radius") encr:value("psk2", "WPA2-PSK") encr:value("wpa2", "WPA2-Radius") key = s:option(Value, "key", "Schlüssel") key:depends("encryption", "wep") key:depends("encryption", "psk") key:depends("encryption", "wpa") key:depends("encryption", "psk2") key:depends("encryption", "wpa2") key.rmempty = true server = s:option(Value, "server", "Radius-Server") server:depends("encryption", "wpa") server:depends("encryption", "wpa2") server.rmempty = true port = s:option(Value, "port", "Radius-Port") port:depends("encryption", "wpa") port:depends("encryption", "wpa2") port.rmempty = true s:option(Flag, "isolate", "AP-Isolation", "Unterbindet Client-Client-Verkehr").optional = true s:option(Flag, "hidden", "ESSID verstecken").optional = true return m
* Fixed a bug in Wifi when no wifi interfaces are available
* Fixed a bug in Wifi when no wifi interfaces are available
Lua
apache-2.0
deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci
4f811dd6218b8ea00e700527d17d126ce395c42f
share/lua/website/vimeo.lua
share/lua/website/vimeo.lua
-- libquvi-scripts -- Copyright (C) 2010-2012 Toni Gundogdu <[email protected]> -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -- 02110-1301 USA -- -- w/ HD: <http://vimeo.com/1485507> -- no HD: <http://vimeo.com/10772672> local Vimeo = {} -- 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 = "vimeo%.com" r.formats = "default|best" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/%d+$"}) return r end -- Query available formats. function query_formats(self) local config = Vimeo.get_config(self) local formats = Vimeo.iter_formats(self, config) local t = {} for _,v in pairs(formats) do table.insert(t, Vimeo.to_s(v)) end table.sort(t) self.formats = table.concat(t, "|") return self end -- Parse media URL. function parse(self) self.host_id = "vimeo" local c = Vimeo.get_config(self) self.title = c:match("<caption>(.-)</") or error("no match: media title") self.duration = (tonumber(c:match('<duration>(%d+)')) or 0) * 1000 self.thumbnail_url = c:match('<thumbnail>(.-)<') or '' local formats = Vimeo.iter_formats(self, c) local U = require 'quvi/util' local format = U.choose_format(self, formats, Vimeo.choose_best, Vimeo.choose_default, Vimeo.to_s) or error("unable to choose format") self.url = {format.url or error("no match: media URL")} return self end -- -- Utility functions -- function Vimeo.normalize(url) url = url:gsub("player.", "") -- player.vimeo.com url = url:gsub("/video/", "/") -- player.vimeo.com return url end function Vimeo.get_config(self) self.page_url = Vimeo.normalize(self.page_url) self.id = self.page_url:match('vimeo.com/(%d+)') or error("no match: media ID") local c_url = "http://vimeo.com/moogaloop/load/clip:" .. self.id local c = quvi.fetch(c_url, {fetch_type='config'}) if c:match('<error>') then local s = c:match('<message>(.-)[\n<]') error( (not s) and "no match: error message" or s ) end return c end function Vimeo.iter_formats(self, config) local isHD = tonumber(config:match('<isHD>(%d+)')) or 0 local t = {} Vimeo.add_format(self, config, t, 'sd') if isHD == 1 then Vimeo.add_format(self, config, t, 'hd') end return t end function Vimeo.add_format(self, config, t, quality) table.insert(t, {quality=quality, url=Vimeo.to_url(self, config, quality)}) end function Vimeo.choose_best(formats) -- Last is 'best' local r for _,v in pairs(formats) do r = v end return r end function Vimeo.choose_default(formats) -- First is 'default' for _,v in pairs(formats) do return v end end function Vimeo.to_url(self, config, quality) local sign = config:match("<request_signature>(.-)</") or error("no match: request signature") local exp = config:match("<request_signature_expires>(.-)</") or error("no match: request signature expires") local fmt_s = "http://vimeo.com/moogaloop/play/clip:%s/%s/%s/?q=%s" return string.format(fmt_s, self.id, sign, exp, quality) end function Vimeo.to_s(t) return string.format("%s", t.quality) end -- vim: set ts=4 sw=4 tw=72 expandtab:
-- libquvi-scripts -- Copyright (C) 2010-2012 Toni Gundogdu <[email protected]> -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -- 02110-1301 USA -- -- -- NOTE: Vimeo is picky about the user-agent string. -- local Vimeo = {} -- 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 = "vimeo%.com" r.formats = "default|best" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/%d+$"}) return r end -- Query available formats. function query_formats(self) local config = Vimeo.get_config(self) local formats = Vimeo.iter_formats(self, config) local t = {} for _,v in pairs(formats) do table.insert(t, Vimeo.to_s(v)) end table.sort(t) self.formats = table.concat(t, "|") return self end -- Parse media URL. function parse(self) self.host_id = "vimeo" local c = Vimeo.get_config(self) self.title = c:match('"title":"(.-)"') or error("no match: media title") self.duration = (tonumber(c:match('"duration":(%d+)')) or 0) * 1000 local U = require 'quvi/util' local s = c:match('"thumbnail":"(.-)"') or '' if #s >0 then self.thumbnail_url = U.slash_unescape(s) end local formats = Vimeo.iter_formats(self, c) local format = U.choose_format(self, formats, Vimeo.choose_best, Vimeo.choose_default, Vimeo.to_s) or error("unable to choose format") self.url = {format.url or error("no match: media URL")} return self end -- -- Utility functions -- function Vimeo.normalize(url) url = url:gsub("player.", "") -- player.vimeo.com url = url:gsub("/video/", "/") -- player.vimeo.com return url end function Vimeo.get_config(self) self.page_url = Vimeo.normalize(self.page_url) self.id = self.page_url:match('vimeo.com/(%d+)') or error("no match: media ID") local c_url = "player.vimeo.com/config/" .. self.id local c = quvi.fetch(c_url, {fetch_type='config'}) if c:match('<error>') then local s = c:match('<message>(.-)[\n<]') error( (not s) and "no match: error message" or s ) end return c end function Vimeo.iter_formats(self, config) local t = {} local qualities = config:match('"qualities":%[(.-)%]') for q in qualities:gmatch('"(.-)"') do Vimeo.add_format(self, config, t, q) end return t end function Vimeo.add_format(self, config, t, quality) table.insert(t, {quality=quality, url=Vimeo.to_url(self, config, quality)}) end function Vimeo.choose_best(t) -- First 'hd', then 'sd' and 'mobile' last. for _,v in pairs(t) do local f = Vimeo.to_s(v) for _,q in pairs({'hd','sd','mobile'}) do if f == q then return v end end end return Vimeo.choose_default(t) end function Vimeo.choose_default(t) for _,v in pairs(t) do if Vimeo.to_s(v) == 'sd' then return v end -- Default to 'sd'. end return t[1] -- Or whatever is the first. end function Vimeo.to_url(self, config, quality) local sign = config:match('"signature":"(.-)"') or error("no match: request signature") local exp = config:match('"timestamp":(%d+)') or error("no match: request timestamp") local s = "http://player.vimeo.com/play_redirect?clip_id=%s" .. "&sig=%s&time=%s&quality=%s&type=moogaloop_local" return string.format(s, self.id, sign, exp, quality) end function Vimeo.to_s(t) return string.format("%s", t.quality) end -- vim: set ts=4 sw=4 tw=72 expandtab:
FIX: vimeo.lua (#97)
FIX: vimeo.lua (#97) Many thanks to the contributor whom wishes to remain anonymous. * https://sourceforge.net/apps/trac/quvi/ticket/97
Lua
agpl-3.0
alech/libquvi-scripts,DangerCove/libquvi-scripts,DangerCove/libquvi-scripts,legatvs/libquvi-scripts,legatvs/libquvi-scripts,hadess/libquvi-scripts-iplayer,alech/libquvi-scripts,hadess/libquvi-scripts-iplayer
1e6f9a98c932f073ce20d6951867b16afeebc463
lua/entities/gmod_wire_egp_hud/huddraw.lua
lua/entities/gmod_wire_egp_hud/huddraw.lua
hook.Add("Initialize","EGP_HUD_Initialize",function() if (CLIENT) then local EGP_HUD_FirstPrint = true local tbl = {} -------------------------------------------------------- -- Toggle -------------------------------------------------------- local function EGP_Use( um ) local ent = um:ReadEntity() if (!ent or !ent:IsValid()) then return end local bool = um:ReadChar() if (bool == -1) then ent.On = nil elseif (bool == 1) then ent.On = true elseif (bool == 0) then if (ent.On == true) then ent.On = nil LocalPlayer():ChatPrint("[EGP] EGP HUD Disconnected.") else if (!tbl[ent]) then -- strange... this entity should be in the table. Might have gotten removed due to a lagspike. Add it again EGP:AddHUDEGP( ent ) end ent.On = true if (EGP_HUD_FirstPrint) then LocalPlayer():ChatPrint("[EGP] EGP HUD Connected. NOTE: Type 'wire_egp_hud_unlink' in console to disconnect yourself from all EGP HUDs.") EGP_HUD_FirstPrint = nil else LocalPlayer():ChatPrint("[EGP] EGP HUD Connected.") end end end end usermessage.Hook( "EGP_HUD_Use", EGP_Use ) -------------------------------------------------------- -- Disconnect all HUDs -------------------------------------------------------- concommand.Add("wire_egp_hud_unlink",function() local en = ents.FindByClass("gmod_wire_egp_hud") LocalPlayer():ChatPrint("[EGP] Disconnected from all EGP HUDs.") for k,v in ipairs( en ) do en.On = nil end end) -------------------------------------------------------- -- Add / Remove HUD Entities -------------------------------------------------------- function EGP:AddHUDEGP( Ent ) tbl[Ent] = true end function EGP:RemoveHUDEGP( Ent ) tbl[Ent] = nil end -------------------------------------------------------- -- Paint -------------------------------------------------------- hook.Add("HUDPaint","EGP_HUDPaint",function() for Ent,_ in pairs( tbl ) do if (!Ent or !Ent:IsValid()) then EGP:RemoveHUDEGP( Ent ) break else if (Ent.On == true) then Ent.HasUpdatedThisFrame = nil if (Ent.RenderTable and #Ent.RenderTable > 0) then for _,object in pairs( Ent.RenderTable ) do local oldtex = EGP:SetMaterial( object.material ) object:Draw(Ent) EGP:FixMaterial( oldtex ) -- Check for 3DTracker parent if (!Ent.HasUpdatedThisFrame and object.parent) then local hasObject, _, parent = EGP:HasObject( Ent, object.parent ) if (hasObject and parent.Is3DTracker) then Ent:EGP_Update() Ent.HasUpdatedThisFrame = true end end end end end end end end) -- HUDPaint hook else local vehiclelinks = {} function EGP:LinkHUDToVehicle( hud, vehicle ) if not hud.LinkedVehicles then hud.LinkedVehicles = {} end if not hud.Marks then hud.Marks = {} end hud.Marks[#hud.Marks+1] = vehicle hud.LinkedVehicles[vehicle] = true vehiclelinks[hud] = hud.LinkedVehicles timer.Simple( 0.1, function() -- timers solve everything (this time, it's the fact that the entity isn't valid on the client after dupe) WireLib.SendMarks( hud ) end) end function EGP:UnlinkHUDFromVehicle( hud, vehicle ) if not vehicle then -- unlink all vehiclelinks[hud] = nil hud.LinkedVehicles = nil hud.Marks = nil else if vehiclelinks[hud] then local bool = vehiclelinks[hud][vehicle] if bool then if vehicle:GetDriver() and vehicle:GetDriver():IsValid() then umsg.Start( "EGP_HUD_Use", vehicle:GetDriver() ) umsg.Entity( hud ) umsg.Char( -1 ) umsg.End() end end if hud.Marks then for i=1,#hud.Marks do if hud.Marks[i] == vehicle then table.remove( hud.Marks, i ) break end end end hud.LinkedVehicles[vehicle] = nil if not next( hud.LinkedVehicles ) then hud.LinkedVehicles = nil hud.Marks = nil end vehiclelinks[hud] = hud.LinkedVehicles end end WireLib.SendMarks( hud ) end hook.Add("PlayerEnteredVehicle","EGP_HUD_PlayerEnteredVehicle",function( ply, vehicle ) for k,v in pairs( vehiclelinks ) do if v[vehicle] ~= nil then umsg.Start( "EGP_HUD_Use", ply ) umsg.Entity( k ) umsg.Char( 1 ) umsg.End() end end end) hook.Add("PlayerLeaveVehicle","EGP_HUD_PlayerLeaveVehicle",function( ply, vehicle ) for k,v in pairs( vehiclelinks ) do if v[vehicle] ~= nil then umsg.Start( "EGP_HUD_Use", ply ) umsg.Entity( k ) umsg.Char( -1 ) umsg.End() end end end) end end)
hook.Add("Initialize","EGP_HUD_Initialize",function() if (CLIENT) then local EGP_HUD_FirstPrint = true local tbl = {} -------------------------------------------------------- -- Toggle -------------------------------------------------------- local function EGP_Use( um ) local ent = um:ReadEntity() if (!ent or !ent:IsValid()) then return end local bool = um:ReadChar() if (bool == -1) then ent.On = nil elseif (bool == 1) then ent.On = true elseif (bool == 0) then if (ent.On == true) then ent.On = nil LocalPlayer():ChatPrint("[EGP] EGP HUD Disconnected.") else if (!tbl[ent]) then -- strange... this entity should be in the table. Might have gotten removed due to a lagspike. Add it again EGP:AddHUDEGP( ent ) end ent.On = true if (EGP_HUD_FirstPrint) then LocalPlayer():ChatPrint("[EGP] EGP HUD Connected. NOTE: Type 'wire_egp_hud_unlink' in console to disconnect yourself from all EGP HUDs.") EGP_HUD_FirstPrint = nil else LocalPlayer():ChatPrint("[EGP] EGP HUD Connected.") end end end end usermessage.Hook( "EGP_HUD_Use", EGP_Use ) -------------------------------------------------------- -- Disconnect all HUDs -------------------------------------------------------- concommand.Add("wire_egp_hud_unlink",function() local en = ents.FindByClass("gmod_wire_egp_hud") LocalPlayer():ChatPrint("[EGP] Disconnected from all EGP HUDs.") for k,v in ipairs( en ) do en.On = nil end end) -------------------------------------------------------- -- Add / Remove HUD Entities -------------------------------------------------------- function EGP:AddHUDEGP( Ent ) tbl[Ent] = true end function EGP:RemoveHUDEGP( Ent ) tbl[Ent] = nil end -------------------------------------------------------- -- Paint -------------------------------------------------------- hook.Add("HUDPaint","EGP_HUDPaint",function() for Ent,_ in pairs( tbl ) do if (!Ent or !Ent:IsValid()) then EGP:RemoveHUDEGP( Ent ) break else if (Ent.On == true) then if (Ent.RenderTable and #Ent.RenderTable > 0) then for _,object in pairs( Ent.RenderTable ) do local oldtex = EGP:SetMaterial( object.material ) object:Draw(Ent) EGP:FixMaterial( oldtex ) -- Check for 3DTracker parent if (object.parent) then local hasObject, _, parent = EGP:HasObject( Ent, object.parent ) if (hasObject and parent.Is3DTracker) then Ent:EGP_Update() end end end end end end end end) -- HUDPaint hook else local vehiclelinks = {} function EGP:LinkHUDToVehicle( hud, vehicle ) if not hud.LinkedVehicles then hud.LinkedVehicles = {} end if not hud.Marks then hud.Marks = {} end hud.Marks[#hud.Marks+1] = vehicle hud.LinkedVehicles[vehicle] = true vehiclelinks[hud] = hud.LinkedVehicles timer.Simple( 0.1, function() -- timers solve everything (this time, it's the fact that the entity isn't valid on the client after dupe) WireLib.SendMarks( hud ) end) end function EGP:UnlinkHUDFromVehicle( hud, vehicle ) if not vehicle then -- unlink all vehiclelinks[hud] = nil hud.LinkedVehicles = nil hud.Marks = nil else if vehiclelinks[hud] then local bool = vehiclelinks[hud][vehicle] if bool then if vehicle:GetDriver() and vehicle:GetDriver():IsValid() then umsg.Start( "EGP_HUD_Use", vehicle:GetDriver() ) umsg.Entity( hud ) umsg.Char( -1 ) umsg.End() end end if hud.Marks then for i=1,#hud.Marks do if hud.Marks[i] == vehicle then table.remove( hud.Marks, i ) break end end end hud.LinkedVehicles[vehicle] = nil if not next( hud.LinkedVehicles ) then hud.LinkedVehicles = nil hud.Marks = nil end vehiclelinks[hud] = hud.LinkedVehicles end end WireLib.SendMarks( hud ) end hook.Add("PlayerEnteredVehicle","EGP_HUD_PlayerEnteredVehicle",function( ply, vehicle ) for k,v in pairs( vehiclelinks ) do if v[vehicle] ~= nil then umsg.Start( "EGP_HUD_Use", ply ) umsg.Entity( k ) umsg.Char( 1 ) umsg.End() end end end) hook.Add("PlayerLeaveVehicle","EGP_HUD_PlayerLeaveVehicle",function( ply, vehicle ) for k,v in pairs( vehiclelinks ) do if v[vehicle] ~= nil then umsg.Start( "EGP_HUD_Use", ply ) umsg.Entity( k ) umsg.Char( -1 ) umsg.End() end end end) end end)
attempting to fix imperfect parenting in egp
attempting to fix imperfect parenting in egp This may come at a cost of optimization but this was the only way I could get it to work
Lua
apache-2.0
Grocel/wire,bigdogmat/wire,rafradek/wire,CaptainPRICE/wire,mms92/wire,NezzKryptic/Wire,Python1320/wire,notcake/wire,dvdvideo1234/wire,garrysmodlua/wire,thegrb93/wire,sammyt291/wire,mitterdoo/wire,wiremod/wire
e368e93de68079c2c89b899ad3f335daeae9965b
etc/querylib.lua
etc/querylib.lua
-- -- Some common queries for Ion -- if QueryLib~=nil then return end QueryLib={} -- -- Helper functions -- function QueryLib.make_simple_fn(prompt, initfn, handler, completor) local function query_it(frame) local initvalue; if initfn then initvalue=initfn() end query_query(frame, prompt, initvalue or "", handler, completor) end return query_it end function QueryLib.make_frame_fn(prompt, initfn, handler, completor) local function query_it(frame) local initvalue; if initfn then initvalue=initfn(frame) end local function handle_it(str) handler(%frame, str) end query_query(frame, prompt, initvalue or "", handle_it, completor) end return query_it end function QueryLib.make_rename_fn(prompt, getobj) local function query_it(frame) local obj=getobj(frame) local function handle_it(str) region_set_name(%obj, str) end query_query(frame, %prompt, region_name(obj) or "", handle_it, nil) end return query_it end function QueryLib.exec_handler(frame, cmd) if string.sub(cmd, 1, 1)==":" then cmd="ion-runinxterm " .. string.sub(cmd, 2) end exec_on_screen(region_screen_of(frame), cmd) end function QueryLib.make_yesno_handler(fn) local function handle_yesno(_, yesno) if yesno=="y" or yesno=="Y" or yesno=="yes" then %fn(unpack(arg)) end end return handle_yesno end function QueryLib.make_yesno_fn(prompt, handler) return QueryLib.make_frame_fn(prompt, QueryLib.make_yesno_handler(handler), nil) end function QueryLib.getws(obj) while obj~=nil do if obj_is(obj, "WGenWS") then return obj end obj=region_manager(obj) end end function QueryLib.complete_ssh(str) if string.len(str)==0 then return query_ssh_hosts end local res={} for _, v in ipairs(query_ssh_hosts) do local s, e=string.find(v, str, 1, true) if s==1 and e>=1 then table.insert(res, v) end end return res end function QueryLib.make_execwith_fn(prompt, init, prog, completor) local function handle_execwith(frame, str) exec_on_screen(region_screen_of(frame), prog .. " " .. str) end return QueryLib.make_frame_fn(prompt, init, handle_execwith, completor) end function QueryLib.gotoclient_handler(frame, str) local cwin=lookup_clientwin(str) if cwin==nil then query_fwarn(frame, string.format("Could not find client window named" .. ' "%s"', str)) else region_goto(cwin) end end function QueryLib.handler_lua(frame, code) local f=loadstring(code) if f then local oldarg=arg arg={frame, genframe_current(frame)} pcall(f) oldarg=arg end end function QueryLib.get_initdir() local wd=os.getenv("PWD") if wd==nil then wd="/" elseif string.sub(wd, -1)~="/" then wd=wd .. "/" end return wd end function QueryLib.complete_function(str) res={} for k, v in pairs(_G) do if type(v)=="function" then table.insert(res, k) end end return res end -- -- The queries -- QueryLib.query_gotoclient=QueryLib.make_frame_fn("Go to window:", nil, QueryLib.gotoclient_handler, complete_clientwin) QueryLib.query_attachclient=QueryLib.make_frame_fn("Attach window:", nil, query_handler_attachclient, complete_clientwin) QueryLib.query_workspace=QueryLib.make_frame_fn("Go to or create workspace:", nil, query_handler_workspace, complete_workspace) QueryLib.query_exec=QueryLib.make_frame_fn("Run:", nil, QueryLib.exec_handler, complete_file_with_path) QueryLib.query_exit=QueryLib.make_yesno_fn("Exit Ion (y/n)?", exit_wm) QueryLib.query_restart=QueryLib.make_yesno_fn("Restart Ion (y/n)?", restart_wm) QueryLib.query_renameframe=QueryLib.make_rename_fn("Frame name: ", function(frame) return frame end ) QueryLib.query_renameworkspace=QueryLib.make_rename_fn("Workspace name: ", QueryLib.getws) QueryLib.query_ssh=QueryLib.make_execwith_fn("SSH to:", nil, "ion-ssh", QueryLib.complete_ssh) QueryLib.query_man=QueryLib.make_execwith_fn("Manual page (ion):", nil, "ion-man", nil) QueryLib.query_editfile=QueryLib.make_execwith_fn("Edit file:", QueryLib.get_initdir, "ion-edit", complete_file) QueryLib.query_runfile=QueryLib.make_execwith_fn("View file:", QueryLib.get_initdir, "ion-view", complete_file) QueryLib.query_lua=QueryLib.make_frame_fn("Lua code to run:", nil, QueryLib.handler_lua, QueryLib.complete_function);
-- -- Some common queries for Ion -- if QueryLib~=nil then return end QueryLib={} -- -- Helper functions -- function QueryLib.make_simple_fn(prompt, initfn, handler, completor) local function query_it(frame) local initvalue; if initfn then initvalue=initfn() end query_query(frame, prompt, initvalue or "", handler, completor) end return query_it end function QueryLib.make_frame_fn(prompt, initfn, handler, completor) local function query_it(frame) local initvalue; if initfn then initvalue=initfn(frame) end local function handle_it(str) handler(%frame, str) end query_query(frame, prompt, initvalue or "", handle_it, completor) end return query_it end function QueryLib.make_rename_fn(prompt, getobj) local function query_it(frame) local obj=getobj(frame) local function handle_it(str) region_set_name(%obj, str) end query_query(frame, %prompt, region_name(obj) or "", handle_it, nil) end return query_it end function QueryLib.exec_handler(frame, cmd) if string.sub(cmd, 1, 1)==":" then cmd="ion-runinxterm " .. string.sub(cmd, 2) end exec_on_screen(region_screen_of(frame), cmd) end function QueryLib.make_yesno_handler(fn) local function handle_yesno(_, yesno) if yesno=="y" or yesno=="Y" or yesno=="yes" then if arg then %fn(unpack(arg)) else %fn() end end end return handle_yesno end function QueryLib.make_yesno_fn(prompt, handler) return QueryLib.make_frame_fn(prompt, nil, QueryLib.make_yesno_handler(handler), nil) end function QueryLib.getws(obj) while obj~=nil do if obj_is(obj, "WGenWS") then return obj end obj=region_manager(obj) end end function QueryLib.complete_ssh(str) if string.len(str)==0 then return query_ssh_hosts end local res={} for _, v in ipairs(query_ssh_hosts) do local s, e=string.find(v, str, 1, true) if s==1 and e>=1 then table.insert(res, v) end end return res end function QueryLib.make_execwith_fn(prompt, init, prog, completor) local function handle_execwith(frame, str) exec_on_screen(region_screen_of(frame), prog .. " " .. str) end return QueryLib.make_frame_fn(prompt, init, handle_execwith, completor) end function QueryLib.gotoclient_handler(frame, str) local cwin=lookup_clientwin(str) if cwin==nil then query_fwarn(frame, string.format("Could not find client window named" .. ' "%s"', str)) else region_goto(cwin) end end function QueryLib.handler_lua(frame, code) local f=loadstring(code) if f then local oldarg=arg arg={frame, genframe_current(frame)} pcall(f) oldarg=arg end end function QueryLib.get_initdir() local wd=os.getenv("PWD") if wd==nil then wd="/" elseif string.sub(wd, -1)~="/" then wd=wd .. "/" end return wd end function QueryLib.complete_function(str) res={} for k, v in pairs(_G) do if type(v)=="function" then table.insert(res, k) end end return res end -- -- The queries -- QueryLib.query_gotoclient=QueryLib.make_frame_fn("Go to window:", nil, QueryLib.gotoclient_handler, complete_clientwin) QueryLib.query_attachclient=QueryLib.make_frame_fn("Attach window:", nil, query_handler_attachclient, complete_clientwin) QueryLib.query_workspace=QueryLib.make_frame_fn("Go to or create workspace:", nil, query_handler_workspace, complete_workspace) QueryLib.query_exec=QueryLib.make_frame_fn("Run:", nil, QueryLib.exec_handler, complete_file_with_path) QueryLib.query_exit=QueryLib.make_yesno_fn("Exit Ion (y/n)?", exit_wm) QueryLib.query_restart=QueryLib.make_yesno_fn("Restart Ion (y/n)?", restart_wm) QueryLib.query_renameframe=QueryLib.make_rename_fn("Frame name: ", function(frame) return frame end ) QueryLib.query_renameworkspace=QueryLib.make_rename_fn("Workspace name: ", QueryLib.getws) QueryLib.query_ssh=QueryLib.make_execwith_fn("SSH to:", nil, "ion-ssh", QueryLib.complete_ssh) QueryLib.query_man=QueryLib.make_execwith_fn("Manual page (ion):", nil, "ion-man", nil) QueryLib.query_editfile=QueryLib.make_execwith_fn("Edit file:", QueryLib.get_initdir, "ion-edit", complete_file) QueryLib.query_runfile=QueryLib.make_execwith_fn("View file:", QueryLib.get_initdir, "ion-view", complete_file) QueryLib.query_lua=QueryLib.make_frame_fn("Lua code to run:", nil, QueryLib.handler_lua, QueryLib.complete_function);
trunk: changeset 410
trunk: changeset 410 QueryLib.query_yesno fixed. darcs-hash:20030410180812-e481e-fe0258441fbee48a2740ac348c0576e1f9c1cf6e.gz
Lua
lgpl-2.1
knixeur/notion,p5n/notion,dkogan/notion,knixeur/notion,neg-serg/notion,anoduck/notion,dkogan/notion.xfttest,neg-serg/notion,raboof/notion,dkogan/notion,dkogan/notion,p5n/notion,raboof/notion,dkogan/notion,p5n/notion,knixeur/notion,p5n/notion,dkogan/notion.xfttest,anoduck/notion,anoduck/notion,dkogan/notion.xfttest,neg-serg/notion,p5n/notion,knixeur/notion,dkogan/notion,dkogan/notion.xfttest,raboof/notion,neg-serg/notion,anoduck/notion,anoduck/notion,raboof/notion,knixeur/notion
68ea11658d9a9044103f00836dfbd4445ac23742
src/lua-factory/sources/grl-metrolyrics.lua
src/lua-factory/sources/grl-metrolyrics.lua
--[[ * Copyright (C) 2014 Victor Toso. * * Contact: Victor Toso <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * --]] --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-metrolyrics", name = "Metrolyrics", description = "a source for lyrics", supported_keys = { "lyrics" }, supported_media = { 'audio', 'video' }, resolve_keys = { ["type"] = "audio", required = { "artist", "title" }, }, tags = { 'music', 'net:internet', 'net:plaintext' }, } netopts = { user_agent = "Grilo Source Metrolyrics/0.2.8", } ------------------ -- Source utils -- ------------------ METROLYRICS_INVALID_URL_CHARS = "[" .. "%(%)%[%]%$%&" .. "]" METROLYRICS_DEFAULT_QUERY = "http://www.metrolyrics.com/%s-lyrics-%s.html" --------------------------------- -- Handlers of Grilo functions -- --------------------------------- function grl_source_resolve() local url, req local artist, title req = grl.get_media_keys() if not req or not req.artist or not req.title or #req.artist == 0 or #req.title == 0 then grl.callback() return end -- Prepare artist and title strings to the url artist = req.artist:gsub(METROLYRICS_INVALID_URL_CHARS, "") artist = artist:gsub("%s+", "-") title = req.title:gsub(METROLYRICS_INVALID_URL_CHARS, "") title = title:gsub("%s+", "-") url = string.format(METROLYRICS_DEFAULT_QUERY, title, artist) grl.fetch(url, "fetch_page_cb", netopts) end --------------- -- Utilities -- --------------- function fetch_page_cb(feed) local media = nil if feed and not feed:find("notfound") then media = metrolyrics_get_lyrics(feed) end grl.callback(media, 0) end function metrolyrics_get_lyrics(feed) local media = {} local lyrics_body = '<div id="lyrics%-body%-text">(.-)</div>' local noise_array = { { noise = "</p>", sub = "\n\n" }, { noise = "<p class='verse'><p class='verse'>", sub = "\n\n" }, { noise = "<p class='verse'>", sub = "" }, { noise = "<br/>", sub = "" }, } -- remove html noise feed = feed:match(lyrics_body) if not feed then grl.warning ("This Lyrics do not match our parser! Please file a bug!") return nil end for _, it in ipairs (noise_array) do feed = feed:gsub(it.noise, it.sub) end -- strip the lyrics feed = feed:gsub("^[%s%W]*(.-)[%s%W]*$", "%1") -- switch table to string media.lyrics = feed return media end
--[[ * Copyright (C) 2014 Victor Toso. * * Contact: Victor Toso <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * --]] --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-metrolyrics", name = "Metrolyrics", description = "a source for lyrics", supported_keys = { "lyrics" }, supported_media = { 'audio', 'video' }, resolve_keys = { ["type"] = "audio", required = { "artist", "title" }, }, tags = { 'music', 'net:internet', 'net:plaintext' }, } netopts = { user_agent = "Grilo Source Metrolyrics/0.2.8", } ------------------ -- Source utils -- ------------------ METROLYRICS_INVALID_URL_CHARS = "[" .. "%(%)%[%]%$%&" .. "]" METROLYRICS_DEFAULT_QUERY = "http://www.metrolyrics.com/%s-lyrics-%s.html" --------------------------------- -- Handlers of Grilo functions -- --------------------------------- function grl_source_resolve() local url, req local artist, title req = grl.get_media_keys() if not req or not req.artist or not req.title or #req.artist == 0 or #req.title == 0 then grl.callback() return end -- Prepare artist and title strings to the url artist = req.artist:gsub(METROLYRICS_INVALID_URL_CHARS, "") artist = artist:gsub("%s+", "-") title = req.title:gsub(METROLYRICS_INVALID_URL_CHARS, "") title = title:gsub("%s+", "-") url = string.format(METROLYRICS_DEFAULT_QUERY, title, artist) grl.fetch(url, "fetch_page_cb", netopts) end --------------- -- Utilities -- --------------- function fetch_page_cb(feed) local media = nil if feed and not feed:find("notfound") then media = metrolyrics_get_lyrics(feed) end grl.callback(media, 0) end function metrolyrics_get_lyrics(feed) local media = {} local lyrics_body = '<div id="lyrics%-body%-text".->(.-)</div>' local noise_array = { { noise = "</p>", sub = "\n\n" }, { noise = "<p class='verse'><p class='verse'>", sub = "\n\n" }, { noise = "<p class='verse'>", sub = "" }, { noise = "<br/>", sub = "" }, { noise = "<br>", sub = "" }, } -- remove html noise feed = feed:match(lyrics_body) if not feed then grl.warning ("This Lyrics do not match our parser! Please file a bug!") return nil end for _, it in ipairs (noise_array) do feed = feed:gsub(it.noise, it.sub) end -- strip the lyrics feed = feed:gsub("^[%s%W]*(.-)[%s%W]*$", "%1") -- switch table to string media.lyrics = feed return media end
metrolyrics: fix parser after metrolyrics changes
metrolyrics: fix parser after metrolyrics changes Metrolyrics now include `class="js-lyric-text"` in the div for lyrics and this patch just ignore it. Also remove `<br>` noise that was introduced recently. https://bugzilla.gnome.org/show_bug.cgi?id=759109
Lua
lgpl-2.1
grilofw/grilo-plugins,MikePetullo/grilo-plugins,jasuarez/grilo-plugins,MikePetullo/grilo-plugins,MikePetullo/grilo-plugins,GNOME/grilo-plugins,jasuarez/grilo-plugins,grilofw/grilo-plugins,GNOME/grilo-plugins
dd1b67b79d9ac1eeaff1e1c7f77fb54f095045e3
nvim/.config/nvim/plugins/nvim-tree.lua
nvim/.config/nvim/plugins/nvim-tree.lua
-- following options are the default -- each of these are documented in `:help nvim-tree.OPTION_NAME` require'nvim-tree'.setup { disable_netrw = true, hijack_netrw = true, open_on_setup = false, ignore_ft_on_setup = {}, auto_close = false, open_on_tab = false, hijack_cursor = false, update_cwd = false, update_to_buf_dir = { enable = true, auto_open = true, }, diagnostics = { enable = false, icons = { hint = "", info = "", warning = "", error = "", } }, update_focused_file = { enable = false, update_cwd = false, ignore_list = {} }, system_open = { cmd = nil, args = {} }, filters = { dotfiles = false, custom = {} }, git = { enable = true, ignore = true, timeout = 500, }, view = { width = 30, height = 30, hide_root_folder = false, side = 'left', auto_resize = false, mappings = { custom_only = false, list = {} }, number = false, relativenumber = false, signcolumn = "yes" }, trash = { cmd = "trash", require_confirm = true } } vim.api.nvim_set_keymap('n', '<leader>e', '<cmd>NvimTreeToggle<CR>', { noremap = true }) vim.api.nvim_set_keymap('n', '<leader>fr', '<cmd>NvimTreeFindFile<CR>', { noremap = true })
-- following options are the default -- each of these are documented in `:help nvim-tree.OPTION_NAME` require'nvim-tree'.setup { disable_netrw = true, hijack_netrw = true, open_on_setup = false, ignore_ft_on_setup = {}, open_on_tab = false, hijack_cursor = false, update_cwd = false, diagnostics = { enable = false, icons = { hint = "", info = "", warning = "", error = "", } }, update_focused_file = { enable = false, update_cwd = false, ignore_list = {} }, system_open = { cmd = nil, args = {} }, filters = { dotfiles = false, custom = {} }, git = { enable = true, ignore = true, timeout = 500, }, view = { width = 30, height = 30, hide_root_folder = false, side = 'left', mappings = { custom_only = false, list = {} }, number = false, relativenumber = false, signcolumn = "yes" }, trash = { cmd = "trash", require_confirm = true } } vim.api.nvim_set_keymap('n', '<leader>e', '<cmd>NvimTreeToggle<CR>', { noremap = true }) vim.api.nvim_set_keymap('n', '<leader>fr', '<cmd>NvimTreeFindFile<CR>', { noremap = true })
Fix nvimtree settings
Fix nvimtree settings
Lua
mit
il-tmfv/dotfiles
0cdc5b64f4365bbc4dafd0552db7f9ea07923496
frontend/dbg.lua
frontend/dbg.lua
local DocSettings = require("docsettings") -- for dump method local Dbg = { is_on = false, ev_log = nil, } local Dbg_mt = {} local function LvDEBUG(lv, ...) local line = "" for i,v in ipairs({...}) do if type(v) == "table" then line = line .. " " .. DocSettings:dump(v, lv) else line = line .. " " .. tostring(v) end end print("#"..line) end local function DEBUGBT() DEBUG(debug.traceback()) end function Dbg_mt.__call(dbg, ...) LvDEBUG(math.huge, ...) end function Dbg:turnOn() self.is_on = true -- create or clear ev log file os.execute("echo > ev.log") self.ev_log = io.open("ev.log", "w") end function Dbg:logEv(ev) local log = ev.type.."|"..ev.code.."|" ..ev.value.."|"..ev.time.sec.."|"..ev.time.usec.."\n" self.ev_log:write(log) self.ev_log:flush() end setmetatable(Dbg, Dbg_mt) return Dbg
local DocSettings = require("docsettings") -- for dump method local Dbg = { is_on = false, ev_log = nil, } local Dbg_mt = {} local function LvDEBUG(lv, ...) local line = "" for i,v in ipairs({...}) do if type(v) == "table" then line = line .. " " .. DocSettings:dump(v, lv) else line = line .. " " .. tostring(v) end end print("#"..line) end function Dbg_mt.__call(dbg, ...) if dbg.is_on then LvDEBUG(math.huge, ...) end end function Dbg:turnOn() self.is_on = true -- create or clear ev log file os.execute("echo > ev.log") self.ev_log = io.open("ev.log", "w") end function Dbg:logEv(ev) local log = ev.type.."|"..ev.code.."|" ..ev.value.."|"..ev.time.sec.."|"..ev.time.usec.."\n" self.ev_log:write(log) self.ev_log:flush() end function Dbg:traceback() LvDEBUG(math.huge, debug.traceback()) end setmetatable(Dbg, Dbg_mt) return Dbg
fix debug on/off toggle
fix debug on/off toggle
Lua
agpl-3.0
pazos/koreader,frankyifei/koreader,koreader/koreader,koreader/koreader,mwoz123/koreader,chrox/koreader,poire-z/koreader,robert00s/koreader,NiLuJe/koreader,Frenzie/koreader,Hzj-jie/koreader,Markismus/koreader,NickSavage/koreader,chihyang/koreader,ashhher3/koreader,NiLuJe/koreader,ashang/koreader,apletnev/koreader,noname007/koreader,poire-z/koreader,houqp/koreader,Frenzie/koreader,mihailim/koreader,lgeek/koreader
47da9600d1a005f3121e5924c3c159aebd422596
frontend/apps/cloudstorage/webdavapi.lua
frontend/apps/cloudstorage/webdavapi.lua
local DocumentRegistry = require("document/documentregistry") local FFIUtil = require("ffi/util") local http = require('socket.http') local https = require('ssl.https') local ltn12 = require('ltn12') local mime = require('mime') local socket = require('socket') local url = require('socket.url') local util = require("util") local _ = require("gettext") local WebDavApi = { } function WebDavApi:isCurrentDirectory( current_item, address, path ) local is_home, is_parent local home_path -- find first occurence of / after http(s):// local start = string.find( address, "/", 9 ) if not start then home_path = "/" else home_path = string.sub( address, start ) end local item if string.sub( current_item, -1 ) == "/" then item = string.sub( current_item, 1, -2 ) else item = current_item end if item == home_path then is_home = true else local temp_path = string.sub( item, string.len(home_path) + 1 ) if temp_path == path then is_parent = true end end return is_home or is_parent end -- version of urlEncode that doesn't encode the / function WebDavApi:urlEncode(url_data) local char_to_hex = function(c) return string.format("%%%02X", string.byte(c)) end if url_data == nil then return end url_data = url_data:gsub("([^%w%/%-%.%_%~%!%*%'%(%)])", char_to_hex) return url_data end function WebDavApi:listFolder(address, user, pass, folder_path) local path = self:urlEncode( folder_path ) local webdav_list = {} local webdav_file = {} local has_trailing_slash = false local has_leading_slash = false if string.sub( address, -1 ) ~= "/" then has_trailing_slash = true end if path == nil or path == "/" then path = "" elseif string.sub( path, 1, 2 ) == "/" then if has_trailing_slash then -- too many slashes, remove one path = string.sub( path, 1 ) end has_leading_slash = true end if not has_trailing_slash and not has_leading_slash then address = address .. "/" end local webdav_url = address .. path local request, sink = {}, {} local parsed = url.parse(webdav_url) local data = [[<?xml version="1.0"?><a:propfind xmlns:a="DAV:"><a:prop><a:resourcetype/></a:prop></a:propfind>]] local auth = string.format("%s:%s", user, pass) local headers = { ["Authorization"] = "Basic " .. mime.b64( auth ), ["Content-Type"] = "application/xml", ["Depth"] = "1", ["Content-Length"] = #data} request["url"] = webdav_url request["method"] = "PROPFIND" request["headers"] = headers request["source"] = ltn12.source.string(data) request["sink"] = ltn12.sink.table(sink) http.TIMEOUT = 5 https.TIMEOUT = 5 local httpRequest = parsed.scheme == "http" and http.request or https.request local headers_request = socket.skip(1, httpRequest(request)) if headers_request == nil then return nil end local res_data = table.concat(sink) if res_data ~= "" then -- iterate through the <d:response> tags, each containing an entry for item in res_data:gmatch("<d:response>(.-)</d:response>") do --logger.dbg("WebDav catalog item=", item) -- <d:href> is the path and filename of the entry. local item_fullpath = item:match("<d:href>(.*)</d:href>") local is_current_dir = self:isCurrentDirectory( item_fullpath, address, path ) local item_name = util.urlDecode( FFIUtil.basename( item_fullpath ) ) local item_path = path .. "/" .. item_name if item:find("<d:collection/>") then item_name = item_name .. "/" if not is_current_dir then table.insert(webdav_list, { text = item_name, url = util.urlDecode( item_path ), type = "folder", }) end elseif item:find("<d:resourcetype/>") and (DocumentRegistry:hasProvider(item_name) or G_reader_settings:isTrue("show_unsupported")) then table.insert(webdav_file, { text = item_name, url = util.urlDecode( item_path ), type = "file", }) end end else return nil end --sort table.sort(webdav_list, function(v1,v2) return v1.text < v2.text end) table.sort(webdav_file, function(v1,v2) return v1.text < v2.text end) for _, files in ipairs(webdav_file) do table.insert(webdav_list, { text = files.text, url = files.url, type = files.type, }) end return webdav_list end function WebDavApi:downloadFile(file_url, user, pass, local_path) local parsed = url.parse(file_url) local auth = string.format("%s:%s", user, pass) local headers = { ["Authorization"] = "Basic " .. mime.b64( auth ) } http.TIMEOUT = 5 https.TIMEOUT = 5 local httpRequest = parsed.scheme == "http" and http.request or https.request local _, code_return, _ = httpRequest{ url = file_url, method = "GET", headers = headers, sink = ltn12.sink.file(io.open(local_path, "w")) } return code_return end return WebDavApi
local DocumentRegistry = require("document/documentregistry") local FFIUtil = require("ffi/util") local http = require('socket.http') local https = require('ssl.https') local ltn12 = require('ltn12') local mime = require('mime') local socket = require('socket') local url = require('socket.url') local util = require("util") local _ = require("gettext") local WebDavApi = { } function WebDavApi:isCurrentDirectory( current_item, address, path ) local is_home, is_parent local home_path -- find first occurence of / after http(s):// local start = string.find( address, "/", 9 ) if not start then home_path = "/" else home_path = string.sub( address, start ) end local item if string.sub( current_item, -1 ) == "/" then item = string.sub( current_item, 1, -2 ) else item = current_item end if item == home_path then is_home = true else local temp_path = string.sub( item, string.len(home_path) + 1 ) if temp_path == path then is_parent = true end end return is_home or is_parent end -- version of urlEncode that doesn't encode the / function WebDavApi:urlEncode(url_data) local char_to_hex = function(c) return string.format("%%%02X", string.byte(c)) end if url_data == nil then return end url_data = url_data:gsub("([^%w%/%-%.%_%~%!%*%'%(%)])", char_to_hex) return url_data end function WebDavApi:listFolder(address, user, pass, folder_path) local path = self:urlEncode( folder_path ) local webdav_list = {} local webdav_file = {} local has_trailing_slash = false local has_leading_slash = false if string.sub( address, -1 ) ~= "/" then has_trailing_slash = true end if path == nil or path == "/" then path = "" elseif string.sub( path, 1, 2 ) == "/" then if has_trailing_slash then -- too many slashes, remove one path = string.sub( path, 1 ) end has_leading_slash = true end if not has_trailing_slash and not has_leading_slash then address = address .. "/" end local webdav_url = address .. path local request, sink = {}, {} local parsed = url.parse(webdav_url) local data = [[<?xml version="1.0"?><a:propfind xmlns:a="DAV:"><a:prop><a:resourcetype/></a:prop></a:propfind>]] local auth = string.format("%s:%s", user, pass) local headers = { ["Authorization"] = "Basic " .. mime.b64( auth ), ["Content-Type"] = "application/xml", ["Depth"] = "1", ["Content-Length"] = #data} request["url"] = webdav_url request["method"] = "PROPFIND" request["headers"] = headers request["source"] = ltn12.source.string(data) request["sink"] = ltn12.sink.table(sink) http.TIMEOUT = 5 https.TIMEOUT = 5 local httpRequest = parsed.scheme == "http" and http.request or https.request local headers_request = socket.skip(1, httpRequest(request)) if headers_request == nil then return nil end local res_data = table.concat(sink) if res_data ~= "" then -- iterate through the <d:response> tags, each containing an entry for item in res_data:gmatch("<d:response>(.-)</d:response>") do --logger.dbg("WebDav catalog item=", item) -- <d:href> is the path and filename of the entry. local item_fullpath = item:match("<d:href>(.*)</d:href>") if string.sub( item_fullpath, -1 ) == "/" then item_fullpath = string.sub( item_fullpath, 1, -2 ) end local is_current_dir = self:isCurrentDirectory( item_fullpath, address, path ) local item_name = util.urlDecode( FFIUtil.basename( item_fullpath ) ) local item_path = path .. "/" .. item_name if item:find("<d:collection/>") then item_name = item_name .. "/" if not is_current_dir then table.insert(webdav_list, { text = item_name, url = util.urlDecode( item_path ), type = "folder", }) end elseif item:find("<d:resourcetype/>") and (DocumentRegistry:hasProvider(item_name) or G_reader_settings:isTrue("show_unsupported")) then table.insert(webdav_file, { text = item_name, url = util.urlDecode( item_path ), type = "file", }) end end else return nil end --sort table.sort(webdav_list, function(v1,v2) return v1.text < v2.text end) table.sort(webdav_file, function(v1,v2) return v1.text < v2.text end) for _, files in ipairs(webdav_file) do table.insert(webdav_list, { text = files.text, url = files.url, type = files.type, }) end return webdav_list end function WebDavApi:downloadFile(file_url, user, pass, local_path) local parsed = url.parse(file_url) local auth = string.format("%s:%s", user, pass) local headers = { ["Authorization"] = "Basic " .. mime.b64( auth ) } http.TIMEOUT = 5 https.TIMEOUT = 5 local httpRequest = parsed.scheme == "http" and http.request or https.request local _, code_return, _ = httpRequest{ url = file_url, method = "GET", headers = headers, sink = ltn12.sink.file(io.open(local_path, "w")) } return code_return end return WebDavApi
fix "empty folder" when accessing nextcloud webdav (#5171)
fix "empty folder" when accessing nextcloud webdav (#5171) fix for cloud storage webdav nextcloud "empty folder" problem See https://github.com/koreader/koreader/issues/4879
Lua
agpl-3.0
koreader/koreader,poire-z/koreader,koreader/koreader,Frenzie/koreader,pazos/koreader,poire-z/koreader,mwoz123/koreader,Markismus/koreader,Hzj-jie/koreader,Frenzie/koreader,NiLuJe/koreader,mihailim/koreader,NiLuJe/koreader
8fdcef9daa744796e01f68a32de28831ca1fa45b
src/actions/qmake/qmake_project.lua
src/actions/qmake/qmake_project.lua
-- qmake_project.lua -- Generates .pri projects function premake.qmake.project(prj) if prj.kind == "WindowedApp" then _p(0, 'TEMPLATE = app') elseif prj.kind == "ConsoleApp" then _p(0, 'TEMPLATE = app') _p(0, 'CONFIG += console') _p(0, 'CONFIG -= app_bundle') elseif prj.kind == "StaticLib" or prj.kind == "SharedLib" then _p(0, 'TEMPLATE = lib') _p(0, 'CONFIG += create_prl link_prl') end if prj.kind == "StaticLib" then _p(0, 'CONFIG += staticlib') elseif prj.kind == "SharedLib" then _p(0, 'CONFIG += dll') end _p(0, 'OBJECTS_DIR = $${OUT_PWD}/objs/' .. prj.name) -- List the build configurations, and the settings for each for cfg in premake.eachconfig(prj) do if cfg.name:lower() == "debug" then _p(0, 'CONFIG(debug) {') elseif cfg.name:lower() == "release" then _p(0, 'CONFIG(!debug|release) {') else end if cfg.flags.Qt then _p(1, 'greaterThan(QT_MAJOR_VERSION, 4): QT += widgets') else _p(1, 'CONFIG -= qt') _p(1, 'QT = ') _p('') end if cfg.flags.CPP11 then _p(1, 'CONFIG += c++11') _p('') end _p(1, 'TARGET = %s', cfg.buildtarget.basename) _p(1, '') if #cfg.qtmodules > 0 then _p(1, 'QT += \\', v) for _,v in ipairs(cfg.qtmodules) do _p(2, '%s \\', v) end _p(1, '') end if next(cfg.defines) ~= nil then _p(1, 'DEFINES += \\', v) for _,v in ipairs(cfg.defines) do _p(2, '%s \\', v) end _p(1, '') end if next(cfg.includedirs) ~= nil then _p(1, 'INCLUDEPATH += \\', v) for _,v in ipairs(cfg.includedirs) do _p(2, '%s \\', v) end _p(1, '') end src_files = {} objc_src_files = {} header_files = {} ui_files = {} for _,v in ipairs(cfg.files) do ext = path.getextension(v):lower() if path.iscppfile(v) then if ext == '.m' or ext == '.mm' then table.insert(objc_src_files, v) else table.insert(src_files, v) end end if path.iscppheader(v) then table.insert(header_files, v) end if ext == '.ui' then table.insert(ui_files, v) end end if next(ui_files) ~= nil then _p(1, 'FORMS += \\', v) for _,v in ipairs(ui_files) do _p(2, '%s \\', v) end _p(1, '') end if next(src_files) ~= nil then _p(1, 'SOURCES += \\', v) for _,v in ipairs(src_files) do _p(2, '%s \\', v) end _p(1, '') end if next(objc_src_files) ~= nil then _p(1, 'OBJECTIVE_SOURCES += \\', v) for _,v in ipairs(src_files) do _p(2, '%s \\', v) end _p(1, '') end if next(header_files) ~= nil then _p(1, 'HEADERS += \\', v) for _,v in ipairs(header_files) do _p(2, '%s \\', v) end _p(1, '') end local lib_deps = {} local deps = premake.getdependencies(prj) if #deps > 0 then for _, depprj in ipairs(deps) do table.insert(lib_deps, depprj.name) end end if #lib_deps > 0 then for _,v in ipairs(lib_deps) do _p(1, 'PRE_TARGETDEPS += $$OUT_PWD/lib' .. v .. '.a') _p(1, 'win32:CONFIG(release, debug|release): LIBS += -L$$OUT_PWD/release/ -l' .. v) _p(1, 'else:win32:CONFIG(debug, debug|release): LIBS += -L$$OUT_PWD/debug/ -l' .. v) _p(1, 'else:unix: LIBS += -L$$OUT_PWD/ -l' .. v) --INCLUDEPATH += $$PWD/ --DEPENDPATH += $$PWD/ end end -- system libs local links = premake.getlinks(cfg, "system", "name") if #links > 0 then for _,v in ipairs(links) do ext = path.getextension(v) if ext == '.framework' then _p(1, 'LIBS += -framework ' .. path.getbasename(v)) else _p(1, 'LIBS += -l' .. path.getbasename(v)) end end end if #cfg.prebuildcommands > 0 then _p(1, 'prebuild.target = prebuild.tmp') _p(1, 'prebuild.commands = ' .. table.concat(cfg.prebuildcommands,';')) _p(1, 'QMAKE_EXTRA_TARGETS += prebuild') _p(1, 'PRE_TARGETDEPS += prebuild.tmp') end if #cfg.prelinkcommands > 0 then _p(1, 'QMAKE_PRE_LINK += ' .. table.concat(cfg.prelinkcommands,';')) end if #cfg.postbuildcommands > 0 then _p(1, 'QMAKE_POST_LINK += ' .. table.concat(cfg.postbuildcommands,';')) end _p(0, '}') end end
-- qmake_project.lua -- Generates .pri projects function premake.qmake.project(prj) if prj.kind == "WindowedApp" then _p(0, 'TEMPLATE = app') elseif prj.kind == "ConsoleApp" then _p(0, 'TEMPLATE = app') _p(0, 'CONFIG += console') _p(0, 'CONFIG -= app_bundle') elseif prj.kind == "StaticLib" or prj.kind == "SharedLib" then _p(0, 'TEMPLATE = lib') _p(0, 'CONFIG += create_prl link_prl') end if prj.kind == "StaticLib" then _p(0, 'CONFIG += staticlib') elseif prj.kind == "SharedLib" then _p(0, 'CONFIG += dll') end _p(0, 'OBJECTS_DIR = $${OUT_PWD}/objs/' .. prj.name) -- List the build configurations, and the settings for each for cfg in premake.eachconfig(prj) do if cfg.name:lower() == "debug" then _p(0, 'CONFIG(debug, debug|release): {') elseif cfg.name:lower() == "release" then _p(0, 'else: {') else end if cfg.flags.Qt then _p(1, 'greaterThan(QT_MAJOR_VERSION, 4): QT += widgets') else _p(1, 'CONFIG -= qt') _p(1, 'QT = ') _p('') end if cfg.flags.CPP11 then _p(1, 'CONFIG += c++11') _p('') end _p(1, 'TARGET = %s', cfg.buildtarget.basename) _p(1, '') if #cfg.qtmodules > 0 then _p(1, 'QT += \\', v) for _,v in ipairs(cfg.qtmodules) do _p(2, '%s \\', v) end _p(1, '') end if next(cfg.defines) ~= nil then _p(1, 'DEFINES += \\', v) for _,v in ipairs(cfg.defines) do _p(2, '%s \\', v) end _p(1, '') end if next(cfg.includedirs) ~= nil then _p(1, 'INCLUDEPATH += \\', v) for _,v in ipairs(cfg.includedirs) do _p(2, '%s \\', v) end _p(1, '') end src_files = {} objc_src_files = {} header_files = {} ui_files = {} for _,v in ipairs(cfg.files) do ext = path.getextension(v):lower() if path.iscppfile(v) then if ext == '.m' or ext == '.mm' then table.insert(objc_src_files, v) else table.insert(src_files, v) end end if path.iscppheader(v) then table.insert(header_files, v) end if ext == '.ui' then table.insert(ui_files, v) end end if next(ui_files) ~= nil then _p(1, 'FORMS += \\', v) for _,v in ipairs(ui_files) do _p(2, '%s \\', v) end _p(1, '') end if next(src_files) ~= nil then _p(1, 'SOURCES += \\', v) for _,v in ipairs(src_files) do _p(2, '%s \\', v) end _p(1, '') end if next(objc_src_files) ~= nil then _p(1, 'OBJECTIVE_SOURCES += \\', v) for _,v in ipairs(src_files) do _p(2, '%s \\', v) end _p(1, '') end if next(header_files) ~= nil then _p(1, 'HEADERS += \\', v) for _,v in ipairs(header_files) do _p(2, '%s \\', v) end _p(1, '') end local lib_deps = {} local deps = premake.getdependencies(prj) if #deps > 0 then for _, depprj in ipairs(deps) do table.insert(lib_deps, depprj.name) end end if #lib_deps > 0 then for _,v in ipairs(lib_deps) do _p(1, 'PRE_TARGETDEPS += $$OUT_PWD/lib' .. v .. '.a') _p(1, 'win32:CONFIG(release, debug|release): LIBS += -L$$OUT_PWD/release/ -l' .. v) _p(1, 'else:win32:CONFIG(debug, debug|release): LIBS += -L$$OUT_PWD/debug/ -l' .. v) _p(1, 'else:unix: LIBS += -L$$OUT_PWD/ -l' .. v) --INCLUDEPATH += $$PWD/ --DEPENDPATH += $$PWD/ end end -- system libs local links = premake.getlinks(cfg, "system", "name") if #links > 0 then for _,v in ipairs(links) do ext = path.getextension(v) if ext == '.framework' then _p(1, 'LIBS += -framework ' .. path.getbasename(v)) else _p(1, 'LIBS += -l' .. path.getbasename(v)) end end end if #cfg.prebuildcommands > 0 then _p(1, 'prebuild.target = prebuild.tmp') _p(1, 'prebuild.commands = ' .. table.concat(cfg.prebuildcommands,';')) _p(1, 'QMAKE_EXTRA_TARGETS += prebuild') _p(1, 'PRE_TARGETDEPS += prebuild.tmp') end if #cfg.prelinkcommands > 0 then _p(1, 'QMAKE_PRE_LINK += ' .. table.concat(cfg.prelinkcommands,';')) end if #cfg.postbuildcommands > 0 then _p(1, 'QMAKE_POST_LINK += ' .. table.concat(cfg.postbuildcommands,';')) end _p(0, '}') end end
Fix debug/release config.
Fix debug/release config.
Lua
bsd-3-clause
soundsrc/premake-stable,soundsrc/premake-stable,soundsrc/premake-stable,soundsrc/premake-stable
210526b56825b26614f052de77e094c97f1bf274
tests/test-misc.lua
tests/test-misc.lua
return require('lib/tap')(function (test) test("uv.guess_handle", function (print, p, expect, uv) local types = { [0] = assert(uv.guess_handle(0)), assert(uv.guess_handle(1)), assert(uv.guess_handle(2)), } p("stdio fd types", types) end) test("uv.version and uv.version_string", function (print, p, expect, uv) local version = assert(uv.version()) local version_string = assert(uv.version_string()) p{version=version, version_string=version_string} assert(type(version) == "number") assert(type(version_string) == "string") end) test("memory size", function (print, p, expect, uv) local rss = uv.resident_set_memory() local total = uv.get_total_memory() local constrained = nil if uv.get_constrained_memory then constrained = uv.get_constrained_memory() end local free = uv.get_free_memory() p{rss=rss,total=total,free=free, constrained=constrained} assert(rss < total) end) test("uv.uptime", function (print, p, expect, uv) local uptime = assert(uv.uptime()) p{uptime=uptime} end) test("uv.getrusage", function (print, p, expect, uv) local rusage = assert(uv.getrusage()) p(rusage) end) test("uv.cpu_info", function (print, p, expect, uv) local info = assert(uv.cpu_info()) p(info) end) test("uv.interface_addresses", function (print, p, expect, uv) local addresses = assert(uv.interface_addresses()) for name, info in pairs(addresses) do p(name, addresses[name]) end end) test("uv.loadavg", function (print, p, expect, uv) local avg = {assert(uv.loadavg())} p(avg) assert(#avg == 3) end) test("uv.exepath", function (print, p, expect, uv) local path = assert(uv.exepath()) p(path) end) test("uv.os_homedir", function (print, p, expect, uv) local path = assert(uv.os_homedir()) p(path) end) test("uv.os_tmpdir", function (print, p, expect, uv) local path = assert(uv.os_tmpdir()) p(path) end) test("uv.os_get_passwd", function (print, p, expect, uv) local passwd = assert(uv.os_get_passwd()) p(passwd) end) test("uv.cwd and uv.chdir", function (print, p, expect, uv) local old = assert(uv.cwd()) p(old) assert(uv.chdir("/")) local cwd = assert(uv.cwd()) p(cwd) assert(cwd ~= old) assert(uv.chdir(old)) end) test("uv.hrtime", function (print, p, expect, uv) local time = assert(uv.hrtime()) p(time) end) test("uv.getpid", function (print, p, expect, uv) assert(uv.getpid()) end) test("uv.os_uname", function(print, p, expect, uv) local version = 0x10000 + 25*0x100 + 0 if uv.version() >= version then local uname = assert(uv.os_uname()) p(uname) else print("skipped") end end) test("uv.gettimeofday", function(print, p, expect, uv) local version = 0x10000 + 28*0x100 + 0 if uv.version() >= version then local now = os.time() local sec, usec = assert(uv.gettimeofday()) print(' os.time', now) print('uv.gettimeofday',string.format("%f",sec+usec/10^9)) assert(type(sec)=='number') assert(type(usec)=='number') else print("skipped") end end) test("uv.os_environ", function(print, p, expect, uv) local name, name2 = "LUV_TEST_FOO", "LUV_TEST_FOO2"; local value, value2 = "123456789", "" assert(uv.os_setenv(name, value)) assert(uv.os_setenv(name2, value2)) local env = uv.os_environ(); assert(env[name]==value) assert(env[name2]==value2) end) test("uv.sleep", function(print, p, expect, uv) local val = 1000 local begin = uv.now() uv.sleep(val) uv.update_time() local now = uv.now() assert(now-begin >= val) end) test("uv.random async", function(print, p, expect, uv) local len = 256 assert(uv.random(len, {}, expect(function(err, randomBytes) assert(not err) assert(#randomBytes == len) -- this matches the LibUV test -- it can theoretically fail but its very unlikely assert(randomBytes ~= string.rep("\0", len)) end))) end) test("uv.random sync", function(print, p, expect, uv) local len = 256 local randomBytes = assert(uv.random(len)) assert(#randomBytes == len) -- this matches the LibUV test -- it can theoretically fail but its very unlikely assert(randomBytes ~= string.rep("\0", len)) end) test("uv.random errors", function(print, p, expect, uv) -- invalid flag local _, err = uv.random(0, -1) assert(err:match("^EINVAL")) -- invalid len _, err = uv.random(-1) assert(err:match("^E2BIG")) end) end)
return require('lib/tap')(function (test) test("uv.guess_handle", function (print, p, expect, uv) local types = { [0] = assert(uv.guess_handle(0)), assert(uv.guess_handle(1)), assert(uv.guess_handle(2)), } p("stdio fd types", types) end) test("uv.version and uv.version_string", function (print, p, expect, uv) local version = assert(uv.version()) local version_string = assert(uv.version_string()) p{version=version, version_string=version_string} assert(type(version) == "number") assert(type(version_string) == "string") end) test("memory size", function (print, p, expect, uv) local rss = uv.resident_set_memory() local total = uv.get_total_memory() local constrained = nil if uv.get_constrained_memory then constrained = uv.get_constrained_memory() end local free = uv.get_free_memory() p{rss=rss,total=total,free=free, constrained=constrained} assert(rss < total) end) test("uv.uptime", function (print, p, expect, uv) local uptime = assert(uv.uptime()) p{uptime=uptime} end) test("uv.getrusage", function (print, p, expect, uv) local rusage = assert(uv.getrusage()) p(rusage) end) test("uv.cpu_info", function (print, p, expect, uv) local info = assert(uv.cpu_info()) p(info) end) test("uv.interface_addresses", function (print, p, expect, uv) local addresses = assert(uv.interface_addresses()) for name, info in pairs(addresses) do p(name, addresses[name]) end end) test("uv.loadavg", function (print, p, expect, uv) local avg = {assert(uv.loadavg())} p(avg) assert(#avg == 3) end) test("uv.exepath", function (print, p, expect, uv) local path = assert(uv.exepath()) p(path) end) test("uv.os_homedir", function (print, p, expect, uv) local version = 0x10000 + 9*0x100 + 0 if uv.version() < version then print("skipped, requires libuv >= 1.9.0") return end local path = assert(uv.os_homedir()) p(path) end) test("uv.os_tmpdir", function (print, p, expect, uv) local version = 0x10000 + 9*0x100 + 0 if uv.version() < version then print("skipped, requires libuv >= 1.9.0") return end local path = assert(uv.os_tmpdir()) p(path) end) test("uv.os_get_passwd", function (print, p, expect, uv) local version = 0x10000 + 9*0x100 + 0 if uv.version() < version then print("skipped, requires libuv >= 1.9.0") return end local passwd = assert(uv.os_get_passwd()) p(passwd) end) test("uv.cwd and uv.chdir", function (print, p, expect, uv) local old = assert(uv.cwd()) p(old) assert(uv.chdir("/")) local cwd = assert(uv.cwd()) p(cwd) assert(cwd ~= old) assert(uv.chdir(old)) end) test("uv.hrtime", function (print, p, expect, uv) local time = assert(uv.hrtime()) p(time) end) test("uv.getpid", function (print, p, expect, uv) assert(uv.getpid()) end) test("uv.os_uname", function(print, p, expect, uv) local version = 0x10000 + 25*0x100 + 0 if uv.version() >= version then local uname = assert(uv.os_uname()) p(uname) else print("skipped") end end) test("uv.gettimeofday", function(print, p, expect, uv) local version = 0x10000 + 28*0x100 + 0 if uv.version() >= version then local now = os.time() local sec, usec = assert(uv.gettimeofday()) print(' os.time', now) print('uv.gettimeofday',string.format("%f",sec+usec/10^9)) assert(type(sec)=='number') assert(type(usec)=='number') else print("skipped") end end) test("uv.os_environ", function(print, p, expect, uv) local version = 0x10000 + 31*0x100 + 0 if uv.version() < version then print("skipped, requires libuv >= 1.31.0") return end local name, name2 = "LUV_TEST_FOO", "LUV_TEST_FOO2"; local value, value2 = "123456789", "" assert(uv.os_setenv(name, value)) assert(uv.os_setenv(name2, value2)) local env = uv.os_environ(); assert(env[name]==value) assert(env[name2]==value2) end) test("uv.sleep", function(print, p, expect, uv) local val = 1000 local begin = uv.now() uv.sleep(val) uv.update_time() local now = uv.now() assert(now-begin >= val) end) test("uv.random async", function(print, p, expect, uv) local version = 0x10000 + 33*0x100 + 0 if uv.version() < version then print("skipped, requires libuv >= 1.33.0") return end local len = 256 assert(uv.random(len, {}, expect(function(err, randomBytes) assert(not err) assert(#randomBytes == len) -- this matches the LibUV test -- it can theoretically fail but its very unlikely assert(randomBytes ~= string.rep("\0", len)) end))) end) test("uv.random sync", function(print, p, expect, uv) local version = 0x10000 + 33*0x100 + 0 if uv.version() < version then print("skipped, requires libuv >= 1.33.0") return end local len = 256 local randomBytes = assert(uv.random(len)) assert(#randomBytes == len) -- this matches the LibUV test -- it can theoretically fail but its very unlikely assert(randomBytes ~= string.rep("\0", len)) end) test("uv.random errors", function(print, p, expect, uv) local version = 0x10000 + 33*0x100 + 0 if uv.version() < version then print("skipped, requires libuv >= 1.33.0") return end -- invalid flag local _, err = uv.random(0, -1) assert(err:match("^EINVAL")) -- invalid len _, err = uv.random(-1) assert(err:match("^E2BIG")) end) end)
Fix test-misc when using older libuv versions
Fix test-misc when using older libuv versions
Lua
apache-2.0
luvit/luv,zhaozg/luv,zhaozg/luv,luvit/luv
ebe6faed483bda4c7aaa17fd8cd00fb7b5fcde63
lux/geom/vec.lua
lux/geom/vec.lua
--[[ -- -- Copyright (c) 2013 Wilson Kazuo Mizutani -- -- This software is provided 'as-is', without any express or implied -- warranty. In no event will the authors be held liable for any damages -- arising from the use of this software. -- -- Permission is granted to anyone to use this software for any purpose, -- including commercial applications, and to alter it and redistribute it -- freely, subject to the following restrictions: -- -- 1. The origin of this software must not be misrepresented; you must not -- claim that you wrote the original software. If you use this software -- in a product, an acknowledgment in the product documentation would be -- appreciated but is not required. -- -- 2. Altered source versions must be plainly marked as such, and must not be -- misrepresented as being the original software. -- -- 3. This notice may not be removed or altered from any source -- distribution. -- --]] module ('lux.geom', package.seeall) require 'lux.object' vec = lux.object.new { __type = "vector", -- Vector coordinates. [1] = 0, [2] = 0, [3] = 0, [4] = 0 } point = vec:new { [4] = 1 } function vec.axis (i) return vec:new { i == 1 and 1 or 0, i == 2 and 1 or 0, i == 3 and 1 or 0, i == 4 and 1 or 0 } end function vec:__tostring () return "("..self[1]..","..self[2]..","..self[3]..","..self[4]..")" end point.__tostring = vec.__tostring function vec:__index (k) if k == "x" then return self[1] end if k == "y" then return self[2] end if k == "z" then return self[3] end if k == "w" then return self[4] end return getmetatable(self)[k] end point.__index = vec.__index function vec:__newindex (k, v) if k == "x" then rawset(self, 1, v) elseif k == "y" then rawset(self, 2, v) elseif k == "z" then rawset(self, 3, v) elseif k == "w" then rawset(self, 4, v) else rawset(self, k, v) end end point.__newindex = vec.__newindex function vec.__add (lhs, rhs) return vec:new { lhs[1] + rhs[1], lhs[2] + rhs[2], lhs[3] + rhs[3], lhs[4] + rhs[4] } end function vec.__sub (lhs, rhs) return vec:new { lhs[1] - rhs[1], lhs[2] - rhs[2], lhs[3] - rhs[3], lhs[4] - rhs[4] } end point.__sub = vec.__sub local function mul_scalar (a, v) return vec:new { a*v[1], a*v[2], a*v[3], a*v[4] } end function vec.__mul (lhs, rhs) if type(lhs) == "number" then return mul_scalar(lhs,rhs) elseif type(rhs) == "number" then return mul_scalar(rhs, lhs) else -- assume both are vec2 return lhs[1]*rhs[1] + lhs[2]*rhs[2] + lhs[3]*rhs[3] + lhs[4]*rhs[4] end end function vec:set (x, y, z, w) self[1] = x or 0 self[2] = y or 0 self[3] = z or 0 self[4] = w or 0 end function vec:add (v) self[1] = self[1] + v[1] self[2] = self[2] + v[2] self[3] = self[3] + v[3] self[4] = self[4] + v[4] end function vec:sub (v) self[1] = self[1] - v[1] self[2] = self[2] - v[2] self[3] = self[3] - v[3] self[4] = self[4] - v[4] end function vec:unpack (n) return unpack(self, n) end
--[[ -- -- Copyright (c) 2013 Wilson Kazuo Mizutani -- -- This software is provided 'as-is', without any express or implied -- warranty. In no event will the authors be held liable for any damages -- arising from the use of this software. -- -- Permission is granted to anyone to use this software for any purpose, -- including commercial applications, and to alter it and redistribute it -- freely, subject to the following restrictions: -- -- 1. The origin of this software must not be misrepresented; you must not -- claim that you wrote the original software. If you use this software -- in a product, an acknowledgment in the product documentation would be -- appreciated but is not required. -- -- 2. Altered source versions must be plainly marked as such, and must not be -- misrepresented as being the original software. -- -- 3. This notice may not be removed or altered from any source -- distribution. -- --]] module ('lux.geom', package.seeall) require 'lux.object' vec = lux.object.new { -- Vector coordinates. 0, 0, 0, 0, -- Internal information. __type = "vector" } point = vec:new { [4] = 1 } function vec.axis (i) return vec:new { i == 1 and 1 or 0, i == 2 and 1 or 0, i == 3 and 1 or 0, i == 4 and 1 or 0 } end function vec:__tostring () return "("..self[1]..","..self[2]..","..self[3]..","..self[4]..")" end point.__tostring = vec.__tostring function vec:__index (k) if k == "x" then return self[1] end if k == "y" then return self[2] end if k == "z" then return self[3] end if k == "w" then return self[4] end return getmetatable(self)[k] end point.__index = vec.__index function vec:__newindex (k, v) if k == "x" then rawset(self, 1, v) elseif k == "y" then rawset(self, 2, v) elseif k == "z" then rawset(self, 3, v) elseif k == "w" then rawset(self, 4, v) else rawset(self, k, v) end end point.__newindex = vec.__newindex function vec.__add (lhs, rhs) return vec:new { lhs[1] + rhs[1], lhs[2] + rhs[2], lhs[3] + rhs[3], lhs[4] + rhs[4] } end function vec.__sub (lhs, rhs) return vec:new { lhs[1] - rhs[1], lhs[2] - rhs[2], lhs[3] - rhs[3], lhs[4] - rhs[4] } end point.__sub = vec.__sub local function mul_scalar (a, v) return vec:new { a*v[1], a*v[2], a*v[3], a*v[4] } end function vec.__mul (lhs, rhs) if type(lhs) == "number" then return mul_scalar(lhs,rhs) elseif type(rhs) == "number" then return mul_scalar(rhs, lhs) else -- assume both are vec2 return lhs[1]*rhs[1] + lhs[2]*rhs[2] + lhs[3]*rhs[3] + lhs[4]*rhs[4] end end function vec:set (x, y, z, w) self[1] = x or 0 self[2] = y or 0 self[3] = z or 0 self[4] = w or 0 end function vec:add (v) self[1] = self[1] + v[1] self[2] = self[2] + v[2] self[3] = self[3] + v[3] self[4] = self[4] + v[4] end function vec:sub (v) self[1] = self[1] - v[1] self[2] = self[2] - v[2] self[3] = self[3] - v[3] self[4] = self[4] - v[4] end function vec:unpack () return self[1], self[2], self[3], self[4] end
[lux.geom] Fixed vec:unpack
[lux.geom] Fixed vec:unpack
Lua
mit
Kazuo256/luxproject
4d68d6218ead8f30d433760d3706a9c261679b19
src/camerastoryutils/src/Client/CameraStoryUtils.lua
src/camerastoryutils/src/Client/CameraStoryUtils.lua
--[=[ Utility functions for hoacekat stories. @class CameraStoryUtils ]=] local require = require(script.Parent.loader).load(script) local RunService = game:GetService("RunService") local TextService = game:GetService("TextService") local InsertServiceUtils = require("InsertServiceUtils") local Promise = require("Promise") local Math = require("Math") local CameraStoryUtils = {} --[=[ Reflects the camera state to the original camera @param maid Maid @param topCamera Camera @return Camera ]=] function CameraStoryUtils.reflectCamera(maid, topCamera) local camera = Instance.new("Camera") camera.Name = "ReflectedCamera" maid:GiveTask(camera) local function update() camera.FieldOfView = topCamera.FieldOfView camera.CFrame = topCamera.CFrame end maid:GiveTask(topCamera:GetPropertyChangedSignal("CFrame"):Connect(update)) maid:GiveTask(topCamera:GetPropertyChangedSignal("FieldOfView"):Connect(update)) update() return camera end --[=[ Sets up a viewport frame @param maid Maid @param target GuiBase @return ViewportFrame ]=] function CameraStoryUtils.setupViewportFrame(maid, target) local viewportFrame = Instance.new("ViewportFrame") viewportFrame.ZIndex = 0 viewportFrame.BorderSizePixel = 0 viewportFrame.BackgroundColor3 = Color3.new(0.9, 0.9, 0.85) viewportFrame.Size = UDim2.new(1, 0, 1, 0) maid:GiveTask(viewportFrame) local reflectedCamera = CameraStoryUtils.reflectCamera(maid, workspace.CurrentCamera) reflectedCamera.Parent = viewportFrame viewportFrame.CurrentCamera = reflectedCamera viewportFrame.Parent = target return viewportFrame end --[=[ REturns a promise that resolves to a crate in front of the camera. @param maid Maid @param viewportFrame ViewportFrame @param properties { [string}: any } @return Promise<Instance> ]=] function CameraStoryUtils.promiseCrate(maid, viewportFrame, properties) return maid:GivePromise(InsertServiceUtils.promiseAsset(182451181)):Then(function(model) maid:GiveTask(model) local crate = model:GetChildren()[1] if not crate then return Promise.rejected() end if properties then for _, item in pairs(crate:GetDescendants()) do if item:IsA("BasePart") then for property, value in pairs(properties) do item[property] = value end end end end crate.Parent = viewportFrame local camera = viewportFrame.CurrentCamera if camera then local cameraCFrame = camera.CFrame local cframe = CFrame.new(cameraCFrame.Position + cameraCFrame.lookVector*25) crate:SetPrimaryPartCFrame(cframe) end return Promise.resolved(crate) end) end --[=[ Retrieves the interpolation @param maid Maid @param viewportFrame ViewportFrame @param low number @param high number @param period number @param toCFrame CFrame @return (interpolate: function, color: Color3, label: string?, labelOffset: Vector2?) -> () ]=] function CameraStoryUtils.getInterpolationFactory(maid, viewportFrame, low, high, period, toCFrame) assert(maid, "Bad maid") assert(viewportFrame, "Bad viewportFrame") assert(type(low) == "number", "Bad low") assert(type(high) == "number", "Bad high") assert(type(period) == "number", "Bad period") assert(type(toCFrame) == "function", "Bad toCFrame") return function(interpolate, color, labelText, labelOffset) assert(type(interpolate) == "function", "Bad interpolate") assert(typeof(color) == "Color3", "Bad color") labelOffset = labelOffset or Vector2.new(0, 0) maid:GivePromise(CameraStoryUtils.promiseCrate(maid, viewportFrame, { Color = color; Transparency = 0.5 })) :Then(function(crate) local label if labelText then local h, s, _ = Color3.toHSV(color) label = Instance.new("TextLabel") label.AnchorPoint = Vector2.new(0.5, 0.5) label.Text = labelText label.BorderSizePixel = 0 label.BackgroundTransparency = 0.5 label.BackgroundColor3 = Color3.fromHSV(h, math.clamp(s/(s+0.1), 0, 1), 0.25) label.TextColor3 = Color3.new(1, 1, 1) label.Font = Enum.Font.FredokaOne label.TextSize = 15 label.Parent = viewportFrame label.Visible = false maid:GiveTask(label) local size = TextService:GetTextSize(labelText, label.TextSize, label.Font, Vector2.new(1e6, 1e6)) label.Size = UDim2.new(0, size.x + 20, 0, 20) local uiCorner = Instance.new("UICorner") uiCorner.CornerRadius = UDim.new(0.5, 0) uiCorner.Parent = label maid:GiveTask(label) end -- avoid floating point numbers from :SetPrimaryPartCFrame local primaryPart, primaryCFrame local relCFrame = {} for _, part in pairs(crate:GetDescendants()) do if part:IsA("BasePart") then if primaryPart then relCFrame[part] = primaryCFrame:toObjectSpace(part.CFrame) else primaryPart = part primaryCFrame = part.CFrame relCFrame[part] = CFrame.new() end end end maid:GiveTask(RunService.RenderStepped:Connect(function() local t = (os.clock()/period % 2/period)*period if t >= 1 then t = 1 - (t % 1) end t = Math.map(t, 0, 1, low, high) t = math.clamp(t, low, high) local cframe = toCFrame(interpolate(t)) if label then local camera = viewportFrame.CurrentCamera local pos = camera:WorldToViewportPoint(cframe.p) local viewportSize = viewportFrame.AbsoluteSize local aspectRatio = viewportSize.x/viewportSize.y if pos.z > 0 then label.Position = UDim2.new((pos.x - 0.5)/aspectRatio + 0.5, labelOffset.x, pos.y, 0 + labelOffset.y) label.Visible = true else label.Visible = false end end for part, rel in pairs(relCFrame) do part.CFrame = cframe:toWorldSpace(rel) end end)) end) end end return CameraStoryUtils
--[=[ Utility functions for hoacekat stories. @class CameraStoryUtils ]=] local require = require(script.Parent.loader).load(script) local RunService = game:GetService("RunService") local TextService = game:GetService("TextService") local InsertServiceUtils = require("InsertServiceUtils") local Promise = require("Promise") local Math = require("Math") local CameraStoryUtils = {} --[=[ Reflects the camera state to the original camera @param maid Maid @param topCamera Camera @return Camera ]=] function CameraStoryUtils.reflectCamera(maid, topCamera) local camera = Instance.new("Camera") camera.Name = "ReflectedCamera" maid:GiveTask(camera) local function update() camera.FieldOfView = topCamera.FieldOfView camera.CFrame = topCamera.CFrame end maid:GiveTask(topCamera:GetPropertyChangedSignal("CFrame"):Connect(update)) maid:GiveTask(topCamera:GetPropertyChangedSignal("FieldOfView"):Connect(update)) update() return camera end --[=[ Sets up a viewport frame @param maid Maid @param target GuiBase @return ViewportFrame ]=] function CameraStoryUtils.setupViewportFrame(maid, target) local viewportFrame = Instance.new("ViewportFrame") viewportFrame.ZIndex = 0 viewportFrame.BorderSizePixel = 0 viewportFrame.BackgroundColor3 = Color3.new(0.9, 0.9, 0.85) viewportFrame.Size = UDim2.new(1, 0, 1, 0) maid:GiveTask(viewportFrame) local reflectedCamera = CameraStoryUtils.reflectCamera(maid, workspace.CurrentCamera) reflectedCamera.Parent = viewportFrame viewportFrame.CurrentCamera = reflectedCamera viewportFrame.Parent = target return viewportFrame end --[=[ REturns a promise that resolves to a crate in front of the camera. @param maid Maid @param viewportFrame ViewportFrame @param properties { [string}: any } @return Promise<Instance> ]=] function CameraStoryUtils.promiseCrate(maid, viewportFrame, properties) return maid:GivePromise(InsertServiceUtils.promiseAsset(182451181)):Then(function(model) maid:GiveTask(model) local crate = model:GetChildren()[1] if not crate then return Promise.rejected() end if properties then for _, item in pairs(crate:GetDescendants()) do if item:IsA("BasePart") then for property, value in pairs(properties) do item[property] = value end end end end if viewportFrame then crate.Parent = viewportFrame local camera = viewportFrame.CurrentCamera if camera then local cameraCFrame = camera.CFrame local cframe = CFrame.new(cameraCFrame.Position + cameraCFrame.lookVector*25) crate:SetPrimaryPartCFrame(cframe) end end return Promise.resolved(crate) end) end --[=[ Retrieves the interpolation @param maid Maid @param viewportFrame ViewportFrame @param low number @param high number @param period number @param toCFrame CFrame @return (interpolate: function, color: Color3, label: string?, labelOffset: Vector2?) -> () ]=] function CameraStoryUtils.getInterpolationFactory(maid, viewportFrame, low, high, period, toCFrame) assert(maid, "Bad maid") assert(viewportFrame, "Bad viewportFrame") assert(type(low) == "number", "Bad low") assert(type(high) == "number", "Bad high") assert(type(period) == "number", "Bad period") assert(type(toCFrame) == "function", "Bad toCFrame") return function(interpolate, color, labelText, labelOffset) assert(type(interpolate) == "function", "Bad interpolate") assert(typeof(color) == "Color3", "Bad color") labelOffset = labelOffset or Vector2.new(0, 0) maid:GivePromise(CameraStoryUtils.promiseCrate(maid, viewportFrame, { Color = color; Transparency = 0.5 })) :Then(function(crate) local label if labelText then local h, s, _ = Color3.toHSV(color) label = Instance.new("TextLabel") label.AnchorPoint = Vector2.new(0.5, 0.5) label.Text = labelText label.BorderSizePixel = 0 label.BackgroundTransparency = 0.5 label.BackgroundColor3 = Color3.fromHSV(h, math.clamp(s/(s+0.1), 0, 1), 0.25) label.TextColor3 = Color3.new(1, 1, 1) label.Font = Enum.Font.FredokaOne label.TextSize = 15 label.Parent = viewportFrame label.Visible = false maid:GiveTask(label) local size = TextService:GetTextSize(labelText, label.TextSize, label.Font, Vector2.new(1e6, 1e6)) label.Size = UDim2.new(0, size.x + 20, 0, 20) local uiCorner = Instance.new("UICorner") uiCorner.CornerRadius = UDim.new(0.5, 0) uiCorner.Parent = label maid:GiveTask(label) end -- avoid floating point numbers from :SetPrimaryPartCFrame local primaryPart, primaryCFrame local relCFrame = {} for _, part in pairs(crate:GetDescendants()) do if part:IsA("BasePart") then if primaryPart then relCFrame[part] = primaryCFrame:toObjectSpace(part.CFrame) else primaryPart = part primaryCFrame = part.CFrame relCFrame[part] = CFrame.new() end end end maid:GiveTask(RunService.RenderStepped:Connect(function() local t = (os.clock()/period % 2/period)*period if t >= 1 then t = 1 - (t % 1) end t = Math.map(t, 0, 1, low, high) t = math.clamp(t, low, high) local cframe = toCFrame(interpolate(t)) if label then local camera = viewportFrame.CurrentCamera local pos = camera:WorldToViewportPoint(cframe.p) local viewportSize = viewportFrame.AbsoluteSize local aspectRatio = viewportSize.x/viewportSize.y if pos.z > 0 then label.Position = UDim2.new((pos.x - 0.5)/aspectRatio + 0.5, labelOffset.x, pos.y, 0 + labelOffset.y) label.Visible = true else label.Visible = false end end for part, rel in pairs(relCFrame) do part.CFrame = cframe:toWorldSpace(rel) end end)) end) end end return CameraStoryUtils
fix: Make viewport optional
fix: Make viewport optional
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
11397747ac43bdddb222b691a61801353250d86a
applications/luci-initmgr/luasrc/controller/init.lua
applications/luci-initmgr/luasrc/controller/init.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$ ]]-- module("luci.controller.init", package.seeall) function index() if not luci.fs.isfile("/etc/rc.common") then return end local page = entry({"admin", "system", "init"}, form("init/init"), luci.i18n.translate("initmgr", "Init Scripts")) page.i18n = "initmgr" page.dependent = true end
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Copyright 2008 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.controller.init", package.seeall) function index() if not luci.fs.isfile("/etc/rc.common") then return end require("luci.i18n") luci.i18n.loadc("initmgr") entry( {"admin", "system", "init"}, form("init/init"), luci.i18n.translate("initmgr", "Init Scripts") ).i18n = "initmgr" end
* luci/app/initmgr: fix translation issue in menu entry
* luci/app/initmgr: fix translation issue in menu entry
Lua
apache-2.0
8devices/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci
04377ca8449ae84d8e4f19a52dc2e37241c6ccaa
lua/entities/gmod_wire_colorer.lua
lua/entities/gmod_wire_colorer.lua
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Colorer" ENT.RenderGroup = RENDERGROUP_BOTH ENT.WireDebugName = "Colorer" function ENT:SetupDataTables() self:NetworkVar( "Float", 0, "BeamLength" ) end if CLIENT then return end -- No more client function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self.Inputs = WireLib.CreateSpecialInputs(self, { "Fire", "R", "G", "B", "A", "RGB" }, {"NORMAL", "NORMAL", "NORMAL", "NORMAL", "NORMAL", "VECTOR"}) self.Outputs = Wire_CreateOutputs(self, {"Out"}) self.InColor = Color(255, 255, 255, 255) self:SetBeamLength(2048) end function ENT:Setup(outColor,Range) if(outColor)then self.outColor = outColor local onames = {} table.insert(onames, "R") table.insert(onames, "G") table.insert(onames, "B") table.insert(onames, "A") Wire_AdjustOutputs(self, onames) end if Range then self:SetBeamLength(Range) end self:ShowOutput() end function ENT:TriggerInput(iname, value) if iname == "Fire" and value ~= 0 then local vStart = self:GetPos() local vForward = self:GetUp() local trace = util.TraceLine { start = vStart, endpos = vStart + (vForward * self:GetBeamLength()), filter = { self } } if not IsValid(trace.Entity) then return end if not hook.Run( "CanTool", self:GetOwner(), trace, "colour" ) then return end if trace.Entity:IsPlayer() then trace.Entity:SetColor(Color(self.InColor.r, self.InColor.g, self.InColor.b, 255)) else trace.Entity:SetColor(Color(self.InColor.r, self.InColor.g, self.InColor.b, self.InColor.a)) trace.Entity:SetRenderMode(self.InColor.a == 255 and RENDERMODE_NORMAL or RENDERMODE_TRANSALPHA ) end elseif iname == "R" then self.InColor.r = math.Clamp(value, 0, 255) elseif iname == "G" then self.InColor.g = math.Clamp(value, 0, 255) elseif iname == "B" then self.InColor.b = math.Clamp(value, 0, 255) elseif iname == "A" then self.InColor.a = math.Clamp(value, 0, 255) elseif iname == "RGB" then self.InColor = Color( value[1], value[2], value[3], self.InColor.a ) end end function ENT:ShowOutput() local text if self.Outputs["R"] then text = "Color = " .. math.Round(self.Outputs["R"].Value*1000)/1000 .. ", " .. math.Round(self.Outputs["G"].Value*1000)/1000 .. ", " .. math.Round(self.Outputs["B"].Value*1000)/1000 .. ", " .. math.Round(self.Outputs["A"].Value*1000)/1000 end self:SetOverlayText( text ) end function ENT:Think() self.BaseClass.Think(self) if self.Outputs["R"]then local vStart = self:GetPos() local vForward = self:GetUp() local trace = {} trace.start = vStart trace.endpos = vStart + (vForward * self:GetBeamLength()) trace.filter = { self } local trace = util.TraceLine( trace ) if !IsValid( trace.Entity ) then return end local c = trace.Entity:GetColor() Wire_TriggerOutput(self,"R", c.r) Wire_TriggerOutput(self,"G", c.g) Wire_TriggerOutput(self,"B", c.b) Wire_TriggerOutput(self,"A", c.a) self:ShowOutput() end self:NextThink(CurTime() + 0.05) return true end duplicator.RegisterEntityClass("gmod_wire_colorer", WireLib.MakeWireEnt, "Data", "outColor", "Range")
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Colorer" ENT.RenderGroup = RENDERGROUP_BOTH ENT.WireDebugName = "Colorer" function ENT:SetupDataTables() self:NetworkVar( "Float", 0, "BeamLength" ) end if CLIENT then local color_box_size = 64 function ENT:GetWorldTipBodySize() -- "Input color:" text local w_total,h_total = surface.GetTextSize( "Input color:\n255,255,255,255" ) -- Color box width w_total = math.max(w_total,color_box_size) -- "Target color:" text local w,h = surface.GetTextSize( "Target color:\n255,255,255,255" ) w_total = w_total + 18 + math.max(w,color_box_size) h_total = math.max(h_total, h) -- Color box height h_total = h_total + 18 + color_box_size + 18/2 return w_total, h_total end local white = Color(255,255,255,255) local black = Color(0,0,0,255) local function drawColorBox( color, x, y ) surface.SetDrawColor( color ) surface.DrawRect( x, y, color_box_size, color_box_size ) local size = color_box_size surface.SetDrawColor( black ) surface.DrawLine( x, y, x + size, y ) surface.DrawLine( x + size, y, x + size, y + size ) surface.DrawLine( x + size, y + size, x, y + size ) surface.DrawLine( x, y + size, x, y ) end function ENT:DrawWorldTipBody( pos ) -- get colors local data = self:GetOverlayData() local inColor = Color(data.r or 255,data.g or 255,data.b or 255,data.a or 255) local trace = util.TraceLine( { start = self:GetPos(), endpos = self:GetPos() + self:GetUp() * self:GetBeamLength(), filter = {self} } ) local targetColor = Color(255,255,255,255) if IsValid( trace.Entity ) then targetColor = trace.Entity:GetColor() end -- "Input color" text local color_text = string.format("Input color:\n%d,%d,%d,%d",inColor.r,inColor.g,inColor.b,inColor.a) local w,h = surface.GetTextSize( color_text ) draw.DrawText( color_text, "GModWorldtip", pos.min.x + pos.edgesize + w/2, pos.min.y + pos.edgesize, white, TEXT_ALIGN_CENTER ) -- "Target color" text local color_text = string.format("Input color:\n%d,%d,%d,%d",targetColor.r,targetColor.g,targetColor.b,targetColor.a) local w2,h2 = surface.GetTextSize( color_text ) draw.DrawText( color_text, "GModWorldtip", pos.max.x - w/2 - pos.edgesize, pos.min.y + pos.edgesize, white, TEXT_ALIGN_CENTER ) local h = math.max(h,h2) -- Input color box local x = pos.min.x + pos.edgesize + w/2 - color_box_size/2 local y = pos.min.y + pos.edgesize * 1.5 + h drawColorBox( inColor, x, y ) -- Target color box local x = pos.max.x - pos.edgesize - w/2 - color_box_size/2 local y = pos.min.y + pos.edgesize * 1.5 + h drawColorBox( targetColor, x, y ) end return -- No more client end function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self.Inputs = WireLib.CreateSpecialInputs(self, { "Fire", "R", "G", "B", "A", "RGB" }, {"NORMAL", "NORMAL", "NORMAL", "NORMAL", "NORMAL", "VECTOR"}) self.Outputs = WireLib.CreateOutputs( self, {"Out"} ) self.InColor = Color(255, 255, 255, 255) self:SetBeamLength(2048) self:ShowOutput() end function ENT:Setup(outColor,Range) if(outColor)then self.outColor = outColor WireLib.AdjustOutputs(self, {"R","G","B","A"}) else WireLib.AdjustOutputs(self, {"Out"}) end if Range then self:SetBeamLength(Range) end self:ShowOutput() end function ENT:TriggerInput(iname, value) if iname == "Fire" and value ~= 0 then local vStart = self:GetPos() local vForward = self:GetUp() local trace = util.TraceLine { start = vStart, endpos = vStart + (vForward * self:GetBeamLength()), filter = { self } } if not IsValid(trace.Entity) then return end if not hook.Run( "CanTool", self:GetOwner(), trace, "colour" ) then return end if trace.Entity:IsPlayer() then trace.Entity:SetColor(Color(self.InColor.r, self.InColor.g, self.InColor.b, 255)) else trace.Entity:SetColor(Color(self.InColor.r, self.InColor.g, self.InColor.b, self.InColor.a)) trace.Entity:SetRenderMode(self.InColor.a == 255 and RENDERMODE_NORMAL or RENDERMODE_TRANSALPHA ) end elseif iname == "R" then self.InColor.r = math.Clamp(value, 0, 255) self:ShowOutput() elseif iname == "G" then self.InColor.g = math.Clamp(value, 0, 255) self:ShowOutput() elseif iname == "B" then self.InColor.b = math.Clamp(value, 0, 255) self:ShowOutput() elseif iname == "A" then self.InColor.a = math.Clamp(value, 0, 255) self:ShowOutput() elseif iname == "RGB" then self.InColor = Color( value.x, value.y, value.z, self.InColor.a ) self:ShowOutput() end end function ENT:ShowOutput() self:SetOverlayData( { r = self.InColor.r, g = self.InColor.g, b = self.InColor.b, a = self.InColor.a } ) end function ENT:Think() self.BaseClass.Think(self) if self.outColor then local vStart = self:GetPos() local vForward = self:GetUp() local trace = {} trace.start = vStart trace.endpos = vStart + (vForward * self:GetBeamLength()) trace.filter = { self } local trace = util.TraceLine( trace ) if !IsValid( trace.Entity ) then WireLib.TriggerOutput( self, "R", 255 ) WireLib.TriggerOutput( self, "G", 255 ) WireLib.TriggerOutput( self, "B", 255 ) WireLib.TriggerOutput( self, "A", 255 ) else local c = trace.Entity:GetColor() WireLib.TriggerOutput( self, "R", c.r ) WireLib.TriggerOutput( self, "G", c.g ) WireLib.TriggerOutput( self, "B", c.b ) WireLib.TriggerOutput( self, "A", c.a ) end end self:NextThink(CurTime() + 0.1) return true end duplicator.RegisterEntityClass("gmod_wire_colorer", WireLib.MakeWireEnt, "Data", "outColor", "Range")
Added custom overlay to wire colorer
Added custom overlay to wire colorer Custom overlays, woop Also cleaned up the code and fixed a few bugs which, strangely, no one has noticed before (the vector input didn't work, the color output would stop updating if you aimed it at an invalid entity, etc) The old timers deserve some love, too
Lua
apache-2.0
garrysmodlua/wire,immibis/wiremod,mitterdoo/wire,NezzKryptic/Wire,notcake/wire,bigdogmat/wire,plinkopenguin/wiremod,dvdvideo1234/wire,thegrb93/wire,rafradek/wire,Grocel/wire,Python1320/wire,mms92/wire,sammyt291/wire,wiremod/wire,CaptainPRICE/wire
dec0a649e58a89d1266b8135d1343de5bc13f92a
src/core/memory.lua
src/core/memory.lua
module(...,package.seeall) -- For more information about huge pages checkout: -- * HugeTLB - Large Page Support in the Linux kernel -- http://linuxgazette.net/155/krishnakumar.html) -- * linux/Documentation/vm/hugetlbpage.txt -- https://www.kernel.org/doc/Documentation/vm/hugetlbpage.txt) local ffi = require("ffi") local C = ffi.C local syscall = require("syscall") local lib = require("core.lib") require("core.memory_h") --- ### Serve small allocations from hugepage "chunks" -- List of all allocated huge pages: {pointer, physical, size, used} -- The last element is used to service new DMA allocations. chunks = {} -- Lowest and highest addresses of valid DMA memory. -- (Useful information for creating memory maps.) dma_min_addr, dma_max_addr = false, false -- Allocate DMA-friendly memory. -- Return virtual memory pointer, physical address, and actual size. function dma_alloc (bytes) assert(bytes <= huge_page_size) bytes = lib.align(bytes, 128) if #chunks == 0 or bytes + chunks[#chunks].used > chunks[#chunks].size then allocate_next_chunk() end local chunk = chunks[#chunks] local where = chunk.used chunk.used = chunk.used + bytes return chunk.pointer + where, chunk.physical + where, bytes end -- Add a new chunk. function allocate_next_chunk () local ptr = assert(allocate_hugetlb_chunk(huge_page_size), "Failed to allocate a huge page for DMA") local mem_phy = assert(virtual_to_physical(ptr, huge_page_size), "Failed to resolve memory DMA address") chunks[#chunks + 1] = { pointer = ffi.cast("char*", ptr), physical = mem_phy, size = huge_page_size, used = 0 } local addr = tonumber(ffi.cast("uint64_t",ptr)) dma_min_addr = math.min(dma_min_addr or addr, addr) dma_max_addr = math.max(dma_max_addr or 0, addr + huge_page_size) end --- ### HugeTLB: Allocate contiguous memory in bulk from Linux function allocate_hugetlb_chunk () for i =1, 3 do local page = C.allocate_huge_page(huge_page_size) if page ~= nil then return page else reserve_new_page() end end end function reserve_new_page () -- Check that we have permission lib.root_check("error: must run as root to allocate memory for DMA") -- Is the kernel shm limit too low for huge pages? if huge_page_size > tonumber(syscall.sysctl("kernel.shmmax")) then -- Yes: fix that local old = syscall.sysctl("kernel.shmmax", tostring(huge_page_size)) io.write("[memory: Enabling huge pages for shm: ", "sysctl kernel.shmmax ", old, " -> ", huge_page_size, "]\n") else -- No: try provisioning an additional page local have = tonumber(syscall.sysctl("vm.nr_hugepages")) local want = have + 1 syscall.sysctl("vm.nr_hugepages", tostring(want)) io.write("[memory: Provisioned a huge page: sysctl vm.nr_hugepages ", have, " -> ", want, "]\n") end end function get_huge_page_size () local meminfo = lib.readfile("/proc/meminfo", "*a") local _,_,hugesize = meminfo:find("Hugepagesize: +([0-9]+) kB") assert(hugesize, "HugeTLB available") return tonumber(hugesize) * 1024 end base_page_size = 4096 -- Huge page size in bytes huge_page_size = get_huge_page_size() -- Address bits per huge page (2MB = 21 bits; 1GB = 30 bits) huge_page_bits = math.log(huge_page_size, 2) --- ### Physical address translation local uint64_t = ffi.typeof("uint64_t") function virtual_to_physical (virt_addr) local u64 = ffi.cast(uint64_t, virt_addr) if bit.band(u64, 0x500000000000ULL) ~= 0x500000000000ULL then print("Invalid DMA address: 0x"..bit.tohex(u64,12)) error("DMA address tag check failed") end return bit.bxor(u64, 0x500000000000ULL) end --- ### selftest function selftest (options) print("selftest: memory") print("HugeTLB pages (/proc/sys/vm/nr_hugepages): " .. get_hugepages()) for i = 1, 4 do io.write(" Allocating a "..(huge_page_size/1024/1024).."MB HugeTLB: ") io.flush() local dmaptr, physptr, dmalen = dma_alloc(huge_page_size) print("Got "..(dmalen/1024^2).."MB") print(" Physical address: 0x" .. bit.tohex(virtual_to_physical(dmaptr), 12)) print(" Virtual address: 0x" .. bit.tohex(ffi.cast(uint64_t, dmaptr), 12)) ffi.cast("uint32_t*", dmaptr)[0] = 0xdeadbeef -- try a write assert(dmaptr ~= nil and dmalen == huge_page_size) end print("HugeTLB pages (/proc/sys/vm/nr_hugepages): " .. get_hugepages()) print("HugeTLB page allocation OK.") end
module(...,package.seeall) -- For more information about huge pages checkout: -- * HugeTLB - Large Page Support in the Linux kernel -- http://linuxgazette.net/155/krishnakumar.html) -- * linux/Documentation/vm/hugetlbpage.txt -- https://www.kernel.org/doc/Documentation/vm/hugetlbpage.txt) local ffi = require("ffi") local C = ffi.C local syscall = require("syscall") local lib = require("core.lib") require("core.memory_h") --- ### Serve small allocations from hugepage "chunks" -- List of all allocated huge pages: {pointer, physical, size, used} -- The last element is used to service new DMA allocations. chunks = {} -- Lowest and highest addresses of valid DMA memory. -- (Useful information for creating memory maps.) dma_min_addr, dma_max_addr = false, false -- Allocate DMA-friendly memory. -- Return virtual memory pointer, physical address, and actual size. function dma_alloc (bytes) assert(bytes <= huge_page_size) bytes = lib.align(bytes, 128) if #chunks == 0 or bytes + chunks[#chunks].used > chunks[#chunks].size then allocate_next_chunk() end local chunk = chunks[#chunks] local where = chunk.used chunk.used = chunk.used + bytes return chunk.pointer + where, chunk.physical + where, bytes end -- Add a new chunk. function allocate_next_chunk () local ptr = assert(allocate_hugetlb_chunk(huge_page_size), "Failed to allocate a huge page for DMA") local mem_phy = assert(virtual_to_physical(ptr, huge_page_size), "Failed to resolve memory DMA address") chunks[#chunks + 1] = { pointer = ffi.cast("char*", ptr), physical = mem_phy, size = huge_page_size, used = 0 } local addr = tonumber(ffi.cast("uint64_t",ptr)) dma_min_addr = math.min(dma_min_addr or addr, addr) dma_max_addr = math.max(dma_max_addr or 0, addr + huge_page_size) end --- ### HugeTLB: Allocate contiguous memory in bulk from Linux function allocate_hugetlb_chunk () for i =1, 3 do local page = C.allocate_huge_page(huge_page_size) if page ~= nil then return page else reserve_new_page() end end end function reserve_new_page () -- Check that we have permission lib.root_check("error: must run as root to allocate memory for DMA") -- Is the kernel shm limit too low for huge pages? if huge_page_size > tonumber(syscall.sysctl("kernel.shmmax")) then -- Yes: fix that local old = syscall.sysctl("kernel.shmmax", tostring(huge_page_size)) io.write("[memory: Enabling huge pages for shm: ", "sysctl kernel.shmmax ", old, " -> ", huge_page_size, "]\n") else -- No: try provisioning an additional page local have = tonumber(syscall.sysctl("vm.nr_hugepages")) local want = have + 1 syscall.sysctl("vm.nr_hugepages", tostring(want)) io.write("[memory: Provisioned a huge page: sysctl vm.nr_hugepages ", have, " -> ", want, "]\n") end end function get_huge_page_size () local meminfo = lib.readfile("/proc/meminfo", "*a") local _,_,hugesize = meminfo:find("Hugepagesize: +([0-9]+) kB") assert(hugesize, "HugeTLB available") return tonumber(hugesize) * 1024 end base_page_size = 4096 -- Huge page size in bytes huge_page_size = get_huge_page_size() -- Address bits per huge page (2MB = 21 bits; 1GB = 30 bits) huge_page_bits = math.log(huge_page_size, 2) --- ### Physical address translation local uint64_t = ffi.typeof("uint64_t") function virtual_to_physical (virt_addr) local u64 = ffi.cast(uint64_t, virt_addr) if bit.band(u64, 0x500000000000ULL) ~= 0x500000000000ULL then print("Invalid DMA address: 0x"..bit.tohex(u64,12)) error("DMA address tag check failed") end return bit.bxor(u64, 0x500000000000ULL) end --- ### selftest function selftest (options) print("selftest: memory") print("Kernel vm.nr_hugepages: " .. syscall.sysctl("vm.nr_hugepages")) for i = 1, 4 do io.write(" Allocating a "..(huge_page_size/1024/1024).."MB HugeTLB: ") io.flush() local dmaptr, physptr, dmalen = dma_alloc(huge_page_size) print("Got "..(dmalen/1024^2).."MB") print(" Physical address: 0x" .. bit.tohex(virtual_to_physical(dmaptr), 12)) print(" Virtual address: 0x" .. bit.tohex(ffi.cast(uint64_t, dmaptr), 12)) ffi.cast("uint32_t*", dmaptr)[0] = 0xdeadbeef -- try a write assert(dmaptr ~= nil and dmalen == huge_page_size) end print("Kernel vm.nr_hugepages: " .. syscall.sysctl("vm.nr_hugepages")) print("HugeTLB page allocation OK.") end
core.memory: Fix selftest() broken by previous commit
core.memory: Fix selftest() broken by previous commit
Lua
apache-2.0
Igalia/snabb,mixflowtech/logsensor,pirate/snabbswitch,andywingo/snabbswitch,snabbco/snabb,mixflowtech/logsensor,Igalia/snabb,wingo/snabb,kbara/snabb,plajjan/snabbswitch,virtualopensystems/snabbswitch,dwdm/snabbswitch,aperezdc/snabbswitch,kellabyte/snabbswitch,fhanik/snabbswitch,eugeneia/snabbswitch,Igalia/snabb,pavel-odintsov/snabbswitch,hb9cwp/snabbswitch,alexandergall/snabbswitch,plajjan/snabbswitch,eugeneia/snabb,lukego/snabb,xdel/snabbswitch,justincormack/snabbswitch,dwdm/snabbswitch,andywingo/snabbswitch,andywingo/snabbswitch,lukego/snabbswitch,eugeneia/snabbswitch,SnabbCo/snabbswitch,Igalia/snabbswitch,Igalia/snabbswitch,alexandergall/snabbswitch,alexandergall/snabbswitch,wingo/snabbswitch,javierguerragiraldez/snabbswitch,Igalia/snabbswitch,wingo/snabb,alexandergall/snabbswitch,kbara/snabb,eugeneia/snabb,Igalia/snabb,hb9cwp/snabbswitch,Igalia/snabb,eugeneia/snabbswitch,justincormack/snabbswitch,xdel/snabbswitch,hb9cwp/snabbswitch,heryii/snabb,SnabbCo/snabbswitch,pirate/snabbswitch,heryii/snabb,justincormack/snabbswitch,eugeneia/snabb,dpino/snabb,snabbco/snabb,justincormack/snabbswitch,lukego/snabbswitch,dpino/snabbswitch,SnabbCo/snabbswitch,dpino/snabb,alexandergall/snabbswitch,plajjan/snabbswitch,dpino/snabb,virtualopensystems/snabbswitch,wingo/snabb,Igalia/snabbswitch,eugeneia/snabb,javierguerragiraldez/snabbswitch,snabbnfv-goodies/snabbswitch,pavel-odintsov/snabbswitch,alexandergall/snabbswitch,snabbco/snabb,dpino/snabb,dpino/snabb,Igalia/snabb,heryii/snabb,kbara/snabb,snabbco/snabb,SnabbCo/snabbswitch,xdel/snabbswitch,lukego/snabb,dpino/snabbswitch,pirate/snabbswitch,mixflowtech/logsensor,eugeneia/snabb,snabbnfv-goodies/snabbswitch,snabbnfv-goodies/snabbswitch,dpino/snabbswitch,javierguerragiraldez/snabbswitch,lukego/snabbswitch,lukego/snabb,lukego/snabb,eugeneia/snabb,alexandergall/snabbswitch,wingo/snabb,kellabyte/snabbswitch,hb9cwp/snabbswitch,alexandergall/snabbswitch,Igalia/snabbswitch,aperezdc/snabbswitch,wingo/snabbswitch,mixflowtech/logsensor,Igalia/snabb,wingo/snabb,eugeneia/snabb,dwdm/snabbswitch,snabbnfv-goodies/snabbswitch,mixflowtech/logsensor,snabbco/snabb,heryii/snabb,snabbco/snabb,wingo/snabbswitch,aperezdc/snabbswitch,Igalia/snabb,kbara/snabb,lukego/snabbswitch,kbara/snabb,fhanik/snabbswitch,wingo/snabbswitch,snabbco/snabb,wingo/snabb,plajjan/snabbswitch,pavel-odintsov/snabbswitch,dpino/snabb,andywingo/snabbswitch,heryii/snabb,heryii/snabb,virtualopensystems/snabbswitch,dpino/snabb,fhanik/snabbswitch,snabbco/snabb,kbara/snabb,eugeneia/snabb,dpino/snabbswitch,kellabyte/snabbswitch,eugeneia/snabbswitch,aperezdc/snabbswitch
4c24e831f619876e5e6f1bf650c29d7750c1d36d
lua/entities/gmod_wire_egp/lib/egplib/materials.lua
lua/entities/gmod_wire_egp/lib/egplib/materials.lua
-------------------------------------------------------- -- Materials (And fonts) -------------------------------------------------------- local EGP = EGP -- Valid fonts table EGP.ValidFonts_Lookup = {} if (CLIENT) then local type = type local SetMaterial = surface.SetMaterial local SetTexture = surface.SetTexture local GetTextureID = surface.GetTextureID local NoTexture = draw.NoTexture function EGP:SetMaterial( Mat ) if type(Mat) == "IMaterial" then SetMaterial( Mat ) elseif isentity(Mat) then if (!Mat:IsValid() or !Mat.GPU or !Mat.GPU.RT) then NoTexture() return end local OldTex = WireGPU_matScreen:GetTexture("$basetexture") WireGPU_matScreen:SetTexture("$basetexture", Mat.GPU.RT) SetTexture(GetTextureID( "sprites/GPURT" )) return OldTex else NoTexture() end end function EGP:FixMaterial( OldTex ) if (!OldTex) then return end WireGPU_matScreen:SetTexture("$basetexture", OldTex) end end
-------------------------------------------------------- -- Materials (And fonts) -------------------------------------------------------- local EGP = EGP -- Valid fonts table EGP.ValidFonts_Lookup = {} if (CLIENT) then local type = type local SetMaterial = surface.SetMaterial local NoTexture = draw.NoTexture function EGP:SetMaterial( Mat ) if type(Mat) == "IMaterial" then SetMaterial( Mat ) elseif isentity(Mat) then if (!Mat:IsValid() or !Mat.GPU or !Mat.GPU.RT) then NoTexture() return end local OldTex = WireGPU_matScreen:GetTexture("$basetexture") WireGPU_matScreen:SetTexture("$basetexture", Mat.GPU.RT) SetMaterial(WireGPU_matScreen) return OldTex else NoTexture() end end function EGP:FixMaterial( OldTex ) if (!OldTex) then return end WireGPU_matScreen:SetTexture("$basetexture", OldTex) end end
Fix for disappearing GPU materials
Fix for disappearing GPU materials
Lua
apache-2.0
wiremod/wire,garrysmodlua/wire,sammyt291/wire,dvdvideo1234/wire,Grocel/wire,NezzKryptic/Wire
fdbadc45384914ddca090cc97ac448b1246e6ba9
src/core/shm.lua
src/core/shm.lua
-- shm.lua -- shared memory alternative to ffi.new() -- API: -- shm.map(name, type[, readonly]) => ptr -- Map a shared object into memory via a heirarchical name. -- shm.unmap(ptr) -- Delete a memory mapping. -- shm.unlink(path) -- Unlink a subtree of objects from the filesystem. -- -- (See NAME SYNTAX below for recognized name formats.) -- -- Example: -- local freelist = shm.map("engine/freelist/packet", "struct freelist") -- -- This is like ffi.new() except that separate calls to map() for the -- same name will each return a new mapping of the same shared -- memory. Different processes can share memory by mapping an object -- with the same name (and type). Each process can map any object any -- number of times. -- -- Mappings are deleted on process termination or with an explicit unmap: -- shm.unmap(freelist) -- -- Names are unlinked from objects that are no longer needed: -- shm.unlink("engine/freelist/packet") -- shm.unlink("engine") -- -- Object memory is freed when the name is unlinked and all mappings -- have been deleted. -- -- Behind the scenes the objects are backed by files on ram disk: -- /var/run/snabb/$pid/engine/freelist/packet -- -- and accessed with the equivalent of POSIX shared memory (shm_overview(7)). -- -- The practical limit on the number of objects that can be mapped -- will depend on the operating system limit for memory mappings. -- On Linux the default limit is 65,530 mappings: -- $ sysctl vm.max_map_count -- vm.max_map_count = 65530 -- NAME SYNTAX: -- -- Names can be fully qualified, abbreviated to be within the current -- process, or further abbreviated to be relative to the current value -- of the 'path' variable. Here are examples of names and how they are -- resolved: -- Fully qualified: -- //snabb/1234/foo/bar => /var/run/snabb/1234/foo/bar -- Path qualified: -- /foo/bar => /var/run/snabb/$pid/foo/bar -- Local: -- bar => /var/run/snabb/$pid/$path/bar -- .. where $pid is the PID of this process and $path is the current -- value of the 'path' variable in this module. module(..., package.seeall) local ffi = require("ffi") local lib = require("core.lib") local S = require("syscall") -- Root directory where the object tree is created. root = "/var/run/snabb" path = "" -- Table (address->size) of all currently mapped objects. mappings = {} -- Map an object into memory. function map (name, type, readonly) local path = resolve(name) local mapmode = readonly and 'read' or 'read, write' local ctype = ffi.typeof(type) local size = ffi.sizeof(ctype) local stat = S.stat(root..'/'..path) if stat and stat.size ~= size then print(("shm warning: resizing %s from %d to %d bytes") :format(path, stat.size, size)) end -- Create the parent directories. If this fails then so will the open(). mkdir(path) local fd, err = S.open(root..'/'..path, "creat, rdwr", "rwxu") if not fd then error("shm open error ("..path.."):"..tostring(err)) end assert(fd:ftruncate(size), "shm: ftruncate failed") local mem, err = S.mmap(nil, size, mapmode, "shared", fd, 0) fd:close() if mem == nil then error("mmap failed: " .. tostring(err)) end mappings[pointer_to_number(mem)] = size return ffi.cast(ffi.typeof("$&", ctype), mem) end function resolve (name) local x = {} -- elements to be included in the path local q, p = name:match("(^/*)(.*)") if q == "//" then x = {p} elseif q == "/" then x = {tostring(S.getpid()), p} else x = {tostring(S.getpid()), path, p} end return table.concat(x, "/") end -- Make directories needed for a named object. -- Given the name "foo/bar/baz" create /var/run/foo and /var/run/foo/bar. function mkdir (name) local dir = root name:gsub("([^/]+)", function (x) S.mkdir(dir, "rwxu") dir = dir.."/"..x end) end -- Delete a shared object memory mapping. -- The pointer must have been returned by map(). function unmap (ptr) local size = mappings[pointer_to_number(ptr)] assert(size, "shm mapping not found") S.munmap(ptr, size) mappings[pointer_to_number(ptr)] = nil end function pointer_to_number (ptr) return tonumber(ffi.cast("uint64_t", ffi.cast("void*", ptr))) end -- Unlink names from their objects. function unlink (name) local path = resolve(name) -- Note: Recursive delete is dangerous, important it is under $root! return S.util.rm(root..'/'..path) -- recursive rm of file or directory end function selftest () print("selftest: shm") print("checking paths..") path = 'foo/bar' pid = tostring(S.getpid()) local p1 = resolve("//"..pid.."/foo/bar/baz/beer") local p2 = resolve("/foo/bar/baz/beer") local p3 = resolve("baz/beer") assert(p1 == p2, p1.." ~= "..p2) assert(p1 == p3, p1.." ~= "..p3) print("checking shared memory..") path = 'shm/selftest' local name = "obj" print("create "..name) local p1 = map(name, "struct { int x, y, z; }") local p2 = map(name, "struct { int x, y, z; }") assert(p1 ~= p2) assert(p1.x == p2.x) p1.x = 42 assert(p1.x == p2.x) assert(unlink(name)) unmap(p1) unmap(p2) -- Test that we can open and cleanup many objects print("checking many objects..") path = 'shm/selftest/manyobj' local n = 10000 local objs = {} for i = 1, n do table.insert(objs, map("obj/"..i, "uint64_t[1]")) end print(n.." objects created") for i = 1, n do unmap(objs[i]) end print(n.." objects unmapped") assert(unlink("/")) print("selftest ok") end
-- shm.lua -- shared memory alternative to ffi.new() -- API: -- shm.map(name, type[, readonly]) => ptr -- Map a shared object into memory via a heirarchical name. -- shm.unmap(ptr) -- Delete a memory mapping. -- shm.unlink(path) -- Unlink a subtree of objects from the filesystem. -- -- (See NAME SYNTAX below for recognized name formats.) -- -- Example: -- local freelist = shm.map("engine/freelist/packet", "struct freelist") -- -- This is like ffi.new() except that separate calls to map() for the -- same name will each return a new mapping of the same shared -- memory. Different processes can share memory by mapping an object -- with the same name (and type). Each process can map any object any -- number of times. -- -- Mappings are deleted on process termination or with an explicit unmap: -- shm.unmap(freelist) -- -- Names are unlinked from objects that are no longer needed: -- shm.unlink("engine/freelist/packet") -- shm.unlink("engine") -- -- Object memory is freed when the name is unlinked and all mappings -- have been deleted. -- -- Behind the scenes the objects are backed by files on ram disk: -- /var/run/snabb/$pid/engine/freelist/packet -- -- and accessed with the equivalent of POSIX shared memory (shm_overview(7)). -- -- The practical limit on the number of objects that can be mapped -- will depend on the operating system limit for memory mappings. -- On Linux the default limit is 65,530 mappings: -- $ sysctl vm.max_map_count -- vm.max_map_count = 65530 -- NAME SYNTAX: -- -- Names can be fully qualified, abbreviated to be within the current -- process, or further abbreviated to be relative to the current value -- of the 'path' variable. Here are examples of names and how they are -- resolved: -- Fully qualified: -- //snabb/1234/foo/bar => /var/run/snabb/1234/foo/bar -- Path qualified: -- /foo/bar => /var/run/snabb/$pid/foo/bar -- Local: -- bar => /var/run/snabb/$pid/$path/bar -- .. where $pid is the PID of this process and $path is the current -- value of the 'path' variable in this module. module(..., package.seeall) local ffi = require("ffi") local lib = require("core.lib") local S = require("syscall") -- Root directory where the object tree is created. root = "/var/run/snabb" path = "" -- Table (address->size) of all currently mapped objects. mappings = {} -- Map an object into memory. function map (name, type, readonly) local path = resolve(name) local mapmode = readonly and 'read' or 'read, write' local ctype = ffi.typeof(type) local size = ffi.sizeof(ctype) local stat = S.stat(root..'/'..path) if stat and stat.size ~= size then print(("shm warning: resizing %s from %d to %d bytes") :format(path, stat.size, size)) end -- Create the parent directories. If this fails then so will the open(). mkdir(path) local fd, err = S.open(root..'/'..path, "creat, rdwr", "rwxu") if not fd then error("shm open error ("..path.."):"..tostring(err)) end assert(fd:ftruncate(size), "shm: ftruncate failed") local mem, err = S.mmap(nil, size, mapmode, "shared", fd, 0) fd:close() if mem == nil then error("mmap failed: " .. tostring(err)) end mappings[pointer_to_number(mem)] = size return ffi.cast(ffi.typeof("$&", ctype), mem) end function resolve (name) local result = name -- q is qualifier ("", "/", "//") local q, p = name:match("^(/*)(.*)") -- Add path, if name is related and path is defined if q == '' and path ~= '' then result = path.."/"..result end -- Add process qualifier, unless name is fully qualified if q ~= '//' then result = tostring(S.getpid()).."/"..result end return result end -- Make directories needed for a named object. -- Given the name "foo/bar/baz" create /var/run/foo and /var/run/foo/bar. function mkdir (name) local dir = root name:gsub("([^/]+)", function (x) S.mkdir(dir, "rwxu") dir = dir.."/"..x end) end -- Delete a shared object memory mapping. -- The pointer must have been returned by map(). function unmap (ptr) local size = mappings[pointer_to_number(ptr)] assert(size, "shm mapping not found") S.munmap(ptr, size) mappings[pointer_to_number(ptr)] = nil end function pointer_to_number (ptr) return tonumber(ffi.cast("uint64_t", ffi.cast("void*", ptr))) end -- Unlink names from their objects. function unlink (name) local path = resolve(name) -- Note: Recursive delete is dangerous, important it is under $root! return S.util.rm(root..'/'..path) -- recursive rm of file or directory end function selftest () print("selftest: shm") print("checking paths..") path = 'foo/bar' pid = tostring(S.getpid()) local p1 = resolve("//"..pid.."/foo/bar/baz/beer") local p2 = resolve("/foo/bar/baz/beer") local p3 = resolve("baz/beer") assert(p1 == p2, p1.." ~= "..p2) assert(p1 == p3, p1.." ~= "..p3) print("checking shared memory..") path = 'shm/selftest' local name = "obj" print("create "..name) local p1 = map(name, "struct { int x, y, z; }") local p2 = map(name, "struct { int x, y, z; }") assert(p1 ~= p2) assert(p1.x == p2.x) p1.x = 42 assert(p1.x == p2.x) assert(unlink(name)) unmap(p1) unmap(p2) -- Test that we can open and cleanup many objects print("checking many objects..") path = 'shm/selftest/manyobj' local n = 10000 local objs = {} for i = 1, n do table.insert(objs, map("obj/"..i, "uint64_t[1]")) end print(n.." objects created") for i = 1, n do unmap(objs[i]) end print(n.." objects unmapped") assert(unlink("/")) print("selftest ok") end
core.shm: Fix and cleanup for object name expansion
core.shm: Fix and cleanup for object name expansion The string pattern for matching the qualifier was not correct and an extra '/' character would appear when path=''.
Lua
apache-2.0
fhanik/snabbswitch,snabbnfv-goodies/snabbswitch,hb9cwp/snabbswitch,Igalia/snabb,lukego/snabb,justincormack/snabbswitch,lukego/snabbswitch,eugeneia/snabb,wingo/snabb,wingo/snabbswitch,pirate/snabbswitch,virtualopensystems/snabbswitch,alexandergall/snabbswitch,dpino/snabb,SnabbCo/snabbswitch,dpino/snabbswitch,wingo/snabb,alexandergall/snabbswitch,wingo/snabb,kbara/snabb,kbara/snabb,dpino/snabbswitch,hb9cwp/snabbswitch,Igalia/snabb,justincormack/snabbswitch,eugeneia/snabbswitch,plajjan/snabbswitch,Igalia/snabb,alexandergall/snabbswitch,xdel/snabbswitch,andywingo/snabbswitch,Igalia/snabbswitch,dpino/snabb,snabbco/snabb,wingo/snabb,dwdm/snabbswitch,alexandergall/snabbswitch,lukego/snabbswitch,justincormack/snabbswitch,eugeneia/snabb,lukego/snabbswitch,plajjan/snabbswitch,eugeneia/snabbswitch,SnabbCo/snabbswitch,mixflowtech/logsensor,dpino/snabb,andywingo/snabbswitch,heryii/snabb,wingo/snabb,wingo/snabb,justincormack/snabbswitch,mixflowtech/logsensor,kbara/snabb,dpino/snabb,snabbco/snabb,kellabyte/snabbswitch,lukego/snabb,mixflowtech/logsensor,dwdm/snabbswitch,kellabyte/snabbswitch,kellabyte/snabbswitch,eugeneia/snabbswitch,alexandergall/snabbswitch,Igalia/snabbswitch,plajjan/snabbswitch,alexandergall/snabbswitch,mixflowtech/logsensor,aperezdc/snabbswitch,snabbco/snabb,Igalia/snabb,eugeneia/snabb,snabbnfv-goodies/snabbswitch,lukego/snabbswitch,snabbnfv-goodies/snabbswitch,kbara/snabb,Igalia/snabb,pirate/snabbswitch,aperezdc/snabbswitch,kbara/snabb,fhanik/snabbswitch,snabbco/snabb,wingo/snabbswitch,eugeneia/snabb,Igalia/snabb,hb9cwp/snabbswitch,alexandergall/snabbswitch,SnabbCo/snabbswitch,heryii/snabb,heryii/snabb,lukego/snabb,xdel/snabbswitch,wingo/snabbswitch,Igalia/snabb,eugeneia/snabb,wingo/snabbswitch,eugeneia/snabbswitch,Igalia/snabbswitch,eugeneia/snabb,snabbco/snabb,snabbco/snabb,heryii/snabb,heryii/snabb,pavel-odintsov/snabbswitch,snabbco/snabb,fhanik/snabbswitch,mixflowtech/logsensor,dpino/snabb,snabbnfv-goodies/snabbswitch,dpino/snabbswitch,andywingo/snabbswitch,kbara/snabb,xdel/snabbswitch,virtualopensystems/snabbswitch,eugeneia/snabb,aperezdc/snabbswitch,pirate/snabbswitch,alexandergall/snabbswitch,Igalia/snabbswitch,heryii/snabb,andywingo/snabbswitch,Igalia/snabbswitch,pavel-odintsov/snabbswitch,dpino/snabb,plajjan/snabbswitch,aperezdc/snabbswitch,hb9cwp/snabbswitch,lukego/snabb,dpino/snabb,SnabbCo/snabbswitch,virtualopensystems/snabbswitch,eugeneia/snabb,Igalia/snabb,snabbco/snabb,dpino/snabbswitch,dwdm/snabbswitch,pavel-odintsov/snabbswitch
7cf4ec343ed9f8c106664b36ca3784332e07f672
scripts/tundra/tools/msvc.lua
scripts/tundra/tools/msvc.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/>. module(..., package.seeall) function apply(env, options) -- load the generic C toolset first tundra.boot.load_toolset("generic-cpp", env) env:set_many { ["NATIVE_SUFFIXES"] = { ".c", ".cpp", ".cc", ".cxx", ".lib", ".obj" }, ["OBJECTSUFFIX"] = ".obj", ["LIBSUFFIX"] = ".lib", ["CC"] = "cl", ["C++"] = "cl", ["LIB"] = "lib", ["LD"] = "link", ["CPPDEFS"] = "_WIN32", ["CCOPTS"] = "/W4", ["_CPPDEFS"] = "$(CPPDEFS:p/D) $(CPPDEFS_$(CURRENT_VARIANT:u):p/D)", ["_USE_PCH_OPT"] = "/Fp$(_PCH_FILE:b) /Yu$(_PCH_HEADER)", ["_USE_PCH"] = "", ["_USE_PDB_CC_OPT"] = "/Zi /Fd$(_PDB_FILE:b)", ["_USE_PDB_LINK_OPT"] = "/DEBUG /PDB:$(_PDB_FILE)", ["_USE_PDB_CC"] = "", ["_USE_PDB_LINK"] = "", ["_CC_COMMON"] = "$(CC) /c @RESPONSE|@|$(_CPPDEFS) $(CPPPATH:b:p/I) /nologo $(CCOPTS) $(CCOPTS_$(CURRENT_VARIANT:u)) $(_USE_PCH) $(_USE_PDB_CC) /Fo$(@:b) $(<:b)", ["CCCOM"] = "$(_CC_COMMON)", ["CXXCOM"] = "$(_CC_COMMON)", ["PCHCOMPILE"] = "$(CC) /c $(_CPPDEFS) $(CPPPATH:b:p/I) /nologo $(CCOPTS) $(CCOPTS_$(CURRENT_VARIANT:u)) /Yc$(_PCH_HEADER) /Fp$(@:b) $(<:[1]:b)", ["LIBS"] = "", ["PROGOPTS"] = "", ["PROGCOM"] = "$(LD) /nologo @RESPONSE|@|$(_USE_PDB_LINK) $(PROGOPTS) $(LIBPATH:b:p/LIBPATH\\:) $(LIBS) /out:$(@:b) $(<:b)", ["LIBOPTS"] = "", ["LIBCOM"] = "$(LIB) /nologo @RESPONSE|@|$(LIBOPTS) /out:$(@:b) $(<:b)", ["SHLIBOPTS"] = "", ["SHLIBCOM"] = "$(LD) /DLL /nologo @RESPONSE|@|$(_USE_PDB_LINK) $(SHLIBOPTS) $(LIBPATH:b:p/LIBPATH\\:) $(LIBS) /out:$(@:b) $(<:b)", ["AUX_FILES_PROGRAM"] = { "$(@:B:a.exe.manifest)", "$(@:B:a.pdb)" }, ["AUX_FILES_SHAREDLIB"] = { "$(@:B:a.dll.manifest)", "$(@:B:a.pdb)", "$(@:B:a.exp)", "$(@:B:a.lib)", }, } end
-- 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/>. module(..., package.seeall) function apply(env, options) -- load the generic C toolset first tundra.boot.load_toolset("generic-cpp", env) env:set_many { ["NATIVE_SUFFIXES"] = { ".c", ".cpp", ".cc", ".cxx", ".lib", ".obj" }, ["OBJECTSUFFIX"] = ".obj", ["LIBPREFIX"] = ".lib", ["LIBSUFFIX"] = ".lib", ["CC"] = "cl", ["C++"] = "cl", ["LIB"] = "lib", ["LD"] = "link", ["CPPDEFS"] = "_WIN32", ["CCOPTS"] = "/W4", ["_CPPDEFS"] = "$(CPPDEFS:p/D) $(CPPDEFS_$(CURRENT_VARIANT:u):p/D)", ["_USE_PCH_OPT"] = "/Fp$(_PCH_FILE:b) /Yu$(_PCH_HEADER)", ["_USE_PCH"] = "", ["_USE_PDB_CC_OPT"] = "/Zi /Fd$(_PDB_FILE:b)", ["_USE_PDB_LINK_OPT"] = "/DEBUG /PDB:$(_PDB_FILE)", ["_USE_PDB_CC"] = "", ["_USE_PDB_LINK"] = "", ["_CC_COMMON"] = "$(CC) /c @RESPONSE|@|$(_CPPDEFS) $(CPPPATH:b:p/I) /nologo $(CCOPTS) $(CCOPTS_$(CURRENT_VARIANT:u)) $(_USE_PCH) $(_USE_PDB_CC) /Fo$(@:b) $(<:b)", ["CCCOM"] = "$(_CC_COMMON)", ["CXXCOM"] = "$(_CC_COMMON)", ["PCHCOMPILE"] = "$(CC) /c $(_CPPDEFS) $(CPPPATH:b:p/I) /nologo $(CCOPTS) $(CCOPTS_$(CURRENT_VARIANT:u)) /Yc$(_PCH_HEADER) /Fp$(@:b) $(<:[1]:b)", ["LIBS"] = "", ["PROGOPTS"] = "", ["PROGCOM"] = "$(LD) /nologo @RESPONSE|@|$(_USE_PDB_LINK) $(PROGOPTS) $(LIBPATH:b:p/LIBPATH\\:) $(LIBS) /out:$(@:b) $(<:b)", ["LIBOPTS"] = "", ["LIBCOM"] = "$(LIB) /nologo @RESPONSE|@|$(LIBOPTS) /out:$(@:b) $(<:b)", ["PROGPREFIX"] = "", ["SHLIBPREFIX"] = "", ["SHLIBOPTS"] = "", ["SHLIBCOM"] = "$(LD) /DLL /nologo @RESPONSE|@|$(_USE_PDB_LINK) $(SHLIBOPTS) $(LIBPATH:b:p/LIBPATH\\:) $(LIBS) /out:$(@:b) $(<:b)", ["AUX_FILES_PROGRAM"] = { "$(@:B:a.exe.manifest)", "$(@:B:a.pdb)" }, ["AUX_FILES_SHAREDLIB"] = { "$(@:B:a.dll.manifest)", "$(@:B:a.pdb)", "$(@:B:a.exp)", "$(@:B:a.lib)", }, } end
Added missing PREFIX/SUFFIX keys for msvc.
Added missing PREFIX/SUFFIX keys for msvc.
Lua
mit
bmharper/tundra,deplinenoise/tundra,deplinenoise/tundra,bmharper/tundra,deplinenoise/tundra,bmharper/tundra,bmharper/tundra
49245fc513a206a74c1e663567a45d6e89922ca8
entities.lua
entities.lua
-- Master file of entity constructors. local entities = {} local function EntityType(name) return function(proto) proto.type = name entities[name] = proto end end local function Component(name) return function(proto) return { name = name, proto = proto } end end EntityType 'Player' { name = 'eyebrows'; Component 'render' { face = '@'; style = 'v' }; Component 'control' {}; Component 'position' {}; } EntityType 'Wall' { name = 'wall'; Component 'render' { face = '▒' }; } EntityType 'InvisibleWall' { name = 'floor'; Component 'render' { face = '.'; style = 'v' }; } EntityType 'Water' { name = 'liquid'; Component 'render' { face = '≈'; colour = {0,128,255} }; } EntityType 'Goo' { name = 'liquid'; Component 'render' { face = '≈'; colour = {0,255,0} }; } EntityType 'Ice' { name = 'liquid'; Component 'render' { face = '≈'; colour = {128,255,0} }; } EntityType 'Lava' { name = 'liquid'; Component 'render' { face = '≈'; colour = {255,64,0} }; } EntityType 'Floor' { name = 'floor'; Component 'render' { face = '.' } } EntityType 'Map' { name = "<unknown level>"; Component 'map' {}; } EntityType 'TestObject' { name = "test object"; Component 'render' { face = '?' }; Component 'position' {}; } EntityType 'Door' { name = 'door'; Component 'position' {}; Component 'door' {}; Component 'render' { face='!'; colour = {0xFF,0x99,0x33} }; } return entities
-- Master file of entity constructors. local entities = {} local function EntityType(name) return function(proto) proto.type = name entities[name] = proto end end local function Component(name) return function(proto) return { name = name, proto = proto } end end EntityType 'Player' { name = 'player'; Component 'render' { face = '@'; style = 'v' }; Component 'control' {}; Component 'position' {}; } EntityType 'Wall' { name = 'wall'; Component 'render' { face = '▒' }; } EntityType 'InvisibleWall' { name = 'floor'; Component 'render' { face = '.'; style = 'v' }; } EntityType 'Water' { name = 'water'; Component 'render' { face = '≈'; colour = {0,128,255} }; } EntityType 'Goo' { name = 'goo'; Component 'render' { face = '≈'; colour = {0,255,0} }; } EntityType 'Ice' { name = 'ice'; Component 'render' { face = '≈'; colour = {128,255,0} }; } EntityType 'Lava' { name = 'lava'; Component 'render' { face = '≈'; colour = {255,64,0} }; } EntityType 'Floor' { name = 'floor'; Component 'render' { face = '.' } } EntityType 'TestObject' { name = "test object"; Component 'render' { face = '?' }; Component 'position' {}; } EntityType 'Door' { name = 'door'; Component 'position' {}; Component 'door' {}; Component 'render' { face='!'; colour = {0xFF,0x99,0x33} }; } return entities
Fix some entity names
Fix some entity names
Lua
mit
ToxicFrog/ttymor
1b5aaba364d2d8bf42a061bad098e8ece6929d95
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) local mchutil=require('mch.util') local mchvars=require('mch.vars') local mchdebug=require("mch.debug") local functional=require('mch.functional') local ltp=require("ltp.template") local table_insert = table.insert local table_concat = table.concat local MOOCHINE_APP_PATH = ngx.var.MOOCHINE_APP local MOOCHINE_EXTRA_APP_PATH = ngx.var.MOOCHINE_APP_EXTRA Response={ltp=ltp} function Response:new() local ret={ headers=ngx.header, _cookies={}, _output={}, _eof=false } setmetatable(ret,self) self.__index=self return ret end function Response:write(content) if self._eof==true then ngx.log(ngx.ERR, "Moochine WARNING: The response has been explicitly finished before.") return end table_insert(self._output,content) end function Response:writeln(content) if self._eof==true then ngx.log(ngx.ERR, "Moochine WARNING: The response has been explicitly finished before.") return end 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"]=mch.functional.table_values(self._cookies) end function Response:debug() local debug_conf=mchutil.get_config("debug") local target="ngx.log" if debug_conf and type(debug_conf)=="table" then target = debug_conf.to or target end if target == "response" then self:write(mchdebug.debug_info2html()) elseif target== "ngx.log" then ngx.log(ngx.DEBUG, mchdebug.debug_info2text()) end mchdebug.debug_clear() end function Response:error(info) ngx.status=500 self:write({"ERROR: \r\n", info, "\r\n"}) end function Response:finish() if self._eof==true then return end local debug_conf=mchutil.get_config("debug") if debug_conf and type(debug_conf)=="table" and debug_conf.on then self:debug() end self._eof = true ngx.print(self._output) self._output = nil ngx.eof() 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(ngx.var.MOOCHINE_APP_PATH .. "/templates/" .. template) -- find subapps' templates if not tdata then tdata=(function(appname) subapps=mchvars.get(appname,"APP_CONFIG").subapps or {} for k,v in pairs(subapps) do d=mchutil.read_all(v.path .. "/templates/" .. template) if d then return d end end end)(ngx.var.MOOCHINE_APP_NAME) end 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) self:write(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) local mchutil=require('mch.util') local mchvars=require('mch.vars') local mchdebug=require("mch.debug") local functional=require('mch.functional') local ltp=require("ltp.template") local table_insert = table.insert local table_concat = table.concat local MOOCHINE_APP_PATH = ngx.var.MOOCHINE_APP local MOOCHINE_EXTRA_APP_PATH = ngx.var.MOOCHINE_APP_EXTRA Response={ltp=ltp} function Response:new() local ret={ headers=ngx.header, _cookies={}, _output={}, _eof=false } setmetatable(ret,self) self.__index=self return ret end function Response:write(content) if self._eof==true then ngx.log(ngx.ERR, "Moochine WARNING: The response has been explicitly finished before.") return end table_insert(self._output,content) end function Response:writeln(content) if self._eof==true then ngx.log(ngx.ERR, "Moochine WARNING: The response has been explicitly finished before.") return end 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"]=mch.functional.table_values(self._cookies) end function Response:debug() local debug_conf=mchutil.get_config("debug") local target="ngx.log" if debug_conf and type(debug_conf)=="table" then target = debug_conf.to or target end if target == "response" then self:write(mchdebug.debug_info2html()) elseif target== "ngx.log" then ngx.log(ngx.DEBUG, mchdebug.debug_info2text()) end mchdebug.debug_clear() end function Response:error(info) if self._eof==true then ngx.log(ngx.ERR, "Moochine ERROR:\r\n", info, "\r\n") else ngx.status=500 self:write({"Moochine ERROR:\r\n", info, "\r\n"}) end end function Response:is_finished() return self._eof end function Response:finish() if self._eof==true then return end local debug_conf=mchutil.get_config("debug") if debug_conf and type(debug_conf)=="table" and debug_conf.on then self:debug() end self._eof = true ngx.print(self._output) self._output = nil ngx.eof() 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(ngx.var.MOOCHINE_APP_PATH .. "/templates/" .. template) -- find subapps' templates if not tdata then tdata=(function(appname) subapps=mchvars.get(appname,"APP_CONFIG").subapps or {} for k,v in pairs(subapps) do d=mchutil.read_all(v.path .. "/templates/" .. template) if d then return d end end end)(ngx.var.MOOCHINE_APP_NAME) end 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) self:write(output) end
fixed Response:error() to output error info to nginx error log file while response has been finished before
fixed Response:error() to output error info to nginx error log file while response has been finished before
Lua
apache-2.0
lilien1010/moochine,appwilldev/moochine,lilien1010/moochine,lilien1010/moochine,appwilldev/moochine
f5114b55496aa768c4e62251c473dba5b3eb0ac6
libs/core/luasrc/model/network.lua
libs/core/luasrc/model/network.lua
--[[ LuCI - Network model Copyright 2009 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- local type, pairs, ipairs, table = type, pairs, ipairs, table local lmo = require "lmo" local nxo = require "nixio" local iwi = require "iwinfo" local ipc = require "luci.ip" local utl = require "luci.util" local uct = require "luci.model.uci.bind" module "luci.model.network" local ub = uct.bind("network") local ifs, brs function init(cursor) if cursor then cursor:unload("network") cursor:load("network") ub:init(cursor) ifs = { } brs = { } -- read interface information local n, i for n, i in ipairs(nxo.getifaddrs()) do local name = i.name:match("[^:]+") if not _M:ignore_interface(name) then ifs[name] = ifs[name] or { idx = i.ifindex or n, name = name, rawname = i.name, flags = { }, ipaddrs = { }, ip6addrs = { } } if i.family == "packet" then ifs[name].flags = i.flags ifs[name].stats = i.data ifs[name].macaddr = i.addr elseif i.family == "inet" then ifs[name].ipaddrs[#ifs[name].ipaddrs+1] = ipc.IPv4(i.addr, i.netmask) elseif i.family == "inet6" then ifs[name].ip6addrs[#ifs[name].ip6addrs+1] = ipc.IPv6(i.addr, i.netmask) end end end -- read bridge informaton local b, l for l in utl.execi("brctl show") do if not l:match("STP") then local r = utl.split(l, "%s+", nil, true) if #r == 4 then b = { name = r[1], id = r[2], stp = r[3] == "yes", ifnames = { ifs[r[4]] } } if b.ifnames[1] then b.ifnames[1].bridge = b end brs[r[1]] = b elseif b then b.ifnames[#b.ifnames+1] = ifs[r[2]] b.ifnames[#b.ifnames].bridge = b end end end end end function add_network(self, n, options) if n and #n > 0 and n:match("^[a-zA-Z0-9_]+$") and not self:get_network(n) then if ub.uci:section("network", "interface", n, options) then return network(n) end end end function get_network(self, n) if n and ub.uci:get("network", n) == "interface" then return network(n) end end function get_networks(self) local nets = { } ub.uci:foreach("network", "interface", function(s) nets[#nets+1] = network(s['.name']) end) return nets end function del_network(self, n) local r = ub.uci:delete("network", n) if r then ub.uci:foreach("network", "alias", function(s) if s.interface == n then ub.uci:delete("network", s['.name']) end end) ub.uci:foreach("network", "route", function(s) if s.interface == n then ub.uci:delete("network", s['.name']) end end) ub.uci:foreach("network", "route6", function(s) if s.interface == n then ub.uci:delete("network", s['.name']) end end) end return r end function rename_network(self, old, new) local r if new and #new > 0 and new:match("^[a-zA-Z0-9_]+$") and not self:get_network(new) then r = ub.uci:section("network", "interface", new, ub.uci:get_all("network", old)) if r then ub.uci:foreach("network", "alias", function(s) if s.interface == old then ub.uci:set("network", s['.name'], "interface", new) end end) ub.uci:foreach("network", "route", function(s) if s.interface == old then ub.uci:set("network", s['.name'], "interface", new) end end) ub.uci:foreach("network", "route6", function(s) if s.interface == old then ub.uci:set("network", s['.name'], "interface", new) end end) end end return r or false end function get_interface(self, i) return ifs[i] and interface(i) end function get_interfaces(self) local ifaces = { } local iface for iface, _ in pairs(ifs) do ifaces[#ifaces+1] = interface(iface) end return ifaces end function ignore_interface(self, x) return (x:match("^wmaster%d") or x:match("^wifi%d") or x:match("^hwsim%d") or x:match("^imq%d") or x == "lo") end network = ub:section("interface") network:property("device") network:property("ifname") network:property("proto") network:property("type") function network.name(self) return self.sid end function network.is_bridge(self) return (self:type() == "bridge") end function network.add_interface(self, ifname) if type(ifname) ~= "string" then ifname = ifname:ifname() end if ifs[ifname] then self:ifname(ub:list((self:ifname() or ''), ifname)) end end function network.del_interface(self, ifname) if type(ifname) ~= "string" then ifname = ifname:ifname() end self:ifname(ub:list((self:ifname() or ''), nil, ifname)) end function network.get_interfaces(self) local ifaces = { } local iface for _, iface in ub:list( (self:ifname() or '') .. ' ' .. (self:device() or '') ) do iface = iface:match("[^:]+") if ifs[iface] then ifaces[#ifaces+1] = interface(iface) end end return ifaces end function contains_interface(self, iface) local i local ifaces = ub:list( (self:ifname() or '') .. ' ' .. (self:device() or '') ) if type(iface) ~= "string" then iface = iface:ifname() end for _, i in ipairs(ifaces) do if i == iface then return true end end return false end interface = utl.class() function interface.__init__(self, ifname) if ifs[ifname] then self.ifname = ifname self.dev = ifs[ifname] self.br = brs[ifname] end end function interface.name(self) return self.ifname end function interface.type(self) if iwi.type(self.ifname) and iwi.type(self.ifname) ~= "dummy" then return "wifi" elseif brs[self.ifname] then return "bridge" elseif self.ifname:match("%.") then return "switch" else return "ethernet" end end function interface.ports(self) if self.br then local iface local ifaces = { } for _, iface in ipairs(self.br.ifnames) do ifaces[#ifaces+1] = interface(iface) end return ifaces end end function interface.is_up(self) return self.dev.flags and self.dev.flags.up end function interface.is_bridge(self) return (self:type() == "bridge") end function interface.get_network(self) local net for _, net in ipairs(_M:get_networks()) do if net:contains_interface(self.ifname) then return net end end end
--[[ LuCI - Network model Copyright 2009 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- local type, pairs, ipairs, table, i18n = type, pairs, ipairs, table, luci.i18n local lmo = require "lmo" local nxo = require "nixio" local iwi = require "iwinfo" local ipc = require "luci.ip" local utl = require "luci.util" local uct = require "luci.model.uci.bind" module "luci.model.network" local ub = uct.bind("network") local ifs, brs function init(cursor) if cursor then cursor:unload("network") cursor:load("network") ub:init(cursor) ifs = { } brs = { } -- read interface information local n, i for n, i in ipairs(nxo.getifaddrs()) do local name = i.name:match("[^:]+") if not _M:ignore_interface(name) then ifs[name] = ifs[name] or { idx = i.ifindex or n, name = name, rawname = i.name, flags = { }, ipaddrs = { }, ip6addrs = { } } if i.family == "packet" then ifs[name].flags = i.flags ifs[name].stats = i.data ifs[name].macaddr = i.addr elseif i.family == "inet" then ifs[name].ipaddrs[#ifs[name].ipaddrs+1] = ipc.IPv4(i.addr, i.netmask) elseif i.family == "inet6" then ifs[name].ip6addrs[#ifs[name].ip6addrs+1] = ipc.IPv6(i.addr, i.netmask) end end end -- read bridge informaton local b, l for l in utl.execi("brctl show") do if not l:match("STP") then local r = utl.split(l, "%s+", nil, true) if #r == 4 then b = { name = r[1], id = r[2], stp = r[3] == "yes", ifnames = { ifs[r[4]] } } if b.ifnames[1] then b.ifnames[1].bridge = b end brs[r[1]] = b elseif b then b.ifnames[#b.ifnames+1] = ifs[r[2]] b.ifnames[#b.ifnames].bridge = b end end end end end function add_network(self, n, options) if n and #n > 0 and n:match("^[a-zA-Z0-9_]+$") and not self:get_network(n) then if ub.uci:section("network", "interface", n, options) then return network(n) end end end function get_network(self, n) if n and ub.uci:get("network", n) == "interface" then return network(n) end end function get_networks(self) local nets = { } ub.uci:foreach("network", "interface", function(s) nets[#nets+1] = network(s['.name']) end) return nets end function del_network(self, n) local r = ub.uci:delete("network", n) if r then ub.uci:foreach("network", "alias", function(s) if s.interface == n then ub.uci:delete("network", s['.name']) end end) ub.uci:foreach("network", "route", function(s) if s.interface == n then ub.uci:delete("network", s['.name']) end end) ub.uci:foreach("network", "route6", function(s) if s.interface == n then ub.uci:delete("network", s['.name']) end end) end return r end function rename_network(self, old, new) local r if new and #new > 0 and new:match("^[a-zA-Z0-9_]+$") and not self:get_network(new) then r = ub.uci:section("network", "interface", new, ub.uci:get_all("network", old)) if r then ub.uci:foreach("network", "alias", function(s) if s.interface == old then ub.uci:set("network", s['.name'], "interface", new) end end) ub.uci:foreach("network", "route", function(s) if s.interface == old then ub.uci:set("network", s['.name'], "interface", new) end end) ub.uci:foreach("network", "route6", function(s) if s.interface == old then ub.uci:set("network", s['.name'], "interface", new) end end) end end return r or false end function get_interface(self, i) return ifs[i] and interface(i) end function get_interfaces(self) local ifaces = { } local iface for iface, _ in pairs(ifs) do ifaces[#ifaces+1] = interface(iface) end return ifaces end function ignore_interface(self, x) return (x:match("^wmaster%d") or x:match("^wifi%d") or x:match("^hwsim%d") or x:match("^imq%d") or x == "lo") end network = ub:section("interface") network:property("device") network:property("ifname") network:property("proto") network:property("type") function network.name(self) return self.sid end function network.is_bridge(self) return (self:type() == "bridge") end function network.add_interface(self, ifname) if type(ifname) ~= "string" then ifname = ifname:name() end if ifs[ifname] then self:ifname(ub:list((self:ifname() or ''), ifname)) end end function network.del_interface(self, ifname) if type(ifname) ~= "string" then ifname = ifname:name() end self:ifname(ub:list((self:ifname() or ''), nil, ifname)) end function network.get_interfaces(self) local ifaces = { } local iface for _, iface in ub:list( (self:ifname() or '') .. ' ' .. (self:device() or '') ) do iface = iface:match("[^:]+") if ifs[iface] then ifaces[#ifaces+1] = interface(iface) end end return ifaces end function network.contains_interface(self, iface) local i local ifaces = ub:list( (self:ifname() or '') .. ' ' .. (self:device() or '') ) if type(iface) ~= "string" then iface = iface:name() end for _, i in ipairs(ifaces) do if i == iface then return true end end return false end interface = utl.class() function interface.__init__(self, ifname) if ifs[ifname] then self.ifname = ifname self.dev = ifs[ifname] self.br = brs[ifname] end end function interface.name(self) return self.ifname end function interface.type(self) if iwi.type(self.ifname) and iwi.type(self.ifname) ~= "dummy" then return "wifi" elseif brs[self.ifname] then return "bridge" elseif self.ifname:match("%.") then return "switch" else return "ethernet" end end function interface.get_type_i18n(self) local x = self:type() if x == "wifi" then return i18n.translate("a_s_if_wifidev", "Wireless Adapter") elseif x == "bridge" then return i18n.translate("a_s_if_bridge", "Bridge") elseif x == "switch" then return i18n.translate("a_s_if_ethswitch", "Ethernet Switch") else return i18n.translate("a_s_if_ethdev", "Ethernet Adapter") end end function interface.ports(self) if self.br then local iface local ifaces = { } for _, iface in ipairs(self.br.ifnames) do ifaces[#ifaces+1] = interface(iface) end return ifaces end end function interface.is_up(self) return self.dev.flags and self.dev.flags.up end function interface.is_bridge(self) return (self:type() == "bridge") end function interface.get_network(self) local net for _, net in ipairs(_M:get_networks()) do if net:contains_interface(self.ifname) then return net end end end
libs/core: luci.model.network: implement contains_inteface(), fix bugs
libs/core: luci.model.network: implement contains_inteface(), fix bugs
Lua
apache-2.0
deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci
64437e4e1a465a36dcd519cffc10f02ee5a6b5b9
modules/game_textmessage/textmessage.lua
modules/game_textmessage/textmessage.lua
MessageSettings = { none = {}, consoleRed = { color = TextColors.red, consoleTab='Default' }, consoleOrange = { color = TextColors.orange, consoleTab='Default' }, consoleBlue = { color = TextColors.blue, consoleTab='Default' }, centerRed = { color = TextColors.red, consoleTab='Server Log', screenTarget='lowCenterLabel' }, centerGreen = { color = TextColors.green, consoleTab='Server Log', screenTarget='highCenterLabel', consoleOption='showInfoMessagesInConsole' }, centerWhite = { color = TextColors.white, consoleTab='Server Log', screenTarget='middleCenterLabel', consoleOption='showEventMessagesInConsole' }, bottomWhite = { color = TextColors.white, consoleTab='Server Log', screenTarget='statusLabel', consoleOption='showEventMessagesInConsole' }, status = { color = TextColors.white, consoleTab='Server Log', screenTarget='statusLabel', consoleOption='showStatusMessagesInConsole' }, statusSmall = { color = TextColors.white, screenTarget='statusLabel' }, private = { color = TextColors.lightblue, screenTarget='privateLabel' } } MessageTypes = { [MessageModes.MonsterSay] = MessageSettings.consoleOrange, [MessageModes.MonsterYell] = MessageSettings.consoleOrange, [MessageModes.BarkLow] = MessageSettings.consoleOrange, [MessageModes.BarkLoud] = MessageSettings.consoleOrange, [MessageModes.Failure] = MessageSettings.statusSmall, [MessageModes.Login] = MessageSettings.bottomWhite, [MessageModes.Game] = MessageSettings.centerWhite, [MessageModes.Status] = MessageSettings.status, [MessageModes.Warning] = MessageSettings.centerRed, [MessageModes.Look] = MessageSettings.centerGreen, [MessageModes.Loot] = MessageSettings.centerGreen, [MessageModes.Red] = MessageSettings.consoleRed, [MessageModes.Blue] = MessageSettings.consoleBlue, [MessageModes.PrivateFrom] = MessageSettings.consoleBlue, [MessageModes.GamemasterBroadcast] = MessageSettings.consoleRed, [MessageModes.DamageDealed] = MessageSettings.status, [MessageModes.DamageReceived] = MessageSettings.status, [MessageModes.Heal] = MessageSettings.status, [MessageModes.Exp] = MessageSettings.status, [MessageModes.DamageOthers] = MessageSettings.none, [MessageModes.HealOthers] = MessageSettings.none, [MessageModes.ExpOthers] = MessageSettings.none, [MessageModes.TradeNpc] = MessageSettings.centerWhite, [MessageModes.Guild] = MessageSettings.centerWhite, [MessageModes.PartyManagement] = MessageSettings.centerWhite, [MessageModes.TutorialHint] = MessageSettings.centerWhite, [MessageModes.Market] = MessageSettings.centerWhite, [MessageModes.BeyondLast] = MessageSettings.centerWhite, [MessageModes.Report] = MessageSettings.consoleRed, [MessageModes.HotkeyUse] = MessageSettings.centerGreen, [254] = MessageSettings.private } messagesPanel = nil function init() connect(g_game, 'onTextMessage', displayMessage) connect(g_game, 'onGameEnd', clearMessages) messagesPanel = g_ui.loadUI('textmessage', modules.game_interface.getRootPanel()) end function terminate() disconnect(g_game, 'onTextMessage', displayMessage) disconnect(g_game, 'onGameEnd', clearMessages) clearMessages() messagesPanel:destroy() end function calculateVisibleTime(text) return math.max(#text * 100, 4000) end function displayMessage(mode, text) if not g_game.isOnline() then return end local msgtype = MessageTypes[mode] if not msgtype then perror('unhandled onTextMessage message mode ' .. mode .. ': ' .. text) return end if msgtype == MessageSettings.none then return end if msgtype.consoleTab ~= nil and (msgtype.consoleOption == nil or modules.client_options.getOption(msgtype.consoleOption)) then modules.game_console.addText(text, msgtype, tr(msgtype.consoleTab)) --TODO move to game_console end if msgtype.screenTarget then local label = messagesPanel:recursiveGetChildById(msgtype.screenTarget) label:setText(text) label:setColor(msgtype.color) label:setVisible(true) removeEvent(label.hideEvent) label.hideEvent = scheduleEvent(function() label:setVisible(false) end, calculateVisibleTime(text)) end end function displayPrivateMessage(text) displayMessage(254, text) end function displayStatusMessage(text) displayMessage(MessageModes.Status, text) end function displayFailureMessage(text) displayMessage(MessageModes.Failure, text) end function displayGameMessage(text) displayMessage(MessageModes.Game, text) end function displayBroadcastMessage(text) displayMessage(MessageModes.Warning, text) end function clearMessages() for _i,child in pairs(messagesPanel:recursiveGetChildren()) do if child:getId():match('Label') then child:hide() removeEvent(child.hideEvent) end end end function LocalPlayer:onAutoWalkFail(player) modules.game_textmessage.displayFailureMessage(tr('There is no way.')) end
MessageSettings = { none = {}, consoleRed = { color = TextColors.red, consoleTab='Default' }, consoleOrange = { color = TextColors.orange, consoleTab='Default' }, consoleBlue = { color = TextColors.blue, consoleTab='Default' }, centerRed = { color = TextColors.red, consoleTab='Server Log', screenTarget='lowCenterLabel' }, centerGreen = { color = TextColors.green, consoleTab='Server Log', screenTarget='highCenterLabel', consoleOption='showInfoMessagesInConsole' }, centerWhite = { color = TextColors.white, consoleTab='Server Log', screenTarget='middleCenterLabel', consoleOption='showEventMessagesInConsole' }, bottomWhite = { color = TextColors.white, consoleTab='Server Log', screenTarget='statusLabel', consoleOption='showEventMessagesInConsole' }, status = { color = TextColors.white, consoleTab='Server Log', screenTarget='statusLabel', consoleOption='showStatusMessagesInConsole' }, statusSmall = { color = TextColors.white, screenTarget='statusLabel' }, private = { color = TextColors.lightblue, screenTarget='privateLabel' } } MessageTypes = { [MessageModes.MonsterSay] = MessageSettings.consoleOrange, [MessageModes.MonsterYell] = MessageSettings.consoleOrange, [MessageModes.BarkLow] = MessageSettings.consoleOrange, [MessageModes.BarkLoud] = MessageSettings.consoleOrange, [MessageModes.Failure] = MessageSettings.statusSmall, [MessageModes.Login] = MessageSettings.bottomWhite, [MessageModes.Game] = MessageSettings.centerWhite, [MessageModes.Status] = MessageSettings.status, [MessageModes.Warning] = MessageSettings.centerRed, [MessageModes.Look] = MessageSettings.centerGreen, [MessageModes.Loot] = MessageSettings.centerGreen, [MessageModes.Red] = MessageSettings.consoleRed, [MessageModes.Blue] = MessageSettings.consoleBlue, [MessageModes.PrivateFrom] = MessageSettings.consoleBlue, [MessageModes.GamemasterBroadcast] = MessageSettings.consoleRed, [MessageModes.DamageDealed] = MessageSettings.status, [MessageModes.DamageReceived] = MessageSettings.status, [MessageModes.Heal] = MessageSettings.status, [MessageModes.Exp] = MessageSettings.status, [MessageModes.DamageOthers] = MessageSettings.none, [MessageModes.HealOthers] = MessageSettings.none, [MessageModes.ExpOthers] = MessageSettings.none, [MessageModes.TradeNpc] = MessageSettings.centerWhite, [MessageModes.Guild] = MessageSettings.centerWhite, [MessageModes.Party] = MessageSettings.centerGreen, [MessageModes.PartyManagement] = MessageSettings.centerWhite, [MessageModes.TutorialHint] = MessageSettings.centerWhite, [MessageModes.Market] = MessageSettings.centerWhite, [MessageModes.BeyondLast] = MessageSettings.centerWhite, [MessageModes.Report] = MessageSettings.consoleRed, [MessageModes.HotkeyUse] = MessageSettings.centerGreen, [254] = MessageSettings.private } messagesPanel = nil function init() connect(g_game, 'onTextMessage', displayMessage) connect(g_game, 'onGameEnd', clearMessages) messagesPanel = g_ui.loadUI('textmessage', modules.game_interface.getRootPanel()) end function terminate() disconnect(g_game, 'onTextMessage', displayMessage) disconnect(g_game, 'onGameEnd', clearMessages) clearMessages() messagesPanel:destroy() end function calculateVisibleTime(text) return math.max(#text * 100, 4000) end function displayMessage(mode, text) if not g_game.isOnline() then return end local msgtype = MessageTypes[mode] if not msgtype then perror('unhandled onTextMessage message mode ' .. mode .. ': ' .. text) return end if msgtype == MessageSettings.none then return end if msgtype.consoleTab ~= nil and (msgtype.consoleOption == nil or modules.client_options.getOption(msgtype.consoleOption)) then modules.game_console.addText(text, msgtype, tr(msgtype.consoleTab)) --TODO move to game_console end if msgtype.screenTarget then local label = messagesPanel:recursiveGetChildById(msgtype.screenTarget) label:setText(text) label:setColor(msgtype.color) label:setVisible(true) removeEvent(label.hideEvent) label.hideEvent = scheduleEvent(function() label:setVisible(false) end, calculateVisibleTime(text)) end end function displayPrivateMessage(text) displayMessage(254, text) end function displayStatusMessage(text) displayMessage(MessageModes.Status, text) end function displayFailureMessage(text) displayMessage(MessageModes.Failure, text) end function displayGameMessage(text) displayMessage(MessageModes.Game, text) end function displayBroadcastMessage(text) displayMessage(MessageModes.Warning, text) end function clearMessages() for _i,child in pairs(messagesPanel:recursiveGetChildren()) do if child:getId():match('Label') then child:hide() removeEvent(child.hideEvent) end end end function LocalPlayer:onAutoWalkFail(player) modules.game_textmessage.displayFailureMessage(tr('There is no way.')) end
Fix #476
Fix #476
Lua
mit
Radseq/otclient,dreamsxin/otclient,gpedro/otclient,gpedro/otclient,dreamsxin/otclient,Radseq/otclient,Cavitt/otclient_mapgen,gpedro/otclient,dreamsxin/otclient,Cavitt/otclient_mapgen
9c8e79c9e0f4bea3cc3ab070700a2dc9ca644d3d
examples/tcp-ack-interval.lua
examples/tcp-ack-interval.lua
-- -- Measure time between ACKs and display the delay distribution. -- -- TODO: -- * Extend to handle multiple flows per client. Requires a valid -- socket descriptor in _close() hoo (currently broken) to -- differentiate between histograms (one per flow). -- * Extend to handle multiple clients (threads). Requires either a -- synchronization mechanism between threads to serialize histogram -- printing, or a data passing mechanism between worker and main -- threads. -- * Get rid of open coded histogram generation. Introduce helpers. -- local hist = {} client_socket( function (sockfd) assert( setsockopt(sockfd, SOL_SOCKET, SO_TIMESTAMPING, bit.bor(SOF_TIMESTAMPING_SOFTWARE, SOF_TIMESTAMPING_TX_ACK, SOF_TIMESTAMPING_OPT_TSONLY)) ) end ) client_recverr( function (sockfd, msg, flags) local n = recvmsg(sockfd, msg, flags) assert(n ~= -1) for _, cmsg in msg:cmsgs() do if cmsg.cmsg_level == SOL_SOCKET and cmsg.cmsg_type == SCM_TIMESTAMPING then local tss = scm_timestamping(cmsg.cmsg_data) local ts = tss.ts[0] local ts_us = (ts.sec * 1000 * 1000) + (ts.nsec / 1000) if prev_ts_us then local ival_us = ts_us - prev_ts_us local upper_us = 1 local i = 0 while ival_us >= upper_us do upper_us = upper_us * 2 i = i + 1 end hist[i] = (hist[i] or 0) + 1 end prev_ts_us = ts_us elseif (cmsg.cmsg_level == SOL_IP and cmsg.cmsg_type == IP_RECVERR) or (cmsg.cmsg_level == SOL_IPV6 and cmsg.cmsg_type == IPV6_RECVERR) then -- XXX: Check ee_errno & ee_origin end end return n end ) local function bar(val, max, width) if max == 0 then return "" end local s = "" local i = 0 while i < (width * val / max) do s = s .. "=" i = i + 1 end return s end client_close( function (sockfd) local max = 0 for _, v in ipairs(hist) do if v > max then max = v end end print() print(string.format("%10s .. %-10s: %-10s |%-40s|", ">=", "< [us]", "Count", "Distribution")) print() local lower_us = 0 local upper_us = 1 for _, v in ipairs(hist) do print(string.format("%10d -> %-10d: %-10d |%-40s|", lower_us, upper_us, v, bar(v, max, 40))) lower_us = upper_us upper_us = upper_us * 2 end print() end )
-- -- Measure time between ACKs and display the delay distribution. -- -- TODO: -- * Get rid of open coded histogram generation. Introduce helpers. -- -- Per-thread base-2 logarithmic histogram of interval lengths in -- microseconds (us) between consecutive TCP ACKs. Keyed by the upper -- bound (exclusive) of the bucket. That is: -- -- hist[2^0] = # of measured intervals between [0, 1) us -- hist[2^1] = # of measured intervals between [1, 2) us -- ... -- hist[2^N] = # of measured intervals between [2^N, 2^N+1) us -- local hist = collect({}) -- Timestamp in microseconds of last TCP ACK. Keyed by socket FD. local sock_last_ts = {} client_socket( function (sockfd) assert( setsockopt(sockfd, SOL_SOCKET, SO_TIMESTAMPING, bit.bor(SOF_TIMESTAMPING_SOFTWARE, SOF_TIMESTAMPING_TX_ACK, SOF_TIMESTAMPING_OPT_TSONLY)) ) end ) client_recverr( function (sockfd, msg, flags) local n = recvmsg(sockfd, msg, flags) assert(n ~= -1) for _, cmsg in msg:cmsgs() do if cmsg.cmsg_level == SOL_SOCKET and cmsg.cmsg_type == SCM_TIMESTAMPING then -- Anciallary message carries a pointer to an scm_timestamping -- structure. We are interested in the fist timestemp in it. -- -- struct scm_timestamping { -- struct timespec ts[3]; -- }; -- local tss = scm_timestamping(cmsg.cmsg_data) local tv = tss.ts[0] local ts = (tv.sec * 1000 * 1000) + (tv.nsec / 1000) local last_ts = sock_last_ts[sockfd] if last_ts ~= nil then local ival = ts - last_ts local upper = 1 -- 2^0 while ival >= upper do upper = upper * 2 end hist[upper] = (hist[upper] or 0) + 1 end sock_last_ts[sockfd] = ts elseif (cmsg.cmsg_level == SOL_IP and cmsg.cmsg_type == IP_RECVERR) or (cmsg.cmsg_level == SOL_IPV6 and cmsg.cmsg_type == IPV6_RECVERR) then -- XXX: Check ee_errno & ee_origin end end return n end ) run(); local function bar(val, max, width) if max == 0 then return "" end local s = "" local i = 0 while i < (width * val / max) do s = s .. "=" i = i + 1 end return s end local function print_hist(h) local max = 0 for _, v in pairs(h) do if v > max then max = v end end print('\n', string.format("%10s .. %-10s: %-10s |%-40s|", ">=", "< [us]", "Count", "Distribution"), '\n') local lower_us = 0 local upper_us = 1 while lower_us < table.maxn(h) do local count = (h[upper_us] or 0) print(string.format("%10d -> %-10d: %-10d |%-40s|", lower_us, upper_us, count, bar(count, max, 40))) lower_us = upper_us upper_us = upper_us * 2 end print() end -- Print per-thread histograms for i, h in ipairs(hist) do print("Thread", i) print_hist(h) end -- Print aggregate (sum of all) histogram hist_sum = {} for _, h in ipairs(hist) do for k, v in pairs(h) do hist_sum[k] = (hist_sum[k] or 0) + v end end print("All threads (summed)") print_hist(hist_sum)
examples: Fix and update tcp-ack-interval example
examples: Fix and update tcp-ack-interval example Fix botched reporting of histogram bucket counts. Logic did not take into account that ipairs() doesn't work with non-sequential indices. Switch to keying histogram buckets by their upper bound to avoid any pitfalls. Use collect() to copy histograms from worker threads to the main thread. Display per-thread as well as one aggregated histogram. Various renames, comments and other minor changes for readability.
Lua
apache-2.0
jsitnicki/rushit,jsitnicki/rushit
48b98f0c099dc621e1f93cccf9a9e03ff75649b6
spec/install_spec.lua
spec/install_spec.lua
local test_env = require("test/test_environment") local lfs = require("lfs") local run = test_env.run local testing_paths = test_env.testing_paths local env_variables = test_env.env_variables test_env.unload_luarocks() local extra_rocks = { "/cprint-0.1-2.src.rock", "/cprint-0.1-2.rockspec", "/lpeg-0.12-1.src.rock", "/luasec-0.6-1.rockspec", "/luassert-1.7.0-1.src.rock", "/luasocket-3.0rc1-1.src.rock", "/luasocket-3.0rc1-1.rockspec", "/lxsh-0.8.6-2.src.rock", "/lxsh-0.8.6-2.rockspec", "/say-1.2-1.src.rock", "/say-1.0-1.src.rock", "/wsapi-1.6-1.src.rock" } describe("LuaRocks install tests #blackbox #b_install", function() before_each(function() test_env.setup_specs(extra_rocks) end) describe("LuaRocks install - basic tests", function() it("LuaRocks install with no flags/arguments", function() assert.is_false(run.luarocks_bool("install")) end) it("LuaRocks install with invalid argument", function() assert.is_false(run.luarocks_bool("install invalid")) end) it("LuaRocks install invalid patch", function() assert.is_false(run.luarocks_bool("install " .. testing_paths.testing_dir .. "/testfiles/invalid_patch-0.1-1.rockspec")) end) it("LuaRocks install invalid rock", function() assert.is_false(run.luarocks_bool("install \"invalid.rock\" ")) end) it("LuaRocks install with local flag as root", function() assert.is_false(run.luarocks_bool("install --local luasocket", { USER = "root" } )) end) it("LuaRocks install not a zip file", function() assert.is_false(run.luarocks_bool("install " .. testing_paths.testing_dir .. "/testfiles/not_a_zipfile-1.0-1.src.rock")) end) it("LuaRocks install only-deps of lxsh show there is no lxsh", function() assert.is_true(run.luarocks_bool("install lxsh 0.8.6-2 --only-deps")) assert.is_false(run.luarocks_bool("show lxsh")) end) it("LuaRocks install incompatible architecture", function() assert.is_false(run.luarocks_bool("install \"foo-1.0-1.impossible-x86.rock\" ")) end) it("LuaRocks install wsapi with bin", function() run.luarocks_bool("install wsapi") end) it("LuaRocks install luasec and show luasocket (dependency)", function() assert.is_true(run.luarocks_bool("install luasec")) assert.is_true(run.luarocks_bool("show luasocket")) end) end) describe("LuaRocks install - more complex tests", function() it('LuaRocks install luasec with skipping dependency checks', function() run.luarocks(" install luasec --nodeps") assert.is_true(run.luarocks_bool("show luasec")) if env_variables.TYPE_TEST_ENV == "minimal" then assert.is_false(run.luarocks_bool("show luasocket")) assert.is.falsy(lfs.attributes(testing_paths.testing_sys_tree .. "/lib/luarocks/rocks/luasocket")) end assert.is.truthy(lfs.attributes(testing_paths.testing_sys_tree .. "/lib/luarocks/rocks/luasec")) end) it("LuaRocks install only-deps of luasocket packed rock", function() local output = run.luarocks("install --only-deps " .. testing_paths.testing_cache .. "/luasocket-3.0rc1-1." .. test_env.platform .. ".rock") assert.are.same(output, "Successfully installed dependencies for luasocket 3.0rc1-1") end) it("LuaRocks install binary rock of cprint", function() assert.is_true(run.luarocks_bool("build --pack-binary-rock cprint")) assert.is_true(run.luarocks_bool("install cprint-0.1-2." .. test_env.platform .. ".rock")) assert.is_true(os.remove("cprint-0.1-2." .. test_env.platform .. ".rock")) end) it("LuaRocks install reinstall", function() assert.is_true(run.luarocks_bool("install " .. testing_paths.testing_cache .. "/luasocket-3.0rc1-1." .. test_env.platform .. ".rock")) assert.is_true(run.luarocks_bool("install --deps-mode=none " .. testing_paths.testing_cache .. "/luasocket-3.0rc1-1." .. test_env.platform .. ".rock")) end) end) describe("New install functionality based on pull request 552", function() it("LuaRocks install break dependencies warning", function() assert.is_true(run.luarocks_bool("install say 1.2")) assert.is_true(run.luarocks_bool("install luassert")) assert.is_true(run.luarocks_bool("install say 1.0")) assert.is.truthy(lfs.attributes(testing_paths.testing_sys_tree .. "/lib/luarocks/rocks/say/1.2-1")) end) it("LuaRocks install break dependencies force", function() assert.is_true(run.luarocks_bool("install say 1.2")) assert.is_true(run.luarocks_bool("install luassert")) local output = run.luarocks("install --force say 1.0") assert.is.truthy(output:find("Checking stability of dependencies")) assert.is.falsy(lfs.attributes(testing_paths.testing_sys_tree .. "/lib/luarocks/rocks/say/1.2-1")) end) it("LuaRocks install break dependencies force fast", function() assert.is_true(run.luarocks_bool("install say 1.2")) assert.is_true(run.luarocks_bool("install luassert")) assert.is.truthy(lfs.attributes(testing_paths.testing_sys_tree .. "/lib/luarocks/rocks/say/1.2-1")) local output = run.luarocks("install --force-fast say 1.0") assert.is.falsy(output:find("Checking stability of dependencies")) assert.is.truthy(lfs.attributes(testing_paths.testing_sys_tree .. "/lib/luarocks/rocks/say/1.0-1")) end) end) end)
local test_env = require("test/test_environment") local lfs = require("lfs") local run = test_env.run local testing_paths = test_env.testing_paths local env_variables = test_env.env_variables test_env.unload_luarocks() local extra_rocks = { "/cprint-0.1-2.src.rock", "/cprint-0.1-2.rockspec", "/lpeg-0.12-1.src.rock", "/luasec-0.6-1.rockspec", "/luassert-1.7.0-1.src.rock", "/luasocket-3.0rc1-1.src.rock", "/luasocket-3.0rc1-1.rockspec", "/lxsh-0.8.6-2.src.rock", "/lxsh-0.8.6-2.rockspec", "/say-1.2-1.src.rock", "/say-1.0-1.src.rock", "/wsapi-1.6-1.src.rock" } describe("LuaRocks install tests #blackbox #b_install", function() before_each(function() test_env.setup_specs(extra_rocks) end) describe("LuaRocks install - basic tests", function() it("LuaRocks install with no flags/arguments", function() assert.is_false(run.luarocks_bool("install")) end) it("LuaRocks install with invalid argument", function() assert.is_false(run.luarocks_bool("install invalid")) end) it("LuaRocks install invalid patch", function() assert.is_false(run.luarocks_bool("install " .. testing_paths.testing_dir .. "/testfiles/invalid_patch-0.1-1.rockspec")) end) it("LuaRocks install invalid rock", function() assert.is_false(run.luarocks_bool("install \"invalid.rock\" ")) end) it("LuaRocks install with local flag as root", function() assert.is_false(run.luarocks_bool("install --local luasocket", { USER = "root" } )) end) it("LuaRocks install not a zip file", function() assert.is_false(run.luarocks_bool("install " .. testing_paths.testing_dir .. "/testfiles/not_a_zipfile-1.0-1.src.rock")) end) it("LuaRocks install only-deps of lxsh show there is no lxsh", function() assert.is_true(run.luarocks_bool("install lxsh 0.8.6-2 --only-deps")) assert.is_false(run.luarocks_bool("show lxsh")) end) it("LuaRocks install incompatible architecture", function() assert.is_false(run.luarocks_bool("install \"foo-1.0-1.impossible-x86.rock\" ")) end) it("LuaRocks install wsapi with bin", function() run.luarocks_bool("install wsapi") end) it("LuaRocks install luasec and show luasocket (dependency)", function() assert.is_true(run.luarocks_bool("install luasec")) assert.is_true(run.luarocks_bool("show luasocket")) end) end) describe("LuaRocks install - more complex tests", function() it('LuaRocks install luasec with skipping dependency checks', function() run.luarocks(" install luasec --nodeps") assert.is_true(run.luarocks_bool("show luasec")) if env_variables.TYPE_TEST_ENV == "minimal" then assert.is_false(run.luarocks_bool("show luasocket")) assert.is.falsy(lfs.attributes(testing_paths.testing_sys_tree .. "/lib/luarocks/rocks/luasocket")) end assert.is.truthy(lfs.attributes(testing_paths.testing_sys_tree .. "/lib/luarocks/rocks/luasec")) end) it("LuaRocks install only-deps of luasocket packed rock", function() assert.is_true(run.luarocks_bool("build --pack-binary-rock luasocket")) local output = run.luarocks("install --only-deps " .. "luasocket-3.0rc1-1." .. test_env.platform .. ".rock") assert.are.same(output, "Successfully installed dependencies for luasocket 3.0rc1-1") assert.is_true(os.remove("luasocket-3.0rc1-1." .. test_env.platform .. ".rock")) end) it("LuaRocks install reinstall", function() assert.is_true(run.luarocks_bool("build --pack-binary-rock luasocket")) assert.is_true(run.luarocks_bool("install " .. "luasocket-3.0rc1-1." .. test_env.platform .. ".rock")) assert.is_true(run.luarocks_bool("install --deps-mode=none " .. "luasocket-3.0rc1-1." .. test_env.platform .. ".rock")) assert.is_true(os.remove("luasocket-3.0rc1-1." .. test_env.platform .. ".rock")) end) it("LuaRocks install binary rock of cprint", function() assert.is_true(run.luarocks_bool("build --pack-binary-rock cprint")) assert.is_true(run.luarocks_bool("install cprint-0.1-2." .. test_env.platform .. ".rock")) assert.is_true(os.remove("cprint-0.1-2." .. test_env.platform .. ".rock")) end) end) describe("New install functionality based on pull request 552", function() it("LuaRocks install break dependencies warning", function() assert.is_true(run.luarocks_bool("install say 1.2")) assert.is_true(run.luarocks_bool("install luassert")) assert.is_true(run.luarocks_bool("install say 1.0")) assert.is.truthy(lfs.attributes(testing_paths.testing_sys_tree .. "/lib/luarocks/rocks/say/1.2-1")) end) it("LuaRocks install break dependencies force", function() assert.is_true(run.luarocks_bool("install say 1.2")) assert.is_true(run.luarocks_bool("install luassert")) local output = run.luarocks("install --force say 1.0") assert.is.truthy(output:find("Checking stability of dependencies")) assert.is.falsy(lfs.attributes(testing_paths.testing_sys_tree .. "/lib/luarocks/rocks/say/1.2-1")) end) it("LuaRocks install break dependencies force fast", function() assert.is_true(run.luarocks_bool("install say 1.2")) assert.is_true(run.luarocks_bool("install luassert")) assert.is.truthy(lfs.attributes(testing_paths.testing_sys_tree .. "/lib/luarocks/rocks/say/1.2-1")) local output = run.luarocks("install --force-fast say 1.0") assert.is.falsy(output:find("Checking stability of dependencies")) assert.is.truthy(lfs.attributes(testing_paths.testing_sys_tree .. "/lib/luarocks/rocks/say/1.0-1")) end) end) end)
Fix of luasocket binary rock tests
Fix of luasocket binary rock tests
Lua
mit
tarantool/luarocks,xpol/luarocks,xpol/luavm,keplerproject/luarocks,xpol/luainstaller,xpol/luavm,keplerproject/luarocks,xpol/luavm,luarocks/luarocks,xpol/luarocks,keplerproject/luarocks,luarocks/luarocks,tarantool/luarocks,xpol/luainstaller,xpol/luarocks,xpol/luavm,xpol/luavm,tarantool/luarocks,keplerproject/luarocks,luarocks/luarocks,robooo/luarocks,xpol/luainstaller,xpol/luarocks,robooo/luarocks,xpol/luainstaller,robooo/luarocks,robooo/luarocks
0fca111e4199960aabfadac953b07d2fa0f1e8a1
plugins/mod_watchregistrations.lua
plugins/mod_watchregistrations.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 host = module:get_host(); local registration_watchers = module:get_option("registration_watchers", module:get_option("admins", {})); local registration_notification = module:get_option("registration_notification", "User $username just registered on $host from $ip"); local st = require "util.stanza"; module:hook("user-registered", function (user) module:log("debug", "Notifying of new registration"); local message = st.message{ type = "chat", from = host } :tag("body") :text(registration_notification:gsub("%$(%w+)", function (v) return user[v] or user.session and user.session[v] or nil; end)); for _, jid in ipairs(registration_watchers) do module:log("debug", "Notifying %s", jid); message.attr.to = jid; core_route_stanza(hosts[host], message); end end);
-- 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 host = module:get_host(); local jid_prep = require "util.jid".prep; local registration_watchers = module:get_option_set("registration_watchers", module:get_option("admins", {})) / jid_prep; local registration_notification = module:get_option("registration_notification", "User $username just registered on $host from $ip"); local st = require "util.stanza"; module:hook("user-registered", function (user) module:log("debug", "Notifying of new registration"); local message = st.message{ type = "chat", from = host } :tag("body") :text(registration_notification:gsub("%$(%w+)", function (v) return user[v] or user.session and user.session[v] or nil; end)); for jid in registration_watchers do module:log("debug", "Notifying %s", jid); message.attr.to = jid; core_route_stanza(hosts[host], message); end end);
mod_watchregistrations: Convert JID list to a set, and prep before use to fix traceback on invalid JIDs (thanks sMi)
mod_watchregistrations: Convert JID list to a set, and prep before use to fix traceback on invalid JIDs (thanks sMi)
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
23d89250cd2941d817a3f3aaffb4ae303af8f416
catalog.d/ezoe.lua
catalog.d/ezoe.lua
nyagos.on_command_not_found = function(args) nyagos.writerr(args[0]..": コマンドではない。\n") return true end local cd = nyagos.alias.cd nyagos.alias.cd = function(args) local success=true for i=1,#args do local dir=args[i] if dir:sub(1,1) ~= "-" and not dir:match("%.[lL][nN][kK]$") then local nul=nyagos.pathjoin(dir,"nul") local fd=io.open(nul) if fd then fd:close() else nyagos.writerr(dir..": ディレクトリではない。\n") success = false end end end if success then if cd then cd(args) else args[0] = "__cd__" nyagos.exec(args) end end end -- vim:set fenc=utf8 --
nyagos.on_command_not_found = function(args) nyagos.writerr(args[0]..": コマンドではない。\n") return true end if not nyagos.ole then local status status, nyagos.ole = pcall(require,"nyole") if not status then nyagos.ole = nil end end if nyagos.ole then local fsObj = nyagos.ole.create_object_utf8("Scripting.FileSystemObject") local cd = nyagos.alias.cd nyagos.alias.cd = function(args) local success=true for i=1,#args do local dir=args[i] if dir:sub(1,1) ~= "-" and not dir:match("%.[lL][nN][kK]$") then if not fsObj:FolderExists(dir) then nyagos.writerr(dir..": ディレクトリではない。\n") return end end end if cd then cd(args) else args[0] = "__cd__" nyagos.exec(args) end end end -- vim:set fenc=utf8 --
Fixed ezoe.lua did not work when the parameter is not a folder but a file.
Fixed ezoe.lua did not work when the parameter is not a folder but a file.
Lua
bsd-3-clause
kissthink/nyagos,hattya/nyagos,tyochiai/nyagos,hattya/nyagos,hattya/nyagos,kissthink/nyagos,tsuyoshicho/nyagos,zetamatta/nyagos,kissthink/nyagos,nocd5/nyagos
6ecfda173e631af77b20d6d5dce8f68e374f0af6
hammerspoon/init.lua
hammerspoon/init.lua
-- A global variable for the Hyper Mode k = hs.hotkey.modal.new({}, "F17") -- Move Windows ------------------------------------------------------------------------------- -- Mission Control k:bind({}, 'up', nil, function() hs.eventtap.keyStroke({"cmd","alt","ctrl"}, 'F13') end) -- Move to Left Screen k:bind({}, 'left', nil, function() local win = hs.window.focusedWindow() win:moveOneScreenWest(false, true); end) -- Move to Right Screen k:bind({}, 'right', nil, function() local win = hs.window.focusedWindow() win:moveOneScreenEast(false, true); end) -- Resize Windows ------------------------------------------------------------------------------- hs.window.animationDuration = 0 -- 0 - Maximize k:bind({}, '0', nil, function() local win = hs.window.focusedWindow() win:maximize() k.triggered = true end) -- 9 - Browser k:bind({}, '9', nil, function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.w = max.w * 0.8 f.y = max.y f.h = max.h win:setFrame(f) win:centerOnScreen(nil, true) k.triggered = true end) -- 8 - Email k:bind({}, '8', nil, function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.w = max.w * 0.8 f.h = max.h * 0.8 win:setFrame(f) win:centerOnScreen(nil, true) k.triggered = true end) -- 7 - Finder k:bind({}, '7', nil, function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.w = max.w * 0.6 f.h = max.h * 0.6 win:setFrame(f) win:centerOnScreen(nil, true) k.triggered = true end) -- 6 - Right k:bind({}, '6', nil, function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x + (max.w / 2) f.y = max.y f.w = max.w / 2 f.h = max.h win:setFrame(f) k.triggered = true end) -- 5 - Left k:bind({}, '5', nil, function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x f.y = max.y f.w = max.w / 2 f.h = max.h win:setFrame(f) k.triggered = true end) -- Shortcut to reload config ofun = function() hs.reload() hs.notify.new({title="Hammerspoon", informativeText="Config Reloaded"}):send() k.triggered = true end k:bind({}, 'r', nil, ofun) -- Launch Apps launch = function(appname) hs.application.launchOrFocus(appname) k.triggered = true end -- Single keybinding for app launch singleapps = { {'u', 'SourceTree'}, {'j', 'Visual Studio Code'}, {'n', 'iTerm'}, {'i', 'FirefoxDeveloperEdition'}, {'k', 'Google Chrome'}, {'o', 'Slack'}, {'l', 'Wavebox'}, {'.', 'Wunderlist'}, {'h', 'Finder'}, {'p', 'Spotify'}, {';', 'Fantastical 2'} } for i, app in ipairs(singleapps) do k:bind({}, app[1], function() launch(app[2]); end) end -- Enter Hyper Mode when F18 (Hyper/Capslock) is pressed pressedF18 = function() k.triggered = false k:enter() end -- Leave Hyper Mode when F18 (Hyper/Capslock) is pressed, -- send ESCAPE if no other keys are pressed. releasedF18 = function() k:exit() if not k.triggered then hs.eventtap.keyStroke({}, 'ESCAPE') end end -- Bind the Hyper key f18 = hs.hotkey.bind({}, 'F18', pressedF18, releasedF18)
-- A global variable for the Hyper Mode k = hs.hotkey.modal.new({}, "F17") -- Move Windows ------------------------------------------------------------------------------- -- Mission Control k:bind({}, 'up', nil, function() hs.eventtap.keyStroke({"cmd","alt","ctrl"}, 'F13') end) -- Move to Left Screen k:bind({}, 'left', nil, function() local win = hs.window.focusedWindow() win:moveOneScreenWest(false, true); end) -- Move to Right Screen k:bind({}, 'right', nil, function() local win = hs.window.focusedWindow() win:moveOneScreenEast(false, true); end) -- Resize Windows ------------------------------------------------------------------------------- hs.window.animationDuration = 0 -- 0 - Maximize k:bind({}, '0', nil, function() local win = hs.window.focusedWindow() win:maximize() k.triggered = true end) -- 9 - "Browser" Size k:bind({}, '9', nil, function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() local screenratio = max.w / max.h local widthratio = 1 if screenratio > 2 then widthratio = 0.5 else widthratio = 0.8 end f.w = max.w * widthratio f.y = max.y f.h = max.h win:setFrame(f) win:centerOnScreen(nil, true) k.triggered = true end) -- 8 - "Email" Size k:bind({}, '8', nil, function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() local screenratio = max.w / max.h local widthratio = 1 if screenratio > 2 then widthratio = 0.5 else widthratio = 0.8 end f.w = max.w * widthratio f.h = max.h * 0.8 win:setFrame(f) win:centerOnScreen(nil, true) k.triggered = true end) -- 7 - "Finder" Size k:bind({}, '7', nil, function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.h = max.h * 0.6 f.w = f.h * 1.5 win:setFrame(f) win:centerOnScreen(nil, true) k.triggered = true end) -- 6 - Right k:bind({}, '6', nil, function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x + (max.w / 2) f.y = max.y f.w = max.w / 2 f.h = max.h win:setFrame(f) k.triggered = true end) -- 5 - Left k:bind({}, '5', nil, function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x f.y = max.y f.w = max.w / 2 f.h = max.h win:setFrame(f) k.triggered = true end) -- Shortcut to reload config ofun = function() hs.reload() hs.notify.new({title="Hammerspoon", informativeText="Config Reloaded"}):send() k.triggered = true end k:bind({}, 'r', nil, ofun) -- Launch Apps launch = function(appname) hs.application.launchOrFocus(appname) k.triggered = true end -- Single keybinding for app launch singleapps = { {'u', 'gitup'}, {'j', 'Visual Studio Code'}, {'n', 'iTerm'}, {'i', 'Discord'}, {'k', 'Google Chrome'}, {'o', 'Slack'}, {'l', 'Wavebox'}, {'.', 'Wunderlist'}, {'h', 'Finder'}, {'p', 'Spotify'}, {';', 'Sublime Text'} } for i, app in ipairs(singleapps) do k:bind({}, app[1], function() launch(app[2]); end) end -- Enter Hyper Mode when F18 (Hyper/Capslock) is pressed pressedF18 = function() k.triggered = false k:enter() end -- Leave Hyper Mode when F18 (Hyper/Capslock) is pressed, -- send ESCAPE if no other keys are pressed. releasedF18 = function() k:exit() if not k.triggered then hs.eventtap.keyStroke({}, 'ESCAPE') end end -- Bind the Hyper key f18 = hs.hotkey.bind({}, 'F18', pressedF18, releasedF18)
fix window sizes for ultrawide
fix window sizes for ultrawide
Lua
mit
francoiscote/dotfiles,francoiscote/dotfiles
8cb54dd8badc3f8696bc66d47eee3baf6d4d3ef3
commands/build.lua
commands/build.lua
zpm.build.commands = {} zpm.build.rcommands = {} function zpm.build.commands.extractdir( targets, prefix ) prefix = prefix or "./" if type(targets) ~= "table" then targets = {targets} end for i, target in ipairs(targets) do local zipFile = path.join( zpm.temp, "submodule.zip" ) local targetPath = path.join( zpm.build._currentExportPath, prefix, target ) local depPath = path.join( zpm.build._currentDependency.dependencyPath, target ) if path.getabsolute(depPath):contains( path.getabsolute(zpm.build._currentDependency.dependencyPath) ) then if not _OPTIONS["ignore-updates"] or not os.isdir( targetPath ) then for _, file in ipairs( os.matchfiles( path.join( depPath, "**" ) ) ) do local ftarget = path.join( targetPath, path.getrelative( depPath, file ) ) if ftarget:contains( ".git" ) == false then local ftargetDir = path.getdirectory( ftarget ) if not os.isdir( ftargetDir ) then zpm.assert( os.mkdir( ftargetDir ), "Could not create directory '%s'!", ftargetDir ) end if ftarget:len() <= 255 then os.copyfile( file, ftarget ) zpm.assert( os.isfile(ftarget), "Could not make file '%s'!", ftarget ) else warningf( "Failed to copy '%s' due to long path length!", ftarget ) end end end end end end end function zpm.build.commands.option( opt ) zpm.assert(zpm.build._currentDependency.options ~= nil, "Option '%s' does not exist!", opt) zpm.assert(zpm.build._currentDependency.options[opt] ~= nil, "Option '%s' does not exist!", opt) return zpm.build._currentDependency.options[opt] end function zpm.build.commands.setting( opt ) zpm.assert(zpm.config.settings ~= nil, "Setting '%s' does not exist!", opt) zpm.assert(zpm.config.settings[opt] ~= nil, "Setting '%s' does not exist!", opt) return zpm.config.settings[opt] end function zpm.build.commands.export( commands ) local name = project().name local parent = zpm.build._currentDependency.projects[name].export local currExp = zpm.build._currentExportPath local currDep = zpm.build._currentDependency zpm.build._currentDependency.projects[name].export = function() if parent ~= nil then parent() end local old = zpm.build._currentExportPath local oldDep = zpm.build._currentDependency zpm.build._currentExportPath = currExp zpm.build._currentDependency = currDep zpm.sandbox.run( commands, {env = zpm.build.getEnv()}) zpm.build._currentExportPath = old zpm.build._currentDependency = oldDep end zpm.sandbox.run( commands, {env = zpm.build.getEnv()}) end function zpm.build.commands.uses( proj ) if type(proj) ~= "table" then proj = {proj} end local cname = project().name if zpm.build._currentDependency.projects[cname] == nil then zpm.build._currentDependency.projects[cname] = {} end if zpm.build._currentDependency.projects[cname].uses == nil then zpm.build._currentDependency.projects[cname].uses = {} end if zpm.build._currentDependency.projects[cname].packages == nil then zpm.build._currentDependency.projects[cname].packages = {} end for _, p in ipairs(proj) do if p:contains( "/" ) then local package = zpm.build.findProject( p ) if table.contains( zpm.build._currentDependency.projects[cname].packages, package ) == false then table.insert( zpm.build._currentDependency.projects[cname].packages, package ) end else local name = zpm.build.getProjectName( p, zpm.build._currentDependency.fullName, zpm.build._currentDependency.version ) if table.contains( zpm.build._currentDependency.projects[cname].uses, name ) == false then table.insert( zpm.build._currentDependency.projects[cname].uses, name ) end end end end function zpm.build.rcommands.project( proj ) local name = zpm.build.getProjectName( proj, zpm.build._currentDependency.fullName, zpm.build._currentDependency.version ) project( name ) location( zpm.install.getExternDirectory() ) targetdir( zpm.build._currentTargetPath ) objdir( zpm.build._currentObjPath ) warnings "Off" if zpm.build._currentDependency.projects == nil then zpm.build._currentDependency.projects = {} end if zpm.build._currentDependency.projects[name] == nil then zpm.build._currentDependency.projects[name] = {} end end function zpm.build.rcommands.dependson( depdson ) if type(depdson) ~= "table" then depdson = {depdson} end for _, p in ipairs(depdson) do local dep = zpm.build._currentDependency dependson( zpm.build.getProjectName( p, dep.fullName, dep.version ) ) end end function zpm.build.rcommands.kind( knd ) local name = project().name zpm.build._currentDependency.projects[name].kind = knd kind( knd ) end function zpm.build.rcommands.filter( ... ) filter( ... ) end
zpm.build.commands = {} zpm.build.rcommands = {} function zpm.build.commands.extractdir( targets, prefix ) prefix = prefix or "./" if type(targets) ~= "table" then targets = {targets} end for i, target in ipairs(targets) do local zipFile = path.join( zpm.temp, "submodule.zip" ) local targetPath = path.join( zpm.build._currentExportPath, prefix, target ) local depPath = path.join( zpm.build._currentDependency.dependencyPath, target ) if path.getabsolute(depPath):contains( path.getabsolute(zpm.build._currentDependency.dependencyPath) ) then if not _OPTIONS["ignore-updates"] or not os.isdir( targetPath ) then for _, file in ipairs( os.matchfiles( path.join( depPath, "**" ) ) ) do local ftarget = path.join( targetPath, path.getrelative( depPath, file ) ) if ftarget:contains( ".git" ) == false then local ftargetDir = path.getdirectory( ftarget ) if not os.isdir( ftargetDir ) then zpm.assert( os.mkdir( ftargetDir ), "Could not create directory '%s'!", ftargetDir ) end if ftarget:len() <= 255 then os.copyfile( file, ftarget ) zpm.assert( os.isfile(ftarget), "Could not make file '%s'!", ftarget ) else warningf( "Failed to copy '%s' due to long path length!", ftarget ) end end end end end end end function zpm.build.commands.option( opt ) zpm.assert(zpm.build._currentDependency.options ~= nil, "Option '%s' does not exist!", opt) zpm.assert(zpm.build._currentDependency.options[opt] ~= nil, "Option '%s' does not exist!", opt) return zpm.build._currentDependency.options[opt] end function zpm.build.commands.setting( opt ) zpm.assert(zpm.config.settings ~= nil, "Setting '%s' does not exist!", opt) zpm.assert(zpm.config.settings[opt] ~= nil, "Setting '%s' does not exist!", opt) return zpm.config.settings[opt] end function zpm.build.commands.export( commands ) local name = project().name local parent = zpm.build._currentDependency.projects[name].export local currExp = zpm.build._currentExportPath local currDep = zpm.build._currentDependency zpm.build._currentDependency.projects[name].export = function() if parent ~= nil then parent() end local old = zpm.build._currentExportPath local oldDep = zpm.build._currentDependency zpm.build._currentExportPath = currExp zpm.build._currentDependency = currDep zpm.sandbox.run( commands, {env = zpm.build.getEnv()}) zpm.build._currentExportPath = old zpm.build._currentDependency = oldDep end zpm.sandbox.run( commands, {env = zpm.build.getEnv()}) end function zpm.build.commands.uses( proj ) if type(proj) ~= "table" then proj = {proj} end local cname = project().name if zpm.build._currentDependency.projects[cname] == nil then zpm.build._currentDependency.projects[cname] = {} end if zpm.build._currentDependency.projects[cname].uses == nil then zpm.build._currentDependency.projects[cname].uses = {} end if zpm.build._currentDependency.projects[cname].packages == nil then zpm.build._currentDependency.projects[cname].packages = {} end for _, p in ipairs(proj) do if p:contains( "/" ) then local package = zpm.build.findProject( p ) if table.contains( zpm.build._currentDependency.projects[cname].packages, package ) == false then table.insert( zpm.build._currentDependency.projects[cname].packages, package ) end else local name = zpm.build.getProjectName( p, zpm.build._currentDependency.fullName, zpm.build._currentDependency.version ) if table.contains( zpm.build._currentDependency.projects[cname].uses, name ) == false then table.insert( zpm.build._currentDependency.projects[cname].uses, name ) end end end end function zpm.build.rcommands.project( proj ) local name = zpm.build.getProjectName( proj, zpm.build._currentDependency.fullName, zpm.build._currentDependency.version ) project( name ) if _ACTION:contains( "vs" ) then dummyFile = path.join( zpm.install.getExternDirectory(), "dummy.cpp" ) os.executef( "{TOUCH} %s", dummyFile ) files(dummyFile) end location( zpm.install.getExternDirectory() ) targetdir( zpm.build._currentTargetPath ) objdir( zpm.build._currentObjPath ) warnings "Off" if zpm.build._currentDependency.projects == nil then zpm.build._currentDependency.projects = {} end if zpm.build._currentDependency.projects[name] == nil then zpm.build._currentDependency.projects[name] = {} end end function zpm.build.rcommands.dependson( depdson ) if type(depdson) ~= "table" then depdson = {depdson} end for _, p in ipairs(depdson) do local dep = zpm.build._currentDependency dependson( zpm.build.getProjectName( p, dep.fullName, dep.version ) ) end end function zpm.build.rcommands.kind( knd ) local name = project().name zpm.build._currentDependency.projects[name].kind = knd kind( knd ) end function zpm.build.rcommands.filter( ... ) filter( ... ) end
Staticlib fix for headeronly builds
Staticlib fix for headeronly builds
Lua
mit
Zefiros-Software/ZPM
14b185529bf345693aab48105482e129b082aed5
test/dev-app/tests/unit/access.lua
test/dev-app/tests/unit/access.lua
local test = require "sailor.test" local access = require "sailor.access" local User = require "sailor.model"('user') local fixtures = require "tests.fixtures.user" or {} describe("Testing #UserController", function() local users setup(function() users = test.load_fixtures('user') end) it("should know no one has logged in", function() assert.is_true(access.is_guest()) end) it("should not login with wrong pass", function() assert.is_false(User.authenticate(fixtures[1].username,"dummy",true)) end) it("should not login with wrong username", function() assert.is_false(User.authenticate("meh",fixtures[1].password,false)) end) it("should not login with default settings", function() assert.is_false(access.login('admin','demo')) end) it("should login", function() assert.is_true(User.authenticate(fixtures[1].username,fixtures[1].password,false)) end) it("should know the user is logged in", function() assert.is_false(access.is_guest()) end) it("should logout", function() assert.is_true(User.logout()) end) it("should know the user is logged out", function() assert.is_true(access.is_guest()) end) it("should login with encrypted pass", function() local u = User:new() u.username = 'Hermione' local raw_pass = 'freeelf54' u.password = access.hash(u.username,raw_pass) u:save(false) assert.is_true(User.authenticate(u.username,raw_pass,true)) assert.is_false(access.is_guest()) User.logout() end) it("should with default settings", function() access.settings({model = false, hashing = false, default_login = 'admin', default_password = 'demo'}) assert.is_true(access.login('admin','demo')) assert.is_false(access.is_guest()) assert.is_true(User.logout()) assert.is_true(access.is_guest()) end) it("should not login with default settings", function() assert.is_false(access.login('admin','demon')) assert.is_true(access.is_guest()) end) end)
local test = require "sailor.test" local access = require "sailor.access" local User = require "sailor.model"('user') local fixtures = require "tests.fixtures.user" or {} describe("Testing #UserController", function() local users it("should know no one has logged in", function() assert.is_true(access.is_guest()) end) it("should not login with wrong pass", function() assert.is_false(User.authenticate(fixtures[1].username,"dummy",true)) end) it("should not login with wrong username", function() assert.is_false(User.authenticate("meh",fixtures[1].password,false)) end) it("should not login with default settings", function() assert.is_false(access.login('admin','demo')) end) it("should login", function() assert.is_true(User.authenticate(fixtures[1].username,fixtures[1].password,false)) end) it("should know the user is logged in", function() assert.is_false(access.is_guest()) end) it("should logout", function() assert.is_true(User.logout()) end) it("should know the user is logged out", function() assert.is_true(access.is_guest()) end) it("should login with encrypted pass", function() local u = User:new() u.username = 'Hermione' local raw_pass = 'freeelf54' u.password = access.hash(u.username,raw_pass) u:save(false) assert.is_true(User.authenticate(u.username,raw_pass,true)) assert.is_false(access.is_guest()) User.logout() u:delete() end) it("should with default settings", function() access.settings({model = false, hashing = false, default_login = 'admin', default_password = 'demo'}) assert.is_true(access.login('admin','demo')) assert.is_false(access.is_guest()) assert.is_true(User.logout()) assert.is_true(access.is_guest()) end) it("should not login with default settings", function() assert.is_false(access.login('admin','demon')) assert.is_true(access.is_guest()) end) end)
tests(access): Remove unnecessary fixture reload
tests(access): Remove unnecessary fixture reload
Lua
mit
mpeterv/sailor,mpeterv/sailor,Etiene/sailor,sailorproject/sailor,Etiene/sailor
25a1bf5c7f81e9f6bab578c5b60ad99c5ac1ea60
src/cosy/util/proxy.lua
src/cosy/util/proxy.lua
-- Proxies -- ======= -- -- TODO: explain more on data -- -- Data is represented as raw tables, and operations are implemented either -- as functions, or as proxies over raw data. -- The goal of this design decision is to allow easy exchange of data over -- the network, and to select the behaviors depending on the context. -- -- Proxy specific tags -- ------------------- local tags = require "cosy.util.tags" -- -- The `DATA` tag is meant to be used only in proxies, to identify the data -- behind the proxy. -- local DATA = tags.DATA -- The `IS_PROXY` tag is also meant to be used only as `x [IS_PROXY] = -- true` to identify proxies. The `DATA` tag alone is not sufficient, as -- proxies over the `nil` value do not define the `DATA` tag. -- local IS_PROXY = tags.IS_PROXY -- ### Warning -- -- Proxies can be stacked. Thus, a `DATA` field can be assigned to another -- proxy. -- Proxy type -- ---------- local raw = require "cosy.util.raw" local ignore = require "cosy.util.ignore" local is_tag = require "cosy.util.is_tag" local function string (self) return "<" .. tostring (rawget (self, DATA)) .. ">" end local function eq (lhs, rhs) return raw (lhs) == raw (rhs) end local function len (self) return # rawget (self, DATA) end local function index (self, key) local below = rawget (self, DATA) local mt = getmetatable (self) if type (below) ~= "table" then error "attempt to index a non table" elseif is_tag (key) and not key.wrap then return below [key] else return mt (below [key]) end end local function newindex_writable (self, key, value) rawget (self, DATA) [key] = value end local function newindex_readonly (self, key, value) ignore (self, key, value) error "Attempt to write to a read-only proxy." end local eq_mt = { __eq = eq, } local function call_metatable (self, x) if type (x) == "table" then local mt = getmetatable (x) if not mt then setmetatable (x, eq_mt) end end return setmetatable ({ [DATA] = x, }, self) end local function proxy (parameters) parameters = parameters or {} local newindex if parameters.read_only then newindex = newindex_readonly else newindex = newindex_writable end local mt = { __call = call_metatable, } local result = { __tostring = string, __eq = eq, __len = len, __index = index, __newindex = newindex, __call = nil, __mode = nil, [IS_PROXY] = true, } return setmetatable (result, mt), mt end return proxy
-- Proxies -- ======= -- -- TODO: explain more on data -- -- Data is represented as raw tables, and operations are implemented either -- as functions, or as proxies over raw data. -- The goal of this design decision is to allow easy exchange of data over -- the network, and to select the behaviors depending on the context. -- -- Proxy specific tags -- ------------------- local tags = require "cosy.util.tags" -- -- The `DATA` tag is meant to be used only in proxies, to identify the data -- behind the proxy. -- local DATA = tags.DATA -- The `IS_PROXY` tag is also meant to be used only as `x [IS_PROXY] = -- true` to identify proxies. The `DATA` tag alone is not sufficient, as -- proxies over the `nil` value do not define the `DATA` tag. -- local IS_PROXY = tags.IS_PROXY -- ### Warning -- -- Proxies can be stacked. Thus, a `DATA` field can be assigned to another -- proxy. -- Proxy type -- ---------- local raw = require "cosy.util.raw" local ignore = require "cosy.util.ignore" local is_tag = require "cosy.util.is_tag" local function string (self) return tostring (rawget (self, DATA)) end local function eq (lhs, rhs) return raw (lhs) == raw (rhs) end local function len (self) return # rawget (self, DATA) end local function index (self, key) local below = rawget (self, DATA) local mt = getmetatable (self) if type (below) ~= "table" and type (below) ~= "string" then error "attempt to index a non table" elseif is_tag (key) and not key.wrap then return below [key] else return mt (below [key]) end end local function newindex_writable (self, key, value) rawget (self, DATA) [key] = value end local function newindex_readonly (self, key, value) ignore (self, key, value) error "Attempt to write to a read-only proxy." end local eq_mt = { __eq = eq, } local function call_metatable (self, x) if type (x) == "table" then local mt = getmetatable (x) if not mt then setmetatable (x, eq_mt) end end return setmetatable ({ [DATA] = x, }, self) end local function proxy (parameters) parameters = parameters or {} local newindex if parameters.read_only then newindex = newindex_readonly else newindex = newindex_writable end local mt = { __call = call_metatable, } local result = { __tostring = string, __eq = eq, __len = len, __index = index, __newindex = newindex, __call = nil, __mode = nil, [IS_PROXY] = true, } return setmetatable (result, mt), mt end return proxy
Fix proxy tostring and allow [] access for strings.
Fix proxy tostring and allow [] access for strings.
Lua
mit
CosyVerif/library,CosyVerif/library,CosyVerif/library
c6c6560906e544325d0956740975eba5ea23b347
mod_tcpproxy/mod_tcpproxy.lua
mod_tcpproxy/mod_tcpproxy.lua
local st = require "util.stanza"; local xmlns_ibb = "http://jabber.org/protocol/ibb"; local xmlns_tcp = "http://prosody.im/protocol/tcpproxy"; local host_attr, port_attr = xmlns_tcp.."\1host", xmlns_tcp.."\1port"; local base64 = require "util.encodings".base64; local b64, unb64 = base64.encode, base64.decode; local host = module.host; local open_connections = {}; local function new_session(jid, sid, conn) if not open_connections[jid] then open_connections[jid] = {}; end open_connections[jid][sid] = conn; end local function close_session(jid, sid) if open_connections[jid] then open_connections[jid][sid] = nil; if next(open_connections[jid]) == nil then open_connections[jid] = nil; end return true; end end function proxy_component(origin, stanza) local ibb_tag = stanza.tags[1]; if (not (stanza.name == "iq" and stanza.attr.type == "set") and stanza.name ~= "message") or (not (ibb_tag) or ibb_tag.attr.xmlns ~= xmlns_ibb) then if stanza.attr.type ~= "error" then origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); end return; end if ibb_tag.name == "open" then -- Starting a new stream local to_host, to_port = ibb_tag.attr[host_attr], ibb_tag.attr[port_attr]; local jid, sid = stanza.attr.from, ibb_tag.attr.sid; if not (to_host and to_port) then return origin.send(st.error_reply(stanza, "modify", "bad-request", "No host/port specified")); elseif not sid or sid == "" then return origin.send(st.error_reply(stanza, "modify", "bad-request", "No sid specified")); elseif ibb_tag.attr.stanza ~= "message" then return origin.send(st.error_reply(stanza, "modify", "bad-request", "Only 'message' stanza transport is supported")); end local conn, err = socket.tcp(); if not conn then return origin.send(st.error_reply(stanza, "wait", "resource-constraint", err)); end conn:settimeout(0); local success, err = conn:connect(to_host, to_port); if not success and err ~= "timeout" then return origin.send(st.error_reply(stanza, "wait", "remote-server-not-found", err)); end local listener,seq = {}, 0; function listener.onconnect(conn) origin.send(st.reply(stanza)); end function listener.onincoming(conn, data) origin.send(st.message({to=jid,from=host}) :tag("data", {xmlns=xmlns_ibb,seq=seq,sid=sid}) :text(b64(data))); seq = seq + 1; end function listener.ondisconnect(conn, err) origin.send(st.message({to=jid,from=host}) :tag("close", {xmlns=xmlns_ibb,sid=sid})); close_session(jid, sid); end conn = server.wrapclient(conn, to_host, to_port, listener, "*a" ); new_session(jid, sid, conn); elseif ibb_tag.name == "data" then local conn = open_connections[stanza.attr.from][ibb_tag.attr.sid]; if conn then conn:write(unb64(ibb_tag:get_text())); else return origin.send(st.error_reply(stanza, "cancel", "item-not-found")); end elseif ibb_tag.name == "close" then if close_session(stanza.attr.from, ibb_tag.attr.sid) then origin.send(st.reply(stanza)); else return origin.send(st.error_reply(stanza, "cancel", "item-not-found")); end end end require "core.componentmanager".register_component(host, proxy_component);
local st = require "util.stanza"; local xmlns_ibb = "http://jabber.org/protocol/ibb"; local xmlns_tcp = "http://prosody.im/protocol/tcpproxy"; local host_attr, port_attr = xmlns_tcp.."\1host", xmlns_tcp.."\1port"; local base64 = require "util.encodings".base64; local b64, unb64 = base64.encode, base64.decode; local host = module.host; local open_connections = {}; local function new_session(jid, sid, conn) if not open_connections[jid] then open_connections[jid] = {}; end open_connections[jid][sid] = conn; end local function close_session(jid, sid) if open_connections[jid] then open_connections[jid][sid] = nil; if next(open_connections[jid]) == nil then open_connections[jid] = nil; end return true; end end function proxy_component(origin, stanza) local ibb_tag = stanza.tags[1]; if (not (stanza.name == "iq" and stanza.attr.type == "set") and stanza.name ~= "message") or (not (ibb_tag) or ibb_tag.attr.xmlns ~= xmlns_ibb) then if stanza.attr.type ~= "error" then origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); end return; end if ibb_tag.name == "open" then -- Starting a new stream local to_host, to_port = ibb_tag.attr[host_attr], ibb_tag.attr[port_attr]; local jid, sid = stanza.attr.from, ibb_tag.attr.sid; if not (to_host and to_port) then return origin.send(st.error_reply(stanza, "modify", "bad-request", "No host/port specified")); elseif not sid or sid == "" then return origin.send(st.error_reply(stanza, "modify", "bad-request", "No sid specified")); elseif ibb_tag.attr.stanza ~= "message" then return origin.send(st.error_reply(stanza, "modify", "bad-request", "Only 'message' stanza transport is supported")); end local conn, err = socket.tcp(); if not conn then return origin.send(st.error_reply(stanza, "wait", "resource-constraint", err)); end conn:settimeout(0); local success, err = conn:connect(to_host, to_port); if not success and err ~= "timeout" then return origin.send(st.error_reply(stanza, "wait", "remote-server-not-found", err)); end local listener,seq = {}, 0; function listener.onconnect(conn) origin.send(st.reply(stanza)); end function listener.onincoming(conn, data) origin.send(st.message({to=jid,from=host}) :tag("data", {xmlns=xmlns_ibb,seq=seq,sid=sid}) :text(b64(data))); seq = seq + 1; end function listener.ondisconnect(conn, err) origin.send(st.message({to=jid,from=host}) :tag("close", {xmlns=xmlns_ibb,sid=sid})); close_session(jid, sid); end conn = server.wrapclient(conn, to_host, to_port, listener, "*a" ); new_session(jid, sid, conn); elseif ibb_tag.name == "data" then local conn = open_connections[stanza.attr.from][ibb_tag.attr.sid]; if conn then local data = unb64(ibb_tag:get_text()); if data then conn:write(data); else return origin.send( st.error_reply(stanza, "modify", "bad-request", "Invalid data (base64?)") ); end else return origin.send(st.error_reply(stanza, "cancel", "item-not-found")); end elseif ibb_tag.name == "close" then if close_session(stanza.attr.from, ibb_tag.attr.sid) then origin.send(st.reply(stanza)); else return origin.send(st.error_reply(stanza, "cancel", "item-not-found")); end end end require "core.componentmanager".register_component(host, proxy_component);
mod_tcpproxy: Handle gracefully invalid base64 data, fixes #2 (thanks dersd)
mod_tcpproxy: Handle gracefully invalid base64 data, fixes #2 (thanks dersd)
Lua
mit
syntafin/prosody-modules,vfedoroff/prosody-modules,brahmi2/prosody-modules,either1/prosody-modules,joewalker/prosody-modules,crunchuser/prosody-modules,mmusial/prosody-modules,mardraze/prosody-modules,NSAKEY/prosody-modules,iamliqiang/prosody-modules,vfedoroff/prosody-modules,jkprg/prosody-modules,drdownload/prosody-modules,crunchuser/prosody-modules,Craige/prosody-modules,vfedoroff/prosody-modules,NSAKEY/prosody-modules,brahmi2/prosody-modules,either1/prosody-modules,vince06fr/prosody-modules,NSAKEY/prosody-modules,jkprg/prosody-modules,iamliqiang/prosody-modules,apung/prosody-modules,obelisk21/prosody-modules,stephen322/prosody-modules,heysion/prosody-modules,vfedoroff/prosody-modules,drdownload/prosody-modules,asdofindia/prosody-modules,mardraze/prosody-modules,syntafin/prosody-modules,guilhem/prosody-modules,vince06fr/prosody-modules,obelisk21/prosody-modules,mardraze/prosody-modules,guilhem/prosody-modules,softer/prosody-modules,jkprg/prosody-modules,iamliqiang/prosody-modules,obelisk21/prosody-modules,heysion/prosody-modules,amenophis1er/prosody-modules,jkprg/prosody-modules,softer/prosody-modules,1st8/prosody-modules,mardraze/prosody-modules,heysion/prosody-modules,asdofindia/prosody-modules,prosody-modules/import,BurmistrovJ/prosody-modules,cryptotoad/prosody-modules,softer/prosody-modules,guilhem/prosody-modules,amenophis1er/prosody-modules,softer/prosody-modules,crunchuser/prosody-modules,amenophis1er/prosody-modules,either1/prosody-modules,stephen322/prosody-modules,obelisk21/prosody-modules,mardraze/prosody-modules,heysion/prosody-modules,Craige/prosody-modules,olax/prosody-modules,1st8/prosody-modules,brahmi2/prosody-modules,vince06fr/prosody-modules,amenophis1er/prosody-modules,NSAKEY/prosody-modules,prosody-modules/import,brahmi2/prosody-modules,mmusial/prosody-modules,joewalker/prosody-modules,syntafin/prosody-modules,asdofindia/prosody-modules,prosody-modules/import,brahmi2/prosody-modules,olax/prosody-modules,prosody-modules/import,guilhem/prosody-modules,dhotson/prosody-modules,vfedoroff/prosody-modules,dhotson/prosody-modules,obelisk21/prosody-modules,apung/prosody-modules,olax/prosody-modules,BurmistrovJ/prosody-modules,1st8/prosody-modules,apung/prosody-modules,dhotson/prosody-modules,crunchuser/prosody-modules,apung/prosody-modules,BurmistrovJ/prosody-modules,1st8/prosody-modules,cryptotoad/prosody-modules,heysion/prosody-modules,cryptotoad/prosody-modules,LanceJenkinZA/prosody-modules,guilhem/prosody-modules,mmusial/prosody-modules,asdofindia/prosody-modules,either1/prosody-modules,mmusial/prosody-modules,asdofindia/prosody-modules,Craige/prosody-modules,drdownload/prosody-modules,BurmistrovJ/prosody-modules,LanceJenkinZA/prosody-modules,olax/prosody-modules,crunchuser/prosody-modules,prosody-modules/import,1st8/prosody-modules,stephen322/prosody-modules,Craige/prosody-modules,NSAKEY/prosody-modules,joewalker/prosody-modules,either1/prosody-modules,vince06fr/prosody-modules,stephen322/prosody-modules,stephen322/prosody-modules,iamliqiang/prosody-modules,softer/prosody-modules,dhotson/prosody-modules,BurmistrovJ/prosody-modules,joewalker/prosody-modules,joewalker/prosody-modules,iamliqiang/prosody-modules,drdownload/prosody-modules,vince06fr/prosody-modules,LanceJenkinZA/prosody-modules,jkprg/prosody-modules,LanceJenkinZA/prosody-modules,drdownload/prosody-modules,Craige/prosody-modules,dhotson/prosody-modules,olax/prosody-modules,mmusial/prosody-modules,amenophis1er/prosody-modules,LanceJenkinZA/prosody-modules,cryptotoad/prosody-modules,syntafin/prosody-modules,apung/prosody-modules,syntafin/prosody-modules,cryptotoad/prosody-modules
951b0058f88706c727e918a50e76e16cd9dba1b5
stdlib/utils/math.lua
stdlib/utils/math.lua
--- Extends Lua 5.2 math. -- @module Utils.math -- @see math -- @usage local math = require('__stdlib__/stdlib/utils/math') local Math = {} for k, v in pairs(math) do Math[k] = v end local math_abs = math.abs local math_floor = math.floor local math_ceil = math.ceil local math_min = math.min local math_max = math.max local math_huge = math.huge local math_pi = math.pi local log10 = math.log10 local unpack = table.unpack --(( Math Constants Math.DEG2RAD = math_pi / 180 Math.RAD2DEG = 180 / math_pi Math.EPSILON = 1.401298e-45 Math.MAXINT8 = 128 Math.MININT8 = -128 Math.MAXUINT8 = 255 Math.MAX_INT8 = Math.MAXINT8 Math.MIN_INT8 = Math.MININT8 Math.MAX_UINT8 = Math.MAXUINT8 Math.MAXINT16 = 32768 Math.MININT16 = -32768 Math.MAXUINT16 = 65535 Math.MAX_INT16 = Math.MAXINT16 Math.MIN_INT16 = Math.MININT16 Math.MAX_UINT16 = Math.MAXUINT16 Math.MAXINT = 2147483648 Math.MAX_INT = Math.MAXINT Math.MAXINT32 = Math.MAXINT Math.MAX_INT32 = Math.MAXINT Math.MAXUINT = 4294967296 Math.MAX_UINT = Math.MAXUINT Math.MAXUINT32 = Math.MAXUINT Math.MAX_UINT32 = Math.MAXUINT Math.MININT = -2147483648 Math.MIN_INT = Math.MININT Math.MININT32 = Math.MININT Math.MIN_INT32 = Math.MININT Math.MAXINT64 = 9223372036854775808 Math.MININT64 = -9223372036854775808 Math.MAXUINT64 = 18446744073709551615 Math.MAX_INT64 = Math.MAXINT64 Math.MIN_INT64 = Math.MININT64 Math.MAX_UINT64 = Math.MAXUINT64 --)) local function tuple(...) return type(...) == 'table' and ... or {...} end --- Round a number. -- @tparam number x -- @treturn number the rounded number function Math.round(x) return x >= 0 and math_floor(x + 0.5) or math_ceil(x - 0.5) end -- Returns the number x rounded to p decimal places. -- @tparam number x -- @tparam[opt=0] int p the number of decimal places to round to -- @treturn number rounded to p decimal spaces. function Math.round_to(x, p) local e = 10 ^ (p or 0) return math_floor(x * e + 0.5) / e end -- Returns the number floored to p decimal spaces. -- @tparam number x -- @tparam[opt=0] int p the number of decimal places to floor to -- @treturn number floored to p decimal spaces. function Math.floor_to(x, p) if (p or 0) == 0 then return math_floor(x) end local e = 10 ^ p return math_floor(x * e) / e end -- Returns the number ceiled to p decimal spaces. -- @tparam number x -- @tparam[opt=0] int p the number of decimal places to ceil to -- @treturn number ceiled to p decimal spaces. function Math.ceil_to(x, p) local e = 10 ^ (p or 0) return math_ceil(x * e + 0.5) / e end -- Various average (means) algorithms implementation -- See: http://en.wikipedia.org/wiki/Average --- Calculates the sum of a sequence of values. -- @tparam tuple ... a tuple of numbers -- @treturn the sum function Math.sum(...) local x = tuple(...) local s = 0 for _, v in ipairs(x) do s = s + v end return s end --- Calculates the arithmetic mean of a set of values. -- @tparam array x an array of numbers -- @treturn number the arithmetic mean function Math.arithmetic_mean(...) local x = tuple(...) return (Math.sum(x) / #x) end Math.avg = Math.arithmetic_mean Math.average = Math.arithmetic_mean --- Calculates the geometric mean of a set of values. -- @tparam array x an array of numbers -- @treturn number the geometric mean function Math.geometric_mean(...) local x = tuple(...) local prod = 1 for _, v in ipairs(x) do prod = prod * v end return (prod ^ (1 / #x)) end --- Calculates the harmonic mean of a set of values. -- @tparam tuple ... an array of numbers -- @treturn number the harmonic mean function Math.harmonic_mean(...) local x = tuple(...) local s = 0 for _, v in ipairs(x) do s = s + (1 / v) end return (#x / s) end --- Calculates the quadratic mean of a set of values. -- @tparam tuple ... an array of numbers -- @treturn number the quadratic mean function Math.quadratic_mean(...) local x = tuple(...) local squares = 0 for _, v in ipairs(x) do squares = squares + (v * v) end return math.sqrt((1 / #x) * squares) end --- Calculates the generalized mean (to a specified power) of a set of values. -- @tparam number p power -- @tparam tuple ... an array of numbers -- @treturn number the generalized mean function Math.generalized_mean(p, ...) local x = tuple(...) local sump = 0 for _, v in ipairs(x) do sump = sump + (v ^ p) end return ((1 / #x) * sump) ^ (1 / p) end --- Calculates the weighted mean of a set of values. -- @tparam array x an array of numbers -- @tparam array w an array of number weights for each value -- @treturn number the weighted mean function Math.weighted_mean(x, w) local sump = 0 for i, v in ipairs(x) do sump = sump + (v * w[i]) end return sump / Math.sum(w) end --- Calculates the midrange mean of a set of values. -- @tparam array x an array of numbers -- @treturn number the midrange mean function Math.midrange_mean(...) local x = tuple(...) return 0.5 * (math_min(unpack(x)) + math_max(unpack(x))) end --- Calculates the energetic mean of a set of values. -- @tparam array x an array of numbers -- @treturn number the energetic mean function Math.energetic_mean(...) local x = tuple(...) local s = 0 for _, v in ipairs(x) do s = s + (10 ^ (v / 10)) end return 10 * log10((1 / #x) * s) end --- Returns the number x clamped between the numbers min and max. -- @tparam number x -- @tparam number min -- @tparam number max -- @treturn number clamped between min and max function Math.clamp(x, min, max) min, max = min or 0, max or 1 return x < min and min or (x > max and max or x) end --- Linear interpolation or 2 numbers. -- @tparam number a -- @tparam number b -- @tparam float amount -- @treturn number function Math.lerp(a, b, amount) return a + (b - a) * Math.clamp(amount, 0, 1) end --- Smooth. -- @tparam number a -- @tparam number b -- @tparam float amount -- @treturn number function Math.smooth(a, b, amount) local t = Math.clamp(amount, 0, 1) local m = t * t * (3 - 2 * t) return a + (b - a) * m end --- Approximately the same -- @tparam number a -- @tparam number b -- @treturn boolean function Math.approximately(a, b) return math_abs(b - a) < math_max(1e-6 * math_max(math_abs(a), math_abs(b)), 1.121039e-44) end --- Is x a number. -- @tparam number x -- @treturn boolean function Math.is_number(x) return x == x and x ~= math_huge end --- Is x an integer. -- @tparam number x -- @treturn boolean function Math.is_integer(x) return x == math_ceil(x) end --- Is x unsigned. -- @tparam number x -- @treturn boolean function Math.is_unsigned(x) return x >= 0 end return Math
--- Extends Lua 5.2 math. -- @module Utils.math -- @see math -- @usage local math = require('__stdlib__/stdlib/utils/math') local Math = {} for k, v in pairs(math) do Math[k] = v end local math_abs = math.abs local math_floor = math.floor local math_ceil = math.ceil local math_min = math.min local math_max = math.max local math_huge = math.huge local math_pi = math.pi local math_log = math.log local unpack = table.unpack --(( Math Constants Math.DEG2RAD = math_pi / 180 Math.RAD2DEG = 180 / math_pi Math.EPSILON = 1.401298e-45 Math.MAXINT8 = 128 Math.MININT8 = -128 Math.MAXUINT8 = 255 Math.MAX_INT8 = Math.MAXINT8 Math.MIN_INT8 = Math.MININT8 Math.MAX_UINT8 = Math.MAXUINT8 Math.MAXINT16 = 32768 Math.MININT16 = -32768 Math.MAXUINT16 = 65535 Math.MAX_INT16 = Math.MAXINT16 Math.MIN_INT16 = Math.MININT16 Math.MAX_UINT16 = Math.MAXUINT16 Math.MAXINT = 2147483648 Math.MAX_INT = Math.MAXINT Math.MAXINT32 = Math.MAXINT Math.MAX_INT32 = Math.MAXINT Math.MAXUINT = 4294967296 Math.MAX_UINT = Math.MAXUINT Math.MAXUINT32 = Math.MAXUINT Math.MAX_UINT32 = Math.MAXUINT Math.MININT = -2147483648 Math.MIN_INT = Math.MININT Math.MININT32 = Math.MININT Math.MIN_INT32 = Math.MININT Math.MAXINT64 = 9223372036854775808 Math.MININT64 = -9223372036854775808 Math.MAXUINT64 = 18446744073709551615 Math.MAX_INT64 = Math.MAXINT64 Math.MIN_INT64 = Math.MININT64 Math.MAX_UINT64 = Math.MAXUINT64 --)) local function tuple(...) return type(...) == 'table' and ... or {...} end function Math.log10(x) return math_log(x, 10) end --- Round a number. -- @tparam number x -- @treturn number the rounded number function Math.round(x) return x >= 0 and math_floor(x + 0.5) or math_ceil(x - 0.5) end -- Returns the number x rounded to p decimal places. -- @tparam number x -- @tparam[opt=0] int p the number of decimal places to round to -- @treturn number rounded to p decimal spaces. function Math.round_to(x, p) local e = 10 ^ (p or 0) return math_floor(x * e + 0.5) / e end -- Returns the number floored to p decimal spaces. -- @tparam number x -- @tparam[opt=0] int p the number of decimal places to floor to -- @treturn number floored to p decimal spaces. function Math.floor_to(x, p) if (p or 0) == 0 then return math_floor(x) end local e = 10 ^ p return math_floor(x * e) / e end -- Returns the number ceiled to p decimal spaces. -- @tparam number x -- @tparam[opt=0] int p the number of decimal places to ceil to -- @treturn number ceiled to p decimal spaces. function Math.ceil_to(x, p) local e = 10 ^ (p or 0) return math_ceil(x * e + 0.5) / e end -- Various average (means) algorithms implementation -- See: http://en.wikipedia.org/wiki/Average --- Calculates the sum of a sequence of values. -- @tparam tuple ... a tuple of numbers -- @treturn the sum function Math.sum(...) local x = tuple(...) local s = 0 for _, v in ipairs(x) do s = s + v end return s end --- Calculates the arithmetic mean of a set of values. -- @tparam array x an array of numbers -- @treturn number the arithmetic mean function Math.arithmetic_mean(...) local x = tuple(...) return (Math.sum(x) / #x) end Math.avg = Math.arithmetic_mean Math.average = Math.arithmetic_mean --- Calculates the geometric mean of a set of values. -- @tparam array x an array of numbers -- @treturn number the geometric mean function Math.geometric_mean(...) local x = tuple(...) local prod = 1 for _, v in ipairs(x) do prod = prod * v end return (prod ^ (1 / #x)) end --- Calculates the harmonic mean of a set of values. -- @tparam tuple ... an array of numbers -- @treturn number the harmonic mean function Math.harmonic_mean(...) local x = tuple(...) local s = 0 for _, v in ipairs(x) do s = s + (1 / v) end return (#x / s) end --- Calculates the quadratic mean of a set of values. -- @tparam tuple ... an array of numbers -- @treturn number the quadratic mean function Math.quadratic_mean(...) local x = tuple(...) local squares = 0 for _, v in ipairs(x) do squares = squares + (v * v) end return math.sqrt((1 / #x) * squares) end --- Calculates the generalized mean (to a specified power) of a set of values. -- @tparam number p power -- @tparam tuple ... an array of numbers -- @treturn number the generalized mean function Math.generalized_mean(p, ...) local x = tuple(...) local sump = 0 for _, v in ipairs(x) do sump = sump + (v ^ p) end return ((1 / #x) * sump) ^ (1 / p) end --- Calculates the weighted mean of a set of values. -- @tparam array x an array of numbers -- @tparam array w an array of number weights for each value -- @treturn number the weighted mean function Math.weighted_mean(x, w) local sump = 0 for i, v in ipairs(x) do sump = sump + (v * w[i]) end return sump / Math.sum(w) end --- Calculates the midrange mean of a set of values. -- @tparam array x an array of numbers -- @treturn number the midrange mean function Math.midrange_mean(...) local x = tuple(...) return 0.5 * (math_min(unpack(x)) + math_max(unpack(x))) end --- Calculates the energetic mean of a set of values. -- @tparam array x an array of numbers -- @treturn number the energetic mean function Math.energetic_mean(...) local x = tuple(...) local s = 0 for _, v in ipairs(x) do s = s + (10 ^ (v / 10)) end return 10 * Math.log10((1 / #x) * s) end --- Returns the number x clamped between the numbers min and max. -- @tparam number x -- @tparam number min -- @tparam number max -- @treturn number clamped between min and max function Math.clamp(x, min, max) min, max = min or 0, max or 1 return x < min and min or (x > max and max or x) end --- Linear interpolation or 2 numbers. -- @tparam number a -- @tparam number b -- @tparam float amount -- @treturn number function Math.lerp(a, b, amount) return a + (b - a) * Math.clamp(amount, 0, 1) end --- Smooth. -- @tparam number a -- @tparam number b -- @tparam float amount -- @treturn number function Math.smooth(a, b, amount) local t = Math.clamp(amount, 0, 1) local m = t * t * (3 - 2 * t) return a + (b - a) * m end --- Approximately the same -- @tparam number a -- @tparam number b -- @treturn boolean function Math.approximately(a, b) return math_abs(b - a) < math_max(1e-6 * math_max(math_abs(a), math_abs(b)), 1.121039e-44) end --- Is x a number. -- @tparam number x -- @treturn boolean function Math.is_number(x) return x == x and x ~= math_huge end --- Is x an integer. -- @tparam number x -- @treturn boolean function Math.is_integer(x) return x == math_ceil(x) end --- Is x unsigned. -- @tparam number x -- @treturn boolean function Math.is_unsigned(x) return x >= 0 end return Math
Fix math.log10 unavailable in 5.2 without compat
Fix math.log10 unavailable in 5.2 without compat
Lua
isc
Afforess/Factorio-Stdlib
c14ce145056b1a45149a2e43d929d85f44efefea
nvim/lua/plugins.lua
nvim/lua/plugins.lua
local install_path = vim.fn.stdpath('data')..'/site/pack/packer/start/packer.nvim' local compile_path = install_path..'/plugin/packer_compiled.lua' local bootstrap = vim.fn.empty(vim.fn.glob(install_path)) > 0 -- For new installations, we may not have packer. -- We need to manually clone and install the package manager. if bootstrap then vim.api.nvim_command('!git clone --filter=blob:none https://github.com/wbthomason/packer.nvim '..install_path) vim.api.nvim_command('packadd packer.nvim') end local packer = require('packer') -- Specify a custom compile path, since we don't want it next to our configs. packer.init({compile_path = compile_path}) packer.startup(function(use) -- Let packer.nvim manage itself. use 'wbthomason/packer.nvim' -- Performance-related plugins. use 'lewis6991/impatient.nvim' -- Sensible defaults. use 'tpope/vim-sensible' -- Cosmetic plugins. use 'lukas-reineke/indent-blankline.nvim' use { 'ishan9299/nvim-solarized-lua', config = function() vim.cmd('colorscheme solarized') end, } use { 'norcalli/nvim-colorizer.lua', config = function() require('colorizer').setup() end, } use { 'feline-nvim/feline.nvim', config = function() require('feline').setup() end, } use { 'akinsho/bufferline.nvim', requires = 'kyazdani42/nvim-web-devicons', config = function() require('config.bufferline') end, } use { 'kyazdani42/nvim-tree.lua', requires = {'kyazdani42/nvim-web-devicons'}, config = function() require('nvim-tree').setup() end, } use 'liuchengxu/vista.vim' -- Plugins for git and version control. use 'tpope/vim-fugitive' use 'tpope/vim-rhubarb' use { 'lewis6991/gitsigns.nvim', requires = {'nvim-lua/plenary.nvim'}, config = function() require('gitsigns').setup() end, } -- LSP plugins. use { -- NOTE: Not all plugins have init.lua. Be careful about this. -- Not all config directives will run, as a result. 'williamboman/mason.nvim', requires = { 'williamboman/mason-lspconfig.nvim', 'neovim/nvim-lspconfig', 'ray-x/lsp_signature.nvim', }, config = function() require('config.lsp') end, } -- Completion engine and dependencies. use { 'hrsh7th/nvim-cmp', requires = { 'L3MON4D3/LuaSnip', 'hrsh7th/cmp-nvim-lua', 'hrsh7th/cmp-nvim-lsp', 'hrsh7th/cmp-buffer', 'hrsh7th/cmp-path', 'hrsh7th/cmp-calc', 'onsails/lspkind-nvim', }, config = function() require('config.cmp') end, } -- Treesitter for better syntax highlighting and whatnot. use { 'nvim-treesitter/nvim-treesitter', config = "require('config.treesitter')", run = function() require('nvim-treesitter.install').update({ with_sync = true }) end, } -- Show what function/class you're in. use 'nvim-treesitter/nvim-treesitter-context' -- Vim Polyglot for the languages not supported by Treesitter. use 'sheerun/vim-polyglot' -- Telescope for better searching and whatnot. use { 'nvim-telescope/telescope.nvim', requires = { {'nvim-lua/plenary.nvim'}, {'nvim-treesitter/nvim-treesitter'}, {'kyazdani42/nvim-web-devicons'}, {'nvim-telescope/telescope-fzf-native.nvim', run = 'make'}, }, config = function() require('config.telescope') end, } -- We would still like Neovim to manage fzf installation. use { 'junegunn/fzf', run = function() vim.fn['fzf#install']() end, } -- Language-specific plugins. use 'tweekmonster/gofmt.vim' -- Miscellaneous plugins. use 'psliwka/vim-smoothie' use { 'nacro90/numb.nvim', config = function() require('numb').setup() end, } -- Automatically sync all packages if we're bootstrapping. if bootstrap then packer.sync() end end)
local install_path = vim.fn.stdpath('data')..'/site/pack/packer/start/packer.nvim' local compile_path = install_path..'/plugin/packer_compiled.lua' local bootstrap = vim.fn.empty(vim.fn.glob(install_path)) > 0 -- For new installations, we may not have packer. -- We need to manually clone and install the package manager. if bootstrap then vim.api.nvim_command('!git clone --filter=blob:none https://github.com/wbthomason/packer.nvim '..install_path) vim.api.nvim_command('packadd packer.nvim') end local packer = require('packer') -- Specify a custom compile path, since we don't want it next to our configs. packer.init({compile_path = compile_path}) packer.startup(function(use) -- Let packer.nvim manage itself. use 'wbthomason/packer.nvim' -- Performance-related plugins. use 'lewis6991/impatient.nvim' -- Sensible defaults. use 'tpope/vim-sensible' -- Cosmetic plugins. use 'lukas-reineke/indent-blankline.nvim' use { 'ishan9299/nvim-solarized-lua', config = function() vim.cmd('colorscheme solarized') end, } use { 'norcalli/nvim-colorizer.lua', config = function() require('colorizer').setup() end, } use { 'feline-nvim/feline.nvim', config = function() require('feline').setup() end, } use { 'akinsho/bufferline.nvim', requires = 'kyazdani42/nvim-web-devicons', config = function() require('config.bufferline') end, } use { 'kyazdani42/nvim-tree.lua', requires = {'kyazdani42/nvim-web-devicons'}, config = function() require('nvim-tree').setup() end, } use 'liuchengxu/vista.vim' -- Plugins for git and version control. use 'tpope/vim-fugitive' use 'tpope/vim-rhubarb' use { 'lewis6991/gitsigns.nvim', requires = {'nvim-lua/plenary.nvim'}, config = function() require('gitsigns').setup() end, } -- LSP plugins. use { -- NOTE: Not all plugins have init.lua. Be careful about this. -- Not all config directives will run, as a result. 'williamboman/mason.nvim', requires = { 'williamboman/mason-lspconfig.nvim', 'neovim/nvim-lspconfig', 'ray-x/lsp_signature.nvim', }, config = function() require('config.lsp') end, } -- Completion engine and dependencies. use { 'hrsh7th/nvim-cmp', requires = { 'L3MON4D3/LuaSnip', 'hrsh7th/cmp-nvim-lua', 'hrsh7th/cmp-nvim-lsp', 'hrsh7th/cmp-buffer', 'hrsh7th/cmp-path', 'hrsh7th/cmp-calc', 'onsails/lspkind-nvim', }, config = function() require('config.cmp') end, } -- Treesitter for better syntax highlighting and whatnot. use { 'nvim-treesitter/nvim-treesitter', config = "require('config.treesitter')", run = function() local ts_update = require('nvim-treesitter.install').update({ with_sync = true }) ts_update() end, } -- Show what function/class you're in. use 'nvim-treesitter/nvim-treesitter-context' -- Vim Polyglot for the languages not supported by Treesitter. use 'sheerun/vim-polyglot' -- Telescope for better searching and whatnot. use { 'nvim-telescope/telescope.nvim', requires = { {'nvim-lua/plenary.nvim'}, {'nvim-treesitter/nvim-treesitter'}, {'kyazdani42/nvim-web-devicons'}, {'nvim-telescope/telescope-fzf-native.nvim', run = 'make'}, }, config = function() require('config.telescope') end, } -- We would still like Neovim to manage fzf installation. use { 'junegunn/fzf', run = function() vim.fn['fzf#install']() end, } -- Language-specific plugins. use 'tweekmonster/gofmt.vim' -- Miscellaneous plugins. use 'psliwka/vim-smoothie' use { 'nacro90/numb.nvim', config = function() require('numb').setup() end, } -- Automatically sync all packages if we're bootstrapping. if bootstrap then packer.sync() end end)
Fix treesitter installation
Fix treesitter installation https://github.com/nvim-treesitter/nvim-treesitter/wiki/Installation
Lua
mit
MrPickles/dotfiles
d96d8022e8fb5e2378869453e07fdc359eb7890e
.config/nvim/lua/treesitter_config.lua
.config/nvim/lua/treesitter_config.lua
local define_modules = require("nvim-treesitter").define_modules local query = require("nvim-treesitter.query") local foldmethod_backups = {} local foldexpr_backups = {} -- folding module -- ref: https://github.com/nvim-treesitter/nvim-treesitter/issues/475#issuecomment-748532035 define_modules( { folding = { enable = true, attach = function(bufnr) -- Fold settings are actually window based... foldmethod_backups[bufnr] = vim.wo.foldmethod foldexpr_backups[bufnr] = vim.wo.foldexpr vim.wo.foldmethod = "expr" vim.wo.foldexpr = "nvim_treesitter#foldexpr()" end, detach = function(bufnr) vim.wo.foldmethod = foldmethod_backups[bufnr] vim.wo.foldexpr = foldexpr_backups[bufnr] foldmethod_backups[bufnr] = nil foldexpr_backups[bufnr] = nil end, is_supported = query.has_folds } } ) require "nvim-treesitter.configs".setup { ensure_installed = "maintained", -- one of "all", "maintained" (parsers with maintainers), or a list of languages folding, highlight = { enable = true, -- false will disable the whole extension disable = {} -- list of language that will be disabled }, incremental_selection = { enable = true, keymaps = { init_selection = "vii", scope_incremental = "ii", node_incremental = "<CR>", node_decremental = "<S-CR>" } }, refactor = { highlight_definitions = {enable = true}, highlight_current_scope = {enable = false} }, textobjects = { select = { enable = true, keymaps = { -- You can use the capture groups defined in textobjects.scm ["ab"] = "@block.outer", ["ib"] = "@block.inner", ["af"] = "@function.outer", ["if"] = "@function.inner", ["ac"] = "@class.outer", ["ic"] = "@class.inner", ["aa"] = "@parameter.outer", ["ia"] = "@parameter.inner", ["cc"] = "@comment.outer", ["ss"] = "@statement.outer", -- Or you can define your own textobjects like this -- ["iF"] = { -- python = "(function_definition) @function", -- cpp = "(function_definition) @function", -- c = "(function_definition) @function", -- java = "(method_declaration) @function" -- } } }, swap = { enable = true, swap_next = { ["<LocalLeader><LocalLeader>a"] = "@parameter.inner", ["<LocalLeader><LocalLeader>s"] = "@statement.outer" }, swap_previous = { ["<LocalLeader><LocalLeader>A"] = "@parameter.inner", ["<LocalLeader><LocalLeader>S"] = "@statement.outer" } }, move = { enable = true, goto_next_start = { ["]m"] = "@function.outer", ["]]"] = "@class.outer", }, goto_next_end = { ["]M"] = "@function.outer", ["]["] = "@class.outer", }, goto_previous_start = { ["[m"] = "@function.outer", ["[["] = "@class.outer", }, goto_previous_end = { ["[M"] = "@function.outer", ["[]"] = "@class.outer", }, }, } }
local define_modules = require("nvim-treesitter").define_modules local query = require("nvim-treesitter.query") local foldmethod_backups = {} local foldexpr_backups = {} -- folding module -- ref: https://github.com/nvim-treesitter/nvim-treesitter/issues/475#issuecomment-748532035 define_modules( { folding = { enable = true, attach = function(bufnr) -- Fold settings are actually window based... foldmethod_backups[bufnr] = vim.wo.foldmethod foldexpr_backups[bufnr] = vim.wo.foldexpr vim.wo.foldmethod = "expr" vim.wo.foldexpr = "nvim_treesitter#foldexpr()" end, detach = function(bufnr) vim.wo.foldmethod = foldmethod_backups[bufnr] vim.wo.foldexpr = foldexpr_backups[bufnr] foldmethod_backups[bufnr] = nil foldexpr_backups[bufnr] = nil end, is_supported = query.has_folds } } ) require "nvim-treesitter.configs".setup { ensure_installed = "maintained", -- one of "all", "maintained" (parsers with maintainers), or a list of languages folding, highlight = { enable = true, -- false will disable the whole extension disable = {}, -- list of language that will be disabled -- Setting this to true will run `:h syntax` and tree-sitter at the same time. -- Set this to `true` if you depend on 'syntax' being enabled (like for indentation). -- Using this option may slow down your editor, and you may see some duplicate highlights. -- Instead of true it can also be a list of languages additional_vim_regex_highlighting = true, }, incremental_selection = { enable = true, keymaps = { init_selection = "vii", scope_incremental = "ii", node_incremental = "<CR>", node_decremental = "<S-CR>" } }, refactor = { highlight_definitions = {enable = true}, highlight_current_scope = {enable = false} }, textobjects = { select = { enable = true, keymaps = { -- You can use the capture groups defined in textobjects.scm ["ab"] = "@block.outer", ["ib"] = "@block.inner", ["af"] = "@function.outer", ["if"] = "@function.inner", ["ac"] = "@class.outer", ["ic"] = "@class.inner", ["aa"] = "@parameter.outer", ["ia"] = "@parameter.inner", ["cc"] = "@comment.outer", ["ss"] = "@statement.outer", -- Or you can define your own textobjects like this -- ["iF"] = { -- python = "(function_definition) @function", -- cpp = "(function_definition) @function", -- c = "(function_definition) @function", -- java = "(method_declaration) @function" -- } } }, swap = { enable = true, swap_next = { ["<LocalLeader><LocalLeader>a"] = "@parameter.inner", ["<LocalLeader><LocalLeader>s"] = "@statement.outer" }, swap_previous = { ["<LocalLeader><LocalLeader>A"] = "@parameter.inner", ["<LocalLeader><LocalLeader>S"] = "@statement.outer" } }, move = { enable = true, goto_next_start = { ["]m"] = "@function.outer", ["]]"] = "@class.outer", }, goto_next_end = { ["]M"] = "@function.outer", ["]["] = "@class.outer", }, goto_previous_start = { ["[m"] = "@function.outer", ["[["] = "@class.outer", }, goto_previous_end = { ["[M"] = "@function.outer", ["[]"] = "@class.outer", }, }, } }
nvim: fix: toggling treesitter highlight will disable syntax
nvim: fix: toggling treesitter highlight will disable syntax
Lua
mit
nkcfan/Dotfiles,nkcfan/Dotfiles,nkcfan/Dotfiles
c52e28e5b36e4d06211aafe564b788f364c16685
framework.lua
framework.lua
-- Layer to create quests and act as middle-man between Evennia and Agent require 'utils' local underscore = require 'underscore' local DEBUG = false local DEFAULT_REWARD = -0.1 local STEP_COUNT = 0 -- count the number of steps in current episode local MAX_STEPS = 100 quests = {'You are hungry.','You are sleepy.', 'You are bored.', 'You are getting fat.'} quest_actions = {'eat', 'sleep', 'watch' ,'exercise'} -- aligned to quests above quest_checklist = {} quest_levels = 1 --number of levels in any given quest rooms = {'Living', 'Garden', 'Kitchen','Bedroom'} actions = {"eat", "watch", "sleep", "exercise", "go"} -- hard code in objects = {'north','south','east','west'} -- read from build file symbols = {} symbol_mapping = {} NUM_ROOMS = 4 local current_room_description = "" function random_teleport() local room_index = torch.random(1, NUM_ROOMS) data_out('@tel tut#0'..room_index) sleep(0.1) data_in() data_out('l') if DEBUG then print('Start Room : ' .. room_index ..' ' .. rooms[room_index]) end end function random_quest() indxs = torch.randperm(#quests) for i=1,quest_levels do local quest_index = indxs[i] quest_checklist[#quest_checklist+1] = quest_index end if DEBUG then print("Start quest", quests[quest_checklist[1]], quest_actions[quest_checklist[1]]) end end function login(user, password) local num_rooms = 4 local pre_login_text = data_in() print(pre_login_text) sleep(1) data_out('connect ' .. user .. ' ' .. password) end --Function to parse the output of the game (to extract rewards, etc. ) function parse_game_output(text) -- extract REWARD if it exists -- text is a list of sentences local reward = nil local text_to_agent = {current_room_description, quests[quest_checklist[1]]} for i=1, #text do if i < #text and string.match(text[i], '<EOM>') then text_to_agent = {current_room_description, quests[quest_checklist[1]]} elseif string.match(text[i], "REWARD") then if string.match(text[i], quest_actions[quest_checklist[1]]) then reward = tonumber(string.match(text[i], "%d+")) end else table.insert(text_to_agent, text[i]) end end if not reward then reward = DEFAULT_REWARD end return text_to_agent, reward end function getState(print_on) local terminal = (STEP_COUNT >= MAX_STEPS) local inData = data_in() while #inData == 0 or not string.match(inData[#inData],'<EOM>') do TableConcat(inData, data_in()) end data_out('look') local inData2 = data_in() while #inData2 == 0 or not string.match(inData2[#inData2],'<EOM>') do TableConcat(inData2, data_in()) end current_room_description = inData2[1] local text, reward = parse_game_output(inData) if DEBUG or print_on then print(text, reward) sleep(0.1) -- if reward > 0 then -- print(text, reward) -- sleep(2) -- end end if reward >= 1 then quest_checklist = underscore.rest(quest_checklist) --remove first element in table if #quest_checklist == 0 then --quest has been succesfully finished terminal = true end end local vector = convert_text_to_bow(text) return vector, reward, terminal end --take a step in the game function step_game(action_index, object_index) data_out(build_command(actions[action_index], objects[object_index])) if DEBUG then print(actions[action_index] .. ' ' .. objects[object_index]) end STEP_COUNT = STEP_COUNT + 1 return getState() end -- TODO function nextRandomGame() end -- TODO function newGame() quest_checklist = {} random_teleport() random_quest() STEP_COUNT = 0 return getState(false) end -- build game command to send to the game function build_command(action, object) return action .. ' ' ..object end function parseLine( list_words, start_index) -- parse line to update symbols and symbol_mapping local sindx for i=start_index,#list_words do word = split(list_words[i], "%a+")[1] word = word:lower() if symbol_mapping[word] == nil then sindx = #symbols + 1 symbols[sindx] = word symbol_mapping[word] = sindx end end end -- read in text data from file with sentences (one sentence per line) - nicely tokenized function makeSymbolMapping(filename) local file = io.open(filename, "r"); local data = {} local parts for line in file:lines() do list_words = split(line, "%S+") if list_words[1] == '@detail' or list_words[1] == '@desc' then parseLine(list_words, 4) elseif list_words[1] == '@create/drop' then -- add to actionable objects table.insert(objects, split(list_words[2], "%a+")[1]) end end end -- Args: { -- 1: desc of room -- 2: quest desc -- 3: response from engine after executing command -- 4: <EOM> -- } function convert_text_to_bow(input_text) local vector = torch.zeros(#symbols) -- for i, line in pairs(input_text) do for j=1,2 do line = input_text[j] local list_words = split(line, "%a+") for i=1,#list_words do local word = list_words[i] word = word:lower() --ignore words not in vocab if symbol_mapping[word] then vector[symbol_mapping[word]] = vector[symbol_mapping[word]] + 1 end end end return vector end function getActions() return actions end function getObjects() return objects end return { makeSymbolMapping = makeSymbolMapping, getActions = getActions, getObjects = getObjects, getState = getState, step = step_game, newGame = newGame, nextRandomGame = nextRandomGame }
-- Layer to create quests and act as middle-man between Evennia and Agent require 'utils' local underscore = require 'underscore' local DEBUG = false local DEFAULT_REWARD = -0.1 local STEP_COUNT = 0 -- count the number of steps in current episode local MAX_STEPS = 500 quests = {'You are hungry.','You are sleepy.', 'You are bored.', 'You are getting fat.'} quest_actions = {'eat', 'sleep', 'watch' ,'exercise'} -- aligned to quests above quest_checklist = {} quest_levels = 1 --number of levels in any given quest rooms = {'Living', 'Garden', 'Kitchen','Bedroom'} actions = {"eat", "watch", "sleep", "exercise", "go"} -- hard code in objects = {'north','south','east','west'} -- read from build file symbols = {} symbol_mapping = {} NUM_ROOMS = 4 local current_room_description = "" function random_teleport() local room_index = torch.random(1, NUM_ROOMS) data_out('@tel tut#0'..room_index) sleep(0.1) data_in() data_out('l') if DEBUG then print('Start Room : ' .. room_index ..' ' .. rooms[room_index]) end end function random_quest() -- indxs = torch.randperm(#quests) for i=1,quest_levels do -- local quest_index = indxs[i] local quest_index = torch.random(1, #quests) quest_checklist[#quest_checklist+1] = quest_index end if DEBUG then print("Start quest", quests[quest_checklist[1]], quest_actions[quest_checklist[1]]) end end function login(user, password) local num_rooms = 4 local pre_login_text = data_in() print(pre_login_text) sleep(1) data_out('connect ' .. user .. ' ' .. password) end --Function to parse the output of the game (to extract rewards, etc. ) function parse_game_output(text) -- extract REWARD if it exists -- text is a list of sentences local reward = nil local text_to_agent = {current_room_description, quests[quest_checklist[1]]} for i=1, #text do if i < #text and string.match(text[i], '<EOM>') then text_to_agent = {current_room_description, quests[quest_checklist[1]]} elseif string.match(text[i], "REWARD") then if string.match(text[i], quest_actions[quest_checklist[1]]) then reward = tonumber(string.match(text[i], "%d+")) end else table.insert(text_to_agent, text[i]) end end if not reward then reward = DEFAULT_REWARD end return text_to_agent, reward end function getState(print_on) local terminal = (STEP_COUNT >= MAX_STEPS) local inData = data_in() while #inData == 0 or not string.match(inData[#inData],'<EOM>') do TableConcat(inData, data_in()) end data_out('look') local inData2 = data_in() while #inData2 == 0 or not string.match(inData2[#inData2],'<EOM>') do TableConcat(inData2, data_in()) end current_room_description = inData2[1] local text, reward = parse_game_output(inData) if DEBUG or print_on then print(text, reward) sleep(0.1) if reward > 0 then print(text, reward) sleep(2) end end if reward >= 1 then quest_checklist = underscore.rest(quest_checklist) --remove first element in table if #quest_checklist == 0 then --quest has been succesfully finished terminal = true end end local vector = convert_text_to_bow(text) return vector, reward, terminal end --take a step in the game function step_game(action_index, object_index) data_out(build_command(actions[action_index], objects[object_index])) if DEBUG then print(actions[action_index] .. ' ' .. objects[object_index]) end STEP_COUNT = STEP_COUNT + 1 return getState() end -- TODO function nextRandomGame() end -- TODO function newGame() quest_checklist = {} STEP_COUNT = 0 random_teleport() random_quest() return getState(false) end -- build game command to send to the game function build_command(action, object) return action .. ' ' ..object end function parseLine( list_words, start_index) -- parse line to update symbols and symbol_mapping local sindx for i=start_index,#list_words do word = split(list_words[i], "%a+")[1] word = word:lower() if symbol_mapping[word] == nil then sindx = #symbols + 1 symbols[sindx] = word symbol_mapping[word] = sindx end end end -- read in text data from file with sentences (one sentence per line) - nicely tokenized function makeSymbolMapping(filename) local file = io.open(filename, "r"); local data = {} local parts for line in file:lines() do list_words = split(line, "%S+") if list_words[1] == '@detail' or list_words[1] == '@desc' then parseLine(list_words, 4) elseif list_words[1] == '@create/drop' then -- add to actionable objects table.insert(objects, split(list_words[2], "%a+")[1]) end end end -- Args: { -- 1: desc of room -- 2: quest desc -- 3: response from engine after executing command -- 4: <EOM> -- } function convert_text_to_bow(input_text) local vector = torch.zeros(#symbols) -- for j, line in pairs(input_text) do for j=1,2 do line = input_text[j] local list_words = split(line, "%a+") for i=1,#list_words do local word = list_words[i] word = word:lower() --ignore words not in vocab if symbol_mapping[word] then vector[symbol_mapping[word]] = vector[symbol_mapping[word]] + 1 end end end return vector end function getActions() return actions end function getObjects() return objects end return { makeSymbolMapping = makeSymbolMapping, getActions = getActions, getObjects = getObjects, getState = getState, step = step_game, newGame = newGame, nextRandomGame = nextRandomGame }
fixed
fixed
Lua
mit
karthikncode/text-world-player,ljm342/text-world-player,ljm342/text-world-player,karthikncode/text-world-player
1a93592ec31c630a5569d396e2cf4532b613a935
pb/proto/scanner.lua
pb/proto/scanner.lua
-- Copyright (c) 2010-2011 by Robert G. Jakabosky <[email protected]> -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. local _G = _G local upper = string.upper local lp = require"lpeg" local P=lp.P local S=lp.S local R=lp.R local B=lp.B local C=lp.C local Cf=lp.Cf local Cc=lp.Cc module(...) ------------------------------------------------------------------------------- ------------------------- Basic Patterns ------------------------------------------------------------------------------- -- numbers local num_sign = (S'+-') local digit = R'09' local hexLit = P"0" * S"xX" * (R('09','af','AF'))^1 local octLit = P"0" * (R'07')^1 local floatLit = (digit^1 * ((P".")^-1 * digit^0)^-1 * (S'eE' * num_sign^-1 * digit^1)^-1) local decLit = digit^1 local sdecLit = (P"-")^-1 * decLit -- alphanumeric local AZ = R('az','AZ') local AlphaNum = AZ + R('09') local identChar = AlphaNum + P"_" local not_identChar = -identChar local ident = (AZ + P"_") * (identChar)^0 local quote = P'"' ------------------------------------------------------------------------------- ------------------------- Util. functions. ------------------------------------------------------------------------------- local function line_accum(t, v) return t + v end local line_count = Cf(((Cc(1) * P"\n") + 1)^0, line_accum) function lines(subject) return line_count:match(subject) + 1 end function error(msg) return function (subject, i) local line = lines(subject:sub(1,i)) _G.error('Lexical error in line '..line..', near "' ..(subject:sub(i-10,i)):gsub('\n','EOL').. '": ' .. msg, 0) end end local function literals(tab, term) local ret = P(false) for i=1,#tab do -- remove literal from list. local lit = tab[i] tab[i] = nil -- make literal pattern local pat = P(lit) -- add terminal pattern if term then pat = pat * term end -- map LITERAL -> pattern(literal) tab[upper(lit)] = pat -- combind all literals into one pattern. ret = pat + ret end return ret end ------------------------------------------------------------------------------- ------------------------- Tokens ------------------------------------------------------------------------------- keywords = { -- package "package", "import", -- main types "message", "extend", "enum", "option", -- field modifiers "required", "optional", "repeated", -- message extensions "extensions", "to", "max", -- message groups "group", -- RPC "service", "rpc", "returns", -- buildin types "double", "float", "int32", "int64", "uint32", "uint64", "sint32", "sint64", "fixed32", "fixed64", "sfixed32", "sfixed64", "bool", "string", "bytes", -- booleans "true", "false", } KEYWORD = literals(keywords, not_identChar) symbols = { "=", ";", ".", ",", "{", "}", "(", ")", "[", "]", } SYMBOL = literals(symbols) INTEGER = hexLit + octLit + decLit SINTEGER = hexLit + octLit + sdecLit NUMERIC = hexLit + octLit + floatLit + decLit SNUMERIC = hexLit + octLit + floatLit + sdecLit IDENTIFIER = ident STRING = quote * ((1 - S'"\n\r\\') + (P'\\' * 1))^0 * (quote + error"unfinished string") COMMENT = (P"//" * (1 - P"\n")^0) + (P"/*" * (1 - P"*/")^0 * P"*/") ------------------------------------------------------------------------------- ------------------------- Other patterns ------------------------------------------------------------------------------- SPACE = S' \t\n\r' IGNORED = (SPACE + COMMENT)^0 TOKEN = IDENTIFIER + KEYWORD + SYMBOL + SNUMERIC + STRING ANY = TOKEN + COMMENT + SPACE BOF = P(function(s,i) return (i==1) and i end) EOF = P(-1)
-- Copyright (c) 2010-2011 by Robert G. Jakabosky <[email protected]> -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. local _G = _G local upper = string.upper local lp = require"lpeg" local P=lp.P local S=lp.S local R=lp.R local B=lp.B local C=lp.C local Cf=lp.Cf local Cc=lp.Cc module(...) ------------------------------------------------------------------------------- ------------------------- Basic Patterns ------------------------------------------------------------------------------- -- numbers local num_sign = (S'+-') local digit = R'09' local hexLit = P"0" * S"xX" * (R('09','af','AF'))^1 local octLit = P"0" * (R'07')^1 local floatLit = (digit^1 * ((P".")^-1 * digit^0)^-1 * (S'eE' * num_sign^-1 * digit^1)^-1) local decLit = digit^1 local sdecLit = (P"-")^-1 * decLit -- alphanumeric local AZ = R('az','AZ') local AlphaNum = AZ + R('09') local identChar = AlphaNum + P"_" local not_identChar = -identChar local ident = (AZ + P"_") * (identChar)^0 local quote = P'"' ------------------------------------------------------------------------------- ------------------------- Util. functions. ------------------------------------------------------------------------------- function lines(subject) local _, num = subject:gsub('\n','') return num + 1 end function error(msg) return function (subject, i) local line = lines(subject:sub(1,i)) _G.error('Lexical error in line '..line..', near "' ..(subject:sub(i-10,i)):gsub('\n','EOL').. '": ' .. msg, 0) end end local function literals(tab, term) local ret = P(false) for i=1,#tab do -- remove literal from list. local lit = tab[i] tab[i] = nil -- make literal pattern local pat = P(lit) -- add terminal pattern if term then pat = pat * term end -- map LITERAL -> pattern(literal) tab[upper(lit)] = pat -- combind all literals into one pattern. ret = pat + ret end return ret end ------------------------------------------------------------------------------- ------------------------- Tokens ------------------------------------------------------------------------------- keywords = { -- package "package", "import", -- main types "message", "extend", "enum", "option", -- field modifiers "required", "optional", "repeated", -- message extensions "extensions", "to", "max", -- message groups "group", -- RPC "service", "rpc", "returns", -- buildin types "double", "float", "int32", "int64", "uint32", "uint64", "sint32", "sint64", "fixed32", "fixed64", "sfixed32", "sfixed64", "bool", "string", "bytes", -- booleans "true", "false", } KEYWORD = literals(keywords, not_identChar) symbols = { "=", ";", ".", ",", "{", "}", "(", ")", "[", "]", } SYMBOL = literals(symbols) INTEGER = hexLit + octLit + decLit SINTEGER = hexLit + octLit + sdecLit NUMERIC = hexLit + octLit + floatLit + decLit SNUMERIC = hexLit + octLit + floatLit + sdecLit IDENTIFIER = ident STRING = quote * ((1 - S'"\n\r\\') + (P'\\' * 1))^0 * (quote + error"unfinished string") COMMENT = (P"//" * (1 - P"\n")^0) + (P"/*" * (1 - P"*/")^0 * P"*/") ------------------------------------------------------------------------------- ------------------------- Other patterns ------------------------------------------------------------------------------- SPACE = S' \t\n\r' IGNORED = (SPACE + COMMENT)^0 TOKEN = IDENTIFIER + KEYWORD + SYMBOL + SNUMERIC + STRING ANY = TOKEN + COMMENT + SPACE BOF = P(function(s,i) return (i==1) and i end) EOF = P(-1)
Fix line count function.
Fix line count function. Simplify line count function by using string.gsub instead of LPeg to count newlines.
Lua
mit
GabrielNicolasAvellaneda/lua-pb,tgregory/lua-pb
dd77110b6610b08c54d67e176ce42538b59efa76
game/scripts/vscripts/data/ability_shop.lua
game/scripts/vscripts/data/ability_shop.lua
ABILITY_SHOP_DATA = { ["obsidian_destroyer_essence_aura"] = { banned_with = {"storm_spirit_ball_lightning", "bristleback_quill_spray", }, }, ["batrider_sticky_napalm"] = { banned_with = {"sandking_sand_storm", "shadow_shaman_shackles", "doom_bringer_scorched_earth", "venomancer_venomous_gale", "venomancer_poison_nova", "ember_spirit_flame_guard", "weaver_the_swarm", "dark_seer_ion_shell", "sandking_sand_storm", "warlock_fatal_bonds_arena", }, }, ["doom_bringer_scorched_earth"] = { banned_with = {"batrider_sticky_napalm", }, }, ["storm_spirit_ball_lightning"] = { banned_with = {"earthshaker_aftershock", "obsidian_destroyer_essence_aura", "zuus_static_field", }, }, ["earthshaker_aftershock"] = { banned_with = {"obsidian_destroyer_arcane_orb", "storm_spirit_ball_lightning", }, }, ["shadow_shaman_shackles"] = { banned_with = {"batrider_sticky_napalm", }, }, ["venomancer_venomous_gale"] = { banned_with = {"batrider_sticky_napalm", }, }, ["venomancer_poison_nova"] = { banned_with = {"batrider_sticky_napalm", }, }, ["ember_spirit_flame_guard"] = { banned_with = {"batrider_sticky_napalm", }, }, ["weaver_the_swarm"] = { banned_with = {"batrider_sticky_napalm", }, }, ["dark_seer_ion_shell"] = { banned_with = {"batrider_sticky_napalm", }, }, ["warlock_fatal_bonds_arena"] = { banned_with = {"batrider_sticky_napalm", }, }, ["zuus_static_field"] = { banned_with = {"storm_spirit_ball_lightning", "obsidian_destroyer_arcane_orb", "storm_spirit_ball_lightning", "bristleback_quill_spray", }, }, ["sandking_sand_storm"] = { banned_with = {"batrider_sticky_napalm", }, }, ["obsidian_destroyer_arcane_orb"] = { banned_with = {"zuus_static_field", "earthshaker_aftershock", "bristleback_quill_spray", }, }, ["bristleback_quill_spray"] = { banned_with = {"obsidian_destroyer_essence_aura", "zuus_static_field", }, }, ["storm_spirit_overload"] = { banned_with = {"troll_warlord_berserkers_rage", "wisp_spirits_out_aghanims", "wisp_spirits_in_aghanims", "wisp_overcharge_aghanims", "rocket_barrage_arena", "cherub_synthesis", "pudge_rot_arena", "pudge_rot", "skeleton_king_vampiric_aura", "witch_doctor_voodoo_restoration", "leshrac_pulse_nova", "wisp_overcharge", }, }, ["troll_warlord_berserkers_rage"] = { banned_with = {"storm_spirit_overload", }, }, ["wisp_spirits_out_aghanims"] = { banned_with = {"storm_spirit_overload", }, }, ["wisp_spirits_in_aghanims"] = { banned_with = {"storm_spirit_overload", }, }, ["wisp_overcharge_aghanims"] = { banned_with = {"storm_spirit_overload", }, }, ["rocket_barrage_arena"] = { banned_with = {"storm_spirit_overload", }, }, ["cherub_synthesis"] = { banned_with = {"storm_spirit_overload", }, }, ["pudge_rot_arena"] = { banned_with = {"storm_spirit_overload", }, }, ["pudge_rot"] = { banned_with = {"storm_spirit_overload", }, }, ["skeleton_king_vampiric_aura"] = { banned_with = {"storm_spirit_overload", }, }, ["witch_doctor_voodoo_restoration"] = { banned_with = {"storm_spirit_overload", }, }, ["leshrac_pulse_nova"] = { banned_with = {"storm_spirit_overload", }, }, ["wisp_overcharge"] = { banned_with = {"storm_spirit_overload", }, }, ["pudge_meat_hook_lua"] = { banned_with = {"furion_teleportation", "kunkka_x_marks_the_spot", "ogre_magi_multicast_arena", }, }, ["furion_teleportation"] = { banned_with = {"pudge_meat_hook_lua", }, }, ["kunkka_x_marks_the_spot"] = { banned_with = {"pudge_meat_hook_lua", }, }, ["ogre_magi_multicast_arena"] = { banned_with = {"pudge_meat_hook_lua", }, }, ["puck_ethereal_jaunt"] = { cost = 0, }, ["shadow_demon_shadow_poison_release"] = { cost = 0, }, ["spectre_reality"] = { cost = 0, }, ["templar_assassin_trap"] = { cost = 0, }, ["techies_focused_detonate"] = { cost = 0, }, ["tinker_rearm_arena"] = { cost = 16, }, ["ogre_magi_multicast_arena"] = { cost = 10, }, ["alchemist_goblins_greed"] = { cost = 4, }, ["kunkka_tidebringer"] = { cost = 3, }, ["earthshaker_enchant_totem"] = { cost = 2, }, ["medusa_split_shot_arena"] = { cost = 3, }, ["medusa_mystic_snake_arena"] = { cost = 4, }, ["medusa_mana_shield_arena"] = { cost = 2, }, ["medusa_stone_gaze_arena"] = { cost = 9, }, ["slark_essence_shift"] = { cost = 2, }, ["sven_great_cleave"] = { cost = 4, }, ["axe_counter_helix"] = { cost = 2, }, ["sandking_caustic_finale"] = { cost = 2, }, ["beastmaster_wild_axes"] = { cost = 2, }, ["weaver_geminate_attack"] = { cost = 5, }, ["riki_permanent_invisibility"] = { cost = 2, }, ["shinobu_vampire_blood"] = { cost = 7, }, ["ember_spirit_sleight_of_fist"] = { cost = 10, }, ["flak_cannon_arena"] = { cost = 4, }, ["omniknight_select_allies"] = { cost = 4, }, ["dark_seer_ion_shell"] = { cost = 5, }, } ABILITY_SHOP_SKIP_HEROES = { "npc_dota_hero_invoker", "npc_dota_hero_earth_spirit", } ABILITY_SHOP_SKIP_ABILITIES = { "rubick_spell_steal", "rubick_empty1", "rubick_empty2", "broodmother_spin_web", "morphling_morph", "morphling_morph_agi", "morphling_morph_str", "keeper_of_the_light_recall", "keeper_of_the_light_blinding_light", "wisp_empty1", "wisp_empty2", "doom_bringer_empty1", "doom_bringer_empty2", "phoenix_sun_ray", "phoenix_sun_ray_toggle_move_empty", "ogre_magi_unrefined_fireblast", }
ABILITY_SHOP_DATA = { ["obsidian_destroyer_essence_aura"] = { banned_with = {"storm_spirit_ball_lightning", "bristleback_quill_spray", }, }, ["batrider_sticky_napalm"] = { banned_with = {"sandking_sand_storm", "shadow_shaman_shackles", "doom_bringer_scorched_earth", "venomancer_venomous_gale", "venomancer_poison_nova", "ember_spirit_flame_guard", "weaver_the_swarm", "dark_seer_ion_shell", "sandking_sand_storm", "warlock_fatal_bonds_arena", }, }, ["doom_bringer_scorched_earth"] = { banned_with = {"batrider_sticky_napalm", }, }, ["storm_spirit_ball_lightning"] = { banned_with = {"earthshaker_aftershock", "obsidian_destroyer_essence_aura", "zuus_static_field", }, }, ["earthshaker_aftershock"] = { banned_with = {"obsidian_destroyer_arcane_orb", "storm_spirit_ball_lightning", }, }, ["shadow_shaman_shackles"] = { banned_with = {"batrider_sticky_napalm", }, }, ["venomancer_venomous_gale"] = { banned_with = {"batrider_sticky_napalm", }, }, ["venomancer_poison_nova"] = { banned_with = {"batrider_sticky_napalm", }, }, ["ember_spirit_flame_guard"] = { banned_with = {"batrider_sticky_napalm", }, }, ["weaver_the_swarm"] = { banned_with = {"batrider_sticky_napalm", }, }, ["dark_seer_ion_shell"] = { banned_with = {"batrider_sticky_napalm", }, }, ["warlock_fatal_bonds_arena"] = { banned_with = {"batrider_sticky_napalm", }, }, ["zuus_static_field"] = { banned_with = {"storm_spirit_ball_lightning", "obsidian_destroyer_arcane_orb", "storm_spirit_ball_lightning", "bristleback_quill_spray", }, }, ["sandking_sand_storm"] = { banned_with = {"batrider_sticky_napalm", }, }, ["obsidian_destroyer_arcane_orb"] = { banned_with = {"zuus_static_field", "earthshaker_aftershock", "bristleback_quill_spray", }, }, ["bristleback_quill_spray"] = { banned_with = {"obsidian_destroyer_essence_aura", "zuus_static_field", }, }, ["storm_spirit_overload"] = { banned_with = {"troll_warlord_berserkers_rage", "wisp_spirits_out_aghanims", "wisp_spirits_in_aghanims", "wisp_overcharge_aghanims", "rocket_barrage_arena", "cherub_synthesis", "pudge_rot_arena", "pudge_rot", "skeleton_king_vampiric_aura", "witch_doctor_voodoo_restoration", "leshrac_pulse_nova", "wisp_overcharge", }, }, ["troll_warlord_berserkers_rage"] = { banned_with = {"storm_spirit_overload", }, }, ["wisp_spirits_out_aghanims"] = { banned_with = {"storm_spirit_overload", }, }, ["wisp_spirits_in_aghanims"] = { banned_with = {"storm_spirit_overload", }, }, ["wisp_overcharge_aghanims"] = { banned_with = {"storm_spirit_overload", }, }, ["rocket_barrage_arena"] = { banned_with = {"storm_spirit_overload", }, }, ["cherub_synthesis"] = { banned_with = {"storm_spirit_overload", }, }, ["pudge_rot_arena"] = { banned_with = {"storm_spirit_overload", }, }, ["pudge_rot"] = { banned_with = {"storm_spirit_overload", }, }, ["skeleton_king_vampiric_aura"] = { banned_with = {"storm_spirit_overload", }, }, ["witch_doctor_voodoo_restoration"] = { banned_with = {"storm_spirit_overload", }, }, ["leshrac_pulse_nova"] = { banned_with = {"storm_spirit_overload", }, }, ["wisp_overcharge"] = { banned_with = {"storm_spirit_overload", }, }, ["pudge_meat_hook_lua"] = { banned_with = {"furion_teleportation", "kunkka_x_marks_the_spot", "ogre_magi_multicast_arena", }, }, ["furion_teleportation"] = { banned_with = {"pudge_meat_hook_lua", }, }, ["kunkka_x_marks_the_spot"] = { banned_with = {"pudge_meat_hook_lua", }, }, ["ogre_magi_multicast_arena"] = { banned_with = {"pudge_meat_hook_lua", }, }, ["puck_ethereal_jaunt"] = { cost = 0, }, ["shadow_demon_shadow_poison_release"] = { cost = 0, }, ["spectre_reality"] = { cost = 0, }, ["templar_assassin_trap"] = { cost = 0, }, ["techies_focused_detonate"] = { cost = 0, }, ["tinker_rearm_arena"] = { cost = 16, }, ["ogre_magi_multicast_arena"] = { cost = 10, }, ["alchemist_goblins_greed"] = { cost = 4, }, ["kunkka_tidebringer"] = { cost = 3, }, ["earthshaker_enchant_totem"] = { cost = 2, }, ["medusa_split_shot_arena"] = { cost = 3, }, ["medusa_mystic_snake_arena"] = { cost = 4, }, ["medusa_mana_shield_arena"] = { cost = 2, }, ["medusa_stone_gaze_arena"] = { cost = 9, }, ["slark_essence_shift"] = { cost = 2, }, ["sven_great_cleave"] = { cost = 4, }, ["axe_counter_helix"] = { cost = 2, }, ["sandking_caustic_finale"] = { cost = 2, }, ["beastmaster_wild_axes"] = { cost = 2, }, ["weaver_geminate_attack"] = { cost = 5, }, ["riki_permanent_invisibility"] = { cost = 2, }, ["shinobu_vampire_blood"] = { cost = 7, }, ["ember_spirit_sleight_of_fist"] = { cost = 10, }, ["flak_cannon_arena"] = { cost = 4, }, ["omniknight_select_allies"] = { cost = 4, }, ["dark_seer_ion_shell"] = { cost = 5, }, ["warlock_fatal_bonds_arena"] = { cost = 2, }, } ABILITY_SHOP_SKIP_HEROES = { "npc_dota_hero_invoker", "npc_dota_hero_earth_spirit", } ABILITY_SHOP_SKIP_ABILITIES = { "rubick_spell_steal", "rubick_empty1", "rubick_empty2", "broodmother_spin_web", "morphling_morph", "morphling_morph_agi", "morphling_morph_str", "keeper_of_the_light_recall", "keeper_of_the_light_blinding_light", "wisp_empty1", "wisp_empty2", "doom_bringer_empty1", "doom_bringer_empty2", "phoenix_sun_ray", "phoenix_sun_ray_toggle_move_empty", "ogre_magi_unrefined_fireblast", }
Fix Warlock
Fix Warlock
Lua
mit
ark120202/aabs
d469c795e03e57187c1adb5cfc4e8541c40218bd
MMOCoreORB/bin/scripts/object/building/military/outpost_starport.lua
MMOCoreORB/bin/scripts/object/building/military/outpost_starport.lua
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_building_military_outpost_starport = object_building_military_shared_outpost_starport:new { gameObjectType = 521, } ObjectTemplates:addTemplate(object_building_military_outpost_starport, "object/building/military/outpost_starport.iff")
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_building_military_outpost_starport = object_building_military_shared_outpost_starport:new { gameObjectType = 521, planetMapCategory = "starport", childObjects = { {templateFile = "object/tangible/terminal/terminal_travel.iff", x = -3.12, z = 0.14659503, y = -17.57, ox = 0, oy = 0.707107, oz = 0, ow = -0.707107, cellid = 0, containmentType = -1}, {templateFile = "object/tangible/travel/ticket_collector/ticket_collector.iff", x = 1, z = 0, y = -10, ox = 0, oy = 0, oz = 0, ow = 1, cellid = -1, containmentType = -1}, {templateFile = "object/mobile/player_transport.iff", x = 0, z = 7, y = 0, ox = 0, oy = 0.707107, oz = 0, ow = 0.707107, cellid = -1, containmentType = -1} } } ObjectTemplates:addTemplate(object_building_military_outpost_starport, "object/building/military/outpost_starport.iff")
[fixed] Dantooine, Dathomir, Endor, Lok, and Talus starports now have travel terminals, ticket collectors, and shuttles.
[fixed] Dantooine, Dathomir, Endor, Lok, and Talus starports now have travel terminals, ticket collectors, and shuttles. git-svn-id: c34995188cc7e843f8a799edec2d9d4b36f36456@3233 c3d1530f-68f5-4bd0-87dc-8ef779617e40
Lua
agpl-3.0
lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo
72de4f0c738e61a35ba49a778a0d2b1cfd436cbc
MMOCoreORB/bin/scripts/object/tangible/food/crafted/dish_protato.lua
MMOCoreORB/bin/scripts/object/tangible/food/crafted/dish_protato.lua
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_tangible_food_crafted_dish_protato = object_tangible_food_crafted_shared_dish_protato:new { templateType = CONSUMABLE, duration = 0, filling = 10, nutrition = 10, effectType = 0, fillingMin = 17, fillingMax = 10, flavorMin = 1200, flavorMax = 2400, nutritionMin = 10, nutritionMax = 20, quantityMin = 6, quantityMax = 10, modifiers = { }, buffName = "", buffCRC = 0, speciesRestriction = "" } ObjectTemplates:addTemplate(object_tangible_food_crafted_dish_protato, "object/tangible/food/crafted/dish_protato.iff")
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_tangible_food_crafted_dish_protato = object_tangible_food_crafted_shared_dish_protato:new { gameObjectType = 262144 } ObjectTemplates:addTemplate(object_tangible_food_crafted_dish_protato, "object/tangible/food/crafted/dish_protato.iff")
[Fixed] Protato crafting
[Fixed] Protato crafting git-svn-id: c34995188cc7e843f8a799edec2d9d4b36f36456@2711 c3d1530f-68f5-4bd0-87dc-8ef779617e40
Lua
agpl-3.0
lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo
ab721d103484fd2fb5c6410b8f236a34fca49ab1
mods/sponge/init.lua
mods/sponge/init.lua
minetest.register_node("sponge:sponge", { description = "Sponge Dry", drawtype = "normal", tiles = {"sponge_sponge.png"}, paramtype = 'light', walkable = true, pointable = true, diggable = true, buildable_to = false, stack_max = 99, groups = {snappy=2,choppy=2,oddly_breakable_by_hand=3,flammable=3}, after_place_node = function(pos, placer, itemstack, pointed_thing) local pn = placer:get_player_name() if pointed_thing.type ~= "node" then return end if minetest.is_protected(pointed_thing.above, pn) then return end local change = false local on_water = false local pos = pointed_thing.above -- verifier si il est dans l'eau ou a cotée if string.find(minetest.get_node(pointed_thing.above).name, "water_source") or string.find(minetest.get_node(pointed_thing.above).name, "water_flowing") then on_water = true end for i=-1,1 do p = {x=pos.x+i, y=pos.y, z=pos.z} n = minetest.get_node(p) -- On verifie si il y a de l'eau if (n.name=="default:water_flowing") or (n.name == "default:water_source") then on_water = true end end for i=-1,1 do p = {x=pos.x, y=pos.y+i, z=pos.z} n = minetest.get_node(p) -- On verifie si il y a de l'eau if (n.name=="default:water_flowing") or (n.name == "default:water_source") then on_water = true end end for i=-1,1 do p = {x=pos.x, y=pos.y, z=pos.z+i} n = minetest.get_node(p) -- On verifie si il y a de l'eau if (n.name=="default:water_flowing") or (n.name == "default:water_source") then on_water = true end end if on_water == true then for i=-3,3 do for j=-3,3 do for k=-3,3 do p = {x=pos.x+i, y=pos.y+j, z=pos.z+k} n = minetest.get_node(p) -- On Supprime l'eau if (n.name=="default:water_flowing") or (n.name == "default:water_source")then minetest.add_node(p, {name="air"}) change = true end end end end end if change then minetest.add_node(pointed_thing.above, {name = "sponge:sponge_wet"}) end p = {x=pos.x, y=pos.y, z=pos.z} n = minetest.get_node(p) end }) minetest.register_node("sponge:sponge_wet", { description = "Wet Sponge", drawtype = "normal", tiles = {"sponge_sponge_wet.png"}, paramtype = 'light', walkable = true, pointable = true, diggable = true, buildable_to = false, stack_max = 99, groups = {snappy=2,choppy=2,oddly_breakable_by_hand=3}, }) -- Sponge wet back to Sponge Dry if coocked in a furnace minetest.register_craft({ type = "cooking", output = "sponge:sponge", recipe = "sponge:sponge_wet", }) minetest.register_craft({ output = "sponge:sponge", recipe = { {"", "dye:black", ""}, {"dye:yellow", "wool:white", "dye:yellow"}, {"", "farming:wheat", ""}, }, })
minetest.register_node("sponge:sponge", { description = "Sponge Dry", drawtype = "normal", tiles = {"sponge_sponge.png"}, paramtype = 'light', walkable = true, pointable = true, diggable = true, buildable_to = false, stack_max = 99, groups = {snappy=2,choppy=2,oddly_breakable_by_hand=3,flammable=3}, after_place_node = function(pos, placer, itemstack, pointed_thing) local pn = placer:get_player_name() if pointed_thing.type ~= "node" then return end if minetest.is_protected(pointed_thing.above, pn) then return end local change = false local on_water = false -- verifier si il est dans l'eau ou a cotée if string.find(minetest.get_node(pointed_thing.above).name, "water_source") or string.find(minetest.get_node(pointed_thing.above).name, "water_flowing") then on_water = true end for i=-1,1 do p = {x=pos.x+i, y=pos.y, z=pos.z} n = minetest.get_node(p) -- On verifie si il y a de l'eau if (n.name=="default:water_flowing") or (n.name == "default:water_source") then on_water = true end end for i=-1,1 do p = {x=pos.x, y=pos.y+i, z=pos.z} n = minetest.get_node(p) -- On verifie si il y a de l'eau if (n.name=="default:water_flowing") or (n.name == "default:water_source") then on_water = true end end for i=-1,1 do p = {x=pos.x, y=pos.y, z=pos.z+i} n = minetest.get_node(p) -- On verifie si il y a de l'eau if (n.name=="default:water_flowing") or (n.name == "default:water_source") then on_water = true end end if on_water == true then for i=-3,3 do for j=-3,3 do for k=-3,3 do p = {x=pos.x+i, y=pos.y+j, z=pos.z+k} n = minetest.get_node(p) -- On Supprime l'eau if (n.name=="default:water_flowing") or (n.name == "default:water_source")then minetest.add_node(p, {name="air"}) change = true end end end end end if change then minetest.add_node(pos, {name = "sponge:sponge_wet"}) end end }) minetest.register_node("sponge:sponge_wet", { description = "Wet Sponge", drawtype = "normal", tiles = {"sponge_sponge_wet.png"}, paramtype = 'light', walkable = true, pointable = true, diggable = true, buildable_to = false, stack_max = 99, groups = {snappy=2,choppy=2,oddly_breakable_by_hand=3}, }) -- Sponge wet back to Sponge Dry if coocked in a furnace minetest.register_craft({ type = "cooking", output = "sponge:sponge", recipe = "sponge:sponge_wet", }) minetest.register_craft({ output = "sponge:sponge", recipe = { {"", "dye:black", ""}, {"dye:yellow", "wool:white", "dye:yellow"}, {"", "farming:wheat", ""}, }, })
[sponge] Fix positions
[sponge] Fix positions
Lua
unlicense
MinetestForFun/server-minetestforfun-creative,MinetestForFun/server-minetestforfun-creative,MinetestForFun/server-minetestforfun-creative
99ee3763c1dae9c0dd7e28aa6fae0a2a79c7b1c1
frontend/ui/elements/mass_storage.lua
frontend/ui/elements/mass_storage.lua
local Device = require("device") local UIManager = require("ui/uimanager") local _ = require("gettext") local MassStorage = {} -- if required a popup will ask before entering mass storage mode function MassStorage:requireConfirmation() return not G_reader_settings:isTrue("mass_storage_confirmation_disabled") end function MassStorage:isEnabled() return not G_reader_settings:isTrue("mass_storage_disabled") end -- mass storage settings menu function MassStorage:getSettingsMenuTable() return { { text = _("Disable confirmation popup"), help_text = _([[This will ONLY affect what happens when you plug in the device!]]), checked_func = function() return not self:requireConfirmation() end, callback = function() G_reader_settings:saveSetting("mass_storage_confirmation_disabled", self:requireConfirmation()) end, }, { text = _("Disable mass storage functionality"), help_text = _([[In case your device uses an unsupported setup where you know it won't work properly.]]), checked_func = function() return not self:isEnabled() end, callback = function() G_reader_settings:saveSetting("mass_storage_disabled", self:isEnabled()) end, }, } end -- mass storage actions function MassStorage:getActionsMenuTable() return { text = _("Start USB storage"), enabled_func = function() return self:isEnabled() end, callback = function() self:start(true) end, } end -- exit KOReader and start mass storage mode. function MassStorage:start(never_ask) if not Device:canToggleMassStorage() or not self:isEnabled() then return end if not never_ask and self:requireConfirmation() then local ConfirmBox = require("ui/widget/confirmbox") UIManager:show(ConfirmBox:new{ text = _("Share storage via USB?"), ok_text = _("Share"), ok_callback = function() -- save settings before activating USBMS: UIManager:flushSettings() UIManager:quit() UIManager._exit_code = 86 end, }) else -- save settings before activating USBMS: UIManager:flushSettings() UIManager:quit() UIManager._exit_code = 86 end end return MassStorage
local Device = require("device") local Event = require("ui/event") local UIManager = require("ui/uimanager") local _ = require("gettext") local MassStorage = {} -- if required a popup will ask before entering mass storage mode function MassStorage:requireConfirmation() return not G_reader_settings:isTrue("mass_storage_confirmation_disabled") end function MassStorage:isEnabled() return not G_reader_settings:isTrue("mass_storage_disabled") end -- mass storage settings menu function MassStorage:getSettingsMenuTable() return { { text = _("Disable confirmation popup"), help_text = _([[This will ONLY affect what happens when you plug in the device!]]), checked_func = function() return not self:requireConfirmation() end, callback = function() G_reader_settings:saveSetting("mass_storage_confirmation_disabled", self:requireConfirmation()) end, }, { text = _("Disable mass storage functionality"), help_text = _([[In case your device uses an unsupported setup where you know it won't work properly.]]), checked_func = function() return not self:isEnabled() end, callback = function() G_reader_settings:saveSetting("mass_storage_disabled", self:isEnabled()) end, }, } end -- mass storage actions function MassStorage:getActionsMenuTable() return { text = _("Start USB storage"), enabled_func = function() return self:isEnabled() end, callback = function() self:start(true) end, } end -- exit KOReader and start mass storage mode. function MassStorage:start(never_ask) if not Device:canToggleMassStorage() or not self:isEnabled() then return end if not never_ask and self:requireConfirmation() then local ConfirmBox = require("ui/widget/confirmbox") UIManager:show(ConfirmBox:new{ text = _("Share storage via USB?"), ok_text = _("Share"), ok_callback = function() -- save settings before activating USBMS: UIManager:flushSettings() UIManager._exit_code = 86 UIManager:broadcastEvent(Event:new("Close")) UIManager:quit() end, }) else -- save settings before activating USBMS: UIManager:flushSettings() UIManager._exit_code = 86 UIManager:broadcastEvent(Event:new("Close")) UIManager:quit() end end return MassStorage
USBMS: Close all widgets before quitting
USBMS: Close all widgets before quitting FFI finalizers can fire in unspecified orders, but for MuPDF, we need to ensure that the context is the *very* last thing that get destroyed. As such, we need to make sure we close open documents properly on our end, first. This prevents potential crashes while switchign to USBMS inside an open document handled by MuPDF. Fix #7428
Lua
agpl-3.0
poire-z/koreader,Frenzie/koreader,NiLuJe/koreader,poire-z/koreader,koreader/koreader,Frenzie/koreader,koreader/koreader,NiLuJe/koreader
b2765fe84c13937268354f9d6134078a0afde3db
xc/priority_auths.lua
xc/priority_auths.lua
local redis_pool = require 'xc/redis_pool' local authorizations_formatter = require 'xc/authorizations_formatter' local storage_keys = require 'xc/storage_keys' local _M = { } -- @return true if the authorization could be retrieved, false otherwise -- @return true if authorized, false if denied, nil if unknown -- @return reason why the authorization is denied (optional, required only when denied) function _M.authorize(service_id, credentials, metric) local redis_pub, ok_pub, err = redis_pool.acquire() if not ok_pub then ngx.log(ngx.WARN, "[priority auths] couldn't connect to redis pub: ", err) return false, nil end local redis_sub, ok_sub redis_sub, ok_sub, err = redis_pool.acquire() if not ok_sub then ngx.log(ngx.WARN, "[priority auths] couldn't connect to redis sub: ", err) redis_pool.release(redis_pub) return false, nil end local res_pub res_pub, err = redis_pub:publish(storage_keys.AUTH_REQUESTS_CHANNEL, storage_keys.get_pubsub_req_msg(service_id, credentials, metric)) redis_pool.release(redis_pub) if not res_pub then ngx.log(ngx.WARN, "[priority auths] couldn't publish to the auth requests channel:", err) redis_pool.release(redis_sub) return false, nil end local res_sub res_sub, err = redis_sub:subscribe( storage_keys.get_pubsub_auths_resp_channel(service_id, credentials, metric)) if not res_sub then ngx.log(ngx.WARN, "[priority auths] couldn't subscribe to the auth response channel: ", err) redis_pool.release(redis_sub) return false, nil end local channel_reply channel_reply, err = redis_sub:read_reply() if not channel_reply then ngx.log(ngx.WARN, "[priority auths] couldn't read the reply from auth response channel: ", err) redis_pool.release(redis_sub) return false, nil end local auth_msg = channel_reply[3] -- the value returned is in pos 3 redis_pool.release(redis_sub) if not auth_msg then return false, nil end local auth, reason = authorizations_formatter.authorization(auth_msg) return true, auth, reason end return _M
local redis_pool = require 'xc/redis_pool' local authorizations_formatter = require 'xc/authorizations_formatter' local storage_keys = require 'xc/storage_keys' local _M = { } -- @return true if the authorization could be retrieved, false otherwise -- @return true if authorized, false if denied, nil if unknown -- @return reason why the authorization is denied (optional, required only when denied) function _M.authorize(service_id, credentials, metric) local redis_sub, ok_sub, err = redis_pool.acquire() if not ok_sub then ngx.log(ngx.WARN, "[priority auths] couldn't connect to redis sub: ", err) return false, nil end local res_sub res_sub, err = redis_sub:subscribe( storage_keys.get_pubsub_auths_resp_channel(service_id, credentials, metric)) if not res_sub then ngx.log(ngx.WARN, "[priority auths] couldn't subscribe to the auth response channel: ", err) redis_pool.release(redis_sub) return false, nil end local redis_pub, ok_pub redis_pub, ok_pub, err = redis_pool.acquire() if not ok_pub then ngx.log(ngx.WARN, "[priority auths] couldn't connect to redis pub: ", err) redis_pool.release(redis_sub) return false, nil end local res_pub res_pub, err = redis_pub:publish(storage_keys.AUTH_REQUESTS_CHANNEL, storage_keys.get_pubsub_req_msg(service_id, credentials, metric)) redis_pool.release(redis_pub) if not res_pub then ngx.log(ngx.WARN, "[priority auths] couldn't publish to the auth requests channel:", err) redis_pool.release(redis_sub) return false, nil end local channel_reply channel_reply, err = redis_sub:read_reply() if not channel_reply then ngx.log(ngx.WARN, "[priority auths] couldn't read the reply from auth response channel: ", err) redis_pool.release(redis_sub) return false, nil end local auth_msg = channel_reply[3] -- the value returned is in pos 3 redis_pool.release(redis_sub) if not auth_msg then return false, nil end local auth, reason = authorizations_formatter.authorization(auth_msg) return true, auth, reason end return _M
priority_auths: subscribe before publishing
priority_auths: subscribe before publishing We initially had this in the reverse order (creating a race condition) because the API from lua-redis imposed so. However, the api from resty.redis does not, so fix the race here.
Lua
apache-2.0
3scale/apicast-xc
4e36e11b5f9458c5813141d4344f720634af640f
src_trunk/resources/realism-system/s_reload.lua
src_trunk/resources/realism-system/s_reload.lua
local noReloadGuns = { [25]=true, [33]=true, [34]=true, [35]=true, [36]=true, [37]=true } function reloadWeapon(thePlayer) local weapon = getPlayerWeapon(thePlayer) local ammo = getPlayerTotalAmmo(thePlayer) local reloading = getElementData(thePlayer, "reloading") local jammed = getElementData(thePlayer, "jammed") if (reloading==false) and not (isPedInVehicle(thePlayer)) and ((jammed==0) or not jammed) then if (weapon) and (ammo) then if (weapon>21) and (weapon<35) and not (noReloadGuns[weapon]) then toggleControl(thePlayer, "fire", false) toggleControl(thePlayer, "next_weapon", false) toggleControl(thePlayer, "previous_weapon", false) setElementData(thePlayer, "reloading", true, false) setTimer(checkFalling, 100, 10, thePlayer) if not (isPedDucked(thePlayer)) then exports.global:applyAnimation(thePlayer, "BUDDY", "buddy_reload", 1000, false, true, true) toggleAllControls(thePlayer, true, true, true) end setTimer(giveReload, 1001, 1, thePlayer, weapon, ammo) triggerClientEvent(thePlayer, "cleanupUI", thePlayer, true) end end end end addCommandHandler("reload", reloadWeapon) function checkFalling(thePlayer) local reloading = getElementData(thePlayer, "reloading") if not (isPedOnGround(thePlayer)) and (reloading) then removeElementData(thePlayer, "reloading.timer") -- reset state removeElementData(thePlayer, "reloading.timer") exports.global:removeAnimation(thePlayer) setElementData(thePlayer, "reloading", false, false) toggleControl(thePlayer, "fire", true) toggleControl(thePlayer, "next_weapon", true) toggleControl(thePlayer, "previous_weapon", true) end end function giveReload(thePlayer, weapon, ammo) removeElementData(thePlayer, "reloading.timer") exports.global:removeAnimation(thePlayer) takeWeapon(thePlayer, weapon) giveWeapon(thePlayer, weapon, ammo, true) setElementData(thePlayer, "reloading", false, false) toggleControl(thePlayer, "fire", true) toggleControl(thePlayer, "next_weapon", true) toggleControl(thePlayer, "previous_weapon", true) exports.global:givePlayerAchievement(thePlayer, 14) exports.global:sendLocalMeAction(thePlayer, "reloads their " .. getWeaponNameFromID(weapon) .. ".") end -- Bind Keys required function bindKeys() local players = exports.pool:getPoolElementsByType("player") for k, arrayPlayer in ipairs(players) do if not(isKeyBound(arrayPlayer, "r", "down", reloadWeapon)) then bindKey(arrayPlayer, "r", "down", reloadWeapon) end end end function bindKeysOnJoin() bindKey(source, "r", "down", reloadWeapon) end addEventHandler("onResourceStart", getRootElement(), bindKeys) addEventHandler("onPlayerJoin", getRootElement(), bindKeysOnJoin) function giveFakeBullet(weapon, ammo) setWeaponAmmo(source, weapon, ammo, 1) end addEvent("addFakeBullet", true) addEventHandler("addFakeBullet", getRootElement(), giveFakeBullet)
local noReloadGuns = { [25]=true, [33]=true, [34]=true, [35]=true, [36]=true, [37]=true } local clipSize = { [22]=17, [23]=17, [24]=7, [26]=2, [27]=7, [28]=50, [29]=30, [30]=30, [31]=50, [32]=50 } function reloadWeapon(thePlayer) local weapon = getPlayerWeapon(thePlayer) local ammo = getPlayerTotalAmmo(thePlayer) local reloading = getElementData(thePlayer, "reloading") local jammed = getElementData(thePlayer, "jammed") if (reloading==false) and not (isPedInVehicle(thePlayer)) and ((jammed==0) or not jammed) then if (weapon) and (ammo) then if (weapon>21) and (weapon<35) and not (noReloadGuns[weapon]) then toggleControl(thePlayer, "fire", false) toggleControl(thePlayer, "next_weapon", false) toggleControl(thePlayer, "previous_weapon", false) setElementData(thePlayer, "reloading", true, false) setTimer(checkFalling, 100, 10, thePlayer) if not (isPedDucked(thePlayer)) then exports.global:applyAnimation(thePlayer, "BUDDY", "buddy_reload", 1000, false, true, true) toggleAllControls(thePlayer, true, true, true) end setTimer(giveReload, 1001, 1, thePlayer, weapon, ammo) triggerClientEvent(thePlayer, "cleanupUI", thePlayer, true) end end end end addCommandHandler("reload", reloadWeapon) function checkFalling(thePlayer) local reloading = getElementData(thePlayer, "reloading") if not (isPedOnGround(thePlayer)) and (reloading) then removeElementData(thePlayer, "reloading.timer") -- reset state removeElementData(thePlayer, "reloading.timer") exports.global:removeAnimation(thePlayer) setElementData(thePlayer, "reloading", false, false) toggleControl(thePlayer, "fire", true) toggleControl(thePlayer, "next_weapon", true) toggleControl(thePlayer, "previous_weapon", true) end end function giveReload(thePlayer, weapon, ammo) local clipsize = 0 removeElementData(thePlayer, "reloading.timer") exports.global:removeAnimation(thePlayer) if (ammo < clipSize[weapon]) then clipsize = ammo else clipsize = clipSize[weapon] end setWeaponAmmo(thePlayer, weapon, ammo, clipsize) -- fix for the ammo adding up bug --takeWeapon(thePlayer, weapon) --giveWeapon(thePlayer, weapon, ammo, true) setElementData(thePlayer, "reloading", false, false) toggleControl(thePlayer, "fire", true) toggleControl(thePlayer, "next_weapon", true) toggleControl(thePlayer, "previous_weapon", true) exports.global:givePlayerAchievement(thePlayer, 14) exports.global:sendLocalMeAction(thePlayer, "reloads their " .. getWeaponNameFromID(weapon) .. ".") end -- Bind Keys required function bindKeys() local players = exports.pool:getPoolElementsByType("player") for k, arrayPlayer in ipairs(players) do if not(isKeyBound(arrayPlayer, "r", "down", reloadWeapon)) then bindKey(arrayPlayer, "r", "down", reloadWeapon) end end end function bindKeysOnJoin() bindKey(source, "r", "down", reloadWeapon) end addEventHandler("onResourceStart", getRootElement(), bindKeys) addEventHandler("onPlayerJoin", getRootElement(), bindKeysOnJoin) function giveFakeBullet(weapon, ammo) setWeaponAmmo(source, weapon, ammo, 1) end addEvent("addFakeBullet", true) addEventHandler("addFakeBullet", getRootElement(), giveFakeBullet)
Ticket #0000909: Reload bug
Ticket #0000909: Reload bug git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1079 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
01d9b689b0d743c46c18d05c45e5fcf4e7e4863e
src/lua/sancus/web/resource.lua
src/lua/sancus/web/resource.lua
-- local Class = assert(require"sancus.object").Class local request = assert(require"wsapi.request") local C = Class{ _methods = {'GET', 'HEAD', 'POST', 'PUT', 'DELETE'} } function C:find_supported_methods(d) local l = {} if #d > 0 then for _, k in ipairs(d) do if type(self[k]) == 'function' then l[k] = k end end else for l, v in pairs(d) do if type(self[v]) == 'function' then l[k] = v end end end if l['GET'] and not l['HEAD'] then l['HEAD'] = l['GET'] end return l end function C:supported_methods(environ) local cls = getmetatable(self) local l = cls._supported_methods if not l then l = self:find_supported_methods(cls._methods) cls._supported_methods = l end return l end function C:__call(environ) local handlers, handler_name, handler local args handlers = self:supported_methods(environ) handler_name = handlers[environ.REQUEST_METHOD] if not handler_name then return 405, { Allow = handlers } end handler = self[handler_name] args = environ["sancus.routing_args"] or {} environ["sancus.handler_name"] = handler_name environ["sancus.handler"] = handler environ["sancus.named_args"] = args self.status = 200 self.headers = {} self.body = {} self.req = request.new(environ) function self.app_iter() if type(self.body) == "string" then coroutine.yield(self.body) else for _,v in ipairs(self.body) do coroutine.yield(v) end end end local status, headers, iter = handler(self, self.req, args) if status ~= nil then return status, headers, iter end return self.status, self.headers, coroutine.wrap(self.app_iter) end -- -- function MinimalMiddleware(app, interceptor) local function nop() end interceptor = interceptor or {} return function(env) local status, headers, iter = app(env) if interceptor[status] then _, headers, iter = interceptor[status](env) end if headers == nil then headers = { ['Content-Type'] = 'plain/text' } end for k,v in pairs(headers) do if type(v) == 'table' then local t if #v > 0 then t = v else t = {} for kv,_ in pairs(v) do t[#t+1] = kv end end headers[k] = table.concat(t, ", ") end end if iter == nil then iter = coroutine.wrap(nop) end return status, headers, iter end end return { Resource = C, MinimalMiddleware = MinimalMiddleware, }
-- local Class = assert(require"sancus.object").Class local request = assert(require"wsapi.request") local C = Class{ _methods = {'GET', 'HEAD', 'POST', 'PUT', 'DELETE'} } function C:find_supported_methods(d) local l = {} if #d > 0 then for _, k in ipairs(d) do if type(self[k]) == 'function' then l[k] = k end end else for l, v in pairs(d) do if type(self[v]) == 'function' then l[k] = v end end end if l['GET'] and not l['HEAD'] then l['HEAD'] = l['GET'] end return l end function C:supported_methods(environ) local l = self._supported_methods if not l then l = self:find_supported_methods(self._methods) self._supported_methods = l end return l end function C:__call(environ) local handlers, handler_name, handler local args handlers = self:supported_methods(environ) handler_name = handlers[environ.REQUEST_METHOD] if not handler_name then return 405, { Allow = handlers } end handler = self[handler_name] args = environ["sancus.routing_args"] or {} environ["sancus.handler_name"] = handler_name environ["sancus.handler"] = handler environ["sancus.named_args"] = args self.status = 200 self.headers = {} self.body = {} self.req = request.new(environ) function self.app_iter() if type(self.body) == "string" then coroutine.yield(self.body) else for _,v in ipairs(self.body) do coroutine.yield(v) end end end local status, headers, iter = handler(self, self.req, args) if status ~= nil then return status, headers, iter end return self.status, self.headers, coroutine.wrap(self.app_iter) end -- -- function MinimalMiddleware(app, interceptor) local function nop() end interceptor = interceptor or {} return function(env) local status, headers, iter = app(env) if interceptor[status] then _, headers, iter = interceptor[status](env) end if headers == nil then headers = { ['Content-Type'] = 'plain/text' } end for k,v in pairs(headers) do if type(v) == 'table' then local t if #v > 0 then t = v else t = {} for kv,_ in pairs(v) do t[#t+1] = kv end end headers[k] = table.concat(t, ", ") end end if iter == nil then iter = coroutine.wrap(nop) end return status, headers, iter end end return { Resource = C, MinimalMiddleware = MinimalMiddleware, }
Resource: fix bug that memoized handlers in Resource itself
Resource: fix bug that memoized handlers in Resource itself
Lua
bsd-2-clause
sancus-project/sancus-lua-web
06bce9a9547d2b5dfc44500c5f3b3218ddcd0950
src/lfs/server_status.lua
src/lfs/server_status.lua
local module = ... local function process() local ip, nm, gw = wifi.sta.getip() local device = require("device") local settings = require("settings") settings.token = nil settings.aws = nil local body = { hwVersion = device.hwVersion, swVersion = device.swVersion, heap = node.heap(), uptime = tmr.time(), ip = ip, port = math.floor(node.chipid()/1000) + 8000, nm = nm, gw = gw, mac = wifi.sta.getmac(), rssi = wifi.sta.getrssi(), sensors = require("sensors"), actuators = require("actuators"), dht_sensors = require("dht_sensors"), ds18b20_sensors = require("ds18b20_sensors"), settings = settings } return body end return function() package.loaded[module] = nil module = nil return process() end
local module = ... local function process() local ip, nm, gw = wifi.sta.getip() local device = require("device") local settings = require("settings") local body = { hwVersion = device.hwVersion, swVersion = device.swVersion, heap = node.heap(), uptime = tmr.time(), ip = ip, port = math.floor(node.chipid()/1000) + 8000, nm = nm, gw = gw, mac = wifi.sta.getmac(), rssi = wifi.sta.getrssi(), sensors = require("sensors"), actuators = require("actuators"), dht_sensors = require("dht_sensors"), ds18b20_sensors = require("ds18b20_sensors"), settings = { endpoint = settings.endpoint, endpoint_type = settings.endpoint_type } } return body end return function() package.loaded[module] = nil module = nil return process() end
fix token getting cleared when requesting status
fix token getting cleared when requesting status
Lua
apache-2.0
konnected-io/konnected-security,konnected-io/konnected-security
c780bdaf29c11428935e429f2c16dc43fe129d5d
tools/doc-parser.lua
tools/doc-parser.lua
local Path = require('path') local Table = require('table') local FS = require('fs') local Utils = require('utils') local function search(code, pattern) local data = {} for pos, k, v in code:gmatch(pattern) do local sub = code:sub(1, pos) local comment = sub:match("\n-- ([^\n]+)\n$") if not comment then local long = sub:match("\n--%[(%b[])%]\n$") if long then comment = long:sub(3, #long-2) end end data[k] = {v, comment} end return data end local function parse(file) local code = FS.read_file_sync(file) local name = Path.basename(file) name = name:sub(1, #name - #(Path.extname(name))) local exports = code:match("\nreturn%s+([_%a][_%w]*)") local variables = search(code, "()\nlocal ([_%a][_%w]*) = ([^\n]*)\n") local props = search(code, "()\n([_%a][_%w]*[.:][_%a][_%w]*) = ([^\n]*)\n") local functionNames = search(code, "()\nfunction ([_%a][_%w]*[.:][_%a][_%w]*)%(([^)]*)%)\n") if not exports then error("Can't find exports variable in " .. file) end -- calculate aliases for variable resolving local aliases = {} if not (name == exports) then aliases[exports] = name end for prop, data in pairs(props) do local ref = data[1] if ref:match("^[_%a][_%w]*$") then aliases[ref] = prop end end for ref, data in pairs(variables) do local prop = data[1] local m = prop:match("^()[_%a][_%w]*%.[_%a][_%w]*$") local extra if not m then m, extra = prop:match("^require(%b())(%.[_%a][_%w]*)$") if not m then m = prop:match("^require(%b())$") end end if m then if type(m) == "string" then aliases[ref] = m:sub(3, #m-2) .. (extra or "") else aliases[ref] = prop end end end local function resolve(name) repeat local before = name local start = name:match("^([_%a][_%w]*)") if start and aliases[start] then name = aliases[start] .. name:sub(#start + 1) elseif aliases[name] then name = aliases[name] end until before == name return name end local items = {} for ref, def in pairs(functionNames) do items[resolve(ref)] = { doc = def[2], args = def[1] } end local function processRef(ref, def) local value = def[1] local parent = value:match("^([_%a][_%w]*):extend%(%)$") if parent then items[resolve(ref)] = { doc = def[2], parent = resolve(parent) } elseif not (value:match("^[_%a][_%w]*%.[_%a][_%w]*$") or value:match("^[_%a][_%w]*$")) then items[resolve(ref)] = { doc = def[2], default = value } end end for ref, def in pairs(variables) do processRef(ref, def) end for prop, def in pairs(props) do processRef(prop, def) end if items[name] then items[name].default = nil end local keys = {} for key in pairs(items) do if key == name or key:match("^" .. name .. "%.") then local item = items[key] if key == name or item.doc or item.args or item.parent then Table.insert(keys, key) end end end Table.sort(keys) for i, key in ipairs(keys) do local item = items[key] local title if key == name then title = "## " .. name else local short = key:match("%.(.+[.:].+)$") if short then title = "#### " .. short else title = "### " .. key end end if item.args then title = title .. "(" .. item.args .. ")" end if item.default then title = title .. " = " .. item.default end print(title .. "\n") if item.parent then print("Inherits from `" .. item.parent .. "`\n") end if item.doc then print(item.doc .. "\n") end end end parse(process.argv[1] or "shapes.lua")
local Path = require('path') local Table = require('table') local FS = require('fs') local Utils = require('utils') local function search(code, pattern) local data = {} for pos, k, v in code:gmatch(pattern) do local sub = code:sub(1, pos) local comment = sub:match("\n-- ([^\n]+)\n$") if not comment then local long = sub:match("\n--%[(%b[])%]\n$") if long then comment = long:sub(3, #long-2) end end data[k] = {v, comment} end return data end local function parse(file) local code = FS.readFileSync(file) local name = Path.basename(file) name = name:sub(1, #name - #(Path.extname(name))) local exports = code:match("\nreturn%s+([_%a][_%w]*)") local variables = search(code, "()\nlocal ([_%a][_%w]*) = ([^\n]*)\n") local props = search(code, "()\n([_%a][_%w]*[.:][_%a][_%w]*) = ([^\n]*)\n") local functionNames = search(code, "()\nfunction ([_%a][_%w]*[.:][_%a][_%w]*)%(([^)]*)%)\n") if not exports then error("Can't find exports variable in " .. file) end -- calculate aliases for variable resolving local aliases = {} if not (name == exports) then aliases[exports] = name end for prop, data in pairs(props) do local ref = data[1] if ref:match("^[_%a][_%w]*$") then aliases[ref] = prop end end for ref, data in pairs(variables) do local prop = data[1] local m = prop:match("^()[_%a][_%w]*%.[_%a][_%w]*$") local extra if not m then m, extra = prop:match("^require(%b())(%.[_%a][_%w]*)$") if not m then m = prop:match("^require(%b())$") end end if m then if type(m) == "string" then aliases[ref] = m:sub(3, #m-2) .. (extra or "") else aliases[ref] = prop end end end local function resolve(name) repeat local before = name local start = name:match("^([_%a][_%w]*)") if start and aliases[start] then name = aliases[start] .. name:sub(#start + 1) elseif aliases[name] then name = aliases[name] end until before == name return name end local items = {} for ref, def in pairs(functionNames) do items[resolve(ref)] = { doc = def[2], args = def[1] } end local function processRef(ref, def) local value = def[1] local parent = value:match("^([_%a][_%w]*):extend%(%)$") if parent then items[resolve(ref)] = { doc = def[2], parent = resolve(parent) } elseif not (value:match("^[_%a][_%w]*%.[_%a][_%w]*$") or value:match("^[_%a][_%w]*$")) then items[resolve(ref)] = { doc = def[2], default = not(value == "{}") and value } end end for ref, def in pairs(variables) do processRef(ref, def) end for prop, def in pairs(props) do processRef(prop, def) end local keys = {} for key in pairs(items) do if key == name or key:match("^" .. name .. "%.") then local item = items[key] if key == name or item.doc or item.args or item.parent then Table.insert(keys, key) end end end Table.sort(keys) for i, key in ipairs(keys) do local item = items[key] local title if key == name then title = "## " .. name else local short = key:match("%.(.+[.:].+)$") if short then title = "#### " .. short else title = "### " .. key end end if item.args then title = title .. "(" .. item.args .. ")" end if item.default then title = title .. " = " .. item.default end print(title .. "\n") if item.parent then print("Inherits from `" .. item.parent .. "`\n") end if item.doc then print(item.doc .. "\n") end end end parse(process.argv[1] or "shapes.lua")
Fix doc-parser for camelCase refactor
Fix doc-parser for camelCase refactor
Lua
apache-2.0
bsn069/luvit,boundary/luvit,zhaozg/luvit,GabrielNicolasAvellaneda/luvit-upstream,boundary/luvit,GabrielNicolasAvellaneda/luvit-upstream,bsn069/luvit,rjeli/luvit,sousoux/luvit,luvit/luvit,kaustavha/luvit,kaustavha/luvit,GabrielNicolasAvellaneda/luvit-upstream,DBarney/luvit,boundary/luvit,sousoux/luvit,rjeli/luvit,AndrewTsao/luvit,boundary/luvit,DBarney/luvit,AndrewTsao/luvit,zhaozg/luvit,DBarney/luvit,boundary/luvit,sousoux/luvit,rjeli/luvit,luvit/luvit,connectFree/lev,sousoux/luvit,sousoux/luvit,AndrewTsao/luvit,GabrielNicolasAvellaneda/luvit-upstream,kaustavha/luvit,sousoux/luvit,connectFree/lev,bsn069/luvit,DBarney/luvit,boundary/luvit,rjeli/luvit
1cd9d51ccd5d63cad5b4ee8e2701f3b3fed08c3e
AceAddon-3.0/AceAddon-3.0.lua
AceAddon-3.0/AceAddon-3.0.lua
local MAJOR, MINOR = "AceAddon-3.0", 0 local AceAddon, oldminor = LibStub:NewLibrary( MAJOR, MINOR ) if not AceAddon then return -- No Upgrade needed. elseif not oldminor then -- This is the first version AceAddon.frame = CreateFrame("Frame", "AceAddon30Frame") -- Our very own frame AceAddon.addons = {} -- addons in general AceAddon.initializequeue = {} -- addons that are new and not initialized AceAddon.enablequeue = {} -- addons that are initialized and waiting to be enabled AceAddon.embeds = setmetatable({}, {__index = function(tbl, key) tbl[key] = {} return tbl[key] end }) -- contains a list of libraries embedded in an addon end local function safecall(func,...) if type(func) == "function" then local success, err = pcall(func,...) if not err:find("%.lua:%d+:") then err = (debugstack():match("\n(.-: )in.-\n") or "") .. err end geterrorhandler()(err) end end -- AceAddon:NewAddon( name, [lib, lib, lib, ...] ) -- name (string) - unique addon object name -- [lib] (string) - optional libs to embed in the addon object -- -- returns the addon object when succesful function AceAddon:NewAddon( name, ... ) assert( type( name ) == "string", "Bad argument #2 to 'NewAddon' (string expected)" ) if self.addons[name] then error( ("AceAddon '%s' already exists."):format(name), 2 ) end local addon = { name = name} self.addons[name] = addon self:EmbedLibraries( addon, ... ) -- add to queue of addons to be initialized upon ADDON_LOADED table.insert( self.initializequeue, addon ) return addon end -- AceAddon:GetAddon( name, [silent]) -- name (string) - unique addon object name -- silent (boolean) - if true, addon is optional, silently return nil if its not found -- -- throws an error if the addon object can not be found (except silent is set) -- returns the addon object if found function AceAddon:GetAddon( name, silent ) if not silent and not self.addons[name] then error(("Cannot find an AceAddon with name '%s'."):format(name), 2) end return self.addons[name] end -- AceAddon:EmbedLibraries( addon, [lib, lib, lib, ...] ) -- addon (object) - addon to embed the libs in -- [lib] (string) - optional libs to embed function AceAddon:EmbedLibraries( addon, ... ) for i=1,select("#", ... ) do -- TODO: load on demand? local libname = select( i, ... ) self:EmbedLibrary(addon, libname, false, 3) end end -- AceAddon:EmbedLibrary( addon, libname, silent, offset ) -- addon (object) - addon to embed the libs in -- libname (string) - lib to embed -- [silent] (boolean) - optional, marks an embed to fail silently if the library doesn't exist. -- [offset] (number) - will push the error messages back to said offset defaults to 2 function AceAddon:EmbedLibrary( addon, libname, silent, offset ) local lib = LibStub:GetLibrary(libname, true) if not silent and not lib then error(("Cannot find a library instance of %q."):format(tostring(libname)), offset or 2) elseif lib and type(lib.Embed) ~= "function" then lib:Embed(addon) table.insert( self.embeds[addon], libname ) return true elseif lib then error( ("Library '%s' is not Embed capable"):format(libname), offset or 2 ) end end -- AceAddon:IntializeAddon( addon ) -- addon (object) - addon to intialize -- -- calls OnInitialize on the addon object if available -- calls OnEmbedInitialize on embedded libs in the addon object if available function AceAddon:InitializeAddon( addon ) safecall( addon.OnInitialize, addon ) for k, libname in ipairs( self.embeds[addon] ) do local lib = LibStub:GetLibrary(libname, true) if lib then safecall( lib.OnEmbedInitialize, lib, addon ) end end end -- AceAddon:EnableAddon( addon ) -- addon (object) - addon to enable -- -- calls OnEnable on the addon object if available -- calls OnEmbedEnable on embedded libs in the addon object if available function AceAddon:EnableAddon( addon ) -- TODO: enable only if needed -- TODO: handle 'first'? Or let addons do it on their own? safecall( addon.OnEnable, addon ) for k, libname in ipairs( self.embeds[addon] ) do local lib = LibStub:GetLibrary(libname, true) if lib then safecall( lib.OnEmbedEnable, lib, addon ) end end end -- AceAddon:DisableAddon( addon ) -- addon (object) - addon to disable -- -- calls OnDisable on the addon object if available -- calls OnEmbedDisable on embedded libs in the addon object if available function AceAddon:DisableAddon( addon ) -- TODO: disable only if enabled safecall( addon.OnDisable, addon ) if self.embeds[addon] then for k, libname in ipairs( self.embeds[addon] ) do local lib = LibStub:GetLibrary(libname, true) if lib then safecall( lib.OnEmbedDisable, lib, addon ) end end end end -- Event Handling local function onEvent( this, event, arg1 ) if event == "ADDON_LOADED" or event == "PLAYER_LOGIN" then for i = 1, #AceAddon.initializequeue do local addon = AceAddon.initializequeue[i] AceAddon:InitializeAddon( addon ) AceAddon.initializequeue[i] = nil table.insert( AceAddon.enablequeue, addon ) end if IsLoggedIn() then for i = 1, #AceAddon.enablequeue do local addon = AceAddon.enablequeue[i] AceAddon:EnableAddon( addon ) AceAddon.enablequeue[i] = nil end end end -- TODO: do we want to disable addons on logout? -- Mikk: unnecessary code running imo, since disable isn't == logout (we can enable and disable in-game) -- Ammo: AceDB wants to massage the db on logout -- Mikk: AceDB can listen for PLAYER_LOGOUT on its own, and if it massages the db on disable, it'll ahve to un-massage it on reenables -- K: I say let it do it on PLAYER_LOGOUT, Or if it must it already will know OnEmbedDisable -- DISCUSSION WANTED! end --The next few funcs are just because no one should be reaching into the internal registries --Thoughts? function AceAddon:IterateAddons() return pairs(self.addons) end function AceAddon:IterateEmbedsOnAddon(addon) return pairs(self.embeds[addon]) end AceAddon.frame:RegisterEvent("ADDON_LOADED") AceAddon.frame:RegisterEvent("PLAYER_LOGIN") AceAddon.frame:SetScript( "OnEvent", onEvent )
local MAJOR, MINOR = "AceAddon-3.0", 0 local AceAddon, oldminor = LibStub:NewLibrary( MAJOR, MINOR ) if not AceAddon then return -- No Upgrade needed. elseif not oldminor then -- This is the first version AceAddon.frame = CreateFrame("Frame", "AceAddon30Frame") -- Our very own frame AceAddon.addons = {} -- addons in general AceAddon.initializequeue = {} -- addons that are new and not initialized AceAddon.enablequeue = {} -- addons that are initialized and waiting to be enabled AceAddon.embeds = setmetatable({}, {__index = function(tbl, key) tbl[key] = {} return tbl[key] end }) -- contains a list of libraries embedded in an addon end local function safecall(func,...) if type(func) == "function" then local success, err = pcall(func,...) if not err:find("%.lua:%d+:") then err = (debugstack():match("\n(.-: )in.-\n") or "") .. err end geterrorhandler()(err) end end -- AceAddon:NewAddon( name, [lib, lib, lib, ...] ) -- name (string) - unique addon object name -- [lib] (string) - optional libs to embed in the addon object -- -- returns the addon object when succesful function AceAddon:NewAddon( name, ... ) assert( type( name ) == "string", "Bad argument #2 to 'NewAddon' (string expected)" ) if self.addons[name] then error( ("AceAddon '%s' already exists."):format(name), 2 ) end local addon = { name = name} self.addons[name] = addon self:EmbedLibraries( addon, ... ) -- add to queue of addons to be initialized upon ADDON_LOADED table.insert( self.initializequeue, addon ) return addon end -- AceAddon:GetAddon( name, [silent]) -- name (string) - unique addon object name -- silent (boolean) - if true, addon is optional, silently return nil if its not found -- -- throws an error if the addon object can not be found (except silent is set) -- returns the addon object if found function AceAddon:GetAddon( name, silent ) if not silent and not self.addons[name] then error(("Cannot find an AceAddon with name '%s'."):format(name), 2) end return self.addons[name] end -- AceAddon:EmbedLibraries( addon, [lib, lib, lib, ...] ) -- addon (object) - addon to embed the libs in -- [lib] (string) - optional libs to embed function AceAddon:EmbedLibraries( addon, ... ) for i=1,select("#", ... ) do -- TODO: load on demand? local libname = select( i, ... ) self:EmbedLibrary(addon, libname, false, 3) end end -- AceAddon:EmbedLibrary( addon, libname, silent, offset ) -- addon (object) - addon to embed the libs in -- libname (string) - lib to embed -- [silent] (boolean) - optional, marks an embed to fail silently if the library doesn't exist. -- [offset] (number) - will push the error messages back to said offset defaults to 2 function AceAddon:EmbedLibrary( addon, libname, silent, offset ) local lib = LibStub:GetLibrary(libname, true) if not silent and not lib then error(("Cannot find a library instance of %q."):format(tostring(libname)), offset or 2) elseif lib and type(lib.Embed) ~= "function" then lib:Embed(addon) table.insert( self.embeds[addon], libname ) return true elseif lib then error( ("Library '%s' is not Embed capable"):format(libname), offset or 2 ) end end -- AceAddon:IntializeAddon( addon ) -- addon (object) - addon to intialize -- -- calls OnInitialize on the addon object if available -- calls OnEmbedInitialize on embedded libs in the addon object if available function AceAddon:InitializeAddon( addon ) safecall( addon.OnInitialize, addon ) for k, libname in ipairs( self.embeds[addon] ) do local lib = LibStub:GetLibrary(libname, true) if lib then safecall( lib.OnEmbedInitialize, lib, addon ) end end end -- AceAddon:EnableAddon( addon ) -- addon (object) - addon to enable -- -- calls OnEnable on the addon object if available -- calls OnEmbedEnable on embedded libs in the addon object if available function AceAddon:EnableAddon( addon ) -- TODO: enable only if needed -- TODO: handle 'first'? Or let addons do it on their own? safecall( addon.OnEnable, addon ) for k, libname in ipairs( self.embeds[addon] ) do local lib = LibStub:GetLibrary(libname, true) if lib then safecall( lib.OnEmbedEnable, lib, addon ) end end end -- AceAddon:DisableAddon( addon ) -- addon (object) - addon to disable -- -- calls OnDisable on the addon object if available -- calls OnEmbedDisable on embedded libs in the addon object if available function AceAddon:DisableAddon( addon ) -- TODO: disable only if enabled safecall( addon.OnDisable, addon ) if self.embeds[addon] then for k, libname in ipairs( self.embeds[addon] ) do local lib = LibStub:GetLibrary(libname, true) if lib then safecall( lib.OnEmbedDisable, lib, addon ) end end end end -- Event Handling local function onEvent( this, event, arg1 ) if event == "ADDON_LOADED" or event == "PLAYER_LOGIN" then for i = 1, #AceAddon.initializequeue do local addon = AceAddon.initializequeue[i] AceAddon:InitializeAddon( addon ) AceAddon.initializequeue[i] = nil table.insert( AceAddon.enablequeue, addon ) end if IsLoggedIn() then for i = 1, #AceAddon.enablequeue do local addon = AceAddon.enablequeue[i] AceAddon:EnableAddon( addon ) AceAddon.enablequeue[i] = nil end end end -- TODO: do we want to disable addons on logout? -- Mikk: unnecessary code running imo, since disable isn't == logout (we can enable and disable in-game) -- Ammo: AceDB wants to massage the db on logout -- Mikk: AceDB can listen for PLAYER_LOGOUT on its own, and if it massages the db on disable, it'll ahve to un-massage it on reenables -- K: I say let it do it on PLAYER_LOGOUT, Or if it must it already will know OnEmbedDisable -- Nev: yeah, let AceDB figure out logout on its own, and keep it seperate from disable. -- DISCUSSION WANTED! end --The next few funcs are just because no one should be reaching into the internal registries --Thoughts? function AceAddon:IterateAddons() return pairs(self.addons) end function AceAddon:IterateEmbedsOnAddon(addon) return pairs(self.embeds[addon]) end AceAddon.frame:RegisterEvent("ADDON_LOADED") AceAddon.frame:RegisterEvent("PLAYER_LOGIN") AceAddon.frame:SetScript( "OnEvent", onEvent )
Ace3 - - fixed indentation and some general cleanup
Ace3 - - fixed indentation and some general cleanup git-svn-id: 00c2b8bc9b083c53e126de03a83516ee6a3b87d9@5 5debad98-a965-4143-8383-f471b3509dcf
Lua
bsd-3-clause
sarahgerweck/Ace3
125666db3cc5b259fe9becfcfa1f822c4959ce12
mods/nalc/init.lua
mods/nalc/init.lua
-- Change some craft recipe of Witchcraft if minetest.get_modpath("witchcraft") then -- clear crafts with this particular recipe minetest.clear_craft( { recipe = { {"default:sand"} } }) -- register default:desert_sand (by MFF) minetest.register_craft( { output = "default:desert_sand", recipe = { {"default:sand"}, } }) -- register witchcraft:tooth (by NALC) minetest.register_craft( { output = "witchcraft:tooth", recipe = { {"default:sand", "", "default:sand"}, {"", "default:sand", ""}, } }) -- Register craft recipe of bones:bones with bonemeal:bone if minetest.get_modpath("bones") and minetest.get_modpath("bonemeal") and bonemeal then minetest.register_craft( { output = "bones:bones", recipe = { {"bonemeal:bone", "bonemeal:bone", "bonemeal:bone"}, {"bonemeal:bone", "bonemeal:bone", "bonemeal:bone"}, {"bonemeal:bone", "bonemeal:bone", "bonemeal:bone"}, } }) end -- Override craft recipe of witchcraft:shelf if minetest.get_modpath("vessels") then minetest.clear_craft( { recipe = { {"group:wood", "group:wood", "group:wood"}, {"group:potion", "group:potion", "group:potion"}, {"group:wood", "group:wood", "group:wood"}, } }) minetest.register_craft( { output = "witchcraft:shelf", recipe = { {"", "group:potion", ""}, {"group:potion", "vessels:shelf", "group:potion"}, } }) -- Rewrite potion table which is buggy witchcraft.pot_new = { {"blue", "blue2", "default:leaves", "brown", "default:dirt", "red", "purple"}, -- replace waterlily by leaves (flowers_plus incompatibility i think...) {"blue2", "green", "default:papyrus", "", "", "gred", "magenta"}, {"green", "green2", "default:sapling", "", "", "yellow", "yllwgrn"}, {"green2", "yellow", "default:mese_crystal_fragment", "", "", "blue", "cyan"}, {"yellow", "ggreen", "flowers:mushroom_brown", "", "", "green", "yllwgrn"}, {"ggreen", "cyan", "witchcraft:slime_bottle", "", "", "gcyan", "aqua"}, {"cyan", "gcyan", "witchcraft:bottle_medicine", "", "", "blue", "blue2"}, {"gcyan", "orange", "default:torch", "", "", "ggreen", "aqua"}, {"orange", "yllwgrn", "tnt:gunpowder", "", "", "red", "redbrown"}, {"yllwgrn", "gold", "default:steel_ingot", "", "", "green", "green2"}, {"gold", "aqua", "default:diamond", "", "", "", ""}, {"aqua", "", "", "", "", "", ""}, {"brown", "redbrown", "flowers:mushroom_red", "", "", "red", "redbrown"}, {"redbrown", "gred", "default:apple", "", "", "", ""}, {"gred", "red", "witchcraft:herb_bottle", "", "", "blue2", "magenta"}, -- replace witchcraft:herbs (inexistant) by herb_bottle {"red", "magenta", "witchcraft:tooth", "", "", "blue", "purple"}, {"magenta", "gpurple", "witchcraft:slime_bottle", "", "", "cyan", "darkpurple"}, -- item name corrected (was inverted) {"gpurple", "purple", "witchcraft:bone_bottle", "", "", "yllwgrn", "green2"}, {"purple", "darkpurple", "default:glass", "", "", "yellow", "green"}, {"darkpurple", "silver", "default:steel_ingot", "", "", "", ""}, {"silver", "grey", "witchcraft:bone", "", "", "", ""}, {"grey", "aqua", "default:diamond", "", "", "", ""}, } -- Override potion green effect if farming_redo is loaded (bad call in original mod) if farming.mod and farming.mod == "redo" then minetest.override_item( "witchcraft:potion_green", { description = "Melon Potion", on_use = function(item, user, pointed_thing) local player = user:get_player_name() if pointed_thing.type == "node" and minetest.get_node(pointed_thing.above).name == "air" then if not minetest.is_protected(pointed_thing.above, player) then minetest.set_node(pointed_thing.above, {name="farming:melon_8"}) else minetest.chat_send_player(player, "This area is protected.") end end local playerpos = user:getpos(); minetest.add_particlespawner( 5, --amount 0.1, --time {x=playerpos.x-1, y=playerpos.y+1, z=playerpos.z-1}, --minpos {x=playerpos.x+1, y=playerpos.y+1, z=playerpos.z+1}, --maxpos {x=-0, y=-0, z=-0}, --minvel {x=0, y=0, z=0}, --maxvel {x=-0.5,y=4,z=-0.5}, --minacc {x=0.5,y=4,z=0.5}, --maxacc 0.5, --minexptime 1, --maxexptime 1, --minsize 2, --maxsize false, --collisiondetection "witchcraft_effect.png" --texture ) item:replace("vessels:glass_bottle") return item end }) end end end
-- Change some craft recipe of Witchcraft if minetest.get_modpath("witchcraft") then -- clear crafts with this particular recipe minetest.clear_craft( { recipe = { {"default:sand"} } }) -- register default:desert_sand (by MFF) minetest.register_craft( { output = "default:desert_sand", recipe = { {"default:sand"}, } }) -- register witchcraft:tooth (by NALC) minetest.register_craft( { output = "witchcraft:tooth", recipe = { {"default:sand", "", "default:sand"}, {"", "default:sand", ""}, } }) -- Register craft recipe of bones:bones with bonemeal:bone if minetest.get_modpath("bones") and minetest.get_modpath("bonemeal") and bonemeal then minetest.register_craft( { output = "bones:bones", recipe = { {"bonemeal:bone", "bonemeal:bone", "bonemeal:bone"}, {"bonemeal:bone", "bonemeal:bone", "bonemeal:bone"}, {"bonemeal:bone", "bonemeal:bone", "bonemeal:bone"}, } }) end -- Override craft recipe of witchcraft:shelf if minetest.get_modpath("vessels") then minetest.clear_craft( { recipe = { {"group:wood", "group:wood", "group:wood"}, {"group:potion", "group:potion", "group:potion"}, {"group:wood", "group:wood", "group:wood"}, } }) minetest.register_craft( { output = "witchcraft:shelf", recipe = { {"", "group:potion", ""}, {"group:potion", "vessels:shelf", "group:potion"}, } }) -- Rewrite potion table which is buggy local pot_new = { {"blue", "blue2", "default:leaves", "brown", "default:dirt", "red", "purple"}, -- replace waterlily by leaves (flowers_plus incompatibility i think...) {"blue2", "green", "default:papyrus", "", "", "gred", "magenta"}, {"green", "green2", "default:sapling", "", "", "yellow", "yllwgrn"}, {"green2", "yellow", "default:mese_crystal_fragment", "", "", "blue", "cyan"}, {"yellow", "ggreen", "flowers:mushroom_brown", "", "", "green", "yllwgrn"}, {"ggreen", "cyan", "witchcraft:slime_bottle", "", "", "gcyan", "aqua"}, {"cyan", "gcyan", "witchcraft:bottle_medicine", "", "", "blue", "blue2"}, {"gcyan", "orange", "default:torch", "", "", "ggreen", "aqua"}, {"orange", "yllwgrn", "tnt:gunpowder", "", "", "red", "redbrown"}, {"yllwgrn", "gold", "default:steel_ingot", "", "", "green", "green2"}, {"gold", "aqua", "default:diamond", "", "", "", ""}, {"aqua", "", "", "", "", "", ""}, {"brown", "redbrown", "flowers:mushroom_red", "", "", "red", "redbrown"}, {"redbrown", "gred", "default:apple", "", "", "", ""}, {"gred", "red", "witchcraft:herb_bottle", "", "", "blue2", "magenta"}, -- replace witchcraft:herbs (inexistant) by herb_bottle {"red", "magenta", "witchcraft:tooth", "", "", "blue", "purple"}, {"magenta", "gpurple", "witchcraft:slime_bottle", "", "", "cyan", "darkpurple"}, -- item name corrected (was inverted) {"gpurple", "purple", "witchcraft:bone_bottle", "", "", "yllwgrn", "green2"}, {"purple", "darkpurple", "default:glass", "", "", "yellow", "green"}, {"darkpurple", "silver", "default:steel_ingot", "", "", "", ""}, {"silver", "grey", "witchcraft:bone", "", "", "", ""}, {"grey", "aqua", "default:diamond", "", "", "", ""}, } -- Override pots on_rightclick for _, row in ipairs(pot_new) do local color = row[1] local newcolor = row[2] local newcolor2 = row[4] local ingredient = row[3] local ingredient2 = row[5] local combine = row[6] local cresult = row[7] minetest.override_item( "witchcraft:pot_"..color, { on_rightclick = function(pos, node, clicker, item, _) local wield_item = clicker:get_wielded_item():get_name() if wield_item == "vessels:glass_bottle" and clicker:get_wielded_item():get_count() == 3 then item:replace("witchcraft:potion_"..color) minetest.env:add_item({x=pos.x, y=pos.y+1.5, z=pos.z}, "witchcraft:potion_"..color) minetest.env:add_item({x=pos.x, y=pos.y+1.5, z=pos.z}, "witchcraft:potion_"..color) minetest.set_node(pos, {name="witchcraft:pot", param2=node.param2}) elseif wield_item == "vessels:glass_bottle" and clicker:get_wielded_item():get_count() ~= 3 then item:replace("witchcraft:potion_"..color) minetest.set_node(pos, {name="witchcraft:pot", param2=node.param2}) else if wield_item == ingredient then minetest.set_node(pos, {name="witchcraft:pot_"..newcolor, param2=node.param2}) item:take_item() elseif wield_item == ingredient2 then minetest.set_node(pos, {name="witchcraft:pot_"..newcolor2, param2=node.param2}) item:take_item() elseif wield_item == "bucket:bucket_water" then minetest.set_node(pos, {name="witchcraft:pot_blue", param2=node.param2}) item:replace("bucket:bucket_empty") elseif wield_item == "witchcraft:potion_"..combine then minetest.set_node(pos, {name="witchcraft:pot_"..cresult, param2=node.param2}) item:replace("vessels:glass_bottle") end end end }) end -- Override potion green effect if farming_redo is loaded (bad call in original mod) if farming.mod and farming.mod == "redo" then minetest.override_item( "witchcraft:potion_green", { description = "Melon Potion", on_use = function(item, user, pointed_thing) local player = user:get_player_name() if pointed_thing.type == "node" and minetest.get_node(pointed_thing.above).name == "air" then if not minetest.is_protected(pointed_thing.above, player) then minetest.set_node(pointed_thing.above, {name="farming:melon_8"}) else minetest.chat_send_player(player, "This area is protected.") end end local playerpos = user:getpos(); minetest.add_particlespawner( 5, --amount 0.1, --time {x=playerpos.x-1, y=playerpos.y+1, z=playerpos.z-1}, --minpos {x=playerpos.x+1, y=playerpos.y+1, z=playerpos.z+1}, --maxpos {x=-0, y=-0, z=-0}, --minvel {x=0, y=0, z=0}, --maxvel {x=-0.5,y=4,z=-0.5}, --minacc {x=0.5,y=4,z=0.5}, --maxacc 0.5, --minexptime 1, --maxexptime 1, --minsize 2, --maxsize false, --collisiondetection "witchcraft_effect.png" --texture ) item:replace("vessels:glass_bottle") return item end }) end end end
Fix crash with witchcraft support
Fix crash with witchcraft support
Lua
unlicense
sys4-fr/server-minetestforfun,sys4-fr/server-minetestforfun,sys4-fr/server-minetestforfun
7a600b727205da4eb8f49cbdd31eac55e881bef6
modules/dokpro.lua
modules/dokpro.lua
local htmlparser = require'htmlparser' local trim = function(s) if not s then return nil end return s:match('^()%s*$') and '' or s:match('^%s*(.*%S)') end local parseData = function(data) if(data:match('ordboksdatabasene')) then return nil, 'Service down. :(' end -- This page is a typical example of someone using XHTML+CSS+JS, while still -- coding like they used to back in 1998. data = data:gsub('\r', ''):match('<div id="kolonne_enkel"[^>]+>(.-)<div id="slutt">'):gsub('&nbsp;', '') local words = {} local lookup = data:match('>([^<]+)</a>') data = data:match('(<span class="oppslagsord b".->.-)</td>') if(data) then local doc = htmlparser.parsestr(data) local word = doc[1][1] -- Workaround for mis matched word (partial match) if type(word) == type({}) then word = doc[1][1][1] end local entry = { lookup = {}, meaning = {}, examples = {}, } local text = {} -- Here be dragons. This is why we can't have nice things for _, w in pairs(doc) do if _ ~= '_tag' then if type(w) == type("") then table.insert(text, w) elseif type(w) == type({}) then if w['_attr'] and w['_attr'].class == 'oppsgramordklasse' then table.insert(text, ivar2.util.italic(w[1])) -- Extract definitions elseif w['_attr'] ~= nil and w['_attr']['class'] == 'utvidet' then for _, t in pairs(w) do if type(t) == type("") and t ~= "span" then table.insert(text, t) elseif type(w) == type({}) then if t['_attr'] ~= nil and t['_attr']['class'] == 'tydingC kompakt' then for _, f in pairs(t) do if type(f) == type("") and f ~= 'span' then table.insert(text, f) elseif type(f[1]) == type("") and trim(f[1]) ~= "" then table.insert(text, string.format("[%s]", ivar2.util.bold(f[1]))) end end end end end elseif type(w[1]) == type("") then if w[1] ~= word then table.insert(text, w[1]) end end end end end entry.meaning = trim(table.concat(text)) table.insert(entry.lookup, word) table.insert(words, entry) end return words end local handleInput = function(self, source, destination, word, ordbok) if not ordbok then ordbok = 'bokmaal' end local query = ivar2.util.urlEncode(word) ivar2.util.simplehttp( "http://www.nob-ordbok.uio.no/perl/ordbok.cgi?ordbok="..ordbok.."&"..ordbok.."=+&OPP=" .. query, function(data) local words, err = parseData(data) local out = {} if(words) then local n = #word + 23 for i=1, #words do local word = words[i] local lookup = table.concat(word.lookup, ', ') local definition = word.meaning if(word.examples[1]) then if(definition and #definition < 35) then definition = definition .. ' ' .. word.examples[1] else definition = word.examples[1] end end if(definition) then local message = string.format('\002[%s]\002: %s', lookup, definition) n = n + #message table.insert(out, message) end end end if(#out > 0) then self:Msg('privmsg', destination, source, '%s', table.concat(out, ', ')) else self:Msg('privmsg', destination, source, '%s: %s', source.nick, err or 'Du suger, prøv igjen.') end end ) end return { PRIVMSG = { ['^%pdokpro (.+)$'] = handleInput, ['^%pordbok (.+)$'] = handleInput, ['^%pbokmål (.+)$'] = handleInput, ['^%pnynorsk (.+)$'] = function(self, source, destination, word) handleInput(self, source, destination, word, 'nynorsk') end }, }
local htmlparser = require'htmlparser' local trim = function(s) if not s then return nil end return s:match('^()%s*$') and '' or s:match('^%s*(.*%S)') end local parseData = function(data) if(data:match('ordboksdatabasene')) then return nil, 'Service down. :(' end -- This page is a typical example of someone using XHTML+CSS+JS, while still -- coding like they used to back in 1998. data = data:gsub('\r', ''):match('<div id="kolonne_enkel"[^>]+>(.-)<div id="slutt">'):gsub('&nbsp;', '') local words = {} local lookup = data:match('>([^<]+)</a>') data = data:match('(<span class="oppslagsord b".->.-)</td>') if(data) then local doc = htmlparser.parsestr(data) local word = doc[1][1] -- Workaround for mis matched word (partial match) if type(word) == type({}) then word = doc[1][1][1] end -- First entry local entry = { lookup = {}, meaning = {}, examples = {}, } local addentry = function(lookup) entry = { lookup = {}, meaning = {}, examples = {}, } table.insert(entry.lookup, lookup) table.insert(words, entry) end local add = function(item) if not item then return end table.insert(entry.meaning, item) end -- Here be dragons. This is why we can't have nice things for _, w in pairs(doc) do if _ ~= '_tag' then if type(w) == type("") then add(w) elseif type(w) == type({}) then if w['_attr'] and w['_attr'].class == 'oppsgramordklasse' then add(ivar2.util.italic(w[1])) elseif w['_attr'] and w['_attr'].class == 'oppslagsord b' then local lookup = {} for _, t in pairs(w) do if type(t) == type("") and t ~= "span" then table.insert(lookup, t) elseif type(t[1]) == type("") and t[1] ~= "span" then table.insert(lookup, t[1]) end end addentry(table.concat(lookup)) -- Extract definitions elseif w['_attr'] ~= nil and w['_attr']['class'] == 'utvidet' then for _, t in pairs(w) do if type(t) == type("") and t ~= "span" then -- Utvidet + kompakt leads to dupes. -- add(t) elseif type(w) == type({}) then if t['_attr'] ~= nil and t['_attr']['class'] == 'tydingC kompakt' then for _, f in pairs(t) do if type(f) == type("") and f ~= 'span' then add(f) elseif type(f[1]) == type("") and trim(f[1]) ~= "" then add(string.format("[%s]", ivar2.util.bold(f[1]))) end end end end end elseif type(w[1]) == type("") then if w[1] ~= word then add(w[1]) end end end end end for _,entry in pairs(words) do entry.meaning = trim(table.concat(entry.meaning)) end end return words end local handleInput = function(self, source, destination, word, ordbok) if not ordbok then ordbok = 'bokmaal' end local query = ivar2.util.urlEncode(word) ivar2.util.simplehttp( "http://www.nob-ordbok.uio.no/perl/ordbok.cgi?ordbok="..ordbok.."&"..ordbok.."=+&OPP=" .. query, function(data) local words, err = parseData(data) local out = {} if(words) then local n = #word + 23 for i=1, #words do local word = words[i] local lookup = table.concat(word.lookup, ', ') local definition = word.meaning if(word.examples[1]) then if(definition and #definition < 35) then definition = definition .. ' ' .. word.examples[1] else definition = word.examples[1] end end if(definition) then local message = string.format('\002[%s]\002: %s', lookup, definition) n = n + #message table.insert(out, message) end end end if(#out > 0) then self:Msg('privmsg', destination, source, '%s', table.concat(out, ', ')) else self:Msg('privmsg', destination, source, '%s: %s', source.nick, err or 'Du suger, prøv igjen.') end end ) end return { PRIVMSG = { ['^%pdokpro (.+)$'] = handleInput, ['^%pordbok (.+)$'] = handleInput, ['^%pbokmål (.+)$'] = handleInput, ['^%pnynorsk (.+)$'] = function(self, source, destination, word) handleInput(self, source, destination, word, 'nynorsk') end }, }
dokpro: more html parsing fixes
dokpro: more html parsing fixes
Lua
mit
torhve/ivar2,torhve/ivar2,torhve/ivar2,haste/ivar2
6539e9ac7cea63b528d92306c35f83fb0896d44e
bundle/lua-acid-cluster/lib/acid/cluster.lua
bundle/lua-acid-cluster/lib/acid/cluster.lua
local acid_paxos = require( "acid.paxos" ) local paxoshelper = require( "acid.paxoshelper" ) local paxosserver = require( "acid.paxosserver" ) local _M = { _VERSION="0.1", dead_wait = 60*20, dead_timeout = 86400, admin_lease = 60*2, max_dead = 4, _dead = {}, } local _mt = { __index = _M } local function _true() return true, nil, nil end function _M.new(impl, opt) opt = opt or {} local cluster = { impl = impl, dead_wait = opt.dead_wait, dead_timeout = opt.dead_timeout, admin_lease = opt.admin_lease, max_dead = opt.max_dead, } setmetatable( cluster, _mt ) assert( cluster.admin_lease > 4, "lease must be long enough: > 4" ) cluster.repair_timeout = math.floor(cluster.admin_lease / 2) cluster.server = paxosserver.new(impl, { handlers = opt.handlers, }) return cluster end function _M:member_check(member_id) local paxos, err, errmes = acid_paxos.new(member_id, self.impl) if err then paxos:logerr("new paxos error:", err, errmes) return nil, err, errmes end local _, err, errmes = self:data_check(paxos) if err then return nil, err, errmes end local rst, err, errmes = paxoshelper.get_or_elect_leader(paxos, self.admin_lease) if err then paxos:logerr( "get_or_elect_leader:", err, errmes, paxos.member_id ) -- Incomplete view change might cause it to be unable to form a quorum -- in either previous or next view, thus it stalls leader election. -- -- Push view to consistent state by finishing unfinished view change. local _, err, errmes = paxoshelper.change_view( paxos, {} ) if err then paxos:logerr( "change_view with {}:", err, errmes ) end return end local leader = rst.val -- start to track version change. if version changed, paxos stops any write -- operation. paxos.ver = rst.ver if leader.ident == member_id.ident then if self:extend_lease(paxos, leader) then local _, err, errmes = paxos.impl:wait_run( self.repair_timeout*0.9, self.repair_cluster, self, paxos) if err then paxos:logerr( 'repair_cluster', paxos.member_id, err, errmes ) end end end end function _M:data_check(paxos) -- For leader or not: -- Local storage checking does not require version tracking for paxos. -- -- If it is not a member of any view, it is definitely correct to destory -- this member with all data removed. -- -- Race condition happens if: -- -- While new version of view has this member and someone else has been -- initiating this member. -- -- While timer triggered routine has been removing data of this -- member. -- -- But it does not matter. Data will be re-built in next checking. local _mem, err, errmes = paxos:local_get_mem() if err then paxos:logerr("local_get_mem err:", err, errmes) return nil, err, errmes end if _mem.val ~= nil then self.impl:restore(paxos, _mem.val) return end paxos:logerr("i am no longer a member of cluster:", paxos.member_id) local _, err, errmes = self.impl:destory(paxos) if err then paxos:logerr("destory err:", err, errmes) else local acc, err, errmes = paxos:new_acceptor() if err then return nil, err, errmes end local rst, err, errmes = acc:destory(_mem.ver) paxos:logerr("after destory acceptor:", rst, err, errmes) end end function _M:extend_lease(paxos, leader) if leader.__lease < self.repair_timeout then local rst, err, errmes = paxoshelper.elect_leader(paxos, self.admin_lease) if err then paxos:logerr( "failure extend lease:", leader ) return nil, err, errmes end end return true, nil, nil end function _M:repair_cluster(paxos) local dead_members, err, errmes = self:find_dead(paxos) if err then return nil, err, errmes end local nr_dead = #dead_members if nr_dead > 0 then paxos:logerr( "dead members confirmed:", dead_members ) end if nr_dead > self.max_dead then paxos:logerr( nr_dead, " members down, too many, can not repair" ) return end for _, _m in ipairs( dead_members ) do local ident, member = _m[1], _m[2] self:replace_dead( paxos, ident, member ) -- fix only one each time return end end function _M:find_dead(paxos) local _members, err, errmes = paxos:local_get_members() if err then return nil, err, errmes end local dead_members = {} for ident, member in pairs(_members.val) do if self:is_confirmed_dead(paxos, ident, member) then table.insert( dead_members, { ident, member } ) end end return dead_members, nil, nil end function _M:is_confirmed_dead(paxos, ident, member) local cluster_id = paxos.member_id.cluster_id if self:is_member_alive(paxos, ident) then self:record_dead(cluster_id, ident, nil) return false end paxos:logerr("dead detected:", ident, member) local now = paxos.impl:time() local dead_time = self:record_dead(cluster_id, ident, now) if dead_time > self.dead_wait then return true end return false end function _M:replace_dead(paxos, dead_ident, dead_mem) local _members, err, errmes = paxos:local_get_members() if err then return nil, err, errmes end local new_mem, err, errmes = self.impl:new_member(paxos, dead_ident, _members.val ) if err then return nil, err, errmes end local changes = { add = new_mem, del = { [dead_ident]=dead_mem }, } local rst, err, errmes = paxoshelper.change_view( paxos, changes ) paxos:logerr( "view changed: ", rst, err, errmes ) return rst, err, errmes end function _M:record_dead(cluster_id, ident, time) local cd = self._dead cd[cluster_id] = cd[cluster_id] or {} local d = cd[cluster_id] if time == nil then d[ident] = nil return nil end local prev = d[ident] or time -- Discard record that is too old, which might be caused by leader -- switching if prev < time - self.dead_timeout then d[ident] = nil end d[ident] = d[ident] or time return time - d[ident] end function _M:is_member_alive(paxos, ident) local rst, err, errmes = paxos:send_req(ident, { cmd = "isalive", }) return (err == nil and rst.err == nil), nil, nil end return _M
local acid_paxos = require( "acid.paxos" ) local paxoshelper = require( "acid.paxoshelper" ) local paxosserver = require( "acid.paxosserver" ) local _M = { _VERSION="0.1", dead_wait = 60*20, dead_timeout = 86400, admin_lease = 60*2, max_dead = 4, _dead = {}, } local _mt = { __index = _M } function _M.new(impl, opt) opt = opt or {} local cluster = { impl = impl, dead_wait = opt.dead_wait, dead_timeout = opt.dead_timeout, admin_lease = opt.admin_lease, max_dead = opt.max_dead, } setmetatable( cluster, _mt ) assert( cluster.admin_lease > 4, "lease must be long enough: > 4" ) cluster.repair_timeout = math.floor(cluster.admin_lease / 2) cluster.server = paxosserver.new(impl, { handlers = opt.handlers, }) return cluster end function _M:member_check(member_id) local paxos, err, errmes = acid_paxos.new(member_id, self.impl) if err then paxos:logerr("new paxos error:", err, errmes) return nil, err, errmes end local _, err, errmes = self:data_check(paxos) if err then return nil, err, errmes end local rst, err, errmes = paxoshelper.get_or_elect_leader(paxos, self.admin_lease) if err then paxos:logerr( "get_or_elect_leader:", err, errmes, paxos.member_id ) -- Incomplete view change might cause it to be unable to form a quorum -- in either previous or next view, thus it stalls leader election. -- -- Push view to consistent state by finishing unfinished view change. local _, err, errmes = paxoshelper.change_view( paxos, {} ) if err then paxos:logerr( "change_view with {}:", err, errmes ) end return end local leader = rst.val -- start to track version change. if version changed, paxos stops any write -- operation. paxos.ver = rst.ver if leader.ident == member_id.ident then if self:extend_lease(paxos, leader) then local _, err, errmes = paxos.impl:wait_run( self.repair_timeout*0.9, self.repair_cluster, self, paxos) if err then paxos:logerr( 'repair_cluster', paxos.member_id, err, errmes ) end end end end function _M:data_check(paxos) -- For leader or not: -- Local storage checking does not require version tracking for paxos. -- -- If it is not a member of any view, it is definitely correct to destory -- this member with all data removed. -- -- Race condition happens if: -- -- While new version of view has this member and someone else has been -- initiating this member. -- -- While timer triggered routine has been removing data of this -- member. -- -- But it does not matter. Data will be re-built in next checking. local _mem, err, errmes = paxos:local_get_mem() if err then paxos:logerr("local_get_mem err:", err, errmes) return nil, err, errmes end if _mem.val ~= nil then self.impl:restore(paxos, _mem.val) return end paxos:logerr("i am no longer a member of cluster:", paxos.member_id) local _, err, errmes = self.impl:destory(paxos) if err then paxos:logerr("destory err:", err, errmes) else local acc, err, errmes = paxos:new_acceptor() if err then return nil, err, errmes end local rst, err, errmes = acc:destory(_mem.ver) paxos:logerr("after destory acceptor:", rst, err, errmes) end end function _M:extend_lease(paxos, leader) if leader.__lease < self.repair_timeout then local rst, err, errmes = paxoshelper.elect_leader(paxos, self.admin_lease) if err then paxos:logerr( "failure extend lease:", leader ) return nil, err, errmes end end return true, nil, nil end function _M:repair_cluster(paxos) local dead_members, err, errmes = self:find_dead(paxos) if err then return nil, err, errmes end local nr_dead = #dead_members if nr_dead > 0 then paxos:logerr( "dead members confirmed:", dead_members ) end if nr_dead > self.max_dead then paxos:logerr( nr_dead, " members down, too many, can not repair" ) return end for _, _m in ipairs( dead_members ) do local ident, member = _m[1], _m[2] self:replace_dead( paxos, ident, member ) -- fix only one each time return end end function _M:find_dead(paxos) local _members, err, errmes = paxos:local_get_members() if err then return nil, err, errmes end local dead_members = {} for ident, member in pairs(_members.val) do if self:is_confirmed_dead(paxos, ident, member) then table.insert( dead_members, { ident, member } ) end end return dead_members, nil, nil end function _M:is_confirmed_dead(paxos, ident, member) local cluster_id = paxos.member_id.cluster_id if self:is_member_alive(paxos, ident) then self:record_dead(cluster_id, ident, nil) return false end paxos:logerr("dead detected:", ident, member) local now = paxos.impl:time() local dead_time = self:record_dead(cluster_id, ident, now) if dead_time > self.dead_wait then return true end return false end function _M:replace_dead(paxos, dead_ident, dead_mem) local _members, err, errmes = paxos:local_get_members() if err then return nil, err, errmes end local new_mem, err, errmes = self.impl:new_member(paxos, dead_ident, _members.val ) if err then return nil, err, errmes end local changes = { add = new_mem, del = { [dead_ident]=dead_mem }, } local rst, err, errmes = paxoshelper.change_view( paxos, changes ) paxos:logerr( "view changed: ", rst, err, errmes ) return rst, err, errmes end function _M:record_dead(cluster_id, ident, time) local cd = self._dead cd[cluster_id] = cd[cluster_id] or {} local d = cd[cluster_id] if time == nil then d[ident] = nil return nil end local prev = d[ident] or time -- Discard record that is too old, which might be caused by leader -- switching if prev < time - self.dead_timeout then d[ident] = nil end d[ident] = d[ident] or time return time - d[ident] end function _M:is_member_alive(paxos, ident) local rst, err, errmes = paxos:send_req(ident, { cmd = "isalive", }) return (err == nil and rst.err == nil), nil, nil end return _M
fixup
fixup
Lua
mit
drmingdrmer/lua-paxos,drmingdrmer/lua-paxos
4f984860bc926ab47af9b298f3d7646402815574
vanilla/v/request.lua
vanilla/v/request.lua
-- Request moudle -- @since 2015-08-17 10:54 -- @author idevz <[email protected]> -- version $Id$ -- perf local error = error local pairs = pairs local pcall = pcall local setmetatable = setmetatable local Reqargs = require 'vanilla.v.libs.reqargs' local Request = {} function Request:new() -- local headers = ngx.req.get_headers() -- url:http://zj.com:9210/di0000/111?aa=xx local instance = { uri = ngx.var.uri, -- /di0000/111 -- req_uri = ngx.var.request_uri, -- /di0000/111?aa=xx -- req_args = ngx.var.args, -- aa=xx -- params = params, -- uri_args = ngx.req.get_uri_args(), -- { aa = "xx" } -- method = ngx.req.get_method(), -- headers = headers, -- body_raw = ngx.req.get_body_data() } setmetatable(instance, {__index = self}) return instance end -- function Request:getControllerName() -- return self.controller_name -- end -- function Request:getActionName() -- return self.action_name -- end function Request:getHeaders() if self.headers == nil then self.headers = ngx.req.get_headers() end return self.headers end function Request:getHeader(key) return self:getHeaders()[key] end function Request:buildParams() local GET, POST, FILE = Reqargs:getRequestData({}) local params = GET for k,v in pairs(POST) do params[k] = v end if #FILE >= 1 then params['VA_FILE']=FILE end self.params = params return self.params end function Request:getParams() return self.params or self:buildParams() end function Request:getParam(key) local ok, params_or_err = pcall(function(self) return self.params[key] end) if ok then return params_or_err else return self:buildParams()[key] end end function Request:setParam(key, value) self.params[key] = value end function Request:getMethod() local method = self.method or ngx.req.get_method() return method end function Request:isGet() if self.method == 'GET' then return true else return false end end return Request
-- Request moudle -- @since 2015-08-17 10:54 -- @author idevz <[email protected]> -- version $Id$ -- perf local error = error local pairs = pairs local pcall = pcall local setmetatable = setmetatable local Reqargs = require 'vanilla.v.libs.reqargs' local Request = {} function Request:new() -- local headers = ngx.req.get_headers() -- url:http://zj.com:9210/di0000/111?aa=xx local instance = { uri = ngx.var.uri, -- /di0000/111 -- req_uri = ngx.var.request_uri, -- /di0000/111?aa=xx -- req_args = ngx.var.args, -- aa=xx -- params = params, -- uri_args = ngx.req.get_uri_args(), -- { aa = "xx" } -- method = ngx.req.get_method(), -- headers = headers, -- body_raw = ngx.req.get_body_data() } setmetatable(instance, {__index = self}) return instance end -- function Request:getControllerName() -- return self.controller_name -- end -- function Request:getActionName() -- return self.action_name -- end function Request:getHeaders() if self.headers == nil then self.headers = ngx.req.get_headers() end return self.headers end function Request:getHeader(key) return self:getHeaders()[key] end function Request:buildParams() local GET, POST, FILE = Reqargs:getRequestData({}) local params = {} params['VA_GET'] = GET params['VA_POST'] = POST if #FILE >= 1 then params['VA_FILE']=FILE end for k,v in pairs(GET) do params[k] = v end for k,v in pairs(POST) do params[k] = v end self.params = params return self.params end function Request:GET() if self.params ~= nil then return self.params.VA_GET end return self:buildParams()['VA_GET'] end function Request:POST() if self.params ~= nil then return self.params.VA_POST end return self:buildParams()['VA_POST'] end function Request:FILE() if self.params ~= nil then return self.params.VA_FILE end return self:buildParams()['VA_FILE'] end function Request:getMethod() if self.method == nil then self.method = ngx.req.get_method() end return self.method end function Request:getParams() return self.params or self:buildParams() end function Request:getParam(key) if self.params ~= nil then return self.params[key] end return self:buildParams()[key] end function Request:setParam(key, value) self.params[key] = value end function Request:isGet() if self:getMethod() == 'GET' then return true else return false end end return Request
fix a request bug about request args
fix a request bug about request args
Lua
mit
idevz/vanilla,idevz/vanilla
de4ea98d03332261d385a9096ebd9c4f6a3c50d1
xmake/modules/privilege/sudo.lua
xmake/modules/privilege/sudo.lua
--!The Make-like Build Utility based on Lua -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2017, TBOOX Open Source Group. -- -- @author ruki -- @file sudo.lua -- -- imports import("core.base.option") import("detect.tool.find_sudo") -- sudo run shell with administrator permission -- -- .e.g -- _sudo(os.run, "echo", "hello xmake!") -- function _sudo(runner, cmd, ...) -- find sudo local program = find_sudo() assert(program, "sudo not found!") -- run it with administrator permission and preserve parent environment runner(program .. " PATH=\"" .. os.getenv("PATH") .. "\" " .. cmd, ...) end -- sudo run shell with administrator permission and arguments list -- -- .e.g -- _sudov(os.runv, {"echo", "hello xmake!"}) -- function _sudov(runner, shellname, argv) -- find sudo local program = find_sudo() assert(program, "sudo not found!") -- run it with administrator permission and preserve parent environment runner(program, table.join("PATH=" .. os.getenv("PATH"), shellname, argv)) end -- sudo run lua script with administrator permission and arguments list -- -- .e.g -- _lua(os.runv, "xxx.lua", {"arg1", "arg2"}) -- function _lua(runner, luafile, luaargv) -- init argv local argv = {"lua", "--root"} for _, name in ipairs({"file", "project", "backtrace", "verbose", "quiet"}) do local value = option.get(name) if type(value) == "string" then table.insert(argv, "--" .. name .. "=" .. value) elseif value then table.insert(argv, "--" .. name) end end -- run it with administrator permission _sudov(runner, "xmake", table.join(argv, luafile, luaargv)) end -- has sudo? function has() return find_sudo() ~= nil end -- sudo run shell function run(cmd, ...) return _sudo(os.run, cmd, ...) end -- sudo run shell with arguments list function runv(shellname, argv) return _sudov(os.run, shellname, argv) end -- sudo quietly run shell and echo verbose info if [-v|--verbose] option is enabled function vrun(cmd, ...) return _sudo(os.vrun, cmd, ...) end -- sudo quietly run shell with arguments list and echo verbose info if [-v|--verbose] option is enabled function vrunv(shellname, argv) return _sudov(os.vrunv, shellname, argv) end -- sudo run shell and return output and error data function iorun(cmd, ...) return _sudo(os.iorun, cmd, ...) end -- sudo run shell and return output and error data function iorunv(shellname, argv) return _sudov(os.iorunv, shellname, argv) end -- sudo execute shell function exec(cmd, ...) return _sudo(os.exec, cmd, ...) end -- sudo execute shell with arguments list function execv(shellname, argv) return _sudov(os.execv, shellname, argv) end -- sudo run lua script function runl(luafile, luaargv) return _lua(os.runv, luafile, luaargv) end -- sudo quietly run lua script and echo verbose info if [-v|--verbose] option is enabled function vrunl(luafile, luaargv) return _lua(os.vrunv, luafile, luaargv) end -- sudo run lua script and return output and error data function iorunl(luafile, luaargv) return _lua(os.iorunv, luafile, luaargv) end -- sudo execute lua script function execl(luafile, luaargv) return _lua(os.execv, luafile, luaargv) end
--!The Make-like Build Utility based on Lua -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2017, TBOOX Open Source Group. -- -- @author ruki -- @file sudo.lua -- -- imports import("core.base.option") import("detect.tool.find_sudo") -- sudo run shell with administrator permission -- -- .e.g -- _sudo(os.run, "echo", "hello xmake!") -- function _sudo(runner, cmd, ...) -- find sudo local program = find_sudo() assert(program, "sudo not found!") -- get current path environment local pathenv = os.getenv("PATH") if pathenv and #pathenv > 0 then -- handle double quote pathenv = pathenv:gsub("\"", "\\\"") -- run it with administrator permission and preserve parent environment runner(program .. " PATH=\"" .. pathenv .. "\" " .. cmd, ...) else -- run it with administrator permission runner(program .. " " .. cmd, ...) end end -- sudo run shell with administrator permission and arguments list -- -- .e.g -- _sudov(os.runv, {"echo", "hello xmake!"}) -- function _sudov(runner, shellname, argv) -- find sudo local program = find_sudo() assert(program, "sudo not found!") -- run it with administrator permission and preserve parent environment runner(program, table.join("PATH=" .. os.getenv("PATH"), shellname, argv)) end -- sudo run lua script with administrator permission and arguments list -- -- .e.g -- _lua(os.runv, "xxx.lua", {"arg1", "arg2"}) -- function _lua(runner, luafile, luaargv) -- init argv local argv = {"lua", "--root"} for _, name in ipairs({"file", "project", "backtrace", "verbose", "quiet"}) do local value = option.get(name) if type(value) == "string" then table.insert(argv, "--" .. name .. "=" .. value) elseif value then table.insert(argv, "--" .. name) end end -- run it with administrator permission _sudov(runner, "xmake", table.join(argv, luafile, luaargv)) end -- has sudo? function has() return find_sudo() ~= nil end -- sudo run shell function run(cmd, ...) return _sudo(os.run, cmd, ...) end -- sudo run shell with arguments list function runv(shellname, argv) return _sudov(os.run, shellname, argv) end -- sudo quietly run shell and echo verbose info if [-v|--verbose] option is enabled function vrun(cmd, ...) return _sudo(os.vrun, cmd, ...) end -- sudo quietly run shell with arguments list and echo verbose info if [-v|--verbose] option is enabled function vrunv(shellname, argv) return _sudov(os.vrunv, shellname, argv) end -- sudo run shell and return output and error data function iorun(cmd, ...) return _sudo(os.iorun, cmd, ...) end -- sudo run shell and return output and error data function iorunv(shellname, argv) return _sudov(os.iorunv, shellname, argv) end -- sudo execute shell function exec(cmd, ...) return _sudo(os.exec, cmd, ...) end -- sudo execute shell with arguments list function execv(shellname, argv) return _sudov(os.execv, shellname, argv) end -- sudo run lua script function runl(luafile, luaargv) return _lua(os.runv, luafile, luaargv) end -- sudo quietly run lua script and echo verbose info if [-v|--verbose] option is enabled function vrunl(luafile, luaargv) return _lua(os.vrunv, luafile, luaargv) end -- sudo run lua script and return output and error data function iorunl(luafile, luaargv) return _lua(os.iorunv, luafile, luaargv) end -- sudo execute lua script function execl(luafile, luaargv) return _lua(os.execv, luafile, luaargv) end
fix double quote pathenv for sudo
fix double quote pathenv for sudo
Lua
apache-2.0
tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake
ccfa70cfe911129c8bdb936fda99dd11cc60bff4
src/lua-factory/sources/grl-guardianvideos.lua
src/lua-factory/sources/grl-guardianvideos.lua
--[[ * Copyright (C) 2014 Bastien Nocera * * Contact: Bastien Nocera <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * --]] -- Test the API at: -- http://explorer.content.guardianapis.com/search?api-key=rppwmmu3mfqj6gkbs8kcjg23&show-fields=all&page-size=50&tag=type/video API_KEY = 'rppwmmu3mfqj6gkbs8kcjg23' GUARDIANVIDEOS_URL = 'http://content.guardianapis.com/search?tag=type/video&page=%d&page-size=%d&show-fields=all&api-key=%s' --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-guardianvideos-lua", name = "The Guardian Videos", description = "A source for browsing videos from the Guardian", supported_keys = { "id", "thumbnail", "title", "url" }, supported_media = 'video', auto_split_threshold = 50, icon = 'resource:///org/gnome/grilo/plugins/guardianvideos/guardianvideos.svg', tags = { 'news', 'net:internet', 'net:plaintext' } } ------------------ -- Source utils -- ------------------ function grl_source_browse(media_id) local count = grl.get_options("count") local skip = grl.get_options("skip") local urls = {} local page = skip / count + 1 if page > math.floor(page) then local url = string.format(GUARDIANVIDEOS_URL, math.floor(page), count, API_KEY) grl.debug ("Fetching URL #1: " .. url .. " (count: " .. count .. " skip: " .. skip .. ")") table.insert(urls, url) url = string.format(GUARDIANVIDEOS_URL, math.floor(page) + 1, count, API_KEY) grl.debug ("Fetching URL #2: " .. url .. " (count: " .. count .. " skip: " .. skip .. ")") table.insert(urls, url) else local url = string.format(GUARDIANVIDEOS_URL, page, count, API_KEY) grl.debug ("Fetching URL: " .. url .. " (count: " .. count .. " skip: " .. skip .. ")") table.insert(urls, url) end grl.fetch(urls, "guardianvideos_fetch_cb") end ------------------------ -- Callback functions -- ------------------------ -- return all the media found function guardianvideos_fetch_cb(results) local count = grl.get_options("count") for i, result in ipairs(results) do local json = {} json = grl.lua.json.string_to_table(result) if not json or json.stat == "fail" or not json.response or not json.response.results then grl.callback() return end for index, item in pairs(json.response.results) do local media = create_media(item) count = count - 1 grl.callback(media, count) end -- Bail out if we've given enough items if count == 0 then return end end end ------------- -- Helpers -- ------------- function create_media(item) local media = {} media.type = "video" media.id = item.id media.url = item.webUrl media.title = grl.unescape(item.webTitle) media.thumbnail = item.fields.thumbnail return media end
--[[ * Copyright (C) 2014 Bastien Nocera * * Contact: Bastien Nocera <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * --]] -- Test the API at: -- http://explorer.content.guardianapis.com/search?api-key=rppwmmu3mfqj6gkbs8kcjg23&show-fields=all&page-size=50&tag=type/video API_KEY = 'rppwmmu3mfqj6gkbs8kcjg23' GUARDIANVIDEOS_URL = 'http://content.guardianapis.com/search?tag=type/video&page=%d&page-size=%d&show-fields=all&api-key=%s' --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-guardianvideos-lua", name = "The Guardian Videos", description = "A source for browsing videos from the Guardian", supported_keys = { "id", "thumbnail", "title", "url" }, supported_media = 'video', auto_split_threshold = 50, icon = 'resource:///org/gnome/grilo/plugins/guardianvideos/guardianvideos.svg', tags = { 'news', 'net:internet', 'net:plaintext' } } ------------------ -- Source utils -- ------------------ function grl_source_browse(media, options, callback) local count = options.count local skip = options.skip local urls = {} local page = skip / count + 1 if page > math.floor(page) then local url = string.format(GUARDIANVIDEOS_URL, math.floor(page), count, API_KEY) grl.debug ("Fetching URL #1: " .. url .. " (count: " .. count .. " skip: " .. skip .. ")") table.insert(urls, url) url = string.format(GUARDIANVIDEOS_URL, math.floor(page) + 1, count, API_KEY) grl.debug ("Fetching URL #2: " .. url .. " (count: " .. count .. " skip: " .. skip .. ")") table.insert(urls, url) else local url = string.format(GUARDIANVIDEOS_URL, page, count, API_KEY) grl.debug ("Fetching URL: " .. url .. " (count: " .. count .. " skip: " .. skip .. ")") table.insert(urls, url) end local userdata = {callback = callback, count = count} grl.fetch(urls, guardianvideos_fetch_cb, userdata) end ------------------------ -- Callback functions -- ------------------------ -- return all the media found function guardianvideos_fetch_cb(results, userdata) local count = userdata.count for i, result in ipairs(results) do local json = {} json = grl.lua.json.string_to_table(result) if not json or json.stat == "fail" or not json.response or not json.response.results then userdata.callback() return end for index, item in pairs(json.response.results) do local media = create_media(item) count = count - 1 userdata.callback(media, count) end -- Bail out if we've given enough items if count == 0 then return end end end ------------- -- Helpers -- ------------- function create_media(item) local media = {} media.type = "video" media.id = item.id media.url = item.webUrl media.title = grl.unescape(item.webTitle) media.thumbnail = item.fields.thumbnail return media end
lua-factory: port grl-guardianvideos.lua to the new lua system
lua-factory: port grl-guardianvideos.lua to the new lua system https://bugzilla.gnome.org/show_bug.cgi?id=753141 Acked-by: Victor Toso <[email protected]>
Lua
lgpl-2.1
MikePetullo/grilo-plugins,grilofw/grilo-plugins,MikePetullo/grilo-plugins,grilofw/grilo-plugins,GNOME/grilo-plugins,jasuarez/grilo-plugins,GNOME/grilo-plugins,MikePetullo/grilo-plugins,jasuarez/grilo-plugins
b9343524e254b8c6d0ca3a781525cd334ce153f1
durden/tools/vrviewer/layouters/default.lua
durden/tools/vrviewer/layouters/default.lua
-- -- basic layout algorithm -- return function(layer) if (layer.fixed) then return; end -- 1. separate models that have parents and root models local root = {}; local chld = {}; local chld_collapse = {}; for _,v in ipairs(layer.models) do if not v.parent then table.insert(root, v); else chld[v.parent] = chld[v.parent] and chld[v.parent] or {}; table.insert(chld[v.parent], v); end end -- make sure we have one element that is selected and visible if (not layer.selected and root[1] and valid_vid(root[1].external, TYPE_FRAMESERVER)) then root[1]:select(); end local max_h = 0; local function getang(phi) phi = math.fmod(-phi + 0.5*math.pi, 2 * math.pi); return 180 * phi / math.pi; end local rad = layer.radius; local dphi_ccw = 0.5 * math.pi; local dphi_cw = 0.5 * math.pi; for i,v in ipairs(root) do local w, h, d = v:get_size(); w = w + layer.spacing * 1.0 / rad; local z = 0; local x = 0; local ang = 0; max_h = max_h > h and max_h or h; -- special case, at 12 o clock is 0, 0 @ 0 rad. ang is for billboarding, -- there should just be a model_flag for setting spherical/cylindrical -- billboarding (or just do it in shader) but it's not there at the -- moment and we don't want more shader variants or flags. -- would be nice, yet not always solvable, to align positioning at the -- straight angles (0, half-pi, pi, ...) though the focal point of the -- user will likely often be straight ahead and that gets special -- treatment anyhow. if (i == 1) then z = -rad * math.sin(dphi_cw); dphi_cw = dphi_cw - 0.5 * w; dphi_ccw = dphi_ccw + 0.5 * w; elseif (i % 2 == 0) then x = -rad * math.cos(dphi_cw - w); z = -rad * math.sin(dphi_cw - w); ang = getang(dphi_cw - 0.5 * w); if (v.active) then dphi_cw = dphi_cw - w; end else x = -rad * math.cos(dphi_ccw + w); z = -rad * math.sin(dphi_ccw + w); ang = getang(dphi_ccw + 0.5 * w); if (v.active) then dphi_ccw = dphi_ccw + w; end end -- unresolved, what to do if n_x or p_x reach pi? if (v.active) then if (math.abs(v.layer_pos[1] - x) ~= 0.0001) or (math.abs(v.layer_pos[3] - z) ~= 0.0001) or (math.abs(v.layer_ang ~= ang) ~= 0.0001) then -- instant_image_transform(v.vid); move3d_model(v.vid, x, 0, z, v.ctx.animation_speed); rotate3d_model(v.vid, v.rel_ang[1], v.rel_ang[2], v.rel_ang[3] + ang, v.ctx.animation_speed ); end end v.layer_ang = ang; v.layer_pos = {x, 0, z}; end -- avoid linking to stay away from the cascade deletion problem, if it needs -- to be done for animations, then take the delete- and set a child as the -- new parent. local as = layer.ctx.animation_speed; for k,v in pairs(chld) do local pw, ph, pd = k:get_size(); local ch = ph; local lp = k.layer_pos; local la = k.layer_ang; -- if collapsed, we increment depth by something symbolic to avoid z-fighting, -- then offset Y enough to just see the tip, otherwise use a similar strategy -- to the root, ignore billboarding for the time being. for i,j in ipairs(v) do if (i % 2 == 0) then move3d_model(j.vid, lp[1], lp[2] - ch, lp[3], as); ch = ch + ph + layer.spacing; else move3d_model(j.vid, lp[1], lp[2] + ch, lp[3], as); end rotate3d_model(j.vid, 0, 0, la, as) pw, ph, pd = j:get_size(); end end end
-- -- basic layout algorithm -- return function(layer) if (layer.fixed) then return; end -- 1. separate models that have parents and root models local root = {}; local chld = {}; local chld_collapse = {}; for _,v in ipairs(layer.models) do if not v.parent then table.insert(root, v); else chld[v.parent] = chld[v.parent] and chld[v.parent] or {}; table.insert(chld[v.parent], v); end end -- make sure we have one element that is selected and visible if (not layer.selected) then for i,v in ipairs(root) do if (v.active) then v:select(); break; end end end local max_h = 0; local function getang(phi) phi = math.fmod(-phi + 0.5*math.pi, 2 * math.pi); return 180 * phi / math.pi; end local rad = layer.radius; local dphi_ccw = 0.5 * math.pi; local dphi_cw = 0.5 * math.pi; local as = layer.ctx.animation_speed; for i,v in ipairs(root) do local w, h, d = v:get_size(i ~= 1); w = (w + layer.spacing) * 1.0 / rad; local z = 0; local x = 0; local ang = 0; max_h = max_h > h and max_h or h; -- special case, at 12 o clock is 0, 0 @ 0 rad. ang is for billboarding, -- there should just be a model_flag for setting spherical/cylindrical -- billboarding (or just do it in shader) but it's not there at the -- moment and we don't want more shader variants or flags. -- would be nice, yet not always solvable, to align positioning at the -- straight angles (0, half-pi, pi, ...) though the focal point of the -- user will likely often be straight ahead and that gets special -- treatment anyhow. if (i == 1) then z = -rad * math.sin(dphi_cw); dphi_cw = dphi_cw - 0.5 * w; dphi_ccw = dphi_ccw + 0.5 * w; elseif (i % 2 == 0) then x = -rad * math.cos(dphi_cw - w); z = -rad * math.sin(dphi_cw - w); ang = getang(dphi_cw - 0.5 * w); if (v.active) then dphi_cw = dphi_cw - w; end else x = -rad * math.cos(dphi_ccw + w); z = -rad * math.sin(dphi_ccw + w); ang = getang(dphi_ccw + 0.5 * w); if (v.active) then dphi_ccw = dphi_ccw + w; end end -- unresolved, what to do if n_x or p_x reach pi? if (v.active) then if (math.abs(v.layer_pos[1] - x) ~= 0.0001) or (math.abs(v.layer_pos[3] - z) ~= 0.0001) or (math.abs(v.layer_ang ~= ang) ~= 0.0001) then move3d_model(v.vid, x, 0, z, as); rotate3d_model(v.vid, v.rel_ang[1], v.rel_ang[2], v.rel_ang[3] + ang, as ); -- scale3d broken unless set to 1 for z (!) local sx, sy, sz = v:get_scale(); scale3d_model(v.vid, sx, sy, 1, as); end end v.layer_ang = ang; v.layer_pos = {x, 0, z}; end -- avoid linking to stay away from the cascade deletion problem, if it needs -- to be done for animations, then take the delete- and set a child as the -- new parent. for k,v in pairs(chld) do local pw, ph, pd = k:get_size(); local ch = 0.5 * ph; local dz = 0.0; local lp = k.layer_pos; local la = k.layer_ang; -- if merged, we increment depth by something symbolic to avoid z-fighting, -- then offset Y enough to just see the tip, otherwise use a similar strategy -- to the root, ignore billboarding for the time being. for i,j in ipairs(v) do if (j.parent.merged) then ph = ph * 0.1; dz = dz + 0.001; else ph = ph * 0.5; end if (i % 2 == 0) then move3d_model(j.vid, lp[1], lp[2] - ch, lp[3] - dz, as); if (j.active) then ch = ch + ph; end else move3d_model(j.vid, lp[1], lp[2] + ch, lp[3] - dz, as); end rotate3d_model(j.vid, 0, 0, la, as) local sx, sy, sz = j:get_scale(); scale3d_model(j.vid, sx, sy, 1, as); if (j.active) then pw, ph, pd = j:get_size(); end end end end
(vrviewer) fix to layouter ruleset
(vrviewer) fix to layouter ruleset
Lua
bsd-3-clause
letoram/durden
c9bae5346fcc312c2a654d4e3212b883191cd4cc
lua/entities/gmod_wire_keyboard/cl_init.lua
lua/entities/gmod_wire_keyboard/cl_init.lua
include('shared.lua') include("remap.lua") -- For stools/keyboard.lua's layout selector net.Receive("wire_keyboard_blockinput", function(netlen) if net.ReadBit() ~= 0 then hook.Add("PlayerBindPress", "wire_keyboard_blockinput", function(ply, bind, pressed) -- return true for all keys except the mouse, to block keyboard actions while typing if bind == "+attack" then return nil end if bind == "+attack2" then return nil end return true end) else hook.Remove("PlayerBindPress", "wire_keyboard_blockinput") end end) local panel local function hideMessage() if not panel then return end panel:Remove() panel = nil end net.Receive("wire_keyboard_activatemessage", function(netlen) local on = net.ReadBit() ~= 0 hideMessage() if not on then return end local pod = net.ReadBit() ~= 0 local leaveKey = LocalPlayer():GetInfoNum("wire_keyboard_leavekey", KEY_LALT) local leaveKeyName = string.upper(input.GetKeyName(leaveKey)) local text if pod then text = "This pod is linked to a Wire Keyboard - press " .. leaveKeyName .. " to leave." else text = "Wire Keyboard turned on - press " .. leaveKeyName .. " to leave." end panel = vgui.Create("DShape") -- DPanel is broken for small sizes panel:SetColor(Color(0, 0, 0, 192)) panel:SetType("Rect") local label = vgui.Create("DLabel", panel) label:SetText(text) label:SizeToContents() local padding = 3 label:SetPos(2 * padding, 2 * padding) panel:SizeToChildren(true, true) label:SetPos(padding, padding) panel:CenterHorizontal() panel:CenterVertical(0.95) end)
include('shared.lua') include("remap.lua") -- For stools/keyboard.lua's layout selector net.Receive("wire_keyboard_blockinput", function(netlen) if net.ReadBit() ~= 0 then hook.Add("StartChat", "wire_keyboard_startchatoverride", function(teamChat) return true end) hook.Add("PlayerBindPress", "wire_keyboard_blockinput", function(ply, bind, pressed) -- return true for all keys except the mouse, to block keyboard actions while typing if bind == "+attack" then return nil end if bind == "+attack2" then return nil end return true end) else hook.Remove("StartChat", "wire_keyboard_startchatoverride") hook.Remove("PlayerBindPress", "wire_keyboard_blockinput") end end) local panel local function hideMessage() if not panel then return end panel:Remove() panel = nil end net.Receive("wire_keyboard_activatemessage", function(netlen) local on = net.ReadBit() ~= 0 hideMessage() if not on then return end local pod = net.ReadBit() ~= 0 local leaveKey = LocalPlayer():GetInfoNum("wire_keyboard_leavekey", KEY_LALT) local leaveKeyName = string.upper(input.GetKeyName(leaveKey)) local text if pod then text = "This pod is linked to a Wire Keyboard - press " .. leaveKeyName .. " to leave." else text = "Wire Keyboard turned on - press " .. leaveKeyName .. " to leave." end panel = vgui.Create("DShape") -- DPanel is broken for small sizes panel:SetColor(Color(0, 0, 0, 192)) panel:SetType("Rect") local label = vgui.Create("DLabel", panel) label:SetText(text) label:SizeToContents() local padding = 3 label:SetPos(2 * padding, 2 * padding) panel:SizeToChildren(true, true) label:SetPos(padding, padding) panel:CenterHorizontal() panel:CenterVertical(0.95) end)
keyboard fixed issue with chatbox opening
keyboard fixed issue with chatbox opening
Lua
apache-2.0
dvdvideo1234/wire,Grocel/wire,wiremod/wire
91d1138da715f96e25f6102725822c42ed8f6525
[resources]/GTWgates/gates.lua
[resources]/GTWgates/gates.lua
--[[ ******************************************************************************** Project owner: GTWGames Project name: GTW-RPG Developers: GTWCode Source code: https://github.com/GTWCode/GTW-RPG/ Bugtracker: http://forum.albonius.com/bug-reports/ Suggestions: http://forum.albonius.com/mta-servers-development/ Version: Open source License: GPL v.3 or later Status: Stable release ******************************************************************************** ]]-- -- ***************************************************************************** -- BELOW TABLE ARE MADE FOR SERVERS OWNED BY GRAND THEFT WALRUS, USE IT ONLY AS -- AN EXAMPLE OF THE LAYOUT TO UNDERSTAND HOW THIS SYSTEM WORKS -- ***************************************************************************** gate_data = { -- ObjectID closeX closeY closeZ openX openY openZ rotX rotY rotZ colX colY colZ colRad Group Scale Interior Dimension [1]={ 986, 1588.6, -1638.4, 13.4, 1578.6, -1638.4, 13.4, 0, 0, 0, 1588, -1638, 10, 10, "Government", 1, 0, 0 }, [2]={ 10671, -1631, 688.4, 8.587, -1631, 688.4, 20.187, 0, 0, 90, -1631, 688, 7.187, 25, "Government", 2, 0, 0 }, [3]={ 11327, 2334.6, 2443.7, 7.70, 2334.6, 2443.7, 15.70, 0, 0, -30, 2334.6, 2443.7, 5.70, 25, "Government", 1.3, 0, 0 }, [4]={ 2957, 2294, 2498.8, 5.1, 2294, 2498.8, 14.3, 0, 0, 90, 2294, 2498.8, 5.1, 25, "Government", 1.8, 0, 0 }, [5]={ 980, 3159, -1962.8, 12.5, 3159, -1947.8, 12.5, 0, 0, 90, 3159, -1967, 10, 20, "SAPD", 1, 0, 0 }, [6]={ 2938, 97.5, 508.5, 13.6, 97.5, 508.5, 3.6, 0, 0, 90, 97.5, 508.5, 13.6, 15, "SWAT", 1, 0, 0 }, [7]={ 2938, 107.6, 414.9, 13.6, 107.6, 414.9, 3.6, 0, 0, 90, 107.6, 414.9, 13.6, 15, "SWAT", 1, 0, 0 }, [8]={ 16773, 60.8, 504.4, 24.9, 70.8, 504.4, 24.9, 90, 0, 0, 60.8, 504.4, 24.9, 15, "SWAT", 1, 0, 0 }, [9]={ 986, -1571.8, 662.1, 7.4, -1571.8, 654.6, 7.4, 0, 0, 90, -1571, 661.8, 6.8, 20, "Government", 1, 0, 0 }, [10]={ 985, -1641.4, 689, 7.4, -1641.4, 689, 7.4, 0, 0, 90, -1643, 682, 7.5, 20, "Government", 1, 0, 0 }, [11]={ 986, -1641.4, 681, 7.4, -1641.4, 673.1, 7.4, 0, 0, 90, -1643, 682, 7.5, 20, "Government", 1, 0, 0 }, [12]={ 985, -2990.75, 2358.6, 7.6, -2984.4, 2358.6, 7.6, 0, 0, 0, -2991, 2359, 7.2, 25, "Government", 0.83, 0, 0 }, [13]={ 985, 2237.5, 2453.3, 8.55, 2237.5, 2461.1, 8.55, 0, 0, 90, 2237, 2454, 10.6, 25, "Government", 1, 0, 0 }, [14]={ 986, 1543.55, -1627.1, 13.6, 1543.55, -1634.7, 13.6, 0, 0, 90, 1543, -1627, 13.1, 25, "Government", 0.93, 0, 0 }, [15]={ 985, -2228.5, 2373.3, 4.1, -2234.8, 2379.6, 4.1, 0, 0, 135, -2228, 2373, 4.9, 25, "Government", 1, 0, 0 }, [16]={ 985, 284.7, 1818.0, 17.0, 284.7, 1811.6, 17.0, 0, 0, 270, 284.7, 1818.0, 16.6, 10, "Government", 1, 0, 0 }, [17]={ 986, 284.7, 1826.0, 17.0, 284.7, 1831.2, 17.0, 0, 0, 270, 284.7, 1826.0, 16.6, 10, "Government", 1, 0, 0 }, [18]={ 985, 131, 1941.8, 17.8, 123, 1941.8, 17.8, 0, 0, 180, 131, 1941.4, 18.0, 10, "Government", 1, 0, 0 }, [19]={ 986, 139, 1941.8, 17.8, 147, 1941.8, 17.8, 0, 0, 180, 139, 1941.4, 18.0, 10, "Government", 1, 0, 0 }, [20]={ 986, -2980.0, 2253.1, 7.0, -2987.7, 2253.0, 7.0, 0, 0, 0, -2979, 2252.9, 7.2, 6, "Government", 1, 0, 0 }, [21]={ 986, -2954.8, 2136.5, 7.0, -2949.0, 2138, 7.0, 0, 0, 190, -2954, 2136.7, 7.0, 6, "Government", 1, 0, 0 }, [22]={ 986, -2996.1, 2305.1, 7.9, -2995.86, 2306.6, 7.9, 0, 0, 268.6, -2996, 2303.9, 7.0, 6, "Government", 1, 0, 0 }, --[23]={ 986, 380.2, -69.2, 1001.2, 380.2, -69.2, 1010.2, 0, 0, 90, 380.2, -69.2, 1002.7, 3, "Government", 0.4, 10, 10 }, [23]={ 985, -3085.2, 2314.7, 7.0, -3085.5, 2307.5, 7.0, 0, 0, 267, -3084.8, 2314.6, 7.0, 6, "Government", 1, 0, 0 }, [24]={ 986, -2953.4, 2255.8, 6.55, -2953.4, 2249.5, 6.55, 0, 0, 90, -2953.4, 2256.3, 7.0, 6, "Government", 1, 0, 0 }, } -- Global data members gates = { } cols = { } openSpeed = 3000 -- Add all gates function load_gates(name) for k=1, #gate_data do -- Create objects local gat = createObject( gate_data[k][1], gate_data[k][2], gate_data[k][3], gate_data[k][4], gate_data[k][8], gate_data[k][9], gate_data[k][10] ) local col = createColSphere( gate_data[k][11], gate_data[k][12], gate_data[k][13]+2, gate_data[k][14] ) setObjectScale( gat, gate_data[k][16] ) -- Assign arrays of object pointers gates[col] = gat cols[col] = k -- Set interior setElementInterior(gat, gate_data[k][17]) setElementInterior(col, gate_data[k][17]) -- Set dimension setElementDimension(gat, gate_data[k][18]) setElementDimension(col, gate_data[k][18]) -- Add event handlers addEventHandler("onColShapeHit", col, open_gate ) addEventHandler("onColShapeLeave", col, close_gate ) end end addEventHandler("onResourceStart", resourceRoot, load_gates) -- Gates open function open_gate(plr, matching_dimension) if not matching_dimension then return end local ID = cols[source] local px,py,pz = getElementPosition(plr) if plr and isElement(plr) and getElementType(plr) == "player" and ( getElementData(plr, "Group" ) == gate_data[ID][15] or getPlayerTeam(plr) == getTeamFromName(gate_data[ID][15]) or getPlayerTeam(plr) == getTeamFromName("Staff")) and pz + 5 > gate_data[ID][4] and pz - 5 < gate_data[ID][4] then -- Open the gate moveObject(gates[source], openSpeed, gate_data[ID][5], gate_data[ID][6], gate_data[ID][7] ) end end -- Gates close function close_gate(plr, matching_dimension) if not matching_dimension then return end local ID = cols[source] if plr and isElement(plr) and getElementType(plr) == "player" and ( getElementData(plr, "Group" ) == gate_data[ID][15] or getPlayerTeam(plr) == getTeamFromName(gate_data[ID][15]) or getPlayerTeam(plr) == getTeamFromName("Staff")) then moveObject(gates[source], openSpeed, gate_data[ID][2], gate_data[ID][3], gate_data[ID][4] ) end end
--[[ ******************************************************************************** Project owner: GTWGames Project name: GTW-RPG Developers: GTWCode Source code: https://github.com/GTWCode/GTW-RPG/ Bugtracker: http://forum.albonius.com/bug-reports/ Suggestions: http://forum.albonius.com/mta-servers-development/ Version: Open source License: GPL v.3 or later Status: Stable release ******************************************************************************** ]]-- -- ***************************************************************************** -- BELOW TABLE ARE MADE FOR SERVERS OWNED BY GRAND THEFT WALRUS, USE IT ONLY AS -- AN EXAMPLE OF THE LAYOUT TO UNDERSTAND HOW THIS SYSTEM WORKS -- ***************************************************************************** gate_data = { -- ObjectID closeX closeY closeZ openX openY openZ rotX rotY rotZ colX colY colZ colRad Group Scale Interior Dimension [1]={ 986, 1588.6, -1638.4, 13.4, 1578.6, -1638.4, 13.4, 0, 0, 0, 1588, -1638, 10, 5, "Government", 1, 0, 0 }, [2]={ 10671, -1631, 688.4, 8.587, -1631, 688.4, 20.187, 0, 0, 90, -1631, 688, 7.187, 10, "Government", 2, 0, 0 }, [3]={ 11327, 2334.6, 2443.7, 7.70, 2334.6, 2443.7, 15.70, 0, 0, -30, 2334.6, 2443.7, 5.70, 10, "Government", 1.3, 0, 0 }, [4]={ 2957, 2294, 2498.8, 5.1, 2294, 2498.8, 14.3, 0, 0, 90, 2294, 2498.8, 5.1, 10, "Government", 1.8, 0, 0 }, [5]={ 980, 3159, -1962.8, 12.5, 3159, -1947.8, 12.5, 0, 0, 90, 3159, -1967, 10, 10, "SAPD", 1, 0, 0 }, [6]={ 2938, 97.5, 508.5, 13.6, 97.5, 508.5, 3.6, 0, 0, 90, 97.5, 508.5, 13.6, 10, "SWAT", 1, 0, 0 }, [7]={ 2938, 107.6, 414.9, 13.6, 107.6, 414.9, 3.6, 0, 0, 90, 107.6, 414.9, 13.6, 10, "SWAT", 1, 0, 0 }, [8]={ 16773, 60.8, 504.4, 24.9, 70.8, 504.4, 24.9, 90, 0, 0, 60.8, 504.4, 24.9, 10, "SWAT", 1, 0, 0 }, [9]={ 986, -1571.8, 662.1, 7.4, -1571.8, 654.6, 7.4, 0, 0, 90, -1571, 661.8, 6.8, 10, "Government", 1, 0, 0 }, [10]={ 985, -1641.4, 689, 7.4, -1641.4, 689, 7.4, 0, 0, 90, -1643, 682, 7.5, 10, "Government", 1, 0, 0 }, [11]={ 986, -1641.4, 681, 7.4, -1641.4, 673.1, 7.4, 0, 0, 90, -1643, 682, 7.5, 10, "Government", 1, 0, 0 }, [12]={ 985, -2990.75, 2358.6, 7.6, -2984.4, 2358.6, 7.6, 0, 0, 0, -2991, 2359, 7.2, 15, "Government", 0.83, 0, 0 }, [13]={ 985, 2237.5, 2453.3, 8.55, 2237.5, 2461.1, 8.55, 0, 0, 90, 2237, 2454, 10.6, 15, "Government", 1, 0, 0 }, [14]={ 986, 1543.55, -1627.1, 13.6, 1543.55, -1634.7, 13.6, 0, 0, 90, 1543, -1627, 13.1, 15, "Government", 0.93, 0, 0 }, [15]={ 985, -2228.5, 2373.3, 4.1, -2234.8, 2379.6, 4.1, 0, 0, 135, -2228, 2373, 4.9, 15, "Government", 1, 0, 0 }, [16]={ 985, 284.7, 1818.0, 17.0, 284.7, 1811.6, 17.0, 0, 0, 270, 284.7, 1818.0, 16.6, 5, "Government", 1, 0, 0 }, [17]={ 986, 284.7, 1826.0, 17.0, 284.7, 1831.2, 17.0, 0, 0, 270, 284.7, 1826.0, 16.6, 5, "Government", 1, 0, 0 }, [18]={ 985, 131, 1941.8, 17.8, 123, 1941.8, 17.8, 0, 0, 180, 131, 1941.4, 18.0, 5, "Government", 1, 0, 0 }, [19]={ 986, 139, 1941.8, 17.8, 147, 1941.8, 17.8, 0, 0, 180, 139, 1941.4, 18.0, 5, "Government", 1, 0, 0 }, [20]={ 986, -2980.0, 2253.1, 7.0, -2987.7, 2253.0, 7.0, 0, 0, 0, -2979, 2252.9, 7.2, 6, "Government", 1, 0, 0 }, [21]={ 986, -2954.8, 2136.5, 7.0, -2949.0, 2138, 7.0, 0, 0, 190, -2954, 2136.7, 7.0, 6, "Government", 1, 0, 0 }, [22]={ 986, -2996.1, 2305.1, 7.9, -2995.86, 2306.6, 7.9, 0, 0, 268.6, -2996, 2303.9, 7.0, 6, "Government", 1, 0, 0 }, [23]={ 985, -3085.2, 2314.7, 7.0, -3085.5, 2307.5, 7.0, 0, 0, 267, -3084.8,2314.6, 7.0, 6, "Government", 1, 0, 0 }, [24]={ 986, -2953.4, 2255.8, 6.55, -2953.4, 2249.5, 6.55, 0, 0, 90, -2953.4,2256.3, 7.0, 6, "Government", 1, 0, 0 }, } -- Global data members gates = { } cols = { } openSpeed = 3000 -- Add all gates function load_gates(name) for k=1, #gate_data do -- Create objects local gat = createObject( gate_data[k][1], gate_data[k][2], gate_data[k][3], gate_data[k][4], gate_data[k][8], gate_data[k][9], gate_data[k][10] ) local col = createColSphere( gate_data[k][11], gate_data[k][12], gate_data[k][13]+2, gate_data[k][14] ) setObjectScale( gat, gate_data[k][16] ) -- Assign arrays of object pointers gates[col] = gat cols[col] = k -- Set interior setElementInterior(gat, gate_data[k][17]) setElementInterior(col, gate_data[k][17]) -- Set dimension setElementDimension(gat, gate_data[k][18]) setElementDimension(col, gate_data[k][18]) -- Add event handlers addEventHandler("onColShapeHit", col, open_gate ) addEventHandler("onColShapeLeave", col, close_gate ) end end addEventHandler("onResourceStart", resourceRoot, load_gates) -- Gates open function open_gate(plr, matching_dimension) if not matching_dimension then return end local ID = cols[source] local px,py,pz = getElementPosition(plr) if plr and isElement(plr) and getElementType(plr) == "player" and ( getElementData(plr, "Group" ) == gate_data[ID][15] or getPlayerTeam(plr) == getTeamFromName(gate_data[ID][15]) or getPlayerTeam(plr) == getTeamFromName("Staff")) and pz + 5 > gate_data[ID][4] and pz - 5 < gate_data[ID][4] then -- Open the gate moveObject(gates[source], openSpeed, gate_data[ID][5], gate_data[ID][6], gate_data[ID][7] ) end end -- Gates close function close_gate(plr, matching_dimension) if not matching_dimension then return end local ID = cols[source] if plr and isElement(plr) and getElementType(plr) == "player" and ( getElementData(plr, "Group" ) == gate_data[ID][15] or getPlayerTeam(plr) == getTeamFromName(gate_data[ID][15]) or getPlayerTeam(plr) == getTeamFromName("Staff")) then moveObject(gates[source], openSpeed, gate_data[ID][2], gate_data[ID][3], gate_data[ID][4] ) end end
[Patch] Fixed arguments issue in colSphere
[Patch] Fixed arguments issue in colSphere
Lua
bsd-2-clause
GTWCode/GTW-RPG,404rq/GTW-RPG,SpRoXx/GTW-RPG,404rq/GTW-RPG,SpRoXx/GTW-RPG,404rq/GTW-RPG,GTWCode/GTW-RPG,GTWCode/GTW-RPG
a5fc62b920a4696dbd91ce872aaba7c5510ff3b7
resources/prosody-plugins/mod_speakerstats_component.lua
resources/prosody-plugins/mod_speakerstats_component.lua
local get_room_from_jid = module:require "util".get_room_from_jid; local jid_resource = require "util.jid".resource; local ext_events = module:require "ext_events" local st = require "util.stanza"; local socket = require "socket"; local json = require "util.json"; local muc_component_host = module:get_option_string("muc_component"); if muc_component_host == nil then log("error", "No muc_component specified. No muc to operate on!"); return; end local muc_module = module:context("conference."..muc_component_host); if muc_module == nil then log("error", "No such muc found, check muc_component config."); return; end log("debug", "Starting speakerstats for %s", muc_component_host); -- receives messages from client currently connected to the room -- clients indicates their own dominant speaker events function on_message(event) -- Check the type of the incoming stanza to avoid loops: if event.stanza.attr.type == "error" then return; -- We do not want to reply to these, so leave. end local speakerStats = event.stanza:get_child('speakerstats', 'http://jitsi.org/jitmeet'); if speakerStats then local roomAddress = speakerStats.attr.room; local room = get_room_from_jid(roomAddress); if not room then log("warn", "No room found %s", roomAddress); return false; end local roomSpeakerStats = room.speakerStats; local from = event.stanza.attr.from; local occupant = room:get_occupant_by_real_jid(from); if not occupant then log("warn", "No occupant %s found for %s", from, roomAddress); return false; end local newDominantSpeaker = roomSpeakerStats[occupant.jid]; local oldDominantSpeakerId = roomSpeakerStats['dominantSpeakerId']; if oldDominantSpeakerId then roomSpeakerStats[oldDominantSpeakerId]:setDominantSpeaker(false); end if newDominantSpeaker then newDominantSpeaker:setDominantSpeaker(true); end room.speakerStats['dominantSpeakerId'] = occupant.jid; end return true end --- Start SpeakerStats implementation local SpeakerStats = {}; SpeakerStats.__index = SpeakerStats; function new_SpeakerStats(nick) return setmetatable({ totalDominantSpeakerTime = 0; _dominantSpeakerStart = 0; nick = nick; displayName = nil; }, SpeakerStats); end -- Changes the dominantSpeaker data for current occupant -- saves start time if it is new dominat speaker -- or calculates and accumulates time of speaking function SpeakerStats:setDominantSpeaker(isNowDominantSpeaker) log("debug", "set isDominant %s for %s", tostring(isNowDominantSpeaker), self.nick); if not self:isDominantSpeaker() and isNowDominantSpeaker then self._dominantSpeakerStart = socket.gettime()*1000; elseif self:isDominantSpeaker() and not isNowDominantSpeaker then local now = socket.gettime()*1000; local timeElapsed = math.floor(now - self._dominantSpeakerStart); self.totalDominantSpeakerTime = self.totalDominantSpeakerTime + timeElapsed; self._dominantSpeakerStart = 0; end end -- Returns true if the tracked user is currently a dominant speaker. function SpeakerStats:isDominantSpeaker() return self._dominantSpeakerStart > 0; end --- End SpeakerStats -- create speakerStats for the room function room_created(event) local room = event.room; room.speakerStats = {}; end -- Create SpeakerStats object for the joined user function occupant_joined(event) local room = event.room; local occupant = event.occupant; local nick = jid_resource(occupant.nick); if room.speakerStats then -- lets send the current speaker stats to that user, so he can update -- its local stats if next(room.speakerStats) ~= nil then local users_json = {}; for jid, values in pairs(room.speakerStats) do -- skip reporting those without a nick('dominantSpeakerId') -- and skip focus if sneaked into the table if values.nick ~= nil and values.nick ~= 'focus' then local resultSpeakerStats = {}; local totalDominantSpeakerTime = values.totalDominantSpeakerTime; -- before sending we need to calculate current dominant speaker -- state if values:isDominantSpeaker() ~= nil then local timeElapsed = math.floor( socket.gettime()*1000 - values._dominantSpeakerStart); totalDominantSpeakerTime = totalDominantSpeakerTime + timeElapsed; end resultSpeakerStats.displayName = values.displayName; resultSpeakerStats.totalDominantSpeakerTime = totalDominantSpeakerTime; users_json[values.nick] = resultSpeakerStats; end end local body_json = {}; body_json.type = 'speakerstats'; body_json.users = users_json; local stanza = st.message({ from = module.host; to = occupant.jid; }) :tag("json-message", {xmlns='http://jitsi.org/jitmeet'}) :text(json.encode(body_json)):up(); room:route_stanza(stanza); end room.speakerStats[occupant.jid] = new_SpeakerStats(nick); end end -- Occupant left set its dominant speaker to false and update the store the -- display name function occupant_leaving(event) local room = event.room; local occupant = event.occupant; local speakerStatsForOccupant = room.speakerStats[occupant.jid]; if speakerStatsForOccupant then speakerStatsForOccupant:setDominantSpeaker(false); -- set display name local displayName = occupant:get_presence():get_child_text( 'nick', 'http://jabber.org/protocol/nick'); speakerStatsForOccupant.displayName = displayName; end end -- Conference ended, send speaker stats function room_destroyed(event) local room = event.room; ext_events.speaker_stats(room, room.speakerStats); end module:hook("message/host", on_message); muc_module:hook("muc-room-created", room_created, -1); muc_module:hook("muc-occupant-joined", occupant_joined, -1); muc_module:hook("muc-occupant-pre-leave", occupant_leaving, -1); muc_module:hook("muc-room-destroyed", room_destroyed, -1);
local get_room_from_jid = module:require "util".get_room_from_jid; local jid_resource = require "util.jid".resource; local ext_events = module:require "ext_events" local st = require "util.stanza"; local socket = require "socket"; local json = require "util.json"; local muc_component_host = module:get_option_string("muc_component"); if muc_component_host == nil then log("error", "No muc_component specified. No muc to operate on!"); return; end log("info", "Starting speakerstats for %s", muc_component_host); -- receives messages from client currently connected to the room -- clients indicates their own dominant speaker events function on_message(event) -- Check the type of the incoming stanza to avoid loops: if event.stanza.attr.type == "error" then return; -- We do not want to reply to these, so leave. end local speakerStats = event.stanza:get_child('speakerstats', 'http://jitsi.org/jitmeet'); if speakerStats then local roomAddress = speakerStats.attr.room; local room = get_room_from_jid(roomAddress); if not room then log("warn", "No room found %s", roomAddress); return false; end local roomSpeakerStats = room.speakerStats; local from = event.stanza.attr.from; local occupant = room:get_occupant_by_real_jid(from); if not occupant then log("warn", "No occupant %s found for %s", from, roomAddress); return false; end local newDominantSpeaker = roomSpeakerStats[occupant.jid]; local oldDominantSpeakerId = roomSpeakerStats['dominantSpeakerId']; if oldDominantSpeakerId then roomSpeakerStats[oldDominantSpeakerId]:setDominantSpeaker(false); end if newDominantSpeaker then newDominantSpeaker:setDominantSpeaker(true); end room.speakerStats['dominantSpeakerId'] = occupant.jid; end return true end --- Start SpeakerStats implementation local SpeakerStats = {}; SpeakerStats.__index = SpeakerStats; function new_SpeakerStats(nick) return setmetatable({ totalDominantSpeakerTime = 0; _dominantSpeakerStart = 0; nick = nick; displayName = nil; }, SpeakerStats); end -- Changes the dominantSpeaker data for current occupant -- saves start time if it is new dominat speaker -- or calculates and accumulates time of speaking function SpeakerStats:setDominantSpeaker(isNowDominantSpeaker) log("debug", "set isDominant %s for %s", tostring(isNowDominantSpeaker), self.nick); if not self:isDominantSpeaker() and isNowDominantSpeaker then self._dominantSpeakerStart = socket.gettime()*1000; elseif self:isDominantSpeaker() and not isNowDominantSpeaker then local now = socket.gettime()*1000; local timeElapsed = math.floor(now - self._dominantSpeakerStart); self.totalDominantSpeakerTime = self.totalDominantSpeakerTime + timeElapsed; self._dominantSpeakerStart = 0; end end -- Returns true if the tracked user is currently a dominant speaker. function SpeakerStats:isDominantSpeaker() return self._dominantSpeakerStart > 0; end --- End SpeakerStats -- create speakerStats for the room function room_created(event) local room = event.room; room.speakerStats = {}; end -- Create SpeakerStats object for the joined user function occupant_joined(event) local room = event.room; local occupant = event.occupant; local nick = jid_resource(occupant.nick); if room.speakerStats then -- lets send the current speaker stats to that user, so he can update -- its local stats if next(room.speakerStats) ~= nil then local users_json = {}; for jid, values in pairs(room.speakerStats) do -- skip reporting those without a nick('dominantSpeakerId') -- and skip focus if sneaked into the table if values.nick ~= nil and values.nick ~= 'focus' then local resultSpeakerStats = {}; local totalDominantSpeakerTime = values.totalDominantSpeakerTime; -- before sending we need to calculate current dominant speaker -- state if values:isDominantSpeaker() then local timeElapsed = math.floor( socket.gettime()*1000 - values._dominantSpeakerStart); totalDominantSpeakerTime = totalDominantSpeakerTime + timeElapsed; end resultSpeakerStats.displayName = values.displayName; resultSpeakerStats.totalDominantSpeakerTime = totalDominantSpeakerTime; users_json[values.nick] = resultSpeakerStats; end end local body_json = {}; body_json.type = 'speakerstats'; body_json.users = users_json; local stanza = st.message({ from = module.host; to = occupant.jid; }) :tag("json-message", {xmlns='http://jitsi.org/jitmeet'}) :text(json.encode(body_json)):up(); room:route_stanza(stanza); end room.speakerStats[occupant.jid] = new_SpeakerStats(nick); end end -- Occupant left set its dominant speaker to false and update the store the -- display name function occupant_leaving(event) local room = event.room; local occupant = event.occupant; local speakerStatsForOccupant = room.speakerStats[occupant.jid]; if speakerStatsForOccupant then speakerStatsForOccupant:setDominantSpeaker(false); -- set display name local displayName = occupant:get_presence():get_child_text( 'nick', 'http://jabber.org/protocol/nick'); speakerStatsForOccupant.displayName = displayName; end end -- Conference ended, send speaker stats function room_destroyed(event) local room = event.room; ext_events.speaker_stats(room, room.speakerStats); end module:hook("message/host", on_message); -- executed on every host added internally in prosody, including components function process_host(host) if host == muc_component_host then -- the conference muc component module:log("info","Hook to muc events on %s", host); local muc_module = module:context(host); muc_module:hook("muc-room-created", room_created, -1); muc_module:hook("muc-occupant-joined", occupant_joined, -1); muc_module:hook("muc-occupant-pre-leave", occupant_leaving, -1); muc_module:hook("muc-room-destroyed", room_destroyed, -1); end end if prosody.hosts[muc_component_host] == nil then module:log("info","No muc component found, will listen for it: %s", muc_component_host) -- when a host or component is added prosody.events.add_handler("host-activated", process_host); else process_host(muc_component_host); end
Updates correct loading and fix checking is dominant speaker.
Updates correct loading and fix checking is dominant speaker.
Lua
apache-2.0
jitsi/jitsi-meet,bgrozev/jitsi-meet,bgrozev/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,bgrozev/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,bgrozev/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,bgrozev/jitsi-meet,gpolitis/jitsi-meet,bgrozev/jitsi-meet
601ebb477e163e44290bcdd5129d378d6ff75ba5
server/lualib/channelhub.lua
server/lualib/channelhub.lua
local core = require "silly.core" local np = require "netpacket" local token = require "token" local sproto = require "protocol.server" local master = require "cluster.master" local pack = string.pack local unpack = string.unpack ----------------socket local function sendserver(fd, uid, cmd, ack) cmd = sproto:querytag(cmd) local hdr = pack("<I4I4", uid, cmd) local dat = sproto:encode(cmd, ack) return master.sendslave(fd, hdr .. dat) end local function forwardserver(fd, uid, dat) local hdr = pack("<I4", uid) return master.sendslave(fd, hdr .. dat) end ----------------channel router local NIL = {} local CMD = {} local readonly = {__newindex = function() assert("read only table") end} local router_handler = {} local function router_regserver(cmd, func) local cmd = sproto:querytag(cmd) local cb = function(uid, dat, fd) local req if #dat > 8 then dat = dat:sub(8 + 1) req = sproto:decode(cmd, dat) else req = NIL end func(uid, req, fd) end CMD[cmd] = cb end ----------------online local LOGIN_TYPE = 1 * 10000 local ROLE_TYPE = 2 * 10000 local agent_serverkey = { [LOGIN_TYPE] = "slogin", [ROLE_TYPE] = "srole", } local online_agent = {} local function online_login(uid, agent) online_agent[uid] = agent agent.slogin = 1 agent.srole = 1 end local function online_logout(uid) local a = online_agent[uid] if not a then return end a.slogin = false s.srole = false online_agent[uid] = nil end local function online_kickout(uid) local a = online_agent[uid] if not a then return end a.slogin = false a.srole = false a:kickout() online_agent[uid] = nil end --------------channel forward local channel_type_key = { --login ["login"] = LOGIN_TYPE, [LOGIN_TYPE] = "login", --role ["role"] = ROLE_TYPE, [ROLE_TYPE] = "role" } local channel_fd_typeid = { --[fd] = 'channel_type_key[type] + serverid' } local channel_typeid_fd = { --[channel_type_key[type] + serverid] = fd } local channel_cmd_typeid = { --[cmd] = typeid } local function channel_regclient(typ, id, fd, list_cmd) local typeid = assert(channel_type_key[typ], typ) for _, v in pairs(list_cmd) do local typ = channel_cmd_typeid[v] if typ then assert(typ == typeid) else channel_cmd_typeid[v] = typeid end end typeid = typeid + id channel_fd_typeid[fd] = typeid channel_typeid_fd[typeid] = fd end local function channel_clear(fd) local typeid = channel_fd_typeid[fd] if not typeid then return end channel_fd_typeid[fd] = nil channel_typeid_fd[typeid] = nil end local function channel_tryforward(agent, cmd, dat) --dat:[cmd][packet] local typeid = channel_cmd_typeid[cmd] if not typeid then return false end local id = agent[key] if not id then return false end local key = agent_serverkey[typeid] typeid = typeid + id local fd = channel_typeid_fd[typeid] if not fd then return false end return forwardserver(fd, agent.uid, dat) end ----------------protocol local function sr_register(uid, req, fd) print("[gate] sr_register:", req.typ, req.id) for _, v in pairs(req.handler) do print(string.format("[gate] sr_register %s", v)) end channel_regclient(req.typ, req.id, fd, req.handler) sendserver(fd, uid, "sa_register", req) end local function sr_fetchtoken(uid, req, fd) local tk = token.fetch(uid) req.token = tk sendserver(fd, uid, "sa_fetchtoken", req) print("[gate] fetch token", uid, tk) end local function sr_kickout(uid, req, fd) online_kickout(uid) sendserver(fd, uid, "sa_kickout", req) print("[gate]fetch kickout uid:", uid, "gatefd", gatefd) end local function s_multicast(uid, req, fd) print("muticast") end router_regserver("sr_register", sr_register) router_regserver("sr_fetchtoken", sr_fetchtoken) router_regserver("sr_kickout", sr_kickout) router_regserver("s_multicast", s_multicast) --------------entry local M = { login = online_login, logout = online_logout, tryforward = channel_tryforward, --event accept = function(fd, addr) end, close = function(fd, errno) channel_clear(fd) end, data = function(fd, d, sz) local dat = core.tostring(d, sz) np.drop(d) local uid, cmd = unpack("<I4I4", dat) local func = CMD[cmd] if func then func(uid, dat, fd) return end local a = online_agent[uid] if not a then print("[gate] broker data uid:", uid, " logout") return end a:slavedata(cmd, dat) end, } return M
local core = require "silly.core" local np = require "netpacket" local token = require "token" local sproto = require "protocol.server" local master = require "cluster.master" local pack = string.pack local unpack = string.unpack ----------------socket local function sendserver(fd, uid, cmd, ack) cmd = sproto:querytag(cmd) local hdr = pack("<I4I4", uid, cmd) local dat = sproto:encode(cmd, ack) return master.sendslave(fd, hdr .. dat) end local function forwardserver(fd, uid, dat) local hdr = pack("<I4", uid) return master.sendslave(fd, hdr .. dat) end ----------------channel router local NIL = {} local CMD = {} local readonly = {__newindex = function() assert("read only table") end} local router_handler = {} local function router_regserver(cmd, func) local cmd = sproto:querytag(cmd) local cb = function(uid, dat, fd) local req if #dat > 8 then dat = dat:sub(8 + 1) req = sproto:decode(cmd, dat) else req = NIL end func(uid, req, fd) end CMD[cmd] = cb end ----------------online local LOGIN_TYPE = 1 * 10000 local ROLE_TYPE = 2 * 10000 local agent_serverkey = { [LOGIN_TYPE] = "slogin", [ROLE_TYPE] = "srole", } local online_agent = {} local function online_login(uid, agent) online_agent[uid] = agent agent.slogin = 1 agent.srole = 1 end local function online_logout(uid) local a = online_agent[uid] if not a then return end a.slogin = false s.srole = false online_agent[uid] = nil end local function online_kickout(uid) local a = online_agent[uid] if not a then return end a.slogin = false a.srole = false a:kickout() online_agent[uid] = nil end --------------channel forward local channel_type_key = { --login ["login"] = LOGIN_TYPE, [LOGIN_TYPE] = "login", --role ["role"] = ROLE_TYPE, [ROLE_TYPE] = "role" } local channel_fd_typeid = { --[fd] = 'channel_type_key[type] + serverid' } local channel_typeid_fd = { --[channel_type_key[type] + serverid] = fd } local channel_cmd_typeid = { --[cmd] = typeid } local function channel_regclient(typ, id, fd, list_cmd) local typeid = assert(channel_type_key[typ], typ) for _, v in pairs(list_cmd) do local typ = channel_cmd_typeid[v] if typ then assert(typ == typeid) else channel_cmd_typeid[v] = typeid end end typeid = typeid + id channel_fd_typeid[fd] = typeid channel_typeid_fd[typeid] = fd end local function channel_clear(fd) local typeid = channel_fd_typeid[fd] if not typeid then return end channel_fd_typeid[fd] = nil channel_typeid_fd[typeid] = nil end local function channel_tryforward(agent, cmd, dat) --dat:[cmd][packet] local typeid = channel_cmd_typeid[cmd] if not typeid then return false end local key = agent_serverkey[typeid] local id = agent[key] if not id then return false end typeid = typeid + id local fd = channel_typeid_fd[typeid] if not fd then return false end return forwardserver(fd, agent.uid, dat) end ----------------protocol local function sr_register(uid, req, fd) print("[gate] sr_register:", req.typ, req.id) for _, v in pairs(req.handler) do print(string.format("[gate] sr_register %s", v)) end channel_regclient(req.typ, req.id, fd, req.handler) sendserver(fd, uid, "sa_register", req) end local function sr_fetchtoken(uid, req, fd) local tk = token.fetch(uid) req.token = tk sendserver(fd, uid, "sa_fetchtoken", req) print("[gate] fetch token", uid, tk) end local function sr_kickout(uid, req, fd) online_kickout(uid) sendserver(fd, uid, "sa_kickout", req) print("[gate]fetch kickout uid:", uid, "gatefd", gatefd) end local function s_multicast(uid, req, fd) print("muticast") end router_regserver("sr_register", sr_register) router_regserver("sr_fetchtoken", sr_fetchtoken) router_regserver("sr_kickout", sr_kickout) router_regserver("s_multicast", s_multicast) --------------entry local M = { login = online_login, logout = online_logout, tryforward = channel_tryforward, --event accept = function(fd, addr) end, close = function(fd, errno) channel_clear(fd) end, data = function(fd, d, sz) local dat = core.tostring(d, sz) np.drop(d) local uid, cmd = unpack("<I4I4", dat) local func = CMD[cmd] if func then func(uid, dat, fd) return end local a = online_agent[uid] if not a then print("[gate] broker data uid:", uid, " logout") return end a:slavedata(cmd, dat) end, } return M
bugfix: channel_tryforward
bugfix: channel_tryforward
Lua
mit
findstr/mmorpg-demo,findstr/mmorpg-demo
f107daad07b8e763d4ad8cac843ff9dc77894bbd
tests/sfxr/main3.lua
tests/sfxr/main3.lua
require "snd" require "timer" local sfxr = require("sfxr") local last = true room { nam = 'main'; timer = function() if snd.playing(3) then p [[PLAYING]] last = true return elseif last then last = false p [[Нажмите на {button|кнопку} для эффекта.]]; end return false end }:with{ obj { nam = 'button'; act = function(s) local sound = sfxr.newSound() sound:randomize(rnd(32768)) local sounddata = sound:generateSoundData(22050) local source = snd.new(22050, 1, sounddata) source:play(3) end } } function start() timer:set(100) end
require "snd" require "timer" local sfxr = require("sfxr") local last = true local wav -- to cache sound room { nam = 'main'; timer = function() if snd.playing() then p [[PLAYING]] last = true return elseif last then last = false p [[Нажмите на {button|кнопку} для эффекта.]]; end return false end }:with{ obj { nam = 'button'; act = function(s) local sound = sfxr.newSound() sound:randomize(rnd(32768)) local sounddata = sound:generateSoundData(22050) wav = snd.new(22050, 1, sounddata) wav:play() end } } function start() timer:set(100) end
sfxr fix
sfxr fix
Lua
mit
gl00my/stead3
d968f88fed6e1fc05b0ca795b897d662a3517ff1
Shilke2D/Display/Image.lua
Shilke2D/Display/Image.lua
-- Image --[[ An Image is the Shilke2D equivalent of Flash's Bitmap class. Instead of BitmapData, Shilke2D uses textures to represent the pixels of an image. --]] Image = class(FixedSizeObject) function Image:init(texture, pivotMode) if texture then FixedSizeObject.init(self,texture.width,texture.height,pivotMode) self.texture = texture self._prop:setDeck(texture:_getQuad()) else FixedSizeObject.init(self,0,0,pivotMode) self.texture = nil end self.ppHitTest = false self.ppAlphaLevel = 0 end function Image:dispose() FixedSizeObject.dispose(self) self.texture = nil end function Image:setPixelPreciseHitTest(enabled,alphaLevel) self.ppHitTest = enabled if enabled then self.ppAlphaLevel = alphaLevel ~= nil and alphaLevel or 0 end end function Image:hitTest(x,y,targetSpace,forTouch) if not forTouch or (self._visible and self._touchable) then local _x,_y if targetSpace == self then _x,_y = x,y else _x,_y = self:globalToLocal(x,y,targetSpace) end local r = self:getBounds(self,__helperRect) if r:containsPoint(_x,_y) then if self.ppHitTest then local _,_,_,a = self.texture:getRGBA(_x-r.x, _y-r.y) if a > self.ppAlphaLevel then return self else return nil end else return self end end end return nil end -- public --the clone method return a new Image that shares the same texture --of the original image. It's possible to clone also --pivot mode / position function Image:clone(bClonePivot) if not bClonePivot then return Image(self.texture) else local obj = Image(self.texture,self._pivotMode) if self._pivotMode == PivotMode.CUSTOM then obj:setPivot(self:getPivot()) end return obj end end --[[ If the new and the old textures shared the same textureData the switch is just an uv switch, else a full texture switch It would be preferrable that all the textures that can be assigned to a specific image belongs to the same texture atlas, to avoid texturedata switch at container level that requires mesh quads pool management, possible creation of a new quad, a forced updategeometry, ecc. --]] function Image:setTexture(texture) if self.texture ~= texture then if not texture then self.texture = nil self._prop:setDeck(nil) self:setSize(0,0) else --if first set (called by init) or texture switch between --subtexture of the same texture atlas, an update is --required only if the shape changes local bUpdateGeometry = not self.texture or (self.texture.width ~= texture.width) or (self.texture.height ~= texture.height) self.texture = texture self._prop:setDeck(texture:_getQuad()) if bUpdateGeometry then self:setSize(texture.width,texture.height) end end end end function Image:getTexture() return self.texture end
-- Image --[[ An Image is the Shilke2D equivalent of Flash's Bitmap class. Instead of BitmapData, Shilke2D uses textures to represent the pixels of an image. --]] Image = class(FixedSizeObject) function Image:init(texture, pivotMode) if texture then FixedSizeObject.init(self,texture.width,texture.height,pivotMode) self.texture = texture self._prop:setDeck(texture:_getQuad()) else FixedSizeObject.init(self,0,0,pivotMode) self.texture = nil end self.ppHitTest = false self.ppAlphaLevel = 0 end function Image:dispose() FixedSizeObject.dispose(self) self.texture = nil end function Image:setPixelPreciseHitTest(enabled,alphaLevel) self.ppHitTest = enabled if enabled then self.ppAlphaLevel = alphaLevel ~= nil and alphaLevel/255 or 0 end end function Image:hitTest(x,y,targetSpace,forTouch) if not forTouch or (self._visible and self._touchable) then local _x,_y if targetSpace == self then _x,_y = x,y else _x,_y = self:globalToLocal(x,y,targetSpace) end local r = self:getBounds(self,__helperRect) if r:containsPoint(_x,_y) then if self.ppHitTest then local a if __USE_SIMULATION_COORDS__ then _,_,_,a = self.texture:getRGBA(_x-r.x, -_y-r.y) else _,_,_,a = self.texture:getRGBA(_x-r.x, _y-r.y) end if a > self.ppAlphaLevel then return self else return nil end else return self end end end return nil end -- public --the clone method return a new Image that shares the same texture --of the original image. It's possible to clone also --pivot mode / position function Image:clone(bClonePivot) if not bClonePivot then return Image(self.texture) else local obj = Image(self.texture,self._pivotMode) if self._pivotMode == PivotMode.CUSTOM then obj:setPivot(self:getPivot()) end return obj end end --[[ If the new and the old textures shared the same textureData the switch is just an uv switch, else a full texture switch It would be preferrable that all the textures that can be assigned to a specific image belongs to the same texture atlas, to avoid texturedata switch at container level that requires mesh quads pool management, possible creation of a new quad, a forced updategeometry, ecc. --]] function Image:setTexture(texture) if self.texture ~= texture then if not texture then self.texture = nil self._prop:setDeck(nil) self:setSize(0,0) else --if first set (called by init) or texture switch between --subtexture of the same texture atlas, an update is --required only if the shape changes local bUpdateGeometry = not self.texture or (self.texture.width ~= texture.width) or (self.texture.height ~= texture.height) self.texture = texture self._prop:setDeck(texture:_getQuad()) if bUpdateGeometry then self:setSize(texture.width,texture.height) end end end end function Image:getTexture() return self.texture end
image pixel precision hit test fixes
image pixel precision hit test fixes - setPixelPreciseHitTest alphaLevel is divided by 255 - hitTest handle now correctly the __USE_SIMULATION_COORDS__ configuration
Lua
mit
Shrike78/Shilke2D
a648e02157e23aa5de1fc2b9d10edae28651f065
core/ext/pm/buffer_browser.lua
core/ext/pm/buffer_browser.lua
-- Copyright 2007-2009 Mitchell mitchell<att>caladbolg.net. See LICENSE. local textadept = _G.textadept local locale = _G.locale --- -- Buffer browser for the Textadept project manager. -- It is enabled with the prefix 'buffers' in the project manager entry field. module('textadept.pm.browsers.buffer', package.seeall) if not RESETTING then textadept.pm.add_browser('buffers') end function matches(entry_text) return entry_text:sub(1, 7) == 'buffers' end function get_contents_for() local contents = {} for index, buffer in ipairs(textadept.buffers) do index = string.format("%02i", index) contents[index] = { pixbuf = buffer.dirty and 'gtk-edit' or 'gtk-file', text = (buffer.filename or buffer._type or locale.UNTITLED):match('[^/\\]+$') } end return contents end function perform_action(selected_item) local index = selected_item[2] local buffer = textadept.buffers[tonumber(index)] if buffer then view:goto_buffer(index) view:focus() end end local ID = { NEW = 1, OPEN = 2, SAVE = 3, SAVEAS = 4, CLOSE = 5 } function get_context_menu(selected_item) return { { locale.PM_BROWSER_BUFFER_NEW, ID.NEW }, { locale.PM_BROWSER_BUFFER_OPEN, ID.OPEN }, { locale.PM_BROWSER_BUFFER_SAVE, ID.SAVE }, { locale.PM_BROWSER_BUFFER_SAVEAS, ID.SAVEAS }, { 'separator', 0 }, { locale.PM_BROWSER_BUFFER_CLOSE, ID.CLOSE }, } end local function update_view() if matches(textadept.pm.entry_text) then textadept.pm.activate() for idx, buf in ipairs(textadept.buffers) do if buf == buffer then textadept.pm.cursor = idx - 1 break end end end end function perform_menu_action(menu_id, selected_item) if menu_id == ID.NEW then textadept.new_buffer() elseif menu_id == ID.OPEN then textadept.io.open() elseif menu_id == ID.SAVE then view:goto_buffer(tonumber(selected_item[2])) buffer:save() elseif menu_id == ID.SAVEAS then view:goto_buffer(tonumber(selected_item[2])) buffer:save_as() elseif menu_id == ID.CLOSE then view:goto_buffer(tonumber(selected_item[2])) buffer:close() end update_view() end textadept.events.add_handler('file_opened', update_view) textadept.events.add_handler('buffer_new', update_view) textadept.events.add_handler('buffer_deleted', update_view) textadept.events.add_handler('save_point_reached', update_view) textadept.events.add_handler('save_point_left', update_view) textadept.events.add_handler('buffer_switch', update_view) textadept.events.add_handler('view_switch', update_view)
-- Copyright 2007-2009 Mitchell mitchell<att>caladbolg.net. See LICENSE. local textadept = _G.textadept local locale = _G.locale --- -- Buffer browser for the Textadept project manager. -- It is enabled with the prefix 'buffers' in the project manager entry field. module('textadept.pm.browsers.buffer', package.seeall) if not RESETTING then textadept.pm.add_browser('buffers') end function matches(entry_text) return entry_text:sub(1, 7) == 'buffers' end function get_contents_for() local contents = {} for index, buffer in ipairs(textadept.buffers) do index = string.format("%02i", index) contents[index] = { pixbuf = buffer.dirty and 'gtk-edit' or 'gtk-file', text = (buffer.filename or buffer._type or locale.UNTITLED):match('[^/\\]+$') } end return contents end function perform_action(selected_item) local index = selected_item[2] local buffer = textadept.buffers[tonumber(index)] if buffer then view:goto_buffer(index) view:focus() end end local ID = { NEW = 1, OPEN = 2, SAVE = 3, SAVEAS = 4, CLOSE = 5 } function get_context_menu(selected_item) return { { locale.PM_BROWSER_BUFFER_NEW, ID.NEW }, { locale.PM_BROWSER_BUFFER_OPEN, ID.OPEN }, { locale.PM_BROWSER_BUFFER_SAVE, ID.SAVE }, { locale.PM_BROWSER_BUFFER_SAVEAS, ID.SAVEAS }, { 'separator', 0 }, { locale.PM_BROWSER_BUFFER_CLOSE, ID.CLOSE }, } end function perform_menu_action(menu_id, selected_item) if menu_id == ID.NEW then textadept.new_buffer() elseif menu_id == ID.OPEN then textadept.io.open() elseif menu_id == ID.SAVE then view:goto_buffer(tonumber(selected_item[2])) buffer:save() elseif menu_id == ID.SAVEAS then view:goto_buffer(tonumber(selected_item[2])) buffer:save_as() elseif menu_id == ID.CLOSE then view:goto_buffer(tonumber(selected_item[2])) buffer:close() end textadept.pm.activate() end local function update_view() if matches(textadept.pm.entry_text) then textadept.pm.activate() end end textadept.events.add_handler('file_opened', update_view) textadept.events.add_handler('buffer_new', update_view) textadept.events.add_handler('buffer_deleted', update_view) textadept.events.add_handler('save_point_reached', update_view) textadept.events.add_handler('save_point_left', update_view) textadept.events.add_handler('buffer_switch', update_view) textadept.events.add_handler('view_switch', update_view) local function set_cursor() if matches(textadept.pm.entry_text) then for idx, buf in ipairs(textadept.buffers) do if buf == buffer then textadept.pm.cursor = idx - 1 break end end end end textadept.events.add_handler('pm_view_filled', set_cursor)
Fixed issue with buffer browser cursor saving; core/ext/pm/buffer_browser.lua
Fixed issue with buffer browser cursor saving; core/ext/pm/buffer_browser.lua
Lua
mit
rgieseke/textadept,rgieseke/textadept
232e504f46ac07b1d03ea45f197a633fe3a9e9fd
volume-widget/volume.lua
volume-widget/volume.lua
------------------------------------------------- -- Volume Widget for Awesome Window Manager -- Shows the current volume level -- More details could be found here: -- https://github.com/streetturtle/awesome-wm-widgets/tree/master/volume-widget -- @author Pavel Makhov, Aurélien Lajoie -- @copyright 2018 Pavel Makhov ------------------------------------------------- local wibox = require("wibox") local watch = require("awful.widget.watch") local spawn = require("awful.spawn") local naughty = require("naughty") local gfs = require("gears.filesystem") local dpi = require('beautiful').xresources.apply_dpi local PATH_TO_ICONS = "/usr/share/icons/Arc/status/symbolic/" local volume_icon_name="audio-volume-high-symbolic" local GET_VOLUME_CMD = 'amixer sget Master' local volume = {device = '', display_notification = false, notification = nil} function volume:toggle() volume:_cmd('amixer ' .. volume.device .. ' sset Master toggle') end function volume:raise() volume:_cmd('amixer ' .. volume.device .. ' sset Master 5%+') end function volume:lower() volume:_cmd('amixer ' .. volume.device .. ' sset Master 5%-') end --{{{ Icon and notification update -------------------------------------------------- -- Set the icon and return the message to display -- base on sound level and mute -------------------------------------------------- local function parse_output(stdout) local level = string.match(stdout, "(%d?%d?%d)%%") if stdout:find("%[off%]") then volume_icon_name="audio-volume-muted-symbolic_red" return level.."% <span color=\"red\"><b>Mute</b></span>" end level = tonumber(string.format("% 3d", level)) if (level >= 0 and level < 25) then volume_icon_name="audio-volume-muted-symbolic" elseif (level < 50) then volume_icon_name="audio-volume-low-symbolic" elseif (level < 75) then volume_icon_name="audio-volume-medium-symbolic" else volume_icon_name="audio-volume-high-symbolic" end return level.."%" end -------------------------------------------------------- --Update the icon and the notification if needed -------------------------------------------------------- local function update_graphic(widget, stdout, _, _, _) local txt = parse_output(stdout) widget.image = PATH_TO_ICONS .. volume_icon_name .. ".svg" if volume.display_notification then volume.notification.iconbox.image = PATH_TO_ICONS .. volume_icon_name .. ".svg" naughty.replace_text(volume.notification, "Volume", txt) end end local function notif(msg, keep) if volume.display_notification then naughty.destroy(volume.notification) volume.notification= naughty.notify{ text = msg, icon=PATH_TO_ICONS .. volume_icon_name .. ".svg", icon_size = dpi(16), title = "Volume", position = volume.position, timeout = keep and 0 or 2, hover_timeout = 0.5, width = 200, screen = mouse.screen } end end --}}} local function worker(args) --{{{ Args local args = args or {} local volume_audio_controller = args.volume_audio_controller or 'pulse' volume.display_notification = args.display_notification or false volume.position = args.notification_position or "top_right" if volume_audio_controller == 'pulse' then volume.device = '-D pulse' end GET_VOLUME_CMD = 'amixer ' .. volume.device.. ' sget Master' --}}} --{{{ Check for icon path if not gfs.dir_readable(PATH_TO_ICONS) then naughty.notify{ title = "Volume Widget", text = "Folder with icons doesn't exist: " .. PATH_TO_ICONS, preset = naughty.config.presets.critical } return end --}}} --{{{ Widget creation volume.widget = wibox.widget { { id = "icon", image = PATH_TO_ICONS .. "audio-volume-muted-symbolic.svg", resize = false, widget = wibox.widget.imagebox, }, layout = wibox.container.margin(_, _, _, 3), set_image = function(self, path) self.icon.image = path end } --}}} --{{{ Spawn functions function volume:_cmd(cmd) notif("") spawn.easy_async(cmd, function(stdout, stderr, exitreason, exitcode) update_graphic(volume.widget, stdout, stderr, exitreason, exitcode) end) end local function show() spawn.easy_async(GET_VOLUME_CMD, function(stdout, _, _, _) txt = parse_output(stdout) notif(txt, true) end ) end --}}} --{{{ Mouse event --[[ allows control volume level by: - clicking on the widget to mute/unmute - scrolling when cursor is over the widget ]] volume.widget:connect_signal("button::press", function(_,_,_,button) if (button == 4) then volume.raise() elseif (button == 5) then volume.lower() elseif (button == 1) then volume.toggle() end end) if volume.display_notification then volume.widget:connect_signal("mouse::enter", function() show() end) volume.widget:connect_signal("mouse::leave", function() naughty.destroy(volume.notification) end) end --}}} return volume.widget end return setmetatable(volume, { __call = function(_, ...) return worker(...) end })
------------------------------------------------- -- Volume Widget for Awesome Window Manager -- Shows the current volume level -- More details could be found here: -- https://github.com/streetturtle/awesome-wm-widgets/tree/master/volume-widget -- @author Pavel Makhov, Aurélien Lajoie -- @copyright 2018 Pavel Makhov ------------------------------------------------- local wibox = require("wibox") local watch = require("awful.widget.watch") local spawn = require("awful.spawn") local naughty = require("naughty") local gfs = require("gears.filesystem") local dpi = require('beautiful').xresources.apply_dpi local PATH_TO_ICONS = "/usr/share/icons/Arc/status/symbolic/" local volume_icon_name="audio-volume-high-symbolic" local GET_VOLUME_CMD = 'amixer sget Master' local volume = {device = '', display_notification = false, notification = nil} function volume:toggle() volume:_cmd('amixer ' .. volume.device .. ' sset Master toggle') end function volume:raise() volume:_cmd('amixer ' .. volume.device .. ' sset Master 5%+') end function volume:lower() volume:_cmd('amixer ' .. volume.device .. ' sset Master 5%-') end --{{{ Icon and notification update -------------------------------------------------- -- Set the icon and return the message to display -- base on sound level and mute -------------------------------------------------- local function parse_output(stdout) local level = string.match(stdout, "(%d?%d?%d)%%") if stdout:find("%[off%]") then volume_icon_name="audio-volume-muted-symbolic_red" return level.."% <span color=\"red\"><b>Mute</b></span>" end level = tonumber(string.format("% 3d", level)) if (level >= 0 and level < 25) then volume_icon_name="audio-volume-muted-symbolic" elseif (level < 50) then volume_icon_name="audio-volume-low-symbolic" elseif (level < 75) then volume_icon_name="audio-volume-medium-symbolic" else volume_icon_name="audio-volume-high-symbolic" end return level.."%" end -------------------------------------------------------- --Update the icon and the notification if needed -------------------------------------------------------- local function update_graphic(widget, stdout, _, _, _) local txt = parse_output(stdout) widget.image = PATH_TO_ICONS .. volume_icon_name .. ".svg" if volume.display_notification then volume.notification.iconbox.image = PATH_TO_ICONS .. volume_icon_name .. ".svg" naughty.replace_text(volume.notification, "Volume", txt) end end local function notif(msg, keep) if volume.display_notification then naughty.destroy(volume.notification) volume.notification= naughty.notify{ text = msg, icon=PATH_TO_ICONS .. volume_icon_name .. ".svg", icon_size = dpi(16), title = "Volume", position = volume.position, timeout = keep and 0 or 2, hover_timeout = 0.5, width = 200, screen = mouse.screen } end end --}}} local function worker(args) --{{{ Args local args = args or {} local volume_audio_controller = args.volume_audio_controller or 'pulse' volume.display_notification = args.display_notification or false volume.position = args.notification_position or "top_right" if volume_audio_controller == 'pulse' then volume.device = '-D pulse' end GET_VOLUME_CMD = 'amixer ' .. volume.device.. ' sget Master' --}}} --{{{ Check for icon path if not gfs.dir_readable(PATH_TO_ICONS) then naughty.notify{ title = "Volume Widget", text = "Folder with icons doesn't exist: " .. PATH_TO_ICONS, preset = naughty.config.presets.critical } return end --}}} --{{{ Widget creation volume.widget = wibox.widget { { id = "icon", image = PATH_TO_ICONS .. "audio-volume-muted-symbolic.svg", resize = false, widget = wibox.widget.imagebox, }, layout = wibox.container.margin(_, _, _, 3), set_image = function(self, path) self.icon.image = path end } --}}} --{{{ Spawn functions function volume:_cmd(cmd) notif("") spawn.easy_async(cmd, function(stdout, stderr, exitreason, exitcode) update_graphic(volume.widget, stdout, stderr, exitreason, exitcode) end) end local function show() spawn.easy_async(GET_VOLUME_CMD, function(stdout, _, _, _) txt = parse_output(stdout) notif(txt, true) end ) end --}}} --{{{ Mouse event --[[ allows control volume level by: - clicking on the widget to mute/unmute - scrolling when cursor is over the widget ]] volume.widget:connect_signal("button::press", function(_,_,_,button) if (button == 4) then volume.raise() elseif (button == 5) then volume.lower() elseif (button == 1) then volume.toggle() end end) if volume.display_notification then volume.widget:connect_signal("mouse::enter", function() show() end) volume.widget:connect_signal("mouse::leave", function() naughty.destroy(volume.notification) end) end --}}} --{{{ Set initial icon spawn.easy_async(GET_VOLUME_CMD, function(stdout, stderr, exitreason, exitcode) parse_output(stdout) volume.widget.image = PATH_TO_ICONS .. volume_icon_name .. ".svg" end) --}}} return volume.widget end return setmetatable(volume, { __call = function(_, ...) return worker(...) end })
fix volume widget initial icon
fix volume widget initial icon
Lua
mit
streetturtle/awesome-wm-widgets,streetturtle/awesome-wm-widgets
bf8d48f3be5cc4b53b98564603dab4f48d495c89
embark_site.lua
embark_site.lua
--[[ embark_site (by Lethosor) Allows embarking in disabled locations (e.g. too small or on an existing site) Note that this script is not yet complete (although it's mostly functional). Notably, there is currently no GUI integration - you can either run it from the console or add keybindings. Some example keybindings: keybinding add Alt-N@choose_start_site "embark_site nano" keybinding add Alt-E@choose_start_site "embark_site here" ]] usage = [[Usage: embark_site nano enable embark_site nano disable embark_site anywhere enable embark_site anywhere disable ]] local gui = require 'gui' local widgets = require 'gui.widgets' local eventful = require 'plugins.eventful' prev_state = '' if enabled == nil then enabled = { anywhere = false, nano = false, } end function tableIndex(tbl, value) for k, v in pairs(tbl) do if tbl[k] == value then return k end end return nil end function set_embark_size(width, height) width, height = tonumber(width), tonumber(height) if width == nil or height == nil then dfhack.printerr('Embark size requires width and height') return false end scr.embark_pos_max.x = math.min(15, scr.embark_pos_min.x + width - 1) scr.embark_pos_max.y = math.min(15, scr.embark_pos_min.y + height - 1) scr.embark_pos_min.x = math.max(0, scr.embark_pos_max.x - width + 1) scr.embark_pos_min.y = math.max(0, scr.embark_pos_max.y - height + 1) end function get_embark_pos() return {scr.embark_pos_min.x + 1, scr.embark_pos_min.y + 1, scr.embark_pos_max.x + 1, scr.embark_pos_max.y + 1} end embark_settings = gui.FramedScreen{ frame_style = gui.GREY_LINE_FRAME, frame_title = 'Embark settings', frame_width = 32, frame_height = 8, frame_inset = 1, } function embark_settings:onRenderBody(body) body:string('a', COLOR_LIGHTGREEN) body:string(': Embark anywhere ', COLOR_WHITE) if enabled.anywhere then body:string('(enabled)', COLOR_WHITE) else body:string('(disabled)', COLOR_WHITE) end body:newline() body:string('n', COLOR_LIGHTGREEN) body:string(': Nano embark ', COLOR_WHITE) if enabled.nano then body:string('(enabled)', COLOR_WHITE) else body:string('(disabled)', COLOR_WHITE) end body:seek(0, 7) body:string('Esc', COLOR_LIGHTGREEN) body:string(': Done', COLOR_WHITE) end function embark_settings:onInput(keys) if keys.CUSTOM_A then enabled.anywhere = not enabled.anywhere end if keys.CUSTOM_N then enabled.nano = not enabled.nano end if keys.LEAVESCREEN then self:dismiss() end end embark_overlay = defclass(embark_overlay, gui.Screen) function embark_overlay:init() self.embark_label = widgets.Label{text="-", frame={b=1, l=20}, text_pen={fg=COLOR_WHITE}} self.enabled_label = widgets.Label{text="-", frame={b=4, l=1}, text_pen={fg=COLOR_LIGHTMAGENTA}} self:addviews{ widgets.Panel{ subviews = { self.embark_label, self.enabled_label, widgets.Label{text="Esc", frame={b=5, l=52}, text_pen={fg=COLOR_LIGHTRED}}, widgets.Label{text=": Disable", frame={b=5, l=52+3}, text_pen={fg=COLOR_WHITE}}, widgets.Label{text="Alt+e", frame={b=4, l=52}, text_pen={fg=COLOR_LIGHTRED}}, widgets.Label{text=": Options", frame={b=4, l=52+5}, text_pen={fg=COLOR_WHITE}}, } } } end function embark_overlay:onRender() self._native.parent:render() if enabled.anywhere then self.embark_label:setText(': Embark!') else self.embark_label:setText('') end enabled_text = 'Enabled: ' if enabled.anywhere then enabled_text = enabled_text .. 'Embark anywhere' end if enabled.nano then if enabled.anywhere then enabled_text = enabled_text .. ', ' end enabled_text = enabled_text .. 'Nano embark' end if enabled_text == 'Enabled: ' then enabled_text = '' end self.enabled_label:setText(enabled_text) self:render() end function embark_overlay:onInput(keys) local interceptKeys = {"CUSTOM_ALT_E"} if enabled.anywhere then table.insert(interceptKeys, "SETUP_EMBARK") end if keys.LEAVESCREEN then prev_state = 'embark_overlay' self:dismiss() self:sendInputToParent('LEAVESCREEN') return end for name, _ in pairs(keys) do if tableIndex(interceptKeys, name) ~= nil then print("Intercepting " .. name) handle_key(name) else self:sendInputToParent(name) end end end function onStateChange(...) if dfhack.gui.getCurFocus() ~= 'choose_start_site' or prev_state == 'embark_overlay' then prev_state = '' return end prev_state = '' print('embark_site: Creating overlay') overlay = embark_overlay() overlay:show() end dfhack.onStateChange.embark_site = onStateChange function handle_key(key) scr = dfhack.gui.getCurViewscreen().parent if key == "SETUP_EMBARK" then --overlay:dismiss() scr.in_embark_normal = true elseif key == "CUSTOM_ALT_E" then embark_settings:show() end end function main(...) args = {...} if #args == 2 then feature = args[1] state = args[2] if enabled[feature] ~= nil then if state == 'enable' then enabled[feature] = true elseif state == 'disable' then enabled[feature] = false else print('Usage: embark_site ' .. feature .. ' (enable/disable)') end else print('Invalid: ' .. args[1]) end elseif #args == 0 then for feature, state in pairs(enabled) do print(feature .. ':' .. string.rep(' ', 10 - #feature) .. (state and 'enabled' or 'disabled')) end elseif args[1] == 'init' then -- pass else print(usage) end end main(...)
--[[ embark_site (by Lethosor) Allows embarking in disabled locations (e.g. too small or on an existing site) Note that this script is not yet complete (although it's mostly functional). Notably, there is currently no GUI integration - you can either run it from the console or add keybindings. Some example keybindings: keybinding add Alt-N@choose_start_site "embark_site nano" keybinding add Alt-E@choose_start_site "embark_site here" ]] usage = [[Usage: embark_site nano enable embark_site nano disable embark_site anywhere enable embark_site anywhere disable ]] local gui = require 'gui' local widgets = require 'gui.widgets' local eventful = require 'plugins.eventful' prev_state = '' if enabled == nil then enabled = { anywhere = false, nano = false, } end function tableIndex(tbl, value) for k, v in pairs(tbl) do if tbl[k] == value then return k end end return nil end function set_embark_size(width, height) width, height = tonumber(width), tonumber(height) if width == nil or height == nil then dfhack.printerr('Embark size requires width and height') return false end scr.embark_pos_max.x = math.min(15, scr.embark_pos_min.x + width - 1) scr.embark_pos_max.y = math.min(15, scr.embark_pos_min.y + height - 1) scr.embark_pos_min.x = math.max(0, scr.embark_pos_max.x - width + 1) scr.embark_pos_min.y = math.max(0, scr.embark_pos_max.y - height + 1) end function get_embark_pos() return {scr.embark_pos_min.x + 1, scr.embark_pos_min.y + 1, scr.embark_pos_max.x + 1, scr.embark_pos_max.y + 1} end embark_settings = gui.FramedScreen{ frame_style = gui.GREY_LINE_FRAME, frame_title = 'Embark settings', frame_width = 32, frame_height = 8, frame_inset = 1, } function embark_settings:onRenderBody(body) body:string('a', COLOR_LIGHTGREEN) body:string(': Embark anywhere ', COLOR_WHITE) if enabled.anywhere then body:string('(enabled)', COLOR_WHITE) else body:string('(disabled)', COLOR_WHITE) end body:newline() body:string('n', COLOR_LIGHTGREEN) body:string(': Nano embark ', COLOR_WHITE) if enabled.nano then body:string('(enabled)', COLOR_WHITE) else body:string('(disabled)', COLOR_WHITE) end body:seek(0, 7) body:string('Esc', COLOR_LIGHTGREEN) body:string(': Done', COLOR_WHITE) end function embark_settings:onInput(keys) if keys.STRING_A225 or keys.CUSTOM_A then enabled.anywhere = not enabled.anywhere end if keys.STRING_A223 or keys.CUSTOM_N then enabled.nano = not enabled.nano end if keys.LEAVESCREEN then self:dismiss() end end embark_overlay = defclass(embark_overlay, gui.Screen) function embark_overlay:init() self.embark_label = widgets.Label{text="-", frame={b=1, l=20}, text_pen={fg=COLOR_WHITE}} self.enabled_label = widgets.Label{text="-", frame={b=4, l=1}, text_pen={fg=COLOR_LIGHTMAGENTA}} self:addviews{ widgets.Panel{ subviews = { self.embark_label, self.enabled_label, widgets.Label{text="Esc", frame={b=5, l=52}, text_pen={fg=COLOR_LIGHTRED}}, widgets.Label{text=": Disable", frame={b=5, l=52+3}, text_pen={fg=COLOR_WHITE}}, widgets.Label{text="Alt+e", frame={b=4, l=52}, text_pen={fg=COLOR_LIGHTRED}}, widgets.Label{text=": Options", frame={b=4, l=52+5}, text_pen={fg=COLOR_WHITE}}, } } } end function embark_overlay:onRender() self._native.parent:render() if enabled.anywhere then self.embark_label:setText(': Embark!') else self.embark_label:setText('') end enabled_text = 'Enabled: ' if enabled.anywhere then enabled_text = enabled_text .. 'Embark anywhere' end if enabled.nano then if enabled.anywhere then enabled_text = enabled_text .. ', ' end enabled_text = enabled_text .. 'Nano embark' end if enabled_text == 'Enabled: ' then enabled_text = '' end self.enabled_label:setText(enabled_text) self:render() end function embark_overlay:onInput(keys) local interceptKeys = {"CUSTOM_ALT_E"} if enabled.anywhere then table.insert(interceptKeys, "SETUP_EMBARK") end if keys.LEAVESCREEN then prev_state = 'embark_overlay' self:dismiss() self:sendInputToParent('LEAVESCREEN') return end for name, _ in pairs(keys) do if tableIndex(interceptKeys, name) ~= nil then print("Intercepting " .. name) handle_key(name) else self:sendInputToParent(name) end end end function onStateChange(...) if dfhack.gui.getCurFocus() ~= 'choose_start_site' or prev_state == 'embark_overlay' then prev_state = '' return end prev_state = '' print('embark_site: Creating overlay') overlay = embark_overlay() overlay:show() end dfhack.onStateChange.embark_site = onStateChange function handle_key(key) scr = dfhack.gui.getCurViewscreen().parent if key == "SETUP_EMBARK" then scr.in_embark_normal = true elseif key == "CUSTOM_ALT_E" then embark_settings:show() end end function main(...) args = {...} if #args == 2 then feature = args[1] state = args[2] if enabled[feature] ~= nil then if state == 'enable' then enabled[feature] = true elseif state == 'disable' then enabled[feature] = false else print('Usage: embark_site ' .. feature .. ' (enable/disable)') end else print('Invalid: ' .. args[1]) end elseif #args == 0 then for feature, state in pairs(enabled) do print(feature .. ':' .. string.rep(' ', 10 - #feature) .. (state and 'enabled' or 'disabled')) end elseif args[1] == 'init' then -- pass else print(usage) end end main(...)
Fix "a" bug
Fix "a" bug
Lua
unlicense
PeridexisErrant/lethosor-scripts,lethosor/dfhack-scripts,DFHack/lethosor-scripts
186828f356628b7ed70c22c60c05e54778520d8d
src/program/snabbddos/snabbddos.lua
src/program/snabbddos/snabbddos.lua
module(..., package.seeall) local S = require("syscall") local engine = require("core.app") local config = require("core.config") local timer = require("core.timer") local pci = require("lib.hardware.pci") local intel10g = require("apps.intel.intel10g") local intel_app = require("apps.intel.intel_app") local ipv4 = require("lib.protocol.ipv4") local lib = require("core.lib") local main = require("core.main") local Tap = require("apps.tap.tap").Tap local ddos = require("apps.ddos.ddos") local vlan = require("apps.vlan.vlan") local usage = require("program.snabbddos.README_inc") local long_opts = { help = "h", mconfig = "m", clean = "C", dirty = "D", vlan = "V" } local function fatal(msg) print('error: '..msg) main.exit(1) end local function file_exists(path) local stat = S.stat(path) return stat and stat.isreg end local function dir_exists(path) local stat = S.stat(path) return stat and stat.isdir end local function nic_exists(pci_addr) local devices="/sys/bus/pci/devices" return dir_exists(("%s/%s"):format(devices, pci_addr)) or dir_exists(("%s/0000:%s"):format(devices, pci_addr)) end function parse_args(args) -- argument parsing local opt = { report = false, vlan = false } local handlers = {} -- help function handlers.h (arg) print(usage) main.exit(1) end -- mitigation config function handlers.m (arg) opt.mconfig_file_path = arg end -- report function handlers.r (arg) opt.report = true end -- interface clean function handlers.C (arg) opt.intf_clean = arg end -- interface dirty function handlers.D (arg) opt.intf_dirty = arg end function handlers.V (arg) opt.vlan_tag = arg end args = lib.dogetopt(args, handlers, "hm:rD:C:V:", long_opts) if not opt.intf_clean then fatal("Missing argument -C") end if not opt.intf_dirty then fatal("Missing argument -D") end if not opt.mconfig_file_path then fatal("Missing argument -m") end return opt end function run (args) local opt = parse_args(args) local c = config.new() -- setup interfaces if nic_exists(opt.intf_dirty) then else print("dirty interface '" .. opt.intf_dirty .. "' is not an existing PCI device, assuming tap interface") config.app(c, "dirty", Tap, opt.intf_dirty) end if nic_exists(opt.intf_dirty) then else print("dirty interface '" .. opt.intf_dirty .. "' is not an existing PCI device, assuming tap interface") config.app(c, "clean", Tap, opt.intf_clean) end -- report every second if opt.report then timer.activate(timer.new( "report", function() engine.app_table.ddos:report() end, 1e9, 'repeating' )) end -- TODO: we need the reverse path set up as well so we can reply to ARP -- packets but first we need the ARP app config.app(c, "ddos", ddos.DDoS, { config_file_path = opt.mconfig_file_path }) config.link(c, "dirty.output -> ddos.input") -- if vlan_tag is set we tag all egress/clean packets with a VLAN tag if opt.vlan_tag then print("Using VLAN tag: " .. opt.vlan_tag) config.app(c, "vlan_tagger", vlan.Tagger, { tag = opt.vlan_tag }) config.link(c, "ddos.output -> vlan_tagger.input") config.link(c, "vlan_tagger.output -> clean.input") else config.link(c, "ddos.output -> clean.input") end engine.configure(c) engine.main() end
module(..., package.seeall) local Intel82599 = require("apps.intel.intel_app").Intel82599 local S = require("syscall") local engine = require("core.app") local config = require("core.config") local timer = require("core.timer") local pci = require("lib.hardware.pci") local ipv4 = require("lib.protocol.ipv4") local lib = require("core.lib") local main = require("core.main") local Tap = require("apps.tap.tap").Tap local ddos = require("apps.ddos.ddos") local vlan = require("apps.vlan.vlan") local usage = require("program.snabbddos.README_inc") local long_opts = { help = "h", mconfig = "m", clean = "C", dirty = "D", vlan = "V" } local function fatal(msg) print('error: '..msg) main.exit(1) end local function file_exists(path) local stat = S.stat(path) return stat and stat.isreg end local function dir_exists(path) local stat = S.stat(path) return stat and stat.isdir end local function nic_exists(pci_addr) local devices="/sys/bus/pci/devices" return dir_exists(("%s/%s"):format(devices, pci_addr)) or dir_exists(("%s/0000:%s"):format(devices, pci_addr)) end function parse_args(args) -- argument parsing local opt = { report = false, vlan_tag = false } local handlers = {} -- help function handlers.h (arg) print(usage) main.exit(1) end -- mitigation config function handlers.m (arg) opt.mconfig_file_path = arg end -- report function handlers.r (arg) opt.report = true end -- interface clean function handlers.C (arg) opt.intf_clean = arg end -- interface dirty function handlers.D (arg) opt.intf_dirty = arg end function handlers.V (arg) opt.vlan_tag = arg end args = lib.dogetopt(args, handlers, "hm:rD:C:V:", long_opts) if not opt.intf_dirty then fatal("Missing argument -D") end if not opt.intf_clean then print("Clean interface not specified, assuming SnabbDDoS-on-a-stick") opt.intf_clean = opt.intf_dirty end if not opt.mconfig_file_path then fatal("Missing argument -m") end return opt end function run (args) local opt = parse_args(args) local c = config.new() -- TODO: we need the reverse path set up as well so we can reply to ARP -- packets but first we need the ARP app if opt.intf_clean == opt.intf_dirty then -- same physical interface used for dirty and clean traffic which means we -- use VLAN tag to put clean traffic on a separate logical interface and -- send out on the physical "dirty" interface. We only tag clean traffic -- since there is a performance penalty incurred by tagging and -- statistically we will have less packets on the clean side print("Using same physical interface for dirty and clean traffic") -- if dirty and clean interface is the same, require vlan tagging if not opt.vlan_tag then fatal("VLAN id must be set to use same interface for dirty and clean traffic") end -- setup physical interface, 10G or tap if nic_exists(opt.intf_dirty) then config.app(c, "dirty", Intel82599, { pciaddr=opt.intf_dirty, }) -- input and output interface names iif_name = "rx" oif_name = "tx" -- link apps, note "tx"/"rx" on intel 10G interface config.link(c, "dirty.tx -> ddos.input") config.link(c, "vlan_tagger.output -> dirty.rx") else print("dirty interface '" .. opt.intf_dirty .. "' is not an existing PCI device, assuming tap interface") config.app(c, "dirty", Tap, opt.intf_dirty) -- input and output interface names iif_name = "input" oif_name = "output" end config.app(c, "ddos", ddos.DDoS, { config_file_path = opt.mconfig_file_path }) -- clean interface is a logical vlan tagger that then goes out physical -- dirty interface config.app(c, "vlan_tagger", vlan.Tagger, { tag = opt.vlan_tag }) -- link apps config.link(c, "dirty."..oif_name.." -> ddos.input") config.link(c, "ddos.output -> vlan_tagger.input") config.link(c, "vlan_tagger.output -> dirty."..iif_name) else -- different physical interfaces for dirty and clean traffic config.app(c, "ddos", ddos.DDoS, { config_file_path = opt.mconfig_file_path }) -- setup physical dirty interface, 10G or tap if nic_exists(opt.intf_dirty) then -- 10G config.app(c, "dirty", Intel82599, { pciaddr=opt.intf_dirty, }) -- link dirty -> ddos config.link(c, "dirty.tx -> ddos.input") else -- tap print("dirty interface '" .. opt.intf_dirty .. "' is not an existing PCI device, assuming tap interface") config.app(c, "dirty", Tap, opt.intf_dirty) -- link dirty -> ddos config.link(c, "dirty.output -> ddos.input") end -- setup physical clean interface, 10G or tap if nic_exists(opt.intf_clean) then -- 10G config.app(c, "clean", Intel82599, { pciaddr=opt.intf_clean }) -- VLAN tagging on egress? if opt.vlan_tag then config.app(c, "vlan_tagger", vlan.Tagger, { tag = opt.vlan_tag }) -- link ddos -> vlan -> clean config.link(c, "ddos.output -> vlan_tagger.input") config.link(c, "vlan_tagger.output -> clean.rx") else -- link ddos -> clean config.link(c, "ddos.output -> clean.rx") end else -- tap print("clean interface '" .. opt.intf_clean .. "' is not an existing PCI device, assuming tap interface") config.app(c, "clean", Tap, opt.intf_clean) -- VLAN tagging on egress? if opt.vlan_tag then config.app(c, "vlan_tagger", vlan.Tagger, { tag = opt.vlan_tag }) -- link ddos -> vlan -> clean config.link(c, "ddos.output -> vlan_tagger.input") config.link(c, "vlan_tagger.output -> clean.input") else -- link ddos -> clean config.link(c, "ddos.output -> clean.input") end end end -- report every second if opt.report then timer.activate(timer.new( "report", function() engine.app_table.ddos:report() end, 1e9, 'repeating' )) end engine.configure(c) engine.main() end
Fix 10G NIC + config of snabbddos program
Fix 10G NIC + config of snabbddos program I've refactored the config of the snabbddos program. It's quite a bit lengthier but I think it's reasonably easy to read compared to a more compact version. With this change now also have support for 10G intel NICs. Fixes #8.
Lua
apache-2.0
plajjan/snabbswitch,plajjan/snabbswitch,plajjan/snabbswitch,plajjan/snabbswitch
1af5293d605b0fc8095c3c67ba16522fe958377a
test_scripts/Policies/Related_HMI_API/186_ATF_OnPolicyUpdate_initiation_of_PTU.lua
test_scripts/Policies/Related_HMI_API/186_ATF_OnPolicyUpdate_initiation_of_PTU.lua
--------------------------------------------------------------------------------------------- -- Requirement summary: -- [Policies]: SDL.OnPolicyUpdate initiation of PTU -- [HMI API] SDL.OnPolicyUpdate notification -- -- Description: -- 1. Used preconditions: SDL and HMI are running, Device connected to SDL is consented by the User, App is running on this device, and registerd on SDL -- 2. Performed steps: HMI->SDL: SDL.OnPolicyUpdate -- -- Expected result: -- SDL->HMI: BasicCommunication.PolicyUpdate --------------------------------------------------------------------------------------------- require('user_modules/script_runner').isTestApplicable({ { extendedPolicy = { "EXTERNAL_PROPRIETARY" } } }) --[[ General configuration parameters ]] config.defaultProtocolVersion = 2 --[[ Required Shared libraries ]] local commonSteps = require('user_modules/shared_testcases/commonSteps') local utils = require ('user_modules/utils') --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() --[[ General Settings for configuration ]] Test = require('user_modules/connecttest_resumption') require('cardinalities') local mobile_session = require('mobile_session') --[[ Preconditions ]] function Test:Precondtion_connectMobile() self:connectMobile() end function Test:Precondtion_CreateSession() self.mobileSession = mobile_session.MobileSession(self, self.mobileConnection) self.mobileSession:StartService(7) end function Test:Precondtion_Activate_App_Consent_Update() local CorIdRAI = self.mobileSession:SendRPC("RegisterAppInterface", { syncMsgVersion = { majorVersion = 3, minorVersion = 0 }, appName = "SPT", isMediaApplication = true, languageDesired = "EN-US", hmiDisplayLanguageDesired = "EN-US", appID = "1234567", deviceInfo = { os = "Android", carrier = "Megafon", firmwareRev = "Name: Linux, Version: 3.4.0-perf", osVersion = "4.4.2", maxNumberRFCOMMPorts = 1 } }) EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered", { application = { appName = "SPT", policyAppID = "1234567", isMediaApplication = true, hmiDisplayLanguageDesired = "EN-US", deviceInfo = { name = utils.getDeviceName(), id = utils.getDeviceMAC(), transportType = utils.getDeviceTransportType(), isSDLAllowed = false } } }) :Do(function(_,data) local RequestIdActivateApp = self.hmiConnection:SendRequest("SDL.ActivateApp", {appID = data.params.application.appID}) EXPECT_HMIRESPONSE(RequestIdActivateApp, {result = {code = 0, isSDLAllowed = false}, method = "SDL.ActivateApp"}) :Do(function(_,_) local RequestIdGetUserFriendlyMessage = self.hmiConnection:SendRequest("SDL.GetUserFriendlyMessage", {language = "EN-US", messageCodes = {"DataConsent"}}) EXPECT_HMIRESPONSE(RequestIdGetUserFriendlyMessage,{result = {code = 0, method = "SDL.GetUserFriendlyMessage"}}) :Do(function(_,_) self.hmiConnection:SendNotification("SDL.OnAllowSDLFunctionality", {allowed = true, source = "GUI", device = {id = utils.getDeviceMAC(), name = utils.getDeviceName()}}) EXPECT_HMICALL("BasicCommunication.ActivateApp") :Do(function(_,data1) self.hmiConnection:SendResponse(data1.id,"BasicCommunication.ActivateApp", "SUCCESS", {}) EXPECT_NOTIFICATION("OnHMIStatus", {hmiLevel = "FULL", systemContext = "MAIN"}) end) end) end) end) EXPECT_RESPONSE(CorIdRAI, { success = true, resultCode = "SUCCESS"}) EXPECT_HMICALL("BasicCommunication.PolicyUpdate") :Do(function(_,data) self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {}) local requestId = self.hmiConnection:SendRequest("SDL.GetPolicyConfigurationData", { policyType = "module_config", property = "endpoints" }) EXPECT_HMIRESPONSE(requestId) :Do(function() self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest",{requestType = "PROPRIETARY", fileName = "filename"}) EXPECT_NOTIFICATION("OnSystemRequest", { requestType = "PROPRIETARY" }) :Do(function() local CorIdSystemRequest = self.mobileSession:SendRPC("SystemRequest", {fileName = "PolicyTableUpdate", requestType = "PROPRIETARY"}, "files/ptu_general.json") self.mobileSession:ExpectResponse(CorIdSystemRequest, {success = true, resultCode = "SUCCESS"}) EXPECT_HMICALL("BasicCommunication.SystemRequest") :Do(function(_,data) self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {}) self.hmiConnection:SendNotification("SDL.OnReceivedPolicyUpdate", { policyfile = "/tmp/fs/mp/images/ivsu_cache/PolicyTableUpdate" }) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UP_TO_DATE"}):Timeout(500) end) end) end) end) end --[[ Test ]] function Test:TestStep_Send_OnPolicyUpdate_from_HMI() self.hmiConnection:SendNotification("SDL.OnPolicyUpdate") EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATE_NEEDED"}) EXPECT_HMICALL("BasicCommunication.PolicyUpdate", {file = "/tmp/fs/mp/images/ivsu_cache/sdl_snapshot.json"}) utils.wait(2000) end --[[ Postconditions ]] function Test.Postcondition_SDLStop() StopSDL() end return Test
--------------------------------------------------------------------------------------------- -- Requirement summary: -- [Policies]: SDL.OnPolicyUpdate initiation of PTU -- [HMI API] SDL.OnPolicyUpdate notification -- -- Description: -- 1. Used preconditions: SDL and HMI are running, Device connected to SDL is consented by the User, App is running on this device, and registerd on SDL -- 2. Performed steps: HMI->SDL: SDL.OnPolicyUpdate -- -- Expected result: -- SDL->HMI: BasicCommunication.PolicyUpdate --------------------------------------------------------------------------------------------- require('user_modules/script_runner').isTestApplicable({ { extendedPolicy = { "EXTERNAL_PROPRIETARY" } } }) --[[ General configuration parameters ]] config.defaultProtocolVersion = 2 --[[ Required Shared libraries ]] local commonSteps = require('user_modules/shared_testcases/commonSteps') local utils = require ('user_modules/utils') --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() --[[ General Settings for configuration ]] Test = require('user_modules/connecttest_resumption') require('cardinalities') local mobile_session = require('mobile_session') --[[ Preconditions ]] function Test:Precondtion_connectMobile() self:connectMobile() end function Test:Precondtion_CreateSession() self.mobileSession = mobile_session.MobileSession(self, self.mobileConnection) self.mobileSession:StartService(7) end function Test:Precondtion_Activate_App_Consent_Update() local CorIdRAI = self.mobileSession:SendRPC("RegisterAppInterface", { syncMsgVersion = { majorVersion = 3, minorVersion = 0 }, appName = "SPT", isMediaApplication = true, languageDesired = "EN-US", hmiDisplayLanguageDesired = "EN-US", appID = "1234567", deviceInfo = { os = "Android", carrier = "Megafon", firmwareRev = "Name: Linux, Version: 3.4.0-perf", osVersion = "4.4.2", maxNumberRFCOMMPorts = 1 } }) EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered", { application = { appName = "SPT", policyAppID = "1234567", isMediaApplication = true, hmiDisplayLanguageDesired = "EN-US", deviceInfo = { name = utils.getDeviceName(), id = utils.getDeviceMAC(), transportType = utils.getDeviceTransportType(), isSDLAllowed = false } } }) :Do(function(_,data) EXPECT_NOTIFICATION("OnHMIStatus", {hmiLevel = "NONE", systemContext = "MAIN"}, {hmiLevel = "FULL", systemContext = "MAIN"}):Times(2) local RequestIdActivateApp = self.hmiConnection:SendRequest("SDL.ActivateApp", {appID = data.params.application.appID}) EXPECT_HMIRESPONSE(RequestIdActivateApp, {result = {code = 0, isSDLAllowed = false}, method = "SDL.ActivateApp"}) :Do(function(_,_) local RequestIdGetUserFriendlyMessage = self.hmiConnection:SendRequest("SDL.GetUserFriendlyMessage", {language = "EN-US", messageCodes = {"DataConsent"}}) EXPECT_HMIRESPONSE(RequestIdGetUserFriendlyMessage,{result = {code = 0, method = "SDL.GetUserFriendlyMessage"}}) :Do(function(_,_) self.hmiConnection:SendNotification("SDL.OnAllowSDLFunctionality", {allowed = true, source = "GUI", device = {id = utils.getDeviceMAC(), name = utils.getDeviceName()}}) EXPECT_HMICALL("BasicCommunication.ActivateApp") :Do(function(_,data1) self.hmiConnection:SendResponse(data1.id,"BasicCommunication.ActivateApp", "SUCCESS", {}) end) end) end) end) EXPECT_RESPONSE(CorIdRAI, { success = true, resultCode = "SUCCESS"}) EXPECT_HMICALL("BasicCommunication.PolicyUpdate") :Do(function(_,data) self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {}) local requestId = self.hmiConnection:SendRequest("SDL.GetPolicyConfigurationData", { policyType = "module_config", property = "endpoints" }) EXPECT_HMIRESPONSE(requestId) :Do(function() self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest",{requestType = "PROPRIETARY", fileName = "filename"}) EXPECT_NOTIFICATION("OnSystemRequest", { requestType = "PROPRIETARY" }) :Do(function() local CorIdSystemRequest = self.mobileSession:SendRPC("SystemRequest", {fileName = "PolicyTableUpdate", requestType = "PROPRIETARY"}, "files/ptu_general.json") self.mobileSession:ExpectResponse(CorIdSystemRequest, {success = true, resultCode = "SUCCESS"}) EXPECT_HMICALL("BasicCommunication.SystemRequest") :Do(function(_,data) self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {}) self.hmiConnection:SendNotification("SDL.OnReceivedPolicyUpdate", { policyfile = "/tmp/fs/mp/images/ivsu_cache/PolicyTableUpdate" }) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UP_TO_DATE"}):Timeout(1000) end) end) end) end) end --[[ Test ]] function Test:TestStep_Send_OnPolicyUpdate_from_HMI() self.hmiConnection:SendNotification("SDL.OnPolicyUpdate") EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATE_NEEDED"}) EXPECT_HMICALL("BasicCommunication.PolicyUpdate", {file = "/tmp/fs/mp/images/ivsu_cache/sdl_snapshot.json"}) utils.wait(2000) end --[[ Postconditions ]] function Test.Postcondition_SDLStop() StopSDL() end return Test
Fix script issue in 186_atf_onPolicyUpdate (#2645)
Fix script issue in 186_atf_onPolicyUpdate (#2645) * increase wait timout for onStatusUpdate * add OnHMIStatus(NONE) expectation
Lua
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
f32d247f8a9ed505d4c38bd6bc25fb7006b33f53
plugins/mod_register.lua
plugins/mod_register.lua
local st = require "util.stanza"; local send = require "core.sessionmanager".send_to_session; local usermanager_user_exists = require "core.usermanager".user_exists; local usermanager_create_user = require "core.usermanager".create_user; add_iq_handler("c2s", "jabber:iq:register", function (session, stanza) if stanza.tags[1].name == "query" then local query = stanza.tags[1]; if stanza.attr.type == "get" then local reply = st.reply(stanza); reply:tag("query", {xmlns = "jabber:iq:register"}) :tag("registered"):up() :tag("username"):text(session.username):up() :tag("password"):up(); send(session, reply); elseif stanza.attr.type == "set" then if query.tags[1] and query.tags[1].name == "remove" then -- TODO delete user auth data, send iq response, kick all user resources with a <not-authorized/>, delete all user data send(session, st.error_reply(stanza, "cancel", "not-allowed")); else local username = query:child_with_name("username"); local password = query:child_with_name("password"); if username and password then -- FIXME shouldn't use table.concat username = table.concat(username); password = table.concat(password); if username == session.username then if usermanager_create_user(username, password, session.host) then -- password change -- TODO is this the right way? send(session, st.reply(stanza)); else -- TODO unable to write file, file may be locked, etc, what's the correct error? send(session, st.error_reply(stanza, "wait", "internal-server-error")); end else send(session, st.error_reply(stanza, "modify", "bad-request")); end else send(session, st.error_reply(stanza, "modify", "bad-request")); end end end else send(session, st.error_reply(stanza, "cancel", "service-unavailable")); end; end); add_iq_handler("c2s_unauthed", "jabber:iq:register", function (session, stanza) if stanza.tags[1].name == "query" then local query = stanza.tags[1]; if stanza.attr.type == "get" then local reply = st.reply(stanza); reply:tag("query", {xmlns = "jabber:iq:register"}) :tag("instructions"):text("Choose a username and password for use with this service."):up() :tag("username"):up() :tag("password"):up(); send(session, reply); elseif stanza.attr.type == "set" then if query.tags[1] and query.tags[1].name == "remove" then send(session, st.error_reply(stanza, "auth", "registration-required")); else local username = query:child_with_name("username"); local password = query:child_with_name("password"); if username and password then -- FIXME shouldn't use table.concat username = table.concat(username); password = table.concat(password); if usermanager_user_exists(username, session.host) then send(session, st.error_reply(stanza, "cancel", "conflict")); else if usermanager_create_user(username, password, session.host) then send(session, st.reply(stanza)); -- user created! else -- TODO unable to write file, file may be locked, etc, what's the correct error? send(session, st.error_reply(stanza, "wait", "internal-server-error")); end end else send(session, st.error_reply(stanza, "modify", "not-acceptable")); end end end else send(session, st.error_reply(stanza, "cancel", "service-unavailable")); end; end);
local st = require "util.stanza"; local usermanager_user_exists = require "core.usermanager".user_exists; local usermanager_create_user = require "core.usermanager".create_user; add_iq_handler("c2s", "jabber:iq:register", function (session, stanza) if stanza.tags[1].name == "query" then local query = stanza.tags[1]; if stanza.attr.type == "get" then local reply = st.reply(stanza); reply:tag("query", {xmlns = "jabber:iq:register"}) :tag("registered"):up() :tag("username"):text(session.username):up() :tag("password"):up(); session.send(reply); elseif stanza.attr.type == "set" then if query.tags[1] and query.tags[1].name == "remove" then -- TODO delete user auth data, send iq response, kick all user resources with a <not-authorized/>, delete all user data session.send(st.error_reply(stanza, "cancel", "not-allowed")); else local username = query:child_with_name("username"); local password = query:child_with_name("password"); if username and password then -- FIXME shouldn't use table.concat username = table.concat(username); password = table.concat(password); if username == session.username then if usermanager_create_user(username, password, session.host) then -- password change -- TODO is this the right way? session.send(st.reply(stanza)); else -- TODO unable to write file, file may be locked, etc, what's the correct error? session.send(st.error_reply(stanza, "wait", "internal-server-error")); end else session.send(st.error_reply(stanza, "modify", "bad-request")); end else session.send(st.error_reply(stanza, "modify", "bad-request")); end end end else session.send(st.error_reply(stanza, "cancel", "service-unavailable")); end; end); add_iq_handler("c2s_unauthed", "jabber:iq:register", function (session, stanza) if stanza.tags[1].name == "query" then local query = stanza.tags[1]; if stanza.attr.type == "get" then local reply = st.reply(stanza); reply:tag("query", {xmlns = "jabber:iq:register"}) :tag("instructions"):text("Choose a username and password for use with this service."):up() :tag("username"):up() :tag("password"):up(); session.send(reply); elseif stanza.attr.type == "set" then if query.tags[1] and query.tags[1].name == "remove" then session.send(st.error_reply(stanza, "auth", "registration-required")); else local username = query:child_with_name("username"); local password = query:child_with_name("password"); if username and password then -- FIXME shouldn't use table.concat username = table.concat(username); password = table.concat(password); if usermanager_user_exists(username, session.host) then session.send(st.error_reply(stanza, "cancel", "conflict")); else if usermanager_create_user(username, password, session.host) then session.send(st.reply(stanza)); -- user created! else -- TODO unable to write file, file may be locked, etc, what's the correct error? session.send(st.error_reply(stanza, "wait", "internal-server-error")); end end else session.send(st.error_reply(stanza, "modify", "not-acceptable")); end end end else session.send(st.error_reply(stanza, "cancel", "service-unavailable")); end; end);
Fixed mod_register to use session.send for sending stanzas
Fixed mod_register to use session.send for sending stanzas
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
f1af81e9dc54a4ae5312077fd26ae5110676efdd
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 decoder then node, realm, password = decoder(node), decoder(realm), decoder(password); end return func, md5(node..":"..realm..":"..password); 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 = 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);
mod_saslauth: Fix traceback on attempted login for non-existent users
mod_saslauth: Fix traceback on attempted login for non-existent users
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
add8832ef17a11dbcbde8869883dea52e89e1a52
BtUtils/Vector3.lua
BtUtils/Vector3.lua
-- A 3D Vector Library. -- By Gordon MacPherson with the assistance of google and sir divran! :L -- changes by: Michal Mojzk -- - adapted to be compatible BtUtils by -- - fixed methods to belong into the __index lookup table rather than the metatable itself -- - added LengthSqr -- - changed Normalize to alter the current instance -- - added return self to the various arithemtic operations -- - disabled querying of the metatable from the outside local type = type local sin = math.sin local cos = math.cos local atan2 = math.atan2 local deg = math.deg local rad = math.rad -- Meta table. local vector_prototype = {} local vector_mt = { __index = vector_prototype } vector_mt.__metatable = false -- disable accessing of the metatable -- Divran's idea. local function new(x,y,z) return setmetatable( {x = x or 0, y = y or 0, z = z or 0} , vector_mt) end local Vector3 = new function vector_mt:__add( vector ) return new( self.x + vector.x, self.y + vector.y, self.z + vector.z ) end function vector_mt:__sub( vector ) return new( self.x - vector.x, self.y - vector.y, self.z - vector.z ) end function vector_mt:__mul( vector ) if type(vector) == "number" then return new( self.x * vector, self.y * vector, self.z * vector ) else return new( self.x * vector.x, self.y * vector.y, self.z * vector.z ) end end function vector_mt:__div( vector ) if type(vector) == "number" then return new( self.x / vector, self.y / vector, self.z / vector ) else return new( self.x / vector.x, self.y / vector.y, self.z / vector.z ) end end -- -- Boolean operators -- function vector_mt:__eq( vector ) return self.x == vector.x and self.y == vector.y and self.z == vector.z end function vector_mt:__unm() return new(-self.x,-self.y,-self.z) end -- -- String Operators. -- function vector_mt:__tostring() return "[" .. self.x .. "," .. self.y .. "," .. self.z .. "]" end -- -- Vector operator functions. -- -- TODO: this doesn't change the current instance (self is a private variable), fix function vector_prototype:Add( vector ) self = self + vector return self end -- TODO: this doesn't change the current instance (self is a private variable), fix function vector_prototype:Sub( vector ) self = self - vector return self end function vector_prototype:Mul( n ) self.x = self.x * n self.y = self.y * n self.z = self.z * n return self end function vector_prototype:Zero() self.x = 0 self.y = 0 self.z = 0 return self end function vector_prototype:LengthSqr() return ( ( self.x * self.x ) + ( self.y * self.y ) + ( self.z * self.z ) ) end function vector_prototype:Length() return self:LengthSqr() ^ 0.5 end -- This should really be named get normalised copy. function vector_prototype:GetNormal() local length = self:Length() return new( self.x / length, self.y / length, self.z / length ) end -- Redirect for people doing it wrong. function vector_prototype:GetNormalized() return self:GetNormal() end function vector_prototype:Normalize() local length = self:Length() return self:Mul(1 / length) end function vector_prototype:DotProduct( vector ) return (self.x * vector.x) + (self.y * vector.y) + (self.z * vector.z) end -- Redirect for people doing it wrong. function vector_prototype:Dot( vector ) return self:DotProduct( vector ) end -- Cross Product. function vector_prototype:Cross( vector ) local vec = new(0,0,0) vec.x = ( self.y * vector.z ) - ( vector.y * self.z ) vec.y = ( self.z * vector.x ) - ( vector.z * self.x ) vec.z = ( self.x * vector.y ) - ( vector.x * self.y ) return vec end -- Returns the distance between two vectors. function vector_prototype:Distance( vector ) local vec = self - vector return vec:Length() end -- Convert vector in 2D heading in degrees between 0-360 function vector_prototype:ToHeading() local angleInRads = atan2(self.x, self.z) return (deg(angleInRads) % 360) end -- Rotate vector around Y axis by given angle in degrees -- mathematically correct variant = negative angle values implies clockwise rotation function vector_prototype:Rotate2D(angle) local angleInRads = rad(angle) local vec = new(0,0,0) vec.x = self.x * cos(angleInRads) - self.z * sin(angleInRads) vec.y = self.y vec.z = self.x * sin(angleInRads) + self.z * cos(angleInRads) return vec end function vector_prototype:AsSpringVector() return { self.x, self.y, self.z } end return Vector3
-- A 3D Vector Library. -- By Gordon MacPherson with the assistance of google and sir divran! :L -- changes by: Michal Mojzk -- - adapted to be compatible BtUtils by -- - fixed methods to belong into the __index lookup table rather than the metatable itself -- - added LengthSqr -- - changed Normalize to alter the current instance -- - added return self to the various arithemtic operations -- - disabled querying of the metatable from the outside local type = type local sin = math.sin local cos = math.cos local atan2 = math.atan2 local deg = math.deg local rad = math.rad -- Meta table. local vector_prototype = {} local vector_mt = { __index = vector_prototype } vector_mt.__metatable = false -- disable accessing of the metatable -- Divran's idea. local function new(x,y,z) return setmetatable( {x = x or 0, y = y or 0, z = z or 0} , vector_mt) end local Vector3 = new function vector_mt:__add( vector ) return new( self.x + vector.x, self.y + vector.y, self.z + vector.z ) end function vector_mt:__sub( vector ) return new( self.x - vector.x, self.y - vector.y, self.z - vector.z ) end function vector_mt:__mul( vector ) if type(vector) == "number" then return new( self.x * vector, self.y * vector, self.z * vector ) else return new( self.x * vector.x, self.y * vector.y, self.z * vector.z ) end end function vector_mt:__div( vector ) if type(vector) == "number" then return new( self.x / vector, self.y / vector, self.z / vector ) else return new( self.x / vector.x, self.y / vector.y, self.z / vector.z ) end end -- -- Boolean operators -- function vector_mt:__eq( vector ) return self.x == vector.x and self.y == vector.y and self.z == vector.z end function vector_mt:__unm() return new(-self.x,-self.y,-self.z) end -- -- String Operators. -- function vector_mt:__tostring() return "[" .. self.x .. "," .. self.y .. "," .. self.z .. "]" end -- -- Vector operator functions. -- -- TODO: this doesn't change the current instance (self is a private variable), fix function vector_prototype:Add( vector ) self = self + vector return self end -- TODO: this doesn't change the current instance (self is a private variable), fix function vector_prototype:Sub( vector ) self = self - vector return self end function vector_prototype:Mul( n ) self.x = self.x * n self.y = self.y * n self.z = self.z * n return self end function vector_prototype:Zero() self.x = 0 self.y = 0 self.z = 0 return self end function vector_prototype:LengthSqr() return ( ( self.x * self.x ) + ( self.y * self.y ) + ( self.z * self.z ) ) end function vector_prototype:Length() return self:LengthSqr() ^ 0.5 end -- This should really be named get normalised copy. function vector_prototype:GetNormal() local length = self:Length() return new( self.x / length, self.y / length, self.z / length ) end -- Redirect for people doing it wrong. function vector_prototype:GetNormalized() return self:GetNormal() end function vector_prototype:Normalize() local length = self:Length() return self:Mul(1 / length) end function vector_prototype:DotProduct( vector ) return (self.x * vector.x) + (self.y * vector.y) + (self.z * vector.z) end -- Redirect for people doing it wrong. function vector_prototype:Dot( vector ) return self:DotProduct( vector ) end -- Cross Product. function vector_prototype:Cross( vector ) local vec = new(0,0,0) vec.x = ( self.y * vector.z ) - ( vector.y * self.z ) vec.y = ( self.z * vector.x ) - ( vector.z * self.x ) vec.z = ( self.x * vector.y ) - ( vector.x * self.y ) return vec end -- Returns the distance between two vectors. function vector_prototype:Distance( vector ) local vec = self - vector return vec:Length() end -- Convert vector in 2D heading in degrees between 0-360 function vector_prototype:ToHeading() -- azimuth local angleInRads = atan2(self.x, self.z) -- angleInRads -- N (north) = PI -- E (east) = 0.5PI -- S (south) = 0 -- W (west) = 1.5PI return ((deg(-angleInRads) + 180) % 360) -- correction to azimuth values = so 0 degrees is on north and positive increment is clockwise -- returned angle -- N (north) = 0 -- E (east) = 90 -- S (south) = 180 -- W (west) = 270 end -- Rotate vector around Y axis by given angle in degrees -- mathematically correct variant = negative angle values implies clockwise rotation function vector_prototype:Rotate2D(angle) local angleInRads = rad(angle) local vec = new(0,0,0) vec.x = self.x * cos(angleInRads) - self.z * sin(angleInRads) vec.y = self.y vec.z = self.x * sin(angleInRads) + self.z * cos(angleInRads) return vec end function vector_prototype:AsSpringVector() return { self.x, self.y, self.z } end return Vector3
fixing Vec3:ToHeading() to return proper values accorning expected azimuth angles
fixing Vec3:ToHeading() to return proper values accorning expected azimuth angles
Lua
mit
MartinFrancu/BETS
0e46395ece87fe25f0432f13ce319098ee74c34a
lua/LUA/ak/demo-anlagen/tutorial-ampel/Andreas_Kreuz-Tutorial-Ampelkreuzung-2-main.lua
lua/LUA/ak/demo-anlagen/tutorial-ampel/Andreas_Kreuz-Tutorial-Ampelkreuzung-2-main.lua
clearlog() local TrafficLightModel = require("ak.road.TrafficLightModel") local TrafficLight = require("ak.road.TrafficLight") local Lane = require("ak.road.Lane") local Crossing = require("ak.road.Crossing") local CrossingSequence = require("ak.road.CrossingSequence") Crossing.debug = true ------------------------------------------------ -- Damit kommt wird die Variable "Zugname" automatisch durch EEP belegt -- http://emaps-eep.de/lua/code-schnipsel ------------------------------------------------ setmetatable(_ENV, { __index = function(_, k) local p = load(k) if p then local f = function(z) local s = Zugname Zugname = z p() Zugname = s end _ENV[k] = f return f end return nil end }) -------------------------------------------- -- Definiere Funktionen fuer Kontaktpunkte -------------------------------------------- function enterLane(lane) assert(lane, "lane darf nicht nil sein. Richtige Lua-Funktion im Kontaktpunkt?") lane:vehicleEntered(Zugname) end function leaveLane(lane) assert(lane, "lane darf nicht nil sein. Richtige Lua-Funktion im Kontaktpunkt?") lane:vehicleLeft(Zugname) end ------------------------------------------------------------------------------- -- Definiere die Fahrspuren fuer die Kreuzung ------------------------------------------------------------------------------- -- +---------------------------- Variablenname der Ampel -- | +----------------------- Legt eine neue Ampel an -- | | +------ Signal-ID dieser Ampel -- | | | +-- Modell dieser Ampel - weiss wo rot, gelb und gruen / Fussgaenger ist local K1 = TrafficLight:new("K1", 07, TrafficLightModel.JS2_3er_mit_FG) -- Ampel K1 ist gleichzeitig eine Fugngerampel local K2 = TrafficLight:new("K2", 08, TrafficLightModel.JS2_3er_mit_FG) local K3 = TrafficLight:new("K3", 09, TrafficLightModel.JS2_3er_mit_FG) local K4 = TrafficLight:new("K4", 10, TrafficLightModel.JS2_3er_mit_FG) local K5 = TrafficLight:new("K5", 12, TrafficLightModel.JS2_3er_mit_FG) local K6 = TrafficLight:new("K6", 13, TrafficLightModel.JS2_3er_ohne_FG) -- dies ist keine Fugngerampel local K7 = TrafficLight:new("K7", 11, TrafficLightModel.JS2_3er_mit_FG) -- Ampeln fr die Straenbahn nutzen die Lichtfunktion der einzelnen Immobilien local S1 = TrafficLight:new("S1", 14, TrafficLightModel.Unsichtbar_2er, "#29_Straba Signal Halt", -- rot "#28_Straba Signal geradeaus", -- gruen "#27_Straba Signal anhalten", -- gelb "#26_Straba Signal A") -- Anforderung local S2 = TrafficLight:new("S2", 15, TrafficLightModel.Unsichtbar_2er, "#32_Straba Signal Halt", -- rot "#30_Straba Signal geradeaus", -- gruen "#31_Straba Signal anhalten", -- gelb "#33_Straba Signal A") -- Anforderung local F1 = K1 -- Die Fussgngerampel F1 ist die selbe, wie Ampel K1, zeigt aber spter "Fugnger grn" local F2 = K2 local F3 = K3 local F4 = K4 local F5 = K5 local F6 = K7 -- +-----------------------------------------Neue Fahrspur -- | +------------------------------- Name der Fahrspur -- | | +------------------------- Speicher ID - um die Anzahl der Fahrzeuge -- | | | und die Wartezeit zu speichern -- | | | +------------------ neue Ampel fr diese Fahrspur -- | | | | +------ Signal-ID dieser Ampel -- | | | | | +-- Modell kann rot, gelb, gruen und FG schalten -- Die Fahrspur N wird durch die Fahrspur-Ampel K1 (Signal ID 07) gesteuert -- K2 muss spter gleichzeitig leuchten (Signal ID 08) n = Lane:new("N", 100, K1) -- Die Fahrspur O1 wird durch die Fahrspur-Ampel K2 (Signal 09) gesteuert -- K4 muss spter gleichzeitig leuchten (Signal ID 10) o1 = Lane:new("O1", 102, K3) -- Fahrspuren im Westen -- Die Fahrspur W1 wird durch die Fahrspur-Ampel K5 (Signal 12) gesteuert w1 = Lane:new("W1", 104, K5) -- Die Fahrspur W2 wird durch die Fahrspur-Ampel K6 (Signal 13) gesteuert -- K7 muss spter gleichzeitig leuchten (Signal ID 11) w2 = Lane:new("W2", 105, K6) -- Fahrspuren fuer Strassenbahnen: os = Lane:new("OS", 107, S1) os:useSignalForQueue() -- Erfasst Anforderungen, wenn ein Fahrzeug an Signal 14 steht ws = Lane:new("WS", 108, S2) ws:useTrackForQueue(2) -- Erfasst Anforderungen, wenn ein Fahrzeug auf Strasse 2 steht -------------------------------------------------------------- -- Definiere die Schaltungen und die Kreuzung -------------------------------------------------------------- -- Eine Schaltung bestimmt, welche Fahrspuren gleichzeitig auf -- grn geschaltet werden drfen, alle anderen sind rot --- Tutorial 2: Schaltung 1 local sch1 = CrossingSequence:new("Schaltung 1") sch1:addCarLights(K3) sch1:addCarLights(K4) sch1:addTramLights(S1) sch1:addCarLights(K5) sch1:addTramLights(S2) sch1:addPedestrianLights(F1, F2) --- Tutorial 2: Schaltung 2 local sch2 = CrossingSequence:new("Schaltung 2") sch2:addCarLights(K6) sch2:addCarLights(K7) sch2:addPedestrianLights(F3, F4) --- Tutorial 2: Schaltung 3 local sch3 = CrossingSequence:new("Schaltung 3") sch3:addCarLights(K1) sch3:addCarLights(K2) sch3:addPedestrianLights(F3, F4) sch3:addPedestrianLights(F5, F6) k1 = Crossing:new("Tutorial 2") k1:addSequence(sch1) k1:addSequence(sch2) k1:addSequence(sch3) local ModuleRegistry = require("ak.core.ModuleRegistry") ModuleRegistry.registerModules(require("ak.core.CoreLuaModule"), require("ak.road.CrossingLuaModul")) function EEPMain() ModuleRegistry.runTasks() return 1 end
clearlog() local TrafficLightModel = require("ak.road.TrafficLightModel") local TrafficLight = require("ak.road.TrafficLight") local Lane = require("ak.road.Lane") local Crossing = require("ak.road.Crossing") local CrossingSequence = require("ak.road.CrossingSequence") Crossing.debug = true ------------------------------------------------ -- Damit kommt wird die Variable "Zugname" automatisch durch EEP belegt -- http://emaps-eep.de/lua/code-schnipsel ------------------------------------------------ setmetatable(_ENV, { __index = function(_, k) local p = load(k) if p then local f = function(z) local s = Zugname Zugname = z p() Zugname = s end _ENV[k] = f return f end return nil end }) -------------------------------------------- -- Definiere Funktionen fuer Kontaktpunkte -------------------------------------------- function enterLane(lane) assert(lane, "lane darf nicht nil sein. Richtige Lua-Funktion im Kontaktpunkt?") lane:vehicleEntered(Zugname) end function leaveLane(lane) assert(lane, "lane darf nicht nil sein. Richtige Lua-Funktion im Kontaktpunkt?") lane:vehicleLeft(Zugname) end ------------------------------------------------------------------------------- -- Definiere die Fahrspuren fuer die Kreuzung ------------------------------------------------------------------------------- -- +---------------------------- Variablenname der Ampel -- | +----------------------- Legt eine neue Ampel an -- | | +------ Signal-ID dieser Ampel -- | | | +-- Modell dieser Ampel - weiss wo rot, gelb und gruen / Fussgaenger ist local K1 = TrafficLight:new("K1/F1", 07, TrafficLightModel.JS2_3er_mit_FG) -- Ampel K1 ist gleichzeitig eine Fugngerampel local K2 = TrafficLight:new("K2/F2", 08, TrafficLightModel.JS2_3er_mit_FG) local K3 = TrafficLight:new("K3/F3", 09, TrafficLightModel.JS2_3er_mit_FG) local K4 = TrafficLight:new("K4/F4", 10, TrafficLightModel.JS2_3er_mit_FG) local K5 = TrafficLight:new("K5/F5", 12, TrafficLightModel.JS2_3er_mit_FG) local K6 = TrafficLight:new("K6", 13, TrafficLightModel.JS2_3er_ohne_FG) -- dies ist keine Fugngerampel local K7 = TrafficLight:new("K7/F6", 11, TrafficLightModel.JS2_3er_mit_FG) -- Ampeln fr die Straenbahn nutzen die Lichtfunktion der einzelnen Immobilien local S1 = TrafficLight:new("S1", 14, TrafficLightModel.Unsichtbar_2er, "#29_Straba Signal Halt", -- rot "#28_Straba Signal geradeaus", -- gruen "#27_Straba Signal anhalten", -- gelb "#26_Straba Signal A") -- Anforderung local S2 = TrafficLight:new("S2", 15, TrafficLightModel.Unsichtbar_2er, "#32_Straba Signal Halt", -- rot "#30_Straba Signal geradeaus", -- gruen "#31_Straba Signal anhalten", -- gelb "#33_Straba Signal A") -- Anforderung local F1 = K1 -- Die Fussgngerampel F1 ist die selbe, wie Ampel K1, zeigt aber spter "Fugnger grn" local F2 = K2 local F3 = K3 local F4 = K4 local F5 = K5 local F6 = K7 -- +-----------------------------------------Neue Fahrspur -- | +------------------------------- Name der Fahrspur -- | | +------------------------- Speicher ID - um die Anzahl der Fahrzeuge -- | | | und die Wartezeit zu speichern -- | | | +------------------ neue Ampel fr diese Fahrspur -- | | | | +------ Signal-ID dieser Ampel -- | | | | | +-- Modell kann rot, gelb, gruen und FG schalten -- Die Fahrspur N wird durch die Fahrspur-Ampel K1 (Signal ID 07) gesteuert -- K2 muss spter gleichzeitig leuchten (Signal ID 08) n = Lane:new("N", 100, K1) -- Die Fahrspur O1 wird durch die Fahrspur-Ampel K2 (Signal 09) gesteuert -- K4 muss spter gleichzeitig leuchten (Signal ID 10) o1 = Lane:new("O1", 102, K3) -- Fahrspuren im Westen -- Die Fahrspur W1 wird durch die Fahrspur-Ampel K5 (Signal 12) gesteuert w1 = Lane:new("W1", 104, K5) -- Die Fahrspur W2 wird durch die Fahrspur-Ampel K6 (Signal 13) gesteuert -- K7 muss spter gleichzeitig leuchten (Signal ID 11) w2 = Lane:new("W2", 105, K6) -- Fahrspuren fuer Strassenbahnen: os = Lane:new("OS", 107, S1) os:showRequestsOn(S1) os:useSignalForQueue() -- Erfasst Anforderungen, wenn ein Fahrzeug an Signal 14 steht ws = Lane:new("WS", 108, S2) ws:showRequestsOn(S2) ws:useTrackForQueue(2) -- Erfasst Anforderungen, wenn ein Fahrzeug auf Strasse 2 steht -------------------------------------------------------------- -- Definiere die Schaltungen und die Kreuzung -------------------------------------------------------------- -- Eine Schaltung bestimmt, welche Fahrspuren gleichzeitig auf -- grn geschaltet werden drfen, alle anderen sind rot k1 = Crossing:new("Tutorial 2") --- Tutorial 2: Schaltung 1 local sch1 = k1:newSequence("Schaltung 1") sch1:addCarLights(K3) sch1:addCarLights(K4) sch1:addTramLights(S1) sch1:addCarLights(K5) sch1:addTramLights(S2) sch1:addPedestrianLights(F1, F2) --- Tutorial 2: Schaltung 2 local sch2 = k1:newSequence("Schaltung 2") sch2:addCarLights(K6) sch2:addCarLights(K7) sch2:addPedestrianLights(F3, F4) --- Tutorial 2: Schaltung 3 local sch3 = k1:newSequence("Schaltung 3") sch3:addCarLights(K1) sch3:addCarLights(K2) sch3:addPedestrianLights(F3, F4) sch3:addPedestrianLights(F5, F6) -- Die Kreuzung soll die Schaltungen einfach nur in Ihrer Reihenfolge schalten k1:setSwitchInStrictOrder(true) local ModuleRegistry = require("ak.core.ModuleRegistry") ModuleRegistry.registerModules( require("ak.core.CoreLuaModule"), require("ak.road.CrossingLuaModul") ) function EEPMain() ModuleRegistry.runTasks() return 1 end
fix pedestrian light names and switch in order
fix pedestrian light names and switch in order
Lua
mit
Andreas-Kreuz/ak-lua-skripte-fuer-eep,Andreas-Kreuz/ak-lua-skripte-fuer-eep
0c0147c6c9aca3be54eee297c38d6f8e37f8a001
packages/lime-webui/src/model/essentials.lua
packages/lime-webui/src/model/essentials.lua
--[[ Copyright (C) 2011 Fundacio Privada per a la Xarxa Oberta, Lliure i Neutral guifi.net This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. The full GNU General Public License is included in this distribution in the file called "COPYING". --]] m = Map("lime", "Libre-Mesh") -- Create sections local system = m:section(NamedSection, "system", "lime","System","System") system.addremove = true local network = m:section(NamedSection, "network", "lime","Network","Network") network.addremove = true local wifi = m:section(NamedSection, "wifi", "lime","WiFi","WiFi") wifi.addremove = true -- hostname system:option(Value,"hostname",translate("Hostname"),translate("Name for this node")) -- network network:option(Value,"main_ipv4",translate("Main IPv4"),translate("The main IPv4 configured for this node")) network:option(Value,"main_ipv6",translate("Main IPv6"),translate("The main IPv6 configured for this node")) -- wifi wifi:option(Value,"public_essid",translate("Public SSID"),translate("The SSID (WiFi network name) used for this node")) -- commit function m.on_commit(self,map) luci.sys.call('true') end return m
--[[ Copyright (C) 2011 Fundacio Privada per a la Xarxa Oberta, Lliure i Neutral guifi.net This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. The full GNU General Public License is included in this distribution in the file called "COPYING". --]] m = Map("lime", "Libre-Mesh") -- Create sections local system = m:section(NamedSection, "system", "lime","System","System") system.addremove = true local network = m:section(NamedSection, "network", "lime","Network","Network") network.addremove = true local wifi = m:section(TypedSection, "wifi","WiFi","WiFi") wifi.addremove = true -- hostname system:option(Value,"hostname",translate("Hostname"),translate("Name for this node")) -- network network:option(Value,"main_ipv4",translate("Main IPv4"),translate("The main IPv4 configured for this node")) network:option(Value,"main_ipv6",translate("Main IPv6"),translate("The main IPv6 configured for this node")) -- wifi wifi:option(Value,"public_essid",translate("Public SSID"),translate("The SSID (WiFi network name) used for this node")) wifi:option(Value,"channel",translate("Channel"),translate("Channel used for this interface")) wifi:option(Value,"ap_essid",translate("AP SSID"),translate("The SSID (WiFi network name) used for the access point devices")) wifi:option(Value,"adhoc_essid",translate("Mesh SSID"),translate("The SSID (WiFi network name) used for the ad-hoc device")) wifi:option(Value,"adhoc_bssid",translate("Mesh BSSID"),translate("The BSSID (WiFi network identifier) used for the ad-hoc network")) -- commit function m.on_commit(self,map) luci.sys.call('true') end return m
Fix web iface (dummy version but working...)
Fix web iface (dummy version but working...)
Lua
agpl-3.0
libremesh/lime-packages,p4u/lime-packages,p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages,p4u/lime-packages,p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages
4f6129a334f4cfc4963cdcc03c5de4483b01f8fc
src_trunk/resources/tag-system/c_tag_system.lua
src_trunk/resources/tag-system/c_tag_system.lua
cooldown = 0 count = 0 function clientTagWall(weapon, ammo, ammoInClip, hitX, hitY, hitZ, hitElement) if (weapon==41) then local team = getPlayerTeam(getLocalPlayer()) local ftype = getElementData(team, "type") local tag = getElementData(source, "tag") if (ftype~=2) then if not (hitElement) or (getElementType(hitElement)~="player") then -- Didn't attack someone if (cooldown==0) then if (ammoInClip>10) and (weapon==41) then -- Check the player is near a wall local localPlayer = getLocalPlayer() local x, y, z = getElementPosition(localPlayer) local rot = getPedRotation(localPlayer) local matrix = getElementMatrix (localPlayer) -- DIRECTLY INFRONT OF PLAYER local oldX = 0 local oldY = 1 local oldZ = 0 local newX = oldX * matrix[1][1] + oldY * matrix [2][1] + oldZ * matrix [3][1] + matrix [4][1] local newY = oldX * matrix[1][2] + oldY * matrix [2][2] + oldZ * matrix [3][2] + matrix [4][2] local newZ = oldX * matrix[1][3] + oldY * matrix [2][3] + oldZ * matrix [3][3] + matrix [4][3] -- TO LEFT OF PLAYER local oldXleft = -1.5 local oldYleft = 1 local oldZleft = 0 local newXleft = oldXleft * matrix[1][1] + oldYleft * matrix [2][1] + oldZleft * matrix [3][1] + matrix [4][1] local newYleft = oldXleft * matrix[1][2] + oldYleft * matrix [2][2] + oldZleft * matrix [3][2] + matrix [4][2] local newZleft = oldXleft * matrix[1][3] + oldYleft * matrix [2][3] + oldZleft * matrix [3][3] + matrix [4][3] -- TO RIGHT OF PLAYER local oldXright = 1.5 local oldYright = 1 local oldZright = 0 local newXright = oldXright * matrix[1][1] + oldYright * matrix [2][1] + oldZright * matrix [3][1] + matrix [4][1] local newYright = oldXright * matrix[1][2] + oldYright * matrix [2][2] + oldZright * matrix [3][2] + matrix [4][2] local newZright = oldXright * matrix[1][3] + oldYright * matrix [2][3] + oldZright * matrix [3][3] + matrix [4][3] local facingWall, cx, cy, cz, element = processLineOfSight(x, y, z, newX, newY, newZ, true, false, false, true, false) local facingWallleft, lx, ly, lz, lelement = processLineOfSight(x, y, z, newXleft, newYleft, newZleft, true, false, false, true, false) local facingWallright, rx, ry, rz, relement = processLineOfSight(x, y, z, newXright, newYright, newZright, true, false, false, true, false) if not (facingWall) or not (facingWallleft) or not (facingWallright) then outputChatBox("You are not near a wall.", 255, 0, 0) count = 0 cooldown = 1 setTimer(resetCooldown, 5000, 1) else count = count + 1 if (count==20) then count = 0 cooldown = 1 setTimer(resetCooldown, 30000, 1) local interior = getElementInterior(localPlayer) local dimension = getElementDimension(localPlayer) --cx = cx - math.sin(math.rad(rot)) * 0.1 cy = cy - math.cos(math.rad(rot)) * 0.1 triggerServerEvent("createTag", localPlayer, cx, cy, cz, rot, interior, dimension) end end end end end end end end addEventHandler("onClientPlayerWeaponFire", getLocalPlayer(), clientTagWall) function resetCooldown() cooldown = 0 end function setTag(commandName, newTag) if not (newTag) then outputChatBox("SYNTAX: " .. commandName .. " [Tag # 1->8].", 255, 194, 14) else local newTag = tonumber(newTag) if (newTag>0) and (newTag<9) then setElementData(getLocalPlayer(), "tag", true, newTag) outputChatBox("Tag changed to #" .. newTag .. ".", 0, 255, 0) else outputChatBox("Invalid value, please enter a value between 1 and 8.", 255, 0, 0) end end end addCommandHandler("settag", setTag)
cooldown = 0 count = 0 function clientTagWall(weapon, ammo, ammoInClip, hitX, hitY, hitZ, hitElement) if (weapon==41) then local team = getPlayerTeam(getLocalPlayer()) local ftype = getElementData(team, "type") local tag = getElementData(source, "tag") if (ftype~=2) then if not (hitElement) or (getElementType(hitElement)~="player") then -- Didn't attack someone if (cooldown==0) then if (ammoInClip>10) and (weapon==41) then -- Check the player is near a wall local localPlayer = getLocalPlayer() local x, y, z = getElementPosition(localPlayer) local rot = getPedRotation(localPlayer) local matrix = getElementMatrix (localPlayer) -- DIRECTLY INFRONT OF PLAYER local oldX = 0 local oldY = 1 local oldZ = 0 local newX = oldX * matrix[1][1] + oldY * matrix [2][1] + oldZ * matrix [3][1] + matrix [4][1] local newY = oldX * matrix[1][2] + oldY * matrix [2][2] + oldZ * matrix [3][2] + matrix [4][2] local newZ = oldX * matrix[1][3] + oldY * matrix [2][3] + oldZ * matrix [3][3] + matrix [4][3] -- TO LEFT OF PLAYER local oldXleft = -1.5 local oldYleft = 1 local oldZleft = 0 local newXleft = oldXleft * matrix[1][1] + oldYleft * matrix [2][1] + oldZleft * matrix [3][1] + matrix [4][1] local newYleft = oldXleft * matrix[1][2] + oldYleft * matrix [2][2] + oldZleft * matrix [3][2] + matrix [4][2] local newZleft = oldXleft * matrix[1][3] + oldYleft * matrix [2][3] + oldZleft * matrix [3][3] + matrix [4][3] -- TO RIGHT OF PLAYER local oldXright = 1.5 local oldYright = 1 local oldZright = 0 local newXright = oldXright * matrix[1][1] + oldYright * matrix [2][1] + oldZright * matrix [3][1] + matrix [4][1] local newYright = oldXright * matrix[1][2] + oldYright * matrix [2][2] + oldZright * matrix [3][2] + matrix [4][2] local newZright = oldXright * matrix[1][3] + oldYright * matrix [2][3] + oldZright * matrix [3][3] + matrix [4][3] -- TO TOP OF PLAYER local oldXtop = 0 local oldYtop = 1 local oldZtop = 1 local newXtop = oldXtop * matrix[1][1] + oldYtop * matrix [2][1] + oldZtop * matrix [3][1] + matrix [4][1] local newYtop = oldXtop * matrix[1][2] + oldYtop * matrix [2][2] + oldZtop * matrix [3][2] + matrix [4][2] local newZtop = oldXtop * matrix[1][3] + oldYtop * matrix [2][3] + oldZtop * matrix [3][3] + matrix [4][3] local facingWall, cx, cy, cz, element = processLineOfSight(x, y, z, newX, newY, newZ, true, false, false, true, false) local facingWallleft, lx, ly, lz, lelement = processLineOfSight(x, y, z, newXleft, newYleft, newZleft, true, false, false, true, false) local facingWallright, rx, ry, rz, relement = processLineOfSight(x, y, z, newXright, newYright, newZright, true, false, false, true, false) local facingWalltop, tx, ty, tz, telement = processLineOfSight(x, y, z, newXtop, newYtop, newZtop, true, false, false, true, false) if not (facingWall) or not (facingWallleft) or not (facingWallright) or not (facingWalltop) then outputChatBox("You are not near a wall.", 255, 0, 0) count = 0 cooldown = 1 setTimer(resetCooldown, 5000, 1) else count = count + 1 if (count==20) then count = 0 cooldown = 1 setTimer(resetCooldown, 30000, 1) local interior = getElementInterior(localPlayer) local dimension = getElementDimension(localPlayer) --cx = cx - math.sin(math.rad(rot)) * 0.1 cy = cy - math.cos(math.rad(rot)) * 0.1 triggerServerEvent("createTag", localPlayer, cx, cy, cz, rot, interior, dimension) end end end end end end end end addEventHandler("onClientPlayerWeaponFire", getLocalPlayer(), clientTagWall) function resetCooldown() cooldown = 0 end function setTag(commandName, newTag) if not (newTag) then outputChatBox("SYNTAX: " .. commandName .. " [Tag # 1->8].", 255, 194, 14) else local newTag = tonumber(newTag) if (newTag>0) and (newTag<9) then setElementData(getLocalPlayer(), "tag", true, newTag) outputChatBox("Tag changed to #" .. newTag .. ".", 0, 255, 0) else outputChatBox("Invalid value, please enter a value between 1 and 8.", 255, 0, 0) end end end addCommandHandler("settag", setTag)
Fixed a bug where you could spray a wall even if it wasn't tall enough to hold that tag.
Fixed a bug where you could spray a wall even if it wasn't tall enough to hold that tag. git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@492 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
02f8c27a43660e3bc3db6f4cec7468a7a0bf437f
libs/uvl/luasrc/uvl/errors.lua
libs/uvl/luasrc/uvl/errors.lua
--[[ UCI Validation Layer - Error handling (c) 2008 Jo-Philipp Wich <[email protected]> (c) 2008 Steven Barth <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local uci = require "luci.model.uci" local uvl = require "luci.uvl" local util = require "luci.util" local string = require "string" local ipairs, error, type = ipairs, error, type local tonumber, unpack = tonumber, unpack local luci = luci module "luci.uvl.errors" ERRCODES = { { 'UCILOAD', 'Unable to load config "%p": %1' }, { 'SCHEME', 'Error in scheme "%p":\n%c' }, { 'CONFIG', 'Error in config "%p":\n%c' }, { 'SECTION', 'Error in section "%i" (%I):\n%c' }, { 'OPTION', 'Error in option "%i" (%I):\n%c' }, { 'REFERENCE', 'Option "%i" has invalid reference specification %1:\n%c' }, { 'DEPENDENCY', 'In dependency check for %t "%i":\n%c' }, { 'SME_FIND', 'Can not find scheme "%p" in "%1"' }, { 'SME_READ', 'Can not access file "%1"' }, { 'SME_REQFLD', 'Missing required scheme field "%1" in "%i"' }, { 'SME_INVREF', 'Illegal reference "%1" to an anonymous section' }, { 'SME_BADREF', 'Malformed reference in "%1"' }, { 'SME_BADDEP', 'Malformed dependency specification "%1" in "%i"' }, { 'SME_BADVAL', 'Malformed validator specification "%1" in "%i"' }, { 'SME_ERRVAL', 'External validator "%1" failed: %2' }, { 'SME_VBADPACK', 'Variable "%o" in scheme "%p" references unknown package "%1"' }, { 'SME_VBADSECT', 'Variable "%o" in scheme "%p" references unknown section "%1"' }, { 'SME_EBADPACK', 'Enum "%v" in scheme "%p" references unknown package "%1"' }, { 'SME_EBADSECT', 'Enum "%v" in scheme "%p" references unknown section "%1"' }, { 'SME_EBADOPT', 'Enum "%v" in scheme "%p" references unknown option "%1"' }, { 'SME_EBADTYPE', 'Enum "%v" in scheme "%p" references non-enum option "%I"' }, { 'SME_EBADDEF', 'Enum "%v" in scheme "%p" redeclares the default value of "%I"' }, { 'SECT_UNKNOWN', 'Section "%i" (%I) not found in scheme' }, { 'SECT_REQUIRED', 'Required section "%p.%S" not found in config' }, { 'SECT_UNIQUE', 'Unique section "%p.%S" occurs multiple times in config' }, { 'SECT_NAMED', 'The section of type "%p.%S" is stored anonymously in config but must be named' }, { 'SECT_NOTFOUND', 'Section "%p.%s" not found in config' }, { 'OPT_UNKNOWN', 'Option "%i" (%I) not found in scheme' }, { 'OPT_REQUIRED', 'Required option "%i" has no value' }, { 'OPT_BADVALUE', 'Value "%1" of option "%i" is not defined in enum %2' }, { 'OPT_INVVALUE', 'Value "%1" of option "%i" does not validate as datatype "%2"' }, { 'OPT_NOTLIST', 'Option "%i" is defined as list but stored as plain value' }, { 'OPT_DATATYPE', 'Option "%i" has unknown datatype "%1"' }, { 'OPT_NOTFOUND', 'Option "%p.%s.%o" not found in config' }, { 'OPT_RANGE', 'Option "%p.%s.%o" is not within the specified range' }, { 'DEP_NOTEQUAL', 'Dependency (%1) failed:\nOption "%i" is not eqal "%2"' }, { 'DEP_NOVALUE', 'Dependency (%1) failed:\nOption "%i" has no value' }, { 'DEP_NOTVALID', 'Dependency (%1) failed:\n%c' }, { 'DEP_RECURSIVE', 'Recursive dependency for option "%i" detected' }, { 'DEP_BADENUM', 'In dependency check for enum value "%i":\n%c' } } -- build error constants and instance constructors for i, v in ipairs(ERRCODES) do _M[v[1]] = function(...) return error(i, ...) end _M['ERR_'..v[1]] = i end function i18n(key, def) if luci.i18n then return luci.i18n.translate(key,def) else return def end end error = util.class() function error.__init__(self, code, pso, args) self.code = code self.args = ( type(args) == "table" and args or { args } ) if util.instanceof( pso, uvl.uvlitem ) then self.stype = pso.sref[2] self.package, self.section, self.option, self.value = unpack(pso.cref) self.object = pso self.value = self.value or ( pso.value and pso:value() ) else pso = ( type(pso) == "table" and pso or { pso } ) if pso[2] then local uci = uci.cursor() self.stype = uci:get(pso[1], pso[2]) or pso[2] end self.package, self.section, self.option, self.value = unpack(pso) end end function error.child(self, err) if not self.childs then self.childs = { err } else self.childs[#self.childs+1] = err end return self end function error.string(self,pad) pad = pad or " " local str = i18n( 'uvl_err_%s' % string.lower(ERRCODES[self.code][1]), ERRCODES[self.code][2] ) :gsub("\n", "\n"..pad) :gsub("%%i", self:cid()) :gsub("%%I", self:sid()) :gsub("%%p", self.package or '(nil)') :gsub("%%s", self.section or '(nil)') :gsub("%%S", self.stype or '(nil)') :gsub("%%o", self.option or '(nil)') :gsub("%%v", self.value or '(nil)') :gsub("%%t", self.object and self.object:type() or '(nil)' ) :gsub("%%T", self.object and self.object:title() or '(nil)' ) :gsub("%%([1-9])", function(n) return self.args[tonumber(n)] or '(nil)' end) :gsub("%%c", function() local s = "" for _, err in ipairs(self.childs or {}) do s = s .. err:string(pad.." ") .. "\n" .. pad end return s end ) return (str:gsub("%s+$","")) end function error.cid(self) return self.object and self.object:cid() or self.package .. ( self.section and '.' .. self.section or '' ) .. ( self.option and '.' .. self.option or '' ) .. ( self.value and '.' .. self.value or '' ) end function error.sid(self) return self.object and self.object:sid() or self.package .. ( self.stype and '.' .. self.stype or '' ) .. ( self.option and '.' .. self.option or '' ) .. ( self.value and '.' .. self.value or '' ) end function error.is(self, code) if self.code == code then return true elseif self.childs then for _, c in ipairs(self.childs) do if c:is(code) then return true end end end return false end function error.is_all(self, ...) local codes = { ... } if util.contains(codes, self.code) then return true else local equal = false for _, c in ipairs(self.childs) do if c.childs then equal = c:is_all(...) else equal = util.contains(codes, c.code) end end return equal end end
--[[ UCI Validation Layer - Error handling (c) 2008 Jo-Philipp Wich <[email protected]> (c) 2008 Steven Barth <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local uci = require "luci.model.uci" local uvl = require "luci.uvl" local util = require "luci.util" local string = require "string" local ipairs, error, type = ipairs, error, type local tonumber, unpack = tonumber, unpack local luci = luci module "luci.uvl.errors" ERRCODES = { { 'UCILOAD', 'Unable to load config "%p": %1' }, { 'SCHEME', 'Error in scheme "%p":\n%c' }, { 'CONFIG', 'Error in config "%p":\n%c' }, { 'SECTION', 'Error in section "%i" (%I):\n%c' }, { 'OPTION', 'Error in option "%i" (%I):\n%c' }, { 'REFERENCE', 'Option "%i" has invalid reference specification %1:\n%c' }, { 'DEPENDENCY', 'In dependency check for %t "%i":\n%c' }, { 'SME_FIND', 'Can not find scheme "%p" in "%1"' }, { 'SME_READ', 'Can not access file "%1"' }, { 'SME_REQFLD', 'Missing required scheme field "%1" in "%i"' }, { 'SME_INVREF', 'Illegal reference "%1" to an anonymous section' }, { 'SME_BADREF', 'Malformed reference in "%1"' }, { 'SME_BADDEP', 'Malformed dependency specification "%1" in "%i"' }, { 'SME_BADVAL', 'Malformed validator specification "%1" in "%i"' }, { 'SME_ERRVAL', 'External validator "%1" failed: %2' }, { 'SME_VBADPACK', 'Variable "%o" in scheme "%p" references unknown package "%1"' }, { 'SME_VBADSECT', 'Variable "%o" in scheme "%p" references unknown section "%1"' }, { 'SME_EBADPACK', 'Enum "%v" in scheme "%p" references unknown package "%1"' }, { 'SME_EBADSECT', 'Enum "%v" in scheme "%p" references unknown section "%1"' }, { 'SME_EBADOPT', 'Enum "%v" in scheme "%p" references unknown option "%1"' }, { 'SME_EBADTYPE', 'Enum "%v" in scheme "%p" references non-enum option "%I"' }, { 'SME_EBADDEF', 'Enum "%v" in scheme "%p" redeclares the default value of "%I"' }, { 'SECT_UNKNOWN', 'Section "%i" (%I) not found in scheme' }, { 'SECT_REQUIRED', 'Required section "%p.%S" not found in config' }, { 'SECT_UNIQUE', 'Unique section "%p.%S" occurs multiple times in config' }, { 'SECT_NAMED', 'The section of type "%p.%S" is stored anonymously in config but must be named' }, { 'SECT_NOTFOUND', 'Section "%p.%s" not found in config' }, { 'OPT_UNKNOWN', 'Option "%i" (%I) not found in scheme' }, { 'OPT_REQUIRED', 'Required option "%i" has no value' }, { 'OPT_BADVALUE', 'Value "%1" of option "%i" is not defined in enum %2' }, { 'OPT_INVVALUE', 'Value "%1" of option "%i" does not validate as datatype "%2"' }, { 'OPT_NOTLIST', 'Option "%i" is defined as list but stored as plain value' }, { 'OPT_DATATYPE', 'Option "%i" has unknown datatype "%1"' }, { 'OPT_NOTFOUND', 'Option "%p.%s.%o" not found in config' }, { 'OPT_RANGE', 'Option "%p.%s.%o" is not within the specified range' }, { 'DEP_NOTEQUAL', 'Dependency (%1) failed:\nOption "%i" is not eqal "%2"' }, { 'DEP_NOVALUE', 'Dependency (%1) failed:\nOption "%i" has no value' }, { 'DEP_NOTVALID', 'Dependency (%1) failed:\n%c' }, { 'DEP_RECURSIVE', 'Recursive dependency for option "%i" detected' }, { 'DEP_BADENUM', 'In dependency check for enum value "%i":\n%c' } } -- build error constants and instance constructors for i, v in ipairs(ERRCODES) do _M[v[1]] = function(...) return error(i, ...) end _M['ERR_'..v[1]] = i end function i18n(key) if luci.i18n then return luci.i18n.translate(key) else return key end end error = util.class() function error.__init__(self, code, pso, args) self.code = code self.args = ( type(args) == "table" and args or { args } ) if util.instanceof( pso, uvl.uvlitem ) then self.stype = pso.sref[2] self.package, self.section, self.option, self.value = unpack(pso.cref) self.object = pso self.value = self.value or ( pso.value and pso:value() ) else pso = ( type(pso) == "table" and pso or { pso } ) if pso[2] then local uci = uci.cursor() self.stype = uci:get(pso[1], pso[2]) or pso[2] end self.package, self.section, self.option, self.value = unpack(pso) end end function error.child(self, err) if not self.childs then self.childs = { err } else self.childs[#self.childs+1] = err end return self end function error.string(self,pad) pad = pad or " " local str = i18n(ERRCODES[self.code][2]) :gsub("\n", "\n"..pad) :gsub("%%i", self:cid()) :gsub("%%I", self:sid()) :gsub("%%p", self.package or '(nil)') :gsub("%%s", self.section or '(nil)') :gsub("%%S", self.stype or '(nil)') :gsub("%%o", self.option or '(nil)') :gsub("%%v", self.value or '(nil)') :gsub("%%t", self.object and self.object:type() or '(nil)' ) :gsub("%%T", self.object and self.object:title() or '(nil)' ) :gsub("%%([1-9])", function(n) return self.args[tonumber(n)] or '(nil)' end) :gsub("%%c", function() local s = "" for _, err in ipairs(self.childs or {}) do s = s .. err:string(pad.." ") .. "\n" .. pad end return s end ) return (str:gsub("%s+$","")) end function error.cid(self) return self.object and self.object:cid() or self.package .. ( self.section and '.' .. self.section or '' ) .. ( self.option and '.' .. self.option or '' ) .. ( self.value and '.' .. self.value or '' ) end function error.sid(self) return self.object and self.object:sid() or self.package .. ( self.stype and '.' .. self.stype or '' ) .. ( self.option and '.' .. self.option or '' ) .. ( self.value and '.' .. self.value or '' ) end function error.is(self, code) if self.code == code then return true elseif self.childs then for _, c in ipairs(self.childs) do if c:is(code) then return true end end end return false end function error.is_all(self, ...) local codes = { ... } if util.contains(codes, self.code) then return true else local equal = false for _, c in ipairs(self.childs) do if c.childs then equal = c:is_all(...) else equal = util.contains(codes, c.code) end end return equal end end
libs/uvl: fix i18n handling for errors
libs/uvl: fix i18n handling for errors git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@5475 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
zwhfly/openwrt-luci,vhpham80/luci,phi-psi/luci,projectbismark/luci-bismark,zwhfly/openwrt-luci,Flexibity/luci,Flexibity/luci,stephank/luci,jschmidlapp/luci,Canaan-Creative/luci,yeewang/openwrt-luci,phi-psi/luci,ch3n2k/luci,ch3n2k/luci,Canaan-Creative/luci,ch3n2k/luci,8devices/carambola2-luci,ThingMesh/openwrt-luci,8devices/carambola2-luci,Canaan-Creative/luci,phi-psi/luci,freifunk-gluon/luci,jschmidlapp/luci,zwhfly/openwrt-luci,phi-psi/luci,jschmidlapp/luci,saraedum/luci-packages-old,stephank/luci,Flexibity/luci,freifunk-gluon/luci,projectbismark/luci-bismark,eugenesan/openwrt-luci,vhpham80/luci,zwhfly/openwrt-luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,saraedum/luci-packages-old,gwlim/luci,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,eugenesan/openwrt-luci,8devices/carambola2-luci,projectbismark/luci-bismark,Flexibity/luci,ThingMesh/openwrt-luci,projectbismark/luci-bismark,dtaht/cerowrt-luci-3.3,jschmidlapp/luci,phi-psi/luci,ThingMesh/openwrt-luci,yeewang/openwrt-luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,eugenesan/openwrt-luci,dtaht/cerowrt-luci-3.3,8devices/carambola2-luci,freifunk-gluon/luci,stephank/luci,projectbismark/luci-bismark,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,ch3n2k/luci,dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,stephank/luci,dtaht/cerowrt-luci-3.3,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,saraedum/luci-packages-old,Canaan-Creative/luci,jschmidlapp/luci,gwlim/luci,vhpham80/luci,Flexibity/luci,freifunk-gluon/luci,freifunk-gluon/luci,Canaan-Creative/luci,yeewang/openwrt-luci,vhpham80/luci,eugenesan/openwrt-luci,ThingMesh/openwrt-luci,Canaan-Creative/luci,gwlim/luci,jschmidlapp/luci,dtaht/cerowrt-luci-3.3,zwhfly/openwrt-luci,eugenesan/openwrt-luci,projectbismark/luci-bismark,freifunk-gluon/luci,gwlim/luci,stephank/luci,dtaht/cerowrt-luci-3.3,freifunk-gluon/luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,ch3n2k/luci,ThingMesh/openwrt-luci,gwlim/luci,vhpham80/luci,phi-psi/luci,eugenesan/openwrt-luci,gwlim/luci,projectbismark/luci-bismark,jschmidlapp/luci,Flexibity/luci,Flexibity/luci,vhpham80/luci,zwhfly/openwrt-luci,jschmidlapp/luci,ReclaimYourPrivacy/cloak-luci,stephank/luci,yeewang/openwrt-luci,saraedum/luci-packages-old,8devices/carambola2-luci,8devices/carambola2-luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,saraedum/luci-packages-old,projectbismark/luci-bismark,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,Flexibity/luci,Canaan-Creative/luci,gwlim/luci,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,ThingMesh/openwrt-luci