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
12359927dfeee65f84ea14696260dfccb104b88d
src/formatters/init.lua
src/formatters/init.lua
-- module will not return anything, only register formatters with the main assert engine local assert = require('luassert.assert') local function fmt_string(arg) if type(arg) == "string" then return string.format("(string) '%s'", arg) end end local function fmt_number(arg) if type(arg) == "number" then return string.format("(number) %s", tostring(arg)) end end local function fmt_boolean(arg) if type(arg) == "boolean" then return string.format("(boolean) %s", tostring(arg)) end end local function fmt_nil(arg) if type(arg) == "nil" then return "(nil)" end end local type_priorities = { number = 1, boolean = 2, string = 3, table = 4, ["function"] = 5, userdata = 6, thread = 7 } local function is_in_array_part(key, length) return type(key) == "number" and 1 <= key and key <= length and math.floor(key) == key end local function get_sorted_keys(t) local keys = {} local nkeys = 0 for key in pairs(t) do nkeys = nkeys + 1 keys[nkeys] = key end local length = #t local function key_comparator(key1, key2) local type1, type2 = type(key1), type(key2) local priority1 = is_in_array_part(key1, length) and 0 or type_priorities[type1] or 8 local priority2 = is_in_array_part(key2, length) and 0 or type_priorities[type2] or 8 if priority1 == priority2 then if type1 == "string" or type1 == "number" then return key1 < key2 elseif type1 == "boolean" then return key1 -- put true before false end else return priority1 < priority2 end end table.sort(keys, key_comparator) return keys, nkeys end local function fmt_table(arg) local tmax = assert:get_parameter("TableFormatLevel") local ft ft = function(t, l) local result = "" local keys, nkeys = get_sorted_keys(t) for i = 1, nkeys do local k = keys[i] local v = t[k] if type(v) == "table" then if l < tmax or tmax < 0 then result = result .. string.format(string.rep(" ",l * 2) .. "[%s] = {\n%s }\n", tostring(k), tostring(ft(v, l + 1):sub(1,-2))) else result = result .. string.format(string.rep(" ",l * 2) .. "[%s] = { ... more }\n", tostring(k)) end else if type(v) == "string" then v = "'"..v.."'" end result = result .. string.format(string.rep(" ",l * 2) .. "[%s] = %s\n", tostring(k), tostring(v)) end end return result end if type(arg) == "table" then local result if tmax == 0 then if next(arg) then result = "(table): { ... more }" else result = "(table): { }" end else result = "(table): {\n" .. ft(arg, 1):sub(1,-2) .. " }\n" result = result:gsub("{\n }\n", "{ }\n") -- cleanup empty tables result = result:sub(1,-2) -- remove trailing newline end return result end end local function fmt_function(arg) if type(arg) == "function" then local debug_info = debug.getinfo(arg) return string.format("%s @ line %s in %s", tostring(arg), tostring(debug_info.linedefined), tostring(debug_info.source)) end end local function fmt_userdata(arg) if type(arg) == "userdata" then return string.format("(userdata) '%s'", tostring(arg)) end end local function fmt_thread(arg) if type(arg) == "thread" then return string.format("(thread) '%s'", tostring(arg)) end end assert:add_formatter(fmt_string) assert:add_formatter(fmt_number) assert:add_formatter(fmt_boolean) assert:add_formatter(fmt_nil) assert:add_formatter(fmt_table) assert:add_formatter(fmt_function) assert:add_formatter(fmt_userdata) assert:add_formatter(fmt_thread) -- Set default table display depth for table formatter assert:set_parameter("TableFormatLevel", 3)
-- module will not return anything, only register formatters with the main assert engine local assert = require('luassert.assert') local function fmt_string(arg) if type(arg) == "string" then return string.format("(string) '%s'", arg) end end local function fmt_number(arg) if type(arg) == "number" then return string.format("(number) %s", tostring(arg)) end end local function fmt_boolean(arg) if type(arg) == "boolean" then return string.format("(boolean) %s", tostring(arg)) end end local function fmt_nil(arg) if type(arg) == "nil" then return "(nil)" end end local type_priorities = { number = 1, boolean = 2, string = 3, table = 4, ["function"] = 5, userdata = 6, thread = 7 } local function is_in_array_part(key, length) return type(key) == "number" and 1 <= key and key <= length and math.floor(key) == key end local function get_sorted_keys(t) local keys = {} local nkeys = 0 for key in pairs(t) do nkeys = nkeys + 1 keys[nkeys] = key end local length = #t local function key_comparator(key1, key2) local type1, type2 = type(key1), type(key2) local priority1 = is_in_array_part(key1, length) and 0 or type_priorities[type1] or 8 local priority2 = is_in_array_part(key2, length) and 0 or type_priorities[type2] or 8 if priority1 == priority2 then if type1 == "string" or type1 == "number" then return key1 < key2 elseif type1 == "boolean" then return key1 -- put true before false end else return priority1 < priority2 end end table.sort(keys, key_comparator) return keys, nkeys end local function fmt_table(arg) if type(arg) ~= "table" then return end local tmax = assert:get_parameter("TableFormatLevel") local function ft(t, l) if next(t) == nil then return "{ }" end if l > tmax then return "{ ... more }" end local result = "{" local keys, nkeys = get_sorted_keys(t) for i = 1, nkeys do local k = keys[i] local v = t[k] if type(v) == "table" then v = ft(v, l + 1) elseif type(v) == "string" then v = "'"..v.."'" end result = result .. string.format("\n" .. string.rep(" ",l * 2) .. "[%s] = %s", tostring(k), tostring(v)) end return result .. " }" end return "(table): " .. ft(arg, 1) end local function fmt_function(arg) if type(arg) == "function" then local debug_info = debug.getinfo(arg) return string.format("%s @ line %s in %s", tostring(arg), tostring(debug_info.linedefined), tostring(debug_info.source)) end end local function fmt_userdata(arg) if type(arg) == "userdata" then return string.format("(userdata) '%s'", tostring(arg)) end end local function fmt_thread(arg) if type(arg) == "thread" then return string.format("(thread) '%s'", tostring(arg)) end end assert:add_formatter(fmt_string) assert:add_formatter(fmt_number) assert:add_formatter(fmt_boolean) assert:add_formatter(fmt_nil) assert:add_formatter(fmt_table) assert:add_formatter(fmt_function) assert:add_formatter(fmt_userdata) assert:add_formatter(fmt_thread) -- Set default table display depth for table formatter assert:set_parameter("TableFormatLevel", 3)
Refactored table formatting
Refactored table formatting This fixes a number of problems with the old implementation, which used gsub on result to fix up formatting.
Lua
mit
o-lim/luassert,tst2005/lua-luassert,ZyX-I/luassert,mpeterv/luassert
47fea172a5e5d217fbf3b4627b9bc605e90271df
packages/ruby.lua
packages/ruby.lua
SILE.registerCommand("ruby", function (o,c) local reading = SU.required(o, "reading", "\\ruby") SILE.call("hbox", {}, function() SILE.settings.temporarily(function () SILE.call("noindent") SILE.call("font", {size = "0.6zw", weight = 800 }) SILE.typesetter:typeset(reading) end) end) local rubybox = SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] rubybox.outputYourself = function (self, typesetter, line) local ox = typesetter.frame.state.cursorX typesetter.frame.state.cursorX = typesetter.frame.state.cursorX + rubybox.width.length / 2 typesetter.frame:advancePageDirection(-SILE.toPoints("0.8zw")) SILE.outputter.moveTo(typesetter.frame.state.cursorX, typesetter.frame.state.cursorY) for i = 1, #(self.value) do local node = self.value[i] node:outputYourself(typesetter, line) end typesetter.frame.state.cursorX = ox typesetter.frame:advancePageDirection(SILE.toPoints("0.8zw")) end -- measure the content SILE.call("hbox", {}, c) cbox = SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] local measure if SILE.typesetter.frame:writingDirection() == "LTR" then measure = "width" else measure = "height" end if cbox[measure] > rubybox[measure] then rubybox[measure] = cbox[measure] - rubybox[measure] else local diff = rubybox[measure] - cbox[measure] if type(diff) == "table" then diff = diff.length end local to_insert = SILE.length.new({length = diff / 2, }) cbox[measure] = rubybox[measure] rubybox.width = SILE.length.zero -- add spaces at beginning and end table.insert(cbox.value, 1, SILE.nodefactory.newGlue({ width = to_insert })) table.insert(cbox.value, SILE.nodefactory.newGlue({ width = to_insert })) end end)
SILE.registerCommand("ruby", function (o,c) local reading = SU.required(o, "reading", "\\ruby") SILE.call("hbox", {}, function() SILE.settings.temporarily(function () SILE.call("noindent") SILE.call("font", {size = "0.6zw", weight = 800 }) SILE.typesetter:typeset(reading) end) end) local rubybox = SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] rubybox.outputYourself = function (self, typesetter, line) local ox = typesetter.frame.state.cursorX local oy = typesetter.frame.state.cursorY typesetter.frame.state.cursorX = typesetter.frame.state.cursorX + rubybox.width typesetter.frame:advancePageDirection(-SILE.toPoints("1zw")) SILE.outputter.moveTo(typesetter.frame.state.cursorX, typesetter.frame.state.cursorY) for i = 1, #(self.value) do local node = self.value[i] node:outputYourself(typesetter, line) end typesetter.frame.state.cursorX = ox typesetter.frame.state.cursorY = oy end -- measure the content SILE.call("hbox", {}, c) cbox = SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] SU.debug("ruby", "base box is "..cbox) SU.debug("ruby", "reading is "..rubybox) if cbox:lineContribution() > rubybox:lineContribution() then SU.debug("ruby", "Base is longer, offsetting ruby to fit") -- This is actually the offset against the base rubybox.width = SILE.length.make(cbox:lineContribution() - rubybox:lineContribution()).length else local diff = rubybox:lineContribution() - cbox:lineContribution() if type(diff) == "table" then diff = diff.length end local to_insert = SILE.length.new({length = diff / 2, }) SU.debug("ruby", "Ruby is longer, inserting " ..to_insert.." either side of base") cbox.width = SILE.length.make(rubybox:lineContribution()) rubybox.width = 0 -- add spaces at beginning and end table.insert(cbox.value, 1, SILE.nodefactory.newGlue({ width = to_insert })) table.insert(cbox.value, SILE.nodefactory.newGlue({ width = to_insert })) end end)
This is tidier but there is still a bug (#245) measuring the width of hboxes in TTB mode.
This is tidier but there is still a bug (#245) measuring the width of hboxes in TTB mode.
Lua
mit
simoncozens/sile,simoncozens/sile,simoncozens/sile,alerque/sile,neofob/sile,neofob/sile,alerque/sile,alerque/sile,neofob/sile,simoncozens/sile,alerque/sile,neofob/sile
ecf2b91a0b0538b60fb708a237e10af77afe33dc
misc/freeswitch/scripts/common/sip_account.lua
misc/freeswitch/scripts/common/sip_account.lua
-- Gemeinschaft 5 module: sip account class -- (c) AMOOMA GmbH 2012-2013 -- module(...,package.seeall) SipAccount = {} -- Create SipAccount object function SipAccount.new(self, arg) arg = arg or {} object = arg.object or {} setmetatable(object, self); self.__index = self; self.class = 'sipaccount'; self.log = arg.log; self.database = arg.database; self.record = arg.record; self.domain = arg.domain; return object; end function SipAccount.find_by_sql(self, where) local sql_query = 'SELECT \ `a`.`id`, \ `a`.`uuid`, \ `a`.`auth_name`, \ `a`.`caller_name`, \ `a`.`password`, \ `a`.`voicemail_pin`, \ `a`.`tenant_id`, \ `a`.`sip_domain_id`, \ `a`.`call_waiting`, \ `a`.`clir`, \ `a`.`clip`, \ `a`.`clip_no_screening`, \ `a`.`sip_accountable_type`, \ `a`.`sip_accountable_id`, \ `a`.`hotdeskable`, \ `a`.`gs_node_id`, \ `a`.`language_code`, \ `b`.`host`, \ `c`.`sip_host`, \ `c`.`profile_name` \ FROM `sip_accounts` `a` \ JOIN `sip_domains` `b` ON `a`.`sip_domain_id` = `b`.`id` \ LEFT JOIN `sip_registrations` `c` ON `a`.`auth_name` = `c`.`sip_user` \ WHERE ' .. where .. ' LIMIT 1'; local sip_account = nil; self.database:query(sql_query, function(account_entry) sip_account = SipAccount:new(self); sip_account.record = account_entry; sip_account.id = tonumber(account_entry.id); sip_account.uuid = account_entry.uuid; end) return sip_account; end -- find sip account by id function SipAccount.find_by_id(self, id) local sql_query = '`a`.`id`= ' .. tonumber(id); return self:find_by_sql(sql_query); end -- find sip account by uuid function SipAccount.find_by_uuid(self, uuid) local sql_query = '`a`.`uuid`= "' .. uuid .. '"'; return self:find_by_sql(sql_query); end -- Find SIP Account by auth_name function SipAccount.find_by_auth_name(self, auth_name, domain) local sql_query = '`a`.`auth_name`= "' .. auth_name .. '"'; if domain then sql_query = sql_query .. ' AND `b`.`host` = "' .. domain .. '"'; end return self:find_by_sql(sql_query); end -- retrieve Phone Numbers for SIP Account function SipAccount.phone_numbers(self, id) id = id or self.record.id; if not id then return false; end local sql_query = "SELECT * FROM `phone_numbers` WHERE `phone_numberable_type` = \"SipAccount\" AND `phone_numberable_id`=" .. self.record.id; local phone_numbers = {} self.database:query(sql_query, function(entry) table.insert(phone_numbers,entry.number); end) return phone_numbers; end -- retrieve Ringtone for SIP Account function SipAccount.ringtone(self, id) id = id or self.record.id; if not id then return false; end local sql_query = "SELECT * FROM `ringtones` WHERE `ringtoneable_type` = \"SipAccount\" AND `ringtoneable_id`=" .. self.record.id .. " LIMIT 1"; local ringtone = nil; self.database:query(sql_query, function(entry) ringtone = entry; end) return ringtone; end function SipAccount.send_text(self, text) local event = freeswitch.Event("NOTIFY"); event:addHeader("profile", "gemeinschaft"); event:addHeader("event-string", "text"); event:addHeader("user", self.record.auth_name); event:addHeader("host", self.record.host); event:addHeader("content-type", "text/plain"); event:addBody(text); event:fire(); end function SipAccount.call_state(self) local state = nil local sql_query = "SELECT `callstate` FROM `channels` \ WHERE `name` LIKE (\"\%" .. self.record.auth_name .. "@%\") \ OR `name` LIKE (\"\%" .. self.record.auth_name .. "@%\") LIMIT 1"; self.database:query(sql_query, function(channel_entry) state = channel_entry.callstate; end) return state; end function SipAccount.call_forwarding_on(self, service, destination, destination_type, timeout, source) if not self.call_forwarding then require 'common.call_forwarding'; self.call_forwarding = common.call_forwarding.CallForwarding:new{ log = self.log, database = self.database, parent = self, domain = self.domain }; end return self.call_forwarding:call_forwarding_on(service, destination, destination_type, timeout, source) end function SipAccount.call_forwarding_off(self, service, source, delete) if not self.call_forwarding then require 'common.call_forwarding'; self.call_forwarding = common.call_forwarding.CallForwarding:new{ log = self.log, database = self.database, parent = self, domain = self.domain }; end return self.call_forwarding:call_forwarding_off(service, source, delete) end
-- Gemeinschaft 5 module: sip account class -- (c) AMOOMA GmbH 2012-2013 -- module(...,package.seeall) SipAccount = {} -- Create SipAccount object function SipAccount.new(self, arg) arg = arg or {} object = arg.object or {} setmetatable(object, self); self.__index = self; self.class = 'sipaccount'; self.log = arg.log; self.database = arg.database; self.record = arg.record; self.domain = arg.domain; return object; end function SipAccount.find_by_sql(self, where) local sql_query = 'SELECT \ `a`.`id`, \ `a`.`uuid`, \ `a`.`auth_name`, \ `a`.`caller_name`, \ `a`.`password`, \ `a`.`voicemail_pin`, \ `a`.`tenant_id`, \ `a`.`sip_domain_id`, \ `a`.`call_waiting`, \ `a`.`clir`, \ `a`.`clip`, \ `a`.`clip_no_screening`, \ `a`.`sip_accountable_type`, \ `a`.`sip_accountable_id`, \ `a`.`hotdeskable`, \ `a`.`gs_node_id`, \ `a`.`language_code`, \ `b`.`host`, \ `c`.`sip_host`, \ `c`.`profile_name` \ FROM `sip_accounts` `a` \ JOIN `sip_domains` `b` ON `a`.`sip_domain_id` = `b`.`id` \ LEFT JOIN `sip_registrations` `c` ON `a`.`auth_name` = `c`.`sip_user` \ WHERE ' .. where .. ' LIMIT 1'; local sip_account = nil; self.database:query(sql_query, function(account_entry) sip_account = SipAccount:new(self); sip_account.record = account_entry; sip_account.id = tonumber(account_entry.id); sip_account.uuid = account_entry.uuid; end) return sip_account; end -- find sip account by id function SipAccount.find_by_id(self, id) local sql_query = '`a`.`id`= ' .. tonumber(id); return self:find_by_sql(sql_query); end -- find sip account by uuid function SipAccount.find_by_uuid(self, uuid) local sql_query = '`a`.`uuid`= "' .. uuid .. '"'; return self:find_by_sql(sql_query); end -- Find SIP Account by auth_name function SipAccount.find_by_auth_name(self, auth_name, domain) local sql_query = '`a`.`auth_name`= "' .. auth_name .. '"'; if domain then sql_query = sql_query .. ' AND `b`.`host` = "' .. domain .. '"'; end return self:find_by_sql(sql_query); end -- retrieve Phone Numbers for SIP Account function SipAccount.phone_numbers(self, id) id = id or self.record.id; if not id then return false; end local sql_query = "SELECT * FROM `phone_numbers` WHERE `phone_numberable_type` = \"SipAccount\" AND `phone_numberable_id`=" .. self.record.id; local phone_numbers = {} self.database:query(sql_query, function(entry) table.insert(phone_numbers,entry.number); end) return phone_numbers; end -- retrieve Ringtone for SIP Account function SipAccount.ringtone(self, id) id = id or self.record.id; if not id then return false; end local sql_query = "SELECT * FROM `ringtones` WHERE `ringtoneable_type` = \"SipAccount\" AND `ringtoneable_id`=" .. self.record.id .. " LIMIT 1"; local ringtone = nil; self.database:query(sql_query, function(entry) ringtone = entry; end) return ringtone; end function SipAccount.send_text(self, text) local event = freeswitch.Event("NOTIFY"); event:addHeader("profile", "gemeinschaft"); event:addHeader("event-string", "text"); event:addHeader("user", self.record.auth_name); event:addHeader("host", self.record.host); event:addHeader("content-type", "text/plain"); event:addBody(text); event:fire(); end function SipAccount.call_state(self) local sql_query = 'SELECT `callstate` FROM `detailed_calls` \ WHERE `presence_id` LIKE "' .. self.record.auth_name .. '@%" \ OR `b_presence_id` LIKE "' .. self.record.auth_name .. '@%" \ LIMIT 1'; return self.database:query_return_value(sql_query); end function SipAccount.call_forwarding_on(self, service, destination, destination_type, timeout, source) if not self.call_forwarding then require 'common.call_forwarding'; self.call_forwarding = common.call_forwarding.CallForwarding:new{ log = self.log, database = self.database, parent = self, domain = self.domain }; end return self.call_forwarding:call_forwarding_on(service, destination, destination_type, timeout, source) end function SipAccount.call_forwarding_off(self, service, source, delete) if not self.call_forwarding then require 'common.call_forwarding'; self.call_forwarding = common.call_forwarding.CallForwarding:new{ log = self.log, database = self.database, parent = self, domain = self.domain }; end return self.call_forwarding:call_forwarding_off(service, source, delete) end
call waiting fixed
call waiting fixed
Lua
mit
amooma/GS5,amooma/GS5,funkring/gs5,amooma/GS5,amooma/GS5,funkring/gs5,funkring/gs5,funkring/gs5
f2a7242ef294c46c18a2b4d427411bbd9e321e45
agents/monitoring/tests/helper.lua
agents/monitoring/tests/helper.lua
local spawn = require('childprocess').spawn local constants = require('constants') local misc = require('monitoring/default/util/misc') function runner(name) return spawn('python', {'agents/monitoring/runner.py', name}) end local child local function start_server(callback) local data = '' callback = misc.fireOnce(callback) child = runner('server_fixture_blocking') child.stderr:on('data', function(d) callback(d) end) child.stdout:on('data', function(chunk) data = data .. chunk if data:find('TLS fixture server listening on port 50061') then callback() end end) return child end local function stop_server(child) if not child then return end child:kill(constants.SIGUSR1) -- USR1 end process:on('exit', function() stop_server(child) end) local exports = {} exports.runner = runner exports.start_server = start_server exports.stop_server = stop_server return exports
local spawn = require('childprocess').spawn local constants = require('constants') local misc = require('monitoring/default/util/misc') function runner(name) return spawn('python', {'agents/monitoring/runner.py', name}) end local child local function start_server(callback) local data = '' callback = misc.fireOnce(callback) child = runner('server_fixture_blocking') child.stderr:on('data', function(d) callback(d) end) child.stdout:on('data', function(chunk) data = data .. chunk if data:find('TLS fixture server listening on port 50061') then callback() end end) return child end local function stop_server(child) if not child then return end child:kill(constants.SIGUSR1) -- USR1 end process:on('exit', function() stop_server(child) end) process:on("error", function(e) stop_server(child) end) local exports = {} exports.runner = runner exports.start_server = start_server exports.stop_server = stop_server return exports
Kill the fixture server always.
Kill the fixture server always. As simple as process:on('error'). This will make tests go better.
Lua
apache-2.0
virgo-agent-toolkit/rackspace-monitoring-agent,cp16net/virgo-base,virgo-agent-toolkit/rackspace-monitoring-agent,cp16net/virgo-base,AlphaStaxLLC/rackspace-monitoring-agent,cp16net/virgo-base,christopherjwang/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,cp16net/virgo-base,kaustavha/rackspace-monitoring-agent,cp16net/virgo-base,AlphaStaxLLC/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent
cc8a562413a0a77827c66ec95e70ef4f02bf75db
src_trunk/resources/global/money_globals.lua
src_trunk/resources/global/money_globals.lua
--TAX tax = 15 -- percent function randomizeTax() tax = math.random(5, 30) end setTimer(randomizeTax, 3600000, 0) randomizeTax() function getTaxAmount() return (tax/100) end --INCOME TAX tax = 10 -- percent function randomizeIncomeTax() tax = math.random(1, 25) end setTimer(randomizeIncomeTax, 3600000, 0) randomizeIncomeTax() function getIncomeTaxAmount() return (tax/100) end function givePlayerSafeMoney(thePlayer, amount) if (tonumber(amount)>0) then local money = getElementData(thePlayer, "money") checkMoneyHacks(thePlayer) setElementData(thePlayer, "money", money+tonumber(amount)) givePlayerMoney(thePlayer, tonumber(amount)) end end function takePlayerSafeMoney(thePlayer, amount) if (tonumber(amount)>0) then local money = getElementData(thePlayer, "money") if (amount>=money) then amount = money end checkMoneyHacks(thePlayer) setElementData(thePlayer, "money", money-amount) takePlayerMoney(thePlayer, tonumber(amount)) end end function setPlayerSafeMoney(thePlayer, amount) if (tonumber(amount)>=0) then local money = getElementData(thePlayer, "money") checkMoneyHacks(thePlayer) setElementData(thePlayer, "money", tonumber(amount)) setPlayerMoney(thePlayer, tonumber(amount)) end end function checkMoneyHacks(thePlayer) if not getElementData(thePlayer, "money") then return end local safemoney = tonumber(getElementData(thePlayer, "money")) local hackmoney = getPlayerMoney(thePlayer) if (safemoney~=hackmoney) then --banPlayer(thePlayer, getRootElement(), "Money Hacks: " .. hackmoney .. "$.") setPlayerMoney(thePlayer, safemoney) sendMessageToAdmins("Possible money hack detected: "..getPlayerName(thePlayer)) return true else return false end end
--TAX tax = 15 -- percent function randomizeTax() tax = math.random(5, 30) end setTimer(randomizeTax, 3600000, 0) randomizeTax() function getTaxAmount() return (tax/100) end --INCOME TAX tax = 10 -- percent function randomizeIncomeTax() tax = math.random(1, 25) end setTimer(randomizeIncomeTax, 3600000, 0) randomizeIncomeTax() function getIncomeTaxAmount() return (tax/100) end function givePlayerSafeMoney(thePlayer, amount) if (tonumber(amount)>0) then amount = math.floor( amount ) local money = getElementData(thePlayer, "money") checkMoneyHacks(thePlayer) setElementData(thePlayer, "money", money+tonumber(amount)) givePlayerMoney(thePlayer, tonumber(amount)) end end function takePlayerSafeMoney(thePlayer, amount) if (tonumber(amount)>0) then amount = math.ceil( amount ) local money = getElementData(thePlayer, "money") if (amount>=money) then amount = money end checkMoneyHacks(thePlayer) setElementData(thePlayer, "money", money-amount) takePlayerMoney(thePlayer, tonumber(amount)) end end function setPlayerSafeMoney(thePlayer, amount) if (tonumber(amount)>=0) then amount = math.ceil( amount ) local money = getElementData(thePlayer, "money") checkMoneyHacks(thePlayer) setElementData(thePlayer, "money", tonumber(amount)) setPlayerMoney(thePlayer, tonumber(amount)) end end function checkMoneyHacks(thePlayer) if not getElementData(thePlayer, "money") then return end local safemoney = tonumber(getElementData(thePlayer, "money")) local hackmoney = getPlayerMoney(thePlayer) if (safemoney~=hackmoney) then --banPlayer(thePlayer, getRootElement(), "Money Hacks: " .. hackmoney .. "$.") setPlayerMoney(thePlayer, safemoney) sendMessageToAdmins("Possible money hack detected: "..getPlayerName(thePlayer)) return true else return false end end
money fix
money fix git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1674 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
adfd78e69146657566f18fa8815ff0028b1f4e21
ffi/framebuffer_SDL1_2.lua
ffi/framebuffer_SDL1_2.lua
local ffi = require("ffi") local bit = require("bit") -- load common SDL input/video library local SDL = require("ffi/SDL1_2") local BB = require("ffi/blitbuffer") local fb = {} function fb.open() if not fb.dummy then SDL.open() -- we present this buffer to the outside fb.bb = BB.new(SDL.screen.w, SDL.screen.h) else fb.bb = BB.new(600, 800) end fb.real_bb = BB.new(SDL.screen.w, SDL.screen.h, BB.TYPE_BBRGB32, SDL.screen.pixels, SDL.screen.pitch) fb.real_bb:invert() fb:refresh() return fb end function fb:getSize() return self.bb.w, self.bb.h end function fb:getPitch() return self.bb.pitch end function fb:setOrientation(mode) if mode == 1 or mode == 3 then -- TODO: landscape setting else -- TODO: flip back to portrait end end function fb:getOrientation() if SDL.screen.w > SDL.screen.h then return 1 else return 0 end end function fb:refresh(refreshtype, waveform_mode, x1, y1, w, h) if x1 == nil then x1 = 0 end if y1 == nil then y1 = 0 end -- adapt to possible rotation changes self.real_bb:setRotation(self.bb:getRotation()) if SDL.SDL.SDL_LockSurface(SDL.screen) < 0 then error("Locking screen surface") end self.real_bb:blitFrom(self.bb, x1, y1, x1, y1, w, h) SDL.SDL.SDL_UnlockSurface(SDL.screen) SDL.SDL.SDL_Flip(SDL.screen) end function fb:close() -- for now, we do nothing when in emulator mode end return fb
local ffi = require("ffi") local bit = require("bit") -- load common SDL input/video library local SDL = require("ffi/SDL1_2") local BB = require("ffi/blitbuffer") local fb = {} function fb.open() if not fb.dummy then SDL.open() -- we present this buffer to the outside fb.bb = BB.new(SDL.screen.w, SDL.screen.h) fb.real_bb = BB.new(SDL.screen.w, SDL.screen.h, BB.TYPE_BBRGB32, SDL.screen.pixels, SDL.screen.pitch) else fb.bb = BB.new(600, 800) fb.real_bb = BB.new(600, 800) end fb.real_bb:invert() fb:refresh() return fb end function fb:getSize() return self.bb.w, self.bb.h end function fb:getPitch() return self.bb.pitch end function fb:setOrientation(mode) if mode == 1 or mode == 3 then -- TODO: landscape setting else -- TODO: flip back to portrait end end function fb:getOrientation() if SDL.screen.w > SDL.screen.h then return 1 else return 0 end end function fb:refresh(refreshtype, waveform_mode, x1, y1, w, h) if x1 == nil then x1 = 0 end if y1 == nil then y1 = 0 end -- adapt to possible rotation changes self.real_bb:setRotation(self.bb:getRotation()) if SDL.SDL.SDL_LockSurface(SDL.screen) < 0 then error("Locking screen surface") end self.real_bb:blitFrom(self.bb, x1, y1, x1, y1, w, h) SDL.SDL.SDL_UnlockSurface(SDL.screen) SDL.SDL.SDL_Flip(SDL.screen) end function fb:close() -- for now, we do nothing when in emulator mode end return fb
fix test frontend in travis
fix test frontend in travis
Lua
agpl-3.0
NiLuJe/koreader-base,houqp/koreader-base,Frenzie/koreader-base,NiLuJe/koreader-base,Hzj-jie/koreader-base,NiLuJe/koreader-base,koreader/koreader-base,NiLuJe/koreader-base,Hzj-jie/koreader-base,apletnev/koreader-base,houqp/koreader-base,Frenzie/koreader-base,Hzj-jie/koreader-base,Frenzie/koreader-base,Hzj-jie/koreader-base,frankyifei/koreader-base,apletnev/koreader-base,apletnev/koreader-base,frankyifei/koreader-base,koreader/koreader-base,houqp/koreader-base,frankyifei/koreader-base,koreader/koreader-base,frankyifei/koreader-base,Frenzie/koreader-base,koreader/koreader-base,apletnev/koreader-base,houqp/koreader-base
b2e0ed4f7920ec9e73829c464740db1db306f4b9
share/lua/website/xhamster.lua
share/lua/website/xhamster.lua
-- libquvi-scripts -- Copyright (C) 2010 Paul Kocialkowski <[email protected]> -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -- 02110-1301 USA -- -- Identify the script. function ident (self) package.path = self.script_dir .. '/?.lua' local C = require 'quvi/const' local r = {} r.domain = "xhamster%.com" r.formats = "default" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/movies/%d+/"}) return r end -- Query available formats. function query_formats(self) self.formats = 'default' return self end -- Parse media URL. function parse (self) self.host_id = "xhamster" local page = quvi.fetch(self.page_url) local _,_,s = page:find('class="mTitle">.+<h1>(.-)<') self.title = s or error ("no match: media title") local _,_,s = self.page_url:find("/movies/(.-)/") self.id = s or error ("no match: media id") local _,_,s = page:find("'srv': '(.-)'") local srv = s or error ("no match: server") local _,_,s = page:find("'file': '(.-)'") local file = s or error ("no match: file") self.url = {srv.."/flv2/"..file} return self end -- vim: set ts=4 sw=4 tw=72 expandtab:
-- libquvi-scripts -- Copyright (C) 2010 Paul Kocialkowski <[email protected]> -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -- 02110-1301 USA -- -- Identify the script. function ident (self) package.path = self.script_dir .. '/?.lua' local C = require 'quvi/const' local r = {} r.domain = "xhamster%.com" r.formats = "default" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/movies/%d+/"}) return r end -- Query available formats. function query_formats(self) self.formats = 'default' return self end -- Parse media URL. function parse (self) self.host_id = "xhamster" local page = quvi.fetch(self.page_url) self.title = page:match('class="mTitle">.-<h1?.>(.-)</h1>') or error("no match: media title") local _,_,s = self.page_url:find("/movies/(.-)/") self.id = s or error ("no match: media id") local _,_,s = page:find("'srv': '(.-)'") local srv = s or error ("no match: server") local _,_,s = page:find("'file': '(.-)'") local file = s or error ("no match: file") self.url = {srv.."/flv2/"..file} return self end -- vim: set ts=4 sw=4 tw=72 expandtab:
Fix xhamster.lua title parsing
Fix xhamster.lua title parsing
Lua
agpl-3.0
alech/libquvi-scripts,DangerCove/libquvi-scripts,legatvs/libquvi-scripts,hadess/libquvi-scripts-iplayer,hadess/libquvi-scripts-iplayer,DangerCove/libquvi-scripts,alech/libquvi-scripts,legatvs/libquvi-scripts
d9c87649f34382ade7257444edee935686bd7861
scripts/embed.lua
scripts/embed.lua
-- -- Embed the Lua scripts into src/host/scripts.c as static data buffers. -- I embed the actual scripts, rather than Lua bytecodes, because the -- bytecodes are not portable to different architectures, which causes -- issues in Mac OS X Universal builds. -- local function loadScript(fname) local f = io.open(fname) local s = assert(f:read("*a")) f:close() -- strip tabs s = s:gsub("[\t]", "") -- strip any CRs s = s:gsub("[\r]", "") -- strip out block comments s = s:gsub("[^\"']%-%-%[%[.-%]%]", "") s = s:gsub("[^\"']%-%-%[=%[.-%]=%]", "") s = s:gsub("[^\"']%-%-%[==%[.-%]==%]", "") -- strip out inline comments s = s:gsub("\n%-%-[^\n]*", "\n") -- escape backslashes s = s:gsub("\\", "\\\\") -- strip duplicate line feeds s = s:gsub("\n+", "\n") -- strip out leading comments s = s:gsub("^%-%-[^\n]*\n", "") -- escape line feeds s = s:gsub("\n", "\\n") -- escape double quote marks s = s:gsub("\"", "\\\"") return s end local function appendScript(result, contents) -- break up large strings to fit in Visual Studio's string length limit local max = 4096 local start = 1 local len = contents:len() while start <= len do local n = len - start if n > max then n = max end local finish = start + n -- make sure I don't cut an escape sequence while contents:sub(finish, finish) == "\\" do finish = finish - 1 end local s = contents:sub(start, finish) table.insert(result, "\t\"" .. s .. iif(finish < len, '"', '",')) start = finish + 1 end table.insert(result, "") end -- Prepare the file header local result = {} table.insert(result, "/* Premake's Lua scripts, as static data buffers for release mode builds */") table.insert(result, "/* DO NOT EDIT - this file is autogenerated - see BUILD.txt */") table.insert(result, "/* To regenerate this file, run: premake5 embed */") table.insert(result, "") table.insert(result, '#include "premake.h"') table.insert(result, "") -- Find all of the _manifest.lua files within the project local mask = path.join(_MAIN_SCRIPT_DIR, "**/_manifest.lua") local manifests = os.matchfiles(mask) -- Generate an index of the script file names. Script names are stored -- relative to the directory containing the manifest, i.e. the main -- Xcode script, which is at $/modules/xcode/xcode.lua is stored as -- "xcode/xcode.lua". Core scripts currently get special treatment and -- are stored as "base/os.lua" instead of "core/base/os.lua"; I would -- like to treat core like just another module eventually. table.insert(result, "const char* builtin_scripts_index[] = {") for mi = 1, #manifests do local manifestName = manifests[mi] local manifestDir = path.getdirectory(manifestName) local baseDir = path.getdirectory(manifestDir) local files = dofile(manifests[mi]) for fi = 1, #files do local filename = path.join(manifestDir, files[fi]) filename = path.getrelative(baseDir, filename) -- core files fix-up for backward compatibility if filename:startswith("src/") then filename = filename:sub(5) end table.insert(result, '\t"' .. filename .. '",') end end table.insert(result, "\tNULL") table.insert(result, "};") table.insert(result, "") -- Embed the actual script contents table.insert(result, "const char* builtin_scripts[] = {") for mi = 1, #manifests do local manifestName = manifests[mi] local manifestDir = path.getdirectory(manifestName) local files = dofile(manifests[mi]) for fi = 1, #files do local filename = path.join(manifestDir, files[fi]) local scr = loadScript(filename) appendScript(result, scr) end end table.insert(result, "\tNULL") table.insert(result, "};") table.insert(result, "") -- Write it all out. Check against the current contents of scripts.c first, -- and only overwrite it if there are actual changes. result = table.concat(result, "\n") local scriptsFile = path.getabsolute(path.join(_SCRIPT_DIR, "../src/host/scripts.c")) local oldVersion local file = io.open(scriptsFile, "r") if file then oldVersion = file:read("*a") file:close() end if oldVersion ~= result then print("Writing scripts.c") file = io.open(scriptsFile, "w+b") file:write(result) file:close() end
-- -- Embed the Lua scripts into src/host/scripts.c as static data buffers. -- I embed the actual scripts, rather than Lua bytecodes, because the -- bytecodes are not portable to different architectures, which causes -- issues in Mac OS X Universal builds. -- local function loadScript(fname) local f = io.open(fname) local s = assert(f:read("*a")) f:close() -- strip tabs s = s:gsub("[\t]", "") -- strip any CRs s = s:gsub("[\r]", "") -- strip out block comments s = s:gsub("[^\"']%-%-%[%[.-%]%]", "") s = s:gsub("[^\"']%-%-%[=%[.-%]=%]", "") s = s:gsub("[^\"']%-%-%[==%[.-%]==%]", "") -- strip out inline comments s = s:gsub("\n%-%-[^\n]*", "\n") -- escape backslashes s = s:gsub("\\", "\\\\") -- strip duplicate line feeds s = s:gsub("\n+", "\n") -- strip out leading comments s = s:gsub("^%-%-[^\n]*\n", "") -- escape line feeds s = s:gsub("\n", "\\n") -- escape double quote marks s = s:gsub("\"", "\\\"") return s end local function appendScript(result, contents) -- break up large strings to fit in Visual Studio's string length limit local max = 4096 local start = 1 local len = contents:len() while start <= len do local n = len - start if n > max then n = max end local finish = start + n -- make sure I don't cut an escape sequence while contents:sub(finish, finish) == "\\" do finish = finish - 1 end local s = contents:sub(start, finish) table.insert(result, "\t\"" .. s .. iif(finish < len, '"', '",')) start = finish + 1 end table.insert(result, "") end -- Prepare the file header local result = {} table.insert(result, "/* Premake's Lua scripts, as static data buffers for release mode builds */") table.insert(result, "/* DO NOT EDIT - this file is autogenerated - see BUILD.txt */") table.insert(result, "/* To regenerate this file, run: premake5 embed */") table.insert(result, "") table.insert(result, '#include "premake.h"') table.insert(result, "") -- Find all of the _manifest.lua files within the project local mask = path.join(_MAIN_SCRIPT_DIR, "**/_manifest.lua") local manifests = os.matchfiles(mask) -- Generate an index of the script file names. Script names are stored -- relative to the directory containing the manifest, i.e. the main -- Xcode script, which is at $/modules/xcode/xcode.lua is stored as -- "xcode/xcode.lua". Core scripts currently get special treatment and -- are stored as "base/os.lua" instead of "core/base/os.lua"; I would -- like to treat core like just another module eventually. table.insert(result, "const char* builtin_scripts_index[] = {") for mi = 1, #manifests do local manifestName = manifests[mi] local manifestDir = path.getdirectory(manifestName) local baseDir = path.getdirectory(manifestDir) local files = dofile(manifests[mi]) for fi = 1, #files do local filename = path.join(manifestDir, files[fi]) filename = path.getrelative(baseDir, filename) -- core files fix-up for backward compatibility if filename:startswith("src/") then filename = filename:sub(5) end table.insert(result, '\t"' .. filename .. '",') end end table.insert(result, '\t"_premake_main.lua",') table.insert(result, '\t"_manifest.lua",') table.insert(result, "\tNULL") table.insert(result, "};") table.insert(result, "") -- Embed the actual script contents table.insert(result, "const char* builtin_scripts[] = {") for mi = 1, #manifests do local manifestName = manifests[mi] local manifestDir = path.getdirectory(manifestName) local files = dofile(manifests[mi]) for fi = 1, #files do local filename = path.join(manifestDir, files[fi]) local scr = loadScript(filename) appendScript(result, scr) end end appendScript(result, loadScript(path.join(_SCRIPT_DIR, "../src/_premake_main.lua"))) appendScript(result, loadScript(path.join(_SCRIPT_DIR, "../src/_manifest.lua"))) table.insert(result, "\tNULL") table.insert(result, "};") table.insert(result, "") -- Write it all out. Check against the current contents of scripts.c first, -- and only overwrite it if there are actual changes. result = table.concat(result, "\n") local scriptsFile = path.getabsolute(path.join(_SCRIPT_DIR, "../src/host/scripts.c")) local oldVersion local file = io.open(scriptsFile, "r") if file then oldVersion = file:read("*a") file:close() end if oldVersion ~= result then print("Writing scripts.c") file = io.open(scriptsFile, "w+b") file:write(result) file:close() end
Fix embedding of main script and manifest
Fix embedding of main script and manifest
Lua
bsd-3-clause
TurkeyMan/premake-core,premake/premake-core,saberhawk/premake-core,felipeprov/premake-core,dcourtois/premake-core,kankaristo/premake-core,starkos/premake-core,premake/premake-core,resetnow/premake-core,felipeprov/premake-core,mendsley/premake-core,dcourtois/premake-core,saberhawk/premake-core,CodeAnxiety/premake-core,jstewart-amd/premake-core,tvandijck/premake-core,jstewart-amd/premake-core,resetnow/premake-core,alarouche/premake-core,CodeAnxiety/premake-core,mandersan/premake-core,mandersan/premake-core,resetnow/premake-core,sleepingwit/premake-core,lizh06/premake-core,Blizzard/premake-core,noresources/premake-core,sleepingwit/premake-core,PlexChat/premake-core,felipeprov/premake-core,lizh06/premake-core,grbd/premake-core,jsfdez/premake-core,grbd/premake-core,xriss/premake-core,martin-traverse/premake-core,Meoo/premake-core,prapin/premake-core,martin-traverse/premake-core,grbd/premake-core,noresources/premake-core,prapin/premake-core,LORgames/premake-core,jstewart-amd/premake-core,resetnow/premake-core,Tiger66639/premake-core,starkos/premake-core,tvandijck/premake-core,tritao/premake-core,alarouche/premake-core,Tiger66639/premake-core,bravnsgaard/premake-core,LORgames/premake-core,sleepingwit/premake-core,akaStiX/premake-core,CodeAnxiety/premake-core,xriss/premake-core,noresources/premake-core,sleepingwit/premake-core,aleksijuvani/premake-core,CodeAnxiety/premake-core,felipeprov/premake-core,akaStiX/premake-core,TurkeyMan/premake-core,aleksijuvani/premake-core,starkos/premake-core,Blizzard/premake-core,aleksijuvani/premake-core,PlexChat/premake-core,mendsley/premake-core,dcourtois/premake-core,resetnow/premake-core,kankaristo/premake-core,Zefiros-Software/premake-core,Blizzard/premake-core,dcourtois/premake-core,sleepingwit/premake-core,jsfdez/premake-core,TurkeyMan/premake-core,bravnsgaard/premake-core,saberhawk/premake-core,Tiger66639/premake-core,jstewart-amd/premake-core,tvandijck/premake-core,mendsley/premake-core,aleksijuvani/premake-core,mandersan/premake-core,PlexChat/premake-core,Yhgenomics/premake-core,LORgames/premake-core,Zefiros-Software/premake-core,dcourtois/premake-core,kankaristo/premake-core,dcourtois/premake-core,xriss/premake-core,lizh06/premake-core,kankaristo/premake-core,noresources/premake-core,starkos/premake-core,Meoo/premake-core,noresources/premake-core,premake/premake-core,starkos/premake-core,alarouche/premake-core,soundsrc/premake-core,grbd/premake-core,Meoo/premake-core,Yhgenomics/premake-core,Zefiros-Software/premake-core,LORgames/premake-core,starkos/premake-core,bravnsgaard/premake-core,premake/premake-core,premake/premake-core,jsfdez/premake-core,PlexChat/premake-core,Yhgenomics/premake-core,Meoo/premake-core,mendsley/premake-core,starkos/premake-core,tvandijck/premake-core,tvandijck/premake-core,LORgames/premake-core,TurkeyMan/premake-core,Blizzard/premake-core,tritao/premake-core,saberhawk/premake-core,dcourtois/premake-core,soundsrc/premake-core,xriss/premake-core,akaStiX/premake-core,Yhgenomics/premake-core,premake/premake-core,soundsrc/premake-core,bravnsgaard/premake-core,aleksijuvani/premake-core,xriss/premake-core,Zefiros-Software/premake-core,alarouche/premake-core,mendsley/premake-core,mandersan/premake-core,martin-traverse/premake-core,akaStiX/premake-core,soundsrc/premake-core,jsfdez/premake-core,tritao/premake-core,jstewart-amd/premake-core,soundsrc/premake-core,tritao/premake-core,lizh06/premake-core,Zefiros-Software/premake-core,Tiger66639/premake-core,Blizzard/premake-core,martin-traverse/premake-core,Blizzard/premake-core,CodeAnxiety/premake-core,bravnsgaard/premake-core,noresources/premake-core,premake/premake-core,prapin/premake-core,mandersan/premake-core,prapin/premake-core,noresources/premake-core,TurkeyMan/premake-core
4295e9ca1a6738bdb4bbaa52010724d585140c6a
core/libtexpdf-output.lua
core/libtexpdf-output.lua
local pdf = require("justenoughlibtexpdf") if (not SILE.outputters) then SILE.outputters = {} end local cursorX = 0 local cursorY = 0 local font = 0 local started = false local function ensureInit () if not started then pdf.init(SILE.outputFilename, SILE.documentState.paperSize[1],SILE.documentState.paperSize[2]) pdf.beginpage() started = true end end SILE.outputters.libtexpdf = { init = function() -- We don't do anything yet because this commits us to a page size. end, _init = ensureInit, newPage = function() ensureInit() pdf.endpage() pdf.beginpage() end, finish = function() if not started then return end pdf.endpage() pdf.finish() end, setColor = function(self, color) ensureInit() pdf.setcolor(color.r, color.g, color.b) end, pushColor = function (self, color) ensureInit() pdf.colorpush(color.r, color.g, color.b) end, popColor = function (self) ensureInit() pdf.colorpop() end, outputHbox = function (value,w) ensureInit() if not value.glyphString then return end -- Nodes which require kerning or have offsets to the glyph -- position should be output a glyph at a time. We pass the -- glyph advance from the htmx table, so that libtexpdf knows -- how wide each glyph is. It uses this to then compute the -- relative position between the pen after the glyph has been -- painted (cursorX + glyphAdvance) and the next painting -- position (cursorX + width - remember that the box's "width" -- is actually the shaped x_advance). if value.complex then for i=1,#(value.items) do local glyph = value.items[i].gid local buf = string.char(math.floor(glyph % 2^32 / 2^8)) .. string.char(glyph % 0x100) pdf.setstring(cursorX + (value.items[i].x_offset or 0), cursorY + (value.items[i].y_offset or 0), buf, string.len(buf), font, value.items[i].glyphAdvance) cursorX = cursorX + value.items[i].width end return end local buf = {} for i=1,#(value.glyphString) do glyph = value.glyphString[i] buf[#buf+1] = string.char(math.floor(glyph % 2^32 / 2^8)) buf[#buf+1] = string.char(glyph % 0x100) end buf = table.concat(buf, "") pdf.setstring(cursorX, cursorY, buf, string.len(buf), font, w) end, setFont = function (options) ensureInit() if SILE.font._key(options) == lastkey then return end lastkey = SILE.font._key(options) font = SILE.font.cache(options, SILE.shaper.getFace) if options.direction == "TTB" then font.layout_dir = 1 end if SILE.typesetter.frame and SILE.typesetter.frame:writingDirection() == "TTB" then pdf.setdirmode(1) else pdf.setdirmode(0) end f = pdf.loadfont(font) if f< 0 then SU.error("Font loading error for "..options) end font = f end, drawImage = function (src, x,y,w,h) ensureInit() pdf.drawimage(src, x, y, w, h) end, imageSize = function (src) ensureInit() -- in case it's a PDF file local llx, lly, urx, ury = pdf.imagebbox(src) return (urx-llx), (ury-lly) end, moveTo = function (x,y) cursorX = x cursorY = SILE.documentState.paperSize[2] - y end, rule = function (x,y,w,d) ensureInit() pdf.setrule(x,SILE.documentState.paperSize[2] -y-d,w,d) end, debugFrame = function (self,f) ensureInit() pdf.colorpush(0.8,0,0) self.rule(f:left(), f:top(), f:width(), 0.5) self.rule(f:left(), f:top(), 0.5, f:height()) self.rule(f:right(), f:top(), 0.5, f:height()) self.rule(f:left(), f:bottom(), f:width(), 0.5) --self.rule(f:left() + f:width()/2 - 5, (f:top() + f:bottom())/2+5, 10, 10) local stuff = SILE.shaper:createNnodes(f.id, SILE.font.loadDefaults({})) stuff = stuff[1].nodes[1].value.glyphString -- Horrible hack local buf = {} for i=1,#stuff do glyph = stuff[i] buf[#buf+1] = string.char(math.floor(glyph % 2^32 / 2^8)) buf[#buf+1] = string.char(glyph % 0x100) end buf = table.concat(buf, "") if font == 0 then SILE.outputter.setFont(SILE.font.loadDefaults({})) end pdf.setstring(f:left(), SILE.documentState.paperSize[2] -f:top(), buf, string.len(buf), font, 0) pdf.colorpop() end, debugHbox = function(typesetter, hbox, scaledWidth) end } SILE.outputter = SILE.outputters.libtexpdf
local pdf = require("justenoughlibtexpdf") if (not SILE.outputters) then SILE.outputters = {} end local cursorX = 0 local cursorY = 0 local font = 0 local started = false local function ensureInit () if not started then pdf.init(SILE.outputFilename, SILE.documentState.paperSize[1],SILE.documentState.paperSize[2]) pdf.beginpage() started = true end end SILE.outputters.libtexpdf = { init = function() -- We don't do anything yet because this commits us to a page size. end, _init = ensureInit, newPage = function() ensureInit() pdf.endpage() pdf.beginpage() end, finish = function() if not started then return end pdf.endpage() pdf.finish() end, setColor = function(self, color) ensureInit() pdf.setcolor(color.r, color.g, color.b) end, pushColor = function (self, color) ensureInit() pdf.colorpush(color.r, color.g, color.b) end, popColor = function (self) ensureInit() pdf.colorpop() end, outputHbox = function (value,w) ensureInit() if not value.glyphString then return end -- Nodes which require kerning or have offsets to the glyph -- position should be output a glyph at a time. We pass the -- glyph advance from the htmx table, so that libtexpdf knows -- how wide each glyph is. It uses this to then compute the -- relative position between the pen after the glyph has been -- painted (cursorX + glyphAdvance) and the next painting -- position (cursorX + width - remember that the box's "width" -- is actually the shaped x_advance). if value.complex then for i=1,#(value.items) do local glyph = value.items[i].gid local buf = string.char(math.floor(glyph % 2^32 / 2^8)) .. string.char(glyph % 0x100) pdf.setstring(cursorX + (value.items[i].x_offset or 0), cursorY + (value.items[i].y_offset or 0), buf, string.len(buf), font, value.items[i].glyphAdvance) cursorX = cursorX + value.items[i].width end return end local buf = {} for i=1,#(value.glyphString) do glyph = value.glyphString[i] buf[#buf+1] = string.char(math.floor(glyph % 2^32 / 2^8)) buf[#buf+1] = string.char(glyph % 0x100) end buf = table.concat(buf, "") pdf.setstring(cursorX, cursorY, buf, string.len(buf), font, w) end, setFont = function (options) ensureInit() if SILE.font._key(options) == lastkey then return end lastkey = SILE.font._key(options) font = SILE.font.cache(options, SILE.shaper.getFace) if options.direction == "TTB" then font.layout_dir = 1 end if SILE.typesetter.frame and SILE.typesetter.frame:writingDirection() == "TTB" then pdf.setdirmode(1) else pdf.setdirmode(0) end f = pdf.loadfont(font) if f< 0 then SU.error("Font loading error for "..options) end font = f end, drawImage = function (src, x,y,w,h) ensureInit() pdf.drawimage(src, x, y, w, h) end, imageSize = function (src) ensureInit() -- in case it's a PDF file local llx, lly, urx, ury = pdf.imagebbox(src) return (urx-llx), (ury-lly) end, moveTo = function (x,y) cursorX = x cursorY = SILE.documentState.paperSize[2] - y end, rule = function (x,y,w,d) ensureInit() pdf.setrule(x,SILE.documentState.paperSize[2] -y-d,w,d) end, debugFrame = function (self,f) ensureInit() pdf.colorpush(0.8,0,0) self.rule(f:left(), f:top(), f:width(), 0.5) self.rule(f:left(), f:top(), 0.5, f:height()) self.rule(f:right(), f:top(), 0.5, f:height()) self.rule(f:left(), f:bottom(), f:width(), 0.5) --self.rule(f:left() + f:width()/2 - 5, (f:top() + f:bottom())/2+5, 10, 10) local oldfont = font SILE.outputter.setFont(SILE.font.loadDefaults({})) local stuff = SILE.shaper:createNnodes(f.id, SILE.font.loadDefaults({})) stuff = stuff[1].nodes[1].value.glyphString -- Horrible hack local buf = {} for i=1,#stuff do glyph = stuff[i] buf[#buf+1] = string.char(math.floor(glyph % 2^32 / 2^8)) buf[#buf+1] = string.char(glyph % 0x100) end buf = table.concat(buf, "") pdf.setstring(f:left(), SILE.documentState.paperSize[2] -f:top(), buf, string.len(buf), font, 0) pdf.colorpop() font = oldfont end, debugHbox = function(typesetter, hbox, scaledWidth) end } SILE.outputter = SILE.outputters.libtexpdf
Possible fix for #384
Possible fix for #384
Lua
mit
simoncozens/sile,neofob/sile,neofob/sile,alerque/sile,alerque/sile,simoncozens/sile,simoncozens/sile,neofob/sile,alerque/sile,simoncozens/sile,alerque/sile,neofob/sile
2dcacfcc1292fba9d876a7ee0c8a08d930c364ff
pkg/torch/argtypes.lua
pkg/torch/argtypes.lua
torch.argtypes = {} torch.argtypes["numbers"] = { vararg = true, -- if needed, one can override it to false check = function(self) local idx = self.luaname:match('select%((%d+), %.%.%.%)') if idx then -- ordered arguments if self.vararg then -- can be (1, 2, 3) or {1, 2, 3} return string.format([[ (function(...) if %d == narg and type(select(%d, ...)) == 'table' then %s = select(%d, ...) if type(%s) ~= 'table' or #%s == 0 then %s = nil return false end for k,v in pairs(%s) do if type(k) ~= 'number' or type(v) ~= 'number' then %s = nil return false end end else -- here we have something anyways: only check it is a number %s = {} for i=%d,narg do local z = select(i, ...) if type(z) ~= 'number' then %s = nil return false end table.insert(%s, z) end end return true end)(...) ]], idx, idx, self.name, idx, self.name, self.name, self.name, self.name, self.name, self.name, idx, self.name, self.name) else -- can only be {1, 2, 3} return string.format([[ (function(...) %s = select(%d, ...) if type(%s) ~= 'table' or #%s == 0 then %s = nil return false end for k,v in ipairs(%s) do if type(k) ~= 'number' or type(v) ~= 'number' then %s = nil return false end end return true end)(...) ]], self.name, idx, self.name, self.name, self.name, self.name, self.name) end else -- named arguments return string.format( [[ (function(...) if type(%s) ~= 'table' or #(%s) == 0 then return false end for k,v in ipairs(%s) do if type(k) ~= 'number' or type(v) ~= 'number' then return false end end %s = %s return true end)(...) ]], self.luaname, self.luaname, self.luaname, self.name, self.luaname) end end, read = function(self) end } torch.argtypes["number"] = { check = function(self) return string.format("type(%s) == 'number'", self.luaname) end, initdefault = function(self) assert(type(self.default) == 'number', string.format('argument <%s> default should be a number', self.name)) return string.format('%s', self.default) end } torch.argtypes["boolean"] = { check = function(self) return string.format("type(%s) == 'boolean'", self.luaname) end, initdefault = function(self) assert(type(self.default) == 'boolean', string.format('argument <%s> default should be a boolean', self.name)) return string.format('%s', self.default) end } torch.argtypes["string"] = { check = function(self) assert(type(self.default) == 'string', string.format('argument <%s> default should be a string', self.name)) return string.format("type(%s) == 'string'", self.luaname) end, initdefault = function(self) return string.format('"%s"', self.default) end } for _,Tensor in ipairs{'torch.ByteTensor', 'torch.CharTensor', 'torch.ShortTensor', 'torch.IntTensor', 'torch.LongTensor', 'torch.FloatTensor', 'torch.DoubleTensor'} do torch.argtypes[Tensor] = { check = function(self) if self.dim then return string.format("type(%s) == '" .. Tensor .. "' and (%s).__nDimension == %d", self.luaname, self.luaname, self.dim) else return string.format("type(%s) == '" .. Tensor .. "'", self.luaname) end end, initdefault = function(self) return Tensor .. "()" end } end for _,Storage in ipairs{'torch.ByteStorage', 'torch.CharStorage', 'torch.ShortStorage', 'torch.IntStorage', 'torch.LongStorage', 'torch.FloatStorage', 'torch.DoubleStorage'} do torch.argtypes[Storage] = { check = function(self) if self.size then return string.format("type(%s) == '" .. Storage .. "' and (%s).__size == %d", self.luaname, self.luaname, self.size) else return string.format("type(%s) == '" .. Storage .. "'", self.luaname) end end, initdefault = function(self) return Storage .. "()" end } end
torch.argtypes = {} torch.argtypes["numbers"] = { vararg = true, -- if needed, one can override it to false check = function(self) local idx = self.luaname:match('select%((%d+), %.%.%.%)') if idx then -- ordered arguments if self.vararg then -- can be (1, 2, 3) or {1, 2, 3} return string.format([[ (function(...) if %d == narg and type(select(%d, ...)) == 'table' then %s = select(%d, ...) if type(%s) ~= 'table' or #%s == 0 then %s = nil return false end for k,v in pairs(%s) do if type(k) ~= 'number' or type(v) ~= 'number' then %s = nil return false end end else -- here we have something anyways: only check it is a number %s = {} for i=%d,narg do local z = select(i, ...) if type(z) ~= 'number' then %s = nil return false end table.insert(%s, z) end end return true end)(...) ]], idx, idx, self.name, idx, self.name, self.name, self.name, self.name, self.name, self.name, idx, self.name, self.name) else -- can only be {1, 2, 3} return string.format([[ (function(...) %s = select(%d, ...) if type(%s) ~= 'table' or #%s == 0 then %s = nil return false end for k,v in ipairs(%s) do if type(k) ~= 'number' or type(v) ~= 'number' then %s = nil return false end end return true end)(...) ]], self.name, idx, self.name, self.name, self.name, self.name, self.name) end else -- named arguments return string.format( [[ (function(...) if type(%s) ~= 'table' or #(%s) == 0 then return false end for k,v in ipairs(%s) do if type(k) ~= 'number' or type(v) ~= 'number' then return false end end %s = %s return true end)(...) ]], self.luaname, self.luaname, self.luaname, self.name, self.luaname) end end, read = function(self) end } torch.argtypes["number"] = { check = function(self) return string.format("type(%s) == 'number'", self.luaname) end, initdefault = function(self) assert(type(self.default) == 'number', string.format('argument <%s> default should be a number', self.name)) return string.format('%s', self.default) end } torch.argtypes["boolean"] = { check = function(self) return string.format("type(%s) == 'boolean'", self.luaname) end, initdefault = function(self) assert(type(self.default) == 'boolean', string.format('argument <%s> default should be a boolean', self.name)) return string.format('%s', self.default) end } torch.argtypes["string"] = { check = function(self) return string.format("type(%s) == 'string'", self.luaname) end, initdefault = function(self) assert(type(self.default) == 'string', string.format('argument <%s> default should be a string', self.name)) return string.format('"%s"', self.default) end } torch.argtypes["function"] = { check = function(self) return string.format("type(%s) == 'function'", self.luaname) end, initdefault = function(self) assert(type(self.default) == 'function', string.format('argument <%s> default should be a function', self.name)) return string.format('%s', self.default) end } for _,Tensor in ipairs{'torch.ByteTensor', 'torch.CharTensor', 'torch.ShortTensor', 'torch.IntTensor', 'torch.LongTensor', 'torch.FloatTensor', 'torch.DoubleTensor'} do torch.argtypes[Tensor] = { check = function(self) if self.dim then return string.format("type(%s) == '" .. Tensor .. "' and (%s).__nDimension == %d", self.luaname, self.luaname, self.dim) else return string.format("type(%s) == '" .. Tensor .. "'", self.luaname) end end, initdefault = function(self) return Tensor .. "()" end } end for _,Storage in ipairs{'torch.ByteStorage', 'torch.CharStorage', 'torch.ShortStorage', 'torch.IntStorage', 'torch.LongStorage', 'torch.FloatStorage', 'torch.DoubleStorage'} do torch.argtypes[Storage] = { check = function(self) if self.size then return string.format("type(%s) == '" .. Storage .. "' and (%s).__size == %d", self.luaname, self.luaname, self.size) else return string.format("type(%s) == '" .. Storage .. "'", self.luaname) end end, initdefault = function(self) return Storage .. "()" end } end
argtypes: fixed string type and added function type
argtypes: fixed string type and added function type
Lua
bsd-3-clause
torch/argcheck
b59e9f8b582d55b34aad3b2d94a7fb6efb9bae90
kong/plugins/pre-function/_handler.lua
kong/plugins/pre-function/_handler.lua
-- handler file for both the pre-function and post-function plugin return function(plugin_name, priority) local loadstring = loadstring local insert = table.insert local ipairs = ipairs local config_cache = setmetatable({}, { __mode = "k" }) local ServerlessFunction = { PRIORITY = priority, VERSION = "0.3.0", } function ServerlessFunction:access(config) local functions = config_cache[config] if not functions then functions = {} for _, fn_str in ipairs(config.functions) do local func1 = loadstring(fn_str) local _, func2 = pcall(func1) insert(functions, type(func2) == "function" and func2 or func1) end config_cache[config] = functions end for _, fn in ipairs(functions) do fn() end end return ServerlessFunction end
-- handler file for both the pre-function and post-function plugin return function(plugin_name, priority) local loadstring = loadstring local insert = table.insert local ipairs = ipairs local config_cache = setmetatable({}, { __mode = "k" }) local ServerlessFunction = { PRIORITY = priority, VERSION = "0.3.0", } function ServerlessFunction:access(config) local functions = config_cache[config] if not functions then -- first call, go compile the functions functions = {} for _, fn_str in ipairs(config.functions) do local func1 = loadstring(fn_str) -- load it local _, func2 = pcall(func1) -- run it if type(func2) ~= "function" then -- old style (0.1.0), without upvalues insert(functions, func1) else -- this is a new function (0.2.0+), with upvalues insert(functions, func2) -- the first call to func1 above only initialized it, so run again func2() end end config_cache[config] = functions return -- must return since we allready executed them end for _, fn in ipairs(functions) do fn() end end return ServerlessFunction end
fix(serverless-functions) only run them once when initializing
fix(serverless-functions) only run them once when initializing
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
68eb0795eb6a87189e27001d2e95c701536dac3f
resources/prosody-plugins/mod_polls.lua
resources/prosody-plugins/mod_polls.lua
-- This module provides persistence for the "polls" feature, -- by keeping track of the state of polls in each room, and sending -- that state to new participants when they join. local json = require("util.json"); local st = require("util.stanza"); local util = module:require("util"); local muc = module:depends("muc"); local is_healthcheck_room = util.is_healthcheck_room; -- Checks if the given stanza contains a JSON message, -- and that the message type pertains to the polls feature. -- If yes, returns the parsed message. Otherwise, returns nil. local function get_poll_message(stanza) if stanza.attr.type ~= "groupchat" then return nil; end local json_data = stanza:get_child_text("json-message", "http://jitsi.org/jitmeet"); if json_data == nil then return nil; end local data = json.decode(json_data); if not data or (data.type ~= "new-poll" and data.type ~= "answer-poll") then return nil; end return data; end -- Logs a warning and returns true if a room does not -- have poll data associated with it. local function check_polls(room) if room.polls == nil then module:log("warn", "no polls data in room"); return true; end return false; end -- Sets up poll data in new rooms. module:hook("muc-room-created", function(event) local room = event.room; if is_healthcheck_room(room.jid) then return end module:log("debug", "setting up polls in room %s", room.jid); room.polls = { by_id = {}; order = {}; }; end); -- Keeps track of the current state of the polls in each room, -- by listening to "new-poll" and "answer-poll" messages, -- and updating the room poll data accordingly. -- This mirrors the client-side poll update logic. module:hook("message/bare", function(event) local data = get_poll_message(event.stanza); if data == nil then return end local room = muc.get_room_from_jid(event.stanza.attr.to); if data.type == "new-poll" then if check_polls(room) then return end local answers = {} local compactAnswers = {} for _, name in ipairs(data.answers) do table.insert(answers, { name = name, voters = {} }); table.insert(compactAnswers, {name = name}); end local poll = { id = data.pollId, sender_id = data.senderId, sender_name = data.senderName, question = data.question, answers = answers }; room.polls.by_id[data.pollId] = poll table.insert(room.polls.order, poll) local pollData = { event = event, room = room, poll = { pollId = data.pollId, senderId = data.senderId, senderName = data.senderName, question = data.question, answers = compactAnswers } } module:fire_event("poll-created", pollData); elseif data.type == "answer-poll" then if check_polls(room) then return end local poll = room.polls.by_id[data.pollId]; if poll == nil then module:log("warn", "answering inexistent poll"); return; end local answers = {}; for i, value in ipairs(data.answers) do table.insert(answers, { value = value, name = poll.answers[i].name, }); poll.answers[i].voters[data.voterId] = value and data.voterName or nil; end local answerData = { event = event, room = room, pollId = poll.id, voterName = data.voterName, voterId = data.voterId, answers = answers } module:fire_event("answer-poll", answerData); end end); -- Sends the current poll state to new occupants after joining a room. module:hook("muc-occupant-joined", function(event) local room = event.room; if is_healthcheck_room(room.jid) then return end if room.polls == nil or #room.polls.order == 0 then return end local data = { type = "old-polls", polls = {}, }; for i, poll in ipairs(room.polls.order) do data.polls[i] = { id = poll.id, senderId = poll.sender_id, senderName = poll.sender_name, question = poll.question, answers = poll.answers }; end local stanza = st.message({ from = room.jid, to = event.occupant.jid }) :tag("json-message", { xmlns = "http://jitsi.org/jitmeet" }) :text(json.encode(data)) :up(); room:route_stanza(stanza); end);
-- This module provides persistence for the "polls" feature, -- by keeping track of the state of polls in each room, and sending -- that state to new participants when they join. local json = require("util.json"); local st = require("util.stanza"); local util = module:require("util"); local muc = module:depends("muc"); local is_healthcheck_room = util.is_healthcheck_room; -- Checks if the given stanza contains a JSON message, -- and that the message type pertains to the polls feature. -- If yes, returns the parsed message. Otherwise, returns nil. local function get_poll_message(stanza) if stanza.attr.type ~= "groupchat" then return nil; end local json_data = stanza:get_child_text("json-message", "http://jitsi.org/jitmeet"); if json_data == nil then return nil; end local data = json.decode(json_data); if not data or (data.type ~= "new-poll" and data.type ~= "answer-poll") then return nil; end return data; end -- Logs a warning and returns true if a room does not -- have poll data associated with it. local function check_polls(room) if room.polls == nil then module:log("warn", "no polls data in room"); return true; end return false; end -- Sets up poll data in new rooms. module:hook("muc-room-created", function(event) local room = event.room; if is_healthcheck_room(room.jid) then return end module:log("debug", "setting up polls in room %s", room.jid); room.polls = { by_id = {}; order = {}; }; end); -- Keeps track of the current state of the polls in each room, -- by listening to "new-poll" and "answer-poll" messages, -- and updating the room poll data accordingly. -- This mirrors the client-side poll update logic. module:hook("message/bare", function(event) local data = get_poll_message(event.stanza); if data == nil then return end local room = muc.get_room_from_jid(event.stanza.attr.to); if data.type == "new-poll" then if check_polls(room) then return end local answers = {} local compactAnswers = {} for i, name in ipairs(data.answers) do table.insert(answers, { name = name, voters = {} }); table.insert(compactAnswers, { key = i, name = name}); end local poll = { id = data.pollId, sender_id = data.senderId, sender_name = data.senderName, question = data.question, answers = answers }; room.polls.by_id[data.pollId] = poll table.insert(room.polls.order, poll) local pollData = { event = event, room = room, poll = { pollId = data.pollId, senderId = data.senderId, senderName = data.senderName, question = data.question, answers = compactAnswers } } module:fire_event("poll-created", pollData); elseif data.type == "answer-poll" then if check_polls(room) then return end local poll = room.polls.by_id[data.pollId]; if poll == nil then module:log("warn", "answering inexistent poll"); return; end local answers = {}; for i, value in ipairs(data.answers) do table.insert(answers, { key = i, value = value, name = poll.answers[i].name, }); poll.answers[i].voters[data.voterId] = value and data.voterName or nil; end local answerData = { event = event, room = room, pollId = poll.id, voterName = data.voterName, voterId = data.voterId, answers = answers } module:fire_event("answer-poll", answerData); end end); -- Sends the current poll state to new occupants after joining a room. module:hook("muc-occupant-joined", function(event) local room = event.room; if is_healthcheck_room(room.jid) then return end if room.polls == nil or #room.polls.order == 0 then return end local data = { type = "old-polls", polls = {}, }; for i, poll in ipairs(room.polls.order) do data.polls[i] = { id = poll.id, senderId = poll.sender_id, senderName = poll.sender_name, question = poll.question, answers = poll.answers }; end local stanza = st.message({ from = room.jid, to = event.occupant.jid }) :tag("json-message", { xmlns = "http://jitsi.org/jitmeet" }) :text(json.encode(data)) :up(); room:route_stanza(stanza); end);
feat(polls) fix spacing and send answer identifier
feat(polls) fix spacing and send answer identifier
Lua
apache-2.0
jitsi/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet
1121b152bddc78f1a5b4709d91d4f0a9745ccdb2
Modules/Server/ChunkedDataStore/ChunkedDataStore.lua
Modules/Server/ChunkedDataStore/ChunkedDataStore.lua
--- Stores very large strings into the datastore -- @classmod ChunkDataStore local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore")) local HttpService = game:GetService("HttpService") local ChunkUtils = require("ChunkUtils") local DataStorePromises = require("DataStorePromises") local Promise = require("Promise") local PromiseUtils = require("PromiseUtils") local CHUNK_SIZE = 1000 -- 260000 - 100 local ChunkDataStore = {} ChunkDataStore.ClassName = "ChunkDataStore" ChunkDataStore.__index = ChunkDataStore function ChunkDataStore.new(datastore) local self = setmetatable({}, ChunkDataStore) self._datastore = datastore or error("No datastore") return self end function ChunkDataStore:WriteEntry(largeString) local promises = {} local keys = {} for chunk in ChunkUtils.chunkStr(largeString, CHUNK_SIZE) do local key = HttpService:GenerateGUID(false) table.insert(keys, key) table.insert(promises, DataStorePromises.setAsync(self._datastore, key, chunk)) end return PromiseUtils.all(promises):Then(function(...) return { EntryVersion = 1; FileSize = #largeString; Keys = keys; } end) end function ChunkDataStore:LoadEntry(entry) assert(type(entry) == "table") assert(type(entry.EntryVersion) == "number") assert(type(entry.FileSize) == "number") assert(type(entry.Keys) == "table") return self:_loadChunks(entry.Keys):Then(function(chunks) return self:_decodeChunksToStr(chunks, entry.FileSize) end) end function ChunkDataStore:_loadChunks(keys) local promises = {} for _, item in pairs(keys) do table.insert(promises, self:_loadChunk(item)) end return PromiseUtils.all(promises):Then(function(...) return {...} end) end function ChunkDataStore:_decodeChunksToStr(chunks, expectedSize) return Promise.new(function(resolve, reject) for index, item in pairs(chunks) do if type(item) ~= "string" then reject("Failed to load chunk #" .. index) return end end local total = table.concat(chunks, "") if #total ~= expectedSize then reject(("Combined chunks is %d, expectd %d"):format(#total, expectedSize)) return end resolve(total) return end) end function ChunkDataStore:_loadChunk(key) if type(key) ~= "string" then return Promise.rejected("Key is not a string") end return DataStorePromises.getAsync(self._datastore, key) end return ChunkDataStore
--- Stores very large strings into the datastore -- @classmod ChunkDataStore local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore")) local HttpService = game:GetService("HttpService") local ChunkUtils = require("ChunkUtils") local DataStorePromises = require("DataStorePromises") local Promise = require("Promise") local PromiseUtils = require("PromiseUtils") local CHUNK_SIZE = 1000 -- 260000 - 100 local ChunkDataStore = {} ChunkDataStore.ClassName = "ChunkDataStore" ChunkDataStore.__index = ChunkDataStore function ChunkDataStore.new(datastore) local self = setmetatable({}, ChunkDataStore) self._datastore = datastore or error("No datastore") return self end function ChunkDataStore:WriteEntry(largeString) assert(type(largeString) == "string") local promises = {} local keys = {} for chunk in ChunkUtils.chunkStr(largeString, CHUNK_SIZE) do local key = HttpService:GenerateGUID(false) table.insert(keys, key) table.insert(promises, DataStorePromises.setAsync(self._datastore, key, chunk)) end return PromiseUtils.all(promises):Then(function(...) return { EntryVersion = 1; FileSize = #largeString; Keys = keys; } end) end function ChunkDataStore:LoadEntry(entry) assert(type(entry) == "table") assert(type(entry.EntryVersion) == "number") assert(type(entry.FileSize) == "number") assert(type(entry.Keys) == "table") return self:_loadChunks(entry.Keys):Then(function(chunks) return self:_decodeChunksToStr(chunks, entry.FileSize) end) end function ChunkDataStore:_loadChunks(keys) local promises = {} for _, item in pairs(keys) do table.insert(promises, self:_loadChunk(item)) end return PromiseUtils.all(promises):Then(function(...) return {...} end) end function ChunkDataStore:_decodeChunksToStr(chunks, expectedSize) return Promise.new(function(resolve, reject) for index, item in pairs(chunks) do if type(item) ~= "string" then reject("Failed to load chunk #" .. index) return end end local total = table.concat(chunks, "") if #total ~= expectedSize then reject(("Combined chunks is %d, expected %d"):format(#total, expectedSize)) return end resolve(total) return end) end function ChunkDataStore:_loadChunk(key) if type(key) ~= "string" then return Promise.rejected("Key is not a string") end return DataStorePromises.getAsync(self._datastore, key) end return ChunkDataStore
fix spelling mistake
fix spelling mistake
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
acd1e22bf45485d7155feeab52eea4316373e000
frame/common/string.lua
frame/common/string.lua
-------------------------------------------------------------------------------- -- -- This file is part of the Doxyrest toolkit. -- -- Doxyrest is distributed under the MIT license. -- For details see accompanying license.txt file, -- the public copy of which is also available at: -- http://tibbo.com/downloads/archive/doxyrest/license.txt -- -------------------------------------------------------------------------------- function captialize(string) local s = string.gsub(string, "^%l", string.upper) return s end function trimLeadingWhitespace(string) local s = string.gsub(string, "^%s+", "") return s end function trimTrailingWhitespace(string) local s = string.gsub(string, "%s+$", "") return s end function trimWhitespace(string) local s = trimLeadingWhitespace(string) return trimTrailingWhitespace(s) end function getTitle(title, underline) if not title or title == "" then title = "<Untitled>" end title = string.gsub(title, "(_*)$", "\\%1") -- escape trailing underscores return title .. "\n" .. string.rep(underline, #title) end function replaceCommonSpacePrefix(source, replacement) local s = "\n" .. source -- add leading '\n' local prefix = nil local len = 0 for newPrefix in string.gmatch(s, "(\n[ \t]*)[^%s]") do if not prefix then prefix = newPrefix len = string.len(prefix) else local newLen = string.len(newPrefix) if newLen < len then len = newLen end for i = 2, len do if string.byte(prefix, i) ~= string.byte(newPrefix, i) then len = i - 1 break end end prefix = string.sub(prefix, 1, len) end if len < 2 then break end end if not prefix or len < 2 and replacement == "" then return source end s = string.gsub(s, prefix, "\n" .. replacement) -- replace common prefix s = string.sub(s, 2) -- remove leading '\n' return s end -------------------------------------------------------------------------------
-------------------------------------------------------------------------------- -- -- This file is part of the Doxyrest toolkit. -- -- Doxyrest is distributed under the MIT license. -- For details see accompanying license.txt file, -- the public copy of which is also available at: -- http://tibbo.com/downloads/archive/doxyrest/license.txt -- -------------------------------------------------------------------------------- function captialize(string) local s = string.gsub(string, "^%l", string.upper) return s end function trimLeadingWhitespace(string) local s = string.gsub(string, "^%s+", "") return s end function trimTrailingWhitespace(string) local s = string.gsub(string, "%s+$", "") return s end function trimWhitespace(string) local s = trimLeadingWhitespace(string) return trimTrailingWhitespace(s) end function getTitle(title, underline) if not title or title == "" then title = "<Untitled>" end -- escape trailing underscores title = string.gsub(title, "(_+)(%s+)", "\\%1%2") title = string.gsub(title, "(_+)$", "\\%1") return title .. "\n" .. string.rep(underline, #title) end function replaceCommonSpacePrefix(source, replacement) local s = "\n" .. source -- add leading '\n' local prefix = nil local len = 0 for newPrefix in string.gmatch(s, "(\n[ \t]*)[^%s]") do if not prefix then prefix = newPrefix len = string.len(prefix) else local newLen = string.len(newPrefix) if newLen < len then len = newLen end for i = 2, len do if string.byte(prefix, i) ~= string.byte(newPrefix, i) then len = i - 1 break end end prefix = string.sub(prefix, 1, len) end if len < 2 then break end end if not prefix or len < 2 and replacement == "" then return source end s = string.gsub(s, prefix, "\n" .. replacement) -- replace common prefix s = string.sub(s, 2) -- remove leading '\n' return s end -------------------------------------------------------------------------------
[frame/common] fix: incorrect escaping the trailing underscores
[frame/common] fix: incorrect escaping the trailing underscores
Lua
mit
vovkos/doxyrest,vovkos/doxyrest,vovkos/doxyrest,vovkos/doxyrest,vovkos/doxyrest
efb8e8c1ef851be738d69aa563c9a4097cd42246
xmake/modules/package/manager/vcpkg/find_package.lua
xmake/modules/package/manager/vcpkg/find_package.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-2020, TBOOX Open Source Group. -- -- @author ruki -- @file find_package.lua -- -- imports import("lib.detect.find_file") import("lib.detect.find_library") import("detect.sdks.find_vcpkgdir") import("core.project.config") import("core.project.target") -- find package from the brew package manager -- -- @param name the package name, e.g. zlib, pcre -- @param opt the options, e.g. {verbose = true, version = "1.12.x") -- function main(name, opt) -- attempt to find the vcpkg root directory local vcpkgdir = find_vcpkgdir(opt.vcpkgdir) if not vcpkgdir then return end -- get arch, plat and mode local arch = opt.arch local plat = opt.plat local mode = opt.mode if plat == "macosx" then plat = "osx" end if arch == "x86_64" then arch = "x64" end -- get the vcpkg installed directory local installdir = path.join(vcpkgdir, "installed") -- get the vcpkg info directory local infodir = path.join(installdir, "vcpkg", "info") -- find the package info file, e.g. zlib_1.2.11-3_x86-windows[-static].list local triplet = arch .. "-" .. plat local pkgconfigs = opt.pkgconfigs if plat == "windows" and pkgconfigs and pkgconfigs.shared ~= true then triplet = triplet .. "-static" assert(not pkgconfigs.vs_runtime or pkgconfigs.vs_runtime:startswith("MT"), "only support static libraries with /MT[d] for vcpkg!") end local infofile = find_file(format("%s_*_%s.list", name, triplet), infodir) -- save includedirs, linkdirs and links local result = nil local info = infofile and io.readfile(infofile) or nil if info then for _, line in ipairs(info:split('\n')) do line = line:trim() -- get includedirs if line:endswith("/include/") then result = result or {} result.includedirs = result.includedirs or {} table.insert(result.includedirs, path.join(installdir, line)) end -- get linkdirs and links if (plat == "windows" and line:endswith(".lib")) or line:endswith(".a") then if line:find(triplet .. (mode == "debug" and "/debug" or "") .. "/lib/", 1, true) then result = result or {} result.links = result.links or {} result.linkdirs = result.linkdirs or {} table.insert(result.linkdirs, path.join(installdir, path.directory(line))) table.insert(result.links, target.linkname(path.filename(line))) end end -- add shared library directory (/bin/) to linkdirs for running with PATH on windows if plat == "windows" and line:endswith(".dll") then if line:find(plat .. (mode == "debug" and "/debug" or "") .. "/bin/", 1, true) then result = result or {} result.linkdirs = result.linkdirs or {} table.insert(result.linkdirs, path.join(installdir, path.directory(line))) end end end end -- save version if result and infofile then local infoname = path.basename(infofile) result.version = infoname:match(name .. "_(%d+%.?%d*%.?%d*.-)_" .. arch) if not result.version then result.version = infoname:match(name .. "_(%d+%.?%d*%.-)_" .. arch) end end return result end
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-2020, TBOOX Open Source Group. -- -- @author ruki -- @file find_package.lua -- -- imports import("lib.detect.find_file") import("lib.detect.find_library") import("detect.sdks.find_vcpkgdir") import("core.project.config") import("core.project.target") -- find package from the brew package manager -- -- @param name the package name, e.g. zlib, pcre -- @param opt the options, e.g. {verbose = true, version = "1.12.x") -- function main(name, opt) -- attempt to find the vcpkg root directory local vcpkgdir = find_vcpkgdir(opt.vcpkgdir) if not vcpkgdir then return end -- fix name, e.g. ffmpeg[x264] as ffmpeg -- @see https://github.com/xmake-io/xmake/issues/925 name = name:gsub("%[.-%]", "") -- get arch, plat and mode local arch = opt.arch local plat = opt.plat local mode = opt.mode if plat == "macosx" then plat = "osx" end if arch == "x86_64" then arch = "x64" end -- get the vcpkg installed directory local installdir = path.join(vcpkgdir, "installed") -- get the vcpkg info directory local infodir = path.join(installdir, "vcpkg", "info") -- find the package info file, e.g. zlib_1.2.11-3_x86-windows[-static].list local triplet = arch .. "-" .. plat local pkgconfigs = opt.pkgconfigs if plat == "windows" and pkgconfigs and pkgconfigs.shared ~= true then triplet = triplet .. "-static" assert(not pkgconfigs.vs_runtime or pkgconfigs.vs_runtime:startswith("MT"), "only support static libraries with /MT[d] for vcpkg!") end local infofile = find_file(format("%s_*_%s.list", name, triplet), infodir) -- save includedirs, linkdirs and links local result = nil local info = infofile and io.readfile(infofile) or nil if info then for _, line in ipairs(info:split('\n')) do line = line:trim() -- get includedirs if line:endswith("/include/") then result = result or {} result.includedirs = result.includedirs or {} table.insert(result.includedirs, path.join(installdir, line)) end -- get linkdirs and links if (plat == "windows" and line:endswith(".lib")) or line:endswith(".a") then if line:find(triplet .. (mode == "debug" and "/debug" or "") .. "/lib/", 1, true) then result = result or {} result.links = result.links or {} result.linkdirs = result.linkdirs or {} table.insert(result.linkdirs, path.join(installdir, path.directory(line))) table.insert(result.links, target.linkname(path.filename(line))) end end -- add shared library directory (/bin/) to linkdirs for running with PATH on windows if plat == "windows" and line:endswith(".dll") then if line:find(plat .. (mode == "debug" and "/debug" or "") .. "/bin/", 1, true) then result = result or {} result.linkdirs = result.linkdirs or {} table.insert(result.linkdirs, path.join(installdir, path.directory(line))) end end end end -- save version if result and infofile then local infoname = path.basename(infofile) result.version = infoname:match(name .. "_(%d+%.?%d*%.?%d*.-)_" .. arch) if not result.version then result.version = infoname:match(name .. "_(%d+%.?%d*%.-)_" .. arch) end end return result end
fix find_package for vcpkg
fix find_package for vcpkg
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
b62619859286f00af322d0bc0273aa832a5aedb0
lualib/skynet/db/redis.lua
lualib/skynet/db/redis.lua
local skynet = require "skynet" local socket = require "skynet.socket" local socketchannel = require "skynet.socketchannel" local table = table local string = string local assert = assert local redis = {} local command = {} local meta = { __index = command, -- DO NOT close channel in __gc } ---------- redis response local redcmd = {} redcmd[36] = function(fd, data) -- '$' local bytes = tonumber(data) if bytes < 0 then return true,nil end local firstline = fd:read(bytes+2) return true,string.sub(firstline,1,-3) end redcmd[43] = function(fd, data) -- '+' return true,data end redcmd[45] = function(fd, data) -- '-' return false,data end redcmd[58] = function(fd, data) -- ':' -- todo: return string later return true, tonumber(data) end local function read_response(fd) local result = fd:readline "\r\n" local firstchar = string.byte(result) local data = string.sub(result,2) return redcmd[firstchar](fd,data) end redcmd[42] = function(fd, data) -- '*' local n = tonumber(data) if n < 0 then return true, nil end local bulk = {} local noerr = true for i = 1,n do local ok, v = read_response(fd) if not ok then noerr = false end bulk[i] = v end return noerr, bulk end ------------------- function command:disconnect() self[1]:close() setmetatable(self, nil) end -- msg could be any type of value local function make_cache(f) return setmetatable({}, { __mode = "kv", __index = f, }) end local header_cache = make_cache(function(t,k) local s = "\r\n$" .. k .. "\r\n" t[k] = s return s end) local command_cache = make_cache(function(t,cmd) local s = "\r\n$"..#cmd.."\r\n"..cmd:upper() t[cmd] = s return s end) local count_cache = make_cache(function(t,k) local s = "*" .. k t[k] = s return s end) local command_np_cache = make_cache(function(t, cmd) local s = "*1" .. command_cache[cmd] .. "\r\n" t[cmd] = s return s end) local function compose_message(cmd, msg) if msg == nil then return command_np_cache[cmd] end local t = type(msg) local lines = {} if t == "table" then local n = msg.n or #msg lines[1] = count_cache[n+1] lines[2] = command_cache[cmd] local idx = 3 for i = 1, n do v = msg[i] if v == nil then lines[idx] = "\r\n$-1" idx = idx + 1 else v= tostring(v) lines[idx] = header_cache[#v] lines[idx+1] = v idx = idx + 2 end end lines[idx] = "\r\n" else msg = tostring(msg) lines[1] = "*2" lines[2] = command_cache[cmd] lines[3] = header_cache[#msg] lines[4] = msg lines[5] = "\r\n" end return lines end local function redis_login(auth, db) if auth == nil and db == nil then return end return function(so) if auth then so:request(compose_message("AUTH", auth), read_response) end if db then so:request(compose_message("SELECT", db), read_response) end end end function redis.connect(db_conf) local channel = socketchannel.channel { host = db_conf.host, port = db_conf.port or 6379, auth = redis_login(db_conf.auth, db_conf.db), nodelay = true, overload = db_conf.overload, } -- try connect first only once channel:connect(true) return setmetatable( { channel }, meta ) end setmetatable(command, { __index = function(t,k) local cmd = string.upper(k) local f = function (self, v, ...) if v == nil then return self[1]:request(compose_message(cmd), read_response) elseif type(v) == "table" then return self[1]:request(compose_message(cmd, v), read_response) else return self[1]:request(compose_message(cmd, table.pack(v, ...)), read_response) end end t[k] = f return f end}) local function read_boolean(so) local ok, result = read_response(so) return ok, result ~= 0 end function command:exists(key) local fd = self[1] return fd:request(compose_message ("EXISTS", key), read_boolean) end function command:sismember(key, value) local fd = self[1] return fd:request(compose_message ("SISMEMBER", table.pack(key, value)), read_boolean) end local function compose_table(lines, msg) local tinsert = table.insert tinsert(lines, count_cache[#msg]) for _,v in ipairs(msg) do v = tostring(v) tinsert(lines,header_cache[#v]) tinsert(lines,v) end tinsert(lines, "\r\n") return lines end function command:pipeline(ops,resp) assert(ops and #ops > 0, "pipeline is null") local fd = self[1] local cmds = {} for _, cmd in ipairs(ops) do compose_table(cmds, cmd) end if resp then return fd:request(cmds, function (fd) for i=1, #ops do local ok, out = read_response(fd) table.insert(resp, {ok = ok, out = out}) end return true, resp end) else return fd:request(cmds, function (fd) local ok, out for i=1, #ops do ok, out = read_response(fd) end -- return last response return ok,out end) end end --- watch mode local watch = {} local watchmeta = { __index = watch, __gc = function(self) self.__sock:close() end, } local function watch_login(obj, auth) return function(so) if auth then so:request(compose_message("AUTH", auth), read_response) end for k in pairs(obj.__psubscribe) do so:request(compose_message ("PSUBSCRIBE", k)) end for k in pairs(obj.__subscribe) do so:request(compose_message("SUBSCRIBE", k)) end end end function redis.watch(db_conf) local obj = { __subscribe = {}, __psubscribe = {}, } local channel = socketchannel.channel { host = db_conf.host, port = db_conf.port or 6379, auth = watch_login(obj, db_conf.auth), nodelay = true, } obj.__sock = channel -- try connect first only once channel:connect(true) return setmetatable( obj, watchmeta ) end function watch:disconnect() self.__sock:close() setmetatable(self, nil) end local function watch_func( name ) local NAME = string.upper(name) watch[name] = function(self, ...) local so = self.__sock for i = 1, select("#", ...) do local v = select(i, ...) so:request(compose_message(NAME, v)) end end end watch_func "subscribe" watch_func "psubscribe" watch_func "unsubscribe" watch_func "punsubscribe" function watch:message() local so = self.__sock while true do local ret = so:response(read_response) local type , channel, data , data2 = ret[1], ret[2], ret[3], ret[4] if type == "message" then return data, channel elseif type == "pmessage" then return data2, data, channel elseif type == "subscribe" then self.__subscribe[channel] = true elseif type == "psubscribe" then self.__psubscribe[channel] = true elseif type == "unsubscribe" then self.__subscribe[channel] = nil elseif type == "punsubscribe" then self.__psubscribe[channel] = nil end end end return redis
local socketchannel = require "skynet.socketchannel" local tostring = tostring local tonumber = tonumber local table = table local string = string local assert = assert local setmetatable = setmetatable local ipairs = ipairs local type = type local select = select local pairs = pairs local redis = {} local command = {} local meta = { __index = command, -- DO NOT close channel in __gc } ---------- redis response local redcmd = {} redcmd[36] = function(fd, data) -- '$' local bytes = tonumber(data) if bytes < 0 then return true,nil end local firstline = fd:read(bytes+2) return true,string.sub(firstline,1,-3) end redcmd[43] = function(fd, data) -- '+' return true,data end redcmd[45] = function(fd, data) -- '-' return false,data end redcmd[58] = function(fd, data) -- ':' -- todo: return string later return true, tonumber(data) end local function read_response(fd) local result = fd:readline "\r\n" local firstchar = string.byte(result) local data = string.sub(result,2) return redcmd[firstchar](fd,data) end redcmd[42] = function(fd, data) -- '*' local n = tonumber(data) if n < 0 then return true, nil end local bulk = {} local noerr = true for i = 1,n do local ok, v = read_response(fd) if not ok then noerr = false end bulk[i] = v end return noerr, bulk end ------------------- function command:disconnect() self[1]:close() setmetatable(self, nil) end -- msg could be any type of value local function make_cache(f) return setmetatable({}, { __mode = "kv", __index = f, }) end local header_cache = make_cache(function(t,k) local s = "\r\n$" .. k .. "\r\n" t[k] = s return s end) local command_cache = make_cache(function(t,cmd) local s = "\r\n$"..#cmd.."\r\n"..cmd:upper() t[cmd] = s return s end) local count_cache = make_cache(function(t,k) local s = "*" .. k t[k] = s return s end) local command_np_cache = make_cache(function(t, cmd) local s = "*1" .. command_cache[cmd] .. "\r\n" t[cmd] = s return s end) local function compose_message(cmd, msg) if msg == nil then return command_np_cache[cmd] end local t = type(msg) local lines = {} if t == "table" then local n = msg.n or #msg lines[1] = count_cache[n+1] lines[2] = command_cache[cmd] local idx = 3 for i = 1, n do local v = msg[i] if v == nil then lines[idx] = "\r\n$-1" idx = idx + 1 else v= tostring(v) lines[idx] = header_cache[#v] lines[idx+1] = v idx = idx + 2 end end lines[idx] = "\r\n" else msg = tostring(msg) lines[1] = "*2" lines[2] = command_cache[cmd] lines[3] = header_cache[#msg] lines[4] = msg lines[5] = "\r\n" end return lines end local function redis_login(auth, db) if auth == nil and db == nil then return end return function(so) if auth then so:request(compose_message("AUTH", auth), read_response) end if db then so:request(compose_message("SELECT", db), read_response) end end end function redis.connect(db_conf) local channel = socketchannel.channel { host = db_conf.host, port = db_conf.port or 6379, auth = redis_login(db_conf.auth, db_conf.db), nodelay = true, overload = db_conf.overload, } -- try connect first only once channel:connect(true) return setmetatable( { channel }, meta ) end setmetatable(command, { __index = function(t,k) local cmd = string.upper(k) local f = function (self, v, ...) if v == nil then return self[1]:request(compose_message(cmd), read_response) elseif type(v) == "table" then return self[1]:request(compose_message(cmd, v), read_response) else return self[1]:request(compose_message(cmd, table.pack(v, ...)), read_response) end end t[k] = f return f end}) local function read_boolean(so) local ok, result = read_response(so) return ok, result ~= 0 end function command:exists(key) local fd = self[1] return fd:request(compose_message ("EXISTS", key), read_boolean) end function command:sismember(key, value) local fd = self[1] return fd:request(compose_message ("SISMEMBER", table.pack(key, value)), read_boolean) end local function compose_table(lines, msg) local tinsert = table.insert tinsert(lines, count_cache[#msg]) for _,v in ipairs(msg) do v = tostring(v) tinsert(lines,header_cache[#v]) tinsert(lines,v) end tinsert(lines, "\r\n") return lines end function command:pipeline(ops,resp) assert(ops and #ops > 0, "pipeline is null") local fd = self[1] local cmds = {} for _, cmd in ipairs(ops) do compose_table(cmds, cmd) end if resp then return fd:request(cmds, function (fd) for _=1, #ops do local ok, out = read_response(fd) table.insert(resp, {ok = ok, out = out}) end return true, resp end) else return fd:request(cmds, function (fd) local ok, out for _=1, #ops do ok, out = read_response(fd) end -- return last response return ok,out end) end end --- watch mode local watch = {} local watchmeta = { __index = watch, __gc = function(self) self.__sock:close() end, } local function watch_login(obj, auth) return function(so) if auth then so:request(compose_message("AUTH", auth), read_response) end for k in pairs(obj.__psubscribe) do so:request(compose_message ("PSUBSCRIBE", k)) end for k in pairs(obj.__subscribe) do so:request(compose_message("SUBSCRIBE", k)) end end end function redis.watch(db_conf) local obj = { __subscribe = {}, __psubscribe = {}, } local channel = socketchannel.channel { host = db_conf.host, port = db_conf.port or 6379, auth = watch_login(obj, db_conf.auth), nodelay = true, } obj.__sock = channel -- try connect first only once channel:connect(true) return setmetatable( obj, watchmeta ) end function watch:disconnect() self.__sock:close() setmetatable(self, nil) end local function watch_func( name ) local NAME = string.upper(name) watch[name] = function(self, ...) local so = self.__sock for i = 1, select("#", ...) do local v = select(i, ...) so:request(compose_message(NAME, v)) end end end watch_func "subscribe" watch_func "psubscribe" watch_func "unsubscribe" watch_func "punsubscribe" function watch:message() local so = self.__sock while true do local ret = so:response(read_response) local ttype , channel, data , data2 = ret[1], ret[2], ret[3], ret[4] if ttype == "message" then return data, channel elseif ttype == "pmessage" then return data2, data, channel elseif ttype == "subscribe" then self.__subscribe[channel] = true elseif ttype == "psubscribe" then self.__psubscribe[channel] = true elseif ttype == "unsubscribe" then self.__subscribe[channel] = nil elseif ttype == "punsubscribe" then self.__psubscribe[channel] = nil end end end return redis
fix global var (#1342)
fix global var (#1342) Co-authored-by: xiaojin <[email protected]>
Lua
mit
korialuo/skynet,hongling0/skynet,sanikoyes/skynet,icetoggle/skynet,xjdrew/skynet,cloudwu/skynet,icetoggle/skynet,pigparadise/skynet,hongling0/skynet,hongling0/skynet,sanikoyes/skynet,xjdrew/skynet,wangyi0226/skynet,wangyi0226/skynet,pigparadise/skynet,cloudwu/skynet,icetoggle/skynet,sanikoyes/skynet,wangyi0226/skynet,korialuo/skynet,pigparadise/skynet,xjdrew/skynet,cloudwu/skynet,korialuo/skynet
034a1f9eb147357ad498858bbd22f2d617ef15d1
control.lua
control.lua
require 'util' require 'gui' require 'test' function print(stuff) game.players[1].print(stuff) end function printBool(stuff) game.players[1].print(tostring(stuff)) end function setup() global.hoverboard = global.hoverboard or {} for _, player in pairs(game.players) do createPlayerMag(player.index) end end function activateEquipment(index) global.hoverboard[index].inserted = true global.hoverboard[index].active = false UI.initialize(index) end function deactivateEquipment(index) if global.hoverboard[index].inserted == true then global.hoverboard[index].inserted = false UI.destroy(index) end end function createPlayerMag(i) local entity = { charge = 0, active = false, inserted = false, } global.hoverboard[i] = entity end script.on_init(setup) function getTile(index) return game.players[index].surface.get_tile(game.players[index].position.x,game.players[index].position.y) end function getArmor(index) local armor = game.players[index].get_inventory(defines.inventory.player_armor)[1] return armor end function armorCheck(index) local armor = getArmor(index) if armor.valid_for_read and armor.has_grid then return true end return false end script.on_event(defines.events.on_tick, function(event) local n = 0 for k,v in pairs(game.players) do if global.hoverboard[k].inserted == true and global.hoverboard[k].active == true then locomotion(k) tileCheck(k) UI.updateStatus(k) end end end) script.on_event(defines.events.on_player_armor_inventory_changed, function(event) local index = event.player_index if armorCheck(index) then local armor = getArmor(index) local equipment = armor.grid.equipment for i, e in ipairs(equipment) do if e.name == "hoverboard" then activateEquipment(index) end end else deactivateEquipment(index) end end) script.on_event(defines.events.on_player_placed_equipment, function(event) local index = event.player_index if armorCheck(index) and event.equipment.name == "hoverboard" then activateEquipment(index) end end) script.on_event(defines.events.on_player_removed_equipment, function(event) local index = event.player_index if armorCheck(index) and event.equipment == "hoverboard" then deactivateEquipment(index) end end) script.on_event(defines.events.on_entity_died, function(event) if event.entity.name == "player" then global.dead = true end end) script.on_event(defines.events.on_gui_click,function(event) local index = event.player_index if event.element.name == "mode" then if global.hoverboard[index].active == false then global.hoverboard[index].active = true elseif global.hoverboard[index].active == true then global.hoverboard[index].active = false end UI.switchMode(global.hoverboard[index].active,index) end end) script.on_event(defines.events.on_built_entity,function(event) if event.created_entity.name == "accelerator" then game.player.print("beep") end end) function locomotion(index) local orientation = game.players[index].walking_state.direction if global.hoverboard[index].charge > 0 then global.hoverboard[index].charge = global.hoverboard[index].charge - 1 game.players[index].walking_state = {walking = true, direction = orientation} end end function inboundTile(name) local tiles = {"copper-floor", "copper-floor2", "copper-floor3","accelerator","down","left","up","right"} for _, tile in ipairs(tiles) do if tile == name then return true end end return false end function tileCheck(index) local tile = getTile(index) local walk = game.players[index].walking_state.walking if tile.name == "accelerator" then if global.hoverboard[index].charge <= 40 then global.hoverboard[index].charge = global.hoverboard[index].charge + 10 end elseif tile.name == "down" then game.players[index].walking_state = {walking = walk, direction = defines.direction.south} elseif tile.name == "up" then game.players[index].walking_state = {walking = walk, direction = defines.direction.north} elseif tile.name == "right" then game.players[index].walking_state = {walking = walk, direction = defines.direction.east} elseif tile.name == "left" then game.players[index].walking_state = {walking = walk, direction = defines.direction.west} elseif inboundTile(tile.name) == false then global.hoverboard[index].charge = 0 end end
require 'util' require 'gui' require 'test' function print(stuff) game.players[1].print(stuff) end function printBool(stuff) game.players[1].print(tostring(stuff)) end function setup() global.hoverboard = global.hoverboard or {} for _, player in pairs(game.players) do createPlayerMag(player.index) end end function activateEquipment(index) global.hoverboard[index].inserted = true global.hoverboard[index].active = false UI.initialize(index) end function deactivateEquipment(index) if global.hoverboard[index].inserted == true then global.hoverboard[index].inserted = false UI.destroy(index) end end function createPlayerMag(i) local entity = { charge = 0, active = false, inserted = false, } global.hoverboard[i] = entity end script.on_init(setup) function getTile(index) return game.players[index].surface.get_tile(game.players[index].position.x,game.players[index].position.y) end function getArmor(index) local armor = game.players[index].get_inventory(defines.inventory.player_armor)[1] return armor end function armorCheck(index) local armor = getArmor(index) if armor.valid_for_read and armor.has_grid then return true end return false end script.on_event(defines.events.on_tick, function(event) local n = 0 for k,v in pairs(game.players) do if global.hoverboard[k].inserted == true and global.hoverboard[k].active == true then locomotion(k) tileCheck(k) UI.updateStatus(k) end end end) script.on_event(defines.events.on_player_armor_inventory_changed, function(event) local index = event.player_index if armorCheck(index) then local armor = getArmor(index) local equipment = armor.grid.equipment for i, e in ipairs(equipment) do if e.name == "hoverboard" then activateEquipment(index) end end else deactivateEquipment(index) end end) script.on_event(defines.events.on_player_placed_equipment, function(event) local index = event.player_index if armorCheck(index) and event.equipment.name == "hoverboard" then activateEquipment(index) end end) script.on_event(defines.events.on_player_removed_equipment, function(event) local index = event.player_index if armorCheck(index) and event.equipment == "hoverboard" then deactivateEquipment(index) end end) script.on_event(defines.events.on_entity_died, function(event) if event.entity.name == "player" then global.dead = true end end) script.on_event(defines.events.on_gui_click,function(event) local index = event.player_index if event.element.name == "mode" then if global.hoverboard[index].active == false then global.hoverboard[index].active = true elseif global.hoverboard[index].active == true then global.hoverboard[index].active = false end UI.switchMode(global.hoverboard[index].active,index) end end) script.on_event(defines.events.on_built_entity,function(event) if event.created_entity.name == "accelerator" then game.player.print("beep") end end) function locomotion(index) local orientation = game.players[index].walking_state.direction if global.hoverboard[index].charge > 0 then global.hoverboard[index].charge = global.hoverboard[index].charge - 1 game.players[index].walking_state = {walking = true, direction = orientation} end end function inboundTile(name) local tiles = {"copper-floor", "copper-floor2", "copper-floor3","accelerator","down","left","up","right"} for _, tile in ipairs(tiles) do if tile == name then return true end end return false end function tileCheck(index) local tile = getTile(index) local walk = game.players[index].walking_state.walking if tile.name == "accelerator" then if global.hoverboard[index].charge <= 40 then global.hoverboard[index].charge = global.hoverboard[index].charge + 10 end elseif tile.name == "down" and global.hoverboard[index].charge > 0 then game.players[index].walking_state = {walking = walk, direction = defines.direction.south} elseif tile.name == "up" and global.hoverboard[index].charge > 0 then game.players[index].walking_state = {walking = walk, direction = defines.direction.north} elseif tile.name == "right" and global.hoverboard[index].charge > 0 then game.players[index].walking_state = {walking = walk, direction = defines.direction.east} elseif tile.name == "left" and global.hoverboard[index].charge > 0 then game.players[index].walking_state = {walking = walk, direction = defines.direction.west} elseif inboundTile(tile.name) == false then global.hoverboard[index].charge = 0 end end
fix a subtle bug in which the user is forcefully moved by arrows
fix a subtle bug in which the user is forcefully moved by arrows
Lua
mit
kiba/Factorio-MagneticFloor,kiba/Factorio-MagneticFloor
849edcdb4924c9a8895931e7d90a09eb7de52393
modules/message_dispatcher.lua
modules/message_dispatcher.lua
local ph = require('protocol_handler/protocol_handler') local config = require('config') local module = { mt = { __index = { } } } local fbuffer_mt = { __index = { } } local fstream_mt = { __index = { } } function module.FileStorage(filename) local res = {} res.filename = filename res.protocol_handler = ph.ProtocolHandler() res.wfd = io.open(filename, "w") res.rfd = io.open(filename, "r") setmetatable(res, fbuffer_mt) return res end function module.FileStream(filename, sessionId, service, bandwidth, chunksize) local res = { } res.filename = filename res.service = service res.sessionId = sessionId res.bandwidth = bandwidth res.bytesSent = 0 res.ts = timestamp() res.chunksize = chunksize or 1488 res.protocol_handler = ph.ProtocolHandler() res.messageId = 1 res.rfd, errmsg = io.open(filename, "r") if not res.rfd then error (errmsg) end setmetatable(res, fstream_mt) return res end function fbuffer_mt.__index:KeepMessage(msg) self.keep = msg end function fstream_mt.__index:KeepMessage(msg) self.keep = msg end function fbuffer_mt.__index:WriteMessage(msg) self.wfd:write(string.char(bit32.band(#msg, 0xff), bit32.band(bit32.rshift(#msg, 8), 0xff), bit32.band(bit32.rshift(#msg, 16), 0xff), bit32.band(bit32.rshift(#msg, 24), 0xff))) self.wfd:write(msg) end function fbuffer_mt.__index:Flush() self.wfd:flush() end function fstream_mt.__index:GetMessage() local timespan = timestamp() - self.ts local header = {} if timespan == 0 then return end if timespan > 5000 then self.ts = self.ts + timespan - 1000 self.bytesSent = self.bytesSent / (timespan / 1000) timespan = 1000 end if (self.bytesSent + self.chunksize) / (timespan / 1000) > self.bandwidth then return header, nil, 200 end local res = nil if self.keep then res = self.keep self.keep = nil return header, res end local data = self.rfd:read(self.chunksize) if data then self.bytesSent = self.bytesSent + #data self.messageId = self.messageId + 1 header = { version = config.defaultProtocolVersion or 2, encryption = false, sessionId = self.sessionId, frameInfo = 0, frameType = 1, serviceType = self.service, binaryData = data, messageId = self.messageId } res = table.concat(self.protocol_handler:Compose(header)) end return header, res end function fbuffer_mt.__index:GetMessage() local header = {} if self.keep then local res = self.keep self.keep = nil header = self.protocol_handler:Parse(self.keep) return header, res end local len = self.rfd:read(4) if len then len = bit32.lshift(string.byte(string.sub(len, 4, 4)), 24) + bit32.lshift(string.byte(string.sub(len, 3, 3)), 16) + bit32.lshift(string.byte(string.sub(len, 2, 2)), 8) + string.byte(string.sub(len, 1, 1)) local frame = self.rfd:read(len) local doNotValidateJson = true header = self.protocol_handler:Parse(frame, doNotValidateJson) return header, frame end return header, nil end function module.MessageDispatcher(connection) local res = {} res._d = qt.dynamic() res.generators = { } res.idx = 0 res.connection = connection res.bufferSize = 8192 res.mapped = { } res.timer = timers.Timer() res.timer:setSingleShot(true) function res._d:timeout() self:bytesWritten(0) end res.sender = qt.dynamic() function res.sender:SignalMessageSent() end function res._d:bytesWritten(c) if #res.generators == 0 then return end res.bufferSize = res.bufferSize + c for i = 1, #res.generators do if res.idx < #res.generators then res.idx = res.idx + 1 else res.idx = 1 end local header, msg, timeout = res.generators[res.idx]:GetMessage() if msg and #msg > 0 then if res.bufferSize > #msg then res.bufferSize = res.bufferSize - #msg res.connection:Send({ msg }) break else res.generators[res.idx]:KeepMessage(msg) end elseif timeout then res.timer:start(timeout) end end end res.connection:OnDataSent(function(self, num) res._d:bytesWritten(num) end) qt.connect(res.timer, "timeout()", res._d, "timeout()") setmetatable(res, module.mt) return res end function module.mt.__index:OnMessageSent(func) local d = qt.dynamic() function d:SlotMessageSent(v) func(v) end qt.connect(self.sender, "SignalMessageSent(int)", d, "SlotMessageSent(int)") end function module.mt.__index:MapFile(filebuffer) self.mapped[filebuffer.filename] = filebuffer table.insert(self.generators, filebuffer) end function module.mt.__index:UnmapFile(filebuffer) if not filebuffer then error("File was not mapped") end self.mapped[filebuffer.filename] = nil for i, g in ipairs(self.generators) do if g == filebuffer then table.remove(self.generators, i) break end end end function module.mt.__index:Pulse() self._d:bytesWritten(0) end return module
local ph = require('protocol_handler/protocol_handler') local module = { mt = { __index = { } } } local fbuffer_mt = { __index = { } } local fstream_mt = { __index = { } } function module.FileStorage(filename) local res = {} res.filename = filename res.protocol_handler = ph.ProtocolHandler() res.wfd = io.open(filename, "w") res.rfd = io.open(filename, "r") setmetatable(res, fbuffer_mt) return res end function module.FileStream(filename, sessionId, service, bandwidth, chunksize) local res = { } res.filename = filename res.service = service res.sessionId = sessionId res.bandwidth = bandwidth res.bytesSent = 0 res.ts = timestamp() res.chunksize = chunksize or 1488 res.protocol_handler = ph.ProtocolHandler() res.messageId = 1 res.rfd, errmsg = io.open(filename, "r") if not res.rfd then error (errmsg) end setmetatable(res, fstream_mt) return res end function fbuffer_mt.__index:KeepMessage(msg) self.keep = msg end function fstream_mt.__index:KeepMessage(msg) self.keep = msg end function fbuffer_mt.__index:WriteMessage(msg) self.wfd:write(string.char(bit32.band(#msg, 0xff), bit32.band(bit32.rshift(#msg, 8), 0xff), bit32.band(bit32.rshift(#msg, 16), 0xff), bit32.band(bit32.rshift(#msg, 24), 0xff))) self.wfd:write(msg) end function fbuffer_mt.__index:Flush() self.wfd:flush() end function fstream_mt.__index:GetMessage() local timespan = timestamp() - self.ts local header = {} if timespan == 0 then return end if timespan > 5000 then self.ts = self.ts + timespan - 1000 self.bytesSent = self.bytesSent / (timespan / 1000) timespan = 1000 end if (self.bytesSent + self.chunksize) / (timespan / 1000) > self.bandwidth then return header, nil, 200 end local res = nil if self.keep then res = self.keep self.keep = nil return header, res end local data = self.rfd:read(self.chunksize) if data then self.bytesSent = self.bytesSent + #data self.messageId = self.messageId + 1 header = { version = config.defaultProtocolVersion or 2, encryption = false, sessionId = self.sessionId, frameInfo = 0, frameType = 1, serviceType = self.service, binaryData = data, messageId = self.messageId } res = table.concat(self.protocol_handler:Compose(header)) end return header, res end function fbuffer_mt.__index:GetMessage() local header = {} if self.keep then local res = self.keep header = self.protocol_handler:Parse(self.keep) self.keep = nil return header, res end local len = self.rfd:read(4) if len then len = bit32.lshift(string.byte(string.sub(len, 4, 4)), 24) + bit32.lshift(string.byte(string.sub(len, 3, 3)), 16) + bit32.lshift(string.byte(string.sub(len, 2, 2)), 8) + string.byte(string.sub(len, 1, 1)) local frame = self.rfd:read(len) local doNotValidateJson = true header = self.protocol_handler:Parse(frame, doNotValidateJson) return header, frame end return header, nil end function module.MessageDispatcher(connection) local res = {} res._d = qt.dynamic() res.generators = { } res.idx = 0 res.connection = connection res.bufferSize = 8192 res.mapped = { } res.timer = timers.Timer() res.timer:setSingleShot(true) function res._d:timeout() self:bytesWritten(0) end res.sender = qt.dynamic() function res.sender:SignalMessageSent() end function res._d:bytesWritten(c) if #res.generators == 0 then return end res.bufferSize = res.bufferSize + c for i = 1, #res.generators do if res.idx < #res.generators then res.idx = res.idx + 1 else res.idx = 1 end local header, msg, timeout = res.generators[res.idx]:GetMessage() if msg and #msg > 0 then if res.bufferSize > #msg then res.bufferSize = res.bufferSize - #msg res.connection:Send({ msg }) break else res.generators[res.idx]:KeepMessage(msg) end elseif timeout then res.timer:start(timeout) end end end res.connection:OnDataSent(function(self, num) res._d:bytesWritten(num) end) qt.connect(res.timer, "timeout()", res._d, "timeout()") setmetatable(res, module.mt) return res end function module.mt.__index:OnMessageSent(func) local d = qt.dynamic() function d:SlotMessageSent(v) func(v) end qt.connect(self.sender, "SignalMessageSent(int)", d, "SlotMessageSent(int)") end function module.mt.__index:MapFile(filebuffer) self.mapped[filebuffer.filename] = filebuffer table.insert(self.generators, filebuffer) end function module.mt.__index:UnmapFile(filebuffer) if not filebuffer then error("File was not mapped") end self.mapped[filebuffer.filename] = nil for i, g in ipairs(self.generators) do if g == filebuffer then table.remove(self.generators, i) break end end end function module.mt.__index:Pulse() self._d:bytesWritten(0) end return module
Fix: ATF is stopped when sending many requests APPLINK-13004:ATF is stopped when sending many requests
Fix: ATF is stopped when sending many requests APPLINK-13004:ATF is stopped when sending many requests
Lua
bsd-3-clause
aderiabin/sdl_atf,aderiabin/sdl_atf,aderiabin/sdl_atf
149ea711b0b60034d671863c497c6c994910e782
src/plugins/finalcutpro/tangent/browser.lua
src/plugins/finalcutpro/tangent/browser.lua
--- === plugins.finalcutpro.tangent.browser === --- --- Final Cut Pro Tangent Browser Group local require = require --local log = require("hs.logger").new("tangentBrowser") local timer = require("hs.timer") local fcp = require("cp.apple.finalcutpro") local i18n = require("cp.i18n") local tools = require("cp.tools") local rescale = tools.rescale local delayed = timer.delayed -------------------------------------------------------------------------------- -- -- THE MODULE: -- -------------------------------------------------------------------------------- local mod = {} -------------------------------------------------------------------------------- -- -- THE PLUGIN: -- -------------------------------------------------------------------------------- local plugin = { id = "finalcutpro.tangent.browser", group = "finalcutpro", dependencies = { ["finalcutpro.tangent.group"] = "fcpGroup", } } function plugin.init(deps) local id = 0x00140000 local fcpGroup = deps.fcpGroup local group = fcpGroup:group(i18n("browser")) -------------------------------------------------------------------------------- -- Browser Duration: -------------------------------------------------------------------------------- local hidePopup = delayed.new(0.5, function() if fcp:libraries():appearanceAndFiltering():isShowing() then fcp:libraries():appearanceAndFiltering():hide() end end) local durations = fcp:libraries():appearanceAndFiltering().DURATION group:menu(id + 1) :name(i18n("duration")) :name9(i18n("duration")) :onGet(function() local value = fcp:libraries():appearanceAndFiltering():duration():value() if value then for t, n in pairs(durations) do if value == n then return t end end end end) :onNext(function() fcp:libraries():appearanceAndFiltering():show():duration():increment() hidePopup:start() end) :onPrev(function() fcp:libraries():appearanceAndFiltering():show():duration():decrement() hidePopup:start() end) :onReset(function() fcp:libraries():appearanceAndFiltering():show():duration():value(0) fcp:libraries():appearanceAndFiltering():hide() end) id = id + 1 -------------------------------------------------------------------------------- -- Browser Clip Height: -------------------------------------------------------------------------------- group:menu(id + 1) :name(i18n("height")) :name9(i18n("height")) :onGet(function() local value = fcp:libraries():appearanceAndFiltering():clipHeight():value() if value then local rescaled = rescale(value, 32, 135, 1, 100) return rescaled and tostring(rescaled) .. "%" end end) :onNext(function() fcp:libraries():appearanceAndFiltering():show():clipHeight():increment() hidePopup:start() end) :onPrev(function() fcp:libraries():appearanceAndFiltering():show():clipHeight():decrement() hidePopup:start() end) :onReset(function() fcp:libraries():appearanceAndFiltering():show():clipHeight():value(0) fcp:libraries():appearanceAndFiltering():hide() end) id = id + 1 end return plugin
--- === plugins.finalcutpro.tangent.browser === --- --- Final Cut Pro Tangent Browser Group local require = require --local log = require("hs.logger").new("tangentBrowser") local timer = require("hs.timer") local fcp = require("cp.apple.finalcutpro") local i18n = require("cp.i18n") local tools = require("cp.tools") local rescale = tools.rescale local delayed = timer.delayed -------------------------------------------------------------------------------- -- -- THE PLUGIN: -- -------------------------------------------------------------------------------- local plugin = { id = "finalcutpro.tangent.browser", group = "finalcutpro", dependencies = { ["finalcutpro.tangent.group"] = "fcpGroup", } } function plugin.init(deps) local id = 0x00140000 local fcpGroup = deps.fcpGroup local group = fcpGroup:group(i18n("browser")) -------------------------------------------------------------------------------- -- Browser Duration: -------------------------------------------------------------------------------- local hidePopup = delayed.new(0.5, function() if fcp:libraries():appearanceAndFiltering():isShowing() then fcp:libraries():appearanceAndFiltering():hide() end end) local durations = fcp:libraries():appearanceAndFiltering().DURATION group:menu(id + 1) :name(i18n("duration")) :name9(i18n("duration")) :onGet(function() local value = fcp:libraries():appearanceAndFiltering():duration():value() if value then for t, n in pairs(durations) do if value == n then return t end end end end) :onNext(function() fcp:libraries():appearanceAndFiltering():show():duration():increment() hidePopup:start() end) :onPrev(function() fcp:libraries():appearanceAndFiltering():show():duration():decrement() hidePopup:start() end) :onReset(function() fcp:libraries():appearanceAndFiltering():show():duration():value(0) fcp:libraries():appearanceAndFiltering():hide() end) id = id + 1 -------------------------------------------------------------------------------- -- Browser Clip Height: -------------------------------------------------------------------------------- group:menu(id + 1) :name(i18n("height")) :name9(i18n("height")) :onGet(function() local value = fcp:libraries():appearanceAndFiltering():clipHeight():value() if value then local rescaled = rescale(value, 32, 135, 1, 100) return rescaled and tostring(rescaled) .. "%" end end) :onNext(function() fcp:libraries():appearanceAndFiltering():show():clipHeight():increment() hidePopup:start() end) :onPrev(function() fcp:libraries():appearanceAndFiltering():show():clipHeight():decrement() hidePopup:start() end) :onReset(function() fcp:libraries():appearanceAndFiltering():show():clipHeight():value(0) fcp:libraries():appearanceAndFiltering():hide() end) end return plugin
#1732
#1732 - Fixed @stickler-ci errors
Lua
mit
CommandPost/CommandPost,fcpxhacks/fcpxhacks,fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost
31c878675abfdef589ce80980771e387f0b52393
core/ext/pm/buffer_browser.lua
core/ext/pm/buffer_browser.lua
-- Copyright 2007-2008 Mitchell mitchell<att>caladbolg.net. See LICENSE. --- -- 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) 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 '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 function get_context_menu(selected_item) return { '_New', '_Open', '_Save', 'Save _As...', 'separator', '_Close' } end function perform_menu_action(menu_item, selected_item) if menu_item == 'New' then textadept.new_buffer() elseif menu_item == 'Open' then textadept.io.open() elseif menu_item == 'Save' then textadept.buffers[ tonumber( selected_item[2] ) ]:save() elseif menu_item == 'Save As...' then textadept.buffers[ tonumber( selected_item[2] ) ]:save_as() elseif menu_item == 'Close' then textadept.buffers[ tonumber( selected_item[2] ) ]:close() end textadept.pm.activate() end local add_handler = textadept.events.add_handler local function update_view() if matches(textadept.pm.entry_text) then textadept.pm.activate() end end add_handler('file_opened', update_view) add_handler('buffer_new', update_view) add_handler('buffer_deleted', update_view) add_handler('save_point_reached', update_view) add_handler('save_point_left', update_view)
-- Copyright 2007-2008 Mitchell mitchell<att>caladbolg.net. See LICENSE. --- -- 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) 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 '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 function get_context_menu(selected_item) return { '_New', '_Open', '_Save', 'Save _As...', 'separator', '_Close' } end function perform_menu_action(menu_item, selected_item) if menu_item == 'New' then textadept.new_buffer() elseif menu_item == 'Open' then textadept.io.open() elseif menu_item == 'Save' then view:goto_buffer( tonumber( selected_item[2] ) ) buffer:save() elseif menu_item == 'Save As...' then view:goto_buffer( tonumber( selected_item[2] ) ) buffer:save_as() elseif menu_item == 'Close' then view:goto_buffer( tonumber( selected_item[2] ) ) buffer:close() end textadept.pm.activate() end local add_handler = textadept.events.add_handler local function update_view() if matches(textadept.pm.entry_text) then textadept.pm.activate() end end add_handler('file_opened', update_view) add_handler('buffer_new', update_view) add_handler('buffer_deleted', update_view) add_handler('save_point_reached', update_view) add_handler('save_point_left', update_view)
Fixed bug for menu actions on non-focused buffer; core/ext/pm/buffer_browser.lua
Fixed bug for menu actions on non-focused buffer; core/ext/pm/buffer_browser.lua
Lua
mit
rgieseke/textadept,rgieseke/textadept
bb32f61c7c0aec838cb30d0f457594e5af98d1d0
premake5.lua
premake5.lua
solution "libdrone" configurations { "Debug", "Release" } platforms { "linux", "mingw" } location "build" configuration "Debug" flags { "Symbols" } project "drone" kind "SharedLib" language "C++" location "build/libdrone" -- Enable C++11 buildoptions { "-std=c++11", "-DBOOST_LOG_DYN_LINK" } -- Source files and library headers includedirs { "include" } files { "src/**.h", "src/**.cpp" } -- For Linux configuration { "linux" } -- Include third-party libraries includedirs { "/opt/ffmpeg/include", "/opt/opencv/include", "/usr/include/eigen3" } -- Link libraries libdirs { "/opt/ffmpeg/lib/", "/opt/opencv/lib/" } links { "boost_system", "boost_thread", "boost_timer", "boost_filesystem", "boost_log", "boost_date_time", "opencv_core", "opencv_highgui", "opencv_imgcodecs", "opencv_imgproc", "avcodec", "avutil", "avformat", "swresample", "swscale" } -- For MinGW on Windows configuration { "mingw" } -- Include third-party libraries includedirs { "C:/boost/build/include/boost-1_58", "C:/ffmpeg/include", "C:/opencv/install/include", "C:/eigen3/include" } -- Link libraries libdirs { "C:/boost/build/lib", "C:/ffmpeg/lib/", "C:/opencv/install/x86/mingw/lib" } links { "ws2_32", "boost_system-mgw49-mt-d-1_58", "boost_thread-mgw49-mt-d-1_58", "boost_timer-mgw49-mt-d-1_58", "boost_filesystem-mgw49-mt-d-1_58", "boost_chrono-mgw49-mt-d-1_58", "boost_log-mgw49-mt-d-1_58", "boost_date_time-mgw49-mt-d-1_58", "opencv_core300", "opencv_highgui300", "opencv_imgcodecs300", "opencv_imgproc300", "avcodec", "avutil", "avformat", "swresample", "swscale" } project "example-basic" kind "ConsoleApp" language "C++" location "build/examples/basic" -- Enable C++11 buildoptions { "-std=c++11", "-DBOOST_LOG_DYN_LINK" } -- Include libdrone includedirs { "include" } -- Source files files { "examples/basic/**.h", "examples/basic/**.cpp" } configuration { "linux" } -- Include third-party libraries includedirs { "/opt/ffmpeg/include", "/opt/opencv/include", "/usr/include/eigen3" } -- Link libraries libdirs { "/opt/ffmpeg/lib/", "/opt/opencv/lib/" } links { "boost_system", "boost_thread", "boost_timer", "boost_log", "boost_date_time", "opencv_core", "opencv_highgui", "opencv_imgcodecs", "opencv_imgproc", "avcodec", "avutil", "avformat", "swresample", "swscale", "drone" } -- For MinGW on Windows configuration { "mingw" } -- Include third-party libraries includedirs { "C:/boost/build/include/boost-1_58", "C:/ffmpeg/include", "C:/opencv/install/include", "C:/eigen3/include" } -- Link libraries libdirs { "C:/boost/build/lib", "C:/ffmpeg/lib/", "C:/opencv/install/x86/mingw/lib" } links { "ws2_32", "boost_system-mgw49-mt-d-1_58", "boost_thread-mgw49-mt-d-1_58", "boost_timer-mgw49-mt-d-1_58", "boost_log-mgw49-mt-d-1_58", "boost_date_time-mgw49-mt-d-1_58", "opencv_core300", "opencv_highgui300", "opencv_imgcodecs300", "opencv_imgproc300", "avcodec", "avutil", "avformat", "swresample", "swscale", "drone" }
solution "libdrone" configurations { "Debug", "Release" } platforms { "linux", "mingw" } location "build" configuration "Debug" flags { "Symbols" } project "drone" kind "SharedLib" language "C++" location "build/libdrone" -- Enable C++11 buildoptions { "-std=c++11", "-DBOOST_LOG_DYN_LINK" } -- Source files and library headers includedirs { "include" } files { "src/**.h", "src/**.cpp" } -- For Linux configuration { "linux" } -- Include third-party libraries includedirs { "/opt/ffmpeg/include", "/opt/opencv/include", "/usr/include/eigen3" } -- Link libraries libdirs { "/opt/ffmpeg/lib/", "/opt/opencv/lib/" } links { "boost_system", "boost_thread", "boost_timer", "boost_filesystem", "boost_log", "boost_date_time", "opencv_core", "opencv_highgui", "opencv_imgcodecs", "opencv_imgproc", "avcodec", "avutil", "avformat", "swresample", "swscale" } -- For MinGW on Windows configuration { "mingw" } -- Include third-party libraries includedirs { "C:/boost/include/boost-1_58", "C:/ffmpeg/include", "C:/opencv/include", "C:/eigen3/include/eigen3" } -- Link libraries libdirs { "C:/boost/lib", "C:/ffmpeg/lib/", "C:/opencv/x86/mingw/lib" } links { "ws2_32", "boost_system-mgw49-mt-d-1_58", "boost_thread-mgw49-mt-d-1_58", "boost_timer-mgw49-mt-d-1_58", "boost_filesystem-mgw49-mt-d-1_58", "boost_chrono-mgw49-mt-d-1_58", "boost_log-mgw49-mt-d-1_58", "boost_date_time-mgw49-mt-d-1_58", "opencv_core300", "opencv_highgui300", "opencv_imgcodecs300", "opencv_imgproc300", "avcodec", "avutil", "avformat", "swresample", "swscale" } project "example-basic" kind "ConsoleApp" language "C++" location "build/examples/basic" -- Enable C++11 buildoptions { "-std=c++11", "-DBOOST_LOG_DYN_LINK" } -- Include libdrone includedirs { "include" } -- Source files files { "examples/basic/**.h", "examples/basic/**.cpp" } configuration { "linux" } -- Include third-party libraries includedirs { "/opt/ffmpeg/include", "/opt/opencv/include", "/usr/include/eigen3" } -- Link libraries libdirs { "/opt/ffmpeg/lib/", "/opt/opencv/lib/" } links { "boost_system", "boost_thread", "boost_timer", "boost_log", "boost_date_time", "opencv_core", "opencv_highgui", "opencv_imgcodecs", "opencv_imgproc", "avcodec", "avutil", "avformat", "swresample", "swscale", "drone" } -- For MinGW on Windows configuration { "mingw" } -- Include third-party libraries includedirs { "C:/boost/include/boost-1_58", "C:/ffmpeg/include", "C:/opencv/include", "C:/eigen3/include/eigen3" } -- Link libraries libdirs { "C:/boost/lib", "C:/ffmpeg/lib/", "C:/opencv/x86/mingw/lib" } links { "ws2_32", "boost_system-mgw49-mt-d-1_58", "boost_thread-mgw49-mt-d-1_58", "boost_timer-mgw49-mt-d-1_58", "boost_log-mgw49-mt-d-1_58", "boost_date_time-mgw49-mt-d-1_58", "opencv_core300", "opencv_highgui300", "opencv_imgcodecs300", "opencv_imgproc300", "avcodec", "avutil", "avformat", "swresample", "swscale", "drone" }
Fixes for Windows
Fixes for Windows
Lua
mit
lukaslaobeyer/libdrone,lukaslaobeyer/libdrone,lukaslaobeyer/libdrone
7b54859e358eedc42c1bf94c43330bfbe5f46dc4
build/ode.lua
build/ode.lua
package.name = "ode" package.language = "c++" package.objdir = "obj/ode" -- Separate distribution files into toolset subdirectories if (options["usetargetpath"]) then package.path = options["target"] else package.path = "custom" end -- Write a custom <config.h> to include/ode, based on the specified flags io.input("config-default.h") local text = io.read("*a") if (options["with-doubles"]) then text = string.gsub(text, "#define dSINGLE", "/* #define dSINGLE */") text = string.gsub(text, "/%* #define dDOUBLE %*/", "#define dDOUBLE") end if (options["no-trimesh"]) then text = string.gsub(text, "#define dTRIMESH_ENABLED 1", "/* #define dTRIMESH_ENABLED 1 */") end if (options["with-gimpact"]) then text = string.gsub(text, "#define dTRIMESH_OPCODE 1", "#define dTRIMESH_GIMPACT 1") end if (options["no-alloca"]) then text = string.gsub(text, "/%* #define dUSE_MALLOC_FOR_ALLOCA %*/", "#define dUSE_MALLOC_FOR_ALLOCA") end io.output("../include/ode/config.h") io.write(text) io.close() -- Package Build Settings if (options["enable-shared-only"]) then package.kind = "dll" table.insert(package.defines, "ODE_DLL") elseif (options["enable-static-only"]) then package.kind = "lib" table.insert(package.defines, "ODE_LIB") else package.config["DebugDLL"].kind = "dll" package.config["DebugLib"].kind = "lib" package.config["ReleaseDLL"].kind = "dll" package.config["ReleaseLib"].kind = "lib" table.insert(package.config["DebugDLL"].defines, "ODE_DLL") table.insert(package.config["ReleaseDLL"].defines, "ODE_DLL") table.insert(package.config["DebugLib"].defines, "ODE_LIB") table.insert(package.config["ReleaseLib"].defines, "ODE_LIB") end package.includepaths = { "../../include", "../../OPCODE", "../../GIMPACT/include" } if (windows) then table.insert(package.defines, "WIN32") end -- disable VS2005 CRT security warnings if (options["target"] == "vs2005") then table.insert(package.defines, "_CRT_SECURE_NO_DEPRECATE") end -- Build Flags package.config["DebugLib"].buildflags = { } package.config["DebugDLL"].buildflags = { } package.config["ReleaseDLL"].buildflags = { "optimize-speed", "no-symbols", "no-frame-pointer" } package.config["ReleaseLib"].buildflags = { "optimize-speed", "no-symbols", "no-frame-pointer" } if (options.target == "vs6" or options.target == "vs2002" or options.target == "vs2003") then table.insert(package.config.DebugLib.buildflags, "static-runtime") table.insert(package.config.ReleaseLib.buildflags, "static-runtime") end -- Libraries if (windows) then table.insert(package.links, "user32") end -- Files core_files = { matchfiles("../../include/ode/*.h"), matchfiles ("../../ode/src/*.h", "../../ode/src/*.c", "../../ode/src/*.cpp") } excluded_files = { "../../ode/src/collision_std.cpp", "../../ode/src/scrapbook.cpp", "../../ode/src/stack.cpp" } trimesh_files = { "../../ode/src/collision_trimesh_internal.h", "../../ode/src/collision_trimesh_opcode.cpp", "../../ode/src/collision_trimesh_gimpact.cpp", "../../ode/src/collision_trimesh_box.cpp", "../../ode/src/collision_trimesh_ccylinder.cpp", "../../ode/src/collision_cylinder_trimesh.cpp", "../../ode/src/collision_trimesh_distance.cpp", "../../ode/src/collision_trimesh_ray.cpp", "../../ode/src/collision_trimesh_sphere.cpp", "../../ode/src/collision_trimesh_trimesh.cpp", "../../ode/src/collision_trimesh_plane.cpp" } opcode_files = { matchrecursive("../../OPCODE/*.h", "../../OPCODE/*.cpp") } gimpact_files = { matchrecursive("../../GIMPACT/*.h", "../../GIMPACT/*.cpp") } dif_files = { "../../ode/src/export-dif.cpp" } package.files = { core_files } package.excludes = { excluded_files } if (options["no-dif"]) then table.insert(package.excludes, dif_files) end if (options["no-trimesh"]) then table.insert(package.excludes, trimesh_files) else table.insert(package.files, gimpact_files) table.insert(package.files, opcode_files) end
package.name = "ode" package.language = "c++" package.objdir = "obj/ode" -- Separate distribution files into toolset subdirectories if (options["usetargetpath"]) then package.path = options["target"] else package.path = "custom" end -- Write a custom <config.h> to include/ode, based on the specified flags io.input("config-default.h") local text = io.read("*a") if (options["with-doubles"]) then text = string.gsub(text, "#define dSINGLE", "/* #define dSINGLE */") text = string.gsub(text, "/%* #define dDOUBLE %*/", "#define dDOUBLE") end if (options["no-trimesh"]) then text = string.gsub(text, "#define dTRIMESH_ENABLED 1", "/* #define dTRIMESH_ENABLED 1 */") text = string.gsub(text, "#define dTRIMESH_OPCODE 1", "/* #define dTRIMESH_OPCODE 1 */") elseif (options["with-gimpact"]) then text = string.gsub(text, "#define dTRIMESH_OPCODE 1", "#define dTRIMESH_GIMPACT 1") end if (options["no-alloca"]) then text = string.gsub(text, "/%* #define dUSE_MALLOC_FOR_ALLOCA %*/", "#define dUSE_MALLOC_FOR_ALLOCA") end io.output("../include/ode/config.h") io.write(text) io.close() -- Package Build Settings if (options["enable-shared-only"]) then package.kind = "dll" table.insert(package.defines, "ODE_DLL") elseif (options["enable-static-only"]) then package.kind = "lib" table.insert(package.defines, "ODE_LIB") else package.config["DebugDLL"].kind = "dll" package.config["DebugLib"].kind = "lib" package.config["ReleaseDLL"].kind = "dll" package.config["ReleaseLib"].kind = "lib" table.insert(package.config["DebugDLL"].defines, "ODE_DLL") table.insert(package.config["ReleaseDLL"].defines, "ODE_DLL") table.insert(package.config["DebugLib"].defines, "ODE_LIB") table.insert(package.config["ReleaseLib"].defines, "ODE_LIB") end package.includepaths = { "../../include", "../../OPCODE", "../../GIMPACT/include" } if (windows) then table.insert(package.defines, "WIN32") end -- disable VS2005 CRT security warnings if (options["target"] == "vs2005") then table.insert(package.defines, "_CRT_SECURE_NO_DEPRECATE") end -- Build Flags package.config["DebugLib"].buildflags = { } package.config["DebugDLL"].buildflags = { } package.config["ReleaseDLL"].buildflags = { "optimize-speed", "no-symbols", "no-frame-pointer" } package.config["ReleaseLib"].buildflags = { "optimize-speed", "no-symbols", "no-frame-pointer" } if (options.target == "vs6" or options.target == "vs2002" or options.target == "vs2003") then table.insert(package.config.DebugLib.buildflags, "static-runtime") table.insert(package.config.ReleaseLib.buildflags, "static-runtime") end -- Libraries if (windows) then table.insert(package.links, "user32") end -- Files core_files = { matchfiles("../../include/ode/*.h"), matchfiles ("../../ode/src/*.h", "../../ode/src/*.c", "../../ode/src/*.cpp") } excluded_files = { "../../ode/src/collision_std.cpp", "../../ode/src/scrapbook.cpp", "../../ode/src/stack.cpp" } trimesh_files = { "../../ode/src/collision_trimesh_internal.h", "../../ode/src/collision_trimesh_opcode.cpp", "../../ode/src/collision_trimesh_gimpact.cpp", "../../ode/src/collision_trimesh_box.cpp", "../../ode/src/collision_trimesh_ccylinder.cpp", "../../ode/src/collision_cylinder_trimesh.cpp", "../../ode/src/collision_trimesh_distance.cpp", "../../ode/src/collision_trimesh_ray.cpp", "../../ode/src/collision_trimesh_sphere.cpp", "../../ode/src/collision_trimesh_trimesh.cpp", "../../ode/src/collision_trimesh_plane.cpp" } opcode_files = { matchrecursive("../../OPCODE/*.h", "../../OPCODE/*.cpp") } gimpact_files = { matchrecursive("../../GIMPACT/*.h", "../../GIMPACT/*.cpp") } dif_files = { "../../ode/src/export-dif.cpp" } package.files = { core_files } package.excludes = { excluded_files } if (options["no-dif"]) then table.insert(package.excludes, dif_files) end if (options["no-trimesh"]) then table.insert(package.excludes, trimesh_files) else table.insert(package.files, gimpact_files) table.insert(package.files, opcode_files) end
Fix for build error when using a manually generated project (i.e. dumping in all of the files) and premake to generate config.h with the --no-trimesh option. This was due to "#define dTRIMESH_OPCODE 1" still being present in 'collision_trimesh_internal.h'. Also it now ignores '--with-gimpact' if --no-trimesh is used as they are mutually exclusive.
Fix for build error when using a manually generated project (i.e. dumping in all of the files) and premake to generate config.h with the --no-trimesh option. This was due to "#define dTRIMESH_OPCODE 1" still being present in 'collision_trimesh_internal.h'. Also it now ignores '--with-gimpact' if --no-trimesh is used as they are mutually exclusive.
Lua
lgpl-2.1
forrestv/opende,forrestv/opende,forrestv/opende,forrestv/opende,forrestv/opende
1713e2ab0b055706c956eab5539a54715b7f4df5
reader.lua
reader.lua
#!./kpdfview --[[ KindlePDFViewer: a reader implementation Copyright (C) 2011 Hans-Werner Hilse <[email protected]> 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 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]]-- require "alt_getopt" require "pdfreader" require "filechooser" require "settings" -- option parsing: longopts = { password = "p", goto = "g", gamma = "G", device = "d", help = "h" } optarg, optind = alt_getopt.get_opts(ARGV, "p:G:hg:d:", longopts) if optarg["h"] or ARGV[optind] == nil then print("usage: ./reader.lua [OPTION] ... DOCUMENT.PDF") print("Read PDFs on your E-Ink reader") print("") print("-p, --password=PASSWORD set password for reading PDF document") print("-g, --goto=page start reading on page") print("-G, --gamma=GAMMA set gamma correction") print(" (floating point notation, e.g. \"1.5\")") print("-d, --device=DEVICE set device specific configuration,") print(" currently one of \"kdxg\" (default), \"k3\"") print(" \"emu\" (DXG emulation)") print("-h, --help show this usage help") print("") print("If you give the name of a directory instead of a path, a file") print("chooser will show up and let you select a PDF file") print("") print("This software is licensed under the GPLv3.") print("See http://github.com/hwhw/kindlepdfviewer for more info.") return end if optarg["d"] == "k3" then -- for now, the only difference is the additional input device input.open("/dev/input/event0") input.open("/dev/input/event1") input.open("/dev/input/event2") set_k3_keycodes() elseif optarg["d"] == "emu" then input.open("") -- SDL key codes set_emu_keycodes() else input.open("/dev/input/event0") input.open("/dev/input/event1") -- check if we are running on Kindle 3 (additional volume input) local f=lfs.attributes("/dev/input/event2") print(f) if f then print("Auto-detected Kindle 3") input.open("/dev/input/event2") set_k3_keycodes() end end if optarg["G"] ~= nil then globalgamma = optarg["G"] end fb = einkfb.open("/dev/fb0") width, height = fb:getSize() -- set up reader's setting: font reader_settings = DocSettings:open(".reader") r_cfont = reader_settings:readsetting("cfont") if r_cfont ~=nil then FontChooser.cfont = r_cfont end if lfs.attributes(ARGV[optind], "mode") == "directory" then local running = true FileChooser:setPath(ARGV[optind]) while running do local pdffile = FileChooser:choose(0,height) if pdffile ~= nil then if PDFReader:open(pdffile,"") then -- TODO: query for password PDFReader:goto(tonumber(PDFReader.settings:readsetting("last_page") or 1)) PDFReader:inputloop() end else running = false end end else PDFReader:open(ARGV[optind], optarg["p"]) PDFReader:goto(tonumber(optarg["g"]) or tonumber(PDFReader.settings:readsetting("last_page") or 1)) PDFReader:inputloop() end -- save reader settings reader_settings:savesetting("cfont", FontChooser.cfont) reader_settings:close() input.closeAll() os.execute('test -e /proc/keypad && echo "send '..KEY_HOME..'" > /proc/keypad ')
#!./kpdfview --[[ KindlePDFViewer: a reader implementation Copyright (C) 2011 Hans-Werner Hilse <[email protected]> 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 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]]-- require "alt_getopt" require "pdfreader" require "filechooser" require "settings" -- option parsing: longopts = { password = "p", goto = "g", gamma = "G", device = "d", help = "h" } optarg, optind = alt_getopt.get_opts(ARGV, "p:G:hg:d:", longopts) if optarg["h"] or ARGV[optind] == nil then print("usage: ./reader.lua [OPTION] ... DOCUMENT.PDF") print("Read PDFs on your E-Ink reader") print("") print("-p, --password=PASSWORD set password for reading PDF document") print("-g, --goto=page start reading on page") print("-G, --gamma=GAMMA set gamma correction") print(" (floating point notation, e.g. \"1.5\")") print("-d, --device=DEVICE set device specific configuration,") print(" currently one of \"kdxg\" (default), \"k3\"") print(" \"emu\" (DXG emulation)") print("-h, --help show this usage help") print("") print("If you give the name of a directory instead of a path, a file") print("chooser will show up and let you select a PDF file") print("") print("This software is licensed under the GPLv3.") print("See http://github.com/hwhw/kindlepdfviewer for more info.") return end if optarg["d"] == "k3" then -- for now, the only difference is the additional input device input.open("/dev/input/event0") input.open("/dev/input/event1") input.open("/dev/input/event2") set_k3_keycodes() elseif optarg["d"] == "emu" then input.open("") -- SDL key codes set_emu_keycodes() else input.open("/dev/input/event0") input.open("/dev/input/event1") -- check if we are running on Kindle 3 (additional volume input) local f=lfs.attributes("/dev/input/event2") print(f) if f then print("Auto-detected Kindle 3") input.open("/dev/input/event2") set_k3_keycodes() end end if optarg["G"] ~= nil then globalgamma = optarg["G"] end fb = einkfb.open("/dev/fb0") width, height = fb:getSize() -- set up reader's setting: font reader_settings = DocSettings:open(".reader") r_cfont = reader_settings:readsetting("cfont") if r_cfont ~=nil then FontChooser.cfont = r_cfont end if lfs.attributes(ARGV[optind], "mode") == "directory" then local running = true FileChooser:setPath(ARGV[optind]) while running do local pdffile = FileChooser:choose(0,height) if pdffile ~= nil then if PDFReader:open(pdffile,"") then -- TODO: query for password PDFReader:goto(tonumber(PDFReader.settings:readsetting("last_page") or 1)) PDFReader:inputloop() end else running = false end end else PDFReader:open(ARGV[optind], optarg["p"]) PDFReader:goto(tonumber(optarg["g"]) or tonumber(PDFReader.settings:readsetting("last_page") or 1)) PDFReader:inputloop() end -- save reader settings reader_settings:savesetting("cfont", FontChooser.cfont) reader_settings:close() input.closeAll() --os.execute('test -e /proc/keypad && echo "send '..KEY_HOME..'" > /proc/keypad ') if optarg["d"] ~= "emu" then os.execute('echo "send '..KEY_MENU..'" > /proc/keypad;echo "send '..KEY_MENU..'" > /proc/keypad') end
fix: refresh screen more elegantly after reader exit
fix: refresh screen more elegantly after reader exit
Lua
agpl-3.0
apletnev/koreader,chihyang/koreader,poire-z/koreader,Hzj-jie/koreader-base,koreader/koreader-base,frankyifei/koreader-base,pazos/koreader,houqp/koreader-base,Frenzie/koreader-base,chrox/koreader,Frenzie/koreader-base,NiLuJe/koreader,NiLuJe/koreader-base,NickSavage/koreader,koreader/koreader-base,houqp/koreader,NiLuJe/koreader-base,apletnev/koreader-base,Frenzie/koreader,houqp/koreader-base,Hzj-jie/koreader,houqp/koreader-base,apletnev/koreader-base,frankyifei/koreader-base,koreader/koreader,frankyifei/koreader,Hzj-jie/koreader-base,poire-z/koreader,ashang/koreader,Frenzie/koreader-base,koreader/koreader-base,apletnev/koreader-base,NiLuJe/koreader-base,mihailim/koreader,mwoz123/koreader,Hzj-jie/koreader-base,lgeek/koreader,frankyifei/koreader-base,NiLuJe/koreader-base,Hzj-jie/koreader-base,robert00s/koreader,apletnev/koreader-base,Frenzie/koreader-base,noname007/koreader,ashhher3/koreader,NiLuJe/koreader,houqp/koreader-base,koreader/koreader-base,frankyifei/koreader-base,Frenzie/koreader,koreader/koreader,Markismus/koreader
11bc5fe5215961c2fb05699f302451e29b40f87c
baraza.lua
baraza.lua
dofile("urlcode.lua") dofile("table_show.lua") local url_count = 0 local tries = 0 local item_type = os.getenv('item_type') local item_value = os.getenv('item_value') local downloaded = {} local addedtolist = {} local ids = {} read_file = function(file) if file then local f = assert(io.open(file)) local data = f:read("*all") f:close() return data else return "" end end wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason) local url = urlpos["url"]["url"] local html = urlpos["link_expect_html"] if downloaded[url] == true or addedtolist[url] == true then return false end if item_type == "labelen" and (downloaded[url] ~= true or addedtolist[url] ~= true) then if (string.match(url, item_value) or html == 0) and not (string.match(url, "accounts%.google%.com") or string.match(url, "google%.com/accounts/") or string.match(url, "loginredirect%?")) then addedtolist[url] = true return true else return false end end end wget.callbacks.get_urls = function(file, url, is_css, iri) local urls = {} local html = nil local function check(url, origurl) if (downloaded[url] ~= true and addedtolist[url] ~= true) and not (string.match(url, "accounts%.google%.com") or string.match(url, "google%.com/accounts/") or string.match(url, "loginredirect%?")) then if string.match(url, "&amp;") then table.insert(urls, { url=string.gsub(url, "&amp;", "&") }) addedtolist[url] = true addedtolist[string.gsub(url, "&amp;", "&")] = true else table.insert(urls, { url=url }) addedtolist[url] = true end if string.match(url, "/thread%?tid=[a-z0-9]+") then if ids[string.match(url, "/thread%?tid=([a-z0-9]+)")] ~= true then ids[string.match(url, "/thread%?tid=([a-z0-9]+)")] = true check("http://www.google.com/baraza/en/thread?tid="..string.match(url, "/thread%?tid=([a-z0-9]+)")) end end end end if not ids[item_value] == true then ids[item_value] = true end if item_type == "labelen" then for id in string.gmatch(url, "=([a-z0-9]+)") do if ids[id] == true then html = read_file(file) for newurl in string.gmatch(html, '"(https?://[^"]+)"') do if string.match(newurl, item_value) or string.match(newurl, id) then check(newurl) end end for newurl in string.gmatch(html, '"(/[^"]+)"') do if string.match(newurl, item_value) or string.match(newurl, id) then check("http://www.google.com"..newurl) end end end end end return urls end wget.callbacks.httploop_result = function(url, err, http_stat) -- NEW for 2014: Slightly more verbose messages because people keep -- complaining that it's not moving or not working status_code = http_stat["statcode"] url_count = url_count + 1 io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n") io.stdout:flush() if (status_code >= 200 and status_code <= 399) then if string.match(url.url, "https://") then local newurl = string.gsub(url.url, "https://", "http://") downloaded[newurl] = true else downloaded[url.url] = true end end if status_code >= 500 or (status_code >= 400 and status_code ~= 404 and status_code ~= 403) then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 1") tries = tries + 1 if tries >= 15 then io.stdout:write("\nI give up...\n") io.stdout:flush() tries = 0 return wget.actions.ABORT else return wget.actions.CONTINUE end elseif status_code == 0 then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 10 then io.stdout:write("\nI give up...\n") io.stdout:flush() tries = 0 return wget.actions.ABORT else return wget.actions.CONTINUE end end tries = 0 -- We're okay; sleep a bit (if we have to) and continue -- local sleep_time = 0.5 * (math.random(75, 100) / 100.0) local sleep_time = 0 -- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then -- -- We should be able to go fast on images since that's what a web browser does -- sleep_time = 0 -- end if sleep_time > 0.001 then os.execute("sleep " .. sleep_time) end return wget.actions.NOTHING end
dofile("urlcode.lua") dofile("table_show.lua") local url_count = 0 local tries = 0 local item_type = os.getenv('item_type') local item_value = os.getenv('item_value') local downloaded = {} local addedtolist = {} local ids = {} read_file = function(file) if file then local f = assert(io.open(file)) local data = f:read("*all") f:close() return data else return "" end end wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason) local url = urlpos["url"]["url"] local html = urlpos["link_expect_html"] if downloaded[url] == true or addedtolist[url] == true then return false end if item_type == "labelen" and (downloaded[url] ~= true or addedtolist[url] ~= true) then if (string.match(url, item_value) or html == 0) and not (string.match(url, "accounts%.google%.com") or string.match(url, "google%.com/accounts/") or string.match(url, "loginredirect%?") or string.match(url, "/thread%?tid=")) then addedtolist[url] = true return true else return false end end end wget.callbacks.get_urls = function(file, url, is_css, iri) local urls = {} local html = nil local function check(url, origurl) if (downloaded[url] ~= true and addedtolist[url] ~= true) and not (string.match(url, "accounts%.google%.com") or string.match(url, "google%.com/accounts/") or string.match(url, "loginredirect%?") or string.match(url, "/thread%?tid=")) then if string.match(url, "&amp;") then table.insert(urls, { url=string.gsub(url, "&amp;", "&") }) addedtolist[url] = true addedtolist[string.gsub(url, "&amp;", "&")] = true elseif string.match(url, "//") then table.insert(urls, { url=string.gsub(url, "//", "/") }) addedtolist[url] = true check(string.gsub(url, "//", "/")) else table.insert(urls, { url=url }) addedtolist[url] = true end end end if item_type == "labelen" then if string.match(url, item_value) then html = read_file(file) for newurl in string.gmatch(html, '"(https?://[^"]+)"') do if string.match(newurl, item_value) then check(newurl) end end for newurl in string.gmatch(html, '"(/[^"]+)"') do if string.match(newurl, item_value) then check("http://www.google.com"..newurl) end end end end return urls end wget.callbacks.httploop_result = function(url, err, http_stat) -- NEW for 2014: Slightly more verbose messages because people keep -- complaining that it's not moving or not working status_code = http_stat["statcode"] url_count = url_count + 1 io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n") io.stdout:flush() if (status_code >= 200 and status_code <= 399) then if string.match(url.url, "https://") then local newurl = string.gsub(url.url, "https://", "http://") downloaded[newurl] = true else downloaded[url.url] = true end end if status_code >= 500 or (status_code >= 400 and status_code ~= 404 and status_code ~= 403) then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 1") tries = tries + 1 if tries >= 15 then io.stdout:write("\nI give up...\n") io.stdout:flush() tries = 0 return wget.actions.ABORT else return wget.actions.CONTINUE end elseif status_code == 0 then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 10 then io.stdout:write("\nI give up...\n") io.stdout:flush() tries = 0 return wget.actions.ABORT else return wget.actions.CONTINUE end end tries = 0 local sleep_time = 0 -- We're okay; sleep a bit (if we have to) and continue if not (string.match(url["url"], "https?://[^%.]+%.googleusercontent%.com") or string.match(url["url"], "/photos/")) then local sleep_time = math.random(4, 8) end -- local sleep_time = 0 -- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then -- -- We should be able to go fast on images since that's what a web browser does -- sleep_time = 0 -- end if sleep_time > 0.001 then os.execute("sleep " .. sleep_time) end return wget.actions.NOTHING end
baraza.lua: fixes and additions
baraza.lua: fixes and additions
Lua
unlicense
ArchiveTeam/baraza-grab,ArchiveTeam/baraza-grab
1aaa6fe261f6512989b37900a3136304b1339da9
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 git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@1774 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
projectbismark/luci-bismark,Flexibity/luci,eugenesan/openwrt-luci,gwlim/luci,phi-psi/luci,stephank/luci,8devices/carambola2-luci,saraedum/luci-packages-old,phi-psi/luci,8devices/carambola2-luci,projectbismark/luci-bismark,saraedum/luci-packages-old,Flexibity/luci,Flexibity/luci,phi-psi/luci,freifunk-gluon/luci,eugenesan/openwrt-luci,freifunk-gluon/luci,zwhfly/openwrt-luci,stephank/luci,stephank/luci,gwlim/luci,gwlim/luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,vhpham80/luci,vhpham80/luci,Canaan-Creative/luci,eugenesan/openwrt-luci,saraedum/luci-packages-old,jschmidlapp/luci,ch3n2k/luci,8devices/carambola2-luci,Canaan-Creative/luci,ch3n2k/luci,Canaan-Creative/luci,dtaht/cerowrt-luci-3.3,yeewang/openwrt-luci,ch3n2k/luci,projectbismark/luci-bismark,Flexibity/luci,dtaht/cerowrt-luci-3.3,jschmidlapp/luci,yeewang/openwrt-luci,ThingMesh/openwrt-luci,eugenesan/openwrt-luci,gwlim/luci,dtaht/cerowrt-luci-3.3,alxhh/piratenluci,projectbismark/luci-bismark,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,gwlim/luci,zwhfly/openwrt-luci,phi-psi/luci,phi-psi/luci,vhpham80/luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,Flexibity/luci,yeewang/openwrt-luci,stephank/luci,ThingMesh/openwrt-luci,projectbismark/luci-bismark,yeewang/openwrt-luci,Canaan-Creative/luci,dtaht/cerowrt-luci-3.3,alxhh/piratenluci,jschmidlapp/luci,projectbismark/luci-bismark,alxhh/piratenluci,ReclaimYourPrivacy/cloak-luci,dtaht/cerowrt-luci-3.3,alxhh/piratenluci,Flexibity/luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,Flexibity/luci,phi-psi/luci,8devices/carambola2-luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,ch3n2k/luci,freifunk-gluon/luci,vhpham80/luci,vhpham80/luci,8devices/carambola2-luci,zwhfly/openwrt-luci,freifunk-gluon/luci,8devices/carambola2-luci,freifunk-gluon/luci,8devices/carambola2-luci,zwhfly/openwrt-luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,saraedum/luci-packages-old,gwlim/luci,vhpham80/luci,jschmidlapp/luci,yeewang/openwrt-luci,projectbismark/luci-bismark,Canaan-Creative/luci,dtaht/cerowrt-luci-3.3,freifunk-gluon/luci,saraedum/luci-packages-old,Canaan-Creative/luci,stephank/luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,jschmidlapp/luci,alxhh/piratenluci,zwhfly/openwrt-luci,projectbismark/luci-bismark,stephank/luci,phi-psi/luci,jschmidlapp/luci,ch3n2k/luci,gwlim/luci,ch3n2k/luci,alxhh/piratenluci,ThingMesh/openwrt-luci,Canaan-Creative/luci,eugenesan/openwrt-luci,alxhh/piratenluci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,jschmidlapp/luci
89219a513f2e620459d5058888007149c05fc2df
src/http/request_key.lua
src/http/request_key.lua
local assert, format, load = assert, string.format, loadstring local concat = table.concat local function var_method() return nil, 'req.method' end local function var_path() return nil, 'req.path' end local function var_query(name) return 'local q = req.query or req:parse_query()', '(q["' .. name .. '"] or "")' end local function var_headers(name) name = name:gsub('_', '-') return 'local h = req.headers or req:parse_headers()', '(h["' .. name .. '"] or "")' end local function var_gzip() return 'local h = req.headers', '((h["accept-encoding"] or ""):find("gzip", 1, true) and "z" or "")' end local variables = { method = var_method, m = var_method, path = var_path, p = var_path, query = var_query, q = var_query, headers = var_headers, header = var_headers, h = var_headers, gzip = var_gzip, gz = var_gzip } local function keys(t) local r = {} for k in pairs(t) do r[#r+1] = k end return r end local function parse_parts(s) local parts = {} local b = 1 local e = 1 local pe = 1 while true do b, e = s:find('%$%w+', b) if not b then parts[#parts+1] = s:sub(pe) break end parts[#parts+1] = s:sub(pe, b - 1) local name = s:sub(b + 1, e) local f = variables[name] e = e + 1 b, pe = s:find('^_[%w_]+', e) if b then parts[#parts+1] = {name, s:sub(b + 1, pe)} pe = pe + 1 else parts[#parts+1] = {name} pe = e end b = e end return parts end local function build(parts) local locals = {} local chunks = {} for i = 1, #parts do if i % 2 == 1 then local s = parts[i] if #s > 0 then chunks[#chunks+1] = format('%q', s) end else local name, param = unpack(parts[i]) local v = variables[name] if not v then return error('unknown variable "' .. name .. '"') end local l, c = v(param) if l and #l > 0 then locals[l] = true end chunks[#chunks+1] = c end end locals = concat(keys(locals), '\n ') chunks = concat(chunks, ' ..\n ') return format([[ return function(req) %s return %s end]], locals, chunks) end local function new(s) if type(s) ~= 'string' or #s == 0 then return error('bad argument #1 to \'new\' (non empty string expected)') end local source = build(parse_parts(s)) -- print(source) return assert(load(source))() end return { new = new, variables = variables }
local assert, format, load = assert, string.format, loadstring local concat = table.concat local function var_method() return nil, 'req.method' end local function var_path() return nil, 'req.path' end local function var_query(name) return 'local q = req.query or req:parse_query()', '(q["' .. name .. '"] or "")' end local function var_headers(name) name = name:gsub('_', '-') return 'local h = req.headers or req:parse_headers()', '(h["' .. name .. '"] or "")' end local function var_gzip() return 'local h = req.headers', '((h["accept-encoding"] or ""):find("gzip", 1, true) and "z" or "")' end local variables = { method = var_method, m = var_method, path = var_path, p = var_path, query = var_query, q = var_query, headers = var_headers, header = var_headers, h = var_headers, gzip = var_gzip, gz = var_gzip } local function keys(t) local r = {} for k in pairs(t) do r[#r+1] = k end return r end local function parse_parts(s) local parts = {} local b = 1 local e local pe = 1 while true do b, e = s:find('%$%w+', b) if not b then parts[#parts+1] = s:sub(pe) break end parts[#parts+1] = s:sub(pe, b - 1) local name = s:sub(b + 1, e) e = e + 1 b, pe = s:find('^_[%w_]+', e) if b then parts[#parts+1] = {name, s:sub(b + 1, pe)} pe = pe + 1 else parts[#parts+1] = {name} pe = e end b = e end return parts end local function build(parts) local locals = {} local chunks = {} for i = 1, #parts do if i % 2 == 1 then local s = parts[i] if #s > 0 then chunks[#chunks+1] = format('%q', s) end else local name, param = unpack(parts[i]) local v = variables[name] if not v then return error('unknown variable "' .. name .. '"') end local l, c = v(param) if l and #l > 0 then locals[l] = true end chunks[#chunks+1] = c end end locals = concat(keys(locals), '\n ') chunks = concat(chunks, ' ..\n ') return format([[ return function(req) %s return %s end]], locals, chunks) end local function new(s) if type(s) ~= 'string' or #s == 0 then return error('bad argument #1 to \'new\' (non empty string expected)') end local source = build(parse_parts(s)) -- print(source) return assert(load(source))() end return { new = new, variables = variables }
Fixed check warnings.
Fixed check warnings.
Lua
mit
akornatskyy/lucid
9c4c48e363b09983eae65fed192229740cc62e31
fbnn/Optim.lua
fbnn/Optim.lua
-- Copyright 2004-present Facebook. All Rights Reserved. local pl = require('pl.import_into')() -- from fblualib/fb/util/data.lua , copied here because fblualib is not rockspec ready yet. -- deepcopy routine that assumes the presence of a 'clone' method in user -- data should be used to deeply copy. This matches the behavior of Torch -- tensors. local function deepcopy(x) local typename = type(x) if typename == "userdata" then return x:clone() end if typename == "table" then local retval = { } for k,v in pairs(x) do retval[deepcopy(k)] = deepcopy(v) end return retval end return x end local Optim, parent = torch.class('nn.Optim') -- Returns weight parameters and bias parameters and associated grad parameters -- for this module. Annotates the return values with flag marking parameter set -- as bias parameters set function Optim.weight_bias_parameters(module) local weight_params, bias_params if module.weight then weight_params = {module.weight, module.gradWeight} weight_params.is_bias = false end if module.bias then bias_params = {module.bias, module.gradBias} bias_params.is_bias = true end return {weight_params, bias_params} end -- The regular `optim` package relies on `getParameters`, which is a -- beastly abomination before all. This `optim` package uses separate -- optim state for each submodule of a `nn.Module`. function Optim:__init(model, optState, checkpoint_data) assert(model) assert(checkpoint_data or optState) assert(not (checkpoint_data and optState)) self.model = model self.modulesToOptState = {} -- Keep this around so we update it in setParameters self.originalOptState = optState -- Each module has some set of parameters and grad parameters. Since -- they may be allocated discontinuously, we need separate optState for -- each parameter tensor. self.modulesToOptState maps each module to -- a lua table of optState clones. if not checkpoint_data then self.model:for_each(function(module) self.modulesToOptState[module] = { } local params = self.weight_bias_parameters(module) -- expects either an empty table or 2 element table, one for weights -- and one for biases assert(pl.tablex.size(params) == 0 or pl.tablex.size(params) == 2) for i, _ in ipairs(params) do self.modulesToOptState[module][i] = deepcopy(optState) if params[i] and params[i].is_bias then -- never regularize biases self.modulesToOptState[module][i].weightDecay = 0.0 end end assert(module) assert(self.modulesToOptState[module]) end) else local state = checkpoint_data.optim_state local modules = {} self.model:for_each(function(m) table.insert(modules, m) end) assert(pl.tablex.compare_no_order(modules, pl.tablex.keys(state))) self.modulesToOptState = state end end function Optim:save() return { optim_state = self.modulesToOptState } end local function _type_all(obj, t) for k, v in pairs(obj) do if type(v) == 'table' then _type_all(v, t) else local tn = torch.typename(v) if tn and tn:find('torch%..+Tensor') then obj[k] = v:type(t) end end end end function Optim:type(t) self.model:for_each(function(module) local state= self.modulesToOptState[module] assert(state) _type_all(state, t) end) end local function get_device_for_module(mod) local dev_id = nil for name, val in pairs(mod) do if torch.typename(val) == 'torch.CudaTensor' then local this_dev = val:getDevice() if this_dev ~= 0 then -- _make sure the tensors are allocated consistently assert(dev_id == nil or dev_id == this_dev) dev_id = this_dev end end end return dev_id -- _may still be zero if none are allocated. end local function on_device_for_module(mod, f) local this_dev = get_device_for_module(mod) if this_dev ~= nil then return cutorch.withDevice(this_dev, f) end return f() end function Optim:optimize(optimMethod, inputs, targets, criterion) assert(optimMethod) assert(inputs) assert(targets) assert(criterion) assert(self.modulesToOptState) self.model:zeroGradParameters() local output = self.model:forward(inputs) local err = criterion:forward(output, targets) local df_do = criterion:backward(output, targets) self.model:backward(inputs, df_do) -- Combine gradients for data parallel models if self.model._mixGrads then self.model:_mixGrads() end -- We'll set these in the loop that iterates over each module. Get them -- out here to be captured. local curGrad local curParam local function fEvalMod(x) return err, curGrad end for curMod, opt in pairs(self.modulesToOptState) do on_device_for_module(curMod, function() local curModParams = self.weight_bias_parameters(curMod) -- expects either an empty table or 2 element table, one for weights -- and one for biases assert(pl.tablex.size(curModParams) == 0 or pl.tablex.size(curModParams) == 2) if curModParams then for i, tensor in ipairs(curModParams) do if curModParams[i] then -- expect param, gradParam pair curParam, curGrad = table.unpack(curModParams[i]) assert(curParam and curGrad) optimMethod(fEvalMod, curParam, opt[i]) end end end end) end return err, output end function Optim:setParameters(newParams) assert(newParams) assert(type(newParams) == 'table') local function splice(dest, src) for k,v in pairs(src) do dest[k] = v end end splice(self.originalOptState, newParams) for _,optStates in pairs(self.modulesToOptState) do for i,optState in pairs(optStates) do assert(type(optState) == 'table') splice(optState, newParams) end end end
-- Copyright 2004-present Facebook. All Rights Reserved. local pl = require('pl.import_into')() -- from fblualib/fb/util/data.lua , copied here because fblualib is not rockspec ready yet. -- deepcopy routine that assumes the presence of a 'clone' method in user -- data should be used to deeply copy. This matches the behavior of Torch -- tensors. local function deepcopy(x) local typename = type(x) if typename == "userdata" then return x:clone() end if typename == "table" then local retval = { } for k,v in pairs(x) do retval[deepcopy(k)] = deepcopy(v) end return retval end return x end local Optim, parent = torch.class('nn.Optim') -- Returns weight parameters and bias parameters and associated grad parameters -- for this module. Annotates the return values with flag marking parameter set -- as bias parameters set function Optim.weight_bias_parameters(module) local weight_params, bias_params if module.weight then weight_params = {module.weight, module.gradWeight} weight_params.is_bias = false end if module.bias then bias_params = {module.bias, module.gradBias} bias_params.is_bias = true end return {weight_params, bias_params} end -- The regular `optim` package relies on `getParameters`, which is a -- beastly abomination before all. This `optim` package uses separate -- optim state for each submodule of a `nn.Module`. function Optim:__init(model, optState, checkpoint_data) assert(model) assert(checkpoint_data or optState) assert(not (checkpoint_data and optState)) self.model = model self.modulesToOptState = {} -- Keep this around so we update it in setParameters self.originalOptState = optState -- Each module has some set of parameters and grad parameters. Since -- they may be allocated discontinuously, we need separate optState for -- each parameter tensor. self.modulesToOptState maps each module to -- a lua table of optState clones. if not checkpoint_data then self.model:for_each(function(module) self.modulesToOptState[module] = { } local params = self.weight_bias_parameters(module) -- expects either an empty table or 2 element table, one for weights -- and one for biases assert(pl.tablex.size(params) == 0 or pl.tablex.size(params) == 2) for i, _ in ipairs(params) do self.modulesToOptState[module][i] = deepcopy(optState) if params[i] and params[i].is_bias then -- never regularize biases self.modulesToOptState[module][i].weightDecay = 0.0 end end assert(module) assert(self.modulesToOptState[module]) end) else local state = checkpoint_data.optim_state local modules = {} self.model:for_each(function(m) table.insert(modules, m) end) assert(pl.tablex.compare_no_order(modules, pl.tablex.keys(state))) self.modulesToOptState = state end end function Optim:save() return { optim_state = self.modulesToOptState } end local function _type_all(obj, t) for k, v in pairs(obj) do if type(v) == 'table' then _type_all(v, t) else local tn = torch.typename(v) if tn and tn:find('torch%..+Tensor') then obj[k] = v:type(t) end end end end function Optim:type(t) self.model:for_each(function(module) local state= self.modulesToOptState[module] assert(state) _type_all(state, t) end) end local function get_device_for_module(mod) local dev_id = nil for name, val in pairs(mod) do if torch.typename(val) == 'torch.CudaTensor' then local this_dev = val:getDevice() if this_dev ~= 0 then -- _make sure the tensors are allocated consistently assert(dev_id == nil or dev_id == this_dev) dev_id = this_dev end end end return dev_id -- _may still be zero if none are allocated. end local function on_device_for_module(mod, f) local this_dev = get_device_for_module(mod) if this_dev ~= nil then return cutorch.withDevice(this_dev, f) end return f() end function Optim:optimize(optimMethod, inputs, targets, criterion) assert(optimMethod) assert(inputs) assert(targets) assert(criterion) assert(self.modulesToOptState) self.model:zeroGradParameters() local output = self.model:forward(inputs) local err = criterion:forward(output, targets) local df_do = criterion:backward(output, targets) self.model:backward(inputs, df_do) -- We'll set these in the loop that iterates over each module. Get them -- out here to be captured. local curGrad local curParam local function fEvalMod(x) return err, curGrad end for curMod, opt in pairs(self.modulesToOptState) do on_device_for_module(curMod, function() local curModParams = self.weight_bias_parameters(curMod) -- expects either an empty table or 2 element table, one for weights -- and one for biases assert(pl.tablex.size(curModParams) == 0 or pl.tablex.size(curModParams) == 2) if curModParams then for i, tensor in ipairs(curModParams) do if curModParams[i] then -- expect param, gradParam pair curParam, curGrad = table.unpack(curModParams[i]) assert(curParam and curGrad) optimMethod(fEvalMod, curParam, opt[i]) end end end end) end return err, output end function Optim:setParameters(newParams) assert(newParams) assert(type(newParams) == 'table') local function splice(dest, src) for k,v in pairs(src) do dest[k] = v end end splice(self.originalOptState, newParams) for _,optStates in pairs(self.modulesToOptState) do for i,optState in pairs(optStates) do assert(type(optState) == 'table') splice(optState, newParams) end end end
bug fix for DataParallel
bug fix for DataParallel
Lua
bsd-3-clause
facebook/fbnn,facebook/fbnn,facebook/fbnn
5032cc1e76d4f3bb0ded2073421f47dce926220c
build/premake4.lua
build/premake4.lua
function MakeUnmanagedProjects() dofile("MusiC.Native.Base.lua") dofile("MusiC.Native.Core.lua") dofile("MusiC.Extensions.Classifiers.uBarbedo.lua") end function MakeManagedProjects() dofile("MusiC.lua") dofile("MusiC.Apps.GenreC.lua") dofile("MusiC.Extensions.Classifiers.Barbedo.lua") dofile("MusiC.Extensions.Configs.XMLConfigurator.lua") dofile("MusiC.Extensions.Features.SpecRollOff.lua") dofile("MusiC.Extensions.Features.SpectralFlux.lua") dofile("MusiC.Extensions.Features.Loudness.lua") dofile("MusiC.Extensions.Features.Bandwidth.lua") dofile("MusiC.Extensions.Handlers.WAVHandler.lua") dofile("MusiC.Extensions.Windows.Hamming.lua") end function MakeTestingProjects() dofile("MusiC.Test.lua") dofile("MusiC.Test.Unit.lua") end function CreateProject() base_deps_dir = "../deps" base_src_dir = "../src" base_bin_dir = "../bin" base_prj_dir = _ACTION; solution("MusiC") configurations({"Debug", "Release"}) location(base_prj_dir) if _ACTION == "vs2008" or _ACTION == "vs2005" then MakeManagedProjects() MakeTestingProjects() solution("uMusiC") configurations({"Debug", "Release"}) -- this will change the location of the projects. base_prj_dir = base_prj_dir.."u" location(base_prj_dir) MakeUnmanagedProjects() elseif _ACTION == "vs2003" or _ACTION == "vs2002" then MakeManagedProjects() elseif _ACTION == "codeblocks" or _ACTION == "codelite" then MakeUnmanagedProjects() elseif _ACTION == "gmake" then MakeManagedProjects() MakeUnmanagedProjects() end end function main() CreateProject() end main()
function MakeUnmanagedProjects() dofile("MusiC.Native.Base.lua") dofile("MusiC.Native.Core.lua") dofile("MusiC.Extensions.Classifiers.uBarbedo.lua") end function MakeManagedProjects() dofile("MusiC.lua") dofile("MusiC.Apps.GenreC.lua") dofile("MusiC.Extensions.Classifiers.Barbedo.lua") dofile("MusiC.Extensions.Configs.XMLConfigurator.lua") dofile("MusiC.Extensions.Features.SpecRollOff.lua") dofile("MusiC.Extensions.Features.SpectralFlux.lua") dofile("MusiC.Extensions.Features.Loudness.lua") dofile("MusiC.Extensions.Features.Bandwidth.lua") dofile("MusiC.Extensions.Handlers.WAVHandler.lua") dofile("MusiC.Extensions.Windows.Hamming.lua") end function MakeTestingProjects() dofile("MusiC.Test.lua") end function CreateProject() base_deps_dir = "../deps" base_src_dir = "../src" base_bin_dir = "../bin" base_prj_dir = _ACTION; solution("MusiC") configurations({"Debug", "Release"}) location(base_prj_dir) if _ACTION == "vs2008" or _ACTION == "vs2005" then MakeManagedProjects() MakeTestingProjects() solution("uMusiC") configurations({"Debug", "Release"}) -- this will change the location of the projects. base_prj_dir = base_prj_dir.."u" location(base_prj_dir) MakeUnmanagedProjects() elseif _ACTION == "vs2003" or _ACTION == "vs2002" then MakeManagedProjects() elseif _ACTION == "codeblocks" or _ACTION == "codelite" then MakeUnmanagedProjects() elseif _ACTION == "gmake" then MakeManagedProjects() MakeUnmanagedProjects() end end function main() CreateProject() end main()
FIX: Premake building. Excluded MusiC.Test.Unit entry.
FIX: Premake building. Excluded MusiC.Test.Unit entry.
Lua
mit
berkus/music-cs,berkus/music-cs,berkus/music-cs,berkus/music-cs
c86e1489c81c4ac6ae98416b908e086bac4d587c
src/pcap.lua
src/pcap.lua
module("pcap",package.seeall) local ffi = require("ffi") local pf = require("pf") local pcap = ffi.load("pcap") function pcap_compile (filter_str) ffi.cdef[[ typedef struct pcap pcap_t; pcap_t *pcap_create(const char *source, char *errbuf); int pcap_activate(pcap_t *p); int pcap_compile(pcap_t *p, struct bpf_program *fp, const char *str, int optimize, uint32_t netmask); ]] -- pcap_create local errbuf = ffi.new("char[?]", 256) local p = pcap.pcap_create("any", errbuf) -- pcap_activate err = pcap.pcap_activate(p) if err ~= 0 then return true, "pcap_activate failed!" end -- pcap_compile local fp = pf.bpf_program() err = pcap.pcap_compile(p, fp, filter_str, 0, 0) if err ~= 0 then return true, "pcap_compile failed!" end local ins = pf.bpf_insn(fp.bf_len) -- generate bytecode local fp_arr = {} fp_arr[0] = fp.bf_len - 1 for i = 0,fp.bf_len-2 do fp_arr[4*i+1] = fp.bf_insns[i+1].code fp_arr[4*i+2] = fp.bf_insns[i+1].jt fp_arr[4*i+3] = fp.bf_insns[i+1].jf fp_arr[4*i+4] = fp.bf_insns[i+1].k end return false, fp_arr end function dump_bytecode (fp_arr) io.write(fp_arr[0]) for i = 1,#fp_arr-1,4 do io.write(",") io.write(fp_arr[i] .. " ") io.write(fp_arr[i+1] .. " ") io.write(fp_arr[i+2] .. " ") io.write(fp_arr[i+3]) end io.write("\n") end -- pcap requires root privileges -- run 'sudo make check' to test function selftest () print("selftest: pcap") local err, str = pcap_compile("icmp") if not err then dump_bytecode(str) else print(str) end print("OK") end
module("pcap",package.seeall) local ffi = require("ffi") local pf = require("pf") local pcap = ffi.load("pcap") -- The dlt_name is a "datalink type name" and specifies the link-level -- wrapping to expect. E.g., for raw ethernet frames, you would specify -- "EN10MB" (even though you have a 10G card), which corresponds to the -- numeric DLT_EN10MB value from pcap/bpf.h. See -- http://www.tcpdump.org/linktypes.html for more details on possible -- names. -- -- You probably want "RAW" for raw IP (v4 or v6) frames. If you don't -- supply a dlt_name, "RAW" is the default. function pcap_compile (filter_str, dlt_name) ffi.cdef[[ typedef struct pcap pcap_t; int pcap_datalink_name_to_val(const char *name); pcap_t *pcap_open_dead(int linktype, int snaplen); void pcap_perror(pcap_t *p, const char *suffix); int pcap_compile(pcap_t *p, struct bpf_program *fp, const char *str, int optimize, uint32_t netmask); ]] dlt_name = dlt_name or "RAW" local dlt = pcap.pcap_datalink_name_to_val(dlt_name) assert(dlt >= 0, "bad datalink type name " .. dlt_name) local snaplen = 65535 -- Maximum packet size. local p = pcap.pcap_open_dead(dlt, snaplen) assert(p, "pcap_open_dead failed") -- pcap_compile local fp = pf.bpf_program() err = pcap.pcap_compile(p, fp, filter_str, 0, 0) if err ~= 0 then pcap.pcap_perror(p, "pcap_compile failed!") end local ins = pf.bpf_insn(fp.bf_len) -- generate bytecode local fp_arr = {} fp_arr[0] = fp.bf_len - 1 for i = 0,fp.bf_len-2 do fp_arr[4*i+1] = fp.bf_insns[i+1].code fp_arr[4*i+2] = fp.bf_insns[i+1].jt fp_arr[4*i+3] = fp.bf_insns[i+1].jf fp_arr[4*i+4] = fp.bf_insns[i+1].k end return false, fp_arr end function dump_bytecode (fp_arr) io.write(fp_arr[0]) for i = 1,#fp_arr-1,4 do io.write(",") io.write(fp_arr[i] .. " ") io.write(fp_arr[i+1] .. " ") io.write(fp_arr[i+2] .. " ") io.write(fp_arr[i+3]) end io.write("\n") end function selftest () print("selftest: pcap") local err, str = pcap_compile("icmp") if not err then dump_bytecode(str) else print(str) end print("OK") end
Filter compilation works without root privileges
Filter compilation works without root privileges * src/pcap.lua: Fix to work without root privileges by using pcap_open_dead.
Lua
apache-2.0
mpeterv/pflua,SnabbCo/pflua
c613e06c69a7d05e736aa7c69f83e850c4fed050
tundra.lua
tundra.lua
local common = { Env = { CPPPATH = { "." }, CXXOPTS = { -- clang and GCC { "-std=c++14"; Config = { "*-gcc-*", "*-clang-*" } }, { "-g"; Config = { "*-gcc-debug", "*-clang-debug" } }, { "-g -O2"; Config = { "*-gcc-production", "*-clang-production" } }, { "-O3"; Config = { "*-gcc-release", "*-clang-release" } }, { "-Wall", "-Werror", "-Wextra", "-Wno-unused-parameter", "-Wno-unused-function"; Config = { "*-gcc-*", "*-clang-*" } }, -- MSVC config { "/MD"; Config = "*-msvc-debug" }, { "/MT"; Config = { "*-msvc-production", "*-msvc-release" } }, { "/wd4127", -- conditional expression is constant "/wd4100", -- unreferenced formal parameter "/wd4324", -- structure was padded due to __declspec(align()) Config = "*-msvc-*" }, }, CPPDEFS = { { "_DEBUG"; Config = "*-*-debug" }, { "NDEBUG"; Config = "*-*-release" }, { "_CRT_SECURE_NO_WARNINGS"; Config = "*-msvc-*" }, }, }, ReplaceEnv = { LD = "$(CXX)" }, } Build { Units = function () local deluxe = Program { Name = "deluxe68", Sources = { "deluxe.cpp", "tokenizer.cpp", "registers.cpp" }, } Default(deluxe) local deluxeTest = Program { Name = "deluxe68test", Includes = { "external/gtest/googletest/include", "external/gtest/googletest" }, Sources = { "tokenizer.cpp", "tests/deluxetest.cpp", "tests/tokenizer_test.cpp", "external/gtest/googletest/src/gtest-all.cc" }, } Default(deluxeTest) end, Configs = { Config { Name = "win64-msvc", DefaultOnHost = "windows", Inherit = common, Tools = { { "msvc-winsdk"; TargetArch = "x64" }, }, }, Config { Name = "macosx-clang", Inherit = common, Tools = { "clang-osx" }, DefaultOnHost = "macosx", }, }, }
local common = { Env = { CPPPATH = { "." }, CXXOPTS = { -- clang and GCC { "-std=c++14"; Config = { "*-gcc-*", "*-clang-*" } }, { "-g"; Config = { "*-gcc-debug", "*-clang-debug" } }, { "-g -O2"; Config = { "*-gcc-production", "*-clang-production" } }, { "-O3"; Config = { "*-gcc-release", "*-clang-release" } }, { "-Wall", "-Werror", "-Wextra", "-Wno-unused-parameter", "-Wno-unused-function"; Config = { "*-gcc-*", "*-clang-*" } }, -- MSVC config { "/EHsc"; Config = "*-msvc-*" }, { "/MDd"; Config = "*-msvc-debug" }, { "/MTd"; Config = { "*-msvc-production", "*-msvc-release" } }, { "/wd4127", -- conditional expression is constant "/wd4100", -- unreferenced formal parameter "/wd4324", -- structure was padded due to __declspec(align()) Config = "*-msvc-*" }, }, CPPDEFS = { { "_DEBUG"; Config = "*-*-debug" }, { "NDEBUG"; Config = "*-*-release" }, { "_CRT_SECURE_NO_WARNINGS"; Config = "*-msvc-*" }, }, }, ReplaceEnv = { LD = { "$(CXX)"; Config = { "*-clang-*", "*-gcc-*" } }, }, } Build { Units = function () local deluxe = Program { Name = "deluxe68", Sources = { "deluxe.cpp", "tokenizer.cpp", "registers.cpp" }, } Default(deluxe) local deluxeTest = Program { Name = "deluxe68test", Includes = { "external/gtest/googletest/include", "external/gtest/googletest" }, Sources = { "tokenizer.cpp", "tests/deluxetest.cpp", "tests/tokenizer_test.cpp", "external/gtest/googletest/src/gtest-all.cc" }, } Default(deluxeTest) end, Configs = { Config { Name = "win64-msvc", DefaultOnHost = "windows", Inherit = common, Tools = { { "msvc-vs2015"; TargetArch = "x64" }, }, }, Config { Name = "macosx-clang", Inherit = common, Tools = { "clang-osx" }, DefaultOnHost = "macosx", }, }, }
Fix windows build.
Fix windows build.
Lua
bsd-2-clause
deplinenoise/deluxe68,deplinenoise/deluxe68
53fef98acfc30c53c3481d0fb39cdf4ce379787d
lualib/skynet/datasheet/builder.lua
lualib/skynet/datasheet/builder.lua
local skynet = require "skynet" local dump = require "skynet.datasheet.dump" local core = require "skynet.datasheet.core" local service = require "skynet.service" local builder = {} local cache = {} local dataset = {} local address local function monitor(pointer) skynet.fork(function() skynet.call(address, "lua", "collect", pointer) for k,v in pairs(cache) do if v == pointer then cache[k] = nil return end end end) end local function dumpsheet(v) if type(v) == "string" then return v else return dump.dump(v) end end function builder.new(name, v) assert(dataset[name] == nil) local datastring = dumpsheet(v) local pointer = core.stringpointer(datastring) skynet.call(address, "lua", "update", name, pointer) cache[datastring] = pointer dataset[name] = datastring monitor(pointer) end function builder.update(name, v) local lastversion = assert(dataset[name]) local newversion = dumpsheet(v) local diff = dump.diff(lastversion, newversion) local pointer = core.stringpointer(diff) skynet.call(address, "lua", "update", name, pointer) cache[diff] = pointer local lp = assert(cache[lastversion]) skynet.send(address, "lua", "release", lp) dataset[name] = diff monitor(pointer) end function builder.compile(v) return dump.dump(v) end local function datasheet_service() local skynet = require "skynet" local datasheet = {} local handles = {} -- handle:{ ref:count , name:name , collect:resp } local dataset = {} -- name:{ handle:handle, monitor:{monitors queue} } local function releasehandle(handle) local h = handles[handle] h.ref = h.ref - 1 if h.ref == 0 and h.collect then h.collect(true) h.collect = nil handles[handle] = nil end end -- from builder, create or update handle function datasheet.update(name, handle) local t = dataset[name] if not t then -- new datasheet t = { handle = handle, monitor = {} } dataset[name] = t handles[handle] = { ref = 1, name = name } else t.handle = handle -- report update to customers handles[handle] = { ref = 1 + #t.monitor, name = name } for k,v in ipairs(t.monitor) do v(true, handle) t.monitor[k] = nil end end skynet.ret() end -- from customers function datasheet.query(name) local t = assert(dataset[name], "create data first") local handle = t.handle local h = handles[handle] h.ref = h.ref + 1 skynet.ret(skynet.pack(handle)) end -- from customers, monitor handle change function datasheet.monitor(handle) local h = assert(handles[handle], "Invalid data handle") local t = dataset[h.name] if t.handle ~= handle then -- already changes skynet.ret(skynet.pack(t.handle)) else h.ref = h.ref + 1 table.insert(t.monitor, skynet.response()) end end -- from customers, release handle , ref count - 1 function datasheet.release(handle) -- send message, don't ret releasehandle(handle) end -- from builder, monitor handle release function datasheet.collect(handle) local h = assert(handles[handle], "Invalid data handle") if h.ref == 0 then handles[handle] = nil skynet.ret() else assert(h.collect == nil, "Only one collect allows") h.collect = skynet.response() end end skynet.dispatch("lua", function(_,_,cmd,...) datasheet[cmd](...) end) skynet.info_func(function() local info = {} local tmp = {} for k,v in pairs(handles) do tmp[k] = v end for k,v in pairs(dataset) do local h = handles[v.handle] tmp[v.handle] = nil info[k] = { handle = v.handle, monitors = #v.monitor, } end for k,v in pairs(tmp) do info[k] = v.ref end return info end) end skynet.init(function() address=service.new("datasheet", datasheet_service) end) return builder
local skynet = require "skynet" local dump = require "skynet.datasheet.dump" local core = require "skynet.datasheet.core" local service = require "skynet.service" local builder = {} local cache = {} local dataset = {} local address local unique_id = 0 local function unique_string(str) unique_id = unique_id + 1 return str .. "." .. tostring(unique_id) end local function monitor(pointer) skynet.fork(function() skynet.call(address, "lua", "collect", pointer) for k,v in pairs(cache) do if v == pointer then cache[k] = nil return end end end) end local function dumpsheet(v) if type(v) == "string" then return v else return dump.dump(v) end end function builder.new(name, v) assert(dataset[name] == nil) local datastring = unique_string(dumpsheet(v)) local pointer = core.stringpointer(datastring) skynet.call(address, "lua", "update", name, pointer) cache[datastring] = pointer dataset[name] = datastring monitor(pointer) end function builder.update(name, v) local lastversion = assert(dataset[name]) local newversion = dumpsheet(v) local diff = unique_string(dump.diff(lastversion, newversion)) local pointer = core.stringpointer(diff) skynet.call(address, "lua", "update", name, pointer) cache[diff] = pointer local lp = assert(cache[lastversion]) skynet.send(address, "lua", "release", lp) dataset[name] = diff monitor(pointer) end function builder.compile(v) return dump.dump(v) end local function datasheet_service() local skynet = require "skynet" local datasheet = {} local handles = {} -- handle:{ ref:count , name:name , collect:resp } local dataset = {} -- name:{ handle:handle, monitor:{monitors queue} } local function releasehandle(handle) local h = handles[handle] h.ref = h.ref - 1 if h.ref == 0 and h.collect then h.collect(true) h.collect = nil handles[handle] = nil end end -- from builder, create or update handle function datasheet.update(name, handle) local t = dataset[name] if not t then -- new datasheet t = { handle = handle, monitor = {} } dataset[name] = t handles[handle] = { ref = 1, name = name } else t.handle = handle -- report update to customers handles[handle] = { ref = 1 + #t.monitor, name = name } for k,v in ipairs(t.monitor) do v(true, handle) t.monitor[k] = nil end end skynet.ret() end -- from customers function datasheet.query(name) local t = assert(dataset[name], "create data first") local handle = t.handle local h = handles[handle] h.ref = h.ref + 1 skynet.ret(skynet.pack(handle)) end -- from customers, monitor handle change function datasheet.monitor(handle) local h = assert(handles[handle], "Invalid data handle") local t = dataset[h.name] if t.handle ~= handle then -- already changes skynet.ret(skynet.pack(t.handle)) else h.ref = h.ref + 1 table.insert(t.monitor, skynet.response()) end end -- from customers, release handle , ref count - 1 function datasheet.release(handle) -- send message, don't ret releasehandle(handle) end -- from builder, monitor handle release function datasheet.collect(handle) local h = assert(handles[handle], "Invalid data handle") if h.ref == 0 then handles[handle] = nil skynet.ret() else assert(h.collect == nil, "Only one collect allows") h.collect = skynet.response() end end skynet.dispatch("lua", function(_,_,cmd,...) datasheet[cmd](...) end) skynet.info_func(function() local info = {} local tmp = {} for k,v in pairs(handles) do tmp[k] = v end for k,v in pairs(dataset) do local h = handles[v.handle] tmp[v.handle] = nil info[k] = { handle = v.handle, monitors = #v.monitor, } end for k,v in pairs(tmp) do info[k] = v.ref end return info end) end skynet.init(function() address=service.new("datasheet", datasheet_service) end) return builder
fix #718
fix #718
Lua
mit
great90/skynet,zhouxiaoxiaoxujian/skynet,sanikoyes/skynet,JiessieDawn/skynet,sundream/skynet,zhouxiaoxiaoxujian/skynet,zhangshiqian1214/skynet,ag6ag/skynet,czlc/skynet,korialuo/skynet,great90/skynet,cloudwu/skynet,bigrpg/skynet,jxlczjp77/skynet,zhangshiqian1214/skynet,kyle-wang/skynet,fztcjjl/skynet,korialuo/skynet,xcjmine/skynet,Ding8222/skynet,codingabc/skynet,wangyi0226/skynet,icetoggle/skynet,zhangshiqian1214/skynet,czlc/skynet,fztcjjl/skynet,sanikoyes/skynet,bigrpg/skynet,cmingjian/skynet,zhangshiqian1214/skynet,zhangshiqian1214/skynet,bttscut/skynet,firedtoad/skynet,cmingjian/skynet,zhouxiaoxiaoxujian/skynet,pigparadise/skynet,bttscut/skynet,fztcjjl/skynet,firedtoad/skynet,jxlczjp77/skynet,sundream/skynet,icetoggle/skynet,xjdrew/skynet,jxlczjp77/skynet,JiessieDawn/skynet,ag6ag/skynet,great90/skynet,xjdrew/skynet,hongling0/skynet,czlc/skynet,xcjmine/skynet,kyle-wang/skynet,sundream/skynet,bttscut/skynet,korialuo/skynet,xjdrew/skynet,kyle-wang/skynet,bigrpg/skynet,hongling0/skynet,pigparadise/skynet,icetoggle/skynet,cloudwu/skynet,cmingjian/skynet,firedtoad/skynet,wangyi0226/skynet,codingabc/skynet,JiessieDawn/skynet,xcjmine/skynet,zhangshiqian1214/skynet,sanikoyes/skynet,ag6ag/skynet,hongling0/skynet,cloudwu/skynet,pigparadise/skynet,Ding8222/skynet,codingabc/skynet,Ding8222/skynet,wangyi0226/skynet
95fb7bfdef2f764b8f3a8083d9933000869cff60
src/move.lua
src/move.lua
function getTile(index) return game.players[index].surface.get_tile(game.players[index].position.x,game.players[index].position.y) end function getDirectiveEntity(index) position = {game.players[index].position.x, game.players[index].position.y} local list = {"left","down","up","right","accelerator_charger"} for _, name in ipairs(list) do local target = game.players[index].surface.find_entity(name,position) if target ~= nil then return target end end return nil end function inboundTile(name) local tiles = {"copper-floor", "copper-floor2", "copper-floor3"} for _, tile in ipairs(tiles) do if tile == name then return true end end return false end function charge_hoverboard(index,entity) local charge_needed = 5 - global.hoverboard[index].charge local energy_needed = (charge_needed) * "1000" if (entity.energy - energy_needed) > 0 then entity.energy = entity.energy - energy_needed global.hoverboard[index].charge = global.hoverboard[index].charge + charge_needed else print("Insufficient energy for charging.") end end function motionCheck(index) if entity.name == "up" then game.players[index].walking_state = {walking = walk, direction = defines.direction.north} elseif entity.name == "down" then game.players[index].walking_state = {walking = walk, direction = defines.direction.south} elseif entity.name == "left" then game.players[index].walking_state = {walking = walk, direction = defines.direction.west} elseif entity.name == "right" then game.players[index].walking_state = {walking = walk, direction = defines.direction.east} end end function tileCheck(index) local tile = getTile(index) if inboundTile(tile.name) == false then global.hoverboard[index].charge = 0 return end local walk = game.players[index].walking_state.walking local entity = getDirectiveEntity(index) if entity == nil then return end if entity.name == "accelerator_charger" then charge_hoverboard(index,entity) return end if global.hoverboard[index].charge > 0 then motionCheck(index) end end
function getTile(index) return game.players[index].surface.get_tile(game.players[index].position.x,game.players[index].position.y) end function getDirectiveEntity(index) position = {game.players[index].position.x, game.players[index].position.y} local list = {"left","down","up","right","accelerator_charger"} for _, name in ipairs(list) do local target = game.players[index].surface.find_entity(name,position) if target ~= nil then return target end end return nil end function inboundTile(name) local tiles = {"copper-floor", "copper-floor2", "copper-floor3"} for _, tile in ipairs(tiles) do if tile == name then return true end end return false end function charge_hoverboard(index,entity) local charge_needed = 5 - global.hoverboard[index].charge local energy_needed = (charge_needed) * "1000" if (entity.energy - energy_needed) > 0 then entity.energy = entity.energy - energy_needed global.hoverboard[index].charge = global.hoverboard[index].charge + charge_needed else print("Insufficient energy for charging.") end end function motionCheck(index,entity) local walk = game.players[index].walking_state.walking if entity.name == "up" then game.players[index].walking_state = {walking = walk, direction = defines.direction.north} elseif entity.name == "down" then game.players[index].walking_state = {walking = walk, direction = defines.direction.south} elseif entity.name == "left" then game.players[index].walking_state = {walking = walk, direction = defines.direction.west} elseif entity.name == "right" then game.players[index].walking_state = {walking = walk, direction = defines.direction.east} end end function tileCheck(index) local tile = getTile(index) if inboundTile(tile.name) == false then global.hoverboard[index].charge = 0 return end local entity = getDirectiveEntity(index) if entity == nil then return end if entity.name == "accelerator_charger" then charge_hoverboard(index,entity) return end if global.hoverboard[index].charge > 0 then motionCheck(index,entity) end end
fix regression caused by motionCheck function
fix regression caused by motionCheck function
Lua
mit
kiba/Factorio-MagneticFloor,kiba/Factorio-MagneticFloor
f51be9b269546332e7cfe6f86f1d3c8ab873a5f0
net/cqueues.lua
net/cqueues.lua
-- Prosody IM -- Copyright (C) 2014 Daurnimator -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- -- This module allows you to use cqueues with a net.server mainloop -- local server = require "net.server"; local cqueues = require "cqueues"; -- Create a single top level cqueue local cq; if server.cq then -- server provides cqueues object cq = server.cq; elseif server.get_backend() == "select" and server._addtimer then -- server_select cq = cqueues.new(); local function step() assert(cq:loop(0)); end -- Use wrapclient (as wrapconnection isn't exported) to get server_select to watch cq fd local handler = server.wrapclient({ getfd = function() return cq:pollfd(); end; settimeout = function() end; -- Method just needs to exist close = function() end; -- Need close method for 'closeall' }, nil, nil, {}); -- Only need to listen for readable; cqueues handles everything under the hood -- readbuffer is called when `select` notes an fd as readable handler.readbuffer = step; -- Use server_select low lever timer facility, -- this callback gets called *every* time there is a timeout in the main loop server._addtimer(function(current_time) -- This may end up in extra step()'s, but cqueues handles it for us. step(); return cq:timeout(); end); elseif server.event and server.base then -- server_event cq = cqueues.new(); -- Only need to listen for readable; cqueues handles everything under the hood local EV_READ = server.event.EV_READ; local event_handle; event_handle = server.base:addevent(cq:pollfd(), EV_READ, function(e) -- Need to reference event_handle or this callback will get collected -- This creates a circular reference that can only be broken if event_handle is manually :close()'d local _ = event_handle; assert(cq:loop(0)); -- Convert a cq timeout to an acceptable timeout for luaevent local t = cq:timeout(); if t == 0 then -- if you give luaevent 0, it won't call this callback again t = 0.000001; -- 1 microsecond is the smallest that works (goes into a `struct timeval`) elseif t == nil then -- you always need to give a timeout, pick something big if we don't have one t = 0x7FFFFFFF; -- largest 32bit int end return EV_READ, t; end, -- Schedule the callback to fire on first tick to ensure any cq:wrap calls that happen during start-up are serviced. 0.000001); else error "NYI" end return { cq = cq; }
-- Prosody IM -- Copyright (C) 2014 Daurnimator -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- -- This module allows you to use cqueues with a net.server mainloop -- local server = require "net.server"; local cqueues = require "cqueues"; assert(cqueues.VERSION >= 20150112, "cqueues newer than 20151013 required") -- Create a single top level cqueue local cq; if server.cq then -- server provides cqueues object cq = server.cq; elseif server.get_backend() == "select" and server._addtimer then -- server_select cq = cqueues.new(); local function step() assert(cq:loop(0)); end -- Use wrapclient (as wrapconnection isn't exported) to get server_select to watch cq fd local handler = server.wrapclient({ getfd = function() return cq:pollfd(); end; settimeout = function() end; -- Method just needs to exist close = function() end; -- Need close method for 'closeall' }, nil, nil, {}); -- Only need to listen for readable; cqueues handles everything under the hood -- readbuffer is called when `select` notes an fd as readable handler.readbuffer = step; -- Use server_select low lever timer facility, -- this callback gets called *every* time there is a timeout in the main loop server._addtimer(function(current_time) -- This may end up in extra step()'s, but cqueues handles it for us. step(); return cq:timeout(); end); elseif server.event and server.base then -- server_event cq = cqueues.new(); -- Only need to listen for readable; cqueues handles everything under the hood local EV_READ = server.event.EV_READ; -- Convert a cqueues timeout to an acceptable timeout for luaevent local function luaevent_safe_timeout(cq) local t = cq:timeout(); -- if you give luaevent 0 or nil, it re-uses the previous timeout. if t == 0 then t = 0.000001; -- 1 microsecond is the smallest that works (goes into a `struct timeval`) elseif t == nil then -- pick something big if we don't have one t = 0x7FFFFFFF; -- largest 32bit int end return t end local event_handle; event_handle = server.base:addevent(cq:pollfd(), EV_READ, function(e) -- Need to reference event_handle or this callback will get collected -- This creates a circular reference that can only be broken if event_handle is manually :close()'d local _ = event_handle; -- Run as many cqueues things as possible (with a timeout of 0) -- If an error is thrown, it will break the libevent loop; but prosody resumes after logging a top level error assert(cq:loop(0)); return EV_READ, luaevent_safe_timeout(cq); end, luaevent_safe_timeout(cq)); else error "NYI" end return { cq = cq; }
net.cqueues: Fixes hardcoded timeout for first iteration
net.cqueues: Fixes hardcoded timeout for first iteration This was originally put in place as a fix for what ended up a cqueues bug: https://github.com/wahern/cqueues/issues/40 A check for a cqueues version with the bug fix is included.
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
69d99f4a6c60169c302027ecfa3e91bc93738fa3
lua/wire/flir.lua
lua/wire/flir.lua
--[[ Simulation of FLIR (forward-looking infrared) vision. Possible future ideas: * Different materials have different emissivities: aluminium is about 20%, wherease asphalt is 95%. maybe we could use the physical properties to simulate this? * the luminance of a texture contributes *negatively* to its emissivity * IR sensors often have auto gain control that we might simulate with auto-exposure * players are drawn fullbright but NPCs aren't. --]] if not FLIR then FLIR = { enabled = false } end if CLIENT then FLIR.RenderStack = {} FLIR.Render = 0 FLIR.bright = CreateMaterial("flir_bright", "UnlitGeneric", { ["$basetexture"] = "color/white", ["$model"] = 1 }) FLIR.mapcol = { [ "$pp_colour_brightness" ] = 0.4, [ "$pp_colour_contrast" ] = 0.4 } FLIR.skycol = { [ "$pp_colour_contrast" ] = 0.2, [ "$pp_colour_brightness" ] = 1 } FLIR.desat = { ["$pp_colour_colour"] = 0, ["$pp_colour_contrast"] = 1, ["$pp_colour_brightness"] = 0 } local function SetFLIRMat(ent) if not IsValid(ent) then return end if ent:GetMoveType() == MOVETYPE_VPHYSICS or ent:IsPlayer() or ent:IsNPC() or ent:IsRagdoll() or ent:GetClass() == "gmod_wire_hologram" then ent.FLIRCol = ent:GetColor() ent.RenderOverride = FLIR.Render table.insert(FLIR.RenderStack, ent) --add entity to the FLIR renderstack and remove it from regular opaque rendering end end local function RemoveFLIRMat(ent) ent.RenderOverride = nil if ent.FLIRCol then ent:SetColor(ent.FLIRCol) end table.RemoveByValue(FLIR.RenderStack, ent) end function FLIR.Render(self) if FLIR.Render == 1 then self:DrawModel() end end function FLIR.start() if FLIR.enabled then return else FLIR.enabled = true end bright = false hook.Add("PreRender", "wire_flir", function() --lighting mode 1 = fullbright render.SetLightingMode(1) FLIR.Render = 0 end) hook.Add("PostDraw2DSkyBox", "wire_flir", function() --overrides 2d skybox to be gray, as it normally becomes white or black DrawColorModify(FLIR.skycol) end) hook.Add("PreDrawTranslucentRenderables", "wire_flir", function(a, b, sky) if not sky then DrawColorModify(FLIR.mapcol) end end) hook.Add("PostDrawTranslucentRenderables", "wire_flir", function(_a, _b, sky) if sky then return end render.SetLightingMode(0) FLIR.Render = 1 render.MaterialOverride(FLIR.bright) for k, v in pairs(FLIR.RenderStack) do --draw all the FLIR highlighted enemies after the opaque render if v:IsValid() then v:DrawModel() end --to separate then from the rest of the map end FLIR.Render = 0 render.MaterialOverride(nil) render.SetLightingMode(1) end) hook.Add("RenderScreenspaceEffects", "wire_flir", function() render.SetLightingMode(0) DrawColorModify(FLIR.desat) DrawBloom(0.5,1.0,2,2,2,1, 1, 1, 1) DrawBokehDOF(1, 0.1, 0.1) end) hook.Add("OnEntityCreated", "wire_flir", function(ent) if FLIR.enabled then SetFLIRMat(ent) end end) hook.Add("CreateClientsideRagdoll", "wire_flir", function(ent, rag) if FLIR.enabled then SetFLIRMat(rag) end end) for k, v in pairs(ents.GetAll()) do SetFLIRMat(v) end end function FLIR.stop() if FLIR.enabled then FLIR.enabled = false else return end render.SetLightingMode(0) hook.Remove("PreDrawTranslucentRenderables", "wire_flir") hook.Remove("PostDrawTranslucentRenderables", "wire_flir") hook.Remove("RenderScreenspaceEffects", "wire_flir") hook.Remove("PostDraw2DSkyBox", "wire_flir") hook.Remove("PreRender", "wire_flir") hook.Remove("OnEntityCreated", "wire_flir") hook.Remove("CreateClientsideRagdoll", "wire_flir") render.MaterialOverride(nil) for k, v in pairs(ents.GetAll()) do RemoveFLIRMat(v) end end function FLIR.enable(enabled) if enabled then FLIR.start() else FLIR.stop() end end usermessage.Hook("flir.enable",function(um) FLIR.enable(um:ReadBool()) end) concommand.Add("flir_enable", function(player, command, args) FLIR.enable(tobool(args[1])) end) else function FLIR.start(player) FLIR.enable(player, true) end function FLIR.stop(player) FLIR.enable(player, false) end function FLIR.enable(player, enabled) umsg.Start( "flir.enable", player) umsg.Bool( enabled ) umsg.End() end end
--[[ Simulation of FLIR (forward-looking infrared) vision. Possible future ideas: * Different materials have different emissivities: aluminium is about 20%, wherease asphalt is 95%. maybe we could use the physical properties to simulate this? * the luminance of a texture contributes *negatively* to its emissivity * IR sensors often have auto gain control that we might simulate with auto-exposure * players are drawn fullbright but NPCs aren't. --]] if not FLIR then FLIR = { enabled = false } end if CLIENT then FLIR.RenderStack = {} FLIR.ShouldRender = false FLIR.bright = CreateMaterial("flir_bright", "UnlitGeneric", { ["$basetexture"] = "color/white", ["$model"] = 1 }) FLIR.mapcol = { [ "$pp_colour_brightness" ] = 0.4, [ "$pp_colour_contrast" ] = 0.4 } FLIR.skycol = { [ "$pp_colour_contrast" ] = 0.2, [ "$pp_colour_brightness" ] = 1 } FLIR.desat = { ["$pp_colour_colour"] = 0, ["$pp_colour_contrast"] = 1, ["$pp_colour_brightness"] = 0 } local function SetFLIRMat(ent) if not IsValid(ent) then return end if ent:GetMoveType() == MOVETYPE_VPHYSICS or ent:IsPlayer() or ent:IsNPC() or ent:IsRagdoll() or ent:GetClass() == "gmod_wire_hologram" then ent.RenderOverride = FLIR.Render FLIR.RenderStack[ent] = true end end local function RemoveFLIRMat(ent) ent.RenderOverride = nil FLIR.RenderStack[ent] = nil end function FLIR.Render(self) if FLIR.ShouldRender then self:DrawModel() end end function FLIR.start() if FLIR.enabled then return else FLIR.enabled = true end bright = false hook.Add("PreRender", "wire_flir", function() --lighting mode 1 = fullbright render.SetLightingMode(1) FLIR.ShouldRender = false end) hook.Add("PostDraw2DSkyBox", "wire_flir", function() --overrides 2d skybox to be gray, as it normally becomes white or black DrawColorModify(FLIR.skycol) end) hook.Add("PreDrawTranslucentRenderables", "wire_flir", function(a, b, sky) if not sky then DrawColorModify(FLIR.mapcol) end end) hook.Add("PostDrawTranslucentRenderables", "wire_flir", function(_a, _b, sky) if sky then return end render.SetLightingMode(0) FLIR.ShouldRender = true render.MaterialOverride(FLIR.bright) --draw all the FLIR highlighted enemies after the opaque render to separate then from the rest of the map for v in pairs(FLIR.RenderStack) do if v:IsValid() then v:DrawModel() else FLIR.RenderStack[v] = nil end end FLIR.ShouldRender = false render.MaterialOverride(nil) render.SetLightingMode(1) end) hook.Add("RenderScreenspaceEffects", "wire_flir", function() render.SetLightingMode(0) DrawColorModify(FLIR.desat) DrawBloom(0.5,1.0,2,2,2,1, 1, 1, 1) DrawBokehDOF(1, 0.1, 0.1) end) hook.Add("OnEntityCreated", "wire_flir", function(ent) if FLIR.enabled then SetFLIRMat(ent) end end) hook.Add("CreateClientsideRagdoll", "wire_flir", function(ent, rag) if FLIR.enabled then SetFLIRMat(rag) end end) for k, v in pairs(ents.GetAll()) do SetFLIRMat(v) end end function FLIR.stop() if FLIR.enabled then FLIR.enabled = false else return end render.SetLightingMode(0) hook.Remove("PreDrawTranslucentRenderables", "wire_flir") hook.Remove("PostDrawTranslucentRenderables", "wire_flir") hook.Remove("RenderScreenspaceEffects", "wire_flir") hook.Remove("PostDraw2DSkyBox", "wire_flir") hook.Remove("PreRender", "wire_flir") hook.Remove("OnEntityCreated", "wire_flir") hook.Remove("CreateClientsideRagdoll", "wire_flir") render.MaterialOverride(nil) for k, v in pairs(ents.GetAll()) do RemoveFLIRMat(v) end end function FLIR.enable(enabled) if enabled then FLIR.start() else FLIR.stop() end end usermessage.Hook("flir.enable",function(um) FLIR.enable(um:ReadBool()) end) concommand.Add("flir_enable", function(player, command, args) FLIR.enable(tobool(args[1])) end) else function FLIR.start(player) FLIR.enable(player, true) end function FLIR.stop(player) FLIR.enable(player, false) end function FLIR.enable(player, enabled) umsg.Start( "flir.enable", player) umsg.Bool( enabled ) umsg.End() end end
Flir fixes (#2264)
Flir fixes (#2264) * Flir fixes * fix lua error
Lua
apache-2.0
Grocel/wire,dvdvideo1234/wire,wiremod/wire
206dfa5c816a70753453d0351051f76774e50110
mod_statistics/prosodytop.lua
mod_statistics/prosodytop.lua
local curses = require "curses"; local server = require "net.server_select"; local timer = require "util.timer"; assert(curses.timeout, "Incorrect version of curses library. Try 'sudo luarocks install luaposix'"); local top = require "top"; function main() local stdscr = curses.stdscr() -- it's a userdatum --stdscr:clear(); local view = top.new({ stdscr = stdscr; prosody = { up_since = os.time() }; conn_list = {}; }); timer.add_task(0.01, function () local ch = stdscr:getch(); if ch then if stdscr:getch() == 410 then view:resized(); else curses.ungetch(ch); end end return 0.2; end); timer.add_task(0, function () view:draw(); return 1; end); --[[ posix.signal(28, function () table.insert(view.conn_list, { jid = "WINCH" }); --view:draw(); end); ]] -- Fake socket object around stdin local stdin = { getfd = function () return 0; end; dirty = function (self) return false; end; settimeout = function () end; send = function (_, d) return #d, 0; end; close = function () end; receive = function (_, patt) local ch = stdscr:getch(); if ch >= 0 and ch <=255 then return string.char(ch); elseif ch == 410 then view:resized(); else table.insert(view.conn_list, { jid = tostring(ch) }); --FIXME end return ""; end }; local function on_incoming(stdin, text) -- TODO: Handle keypresses if text:lower() == "q" then os.exit(); end end stdin = server.wrapclient(stdin, "stdin", 0, { onincoming = on_incoming, ondisconnect = function () end }, "*a"); local function handle_line(line) local e = { STAT = function (name) return function (value) view:update_stat(name, value); end end; SESS = function (id) return function (jid) return function (stats) view:update_session(id, jid, stats); end end end; }; local chunk = assert(loadstring(line)); setfenv(chunk, e); chunk(); end local stats_listener = {}; function stats_listener.onconnect(conn) --stdscr:mvaddstr(6, 0, "CONNECTED"); end local partial; function stats_listener.onincoming(conn, data) --print("DATA", data) if partial then partial, data = nil, partial..data; end if not data:match("\n") then partial = data; return; end local lastpos = 1; for line, pos in data:gmatch("([^\n]+)\n()") do lastpos = pos; handle_line(line); end if lastpos == #data then partial = nil; else partial = data:sub(lastpos); end end function stats_listener.ondisconnect(conn, err) stdscr:mvaddstr(6, 0, "DISCONNECTED: "..(err or "unknown")); end local conn = require "socket".tcp(); assert(conn:connect("localhost", 5782)); handler = server.wrapclient(conn, "localhost", 5279, stats_listener, "*a"); end return { run = function () --os.setlocale("UTF-8", "all") curses.initscr() curses.cbreak() curses.echo(false) -- not noecho ! curses.nl(false) -- not nonl ! curses.timeout(0); local ok, err = pcall(main); --while true do stdscr:getch() end --stdscr:endwin() if ok then ok, err = xpcall(server.loop, debug.traceback); end curses.endwin(); --stdscr:refresh(); if not ok then print(err); end print"DONE" end; };
local curses = require "curses"; local server = require "net.server_select"; local timer = require "util.timer"; assert(curses.timeout, "Incorrect version of curses library. Try 'sudo luarocks install luaposix'"); local top = require "top"; function main() local stdscr = curses.stdscr() -- it's a userdatum --stdscr:clear(); local view = top.new({ stdscr = stdscr; prosody = { up_since = os.time() }; conn_list = {}; }); timer.add_task(0.01, function () local ch = stdscr:getch(); if ch then if stdscr:getch() == 410 then view:resized(); else curses.ungetch(ch); end end return 0.2; end); timer.add_task(0, function () view:draw(); return 1; end); --[[ posix.signal(28, function () table.insert(view.conn_list, { jid = "WINCH" }); --view:draw(); end); ]] -- Fake socket object around stdin local stdin = { getfd = function () return 0; end; dirty = function (self) return false; end; settimeout = function () end; send = function (_, d) return #d, 0; end; close = function () end; receive = function (_, patt) local ch = stdscr:getch(); if ch >= 0 and ch <=255 then return string.char(ch); elseif ch == 410 then view:resized(); else table.insert(view.conn_list, { jid = tostring(ch) }); --FIXME end return ""; end }; local function on_incoming(stdin, text) -- TODO: Handle keypresses if text:lower() == "q" then os.exit(); end end stdin = server.wrapclient(stdin, "stdin", 0, { onincoming = on_incoming, ondisconnect = function () end }, "*a"); local function handle_line(line) local e = { STAT = function (name) return function (value) view:update_stat(name, value); end end; SESS = function (id) return function (jid) return function (stats) view:update_session(id, jid, stats); end end end; }; local chunk = assert(loadstring(line)); setfenv(chunk, e); chunk(); end local stats_listener = {}; function stats_listener.onconnect(conn) --stdscr:mvaddstr(6, 0, "CONNECTED"); end local partial = ""; function stats_listener.onincoming(conn, data) --print("DATA", data) data = partial..data; local lastpos = 1; for line, pos in data:gmatch("([^\n]+)\n()") do lastpos = pos; handle_line(line); end partial = data:sub(lastpos); end function stats_listener.ondisconnect(conn, err) stdscr:mvaddstr(6, 0, "DISCONNECTED: "..(err or "unknown")); end local conn = require "socket".tcp(); assert(conn:connect("localhost", 5782)); handler = server.wrapclient(conn, "localhost", 5279, stats_listener, "*a"); end return { run = function () --os.setlocale("UTF-8", "all") curses.initscr() curses.cbreak() curses.echo(false) -- not noecho ! curses.nl(false) -- not nonl ! curses.timeout(0); local ok, err = pcall(main); --while true do stdscr:getch() end --stdscr:endwin() if ok then ok, err = xpcall(server.loop, debug.traceback); end curses.endwin(); --stdscr:refresh(); if not ok then print(err); end print"DONE" end; };
mod_statistics/prosodytop.lua: Simplify and fix buffering and line separation (thanks Ge0rG)
mod_statistics/prosodytop.lua: Simplify and fix buffering and line separation (thanks Ge0rG)
Lua
mit
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
b53daf6803d256fa4750f0a3498af73a89813608
models/upload.lua
models/upload.lua
--- A basic lower upload API -- module(..., package.seeall) require 'posix' local Model = require 'bamboo.model' local Form = require 'bamboo.form' local function calcNewFilename(dest_dir, oldname) -- separate the base name and extense name of a filename local main, ext = oldname:match('^(.+)(%.%w+)$') if not ext then main = oldname ext = '' end -- check if exists the same name file local tstr = '' local i = 0 while posix.stat( dest_dir + main + tstr + ext ) do i = i + 1 tstr = '_' + tostring(i) end -- concat to new filename local newbasename = main + tstr return newbasename, ext end --- here, we temprorily only consider the file data is passed wholly by zeromq -- and save by bamboo -- @field t.req -- @field t.file_obj -- @field t.dest_dir -- @field t.prefix -- @field t.postfix -- local function savefile(t) local req, file_obj = t.req, t.file_obj local monserver_dir = bamboo.config.monserver_dir local project_name = bamboo.config.project_name assert(monserver_dir) assert(project_name) local dest_dir = (t.dest_dir and monserver_dir + '/sites/' + project_name + '/uploads/' + t.dest_dir) dest_dir = string.trailingPath(dest_dir) local url_prefix = 'media/uploads/' + t.dest_dir + '/' url_prefix = string.trailingPath(url_prefix) local prefix = t.prefix or '' local postfix = t.postfix or '' local filename = '' local body = '' -- if upload in html5 way if req.headers['x-requested-with'] then -- when html5 upload, we think of the name of that file was stored in header x-file-name -- if this info missing, we may consider the filename was put in the query string filename = req.headers['x-file-name'] -- TODO: -- req.body contains all file binary data body = req.body else checkType(file_obj, 'table') -- Notice: the filename in the form string are quoted by "" -- this pattern rule can deal with the windows style directory delimiter -- file_obj['content-disposition'] contains many file associated info filename = file_obj['content-disposition'].filename:sub(2, -2):match('\\?([^\\]-%.%w+)$') body = file_obj.body end if isFalse(filename) or isFalse(body) then return nil, nil end if not posix.stat(dest_dir) then -- why posix have no command like " mkdir -p " os.execute('mkdir -p ' + dest_dir) end local newbasename, ext = calcNewFilename(dest_dir, filename) local newname = prefix + newbasename + postfix + ext local disk_path = dest_dir + newname local url_path = url_prefix + newname -- write file to disk local fd = io.open(disk_path, "wb") fd:write(body) fd:close() return disk_path, newname, url_path end local Upload = Model:extend { __tag = 'Bamboo.Model.Upload'; __name = 'Upload'; __desc = "User's upload files."; __fields = { ['name'] = {}, ['path'] = {}, ['size'] = {}, ['timestamp'] = {}, ['desc'] = {}, }; init = function (self, t) if not t then return self end self.name = t.name or self.name self.path = t.url_path self.size = posix.stat(t.path).size self.timestamp = os.time() -- according the current design, desc field is nil self.desc = t.desc or '' return self end; --- For traditional Html4 form upload -- batch = function (self, req, params, dest_dir, prefix, postfix) I_AM_CLASS(self) local file_objs = List() -- file data are stored as arraies in params for i, v in ipairs(params) do local path, name, url_path = savefile { req = req, file_obj = v, dest_dir = dest_dir, prefix = prefix, postfix = postfix } if not path or not name then return nil end -- create file instance local file_instance = self { name = name, path = path, url_path = url_path } if file_instance then -- store to db file_instance:save() file_objs:append(file_instance) end end -- a file object list return file_objs end; process = function (self, web, req, dest_dir, prefix, postfix) I_AM_CLASS(self) assert(web, '[ERROR] Upload input parameter: "web" must be not nil.') assert(req, '[ERROR] Upload input parameter: "req" must be not nil.') -- current scheme: for those larger than PRESIZE, send a ABORT signal, and abort immediately if req.headers['x-mongrel2-upload-start'] then print('return blank to abort upload.') web.conn:reply(req, '') return nil, 'Uploading file is too large.' end -- if upload in html5 way if req.headers['x-requested-with'] then -- stored to disk local path, name, url_path = savefile { req = req, dest_dir = dest_dir, prefix = prefix, postfix = postfix } if not path or not name then return nil, '[ERROR] empty file.' end local file_instance = self { name = name, path = path, url_path = url_path } if file_instance then file_instance:save() return file_instance, 'single' end else -- for uploading in html4 way local params = Form:parse(req) local files = self:batch ( req, params, dest_dir, prefix, postfix ) if not files then return nil, '[ERROR] empty file.' end if #files == 1 then -- even only one file upload, batch function will return a list return files[1], 'single' else return files, 'multiple' end end end; calcNewFilename = function (self, dest_dir, oldname) return calcNewFilename(dest_dir, oldname) end; -- this function, encorage override by child model, to execute their own delete action specDelete = function (self) I_AM_INSTANCE() -- remove file from disk os.execute('mkdir -p ' + self.path) return self end; } return Upload
--- A basic lower upload API -- module(..., package.seeall) require 'posix' local Model = require 'bamboo.model' local Form = require 'bamboo.form' local function calcNewFilename(dest_dir, oldname) -- separate the base name and extense name of a filename local main, ext = oldname:match('^(.+)(%.%w+)$') if not ext then main = oldname ext = '' end -- check if exists the same name file local tstr = '' local i = 0 while posix.stat( dest_dir + main + tstr + ext ) do i = i + 1 tstr = '_' + tostring(i) end -- concat to new filename local newbasename = main + tstr return newbasename, ext end local function absoluteDirPrefix() local monserver_dir = bamboo.config.monserver_dir local project_name = bamboo.config.project_name assert(monserver_dir) assert(project_name) return monserver_dir + '/sites/' + project_name + '/uploads/' end --- here, we temprorily only consider the file data is passed wholly by zeromq -- and save by bamboo -- @field t.req -- @field t.file_obj -- @field t.dest_dir -- @field t.prefix -- @field t.postfix -- local function savefile(t) local req, file_obj = t.req, t.file_obj local dest_dir = t.dest_dir and absoluteDirPrefix() + t.dest_dir dest_dir = string.trailingPath(dest_dir) -- print(dest_dir) local url_prefix = 'media/uploads/' + t.dest_dir + '/' url_prefix = string.trailingPath(url_prefix) local prefix = t.prefix or '' local postfix = t.postfix or '' local filename = '' local body = '' -- if upload in html5 way if req.headers['x-requested-with'] then -- when html5 upload, we think of the name of that file was stored in header x-file-name -- if this info missing, we may consider the filename was put in the query string filename = req.headers['x-file-name'] -- TODO: -- req.body contains all file binary data body = req.body else checkType(file_obj, 'table') -- Notice: the filename in the form string are quoted by "" -- this pattern rule can deal with the windows style directory delimiter -- file_obj['content-disposition'] contains many file associated info filename = file_obj['content-disposition'].filename:sub(2, -2):match('\\?([^\\]-%.%w+)$') body = file_obj.body end if isFalse(filename) or isFalse(body) then return nil, nil end if not posix.stat(dest_dir) then -- why posix have no command like " mkdir -p " os.execute('mkdir -p ' + dest_dir) end local newbasename, ext = calcNewFilename(dest_dir, filename) local newname = prefix + newbasename + postfix + ext local disk_path = dest_dir + newname local url_path = url_prefix + newname -- write file to disk local fd = io.open(disk_path, "wb") fd:write(body) fd:close() return disk_path, newname, url_path end local Upload = Model:extend { __tag = 'Bamboo.Model.Upload'; __name = 'Upload'; __desc = "User's upload files."; __fields = { ['name'] = {}, ['path'] = {}, ['size'] = {}, ['timestamp'] = {}, ['desc'] = {}, }; init = function (self, t) if not t then return self end self.name = t.name or self.name self.path = t.url_path self.size = posix.stat(t.path).size self.timestamp = os.time() -- according the current design, desc field is nil self.desc = t.desc or '' return self end; --- For traditional Html4 form upload -- batch = function (self, req, params, dest_dir, prefix, postfix) I_AM_CLASS(self) local file_objs = List() -- file data are stored as arraies in params for i, v in ipairs(params) do local path, name, url_path = savefile { req = req, file_obj = v, dest_dir = dest_dir, prefix = prefix, postfix = postfix } if not path or not name then return nil end -- create file instance local file_instance = self { name = name, path = path, url_path = url_path } if file_instance then -- store to db file_instance:save() file_objs:append(file_instance) end end -- a file object list return file_objs end; process = function (self, web, req, dest_dir, prefix, postfix) I_AM_CLASS(self) assert(web, '[ERROR] Upload input parameter: "web" must be not nil.') assert(req, '[ERROR] Upload input parameter: "req" must be not nil.') -- current scheme: for those larger than PRESIZE, send a ABORT signal, and abort immediately if req.headers['x-mongrel2-upload-start'] then print('return blank to abort upload.') web.conn:reply(req, '') return nil, 'Uploading file is too large.' end -- if upload in html5 way if req.headers['x-requested-with'] then -- stored to disk local path, name, url_path = savefile { req = req, dest_dir = dest_dir, prefix = prefix, postfix = postfix } if not path or not name then return nil, '[ERROR] empty file.' end local file_instance = self { name = name, path = path, url_path = url_path } if file_instance then file_instance:save() return file_instance, 'single' end else -- for uploading in html4 way local params = Form:parse(req) local files = self:batch ( req, params, dest_dir, prefix, postfix ) if not files then return nil, '[ERROR] empty file.' end if #files == 1 then -- even only one file upload, batch function will return a list return files[1], 'single' else return files, 'multiple' end end end; calcNewFilename = function (self, dest_dir, oldname) return calcNewFilename(dest_dir, oldname) end; absoluteDirPrefix = function (self) return absoluteDirPrefix() end; -- this function, encorage override by child model, to execute their own delete action specDelete = function (self) I_AM_INSTANCE() -- remove file from disk os.execute('mkdir -p ' + self.path) return self end; } return Upload
Add an upload API:
Add an upload API: Upload:absoluteDirPrefix() this function will return the upload files' really absolute directory prefix, can be used for generating files by app code. Signed-off-by: Daogang Tang <[email protected]>
Lua
bsd-3-clause
daogangtang/bamboo,daogangtang/bamboo
1b67164560870d8f48908d2d6448f66632ae97fc
lovetoys/eventManager.lua
lovetoys/eventManager.lua
EventManager = class("EventManager") function EventManager:__init() self.eventListeners = {} self.getKey = function () for index, value in pairs(table) do if value == element then return index end end return false end end end -- Adding an eventlistener to a specific event function EventManager:addListener(eventName, listener) if not self.eventListeners[eventName] then self.eventListeners[eventName] = {} end table.insert(self.eventListeners[eventName], listener) end -- Removing an eventlistener from an event function EventManager:removeListener(eventName, listener) if self.eventListeners[eventName] and getKey(self.eventListener[eventName], listener) then table.remove(self.eventListener[eventName], getKey(self.eventListener[eventName], listener)) end end -- Firing an event. All registered listener will react to this event function EventManager:fireEvent(event) if self.eventListeners[event.__name] then for k,v in pairs(self.eventListeners[event.__name]) do v[2](v[1], event) end end end
EventManager = class("EventManager") function EventManager:__init() self.eventListeners = {} self.getKey = function() for index, value in pairs(table) do if value == element then return index end return false end end end -- Adding an eventlistener to a specific event function EventManager:addListener(eventName, listener) if not self.eventListeners[eventName] then self.eventListeners[eventName] = {} end table.insert(self.eventListeners[eventName], listener) end -- Removing an eventlistener from an event function EventManager:removeListener(eventName, listener) if self.eventListeners[eventName] and getKey(self.eventListener[eventName], listener) then table.remove(self.eventListener[eventName], getKey(self.eventListener[eventName], listener)) end end -- Firing an event. All registered listener will react to this event function EventManager:fireEvent(event) if self.eventListeners[event.__name] then for k,v in pairs(self.eventListeners[event.__name]) do v[2](v[1], event) end end end
Fixed bug in Eventmanager. I'm stupid -.-
Fixed bug in Eventmanager. I'm stupid -.-
Lua
mit
takaaptech/lovetoys,xpol/lovetoys
431feb6f16477eb77f4e95d9fde2989248290481
lualib/http/tlshelper.lua
lualib/http/tlshelper.lua
local socket = require "http.sockethelper" local c = require "ltls.c" local tlshelper = {} function tlshelper.init_requestfunc(fd, tls_ctx) local readfunc = socket.readfunc(fd) local writefunc = socket.writefunc(fd) return function () local ds1 = tls_ctx:handshake() writefunc(ds1) while not tls_ctx:finished() do local ds2 = readfunc() local ds3 = tls_ctx:handshake(ds2) if ds3 then writefunc(ds3) end end end end function tlshelper.init_responsefunc(fd, tls_ctx) local readfunc = socket.readfunc(fd) local writefunc = socket.writefunc(fd) return function () while not tls_ctx:finished() do local ds1 = readfunc() local ds2 = tls_ctx:handshake(ds1) if ds2 then writefunc(ds2) end end local ds3 = tls_ctx:write() writefunc(ds3) end end function tlshelper.closefunc(tls_ctx) return function () tls_ctx:close() end end function tlshelper.readfunc(fd, tls_ctx) local readfunc = socket.readfunc(fd) local read_buff = "" return function (sz) if not sz then local s = "" if #read_buff == 0 then local ds = readfunc(sz) s = tls_ctx:read(ds) end return read_buff .. s else while #read_buff < sz do local ds = readfunc() local s = tls_ctx:read(ds) read_buff = read_buff .. s end local s = string.sub(read_buff, 1, sz) read_buff = string.sub(read_buff, sz+1, #read_buff) return s end end end function tlshelper.writefunc(fd, tls_ctx) local writefunc = socket.writefunc(fd) return function (s) local ds = tls_ctx:write(s) return writefunc(ds) end end function tlshelper.readallfunc(fd, tls_ctx) local readfunc = socket.readfunc(fd) return function () local ds = socket.readall(fd) local s = tls_ctx:read(ds) return s end end function tlshelper.newctx() return c.newctx() end function tlshelper.newtls(method, ssl_ctx) return c.newtls(method, ssl_ctx) end return tlshelper
local socket = require "http.sockethelper" local c = require "ltls.c" local tlshelper = {} function tlshelper.init_requestfunc(fd, tls_ctx) local readfunc = socket.readfunc(fd) local writefunc = socket.writefunc(fd) return function () local ds1 = tls_ctx:handshake() writefunc(ds1) while not tls_ctx:finished() do local ds2 = readfunc() local ds3 = tls_ctx:handshake(ds2) if ds3 then writefunc(ds3) end end end end function tlshelper.init_responsefunc(fd, tls_ctx) local readfunc = socket.readfunc(fd) local writefunc = socket.writefunc(fd) return function () while not tls_ctx:finished() do local ds1 = readfunc() local ds2 = tls_ctx:handshake(ds1) if ds2 then writefunc(ds2) end end local ds3 = tls_ctx:write() writefunc(ds3) end end function tlshelper.closefunc(tls_ctx) return function () tls_ctx:close() end end function tlshelper.readfunc(fd, tls_ctx) local readfunc = socket.readfunc(fd) local read_buff = "" return function (sz) if not sz then local s = "" if #read_buff == 0 then local ds = readfunc(sz) s = tls_ctx:read(ds) end s = read_buff .. s read_buff = "" return s else while #read_buff < sz do local ds = readfunc() local s = tls_ctx:read(ds) read_buff = read_buff .. s end local s = string.sub(read_buff, 1, sz) read_buff = string.sub(read_buff, sz+1, #read_buff) return s end end end function tlshelper.writefunc(fd, tls_ctx) local writefunc = socket.writefunc(fd) return function (s) local ds = tls_ctx:write(s) return writefunc(ds) end end function tlshelper.readallfunc(fd, tls_ctx) local readfunc = socket.readfunc(fd) return function () local ds = socket.readall(fd) local s = tls_ctx:read(ds) return s end end function tlshelper.newctx() return c.newctx() end function tlshelper.newtls(method, ssl_ctx) return c.newtls(method, ssl_ctx) end return tlshelper
bugfix #1007
bugfix #1007
Lua
mit
jxlczjp77/skynet,xcjmine/skynet,xjdrew/skynet,icetoggle/skynet,xcjmine/skynet,bigrpg/skynet,sanikoyes/skynet,cloudwu/skynet,korialuo/skynet,ag6ag/skynet,ag6ag/skynet,pigparadise/skynet,hongling0/skynet,cloudwu/skynet,hongling0/skynet,pigparadise/skynet,bigrpg/skynet,sanikoyes/skynet,xcjmine/skynet,ag6ag/skynet,JiessieDawn/skynet,wangyi0226/skynet,icetoggle/skynet,bigrpg/skynet,jxlczjp77/skynet,jxlczjp77/skynet,xjdrew/skynet,wangyi0226/skynet,korialuo/skynet,JiessieDawn/skynet,JiessieDawn/skynet,icetoggle/skynet,cloudwu/skynet,xjdrew/skynet,hongling0/skynet,pigparadise/skynet,korialuo/skynet,wangyi0226/skynet,sanikoyes/skynet
eaddc558dd524e37691a02262a6768d7573f17b3
Examples/freecad-debian-sandbox.cfg.lua
Examples/freecad-debian-sandbox.cfg.lua
-- example config for freecad sandbox, which is created on top of external debian chroot, prepared by debian-setup.cfg.lua -- using debian-sandbox.cfg.lua config file as base -- redefine defaults.recalculate function, that will be called by base config defaults.recalculate_orig=defaults.recalculate function defaults.recalculate() -- redefine some parameters tunables.datadir=loader.path.combine(loader.workdir,"userdata-freecad") defaults.recalculate_orig() defaults.mounts.resolvconf_mount=defaults.mounts.direct_resolvconf_mount end defaults.recalculate() -- load base config dofile(loader.path.combine(loader.workdir,"debian-sandbox.cfg.lua")) -- remove some unneded features and mounts loader.table.remove_value(sandbox.features,"pulse") -- remove some mounts from base config loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.devsnd_mount) --loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.devdri_mount) --loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.sys_mount) loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.devinput_mount) loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.devshm_mount) loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.sbin_ro_mount) -- modify PATH env table.insert(sandbox.setup.env_set,{"PATH","/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"}) -- remove unshare_ipc bwrap param loader.table.remove_value(sandbox.bwrap,defaults.bwrap.unshare_ipc) freecad={ exec="/home/sandboxer/Freecad/AppRun", path="/home/sandboxer/Freecad", args=loader.args, term_signal=defaults.signals.SIGTERM, attach=true, pty=false, exclusive=true, desktop={ name = "Freecad (in sandbox)", comment = "Freecad, sandbox uid "..config.sandbox_uid, icon = loader.path.combine(tunables.datadir,"/home/sandboxer/Freecad/freecad-daily.png"), terminal = false, startupnotify = false, categories="Graphics;", }, } freecad_install_appimage={ exec="/bin/bash", path="/home/sandboxer", args={"-c","rm -rf $HOME/Freecad && img=`find . -name \"FreeCAD_*.AppImage\"|sort|head -n1` && chmod 755 $img && $img --appimage-extract && mv $HOME/squashfs-root $HOME/Freecad"}, term_signal=defaults.signals.SIGTERM, attach=true, pty=false, exclusive=true, }
-- example config for freecad sandbox, which is created on top of external debian chroot, prepared by debian-setup.cfg.lua -- using debian-sandbox.cfg.lua config file as base -- redefine defaults.recalculate function, that will be called by base config defaults.recalculate_orig=defaults.recalculate function defaults.recalculate() -- redefine some parameters tunables.datadir=loader.path.combine(loader.workdir,"userdata-freecad") defaults.recalculate_orig() defaults.mounts.resolvconf_mount=defaults.mounts.direct_resolvconf_mount end defaults.recalculate() -- load base config dofile(loader.path.combine(loader.workdir,"debian-sandbox.cfg.lua")) -- remove some unneded features and mounts loader.table.remove_value(sandbox.features,"pulse") -- remove some mounts from base config loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.devsnd_mount) --loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.devdri_mount) --loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.sys_mount) loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.devinput_mount) loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.devshm_mount) loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.sbin_ro_mount) -- modify PATH env table.insert(sandbox.setup.env_set,{"PATH","/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"}) -- add host mounts, readonly table.insert(sandbox.setup.mounts,{prio=99,"bind","/mnt/data","/mnt/data"}) -- remove unshare_ipc bwrap param loader.table.remove_value(sandbox.bwrap,defaults.bwrap.unshare_ipc) freecad={ exec="/home/sandboxer/Freecad/AppRun", path="/home/sandboxer/Freecad", args=loader.args, term_signal=defaults.signals.SIGTERM, attach=true, pty=false, exclusive=true, desktop={ name = "Freecad (in sandbox)", comment = "Freecad, sandbox uid "..config.sandbox_uid, icon = loader.path.combine(tunables.datadir,"/home/sandboxer/Freecad/freecad-daily.png"), terminal = false, startupnotify = false, categories="Graphics;", }, } freecad_install_appimage={ exec="/bin/bash", path="/home/sandboxer", args={"-c","rm -rf $HOME/Freecad && img=`find . -name \"FreeCAD_*.AppImage\"|sort|head -n1` && chmod 755 $img && $img --appimage-extract && mv $HOME/squashfs-root $HOME/Freecad"}, term_signal=defaults.signals.SIGTERM, attach=true, pty=false, exclusive=true, }
fixup! Examples: add freecad-debian-sandbox.cfg.lua example config
fixup! Examples: add freecad-debian-sandbox.cfg.lua example config
Lua
mit
DarkCaster/Sandboxer,DarkCaster/Sandboxer
cc50abebc2ee8ac01d3e373397f82ec373974e0c
quiz/c1quiz.lua
quiz/c1quiz.lua
local c1quiz = {} local typing = require 'quiz.typing' c1quiz.typing_direct = typing.direct c1quiz.typing_reverse = typing.reverse function c1quiz.include_direction(req) return '', [[заголовочные файлы - в другие заголовочные файлы и файлы с исходным кодом]], [[файлы с исходным кодом - в другие файлы с исходным кодом и в заголовочные файлы]], [[заголовочные файлы - в файлы с исходным кодом]], [[файлы с исходным кодом - в заголовочные файлы]], [[Известно, что код на языке C пишут в заголовочные файлы и в файлы с исходным кодом. Также известно, что с помощью директивы #include можно включать содержимое одних файлов в другие. Какие файлы при этом включаются в состав каких?]] end function c1quiz.where_directives(req) return '', [[и в заголовочных файлах, и в файлах с исходным кодом]], [[только в заголовочных файлах]], [[только в файлах с исходным кодом]], [[только в batch-файлах]], [[Известно, что код на языке C пишут в заголовочные файлы и в файлы с исходным кодом. В каких из них могут встречаться директивы препроцессора?]] end function c1quiz.directives_char(req) return '', [[#]], [[%]], [[$]], [[@]], [[С какого символа начинаются директивы препроцессора?]] end function c1quiz.linking(req) local headers = math.random(3, 5) local sources = math.random(6, 8) return '', tostring(sources), tostring(headers), tostring(headers + sources), tostring(headers * sources), [[Вася написал программу, состоящую из 5-ти заголовочных файлов и 8-ми файлов с исходным кодом. Сколько раз ему придётся запускать команду компиляции во время сборки программы?]] end function c1quiz.headers_and_sources(req) if math.random(1, 2) == 1 then return [[Что хранится в заголовочных файлах?]], 'объявления функций (declaration)', 'определения функций (definition)', 'реализации функций (implementation)', 'субтитры к Игре престолов :)', '' else return [[Что хранится в файлах с исходным кодом?]], 'определения функций (definition)', 'объявления функций (declaration)', 'интерфейс функций (interface)', 'субтитры к Игре престолов :)', '' end end function c1quiz.progress_github(req) return 'Опрос', [[да]], [[нет]], [[-]], [[не знаю]], [[Есть ли у вас аккаунт на Github?]] end function c1quiz.progress_repo_for_project(req) return 'Опрос', [[да]], [[нет]], [[-]], [[не знаю]], [[Создан ли репозиторий вашего учебного проекта?]] end function c1quiz.progress_commit(req) return 'Опрос', [[да]], [[нет]], [[-]], [[не знаю]], [[Сделали ли вы хотя бы один коммит? (Initial commit не считается)]] end function c1quiz.progress_gcc(req) return 'Опрос', [[да]], [[нет]], [[-]], [[не знаю]], [[Удалось ли вам установить компилятор и прочие утилиты, необходимые для сборки программ, и собрать программу из нескольких файлов (считающую факториалы)?]] end return c1quiz
local c1quiz = {} local typing = require 'quiz.typing' c1quiz.typing_direct = typing.direct c1quiz.typing_reverse = typing.reverse function c1quiz.include_direction(req) return '', [[заголовочные файлы - в другие заголовочные файлы и файлы с исходным кодом]], [[файлы с исходным кодом - в другие файлы с исходным кодом и в заголовочные файлы]], [[заголовочные файлы - в файлы с исходным кодом]], [[файлы с исходным кодом - в заголовочные файлы]], [[Известно, что код на языке C пишут в заголовочные файлы и в файлы с исходным кодом. Также известно, что с помощью директивы #include можно включать содержимое одних файлов в другие. Какие файлы при этом включаются в состав каких?]] end function c1quiz.where_directives(req) return '', [[и в заголовочных файлах, и в файлах с исходным кодом]], [[только в заголовочных файлах]], [[только в файлах с исходным кодом]], [[только в batch-файлах]], [[Известно, что код на языке C пишут в заголовочные файлы и в файлы с исходным кодом. В каких из них могут встречаться директивы препроцессора?]] end function c1quiz.directives_char(req) return '', [[#]], [[%]], [[$]], [[@]], [[С какого символа начинаются директивы препроцессора?]] end function c1quiz.linking(req) local headers = math.random(3, 5) local sources = math.random(6, 8) return ([[Вася написал программу, состоящую из %i заголовочных файлов и %i файлов с исходным кодом. Сколько раз ему придётся запускать команду компиляции во время сборки программы?]]):format(headers, sources), tostring(sources), tostring(headers), tostring(headers + sources), tostring(headers * sources), '' end function c1quiz.headers_and_sources(req) if math.random(1, 2) == 1 then return [[Что хранится в заголовочных файлах?]], 'объявления функций (declaration)', 'определения функций (definition)', 'реализации функций (implementation)', 'субтитры к Игре престолов :)', '' else return [[Что хранится в файлах с исходным кодом?]], 'определения функций (definition)', 'объявления функций (declaration)', 'интерфейс функций (interface)', 'субтитры к Игре престолов :)', '' end end function c1quiz.progress_github(req) return 'Опрос', [[да]], [[нет]], [[-]], [[не знаю]], [[Есть ли у вас аккаунт на Github?]] end function c1quiz.progress_repo_for_project(req) return 'Опрос', [[да]], [[нет]], [[-]], [[не знаю]], [[Создан ли репозиторий вашего учебного проекта?]] end function c1quiz.progress_commit(req) return 'Опрос', [[да]], [[нет]], [[-]], [[не знаю]], [[Сделали ли вы хотя бы один коммит? (Initial commit не считается)]] end function c1quiz.progress_gcc(req) return 'Опрос', [[да]], [[нет]], [[-]], [[не знаю]], [[Удалось ли вам установить компилятор и прочие утилиты, необходимые для сборки программ, и собрать программу из нескольких файлов (считающую факториалы)?]] end return c1quiz
fix task c1quiz.linking
fix task c1quiz.linking
Lua
mit
starius/kodomoquiz
34c11c6453efe79d5718f87e804ce976c54accfb
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 if os.isfile( ftarget ) == false or zpm.util.isNewer( file, ftarget ) then os.copyfile( file, ftarget ) end 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 ) -- always touch just in case if _ACTION:contains( "vs" ) or true then dummyFile = path.join( zpm.install.getExternDirectory(), "dummy.cpp" ) os.outputof( "{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
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 if os.isfile( ftarget ) == false or zpm.util.isNewer( file, ftarget ) then os.copyfile( file, ftarget ) end 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 ) -- always touch just in case if _ACTION:contains( "vs" ) or true then dummyFile = path.join( zpm.install.getExternDirectory(), "dummy.cpp" ) if os.is( "windows" ) then os.executef( "type nul >> {%s} && copy /b {%s}+,, {%s} > nul", dummyFile, dummyFile, dummyFile ) else os.execute( "{TOUCH} %s", dummyFile ) end 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
Fixed touch output
Fixed touch output
Lua
mit
Zefiros-Software/ZPM
744b4060c35229249b6aadd1f414859e2d24b9fe
lib/net.lua
lib/net.lua
--[[ Copyright 2012 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local dns = require('dns') local UV = require('uv') local tcp = require('tcp') local timer = require('timer') local utils = require('utils') local Emitter = require('emitter') local Net = {} --[[ Server ]]-- local Server = { } utils.inherits(Server, Emitter) function Server.prototype:listen(port, ... --[[ ip, callback --]] ) local args = {...} local ip local callback if not self._handle then self._handle = tcp.new() end -- Future proof if type(args[1]) == 'function' then ip = '0.0.0.0' callback = args[1] else ip = args[1] callback = args[2] or function() end end self._handle:bind(ip, port) self._handle:on('listening', callback) self._handle:on('error', function(err) return self:emit("error", err) end) self._handle:listen(function(err) if (err) then return self:emit("error", err) end local client = tcp.new() self._handle:accept(client) client:read_start() self:emit('connection', client) end) end function Server.prototype:close() if self._connectTimer then timer.clear_timer(self._connectTimer) self._connectTimer = nil end self._handle:close() end Server.new = function(...) local args = {...} local options local connectionCallback if #args == 1 then connectionCallback = args[1] elseif #args == 2 then options = args[1] connectionCallback = args[2] end local server = Server.new_obj() server:on('connection', connectionCallback) return server end --[[ Socket ]]-- local Socket = { } utils.inherits(Socket, Emitter) function Socket.prototype:_connect(address, port, addressType) if port then self.remotePort = port end self.remoteAddress = address if addressType == 4 then self._handle:connect(address, port) elseif addressType == 6 then self._handle:connect6(address, port) end end function Socket.prototype:setTimeout(msecs, callback) callback = callback or function() end if not self._connectTimer then self._connectTimer = timer.new() end self._connectTimer:start(msecs, 0, function(status) self._connectTimer:close() callback() end) end function Socket.prototype:close() if self._handle then self._handle:close() end end function Socket.prototype:pipe(destination) self._handle:pipe(destination) end function Socket.prototype:write(data, callback) self.bytesWritten = self.bytesWritten + #data self._handle:write(data) end function Socket.prototype:connect(port, host, callback) self._handle:on('connect', function() if self._connectTimer then timer.clear_timer(self._connectTimer) self._connectTimer = nil end self._handle:read_start() callback() end) self._handle:on('end', function() self:emit('end') end) self._handle:on('data', function(data) self.bytesRead = self.bytesRead + #data self:emit('data', data) end) self._handle:on('error', function(err) self:emit('error', err) self:close() end) dns.lookup(host, function(err, ip, addressType) if err then self:close() callback(err) return end self:_connect(ip, port, addressType) end) return self end Socket.new = function() local sock = Socket.new_obj() sock._connectTimer = timer.new() sock._handle = tcp.new() sock.bytesWritten = 0 sock.bytesRead = 0 return sock end Net.Server = Server Net.Socket = Socket Net.createConnection = function(port, ... --[[ host, cb --]]) local args = {...} local host local callback local s -- future proof host = args[1] callback = args[2] s = Socket.new() return s:connect(port, host, callback) end Net.create = Net.createConnection Net.createServer = function(connectionCallback) local s = Server.new(connectionCallback) return s end return Net
--[[ Copyright 2012 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local dns = require('dns') local UV = require('uv') local tcp = require('tcp') local Timer = require('timer') local utils = require('utils') local Emitter = require('emitter') local Net = {} --[[ Server ]]-- local Server = Emitter:extend() function Server.prototype:listen(port, ... --[[ ip, callback --]] ) local args = {...} local ip local callback if not self._handle then self._handle = tcp:new() end -- Future proof if type(args[1]) == 'function' then ip = '0.0.0.0' callback = args[1] else ip = args[1] callback = args[2] or function() end end self._handle:bind(ip, port) self._handle:on('listening', callback) self._handle:on('error', function(err) return self:emit("error", err) end) self._handle:listen(function(err) if (err) then return self:emit("error", err) end local client = tcp:new() self._handle:accept(client) client:read_start() self:emit('connection', client) end) end function Server.prototype:close() if self._connectTimer then Timer:clear_timer(self._connectTimer) self._connectTimer = nil end self._handle:close() end function Server.prototype:initialize(...) local args = {...} local options local connectionCallback if #args == 1 then connectionCallback = args[1] elseif #args == 2 then options = args[1] connectionCallback = args[2] end self:on('connection', connectionCallback) end --[[ Socket ]]-- local Socket = Emitter:extend() function Socket.prototype:_connect(address, port, addressType) if port then self.remotePort = port end self.remoteAddress = address if addressType == 4 then self._handle:connect(address, port) elseif addressType == 6 then self._handle:connect6(address, port) end end function Socket.prototype:setTimeout(msecs, callback) callback = callback or function() end if not self._connectTimer then self._connectTimer = Timer:new() end self._connectTimer:start(msecs, 0, function(status) self._connectTimer:close() callback() end) end function Socket.prototype:close() if self._handle then self._handle:close() end end function Socket.prototype:pipe(destination) self._handle:pipe(destination) end function Socket.prototype:write(data, callback) self.bytesWritten = self.bytesWritten + #data self._handle:write(data) end function Socket.prototype:connect(port, host, callback) self._handle:on('connect', function() if self._connectTimer then Timer:clear_timer(self._connectTimer) self._connectTimer = nil end self._handle:read_start() callback() end) self._handle:on('end', function() self:emit('end') end) self._handle:on('data', function(data) self.bytesRead = self.bytesRead + #data self:emit('data', data) end) self._handle:on('error', function(err) self:emit('error', err) self:close() end) dns.lookup(host, function(err, ip, addressType) if err then self:close() callback(err) return end self:_connect(ip, port, addressType) end) return self end function Socket.prototype:initialize() self._connectTimer = Timer:new() self._handle = tcp:new() self.bytesWritten = 0 self.bytesRead = 0 end Net.Server = Server Net.Socket = Socket Net.createConnection = function(port, ... --[[ host, cb --]]) local args = {...} local host local callback local s -- future proof host = args[1] callback = args[2] s = Socket:new() return s:connect(port, host, callback) end Net.create = Net.createConnection Net.createServer = function(connectionCallback) local s = Server:new(connectionCallback) return s end return Net
Fix net test
Fix net test
Lua
apache-2.0
zhaozg/luvit,sousoux/luvit,luvit/luvit,rjeli/luvit,luvit/luvit,kaustavha/luvit,boundary/luvit,boundary/luvit,rjeli/luvit,zhaozg/luvit,AndrewTsao/luvit,sousoux/luvit,kaustavha/luvit,sousoux/luvit,kaustavha/luvit,GabrielNicolasAvellaneda/luvit-upstream,boundary/luvit,rjeli/luvit,bsn069/luvit,connectFree/lev,GabrielNicolasAvellaneda/luvit-upstream,GabrielNicolasAvellaneda/luvit-upstream,bsn069/luvit,DBarney/luvit,boundary/luvit,DBarney/luvit,GabrielNicolasAvellaneda/luvit-upstream,sousoux/luvit,rjeli/luvit,sousoux/luvit,connectFree/lev,bsn069/luvit,DBarney/luvit,boundary/luvit,AndrewTsao/luvit,sousoux/luvit,AndrewTsao/luvit,boundary/luvit,DBarney/luvit
e242e8d5e6362f190f1ead9a489f56a0f9143737
modules/admin-full/luasrc/controller/admin/network.lua
modules/admin-full/luasrc/controller/admin/network.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.controller.admin.network", package.seeall) function index() require("luci.i18n") local uci = require("luci.model.uci").cursor() local i18n = luci.i18n.translate local page = node("admin", "network") page.target = alias("admin", "network", "network") page.title = i18n("network") page.order = 50 page.index = true local page = node("admin", "network", "vlan") page.target = cbi("admin_network/vlan") page.title = i18n("a_n_switch") page.order = 20 local page = entry({"admin", "network", "wireless"}, arcombine(template("admin_network/wifi_overview"), cbi("admin_network/wifi")), i18n("wifi"), 15) page.i18n = "wifi" page.leaf = true page.subindex = true uci:foreach("wireless", "wifi-device", function (section) local ifc = section[".name"] entry({"admin", "network", "wireless", ifc}, true, ifc:upper()).i18n = "wifi" end ) local page = entry({"admin", "network", "wireless_join"}, call("wifi_join"), nil, 16) page.i18n = "wifi" page.leaf = true local page = entry({"admin", "network", "network"}, arcombine(cbi("admin_network/network"), cbi("admin_network/ifaces")), i18n("interfaces", "Schnittstellen"), 10) page.leaf = true page.subindex = true local page = entry({"admin", "network", "add"}, cbi("admin_network/iface_add"), nil) page.leaf = true uci:foreach("network", "interface", function (section) local ifc = section[".name"] if ifc ~= "loopback" then entry({"admin", "network", "network", ifc}, true, ifc:upper()) end end ) local page = node("admin", "network", "dhcp") page.target = cbi("admin_network/dhcp") page.title = "DHCP" page.order = 30 page.subindex = true entry( {"admin", "network", "dhcp", "leases"}, cbi("admin_network/dhcpleases"), i18n("dhcp_leases") ) local page = node("admin", "network", "hosts") page.target = cbi("admin_network/hosts") page.title = i18n("hostnames", "Hostnames") page.order = 40 local page = node("admin", "network", "routes") page.target = cbi("admin_network/routes") page.title = i18n("a_n_routes_static") page.order = 50 end function wifi_join() local function param(x) return luci.http.formvalue(x) end local function ptable(x) x = param(x) return x and (type(x) ~= "table" and { x } or x) or {} end local dev = param("device") local ssid = param("join") if dev and ssid then local wep = (tonumber(param("wep")) == 1) local wpa = tonumber(param("wpa_version")) or 0 local channel = tonumber(param("channel")) local mode = param("mode") local bssid = param("bssid") local confirm = (param("confirm") == "1") local cancel = param("cancel") and true or false if confirm and not cancel then local fixed_bssid = (param("fixed_bssid") == "1") local replace_net = (param("replace_net") == "1") local autoconnect = (param("autoconnect") == "1") local attach_intf = param("attach_intf") local uci = require "luci.model.uci".cursor() if replace_net then uci:delete_all("wireless", "wifi-iface") end local wificonf = { device = dev, mode = (mode == "Ad-Hoc" and "adhoc" or "sta"), ssid = ssid } if attach_intf and uci:get("network", attach_intf, "ifname") then -- target network already has a interface, make it a bridge uci:set("network", attach_intf, "type", "bridge") uci:save("network") uci:commit("network") if autoconnect then require "luci.sys".call("/sbin/ifup " .. attach_intf) end end if fixed_bssid then wificonf.bssid = bssid end if wep then wificonf.encryption = "wep" wificonf.key = param("key") elseif wpa > 0 then wificonf.encryption = param("wpa_suite") wificonf.key = param("key") end uci:section("wireless", "wifi-iface", nil, wificonf) uci:delete("wireless", dev, "disabled") uci:set("wireless", dev, "channel", channel) uci:save("wireless") uci:commit("wireless") if autoconnect then require "luci.sys".call("/sbin/wifi") end luci.http.redirect(luci.dispatcher.build_url("admin/network/wireless", dev)) elseif cancel then luci.http.redirect(luci.dispatcher.build_url("admin/network/wireless_join?device=" .. dev)) else luci.template.render("admin_network/wifi_join_settings") end else luci.template.render("admin_network/wifi_join") end end
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.controller.admin.network", package.seeall) function index() require("luci.i18n") local uci = require("luci.model.uci").cursor() local i18n = luci.i18n.translate local page = node("admin", "network") page.target = alias("admin", "network", "network") page.title = i18n("network") page.order = 50 page.index = true local page = node("admin", "network", "vlan") page.target = cbi("admin_network/vlan") page.title = i18n("a_n_switch") page.order = 20 local page = entry({"admin", "network", "wireless"}, arcombine(template("admin_network/wifi_overview"), cbi("admin_network/wifi")), i18n("wifi"), 15) page.i18n = "wifi" page.leaf = true page.subindex = true uci:foreach("wireless", "wifi-device", function (section) local ifc = section[".name"] entry({"admin", "network", "wireless", ifc}, true, ifc:upper()).i18n = "wifi" end ) local page = entry({"admin", "network", "wireless_join"}, call("wifi_join"), nil, 16) page.i18n = "wifi" page.leaf = true local page = entry({"admin", "network", "wireless_delete"}, call("wifi_delete"), nil, 16) page.i18n = "wifi" page.leaf = true local page = entry({"admin", "network", "network"}, arcombine(cbi("admin_network/network"), cbi("admin_network/ifaces")), i18n("interfaces", "Schnittstellen"), 10) page.leaf = true page.subindex = true local page = entry({"admin", "network", "add"}, cbi("admin_network/iface_add"), nil) page.leaf = true uci:foreach("network", "interface", function (section) local ifc = section[".name"] if ifc ~= "loopback" then entry({"admin", "network", "network", ifc}, true, ifc:upper()) end end ) local page = node("admin", "network", "dhcp") page.target = cbi("admin_network/dhcp") page.title = "DHCP" page.order = 30 page.subindex = true entry( {"admin", "network", "dhcp", "leases"}, cbi("admin_network/dhcpleases"), i18n("dhcp_leases") ) local page = node("admin", "network", "hosts") page.target = cbi("admin_network/hosts") page.title = i18n("hostnames", "Hostnames") page.order = 40 local page = node("admin", "network", "routes") page.target = cbi("admin_network/routes") page.title = i18n("a_n_routes_static") page.order = 50 end function wifi_join() local function param(x) return luci.http.formvalue(x) end local function ptable(x) x = param(x) return x and (type(x) ~= "table" and { x } or x) or {} end local dev = param("device") local ssid = param("join") if dev and ssid then local wep = (tonumber(param("wep")) == 1) local wpa = tonumber(param("wpa_version")) or 0 local channel = tonumber(param("channel")) local mode = param("mode") local bssid = param("bssid") local confirm = (param("confirm") == "1") local cancel = param("cancel") and true or false if confirm and not cancel then local fixed_bssid = (param("fixed_bssid") == "1") local replace_net = (param("replace_net") == "1") local autoconnect = (param("autoconnect") == "1") local attach_intf = param("attach_intf") local uci = require "luci.model.uci".cursor() if replace_net then uci:delete_all("wireless", "wifi-iface") end local wificonf = { device = dev, mode = (mode == "Ad-Hoc" and "adhoc" or "sta"), ssid = ssid } if attach_intf and uci:get("network", attach_intf) == "interface" then -- target network already has a interface, make it a bridge uci:set("network", attach_intf, "type", "bridge") uci:save("network") uci:commit("network") wificonf.network = attach_intf if autoconnect then require "luci.sys".call("/sbin/ifup " .. attach_intf) end end if fixed_bssid then wificonf.bssid = bssid end if wep then wificonf.encryption = "wep" wificonf.key = param("key") elseif wpa > 0 then wificonf.encryption = param("wpa_suite") wificonf.key = param("key") end local s = uci:section("wireless", "wifi-iface", nil, wificonf) uci:delete("wireless", dev, "disabled") uci:set("wireless", dev, "channel", channel) uci:save("wireless") uci:commit("wireless") if autoconnect then require "luci.sys".call("/sbin/wifi") end luci.http.redirect(luci.dispatcher.build_url("admin/network/wireless")) elseif cancel then luci.http.redirect(luci.dispatcher.build_url("admin/network/wireless_join?device=" .. dev)) else luci.template.render("admin_network/wifi_join_settings") end else luci.template.render("admin_network/wifi_join") end end function wifi_delete(network) local uci = require "luci.model.uci".cursor() local wlm = require "luci.model.wireless" wlm.init(uci) wlm:del_network(network) uci:save("wireless") luci.http.redirect(luci.dispatcher.build_url("admin/network/wireless")) end
modules/admin-full: support deleting wireless networks and fix wireless join
modules/admin-full: support deleting wireless networks and fix wireless join git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@5442 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
stephank/luci,projectbismark/luci-bismark,ch3n2k/luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,saraedum/luci-packages-old,jschmidlapp/luci,jschmidlapp/luci,gwlim/luci,projectbismark/luci-bismark,8devices/carambola2-luci,jschmidlapp/luci,jschmidlapp/luci,freifunk-gluon/luci,phi-psi/luci,eugenesan/openwrt-luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,stephank/luci,ch3n2k/luci,stephank/luci,ch3n2k/luci,dtaht/cerowrt-luci-3.3,ThingMesh/openwrt-luci,8devices/carambola2-luci,dtaht/cerowrt-luci-3.3,zwhfly/openwrt-luci,saraedum/luci-packages-old,yeewang/openwrt-luci,yeewang/openwrt-luci,Canaan-Creative/luci,vhpham80/luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,gwlim/luci,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,gwlim/luci,eugenesan/openwrt-luci,yeewang/openwrt-luci,saraedum/luci-packages-old,zwhfly/openwrt-luci,Canaan-Creative/luci,Flexibity/luci,projectbismark/luci-bismark,gwlim/luci,phi-psi/luci,zwhfly/openwrt-luci,Canaan-Creative/luci,dtaht/cerowrt-luci-3.3,freifunk-gluon/luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,jschmidlapp/luci,vhpham80/luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,jschmidlapp/luci,freifunk-gluon/luci,8devices/carambola2-luci,projectbismark/luci-bismark,freifunk-gluon/luci,8devices/carambola2-luci,eugenesan/openwrt-luci,gwlim/luci,projectbismark/luci-bismark,stephank/luci,8devices/carambola2-luci,dtaht/cerowrt-luci-3.3,ThingMesh/openwrt-luci,Canaan-Creative/luci,yeewang/openwrt-luci,phi-psi/luci,vhpham80/luci,Canaan-Creative/luci,Flexibity/luci,eugenesan/openwrt-luci,vhpham80/luci,ThingMesh/openwrt-luci,phi-psi/luci,phi-psi/luci,vhpham80/luci,Flexibity/luci,freifunk-gluon/luci,ch3n2k/luci,eugenesan/openwrt-luci,Canaan-Creative/luci,eugenesan/openwrt-luci,yeewang/openwrt-luci,Flexibity/luci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,Flexibity/luci,saraedum/luci-packages-old,8devices/carambola2-luci,saraedum/luci-packages-old,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,gwlim/luci,dtaht/cerowrt-luci-3.3,zwhfly/openwrt-luci,phi-psi/luci,Flexibity/luci,ThingMesh/openwrt-luci,projectbismark/luci-bismark,eugenesan/openwrt-luci,yeewang/openwrt-luci,Flexibity/luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,dtaht/cerowrt-luci-3.3,jschmidlapp/luci,saraedum/luci-packages-old,zwhfly/openwrt-luci,phi-psi/luci,gwlim/luci,freifunk-gluon/luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,stephank/luci,vhpham80/luci,saraedum/luci-packages-old,ch3n2k/luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,stephank/luci,Canaan-Creative/luci
84e6c615c7a41aaf47cd7661b077908278bb9e2a
poll-invertor.lua
poll-invertor.lua
print("Ginlong Reader started\n") function string.fromhex(str) return (str:gsub('..', function (cc) return string.char(tonumber(cc, 16)) end)) end function string.tohex(str) if str ~= nil then return (str:gsub('.', function (c) return string.format('%02X', string.byte(c)) end)) end end inqhex = "7E01A1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000A2" local test = assert(io.open("t1.bin","w")) --test:write(string.fromhex(inqhex)) --test:close() serialport = assert(io.open("/dev/rfcomm0","w")) serialport:write(string.fromhex(inqhex)) serialport:close() local tries = 0 while tries < 5 do print("try " .. tries) serialport = assert(io.open("/dev/rfcomm0","r")) local result = serialport:read("*all") if (result ~= nil) and (string.len(result) > 0) then -- print("res:" .. result) --print the data test:write(result) test:close() return end print("fail") tries = tries+1 serialport:close() end
print("Ginlong Invertor Poller started\n") SERIAL_PORT = "/dev/rfcomm0" -- Bytes to send to request info from invertor inquiryHex = "7E01A1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000A2" -- all valid responses from invertor begin with this set of bytes responsePrefix = "7E01A11C" -------------------------------------------------- -- hex start indeces and lengths for certain data -------------------------------------------------- data_to_follow_index = 3 capacity_index = 20 capacity_length = 0 firmware_index = 32 firmware_length = 0 model_index = 46 model_length = 0 manuf_index = 74 manuf_length = 0 serial_index = 106 serial_length = 0 other_index = 138 other_length = 0 confserial_index = 18 ---------------- -- inverter data ---------------- data = {} data["vpv1"] = { multiply = 0.1, units = "V", index = 0, descr = "Panel 1 Voltage", flip = 1 } data["vpv2"] = { multiply = 0.1, units = "V", index = 24, descr = "Panel 2 Voltage", flip = 1 } data["ipv1"] = { multiply = 0.1, units = "A", index = 2, descr = "Panel 1 DC Current" } data["ipv2"] = { multiply = 0.1, units = "A", index = 26, descr = "Panel 2 DC Current" } data["emonth"] = { multiply = 1, units = "kWh", index = 29, descr = "Accumulated Energy This Month" } data["lmonth"] = { multiply = 1, units = "kWh", index = 31, descr = "Accumulated Energy Last Month" } data["iac"] = { multiply = 0.1, units = "A", index = 6, descr = "Grid Current" } data["vac"] = { multiply = 0.1, units = "V", index = 4, descr = "Grid Voltage" } data["fac"] = { multiply = 0.01, units = "Hz", index = 20, descr = "Grid Frequency" } function string.fromhex(str) if str ~= nil then return (str:gsub('..', function (cc) return string.char(tonumber(cc, 16)) end)) end end function string.tohex(str) if str ~= nil then return (str:gsub('.', function (c) if c == 0 then return "00" end return string.format('%02X', string.byte(c)) end)) end end function parseResponse(str) if str == nill then return end local prefixLen = string.len(responsePrefix) + 1 local hexData = str:tohex() if string.sub(hexData, 1, #responsePrefix) == responsePrefix then print("Data OK: " .. "[" .. #str .."]" .. hexData) else print("Data BAD: " .. "[" .. #str .."]" .. hexData) end -- local highbyte = string.sub(str,2,2) or "0" -- local lowbyte = string.sub(str,1,1) or "0" -- print((lowbyte..highbyte):tohex()) for i in pairs(data) do dataIndex = prefixLen + (data[i].index * 2) print(dataIndex .. ":" .. i) local lowbyte = string.sub(hexData, dataIndex, dataIndex+1) or "0" local highbyte = string.sub(hexData, dataIndex+2, dataIndex+3) or "0" local val = (highbyte .. lowbyte) -- if (data[i].flip == 1) then -- val = (lowbyte .. highbyte) -- end print(val .. "=" .. (tonumber(val, 16) * data[i].multiply) .. data[i].units) end end local test = assert(io.open("docs/examples/reading1.bin","r")) --parseResponse(test:read("*all")) --local test = assert(io.open("t1.bin","w")) serialport = assert(io.open(SERIAL_PORT,"w")) serialport:write(string.fromhex(inquiryHex)) serialport:close() local tries = 0 while tries < 5 do print("try " .. tries) serialport = assert(io.open(SERIAL_PORT,"r")) local result = serialport:read("*all") if (result ~= nil) and (string.len(result) > 0) then test:write(result) test:close() parseResponse(result) return end print("failed to read response") tries = tries+1 serialport:close() end
fixed lots of bugs, now gives correct values
fixed lots of bugs, now gives correct values as compared with perl script
Lua
bsd-2-clause
maks/ginlong-lua
d4e5746eb3fe78c38c619f8a2d3bf0522a14bf35
frontend/device/kindle/powerd.lua
frontend/device/kindle/powerd.lua
local BasePowerD = require("device/generic/powerd") -- liblipclua, see require below local KindlePowerD = BasePowerD:new{ fl_min = 0, fl_max = 24, fl_intensity = nil, battCapacity = nil, is_charging = nil, lipc_handle = nil, } function KindlePowerD:init() local haslipc, lipc = pcall(require, "liblipclua") if haslipc and lipc then self.lipc_handle = lipc.init("com.github.koreader.kindlepowerd") end if self.device.hasFrontlight() then if self.lipc_handle ~= nil then self.fl_intensity = self.lipc_handle:get_int_property("com.lab126.powerd", "flIntensity") else self.fl_intensity = self:read_int_file(self.fl_intensity_file) end end end function KindlePowerD:toggleFrontlight() local sysint = self:read_int_file(self.fl_intensity_file) if sysint == 0 then self:setIntensity(self.fl_intensity) else os.execute("echo -n 0 > " .. self.fl_intensity_file) end end function KindlePowerD:setIntensityHW() if self.lipc_handle ~= nil then self.lipc_handle:set_int_property("com.lab126.powerd", "flIntensity", self.fl_intensity) else os.execute("echo -n ".. self.fl_intensity .." > " .. self.fl_intensity_file) end end function KindlePowerD:getCapacityHW() if self.lipc_handle ~= nil then self.battCapacity = self.lipc_handle:get_int_property("com.lab126.powerd", "battLevel") else self.battCapacity = self:read_int_file(self.batt_capacity_file) end return self.battCapacity end function KindlePowerD:isChargingHW() if self.lipc_handle ~= nil then self.is_charging = self.lipc_handle:get_int_property("com.lab126.powerd", "isCharging") else self.is_charging = self:read_int_file(self.is_charging_file) end return self.is_charging == 1 end function KindlePowerD:__gc() if self.lipc_handle then self.lipc_handle:close() self.lipc_handle = nil end end return KindlePowerD
local BasePowerD = require("device/generic/powerd") -- liblipclua, see require below local KindlePowerD = BasePowerD:new{ fl_min = 0, fl_max = 24, fl_intensity = nil, battCapacity = nil, is_charging = nil, lipc_handle = nil, } function KindlePowerD:init() local haslipc, lipc = pcall(require, "liblipclua") if haslipc and lipc then self.lipc_handle = lipc.init("com.github.koreader.kindlepowerd") end if self.device.hasFrontlight() then if self.lipc_handle ~= nil then self.fl_intensity = self.lipc_handle:get_int_property("com.lab126.powerd", "flIntensity") else self.fl_intensity = self:read_int_file(self.fl_intensity_file) end end end function KindlePowerD:toggleFrontlight() local sysint = self:read_int_file(self.fl_intensity_file) if sysint == 0 then -- NOTE: We want to bypass setIntensity's shenanigans and simply restore the light as-is self:setIntensityHW() else -- NOTE: We want to really kill the light, so do it manually (asking lipc to set it to 0 would in fact set it to 1)... os.execute("echo -n 0 > " .. self.fl_intensity_file) end end function KindlePowerD:setIntensityHW() if self.lipc_handle ~= nil then self.lipc_handle:set_int_property("com.lab126.powerd", "flIntensity", self.fl_intensity) else os.execute("echo -n ".. self.fl_intensity .." > " .. self.fl_intensity_file) end end function KindlePowerD:getCapacityHW() if self.lipc_handle ~= nil then self.battCapacity = self.lipc_handle:get_int_property("com.lab126.powerd", "battLevel") else self.battCapacity = self:read_int_file(self.batt_capacity_file) end return self.battCapacity end function KindlePowerD:isChargingHW() if self.lipc_handle ~= nil then self.is_charging = self.lipc_handle:get_int_property("com.lab126.powerd", "isCharging") else self.is_charging = self:read_int_file(self.is_charging_file) end return self.is_charging == 1 end function KindlePowerD:__gc() if self.lipc_handle then self.lipc_handle:close() self.lipc_handle = nil end end return KindlePowerD
Unbreak toggling the fL on Kindles
Unbreak toggling the fL on Kindles Fix #1960
Lua
agpl-3.0
apletnev/koreader,Hzj-jie/koreader,lgeek/koreader,NiLuJe/koreader,robert00s/koreader,Frenzie/koreader,houqp/koreader,poire-z/koreader,chihyang/koreader,Frenzie/koreader,pazos/koreader,mwoz123/koreader,frankyifei/koreader,koreader/koreader,NickSavage/koreader,mihailim/koreader,poire-z/koreader,koreader/koreader,Markismus/koreader,NiLuJe/koreader
29e0fd3a952633d5fdbbeb1fb0c7cc92ce25b565
MMOCoreORB/bin/scripts/commands/fastBlast.lua
MMOCoreORB/bin/scripts/commands/fastBlast.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. --true = 1, false = 0 FastBlastCommand = { name = "fastblast", damageMultiplier = 4.15, speedMultiplier = 3.05, healthCostMultiplier = 1, actionCostMultiplier = 1, mindCostMultiplier = 1, poolsToDamage = RANDOM_ATTRIBUTE, animationCRC = hashCode("fire_5_special_single_light"), combatSpam = "fastblast", range = -1 } AddCommand(FastBlastCommand)
--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. --true = 1, false = 0 FastBlastCommand = { name = "fastblast", damageMultiplier = 4.15, speedMultiplier = 3.05, healthCostMultiplier = 1.5, actionCostMultiplier = 1.5, mindCostMultiplier = 1, accuracyBonus = 95, poolsToDamage = HEALTH_ATTRIBUTE + ACTION_ATTRIBUTE + MIND_ATTRIBUTE, animationCRC = hashCode("fire_5_special_single_light"), combatSpam = "fastblast", range = -1 } AddCommand(FastBlastCommand)
[fixed] Master BH attack-special 'Fast Blast', Mantis 3552
[fixed] Master BH attack-special 'Fast Blast', Mantis 3552 Change-Id: Icdbec67112ac8db34f7d7b74b255bea53bdbc2d0
Lua
agpl-3.0
Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo
b38e757140070fb5ba2eea4418bf094ead074248
scripts/window_unpin.lua
scripts/window_unpin.lua
-- Macro by Cegaiel -- This will right click all windows found (both searchImage1 or searchImage2), in an attempt to unpin and close all pinned windows. -- It right clicks (closes) every open window that currently shows on screen, in one pass.. If it finds any windows to click then: --Repeat and search for more windows and close all found in another pass again, repeat. -- The purpose of repeating is in case you had any windows were hidden behind other windows from the previous right clicks/close windows. -- Repeat above until no more windows are found. Then do Search Method 2 (another .png) for expired windows (ie. flax bed that turned to seed and window turned blank) -- Repeat same pattern for Method 2, until no more windows are found, then exit. dofile("common.inc"); right_click = true; -- Set this boolean to 'true' to do right clicks. If this was blank or false, then it would do left clicks. per_click_delay = 150; -- Time is in ms searchImage1 = "ThisIs.png" -- Method 1 searchImage2 = "Unpin.png" -- Method 2 searchImage3 = "Ok.png" -- Method 3 repeatMethod1 = 1; repeatMethod2 = 1; repeatMethod3 = 1; function doit() -- Pause, say something to user, wait for Shift key to continue. Give opportunity to put ATITD in focus, if needed. askForWindow("This will right click all windows, attempting to close any pinned windows. This will also close/click any PopUp windows with 'OK' buttons. This will find any windows or popups that are hidden behind other windows, too. Press Shift key continue."); statusScreen("Closing windows and popups..."); --Keep looking for and closing windows with Image1 until no more found, then move to Method 2. while repeatMethod1 == 1 do closeMethod1(); end lsSleep(200); --Keep looking for and closing windows with Image2 until no more found, then move to Method 3. while repeatMethod2 == 1 do closeMethod2(); end lsSleep(200); --Keep looking for and closing windows with Image3 until no more found, then done. while repeatMethod3 == 1 do closeMethod3(); end error 'Closed all windows and popups.'; end function closeMethod1() -- Search Method 1: -- Find pinned windows with searchImage1 srReadScreen(); -- Count how many windows that were found and assign the value to #buttons local buttons = findAllImages(searchImage1); if #buttons == 0 then repeatMethod1 = 0 else for i=#buttons, 1, -1 do srClickMouseNoMove(buttons[i][0]+5, buttons[i][1]+3, right_click); lsSleep(per_click_delay); end end checkBreak(); end function closeMethod2() -- Search Method 2: -- Find pinned windows with searchImage2 srReadScreen(); -- Count how many windows that were found and assign the value to #buttons local buttons = findAllImages(searchImage2); if #buttons == 0 then repeatMethod2 = 0 else for i=#buttons, 1, -1 do srClickMouseNoMove(buttons[i][0]+5, buttons[i][1]+3, right_click); lsSleep(per_click_delay); end end checkBreak(); end function closeMethod3() -- Search Method 3: -- Find OK buttons with searchImage3 srReadScreen(); -- Count how many windows that were found and assign the value to #buttons local buttons = findAllImages(searchImage3); if #buttons == 0 then repeatMethod3 = 0 else for i=#buttons, 1, -1 do srClickMouseNoMove(buttons[i][0]+5, buttons[i][1]+3, right_click); lsSleep(per_click_delay); end end checkBreak(); end
-- Macro by Cegaiel -- This will right click all windows found (both searchImage1 or searchImage2), in an attempt to unpin and close all pinned windows. -- It right clicks (closes) every open window that currently shows on screen, in one pass.. If it finds any windows to click then: --Repeat and search for more windows and close all found in another pass again, repeat. -- The purpose of repeating is in case you had any windows were hidden behind other windows from the previous right clicks/close windows. -- Repeat above until no more windows are found. Then do Search Method 2 (another .png) for expired windows (ie. flax bed that turned to seed and window turned blank) -- Repeat same pattern for Method 2, until no more windows are found, then exit. dofile("common.inc"); right_click = true; -- Set this boolean to 'true' to do right clicks. If this was blank or false, then it would do left clicks. per_click_delay = 150; -- Time is in ms searchImage1 = "ThisIs.png" -- Method 1 searchImage2 = "Unpin.png" -- Method 2 searchImage3 = "Ok.png" -- Method 3 repeatMethod1 = 1; repeatMethod2 = 1; repeatMethod3 = 1; function doit() -- Pause, say something to user, wait for Shift key to continue. Give opportunity to put ATITD in focus, if needed. askForWindow("This will right click all windows, attempting to close any pinned windows. This will also close/click any PopUp windows with 'OK' buttons. This will find any windows or popups that are hidden behind other windows, too. Press Shift key continue."); --Keep looking for and closing windows with Image1 until no more found, then move to Method 2. while repeatMethod1 == 1 do sleepWithStatus(100, "Closing windows and popups, Method 1"); closeMethod1(); end lsSleep(200); --Keep looking for and closing windows with Image2 until no more found, then move to Method 3. while repeatMethod2 == 1 do sleepWithStatus(100, "Closing windows and popups, Method 2"); closeMethod2(); end lsSleep(200); --Keep looking for and closing windows with Image3 until no more found, then done. while repeatMethod3 == 1 do sleepWithStatus(100, "Closing windows and popups, Method 3"); closeMethod3(); end lsPlaySound("Complete.wav"); error 'Closed all windows and popups.'; end function closeMethod1() -- Search Method 1: -- Find pinned windows with searchImage1 srReadScreen(); -- Count how many windows that were found and assign the value to #buttons local buttons = findAllImages(searchImage1); if #buttons == 0 then repeatMethod1 = 0 else for i=#buttons, 1, -1 do srClickMouseNoMove(buttons[i][0]+5, buttons[i][1]+3, right_click); lsSleep(per_click_delay); end end checkBreak(); end function closeMethod2() -- Search Method 2: -- Find pinned windows with searchImage2 srReadScreen(); -- Count how many windows that were found and assign the value to #buttons local buttons = findAllImages(searchImage2); if #buttons == 0 then repeatMethod2 = 0 else for i=#buttons, 1, -1 do srClickMouseNoMove(buttons[i][0]+5, buttons[i][1]+3, right_click); lsSleep(per_click_delay); end end checkBreak(); end function closeMethod3() -- Search Method 3: -- Find OK buttons with searchImage3 srReadScreen(); -- Count how many windows that were found and assign the value to #buttons local buttons = findAllImages(searchImage3); if #buttons == 0 then repeatMethod3 = 0 else for i=#buttons, 1, -1 do srClickMouseNoMove(buttons[i][0]+5, buttons[i][1]+3, right_click); lsSleep(per_click_delay); end end checkBreak(); end
window_unpin.lua - Fix overlapping End Script/Exit buttons (while running). Slight tweak in operation.
window_unpin.lua - Fix overlapping End Script/Exit buttons (while running). Slight tweak in operation.
Lua
mit
DashingStrike/Automato-ATITD,wzydhek/Automato-ATITD,wzydhek/Automato-ATITD,DashingStrike/Automato-ATITD
ce3464c9d0ed4270dcc205ab165c9a7da20ff83e
nvim/lua/plugins.lua
nvim/lua/plugins.lua
local cmd = vim.cmd -- to execute Vim commands e.g. cmd('pwd') local g = vim.g -- a table to access global variables cmd([[packadd packer.nvim]]) return require('packer').startup(function() -- plugin management use('wbthomason/packer.nvim') -- treesitter (LSP) use({ 'nvim-treesitter/nvim-treesitter', run = ':TSUpdate' }) use('nvim-treesitter/playground') -- LSP config use({ 'neovim/nvim-lspconfig', 'williamboman/nvim-lsp-installer', }) -- show signature while typing use('ray-x/lsp_signature.nvim') -- faster than built-in filetype.vim (might go to core at some point) use('nathom/filetype.nvim') -- buffer/tab line use({ 'akinsho/bufferline.nvim', requires = 'kyazdani42/nvim-web-devicons', config = function() require('bufferline').setup({ options = { offsets = { { filetype = 'NvimTree', text = '', padding = 1, text_align = 'right', }, }, }, }) end, }) -- completion and snippets use({ 'rafamadriz/friendly-snippets', event = 'InsertEnter', }) use({ 'hrsh7th/nvim-cmp', }) use({ 'L3MON4D3/LuaSnip', wants = 'friendly-snippets', }) use({ 'saadparwaiz1/cmp_luasnip', }) use({ 'hrsh7th/cmp-nvim-lua', }) use({ 'hrsh7th/cmp-nvim-lsp', }) use({ 'hrsh7th/cmp-buffer', }) use({ 'folke/trouble.nvim', requires = 'kyazdani42/nvim-web-devicons', config = function() require('trouble').setup({ -- your configuration comes here -- or leave it empty to use the default settings -- refer to the configuration section below }) end, }) -- footer support -- NOTE: using fork for now - original is hoob3rt/lualine.nvim use({ 'nvim-lualine/lualine.nvim', requires = { 'kyazdani42/nvim-web-devicons', opt = true }, }) -- highlight TODOs use({ 'folke/todo-comments.nvim', requires = 'nvim-lua/plenary.nvim', config = function() require('todo-comments').setup() end, }) -- pane showing symbols use('simrat39/symbols-outline.nvim') -- scrollbar in terminal use('dstein64/nvim-scrollview') -- toggle terminal use({ 'akinsho/toggleterm.nvim', config = function() require('toggleterm').setup({ -- size can be a number or function which is passed the current terminal size = 20, -- open_mapping = [[<c-\>]], open_mapping = [[<c-t>]], hide_numbers = true, -- hide the number column in toggleterm buffers start_in_insert = true, insert_mappings = true, -- whether or not the open mapping applies in insert mode persist_size = false, direction = 'horizontal', close_on_exit = true, -- close the terminal window when the process exits shell = 'fish', -- change the default shell -- This field is only relevant if direction is set to 'float' float_opts = { -- The border key is *almost* the same as 'nvim_open_win' -- see :h nvim_open_win for details on borders however -- the 'curved' border is a custom border type -- not natively supported but implemented in this plugin. border = 'curved', winblend = 3, highlights = { border = 'Normal', background = 'Normal', }, }, }) end, }) -- which key plugin use('folke/which-key.nvim') -- like nerd tree use({ 'kyazdani42/nvim-tree.lua', cmd = { 'NvimTreeToggle', 'NvimTreeFocus' }, requires = 'kyazdani42/nvim-web-devicons', config = function() require('nvim-tree').setup({ view = { side = 'right', }, }) end, }) -- close buffers without messing up window layout use('moll/vim-bbye') use('editorconfig/editorconfig-vim') -- ident lines use('lukas-reineke/indent-blankline.nvim') -- autopairs use({ 'windwp/nvim-autopairs', config = function() require('nvim-autopairs').setup() end, }) -- s plus motion to jump around (like vim-sneak) use('ggandor/lightspeed.nvim') -- colorizer use({ 'norcalli/nvim-colorizer.lua', config = function() require('colorizer').setup() end, }) -- find files, buffers, etc. use({ 'nvim-telescope/telescope.nvim', requires = { { 'nvim-lua/popup.nvim' }, { 'nvim-lua/plenary.nvim' } }, module_patterns = 'telescope*', }) -- use fzf-native matcher instead use({ 'nvim-telescope/telescope-fzf-native.nvim', run = 'make' }) -- commenting code use({ 'numToStr/Comment.nvim', config = function() require('Comment').setup() end, }) -- notifications use({ 'rcarriga/nvim-notify', config = function() vim.notify = require('notify') end, }) -- git support use({ 'TimUntersberger/neogit', requires = 'nvim-lua/plenary.nvim', config = function() require('neogit').setup({}) end, }) -- git signs use({ 'lewis6991/gitsigns.nvim', requires = { 'nvim-lua/plenary.nvim', }, config = function() require('gitsigns').setup() end, }) -- logging use('tjdevries/vlog.nvim') -- surround motion use('tpope/vim-surround') -- most recently used use('yegappan/mru') use({ 'jose-elias-alvarez/null-ls.nvim', config = function() local null_ls = require('null-ls') local sources = { null_ls.builtins.formatting.prettier, null_ls.builtins.formatting.rustfmt, null_ls.builtins.formatting.stylelint, null_ls.builtins.formatting.stylua, null_ls.builtins.diagnostics.cspell, null_ls.builtins.diagnostics.eslint, null_ls.builtins.diagnostics.luacheck, null_ls.builtins.diagnostics.proselint, } null_ls.config({ sources = sources, }) require('lspconfig')['null-ls'].setup({ on_attach = function(client) if client.resolved_capabilities.document_formatting then vim.cmd('autocmd BufWritePre <buffer> lua vim.lsp.buf.formatting_sync()') end end, }) end, requires = { 'nvim-lua/plenary.nvim', 'neovim/nvim-lspconfig' }, }) -- search for visually selected text use('bronson/vim-visual-star-search') -- rainbow parens use('p00f/nvim-ts-rainbow') -- colors use('fatih/molokai') use('altercation/vim-colors-solarized') use('NLKNguyen/papercolor-theme') use('navarasu/onedark.nvim') end)
local cmd = vim.cmd -- to execute Vim commands e.g. cmd('pwd') local g = vim.g -- a table to access global variables cmd([[packadd packer.nvim]]) return require('packer').startup(function() -- plugin management use('wbthomason/packer.nvim') -- treesitter (LSP) use({ 'nvim-treesitter/nvim-treesitter', run = ':TSUpdate' }) use('nvim-treesitter/playground') -- LSP config use({ 'neovim/nvim-lspconfig', 'williamboman/nvim-lsp-installer', }) -- show signature while typing use('ray-x/lsp_signature.nvim') -- faster than built-in filetype.vim (might go to core at some point) use('nathom/filetype.nvim') -- buffer/tab line use({ 'akinsho/bufferline.nvim', requires = 'kyazdani42/nvim-web-devicons', config = function() require('bufferline').setup({ options = { offsets = { { filetype = 'NvimTree', text = '', padding = 1, text_align = 'right', }, }, }, }) end, }) -- completion and snippets use({ 'rafamadriz/friendly-snippets', event = 'InsertEnter', }) use({ 'hrsh7th/nvim-cmp', }) use({ 'L3MON4D3/LuaSnip', wants = 'friendly-snippets', }) use({ 'saadparwaiz1/cmp_luasnip', }) use({ 'hrsh7th/cmp-nvim-lua', }) use({ 'hrsh7th/cmp-nvim-lsp', }) use({ 'hrsh7th/cmp-buffer', }) use({ 'folke/trouble.nvim', requires = 'kyazdani42/nvim-web-devicons', config = function() require('trouble').setup({ -- your configuration comes here -- or leave it empty to use the default settings -- refer to the configuration section below }) end, }) -- footer support -- NOTE: using fork for now - original is hoob3rt/lualine.nvim use({ 'nvim-lualine/lualine.nvim', requires = { 'kyazdani42/nvim-web-devicons', opt = true }, }) -- highlight TODOs use({ 'folke/todo-comments.nvim', requires = 'nvim-lua/plenary.nvim', config = function() require('todo-comments').setup() end, }) -- pane showing symbols use('simrat39/symbols-outline.nvim') -- scrollbar in terminal use('dstein64/nvim-scrollview') -- toggle terminal use({ 'akinsho/toggleterm.nvim', config = function() require('toggleterm').setup({ -- size can be a number or function which is passed the current terminal size = 20, -- open_mapping = [[<c-\>]], open_mapping = [[<c-t>]], hide_numbers = true, -- hide the number column in toggleterm buffers start_in_insert = true, insert_mappings = true, -- whether or not the open mapping applies in insert mode persist_size = false, direction = 'horizontal', close_on_exit = true, -- close the terminal window when the process exits shell = 'fish', -- change the default shell -- This field is only relevant if direction is set to 'float' float_opts = { -- The border key is *almost* the same as 'nvim_open_win' -- see :h nvim_open_win for details on borders however -- the 'curved' border is a custom border type -- not natively supported but implemented in this plugin. border = 'curved', winblend = 3, highlights = { border = 'Normal', background = 'Normal', }, }, }) end, }) -- which key plugin use('folke/which-key.nvim') -- like nerd tree use({ 'kyazdani42/nvim-tree.lua', cmd = { 'NvimTreeToggle', 'NvimTreeFocus' }, requires = 'kyazdani42/nvim-web-devicons', config = function() require('nvim-tree').setup({ view = { side = 'right', }, }) end, }) -- close buffers without messing up window layout use('moll/vim-bbye') use('editorconfig/editorconfig-vim') -- ident lines use('lukas-reineke/indent-blankline.nvim') -- autopairs use({ 'windwp/nvim-autopairs', config = function() require('nvim-autopairs').setup() end, }) -- s plus motion to jump around (like vim-sneak) use('ggandor/lightspeed.nvim') -- colorizer use({ 'norcalli/nvim-colorizer.lua', config = function() require('colorizer').setup() end, }) -- find files, buffers, etc. use({ 'nvim-telescope/telescope.nvim', requires = { { 'nvim-lua/popup.nvim' }, { 'nvim-lua/plenary.nvim' } }, module_patterns = 'telescope*', }) -- use fzf-native matcher instead use({ 'nvim-telescope/telescope-fzf-native.nvim', run = 'make' }) -- commenting code use({ 'numToStr/Comment.nvim', config = function() require('Comment').setup() end, }) -- notifications use({ 'rcarriga/nvim-notify', config = function() vim.notify = require('notify') end, }) -- git support use({ 'TimUntersberger/neogit', requires = 'nvim-lua/plenary.nvim', config = function() require('neogit').setup({}) end, }) -- git signs use({ 'lewis6991/gitsigns.nvim', requires = { 'nvim-lua/plenary.nvim', }, config = function() require('gitsigns').setup() end, }) -- logging use('tjdevries/vlog.nvim') -- surround motion use('tpope/vim-surround') -- most recently used use('yegappan/mru') use({ 'jose-elias-alvarez/null-ls.nvim', config = function() local null_ls = require('null-ls') null_ls.setup({ sources = { null_ls.builtins.formatting.prettier, null_ls.builtins.formatting.rustfmt, null_ls.builtins.formatting.stylelint, null_ls.builtins.formatting.stylua, null_ls.builtins.diagnostics.cspell, null_ls.builtins.diagnostics.eslint, null_ls.builtins.diagnostics.luacheck, null_ls.builtins.diagnostics.proselint, }, on_attach = function(client) if client.resolved_capabilities.document_formatting then vim.cmd('autocmd BufWritePre <buffer> lua vim.lsp.buf.formatting_sync()') end end, }) end, requires = { 'nvim-lua/plenary.nvim', 'neovim/nvim-lspconfig' }, }) -- search for visually selected text use('bronson/vim-visual-star-search') -- rainbow parens use('p00f/nvim-ts-rainbow') -- colors use('fatih/molokai') use('altercation/vim-colors-solarized') use('NLKNguyen/papercolor-theme') use('navarasu/onedark.nvim') end)
fix: update to latest null-ls config
fix: update to latest null-ls config
Lua
mit
drmohundro/dotfiles
e4eeb014c7ea623ae8128f6766d2ac4904b98751
limefa.lua
limefa.lua
-- limefa.lua: Converts regex trees to nondeterminstic finite automata (NFAs), -- and then thence to a deterministic finite automaton (DFA). -- -- Copyright © 2012 Zachary Catlin. See LICENSE for terms. -- The package table local P = {} if _REQUIREDNAME == nil then limefa = P else _G[_REQUIREDNAME] = P end -- Imports local table = table local string = string require('limeutil') local lu = limeutil setfenv(1, P) -- A state in a DFA or an NFA; state is translate-global state, and doneNum -- is either a number associated with termination-state preference or nil. local function makeState(state, doneNum) local x = {} x.id = state.nextId state.nextId = state.nextId + 1 x.transitions = {} x.doneNum = doneNum return x end -- Adds a transition on character class t (can be nil for NFAs) from state s -- (can't be nil!) to state r (can be nil for NFA fragments); returns the -- object representing the transition. local function makeTransition(s, t, r) local trans = {} trans.cond = t trans.dest = r table.insert(s.transitions, trans) return trans end local nfaFragMeta = { __index = { addFinal = function(frag, t) table.insert(frag.finalTrans, t) end } } -- Creates an NFA fragment, with a start state and a list of final -- transitions (used to connect and compose fragments); state is the -- translate-global state, and the fragment is returned. local function makeNFAfrag(state) local x = {} x.initState = makeState(state) x.finalTrans = {} return x end -- Turn a regex tree into an NFA fragment; returns the NFA fragment. state -- is the translate-global state; re is the tree. local function regexToNFAfrag(state, re) local frag = makeNFAfrag(state) if re == nil or re.type == 'zero' then frag:addFinal(makeTransition(frag.initState, nil, nil)) elseif re.type == 'char' then frag:addFinal(makeTransition(frag.initState, re.char, nil)) elseif re.type == 'class' then local t if not re.negated then t = makeTransition(frag.initState, re.set, nil) else local set = '' for i = 1,255 do local c = string.char(i) local a = string.find(re.set, c, 1, true) if a == nil then set = set .. c end end t = makeTransition(frag.initState, set, nil) end frag:addFinal(t) elseif re.type == 'any' then local set = '' for i = 1,255 do local c = string.char(i) if c ~= '\n' then set = set .. c end end frag:addFinal(makeTransition(frag.initState, set, nil)) elseif re.type == 'option' then for j = 1,table.maxn(re.enc) do local inner = regexToNFAfrag(state, re.enc[j]) makeTransition(frag.initState, nil, inner.initState) for k = 1,table.maxn(inner.finalTrans) do frag:addFinal(inner.finalTrans[k]) end end elseif re.type == 'concat' then frag = regexToNFAfrag(state, re.enc[1]) for j = 2,table.maxn(re.enc) do local next = regexToNFAfrag(state, re.enc[j]) for k = 1,table.maxn(frag.finalTrans) do frag.finalTrans[k].dest = next.initState end frag.finalTrans = next.finalTrans end elseif re.type == 'maybe' then local inner = regexToNFAfrag(state, re.enc) makeTransition(frag.initState, nil, inner.initState) frag:addFinal(makeTransition(frag.initState, nil, nil)) for j = 1,table.maxn(inner.finalTrans) do frag:addFinal(inner.finalTrans[j]) end elseif re.type == 'star' then local inner = regexToNFAfrag(state, re.enc) makeTransition(frag.initState, nil, inner.initState) frag:addFinal(makeTransition(frag.initState, nil, nil)) for j = 1,table.maxn(inner.finalTrans) do inner.finalTrans[j].dest = frag.initState end elseif re.type == 'plus' then local inner, x = regexToNFAfrag(state, re.enc), frag.initState frag.initState = inner.initState for j = 1,table.maxn(inner.finalTrans) do inner.finalTrans[j].dest = x end makeTransition(x, nil, frag.initState) frag:addFinal(makeTransition(x, nil, nil)) elseif re.type == 'num' then if re.min == nil and re.max == nil then frag = regexToNFAfrag(state, lu.re.star(re.enc)) else local r2 = lu.re.concat() local min, max = re.min, re.max if min == nil then min = 0 end for j = 1,min do r2:add(re.enc) end if max == nil then r2:add(lu.re.star(re.enc)) else local y = lu.re.maybe(re.enc) for j = min+1,max do r2:add(y) end end frag = regexToNFAfrag(state, r2) end else error('Unknown regex fragment type') end return frag end -- Returns an object that can be used by e.g. regexToNFAfrag as -- translate-global state local function makeState() return { nextId = 0 } end -- Top-level routine to turn a list of regex trees into an NFA; returns the -- initial state of the NFA. function regexCompile(reList) local globalState = makeState() local initState = makeState(globalState) for j = 1,table.maxn(reList) do local frag = regexToNFAfrag(globalState, reList[j]) local endState = makeState(globalState, j) for k = 1,table.maxn(frag.finalTrans) do frag.finalTrans[k].dest = endState end makeTransition(initState, nil, frag.initState) end return initState end return P
-- limefa.lua: Converts regex trees to nondeterminstic finite automata (NFAs), -- and then thence to a deterministic finite automaton (DFA). -- -- Copyright © 2012 Zachary Catlin. See LICENSE for terms. -- The package table local P = {} if _REQUIREDNAME == nil then limefa = P else _G[_REQUIREDNAME] = P end -- Imports local table = table local string = string local setmetatable = setmetatable require('limeutil') local lu = limeutil -- used in debug --local err = io.stderr setfenv(1, P) -- A state in a DFA or an NFA; state is translate-global state, and doneNum -- is either a number associated with termination-state preference or nil. local function makeState(state, doneNum) local x = {} x.id = state.nextId state.nextId = state.nextId + 1 x.transitions = {} x.doneNum = doneNum return x end -- Adds a transition on character class t (can be nil for NFAs) from state s -- (can't be nil!) to state r (can be nil for NFA fragments); returns the -- object representing the transition. local function makeTransition(s, t, r) local trans = {} trans.cond = t trans.dest = r table.insert(s.transitions, trans) return trans end local nfaFragMeta = { __index = { addFinal = function(frag, t) table.insert(frag.finalTrans, t) end } } -- Creates an NFA fragment, with a start state and a list of final -- transitions (used to connect and compose fragments); state is the -- translate-global state, and the fragment is returned. local function makeNFAfrag(state) local x = {} x.initState = makeState(state) x.finalTrans = {} setmetatable(x, nfaFragMeta) return x end -- Turn a regex tree into an NFA fragment; returns the NFA fragment. state -- is the translate-global state; re is the tree. local function regexToNFAfrag(state, re) local frag = makeNFAfrag(state) if re == nil or re.type == 'zero' then frag:addFinal(makeTransition(frag.initState, nil, nil)) elseif re.type == 'char' then frag:addFinal(makeTransition(frag.initState, re.char, nil)) elseif re.type == 'class' then local t if not re.negated then t = makeTransition(frag.initState, re.set, nil) else local set = '' for i = 1,255 do local c = string.char(i) local a = string.find(re.set, c, 1, true) if a == nil then set = set .. c end end t = makeTransition(frag.initState, set, nil) end frag:addFinal(t) elseif re.type == 'any' then local set = '' for i = 1,255 do local c = string.char(i) if c ~= '\n' then set = set .. c end end frag:addFinal(makeTransition(frag.initState, set, nil)) elseif re.type == 'option' then for j = 1,table.maxn(re.enc) do local inner = regexToNFAfrag(state, re.enc[j]) makeTransition(frag.initState, nil, inner.initState) for k = 1,table.maxn(inner.finalTrans) do frag:addFinal(inner.finalTrans[k]) end end elseif re.type == 'concat' then frag = regexToNFAfrag(state, re.enc[1]) for j = 2,table.maxn(re.enc) do local next = regexToNFAfrag(state, re.enc[j]) for k = 1,table.maxn(frag.finalTrans) do frag.finalTrans[k].dest = next.initState end frag.finalTrans = next.finalTrans end elseif re.type == 'maybe' then local inner = regexToNFAfrag(state, re.enc) makeTransition(frag.initState, nil, inner.initState) frag:addFinal(makeTransition(frag.initState, nil, nil)) for j = 1,table.maxn(inner.finalTrans) do frag:addFinal(inner.finalTrans[j]) end elseif re.type == 'star' then local inner = regexToNFAfrag(state, re.enc) makeTransition(frag.initState, nil, inner.initState) frag:addFinal(makeTransition(frag.initState, nil, nil)) for j = 1,table.maxn(inner.finalTrans) do inner.finalTrans[j].dest = frag.initState end elseif re.type == 'plus' then local inner, x = regexToNFAfrag(state, re.enc), frag.initState frag.initState = inner.initState for j = 1,table.maxn(inner.finalTrans) do inner.finalTrans[j].dest = x end makeTransition(x, nil, frag.initState) frag:addFinal(makeTransition(x, nil, nil)) elseif re.type == 'num' then if re.min == nil and re.max == nil then frag = regexToNFAfrag(state, lu.re.star(re.enc)) else local r2 = lu.re.concat() local min, max = re.min, re.max if min == nil then min = 0 end for j = 1,min do r2:add(re.enc) end if max == nil then r2:add(lu.re.star(re.enc)) else local y = lu.re.maybe(re.enc) for j = min+1,max do r2:add(y) end end frag = regexToNFAfrag(state, r2) end else error('Unknown regex fragment type') end return frag end -- Returns an object that can be used by e.g. regexToNFAfrag as -- translate-global state local function makeGlobalState() return { nextId = 0 } end -- Top-level routine to turn a list of regex trees into an NFA; returns the -- initial state of the NFA. function regexCompile(reList) local gState = makeGlobalState() local initState = makeState(gState) for j = 1,table.maxn(reList) do local frag = regexToNFAfrag(gState, reList[j]) local endState = makeState(gState, j) for k = 1,table.maxn(frag.finalTrans) do frag.finalTrans[k].dest = endState end makeTransition(initState, nil, frag.initState) end return initState end return P
Fixed some dumb bugs in limefa.lua
Fixed some dumb bugs in limefa.lua
Lua
mit
zec/moonlime,zec/moonlime
0137c8c8095d34ce240c503e5e2dd021a6a31aa3
lua/autorun/Wire_Load.lua
lua/autorun/Wire_Load.lua
-- $Rev: 1663 $ -- $LastChangedDate: 2009-09-12 03:34:53 -0700 (Sat, 12 Sep 2009) $ -- $LastChangedBy: TomyLobo $ if VERSION < 70 then Error("WireMod: Your GMod is years too old. Load aborted.\n") end if SERVER then -- this file AddCSLuaFile("autorun/Wire_Load.lua") -- shared includes AddCSLuaFile("wire/WireShared.lua") AddCSLuaFile("wire/UpdateCheck.lua") AddCSLuaFile("wire/Beam_NetVars.lua") AddCSLuaFile("wire/WireGates.lua") AddCSLuaFile("wire/WireMonitors.lua") AddCSLuaFile("wire/opcodes.lua") AddCSLuaFile("wire/GPULib.lua") -- client includes AddCSLuaFile("wire/client/cl_wirelib.lua") AddCSLuaFile("wire/client/cl_modelplug.lua") AddCSLuaFile("wire/client/WireDermaExts.lua") AddCSLuaFile("wire/client/WireMenus.lua") AddCSLuaFile("wire/client/TextEditor.lua") AddCSLuaFile("wire/client/toolscreen.lua") AddCSLuaFile("wire/client/wire_expression2_browser.lua") AddCSLuaFile("wire/client/wire_expression2_editor.lua") AddCSLuaFile("wire/client/e2helper.lua") AddCSLuaFile("wire/client/e2descriptions.lua") AddCSLuaFile("wire/client/gmod_tool_auto.lua") -- resource files for i=1,32 do resource.AddFile("settings/render_targets/WireGPU_RT_"..i..".txt") end resource.AddFile("materials/expression 2/cog.vtf") resource.AddFile("materials/expression 2/cog.vmt") resource.AddSingleFile("materials/expression 2/cog_world.vmt") end -- shared includes include("wire/WireShared.lua") include("wire/UpdateCheck.lua") include("wire/Beam_NetVars.lua") include("wire/WireGates.lua") include("wire/WireMonitors.lua") include("wire/opcodes.lua") include("wire/GPULib.lua") -- server includes if SERVER then include("wire/server/WireLib.lua") include("wire/server/ModelPlug.lua") include("wire/server/radiolib.lua") end -- client includes if CLIENT then include("wire/client/cl_wirelib.lua") include("wire/client/cl_modelplug.lua") include("wire/client/cl_gpulib.lua") include("wire/client/WireDermaExts.lua") include("wire/client/WireMenus.lua") include("wire/client/toolscreen.lua") include("wire/client/TextEditor.lua") include("wire/client/wire_expression2_browser.lua") include("wire/client/wire_expression2_editor.lua") include("wire/client/e2helper.lua") include("wire/client/e2descriptions.lua") include("wire/client/gmod_tool_auto.lua") end
-- $Rev: 1663 $ -- $LastChangedDate: 2009-09-12 03:34:53 -0700 (Sat, 12 Sep 2009) $ -- $LastChangedBy: TomyLobo $ if VERSION < 70 then Error("WireMod: Your GMod is years too old. Load aborted.\n") end if SERVER then -- this file AddCSLuaFile("autorun/Wire_Load.lua") -- shared includes AddCSLuaFile("wire/WireShared.lua") AddCSLuaFile("wire/UpdateCheck.lua") AddCSLuaFile("wire/Beam_NetVars.lua") AddCSLuaFile("wire/WireGates.lua") AddCSLuaFile("wire/WireMonitors.lua") AddCSLuaFile("wire/opcodes.lua") AddCSLuaFile("wire/GPULib.lua") -- client includes AddCSLuaFile("wire/client/cl_wirelib.lua") AddCSLuaFile("wire/client/cl_modelplug.lua") AddCSLuaFile("wire/client/WireDermaExts.lua") AddCSLuaFile("wire/client/WireMenus.lua") AddCSLuaFile("wire/client/TextEditor.lua") AddCSLuaFile("wire/client/toolscreen.lua") AddCSLuaFile("wire/client/wire_expression2_browser.lua") AddCSLuaFile("wire/client/wire_expression2_editor.lua") AddCSLuaFile("wire/client/e2helper.lua") AddCSLuaFile("wire/client/e2descriptions.lua") AddCSLuaFile("wire/client/gmod_tool_auto.lua") -- resource files for i=1,32 do resource.AddFile("settings/render_targets/WireGPU_RT_"..i..".txt") end resource.AddFile("materials/expression 2/cog.vtf") resource.AddFile("materials/expression 2/cog.vmt") resource.AddSingleFile("materials/expression 2/cog_world.vmt") end -- shared includes include("wire/WireShared.lua") include("wire/UpdateCheck.lua") include("wire/Beam_NetVars.lua") include("wire/WireGates.lua") include("wire/WireMonitors.lua") include("wire/opcodes.lua") include("wire/GPULib.lua") -- server includes if SERVER then include("wire/server/WireLib.lua") include("wire/server/ModelPlug.lua") include("wire/server/radiolib.lua") end -- client includes if CLIENT then include("wire/client/cl_wirelib.lua") include("wire/client/cl_modelplug.lua") include("wire/client/WireDermaExts.lua") include("wire/client/WireMenus.lua") include("wire/client/toolscreen.lua") include("wire/client/TextEditor.lua") include("wire/client/wire_expression2_browser.lua") include("wire/client/wire_expression2_editor.lua") include("wire/client/e2helper.lua") include("wire/client/e2descriptions.lua") include("wire/client/gmod_tool_auto.lua") end
Wire_Load.lua: Fixed a leftover include for cl_gpulib.lua.
Wire_Load.lua: Fixed a leftover include for cl_gpulib.lua.
Lua
apache-2.0
mitterdoo/wire,wiremod/wire,rafradek/wire,CaptainPRICE/wire,thegrb93/wire,notcake/wire,NezzKryptic/Wire,mms92/wire,sammyt291/wire,immibis/wiremod,garrysmodlua/wire,bigdogmat/wire,Grocel/wire,Python1320/wire,plinkopenguin/wiremod,dvdvideo1234/wire
d3ffe194727397be8ab7b056e76799d9686c3c89
lunamark/reader/html.lua
lunamark/reader/html.lua
-- (c) 2009-2011 John MacFarlane. Released under MIT license. -- See the file LICENSE in the source for details. local htmlparser = require("lunamark.htmlparser") local entities = require("lunamark.entities") local M = {} local function convert_entities(s) return s:gsub("&#[Xx](%x+);", entities.hex_entity):gsub("&#(%d+);", entities.dec_entity):gsub("&(%a+);", entities.char_entity) end local function lookup_attr(node, name) if node.attrs then for _,x in ipairs(node.attrs) do if x.name == name then return convert_entities(x.value or "") end end end end -- tags that aren't interpreted, but do need to be treated as block tags local leavespace = { address = true, center = true, dir = true, div = true, dl = true, form = true, menu = true, noframes = true, frameset = true, table = true } local function handle_nodes(writer, nodes, preserve_space) local output = {} local firstblock = true local function preblockspace() if firstblock then firstblock = false else table.insert(output, writer.interblocksep) end end local i = 1 while nodes[i] do local node = nodes[i] if type(node) == "string" then -- text node local contents if preserve_space then contents = writer.string(convert_entities(node)) else local s = convert_entities(node) contents = s:gsub("%s+", writer.space):gsub("%S+", writer.string) end table.insert(output, contents) elseif node.tag and node.child then -- tag with contents local tag = node.tag local function getcontents() return handle_nodes(writer, node.child, preserve_space or tag == "pre" or tag == "code") end if tag == "p" then preblockspace() table.insert(output, writer.paragraph(getcontents())) elseif tag == "blockquote" then preblockspace() table.insert(output, writer.blockquote(getcontents())) elseif tag == "li" then table.insert(output, getcontents()) elseif tag == "ul" then preblockspace() local items = {} for _,x in ipairs(node.child) do if x.tag == "li" then table.insert(items, handle_nodes(writer, x.child, false)) end end table.insert(output, writer.bulletlist(items)) elseif tag == "ol" then preblockspace() local items = {} for _,x in ipairs(node.child) do if x.tag == "li" then table.insert(items, handle_nodes(writer, x.child, false)) end end table.insert(output, writer.orderedlist(items)) elseif tag == "dl" then preblockspace() local items = {} local pending = {} for _,x in ipairs(node.child) do if x.tag == "dt" then if pending.definitions then items[#items + 1] = pending pending = {} end local newterm = handle_nodes(writer, x.child, false) if pending.term then pending.term = pending.term .. ", " .. newterm else pending.term = newterm end elseif x.tag == "dd" then local newdef = handle_nodes(writer, x.child, false) if pending.definitions then table.insert(pending.definitions, newdef) else pending.definitions = { newdef } end end end items[#items + 1] = pending table.insert(output, writer.definitionlist(items)) elseif tag == "pre" then preblockspace() table.insert(output, writer.verbatim(getcontents())) elseif tag:match("^h[123456]$") then local lev = tonumber(tag:sub(2,2)) preblockspace() local bodynodes = {} while nodes[i+1] do local nd = nodes[i+1] if nd.tag and nd.tag:match("^h[123456]$") and tonumber(nd.tag:sub(2,2)) <= lev then break else table.insert(bodynodes,nd) end i = i + 1 end local body = handle_nodes(writer, bodynodes, preserve_space) table.insert(output, writer.section(getcontents(), lev, body)) elseif tag == "a" then local src = lookup_attr(node, "href") or "" local tit = lookup_attr(node, "title") table.insert(output, writer.link(getcontents(),src,tit)) elseif tag == "em" or tag == "i" then table.insert(output, writer.emphasis(getcontents())) elseif tag == "strong" or tag == "b" then table.insert(output, writer.strong(getcontents())) elseif tag == "code" then table.insert(output, writer.code(getcontents())) elseif tag == "script" or tag == "style" then -- skip getcontents() elseif tag == "title" then writer.set_metadata("title", writer.string(getcontents())) else --skip unknown tag if leavespace[tag] then preblockspace() end table.insert(output, getcontents()) end elseif node.tag then -- self-closing tag local tag = node.tag if tag == "hr" then preblockspace() table.insert(output, writer.hrule) elseif tag == "br" then table.insert(output, writer.linebreak) elseif tag == "img" then local alt = lookup_attr(node, "alt") or "" local src = lookup_attr(node, "src") or "" local tit = lookup_attr(node, "title") table.insert(output, writer.image(alt,src,tit)) else -- skip end else -- comment or xmlheader -- skip end i = i + 1 end return table.concat(output) end --- Create a new html parser. function M.new(writer, options) return function(inp) local parser = htmlparser.new(inp) local parsed = parser:parse() return handle_nodes(writer, parsed), writer.get_metadata() end end return M
-- (c) 2009-2011 John MacFarlane. Released under MIT license. -- See the file LICENSE in the source for details. local htmlparser = require("lunamark.htmlparser") local entities = require("lunamark.entities") local M = {} local function convert_entities(s) return s:gsub("&#[Xx](%x+);", entities.hex_entity):gsub("&#(%d+);", entities.dec_entity):gsub("&(%a+);", entities.char_entity) end local function lookup_attr(node, name) if node.attrs then for _,x in ipairs(node.attrs) do if x.name == name then return convert_entities(x.value or "") end end end end -- tags that aren't interpreted, but do need to be treated as block tags local leavespace = { address = true, center = true, dir = true, div = true, dl = true, form = true, menu = true, noframes = true, frameset = true, table = true } local function handle_nodes(writer, nodes, preserve_space) local output = {} local firstblock = true local function getcontents(node) return handle_nodes(writer, node.child, preserve_space or node.tag == "pre" or node.tag == "code") end local function preblockspace() if firstblock then firstblock = false else table.insert(output, writer.interblocksep) end end local i = 1 while nodes[i] do local node = nodes[i] if type(node) == "string" then -- text node local contents if preserve_space then contents = writer.string(convert_entities(node)) else local s = convert_entities(node) contents = s:gsub("%s+", writer.space):gsub("%S+", writer.string) end table.insert(output, contents) elseif node.tag and node.child then -- tag with contents local tag = node.tag if tag == "p" then preblockspace() table.insert(output, writer.paragraph(getcontents(node))) elseif tag == "blockquote" then preblockspace() table.insert(output, writer.blockquote(getcontents(node))) elseif tag == "li" then table.insert(output, getcontents(node)) elseif tag == "ul" then preblockspace() local items = {} for _,x in ipairs(node.child) do if x.tag == "li" then table.insert(items, handle_nodes(writer, x.child, false)) end end table.insert(output, writer.bulletlist(items)) elseif tag == "ol" then preblockspace() local items = {} for _,x in ipairs(node.child) do if x.tag == "li" then table.insert(items, handle_nodes(writer, x.child, false)) end end table.insert(output, writer.orderedlist(items)) elseif tag == "dl" then preblockspace() local items = {} local pending = {} for _,x in ipairs(node.child) do if x.tag == "dt" then if pending.definitions then items[#items + 1] = pending pending = {} end local newterm = handle_nodes(writer, x.child, false) if pending.term then pending.term = pending.term .. ", " .. newterm else pending.term = newterm end elseif x.tag == "dd" then local newdef = handle_nodes(writer, x.child, false) if pending.definitions then table.insert(pending.definitions, newdef) else pending.definitions = { newdef } end end end items[#items + 1] = pending table.insert(output, writer.definitionlist(items)) elseif tag == "pre" then preblockspace() table.insert(output, writer.verbatim(getcontents(node))) elseif tag:match("^h[123456]$") then local lev = tonumber(tag:sub(2,2)) preblockspace() local bodynodes = {} while nodes[i+1] do local nd = nodes[i+1] if nd.tag and nd.tag:match("^h[123456]$") and tonumber(nd.tag:sub(2,2)) <= lev then break else table.insert(bodynodes,nd) end i = i + 1 end local body = handle_nodes(writer, bodynodes, preserve_space) table.insert(output, writer.section(getcontents(node), lev, body)) elseif tag == "a" then local src = lookup_attr(node, "href") or "" local tit = lookup_attr(node, "title") table.insert(output, writer.link(getcontents(node),src,tit)) elseif tag == "em" or tag == "i" then table.insert(output, writer.emphasis(getcontents(node))) elseif tag == "strong" or tag == "b" then table.insert(output, writer.strong(getcontents(node))) elseif tag == "code" then if preserve_space then -- we're inside a pre tag table.insert(output, getcontents(node)) else table.insert(output, writer.code(getcontents(node))) end elseif tag == "script" or tag == "style" then -- skip getcontents(node) elseif tag == "title" then writer.set_metadata("title", writer.string(getcontents(node))) else --skip unknown tag if leavespace[tag] then preblockspace() end table.insert(output, getcontents(node)) end elseif node.tag then -- self-closing tag local tag = node.tag if tag == "hr" then preblockspace() table.insert(output, writer.hrule) elseif tag == "br" then table.insert(output, writer.linebreak) elseif tag == "img" then local alt = lookup_attr(node, "alt") or "" local src = lookup_attr(node, "src") or "" local tit = lookup_attr(node, "title") table.insert(output, writer.image(alt,src,tit)) else -- skip end else -- comment or xmlheader -- skip end i = i + 1 end return table.concat(output) end --- Create a new html parser. function M.new(writer, options) return function(inp) local parser = htmlparser.new(inp) local parsed = parser:parse() return handle_nodes(writer, parsed), writer.get_metadata() end end return M
Improvements to html reader.
Improvements to html reader. * Fixed code inside pre. * Moved function defn out of loop.
Lua
mit
simoncozens/lunamark,jgm/lunamark,tst2005/lunamark,jgm/lunamark,tst2005/lunamark,simoncozens/lunamark,jgm/lunamark,tst2005/lunamark,simoncozens/lunamark
41881127aa047dfc61ce27ff2f20c148854e854c
hammerspoon/.hammerspoon/window-management/layouts.lua
hammerspoon/.hammerspoon/window-management/layouts.lua
local export = {} grid = require("window-management/grid") helpers = require("window-management/helpers") local areas = grid.areas local hsGrid = grid.hsGrid -- FILTERS ------------------------------------------------------------------------------- local wf = hs.window.filter -- Single Apps w_chrome = wf.new{'Google Chrome'} w_firefox = wf.new{'Firefox Developer Edition'} w_obs = wf.new{'OBS'} w_figma = wf.new{'Figma'} -- Groups of Apps w_browsers = wf.new{['Firefox Developer Edition'] = true, ['Google Chrome'] = { rejectTitles = 'Picture in Picture' } } w_editors = wf.new{'Code'} w_terminals = wf.new{'iTerm2', 'A lacritty'} w_videos = wf.new{['YouTube'] = true, ['Twitch'] = true, ['Google Meet'] = true, ['zoom.us'] = true, ['Google Chrome'] = {allowTitles = 'Picture in Picture'}, ['Slack'] = {allowTitles = '(.*)screen share$'}}:setCurrentSpace(true) w_notes = wf.new{'Notion', 'Obsidian'}:setCurrentSpace(true) w_todos = wf.new{'Asana', 'Todoist'}:setCurrentSpace(true) w_chats = wf.new{'Slack', 'Ferdi', 'Discord', 'Messages'}:setCurrentSpace(true) -- LAYOUTS ------------------------------------------------------------------------------- --[[ workBrowse: MAIN: Browser, SECONDARY: everything else ]] function export.workBrowse(tight) tight = tight or false local split = tight and areas.smallSplit or areas.mediumSplit --RIGHT grid.setFilteredWindowsToCell(w_browsers, split.main) grid.setFilteredWindowsToCell(w_figma, split.main) grid.setFilteredWindowsToCell(w_todos, split.main) if #w_videos:getWindows() > 0 then -- LEFT grid.setFilteredWindowsToCell(w_videos, split.secondaryTop) grid.setFilteredWindowsToCell(w_editors, split.secondaryBottom) grid.setFilteredWindowsToCell(w_terminals, split.secondaryBottom) grid.setFilteredWindowsToCell(w_notes, split.secondaryBottom) grid.setFilteredWindowsToCell(w_chats, split.secondaryBottom) else -- LEFT grid.setFilteredWindowsToCell(w_terminals, split.secondaryFull) grid.setFilteredWindowsToCell(w_editors, split.secondaryFull) grid.setFilteredWindowsToCell(w_notes, split.secondaryFull) grid.setFilteredWindowsToCell(w_chats, split.secondaryFull) end end --[[ workCode: MAIN: Code, SECONDARY: everything else ]] function export.workCode(tight) tight = tight or false local split = tight and areas.smallSplit or areas.mediumSplit -- RIGHT grid.setFilteredWindowsToCell(w_editors, split.main) grid.setFilteredWindowsToCell(w_figma, split.main) grid.setFilteredWindowsToCell(w_todos, split.main) if #w_videos:getWindows() > 0 then -- LEFT grid.setFilteredWindowsToCell(w_browsers, split.secondaryBottom) grid.setFilteredWindowsToCell(w_terminals, split.secondaryBottom) grid.setFilteredWindowsToCell(w_notes, split.secondaryBottom) grid.setFilteredWindowsToCell(w_chats, split.secondaryBottom) grid.setFilteredWindowsToCell(w_videos, split.secondaryTop) else -- LEFT grid.setFilteredWindowsToCell(w_browsers, split.secondaryFull) grid.setFilteredWindowsToCell(w_terminals, split.secondaryFull) grid.setFilteredWindowsToCell(w_notes, split.secondaryFull) grid.setFilteredWindowsToCell(w_chats, split.secondaryFull) end end --[[ workTriple: LEFT: Terminal + Code + Chat MAIN: Video + Notes RIGHT: Browser ]] function export.workTriple() if #w_videos:getWindows() > 0 then grid.setFilteredWindowsToCell(w_terminals, areas.tripleSplit.leftFull) grid.setFilteredWindowsToCell(w_chats, areas.tripleSplit.leftFull) grid.setFilteredWindowsToCell(w_editors, areas.tripleSplit.leftFull) grid.setFilteredWindowsToCell(w_videos, areas.tripleSplit.mainTop) grid.setFilteredWindowsToCell(w_notes, areas.tripleSplit.mainBottom) grid.setFilteredWindowsToCell(w_todos, areas.tripleSplit.mainBottom) grid.setFilteredWindowsToCell(w_figma, areas.tripleSplit.rightFull) grid.setFilteredWindowsToCell(w_browsers, areas.tripleSplit.rightFull) else grid.setFilteredWindowsToCell(w_terminals, areas.tripleSplit.leftFull) grid.setFilteredWindowsToCell(w_chats, areas.tripleSplit.leftFull) grid.setFilteredWindowsToCell(w_editors, areas.tripleSplit.leftFull) grid.setFilteredWindowsToCell(w_browsers, areas.tripleSplit.mainFull) grid.setFilteredWindowsToCell(w_notes, areas.tripleSplit.rightFull) grid.setFilteredWindowsToCell(w_todos, areas.tripleSplit.rightFull) grid.setFilteredWindowsToCell(w_figma, areas.tripleSplit.rightFull) end end --[[ workEven: When Video, place it on the left and everything else on the right When no video, browser, notes and chats on the left, everything else on the right ]] function export.workEven() if #w_videos:getWindows() > 0 then -- LEFT grid.setFilteredWindowsToCell(w_videos, areas.evenSplit.leftFull) --RIGHT grid.setFilteredWindowsToCell(w_terminals, areas.evenSplit.rightFull) grid.setFilteredWindowsToCell(w_notes, areas.evenSplit.rightFull) grid.setFilteredWindowsToCell(w_todos, areas.evenSplit.rightFull) grid.setFilteredWindowsToCell(w_figma, areas.evenSplit.rightFull) grid.setFilteredWindowsToCell(w_chats, areas.evenSplit.rightFull) grid.setFilteredWindowsToCell(w_browsers, areas.evenSplit.rightFull) grid.setFilteredWindowsToCell(w_editors, areas.evenSplit.rightFull) else -- LEFT grid.setFilteredWindowsToCell(w_browsers, areas.evenSplit.leftFull) grid.setFilteredWindowsToCell(w_todos, areas.evenSplit.leftFull) grid.setFilteredWindowsToCell(w_chats, areas.evenSplit.leftFull) -- RIGHT grid.setFilteredWindowsToCell(w_terminals, areas.evenSplit.rightFull) grid.setFilteredWindowsToCell(w_notes, areas.evenSplit.rightFull) grid.setFilteredWindowsToCell(w_figma, areas.evenSplit.rightFull) grid.setFilteredWindowsToCell(w_editors, areas.evenSplit.rightFull) end end --[[ workMax: MAIN: Browser/Code Maximized, SECONDARY: Terminal and Notes centered ]] function export.workMax() helpers.maximiseFilteredWindows(w_browsers) helpers.maximiseFilteredWindows(w_editors) helpers.maximiseFilteredWindows(w_figma) grid.setFilteredWindowsToCell(w_terminals, areas.custom.center) grid.setFilteredWindowsToCell(w_notes, areas.custom.center) grid.setFilteredWindowsToCell(w_todos, areas.custom.center) grid.setFilteredWindowsToCell(w_chats, areas.custom.center) grid.setFilteredWindowsToCell(w_videos, areas.custom.center) end return export
local export = {} grid = require("window-management/grid") helpers = require("window-management/helpers") local areas = grid.areas local hsGrid = grid.hsGrid -- FILTERS ------------------------------------------------------------------------------- local wf = hs.window.filter local mainScreenName = hs.screen.mainScreen():name() -- Single Apps w_chrome = wf.new{'Google Chrome'}:setCurrentSpace(true) w_firefox = wf.new{'Firefox Developer Edition'}:setCurrentSpace(true) w_obs = wf.new{'OBS'}:setCurrentSpace(true) w_figma = wf.new{'Figma'}:setCurrentSpace(true) -- Groups of Apps w_browsers = wf.new{['Firefox Developer Edition'] = true, ['Google Chrome'] = { rejectTitles = 'Picture in Picture' } }:setCurrentSpace(true) w_editors = wf.new{'Code'}:setCurrentSpace(true) w_terminals = wf.new{'iTerm2', 'Alacritty'}:setCurrentSpace(true) w_videos = wf.new{['YouTube'] = true, ['Twitch'] = true, ['Google Meet'] = true, ['zoom.us'] = true, ['Google Chrome'] = {allowTitles = 'Picture in Picture'}, ['Slack'] = {allowTitles = '(.*)Huddle$'}}:setCurrentSpace(true):setScreens(mainScreenName) w_notes = wf.new{'Notion', 'Obsidian'}:setCurrentSpace(true):setScreens(mainScreenName) w_todos = wf.new{'Asana', 'Todoist'}:setCurrentSpace(true):setScreens(mainScreenName) w_chats = wf.new{'Slack', 'Ferdi', 'Discord', 'Messages'}:setCurrentSpace(true):setScreens(mainScreenName) -- LAYOUTS ------------------------------------------------------------------------------- --[[ workBrowse: MAIN: Browser, SECONDARY: everything else ]] function export.workBrowse(tight) tight = tight or false local split = tight and areas.smallSplit or areas.mediumSplit --RIGHT grid.setFilteredWindowsToCell(w_browsers, split.main) grid.setFilteredWindowsToCell(w_figma, split.main) grid.setFilteredWindowsToCell(w_todos, split.main) if #w_videos:getWindows() > 0 then -- LEFT grid.setFilteredWindowsToCell(w_editors, split.secondaryBottom) grid.setFilteredWindowsToCell(w_terminals, split.secondaryBottom) grid.setFilteredWindowsToCell(w_notes, split.secondaryBottom) grid.setFilteredWindowsToCell(w_chats, split.secondaryBottom) grid.setFilteredWindowsToCell(w_videos, split.secondaryTop) else -- LEFT grid.setFilteredWindowsToCell(w_terminals, split.secondaryFull) grid.setFilteredWindowsToCell(w_editors, split.secondaryFull) grid.setFilteredWindowsToCell(w_notes, split.secondaryFull) grid.setFilteredWindowsToCell(w_chats, split.secondaryFull) end end --[[ workCode: MAIN: Code, SECONDARY: everything else ]] function export.workCode(tight) tight = tight or false local split = tight and areas.smallSplit or areas.mediumSplit -- RIGHT grid.setFilteredWindowsToCell(w_editors, split.main) grid.setFilteredWindowsToCell(w_figma, split.main) grid.setFilteredWindowsToCell(w_todos, split.main) if #w_videos:getWindows() > 0 then -- LEFT grid.setFilteredWindowsToCell(w_browsers, split.secondaryBottom) grid.setFilteredWindowsToCell(w_terminals, split.secondaryBottom) grid.setFilteredWindowsToCell(w_notes, split.secondaryBottom) grid.setFilteredWindowsToCell(w_chats, split.secondaryBottom) grid.setFilteredWindowsToCell(w_videos, split.secondaryTop) else -- LEFT grid.setFilteredWindowsToCell(w_browsers, split.secondaryFull) grid.setFilteredWindowsToCell(w_terminals, split.secondaryFull) grid.setFilteredWindowsToCell(w_notes, split.secondaryFull) grid.setFilteredWindowsToCell(w_chats, split.secondaryFull) end end --[[ workTriple: LEFT: Terminal + Code + Chat MAIN: Video + Notes RIGHT: Browser ]] function export.workTriple() if #w_videos:getWindows() > 0 then grid.setFilteredWindowsToCell(w_terminals, areas.tripleSplit.leftFull) grid.setFilteredWindowsToCell(w_chats, areas.tripleSplit.leftFull) grid.setFilteredWindowsToCell(w_editors, areas.tripleSplit.leftFull) grid.setFilteredWindowsToCell(w_notes, areas.tripleSplit.mainBottom) grid.setFilteredWindowsToCell(w_todos, areas.tripleSplit.mainBottom) grid.setFilteredWindowsToCell(w_figma, areas.tripleSplit.rightFull) grid.setFilteredWindowsToCell(w_browsers, areas.tripleSplit.rightFull) grid.setFilteredWindowsToCell(w_videos, areas.tripleSplit.mainTop) else grid.setFilteredWindowsToCell(w_terminals, areas.tripleSplit.leftFull) grid.setFilteredWindowsToCell(w_chats, areas.tripleSplit.leftFull) grid.setFilteredWindowsToCell(w_editors, areas.tripleSplit.leftFull) grid.setFilteredWindowsToCell(w_browsers, areas.tripleSplit.mainFull) grid.setFilteredWindowsToCell(w_notes, areas.tripleSplit.rightFull) grid.setFilteredWindowsToCell(w_todos, areas.tripleSplit.rightFull) grid.setFilteredWindowsToCell(w_figma, areas.tripleSplit.rightFull) end end --[[ workEven: When Video, place it on the left and everything else on the right When no video, browser, notes and chats on the left, everything else on the right ]] function export.workEven() if #w_videos:getWindows() > 0 then --RIGHT grid.setFilteredWindowsToCell(w_terminals, areas.evenSplit.rightFull) grid.setFilteredWindowsToCell(w_notes, areas.evenSplit.rightFull) grid.setFilteredWindowsToCell(w_todos, areas.evenSplit.rightFull) grid.setFilteredWindowsToCell(w_figma, areas.evenSplit.rightFull) grid.setFilteredWindowsToCell(w_chats, areas.evenSplit.rightFull) grid.setFilteredWindowsToCell(w_browsers, areas.evenSplit.rightFull) grid.setFilteredWindowsToCell(w_editors, areas.evenSplit.rightFull) -- LEFT grid.setFilteredWindowsToCell(w_videos, areas.evenSplit.leftFull) else -- LEFT grid.setFilteredWindowsToCell(w_browsers, areas.evenSplit.leftFull) grid.setFilteredWindowsToCell(w_todos, areas.evenSplit.leftFull) grid.setFilteredWindowsToCell(w_chats, areas.evenSplit.leftFull) -- RIGHT grid.setFilteredWindowsToCell(w_terminals, areas.evenSplit.rightFull) grid.setFilteredWindowsToCell(w_notes, areas.evenSplit.rightFull) grid.setFilteredWindowsToCell(w_figma, areas.evenSplit.rightFull) grid.setFilteredWindowsToCell(w_editors, areas.evenSplit.rightFull) end end --[[ workMax: MAIN: Browser/Code Maximized, SECONDARY: Terminal and Notes centered ]] function export.workMax() helpers.maximiseFilteredWindows(w_browsers) helpers.maximiseFilteredWindows(w_editors) helpers.maximiseFilteredWindows(w_figma) grid.setFilteredWindowsToCell(w_terminals, areas.custom.center) grid.setFilteredWindowsToCell(w_notes, areas.custom.center) grid.setFilteredWindowsToCell(w_todos, areas.custom.center) grid.setFilteredWindowsToCell(w_chats, areas.custom.center) grid.setFilteredWindowsToCell(w_videos, areas.custom.center) end return export
layouts: fix problem with video windows
layouts: fix problem with video windows
Lua
mit
francoiscote/dotfiles,francoiscote/dotfiles
4ff94cd95b47b7710704ea25a53302c3e35a0ec8
mod_smacks/mod_smacks.lua
mod_smacks/mod_smacks.lua
local st = require "util.stanza"; local t_insert, t_remove = table.insert, table.remove; local math_min = math.min; local tonumber, tostring = tonumber, tostring; local add_filter = require "util.filters".add_filter; local xmlns_sm = "urn:xmpp:sm:2"; local sm_attr = { xmlns = xmlns_sm }; local max_unacked_stanzas = 0; module:add_event_hook("stream-features", function (session, features) features:tag("sm", sm_attr):tag("optional"):up():up(); end); module:hook("s2s-stream-features", function (data) data.features:tag("sm", sm_attr):tag("optional"):up():up(); end); module:hook_stanza(xmlns_sm, "enable", function (session, stanza) module:log("debug", "Enabling stream management"); session.smacks = true; -- Overwrite process_stanza() and send() local queue = {}; session.outgoing_stanza_queue = queue; session.last_acknowledged_stanza = 0; local _send = session.send; function session.send(stanza) local attr = stanza.attr; if attr and not attr.xmlns then -- Stanza in default stream namespace queue[#queue+1] = st.reply(stanza); end local ok, err = _send(stanza); if ok and #queue > max_unacked_stanzas and not session.awaiting_ack then session.awaiting_ack = true; return _send(st.stanza("r", { xmlns = xmlns_sm })); end return ok, err; end session.handled_stanza_count = 0; add_filter(session, "stanzas/in", function (stanza) if not stanza.attr.xmlns then session.handled_stanza_count = session.handled_stanza_count + 1; session.log("debug", "Handled %d incoming stanzas", session.handled_stanza_count); end return stanza; end); if not stanza.attr.resume then -- FIXME: Resumption should be a different spec :/ _send(st.stanza("enabled", sm_attr)); return true; end end, 100); module:hook_stanza(xmlns_sm, "r", function (origin, stanza) if not origin.smacks then module:log("debug", "Received ack request from non-smack-enabled session"); return; end module:log("debug", "Received ack request, acking for %d", origin.handled_stanza_count); -- Reply with <a> origin.send(st.stanza("a", { xmlns = xmlns_sm, h = tostring(origin.handled_stanza_count) })); return true; end); module:hook_stanza(xmlns_sm, "a", function (origin, stanza) if not origin.smacks then return; end origin.awaiting_ack = nil; -- Remove handled stanzas from outgoing_stanza_queue local handled_stanza_count = tonumber(stanza.attr.h)-origin.last_acknowledged_stanza; local queue = origin.outgoing_stanza_queue; if handled_stanza_count > #queue then module:log("warn", "The client says it handled %d new stanzas, but we only sent %d :)", handled_stanza_count, #queue); for i=1,#queue do module:log("debug", "Q item %d: %s", i, tostring(queue[i])); end end for i=1,math_min(handled_stanza_count,#queue) do t_remove(origin.outgoing_stanza_queue, 1); end origin.last_acknowledged_stanza = origin.last_acknowledged_stanza + handled_stanza_count; return true; end); --TODO: Optimise... incoming stanzas should be handled by a per-session -- function that has a counter as an upvalue (no table indexing for increments, -- and won't slow non-198 sessions). We can also then remove the .handled flag -- on stanzas function handle_unacked_stanzas(session) local queue = session.outgoing_stanza_queue; local error_attr = { type = "cancel" }; if #queue > 0 then session.outgoing_stanza_queue = {}; for i=1,#queue do local reply = queue[i]; if reply.attr.to ~= session.full_jid then reply.attr.type = "error"; reply:tag("error", error_attr) :tag("recipient-unavailable", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"}); core_process_stanza(session, queue[i]); end end end end local _destroy_session = sessionmanager.destroy_session; function sessionmanager.destroy_session(session, err) if session.smacks then local queue = session.outgoing_stanza_queue; if #queue > 0 then module:log("warn", "Destroying session with %d unacked stanzas:", #queue); for i=1,#queue do module:log("warn", "::%s", tostring(queue[i])); end handle_unacked_stanzas(session); end end return _destroy_session(session, err); end
local st = require "util.stanza"; local t_insert, t_remove = table.insert, table.remove; local math_min = math.min; local tonumber, tostring = tonumber, tostring; local add_filter = require "util.filters".add_filter; local xmlns_sm = "urn:xmpp:sm:2"; local sm_attr = { xmlns = xmlns_sm }; local max_unacked_stanzas = 0; module:add_event_hook("stream-features", function (session, features) features:tag("sm", sm_attr):tag("optional"):up():up(); end); module:hook("s2s-stream-features", function (data) data.features:tag("sm", sm_attr):tag("optional"):up():up(); end); module:hook_stanza(xmlns_sm, "enable", function (session, stanza) module:log("debug", "Enabling stream management"); session.smacks = true; -- Overwrite process_stanza() and send() local queue = {}; session.outgoing_stanza_queue = queue; session.last_acknowledged_stanza = 0; local _send = session.sends2s or session.send; local function new_send(stanza) local attr = stanza.attr; if attr and not attr.xmlns then -- Stanza in default stream namespace queue[#queue+1] = st.reply(stanza); end local ok, err = _send(stanza); if ok and #queue > max_unacked_stanzas and not session.awaiting_ack then session.awaiting_ack = true; return _send(st.stanza("r", { xmlns = xmlns_sm })); end return ok, err; end if session.sends2s then session.sends2s = new_send; else session.send = new_send; end session.handled_stanza_count = 0; add_filter(session, "stanzas/in", function (stanza) if not stanza.attr.xmlns then session.handled_stanza_count = session.handled_stanza_count + 1; session.log("debug", "Handled %d incoming stanzas", session.handled_stanza_count); end return stanza; end); if not stanza.attr.resume then -- FIXME: Resumption should be a different spec :/ _send(st.stanza("enabled", sm_attr)); return true; end end, 100); module:hook_stanza(xmlns_sm, "r", function (origin, stanza) if not origin.smacks then module:log("debug", "Received ack request from non-smack-enabled session"); return; end module:log("debug", "Received ack request, acking for %d", origin.handled_stanza_count); -- Reply with <a> (origin.sends2s or origin.send)(st.stanza("a", { xmlns = xmlns_sm, h = tostring(origin.handled_stanza_count) })); return true; end); module:hook_stanza(xmlns_sm, "a", function (origin, stanza) if not origin.smacks then return; end origin.awaiting_ack = nil; -- Remove handled stanzas from outgoing_stanza_queue local handled_stanza_count = tonumber(stanza.attr.h)-origin.last_acknowledged_stanza; local queue = origin.outgoing_stanza_queue; if handled_stanza_count > #queue then module:log("warn", "The client says it handled %d new stanzas, but we only sent %d :)", handled_stanza_count, #queue); for i=1,#queue do module:log("debug", "Q item %d: %s", i, tostring(queue[i])); end end for i=1,math_min(handled_stanza_count,#queue) do t_remove(origin.outgoing_stanza_queue, 1); end origin.last_acknowledged_stanza = origin.last_acknowledged_stanza + handled_stanza_count; return true; end); --TODO: Optimise... incoming stanzas should be handled by a per-session -- function that has a counter as an upvalue (no table indexing for increments, -- and won't slow non-198 sessions). We can also then remove the .handled flag -- on stanzas function handle_unacked_stanzas(session) local queue = session.outgoing_stanza_queue; local error_attr = { type = "cancel" }; if #queue > 0 then session.outgoing_stanza_queue = {}; for i=1,#queue do local reply = queue[i]; if reply.attr.to ~= session.full_jid then reply.attr.type = "error"; reply:tag("error", error_attr) :tag("recipient-unavailable", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"}); core_process_stanza(session, queue[i]); end end end end local _destroy_session = sessionmanager.destroy_session; function sessionmanager.destroy_session(session, err) if session.smacks then local queue = session.outgoing_stanza_queue; if #queue > 0 then module:log("warn", "Destroying session with %d unacked stanzas:", #queue); for i=1,#queue do module:log("warn", "::%s", tostring(queue[i])); end handle_unacked_stanzas(session); end end return _destroy_session(session, err); end
mod_smacks: Fix to reply to stream for s2s sessions
mod_smacks: Fix to reply to stream for s2s sessions
Lua
mit
dhotson/prosody-modules,1st8/prosody-modules,olax/prosody-modules,LanceJenkinZA/prosody-modules,jkprg/prosody-modules,obelisk21/prosody-modules,softer/prosody-modules,1st8/prosody-modules,crunchuser/prosody-modules,cryptotoad/prosody-modules,heysion/prosody-modules,NSAKEY/prosody-modules,prosody-modules/import,Craige/prosody-modules,crunchuser/prosody-modules,mardraze/prosody-modules,asdofindia/prosody-modules,NSAKEY/prosody-modules,syntafin/prosody-modules,vince06fr/prosody-modules,vfedoroff/prosody-modules,apung/prosody-modules,either1/prosody-modules,apung/prosody-modules,jkprg/prosody-modules,amenophis1er/prosody-modules,asdofindia/prosody-modules,cryptotoad/prosody-modules,mmusial/prosody-modules,jkprg/prosody-modules,amenophis1er/prosody-modules,prosody-modules/import,BurmistrovJ/prosody-modules,heysion/prosody-modules,dhotson/prosody-modules,either1/prosody-modules,stephen322/prosody-modules,BurmistrovJ/prosody-modules,LanceJenkinZA/prosody-modules,softer/prosody-modules,asdofindia/prosody-modules,cryptotoad/prosody-modules,drdownload/prosody-modules,joewalker/prosody-modules,mardraze/prosody-modules,syntafin/prosody-modules,vfedoroff/prosody-modules,syntafin/prosody-modules,mardraze/prosody-modules,brahmi2/prosody-modules,either1/prosody-modules,mmusial/prosody-modules,obelisk21/prosody-modules,heysion/prosody-modules,heysion/prosody-modules,syntafin/prosody-modules,either1/prosody-modules,mardraze/prosody-modules,Craige/prosody-modules,guilhem/prosody-modules,amenophis1er/prosody-modules,crunchuser/prosody-modules,vfedoroff/prosody-modules,dhotson/prosody-modules,syntafin/prosody-modules,olax/prosody-modules,LanceJenkinZA/prosody-modules,prosody-modules/import,iamliqiang/prosody-modules,jkprg/prosody-modules,LanceJenkinZA/prosody-modules,1st8/prosody-modules,LanceJenkinZA/prosody-modules,NSAKEY/prosody-modules,guilhem/prosody-modules,Craige/prosody-modules,cryptotoad/prosody-modules,iamliqiang/prosody-modules,joewalker/prosody-modules,iamliqiang/prosody-modules,amenophis1er/prosody-modules,1st8/prosody-modules,guilhem/prosody-modules,olax/prosody-modules,apung/prosody-modules,heysion/prosody-modules,guilhem/prosody-modules,vince06fr/prosody-modules,drdownload/prosody-modules,stephen322/prosody-modules,vfedoroff/prosody-modules,1st8/prosody-modules,mmusial/prosody-modules,obelisk21/prosody-modules,softer/prosody-modules,joewalker/prosody-modules,apung/prosody-modules,joewalker/prosody-modules,asdofindia/prosody-modules,stephen322/prosody-modules,BurmistrovJ/prosody-modules,dhotson/prosody-modules,mmusial/prosody-modules,asdofindia/prosody-modules,either1/prosody-modules,iamliqiang/prosody-modules,drdownload/prosody-modules,crunchuser/prosody-modules,BurmistrovJ/prosody-modules,dhotson/prosody-modules,softer/prosody-modules,mmusial/prosody-modules,apung/prosody-modules,vfedoroff/prosody-modules,stephen322/prosody-modules,vince06fr/prosody-modules,stephen322/prosody-modules,brahmi2/prosody-modules,olax/prosody-modules,Craige/prosody-modules,brahmi2/prosody-modules,BurmistrovJ/prosody-modules,NSAKEY/prosody-modules,iamliqiang/prosody-modules,jkprg/prosody-modules,drdownload/prosody-modules,softer/prosody-modules,brahmi2/prosody-modules,joewalker/prosody-modules,drdownload/prosody-modules,crunchuser/prosody-modules,obelisk21/prosody-modules,Craige/prosody-modules,NSAKEY/prosody-modules,vince06fr/prosody-modules,guilhem/prosody-modules,cryptotoad/prosody-modules,amenophis1er/prosody-modules,prosody-modules/import,prosody-modules/import,vince06fr/prosody-modules,mardraze/prosody-modules,brahmi2/prosody-modules,olax/prosody-modules,obelisk21/prosody-modules
b130139d962d11d1cd97f0cd062a00856c835e37
titan-compiler/util.lua
titan-compiler/util.lua
local util = {} function util.get_file_contents(filename) local f, err = io.open(filename, "r") if not f then return false, err end local s = f:read("a") f:close() if not s then return false, "unable to open file " .. filename else return s end end function util.set_file_contents(filename, contents) local f, err = io.open(filename, "w") if not f then return false, err end f:write(contents) f:close() return true end local newline_cache = setmetatable({}, { __mode = "k" }) --- Given ordered sequence `xs`, search for `v`, -- If `v` is not found, return the position of -- the lowest item `x` in `xs` such that `x > v`. -- @param xs An ordered sequence of comparable items -- @param v A value comparable to the items in the list -- @param min (optional) The initial position (default 1) -- @param max (optional) The final position (default `#xs`) -- @return The position of `v`, or the position of -- the lowest item greater than it. Inserting `v` at -- the returned position will always keep the sequence -- ordered. local function binary_search(xs, v, min, max) min, max = min or 1, max or #xs if v < xs[min] then return min elseif v > xs[max] then return max + 1 end local i = (min + max) // 2 if v < xs[i] then return binary_search(xs, v, min, i - 1) elseif v > xs[i] then return binary_search(xs, v, i + 1, max) end return i end function util.get_line_number(subject, pos) local newlines if newline_cache[subject] then newlines = newline_cache[subject] else newlines = {} for n in subject:gmatch("()\n") do table.insert(newlines, n) end newline_cache[subject] = newlines end local line = binary_search(newlines, pos) return line, pos - (newlines[line - 1] or 0) end return util
local util = {} function util.get_file_contents(filename) local f, err = io.open(filename, "r") if not f then return false, err end local s = f:read("a") f:close() if not s then return false, "unable to open file " .. filename else return s end end function util.set_file_contents(filename, contents) local f, err = io.open(filename, "w") if not f then return false, err end f:write(contents) f:close() return true end -- @param xs An ordered sequence of comparable items -- @param v A value comparable to the items in the list -- @return The position of the first occurrence of `v` in the sequence or the -- position of the first item greater than `v` in the sequence, otherwise. -- Inserting `v` at the returned position will always keep the sequence ordered. local function binary_search(xs, v) -- Invariants: -- 1 <= lo <= hi <= #xs + 1 -- xs[i] < v , if i < lo -- xs[i] >= v, if i >= hi local lo = 1 local hi = #xs + 1 while lo < hi do -- Average, rounded down (lo <= mid < hi) -- Lua's logical right shift works here even if the addition overflows local mid = (lo + hi) >> 1 if xs[mid] < v then lo = mid + 1 else hi = mid end end return lo end local newline_cache = setmetatable({}, { __mode = "k" }) function util.get_line_number(subject, pos) local newlines if newline_cache[subject] then newlines = newline_cache[subject] else newlines = {} for n in subject:gmatch("()\n") do table.insert(newlines, n) end newline_cache[subject] = newlines end local line = binary_search(newlines, pos) local col = pos - (newlines[line - 1] or 0) return line, col end return util
Fix and cleanup get_line_number's binary search
Fix and cleanup get_line_number's binary search - Return 1 instead of crashing if `xs` is the empty list - Work around integer overflow when computing the averages - Clarify the comments - Document the loop invariants - Don't use tail recursion (in case we want to rewrite this in Titan)
Lua
mit
titan-lang/titan-v0,titan-lang/titan-v0,titan-lang/titan-v0
189be9fa99c373b434596e868d3eb835c06513f9
xmake/rules/wdk/mof/xmake.lua
xmake/rules/wdk/mof/xmake.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-2020, TBOOX Open Source Group. -- -- @author ruki -- @file xmake.lua -- -- define rule: *.mof rule("wdk.mof") -- add rule: wdk environment add_deps("wdk.env") -- set extensions set_extensions(".mof") -- before load before_load(function (target) -- imports import("core.project.config") import("lib.detect.find_program") -- get arch local arch = assert(config.arch(), "arch not found!") -- get wdk local wdk = target:data("wdk") -- get mofcomp local mofcomp = find_program("mofcomp", {check = function (program) local tmpmof = os.tmpfile() io.writefile(tmpmof, "") os.run("%s %s", program, tmpmof) os.tryrm(tmpmof) end}) assert(mofcomp, "mofcomp not found!") -- get wmimofck local wmimofck = nil if arch == "x64" then wmimofck = path.join(wdk.bindir, wdk.sdkver, "x64", "wmimofck.exe") else wmimofck = path.join(wdk.bindir, wdk.sdkver, "x86", "wmimofck.exe") end assert(wmimofck and os.isexec(wmimofck), "wmimofck not found!") -- save mofcomp and wmimofck target:data_set("wdk.mofcomp", mofcomp) target:data_set("wdk.wmimofck", wmimofck) end) -- before build file before_build_file(function (target, sourcefile, opt) -- imports import("core.base.option") import("core.theme.theme") import("core.project.depend") -- get mofcomp local mofcomp = target:data("wdk.mofcomp") -- get wmimofck local wmimofck = target:data("wdk.wmimofck") -- get output directory local outputdir = path.join(target:autogendir(), "rules", "wdk", "mof") -- add includedirs target:add("includedirs", outputdir) -- get header file local header = target:values("wdk.mof.header", sourcefile) local headerfile = path.join(outputdir, header and header or (path.basename(sourcefile) .. ".h")) -- get some temporary file local sourcefile_mof = path.join(outputdir, path.filename(sourcefile)) local targetfile_mfl = path.join(outputdir, "." .. path.basename(sourcefile) .. ".mfl") local targetfile_mof = path.join(outputdir, "." .. path.basename(sourcefile) .. ".mof") local targetfile_mfl_mof = path.join(outputdir, "." .. path.basename(sourcefile) .. ".mfl.mof") local targetfile_bmf = path.join(outputdir, path.basename(sourcefile) .. ".bmf") local outputdir_htm = path.join(outputdir, "htm") local targetfile_vbs = path.join(outputdir, path.basename(sourcefile) .. ".vbs") -- need build this object? local dependfile = target:dependfile(headerfile) local dependinfo = option.get("rebuild") and {} or (depend.load(dependfile) or {}) if not depend.is_changed(dependinfo, {lastmtime = os.mtime(headerfile), values = args}) then return end -- trace progress info cprintf("${color.build.progress}" .. theme.get("text.build.progress_format") .. ":${clear} ", opt.progress) if option.get("verbose") then cprint("${dim color.build.object}compiling.wdk.mof %s", sourcefile) else cprint("${color.build.object}compiling.wdk.mof %s", sourcefile) end -- ensure the output directory if not os.isdir(outputdir) then os.mkdir(outputdir) end -- copy *.mof to output directory os.cp(sourcefile, sourcefile_mof) -- do mofcomp os.vrunv(mofcomp, {"-Amendment:ms_409", "-MFL:" .. targetfile_mfl, "-MOF:" .. targetfile_mof, sourcefile_mof}) -- do wmimofck os.vrunv(wmimofck, {"-y" .. targetfile_mof, "-z" .. targetfile_mfl, targetfile_mfl_mof}) -- do mofcomp to generate *.bmf os.vrunv(mofcomp, {"-B:" .. targetfile_bmf, targetfile_mfl_mof}) -- do wmimofck to generate *.h os.vrunv(wmimofck, {"-h" .. headerfile, "-w" .. outputdir_htm, "-m", "-t" .. targetfile_vbs, targetfile_bmf}) -- update files and values to the dependent file dependinfo.files = {sourcefile} dependinfo.values = args depend.save(dependinfo, dependfile) end)
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-2020, TBOOX Open Source Group. -- -- @author ruki -- @file xmake.lua -- -- define rule: *.mof rule("wdk.mof") -- add rule: wdk environment add_deps("wdk.env") -- set extensions set_extensions(".mof") -- before load before_load(function (target) -- imports import("core.project.config") import("lib.detect.find_program") -- get arch local arch = assert(config.arch(), "arch not found!") -- get wdk local wdk = target:data("wdk") -- get mofcomp local mofcomp = find_program("mofcomp", {check = function (program) local tmpmof = os.tmpfile() io.writefile(tmpmof, "") os.run("%s %s", program, tmpmof) os.tryrm(tmpmof) end}) assert(mofcomp, "mofcomp not found!") -- get wmimofck local wmimofck = nil if arch == "x64" then wmimofck = path.join(wdk.bindir, wdk.sdkver, "x64", "wmimofck.exe") if not os.isexec(wmimofck) then wmimofck = path.join(wdk.bindir, wdk.sdkver, "x86", "x64", "wmimofck.exe") end else wmimofck = path.join(wdk.bindir, wdk.sdkver, "x86", "wmimofck.exe") end assert(wmimofck and os.isexec(wmimofck), "wmimofck not found!") -- save mofcomp and wmimofck target:data_set("wdk.mofcomp", mofcomp) target:data_set("wdk.wmimofck", wmimofck) end) -- before build file before_build_file(function (target, sourcefile, opt) -- imports import("core.base.option") import("core.theme.theme") import("core.project.depend") -- get mofcomp local mofcomp = target:data("wdk.mofcomp") -- get wmimofck local wmimofck = target:data("wdk.wmimofck") -- get output directory local outputdir = path.join(target:autogendir(), "rules", "wdk", "mof") -- add includedirs target:add("includedirs", outputdir) -- get header file local header = target:values("wdk.mof.header", sourcefile) local headerfile = path.join(outputdir, header and header or (path.basename(sourcefile) .. ".h")) -- get some temporary file local sourcefile_mof = path.join(outputdir, path.filename(sourcefile)) local targetfile_mfl = path.join(outputdir, "." .. path.basename(sourcefile) .. ".mfl") local targetfile_mof = path.join(outputdir, "." .. path.basename(sourcefile) .. ".mof") local targetfile_mfl_mof = path.join(outputdir, "." .. path.basename(sourcefile) .. ".mfl.mof") local targetfile_bmf = path.join(outputdir, path.basename(sourcefile) .. ".bmf") local outputdir_htm = path.join(outputdir, "htm") local targetfile_vbs = path.join(outputdir, path.basename(sourcefile) .. ".vbs") -- need build this object? local dependfile = target:dependfile(headerfile) local dependinfo = option.get("rebuild") and {} or (depend.load(dependfile) or {}) if not depend.is_changed(dependinfo, {lastmtime = os.mtime(headerfile), values = args}) then return end -- trace progress info cprintf("${color.build.progress}" .. theme.get("text.build.progress_format") .. ":${clear} ", opt.progress) if option.get("verbose") then cprint("${dim color.build.object}compiling.wdk.mof %s", sourcefile) else cprint("${color.build.object}compiling.wdk.mof %s", sourcefile) end -- ensure the output directory if not os.isdir(outputdir) then os.mkdir(outputdir) end -- copy *.mof to output directory os.cp(sourcefile, sourcefile_mof) -- do mofcomp os.vrunv(mofcomp, {"-Amendment:ms_409", "-MFL:" .. targetfile_mfl, "-MOF:" .. targetfile_mof, sourcefile_mof}) -- do wmimofck os.vrunv(wmimofck, {"-y" .. targetfile_mof, "-z" .. targetfile_mfl, targetfile_mfl_mof}) -- do mofcomp to generate *.bmf os.vrunv(mofcomp, {"-B:" .. targetfile_bmf, targetfile_mfl_mof}) -- do wmimofck to generate *.h os.vrunv(wmimofck, {"-h" .. headerfile, "-w" .. outputdir_htm, "-m", "-t" .. targetfile_vbs, targetfile_bmf}) -- update files and values to the dependent file dependinfo.files = {sourcefile} dependinfo.values = args depend.save(dependinfo, dependfile) end)
FIX WDK path
FIX WDK path FIX WDK path
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
dfe9935d96426aad181dc1b078f06bf9a1d0cf2e
config/sipi.init-knora-test.lua
config/sipi.init-knora-test.lua
-- -- Copyright © 2016 Lukas Rosenthaler, Andrea Bianco, Benjamin Geer, -- Ivan Subotic, Tobias Schweizer, André Kilchenmann, and André Fatton. -- This file is part of Sipi. -- Sipi is free software: you can redistribute it and/or modify -- it under the terms of the GNU Affero General Public License as published -- by the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- Sipi is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- Additional permission under GNU AGPL version 3 section 7: -- If you modify this Program, or any covered work, by linking or combining -- it with Kakadu (or a modified version of that library), containing parts -- covered by the terms of the Kakadu Software Licence, the licensors of this -- Program grant you additional permission to convey the resulting work. -- See the GNU Affero General Public License for more details. -- You should have received a copy of the GNU Affero General Public -- License along with Sipi. If not, see <http://www.gnu.org/licenses/>. ------------------------------------------------------------------------------- -- This function is being called from sipi before the file is served -- Knora is called to ask for the user's permissions on the file -- Parameters: -- prefix: This is the prefix that is given on the IIIF url -- identifier: the identifier for the image -- cookie: The cookie that may be present -- -- Returns: -- permission: -- 'allow' : the view is allowed with the given IIIF parameters -- 'restrict:watermark=<path-to-watermark>' : Add a watermark -- 'restrict:size=<iiif-size-string>' : reduce size/resolution -- 'deny' : no access! -- filepath: server-path where the master file is located ------------------------------------------------------------------------------- function pre_flight(prefix,identifier,cookie) -- -- For Knora Sipi integration testing -- Always the same test file is served -- filepath = config.imgroot .. '/' .. prefix .. '/' .. 'Leaves.jpg' print("serving test image " .. filepath) if prefix == "thumbs" then -- always allow thumbnails return 'allow', filepath end if prefix == "tmp" then -- always deny access to tmp folder return 'deny' end -- comment this in if you do not want to do a preflight request -- print("ignoring permissions") -- do return 'allow', filepath end knora_cookie_header = nil if cookie ~='' then -- tries to extract the Knora session id from the cookie: -- gets the digits between "sid=" and the closing ";" (only given in case of several key value pairs) -- returns nil if it cannot find it session_id = string.match(cookie, "sid=(%d+);?") if session_id == nil then -- no session_id could be extracted print("cookie key is invalid") else knora_cookie_header = { Cookie = "KnoraAuthentication=" .. session_id } end end knora_url = 'http://' .. config.knora_path .. ':' .. config.knora_port .. '/v1/files/' .. identifier print("knora_url: " .. knora_url) result = server.http("GET", knora_url, knora_cookie_header, 5000) -- check HTTP request was successful if not result.success then print("Request to Knora failed: " .. result.errmsg) -- deny request return 'deny' end if result.status_code ~= 200 then print("Knora returned HTTP status code " .. ret.status) print(result.body) return 'deny' end response_json = server.json_to_table(result.body) print("status: " .. response_json.status) print("permission code: " .. response_json.permissionCode) if response_json.status ~= 0 then -- something went wrong with the request, Knora returned a non zero status return 'deny' end if response_json.permissionCode == 0 then -- no view permission on file return 'deny' elseif response_json.permissionCode == 1 then -- restricted view permission on file -- either watermark or size (depends on project, should be returned with permission code by Sipi responder) return 'restrict:size=' .. config.thumb_size, filepath elseif response_json.permissionCode >= 2 then -- full view permissions on file return 'allow', filepath else -- invalid permission code return 'deny' end end -------------------------------------------------------------------------------
-- -- Copyright © 2016 Lukas Rosenthaler, Andrea Bianco, Benjamin Geer, -- Ivan Subotic, Tobias Schweizer, André Kilchenmann, and André Fatton. -- This file is part of Sipi. -- Sipi is free software: you can redistribute it and/or modify -- it under the terms of the GNU Affero General Public License as published -- by the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- Sipi is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- Additional permission under GNU AGPL version 3 section 7: -- If you modify this Program, or any covered work, by linking or combining -- it with Kakadu (or a modified version of that library), containing parts -- covered by the terms of the Kakadu Software Licence, the licensors of this -- Program grant you additional permission to convey the resulting work. -- See the GNU Affero General Public License for more details. -- You should have received a copy of the GNU Affero General Public -- License along with Sipi. If not, see <http://www.gnu.org/licenses/>. ------------------------------------------------------------------------------- -- This function is being called from sipi before the file is served -- Knora is called to ask for the user's permissions on the file -- Parameters: -- prefix: This is the prefix that is given on the IIIF url -- identifier: the identifier for the image -- cookie: The cookie that may be present -- -- Returns: -- permission: -- 'allow' : the view is allowed with the given IIIF parameters -- 'restrict:watermark=<path-to-watermark>' : Add a watermark -- 'restrict:size=<iiif-size-string>' : reduce size/resolution -- 'deny' : no access! -- filepath: server-path where the master file is located ------------------------------------------------------------------------------- function pre_flight(prefix,identifier,cookie) -- -- For Knora Sipi integration testing -- Always the same test file is served -- filepath = config.imgroot .. '/' .. prefix .. '/' .. 'Leaves.jpg' print("serving test image " .. filepath) if prefix == "thumbs" then -- always allow thumbnails return 'allow', filepath end if prefix == "tmp" then -- always deny access to tmp folder return 'deny' end -- comment this in if you do not want to do a preflight request -- print("ignoring permissions") -- do return 'allow', filepath end knora_cookie_header = nil if cookie ~='' then -- tries to extract the Knora session id from the cookie: -- gets the digits between "sid=" and the closing ";" (only given in case of several key value pairs) -- returns nil if it cannot find it session_id = string.match(cookie, "sid=(%d+);?") if session_id == nil then -- no session_id could be extracted print("cookie key is invalid") else knora_cookie_header = { Cookie = "KnoraAuthentication=" .. session_id } end end knora_url = 'http://' .. config.knora_path .. ':' .. config.knora_port .. '/v1/files/' .. identifier print("knora_url: " .. knora_url) result = server.http("GET", knora_url, knora_cookie_header, 5000) -- check HTTP request was successful if not result.success then print("Request to Knora failed: " .. result.errmsg) -- deny request return 'deny' end if result.status_code ~= 200 then print("Knora returned HTTP status code " .. ret.status) print(result.body) return 'deny' end response_json = server.json_to_table(result.body) print("status: " .. response_json.status) print("permission code: " .. response_json.permissionCode) if response_json.status ~= 0 then -- something went wrong with the request, Knora returned a non zero status return 'deny' end if response_json.permissionCode == 0 then -- no view permission on file return 'deny' elseif response_json.permissionCode == 1 then -- restricted view permission on file -- either watermark or size (depends on project, should be returned with permission code by Sipi responder) return 'restrict:size=' .. config.thumb_size, filepath elseif response_json.permissionCode >= 2 then -- full view permissions on file return 'allow', filepath else -- invalid permission code return 'deny' end end ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- String constants to be used in error messages ------------------------------------------------------------------------------- MIMETYPES_INCONSISTENCY = "Submitted mimetypes and/or file extension are inconsistent" FILE_NOT_READBLE = "Submitted file path could not be read: " PARAMETERS_INCORRECT = "Parameters not set correctly" ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- This function is called from the route when an error occurred. -- Parameters: -- 'status' (number): HTTP status code to returned to the client -- 'msg' (string): error message describing the problem that occurred -- -- Returns: -- an unsuccessful HTTP response containing a JSON string with the member 'message' ------------------------------------------------------------------------------- function send_error(status, msg) if type(status) == "number" and status ~= 200 and type(msg) == "string" then result = { message = msg } http_status = status else result = { message = "Unknown error. Please report this as a possible bug in a Sipi route." } http_status = 500 end server.sendHeader("Content-Type", "application/json") server.sendStatus(http_status) jsonstr = server.table_to_json(result) server.print(jsonstr) end ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- This function is called from the route when the request could -- be handled successfully. -- -- Parameters: -- 'result' (table): HTTP status code to returned to the client -- -- Returns: -- a JSON string that represents the table 'result' ------------------------------------------------------------------------------- function send_success(result) if type(result) == "table" then server.sendHeader("Content-Type", "application/json") jsonstr = server.table_to_json(result) server.print(jsonstr) else send_error() end end
fix (adapt sipi.init-knora-test.lua) add new error handling functions
fix (adapt sipi.init-knora-test.lua) add new error handling functions
Lua
agpl-3.0
dhlab-basel/Sipi,dhlab-basel/Sipi,dhlab-basel/Sipi,dhlab-basel/Sipi,dhlab-basel/Sipi,dhlab-basel/Sipi
f9be587a09040469bed2c5e85f5ba6beb6615571
Modules/Shared/Utility/ColorSequenceUtils.lua
Modules/Shared/Utility/ColorSequenceUtils.lua
--- -- @module ColorSequenceUtils local ColorSequenceUtils = {} local EPSILON = 1e-3 function ColorSequenceUtils.stripe(stripes, backgroundColor3, stripeColor3, percentStripeThickness, percentOffset) percentOffset = percentOffset or 0.5 percentStripeThickness = math.clamp(percentStripeThickness or 0.5, 0, 1) if percentStripeThickness == 0 then return ColorSequence.new(backgroundColor3) elseif percentStripeThickness == 1 then return ColorSequence.new(stripeColor3) end local waypoints = {} local timeWidth = 1/stripes local timeOffset = (percentOffset + timeWidth*(percentStripeThickness - 0.5) % 0.5)*timeWidth if percentOffset >= 0.5 then stripeColor3, backgroundColor3 = backgroundColor3, stripeColor3 end table.insert(waypoints, ColorSequenceKeypoint.new(0, backgroundColor3)) for i=0, stripes-1 do local timestampStart = i/stripes + timeOffset local timeStampMiddle = timestampStart + timeWidth*(1 - percentStripeThickness) local timestampEnd = math.min(timestampStart + timeWidth, 1) if timeStampMiddle+EPSILON < timestampEnd-EPSILON then table.insert(waypoints, ColorSequenceKeypoint.new(timeStampMiddle, backgroundColor3)) table.insert(waypoints, ColorSequenceKeypoint.new(timeStampMiddle+EPSILON, stripeColor3)) table.insert(waypoints, ColorSequenceKeypoint.new(timestampEnd-EPSILON, stripeColor3)) table.insert(waypoints, ColorSequenceKeypoint.new(timestampEnd, backgroundColor3)) else table.insert(waypoints, ColorSequenceKeypoint.new(1, backgroundColor3)) end end return ColorSequence.new(waypoints) end return ColorSequenceUtils
--- -- @module ColorSequenceUtils local ColorSequenceUtils = {} local EPSILON = 1e-3 function ColorSequenceUtils.stripe(stripes, backgroundColor3, stripeColor3, percentStripeThickness, percentOffset) percentOffset = percentOffset or 0 percentStripeThickness = math.clamp(percentStripeThickness or 0.5, 0, 1) if percentStripeThickness <= EPSILON then return ColorSequence.new(backgroundColor3) elseif percentStripeThickness >= 1 - EPSILON then return ColorSequence.new(stripeColor3) end local timeWidth = 1/stripes local timeOffset = percentOffset*timeWidth timeOffset = timeOffset + percentStripeThickness*timeWidth*0.5 -- We add thickness to center timeOffset = timeOffset % timeWidth -- Generate initialial points local waypoints = {} for i=0, stripes-1 do local timestampStart = (i/stripes + timeOffset) % 1 local timeStampMiddle = (timestampStart + timeWidth*(1 - percentStripeThickness)) % 1 table.insert(waypoints, ColorSequenceKeypoint.new(timestampStart, backgroundColor3)) table.insert(waypoints, ColorSequenceKeypoint.new(timeStampMiddle, stripeColor3)) end table.sort(waypoints, function(a, b) return a.Time < b.Time end) local fullWaypoints = {} -- Handle first! table.insert(fullWaypoints, waypoints[1]) for i=2, #waypoints do local previous = waypoints[i-1] local current = waypoints[i] if current.Time - EPSILON > previous.Time then table.insert(fullWaypoints, ColorSequenceKeypoint.new(current.Time - EPSILON, previous.Value)) end table.insert(fullWaypoints, current) end -- Add beginning local first = fullWaypoints[1] if first.Time >= EPSILON then local color if first.Value == backgroundColor3 then color = stripeColor3 elseif first.Value == stripeColor3 then color = backgroundColor3 else error("Bad comparison") end table.insert(fullWaypoints, 1, ColorSequenceKeypoint.new(first.Time - EPSILON, color)) table.insert(fullWaypoints, 1, ColorSequenceKeypoint.new(0, color)) else -- Force single entry to actually be at 0 table.remove(fullWaypoints, 1) table.insert(fullWaypoints, 1, ColorSequenceKeypoint.new(0, first.Value)) end local last = fullWaypoints[#fullWaypoints] if last.Time <= (1 - EPSILON) then table.insert(fullWaypoints, ColorSequenceKeypoint.new(1, last.Value)) else -- Force single entry to actually be at 1 table.remove(fullWaypoints) table.insert(fullWaypoints, ColorSequenceKeypoint.new(1, last.Value)) end return ColorSequence.new(fullWaypoints) end return ColorSequenceUtils
Fix striping
Fix striping
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
99c12f8fd2ac022bb3505986e609b1c5ab644d11
src/python.lua
src/python.lua
--[[ @cond ___LICENSE___ -- Copyright (c) 2017 Zefiros Software. -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. -- -- @endcond --]] Python = newclass "Python" function Python:init(loader) self.loader = loader end function Python:yaml2json(yaml) return self(("%s %s"):format(path.join(zpm.env.getSrcDirectory(), "py/yaml2json.py"), yaml)) end function Python:prettifyJSON(json) return self(("%s %s"):format(path.join(zpm.env.getSrcDirectory(), "py/prettifyjson.py"), json)) end function Python:update() self:conda("config --set always_yes yes --set changeps1 no") self:conda("update --all --yes") end function Python:__call(command) return self:_outputof("%s %s", self:_getPythonExe(), command) end function Python:conda(command) self:_executef("%s %s", zpm.util.getExecutable("conda"), command) end function Python:pip(command) self:_executef("%s %s", zpm.util.getExecutable("pip"), command) end function Python:_getBinDirectory() return path.join(self:_getDirectory(), iif(os.is("windows"), "Scripts", "bin")) end function Python:_getDirectory() return path.join(zpm.env.getDataDirectory(), "conda") end function Python:_execute(...) os.executef("%s/%s", self:_getBinDirectory(), string.format(...)) end function Python:_outputof(...) return os.outputoff("%s/%s", self:_getDirectory(), string.format(...)) end function Python:_getPythonExe() return zpm.util.getExecutable(iif(os.is("windows"), "python", "python3")) end
--[[ @cond ___LICENSE___ -- Copyright (c) 2017 Zefiros Software. -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. -- -- @endcond --]] Python = newclass "Python" function Python:init(loader) self.loader = loader end function Python:yaml2json(yaml) return self(("%s %s"):format(path.join(zpm.env.getSrcDirectory(), "py/yaml2json.py"), yaml)) end function Python:prettifyJSON(json) return self(("%s %s"):format(path.join(zpm.env.getSrcDirectory(), "py/prettifyjson.py"), json)) end function Python:update() self:conda("config --set always_yes yes --set changeps1 no") self:conda("update --all --yes") end function Python:__call(command) return os.outputoff("%s %s", self:_getPythonExe(), command) end function Python:conda(command) self:_executef("%s %s", zpm.util.getExecutable("conda"), command) end function Python:pip(command) self:_executef("%s %s", zpm.util.getExecutable("pip"), command) end function Python:_getBinDirectory() return path.join(self:_getDirectory(), iif(os.is("windows"), "Scripts", "bin")) end function Python:_getDirectory() return path.join(zpm.env.getDataDirectory(), "conda") end function Python:_execute(...) os.executef("%s/%s", self:_getBinDirectory(), string.format(...)) end function Python:_getPythonExe() return path.join(self:_getDirectory(), zpm.util.getExecutable(iif(os.is("windows"), "python", "bin/python"))) end
Fix python directory
Fix python directory
Lua
mit
Zefiros-Software/ZPM
348505c67da49d5ef300168715b4cda3b0360741
src/CppParser/premake5.lua
src/CppParser/premake5.lua
clang_msvc_flags = { "/wd4146", "/wd4244", "/wd4800", "/wd4345", "/wd4355", "/wd4996", "/wd4624", "/wd4291", "/wd4251", "/wd4141", -- 'inline' : used more than once } if not (string.starts(action, "vs") and not os.is("windows")) then project "CppSharp.CppParser" kind "SharedLib" language "C++" SetupNativeProject() rtti "Off" filter "action:vs*" buildoptions { clang_msvc_flags } if os.getenv("APPVEYOR") then linkoptions { "/ignore:4099" } -- LNK4099: linking object as if no debug info end filter "system:linux" defines { "_GLIBCXX_USE_CXX11_ABI=0" } filter {} files { "*.h", "*.cpp", "*.lua" } SearchLLVM() SetupLLVMIncludes() SetupLLVMLibs() CopyClangIncludes() filter {} end project "Std-symbols" kind "SharedLib" language "C++" SetupNativeProject() rtti "Off" filter { "action:vs*" } buildoptions { clang_msvc_flags } filter {} if os.istarget("windows") then files { "i686-pc-win32-msvc/Std-symbols.cpp" } elseif os.istarget("macosx") then local file = io.popen("lipo -info `which mono`") local output = file:read('*all') if string.find(output, "x86_64") then files { "x86_64-apple-darwin12.4.0/Std-symbols.cpp" } else files { "i686-apple-darwin12.4.0/Std-symbols.cpp" } end elseif os.istarget("linux") then files { "x86_64-linux-gnu/Std-symbols.cpp" } else print "Unknown architecture" end filter {}
clang_msvc_flags = { "/wd4146", "/wd4244", "/wd4800", "/wd4345", "/wd4355", "/wd4996", "/wd4624", "/wd4291", "/wd4251", "/wd4141", -- 'inline' : used more than once } if not (string.starts(action, "vs") and not os.is("windows")) then project "CppSharp.CppParser" kind "SharedLib" language "C++" SetupNativeProject() rtti "Off" filter "action:vs*" buildoptions { clang_msvc_flags } if os.getenv("APPVEYOR") then linkoptions { "/ignore:4099" } -- LNK4099: linking object as if no debug info end filter "system:linux" defines { "_GLIBCXX_USE_CXX11_ABI=0" } filter {} files { "*.h", "*.cpp", "*.lua" } SearchLLVM() SetupLLVMIncludes() SetupLLVMLibs() CopyClangIncludes() filter {} end project "Std-symbols" kind "SharedLib" language "C++" SetupNativeProject() rtti "Off" filter { "action:vs*" } buildoptions { clang_msvc_flags } filter {} if os.istarget("windows") then files { "Bindings/CSharp/i686-pc-win32-msvc/Std-symbols.cpp" } elseif os.istarget("macosx") then local file = io.popen("lipo -info `which mono`") local output = file:read('*all') if string.find(output, "x86_64") then files { "Bindings/CSharp/x86_64-apple-darwin12.4.0/Std-symbols.cpp" } else files { "Bindings/CSharp/i686-apple-darwin12.4.0/Std-symbols.cpp" } end elseif os.istarget("linux") then files { "Bindings/CSharp/x86_64-linux-gnu/Std-symbols.cpp" } else print "Unknown architecture" end filter {}
Fixed Premake parser symbols build to point to the correct files.
Fixed Premake parser symbols build to point to the correct files.
Lua
mit
mono/CppSharp,ddobrev/CppSharp,zillemarco/CppSharp,u255436/CppSharp,mohtamohit/CppSharp,u255436/CppSharp,mohtamohit/CppSharp,ddobrev/CppSharp,zillemarco/CppSharp,mohtamohit/CppSharp,mohtamohit/CppSharp,mono/CppSharp,mono/CppSharp,mono/CppSharp,zillemarco/CppSharp,ddobrev/CppSharp,u255436/CppSharp,mohtamohit/CppSharp,mono/CppSharp,mono/CppSharp,zillemarco/CppSharp,ddobrev/CppSharp,ddobrev/CppSharp,u255436/CppSharp,zillemarco/CppSharp,u255436/CppSharp
9b9f7b171ad00c963213e6a985652ea05af8ad93
xmake/plugins/project/clang/compile_commands.lua
xmake/plugins/project/clang/compile_commands.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 compile_commands.lua -- -- imports import("core.tool.compiler") import("core.project.project") import("core.language.language") -- make the object function _make_object(jsonfile, target, sourcefile, objectfile) -- get the source file kind local sourcekind = language.sourcekind_of(sourcefile) -- make the object for the *.o/obj? ignore it directly if sourcekind == "obj" or sourcekind == "lib" then return end -- get compile arguments local arguments = table.join(compiler.compargv(sourcefile, {target = target, sourcekind = sourcekind})) -- make body jsonfile:printf( [[%s{ "directory": "%s", "arguments": ["%s"], "file": "%s", "output": "%s" }]], ifelse(_g.firstline, "", ",\n"), os.projectdir(), table.concat(arguments, "\", \""), sourcefile, objectfile) -- clear first line marks _g.firstline = false end -- make each objects function _make_each_objects(jsonfile, target, sourcekind, sourcebatch) for index, objectfile in ipairs(sourcebatch.objectfiles) do _make_object(jsonfile, target, sourcebatch.sourcefiles[index], objectfile) end end -- make single object function _make_single_object(jsonfile, target, sourcekind, sourcebatch) -- not supported now, ignore it directly for _, sourcefile in ipairs(table.wrap(sourcebatch.sourcefiles)) do cprint("${bright yellow}warning: ${default yellow}ignore[%s]: %s", target:name(), sourcefile) end end -- make target function _make_target(jsonfile, target) -- build source batches for sourcekind, sourcebatch in pairs(target:sourcebatches()) do if type(sourcebatch.objectfiles) == "string" then _make_single_object(jsonfile, target, sourcekind, sourcebatch) else _make_each_objects(jsonfile, target, sourcekind, sourcebatch) end end end -- make all function _make_all(jsonfile) -- make header jsonfile:print("[") -- make commands _g.firstline = true for _, target in pairs(project.targets()) do local isdefault = target:get("default") if not target:isphony() and (isdefault == nil or isdefault == true) then _make_target(jsonfile, target) end end -- make tailer jsonfile:print("]") end -- generate compilation databases for clang-based tools(compile_commands.json) -- -- references: -- - https://clang.llvm.org/docs/JSONCompilationDatabase.html -- - https://sarcasm.github.io/notes/dev/compilation-database.html -- - http://eli.thegreenplace.net/2014/05/21/compilation-databases-for-clang-based-tools -- function make(outputdir) -- enter project directory local oldir = os.cd(os.projectdir()) -- open the jsonfile local jsonfile = io.open(path.join(outputdir, "compile_commands.json"), "w") -- make all _make_all(jsonfile) -- close the jsonfile jsonfile:close() -- leave project directory os.cd(oldir) 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 compile_commands.lua -- -- imports import("core.tool.compiler") import("core.project.project") import("core.language.language") -- make the object function _make_object(jsonfile, target, sourcefile, objectfile) -- get the source file kind local sourcekind = language.sourcekind_of(sourcefile) -- make the object for the *.o/obj? ignore it directly if sourcekind == "obj" or sourcekind == "lib" then return end -- get compile arguments local arguments = table.join(compiler.compargv(sourcefile, objectfile, {target = target, sourcekind = sourcekind})) -- make body jsonfile:printf( [[%s{ "directory": "%s", "arguments": ["%s"], "file": "%s" }]], ifelse(_g.firstline, "", ",\n"), os.projectdir(), table.concat(arguments, "\", \""), sourcefile) -- clear first line marks _g.firstline = false end -- make each objects function _make_each_objects(jsonfile, target, sourcekind, sourcebatch) for index, objectfile in ipairs(sourcebatch.objectfiles) do _make_object(jsonfile, target, sourcebatch.sourcefiles[index], objectfile) end end -- make single object function _make_single_object(jsonfile, target, sourcekind, sourcebatch) -- not supported now, ignore it directly for _, sourcefile in ipairs(table.wrap(sourcebatch.sourcefiles)) do cprint("${bright yellow}warning: ${default yellow}ignore[%s]: %s", target:name(), sourcefile) end end -- make target function _make_target(jsonfile, target) -- build source batches for sourcekind, sourcebatch in pairs(target:sourcebatches()) do if type(sourcebatch.objectfiles) == "string" then _make_single_object(jsonfile, target, sourcekind, sourcebatch) else _make_each_objects(jsonfile, target, sourcekind, sourcebatch) end end end -- make all function _make_all(jsonfile) -- make header jsonfile:print("[") -- make commands _g.firstline = true for _, target in pairs(project.targets()) do local isdefault = target:get("default") if not target:isphony() and (isdefault == nil or isdefault == true) then _make_target(jsonfile, target) end end -- make tailer jsonfile:print("]") end -- generate compilation databases for clang-based tools(compile_commands.json) -- -- references: -- - https://clang.llvm.org/docs/JSONCompilationDatabase.html -- - https://sarcasm.github.io/notes/dev/compilation-database.html -- - http://eli.thegreenplace.net/2014/05/21/compilation-databases-for-clang-based-tools -- function make(outputdir) -- enter project directory local oldir = os.cd(os.projectdir()) -- open the jsonfile local jsonfile = io.open(path.join(outputdir, "compile_commands.json"), "w") -- make all _make_all(jsonfile) -- close the jsonfile jsonfile:close() -- leave project directory os.cd(oldir) end
fix compile_commands plugin
fix compile_commands plugin
Lua
apache-2.0
waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake
7ccb62cc5a48d173107df2e08898ba1c77b93949
.hammerspoon/example_config.lua
.hammerspoon/example_config.lua
-- copy this file to config.lua and edit as needed -- local cfg = {} cfg.global = {} -- this will be accessible via hsm.cfg in modules ---------------------------------------------------------------------------- local ufile = require('utils.file') local E = require('hs.application.watcher') -- appwindows events local A = require('appactions') -- appwindows actions -- Monospace font used in multiple modules local MONOFONT = 'Fira Mono' -------------------- -- global paths -- -------------------- cfg.global.paths = {} cfg.global.paths.base = os.getenv('HOME') cfg.global.paths.tmp = os.getenv('TMPDIR') cfg.global.paths.bin = ufile.toPath(cfg.global.paths.base, 'bin') cfg.global.paths.cloud = ufile.toPath(cfg.global.paths.base, 'Dropbox') cfg.global.paths.hs = ufile.toPath(cfg.global.paths.base, '.hammerspoon') cfg.global.paths.data = ufile.toPath(cfg.global.paths.hs, 'data') cfg.global.paths.media = ufile.toPath(cfg.global.paths.hs, 'media') ------------------ -- appwindows -- ------------------ -- Each app name points to a list of rules, which are event/action pairs. -- See hs.application.watcher for events, and appactions.lua for actions. cfg.appwindows = { rules = { Finder = {{evt = E.activated, act = A.toFront}}, ['Google Chrome'] = {{evt = E.launched, act = A.maximize}}, Skype = {{evt = E.launched, act = A.fullscreen}}, }, } --------------- -- battery -- --------------- cfg.battery = { icon = ufile.toPath(cfg.global.paths.media, 'battery.png'), } --------------- -- browser -- --------------- cfg.browser = { apps = { safari = 'com.apple.Safari', chrome = 'com.google.Chrome', firefox = 'org.mozilla.firefox', }, } cfg.browser.defaultApp = cfg.browser.apps.firefox ---------------- -- caffeine -- ---------------- cfg.caffeine = { menupriority = 1390, -- menubar priority (lower is lefter) notifyMinsActive = 30, -- notify when active for this many minutes icons = { on = ufile.toPath(cfg.global.paths.media, 'caffeine-on.pdf'), off = ufile.toPath(cfg.global.paths.media, 'caffeine-off.pdf'), }, } ------------------ -- cheatsheet -- ------------------ cfg.cheatsheet = { maxLines = 38, -- determined from trial/error with Fira Mono 14pt font defaultName = 'default', chooserWidth = 50, path = ufile.toPath(cfg.global.paths.hs, 'cheatsheets'), colors = { bg = {red=0.1, green=0.1, blue=0.1, alpha=0.9}, border = {red=0.3, green=0.3, blue=0.3, alpha=0.9}, text = {red=0.7, green=0.7, blue=0.7, alpha=1.0}, }, } cfg.cheatsheet.style = { font = MONOFONT, size = 14, color = cfg.cheatsheet.colors.text, alignment = 'natural', lineBreak = 'wordWrap', } ------------- -- hazel -- ------------- -- This module is intentionally full of code that ought to be customized, -- so not much is configured here, and it might make more sense to just keep -- all the configuration in modules/hazel.lua instead. cfg.hazel = { path = { dump = ufile.toPath(cfg.global.paths.base, 'Dump'), desktop = ufile.toPath(cfg.global.paths.base, 'Desktop'), downloads = ufile.toPath(cfg.global.paths.base, 'Downloads'), documents = ufile.toPath(cfg.global.paths.base, 'Documents'), transfer = ufile.toPath(cfg.global.paths.cloud, 'xfer'), }, hiddenExtensions = { -- when unhiding extensions, ignore these app = true, }, waitTime = 10, -- seconds to wait after file changed, before running rules } ------------------ -- notational -- ------------------ cfg.notational = { titleWeight = 5, -- title is this much more search-relevant than content width = 60, rows = 15, path = { notes = ufile.toPath(cfg.global.paths.cloud, 'notes'), -- the default location til = ufile.toPath(cfg.global.paths.cloud, 'til'), } } ------------------ -- scratchpad -- ------------------ cfg.scratchpad = { menupriority = 1370, -- menubar priority (lower is lefter) width = 60, file = ufile.toPath(cfg.global.paths.cloud, 'scratchpad.md'), } ------------- -- songs -- ------------- cfg.songs = { -- set this to the path of the track binary if you're using it -- trackBinary = ufile.toPath(cfg.global.paths.bin, 'track'), trackBinary = nil } ------------- -- timer -- ------------- cfg.timer = { menupriority = 1350, -- menubar priority (lower is lefter) width = 28, defaultTime = 5*60, -- in seconds icon = ufile.toPath(cfg.global.paths.media, 'tidy-clock-icon.png'), sound = ufile.toPath(cfg.global.paths.media, 'alert.caf'), volume = 1.0, } --------------- -- weather -- --------------- cfg.weather = { menupriority = 1400, -- menubar priority (lower is lefter) fetchTimeout = 120, -- timeout for downloading weather data locationTimeout = 300, -- timeout for lat/long lookup minPrecipProbability = 0.249, -- minimum to show precipitation details api = { -- forecast.io API config key = 'YOUR_API_KEY', maxCalls = 950, -- forecast.io only allows 1000 per day }, file = ufile.toPath(cfg.global.paths.data, 'weather.json'), iconPath = ufile.toPath(cfg.global.paths.media, 'weather'), tempThresholds = { -- Used for float comparisons, so +0.5 is easier warm = 79.5, hot = 87.5, tooHot = 94.5, tooDamnHot = 99.5, alert = 104.5, }, -- hs.styledtext styles styles = { default = { font = MONOFONT, size = 13, }, warm = { font = MONOFONT, size = 13, color = {red=1, green=0.96, blue=0.737, alpha=1}, }, hot = { font = MONOFONT, size = 13, color = {red=1, green=0.809, blue=0.493, alpha=1}, }, tooHot = { font = MONOFONT, size = 13, color = {red=0.984, green=0.612, blue=0.311, alpha=1}, }, tooDamnHot = { font = MONOFONT, size = 13, color = {red=0.976, green=0.249, blue=0.243, alpha=1}, }, alert = { font = MONOFONT, size = 13, color = {red=0.94, green=0.087, blue=0.319, alpha=1}, }, } } ------------ -- wifi -- ------------ cfg.wifi = { icon = ufile.toPath(cfg.global.paths.media, 'airport.png'), } ---------------- -- worktime -- ---------------- cfg.worktime = { menupriority = 1380, -- menubar priority (lower is lefter) awareness = { time = { chimeAfter = 30, -- mins chimeRepeat = 4, -- seconds between repeated chimes }, chime = { file = ufile.toPath(cfg.global.paths.media, 'bowl.wav'), volume = 0.4, }, }, pomodoro = { time = { work = 25, -- mins rest = 5, -- mins }, chime = { file = ufile.toPath(cfg.global.paths.media, 'temple.mp3'), volume = 1.0, }, }, } ---------------------------------------------------------------------------- return cfg
-- copy this file to config.lua and edit as needed -- local cfg = {} cfg.global = {} -- this will be accessible via hsm.cfg in modules ---------------------------------------------------------------------------- local ufile = require('utils.file') local E = require('hs.application.watcher') -- appwindows events local A = require('appactions') -- appwindows actions -- Monospace font used in multiple modules local MONOFONT = 'Fira Mono' -------------------- -- global paths -- -------------------- cfg.global.paths = {} cfg.global.paths.base = os.getenv('HOME') cfg.global.paths.tmp = os.getenv('TMPDIR') cfg.global.paths.bin = ufile.toPath(cfg.global.paths.base, 'bin') cfg.global.paths.cloud = ufile.toPath(cfg.global.paths.base, 'Dropbox') cfg.global.paths.hs = ufile.toPath(cfg.global.paths.base, '.hammerspoon') cfg.global.paths.data = ufile.toPath(cfg.global.paths.hs, 'data') cfg.global.paths.media = ufile.toPath(cfg.global.paths.hs, 'media') ------------------ -- appwindows -- ------------------ -- Each app name points to a list of rules, which are event/action pairs. -- See hs.application.watcher for events, and appactions.lua for actions. cfg.appwindows = { rules = { Finder = {{evt = E.activated, act = A.toFront}}, ['Google Chrome'] = {{evt = E.launched, act = A.maximize}}, Skype = {{evt = E.launched, act = A.fullscreen}}, }, } --------------- -- battery -- --------------- cfg.battery = { icon = ufile.toPath(cfg.global.paths.media, 'battery.png'), } --------------- -- browser -- --------------- cfg.browser = { apps = { ['com.apple.Safari'] = true, ['com.google.Chrome'] = true, ['org.mozilla.firefox'] = true, }, } cfg.browser.defaultApp = cfg.browser.apps.firefox ---------------- -- caffeine -- ---------------- cfg.caffeine = { menupriority = 1390, -- menubar priority (lower is lefter) notifyMinsActive = 30, -- notify when active for this many minutes icons = { on = ufile.toPath(cfg.global.paths.media, 'caffeine-on.pdf'), off = ufile.toPath(cfg.global.paths.media, 'caffeine-off.pdf'), }, } ------------------ -- cheatsheet -- ------------------ cfg.cheatsheet = { maxLines = 38, -- determined from trial/error with Fira Mono 14pt font defaultName = 'default', chooserWidth = 50, path = ufile.toPath(cfg.global.paths.hs, 'cheatsheets'), colors = { bg = {red=0.1, green=0.1, blue=0.1, alpha=0.9}, border = {red=0.3, green=0.3, blue=0.3, alpha=0.9}, text = {red=0.7, green=0.7, blue=0.7, alpha=1.0}, }, } cfg.cheatsheet.style = { font = MONOFONT, size = 14, color = cfg.cheatsheet.colors.text, alignment = 'natural', lineBreak = 'wordWrap', } ------------- -- hazel -- ------------- -- This module is intentionally full of code that ought to be customized, -- so not much is configured here, and it might make more sense to just keep -- all the configuration in modules/hazel.lua instead. cfg.hazel = { path = { dump = ufile.toPath(cfg.global.paths.base, 'Dump'), desktop = ufile.toPath(cfg.global.paths.base, 'Desktop'), downloads = ufile.toPath(cfg.global.paths.base, 'Downloads'), documents = ufile.toPath(cfg.global.paths.base, 'Documents'), transfer = ufile.toPath(cfg.global.paths.cloud, 'xfer'), }, hiddenExtensions = { -- when unhiding extensions, ignore these app = true, }, waitTime = 10, -- seconds to wait after file changed, before running rules } ------------------ -- notational -- ------------------ cfg.notational = { titleWeight = 5, -- title is this much more search-relevant than content width = 60, rows = 15, path = { notes = ufile.toPath(cfg.global.paths.cloud, 'notes'), -- the default location til = ufile.toPath(cfg.global.paths.cloud, 'til'), } } ------------------ -- scratchpad -- ------------------ cfg.scratchpad = { menupriority = 1370, -- menubar priority (lower is lefter) width = 60, file = ufile.toPath(cfg.global.paths.cloud, 'scratchpad.md'), } ------------- -- songs -- ------------- cfg.songs = { -- set this to the path of the track binary if you're using it -- trackBinary = ufile.toPath(cfg.global.paths.bin, 'track'), trackBinary = nil } ------------- -- timer -- ------------- cfg.timer = { menupriority = 1350, -- menubar priority (lower is lefter) width = 28, defaultTime = 5*60, -- in seconds icon = ufile.toPath(cfg.global.paths.media, 'tidy-clock-icon.png'), sound = ufile.toPath(cfg.global.paths.media, 'alert.caf'), volume = 1.0, } --------------- -- weather -- --------------- cfg.weather = { menupriority = 1400, -- menubar priority (lower is lefter) fetchTimeout = 120, -- timeout for downloading weather data locationTimeout = 300, -- timeout for lat/long lookup minPrecipProbability = 0.249, -- minimum to show precipitation details api = { -- forecast.io API config key = 'YOUR_API_KEY', maxCalls = 950, -- forecast.io only allows 1000 per day }, file = ufile.toPath(cfg.global.paths.data, 'weather.json'), iconPath = ufile.toPath(cfg.global.paths.media, 'weather'), tempThresholds = { -- Used for float comparisons, so +0.5 is easier warm = 79.5, hot = 87.5, tooHot = 94.5, tooDamnHot = 99.5, alert = 104.5, }, -- hs.styledtext styles styles = { default = { font = MONOFONT, size = 13, }, warm = { font = MONOFONT, size = 13, color = {red=1, green=0.96, blue=0.737, alpha=1}, }, hot = { font = MONOFONT, size = 13, color = {red=1, green=0.809, blue=0.493, alpha=1}, }, tooHot = { font = MONOFONT, size = 13, color = {red=0.984, green=0.612, blue=0.311, alpha=1}, }, tooDamnHot = { font = MONOFONT, size = 13, color = {red=0.976, green=0.249, blue=0.243, alpha=1}, }, alert = { font = MONOFONT, size = 13, color = {red=0.94, green=0.087, blue=0.319, alpha=1}, }, } } ------------ -- wifi -- ------------ cfg.wifi = { icon = ufile.toPath(cfg.global.paths.media, 'airport.png'), } ---------------- -- worktime -- ---------------- cfg.worktime = { menupriority = 1380, -- menubar priority (lower is lefter) awareness = { time = { chimeAfter = 30, -- mins chimeRepeat = 4, -- seconds between repeated chimes }, chime = { file = ufile.toPath(cfg.global.paths.media, 'bowl.wav'), volume = 0.4, }, }, pomodoro = { time = { work = 25, -- mins rest = 5, -- mins }, chime = { file = ufile.toPath(cfg.global.paths.media, 'temple.mp3'), volume = 1.0, }, }, } ---------------------------------------------------------------------------- return cfg
Fix browsers in example config
Fix browsers in example config
Lua
mit
scottcs/dot_hammerspoon
f785b29f346e4e54327c40f2db0f0fd0b87de653
frontend/device/kobo/device.lua
frontend/device/kobo/device.lua
local Generic = require("device/generic/device") local lfs = require("libs/libkoreader-lfs") local Geom = require("ui/geometry") local function yes() return true end local Kobo = Generic:new{ model = "Kobo", isKobo = yes, isTouchDevice = yes, -- all of them are -- most Kobos have X/Y switched for the touch screen touch_switch_xy = true, -- most Kobos have also mirrored X coordinates touch_mirrored_x = true, } -- TODO: hasKeys for some devices? local KoboTrilogy = Kobo:new{ model = "Kobo_trilogy", touch_switch_xy = false, } local KoboPixie = Kobo:new{ model = "Kobo_pixie", display_dpi = 200, } local KoboDahlia = Kobo:new{ model = "Kobo_dahlia", hasFrontlight = yes, touch_phoenix_protocol = true, display_dpi = 265, -- bezel: viewport = Geom:new{x=0, y=10, w=1080, h=1430}, } local KoboDragon = Kobo:new{ model = "Kobo_dragon", hasFrontlight = yes, display_dpi = 265, } local KoboKraken = Kobo:new{ model = "Kobo_kraken", hasFrontlight = yes, display_dpi = 212, } local KoboPhoenix = Kobo:new{ model = "Kobo_phoenix", hasFrontlight = yes, touch_phoenix_protocol = true, display_dpi = 212.8, -- bezel: viewport = Geom:new{x=0, y=0, w=752, h=1012}, } function Kobo:init() self.screen = require("device/screen"):new{device = self} self.powerd = require("device/kobo/powerd"):new{device = self} self.input = require("device/input"):new{ device = self, event_map = { [59] = "Power_SleepCover", [90] = "Light", [116] = "Power", } } Generic.init(self) self.input.open("/dev/input/event0") -- Light button and sleep slider self.input.open("/dev/input/event1") -- it's called KOBO_TOUCH_MIRRORED in defaults.lua, but what it -- actually did in its original implementation was to switch X/Y. if self.touch_switch_xy and not KOBO_TOUCH_MIRRORED or not self.touch_switch_xy and KOBO_TOUCH_MIRRORED then self.input:registerEventAdjustHook(self.input.adjustTouchSwitchXY) end if self.touch_mirrored_x then self.input:registerEventAdjustHook( self.input.adjustTouchMirrorX, self.screen:getScreenWidth() ) end if self.touch_phoenix_protocol then self.input.handleTouchEv = self.input.handleTouchEvPhoenix end end function Kobo:getCodeName() local std_out = io.popen("/bin/kobo_config.sh 2>/dev/null", "r") local codename = std_out:read() std_out:close() return codename end function Kobo:getFirmwareVersion() local version_file = io.open("/mnt/onboard/.kobo/version", "r") self.firmware_rev = string.sub(version_file:read(),24,28) version_file:close() end function Kobo:Suspend() os.execute("./suspend.sh") end function Kobo:Resume() os.execute("echo 0 > /sys/power/state-extended") if self.powerd then if KOBO_LIGHT_ON_START and tonumber(KOBO_LIGHT_ON_START) > -1 then self.powerd:setIntensity(math.max(math.min(KOBO_LIGHT_ON_START,100),0)) elseif self.powerd.fl ~= nil then self.powerd.fl:restore() end end Generic.Resume(self) end -------------- device probe ------------ local codename = Kobo:getCodeName() if codename == "dahlia" then return KoboDahlia elseif codename == "dragon" then return KoboDragon elseif codename == "kraken" then return KoboKraken elseif codename == "phoenix" then return KoboPhoenix elseif codename == "trilogy" then return KoboTrilogy elseif codename == "pixie" then return KoboPixie else error("unrecognized Kobo model "..codename) end
local Generic = require("device/generic/device") local lfs = require("libs/libkoreader-lfs") local Geom = require("ui/geometry") local function yes() return true end local Kobo = Generic:new{ model = "Kobo", isKobo = yes, isTouchDevice = yes, -- all of them are -- most Kobos have X/Y switched for the touch screen touch_switch_xy = true, -- most Kobos have also mirrored X coordinates touch_mirrored_x = true, } -- TODO: hasKeys for some devices? local KoboTrilogy = Kobo:new{ model = "Kobo_trilogy", touch_switch_xy = false, } local KoboPixie = Kobo:new{ model = "Kobo_pixie", display_dpi = 200, } local KoboDahlia = Kobo:new{ model = "Kobo_dahlia", hasFrontlight = yes, touch_phoenix_protocol = true, display_dpi = 265, -- bezel: viewport = Geom:new{x=0, y=10, w=1080, h=1430}, } local KoboDragon = Kobo:new{ model = "Kobo_dragon", hasFrontlight = yes, display_dpi = 265, } local KoboKraken = Kobo:new{ model = "Kobo_kraken", hasFrontlight = yes, display_dpi = 212, } local KoboPhoenix = Kobo:new{ model = "Kobo_phoenix", hasFrontlight = yes, touch_phoenix_protocol = true, display_dpi = 212.8, -- the bezel covers 12 pixels at the bottom: viewport = Geom:new{x=0, y=0, w=758, h=1012}, } function Kobo:init() self.screen = require("device/screen"):new{device = self} self.powerd = require("device/kobo/powerd"):new{device = self} self.input = require("device/input"):new{ device = self, event_map = { [59] = "Power_SleepCover", [90] = "Light", [116] = "Power", } } Generic.init(self) self.input.open("/dev/input/event0") -- Light button and sleep slider self.input.open("/dev/input/event1") -- it's called KOBO_TOUCH_MIRRORED in defaults.lua, but what it -- actually did in its original implementation was to switch X/Y. if self.touch_switch_xy and not KOBO_TOUCH_MIRRORED or not self.touch_switch_xy and KOBO_TOUCH_MIRRORED then self.input:registerEventAdjustHook(self.input.adjustTouchSwitchXY) end if self.touch_mirrored_x then self.input:registerEventAdjustHook( self.input.adjustTouchMirrorX, self.screen:getScreenWidth() ) end if self.touch_phoenix_protocol then self.input.handleTouchEv = self.input.handleTouchEvPhoenix end end function Kobo:getCodeName() local std_out = io.popen("/bin/kobo_config.sh 2>/dev/null", "r") local codename = std_out:read() std_out:close() return codename end function Kobo:getFirmwareVersion() local version_file = io.open("/mnt/onboard/.kobo/version", "r") self.firmware_rev = string.sub(version_file:read(),24,28) version_file:close() end function Kobo:Suspend() os.execute("./suspend.sh") end function Kobo:Resume() os.execute("echo 0 > /sys/power/state-extended") if self.powerd then if KOBO_LIGHT_ON_START and tonumber(KOBO_LIGHT_ON_START) > -1 then self.powerd:setIntensity(math.max(math.min(KOBO_LIGHT_ON_START,100),0)) elseif self.powerd.fl ~= nil then self.powerd.fl:restore() end end Generic.Resume(self) end -------------- device probe ------------ local codename = Kobo:getCodeName() if codename == "dahlia" then return KoboDahlia elseif codename == "dragon" then return KoboDragon elseif codename == "kraken" then return KoboKraken elseif codename == "phoenix" then return KoboPhoenix elseif codename == "trilogy" then return KoboTrilogy elseif codename == "pixie" then return KoboPixie else error("unrecognized Kobo model "..codename) end
Fix the viewport on Kobo Aura (phoenix).
Fix the viewport on Kobo Aura (phoenix).
Lua
agpl-3.0
lgeek/koreader,NiLuJe/koreader,Hzj-jie/koreader,robert00s/koreader,houqp/koreader,Frenzie/koreader,Markismus/koreader,pazos/koreader,frankyifei/koreader,koreader/koreader,koreader/koreader,ashang/koreader,poire-z/koreader,apletnev/koreader,ashhher3/koreader,NiLuJe/koreader,mihailim/koreader,chrox/koreader,Frenzie/koreader,noname007/koreader,poire-z/koreader,mwoz123/koreader,chihyang/koreader,NickSavage/koreader
841e8ac4634499007d3ce9434f47172b3ac01d01
libs/term.lua
libs/term.lua
local prev, pl, luv, dir, T, stdin, exit_seq = ... local _colors = { [1] = "white"; [2] = "orange"; [4] = "magenta"; [8] = "lightBlue"; [16] = "yellow"; [32] = "lime"; [64] = "pink"; [128] = "gray"; [256] = "lightGray"; [512] = "cyan"; [1024] = "purple"; [2048] = "blue"; [4096] = "brown"; [8192] = "green"; [16384] = "red"; [32768] = "black"; } local color_escapes = { fg = { white = T.setaf(7); orange = T.setaf(3); magenta = T.setaf(5); lightBlue = T.setaf(4); yellow = T.setaf(3); lime = T.setaf(2); pink = T.setaf(5); gray = T.setaf(0); lightGray = T.setaf(0); cyan = T.setaf(6); purple = T.setaf(5); blue = T.setaf(4); brown = T.setaf(3); green = T.setaf(2); red = T.setaf(1); black = T.setaf(0); }; bg = { white = T.setab(7); orange = T.setab(3); magenta = T.setab(5); lightBlue = T.setab(4); yellow = T.setab(3); lime = T.setab(2); pink = T.setab(5); gray = T.setab(0); lightGray = T.setab(0); cyan = T.setab(6); purple = T.setab(5); blue = T.setab(4); brown = T.setab(3); green = T.setab(2); red = T.setab(1); black = T.setab(0); }; } do local fg_dir = pl.path.join(dir, '.termu', 'term-colors', 'fg') if pl.path.isdir(fg_dir) then for color in pl.path.dir(fg_dir) do local path = pl.path.join(fg_dir, color) if id ~= '.' and id ~= '..' and pl.path.isfile(path) then local h = prev.io.open(path) color_escapes.fg[color] = h:read '*a' h:close() end end end local bg_dir = pl.path.join(dir, '.termu', 'term-colors', 'bg') if pl.path.isdir(bg_dir) then for color in pl.path.dir(bg_dir) do local path = pl.path.join(bg_dir, color) if id ~= '.' and id ~= '..' and pl.path.isfile(path) then local h = prev.io.open(path) color_escapes.bg[color] = h:read '*a' h:close() end end end end local hex = { ['a'] = 10; ['b'] = 11; ['c'] = 12; ['d'] = 13; ['e'] = 14; ['f'] = 15; } for i = 0, 9 do hex[tostring(i)] = i end local cursorX, cursorY = 1, 1 local cursorBlink = true local textColor, backColor = 0, 15 local log2 = math.log(2) local function ccColorFor(c) if type(c) ~= 'number' or c < 0 or c > 15 then error('that\'s not a valid color: ' .. tostring(c)) end return math.pow(2, c) end local function fromHexColor(h) return hex[h] or error('not a hex color: ' .. tostring(h)) end local processOutput if pl.path.exists(pl.path.join(dir, '.termu', 'term-munging')) then local utf8 = prev.utf8 or prev.require 'utf8' function processOutput(out) local res = '' for c in out:gmatch '.' do if c == '\0' or c == '\9' or c == '\10' or c == '\13' or c == '\32' or c == '\128' or c == '\160' then res = res .. c else res = res .. utf8.char(0xE000 + c:byte()) end end return res end else function processOutput(out) return out end end local termNat termNat = { clear = function() local w, h = termNat.getSize() for l = 0, h - 1 do prev.io.write(T.cup(l, 0)) prev.io.write((' '):rep(w)) end termNat.setCursorPos(cursorX, cursorY) end; clearLine = function() local w, h = termNat.getSize() prev.io.write(T.cup(cursorY - 1, 0)) prev.io.write((' '):rep(w)) termNat.setCursorPos(cursorX, cursorY) end; isColour = function() return true end; isColor = function() return true end; getSize = function() return luv.tty_get_winsize(stdin) -- return 52, 19 end; getCursorPos = function() return cursorX, cursorY end; setCursorPos = function(x, y) if type(x) ~= 'number' or type(y) ~= 'number' then error('term.setCursorPos expects number, number, got: ' .. type(x) .. ', ' .. type(y)) end local oldX, oldY = cursorX, cursorY cursorX, cursorY = math.floor(x), math.floor(y) termNat.setCursorBlink(cursorBlink) local w, h = luv.tty_get_winsize(stdin) if cursorY >= 1 and cursorY <= h and cursorX >= 1 and cursorX <= w then prev.io.write(T.cup(cursorY - 1, cursorX - 1)) end end; setTextColour = function(...) return termNat.setTextColor(...) end; setTextColor = function(c) textColor = math.log(c) / log2 prev.io.write(color_escapes.fg[_colors[c] ]) end; getTextColour = function(...) return termNat.getTextColor(...) end; getTextColor = function() return ccColorFor(textColor) end; setBackgroundColour = function(...) return termNat.setBackgroundColor(...) end; setBackgroundColor = function(c) backColor = math.log(c) / log2 prev.io.write(color_escapes.bg[_colors[c] ]) end; getBackgroundColour = function(...) return termNat.getBackgroundColor(...) end; getBackgroundColor = function() return ccColorFor(backColor) end; write = function(text) text = tostring(text or '') text = text:gsub('[\n\r]', '?') local w, h = luv.tty_get_winsize(stdin) if cursorY >= 1 and cursorY <= h and cursorX > 1 - #text and cursorX <= w then prev.io.write(processOutput(text)) end termNat.setCursorPos(cursorX + #text, cursorY) end; blit = function(text, textColors, backColors) text = text:gsub('[\n\r]', '?') if #text ~= #textColors or #text ~= #backColors then error('term.blit: text, textColors and backColors have to be the same length') end local w, h = luv.tty_get_winsize(stdin) if cursorY >= 1 and cursorY <= h and cursorX > 1 - #text and cursorX <= w then local fg, bg = textColor, backColor for i = 1, #text do termNat.setTextColor(ccColorFor(fromHexColor(textColors:sub(i, i)))) termNat.setBackgroundColor(ccColorFor(fromHexColor(backColors:sub(i, i)))) prev.io.write(processOutput(text:sub(i, i))) end termNat.setTextColor(ccColorFor(fg)) termNat.setBackgroundColor(ccColorFor(bg)) end termNat.setCursorPos(cursorX + #text, cursorY) end; setCursorBlink = function(blink) cursorBlink = blink local w, h = luv.tty_get_winsize(stdin) if cursorBlink and cursorY >= 1 and cursorY <= h and cursorX >= 1 and cursorX <= w then prev.io.write(T.cursor_normal()) else prev.io.write(T.cursor_invisible()) end end; scroll = function(n) n = n or 1 local w, h = luv.tty_get_winsize(stdin) prev.io.write(n < 0 and T.cup(0, 0) or T.cup(h, w)) local txt = T[n < 0 and 'ri' or 'ind']() prev.io.write(txt:rep(math.abs(n))) -- if n > 0 then -- prev.io.write(T.cup(h - n, 0)) -- prev.io.write(T.clr_eos()) -- elseif n < 0 then -- for i = 0, n do -- prev.io.write(T.cup(i, 0)) -- prev.io.write((' '):rep(w)) -- end -- end termNat.setCursorPos(cursorX, cursorY) end } prev.io.write(T.smcup()) termNat.setTextColor(1) termNat.setBackgroundColor(32768) termNat.clear() prev.io.flush() exit_seq[#exit_seq + 1] = function() prev.io.write(T.rmcup()) prev.io.flush() end return termNat
local prev, pl, luv, dir, T, stdin, exit_seq = ... local _colors = { [1] = "white"; [2] = "orange"; [4] = "magenta"; [8] = "lightBlue"; [16] = "yellow"; [32] = "lime"; [64] = "pink"; [128] = "gray"; [256] = "lightGray"; [512] = "cyan"; [1024] = "purple"; [2048] = "blue"; [4096] = "brown"; [8192] = "green"; [16384] = "red"; [32768] = "black"; } local color_escapes = { fg = { white = T.setaf(7); orange = T.setaf(3); magenta = T.setaf(5); lightBlue = T.setaf(4); yellow = T.setaf(3); lime = T.setaf(2); pink = T.setaf(5); gray = T.setaf(0); lightGray = T.setaf(0); cyan = T.setaf(6); purple = T.setaf(5); blue = T.setaf(4); brown = T.setaf(3); green = T.setaf(2); red = T.setaf(1); black = T.setaf(0); }; bg = { white = T.setab(7); orange = T.setab(3); magenta = T.setab(5); lightBlue = T.setab(4); yellow = T.setab(3); lime = T.setab(2); pink = T.setab(5); gray = T.setab(0); lightGray = T.setab(0); cyan = T.setab(6); purple = T.setab(5); blue = T.setab(4); brown = T.setab(3); green = T.setab(2); red = T.setab(1); black = T.setab(0); }; } do local fg_dir = pl.path.join(dir, '.termu', 'term-colors', 'fg') if pl.path.isdir(fg_dir) then for color in pl.path.dir(fg_dir) do local path = pl.path.join(fg_dir, color) if id ~= '.' and id ~= '..' and pl.path.isfile(path) then local h = prev.io.open(path) color_escapes.fg[color] = h:read '*a' h:close() end end end local bg_dir = pl.path.join(dir, '.termu', 'term-colors', 'bg') if pl.path.isdir(bg_dir) then for color in pl.path.dir(bg_dir) do local path = pl.path.join(bg_dir, color) if id ~= '.' and id ~= '..' and pl.path.isfile(path) then local h = prev.io.open(path) color_escapes.bg[color] = h:read '*a' h:close() end end end end local hex = { ['a'] = 10; ['b'] = 11; ['c'] = 12; ['d'] = 13; ['e'] = 14; ['f'] = 15; } for i = 0, 9 do hex[tostring(i)] = i end local cursorX, cursorY = 1, 1 local cursorBlink = true local textColor, backColor = 0, 15 local log2 = math.log(2) local function ccColorFor(c) if type(c) ~= 'number' or c < 0 or c > 15 then error('that\'s not a valid color: ' .. tostring(c)) end return math.pow(2, c) end local function fromHexColor(h) return hex[h] or error('not a hex color: ' .. tostring(h)) end local processOutput if pl.path.exists(pl.path.join(dir, '.termu', 'term-munging')) then local utf8 = prev.utf8 or prev.require 'utf8' function processOutput(out) local res = '' for c in out:gmatch '.' do if c == '\0' or c == '\9' or c == '\10' or c == '\13' or c == '\32' or c == '\128' or c == '\160' then res = res .. c else res = res .. utf8.char(0xE000 + c:byte()) end end return res end else function processOutput(out) return out end end local termNat termNat = { clear = function() local w, h = termNat.getSize() for l = 0, h - 1 do prev.io.write(T.cup(l, 0)) prev.io.write((' '):rep(w)) end termNat.setCursorPos(cursorX, cursorY) end; clearLine = function() local w, h = termNat.getSize() prev.io.write(T.cup(cursorY - 1, 0)) prev.io.write((' '):rep(w)) termNat.setCursorPos(cursorX, cursorY) end; isColour = function() return true end; isColor = function() return true end; getSize = function() return luv.tty_get_winsize(stdin) -- return 52, 19 end; getCursorPos = function() return cursorX, cursorY end; setCursorPos = function(x, y) if type(x) ~= 'number' or type(y) ~= 'number' then error('term.setCursorPos expects number, number, got: ' .. type(x) .. ', ' .. type(y)) end local oldX, oldY = cursorX, cursorY cursorX, cursorY = math.floor(x), math.floor(y) termNat.setCursorBlink(cursorBlink) local w, h = luv.tty_get_winsize(stdin) if cursorY >= 1 and cursorY <= h and cursorX <= w then prev.io.write(T.cup(cursorY - 1, math.max(0, cursorX - 1))) end end; setTextColour = function(...) return termNat.setTextColor(...) end; setTextColor = function(c) textColor = math.log(c) / log2 prev.io.write(color_escapes.fg[_colors[c] ]) end; getTextColour = function(...) return termNat.getTextColor(...) end; getTextColor = function() return ccColorFor(textColor) end; setBackgroundColour = function(...) return termNat.setBackgroundColor(...) end; setBackgroundColor = function(c) backColor = math.log(c) / log2 prev.io.write(color_escapes.bg[_colors[c] ]) end; getBackgroundColour = function(...) return termNat.getBackgroundColor(...) end; getBackgroundColor = function() return ccColorFor(backColor) end; write = function(text) text = tostring(text or '') text = text:gsub('[\n\r]', '?') local w, h = luv.tty_get_winsize(stdin) if cursorY >= 1 and cursorY <= h and cursorX <= w then if cursorX >= 1 then prev.io.write(processOutput(text)) elseif cursorX > 1 - #text then prev.io.write(processOutput(text:sub(-cursorX + 2))) end end termNat.setCursorPos(cursorX + #text, cursorY) end; blit = function(text, textColors, backColors) text = text:gsub('[\n\r]', '?') if #text ~= #textColors or #text ~= #backColors then error('term.blit: text, textColors and backColors have to be the same length') end local w, h = luv.tty_get_winsize(stdin) if cursorY >= 1 and cursorY <= h and cursorX <= w then local start if cursorX >= 1 then start = 1 elseif cursorX > 1 - #text then start = -cursorX + 2 end if start then local fg, bg = textColor, backColor for i = start, #text do termNat.setTextColor(ccColorFor(fromHexColor(textColors:sub(i, i)))) termNat.setBackgroundColor(ccColorFor(fromHexColor(backColors:sub(i, i)))) prev.io.write(processOutput(text:sub(i, i))) end termNat.setTextColor(ccColorFor(fg)) termNat.setBackgroundColor(ccColorFor(bg)) end end termNat.setCursorPos(cursorX + #text, cursorY) end; setCursorBlink = function(blink) cursorBlink = blink local w, h = luv.tty_get_winsize(stdin) if cursorBlink and cursorY >= 1 and cursorY <= h and cursorX >= 1 and cursorX <= w then prev.io.write(T.cursor_normal()) else prev.io.write(T.cursor_invisible()) end end; scroll = function(n) n = n or 1 local w, h = luv.tty_get_winsize(stdin) prev.io.write(n < 0 and T.cup(0, 0) or T.cup(h, w)) local txt = T[n < 0 and 'ri' or 'ind']() prev.io.write(txt:rep(math.abs(n))) -- if n > 0 then -- prev.io.write(T.cup(h - n, 0)) -- prev.io.write(T.clr_eos()) -- elseif n < 0 then -- for i = 0, n do -- prev.io.write(T.cup(i, 0)) -- prev.io.write((' '):rep(w)) -- end -- end termNat.setCursorPos(cursorX, cursorY) end } prev.io.write(T.smcup()) termNat.setTextColor(1) termNat.setBackgroundColor(32768) termNat.clear() prev.io.flush() exit_seq[#exit_seq + 1] = function() prev.io.write(T.rmcup()) prev.io.flush() end return termNat
Fix partial rendering
Fix partial rendering when the cursor is off to the left of the screen only part of the text should be rendered
Lua
mit
CoderPuppy/cc-emu,CoderPuppy/cc-emu,CoderPuppy/cc-emu
055b621cf5cdc15b24e78408d610a00f6869b8e0
modules/luci-mod-rpc/luasrc/controller/rpc.lua
modules/luci-mod-rpc/luasrc/controller/rpc.lua
-- Copyright 2008 Steven Barth <[email protected]> -- Copyright 2008 Jo-Philipp Wich <[email protected]> -- Licensed to the public under the Apache License 2.0. module("luci.controller.rpc", package.seeall) function index() local function session_retrieve(sid, allowed_users) local util = require "luci.util" local sdat = util.ubus("session", "get", { ubus_rpc_session = sid }) if type(sdat) == "table" and type(sdat.values) == "table" and type(sdat.values.token) == "string" and type(sdat.values.secret) == "string" and type(sdat.values.username) == "string" and util.contains(allowed_users, sdat.values.username) then return sid, sdat.values end return nil end local function authenticator(validator, accs) local http = require "luci.http" local auth = http.formvalue("auth", true) or http.getcookie("sysauth") if auth then -- if authentication token was given local sid, sdat = session_retrieve(auth, accs) if sdat then -- if given token is valid return sdat.username, sid end http.status(403, "Forbidden") end end local rpc = node("rpc") rpc.sysauth = "root" rpc.sysauth_authenticator = authenticator rpc.notemplate = true entry({"rpc", "uci"}, call("rpc_uci")) entry({"rpc", "fs"}, call("rpc_fs")) entry({"rpc", "sys"}, call("rpc_sys")) entry({"rpc", "ipkg"}, call("rpc_ipkg")) entry({"rpc", "auth"}, call("rpc_auth")).sysauth = false end function rpc_auth() local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local sys = require "luci.sys" local ltn12 = require "luci.ltn12" local util = require "luci.util" local server = {} server.challenge = function(user, pass) local config = require "luci.config" local login = util.ubus("session", "login", { username = user, password = pass, timeout = tonumber(config.sauth.sessiontime) }) if type(login) == "table" and type(login.ubus_rpc_session) == "string" then util.ubus("session", "set", { ubus_rpc_session = login.ubus_rpc_session, values = { token = sys.uniqueid(16), secret = sys.uniqueid(16) } }) local sid, sdat = session_retrieve(login.ubus_rpc_session, { user }) if sdat then return { sid = sid, token = sdat.token, secret = sdat.secret } end end return nil end server.login = function(...) local challenge = server.challenge(...) if challenge then http.header("Set-Cookie", 'sysauth=%s; path=%s' %{ challenge.sid, http.getenv("SCRIPT_NAME") }) return challenge.sid end end http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(server, http.source()), http.write) end function rpc_uci() if not pcall(require, "luci.model.uci") then luci.http.status(404, "Not Found") return nil end local uci = require "luci.jsonrpcbind.uci" local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(uci, http.source()), http.write) end function rpc_fs() local util = require "luci.util" local io = require "io" local fs2 = util.clone(require "nixio.fs") local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" function fs2.readfile(filename) local stat, mime = pcall(require, "mime") if not stat then error("Base64 support not available. Please install LuaSocket.") end local fp = io.open(filename) if not fp then return nil end local output = {} local sink = ltn12.sink.table(output) local source = ltn12.source.chain(ltn12.source.file(fp), mime.encode("base64")) return ltn12.pump.all(source, sink) and table.concat(output) end function fs2.writefile(filename, data) local stat, mime = pcall(require, "mime") if not stat then error("Base64 support not available. Please install LuaSocket.") end local file = io.open(filename, "w") local sink = file and ltn12.sink.chain(mime.decode("base64"), ltn12.sink.file(file)) return sink and ltn12.pump.all(ltn12.source.string(data), sink) or false end http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(fs2, http.source()), http.write) end function rpc_sys() local sys = require "luci.sys" local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(sys, http.source()), http.write) end function rpc_ipkg() if not pcall(require, "luci.model.ipkg") then luci.http.status(404, "Not Found") return nil end local ipkg = require "luci.model.ipkg" local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(ipkg, http.source()), http.write) end
-- Copyright 2008 Steven Barth <[email protected]> -- Copyright 2008 Jo-Philipp Wich <[email protected]> -- Licensed to the public under the Apache License 2.0. module("luci.controller.rpc", package.seeall) function session_retrieve(sid, allowed_users) local util = require "luci.util" local sdat = util.ubus("session", "get", { ubus_rpc_session = sid }) if type(sdat) == "table" and type(sdat.values) == "table" and type(sdat.values.token) == "string" and type(sdat.values.secret) == "string" and type(sdat.values.username) == "string" and util.contains(allowed_users, sdat.values.username) then return sid, sdat.values end return nil end function authenticator(validator, accs) local http = require "luci.http" local ctrl = require "luci.controller.rpc" local auth = http.formvalue("auth", true) or http.getcookie("sysauth") if auth then -- if authentication token was given local sid, sdat = ctrl.session_retrieve(auth, accs) if sdat then -- if given token is valid return sdat.username, sid end http.status(403, "Forbidden") end end function index() local ctrl = require "luci.controller.rpc" local rpc = node("rpc") rpc.sysauth = "root" rpc.sysauth_authenticator = ctrl.authenticator rpc.notemplate = true entry({"rpc", "uci"}, call("rpc_uci")) entry({"rpc", "fs"}, call("rpc_fs")) entry({"rpc", "sys"}, call("rpc_sys")) entry({"rpc", "ipkg"}, call("rpc_ipkg")) entry({"rpc", "ip"}, call("rpc_ip")) entry({"rpc", "auth"}, call("rpc_auth")).sysauth = false end function rpc_auth() local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local sys = require "luci.sys" local ltn12 = require "luci.ltn12" local util = require "luci.util" local server = {} server.challenge = function(user, pass) local config = require "luci.config" local login = util.ubus("session", "login", { username = user, password = pass, timeout = tonumber(config.sauth.sessiontime) }) if type(login) == "table" and type(login.ubus_rpc_session) == "string" then util.ubus("session", "set", { ubus_rpc_session = login.ubus_rpc_session, values = { token = sys.uniqueid(16), secret = sys.uniqueid(16) } }) local sid, sdat = ctrl.session_retrieve(login.ubus_rpc_session, { user }) if sdat then return { sid = sid, token = sdat.token, secret = sdat.secret } end end return nil end server.login = function(...) local challenge = server.challenge(...) if challenge then http.header("Set-Cookie", 'sysauth=%s; path=%s' %{ challenge.sid, http.getenv("SCRIPT_NAME") }) return challenge.sid end end http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(server, http.source()), http.write) end function rpc_uci() if not pcall(require, "luci.model.uci") then luci.http.status(404, "Not Found") return nil end local uci = require "luci.jsonrpcbind.uci" local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(uci, http.source()), http.write) end function rpc_fs() local util = require "luci.util" local io = require "io" local fs2 = util.clone(require "nixio.fs") local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" function fs2.readfile(filename) local stat, mime = pcall(require, "mime") if not stat then error("Base64 support not available. Please install LuaSocket.") end local fp = io.open(filename) if not fp then return nil end local output = {} local sink = ltn12.sink.table(output) local source = ltn12.source.chain(ltn12.source.file(fp), mime.encode("base64")) return ltn12.pump.all(source, sink) and table.concat(output) end function fs2.writefile(filename, data) local stat, mime = pcall(require, "mime") if not stat then error("Base64 support not available. Please install LuaSocket.") end local file = io.open(filename, "w") local sink = file and ltn12.sink.chain(mime.decode("base64"), ltn12.sink.file(file)) return sink and ltn12.pump.all(ltn12.source.string(data), sink) or false end http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(fs2, http.source()), http.write) end function rpc_sys() local util = require "luci.util" local sys = require "luci.sys" local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" local sys2 = util.clone(sys) sys2.net = util.clone(sys.net) sys2.wifi = util.clone(sys.wifi) function sys2.wifi.getiwinfo(ifname, operation) local iw = sys.wifi.getiwinfo(ifname) if iw then if operation then assert(type(iwinfo[iw.type][operation]) == "function") return iw[operation] end local n, f local rv = { ifname = ifname } for n, f in pairs(iwinfo[iw.type]) do if type(f) == "function" and n ~= "scanlist" and n ~= "countrylist" then rv[n] = iw[n] end end return rv end return nil end http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(sys2, http.source()), http.write) end function rpc_ipkg() if not pcall(require, "luci.model.ipkg") then luci.http.status(404, "Not Found") return nil end local ipkg = require "luci.model.ipkg" local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(ipkg, http.source()), http.write) end function rpc_ip() if not pcall(require, "luci.ip") then luci.http.status(404, "Not Found") return nil end local util = require "luci.util" local ip = require "luci.ip" local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" local ip2 = util.clone(ip) local _, n for _, n in ipairs({ "new", "IPv4", "IPv6", "MAC" }) do ip2[n] = function(address, netmask, operation, argument) local cidr = ip[n](address, netmask) if cidr and operation then assert(type(cidr[operation]) == "function") local cidr2 = cidr[operation](cidr, argument) return (type(cidr2) == "userdata") and cidr2:string() or cidr2 end return (type(cidr) == "userdata") and cidr:string() or cidr end end http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(ip2, http.source()), http.write) end
luci-mod-rpc: more auth/login fixes, expose further libraries
luci-mod-rpc: more auth/login fixes, expose further libraries The previous attempt to fix authentication broke login functionality so rework the code once again, this time with referencing helper functions directly via the controller scope. Furthermore, properly expose luci.sys.wifi.getiwinfo() and luci.ip. For getiwinfo(), the RPC wrapped function accepts one further optional parameter specifying the operation to invoke on the iwinfo instance. If no operation is specified, a summary object containing all info without country and scan list is returned. Example to obtain iwinfo summary object: curl --cookie sysauth=... \ --data '{"method": "wifi.getiwinfo", "params": ["wlan0"]}' \ "http://192.168.1.1/cgi-bin/luci/rpc/sys" Example to obtain iwinfo scan list: curl --cookie sysauth=... \ --data '{"method": "wifi.getiwinfo", "params": ["wlan0", "scanlist"]}' \ "http://192.168.1.1/cgi-bin/luci/rpc/sys" The exposed luci.ip class uses a similar approach to allow invoking instance methods on cidr objects. The new(), IPv4(), IPv6() and MAC() constructors accept two further optional arguments, with the first specifying the instance method to invoke and the second the value to pass to the instance method. Example to get list of IPv4 neighbours (ARP entries): curl --cookie sysauth=... \ --data '{"method": "neighbors", "params": [{"family": 4}]}' \ "http://192.168.1.1/cgi-bin/luci/rpc/ip" Example to add 100 hosts to a network address: curl --cookie sysauth=... \ --data '{"method": "IPv4", "params": ["192.168.0.1", "255.255.255.0", "add", 1000]}' \ "http://192.168.1.1/cgi-bin/luci/rpc/ip" Signed-off-by: Jo-Philipp Wich <[email protected]>
Lua
apache-2.0
Noltari/luci,kuoruan/luci,rogerpueyo/luci,remakeelectric/luci,openwrt/luci,artynet/luci,artynet/luci,openwrt/luci,remakeelectric/luci,rogerpueyo/luci,openwrt/luci,kuoruan/lede-luci,kuoruan/luci,artynet/luci,Noltari/luci,Noltari/luci,openwrt-es/openwrt-luci,nmav/luci,kuoruan/luci,artynet/luci,wongsyrone/luci-1,artynet/luci,chris5560/openwrt-luci,lbthomsen/openwrt-luci,wongsyrone/luci-1,tobiaswaldvogel/luci,nmav/luci,lbthomsen/openwrt-luci,kuoruan/lede-luci,remakeelectric/luci,openwrt-es/openwrt-luci,chris5560/openwrt-luci,kuoruan/lede-luci,remakeelectric/luci,nmav/luci,lbthomsen/openwrt-luci,rogerpueyo/luci,kuoruan/lede-luci,openwrt-es/openwrt-luci,kuoruan/luci,lbthomsen/openwrt-luci,kuoruan/lede-luci,artynet/luci,chris5560/openwrt-luci,nmav/luci,chris5560/openwrt-luci,lbthomsen/openwrt-luci,chris5560/openwrt-luci,kuoruan/lede-luci,tobiaswaldvogel/luci,nmav/luci,hnyman/luci,hnyman/luci,wongsyrone/luci-1,Noltari/luci,lbthomsen/openwrt-luci,remakeelectric/luci,openwrt/luci,kuoruan/luci,hnyman/luci,Noltari/luci,openwrt/luci,lbthomsen/openwrt-luci,hnyman/luci,remakeelectric/luci,remakeelectric/luci,hnyman/luci,chris5560/openwrt-luci,nmav/luci,kuoruan/lede-luci,wongsyrone/luci-1,kuoruan/luci,wongsyrone/luci-1,tobiaswaldvogel/luci,chris5560/openwrt-luci,kuoruan/luci,openwrt/luci,wongsyrone/luci-1,Noltari/luci,Noltari/luci,tobiaswaldvogel/luci,openwrt-es/openwrt-luci,openwrt/luci,wongsyrone/luci-1,rogerpueyo/luci,Noltari/luci,openwrt-es/openwrt-luci,artynet/luci,hnyman/luci,rogerpueyo/luci,remakeelectric/luci,openwrt-es/openwrt-luci,rogerpueyo/luci,tobiaswaldvogel/luci,nmav/luci,nmav/luci,chris5560/openwrt-luci,lbthomsen/openwrt-luci,hnyman/luci,hnyman/luci,artynet/luci,wongsyrone/luci-1,tobiaswaldvogel/luci,kuoruan/lede-luci,Noltari/luci,tobiaswaldvogel/luci,nmav/luci,openwrt-es/openwrt-luci,rogerpueyo/luci,openwrt/luci,openwrt-es/openwrt-luci,rogerpueyo/luci,kuoruan/luci,artynet/luci,tobiaswaldvogel/luci
39a15d1bef591eef410d9ead34e7c2fdd925a5fd
libs/core/luasrc/init.lua
libs/core/luasrc/init.lua
--[[ LuCI - Lua Configuration Interface Description: Main class FileId: $Id$ License: Copyright 2008 Steven Barth <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- local require = require module "luci" local v = require "luci.version" __version__ = v.luciversion or "0.9" __appname__ = v.luciname or "LuCI"
--[[ LuCI - Lua Configuration Interface Description: Main class FileId: $Id$ License: Copyright 2008 Steven Barth <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- local require = require -- Make sure that bitlib is loaded if not _G.bit then _G.bit = require "bit" end module "luci" local v = require "luci.version" __version__ = v.luciversion or "0.9" __appname__ = v.luciname or "LuCI"
libs/core: make sure that bitlib is loaded, fixes some sdk problems
libs/core: make sure that bitlib is loaded, fixes some sdk problems
Lua
apache-2.0
deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci
6a191817c7787b15093ef38e95214b3b8b7de984
Pooling.lua
Pooling.lua
local Pooling, parent = torch.class('cudnn._Pooling', 'nn.Module') local ffi = require 'ffi' local errcheck = cudnn.errcheck function Pooling:__init(kW, kH, dW, dH, padW, padH) parent.__init(self) self.kW = kW self.kH = kH self.dW = dW or kW self.dH = dH or kW self.padW = padW or 0 self.padH = padH or 0 self.iSize = torch.LongStorage(4):fill(0) self.ceil_mode = false end function Pooling:ceil() self.ceil_mode = true return self end function Pooling:floor() self.ceil_mode = false return self end function Pooling:resetPoolDescriptors() -- create pooling descriptor self.padW = self.padW or 0 self.padH = self.padH or 0 self.poolDesc = ffi.new('struct cudnnPoolingStruct*[1]') errcheck('cudnnCreatePoolingDescriptor', self.poolDesc) local ker = torch.IntTensor({self.kH, self.kW}) local str = torch.IntTensor({self.dH, self.dW}) local pad = torch.IntTensor({self.padH, self.padW}) errcheck('cudnnSetPoolingNdDescriptor', self.poolDesc[0], self.mode, 2, ker:data(), pad:data(), str:data()); local function destroyPoolDesc(d) errcheck('cudnnDestroyPoolingDescriptor', d[0]); end ffi.gc(self.poolDesc, destroyPoolDesc) end function Pooling:createIODescriptors(input) assert(self.mode, 'mode is not set. (trying to use base class?)'); local batch = true if input:dim() == 3 then input = input:view(1, input:size(1), input:size(2), input:size(3)) batch = false end assert(input:dim() == 4 and input:isContiguous()); if not self.iDesc or not self.oDesc or input:size(1) ~= self.iSize[1] or input:size(2) ~= self.iSize[2] or input:size(3) ~= self.iSize[3] or input:size(4) ~= self.iSize[4] then self.iSize = input:size() -- resize gradInput self.gradInput:resizeAs(input) -- resize output local oW, oH if self.ceil_mode then oW = math.ceil((input:size(4) - self.kW)/self.dW + 1) oH = math.ceil((input:size(3) - self.kH)/self.dH + 1) else oW = math.floor((input:size(4) - self.kW)/self.dW + 1) oH = math.floor((input:size(3) - self.kH)/self.dH + 1) end self.output:resize(input:size(1), input:size(2), oH, oW) -- create input/output descriptor self.iDesc = cudnn.toDescriptor(input) self.oDesc = cudnn.toDescriptor(self.output) if not batch then self.gradInput = self.gradInput:view(self.gradInput:size(2), self.gradInput:size(3), self.gradInput:size(4)) self.output = self.output:view(self.output:size(2), self.output:size(3), self.output:size(4)) end end end local one = torch.FloatTensor({1}); local zero = torch.FloatTensor({0}); function Pooling:updateOutput(input) if not self.poolDesc then self:resetPoolDescriptors() end self:createIODescriptors(input) errcheck('cudnnPoolingForward', cudnn.getHandle(), self.poolDesc[0], one:data(), self.iDesc[0], input:data(), zero:data(), self.oDesc[0], self.output:data()); return self.output end function Pooling:updateGradInput(input, gradOutput) assert(gradOutput:dim() == 3 or gradOutput:dim() == 4); if not gradOutput:isContiguous() then self._gradOutput = self._gradOutput or gradOutput.new():resizeAs(gradOutput) self._gradOutput:copy(gradOutput) gradOutput = self._gradOutput end if not self.poolDesc then self:resetPoolDescriptors() end self:createIODescriptors(input) errcheck('cudnnPoolingBackward', cudnn.getHandle(), self.poolDesc[0], one:data(), self.oDesc[0], self.output:data(), self.oDesc[0], gradOutput:data(), self.iDesc[0], input:data(), zero:data(), self.iDesc[0], self.gradInput:data()); return self.gradInput end
local Pooling, parent = torch.class('cudnn._Pooling', 'nn.Module') local ffi = require 'ffi' local errcheck = cudnn.errcheck function Pooling:__init(kW, kH, dW, dH, padW, padH) parent.__init(self) self.kW = kW self.kH = kH self.dW = dW or kW self.dH = dH or kW self.padW = padW or 0 self.padH = padH or 0 self.iSize = torch.LongStorage(4):fill(0) self.ceil_mode = false end function Pooling:ceil() self.ceil_mode = true return self end function Pooling:floor() self.ceil_mode = false return self end function Pooling:resetPoolDescriptors() -- create pooling descriptor self.padW = self.padW or 0 self.padH = self.padH or 0 self.poolDesc = ffi.new('struct cudnnPoolingStruct*[1]') errcheck('cudnnCreatePoolingDescriptor', self.poolDesc) local ker = torch.IntTensor({self.kH, self.kW}) local str = torch.IntTensor({self.dH, self.dW}) local pad = torch.IntTensor({self.padH, self.padW}) errcheck('cudnnSetPoolingNdDescriptor', self.poolDesc[0], self.mode, 2, ker:data(), pad:data(), str:data()); local function destroyPoolDesc(d) errcheck('cudnnDestroyPoolingDescriptor', d[0]); end ffi.gc(self.poolDesc, destroyPoolDesc) end function Pooling:createIODescriptors(input) assert(self.mode, 'mode is not set. (trying to use base class?)'); local batch = true if input:dim() == 3 then input = input:view(1, input:size(1), input:size(2), input:size(3)) batch = false end assert(input:dim() == 4 and input:isContiguous()); if not self.iDesc or not self.oDesc or input:size(1) ~= self.iSize[1] or input:size(2) ~= self.iSize[2] or input:size(3) ~= self.iSize[3] or input:size(4) ~= self.iSize[4] then self.iSize = input:size() -- resize gradInput self.gradInput:resizeAs(input) -- resize output local oW, oH if self.ceil_mode then oW = math.ceil((input:size(4)+self.padW*2 - self.kW)/self.dW + 1) oH = math.ceil((input:size(3)+self.padH*2 - self.kH)/self.dH + 1) else oW = math.floor((input:size(4)+self.padW*2 - self.kW)/self.dW + 1) oH = math.floor((input:size(3)+self.padH*2 - self.kH)/self.dH + 1) end self.output:resize(input:size(1), input:size(2), oH, oW) -- create input/output descriptor self.iDesc = cudnn.toDescriptor(input) self.oDesc = cudnn.toDescriptor(self.output) if not batch then self.gradInput = self.gradInput:view(self.gradInput:size(2), self.gradInput:size(3), self.gradInput:size(4)) self.output = self.output:view(self.output:size(2), self.output:size(3), self.output:size(4)) end end end local one = torch.FloatTensor({1}); local zero = torch.FloatTensor({0}); function Pooling:updateOutput(input) if not self.poolDesc then self:resetPoolDescriptors() end self:createIODescriptors(input) errcheck('cudnnPoolingForward', cudnn.getHandle(), self.poolDesc[0], one:data(), self.iDesc[0], input:data(), zero:data(), self.oDesc[0], self.output:data()); return self.output end function Pooling:updateGradInput(input, gradOutput) assert(gradOutput:dim() == 3 or gradOutput:dim() == 4); if not gradOutput:isContiguous() then self._gradOutput = self._gradOutput or gradOutput.new():resizeAs(gradOutput) self._gradOutput:copy(gradOutput) gradOutput = self._gradOutput end if not self.poolDesc then self:resetPoolDescriptors() end self:createIODescriptors(input) errcheck('cudnnPoolingBackward', cudnn.getHandle(), self.poolDesc[0], one:data(), self.oDesc[0], self.output:data(), self.oDesc[0], gradOutput:data(), self.iDesc[0], input:data(), zero:data(), self.iDesc[0], self.gradInput:data()); return self.gradInput end
fixing free padding bug in pooling
fixing free padding bug in pooling
Lua
bsd-3-clause
phunghx/phnn.torch,phunghx/phnn.torch,phunghx/phnn.torch
9a12eaffdd128578cb7244b102f7a202312f87b9
test/tree-construction.lua
test/tree-construction.lua
-- Test runner for the html5lib tree-construction test suite. -- Runs quiet by default to avoid clobbering test runner output. -- Run with VERBOSE=1 in the environment for full output. local gumbo = require "gumbo" local Buffer = require "gumbo.Buffer" local Indent = require "gumbo.serialize.Indent" local parse = gumbo.parse local ipairs, assert, sort = ipairs, assert, table.sort local open, popen, write = io.open, io.popen, io.write local clock, exit = os.clock, os.exit local verbose = os.getenv "VERBOSE" local _ENV = nil local ELEMENT_NODE, TEXT_NODE, COMMENT_NODE = 1, 3, 8 local filenames = {} local function serialize(document) assert(document and document.type == "document") local buf = Buffer() local indent = Indent(2) local function writeNode(node, depth) local type = node.nodeType if type == ELEMENT_NODE then local i1, i2 = indent[depth], indent[depth+1] buf:write("| ", i1, "<") local namespace = node.namespace if namespace ~= "html" then buf:write(namespace, " ") end buf:write(node.localName, ">\n") -- The html5lib tree format expects attributes to be sorted by -- name, in lexicographic order. Instead of sorting in-place or -- copying the entire table, we build a lightweight, sorted index. local attr = node.attributes local attrLength = #attr local attrIndex = {} for i = 1, attrLength do attrIndex[i] = i end sort(attrIndex, function(a, b) return attr[a].name < attr[b].name end) for i = 1, attrLength do local a = attr[attrIndex[i]] local prefix = a.prefix and (a.prefix .. " ") or "" buf:write("| ", i2, prefix, a.name, '="', a.value, '"\n') end local children if node.type == "template" then buf:write("| ", i2, "content\n") depth = depth + 1 children = node.content.childNodes else children = node.childNodes end local n = #children for i = 1, n do if children[i].type == "text" and children[i+1] and children[i+1].type == "text" then -- Merge adjacent text nodes, as expected by the -- spec and the html5lib tests -- TODO: Why doesn't Gumbo do this during parsing? local text = children[i+1].data children[i+1] = children[i] children[i+1].data = children[i+1].data .. text else writeNode(children[i], depth + 1) end end elseif type == TEXT_NODE then buf:write("| ", indent[depth], '"', node.data, '"\n') elseif type == COMMENT_NODE then buf:write("| ", indent[depth], "<!-- ", node.data, " -->\n") end end local doctype = document.doctype if doctype then buf:write("| <!DOCTYPE ", doctype.name) local publicId, systemId = doctype.publicId, doctype.systemId if publicId ~= "" or systemId ~= "" then buf:write(' "', publicId, '" "', systemId, '"') end buf:write(">\n") end local childNodes = document.childNodes for i = 1, #childNodes do writeNode(childNodes[i], 0) end return buf:tostring() end local function parseTestData(filename) local file = assert(open(filename, "rb")) local text = assert(file:read("*a")) file:close() local tests = {[0] = {}} local buffer = Buffer() local field = false local testnum, linenum = 0, 0 for line in text:gmatch "([^\n]*)\n" do linenum = linenum + 1 if line:sub(1, 1) == "#" then tests[testnum][field] = buffer:tostring():sub(1, -2) buffer = Buffer() field = line:sub(2, -1) if field == "data" then testnum = testnum + 1 tests[testnum] = {line = linenum} end else buffer:write(line, "\n") end end tests[testnum][field] = buffer:tostring() if testnum > 0 then return tests else return nil, "No test data found in " .. filename end end do local pipe = assert(popen("echo test/tree-construction/*.dat")) local text = assert(pipe:read("*a")) pipe:close() assert(text:len() > 0, "No test data found") local i = 0 for filename in text:gmatch("%S+") do i = i + 1 filenames[i] = filename end assert(i > 0, "No test data found") end do local hrule = ("="):rep(76) local totalPassed, totalFailed, totalSkipped = 0, 0, 0 local start = clock() for _, filename in ipairs(filenames) do local tests = assert(parseTestData(filename)) local passed, failed, skipped = 0, 0, 0 for i, test in ipairs(tests) do local input = assert(test.data) if test["document-fragment"] or input:find("<noscript>") then skipped = skipped + 1 else local expected = assert(test.document) local parsed = assert(parse(input)) local serialized = assert(serialize(parsed)) if serialized == expected then passed = passed + 1 else failed = failed + 1 if verbose then write ( hrule, "\n", filename, ":", test.line, ": Test ", i, " failed\n", hrule, "\n\n", "Input:\n", input, "\n\n", "Expected:\n", expected, "\n", "Received:\n", serialized, "\n" ) end end end end totalPassed = totalPassed + passed totalFailed = totalFailed + failed totalSkipped = totalSkipped + skipped end local stop = clock() if verbose or totalFailed > 0 then write ( "\nRan ", totalPassed + totalFailed + totalSkipped, " tests in ", ("%.2fs"):format(stop - start), "\n\n", "Passed: ", totalPassed, "\n", "Failed: ", totalFailed, "\n", "Skipped: ", totalSkipped, "\n\n" ) end if totalFailed > 0 then if not verbose then write "Re-run with VERBOSE=1 for a full report\n" end exit(1) end end
-- Test runner for the html5lib tree-construction test suite. -- Runs quiet by default to avoid clobbering test runner output. -- Run with VERBOSE=1 in the environment for full output. local gumbo = require "gumbo" local Buffer = require "gumbo.Buffer" local Indent = require "gumbo.serialize.Indent" local parse = gumbo.parse local ipairs, assert, sort = ipairs, assert, table.sort local open, popen, write = io.open, io.popen, io.write local clock, exit = os.clock, os.exit local verbose = os.getenv "VERBOSE" local _ENV = nil local ELEMENT_NODE, TEXT_NODE, COMMENT_NODE = 1, 3, 8 local filenames = {} local function serialize(document) assert(document and document.type == "document") local buf = Buffer() local indent = Indent(2) local function writeNode(node, depth) local type = node.nodeType if type == ELEMENT_NODE then local i1, i2 = indent[depth], indent[depth+1] buf:write("| ", i1, "<") local namespace = node.namespace if namespace ~= "html" then buf:write(namespace, " ") end buf:write(node.localName, ">\n") -- The html5lib tree format expects attributes to be sorted by -- name, in lexicographic order. Instead of sorting in-place or -- copying the entire table, we build a lightweight, sorted index. local attr = node.attributes local attrLength = #attr local attrIndex = {} for i = 1, attrLength do attrIndex[i] = i end sort(attrIndex, function(a, b) return attr[a].name < attr[b].name end) for i = 1, attrLength do local a = attr[attrIndex[i]] local prefix = a.prefix and (a.prefix .. " ") or "" buf:write("| ", i2, prefix, a.name, '="', a.value, '"\n') end local childNodes if node.type == "template" then buf:write("| ", i2, "content\n") depth = depth + 1 childNodes = node.content.childNodes else childNodes = node.childNodes end local n = #childNodes for i = 1, n do if childNodes[i].type == "text" and childNodes[i+1] and childNodes[i+1].type == "text" then -- Merge adjacent text nodes, as expected by the -- spec and the html5lib tests -- TODO: Why doesn't Gumbo do this during parsing? local text = childNodes[i+1].data childNodes[i+1] = childNodes[i] childNodes[i+1].data = childNodes[i+1].data .. text else writeNode(childNodes[i], depth + 1) end end elseif type == TEXT_NODE then buf:write("| ", indent[depth], '"', node.data, '"\n') elseif type == COMMENT_NODE then buf:write("| ", indent[depth], "<!-- ", node.data, " -->\n") end end local doctype = document.doctype if doctype then buf:write("| <!DOCTYPE ", doctype.name) local publicId, systemId = doctype.publicId, doctype.systemId if publicId ~= "" or systemId ~= "" then buf:write(' "', publicId, '" "', systemId, '"') end buf:write(">\n") end local childNodes = document.childNodes for i = 1, #childNodes do writeNode(childNodes[i], 0) end return buf:tostring() end local function parseTestData(filename) local file = assert(open(filename, "rb")) local text = assert(file:read("*a")) file:close() local tests = {[0] = {}} local buffer = Buffer() local field = false local testnum, linenum = 0, 0 for line in text:gmatch "([^\n]*)\n" do linenum = linenum + 1 if line:sub(1, 1) == "#" then tests[testnum][field] = buffer:tostring():sub(1, -2) buffer = Buffer() field = line:sub(2, -1) if field == "data" then testnum = testnum + 1 tests[testnum] = {line = linenum} end else buffer:write(line, "\n") end end assert(testnum > 0, "No test data found in " .. filename) tests[testnum][field] = buffer:tostring() return tests end do local pipe = assert(popen("echo test/tree-construction/*.dat")) local text = assert(pipe:read("*a")) pipe:close() assert(text:len() > 0, "No test data found") local i = 0 for filename in text:gmatch("%S+") do i = i + 1 filenames[i] = filename end assert(i > 0, "No test data found") end do local hrule = ("="):rep(76) local totalPassed, totalFailed, totalSkipped = 0, 0, 0 local start = clock() for _, filename in ipairs(filenames) do local tests = parseTestData(filename) local passed, failed, skipped = 0, 0, 0 for i, test in ipairs(tests) do local input = assert(test.data) if test["document-fragment"] or input:find("<noscript>") then skipped = skipped + 1 else local expected = assert(test.document) local parsed = assert(parse(input)) local serialized = assert(serialize(parsed)) if serialized == expected then passed = passed + 1 else failed = failed + 1 if verbose then write ( hrule, "\n", filename, ":", test.line, ": Test ", i, " failed\n", hrule, "\n\n", "Input:\n", input, "\n\n", "Expected:\n", expected, "\n", "Received:\n", serialized, "\n" ) end end end end totalPassed = totalPassed + passed totalFailed = totalFailed + failed totalSkipped = totalSkipped + skipped end local stop = clock() if verbose or totalFailed > 0 then write ( "\nRan ", totalPassed + totalFailed + totalSkipped, " tests in ", ("%.2fs"):format(stop - start), "\n\n", "Passed: ", totalPassed, "\n", "Failed: ", totalFailed, "\n", "Skipped: ", totalSkipped, "\n\n" ) end if totalFailed > 0 then if not verbose then write "Re-run with VERBOSE=1 for a full report\n" end exit(1) end end
Minor style fixes in test/tree-construction.lua
Minor style fixes in test/tree-construction.lua
Lua
apache-2.0
craigbarnes/lua-gumbo,craigbarnes/lua-gumbo,craigbarnes/lua-gumbo
5e402ee7f062b5a3ac17e3845e3c641bd72755ce
editor/lib/lua/editor/edit/CanvasView/PickingManager.lua
editor/lib/lua/editor/edit/CanvasView/PickingManager.lua
local defaultSortMode = MOAILayer.SORT_Z_ASCENDING --------------------------------------------------------------------------------- -- -- @type PickingManager -- --------------------------------------------------------------------------------- local PickingManager = Class( "PickingManager" ) function PickingManager:init() -- end function PickingManager:setTargetScene( scene ) self.targetScene = scene end --------------------------------------------------------------------------------- function PickingManager:pickPoint( x, y, pad ) for i, layer in ipairs( self:getVisibleLayers() ) do local partition = layer:getPartition() local sortMode = layer:getSortMode() local result = { partition:propListForPoint( x, y, 0, sortMode ) } --propListForRay -1000, 0, 0, 1, for i, prop in ipairs( result ) do local ent = prop.entity if ent and not ent.FLAG_EDITOR_OBJECT then return { ent } end end end return {} end function PickingManager:pickRect( x0, y0, x1, y1, pad ) local picked = {} for i, layer in ipairs( self:getVisibleLayers() ) do local partition = layer:getPartition() local sortMode = layer:getSortMode() local result = { partition:propListForRect( x0, y0, x1, y1, sortMode ) } for i, prop in ipairs( result ) do local ent = prop.entity if ent and not ent.FLAG_EDITOR_OBJECT then picked[ ent ] = true end end end return table.keys(picked) end function PickingManager:getVisibleLayers() local layers = {} for i, layer in ipairs( self.targetScene.layers ) do table.insert( layers, layer ) end return table.reverse( layers ) end --------------------------------------------------------------------------------- return PickingManager
local defaultSortMode = MOAILayer.SORT_PRIORITY_DESCENDING--SORT_Z_ASCENDING --------------------------------------------------------------------------------- -- -- @type PickingManager -- --------------------------------------------------------------------------------- local PickingManager = Class( "PickingManager" ) function PickingManager:init() -- end function PickingManager:setTargetScene( scene ) self.targetScene = scene end --------------------------------------------------------------------------------- function PickingManager:pickPoint( x, y, pad ) for i, layer in ipairs( self:getVisibleLayers() ) do local partition = layer:getPartition() local result = { partition:propListForPoint( x, y, 0, defaultSortMode ) } --propListForRay -1000, 0, 0, 1, for i, prop in ipairs( result ) do local ent = prop.entity if ent and not ent.FLAG_EDITOR_OBJECT then return { ent } end end end return {} end function PickingManager:pickRect( x0, y0, x1, y1, pad ) local picked = {} for i, layer in ipairs( self:getVisibleLayers() ) do local partition = layer:getPartition() local result = { partition:propListForRect( x0, y0, x1, y1, defaultSortMode ) } for i, prop in ipairs( result ) do local ent = prop.entity if ent and not ent.FLAG_EDITOR_OBJECT then picked[ ent ] = true end end end return table.keys(picked) end function PickingManager:getVisibleLayers() local layers = {} for i, layer in ipairs( self.targetScene.layers ) do table.insert( layers, layer ) end return table.reverse( layers ) end --------------------------------------------------------------------------------- return PickingManager
fix pick sprite
fix pick sprite
Lua
mit
cloudteampro/juma-editor,cloudteampro/juma-editor,cloudteampro/juma-editor,RazielSun/juma-editor,cloudteampro/juma-editor,RazielSun/juma-editor,RazielSun/juma-editor,RazielSun/juma-editor
f1efc695e29e0d7a99ae6de7555d85d8f735aedf
nyagos.d/catalog/git.lua
nyagos.d/catalog/git.lua
if not nyagos then print("This is a script for nyagos not lua.exe") os.exit() end -- hub exists, replace git command local hubpath=nyagos.which("hub.exe") if hubpath then nyagos.alias.git = "hub.exe" end share.git = {} local getcommits = function(args) local fd=io.popen("git log --format=\"%h\" -n 20 2>nul","r") if not fd then return {} end local result={} for line in fd:lines() do result[#result+1] = line end fd:close() return result end -- setup local branch listup local branchlist = function(args) if string.find(args[#args],"[/\\\\]") then return nil end local gitbranches = getcommits() local gitbranch_tmp = nyagos.eval('git for-each-ref --format="%(refname:short)" refs/heads/ 2> nul') for line in gitbranch_tmp:gmatch('[^\n]+') do table.insert(gitbranches,line) end return gitbranches end local unquote = function(s) s = string.gsub(s,'"','') return string.gsub(s,'\\[0-7][0-7][0-7]',function(t) return string.char(tonumber(string.sub(t,2),8)) end) end local isUnderUntrackedDir = function(arg,files) local matched_count=0 local last_matched local upper_arg = string.upper(arg) local upper_arg_len = string.len(upper_arg) for i=1,#files do if string.upper(string.sub(files[i],1,upper_arg_len)) == upper_arg then matched_count = matched_count + 1 last_matched = files[i] end end if matched_count == 1 and string.match(last_matched,"/$") then return true elseif matched_count < 1 then return true end return false end local addlist = function(args) local fd = io.popen("git status -s 2>nul","r") if not fd then return nil end local files = {} for line in fd:lines() do local arrowStart,arrowEnd = string.find(line," -> ",1,true) if arrowStart then files[#files+1] = unquote(string.sub(line,4,arrowStart-1)) files[#files+1] = unquote(string.sub(line,arrowEnd+1)) else files[#files+1] = unquote(string.sub(line,4)) end end fd:close() if isUnderUntrackedDir(args[#args],files) then return nil end return files end local checkoutlist = function(args) local result = branchlist(args) or {} local fd = io.popen("git status -s 2>nul","r") if fd then for line in fd:lines() do if string.sub(line,1,2) == " M" then result[1+#result] = unquote(string.sub(line,4)) end end fd:close() end return result end --setup current branch string local currentbranch = function() return nyagos.eval('git rev-parse --abbrev-ref HEAD 2> nul') end -- subcommands local gitsubcommands={} -- keyword gitsubcommands["bisect"]={"start", "bad", "good", "skip", "reset", "visualize", "replay", "log", "run"} gitsubcommands["notes"]={"add", "append", "copy", "edit", "list", "prune", "remove", "show"} gitsubcommands["reflog"]={"show", "delete", "expire"} gitsubcommands["rerere"]={"clear", "forget", "diff", "remaining", "status", "gc"} gitsubcommands["stash"]={"save", "list", "show", "apply", "clear", "drop", "pop", "create", "branch"} gitsubcommands["submodule"]={"add", "status", "init", "deinit", "update", "summary", "foreach", "sync"} gitsubcommands["svn"]={"init", "fetch", "clone", "rebase", "dcommit", "log", "find-rev", "set-tree", "commit-diff", "info", "create-ignore", "propget", "proplist", "show-ignore", "show-externals", "branch", "tag", "blame", "migrate", "mkdirs", "reset", "gc"} gitsubcommands["worktree"]={"add", "list", "lock", "prune", "unlock"} -- branch -- checkout gitsubcommands["checkout"]=checkoutlist -- branch select only gitsubcommands["branch"]=branchlist gitsubcommands["switch"]=branchlist gitsubcommands["reset"]=branchlist gitsubcommands["merge"]=branchlist gitsubcommands["rebase"]=branchlist gitsubcommands["revert"]=branchlist -- current branch's commit gitsubcommands["show"]=getcommits -- add unstage file gitsubcommands["add"]=addlist local gitvar=share.git gitvar.subcommand=gitsubcommands gitvar.commit=getcommits gitvar.branch=branchlist gitvar.currentbranch=currentbranch share.git=gitvar if not share.maincmds then use "subcomplete.lua" end if share.maincmds and share.maincmds["git"] then -- git command complementation exists. nyagos.complete_for.git = function(args) while #args > 2 and args[2]:sub(1,1) == "-" do table.remove(args,2) end if #args == 2 then return share.maincmds.git end local subcmd = table.remove(args,2) while #args > 2 and args[2]:sub(1,1) == "-" do table.remove(args,2) end local t = share.git.subcommand[subcmd] if type(t) == "function" then return t(args) elseif type(t) == "table" and #args == 2 then return t end end end -- EOF
if not nyagos then print("This is a script for nyagos not lua.exe") os.exit() end -- hub exists, replace git command local hubpath=nyagos.which("hub.exe") if hubpath then nyagos.alias.git = "hub.exe" end share.git = {} local getcommits = function(args) local fd=io.popen("git log --format=\"%h\" -n 20 2>nul","r") if not fd then return {} end local result={} for line in fd:lines() do result[#result+1] = line end fd:close() return result end -- setup local branch listup local branchlist = function(args) if string.find(args[#args],"[/\\\\]") then return nil end local gitbranches = getcommits() local gitbranch_tmp = nyagos.eval('git for-each-ref --format="%(refname:short)" refs/heads/ 2> nul') for line in gitbranch_tmp:gmatch('[^\n]+') do table.insert(gitbranches,line) end return gitbranches end local unquote = function(s) s = string.gsub(s,'"','') return string.gsub(s,'\\[0-7][0-7][0-7]',function(t) return string.char(tonumber(string.sub(t,2),8)) end) end local isUnderUntrackedDir = function(arg,files) local matched_count=0 local last_matched local upper_arg = string.upper(arg) local upper_arg_len = string.len(upper_arg) for i=1,#files do if string.upper(string.sub(files[i],1,upper_arg_len)) == upper_arg then matched_count = matched_count + 1 last_matched = files[i] end end if matched_count == 1 and string.match(last_matched,"/$") then return true elseif matched_count < 1 then return true end return false end local addlist = function(args) local fd = io.popen("git status -s 2>nul","r") if not fd then return nil end local files = {} for line in fd:lines() do local arrowStart,arrowEnd = string.find(line," -> ",1,true) if arrowStart then files[#files+1] = unquote(string.sub(line,4,arrowStart-1)) files[#files+1] = unquote(string.sub(line,arrowEnd+1)) else files[#files+1] = unquote(string.sub(line,4)) end end fd:close() if isUnderUntrackedDir(args[#args],files) then return nil end return files end local checkoutlist = function(args) local result = branchlist(args) or {} local fd = io.popen("git status -s 2>nul","r") if fd then for line in fd:lines() do if string.sub(line,1,2) == " M" then result[1+#result] = unquote(string.sub(line,4)) end end fd:close() end return result end --setup current branch string local currentbranch = function() return nyagos.eval('git rev-parse --abbrev-ref HEAD 2> nul') end -- subcommands local gitsubcommands={} -- see https://github.com/git/git/blob/master/command-list.txt -- list-up `$git --list-cmds=list-history` for history group subcommands. -- TODO: feature working in the future -- 1. List up subcommands for each groups. -- 2. Assign function for these subcommands, that function is completion function worked as supported multi groups type. -- keyword (sort alphabetical, currently manual pickup) gitsubcommands["bisect"]={"bad", "good", "help", "log", "new", "old", "replay", "reset", "run", "skip", "start", "terms", "view", "visualize"} gitsubcommands["notes"]={"add", "append", "copy", "edit", "get-ref", "list", "merge", "merge", "merge", "prune", "remove", "show"} gitsubcommands["reflog"]={"delete", "exists", "expire", "show"} gitsubcommands["rerere"]={"clear", "diff", "forget", "gc", "remaining", "status"} gitsubcommands["stash"]={"apply", "branch", "clear", "create", "drop", "list", "pop", "push", "show", "store"} gitsubcommands["submodule"]={"absorbgitdirs", "add", "deinit", "foreach", "init", "set-branch", "set-url", "status", "summary", "sync", "update"} gitsubcommands["svn"]={"blame", "branch", "clone", "commit-diff", "create-ignore", "dcommit", "fetch", "find-rev", "gc", "info", "init", "log", "mkdirs", "propget", "proplist", "propset", "rebase", "reset", "set-tree", "show-externals", "show-ignore", "tag"} gitsubcommands["worktree"]={"add", "list", "lock", "move", "prune", "remove", "repair", "unlock"} -- completion function apply -- checkout gitsubcommands["checkout"]=checkoutlist -- branch select only gitsubcommands["branch"]=branchlist gitsubcommands["switch"]=branchlist gitsubcommands["reset"]=branchlist gitsubcommands["merge"]=branchlist gitsubcommands["rebase"]=branchlist gitsubcommands["revert"]=branchlist -- current branch's commit gitsubcommands["show"]=getcommits -- add unstage file gitsubcommands["add"]=addlist local gitvar=share.git gitvar.subcommand=gitsubcommands gitvar.commit=getcommits gitvar.branch=branchlist gitvar.currentbranch=currentbranch share.git=gitvar if not share.maincmds then use "subcomplete.lua" end if share.maincmds and share.maincmds["git"] then -- git command complementation exists. nyagos.complete_for.git = function(args) while #args > 2 and args[2]:sub(1,1) == "-" do table.remove(args,2) end if #args == 2 then return share.maincmds.git end local subcmd = table.remove(args,2) while #args > 2 and args[2]:sub(1,1) == "-" do table.remove(args,2) end local t = share.git.subcommand[subcmd] if type(t) == "function" then return t(args) elseif type(t) == "table" and #args == 2 then return t end end end -- EOF
git.lua: fixup keyword completion for 2021/11/07 document and commented feature work
git.lua: fixup keyword completion for 2021/11/07 document and commented feature work
Lua
bsd-3-clause
tsuyoshicho/nyagos
a4dbd2df925eb1bdc8fdf286f1615f49355e42db
mods/00_bt_armor/throwing/tnt_arrow.lua
mods/00_bt_armor/throwing/tnt_arrow.lua
minetest.register_craftitem("throwing:arrow_tnt", { description = "TNT Arrow", inventory_image = "throwing_arrow_tnt.png", }) minetest.register_node("throwing:arrow_tnt_box", { drawtype = "nodebox", node_box = { type = "fixed", fixed = { -- Shaft {-6.5/17, -1.5/17, -1.5/17, 6.5/17, 1.5/17, 1.5/17}, --Spitze {-4.5/17, 2.5/17, 2.5/17, -3.5/17, -2.5/17, -2.5/17}, {-8.5/17, 0.5/17, 0.5/17, -6.5/17, -0.5/17, -0.5/17}, --Federn {6.5/17, 1.5/17, 1.5/17, 7.5/17, 2.5/17, 2.5/17}, {7.5/17, -2.5/17, 2.5/17, 6.5/17, -1.5/17, 1.5/17}, {7.5/17, 2.5/17, -2.5/17, 6.5/17, 1.5/17, -1.5/17}, {6.5/17, -1.5/17, -1.5/17, 7.5/17, -2.5/17, -2.5/17}, {7.5/17, 2.5/17, 2.5/17, 8.5/17, 3.5/17, 3.5/17}, {8.5/17, -3.5/17, 3.5/17, 7.5/17, -2.5/17, 2.5/17}, {8.5/17, 3.5/17, -3.5/17, 7.5/17, 2.5/17, -2.5/17}, {7.5/17, -2.5/17, -2.5/17, 8.5/17, -3.5/17, -3.5/17}, } }, tiles = {"throwing_arrow_tnt.png", "throwing_arrow_tnt.png", "throwing_arrow_tnt_back.png", "throwing_arrow_tnt_front.png", "throwing_arrow_tnt_2.png", "throwing_arrow_tnt.png"}, groups = {not_in_creative_inventory=1}, }) local THROWING_ARROW_ENTITY={ physical = false, timer=0, visual = "wielditem", visual_size = {x=0.1, y=0.1}, textures = {"throwing:arrow_tnt_box"}, lastpos={}, collisionbox = {0,0,0,0,0,0}, } THROWING_ARROW_ENTITY.on_step = function(self, dtime) self.timer=self.timer+dtime local pos = self.object:getpos() local node = minetest.env:get_node(pos) if self.timer>0.2 then local objs = minetest.env:get_objects_inside_radius({x=pos.x,y=pos.y,z=pos.z}, 2) for k, obj in pairs(objs) do if obj:get_luaentity() ~= nil then if obj:get_luaentity().name ~= "throwing:arrow_tnt_entity" and obj:get_luaentity().name ~= "__builtin:item" then print(playerArrows[self.object]) local damage = 5 obj:punch(self.object, 1.0, { full_punch_interval=1.0, damage_groups={fleshy=damage}, }, nil) tnt.boom(pos, { radius = 3, damage_radius = 5, ignore_protection = false, ignore_on_blast = false }) throwing.playerArrows[self.object] = nil self.object:remove() end else print(playerArrows[self.object]) local damage = 5 obj:punch(self.object, 1.0, { full_punch_interval=1.0, damage_groups={fleshy=damage}, }, nil) tnt.boom(pos, { radius = 3, damage_radius = 5, ignore_protection = false, ignore_on_blast = true }) throwing.playerArrows[self.object] = nil self.object:remove() end end end if self.lastpos.x~=nil then if node.name ~= "air" then print(playerArrows[self.object]) throwing.playerArrows[self.object] = nil self.object:remove() tnt.boom(self.lastpos, { radius = 3, damage_radius = 5, ignore_protection = false, ignore_on_blast = true }) end end self.lastpos={x=pos.x, y=pos.y, z=pos.z} end minetest.register_entity("throwing:arrow_tnt_entity", THROWING_ARROW_ENTITY) minetest.register_craft({ output = "throwing:arrow_tnt 1", recipe = { {"default:obsidian_shard", "default:obsidian_shard", "tnt:tnt"}, }, replacements = { {"bucket:bucket_lava", "bucket:bucket_empty"} } })
minetest.register_craftitem("throwing:arrow_tnt", { description = "TNT Arrow", inventory_image = "throwing_arrow_tnt.png", }) minetest.register_node("throwing:arrow_tnt_box", { drawtype = "nodebox", node_box = { type = "fixed", fixed = { -- Shaft {-6.5/17, -1.5/17, -1.5/17, 6.5/17, 1.5/17, 1.5/17}, --Spitze {-4.5/17, 2.5/17, 2.5/17, -3.5/17, -2.5/17, -2.5/17}, {-8.5/17, 0.5/17, 0.5/17, -6.5/17, -0.5/17, -0.5/17}, --Federn {6.5/17, 1.5/17, 1.5/17, 7.5/17, 2.5/17, 2.5/17}, {7.5/17, -2.5/17, 2.5/17, 6.5/17, -1.5/17, 1.5/17}, {7.5/17, 2.5/17, -2.5/17, 6.5/17, 1.5/17, -1.5/17}, {6.5/17, -1.5/17, -1.5/17, 7.5/17, -2.5/17, -2.5/17}, {7.5/17, 2.5/17, 2.5/17, 8.5/17, 3.5/17, 3.5/17}, {8.5/17, -3.5/17, 3.5/17, 7.5/17, -2.5/17, 2.5/17}, {8.5/17, 3.5/17, -3.5/17, 7.5/17, 2.5/17, -2.5/17}, {7.5/17, -2.5/17, -2.5/17, 8.5/17, -3.5/17, -3.5/17}, } }, tiles = {"throwing_arrow_tnt.png", "throwing_arrow_tnt.png", "throwing_arrow_tnt_back.png", "throwing_arrow_tnt_front.png", "throwing_arrow_tnt_2.png", "throwing_arrow_tnt.png"}, groups = {not_in_creative_inventory=1}, }) local THROWING_ARROW_ENTITY={ physical = false, timer=0, visual = "wielditem", visual_size = {x=0.1, y=0.1}, textures = {"throwing:arrow_tnt_box"}, lastpos={}, collisionbox = {0,0,0,0,0,0}, } THROWING_ARROW_ENTITY.on_step = function(self, dtime) self.timer=self.timer+dtime local pos = self.object:getpos() local node = minetest.env:get_node(pos) if self.timer>0.2 then local objs = minetest.env:get_objects_inside_radius({x=pos.x,y=pos.y,z=pos.z}, 2) for k, obj in pairs(objs) do if obj:get_luaentity() ~= nil then if obj:get_luaentity().name ~= "throwing:arrow_tnt_entity" and obj:get_luaentity().name ~= "__builtin:item" then local damage = 5 obj:punch(self.object, 1.0, { full_punch_interval=1.0, damage_groups={fleshy=damage}, }, nil) tnt.boom(pos, { radius = 3, damage_radius = 5, ignore_protection = false, ignore_on_blast = false }) throwing.playerArrows[self.object] = nil self.object:remove() end else local damage = 5 obj:punch(self.object, 1.0, { full_punch_interval=1.0, damage_groups={fleshy=damage}, }, nil) tnt.boom(pos, { radius = 3, damage_radius = 5, ignore_protection = false, ignore_on_blast = true }) throwing.playerArrows[self.object] = nil self.object:remove() end end end if self.lastpos.x~=nil then if node.name ~= "air" then print(playerArrows[self.object]) throwing.playerArrows[self.object] = nil self.object:remove() tnt.boom(self.lastpos, { radius = 3, damage_radius = 5, ignore_protection = false, ignore_on_blast = true }) end end self.lastpos={x=pos.x, y=pos.y, z=pos.z} end minetest.register_entity("throwing:arrow_tnt_entity", THROWING_ARROW_ENTITY) minetest.register_craft({ output = "throwing:arrow_tnt 1", recipe = { {"default:obsidian_shard", "default:obsidian_shard", "tnt:tnt"}, }, replacements = { {"bucket:bucket_lava", "bucket:bucket_empty"} } })
Fix of the TNT arrow printing and referring to the wrong table
Fix of the TNT arrow printing and referring to the wrong table
Lua
lgpl-2.1
evrooije/beerarchy,evrooije/beerarchy,evrooije/beerarchy
f552fbc36476b4c2949986ebc2ed8fc82aa137b9
applications/luci-wol/luasrc/model/cbi/wol.lua
applications/luci-wol/luasrc/model/cbi/wol.lua
--[[ LuCI - Lua Configuration Interface Copyright 2010 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local uci = require "luci.model.uci".cursor() local utl = require "luci.util" local sys = require "luci.sys" local fs = require "nixio.fs" m = SimpleForm("wol", translate("Wake on LAN"), translate("Wake on LAN is a mechanism to remotely boot computers in the local network.")) m.submit = translate("Wake up host") m.reset = false local has_ewk = fs.access("/usr/bin/etherwake") local has_wol = fs.access("/usr/bin/wol") s = m:section(SimpleSection) local arp = { } local e, ip, mac, name if has_ewk and has_wol then bin = s:option(ListValue, "binary", translate("WoL program"), translate("Sometimes only one of both tools work. If one of fails, try the other one")) bin:value("/usr/bin/etherwake", "Etherwake") bin:value("/usr/bin/wol", "WoL") end if has_ewk then iface = s:option(ListValue, "iface", translate("Network interface to use"), translate("Specifies the interface the WoL packet is sent on")) if has_wol then iface:depends("binary", "/usr/bin/etherwake") end iface:value("", translate("Broadcast on all interfaces")) for _, e in ipairs(sys.net.devices()) do if e ~= "lo" then iface:value(e) end end end for _, e in ipairs(sys.net.arptable()) do arp[e["HW address"]:upper()] = { e["IP address"] } end for e in io.lines("/etc/ethers") do mac, ip = e:match("^([a-f0-9]%S+) (%S+)") if mac and ip then arp[mac:upper()] = { ip } end end for e in io.lines("/var/dhcp.leases") do mac, ip, name = e:match("^%d+ (%S+) (%S+) (%S+)") if mac and ip then arp[mac:upper()] = { ip, name ~= "*" and name } end end uci:foreach("dhcp", "host", function(s) if s.mac and s.ip then arp[s.mac:upper()] = { s.ip, s.name } end end) host = s:option(Value, "mac", translate("Host to wake up"), translate("Choose the host to wake up or enter a custom MAC address to use")) for mac, ip in utl.kspairs(arp) do host:value(mac, "%s (%s)" %{ mac, ip[2] or ip[1] }) end function host.write(self, s, val) local host = luci.http.formvalue("cbid.wol.1.mac") if host and #host > 0 then local cmd local util = luci.http.formvalue("cbid.wol.1.binary") or ( has_ewk and "/usr/bin/etherwake" or "/usr/bin/wol" ) if util == "/usr/bin/etherwake" then local iface = luci.http.formvalue("cbid.wol.1.iface") cmd = "%s -D%s %q" %{ util, (iface ~= "" and " -i %q" % iface or ""), host } else cmd = "%s -v %q" %{ util, host } end local msg = "<p><strong>%s</strong><br /><br /><code>%s<br /><br />" %{ translate("Starting WoL utility:"), cmd } local p = io.popen(cmd .. " 2>&1") if p then while true do local l = p:read("*l") if l then if #l > 100 then l = l:sub(1, 100) .. "..." end msg = msg .. l .. "<br />" else break end end p:close() end msg = msg .. "</code></p>" m.message = msg end end return m
--[[ LuCI - Lua Configuration Interface Copyright 2010 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local uci = require "luci.model.uci".cursor() local utl = require "luci.util" local sys = require "luci.sys" local fs = require "nixio.fs" m = SimpleForm("wol", translate("Wake on LAN"), translate("Wake on LAN is a mechanism to remotely boot computers in the local network.")) m.submit = translate("Wake up host") m.reset = false local has_ewk = fs.access("/usr/bin/etherwake") local has_wol = fs.access("/usr/bin/wol") s = m:section(SimpleSection) local arp = { } local e, ip, mac, name if has_ewk and has_wol then bin = s:option(ListValue, "binary", translate("WoL program"), translate("Sometimes only one of both tools work. If one of fails, try the other one")) bin:value("/usr/bin/etherwake", "Etherwake") bin:value("/usr/bin/wol", "WoL") end if has_ewk then iface = s:option(ListValue, "iface", translate("Network interface to use"), translate("Specifies the interface the WoL packet is sent on")) if has_wol then iface:depends("binary", "/usr/bin/etherwake") end iface:value("", translate("Broadcast on all interfaces")) for _, e in ipairs(sys.net.devices()) do if e ~= "lo" then iface:value(e) end end end for _, e in ipairs(sys.net.arptable()) do arp[e["HW address"]:upper()] = { e["IP address"] } end for e in io.lines("/etc/ethers") do mac, ip = e:match("^([a-f0-9]%S+) (%S+)") if mac and ip then arp[mac:upper()] = { ip } end end for e in io.lines("/var/dhcp.leases") do mac, ip, name = e:match("^%d+ (%S+) (%S+) (%S+)") if mac and ip then arp[mac:upper()] = { ip, name ~= "*" and name } end end uci:foreach("dhcp", "host", function(s) if s.mac and s.ip then arp[s.mac:upper()] = { s.ip, s.name } end end) host = s:option(Value, "mac", translate("Host to wake up"), translate("Choose the host to wake up or enter a custom MAC address to use")) for mac, ip in utl.kspairs(arp) do host:value(mac, "%s (%s)" %{ mac, ip[2] or ip[1] }) end function host.write(self, s, val) local host = luci.http.formvalue("cbid.wol.1.mac") if host and #host > 0 and host:match("^[a-fA-F0-9:]+$") then local cmd local util = luci.http.formvalue("cbid.wol.1.binary") or ( has_ewk and "/usr/bin/etherwake" or "/usr/bin/wol" ) if util == "/usr/bin/etherwake" then local iface = luci.http.formvalue("cbid.wol.1.iface") cmd = "%s -D%s %q" %{ util, (iface ~= "" and " -i %q" % iface or ""), host } else cmd = "%s -v %q" %{ util, host } end local msg = "<p><strong>%s</strong><br /><br /><code>%s<br /><br />" %{ translate("Starting WoL utility:"), cmd } local p = io.popen(cmd .. " 2>&1") if p then while true do local l = p:read("*l") if l then if #l > 100 then l = l:sub(1, 100) .. "..." end msg = msg .. l .. "<br />" else break end end p:close() end msg = msg .. "</code></p>" m.message = msg end end return m
applications/luci-wol: fix XSS
applications/luci-wol: fix XSS
Lua
apache-2.0
deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci
b6c0bdfbf692e9b76fa766654cd0c4d2f3cff152
eqn/mhd.lua
eqn/mhd.lua
local class = require 'ext.class' local table = require 'ext.table' local file = require 'ext.file' local template = require 'template' local Equation = require 'eqn.eqn' local MHD = class(Equation) MHD.name = 'MHD' MHD.numStates = 8 MHD.numWaves = 7 MHD.consVars = {'rho', 'mx', 'my', 'mz', 'ETotal', 'bx', 'by', 'bz'} MHD.primVars = {'rho', 'vx', 'vy', 'vz', 'P', 'bx', 'by', 'bz'} MHD.mirrorVars = {{'m.x', 'b.x'}, {'m.y', 'b.y'}, {'m.z', 'b.z'}} MHD.hasEigenCode = true -- hmm, we want init.euler and init.mhd here ... MHD.initStates = require 'init.euler' local GuiFloat = require 'guivar.float' MHD.guiVars = table{ GuiFloat{name='heatCapacityRatio', value=2}, -- 5/3 for most problems, but 2 for Brio-Wu, so I will just set it here for now (in case something else is reading it before it is set there) GuiFloat{name='mu0', value=1}, } function MHD:getTypeCode() return [[ typedef struct { real rho; real3 v; real P; real3 b; } prim_t; typedef union { real ptr[8]; struct { real rho; real3 m; real ETotal; real3 b; }; } cons_t; ]] end function MHD:getCodePrefix() return table{ MHD.super.getCodePrefix(self), [[ inline real calc_eKin(prim_t W) { return .5 * real3_lenSq(W.v); } inline real calc_EKin(prim_t W) { return W.rho * calc_eKin(W); } inline real calc_EInt(prim_t W) { return W.P / (heatCapacityRatio - 1.); } inline real calc_eInt(prim_t W) { return calc_EInt(W) / W.rho; } inline real calc_EMag(prim_t W) { return .5 * real3_lenSq(W.b); } inline real calc_eMag(prim_t W) { return calc_EMag(W) / W.rho; } inline real calc_PMag(prim_t W) { return .5 * real3_lenSq(W.b); } inline real calc_EHydro(prim_t W) { return calc_EKin(W) + calc_EInt(W); } inline real calc_eHydro(prim_t W) { return calc_EHydro(W) / W.rho; } inline real calc_ETotal(prim_t W) { return calc_EKin(W) + calc_EInt(W) + calc_EMag(W); } inline real calc_eTotal(prim_t W) { return calc_ETotal(W) / W.rho; } inline real calc_H(real P) { return P * (heatCapacityRatio / (heatCapacityRatio - 1.)); } inline real calc_h(real rho, real P) { return calc_H(P) / rho; } inline real calc_HTotal(prim_t W, real ETotal) { return W.P + calc_PMag(W) + ETotal; } inline real calc_hTotal(prim_t W, real ETotal) { return calc_HTotal(W, ETotal) / W.rho; } inline real calc_Cs(prim_t W) { return sqrt(heatCapacityRatio * W.P / W.rho); } inline prim_t primFromCons(cons_t U) { prim_t W; W.rho = U.rho; W.v = real3_scale(U.m, 1./U.rho); W.b = U.b; real vSq = real3_lenSq(W.v); real bSq = real3_lenSq(W.b); real EKin = .5 * U.rho * vSq; real EMag = .5 * bSq; real EInt = U.ETotal - EKin - EMag; W.P = EInt * (heatCapacityRatio - 1.); W.P = max(W.P, 1e-7); W.rho = max(W.rho, 1e-7); return W; } inline cons_t consFromPrim(prim_t W) { cons_t U; U.rho = W.rho; U.m = real3_scale(W.v, W.rho); U.b = W.b; real vSq = real3_lenSq(W.v); real bSq = real3_lenSq(W.b); real EKin = .5 * W.rho * vSq; real EMag = .5 * bSq; real EInt = W.P / (heatCapacityRatio - 1.); U.ETotal = EInt + EKin + EMag; return U; } ]], }:concat'\n' end function MHD:getInitStateCode(solver) local initState = self.initStates[1+solver.initStatePtr[0]] assert(initState, "couldn't find initState "..solver.initStatePtr[0]) local code = initState.init(solver) return [[ kernel void initState( global cons_t* UBuf ) { SETBOUNDS(0,0); real3 x = cell_x(i); real3 mids = real3_scale(real3_add(mins, maxs), .5); bool lhs = x.x < mids.x #if dim > 1 && x.y < mids.y #endif #if dim > 2 && x.z < mids.z #endif ; real rho = 0; real3 v = _real3(0,0,0); real P = 0; real3 b = _real3(0,0,0); ]]..code..[[ prim_t W = {.rho=rho, .v=v, .P=P, .b=b}; UBuf[index] = consFromPrim(W); } ]] end function MHD:getSolverCode(solver) return template(file['eqn/mhd.cl'], {eqn=self, solver=solver}) end MHD.displayVarCodePrefix = [[ cons_t U = buf[index]; prim_t W = primFromCons(U); ]] function MHD:getDisplayVars(solver) return { {rho = 'value = W.rho;'}, {vx = 'value = W.v.x;'}, {vy = 'value = W.v.y;'}, {vz = 'value = W.v.z;'}, {v = 'value = real3_len(W.v);'}, {mx = 'value = U.m.x;'}, {my = 'value = U.m.y;'}, {mz = 'value = U.m.z;'}, {m = 'value = real3_len(U.m);'}, {bx = 'value = W.b.x;'}, {by = 'value = W.b.y;'}, {bz = 'value = W.b.z;'}, {b = 'value = real3_len(W.b);'}, {P = 'value = W.P;'}, --{PMag = 'value = calc_PMag(W);'}, --{PTotal = 'value = W.P + calc_PMag(W);'}, --{eInt = 'value = calc_eInt(W);'}, {EInt = 'value = calc_EInt(W);'}, --{eKin = 'value = calc_eKin(W);'}, {EKin = 'value = calc_EKin(W);'}, --{eHydro = 'value = calc_eHydro(W);'}, {EHydro = 'value = calc_EHydro(W);'}, --{eMag = 'value = calc_eMag(W);'}, {EMag = 'value = calc_EMag(W);'}, --{eTotal = 'value = U.ETotal / W.rho;'}, {ETotal = 'value = U.ETotal;'}, {S = 'value = W.P / pow(W.rho, (real)heatCapacityRatio);'}, {H = 'value = calc_H(W.P);'}, --{h = 'value = calc_H(W.P) / W.rho;'}, --{HTotal = 'value = calc_HTotal(W, U.ETotal);'}, --{hTotal = 'value = calc_hTotal(W, U.ETotal);'}, --{Cs = 'value = calc_Cs(W); }, {['primitive reconstruction error'] = [[ //prim have just been reconstructed from cons //so reconstruct cons from prims again and calculate the difference cons_t U2 = consFromPrim(W); value = 0; for (int j = 0; j < numStates; ++j) { value += fabs(U.ptr[j] - U2.ptr[j]); } ]]}, } end function Equation:getEigenTypeCode(solver) return template([[ typedef struct { real evL[7*7]; real evR[7*7]; <? if solver.checkFluxError then ?> real A[7*7]; <? end ?> } eigen_t; ]], { solver = solver, }) end return MHD
local class = require 'ext.class' local table = require 'ext.table' local file = require 'ext.file' local template = require 'template' local Equation = require 'eqn.eqn' local MHD = class(Equation) MHD.name = 'MHD' MHD.numStates = 8 MHD.numWaves = 7 MHD.consVars = {'rho', 'mx', 'my', 'mz', 'ETotal', 'bx', 'by', 'bz'} MHD.primVars = {'rho', 'vx', 'vy', 'vz', 'P', 'bx', 'by', 'bz'} MHD.mirrorVars = {{'m.x', 'b.x'}, {'m.y', 'b.y'}, {'m.z', 'b.z'}} MHD.hasEigenCode = true -- hmm, we want init.euler and init.mhd here ... MHD.initStates = require 'init.euler' local GuiFloat = require 'guivar.float' MHD.guiVars = table{ GuiFloat{name='heatCapacityRatio', value=2}, -- 5/3 for most problems, but 2 for Brio-Wu, so I will just set it here for now (in case something else is reading it before it is set there) GuiFloat{name='mu0', value=1}, } function MHD:getTypeCode() return [[ typedef struct { real rho; real3 v; real P; real3 b; } prim_t; typedef union { real ptr[8]; struct { real rho; real3 m; real3 b; real ETotal; }; } cons_t; ]] end function MHD:getCodePrefix() return table{ MHD.super.getCodePrefix(self), [[ inline real calc_eKin(prim_t W) { return .5 * real3_lenSq(W.v); } inline real calc_EKin(prim_t W) { return W.rho * calc_eKin(W); } inline real calc_EInt(prim_t W) { return W.P / (heatCapacityRatio - 1.); } inline real calc_eInt(prim_t W) { return calc_EInt(W) / W.rho; } inline real calc_EMag(prim_t W) { return .5 * real3_lenSq(W.b); } inline real calc_eMag(prim_t W) { return calc_EMag(W) / W.rho; } inline real calc_PMag(prim_t W) { return .5 * real3_lenSq(W.b); } inline real calc_EHydro(prim_t W) { return calc_EKin(W) + calc_EInt(W); } inline real calc_eHydro(prim_t W) { return calc_EHydro(W) / W.rho; } inline real calc_ETotal(prim_t W) { return calc_EKin(W) + calc_EInt(W) + calc_EMag(W); } inline real calc_eTotal(prim_t W) { return calc_ETotal(W) / W.rho; } inline real calc_H(real P) { return P * (heatCapacityRatio / (heatCapacityRatio - 1.)); } inline real calc_h(real rho, real P) { return calc_H(P) / rho; } inline real calc_HTotal(prim_t W, real ETotal) { return W.P + calc_PMag(W) + ETotal; } inline real calc_hTotal(prim_t W, real ETotal) { return calc_HTotal(W, ETotal) / W.rho; } inline real calc_Cs(prim_t W) { return sqrt(heatCapacityRatio * W.P / W.rho); } inline prim_t primFromCons(cons_t U) { prim_t W; W.rho = U.rho; W.v = real3_scale(U.m, 1./U.rho); W.b = U.b; real vSq = real3_lenSq(W.v); real bSq = real3_lenSq(W.b); real EKin = .5 * U.rho * vSq; real EMag = .5 * bSq; real EInt = U.ETotal - EKin - EMag; W.P = EInt * (heatCapacityRatio - 1.); //these are causing ETotal to get errors in prim reconstruction //but they're in the Lua version, which has no such problem W.P = max(W.P, 1e-7); W.rho = max(W.rho, 1e-7); return W; } inline cons_t consFromPrim(prim_t W) { cons_t U; U.rho = W.rho; U.m = real3_scale(W.v, W.rho); U.b = W.b; real vSq = real3_lenSq(W.v); real bSq = real3_lenSq(W.b); real EKin = .5 * W.rho * vSq; real EMag = .5 * bSq; real EInt = W.P / (heatCapacityRatio - 1.); U.ETotal = EInt + EKin + EMag; return U; } ]], }:concat'\n' end function MHD:getInitStateCode(solver) local initState = self.initStates[1+solver.initStatePtr[0]] assert(initState, "couldn't find initState "..solver.initStatePtr[0]) local code = initState.init(solver) return [[ kernel void initState( global cons_t* UBuf ) { SETBOUNDS(0,0); real3 x = cell_x(i); real3 mids = real3_scale(real3_add(mins, maxs), .5); bool lhs = x.x < mids.x #if dim > 1 && x.y < mids.y #endif #if dim > 2 && x.z < mids.z #endif ; real rho = 0; real3 v = _real3(0,0,0); real P = 0; real3 b = _real3(0,0,0); ]]..code..[[ prim_t W = {.rho=rho, .v=v, .P=P, .b=b}; UBuf[index] = consFromPrim(W); } ]] end function MHD:getSolverCode(solver) return template(file['eqn/mhd.cl'], {eqn=self, solver=solver}) end MHD.displayVarCodePrefix = [[ cons_t U = buf[index]; prim_t W = primFromCons(U); ]] function MHD:getDisplayVars(solver) return table{ {rho = 'value = W.rho;'}, {vx = 'value = W.v.x;'}, {vy = 'value = W.v.y;'}, {vz = 'value = W.v.z;'}, {v = 'value = real3_len(W.v);'}, {mx = 'value = U.m.x;'}, {my = 'value = U.m.y;'}, {mz = 'value = U.m.z;'}, {m = 'value = real3_len(U.m);'}, {bx = 'value = W.b.x;'}, {by = 'value = W.b.y;'}, {bz = 'value = W.b.z;'}, {b = 'value = real3_len(W.b);'}, {P = 'value = W.P;'}, --{PMag = 'value = calc_PMag(W);'}, --{PTotal = 'value = W.P + calc_PMag(W);'}, --{eInt = 'value = calc_eInt(W);'}, {EInt = 'value = calc_EInt(W);'}, --{eKin = 'value = calc_eKin(W);'}, {EKin = 'value = calc_EKin(W);'}, --{eHydro = 'value = calc_eHydro(W);'}, {EHydro = 'value = calc_EHydro(W);'}, --{eMag = 'value = calc_eMag(W);'}, {EMag = 'value = calc_EMag(W);'}, --{eTotal = 'value = U.ETotal / W.rho;'}, {ETotal = 'value = U.ETotal;'}, {S = 'value = W.P / pow(W.rho, (real)heatCapacityRatio);'}, {H = 'value = calc_H(W.P);'}, --{h = 'value = calc_H(W.P) / W.rho;'}, --{HTotal = 'value = calc_HTotal(W, U.ETotal);'}, --{hTotal = 'value = calc_hTotal(W, U.ETotal);'}, --{Cs = 'value = calc_Cs(W); }, {['primitive reconstruction error'] = [[ //prim have just been reconstructed from cons //so reconstruct cons from prims again and calculate the difference cons_t U2 = consFromPrim(W); value = 0; for (int j = 0; j < numStates; ++j) { value += fabs(U.ptr[j] - U2.ptr[j]); } ]]}, }:append(require 'ext.range'(8):map(function(i) return { ['cons '..i..' primitive reconstruction error'] = template([[ cons_t U2 = consFromPrim(W); value = U2.ptr[<?=i-1?>] - U.ptr[<?=i-1?>]; ]], { i = i, })} end)) end function MHD:getEigenTypeCode(solver) return template([[ typedef struct { real evL[7*7]; real evR[7*7]; <? if solver.checkFluxError then ?> real A[7*7]; <? end ?> } eigen_t; ]], { solver = solver, }) end return MHD
found another bug
found another bug
Lua
mit
thenumbernine/hydro-cl-lua,thenumbernine/hydro-cl-lua,thenumbernine/hydro-cl-lua
d2536d8b7e9474bd7748b199d1f01a53f332942a
platform/android/llapp_main.lua
platform/android/llapp_main.lua
local A = require("android") A.dl.library_path = A.dl.library_path .. ":" .. A.dir .. "/libs" local ffi = require("ffi") local dummy = require("ffi/posix_h") local C = ffi.C -- check uri of the intent that starts this application local file = A.getIntent() if file ~= nil then A.LOGI("intent file path " .. file) end -- run koreader patch before koreader startup pcall(dofile, "/sdcard/koreader/patch.lua") -- set proper permission for binaries A.execute("chmod", "755", "./sdcv") A.execute("chmod", "755", "./tar") A.execute("chmod", "755", "./zsync") -- set TESSDATA_PREFIX env var C.setenv("TESSDATA_PREFIX", "/sdcard/koreader/data", 1) -- create fake command-line arguments if A.isDebuggable() then arg = {"-d", file or "/sdcard"} else arg = {file or "/sdcard"} end dofile(A.dir.."/reader.lua")
local android = require("android") android.dl.library_path = android.dl.library_path .. ":" .. android.dir .. "/libs" local ffi = require("ffi") local dummy = require("ffi/posix_h") local C = ffi.C -- check uri of the intent that starts this application local file = android.getIntent() if file ~= nil then android.LOGI("intent file path " .. file) end -- run koreader patch before koreader startup pcall(dofile, "/sdcard/koreader/patch.lua") -- set TESSDATA_PREFIX env var C.setenv("TESSDATA_PREFIX", "/sdcard/koreader/data", 1) -- create fake command-line arguments -- luacheck: ignore 121 if android.isDebuggable() then arg = {"-d", file or "/sdcard"} else arg = {file or "/sdcard"} end dofile(android.dir.."/reader.lua")
android: fix some warnings on launcher script, no need to chmod binaries as they are uncompressed on each update, A becomes android
android: fix some warnings on launcher script, no need to chmod binaries as they are uncompressed on each update, A becomes android
Lua
agpl-3.0
koreader/koreader,poire-z/koreader,poire-z/koreader,Frenzie/koreader,Hzj-jie/koreader,Markismus/koreader,NiLuJe/koreader,koreader/koreader,NiLuJe/koreader,mwoz123/koreader,Frenzie/koreader,pazos/koreader,mihailim/koreader
dcb50d38ab8244297124a6532ed23e7ed026da3b
hammerspoon/smart_modifier_keys.lua
hammerspoon/smart_modifier_keys.lua
-- Make the modifiers keys smarter: -- Tap ctrl -> esc. -- Tap shift -> switch input method. -- Whether ctrl and shift is being pressed alone. local ctrlPressed = false local shiftPressed = false local prevModifiers = {} local log = hs.logger.new('smart_modifier_keys','debug') hs.eventtap.new({hs.eventtap.event.types.flagsChanged}, function(e) local events_to_post = nil local modifiers = e:getFlags() local count = 0 for _, __ in pairs(modifiers) do count = count + 1 end -- Check `ctrl` key. if modifiers['ctrl'] and not prevModifiers['ctrl'] and count == 1 then ctrlPressed = true else if count == 0 and ctrlPressed then -- Ctrl was tapped alone, send an esc key. events_to_post = { hs.eventtap.event.newKeyEvent(nil, "escape", true), hs.eventtap.event.newKeyEvent(nil, "escape", false), } end ctrlPressed = false end -- Check `shift` key. if modifiers['shift'] and not prevModifiers['shift'] and count == 1 then shiftPressed = true else if count == 0 and shiftPressed then -- Shift was tapped alone, switch input method (cmd + space). events_to_post = { hs.eventtap.event.newKeyEvent({"cmd"}, "space", true), hs.eventtap.event.newKeyEvent({"cmd"}, "space", false), } end shiftPressed = false end prevModifiers = modifiers return false, events_to_post end):start() hs.eventtap.new({hs.eventtap.event.types.keyDown}, function(e) -- If a non-modifier key is pressed, reset these two flags. ctrlPressed = false shiftPressed = false end):start()
-- Make the modifiers keys smarter: -- Tap ctrl -> esc. -- Tap shift -> switch input method. local module = {} -- Whether ctrl and shift is being pressed alone. module.ctrlPressed = false module.shiftPressed = false module.prevModifiers = {} module.log = hs.logger.new('smart_modifier_keys','debug') module.modifierKeyListener = hs.eventtap.new({hs.eventtap.event.types.flagsChanged}, function(e) local events_to_post = nil local modifiers = e:getFlags() local count = 0 for _, __ in pairs(modifiers) do count = count + 1 end -- Check `ctrl` key. if modifiers['ctrl'] and not module.prevModifiers['ctrl'] and count == 1 then module.ctrlPressed = true else if count == 0 and module.ctrlPressed then -- Ctrl was tapped alone, send an esc key. events_to_post = { hs.eventtap.event.newKeyEvent(nil, "escape", true), hs.eventtap.event.newKeyEvent(nil, "escape", false), } end module.ctrlPressed = false end -- Check `shift` key. if modifiers['shift'] and not module.prevModifiers['shift'] and count == 1 then module.shiftPressed = true else if count == 0 and module.shiftPressed then -- Shift was tapped alone, switch input method (cmd + space). events_to_post = { hs.eventtap.event.newKeyEvent({"cmd"}, "space", true), hs.eventtap.event.newKeyEvent({"cmd"}, "space", false), } end module.shiftPressed = false end module.prevModifiers = modifiers return false, events_to_post end):start() module.normalKeyListener = hs.eventtap.new({hs.eventtap.event.types.keyDown}, function(e) -- If a non-modifier key is pressed, reset these two flags. module.ctrlPressed = false module.shiftPressed = false end):start() return module
Fix listener getting GCed
Fix listener getting GCed
Lua
mit
raulchen/dotfiles,raulchen/dotfiles
9dccbe7792cfdc6ffd56348aa9092004526b3794
MCServer/Plugins/APIDump/Hooks/OnServerPing.lua
MCServer/Plugins/APIDump/Hooks/OnServerPing.lua
(cClientHandle & a_ClientHandle, AString & a_ServerDescription, int & a_OnlinePlayersCount, int & a_MaxPlayersCount, AString & a_Favicon); return { HOOK_SERVER_PING = { CalledWhen = "Client pings the server from the server list.", DefaultFnName = "OnServerPing", -- also used as pagename Desc = [[ A plugin may implement an OnServerPing() function and register it as a Hook to process pings from clients in the server server list. ]], Params = { { Name = "ClientHandle", Type = "{{cClientHandle}}", Notes = "The client handle that pinged the server" }, { Name = "ServerDescription", Type = "string", Notes = "The server description" }, { Name = "OnlinePlayersCount", Type = "number", Notes = "The number of players currently on the server" }, { Name = "MaxPlayersCount", Type = "number", Notes = "The current player cap for the server" }, { Name = "Favicon", Type = "string", Notes = "The base64 encoded favicon to be displayed in the server list for compatible clients" }, }, Returns = [[ The plugin may return a boolean of whether to respond to the client that pinged. ]], }, -- HOOK_SERVER_PING }
return { HOOK_SERVER_PING = { CalledWhen = "Client pings the server from the server list.", DefaultFnName = "OnServerPing", -- also used as pagename Desc = [[ A plugin may implement an OnServerPing() function and register it as a Hook to process pings from clients in the server server list. It can change the logged in players and player capacity, as well as the server description and the favicon by editing the values passed in. ]], Params = { { Name = "ClientHandle", Type = "{{cClientHandle}}", Notes = "The client handle that pinged the server" }, { Name = "ServerDescription", Type = "string", Notes = "The server description" }, { Name = "OnlinePlayersCount", Type = "number", Notes = "The number of players currently on the server" }, { Name = "MaxPlayersCount", Type = "number", Notes = "The current player cap for the server" }, { Name = "Favicon", Type = "string", Notes = "The base64 encoded favicon to be displayed in the server list for compatible clients" }, }, Returns = [[ The plugin may return a boolean. ]], }, -- HOOK_SERVER_PING }
Fixed line left in.
Fixed line left in.
Lua
apache-2.0
ionux/MCServer,mc-server/MCServer,SamOatesPlugins/cuberite,nichwall/cuberite,Frownigami1/cuberite,tonibm19/cuberite,Tri125/MCServer,thetaeo/cuberite,johnsoch/cuberite,zackp30/cuberite,Fighter19/cuberite,zackp30/cuberite,birkett/MCServer,birkett/cuberite,birkett/cuberite,electromatter/cuberite,nichwall/cuberite,mmdk95/cuberite,Tri125/MCServer,birkett/MCServer,mjssw/cuberite,HelenaKitty/EbooMC,thetaeo/cuberite,zackp30/cuberite,marvinkopf/cuberite,linnemannr/MCServer,birkett/MCServer,electromatter/cuberite,Howaner/MCServer,nicodinh/cuberite,mmdk95/cuberite,linnemannr/MCServer,Schwertspize/cuberite,nevercast/cuberite,QUSpilPrgm/cuberite,Fighter19/cuberite,nevercast/cuberite,birkett/cuberite,Tri125/MCServer,Haxi52/cuberite,mc-server/MCServer,Tri125/MCServer,SamOatesPlugins/cuberite,Fighter19/cuberite,thetaeo/cuberite,zackp30/cuberite,tonibm19/cuberite,kevinr/cuberite,jammet/MCServer,birkett/cuberite,nounoursheureux/MCServer,mjssw/cuberite,nounoursheureux/MCServer,johnsoch/cuberite,kevinr/cuberite,HelenaKitty/EbooMC,marvinkopf/cuberite,Frownigami1/cuberite,mc-server/MCServer,Altenius/cuberite,nicodinh/cuberite,linnemannr/MCServer,Howaner/MCServer,Frownigami1/cuberite,marvinkopf/cuberite,bendl/cuberite,johnsoch/cuberite,marvinkopf/cuberite,johnsoch/cuberite,ionux/MCServer,jammet/MCServer,nicodinh/cuberite,tonibm19/cuberite,SamOatesPlugins/cuberite,nounoursheureux/MCServer,bendl/cuberite,zackp30/cuberite,linnemannr/MCServer,electromatter/cuberite,Haxi52/cuberite,nichwall/cuberite,nounoursheureux/MCServer,jammet/MCServer,QUSpilPrgm/cuberite,birkett/MCServer,electromatter/cuberite,SamOatesPlugins/cuberite,marvinkopf/cuberite,mmdk95/cuberite,Frownigami1/cuberite,kevinr/cuberite,guijun/MCServer,birkett/MCServer,SamOatesPlugins/cuberite,kevinr/cuberite,guijun/MCServer,Altenius/cuberite,Howaner/MCServer,guijun/MCServer,nicodinh/cuberite,thetaeo/cuberite,zackp30/cuberite,Fighter19/cuberite,Haxi52/cuberite,nevercast/cuberite,electromatter/cuberite,marvinkopf/cuberite,mmdk95/cuberite,ionux/MCServer,Fighter19/cuberite,jammet/MCServer,mjssw/cuberite,Haxi52/cuberite,jammet/MCServer,mc-server/MCServer,bendl/cuberite,mjssw/cuberite,jammet/MCServer,kevinr/cuberite,Tri125/MCServer,nevercast/cuberite,QUSpilPrgm/cuberite,electromatter/cuberite,tonibm19/cuberite,Haxi52/cuberite,Schwertspize/cuberite,Schwertspize/cuberite,birkett/cuberite,linnemannr/MCServer,Haxi52/cuberite,nichwall/cuberite,guijun/MCServer,mc-server/MCServer,nichwall/cuberite,guijun/MCServer,HelenaKitty/EbooMC,HelenaKitty/EbooMC,Howaner/MCServer,ionux/MCServer,Howaner/MCServer,bendl/cuberite,HelenaKitty/EbooMC,Altenius/cuberite,mmdk95/cuberite,ionux/MCServer,nichwall/cuberite,Tri125/MCServer,nicodinh/cuberite,nicodinh/cuberite,QUSpilPrgm/cuberite,mmdk95/cuberite,mjssw/cuberite,mjssw/cuberite,mc-server/MCServer,Frownigami1/cuberite,Altenius/cuberite,johnsoch/cuberite,Howaner/MCServer,nounoursheureux/MCServer,Schwertspize/cuberite,nounoursheureux/MCServer,kevinr/cuberite,ionux/MCServer,Schwertspize/cuberite,birkett/cuberite,thetaeo/cuberite,linnemannr/MCServer,Altenius/cuberite,bendl/cuberite,tonibm19/cuberite,nevercast/cuberite,QUSpilPrgm/cuberite,guijun/MCServer,QUSpilPrgm/cuberite,thetaeo/cuberite,birkett/MCServer,Fighter19/cuberite,nevercast/cuberite,tonibm19/cuberite
471e73d2037d6875b682651d64d063db5900a50a
share/lua/website/videobash.lua
share/lua/website/videobash.lua
-- libquvi-scripts -- Copyright (C) 2012 Toni Gundogdu <[email protected]> -- Copyright (C) 2011 Thomas Preud'homme <[email protected]> -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -- 02110-1301 USA -- -- Identify the script. function ident(self) package.path = self.script_dir .. '/?.lua' local C = require 'quvi/const' local r = {} r.domain = "videobash%.com" r.formats = "default" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/video_show/"}) return r end -- Query available formats. function query_formats(self) self.formats = 'default' return self end -- Parse media URL. function parse(self) self.host_id = "videobash" local p = quvi.fetch(self.page_url) self.title = p:match("<title>(.-)%s+-") or error ("no match: media title") self.id = p:match("addFavorite%((%d+)") or error ("no match: media ID") local s = p:match('video_url=(.-)&') or error("no match: media URL") local U = require 'quvi/util' self.url = {U.unescape(s)} return self end -- vim: set ts=4 sw=4 tw=72 expandtab:
-- libquvi-scripts -- Copyright (C) 2012 Toni Gundogdu <[email protected]> -- Copyright (C) 2011 Thomas Preud'homme <[email protected]> -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -- 02110-1301 USA -- -- Identify the script. function ident(self) package.path = self.script_dir .. '/?.lua' local C = require 'quvi/const' local r = {} r.domain = "videobash%.com" r.formats = "default" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/video_show/"}) return r end -- Query available formats. function query_formats(self) self.formats = 'default' return self end -- Parse media URL. function parse(self) self.host_id = "videobash" local p = quvi.fetch(self.page_url) self.title = p:match("<title>(.-)%s+-") or error ("no match: media title") self.id = p:match("addFavorite%((%d+)") or error ("no match: media ID") local s = p:match('file="(.-);') or error("no match: media URL") s = s:gsub("[%s+']+", '') self.thumbnail_url = p:match('og:image"%s+content="(.-)"') or '' local U = require 'quvi/util' self.url = {U.unescape(s)} return self end -- vim: set ts=4 sw=4 tw=72 expandtab:
FIX: videobash.lua: media URL parsing
FIX: videobash.lua: media URL parsing
Lua
lgpl-2.1
hadess/libquvi-scripts-iplayer,alech/libquvi-scripts,legatvs/libquvi-scripts,alech/libquvi-scripts,legatvs/libquvi-scripts,DangerCove/libquvi-scripts,hadess/libquvi-scripts-iplayer,DangerCove/libquvi-scripts
5aa1e3e13876809ff14264429ad98fa3d5457b99
xmake/scripts/action/_build.lua
xmake/scripts/action/_build.lua
--!The Automatic Cross-platform Build Tool -- -- XMake is free software; you can redistribute it and/or modify -- it under the terms of the GNU Lesser General Public License as published by -- the Free Software Foundation; either version 2.1 of the License, or -- (at your option) any later version. -- -- XMake is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public License -- along with XMake; -- If not, see <a href="http://www.gnu.org/licenses/"> http://www.gnu.org/licenses/</a> -- -- Copyright (C) 2009 - 2015, ruki All rights reserved. -- -- @author ruki -- @file _build.lua -- -- define module: _build local _build = _build or {} -- load modules local rule = require("base/rule") local utils = require("base/utils") local clean = require("base/clean") local config = require("base/config") local makefile = require("base/makefile") -- done the given config function _build.done() -- the options local options = xmake._OPTIONS assert(options) -- the target name local target_name = options.target -- rebuild it? if options.rebuild or config.get("__rebuild") then clean.remove(target_name) -- update it? elseif options.update then clean.remove(target_name, true) end -- build target for makefile if not makefile.build(target_name) then -- error print("") io.cat(rule.logfile()) utils.error("build target: %s failed!\n", target_name) return false end -- clear rebuild mark and save configure to file if config.get("__rebuild") then -- clear it config.set("__rebuild", nil) -- save the configure if not config.save() then -- error utils.error("update configure failed!") end end -- ok print("build ok!") return true end -- return module: _build return _build
--!The Automatic Cross-platform Build Tool -- -- XMake is free software; you can redistribute it and/or modify -- it under the terms of the GNU Lesser General Public License as published by -- the Free Software Foundation; either version 2.1 of the License, or -- (at your option) any later version. -- -- XMake is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public License -- along with XMake; -- If not, see <a href="http://www.gnu.org/licenses/"> http://www.gnu.org/licenses/</a> -- -- Copyright (C) 2009 - 2015, ruki All rights reserved. -- -- @author ruki -- @file _build.lua -- -- define module: _build local _build = _build or {} -- load modules local rule = require("base/rule") local utils = require("base/utils") local clean = require("base/clean") local config = require("base/config") local makefile = require("base/makefile") -- done the given config function _build.done() -- the options local options = xmake._OPTIONS assert(options) -- the target name local target_name = options.target -- rebuild it? if options.rebuild or config.get("__rebuild") then clean.remove(target_name) -- update it? elseif options.update then clean.remove(target_name, true) end -- clear rebuild mark and save configure to file if config.get("__rebuild") then -- clear it config.set("__rebuild", nil) -- save the configure if not config.save() then -- error utils.error("update configure failed!") end end -- build target for makefile if not makefile.build(target_name) then -- error print("") io.cat(rule.logfile()) utils.error("build target: %s failed!\n", target_name) return false end -- ok print("build ok!") return true end -- return module: _build return _build
fix rebuild bug
fix rebuild bug
Lua
apache-2.0
tboox/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake
e0154a63a4caa38aa653d9b4ca39baa9e094ff35
lua/wire/client/rendertarget_fix.lua
lua/wire/client/rendertarget_fix.lua
WireLib.RTFix = {} local RTFix = WireLib.RTFix --------------------------------------------------------------------- -- RTFix Lib --------------------------------------------------------------------- RTFix.List = {} function RTFix:Add( ClassName, NiceName, Function ) RTFix.List[ClassName] = { NiceName, Function } end function RTFix:GetAll() return RTFix.List end function RTFix:Get( ClassName ) return RTFix.List[ClassName] end function RTFix:ReloadAll() for k,v in pairs( RTFix.List ) do local func = v[2] for k2,v2 in ipairs( ents.FindByClass( k ) ) do func( v2 ) end end end function RTFix:Reload( ClassName ) local func = RTFix.List[ClassName][2] for k, v in ipairs( ents.FindByClass( ClassName ) ) do func( v ) end end --------------------------------------------------------------------- -- Console Command --------------------------------------------------------------------- concommand.Add("wire_rt_fix",function() RTFix:ReloadAll() end) --------------------------------------------------------------------- -- Tool Menu --------------------------------------------------------------------- local function CreateCPanel( Panel ) Panel:ClearControls() Panel:Help( [[Here you can fix screens that use rendertargets if they break due to lag. If a screen is not on this list, it means that either its author has not added it to this list, the screen has its own fix, or that no fix is necessary. You can also use the console command "wire_rt_fix", which does the same thing as pressing the "All" button.]] ) local btn = vgui.Create("DButton") btn:SetText("All") function btn:DoClick() RTFix:ReloadAll() end btn:SetToolTip( "Fix all RTs on the map." ) Panel:AddItem( btn ) for k,v in pairs( RTFix.List ) do local btn = vgui.Create("DButton") btn:SetText( v[1] ) btn:SetToolTip( "Fix all " .. v[1] .. "s on the map\n("..k..")" ) function btn:DoClick() RTFix:Reload( k ) end Panel:AddItem( btn ) end end hook.Add("PopulateToolMenu","WireLib_RenderTarget_Fix",function() spawnmenu.AddToolMenuOption( "Wire", "Options", "RTFix", "Fix RenderTargets", "", "", CreateCPanel, nil ) end) --------------------------------------------------------------------- -- Add all default wire components -- credits to sk89q for making this: http://www.wiremod.com/forum/bug-reports/19921-cs-egp-gpu-etc-issue-when-rejoin-lag-out.html#post193242 --------------------------------------------------------------------- -- Helper function local function def( ent, redrawkey ) if (ent.GPU or ent.GPU.RT) then ent.GPU:FreeRT() end ent.GPU:Initialize() if (redrawkey) then ent[redrawkey] = true end end RTFix:Add("gmod_wire_consolescreen","Console Screen", function( ent ) def( ent, "NeedRefresh" ) end) RTFix:Add("gmod_wire_digitalscreen","Digital Screen", function( ent ) def( ent, "NeedRefresh" ) end) RTFix:Add("gmod_wire_gpu","GPU", def) --RTFix:Add("gmod_wire_graphics_tablet","Graphics Tablet", function( ent ) def( ent, nil, true ) end) No fix is needed for this RTFix:Add("gmod_wire_oscilloscope","Oscilloscope", def) --RTFix:Add("gmod_wire_panel","Control Panel", function( ent ) def( ent, nil, true ) end) No fix is needed for this --RTFix:Add("gmod_wire_screen","Screen", function( ent ) def( ent, nil, true ) end) No fix is needed for this RTFix:Add("gmod_wire_textscreen","Text Screen", function( ent ) def( ent, "NeedRefresh" ) end) RTFix:Add("gmod_wire_egp","EGP",function( ent ) def( ent, "NeedsUpdate" ) end)
WireLib.RTFix = {} local RTFix = WireLib.RTFix --------------------------------------------------------------------- -- RTFix Lib --------------------------------------------------------------------- RTFix.List = {} function RTFix:Add( ClassName, NiceName, Function ) RTFix.List[ClassName] = { NiceName, Function } end function RTFix:GetAll() return RTFix.List end function RTFix:Get( ClassName ) return RTFix.List[ClassName] end function RTFix:ReloadAll() for k,v in pairs( RTFix.List ) do local func = v[2] for k2,v2 in ipairs( ents.FindByClass( k ) ) do func( v2 ) end end end function RTFix:Reload( ClassName ) local func = RTFix.List[ClassName][2] for k, v in ipairs( ents.FindByClass( ClassName ) ) do func( v ) end end --------------------------------------------------------------------- -- Console Command --------------------------------------------------------------------- concommand.Add("wire_rt_fix",function() RTFix:ReloadAll() end) --------------------------------------------------------------------- -- Tool Menu --------------------------------------------------------------------- local function CreateCPanel( Panel ) Panel:ClearControls() Panel:Help( [[Here you can fix screens that use rendertargets if they break due to lag. If a screen is not on this list, it means that either its author has not added it to this list, the screen has its own fix, or that no fix is necessary. You can also use the console command "wire_rt_fix", which does the same thing as pressing the "All" button.]] ) local btn = vgui.Create("DButton") btn:SetText("All") function btn:DoClick() RTFix:ReloadAll() end btn:SetToolTip( "Fix all RTs on the map." ) Panel:AddItem( btn ) for k,v in pairs( RTFix.List ) do local btn = vgui.Create("DButton") btn:SetText( v[1] ) btn:SetToolTip( "Fix all " .. v[1] .. "s on the map\n("..k..")" ) function btn:DoClick() RTFix:Reload( k ) end Panel:AddItem( btn ) end end hook.Add("PopulateToolMenu","WireLib_RenderTarget_Fix",function() spawnmenu.AddToolMenuOption( "Wire", "Options", "RTFix", "Fix RenderTargets", "", "", CreateCPanel, nil ) end) --------------------------------------------------------------------- -- Add all default wire components -- credits to sk89q for making this: http://www.wiremod.com/forum/bug-reports/19921-cs-egp-gpu-etc-issue-when-rejoin-lag-out.html#post193242 --------------------------------------------------------------------- -- Helper function local function def( ent, redrawkey, ) if (ent.GPU or ent.GPU.RT) then ent.GPU:FreeRT() end ent.GPU:Initialize() if (redrawkey) then ent[redrawkey] = true end end RTFix:Add("gmod_wire_consolescreen","Console Screen", function( ent ) def( ent, "NeedRefresh" ) end) RTFix:Add("gmod_wire_digitalscreen","Digital Screen", function( ent ) def( ent, "NeedRefresh" ) end) RTFix:Add("gmod_wire_gpu","GPU", def) --RTFix:Add("gmod_wire_graphics_tablet","Graphics Tablet", function( ent ) def( ent, nil, true ) end) No fix is needed for this RTFix:Add("gmod_wire_oscilloscope","Oscilloscope", def) --RTFix:Add("gmod_wire_panel","Control Panel", function( ent ) def( ent, nil, true ) end) No fix is needed for this --RTFix:Add("gmod_wire_screen","Screen", function( ent ) def( ent, nil, true ) end) No fix is needed for this RTFix:Add("gmod_wire_textscreen","Text Screen", function( ent ) def( ent, "NeedRefresh" ) end) RTFix:Add("gmod_wire_egp","EGP",function( ent ) def( ent, "NeedsUpdate" ) end) RTFix:Add("gmod_wire_egp_emitter","EGP Emitter",function( ent ) def( ent, "NeedsUpdate" ) end)
Added EGP Emitters to the RT fix code.
Added EGP Emitters to the RT fix code.
Lua
apache-2.0
wiremod/wire,dvdvideo1234/wire,garrysmodlua/wire,Grocel/wire,sammyt291/wire,NezzKryptic/Wire
2088bded304c4a7ce1a2b88aebe601ac3e429067
core/length.lua
core/length.lua
local _length _length = std.object { length = 0, stretch = 0, shrink = 0, _type = "Length", absolute = function (self, context) return _length { length = SILE.toAbsoluteMeasurement(self.length), stretch = SILE.toAbsoluteMeasurement(self.stretch), shrink = SILE.toAbsoluteMeasurement(self.shrink) } end, fromLengthOrNumber = function (self, x) if type(x) == "table" then self.length = x.length self.stretch = x.stretch self.shrink = x.shrink else self.length = x end return self end, __tostring = function (x) local s = tostring(x.length).."pt" if x.stretch ~= 0 then s = s .. " plus "..x.stretch.."pt" end if x.shrink ~= 0 then s = s .. " minus "..x.shrink.."pt" end return s end, __add = function (self, other) local result = _length {} result:fromLengthOrNumber(self) result = result:absolute() if type(other) == "table" then other = other:absolute() result.length = result.length + other.length result.stretch = result.stretch + other.stretch result.shrink = result.shrink + other.shrink else result.length = result.length + other end return result end, __sub = function (self, other) local result = _length {} result:fromLengthOrNumber(self) result = result:absolute() other = SILE.toAbsoluteMeasurement(other) if type(other) == "table" then other = other:absolute() result.length = result.length - other.length result.stretch = result.stretch - other.stretch result.shrink = result.shrink - other.shrink else result.length = result.length - other end return result end, -- __mul = function(self, other) -- local result = _length {} -- result:fromLengthOrNumber(self) -- if type(other) == "table" then -- SU.error("Attempt to multiply two lengths together") -- else -- result.length = result.length * other -- result.stretch = result.stretch * other -- result.shrink = result.shrink * other -- end -- return result -- end, __lt = function (self, other) return (self-other).length < 0 end, } local length = { new = function (spec) return _length(spec or {}) end, make = function (n) local result = _length {} result:fromLengthOrNumber(n) return result end, parse = function (spec) if not spec then return _length {} end local t = lpeg.match(SILE.parserBits.length, spec) if not t then SU.error("Bad length definition '"..spec.."'") end if not t.shrink then t.shrink = 0 end if not t.stretch then t.stretch = 0 end return _length(t) end, zero = _length {} } return length
local _length _length = std.object { length = 0, stretch = 0, shrink = 0, _type = "Length", absolute = function (self, context) return _length { length = SILE.toAbsoluteMeasurement(self.length), stretch = SILE.toAbsoluteMeasurement(self.stretch), shrink = SILE.toAbsoluteMeasurement(self.shrink) } end, fromLengthOrNumber = function (self, x) if type(x) == "table" then self.length = x.length self.stretch = x.stretch self.shrink = x.shrink else self.length = x end return self end, __tostring = function (x) local s = tostring(x.length).."pt" if x.stretch ~= 0 then s = s .. " plus "..x.stretch.."pt" end if x.shrink ~= 0 then s = s .. " minus "..x.shrink.."pt" end return s end, __add = function (self, other) local result = _length {} result:fromLengthOrNumber(self) result = result:absolute() if type(other) == "table" then other = other:absolute() result.length = result.length + other.length result.stretch = result.stretch + other.stretch result.shrink = result.shrink + other.shrink else result.length = result.length + other end return result end, __sub = function (self, other) local result = _length {} result:fromLengthOrNumber(self) result = result:absolute() other = SILE.toAbsoluteMeasurement(other) if type(other) == "table" then other = other:absolute() result.length = result.length - other.length result.stretch = result.stretch - other.stretch result.shrink = result.shrink - other.shrink else result.length = result.length - other end return result end, __mul = function(self, other) local result = _length {} result:fromLengthOrNumber(self) result = result:absolute() if type(other) == "table" then SU.error("Attempt to multiply two lengths together") else result.length = result.length * other result.stretch = result.stretch * other result.shrink = result.shrink * other end return result end, __lt = function (self, other) return (self-other).length < 0 end, } local length = { new = function (spec) return _length(spec or {}) end, make = function (n) local result = _length {} result:fromLengthOrNumber(n) return result end, parse = function (spec) if not spec then return _length {} end local t = lpeg.match(SILE.parserBits.length, spec) if not t then SU.error("Bad length definition '"..spec.."'") end if not t.shrink then t.shrink = 0 end if not t.stretch then t.stretch = 0 end return _length(t) end, zero = _length {} } return length
Restore (and fix) function to multiply lengths
Restore (and fix) function to multiply lengths
Lua
mit
alerque/sile,neofob/sile,simoncozens/sile,alerque/sile,neofob/sile,simoncozens/sile,simoncozens/sile,neofob/sile,neofob/sile,simoncozens/sile,alerque/sile,alerque/sile
06d6055374fe358c6ed9263e2f23db5744118cc9
battery-widget/battery.lua
battery-widget/battery.lua
local wibox = require("wibox") local awful = require("awful") local naughty = require("naughty") local watch = require("awful.widget.watch") -- acpi sample outputs -- Battery 0: Discharging, 75%, 01:51:38 remaining -- Battery 0: Charging, 53%, 00:57:43 until charged local PATH_TO_ICONS = "/usr/share/icons/Arc/status/symbolic/" local USERNAME = os.getenv("USER") battery_widget = wibox.widget { { id = "icon", widget = wibox.widget.imagebox, resize = false }, layout = wibox.container.margin(_, 0, 0, 3), set_image = function(self, path) self.icon.image = path end } watch( "acpi", 10, function(widget, stdout, stderr, exitreason, exitcode) local batteryType local _, status, charge_str, time = string.match(stdout, '(.+): (%a+), (%d?%d%d)%%,? ?.*') local charge = tonumber(charge_str) if (charge >= 0 and charge < 15) then batteryType="battery-empty%s-symbolic" if status ~= 'Charging' then show_battery_warning() end elseif (charge >= 15 and charge < 40) then batteryType="battery-caution%s-symbolic" elseif (charge >= 40 and charge < 60) then batteryType="battery-low%s-symbolic" elseif (charge >= 60 and charge < 80) then batteryType="battery-good%s-symbolic" elseif (charge >= 80 and charge <= 100) then batteryType="battery-full%s-symbolic" end if status == 'Charging' then batteryType = string.format(batteryType,'-charging') else batteryType = string.format(batteryType,'') end widget.image = PATH_TO_ICONS .. batteryType .. ".svg" -- Update popup text -- TODO: Filter long lines -- battery_popup.text = string.gsub(stdout, "\n$", "") end, battery_widget ) -- Popup with battery info -- One way of creating a pop-up notification - naughty.notify local notification function show_battery_status() awful.spawn.easy_async([[bash -c 'acpi']], function(stdout, _, _, _) notification = naughty.notify{ text = stdout, title = "Battery status", timeout = 5, hover_timeout = 0.5, width = 200, } end ) end battery_widget:connect_signal("mouse::enter", function() show_battery_status() end) battery_widget:connect_signal("mouse::leave", function() naughty.destroy(notification) end) -- Alternative to naughty.notify - tooltip. You can compare both and choose the preferred one --battery_popup = awful.tooltip({objects = {battery_widget}}) -- To use colors from beautiful theme put -- following lines in rc.lua before require("battery"): -- beautiful.tooltip_fg = beautiful.fg_normal -- beautiful.tooltip_bg = beautiful.bg_normal --[[ Show warning notification ]] function show_battery_warning() naughty.notify{ icon = "/home/" .. USERNAME .. "/.config/awesome/nichosi.png", icon_size=100, text = "Huston, we have a problem", title = "Battery is dying", timeout = 5, hover_timeout = 0.5, position = "bottom_right", bg = "#F06060", fg = "#EEE9EF", width = 300, } end
local awful = require("awful") local naughty = require("naughty") local watch = require("awful.widget.watch") local wibox = require("wibox") -- acpi sample outputs -- Battery 0: Discharging, 75%, 01:51:38 remaining -- Battery 0: Charging, 53%, 00:57:43 until charged local PATH_TO_ICONS = "/usr/share/icons/Arc/status/symbolic/" local HOME = os.getenv("HOME") local battery_widget = wibox.widget { { id = "icon", widget = wibox.widget.imagebox, resize = false }, layout = wibox.container.margin(_, 0, 0, 3) } -- Popup with battery info -- One way of creating a pop-up notification - naughty.notify local notification local function show_battery_status() awful.spawn.easy_async([[bash -c 'acpi']], function(stdout, _, _, _) notification = naughty.notify{ text = stdout, title = "Battery status", timeout = 5, hover_timeout = 0.5, width = 200, } end ) end -- Alternative to naughty.notify - tooltip. You can compare both and choose the preferred one --battery_popup = awful.tooltip({objects = {battery_widget}}) -- To use colors from beautiful theme put -- following lines in rc.lua before require("battery"): -- beautiful.tooltip_fg = beautiful.fg_normal -- beautiful.tooltip_bg = beautiful.bg_normal local function show_battery_warning() naughty.notify{ icon = HOME .. "/.config/awesome/nichosi.png", icon_size=100, text = "Huston, we have a problem", title = "Battery is dying", timeout = 5, hover_timeout = 0.5, position = "bottom_right", bg = "#F06060", fg = "#EEE9EF", width = 300, } end watch("acpi", 10, function(widget, stdout, stderr, exitreason, exitcode) local batteryType local _, status, charge_str, time = string.match(stdout, '(.+): (%a+), (%d?%d%d)%%,? ?.*') local charge = tonumber(charge_str) if (charge >= 0 and charge < 15) then batteryType = "battery-empty%s-symbolic" if status ~= 'Charging' then show_battery_warning() end elseif (charge >= 15 and charge < 40) then batteryType = "battery-caution%s-symbolic" elseif (charge >= 40 and charge < 60) then batteryType = "battery-low%s-symbolic" elseif (charge >= 60 and charge < 80) then batteryType = "battery-good%s-symbolic" elseif (charge >= 80 and charge <= 100) then batteryType = "battery-full%s-symbolic" end if status == 'Charging' then batteryType = string.format(batteryType, '-charging') else batteryType = string.format(batteryType, '') end widget.icon:set_image(PATH_TO_ICONS .. batteryType .. ".svg") -- Update popup text -- battery_popup.text = string.gsub(stdout, "\n$", "") end, battery_widget) battery_widget:connect_signal("mouse::enter", function() show_battery_status() end) battery_widget:connect_signal("mouse::leave", function() naughty.destroy(notification) end) return battery_widget
Attempt to fix memory leak
Attempt to fix memory leak
Lua
mit
streetturtle/awesome-wm-widgets,streetturtle/awesome-wm-widgets,streetturtle/AwesomeWM
8e8eb10f8d9991e0d268cf5febc9c885e5b72df8
lstm_embedding.lua
lstm_embedding.lua
require 'nn' require 'rnn' -- IMP: dont use LSTM package from nnx - buggy require 'nngraph' --require 'cunn' -- IMP if args is not passed, global 'args' are taken. LSTM_MODEL = nil return function(args) -- overriding LSTM factory functions below LSTM = nn.LSTM -- incoming is {input(t), output(t-1), cell(t-1)} function LSTM:buildModel() -- build components self.cellLayer = self:buildCell() self.outputGate = self:buildOutputGate() -- assemble local concat = nn.ConcatTable() local concat2 = nn.ConcatTable() local input_transform = nn.ParallelTable() input_transform:add(EMBEDDING) input_transform:add(nn.Identity()) input_transform:add(nn.Identity()) concat2:add(nn.SelectTable(1)):add(nn.SelectTable(2)) concat:add(concat2):add(self.cellLayer) local model = nn.Sequential() model:add(input_transform) model:add(concat) -- output of concat is {{input, output}, cell(t)}, -- so flatten to {input, output, cell(t)} model:add(nn.FlattenTable()) local cellAct = nn.Sequential() cellAct:add(nn.SelectTable(3)) cellAct:add(nn.Tanh()) local concat3 = nn.ConcatTable() concat3:add(self.outputGate):add(cellAct) local output = nn.Sequential() output:add(concat3) output:add(nn.CMulTable()) -- we want the model to output : {output(t), cell(t)} local concat4 = nn.ConcatTable() concat4:add(output):add(nn.SelectTable(3)) model:add(concat4) print(model) return model end function LSTM:updateOutput(input) local prevOutput, prevCell if self.step == 1 then prevOutput = self.zeroTensor prevCell = self.zeroTensor -- since we have batches of symbols, we need to do this explicitly self.zeroTensor:resize(input:size(1), self.outputSize):zero() self.outputs[0] = self.zeroTensor self.cells[0] = self.zeroTensor else -- previous output and cell of this module prevOutput = self.output prevCell = self.cell end -- output(t), cell(t) = lstm{input(t), output(t-1), cell(t-1)} local output, cell if self.train ~= false then self:recycle() local recurrentModule = self:getStepModule(self.step) -- the actual forward propagation output, cell = unpack(recurrentModule:updateOutput{input, prevOutput, prevCell}) else output, cell = unpack(self.recurrentModule:updateOutput{input, prevOutput, prevCell}) end if self.train ~= false then local input_ = self.inputs[self.step] self.inputs[self.step] = self.copyInputs and rnn.recursiveCopy(input_, input) or rnn.recursiveSet(input_, input) end self.outputs[self.step] = output self.cells[self.step] = cell self.output = output self.cell = cell self.step = self.step + 1 self.gradParametersAccumulated = false -- note that we don't return the cell, just the output return self.output end function create_network(args) l = LSTM(n_hid, n_hid) lstm = nn.Sequential() lstm_seq = nn.Sequential() lstm_seq:add(nn.Sequencer(l)) --Take only last output -- lstm_seq:add(nn.SelectTable(args.state_dim)) -- lstm_seq:add(nn.Linear(n_hid, n_hid)) -- alternative - considering outputs from all timepoints -- lstm_seq:add(nn.JoinTable(2)) -- lstm_seq:add(nn.Linear(args.state_dim * n_hid, n_hid)) -- Mean pooling lstm_seq:add(nn.CAddTable()) lstm_seq:add(nn.Linear(n_hid, n_hid)) lstm_seq:add(nn.Rectifier()) parallel_flows = nn.ParallelTable() print("state dim multiplier", args.state_dim_multiplier) for f=1, args.hist_len * args.state_dim_multiplier do if f > 1 then parallel_flows:add(lstm_seq:clone("weight","bias","gradWeight", "gradBias")) -- TODO share 'weight' and 'bias' else parallel_flows:add(lstm_seq) -- TODO share 'weight' and 'bias' end end local lstm_out = nn.ConcatTable() lstm_out:add(nn.Linear(args.hist_len * args.state_dim_multiplier * n_hid, args.n_actions)) lstm_out:add(nn.Linear(args.hist_len * args.state_dim_multiplier * n_hid, args.n_objects)) lstm:add(parallel_flows) lstm:add(nn.JoinTable(2)) lstm:add(lstm_out) if args.gpu >=0 then lstm:cuda() end return lstm end LSTM_MODEL = lstm_seq return create_network(args) end
require 'nn' require 'rnn' -- IMP: dont use LSTM package from nnx - buggy require 'nngraph' --require 'cunn' -- IMP if args is not passed, global 'args' are taken. LSTM_MODEL = nil return function(args) -- overriding LSTM factory functions below LSTM = nn.LSTM -- incoming is {input(t), output(t-1), cell(t-1)} function LSTM:buildModel() -- build components self.cellLayer = self:buildCell() self.outputGate = self:buildOutputGate() -- assemble local concat = nn.ConcatTable() local concat2 = nn.ConcatTable() local input_transform = nn.ParallelTable() input_transform:add(EMBEDDING) input_transform:add(nn.Identity()) input_transform:add(nn.Identity()) concat2:add(nn.SelectTable(1)):add(nn.SelectTable(2)) concat:add(concat2):add(self.cellLayer) local model = nn.Sequential() model:add(input_transform) model:add(concat) -- output of concat is {{input, output}, cell(t)}, -- so flatten to {input, output, cell(t)} model:add(nn.FlattenTable()) local cellAct = nn.Sequential() cellAct:add(nn.SelectTable(3)) cellAct:add(nn.Tanh()) local concat3 = nn.ConcatTable() concat3:add(self.outputGate):add(cellAct) local output = nn.Sequential() output:add(concat3) output:add(nn.CMulTable()) -- we want the model to output : {output(t), cell(t)} local concat4 = nn.ConcatTable() concat4:add(output):add(nn.SelectTable(3)) model:add(concat4) print(model) return model end function LSTM:updateOutput(input) local prevOutput, prevCell if self.step == 1 then prevOutput = self.zeroTensor prevCell = self.zeroTensor -- since we have batches of symbols, we need to do this explicitly self.zeroTensor:resize(input:size(1), self.outputSize):zero() self.outputs[0] = self.zeroTensor self.cells[0] = self.zeroTensor else -- previous output and cell of this module prevOutput = self.output prevCell = self.cell end -- output(t), cell(t) = lstm{input(t), output(t-1), cell(t-1)} local output, cell if self.train ~= false then self:recycle() local recurrentModule = self:getStepModule(self.step) -- the actual forward propagation output, cell = unpack(recurrentModule:updateOutput{input, prevOutput, prevCell}) else output, cell = unpack(self.recurrentModule:updateOutput{input, prevOutput, prevCell}) end if self.train ~= false then local input_ = self.inputs[self.step] self.inputs[self.step] = self.copyInputs and rnn.recursiveCopy(input_, input) or rnn.recursiveSet(input_, input) end self.outputs[self.step] = output self.cells[self.step] = cell self.output = output self.cell = cell self.step = self.step + 1 self.gradPrevOutput = nil self.updateGradInputStep = nil self.accGradParametersStep = nil self.gradParametersAccumulated = false -- note that we don't return the cell, just the output return self.output end function create_network(args) l = LSTM(n_hid, n_hid) lstm = nn.Sequential() lstm_seq = nn.Sequential() lstm_seq:add(nn.Sequencer(l)) --Take only last output -- lstm_seq:add(nn.SelectTable(args.state_dim)) -- lstm_seq:add(nn.Linear(n_hid, n_hid)) -- alternative - considering outputs from all timepoints -- lstm_seq:add(nn.JoinTable(2)) -- lstm_seq:add(nn.Linear(args.state_dim * n_hid, n_hid)) -- Mean pooling lstm_seq:add(nn.CAddTable()) lstm_seq:add(nn.Linear(n_hid, n_hid)) lstm_seq:add(nn.Rectifier()) parallel_flows = nn.ParallelTable() print("state dim multiplier", args.state_dim_multiplier) for f=1, args.hist_len * args.state_dim_multiplier do if f > 1 then parallel_flows:add(lstm_seq:clone("weight","bias","gradWeight", "gradBias")) -- TODO share 'weight' and 'bias' else parallel_flows:add(lstm_seq) -- TODO share 'weight' and 'bias' end end local lstm_out = nn.ConcatTable() lstm_out:add(nn.Linear(args.hist_len * args.state_dim_multiplier * n_hid, args.n_actions)) lstm_out:add(nn.Linear(args.hist_len * args.state_dim_multiplier * n_hid, args.n_objects)) lstm:add(parallel_flows) lstm:add(nn.JoinTable(2)) lstm:add(lstm_out) if args.gpu >=0 then lstm:cuda() end return lstm end LSTM_MODEL = lstm_seq return create_network(args) end
bug fix with new rnn update
bug fix with new rnn update
Lua
mit
karthikncode/text-world-player,karthikncode/text-world-player
f64ddb0f8cc5ca17dcbd7f7df8c631003f2ec7e3
vrp/client/gui.lua
vrp/client/gui.lua
-- MENU function tvRP.openMenuData(menudata) SendNUIMessage({act="open_menu", menudata = menudata}) end function tvRP.closeMenu() SendNUIMessage({act="close_menu"}) end -- PROMPT function tvRP.prompt(title,default_text) SendNUIMessage({act="prompt",title=title,text=tostring(default_text)}) SetNuiFocus(true) end -- REQUEST function tvRP.request(id,text,time) SendNUIMessage({act="request",id=id,text=tostring(text),time = time}) end -- gui menu events RegisterNUICallback("menu",function(data,cb) if data.act == "close" then vRPserver.closeMenu({data.id}) elseif data.act == "valid" then vRPserver.validMenuChoice({data.id,data.choice}) end end) -- gui prompt event RegisterNUICallback("prompt",function(data,cb) if data.act == "close" then SetNuiFocus(false) SetNuiFocus(false) vRPserver.promptResult({data.result}) end end) -- gui request event RegisterNUICallback("request",function(data,cb) if data.act == "response" then vRPserver.requestResult({data.id,data.ok}) end end) -- cfg RegisterNUICallback("cfg",function(data,cb) -- if NUI loaded after SendNUIMessage({act="cfg",cfg=cfg.gui}) end) SendNUIMessage({act="cfg",cfg=cfg.gui}) -- if NUI loaded before -- PROGRESS BAR -- create/update a progress bar function tvRP.setProgressBar(name,anchor,text,r,g,b,value) local pbar = {name=name,anchor=anchor,text=text,r=r,g=g,b=b,value=value} -- default values if pbar.value == nil then pbar.value = 0 end SendNUIMessage({act="set_pbar",pbar = pbar}) end -- set progress bar value in percent function tvRP.setProgressBarValue(name,value) SendNUIMessage({act="set_pbar_val", name = name, value = value}) end -- set progress bar text function tvRP.setProgressBarText(name,text) SendNUIMessage({act="set_pbar_text", name = name, text = text}) end -- remove a progress bar function tvRP.removeProgressBar(name) SendNUIMessage({act="remove_pbar", name = name}) end -- DIV -- set a div -- css: plain global css, the div class is "div_name" -- content: html content of the div function tvRP.setDiv(name,css,content) SendNUIMessage({act="set_div", name = name, css = css, content = content}) end -- set the div css function tvRP.setDivCss(name,css) SendNUIMessage({act="set_div_css", name = name, css = css}) end -- set the div content function tvRP.setDivContent(name,content) SendNUIMessage({act="set_div_content", name = name, content = content}) end -- execute js for the div in a simple sandbox (useful to optimize data change using functions) -- you can attach objects or functions to the div element for later calls -- js variables: div (the div element), document (the document) function tvRP.divExecuteJS(name,js) SendNUIMessage({act="div_execjs", name = name, js = js}) end -- remove the div function tvRP.removeDiv(name) SendNUIMessage({act="remove_div", name = name}) end -- CONTROLS -- gui controls (from cellphone) Citizen.CreateThread(function() while true do Citizen.Wait(0) -- PHONE CONTROLS if IsControlJustPressed(3,172) then SendNUIMessage({act="event",event="UP"}) end if IsControlJustPressed(3,173) then SendNUIMessage({act="event",event="DOWN"}) end if IsControlJustPressed(3,174) then SendNUIMessage({act="event",event="LEFT"}) end if IsControlJustPressed(3,175) then SendNUIMessage({act="event",event="RIGHT"}) end if IsControlJustPressed(3,176) then SendNUIMessage({act="event",event="SELECT"}) end if IsControlJustPressed(3,177) then SendNUIMessage({act="event",event="CANCEL"}) end -- INPUT_PHONE, open general menu if IsControlJustPressed(3,27) and (not tvRP.isInComa() or not cfg.coma_disable_menu) and (not tvRP.isHandcuffed() or not cfg.handcuff_disable_menu) then vRPserver.openMainMenu({}) end -- F5,F6 (control michael, control franklin) if IsControlJustPressed(1,166) then SendNUIMessage({act="event",event="F5"}) end if IsControlJustPressed(1,167) then SendNUIMessage({act="event",event="F6"}) end end end)
-- MENU function tvRP.openMenuData(menudata) SendNUIMessage({act="open_menu", menudata = menudata}) end function tvRP.closeMenu() SendNUIMessage({act="close_menu"}) end -- PROMPT function tvRP.prompt(title,default_text) SendNUIMessage({act="prompt",title=title,text=tostring(default_text)}) SetNuiFocus(true) end -- REQUEST function tvRP.request(id,text,time) SendNUIMessage({act="request",id=id,text=tostring(text),time = time}) end -- gui menu events RegisterNUICallback("menu",function(data,cb) if data.act == "close" then vRPserver.closeMenu({data.id}) elseif data.act == "valid" then vRPserver.validMenuChoice({data.id,data.choice}) end end) -- gui prompt event RegisterNUICallback("prompt",function(data,cb) if data.act == "close" then SetNuiFocus(false) SetNuiFocus(false) vRPserver.promptResult({data.result}) end end) -- gui request event RegisterNUICallback("request",function(data,cb) if data.act == "response" then vRPserver.requestResult({data.id,data.ok}) end end) -- cfg RegisterNUICallback("cfg",function(data,cb) -- if NUI loaded after SendNUIMessage({act="cfg",cfg=cfg.gui}) end) SendNUIMessage({act="cfg",cfg=cfg.gui}) -- if NUI loaded before -- try to fix missing cfg issue (cf: https://github.com/ImagicTheCat/vRP/issues/89) for i=1,5 do SetTimeout(5000*i, function() SendNUIMessage({act="cfg",cfg=cfg.gui}) end) end -- PROGRESS BAR -- create/update a progress bar function tvRP.setProgressBar(name,anchor,text,r,g,b,value) local pbar = {name=name,anchor=anchor,text=text,r=r,g=g,b=b,value=value} -- default values if pbar.value == nil then pbar.value = 0 end SendNUIMessage({act="set_pbar",pbar = pbar}) end -- set progress bar value in percent function tvRP.setProgressBarValue(name,value) SendNUIMessage({act="set_pbar_val", name = name, value = value}) end -- set progress bar text function tvRP.setProgressBarText(name,text) SendNUIMessage({act="set_pbar_text", name = name, text = text}) end -- remove a progress bar function tvRP.removeProgressBar(name) SendNUIMessage({act="remove_pbar", name = name}) end -- DIV -- set a div -- css: plain global css, the div class is "div_name" -- content: html content of the div function tvRP.setDiv(name,css,content) SendNUIMessage({act="set_div", name = name, css = css, content = content}) end -- set the div css function tvRP.setDivCss(name,css) SendNUIMessage({act="set_div_css", name = name, css = css}) end -- set the div content function tvRP.setDivContent(name,content) SendNUIMessage({act="set_div_content", name = name, content = content}) end -- execute js for the div in a simple sandbox (useful to optimize data change using functions) -- you can attach objects or functions to the div element for later calls -- js variables: div (the div element), document (the document) function tvRP.divExecuteJS(name,js) SendNUIMessage({act="div_execjs", name = name, js = js}) end -- remove the div function tvRP.removeDiv(name) SendNUIMessage({act="remove_div", name = name}) end -- CONTROLS -- gui controls (from cellphone) Citizen.CreateThread(function() while true do Citizen.Wait(0) -- PHONE CONTROLS if IsControlJustPressed(3,172) then SendNUIMessage({act="event",event="UP"}) end if IsControlJustPressed(3,173) then SendNUIMessage({act="event",event="DOWN"}) end if IsControlJustPressed(3,174) then SendNUIMessage({act="event",event="LEFT"}) end if IsControlJustPressed(3,175) then SendNUIMessage({act="event",event="RIGHT"}) end if IsControlJustPressed(3,176) then SendNUIMessage({act="event",event="SELECT"}) end if IsControlJustPressed(3,177) then SendNUIMessage({act="event",event="CANCEL"}) end -- INPUT_PHONE, open general menu if IsControlJustPressed(3,27) and (not tvRP.isInComa() or not cfg.coma_disable_menu) and (not tvRP.isHandcuffed() or not cfg.handcuff_disable_menu) then vRPserver.openMainMenu({}) end -- F5,F6 (control michael, control franklin) if IsControlJustPressed(1,166) then SendNUIMessage({act="event",event="F5"}) end if IsControlJustPressed(1,167) then SendNUIMessage({act="event",event="F6"}) end end end)
Try to fix cfg gui issue
Try to fix cfg gui issue
Lua
mit
ENDrain/vRP-plusplus,ImagicTheCat/vRP,ImagicTheCat/vRP,ENDrain/vRP-plusplus,ENDrain/vRP-plusplus
21328113ddcd07a1711ce0a14c6c4abe6d1de503
libs/http/luasrc/http/protocol/conditionals.lua
libs/http/luasrc/http/protocol/conditionals.lua
--[[ HTTP protocol implementation for LuCI - RFC2616 / 14.19, 14.24 - 14.28 (c) 2008 Freifunk Leipzig / 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$ ]]-- --- LuCI http protocol implementation - HTTP/1.1 bits. -- This class provides basic ETag handling and implements most of the -- conditional HTTP/1.1 headers specified in RFC2616 Sct. 14.24 - 14.28 . module("luci.http.protocol.conditionals", package.seeall) local date = require("luci.http.protocol.date") --- Implement 14.19 / ETag. -- @param stat A file.stat structure -- @return String containing the generated tag suitable for ETag headers function mk_etag( stat ) if stat ~= nil then return string.format( '"%x-%x-%x"', stat.ino, stat.size, stat.mtime ) end end --- 14.24 / If-Match -- Test whether the given message object contains an "If-Match" header and -- compare it against the given stat object. -- @param req HTTP request message object -- @param stat A file.stat object -- @return Boolean indicating wheather the precondition is ok -- @return Alternative status code if the precondition failed function if_match( req, stat ) local h = req.headers local etag = mk_etag( stat ) -- Check for matching resource if type(h['If-Match']) == "string" then for ent in h['If-Match']:gmatch("([^, ]+)") do if ( ent == '*' or ent == etag ) and stat ~= nil then return true end end return false, 412 end return true end --- 14.25 / If-Modified-Since -- Test whether the given message object contains an "If-Modified-Since" header -- and compare it against the given stat object. -- @param req HTTP request message object -- @param stat A file.stat object -- @return Boolean indicating wheather the precondition is ok -- @return Alternative status code if the precondition failed -- @return Table containing extra HTTP headers if the precondition failed function if_modified_since( req, stat ) local h = req.headers -- Compare mtimes if type(h['If-Modified-Since']) == "string" then local since = date.to_unix( h['If-Modified-Since'] ) if stat == nil or since < stat.mtime then return true end return false, 304, { ["ETag"] = mk_etag( stat ); ["Date"] = date.to_http( os.time() ); ["Last-Modified"] = date.to_http( stat.mtime ) } end return true end --- 14.26 / If-None-Match -- Test whether the given message object contains an "If-None-Match" header and -- compare it against the given stat object. -- @param req HTTP request message object -- @param stat A file.stat object -- @return Boolean indicating wheather the precondition is ok -- @return Alternative status code if the precondition failed -- @return Table containing extra HTTP headers if the precondition failed function if_none_match( req, stat ) local h = req.headers local etag = mk_etag( stat ) -- Check for matching resource if type(h['If-None-Match']) == "string" then for ent in h['If-None-Match']:gmatch("([^, ]+)") do if ( ent == '*' or ent == etag ) and stat ~= nil then if req.request_method == "get" or req.request_method == "head" then return false, 304, { ["ETag"] = mk_etag( stat ); ["Date"] = date.to_http( os.time() ); ["Last-Modified"] = date.to_http( stat.mtime ) } else return false, 412 end end end end return true end --- 14.27 / If-Range -- The If-Range header is currently not implemented due to the lack of general -- byte range stuff in luci.http.protocol . This function will always return -- false, 412 to indicate a failed precondition. -- @param req HTTP request message object -- @param stat A file.stat object -- @return Boolean indicating wheather the precondition is ok -- @return Alternative status code if the precondition failed function if_range( req, stat ) -- Sorry, no subranges (yet) return false, 412 end --- 14.28 / If-Unmodified-Since -- Test whether the given message object contains an "If-Unmodified-Since" -- header and compare it against the given stat object. -- @param req HTTP request message object -- @param stat A file.stat object -- @return Boolean indicating wheather the precondition is ok -- @return Alternative status code if the precondition failed function if_unmodified_since( req, stat ) local h = req.headers -- Compare mtimes if type(h['If-Unmodified-Since']) == "string" then local since = date.to_unix( h['If-Unmodified-Since'] ) if stat ~= nil and since <= stat.mtime then return false, 412 end end return true end
--[[ HTTP protocol implementation for LuCI - RFC2616 / 14.19, 14.24 - 14.28 (c) 2008 Freifunk Leipzig / 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$ ]]-- --- LuCI http protocol implementation - HTTP/1.1 bits. -- This class provides basic ETag handling and implements most of the -- conditional HTTP/1.1 headers specified in RFC2616 Sct. 14.24 - 14.28 . module("luci.http.protocol.conditionals", package.seeall) local date = require("luci.http.protocol.date") --- Implement 14.19 / ETag. -- @param stat A file.stat structure -- @return String containing the generated tag suitable for ETag headers function mk_etag( stat ) if stat ~= nil then return string.format( '"%x-%x-%x"', stat.ino, stat.size, stat.mtime ) end end --- 14.24 / If-Match -- Test whether the given message object contains an "If-Match" header and -- compare it against the given stat object. -- @param req HTTP request message object -- @param stat A file.stat object -- @return Boolean indicating wheather the precondition is ok -- @return Alternative status code if the precondition failed function if_match( req, stat ) local h = req.headers local etag = mk_etag( stat ) -- Check for matching resource if type(h['If-Match']) == "string" then for ent in h['If-Match']:gmatch("([^, ]+)") do if ( ent == '*' or ent == etag ) and stat ~= nil then return true end end return false, 412 end return true end --- 14.25 / If-Modified-Since -- Test whether the given message object contains an "If-Modified-Since" header -- and compare it against the given stat object. -- @param req HTTP request message object -- @param stat A file.stat object -- @return Boolean indicating wheather the precondition is ok -- @return Alternative status code if the precondition failed -- @return Table containing extra HTTP headers if the precondition failed function if_modified_since( req, stat ) local h = req.headers -- Compare mtimes if type(h['If-Modified-Since']) == "string" then local since = date.to_unix( h['If-Modified-Since'] ) if stat == nil or since < stat.mtime then return true end return false, 304, { ["ETag"] = mk_etag( stat ); ["Date"] = date.to_http( os.time() ); ["Last-Modified"] = date.to_http( stat.mtime ) } end return true end --- 14.26 / If-None-Match -- Test whether the given message object contains an "If-None-Match" header and -- compare it against the given stat object. -- @param req HTTP request message object -- @param stat A file.stat object -- @return Boolean indicating wheather the precondition is ok -- @return Alternative status code if the precondition failed -- @return Table containing extra HTTP headers if the precondition failed function if_none_match( req, stat ) local h = req.headers local etag = mk_etag( stat ) local method = req.env and req.env.REQUEST_METHOD or "GET" -- Check for matching resource if type(h['If-None-Match']) == "string" then for ent in h['If-None-Match']:gmatch("([^, ]+)") do if ( ent == '*' or ent == etag ) and stat ~= nil then if method == "GET" or method == "HEAD" then return false, 304, { ["ETag"] = mk_etag( stat ); ["Date"] = date.to_http( os.time() ); ["Last-Modified"] = date.to_http( stat.mtime ) } else return false, 412 end end end end return true end --- 14.27 / If-Range -- The If-Range header is currently not implemented due to the lack of general -- byte range stuff in luci.http.protocol . This function will always return -- false, 412 to indicate a failed precondition. -- @param req HTTP request message object -- @param stat A file.stat object -- @return Boolean indicating wheather the precondition is ok -- @return Alternative status code if the precondition failed function if_range( req, stat ) -- Sorry, no subranges (yet) return false, 412 end --- 14.28 / If-Unmodified-Since -- Test whether the given message object contains an "If-Unmodified-Since" -- header and compare it against the given stat object. -- @param req HTTP request message object -- @param stat A file.stat object -- @return Boolean indicating wheather the precondition is ok -- @return Alternative status code if the precondition failed function if_unmodified_since( req, stat ) local h = req.headers -- Compare mtimes if type(h['If-Unmodified-Since']) == "string" then local since = date.to_unix( h['If-Unmodified-Since'] ) if stat ~= nil and since <= stat.mtime then return false, 412 end end return true end
libs/http: fix incorrent treatment of If-None-Match (#100)
libs/http: fix incorrent treatment of If-None-Match (#100)
Lua
apache-2.0
Wedmer/luci,rogerpueyo/luci,remakeelectric/luci,slayerrensky/luci,zhaoxx063/luci,maxrio/luci981213,mumuqz/luci,cappiewu/luci,male-puppies/luci,oyido/luci,cshore/luci,Hostle/luci,openwrt/luci,daofeng2015/luci,Sakura-Winkey/LuCI,Hostle/luci,daofeng2015/luci,fkooman/luci,jorgifumi/luci,jorgifumi/luci,forward619/luci,oneru/luci,jlopenwrtluci/luci,tobiaswaldvogel/luci,981213/luci-1,cshore-firmware/openwrt-luci,taiha/luci,wongsyrone/luci-1,ff94315/luci-1,florian-shellfire/luci,florian-shellfire/luci,aa65535/luci,teslamint/luci,mumuqz/luci,daofeng2015/luci,Wedmer/luci,slayerrensky/luci,dismantl/luci-0.12,male-puppies/luci,teslamint/luci,sujeet14108/luci,david-xiao/luci,kuoruan/luci,jchuang1977/luci-1,openwrt-es/openwrt-luci,male-puppies/luci,nmav/luci,mumuqz/luci,thesabbir/luci,bright-things/ionic-luci,nmav/luci,wongsyrone/luci-1,keyidadi/luci,zhaoxx063/luci,fkooman/luci,schidler/ionic-luci,harveyhu2012/luci,thess/OpenWrt-luci,dwmw2/luci,palmettos/test,urueedi/luci,LazyZhu/openwrt-luci-trunk-mod,sujeet14108/luci,obsy/luci,MinFu/luci,harveyhu2012/luci,thesabbir/luci,jorgifumi/luci,fkooman/luci,cshore-firmware/openwrt-luci,marcel-sch/luci,jchuang1977/luci-1,urueedi/luci,openwrt-es/openwrt-luci,NeoRaider/luci,jlopenwrtluci/luci,david-xiao/luci,Wedmer/luci,bittorf/luci,obsy/luci,bittorf/luci,cshore/luci,Noltari/luci,kuoruan/lede-luci,lbthomsen/openwrt-luci,NeoRaider/luci,Noltari/luci,taiha/luci,joaofvieira/luci,chris5560/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,nwf/openwrt-luci,keyidadi/luci,mumuqz/luci,Sakura-Winkey/LuCI,slayerrensky/luci,dwmw2/luci,kuoruan/lede-luci,artynet/luci,jorgifumi/luci,aircross/OpenWrt-Firefly-LuCI,dismantl/luci-0.12,artynet/luci,thess/OpenWrt-luci,forward619/luci,remakeelectric/luci,thess/OpenWrt-luci,dismantl/luci-0.12,david-xiao/luci,Hostle/openwrt-luci-multi-user,tobiaswaldvogel/luci,kuoruan/lede-luci,RedSnake64/openwrt-luci-packages,shangjiyu/luci-with-extra,oneru/luci,lbthomsen/openwrt-luci,joaofvieira/luci,jorgifumi/luci,openwrt/luci,ff94315/luci-1,taiha/luci,obsy/luci,dwmw2/luci,bittorf/luci,daofeng2015/luci,urueedi/luci,rogerpueyo/luci,Kyklas/luci-proto-hso,urueedi/luci,zhaoxx063/luci,harveyhu2012/luci,maxrio/luci981213,bittorf/luci,mumuqz/luci,bright-things/ionic-luci,ollie27/openwrt_luci,thess/OpenWrt-luci,Wedmer/luci,oyido/luci,RuiChen1113/luci,tcatm/luci,Sakura-Winkey/LuCI,schidler/ionic-luci,kuoruan/luci,maxrio/luci981213,nwf/openwrt-luci,remakeelectric/luci,cshore/luci,slayerrensky/luci,teslamint/luci,Kyklas/luci-proto-hso,chris5560/openwrt-luci,lcf258/openwrtcn,wongsyrone/luci-1,teslamint/luci,tcatm/luci,bright-things/ionic-luci,cshore-firmware/openwrt-luci,ReclaimYourPrivacy/cloak-luci,Hostle/luci,joaofvieira/luci,LazyZhu/openwrt-luci-trunk-mod,harveyhu2012/luci,thesabbir/luci,aa65535/luci,rogerpueyo/luci,Noltari/luci,dwmw2/luci,aa65535/luci,db260179/openwrt-bpi-r1-luci,Hostle/luci,db260179/openwrt-bpi-r1-luci,ff94315/luci-1,aircross/OpenWrt-Firefly-LuCI,cshore-firmware/openwrt-luci,thesabbir/luci,jchuang1977/luci-1,MinFu/luci,jorgifumi/luci,wongsyrone/luci-1,openwrt-es/openwrt-luci,dwmw2/luci,db260179/openwrt-bpi-r1-luci,LazyZhu/openwrt-luci-trunk-mod,rogerpueyo/luci,bright-things/ionic-luci,lcf258/openwrtcn,dismantl/luci-0.12,harveyhu2012/luci,nwf/openwrt-luci,palmettos/test,RedSnake64/openwrt-luci-packages,daofeng2015/luci,thess/OpenWrt-luci,ollie27/openwrt_luci,kuoruan/luci,aircross/OpenWrt-Firefly-LuCI,lcf258/openwrtcn,schidler/ionic-luci,tcatm/luci,daofeng2015/luci,ollie27/openwrt_luci,florian-shellfire/luci,zhaoxx063/luci,ff94315/luci-1,deepak78/new-luci,nmav/luci,RuiChen1113/luci,nmav/luci,MinFu/luci,cshore/luci,cshore/luci,cshore/luci,teslamint/luci,LuttyYang/luci,aa65535/luci,RuiChen1113/luci,Hostle/openwrt-luci-multi-user,lcf258/openwrtcn,lbthomsen/openwrt-luci,Wedmer/luci,Kyklas/luci-proto-hso,RedSnake64/openwrt-luci-packages,fkooman/luci,openwrt/luci,Hostle/openwrt-luci-multi-user,artynet/luci,palmettos/cnLuCI,forward619/luci,ReclaimYourPrivacy/cloak-luci,schidler/ionic-luci,cshore-firmware/openwrt-luci,cappiewu/luci,taiha/luci,jlopenwrtluci/luci,florian-shellfire/luci,palmettos/cnLuCI,jchuang1977/luci-1,Hostle/openwrt-luci-multi-user,lcf258/openwrtcn,cshore-firmware/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,MinFu/luci,joaofvieira/luci,Hostle/openwrt-luci-multi-user,tcatm/luci,deepak78/new-luci,joaofvieira/luci,Kyklas/luci-proto-hso,taiha/luci,Sakura-Winkey/LuCI,joaofvieira/luci,david-xiao/luci,florian-shellfire/luci,MinFu/luci,rogerpueyo/luci,nwf/openwrt-luci,Hostle/luci,mumuqz/luci,cappiewu/luci,oyido/luci,Wedmer/luci,oneru/luci,aa65535/luci,RedSnake64/openwrt-luci-packages,harveyhu2012/luci,cappiewu/luci,male-puppies/luci,RedSnake64/openwrt-luci-packages,openwrt-es/openwrt-luci,RedSnake64/openwrt-luci-packages,palmettos/test,teslamint/luci,palmettos/test,jlopenwrtluci/luci,hnyman/luci,Noltari/luci,RuiChen1113/luci,Sakura-Winkey/LuCI,kuoruan/lede-luci,harveyhu2012/luci,LuttyYang/luci,lbthomsen/openwrt-luci,slayerrensky/luci,fkooman/luci,981213/luci-1,teslamint/luci,male-puppies/luci,lbthomsen/openwrt-luci,cappiewu/luci,palmettos/cnLuCI,kuoruan/luci,wongsyrone/luci-1,marcel-sch/luci,maxrio/luci981213,tcatm/luci,openwrt/luci,mumuqz/luci,david-xiao/luci,remakeelectric/luci,ReclaimYourPrivacy/cloak-luci,dwmw2/luci,aa65535/luci,ff94315/luci-1,oneru/luci,keyidadi/luci,981213/luci-1,ollie27/openwrt_luci,palmettos/test,MinFu/luci,deepak78/new-luci,oneru/luci,Noltari/luci,jlopenwrtluci/luci,palmettos/cnLuCI,deepak78/new-luci,nmav/luci,opentechinstitute/luci,LuttyYang/luci,hnyman/luci,tobiaswaldvogel/luci,dismantl/luci-0.12,artynet/luci,Kyklas/luci-proto-hso,oyido/luci,LuttyYang/luci,MinFu/luci,obsy/luci,openwrt/luci,oneru/luci,zhaoxx063/luci,deepak78/new-luci,hnyman/luci,lcf258/openwrtcn,maxrio/luci981213,nwf/openwrt-luci,Noltari/luci,wongsyrone/luci-1,daofeng2015/luci,lcf258/openwrtcn,thess/OpenWrt-luci,LuttyYang/luci,shangjiyu/luci-with-extra,LuttyYang/luci,fkooman/luci,keyidadi/luci,keyidadi/luci,lcf258/openwrtcn,oyido/luci,ReclaimYourPrivacy/cloak-luci,obsy/luci,hnyman/luci,artynet/luci,ollie27/openwrt_luci,db260179/openwrt-bpi-r1-luci,openwrt-es/openwrt-luci,oneru/luci,palmettos/cnLuCI,NeoRaider/luci,cappiewu/luci,artynet/luci,ff94315/luci-1,david-xiao/luci,hnyman/luci,Noltari/luci,jchuang1977/luci-1,nmav/luci,aa65535/luci,Noltari/luci,marcel-sch/luci,hnyman/luci,openwrt/luci,shangjiyu/luci-with-extra,cappiewu/luci,aircross/OpenWrt-Firefly-LuCI,artynet/luci,shangjiyu/luci-with-extra,opentechinstitute/luci,david-xiao/luci,chris5560/openwrt-luci,db260179/openwrt-bpi-r1-luci,Hostle/openwrt-luci-multi-user,rogerpueyo/luci,db260179/openwrt-bpi-r1-luci,NeoRaider/luci,RuiChen1113/luci,artynet/luci,Noltari/luci,deepak78/new-luci,maxrio/luci981213,Wedmer/luci,Hostle/openwrt-luci-multi-user,kuoruan/luci,tobiaswaldvogel/luci,NeoRaider/luci,thess/OpenWrt-luci,tcatm/luci,981213/luci-1,sujeet14108/luci,sujeet14108/luci,981213/luci-1,981213/luci-1,remakeelectric/luci,bright-things/ionic-luci,florian-shellfire/luci,male-puppies/luci,thesabbir/luci,aircross/OpenWrt-Firefly-LuCI,forward619/luci,wongsyrone/luci-1,bittorf/luci,chris5560/openwrt-luci,tcatm/luci,openwrt-es/openwrt-luci,remakeelectric/luci,keyidadi/luci,nwf/openwrt-luci,palmettos/cnLuCI,joaofvieira/luci,florian-shellfire/luci,lbthomsen/openwrt-luci,Sakura-Winkey/LuCI,urueedi/luci,jlopenwrtluci/luci,zhaoxx063/luci,schidler/ionic-luci,thesabbir/luci,cshore-firmware/openwrt-luci,opentechinstitute/luci,bittorf/luci,LuttyYang/luci,maxrio/luci981213,maxrio/luci981213,hnyman/luci,lcf258/openwrtcn,ollie27/openwrt_luci,jchuang1977/luci-1,dwmw2/luci,marcel-sch/luci,urueedi/luci,opentechinstitute/luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,jorgifumi/luci,fkooman/luci,taiha/luci,tobiaswaldvogel/luci,schidler/ionic-luci,urueedi/luci,ReclaimYourPrivacy/cloak-luci,wongsyrone/luci-1,joaofvieira/luci,kuoruan/lede-luci,chris5560/openwrt-luci,taiha/luci,dismantl/luci-0.12,chris5560/openwrt-luci,daofeng2015/luci,Hostle/luci,shangjiyu/luci-with-extra,tobiaswaldvogel/luci,keyidadi/luci,Kyklas/luci-proto-hso,kuoruan/luci,palmettos/test,dwmw2/luci,Sakura-Winkey/LuCI,RuiChen1113/luci,opentechinstitute/luci,deepak78/new-luci,Kyklas/luci-proto-hso,aircross/OpenWrt-Firefly-LuCI,jchuang1977/luci-1,oyido/luci,kuoruan/lede-luci,cappiewu/luci,marcel-sch/luci,fkooman/luci,urueedi/luci,chris5560/openwrt-luci,tobiaswaldvogel/luci,NeoRaider/luci,chris5560/openwrt-luci,RuiChen1113/luci,nmav/luci,keyidadi/luci,RedSnake64/openwrt-luci-packages,jchuang1977/luci-1,slayerrensky/luci,jlopenwrtluci/luci,MinFu/luci,Sakura-Winkey/LuCI,aircross/OpenWrt-Firefly-LuCI,openwrt-es/openwrt-luci,marcel-sch/luci,bright-things/ionic-luci,Hostle/luci,sujeet14108/luci,ff94315/luci-1,slayerrensky/luci,kuoruan/luci,male-puppies/luci,remakeelectric/luci,schidler/ionic-luci,obsy/luci,ff94315/luci-1,forward619/luci,thess/OpenWrt-luci,opentechinstitute/luci,cshore-firmware/openwrt-luci,opentechinstitute/luci,sujeet14108/luci,kuoruan/luci,forward619/luci,deepak78/new-luci,shangjiyu/luci-with-extra,palmettos/test,forward619/luci,tobiaswaldvogel/luci,openwrt/luci,remakeelectric/luci,jlopenwrtluci/luci,slayerrensky/luci,dismantl/luci-0.12,cshore/luci,lbthomsen/openwrt-luci,openwrt/luci,db260179/openwrt-bpi-r1-luci,marcel-sch/luci,LuttyYang/luci,jorgifumi/luci,forward619/luci,lbthomsen/openwrt-luci,kuoruan/lede-luci,schidler/ionic-luci,shangjiyu/luci-with-extra,RuiChen1113/luci,mumuqz/luci,nmav/luci,oyido/luci,hnyman/luci,sujeet14108/luci,artynet/luci,LazyZhu/openwrt-luci-trunk-mod,nwf/openwrt-luci,marcel-sch/luci,zhaoxx063/luci,ollie27/openwrt_luci,male-puppies/luci,db260179/openwrt-bpi-r1-luci,NeoRaider/luci,LazyZhu/openwrt-luci-trunk-mod,zhaoxx063/luci,palmettos/cnLuCI,cshore/luci,rogerpueyo/luci,Hostle/openwrt-luci-multi-user,oneru/luci,palmettos/cnLuCI,bright-things/ionic-luci,thesabbir/luci,shangjiyu/luci-with-extra,david-xiao/luci,bittorf/luci,kuoruan/lede-luci,nwf/openwrt-luci,thesabbir/luci,oyido/luci,NeoRaider/luci,sujeet14108/luci,teslamint/luci,LazyZhu/openwrt-luci-trunk-mod,opentechinstitute/luci,aa65535/luci,rogerpueyo/luci,981213/luci-1,bright-things/ionic-luci,Hostle/luci,ReclaimYourPrivacy/cloak-luci,openwrt-es/openwrt-luci,nmav/luci,bittorf/luci,ollie27/openwrt_luci,tcatm/luci,palmettos/test,taiha/luci,obsy/luci,Wedmer/luci,obsy/luci,florian-shellfire/luci,lcf258/openwrtcn
7f33a366cf06569c35ad031e0f611dd48eb49d3c
applications/luci-wol/luasrc/model/cbi/wol.lua
applications/luci-wol/luasrc/model/cbi/wol.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id: olsrd.lua 5560 2009-11-21 00:22:35Z jow $ ]]-- local sys = require "luci.sys" local fs = require "nixio.fs" m = SimpleForm("wol", translate("Wake on LAN"), translate("Wake on LAN is a mechanism to remotely boot computers in the local network.")) m.submit = translate("Wake up host") m.reset = false local has_ewk = fs.access("/usr/bin/etherwake") local has_wol = fs.access("/usr/bin/wol") if luci.http.formvalue("cbi.submit") then local host = luci.http.formvalue("cbid.wol.1.mac") if host and #host > 0 then local cmd local util = luci.http.formvalue("cbid.wol.1.binary") or ( has_ewk and "/usr/bin/etherwake" or "/usr/bin/wol" ) if util == "/usr/bin/etherwake" then local iface = luci.http.formvalue("cbid.wol.1.iface") cmd = "%s -D%s %q" %{ util, (iface ~= "" and " -i %q" % iface or ""), host } else cmd = "%s -v %q" %{ util, host } end is = m:section(SimpleSection) function is.render() luci.http.write( "<p><br /><strong>%s</strong><br /><br /><code>%s<br /><br />" %{ translate("Starting WoL utility:"), cmd } ) local p = io.popen(cmd .. " 2>&1") if p then while true do local l = p:read("*l") if l then if #l > 100 then l = l:sub(1, 100) .. "..." end luci.http.write(l .. "<br />") else break end end p:close() end luci.http.write("</code><br /></p>") end end end s = m:section(SimpleSection) local arp = { } local e, ip, mac, name if has_ewk and has_wol then bin = s:option(ListValue, "binary", translate("WoL program"), translate("Sometimes only one of both tools work. If one of fails, try the other one")) bin:value("/usr/bin/etherwake", "Etherwake") bin:value("/usr/bin/wol", "WoL") end if has_ewk then iface = s:option(ListValue, "iface", translate("Network interface to use"), translate("Specifies the interface the WoL packet is sent on")) if has_wol then iface:depends("binary", "/usr/bin/etherwake") end iface:value("", translate("Broadcast on all interfaces")) for _, e in ipairs(sys.net.devices()) do if e ~= "lo" then iface:value(e) end end end for _, e in ipairs(sys.net.arptable()) do arp[e["HW address"]] = { e["IP address"] } end for e in io.lines("/etc/ethers") do mac, ip = e:match("^([a-f0-9]%S+) (%S+)") if mac and ip then arp[mac] = { ip } end end for e in io.lines("/var/dhcp.leases") do mac, ip, name = e:match("^%d+ (%S+) (%S+) (%S+)") if mac and ip then arp[mac] = { ip, name ~= "*" and name } end end host = s:option(Value, "mac", translate("Host to wake up"), translate("Choose the host to wake up or enter a custom MAC address to use")) for mac, ip in pairs(arp) do host:value(mac, "%s (%s)" %{ mac, ip[2] or ip[1] }) end return m
--[[ LuCI - Lua Configuration Interface Copyright 2010 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local sys = require "luci.sys" local fs = require "nixio.fs" m = SimpleForm("wol", translate("Wake on LAN"), translate("Wake on LAN is a mechanism to remotely boot computers in the local network.")) m.submit = translate("Wake up host") m.reset = false local has_ewk = fs.access("/usr/bin/etherwake") local has_wol = fs.access("/usr/bin/wol") if luci.http.formvalue("cbi.submit") then local host = luci.http.formvalue("cbid.wol.1.mac") if host and #host > 0 then local cmd local util = luci.http.formvalue("cbid.wol.1.binary") or ( has_ewk and "/usr/bin/etherwake" or "/usr/bin/wol" ) if util == "/usr/bin/etherwake" then local iface = luci.http.formvalue("cbid.wol.1.iface") cmd = "%s -D%s %q" %{ util, (iface ~= "" and " -i %q" % iface or ""), host } else cmd = "%s -v %q" %{ util, host } end is = m:section(SimpleSection) function is.render() luci.http.write( "<p><br /><strong>%s</strong><br /><br /><code>%s<br /><br />" %{ translate("Starting WoL utility:"), cmd } ) local p = io.popen(cmd .. " 2>&1") if p then while true do local l = p:read("*l") if l then if #l > 100 then l = l:sub(1, 100) .. "..." end luci.http.write(l .. "<br />") else break end end p:close() end luci.http.write("</code><br /></p>") end end end s = m:section(SimpleSection) local arp = { } local e, ip, mac, name if has_ewk and has_wol then bin = s:option(ListValue, "binary", translate("WoL program"), translate("Sometimes only one of both tools work. If one of fails, try the other one")) bin:value("/usr/bin/etherwake", "Etherwake") bin:value("/usr/bin/wol", "WoL") end if has_ewk then iface = s:option(ListValue, "iface", translate("Network interface to use"), translate("Specifies the interface the WoL packet is sent on")) if has_wol then iface:depends("binary", "/usr/bin/etherwake") end iface:value("", translate("Broadcast on all interfaces")) for _, e in ipairs(sys.net.devices()) do if e ~= "lo" then iface:value(e) end end end for _, e in ipairs(sys.net.arptable()) do arp[e["HW address"]] = { e["IP address"] } end for e in io.lines("/etc/ethers") do mac, ip = e:match("^([a-f0-9]%S+) (%S+)") if mac and ip then arp[mac] = { ip } end end for e in io.lines("/var/dhcp.leases") do mac, ip, name = e:match("^%d+ (%S+) (%S+) (%S+)") if mac and ip then arp[mac] = { ip, name ~= "*" and name } end end host = s:option(Value, "mac", translate("Host to wake up"), translate("Choose the host to wake up or enter a custom MAC address to use")) for mac, ip in pairs(arp) do host:value(mac, "%s (%s)" %{ mac, ip[2] or ip[1] }) end return m
applications/luci-wol: fix copyright
applications/luci-wol: fix copyright git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@6092 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
bd52e034c166c7e2abf9b0c7744894c1b55c9f87
Framework/Platforms/Make/NaoRobot.lua
Framework/Platforms/Make/NaoRobot.lua
-- NaoRobot is the platform for the physical Nao >= v4 project "NaoRobot" kind "StaticLib" language "C++" includedirs { "../Source/DCM" } files { "../Source/DCM/NaoRobot/**.cpp", "../Source/DCM/NaoRobot/**.h", "../Source/DCM/Tools/**.cpp", "../Source/DCM/Tools/**.h" } links { "rt", "z", "gthread-2.0", "glib-2.0", "gio-2.0", "gmodule-2.0", "gobject-2.0", "protobuf", "asound", "pthread", "jpeg", -- Whistledetector stuff "fftw3", "pulse-simple", "pulse" -- at the moment we run flite as a separate binary -- in the future it would be good to include it as a lib --"flite", --"flite_cmulex", --"flite_cmu_us_slt", --"flite_usenglish" } targetname "naoth"
-- NaoRobot is the platform for the physical Nao >= v4 project "NaoRobot" kind "StaticLib" language "C++" includedirs { "../Source/DCM" } files { "../Source/DCM/NaoRobot/**.cpp", "../Source/DCM/NaoRobot/**.h", "../Source/DCM/Tools/**.cpp", "../Source/DCM/Tools/**.h" } links { "rt", "z", "gthread-2.0", "glib-2.0", "gio-2.0", "gmodule-2.0", "gobject-2.0", "protobuf", "asound", "pthread", "jpeg", -- Whistledetector stuff "fftw3", "pulse-simple", "pulse" -- at the moment we run flite as a separate binary -- in the future it would be good to include it as a lib --"flite", --"flite_cmulex", --"flite_cmu_us_slt", --"flite_usenglish" } -- additional links needed for the old cross compiler if ROBOT_OS == nil or ROBOT_OS == "naoos" then links { "pulsecommon-3.99", "json", "dbus-1", "sndfile", "asyncns", "FLAC", "gdbm", "vorbis", "vorbisenc", "ogg", "cap", "attr", "wrap" } end targetname "naoth"
bugfix: solve compatimility with the old toolchain
bugfix: solve compatimility with the old toolchain
Lua
apache-2.0
BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH
80253da5638aa45685f2837da07c36ec79e03f3a
arduino+esp01/sendData.lua
arduino+esp01/sendData.lua
file.open("keys") PuKey = file.readline() PrKey = file.readline() file.close() print(PuKey) print(PrKey) if (currentDust.P1~=nil) then if (wifi.sta.status()~=5) then wifi.sleeptype(0) wifi.setmode(1) wifi.sta.config(ssid,pass) wifi.sta.connect() end local address = "54.86.132.254" -- IP for data.sparkfun.com tmr.alarm(1,1000,1,function() print("connecting") if (wifi.sta.status()==5) then print("connected") sk = net.createConnection(net.TCP, 0) sk:on("reconnection",function(conn) print("socket reconnected") end) sk:on("disconnection",function(conn) print("socket disconnected") end) sk:on("receive", function(conn, msg) print(msg) local success = nil _,_,success = string.find(msg, "success") if (success==nil) then file.open('unsentData','a+') file.writeline(currentDust.P1..","..currentDust.P2) file.close() end wifi.sleeptype(1) wifi.sta.disconnect() end) sk:on("connection",function(conn) print("socket connected") print("sending...") -- change the name of 05umprticles and 1um_paricles here, or change the GET request for a different server if needed conn:send("GET /input/"..PuKey.."?private_key="..PrKey.."&05um_particles="..currentDust.P2.."&1um_particles="..currentDust.P1) conn:send(" HTTP/1.1\r\n") conn:send("Host: "..address) conn:send("Connection: close\r\n") conn:send("Accept: */*\r\n") conn:send("User-Agent: Mozilla/4.0 (compatible; ESP8266;)\r\n") conn:send("\r\n") end) sk:connect(80, address) tmr.stop(1) end end) end
file.open("keys") PuKey = file.readline() PrKey = file.readline() file.close() print(PuKey) print(PrKey) if (currentDust.P1~=nil) then if (wifi.sta.status()~=5) then wifi.sleeptype(0) wifi.setmode(1) dofile("tryConnect.lua") end local address = "54.86.132.254" -- IP for data.sparkfun.com tmr.alarm(1,1000,1,function() print("connecting") if (wifi.sta.status()==5) then print("connected") sk = net.createConnection(net.TCP, 0) sk:on("reconnection",function(conn) print("socket reconnected") end) sk:on("disconnection",function(conn) print("socket disconnected") end) sk:on("receive", function(conn, msg) print(msg) local success = nil _,_,success = string.find(msg, "success") if (success==nil) then file.open('unsentData','a+') file.writeline(currentDust.P1..","..currentDust.P2) file.close() end wifi.sleeptype(1) wifi.sta.disconnect() end) sk:on("connection",function(conn) print("socket connected") print("sending...") -- change the name of 05umprticles and 1um_paricles here, or change the GET request for a different server if needed conn:send("GET /input/"..PuKey.."?private_key="..PrKey.."&05um_particles="..currentDust.P2.."&1um_particles="..currentDust.P1) conn:send(" HTTP/1.1\r\n") conn:send("Host: "..address) conn:send("Connection: close\r\n") conn:send("Accept: */*\r\n") conn:send("User-Agent: Mozilla/4.0 (compatible; ESP8266;)\r\n") conn:send("\r\n") end) sk:connect(80, address) tmr.stop(1) end end) end
fixed wifi connecting
fixed wifi connecting
Lua
mit
wordsforthewise/ESP-8266-particle-sensor
cd17cb2de1a23e98572072ef1fdd9477673d8bf4
util/dataforms.lua
util/dataforms.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 setmetatable = setmetatable; local pairs, ipairs = pairs, ipairs; local tostring, type, next = tostring, type, next; local t_concat = table.concat; local st = require "util.stanza"; local jid_prep = require "util.jid".prep; module "dataforms" local xmlns_forms = 'jabber:x:data'; local form_t = {}; local form_mt = { __index = form_t }; function new(layout) return setmetatable(layout, form_mt); end function form_t.form(layout, data, formtype) local form = st.stanza("x", { xmlns = xmlns_forms, type = formtype or "form" }); if layout.title then form:tag("title"):text(layout.title):up(); end if layout.instructions then form:tag("instructions"):text(layout.instructions):up(); end for n, field in ipairs(layout) do local field_type = field.type or "text-single"; -- Add field tag form:tag("field", { type = field_type, var = field.name, label = field.label }); local value = (data and data[field.name]) or field.value; if value then -- Add value, depending on type if field_type == "hidden" then if type(value) == "table" then -- Assume an XML snippet form:tag("value") :add_child(value) :up(); else form:tag("value"):text(tostring(value)):up(); end elseif field_type == "boolean" then form:tag("value"):text((value and "1") or "0"):up(); elseif field_type == "fixed" then elseif field_type == "jid-multi" then for _, jid in ipairs(value) do form:tag("value"):text(jid):up(); end elseif field_type == "jid-single" then form:tag("value"):text(value):up(); elseif field_type == "text-single" or field_type == "text-private" then form:tag("value"):text(value):up(); elseif field_type == "text-multi" then -- Split into multiple <value> tags, one for each line for line in value:gmatch("([^\r\n]+)\r?\n*") do form:tag("value"):text(line):up(); end elseif field_type == "list-single" then local has_default = false; for _, val in ipairs(value) do if type(val) == "table" then form:tag("option", { label = val.label }):tag("value"):text(val.value):up():up(); if val.default and (not has_default) then form:tag("value"):text(val.value):up(); has_default = true; end else form:tag("option", { label= val }):tag("value"):text(tostring(val)):up():up(); end end elseif field_type == "list-multi" then for _, val in ipairs(value) do if type(val) == "table" then form:tag("option", { label = val.label }):tag("value"):text(val.value):up():up(); if val.default then form:tag("value"):text(val.value):up(); end else form:tag("option", { label= val }):tag("value"):text(tostring(val)):up():up(); end end end end if field.required then form:tag("required"):up(); end -- Jump back up to list of fields form:up(); end return form; end local field_readers = {}; function form_t.data(layout, stanza) local data = {}; local errors = {}; for _, field in ipairs(layout) do local tag; for field_tag in stanza:childtags() do if field.name == field_tag.attr.var then tag = field_tag; break; end end if not tag then if field.required then errors[field.name] = "Required value missing"; end else local reader = field_readers[field.type]; if reader then data[field.name], errors[field.name] = reader(tag, field.required); end end end if next(errors) then return data, errors; end return data; end field_readers["text-single"] = function (field_tag, required) local data = field_tag:get_child_text("value"); if data and #data > 0 then return data elseif required then return nil, "Required value missing"; end end field_readers["text-private"] = field_readers["text-single"]; field_readers["jid-single"] = function (field_tag, required) local raw_data = field_tag:get_child_text("value") local data = jid_prep(raw_data); if data and #data > 0 then return data elseif raw_data then return nil, "Invalid JID: " .. raw_data; elseif required then return nil, "Required value missing"; end end field_readers["jid-multi"] = function (field_tag, required) local result = {}; local err = {}; for value_tag in field_tag:childtags("value") do local raw_value = value_tag:get_text(); local value = jid_prep(raw_value); result[#result+1] = value; if raw_value and not value then err[#err+1] = ("Invalid JID: " .. raw_value); end end if #result > 0 then return result, (#err > 0 and t_concat(err, "\n") or nil); elseif required then return nil, "Required value missing"; end end field_readers["list-multi"] = function (field_tag, required) local result = {}; for value in field_tag:childtags("value") do result[#result+1] = value:get_text(); end return result, (required and #result == 0 and "Required value missing" or nil); end field_readers["text-multi"] = function (field_tag, required) local data, err = field_readers["list-multi"](field_tag, required); if data then data = t_concat(data, "\n"); end return data, err; end field_readers["list-single"] = field_readers["text-single"]; local boolean_values = { ["1"] = true, ["true"] = true, ["0"] = false, ["false"] = false, }; field_readers["boolean"] = function (field_tag, required) local raw_value = field_tag:get_child_text("value"); local value = boolean_values[raw_value ~= nil and raw_value]; if value ~= nil then return value; elseif raw_value then return nil, "Invalid boolean representation"; elseif required then return nil, "Required value missing"; end end field_readers["hidden"] = function (field_tag) return field_tag:get_child_text("value"); end return _M; --[=[ Layout: { title = "MUC Configuration", instructions = [[Use this form to configure options for this MUC room.]], { name = "FORM_TYPE", type = "hidden", required = true }; { name = "field-name", type = "field-type", required = false }; } --]=]
-- 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 setmetatable = setmetatable; local pairs, ipairs = pairs, ipairs; local tostring, type, next = tostring, type, next; local t_concat = table.concat; local st = require "util.stanza"; local jid_prep = require "util.jid".prep; module "dataforms" local xmlns_forms = 'jabber:x:data'; local form_t = {}; local form_mt = { __index = form_t }; function new(layout) return setmetatable(layout, form_mt); end function form_t.form(layout, data, formtype) local form = st.stanza("x", { xmlns = xmlns_forms, type = formtype or "form" }); if layout.title then form:tag("title"):text(layout.title):up(); end if layout.instructions then form:tag("instructions"):text(layout.instructions):up(); end for n, field in ipairs(layout) do local field_type = field.type or "text-single"; -- Add field tag form:tag("field", { type = field_type, var = field.name, label = field.label }); local value = (data and data[field.name]) or field.value; if value then -- Add value, depending on type if field_type == "hidden" then if type(value) == "table" then -- Assume an XML snippet form:tag("value") :add_child(value) :up(); else form:tag("value"):text(tostring(value)):up(); end elseif field_type == "boolean" then form:tag("value"):text((value and "1") or "0"):up(); elseif field_type == "fixed" then form:tag("value"):text(value):up(); elseif field_type == "jid-multi" then for _, jid in ipairs(value) do form:tag("value"):text(jid):up(); end elseif field_type == "jid-single" then form:tag("value"):text(value):up(); elseif field_type == "text-single" or field_type == "text-private" then form:tag("value"):text(value):up(); elseif field_type == "text-multi" then -- Split into multiple <value> tags, one for each line for line in value:gmatch("([^\r\n]+)\r?\n*") do form:tag("value"):text(line):up(); end elseif field_type == "list-single" then local has_default = false; for _, val in ipairs(value) do if type(val) == "table" then form:tag("option", { label = val.label }):tag("value"):text(val.value):up():up(); if val.default and (not has_default) then form:tag("value"):text(val.value):up(); has_default = true; end else form:tag("option", { label= val }):tag("value"):text(tostring(val)):up():up(); end end elseif field_type == "list-multi" then for _, val in ipairs(value) do if type(val) == "table" then form:tag("option", { label = val.label }):tag("value"):text(val.value):up():up(); if val.default then form:tag("value"):text(val.value):up(); end else form:tag("option", { label= val }):tag("value"):text(tostring(val)):up():up(); end end end end if field.required then form:tag("required"):up(); end -- Jump back up to list of fields form:up(); end return form; end local field_readers = {}; function form_t.data(layout, stanza) local data = {}; local errors = {}; for _, field in ipairs(layout) do local tag; for field_tag in stanza:childtags() do if field.name == field_tag.attr.var then tag = field_tag; break; end end if not tag then if field.required then errors[field.name] = "Required value missing"; end else local reader = field_readers[field.type]; if reader then data[field.name], errors[field.name] = reader(tag, field.required); end end end if next(errors) then return data, errors; end return data; end field_readers["text-single"] = function (field_tag, required) local data = field_tag:get_child_text("value"); if data and #data > 0 then return data elseif required then return nil, "Required value missing"; end end field_readers["text-private"] = field_readers["text-single"]; field_readers["jid-single"] = function (field_tag, required) local raw_data = field_tag:get_child_text("value") local data = jid_prep(raw_data); if data and #data > 0 then return data elseif raw_data then return nil, "Invalid JID: " .. raw_data; elseif required then return nil, "Required value missing"; end end field_readers["jid-multi"] = function (field_tag, required) local result = {}; local err = {}; for value_tag in field_tag:childtags("value") do local raw_value = value_tag:get_text(); local value = jid_prep(raw_value); result[#result+1] = value; if raw_value and not value then err[#err+1] = ("Invalid JID: " .. raw_value); end end if #result > 0 then return result, (#err > 0 and t_concat(err, "\n") or nil); elseif required then return nil, "Required value missing"; end end field_readers["list-multi"] = function (field_tag, required) local result = {}; for value in field_tag:childtags("value") do result[#result+1] = value:get_text(); end return result, (required and #result == 0 and "Required value missing" or nil); end field_readers["text-multi"] = function (field_tag, required) local data, err = field_readers["list-multi"](field_tag, required); if data then data = t_concat(data, "\n"); end return data, err; end field_readers["list-single"] = field_readers["text-single"]; local boolean_values = { ["1"] = true, ["true"] = true, ["0"] = false, ["false"] = false, }; field_readers["boolean"] = function (field_tag, required) local raw_value = field_tag:get_child_text("value"); local value = boolean_values[raw_value ~= nil and raw_value]; if value ~= nil then return value; elseif raw_value then return nil, "Invalid boolean representation"; elseif required then return nil, "Required value missing"; end end field_readers["hidden"] = function (field_tag) return field_tag:get_child_text("value"); end return _M; --[=[ Layout: { title = "MUC Configuration", instructions = [[Use this form to configure options for this MUC room.]], { name = "FORM_TYPE", type = "hidden", required = true }; { name = "field-name", type = "field-type", required = false }; } --]=]
util.dataforms: Add support for generating type='fixed' fields
util.dataforms: Add support for generating type='fixed' fields
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
c81138f994fea343ca3c8df6f50dab5d00147287
editor/console.lua
editor/console.lua
local terminal = require("terminal") local runtime = require("runtime") local lume = require("libraries.lume") -- use lume for serialization, which is so lame but good enough for nom local pps = lume.serialize local console = lume.clone(terminal) --Clone the terminal console.textbuffer, console.textcolors, console.currentLine = {}, {}, 1 console.lengthLimit = 45 console.linesLimit = 14 local pack = function(...) return {...} end local eval = function(input, print) -- try runnig the compiled code in protected mode. console.G.print, console.G.cprint = print, cprint local chunk, err = runtime:compile(input, console.G) if(not chunk) then api.print("! Compilation error: " .. (err or "Unknown error"),10) return false end local trace local result = pack(xpcall(chunk, function(e) trace = debug.traceback() err = e end)) if(result[1]) then local output, i = pps(result[2]), 3 -- pretty-print out the values it returned. while i <= #result do output = output .. ', ' .. pps(result[i]) i = i + 1 end api.print(output,7) else -- display the error and stack trace. api.print('! Evaluation error: ' .. err or "Unknown") for _,l in ipairs(lume.split(trace, "\n")) do api.print(l,10) end end end function console:_init() for i=1,self.linesLimit do table.insert(self.textbuffer,"") end for i=1,self.linesLimit do table.insert(self.textcolors,8) end api.keyrepeat(true) self:tout("LUA CONSOLE",8) self:tout("> ", 8, true) local function reset() self.G = runtime.newGlobals() self.G.cprint = tout local code = require("editor.code"):export() local chunk = runtime:compile(code, self.G) -- we ignore compile errors here; I think that is OK, but maybe warn? if(chunk) then chunk() end self.G.reset = reset end reset() end function console:_redraw() --Patched this to restore the editor ui api.rect(1,9,192,128-16,6) for line,text in ipairs(self.textbuffer) do api.color(self.textcolors[line]) if text == "-[[liko12]]-" then --THE SECRET PHASE api.SpriteGroup(67,9,line*8,6,1,1,1,api.EditorSheet) else api.print_grid(text,1,line+1) end end end function console:_update(dt) self.blinktimer = self.blinktimer+dt if self.blinktimer > self.blinktime then self.blinktimer = self.blinktimer - self.blinktime self.blinkstate = not self.blinkstate end local curlen = self.textbuffer[self.currentLine]:len() api.color(self.blinkstate and 9 or 6) api.rect(curlen > 0 and ((curlen)*4+3) or 10,(self.currentLine)*8+2,4,5) end function console:_kpress(k,sc,ir) if k == "return" then local input = self.textbuffer[self.currentLine]:sub(3) self:tout("") eval(input, lume.fn(self.tout, self)) self:tout("> ",8,true) self:_redraw() elseif k == "backspace" then self.textbuffer[self.currentLine] = self.textbuffer[self.currentLine]:sub(0,-2) self:_redraw() end end function console:_tinput(t) if t == "\\" then return end --This thing is so bad, so GO AWAY if self.textbuffer[self.currentLine]:len() < self.lengthLimit then self:tout(t,8,true) end self:_redraw() end return console
local terminal = require("terminal") local runtime = require("runtime") local lume = require("libraries.lume") -- use lume for serialization, which is so lame but good enough for nom local pps = lume.serialize local console = lume.clone(terminal) --Clone the terminal console.textbuffer, console.textcolors, console.currentLine = {}, {}, 1 console.lengthLimit = 45 console.linesLimit = 14 local pack = function(...) return {...} end local eval = function(input, console_print) -- try runnig the compiled code in protected mode. console.G.print = console_print local chunk, err = runtime:compile(input, console.G) if(not chunk) then console_print("! Compilation error: " .. (err or "Unknown error"),10) print("! Compilation error: " .. (err or "Unknown error")) return false end local trace local result = pack(xpcall(chunk, function(e) trace = debug.traceback() err = e end)) if(result[1]) then local output, i = pps(result[2]), 3 -- pretty-print out the values it returned. while i <= #result do output = output .. ', ' .. pps(result[i]) i = i + 1 end console_print(output,7) else -- display the error and stack trace. console_print('! Evaluation error: ' .. (err or "Unknown")) print('! Evaluation error: ' .. (err or "Unknown")) for _,l in ipairs(lume.split(trace, "\n")) do console_print(l,10) print(l) end end end function console:_init() for i=1,self.linesLimit do table.insert(self.textbuffer,"") end for i=1,self.linesLimit do table.insert(self.textcolors,8) end api.keyrepeat(true) self:tout("LUA CONSOLE",8) self:tout("> ", 8, true) local function reset() self.G = runtime.newGlobals() self.G.cprint = tout local code = require("editor.code"):export() local chunk = runtime:compile(code, self.G) -- we ignore compile errors here; I think that is OK, but maybe warn? if(chunk) then chunk() end self.G.reset = reset end reset() end function console:_redraw() --Patched this to restore the editor ui api.rect(1,9,192,128-16,6) for line,text in ipairs(self.textbuffer) do api.color(self.textcolors[line]) if text == "-[[liko12]]-" then --THE SECRET PHASE api.SpriteGroup(67,9,line*8,6,1,1,1,api.EditorSheet) else api.print_grid(text,1,line+1) end end end function console:_update(dt) self.blinktimer = self.blinktimer+dt if self.blinktimer > self.blinktime then self.blinktimer = self.blinktimer - self.blinktime self.blinkstate = not self.blinkstate end local curlen = self.textbuffer[self.currentLine]:len() api.color(self.blinkstate and 9 or 6) api.rect(curlen > 0 and ((curlen)*4+3) or 10,(self.currentLine)*8+2,4,5) end function console:_kpress(k,sc,ir) if k == "return" then local input = self.textbuffer[self.currentLine]:sub(3) self:tout("") eval(input, lume.fn(self.tout, self)) self:tout("> ",8,true) self:_redraw() elseif k == "backspace" then self.textbuffer[self.currentLine] = self.textbuffer[self.currentLine]:sub(0,-2) self:_redraw() end end function console:_tinput(t) if t == "\\" then return end --This thing is so bad, so GO AWAY if self.textbuffer[self.currentLine]:len() < self.lengthLimit then self:tout(t,8,true) end self:_redraw() end return console
Fix printing in console.
Fix printing in console.
Lua
mit
RamiLego4Game/LIKO-12
59f766e8c759597e28026ecd8fff1b7cacda4d5a
src_trunk/resources/job-system/s_carjacker_job.lua
src_trunk/resources/job-system/s_carjacker_job.lua
vehicles = {} vehicles [1] = {602} vehicles [2] = {496} vehicles [3] = {517} vehicles [4] = {401} vehicles [5] = {410} vehicles [6] = {518} vehicles [7] = {600} vehicles [8] = {527} vehicles [9] = {436} vehicles [10] = {589} vehicles [11] = {419} vehicles [12] = {549} vehicles [13] = {526} vehicles [14] = {445} vehicles [15] = {507} vehicles [16] = {585} vehicles [17] = {587} vehicles [18] = {409} vehicles [19] = {466} vehicles [20] = {550} vehicles [21] = {492} vehicles [22] = {566} vehicles [23] = {540} vehicles [24] = {551} vehicles [25] = {421} vehicles [26] = {529} vehicles [27] = {536} vehicles [28] = {534} vehicles [29] = {567} vehicles [30] = {535} vehicles [31] = {576} vehicles [32] = {412} vehicles [33] = {402} vehicles [34] = {475} vehicles [35] = {429} vehicles [36] = {411} vehicles [37] = {541} vehicles [38] = {559} vehicles [39] = {560} vehicles [40] = {562} vehicles [41] = {506} vehicles [42] = {565} vehicles [43] = {451} vehicles [44] = {558} vehicles [45] = {477} vehicles [46] = {579} vehicles [47] = {400} parts = {} parts [1] = {"a transmission"} parts [2] = {"a cooling system"} parts [3] = {"front and rear dampers"} parts [4] = {"a sports clutch"} parts [5] = {"an induction kit"} local count = 0 function createTimer(res) if (res==getThisResource()) then --local selectionTime = math.random(300000, 1200000) -- random time between 5 and 20 minutes --local selectPlayerTimer = setTimer(selectPlayer, selectionTime, 1) local selectPlayerTimer = setTimer(selectPlayer, 10000, 1) end end addEventHandler("onResourceStart", getRootElement(), createTimer) function selectPlayer() -- get a random player local theChosenOne = getRandomPlayer() outputChatBox("You have been selected.", theChosenOne, 255, 0, 0) -- trace -- are they a friend of hunter? local huntersFriend = mysql_query(handler, "SELECT hunter FROM characters WHERE charactername='" .. mysql_escape_string(handler, getPlayerName(theChosenOne)) .."'") if (huntersFriend == 0) then outputChatBox("You are not a friend of Hunter.", theChosenOne, 255, 0, 0) -- trace if (count<10) then -- check 10 players before resetting the timer. selectPlayer() -- if this player is not a friend of Hunter's go back and select another player count = count+1 else local selectionTime = math.random(1200000,3600000) -- random time between 20 and 60 minutes selectPlayerTimer = setTimer(selectPlayer, selectionTime, 1) end else -- are they already on a mission? if (getElementData(theChosenOne,"missionModel")) then outputChatBox("You are already on car jacking mission.", theChosenOne, 255, 0, 0) -- trace if (count<10) then selectPlayer() -- if this player is already on a car jacking mission go back and select another player. count = count+1 else local selectionTime = math.random(1200000,3600000) -- random time between 20 and 60 minutes selectPlayerTimer = setTimer(selectPlayer, selectionTime, 1) end else outputChatBox("Let me select a car for you to steal...", theChosenOne, 255, 0, 0) -- trace checkcount = 0 -- select a random car model. local modelID = math.random(1, 47) -- random vehicle ID from the list above. local vehicleID = vehicles[modelID] local vehicleName = getVehicleNameFromModel (vehicleID) -- set the players element data to the car model setElementData(theChosenOne, "missionModel", model) -- output the message local rand = math.random(1, 5) -- random car part from the list above. local carPart = parts[rand] outputChatBox("SMS From: Hunter - Hey, man. I need a ".. carPart .." from a ".. vehicleName ..". Can you help me out?", theChosenOne) outputChatBox("#FF9933((Steal a ".. vehicleName .." and /delivercar at #FF66CCHunter's garage#FF9933.))", theChosenOne, 255, 104, 91, true ) carJackerMarker = createMarker(1108.7441, 1903.98535, 10.52469, "cylinder", 4, 255, 127, 255, 150) addEventHandler("onMarkerHit", carJackerColshape, dropOffCar, false) setElementVisibleTo(carJackerMarker, getRootElement(), false) setElementVisibleTo(carJackerMarker, thePlayer, true) -- start the selectPlayerTimer again for the next person. --local selectionTime = math.random(1200000,3600000) -- random time between 20 and 60 minutes --selectPlayerTimer = setTimer(selectPlayer, selectionTime, 1) selectPlayerTimer = setTimer(selectPlayer, 3000000, 1) end end end function dropOffCar() if(getElementData(source, "missionModel")) then local vehicle = getPedOccupiedVehicle(source) if not(vehicle) then outputChatBox("You were supposed to deliver a car.", source, 255, 0, 0) else local requestedModel = getElementData(theChosenOne,"missionModel") local requestedName = getVehicleNameFromModel(requestedModel) local deliveredName = getVehicleName(vehicle) local deliveredModel = getVehicleModelFromName(deliveredName) if (requestedModel~=deliveredModel) then outputChatBox("Hunter says: I wanted you to bring a ".. requestedName .. ", what am I supposed to do with a " .. deliveredName .. "?", source, 255, 255, 255) else local health = getElementHealth(vehicle) exports.global:givePlayerSafeMoney(source, health) local pedX, pedY, pedZ = getElementPosition( source ) local chatSphere = createColSphere( pedX, pedY, pedZ, 10 ) exports.pool:allocateElement(chatSphere) -- Create the colSphere for chat output to local players local targetPlayers = getElementsWithinColShape( chatSphere, "player" ) local name = string.gsub(getPlayerName(source), "_", " ") for i, key in ipairs( targetPlayers ) do outputChatBox("Hunter says: Thanks, man. Here's $" .. health .. " for the car. I'll call you again soon.", source, 255, 255, 255) end destroyElement(chatSphere) destroyElement(carJackerMarker) -- cleanup removePedFromVehicle(source, vehicle) respawnVehicle (vehicle) setElementData(vehicle, "locked", 0) setVehicleLocked(vehicle, false) setElementData(source, "missionModel", nil) end end end end
vehicles = {} vehicles [1] = {602} vehicles [2] = {496} vehicles [3] = {517} vehicles [4] = {401} vehicles [5] = {410} vehicles [6] = {518} vehicles [7] = {600} vehicles [8] = {527} vehicles [9] = {436} vehicles [10] = {589} vehicles [11] = {419} vehicles [12] = {549} vehicles [13] = {526} vehicles [14] = {445} vehicles [15] = {507} vehicles [16] = {585} vehicles [17] = {587} vehicles [18] = {409} vehicles [19] = {466} vehicles [20] = {550} vehicles [21] = {492} vehicles [22] = {566} vehicles [23] = {540} vehicles [24] = {551} vehicles [25] = {421} vehicles [26] = {529} vehicles [27] = {536} vehicles [28] = {534} vehicles [29] = {567} vehicles [30] = {535} vehicles [31] = {576} vehicles [32] = {412} vehicles [33] = {402} vehicles [34] = {475} vehicles [35] = {429} vehicles [36] = {411} vehicles [37] = {541} vehicles [38] = {559} vehicles [39] = {560} vehicles [40] = {562} vehicles [41] = {506} vehicles [42] = {565} vehicles [43] = {451} vehicles [44] = {558} vehicles [45] = {477} vehicles [46] = {579} vehicles [47] = {400} parts = {} parts [1] = {"a transmission"} parts [2] = {"a cooling system"} parts [3] = {"front and rear dampers"} parts [4] = {"a sports clutch"} parts [5] = {"an induction kit"} local count = 0 function createTimer(res) if (res==getThisResource()) then --local selectionTime = math.random(300000, 1200000) -- random time between 5 and 20 minutes --local selectPlayerTimer = setTimer(selectPlayer, selectionTime, 1) local selectPlayerTimer = setTimer(selectPlayer, 10000, 1) end end addEventHandler("onResourceStart", getRootElement(), createTimer) function selectPlayer() -- get a random player local theChosenOne = getRandomPlayer() outputChatBox("You have been selected.", theChosenOne, 255, 0, 0) -- trace -- are they a friend of hunter? if (isElement(theChosenOne)) then local huntersFriend = mysql_query(handler, "SELECT hunter FROM characters WHERE charactername='" .. mysql_escape_string(handler, getPlayerName(theChosenOne)) .."'") if (huntersFriend == 0) then outputChatBox("You are not a friend of Hunter.", theChosenOne, 255, 0, 0) -- trace if (count<10) then -- check 10 players before resetting the timer. selectPlayer() -- if this player is not a friend of Hunter's go back and select another player count = count+1 else local selectionTime = math.random(1200000,3600000) -- random time between 20 and 60 minutes selectPlayerTimer = setTimer(selectPlayer, selectionTime, 1) end else -- are they already on a mission? if (getElementData(theChosenOne,"missionModel")) then outputChatBox("You are already on car jacking mission.", theChosenOne, 255, 0, 0) -- trace if (count<10) then selectPlayer() -- if this player is already on a car jacking mission go back and select another player. count = count+1 else local selectionTime = math.random(1200000,3600000) -- random time between 20 and 60 minutes selectPlayerTimer = setTimer(selectPlayer, selectionTime, 1) end else outputChatBox("Let me select a car for you to steal...", theChosenOne, 255, 0, 0) -- trace checkcount = 0 -- select a random car model. local modelID = math.random(1, 47) -- random vehicle ID from the list above. local vehicleID = vehicles[modelID] local vehicleName = getVehicleNameFromModel (vehicleID) -- set the players element data to the car model setElementData(theChosenOne, "missionModel", model) -- output the message local rand = math.random(1, 5) -- random car part from the list above. local carPart = parts[rand] outputChatBox("SMS From: Hunter - Hey, man. I need a ".. carPart .." from a ".. vehicleName ..". Can you help me out?", theChosenOne) outputChatBox("#FF9933((Steal a ".. vehicleName .." and /delivercar at #FF66CCHunter's garage#FF9933.))", theChosenOne, 255, 104, 91, true ) carJackerMarker = createMarker(1108.7441, 1903.98535, 10.52469, "cylinder", 4, 255, 127, 255, 150) addEventHandler("onMarkerHit", carJackerColshape, dropOffCar, false) setElementVisibleTo(carJackerMarker, getRootElement(), false) setElementVisibleTo(carJackerMarker, thePlayer, true) -- start the selectPlayerTimer again for the next person. --local selectionTime = math.random(1200000,3600000) -- random time between 20 and 60 minutes --selectPlayerTimer = setTimer(selectPlayer, selectionTime, 1) selectPlayerTimer = setTimer(selectPlayer, 3000000, 1) end end end end function dropOffCar() if(getElementData(source, "missionModel")) then local vehicle = getPedOccupiedVehicle(source) if not(vehicle) then outputChatBox("You were supposed to deliver a car.", source, 255, 0, 0) else local requestedModel = getElementData(theChosenOne,"missionModel") local requestedName = getVehicleNameFromModel(requestedModel) local deliveredName = getVehicleName(vehicle) local deliveredModel = getVehicleModelFromName(deliveredName) if (requestedModel~=deliveredModel) then outputChatBox("Hunter says: I wanted you to bring a ".. requestedName .. ", what am I supposed to do with a " .. deliveredName .. "?", source, 255, 255, 255) else local health = getElementHealth(vehicle) exports.global:givePlayerSafeMoney(source, health) local pedX, pedY, pedZ = getElementPosition( source ) local chatSphere = createColSphere( pedX, pedY, pedZ, 10 ) exports.pool:allocateElement(chatSphere) -- Create the colSphere for chat output to local players local targetPlayers = getElementsWithinColShape( chatSphere, "player" ) local name = string.gsub(getPlayerName(source), "_", " ") for i, key in ipairs( targetPlayers ) do outputChatBox("Hunter says: Thanks, man. Here's $" .. health .. " for the car. I'll call you again soon.", source, 255, 255, 255) end destroyElement(chatSphere) destroyElement(carJackerMarker) -- cleanup removePedFromVehicle(source, vehicle) respawnVehicle (vehicle) setElementData(vehicle, "locked", 0) setVehicleLocked(vehicle, false) setElementData(source, "missionModel", nil) end end end end
Carjacker bug fix
Carjacker bug fix git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@475 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
bef55ac3f83ff34ee0507b0b76cba12df9a14f31
sessions.lua
sessions.lua
local check_type = require("textadept-nim.utils").check_type local errortips = require("textadept-nim.errortips") local parse_errors = errortips.parse_errors local error_handler = errortips.error_handler local get_project = require("textadept-nim.project").detect_project local nimsuggest_executable = require("textadept-nim.constants").nimsuggest_exe local _M = {} -- There is placed active sessions _M.active = {} -- Filename-to-sessionname association _M.session_of = {} function _M:get_handle(filename) -- Creates new session for file if it isn't exist and returns -- handle for the session check_type("string", filename) local session_name = _M.session_of[filename] if session_name == nil then local project = get_project(filename) session_name = project.root if _M.active[session_name] == nil then _M.active[session_name] = {name = session_name, project = project} else _M.active[session_name].project = project end _M.session_of[filename] = session_name end local session = _M.active[session_name] if session.handle == nil or session.handle:status() ~= "running" then -- create new session local current_dir = session_name:match("^(.+)[/\\][^/\\]+$") or "." local current_handler = function(code) error_handler(_M.active[session_name], code) end session.handle = spawn(nimsuggest_executable.." --stdin --debug --v2 "..session_name, current_dir, current_handler, parse_errors, current_handler) if session.handle == nil or session.handle:status() ~= "running" then error("Cann't start nimsuggest!") end end if session.files == nil then session.files = {} end session.files[filename] = true return session.handle end function _M:detach(filename) -- Stops nimsuggest session for filename if no other file uses it check_type("string", filename) local session_name = _M.session_of[filename] if session_name == nil then return end _M.session_of[filename] = nil local session = _M.active[session_name] if session ~= nil then session.files[filename] = nil if #session.files == 0 then if session.handle ~= nil and session.handle:status() ~= "terminated" then session.handle:write("quit\n\n") session.handle:close() end _M.active[session_name] = nil end end end function _M:request(command, filename) -- Requesting nimsuggest to do command and returns -- parsed answer as a structure local nimhandle = _M:get_handle(filename) nimhandle:write(command.."\n") local message_list = {} repeat local answer = nimhandle:read() if answer == "" then break end table.insert(message_list, answer) until answer == nil return message_list end function _M:stop_all() -- Stops all nimsuggest sessions. -- Use at exit or reset only for file, session in pairs(_M.active) do if session.handle ~= nil and session.handle:status() ~= "terminated" then session.handle:write("quit\n\n") session.handle:close() end end _M.active = nil _M.session_of = nil end return _M
local check_type = require("textadept-nim.utils").check_type local errortips = require("textadept-nim.errortips") local parse_errors = errortips.parse_errors local error_handler = errortips.error_handler local get_project = require("textadept-nim.project").detect_project local nimsuggest_executable = require("textadept-nim.constants").nimsuggest_exe local _M = {} -- There is placed active sessions _M.active = {} -- Filename-to-sessionname association _M.session_of = {} function _M:get_handle(filename) -- Creates new session for file if it isn't exist and returns -- handle for the session check_type("string", filename) local session_name = _M.session_of[filename] if session_name == nil or _M.active[session_name] == nil then local project = get_project(filename) session_name = project.root if _M.active[session_name] == nil then _M.active[session_name] = {name = session_name, project = project} else _M.active[session_name].project = project end _M.session_of[filename] = session_name end local session = _M.active[session_name] if session.handle == nil or session.handle:status() ~= "running" then -- create new session local current_dir = session_name:match("^(.+)[/\\][^/\\]+$") or "." local current_handler = function(code) error_handler(_M.active[session_name], code) end session.handle = spawn(nimsuggest_executable.." --stdin --debug --v2 "..session_name, current_dir, current_handler, parse_errors, current_handler) if session.handle == nil or session.handle:status() ~= "running" then error("Cann't start nimsuggest!") end end if session.files == nil then session.files = {} end session.files[filename] = true return session.handle end function _M:detach(filename) -- Stops nimsuggest session for filename if no other file uses it check_type("string", filename) local session_name = _M.session_of[filename] if session_name == nil then return end _M.session_of[filename] = nil local session = _M.active[session_name] if session ~= nil then session.files[filename] = nil if #session.files == 0 then if session.handle ~= nil and session.handle:status() ~= "terminated" then session.handle:write("quit\n\n") session.handle:close() end _M.active[session_name] = nil end end end function _M:request(command, filename) -- Requesting nimsuggest to do command and returns -- parsed answer as a structure local nimhandle = _M:get_handle(filename) nimhandle:write(command.."\n") local message_list = {} repeat local answer = nimhandle:read() if answer == "" then break end table.insert(message_list, answer) until answer == nil return message_list end function _M:stop_all() -- Stops all nimsuggest sessions. -- Use at exit or reset only for file, session in pairs(_M.active) do if session.handle ~= nil and session.handle:status() ~= "terminated" then session.handle:write("quit\n\n") session.handle:close() end end _M.active = nil _M.session_of = nil end return _M
Fixed error message when session_name not exists in _M.active
Fixed error message when session_name not exists in _M.active
Lua
mit
xomachine/textadept-nim
f9491dc8daf48f1204bf9e775fc0cb00b319289f
Quadtastic/Scrollpane.lua
Quadtastic/Scrollpane.lua
local Layout = require("Layout") local Scrollpane = {} local scrollbar_margin = 7 local quads = { up_button = love.graphics.newQuad(80, 0, 7, 7, 128, 128), down_button = love.graphics.newQuad(80, 9, 7, 7, 128, 128), left_button = love.graphics.newQuad(96, 9, 7, 7, 128, 128), right_button = love.graphics.newQuad(96, 0, 7, 7, 128, 128), top_bar = love.graphics.newQuad(89, 0, 7, 3, 128, 128), horizontal_bar = love.graphics.newQuad(89, 3, 7, 1, 128, 128), bottom_bar = love.graphics.newQuad(89, 6, 7, 3, 128, 128), left_bar = love.graphics.newQuad(106, 0, 2, 7, 128, 128), vertical_bar = love.graphics.newQuad(108, 0, 1, 7, 128, 128), right_bar = love.graphics.newQuad(109, 0, 2, 7, 128, 128), background = love.graphics.newQuad(89, 9, 1, 1, 128, 128), corner = love.graphics.newQuad(105, 9, 7, 7, 128, 128), } -- Move the scrollpane to focus on the given bounds. -- Might be restricted by the inner bounds in the scrollpane_state -- (i.e. when moving to the first item, it will not center the viewport on -- that item, but rather have the viewport's upper bound line up with the upper -- bound of that item.) Scrollpane.set_focus = function(gui_state, bounds, scrollpane_state) assert(gui_state) assert(bounds) assert(scrollpane_state) -- We cannot focus on a specific element if we don't know the viewport's -- dimensions if not (scrollpane_state.w or scrollpane_state.h) then return end -- Try to center the scrollpane viewport on the given bounds, but without -- exceeding the limits set in the scrollpane state local center_bounds = Rectangle.center(bounds) -- This works because the scrollpane has x, y, w and h local center_vp = Rectangle.center(scrollpane_state) local dx, dy = center_bounds.x - center_vp.x, center_bounds.y - center_vp.y scrollpane_state.x = scrollpane_state.x + dx scrollpane_state.y = scrollpane_state.y + dy end Scrollpane.init_scrollpane_state = function(x, y, min_x, min_y, max_x, max_y) return { x = x or 0, -- the x offset of the viewport y = y or 0, -- the y offset of the viewport -- If any of the following are set to nil, then the viewport's movement -- is not restricted. min_x = min_x, -- the x coordinate below which the viewport cannot be moved min_y = min_y, -- the y coordinate below which the viewport cannot be moved max_x = max_x, -- the x coordinate above which the viewport cannot be moved max_y = max_y, -- the y coordinate above which the viewport cannot be moved -- the dimensions of the scrollpane's viewport. will be updated -- automatically w = nil, h = nil, -- Scrolling behavior tx = 0, -- target translate translation in x ty = 0, -- target translate translation in y last_dx = 0, -- last translate speed in x last_dy = 0, -- last translate speed in y } end Scrollpane.start = function(state, x, y, w, h, scrollpane_state) scrollpane_state = scrollpane_state or Scrollpane.init_scrollpane_state() assert(state) assert(scrollpane_state) x = x or state.layout.next_x y = y or state.layout.next_y w = w or state.layout.max_w h = h or state.layout.max_h -- Start a layout that contains this scrollpane Layout.start(state, x, y, w, h) love.graphics.clear(76, 100, 117) -- Start a layout that encloses the viewport's content -- Note the flipped signs for the scrollpane's offset Layout.start(state, -scrollpane_state.x, -scrollpane_state.y, w - scrollbar_margin, h - scrollbar_margin) -- Update the scrollpane's viewport width and height scrollpane_state.w = state.layout.max_w scrollpane_state.h = state.layout.max_h return scrollpane_state end Scrollpane.finish = function(state, scrollpane_state) -- Finish the layout that encloses the viewport's content Layout.finish(state) local x = state.layout.next_x local y = state.layout.next_y local w = state.layout.max_w local h = state.layout.max_h -- Render the vertical scrollbar love.graphics.draw(state.style.stylesheet, quads.up_button, x + w - scrollbar_margin, y) love.graphics.draw(state.style.stylesheet, quads.background, x + w - scrollbar_margin, y + scrollbar_margin, 0, 7, h - 3*scrollbar_margin) love.graphics.draw(state.style.stylesheet, quads.down_button, x + w - scrollbar_margin, y + h - 2*scrollbar_margin) -- Render the horizontal scrollbar love.graphics.draw(state.style.stylesheet, quads.left_button, x, y + h - scrollbar_margin) love.graphics.draw(state.style.stylesheet, quads.background, x + scrollbar_margin, y + h - scrollbar_margin, 0, w - 3*scrollbar_margin, 7) love.graphics.draw(state.style.stylesheet, quads.right_button, x + w - 2 * scrollbar_margin, y + h - scrollbar_margin) -- Render the little corner love.graphics.draw(state.style.stylesheet, quads.corner, x + w - scrollbar_margin, y + h - scrollbar_margin) -- This layout always fills the available space state.layout.adv_x = state.layout.max_w state.layout.adv_y = state.layout.max_h Layout.finish(state) -- Image panning local friction = 0.5 local threshold = 3 if state.mouse.wheel_dx ~= 0 then scrollpane_state.tx = scrollpane_state.x + 4*state.mouse.wheel_dx elseif math.abs(scrollpane_state.last_dx) > threshold then scrollpane_state.tx = scrollpane_state.x + scrollpane_state.last_dx end local dx = friction * (scrollpane_state.tx - scrollpane_state.x) if state.mouse.wheel_dy ~= 0 then scrollpane_state.ty = scrollpane_state.y - 4*state.mouse.wheel_dy elseif math.abs(scrollpane_state.last_dy) > threshold then scrollpane_state.ty = scrollpane_state.y + scrollpane_state.last_dy end local dy = friction * (scrollpane_state.ty - scrollpane_state.y) -- Apply the translation change scrollpane_state.x = scrollpane_state.x + dx scrollpane_state.y = scrollpane_state.y + dy -- Remember the last delta to possibly trigger floating in the next frame scrollpane_state.last_dx = dx scrollpane_state.last_dy = dy end return Scrollpane
local Layout = require("Layout") local Scrollpane = {} local scrollbar_margin = 7 local quads = { up_button = love.graphics.newQuad(80, 0, 7, 7, 128, 128), down_button = love.graphics.newQuad(80, 9, 7, 7, 128, 128), left_button = love.graphics.newQuad(96, 9, 7, 7, 128, 128), right_button = love.graphics.newQuad(96, 0, 7, 7, 128, 128), top_bar = love.graphics.newQuad(89, 0, 7, 3, 128, 128), horizontal_bar = love.graphics.newQuad(89, 3, 7, 1, 128, 128), bottom_bar = love.graphics.newQuad(89, 6, 7, 3, 128, 128), left_bar = love.graphics.newQuad(106, 0, 2, 7, 128, 128), vertical_bar = love.graphics.newQuad(108, 0, 1, 7, 128, 128), right_bar = love.graphics.newQuad(109, 0, 2, 7, 128, 128), background = love.graphics.newQuad(89, 9, 1, 1, 128, 128), corner = love.graphics.newQuad(105, 9, 7, 7, 128, 128), } -- Move the scrollpane to focus on the given bounds. -- Might be restricted by the inner bounds in the scrollpane_state -- (i.e. when moving to the first item, it will not center the viewport on -- that item, but rather have the viewport's upper bound line up with the upper -- bound of that item.) Scrollpane.set_focus = function(gui_state, bounds, scrollpane_state) assert(gui_state) assert(bounds) assert(scrollpane_state) -- We cannot focus on a specific element if we don't know the viewport's -- dimensions if not (scrollpane_state.w or scrollpane_state.h) then return end -- Try to center the scrollpane viewport on the given bounds, but without -- exceeding the limits set in the scrollpane state local center_bounds = Rectangle.center(bounds) -- This works because the scrollpane has x, y, w and h local center_vp = Rectangle.center(scrollpane_state) local dx, dy = center_bounds.x - center_vp.x, center_bounds.y - center_vp.y scrollpane_state.x = scrollpane_state.x + dx scrollpane_state.y = scrollpane_state.y + dy end Scrollpane.init_scrollpane_state = function(x, y, min_x, min_y, max_x, max_y) return { x = x or 0, -- the x offset of the viewport y = y or 0, -- the y offset of the viewport -- If any of the following are set to nil, then the viewport's movement -- is not restricted. min_x = min_x, -- the x coordinate below which the viewport cannot be moved min_y = min_y, -- the y coordinate below which the viewport cannot be moved max_x = max_x, -- the x coordinate above which the viewport cannot be moved max_y = max_y, -- the y coordinate above which the viewport cannot be moved -- the dimensions of the scrollpane's viewport. will be updated -- automatically w = nil, h = nil, -- Scrolling behavior tx = 0, -- target translate translation in x ty = 0, -- target translate translation in y last_dx = 0, -- last translate speed in x last_dy = 0, -- last translate speed in y } end Scrollpane.start = function(state, x, y, w, h, scrollpane_state) scrollpane_state = scrollpane_state or Scrollpane.init_scrollpane_state() assert(state) assert(scrollpane_state) x = x or state.layout.next_x y = y or state.layout.next_y w = w or state.layout.max_w h = h or state.layout.max_h -- Start a layout that contains this scrollpane Layout.start(state, x, y, w, h) love.graphics.clear(76, 100, 117) -- Start a layout that encloses the viewport's content -- Note the flipped signs for the scrollpane's offset Layout.start(state, 0, 0, w - scrollbar_margin, h - scrollbar_margin) love.graphics.translate(-scrollpane_state.x, -scrollpane_state.y) -- Update the scrollpane's viewport width and height scrollpane_state.w = state.layout.max_w scrollpane_state.h = state.layout.max_h return scrollpane_state end Scrollpane.finish = function(state, scrollpane_state) -- Finish the layout that encloses the viewport's content Layout.finish(state) local x = state.layout.next_x local y = state.layout.next_y local w = state.layout.max_w local h = state.layout.max_h -- Render the vertical scrollbar love.graphics.draw(state.style.stylesheet, quads.up_button, x + w - scrollbar_margin, y) love.graphics.draw(state.style.stylesheet, quads.background, x + w - scrollbar_margin, y + scrollbar_margin, 0, 7, h - 3*scrollbar_margin) love.graphics.draw(state.style.stylesheet, quads.down_button, x + w - scrollbar_margin, y + h - 2*scrollbar_margin) -- Render the horizontal scrollbar love.graphics.draw(state.style.stylesheet, quads.left_button, x, y + h - scrollbar_margin) love.graphics.draw(state.style.stylesheet, quads.background, x + scrollbar_margin, y + h - scrollbar_margin, 0, w - 3*scrollbar_margin, 7) love.graphics.draw(state.style.stylesheet, quads.right_button, x + w - 2 * scrollbar_margin, y + h - scrollbar_margin) -- Render the little corner love.graphics.draw(state.style.stylesheet, quads.corner, x + w - scrollbar_margin, y + h - scrollbar_margin) -- This layout always fills the available space state.layout.adv_x = state.layout.max_w state.layout.adv_y = state.layout.max_h Layout.finish(state) -- Image panning local friction = 0.5 local threshold = 3 if state.mouse.wheel_dx ~= 0 then scrollpane_state.tx = scrollpane_state.x + 4*state.mouse.wheel_dx elseif math.abs(scrollpane_state.last_dx) > threshold then scrollpane_state.tx = scrollpane_state.x + scrollpane_state.last_dx end local dx = friction * (scrollpane_state.tx - scrollpane_state.x) if state.mouse.wheel_dy ~= 0 then scrollpane_state.ty = scrollpane_state.y - 4*state.mouse.wheel_dy elseif math.abs(scrollpane_state.last_dy) > threshold then scrollpane_state.ty = scrollpane_state.y + scrollpane_state.last_dy end local dy = friction * (scrollpane_state.ty - scrollpane_state.y) -- Apply the translation change scrollpane_state.x = scrollpane_state.x + dx scrollpane_state.y = scrollpane_state.y + dy -- Remember the last delta to possibly trigger floating in the next frame scrollpane_state.last_dx = dx scrollpane_state.last_dy = dy end return Scrollpane
Fix Scrollpane setting the wrong scissor dimensions
Fix Scrollpane setting the wrong scissor dimensions
Lua
mit
25A0/Quadtastic,25A0/Quadtastic
3fa34da3685614a3cadcc5e6b34cb6f95774d0a4
src/nodes/platform.lua
src/nodes/platform.lua
local Timer = require 'vendor/timer' local Platform = {} Platform.__index = Platform function Platform.new(node, collider) local platform = {} setmetatable(platform, Platform) --If the node is a polyline, we need to draw a polygon rather than rectangle if node.polyline or node.polygon then local polygon = node.polyline or node.polygon local vertices = {} for i, point in ipairs(polygon) do table.insert(vertices, node.x + point.x) table.insert(vertices, node.y + point.y) end platform.bb = collider:addPolygon(unpack(vertices)) platform.bb.polyline = polygon else platform.bb = collider:addRectangle(node.x, node.y, node.width, node.height) platform.bb.polyline = nil end platform.drop = node.properties.drop ~= 'false' platform.bb.node = platform collider:setPassive(platform.bb) return platform end function Platform:collide(player, dt, mtv_x, mtv_y) local _, wy1, _, wy2 = self.bb:bbox() local px1, py1, px2, py2 = player.bb:bbox() local distance = math.abs(player.velocity.y * dt) + 0.10 function updatePlayer() player:moveBoundingBox() player.jumping = false player.rebounding = false player:impactDamage() end if self.bb.polyline and player.velocity.y >= 0 -- Prevent the player from being treadmilled through an object and ( self.bb:contains(px2,py2) or self.bb:contains(px1,py2) ) then if self.drop and player.state == 'crouch' and player.velocity.x == 0 and not self.hasdropped then if not self.dropdelay then self.dropdelay = Timer.add(0.5, function() self.hasdropped = true self.dropdelay = nil end) end end if self.dropdelay and ( player.state ~= 'crouch' or player.jumping ) and not self.hasdropped then Timer.cancel(self.dropdelay) self.dropdelay = nil end if self.hasdropped then Timer.add(0.5, function() self.hasdropped = nil end) player.jumping = true player.state = 'crouch' else player.velocity.y = 0 -- Use the MTV to keep players feet on the ground, -- fudge the Y a bit to prevent falling into steep angles player.position.y = (py1 - 4 ) + mtv_y updatePlayer() end elseif player.velocity.y >= 0 and math.abs(wy1 - py2) <= distance then if self.drop and player.state == 'crouch' and player.velocity.x == 0 and not self.hasdropped then if not self.dropdelay then self.dropdelay = Timer.add(0.5, function() self.hasdropped = true self.dropdelay = nil end) end end if player.state ~= 'crouch' or player.jumping then self.hasdropped = false if self.dropdelay then Timer.cancel(self.dropdelay) self.dropdelay = nil end end if self.hasdropped then Timer.add(0.5, function() self.hasdropped = nil end) player.jumping = true player.state = 'crouch' else player.velocity.y = 0 player.position.y = wy1 - player.height updatePlayer() end end end return Platform
local Timer = require 'vendor/timer' local Platform = {} Platform.__index = Platform function Platform.new(node, collider) local platform = {} setmetatable(platform, Platform) --If the node is a polyline, we need to draw a polygon rather than rectangle if node.polyline or node.polygon then local polygon = node.polyline or node.polygon local vertices = {} for i, point in ipairs(polygon) do table.insert(vertices, node.x + point.x) table.insert(vertices, node.y + point.y) end platform.bb = collider:addPolygon(unpack(vertices)) platform.bb.polyline = polygon else platform.bb = collider:addRectangle(node.x, node.y, node.width, node.height) platform.bb.polyline = nil end platform.drop = node.properties.drop ~= 'false' platform.bb.node = platform collider:setPassive(platform.bb) return platform end function Platform:collide(player, dt, mtv_x, mtv_y) local _, wy1, _, wy2 = self.bb:bbox() local px1, py1, px2, py2 = player.bb:bbox() local distance = math.abs(player.velocity.y * dt) + 0.10 function updatePlayer() player:moveBoundingBox() player.jumping = false player.rebounding = false player:impactDamage() end if self.bb.polyline and player.velocity.y >= 0 -- Prevent the player from being treadmilled through an object and ( self.bb:contains(px2,py2) or self.bb:contains(px1,py2) ) then if self.drop and player.state == 'crouch' and player.velocity.x == 0 and not self.hasdropped then if not self.dropdelay then self.dropdelay = Timer.add(0.5, function() self.hasdropped = true self.dropdelay = nil end) end end if self.dropdelay and ( player.state ~= 'crouch' or player.jumping ) and not self.hasdropped then Timer.cancel(self.dropdelay) self.dropdelay = nil end if self.hasdropped then Timer.add(0.5, function() self.hasdropped = nil end) player.jumping = true player.state = 'crouch' else player.velocity.y = 0 -- Use the MTV to keep players feet on the ground, -- fudge the Y a bit to prevent falling into steep angles player.position.y = (py1 - 4 ) + mtv_y updatePlayer() end elseif player.velocity.y >= 0 and math.abs(wy1 - py2) <= distance then if self.drop and player.state == 'crouch' and player.velocity.x == 0 and not self.hasdropped then if not self.dropdelay then self.dropdelay = Timer.add(0.5, function() self.hasdropped = true self.dropdelay = nil end) end end if player.state ~= 'crouch' or player.jumping then self.hasdropped = false if self.dropdelay then Timer.cancel(self.dropdelay) self.dropdelay = nil end end if self.hasdropped then Timer.add(0.5, function() self.hasdropped = nil end) player.jumping = true player.state = 'crouch' else player.velocity.y = 0 player.position.y = wy1 - player.height updatePlayer() end end end return Platform
Fix whitespace
Fix whitespace
Lua
mit
hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua
5b5f6856d30efd916e86bf653eda5035fd2a37dd
frontend/ui/reader/readercropping.lua
frontend/ui/reader/readercropping.lua
require "ui/bbox" ReaderCropping = InputContainer:new{} function ReaderCropping:onPageCrop(mode) if mode == "auto" then return end local orig_reflow_mode = self.document.configurable.text_wrap self.document.configurable.text_wrap = 0 self.ui:handleEvent(Event:new("CloseConfig")) self.cropping_zoommode = true self.cropping_offset = true self.ui:handleEvent(Event:new("SetZoomMode", "page")) self.cropping_zoommode = false local ubbox = self.document:getPageBBox(self.current_page) --DEBUG("used page bbox", ubbox) self.crop_bbox = BBoxWidget:new{ page_bbox = ubbox, ui = self.ui, crop = self, document = self.document, pageno = self.current_page, orig_zoom_mode = self.orig_zoom_mode, orig_reflow_mode = orig_reflow_mode, } UIManager:show(self.crop_bbox) return true end function ReaderCropping:onPageUpdate(page_no) --DEBUG("page updated to", page_no) self.current_page = page_no end function ReaderCropping:onZoomUpdate(zoom) --DEBUG("zoom updated to", zoom) self.zoom = zoom end function ReaderCropping:onScreenOffsetUpdate(screen_offset) if self.cropping_offset then DEBUG("offset updated to", screen_offset) self.screen_offset = screen_offset self.cropping_offset = false end end function ReaderCropping:onSetZoomMode(mode) if not self.cropping_zoommode then --DEBUG("backup zoom mode", mode) self.orig_zoom_mode = mode end end function ReaderCropping:onReadSettings(config) local bbox = config:readSetting("bbox") self.document.bbox = bbox --DEBUG("read document bbox", self.document.bbox) end function ReaderCropping:onCloseDocument() self.ui.doc_settings:saveSetting("bbox", self.document.bbox) end
require "ui/bbox" ReaderCropping = InputContainer:new{} function ReaderCropping:onPageCrop(mode) if mode == "auto" then return end local orig_reflow_mode = self.document.configurable.text_wrap self.document.configurable.text_wrap = 0 self.ui:handleEvent(Event:new("CloseConfig")) self.cropping_zoommode = true self.cropping_offset = true -- we are already in page mode, tell ReaderView to recalculate stuff -- for non-reflow mode self.view:recalculate() self.cropping_zoommode = false local ubbox = self.document:getPageBBox(self.current_page) --DEBUG("used page bbox", ubbox) self.crop_bbox = BBoxWidget:new{ page_bbox = ubbox, ui = self.ui, crop = self, document = self.document, pageno = self.current_page, orig_zoom_mode = self.orig_zoom_mode, orig_reflow_mode = orig_reflow_mode, } UIManager:show(self.crop_bbox) return true end function ReaderCropping:onPageUpdate(page_no) --DEBUG("page updated to", page_no) self.current_page = page_no end function ReaderCropping:onZoomUpdate(zoom) --DEBUG("zoom updated to", zoom) self.zoom = zoom end function ReaderCropping:onScreenOffsetUpdate(screen_offset) if self.cropping_offset then DEBUG("offset updated to", screen_offset) self.screen_offset = screen_offset self.cropping_offset = false end end function ReaderCropping:onSetZoomMode(mode) if not self.cropping_zoommode then --DEBUG("backup zoom mode", mode) self.orig_zoom_mode = mode end end function ReaderCropping:onReadSettings(config) local bbox = config:readSetting("bbox") self.document.bbox = bbox --DEBUG("read document bbox", self.document.bbox) end function ReaderCropping:onCloseDocument() self.ui.doc_settings:saveSetting("bbox", self.document.bbox) end
fix visible_area recalculate for manual crop in reflow mode
fix visible_area recalculate for manual crop in reflow mode
Lua
agpl-3.0
Hzj-jie/koreader-base,apletnev/koreader-base,mwoz123/koreader,houqp/koreader,NiLuJe/koreader,Hzj-jie/koreader-base,robert00s/koreader,NiLuJe/koreader,houqp/koreader-base,apletnev/koreader,frankyifei/koreader,chrox/koreader,Frenzie/koreader,mihailim/koreader,koreader/koreader-base,Frenzie/koreader-base,noname007/koreader,Frenzie/koreader-base,houqp/koreader-base,koreader/koreader-base,frankyifei/koreader-base,NiLuJe/koreader-base,koreader/koreader-base,ashhher3/koreader,pazos/koreader,Hzj-jie/koreader-base,houqp/koreader-base,NiLuJe/koreader-base,Markismus/koreader,apletnev/koreader-base,houqp/koreader-base,NickSavage/koreader,Frenzie/koreader-base,frankyifei/koreader-base,Hzj-jie/koreader-base,NiLuJe/koreader-base,apletnev/koreader-base,poire-z/koreader,Frenzie/koreader-base,poire-z/koreader,lgeek/koreader,Hzj-jie/koreader,frankyifei/koreader-base,koreader/koreader,koreader/koreader-base,apletnev/koreader-base,frankyifei/koreader-base,chihyang/koreader,NiLuJe/koreader-base,ashang/koreader,Frenzie/koreader,koreader/koreader
8416506555a97b629dc25b25471efb8233b03e5e
build/LLVM.lua
build/LLVM.lua
-- Setup the LLVM dependency directories LLVMRootDir = depsdir .. "/llvm/" LLVMBuildDir = LLVMRootDir .. "llvm/build/" require "scripts/LLVM" function SearchLLVM() local pkg_path = basedir .. "/scripts/" .. get_llvm_package_name() print(path.getabsolute(pkg_path)) if os.isdir(pkg_path) then LLVMRootDir = pkg_path elseif os.isdir(LLVMRootDir) then else error("Error finding an LLVM build") end print("Using LLVM build: " .. LLVMRootDir) end function SetupLLVMIncludes() local c = configuration() includedirs { path.join(LLVMRootDir, "include"), path.join(LLVMRootDir, "tools/clang/include"), path.join(LLVMRootDir, "tools/clang/lib"), path.join(LLVMBuildDir, "include"), path.join(LLVMBuildDir, "tools/clang/include"), } configuration(c) end function SetupLLVMLibs() local c = configuration() libdirs { path.join(LLVMBuildDir, "lib") } configuration { "Debug", "vs*" } libdirs { path.join(LLVMBuildDir, "Debug/lib") } configuration { "Release", "vs*" } libdirs { path.join(LLVMBuildDir, "RelWithDebInfo/lib") } configuration "not vs*" defines { "__STDC_CONSTANT_MACROS", "__STDC_LIMIT_MACROS" } configuration "macosx" links { "c++", "curses", "pthread", "z" } configuration "*" links { "clangFrontend", "clangDriver", "clangSerialization", "clangCodeGen", "clangParse", "clangSema", "clangAnalysis", "clangEdit", "clangAST", "clangLex", "clangBasic", "clangIndex", "LLVMLinker", "LLVMipo", "LLVMVectorize", "LLVMBitWriter", "LLVMIRReader", "LLVMAsmParser", "LLVMOption", "LLVMInstrumentation", "LLVMProfileData", "LLVMX86AsmParser", "LLVMX86Desc", "LLVMObject", "LLVMMCParser", "LLVMBitReader", "LLVMX86Info", "LLVMX86AsmPrinter", "LLVMX86Utils", "LLVMCodeGen", "LLVMScalarOpts", "LLVMInstCombine", "LLVMTransformUtils", "LLVMAnalysis", "LLVMTarget", "LLVMMC", "LLVMCore", "LLVMSupport", } configuration(c) end
-- Setup the LLVM dependency directories LLVMRootDir = depsdir .. "/llvm/" require "scripts/LLVM" function SearchLLVM() local pkg_path = basedir .. "/scripts/" .. get_llvm_package_name() print(path.getabsolute(pkg_path)) if os.isdir(pkg_path) then LLVMRootDir = pkg_path elseif os.isdir(LLVMRootDir) then else error("Error finding an LLVM build") end print("Using LLVM build: " .. LLVMRootDir) end function get_llvm_build_dir() return path.join(LLVMRootDir, "build") end function SetupLLVMIncludes() local c = configuration() local LLVMBuildDir = get_llvm_build_dir() includedirs { path.join(LLVMRootDir, "include"), path.join(LLVMRootDir, "tools/clang/include"), path.join(LLVMRootDir, "tools/clang/lib"), path.join(LLVMBuildDir, "include"), path.join(LLVMBuildDir, "tools/clang/include"), } configuration(c) end function SetupLLVMLibs() local c = configuration() local LLVMBuildDir = get_llvm_build_dir() libdirs { path.join(LLVMBuildDir, "lib") } configuration { "Debug", "vs*" } libdirs { path.join(LLVMBuildDir, "Debug/lib") } configuration { "Release", "vs*" } libdirs { path.join(LLVMBuildDir, "RelWithDebInfo/lib") } configuration "not vs*" defines { "__STDC_CONSTANT_MACROS", "__STDC_LIMIT_MACROS" } configuration "macosx" links { "c++", "curses", "pthread", "z" } configuration "*" links { "clangFrontend", "clangDriver", "clangSerialization", "clangCodeGen", "clangParse", "clangSema", "clangAnalysis", "clangEdit", "clangAST", "clangLex", "clangBasic", "clangIndex", "LLVMLinker", "LLVMipo", "LLVMVectorize", "LLVMBitWriter", "LLVMIRReader", "LLVMAsmParser", "LLVMOption", "LLVMInstrumentation", "LLVMProfileData", "LLVMX86AsmParser", "LLVMX86Desc", "LLVMObject", "LLVMMCParser", "LLVMBitReader", "LLVMX86Info", "LLVMX86AsmPrinter", "LLVMX86Utils", "LLVMCodeGen", "LLVMScalarOpts", "LLVMInstCombine", "LLVMTransformUtils", "LLVMAnalysis", "LLVMTarget", "LLVMMC", "LLVMCore", "LLVMSupport", } configuration(c) end
Fixed the LLVM build directory path when searching for the correct LLVM.
Fixed the LLVM build directory path when searching for the correct LLVM.
Lua
mit
mohtamohit/CppSharp,mono/CppSharp,mono/CppSharp,inordertotest/CppSharp,ddobrev/CppSharp,inordertotest/CppSharp,ddobrev/CppSharp,u255436/CppSharp,inordertotest/CppSharp,zillemarco/CppSharp,u255436/CppSharp,zillemarco/CppSharp,zillemarco/CppSharp,mono/CppSharp,ddobrev/CppSharp,ktopouzi/CppSharp,mono/CppSharp,ddobrev/CppSharp,inordertotest/CppSharp,ktopouzi/CppSharp,u255436/CppSharp,u255436/CppSharp,genuinelucifer/CppSharp,inordertotest/CppSharp,zillemarco/CppSharp,mono/CppSharp,mohtamohit/CppSharp,u255436/CppSharp,genuinelucifer/CppSharp,genuinelucifer/CppSharp,mohtamohit/CppSharp,genuinelucifer/CppSharp,mono/CppSharp,mohtamohit/CppSharp,genuinelucifer/CppSharp,ktopouzi/CppSharp,ddobrev/CppSharp,zillemarco/CppSharp,ktopouzi/CppSharp,ktopouzi/CppSharp,mohtamohit/CppSharp
c5df72439f8e753b456feaff288f475f38396efa
lib/alpha_util.lua
lib/alpha_util.lua
local w2nn = require 'w2nn' local reconstruct = require 'reconstruct' local image = require 'image' local iproc = require 'iproc' local gm = require 'graphicsmagick' alpha_util = {} alpha_util.sum2d = nn.SpatialConvolutionMM(1, 1, 3, 3, 1, 1, 1, 1):cuda() alpha_util.sum2d.weight:fill(1) alpha_util.sum2d.bias:zero() function alpha_util.make_border(rgb, alpha, offset) if not alpha then return rgb end local mask = alpha:clone() mask[torch.gt(mask, 0.0)] = 1 mask[torch.eq(mask, 0.0)] = 0 local mask_nega = (mask - 1):abs():byte() local eps = 1.0e-7 rgb = rgb:clone() rgb[1][mask_nega] = 0 rgb[2][mask_nega] = 0 rgb[3][mask_nega] = 0 for i = 1, offset do local mask_weight = alpha_util.sum2d:forward(mask:cuda()):float() local border = rgb:clone() for j = 1, 3 do border[j]:copy(alpha_util.sum2d:forward(rgb[j]:reshape(1, rgb:size(2), rgb:size(3)):cuda())) border[j]:cdiv((mask_weight + eps)) rgb[j][mask_nega] = border[j][mask_nega] end mask = mask_weight:clone() mask[torch.gt(mask_weight, 0.0)] = 1 mask_nega = (mask - 1):abs():byte() end rgb[torch.gt(rgb, 1.0)] = 1.0 rgb[torch.lt(rgb, 0.0)] = 0.0 return rgb end function alpha_util.composite(rgb, alpha, model2x) if not alpha then return rgb end if not (alpha:size(2) == rgb:size(2) and alpha:size(3) == rgb:size(3)) then if model2x then alpha = reconstruct.scale(model2x, 2.0, alpha) else alpha = gm.Image(alpha, "I", "DHW"):size(rgb:size(3), rgb:size(2), "Sinc"):toTensor("float", "I", "DHW") end end local out = torch.Tensor(4, rgb:size(2), rgb:size(3)) out[1]:copy(rgb[1]) out[2]:copy(rgb[2]) out[3]:copy(rgb[3]) out[4]:copy(alpha) return out end local function test() require 'sys' require 'trepl' torch.setdefaulttensortype("torch.FloatTensor") local image_loader = require 'image_loader' local rgb, alpha = image_loader.load_float("alpha.png") local t = sys.clock() rgb = alpha_util.make_border(rgb, alpha, 7) print(sys.clock() - t) print(rgb:min(), rgb:max()) image.display({image = rgb, min = 0, max = 1}) image.save("out.png", rgb) end --test() return alpha_util
local w2nn = require 'w2nn' local reconstruct = require 'reconstruct' local image = require 'image' local iproc = require 'iproc' local gm = require 'graphicsmagick' alpha_util = {} function alpha_util.make_border(rgb, alpha, offset) if not alpha then return rgb end local sum2d = nn.SpatialConvolutionMM(1, 1, 3, 3, 1, 1, 1, 1):cuda() sum2d.weight:fill(1) sum2d.bias:zero() local mask = alpha:clone() mask[torch.gt(mask, 0.0)] = 1 mask[torch.eq(mask, 0.0)] = 0 local mask_nega = (mask - 1):abs():byte() local eps = 1.0e-7 rgb = rgb:clone() rgb[1][mask_nega] = 0 rgb[2][mask_nega] = 0 rgb[3][mask_nega] = 0 for i = 1, offset do local mask_weight = sum2d:forward(mask:cuda()):float() local border = rgb:clone() for j = 1, 3 do border[j]:copy(sum2d:forward(rgb[j]:reshape(1, rgb:size(2), rgb:size(3)):cuda())) border[j]:cdiv((mask_weight + eps)) rgb[j][mask_nega] = border[j][mask_nega] end mask = mask_weight:clone() mask[torch.gt(mask_weight, 0.0)] = 1 mask_nega = (mask - 1):abs():byte() end rgb[torch.gt(rgb, 1.0)] = 1.0 rgb[torch.lt(rgb, 0.0)] = 0.0 return rgb end function alpha_util.composite(rgb, alpha, model2x) if not alpha then return rgb end if not (alpha:size(2) == rgb:size(2) and alpha:size(3) == rgb:size(3)) then if model2x then alpha = reconstruct.scale(model2x, 2.0, alpha) else alpha = gm.Image(alpha, "I", "DHW"):size(rgb:size(3), rgb:size(2), "Sinc"):toTensor("float", "I", "DHW") end end local out = torch.Tensor(4, rgb:size(2), rgb:size(3)) out[1]:copy(rgb[1]) out[2]:copy(rgb[2]) out[3]:copy(rgb[3]) out[4]:copy(alpha) return out end local function test() require 'sys' require 'trepl' torch.setdefaulttensortype("torch.FloatTensor") local image_loader = require 'image_loader' local rgb, alpha = image_loader.load_float("alpha.png") local t = sys.clock() rgb = alpha_util.make_border(rgb, alpha, 7) print(sys.clock() - t) print(rgb:min(), rgb:max()) image.display({image = rgb, min = 0, max = 1}) image.save("out.png", rgb) end --test() return alpha_util
Fix cuda tensor error in async environment
Fix cuda tensor error in async environment
Lua
mit
nagadomi/waifu2x,nagadomi/waifu2x,zyhkz/waifu2x,nagadomi/waifu2x,Spitfire1900/upscaler,vitaliylag/waifu2x,vitaliylag/waifu2x,zyhkz/waifu2x,nagadomi/waifu2x,higankanshi/waifu2x,zyhkz/waifu2x,higankanshi/waifu2x,nagadomi/waifu2x,zyhkz/waifu2x,higankanshi/waifu2x,Spitfire1900/upscaler,vitaliylag/waifu2x
2fc1eb7e0e85a5043abd0dcf696c829cf8858940
kong/plugins/session/storage/kong.lua
kong/plugins/session/storage/kong.lua
local singletons = require "kong.singletons" local concat = table.concat local tonumber = tonumber local setmetatable = setmetatable local floor = math.floor local now = ngx.now local kong_storage = {} kong_storage.__index = kong_storage function kong_storage.new(config) return setmetatable({ dao = singletons.dao, encode = config.encoder.encode, decode = config.encoder.decode, delimiter = config.cookie.delimiter, lifetime = config.cookie.lifetime, }, kong_storage) end local function load_session(sid) local rows, err = singletons.dao.sessions:find_all { session_id = sid } if not rows then return nil, err end return rows[1] end function kong_storage:get(sid) local cache_key = self.dao.sessions:cache_key(sid) local s, err = singletons.cache:get(cache_key, nil, load_session, sid) if err then ngx.log(ngx.ERR, "Error finding session:", err) end return s, err end function kong_storage:cookie(c) local r, d = {}, self.delimiter local i, p, s, e = 1, 1, c:find(d, 1, true) while s do if i > 2 then return nil end r[i] = c:sub(p, e - 1) i, p = i + 1, e + 1 s, e = c:find(d, p, true) end if i ~= 3 then return nil end r[3] = c:sub(p) return r end function kong_storage:open(cookie, lifetime) local c = self:cookie(cookie) if c and c[1] and c[2] and c[3] then local id, expires, hmac = self.decode(c[1]), tonumber(c[2]), self.decode(c[3]) local data if ngx.get_phase() ~= 'header_filter' then local db_s = self:get(c[1]) if db_s then data = self.decode(db_s.data) expires = db_s.expires end end return id, expires, data, hmac end return nil, "invalid" end function kong_storage:insert_session(sid, data, expires) local _, err = self.dao.sessions:insert({ session_id = sid, data = data, expires = expires, }, { ttl = self.lifetime }) if err then ngx.log(ngx.ERR, "Error inserting session: ", err) end end function kong_storage:update_session(id, params, ttl) local _, err = self.dao.sessions:update(params, { id = id }, { ttl = ttl }) if err then ngx.log(ngx.ERR, "Error updating session: ", err) end end function kong_storage:save(id, expires, data, hmac) local life, key = floor(expires - now()), self.encode(id) local value = concat({key, expires, self.encode(hmac)}, self.delimiter) if life > 0 then if ngx.get_phase() == 'header_filter' then ngx.timer.at(0, function() self:insert_session(key, self.encode(data), expires) end) else self:insert_session(key, self.encode(data), expires) end return value end return nil, "expired" end function kong_storage:destroy(id) local db_s = self:get(id) if not db_s then return end local _, err = self.dao.sessions:delete({ id = db_s.id }) if err then ngx.log(ngx.ERR, "Error deleting session: ", err) end end -- used by regenerate strategy to expire old sessions during renewal function kong_storage:ttl(id, ttl) local s = self:get(self.encode(id)) if s then if ngx.get_phase() == 'header_filter' then ngx.timer.at(0, function() self:update_session(s.id, {session_id = s.session_id}, ttl) end) else self:update_session(s.id, {session_id = s.session_id}, ttl) end end end return kong_storage
local singletons = require "kong.singletons" local concat = table.concat local tonumber = tonumber local setmetatable = setmetatable local floor = math.floor local now = ngx.now local kong_storage = {} kong_storage.__index = kong_storage function kong_storage.new(config) return setmetatable({ dao = singletons.dao, encode = config.encoder.encode, decode = config.encoder.decode, delimiter = config.cookie.delimiter, lifetime = config.cookie.lifetime, }, kong_storage) end local function load_session(sid) local rows, err = singletons.dao.sessions:find_all { session_id = sid } if not rows then return nil, err end return rows[1] end function kong_storage:get(sid) local cache_key = self.dao.sessions:cache_key(sid) local s, err = singletons.cache:get(cache_key, nil, load_session, sid) if err then ngx.log(ngx.ERR, "Error finding session:", err) end return s, err end function kong_storage:cookie(c) local r, d = {}, self.delimiter local i, p, s, e = 1, 1, c:find(d, 1, true) while s do if i > 2 then return nil end r[i] = c:sub(p, e - 1) i, p = i + 1, e + 1 s, e = c:find(d, p, true) end if i ~= 3 then return nil end r[3] = c:sub(p) return r end function kong_storage:open(cookie, lifetime) local c = self:cookie(cookie) if c and c[1] and c[2] and c[3] then local id, expires, hmac = self.decode(c[1]), tonumber(c[2]), self.decode(c[3]) local data if ngx.get_phase() ~= 'header_filter' then local db_s = self:get(c[1]) if db_s then data = self.decode(db_s.data) expires = db_s.expires end end return id, expires, data, hmac end return nil, "invalid" end function kong_storage:insert_session(sid, data, expires) local _, err = self.dao.sessions:insert({ session_id = sid, data = data, expires = expires, }, { ttl = self.lifetime }) if err then ngx.log(ngx.ERR, "Error inserting session: ", err) end end function kong_storage:update_session(id, params, ttl) local _, err = self.dao.sessions:update(params, { id = id }, { ttl = ttl }) if err then ngx.log(ngx.ERR, "Error updating session: ", err) end end function kong_storage:save(id, expires, data, hmac) local life, key = floor(expires - now()), self.encode(id) local value = concat({key, expires, self.encode(hmac)}, self.delimiter) if life > 0 then if ngx.get_phase() == 'header_filter' then ngx.timer.at(0, function() self:insert_session(key, self.encode(data), expires) end) else self:insert_session(key, self.encode(data), expires) end return value end return nil, "expired" end function kong_storage:destroy(id) local db_s = self:get(id) if not db_s then return end local _, err = self.dao.sessions:delete({ id = db_s.id }) if err then ngx.log(ngx.ERR, "Error deleting session: ", err) end end -- used by regenerate strategy to expire old sessions during renewal function kong_storage:ttl(id, ttl) if ngx.get_phase() == 'header_filter' then ngx.timer.at(0, function() local s = self:get(self.encode(id)) if s then self:update_session(s.id, {session_id = s.session_id}, ttl) end end) else local s = self:get(self.encode(id)) if s then self:update_session(s.id, {session_id = s.session_id}, ttl) end end end return kong_storage
fix(session) make sure ttl doesn't try to call dao in header_filter phase
fix(session) make sure ttl doesn't try to call dao in header_filter phase
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
a257e0f39ab1fa62c5f5bea046d5cda8f1557d00
kong/db/schema/typedefs.lua
kong/db/schema/typedefs.lua
--- A library of ready-to-use type synonyms to use in schema definitions. -- @module kong.db.schema.typedefs local utils = require "kong.tools.utils" local openssl_pkey = require "openssl.pkey" local openssl_x509 = require "openssl.x509" local Schema = require("kong.db.schema") local socket_url = require("socket.url") local match = string.match local gsub = string.gsub local null = ngx.null local type = type local function validate_host(host) local res, err_or_port = utils.normalize_ip(host) if type(err_or_port) == "string" and err_or_port ~= "invalid port number" then return nil, "invalid value: " .. host end if err_or_port == "invalid port number" or type(res.port) == "number" then return nil, "must not have a port" end return true end local function validate_path(path) if not match(path, "^/[%w%.%-%_~%/%%]*$") then return nil, "invalid path: '" .. path .. "' (characters outside of the reserved list of RFC 3986 found)", "rfc3986" end do -- ensure it is properly percent-encoded local raw = gsub(path, "%%%x%x", "___") if raw:find("%", nil, true) then local err = raw:sub(raw:find("%%.?.?")) return nil, "invalid url-encoded value: '" .. err .. "'" end end return true end local function validate_name(name) if not match(name, "^[%w%.%-%_~]+$") then return nil, "invalid value '" .. name .. "': it must only contain alphanumeric and '., -, _, ~' characters" end return true end local function validate_sni(host) local res, err_or_port = utils.normalize_ip(host) if type(err_or_port) == "string" and err_or_port ~= "invalid port number" then return nil, "invalid value: " .. host end if res.type ~= "name" then return nil, "must not be an IP" end if err_or_port == "invalid port number" or type(res.port) == "number" then return nil, "must not have a port" end return true end local function validate_url(url) local parsed_url, err = socket_url.parse(url) if not parsed_url then return nil, "could not parse url. " .. err end if not parsed_url.host then return nil, "missing host in url" end if not parsed_url.scheme then return nil, "missing scheme in url" end return true end local function validate_certificate(cert) local ok ok, cert = pcall(openssl_x509.new, cert) if not ok then return nil, "invalid certificate: " .. cert end return true end local function validate_key(key) local ok ok, key = pcall(openssl_pkey.new, key) if not ok then return nil, "invalid key: " .. key end return true end local typedefs = {} typedefs.http_method = Schema.define { type = "string", match = "^%u+$", } typedefs.protocol = Schema.define { type = "string", one_of = { "http", "https", } } typedefs.host = Schema.define { type = "string", custom_validator = validate_host, } typedefs.port = Schema.define { type = "integer", between = { 0, 65535 } } typedefs.path = Schema.define { type = "string", starts_with = "/", match_none = { { pattern = "//", err = "must not have empty segments" }, }, custom_validator = validate_path, } typedefs.url = Schema.define { type = "string", custom_validator = validate_url, } typedefs.header_name = Schema.define { type = "string", custom_validator = utils.validate_header_name, } typedefs.timeout = Schema.define { type = "integer", between = { 0, math.pow(2, 31) - 2 }, } typedefs.uuid = Schema.define { type = "string", uuid = true, auto = true, } typedefs.auto_timestamp_s = Schema.define { type = "integer", timestamp = true, auto = true } typedefs.auto_timestamp_ms = Schema.define { type = "number", timestamp = true, auto = true } typedefs.no_api = Schema.define { type = "foreign", reference = "apis", eq = null, } typedefs.no_route = Schema.define { type = "foreign", reference = "routes", eq = null, } typedefs.no_service = Schema.define { type = "foreign", reference = "services", eq = null, } typedefs.no_consumer = Schema.define { type = "foreign", reference = "consumers", eq = null, } typedefs.name = Schema.define { type = "string", unique = true, custom_validator = validate_name } typedefs.sni = Schema.define { type = "string", custom_validator = validate_sni, } typedefs.certificate = Schema.define { type = "string", custom_validator = validate_certificate, } typedefs.key = Schema.define { type = "string", custom_validator = validate_key, } return typedefs
--- A library of ready-to-use type synonyms to use in schema definitions. -- @module kong.db.schema.typedefs local utils = require "kong.tools.utils" local openssl_pkey = require "openssl.pkey" local openssl_x509 = require "openssl.x509" local Schema = require("kong.db.schema") local socket_url = require("socket.url") local match = string.match local gsub = string.gsub local null = ngx.null local type = type local function validate_host(host) local res, err_or_port = utils.normalize_ip(host) if type(err_or_port) == "string" and err_or_port ~= "invalid port number" then return nil, "invalid value: " .. host end if err_or_port == "invalid port number" or type(res.port) == "number" then return nil, "must not have a port" end return true end local function validate_path(path) if not match(path, "^/[%w%.%-%_~%/%%]*$") then return nil, "invalid path: '" .. path .. "' (characters outside of the reserved list of RFC 3986 found)", "rfc3986" end do -- ensure it is properly percent-encoded local raw = gsub(path, "%%%x%x", "___") if raw:find("%", nil, true) then local err = raw:sub(raw:find("%%.?.?")) return nil, "invalid url-encoded value: '" .. err .. "'" end end return true end local function validate_name(name) if not match(name, "^[%w%.%-%_~]+$") then return nil, "invalid value '" .. name .. "': it must only contain alphanumeric and '., -, _, ~' characters" end return true end local function validate_sni(host) local res, err_or_port = utils.normalize_ip(host) if type(err_or_port) == "string" and err_or_port ~= "invalid port number" then return nil, "invalid value: " .. host end if res.type ~= "name" then return nil, "must not be an IP" end if err_or_port == "invalid port number" or type(res.port) == "number" then return nil, "must not have a port" end return true end local function validate_url(url) local parsed_url, err = socket_url.parse(url) if not parsed_url then return nil, "could not parse url. " .. err end if not parsed_url.host then return nil, "missing host in url" end if not parsed_url.scheme then return nil, "missing scheme in url" end return true end local function validate_certificate(cert) local ok ok, cert = pcall(openssl_x509.new, cert) if not ok then return nil, "invalid certificate: " .. cert end return true end local function validate_key(key) local ok ok, key = pcall(openssl_pkey.new, key) if not ok then return nil, "invalid key: " .. key end return true end local typedefs = {} typedefs.http_method = Schema.define { type = "string", match = "^%u+$", } typedefs.protocol = Schema.define { type = "string", one_of = { "http", "https", } } typedefs.host = Schema.define { type = "string", custom_validator = validate_host, } typedefs.port = Schema.define { type = "integer", between = { 0, 65535 } } typedefs.path = Schema.define { type = "string", starts_with = "/", match_none = { { pattern = "//", err = "must not have empty segments" }, }, custom_validator = validate_path, } typedefs.url = Schema.define { type = "string", custom_validator = validate_url, } typedefs.header_name = Schema.define { type = "string", custom_validator = utils.validate_header_name, } typedefs.timeout = Schema.define { type = "integer", between = { 0, math.pow(2, 31) - 2 }, } typedefs.uuid = Schema.define { type = "string", uuid = true, auto = true, } typedefs.auto_timestamp_s = Schema.define { type = "integer", timestamp = true, auto = true } typedefs.auto_timestamp_ms = Schema.define { type = "number", timestamp = true, auto = true } typedefs.no_api = Schema.define { type = "foreign", reference = "apis", eq = null, } typedefs.no_route = Schema.define { type = "foreign", reference = "routes", eq = null, } typedefs.no_service = Schema.define { type = "foreign", reference = "services", eq = null, } typedefs.no_consumer = Schema.define { type = "foreign", reference = "consumers", eq = null, } typedefs.name = Schema.define { type = "string", unique = true, custom_validator = validate_name } typedefs.sni = Schema.define { type = "string", custom_validator = validate_sni, } typedefs.certificate = Schema.define { type = "string", custom_validator = validate_certificate, } typedefs.key = Schema.define { type = "string", custom_validator = validate_key, } setmetatable(typedefs, { __index = function(_, k) error("schema typedef error: definition " .. k .. " does not exist", 2) end }) return typedefs
feat(schema) catch typedef typos to print a nicer error
feat(schema) catch typedef typos to print a nicer error A typo in a typedef could lead to very cryptic error messages. This adds a metatable which catches accesses to unknown fields, producing an immediate error that is more evident for plugin authors. Since the metatable only hits on invalid accesses which are always plugin development bugs, this metatable adds no runtime overhead. From #3935
Lua
apache-2.0
Kong/kong,Kong/kong,Mashape/kong,Kong/kong
13947897ea5af0afc4ea46db4dbfeb63ee557f94
src/gluttony.lua
src/gluttony.lua
local sentinel = {} local end_program = {} local end_quote = {} local function exit (operands) print ('result', unpack (operands)) print ('exit') end local function quote (operands) return operands end local function operator_prototype (operators, execute) local delimit_counter = 1 local delimiter = sentinel if execute == exit then delimiter = end_program end -- a special end_program delimiter is required to exit the program local operands = {} local handle_operands = function (_) table.insert (operands, _) end local handle_quoted_operands = function (_) if _ == quote then delimit_counter = delimit_counter + 1 end handle_operands (_) end local handle_operators = function (_) table.insert (operators, operator_prototype (operators, _)) end if execute == quote then delimiter = end_quote handle_operators = handle_quoted_operands end -- suspend execution of quoted return function (...) -- if (execute == eval_quotes) then print ('!') end local args = {...} local _ while (function () _ = table.remove (args, 1) return not (_ == nil or _ == delimiter) end) () do if type (_) == 'function' then handle_operators (_) else handle_operands (_) end end if _ == delimiter then delimit_counter = delimit_counter - 1 end if delimit_counter <= 0 then table.remove (operators) local output = { execute (operands, operators) } for i, v in ipairs (args) do table.insert (output, v) end return output end end end function eval (operands, operators) for i, v in ipairs (operands) do local _ = operators[#operators] (v) while not (_ == nil or #operators == 0) do _ = operators[#operators] (unpack (_)) end end end function processor_prototype () local operators = {} table.insert (operators, operator_prototype (operators, exit)) return function (...) eval ({...}, operators) end end function eval_quotes (operands, operators) print ('eval', unpack (operands)) for i, v in ipairs (operands) do eval (v, operators) end end local function combinator_prototype (op) return function (operands) -- print ('operands', unpack (operands)) local _ = table.remove (operands, 1) for i, v in ipairs (operands) do if type(v) == 'table' then print ('table', unpack (v)) end _ = op (_, v) end return _ end end local add = combinator_prototype (function (x, y) return x + y end) local sub = combinator_prototype (function (x, y) return x - y end) local loop loop = function (operands, operators) local idx = operands[1] local limit = operands[2] local step = operands[3] print('loop', unpack (operands)) if idx < limit then table.insert (operators, operator_prototype (operators, loop)) return idx + step, limit, step, sentinel end end local app = processor_prototype () app (add, 1, 2, 3, 4, 5, 6, eval_quotes, quote, add, 1, 2, 3, add, 1, 2, 3, sentinel, end_quote, quote, add, 1, 2, 3, sentinel, sentinel, end_quote, sentinel, sub, 2, 3, sentinel, loop, 0, 10, 2, sentinel, sentinel, 7, 8, sentinel, sentinel, end_program) -- app (1, 2) -- app (3, 4) -- app (5, 6) -- app (sub) -- app (2, 3, sentinel) -- app (loop) -- app (0, 10, 2, sentinel) -- app (sentinel, 7, 8, sentinel, sentinel)
local sentinel = {} local end_program = {} local end_quote = {} local function exit (operands) print ('result', unpack (operands)) print ('exit') end local function quote (operands) return operands end local function operator_prototype (operators, execute) local delimit_counter = 1 local delimiter = sentinel local operands = {} local handle_operands = function (_) table.insert (operands, _) end local handle_quoted_operators = function (_) delimit_counter = delimit_counter + 1 handle_operands (_) end local handle_operators = function (_) table.insert (operators, operator_prototype (operators, _)) end local check_sequence = function (_) return not (_ == nil or _ == delimiter) end local check_sequence_quoted = function (_) return _ ~= nil and delimit_counter > 0 end if execute == quote then -- suspend execution of quoted check_sequence = check_sequence_quoted handle_operators = handle_quoted_operators elseif -- a special end_program delimiter is required to exit the program execute == exit then delimiter = end_program end return function (...) local args = {...} local _ while (function () _ = table.remove (args, 1) if _ == delimiter then delimit_counter = delimit_counter - 1 end return check_sequence (_) end) () do if type (_) == 'function' then handle_operators (_) else handle_operands (_) end end -- debug -- print (delimit_counter) -- debug if delimit_counter <= 0 then table.remove (operators) local output = { execute (operands, operators) } for i, v in ipairs (args) do table.insert (output, v) end return output end end end function eval (operands, operators) for i, v in ipairs (operands) do local _ = operators[#operators] (v) while not (_ == nil or #operators == 0) do _ = operators[#operators] (unpack (_)) end end end function processor_prototype () local operators = {} table.insert (operators, operator_prototype (operators, exit)) return function (...) eval ({...}, operators) end end function eval_quotes (operands, operators) print ('eval', unpack (operands)) for i, v in ipairs (operands) do eval (v, operators) end end local function combinator_prototype (op) return function (operands) local _ = table.remove (operands, 1) for i, v in ipairs (operands) do if type(v) == 'table' then print ('table', unpack (v)) end _ = op (_, v) end return _ end end local add = combinator_prototype (function (x, y) return x + y end) local sub = combinator_prototype (function (x, y) return x - y end) local mul = combinator_prototype (function (x, y) return x * y end) local div = combinator_prototype (function (x, y) return x / y end) local loop loop = function (operands, operators) local idx = operands[1] local limit = operands[2] local step = operands[3] print('loop', unpack (operands)) if idx < limit then table.insert (operators, operator_prototype (operators, loop)) return idx + step, limit, step, sentinel end end local app = processor_prototype () -- app (add, 1, 2, 3, 4, 5, 6, eval_quotes, -- quote, add, 1, 2, 3, add, 1, 2, 3, sentinel, sentinel, quote, add, 1, 2, 3, sentinel, sentinel, sentinel, -- sentinel, sub, 2, 3, sentinel, loop, 0, 10, 2, sentinel, sentinel, 7, 8, sentinel, sentinel, end_program) app (eval_quotes, quote, div, 1, 2, 3, add, 4, 5, 6, sentinel, sentinel, sentinel, sentinel, end_program) -- app (1, 2) -- app (3, 4) -- app (5, 6) -- app (sub) -- app (2, 3, sentinel) -- app (loop) -- app (0, 10, 2, sentinel) -- app (sentinel, 7, 8, sentinel, sentinel)
Fixed evaluation.
Fixed evaluation.
Lua
mit
alisa-dolinsky/Thirst,alisa-dolinsky/Gluttony,Alisaxy/Thirst
cea9f62b62ef491c29140992b7e33a801b5fa87d
src/utils.lua
src/utils.lua
local utils = {} function utils.curl(url) local f = io.popen(('curl -s -m 5 "%s"'):format(url)) local r = f:read("*a") f:close() return r end function utils.wget(url) local fn = "/tmp/" ..tostring(math.random()) os.execute('wget --timeout=0 --waitretry=0 --tries=1 -O ' .. fn .. ' "' .. url .. '"') local f = io.open(fn, "rb") local ret = f:read("*a") f:close() os.remove(fn) return ret end function utils.htmlDecode(str) local entities = { ["&#34;"] = [["]], ["&quot;"] = [["]], ["&#39;"] = [[']], ["&apos;"] = [[']], ["&#38;"] = [[&]], ["&amp;"] = [[&]], ["&#60;"] = [[<]], ["&lt;"] = [[<]], ["&#62;"] = [[>]], ["&gt;"] = [[>]], ["&#91;"] = "[", ["&#93;"] = "]", ["&#160;"] = [[ ]], ["&nbsp;"] = [[ ]], } for k, v in pairs(entities) do str = str:gsub(k, v) end return str end function utils.encodeVar(var) if type(var) == "string" then return '"' .. var:gsub("\\", "\\\\"):gsub('"', [[\"]]):gsub("\n", [[\n]]):gsub("\r", [[\r]]) .. '"' elseif type(var) == "number" then return var elseif type(var) == "table" then return utils.encode(var) else return tostring(var) end end function utils.encode(t, n) assert(type(t) == "table") if type(n) ~= "number" then n = 0 end local tabs = string.rep("\t", n) local ret = "{\n" for k, v in pairs(t) do ret = ret .. tabs .. '\t[' .. utils.encodeVar(k) .. '] = ' .. (type(v) == "table" and utils.encode(v, n + 1) or utils.encodeVar(v)) .. ",\n" end ret = ret .. tabs .. "}" return ret end function utils.save(t, path) assert(type(t) == "table") local f = io.open(path, "w") f:write("return " .. utils.encode(t)) f:close() end function utils.sandbox(t) local ret = {} for _, name in pairs(t) do if _G[name] then if type(_G[name]) == "table" then ret[name] = {} for k, v in pairs(_G[name]) do if type(v) == "function" then ret[name][k] = function (...) return v(...) end else ret[name][k] = v end end elseif type(_G[name]) == "function" then ret[name] = function (...) return _G[name](...) end else ret[name] = _G[name] end end end return ret end function utils.rand(...) local t = {...} return t[math.random(#t)] end function utils.url_encode(str) if (str) then str = str:gsub("([^%w %-%_%.%~])", function (c) return string.format ("%%%02X", string.byte(c)) end):gsub(" ", "+") end return str end function utils.shuffle(t) local nums = {} local ret = {} for k = 1, #t do nums[k] = k end for k = 1, #t do local rnd = math.random(#nums) table.insert(ret, t[nums[rnd]]) table.remove(nums, rnd) end for k = 1, #t do t[k] = ret[k] end end function utils.readFile(fn) local f = io.open(fn, "rb") if not f then return "(Not found)" end local data = { filename = fn, data = f:read("*a") } f:close() return data end return utils
local utils = {} function utils.curl(url) local f = io.popen(('curl -s -m 5 "%s"'):format(url)) local r = f:read("*a") f:close() return r end function utils.wget(url) local fn = "/tmp/" ..tostring(math.random()) os.execute('wget --timeout=0 --waitretry=0 --tries=1 -O ' .. fn .. ' "' .. url .. '"') local f = io.open(fn, "rb") local ret = f:read("*a") f:close() os.remove(fn) return ret end function utils.htmlDecode(str) local entities = { ["&#34;"] = [["]], ["&quot;"] = [["]], ["&#39;"] = [[']], ["&apos;"] = [[']], ["&#38;"] = [[&]], ["&amp;"] = [[&]], ["&#60;"] = [[<]], ["&lt;"] = [[<]], ["&#62;"] = [[>]], ["&gt;"] = [[>]], ["&#91;"] = "[", ["&#93;"] = "]", ["&#160;"] = [[ ]], ["&nbsp;"] = [[ ]], } for k, v in pairs(entities) do str = str:gsub(k, v) end return str end function utils.encodeVar(var) if type(var) == "string" then return '"' .. var:gsub("\\", "\\\\"):gsub('"', [[\"]]):gsub("\n", [[\n]]):gsub("\r", [[\r]]) .. '"' elseif type(var) == "number" then if var == math.floor(var) then var = math.floor(var) end return var elseif type(var) == "table" then return utils.encode(var) else return tostring(var) end end function utils.encode(t, n) assert(type(t) == "table") if type(n) ~= "number" then n = 0 end local tabs = string.rep("\t", n) local ret = "{\n" for k, v in pairs(t) do ret = ret .. tabs .. '\t[' .. utils.encodeVar(k) .. '] = ' .. (type(v) == "table" and utils.encode(v, n + 1) or utils.encodeVar(v)) .. ",\n" end ret = ret .. tabs .. "}" return ret end function utils.save(t, path) assert(type(t) == "table") local f = io.open(path, "w") f:write("return " .. utils.encode(t)) f:close() end function utils.sandbox(t) local ret = {} for _, name in pairs(t) do if _G[name] then if type(_G[name]) == "table" then ret[name] = {} for k, v in pairs(_G[name]) do if type(v) == "function" then ret[name][k] = function (...) return v(...) end else ret[name][k] = v end end elseif type(_G[name]) == "function" then ret[name] = function (...) return _G[name](...) end else ret[name] = _G[name] end end end return ret end function utils.rand(...) local t = {...} return t[math.random(#t)] end function utils.url_encode(str) if (str) then str = str:gsub("([^%w %-%_%.%~])", function (c) return string.format ("%%%02X", string.byte(c)) end):gsub(" ", "+") end return str end function utils.shuffle(t) local nums = {} local ret = {} for k = 1, #t do nums[k] = k end for k = 1, #t do local rnd = math.random(#nums) table.insert(ret, t[nums[rnd]]) table.remove(nums, rnd) end for k = 1, #t do t[k] = ret[k] end end function utils.readFile(fn) local f = io.open(fn, "rb") if not f then return "(Not found)" end local data = { filename = fn, data = f:read("*a") } f:close() return data end return utils
fix: a patch for integer
fix: a patch for integer
Lua
apache-2.0
SJoshua/Project-Small-R
d098213fc60109b21ae4014357bab8c7fe0b056b
lua/job.lua
lua/job.lua
local _M = { _VERSION = "1.1.0" } local lock = require "resty.lock" local JOBS = ngx.shared.jobs local ipairs = ipairs local update_time = ngx.update_time local ngx_now = ngx.now local worker_exiting = ngx.worker.exiting local timer_at = ngx.timer.at local ngx_log = ngx.log local INFO, ERR, WARN = ngx.INFO, ngx.ERR, ngx.WARN local pcall, setmetatable = pcall, setmetatable local worker_pid = ngx.worker.pid local tinsert = table.insert local function now() update_time() return ngx_now() end local main local function run_job(delay, self, ...) if worker_exiting() then return self:finish(...) end local ok, err = timer_at(delay, main, self, ...) if not ok then ngx_log(ERR, self.key .. " failed to add timer: ", err) self:stop() self:clean() end end main = function(premature, self, ...) if premature or not self:running() then return self:finish(...) end for _,other in ipairs(self.wait_others) do if not other:completed() then run_job(0.1, self, ...) return end end local mtx = lock:new("jobs", { timeout = 0.1, exptime = 600 }) local remains = mtx:lock(self.key .. ":mtx") if not remains then if self:running() then run_job(0.1, self, ...) end return end if self:suspended() then run_job(0.1, self, ...) mtx:unlock() return end if now() >= self:get_next_time() then local counter = JOBS:incr(self.key .. ":counter", 1, -1) local ok, err = pcall(self.callback, { counter = counter, hup = self.pid == nil }, ...) if not self.pid then self.pid = worker_pid() end if not ok then ngx_log(WARN, self.key, ": ", err) end self:set_next_time() end mtx:unlock() run_job(self:get_next_time() - now(), self, ...) end local job = {} -- public api function _M.new(name, callback, interval, finish) local j = { callback = callback, finish_fn = finish, interval = interval, key = name, wait_others = {}, pid = nil } return setmetatable(j, { __index = job }) end function job:run(...) if not self:completed() then ngx_log(INFO, "job ", self.key, " start") JOBS:set(self.key .. ":running", 1) self:set_next_time() return run_job(0, self, ...) end ngx_log(INFO, "job ", self.key, " already completed") return nil, "completed" end function job:suspend() if not self:suspended() then ngx_log(INFO, "job ", self.key, " suspended") JOBS:set(self.key .. ":suspended", 1) end end function job:resume() if self:suspended() then ngx_log(INFO, "job ", self.key, " resumed") JOBS:delete(self.key .. ":suspended") end end function job:stop() ngx_log(INFO, "job ", self.key, " stopped") JOBS:delete(self.key .. ":running") JOBS:set(self.key .. ":completed", 1) end function job:completed() return JOBS:get(self.key .. ":completed") == 1 end function job:running() return JOBS:get(self.key .. ":running") == 1 end function job:suspended() return JOBS:get(self.key .. ":suspended") == 1 end function job:finish(...) if self.finish_fn then self.finish_fn(...) end JOBS:delete(self.key .. ":running") end function job:wait_for(other) tinsert(self.wait_others, other) end function job:set_next_time() JOBS:set(self.key .. ":next", now() + self.interval) end function job:get_next_time() return JOBS:get(self.key .. ":next") end function job:clean() if not self:running() then JOBS:delete(self.key .. ":running") JOBS:delete(self.key .. ":completed") JOBS:delete(self.key .. ":suspended") return true end return false end return _M
local _M = { _VERSION = "1.8.5" } local lock = require "resty.lock" local JOBS = ngx.shared.jobs local ipairs = ipairs local update_time = ngx.update_time local ngx_now = ngx.now local worker_exiting = ngx.worker.exiting local timer_at = ngx.timer.at local ngx_log = ngx.log local INFO, ERR, WARN = ngx.INFO, ngx.ERR, ngx.WARN local pcall, setmetatable = pcall, setmetatable local worker_pid = ngx.worker.pid local tinsert = table.insert local assert = assert local function now() update_time() return ngx_now() end local main local function run_job(delay, self, ...) if worker_exiting() then return self:finish(...) end local ok, err = timer_at(delay, main, self, ...) if not ok then ngx_log(ERR, self.key .. " failed to add timer: ", err) self:stop() self:clean() return false end return true end main = function(premature, self, ...) if premature or not self:running() then return self:finish(...) end for _,other in ipairs(self.wait_others) do if not other:completed() then run_job(0.1, self, ...) return end end local mtx = lock:new("jobs", { timeout = 0.1, exptime = 600 }) local remains = mtx:lock(self.key .. ":mtx") if not remains then if self:running() then run_job(0.1, self, ...) end return end if self:suspended() then run_job(0.1, self, ...) mtx:unlock() return end if now() >= self:get_next_time() then local counter = JOBS:incr(self.key .. ":counter", 1, -1) local ok, err = pcall(self.callback, { counter = counter, hup = self.pid == nil }, ...) if not self.pid then self.pid = worker_pid() end if not ok then ngx_log(WARN, self.key, ": ", err) end self:set_next_time() end mtx:unlock() run_job(self:get_next_time() - now(), self, ...) end local job = {} -- public api function _M.new(name, callback, interval, finish) local j = { callback = callback, finish_fn = finish, interval = interval, key = name, wait_others = {}, pid = nil } return setmetatable(j, { __index = job }) end function job:run(...) if not self:completed() then ngx_log(INFO, "job ", self.key, " start") JOBS:set(self.key .. ":running", 1) self:set_next_time() return assert(run_job(0, self, ...)) end ngx_log(INFO, "job ", self.key, " already completed") return nil, "completed" end function job:suspend() if not self:suspended() then ngx_log(INFO, "job ", self.key, " suspended") JOBS:set(self.key .. ":suspended", 1) end end function job:resume() if self:suspended() then ngx_log(INFO, "job ", self.key, " resumed") JOBS:delete(self.key .. ":suspended") end end function job:stop() JOBS:delete(self.key .. ":running") JOBS:set(self.key .. ":completed", 1) ngx_log(INFO, "job ", self.key, " stopped") end function job:completed() return JOBS:get(self.key .. ":completed") == 1 end function job:running() return JOBS:get(self.key .. ":running") == 1 end function job:suspended() return JOBS:get(self.key .. ":suspended") == 1 end function job:finish(...) if self.finish_fn then self.finish_fn(...) end return true end function job:wait_for(other) tinsert(self.wait_others, other) end function job:set_next_time() JOBS:set(self.key .. ":next", now() + self.interval) end function job:get_next_time() return JOBS:get(self.key .. ":next") end function job:clean() if not self:running() then JOBS:delete(self.key .. ":running") JOBS:delete(self.key .. ":completed") JOBS:delete(self.key .. ":suspended") return true end return false end return _M
fix job
fix job
Lua
bsd-2-clause
ZigzagAK/nginx-resty-auto-healthcheck-config,ZigzagAK/nginx-resty-auto-healthcheck-config