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
|
|---|---|---|---|---|---|---|---|---|---|
326ceb6afbf0a4fa6a0483f9a11cf440b8e16449
|
mods/_misc/aliases.lua
|
mods/_misc/aliases.lua
|
local alias = minetest.register_alias
-- Remove duplicated items from the carbone subgame because of Moreores mod
-- Stone
alias("default:stone_with_tin", "default:stone")
alias("default:stone_with_silver", "default:stone")
-- Lump
alias("default:tin_lump", "default:stone")
alias("default:silver_lump", "default:stone")
-- Ingot
alias("default:tin_ingot", "default:stone")
alias("default:silver_ingot", "default:stone")
-- Block
alias("default:tinblock", "default:stone")
alias("default:silverblock", "default:stone")
-- Tools
alias("default:pick_silver", "default:stone")
alias("default:shovel_silver", "default:stone")
alias("default:axe_silver", "default:stone")
alias("default:sword_silver", "default:stone")
alias("default:knife_silver", "default:stone")
-- Remove torch from torches => remise des torches par défaut
alias("torches:floor", "default:torch")
alias("torches:wand", "default:torch")
-- Remove copper_rail from moreores => utilisation des rail_copper du mod carts
alias("moreores:copper_rail", "carts:rail_copper")
-- Old fishing mod to the new fishing mod
alias("fishing:fish_cooked", "fishing:fish")
alias("fishing:worm", "fishing:bait_worm")
-- Old itemframes mod to the new itemframes(v2) mod
alias("itemframes:pedestal", "itemframes:pedestal_cobble")
-- Remove "moreores:copper_rail" for "carts:copper_rail"
alias("moreores:copper_rail", "carts:rail_copper")
-- Remove "multitest:hayblock" because farming redo include it now
alias("multitest:hayblock", "farming:straw")
-- Remove "darkage:stair_straw", "darkage:straw", "darkage:straw_bale" and "darkage:adobe"
alias("darkage:stair_straw", "farming:straw")
alias("darkage:straw", "farming:straw")
alias("darkage:straw_bale", "farming:straw")
alias("darkage:adobe", "farming:straw")
-- Remove "wiki:wiki"
alias("wiki:wiki", "default:bookshelf")
-- Remove "building_blocks:knife"
alias("building_blocks:knife", "default:sword_steel")
-- Remove "jumping" mod
alias("jumping:cushion", "wool:dark_green")
for i = 1, 6 do
alias("jumping:trampoline_" .. i, "default:wood")
end
-- Remove "xmas_tree" from snow mod
alias("snow:xmas_tree", "default:dirt")
-- remove "fake_fire:flint_and_steel" from homedecor_modpack mod
alias("fake_fire:flint_and_steel", "fire:flint_and_steel")
|
local alias = minetest.register_alias
-- Remove duplicated items from the carbone subgame because of Moreores mod
-- Stone
alias("default:stone_with_tin", "default:stone")
alias("default:stone_with_silver", "default:stone")
-- Lump
alias("default:tin_lump", "default:stone")
alias("default:silver_lump", "default:stone")
-- Ingot
alias("default:tin_ingot", "default:stone")
alias("default:silver_ingot", "default:stone")
-- Block
alias("default:tinblock", "default:stone")
alias("default:silverblock", "default:stone")
-- Tools
alias("default:pick_silver", "default:stone")
alias("default:shovel_silver", "default:stone")
alias("default:axe_silver", "default:stone")
alias("default:sword_silver", "default:stone")
alias("default:knife_silver", "default:stone")
-- Remove torch from torches => remise des torches par défaut
alias("torches:floor", "default:torch")
alias("torches:wand", "default:torch")
-- Remove copper_rail from moreores => utilisation des rail_copper du mod carts
alias("moreores:copper_rail", "carts:rail_copper")
-- Old fishing mod to the new fishing mod
alias("fishing:fish_cooked", "fishing:fish")
alias("fishing:worm", "fishing:bait_worm")
-- Old itemframes mod to the new itemframes(v2) mod
alias("itemframes:pedestal", "itemframes:pedestal_cobble")
-- Remove "moreores:copper_rail" for "carts:copper_rail"
alias("moreores:copper_rail", "carts:rail_copper")
-- Remove "multitest:hayblock" because farming redo include it now
alias("multitest:hayblock", "farming:straw")
-- Remove "darkage:stair_straw", "darkage:straw", "darkage:straw_bale" and "darkage:adobe"
alias("darkage:stair_straw", "farming:straw")
alias("darkage:straw", "farming:straw")
alias("darkage:straw_bale", "farming:straw")
alias("darkage:adobe", "farming:straw")
-- Remove "wiki:wiki"
alias("wiki:wiki", "default:bookshelf")
-- Remove "building_blocks:knife"
alias("building_blocks:knife", "default:sword_steel")
-- Remove "jumping" mod
alias("jumping:cushion", "wool:dark_green")
for i = 1, 6 do
alias("jumping:trampoline_" .. i, "default:wood")
end
-- Remove "xmas_tree" from snow mod
alias("snow:xmas_tree", "default:dirt")
-- remove "fake_fire:flint_and_steel" from homedecor_modpack mod
alias("fake_fire:flint_and_steel", "fire:flint_and_steel")
-- remove ongen pine saplings from moretrees
alias("moretrees:pine_sapling_ongen", "default:pine_sapling")
|
[_misc] Register alias for ongen pine sapling; fix #481
|
[_misc] Register alias for ongen pine sapling; fix #481
|
Lua
|
unlicense
|
MinetestForFun/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,sys4-fr/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,MinetestForFun/server-minetestforfun,MinetestForFun/server-minetestforfun,Ombridride/minetest-minetestforfun-server,Coethium/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,Coethium/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,Coethium/server-minetestforfun,crabman77/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server
|
0f290f8f0f274e7165de25a7f604f323c9a390bb
|
npc/base/talk.lua
|
npc/base/talk.lua
|
--- Base NPC script for talking NPCs
--
-- This script offers all functions needed to get NPCs to talk.
--
-- Author: Martin Karing
require("base.common")
require("base.messages")
require("base.class")
require("npc.base.basic")
require("npc.base.responses")
module("npc.base.talk", package.seeall)
talkNPC = base.class.class(function(self, rootNPC)
if (rootNPC == nil or not rootNPC:is_a(npc.base.basic.baseNPC)) then
return;
end;
self["_parent"] = rootNPC;
self["_entry"] = nil;
self["_cycleText"] = nil;
self["_state"] = 0;
self["_saidNumber"] = nil;
self["_nextCycleText"] = -1;
end);
function talkNPC:addCycleText(germanText, englishText)
if (self._cycleText == nil) then
self._cycleText = base.messages.Messages();
self._parent:addCycle(self);
end;
self._cycleText:addMessage(germanText, englishText);
end;
function talkNPC:addTalkingEntry(newEntry)
if (newEntry == nil or not newEntry:is_a(talkNPCEntry)) then
return;
end;
if (self._entry == nil) then
self._parent:addRecvText(self);
self._entry = {};
end;
newEntry:setParent(self);
table.insert(self._entry, newEntry);
end;
function talkNPC:receiveText(npcChar, player, text)
local result = false;
table.foreach(self._entry, function(_, entry)
if entry:checkEntry(npcChar, player, text) then
entry:execute(npcChar, player);
result = true;
return true;
end;
end);
return result;
end;
function talkNPC:nextCycle(npcChar, counter)
if (counter >= self._nextCycleText) then
self._nextCycleText = math.random(1200, 3600); --2 to 6 minutes
local german, english = self._cycleText:getRandomMessage();
npcChar:talkLanguage(Character.say, Player.german, german);
npcChar:talkLanguage(Character.say, Player.english, english);
else
self._nextCycleText = self._nextCycleText - counter;
end;
return self._nextCycleText;
end;
talkNPCEntry = base.class.class(function(self)
self["_trigger"] = {};
self["_conditions"] = {};
self["_responses"] = {};
self["_responseProcessors"] = {};
self["_responsesCount"] = 0;
self["_consequences"] = {};
self["_parent"] = nil;
end);
function talkNPCEntry:addTrigger(text)
if (text == nil or type(text) ~= "string") then
return;
end;
text = string.lower(text);
text = string.gsub(text,'([ ]+)',' .*'); -- replace all spaces by " .*"
table.insert(self._trigger, text);
end;
function talkNPCEntry:setParent(npc)
local updateFkt = function(_, value)
value:setNPC(npc);
end;
table.foreach(self._conditions, updateFkt);
table.foreach(self._consequences, updateFkt);
self._parent = npc;
end;
function talkNPCEntry:addCondition(condition)
if (condition == nil or not condition:is_a(npc.base.condition.condition.condition)) then
return;
end;
table.insert(self._conditions, condition);
if (self._parent ~= nil) then
condition:setNPC(self._parent);
end;
end;
function talkNPCEntry:addResponse(text)
if (text == nil or type(text) ~= "string") then
return;
end;
table.insert(self._responses, text);
for _, processor in pairs(npc.base.responses.processorList) do
if processor:check(text) then
if (self._responseProcessors[self._responsesCount] == nil) then
self._responseProcessors[self._responsesCount] = {};
end;
debug("Processor found for response: " .. self._responsesCount);
table.insert(self._responseProcessors[self._responsesCount], processor)
end;
end;
self._responsesCount = self._responsesCount + 1;
end;
function talkNPCEntry:addConsequence(consequence)
if (consequence == nil or not consequence:is_a(npc.base.consequence.consequence.consequence)) then
return;
end;
table.insert(self._consequences, consequence);
if (self._parent ~= nil) then
consequence:setNPC(self._parent);
end;
end;
function talkNPCEntry:checkEntry(npcChar, player, text)
for _1, pattern in pairs(self._trigger) do
local a, _2, number = string.find(text, pattern);
self._saidNumber = number;
if (a ~= nil) then
local conditionsResult = true;
for _3, condition in pairs(self._conditions) do
if not condition:check(npcChar, player) then
conditionsResult = false;
break;
end;
end;
if conditionsResult then
return true;
end;
end;
end;
end;
function talkNPCEntry:execute(npcChar, player)
if (self._responsesCount > 0) then
local selectedResponse = math.random(1, self._responsesCount) - 1;
local responseText = self._responses[selectedResponse];
local responseProcessors = self._responseProcessors[selectedResponse];
if (responseProcessors ~= nil) then
for _, processor in pairs(responseProcessors) do
responseText = processor:process(player, self._parent, npcChar, responseText);
debug("Processing!");
end;
else
debug("No response processors for response: " .. selectedResponse);
end;
npcChar:talk(Character.say, responseText);
end;
table.foreach(self._consequences, function(_, consequence)
if consequence then
consequence:perform(npcChar, player);
end;
end);
end;
function _set_value(value)
if (type(value) == "function") then
return value, 2;
elseif (value == "%NUMBER") then
return nil, 1;
else
return tonumber(value), 0;
end;
end;
function _get_value(npc, value, type)
if (type == 2) then
return value(npc._saidNumber);
elseif (type == 1) then
return npc._saidNumber;
elseif (type == 0) then
return value;
else
return 0;
end;
end;
|
--- Base NPC script for talking NPCs
--
-- This script offers all functions needed to get NPCs to talk.
--
-- Author: Martin Karing
require("base.common")
require("base.messages")
require("base.class")
require("npc.base.basic")
require("npc.base.responses")
module("npc.base.talk", package.seeall)
talkNPC = base.class.class(function(self, rootNPC)
if (rootNPC == nil or not rootNPC:is_a(npc.base.basic.baseNPC)) then
return;
end;
self["_parent"] = rootNPC;
self["_entry"] = nil;
self["_cycleText"] = nil;
self["_state"] = 0;
self["_saidNumber"] = nil;
self["_nextCycleText"] = -1;
end);
function talkNPC:addCycleText(germanText, englishText)
if (self._cycleText == nil) then
self._cycleText = base.messages.Messages();
self._parent:addCycle(self);
end;
self._cycleText:addMessage(germanText, englishText);
end;
function talkNPC:addTalkingEntry(newEntry)
if (newEntry == nil or not newEntry:is_a(talkNPCEntry)) then
return;
end;
if (self._entry == nil) then
self._parent:addRecvText(self);
self._entry = {};
end;
newEntry:setParent(self);
table.insert(self._entry, newEntry);
end;
function talkNPC:receiveText(npcChar, player, text)
local result = false;
table.foreach(self._entry, function(_, entry)
if entry:checkEntry(npcChar, player, text) then
entry:execute(npcChar, player);
result = true;
return true;
end;
end);
return result;
end;
function talkNPC:nextCycle(npcChar, counter)
if (counter >= self._nextCycleText) then
self._nextCycleText = math.random(1200, 3600); --2 to 6 minutes
local german, english = self._cycleText:getRandomMessage();
npcChar:talkLanguage(Character.say, Player.german, german);
npcChar:talkLanguage(Character.say, Player.english, english);
else
self._nextCycleText = self._nextCycleText - counter;
end;
return self._nextCycleText;
end;
talkNPCEntry = base.class.class(function(self)
self["_trigger"] = {};
self["_conditions"] = {};
self["_responses"] = {};
self["_responseProcessors"] = {};
self["_responsesCount"] = 0;
self["_consequences"] = {};
self["_parent"] = nil;
end);
function talkNPCEntry:addTrigger(text)
if (text == nil or type(text) ~= "string") then
return;
end;
text = string.lower(text);
text = string.gsub(text,'([ ]+)',' .*'); -- replace all spaces by " .*"
table.insert(self._trigger, text);
end;
function talkNPCEntry:setParent(npc)
local updateFkt = function(_, value)
value:setNPC(npc);
end;
table.foreach(self._conditions, updateFkt);
table.foreach(self._consequences, updateFkt);
self._parent = npc;
end;
function talkNPCEntry:addCondition(condition)
if (condition == nil or not condition:is_a(npc.base.condition.condition.condition)) then
return;
end;
table.insert(self._conditions, condition);
if (self._parent ~= nil) then
condition:setNPC(self._parent);
end;
end;
function talkNPCEntry:addResponse(text)
if (text == nil or type(text) ~= "string") then
return;
end;
table.insert(self._responses, text);
self._responsesCount = self._responsesCount + 1;
for _, processor in pairs(npc.base.responses.processorList) do
if processor:check(text) then
if (self._responseProcessors[self._responsesCount] == nil) then
self._responseProcessors[self._responsesCount] = {};
end;
table.insert(self._responseProcessors[self._responsesCount], processor)
end;
end;
end;
function talkNPCEntry:addConsequence(consequence)
if (consequence == nil or not consequence:is_a(npc.base.consequence.consequence.consequence)) then
return;
end;
table.insert(self._consequences, consequence);
if (self._parent ~= nil) then
consequence:setNPC(self._parent);
end;
end;
function talkNPCEntry:checkEntry(npcChar, player, text)
for _1, pattern in pairs(self._trigger) do
local a, _2, number = string.find(text, pattern);
self._saidNumber = number;
if (a ~= nil) then
local conditionsResult = true;
for _3, condition in pairs(self._conditions) do
if not condition:check(npcChar, player) then
conditionsResult = false;
break;
end;
end;
if conditionsResult then
return true;
end;
end;
end;
end;
function talkNPCEntry:execute(npcChar, player)
if (self._responsesCount > 0) then
local selectedResponse = math.random(1, self._responsesCount);
local responseText = self._responses[selectedResponse];
local responseProcessors = self._responseProcessors[selectedResponse];
if (responseProcessors ~= nil) then
for _, processor in pairs(responseProcessors) do
responseText = processor:process(player, self._parent, npcChar, responseText);
end;
end;
npcChar:talk(Character.say, responseText);
end;
table.foreach(self._consequences, function(_, consequence)
if consequence then
consequence:perform(npcChar, player);
end;
end);
end;
function _set_value(value)
if (type(value) == "function") then
return value, 2;
elseif (value == "%NUMBER") then
return nil, 1;
else
return tonumber(value), 0;
end;
end;
function _get_value(npc, value, type)
if (type == 2) then
return value(npc._saidNumber);
elseif (type == 1) then
return npc._saidNumber;
elseif (type == 0) then
return value;
else
return 0;
end;
end;
|
Fixed NPC bug
|
Fixed NPC bug
|
Lua
|
agpl-3.0
|
KayMD/Illarion-Content,vilarion/Illarion-Content,LaFamiglia/Illarion-Content,Baylamon/Illarion-Content,Illarion-eV/Illarion-Content
|
8afe5afdb591bd3c74dbd9d76ec8cb983b711cee
|
components/Door.lua
|
components/Door.lua
|
-- A door. It can be open or shut. When shut it blocks both movement and LOS.
-- It has two faces, face_open and face_shut, and displays one or the other depending
-- on its state.
-- For this reason, it implements :render. Entities with a door component should
-- place it before the render component so it can affect the rendering code.
local Door = {
face_open = '■';
face_shut = '+';
open = false;
segments = {};
}
function Door:__init()
self.Render.face = self.Door[self.Door.open and 'face_open' or 'face_shut']
end
function Door:open(state)
if state ~= nil and state ~= self.Door.open then
game.log('The door %s.', state and 'opens' or 'closes')
for _,segment in ipairs(self.Door.segments) do
segment.Door.open = state
segment.Render.face = segment.Door[state and 'face_open' or 'face_shut']
end
end
return self.Door.open
end
function Door:blocks()
return not self:open()
end
function Door:touchedBy(ent)
if ent.type ~= 'Player' then return end
self:open(true)
end
function Door:__frob(frobber, actions)
if self:open() then
for i,segment in ipairs(self.Door.segments) do
local x,y,map = segment:position()
if map:blocked(x, y, 'walk') then
return nil
end
end
table.insert(actions, {
name = "Close Door";
activate = function() return self:open(false) end;
})
else
table.insert(actions, {
name = "Open Door";
activate = function() return self:open(true) end;
})
end
end
return Door
|
-- A door. It can be open or shut. When shut it blocks both movement and LOS.
-- It has two faces, face_open and face_shut, and displays one or the other depending
-- on its state.
-- For this reason, it implements :render. Entities with a door component should
-- place it before the render component so it can affect the rendering code.
local Door = {
face_open = '■';
face_shut = '+';
open = false;
segments = {};
}
function Door:__init()
self.Render.face = self.Door[self.Door.open and 'face_open' or 'face_shut']
end
function Door:open(state)
if state ~= nil and state ~= self.Door.open then
game.log('The door %s.', state and 'opens' or 'closes')
for _,segment in ipairs(self.Door.segments) do
segment.Door.open = state
segment.Render.face = segment.Door[state and 'face_open' or 'face_shut']
end
end
return self.Door.open
end
function Door:blocks()
return not self:open()
end
function Door:touchedBy(ent)
if ent.type ~= 'Player' then return end
self:open(true)
end
function Door:__frob(frobber, actions)
if self:open() then
for i,segment in ipairs(self.Door.segments) do
local map = self._parent
local x,y = map:positionOf(segment)
if map:blocked(x, y, 'walk') then
return nil
end
end
table.insert(actions, {
name = "Close Door";
activate = function() return self:open(false) end;
})
else
table.insert(actions, {
name = "Open Door";
activate = function() return self:open(true) end;
})
end
end
return Door
|
Fix crash when attempting to close a door. Still kind of hacky.
|
Fix crash when attempting to close a door. Still kind of hacky.
|
Lua
|
mit
|
ToxicFrog/ttymor
|
8c2787320aa8e22e21df610904e8e999e2ece090
|
fusion/stdlib/iterable.lua
|
fusion/stdlib/iterable.lua
|
local fnl = require("fusion.stdlib.functional")
local table = require("fusion.stdlib.table")
local unpack = unpack or table.unpack -- luacheck: ignore 113
local function mk_gen(fn)
return function(...)
local a = {...}
return coroutine.wrap(function()
return fn(unpack(a))
end)
end
end
-- Infinite generators
local function count(start, step)
if not step then
return count(start, 1)
end
if not start then
return count(1, step)
end
while true do
coroutine.yield(start)
start = start + step
end
end
local function cycle(pattern, is_ipairs)
local pairs_statement = is_ipairs and ipairs or pairs
while true do
for k, v in pairs_statement(pattern) do
coroutine.yield(k, v)
end
end
end
local function rep(element, n)
if n then
for i=1, n do -- luacheck: ignore 213
coroutine.yield(element)
end
else
while true do
coroutine.yield(element)
end
end
end
-- Terminating generators
local function range(start, stop, step)
if not step then
return range(start, stop, 1)
elseif not stop then
return range(1, start, 1)
else
for i=start, stop, step do
coroutine.yield(i)
end
end
end
local function add(x, y)
return x + y
end
local xrange = mk_gen(range)
local function accumulate(input, fn)
if not fn then
return accumulate(input, add)
end
for i in xrange(#input) do
local t0 = {}
for j in xrange(1, i) do
t0[j] = input[j]
end
coroutine.yield(fnl.reduce(fn, t0))
end
end
local function chain(...)
for k, v in pairs({...}) do -- luacheck: ignore 213
if type(v) == "function" then
for val in v do
coroutine.yield(val)
end
else
for _k, _v in pairs(v) do -- luacheck: ignore 213
coroutine.yield(_v)
end
end
end
end
local function ichain(...)
for i, v in ipairs({...}) do -- luacheck: ignore 213
for _i, _v in ipairs(v) do -- luacheck: ignore 213
coroutine.yield(_v)
end
end
end
local function compress(input, selectors)
-- must use ipairs and numeric input/selectors
for i=1, math.max(#input, #selectors) do
if not input[i] then
return
else
if selectors[i] then
coroutine.yield(input[i])
end
end
end
end
local function groupby(input)
local _prev, _gen
for k, v in pairs(input) do -- luacheck: ignore 213
_gen = {}
if _prev == nil then
_prev = v
end
if _prev == v then
table.insert(_gen, v)
else
coroutine.yield(_prev, pairs(_gen))
_prev = v
_gen = {v}
end
end
coroutine.yield(_prev, pairs(_gen))
end
local function igroupby(input)
local _prev, _gen
for k, v in ipairs(input) do -- luacheck: ignore 213
_gen = {}
if _prev == nil then
_prev = v
end
if _prev == v then
table.insert(_gen, v)
else
coroutine.yield(_prev, pairs(_gen))
_prev = v
_gen = {v}
end
end
coroutine.yield(_prev, pairs(_gen))
end
local function slice(input, start, stop, step)
if not step then
return slice(input, start, stop, 1)
elseif not stop then
return slice(input, start, #input, 1)
end
for i in xrange(start, stop, step) do
coroutine.yield(input[i])
end
end
local function zip(input0, input1, default)
for i=1, math.max(#input0, #input1) do
coroutine.yield(input0[i], input1[i] or default)
end
end
-- Extended module
local xslice = mk_gen(slice)
local function take(n, input)
return table.from_generator(xslice(input, n))
end
local xcount = mk_gen(count)
local function tabulate(fn, start)
for n in xcount(start or 0) do
fn(n)
end
end
local function tail(n, input)
return table.from_generator(xslice(input, n))
end
local function consume(iterator, n)
for i in xrange(n) do -- luacheck: ignore 213
iterator()
end
return iterator
end
local function nth(n, input, default)
return input[n] or default
end
local xgroupby = mk_gen(groupby)
local function all_equal(input)
local _iter = xgroupby(input)
_iter() -- capture first input
if not _iter() then
return true
else
return false
end
end
local function truthy(val)
return not not val
end
local function quantify(input, fn)
if not fn then
return quantify(input, truthy)
end
local _val = 0
for _, n in pairs(fnl.map(fn, table.copy(input))) do
if n then
_val = _val + 1
end
end
return _val
end
local xrep = mk_gen(rep)
local xchain = mk_gen(chain)
local function padnil(input)
return xchain(input, xrep(nil))
end
local function dotproduct(t0, t1)
return fnl.sum(fnl.map((function(a, b) return a * b end), t0, t1))
end
return table.join(fnl.map(mk_gen, {
count = count;
cycle = cycle;
rep = rep;
range = range;
accumulate = accumulate;
chain = chain;
ichain = ichain;
compress = compress;
groupby = groupby;
igroupby = igroupby;
slice = slice;
zip = zip;
}), {
take = take;
tabulate = tabulate;
tail = tail;
consume = consume;
nth = nth;
all_equal = all_equal;
quantify = quantify;
padnil = padnil;
dotproduct = dotproduct;
})
|
local fnl = require("fusion.stdlib.functional")
local table = require("fusion.stdlib.table")
local unpack = unpack or table.unpack -- luacheck: ignore 113
local function mk_gen(fn)
return function(...)
local a = {...}
return coroutine.wrap(function()
return fn(unpack(a))
end)
end
end
-- Infinite generators
local function count(start, step)
if not step then
return count(start, 1)
end
if not start then
return count(1, step)
end
while true do
coroutine.yield(start)
start = start + step
end
end
local function cycle(pattern)
while true do
for k, v in pairs(pattern) do
coroutine.yield(k, v)
end
end
end
local function icycle(pattern)
while true do
for k, v in pairs(pattern) do
coroutine.yield(k, v)
end
end
end
local function rep(element, n)
if n then
for i=1, n do -- luacheck: ignore 213
coroutine.yield(element)
end
else
while true do
coroutine.yield(element)
end
end
end
-- Terminating generators
local function range(start, stop, step)
if not step then
return range(start, stop, 1)
elseif not stop then
return range(1, start, 1)
else
for i=start, stop, step do
coroutine.yield(i)
end
end
end
local function add(x, y)
return x + y
end
local xrange = mk_gen(range)
local function accumulate(input, fn)
if not fn then
return accumulate(input, add)
end
for i in xrange(#input) do
local t0 = {}
for j in xrange(1, i) do
t0[j] = input[j]
end
coroutine.yield(fnl.reduce(fn, t0))
end
end
local function chain(...)
for k, v in pairs({...}) do -- luacheck: ignore 213
if type(v) == "function" then
for val in v do
coroutine.yield(val)
end
else
for _k, _v in pairs(v) do -- luacheck: ignore 213
coroutine.yield(_v)
end
end
end
end
local function ichain(...)
for i, v in ipairs({...}) do -- luacheck: ignore 213
for _i, _v in ipairs(v) do -- luacheck: ignore 213
coroutine.yield(_v)
end
end
end
local function compress(input, selectors)
for i=1, math.max(#input, #selectors) do
if not input[i] then
return
else
if selectors[i] then
coroutine.yield(input[i])
end
end
end
end
local function groupby(input)
local _prev, _gen
for k, v in pairs(input) do -- luacheck: ignore 213
_gen = {}
if _prev == nil then
_prev = v
end
if _prev == v then
table.insert(_gen, v)
else
coroutine.yield(_prev, pairs(_gen))
_prev = v
_gen = {v}
end
end
coroutine.yield(_prev, pairs(_gen))
end
local function igroupby(input)
local _prev, _gen
for k, v in ipairs(input) do -- luacheck: ignore 213
_gen = {}
if _prev == nil then
_prev = v
end
if _prev == v then
table.insert(_gen, v)
else
coroutine.yield(_prev, pairs(_gen))
_prev = v
_gen = {v}
end
end
coroutine.yield(_prev, pairs(_gen))
end
local function slice(input, start, stop, step)
if not step then
return slice(input, start, stop, 1)
elseif not stop then
return slice(input, start, #input, 1)
end
for i in xrange(start, stop, step) do
coroutine.yield(input[i])
end
end
local function zip(input0, input1, default)
for i=1, math.max(#input0, #input1) do
coroutine.yield(input0[i], input1[i] or default)
end
end
-- Extended module
local xslice = mk_gen(slice)
local function take(n, input)
return table.from_generator(xslice(input, 1, n))
end
local xcount = mk_gen(count)
local function tabulate(fn, start)
for n in xcount(start or 0) do
fn(n)
end
end
local function tail(n, input)
return table.from_generator(xslice(input, n))
end
local function consume(iterator, n)
for i in xrange(n) do -- luacheck: ignore 213
iterator()
end
return iterator
end
local function nth(n, input, default)
return input[n] or default
end
local xgroupby = mk_gen(groupby)
local function allequal(input)
local _iter = xgroupby(input)
_iter() -- capture first input
if not _iter() then
return true
else
return false
end
end
local function truthy(val)
return not not val
end
local function quantify(input, fn)
if not fn then
return quantify(input, truthy)
end
local _val = 0
for _, n in pairs(fnl.map(fn, table.copy(input))) do
if n then
_val = _val + 1
end
end
return _val
end
local xrep = mk_gen(rep)
local xchain = mk_gen(chain)
local function padnil(input)
return xchain(input, xrep(nil))
end
local function dotproduct(t0, t1)
return fnl.sum(fnl.map((function(a, b) return a * b end), table.copy(t0),
t1))
end
return table.join(fnl.map(mk_gen, {
count = count;
cycle = cycle;
icycle = icycle;
rep = rep;
range = range;
accumulate = accumulate;
chain = chain;
ichain = ichain;
compress = compress;
groupby = groupby;
igroupby = igroupby;
slice = slice;
zip = zip;
}), {
take = take;
tabulate = tabulate;
tail = tail;
consume = consume;
nth = nth;
allequal = allequal;
quantify = quantify;
padnil = padnil;
dotproduct = dotproduct;
})
|
iterable: minor fixes
|
iterable: minor fixes
|
Lua
|
mit
|
RyanSquared/FusionScript
|
80a46b5c1a83a598144278bea44de2ecb6a4036c
|
whisper.lua
|
whisper.lua
|
local mod = EPGP:NewModule("whisper", "AceEvent-3.0")
local L = LibStub("AceLocale-3.0"):GetLocale("EPGP")
local senderMap = {}
function mod:CHAT_MSG_WHISPER(event_name, msg, sender)
if not UnitInRaid("player") then return end
if msg:sub(1, 12):lower() ~= 'epgp standby' then return end
local member = msg:match("epgp standby ([^ ]+)")
if member then
-- http://lua-users.org/wiki/LuaUnicode
local firstChar, offset = member:match("([%z\1-\127\194-\244][\128-\191]*)()")
member = firstChar:upper()..member:sub(offset):lower()
else
member = sender
end
senderMap[member] = sender
if not EPGP:GetEPGP(member) then
SendChatMessage(L["%s is not eligible for EP awards"]:format(member),
"WHISPER", nil, sender)
elseif EPGP:IsMemberInAwardList(member) then
SendChatMessage(L["%s is already in the award list"]:format(member),
"WHISPER", nil, sender)
else
EPGP:SelectMember(member)
SendChatMessage(L["%s is added to the award list"]:format(member),
"WHISPER", nil, sender)
end
end
local function SendNotifiesAndClearExtras(event_name, names, reason, amount)
EPGP:GetModule("announce"):AnnounceTo(
"GUILD",
L["If you want to be on the award list but you are not in the raid, you need to whisper me: 'epgp standby' or 'epgp standby <name>' where <name> is the toon that should receive awards"])
for member, sender in pairs(senderMap) do
if EPGP:IsMemberInExtrasList(member) then
SendChatMessage(L["%+d EP (%s) to %s"]:format(amount, reason, member),
"WHISPER", nil, sender)
SendChatMessage(
L["%s is now removed from the award list"]:format(member),
"WHISPER", nil, sender)
EPGP:DeSelectMember(member)
end
senderMap[member] = nil
end
end
mod.dbDefaults = {
profile = {
enable = false,
}
}
mod.optionsName = L["Whisper"]
mod.optionsDesc = L["Standby whispers in raid"]
mod.optionsArgs = {
help = {
order = 1,
type = "description",
name = L["Automatic handling of the standby list through whispers when in raid. When this is enabled, the standby list is cleared after each reward."],
},
}
function mod:OnEnable()
self:RegisterEvent("CHAT_MSG_WHISPER")
EPGP.RegisterCallback(self, "MassEPAward", SendNotifiesAndClearExtras)
EPGP.RegisterCallback(self, "StartRecurringAward", SendNotifiesAndClearExtras)
end
function mod:OnDisable()
EPGP.UnregisterAllCallbacks(self)
end
|
local mod = EPGP:NewModule("whisper", "AceEvent-3.0")
local L = LibStub("AceLocale-3.0"):GetLocale("EPGP")
local senderMap = {}
function mod:CHAT_MSG_WHISPER(event_name, msg, sender)
if not UnitInRaid("player") then return end
if msg:sub(1, 12):lower() ~= 'epgp standby' then return end
local member = msg:match("epgp standby ([^ ]+)")
if member then
-- http://lua-users.org/wiki/LuaUnicode
local firstChar, offset = member:match("([%z\1-\127\194-\244][\128-\191]*)()")
member = firstChar:upper()..member:sub(offset):lower()
else
member = sender
end
senderMap[member] = sender
if not EPGP:GetEPGP(member) then
SendChatMessage(L["%s is not eligible for EP awards"]:format(member),
"WHISPER", nil, sender)
elseif EPGP:IsMemberInAwardList(member) then
SendChatMessage(L["%s is already in the award list"]:format(member),
"WHISPER", nil, sender)
else
EPGP:SelectMember(member)
SendChatMessage(L["%s is added to the award list"]:format(member),
"WHISPER", nil, sender)
end
end
local function SendNotifiesAndClearExtras(
event_name, names, reason, amount,
extras_awarded, extras_reason, extras_amount)
EPGP:GetModule("announce"):AnnounceTo(
"GUILD",
L["If you want to be on the award list but you are not in the raid, you need to whisper me: 'epgp standby' or 'epgp standby <name>' where <name> is the toon that should receive awards"])
if extras_awarded then
for member,_ in pairs(extras_awarded) do
local sender = senderMap[member]
if sender then
SendChatMessage(L["%+d EP (%s) to %s"]:format(
extras_amount, extras_reason, member),
"WHISPER", nil, sender)
SendChatMessage(
L["%s is now removed from the award list"]:format(member),
"WHISPER", nil, sender)
end
senderMap[member] = nil
end
end
end
mod.dbDefaults = {
profile = {
enable = false,
}
}
mod.optionsName = L["Whisper"]
mod.optionsDesc = L["Standby whispers in raid"]
mod.optionsArgs = {
help = {
order = 1,
type = "description",
name = L["Automatic handling of the standby list through whispers when in raid. When this is enabled, the standby list is cleared after each reward."],
},
}
function mod:OnEnable()
self:RegisterEvent("CHAT_MSG_WHISPER")
EPGP.RegisterCallback(self, "MassEPAward", SendNotifiesAndClearExtras)
EPGP.RegisterCallback(self, "StartRecurringAward", SendNotifiesAndClearExtras)
end
function mod:OnDisable()
EPGP.UnregisterAllCallbacks(self)
end
|
Report the right awards when whispering to standby members.
|
Report the right awards when whispering to standby members.
This fixes issue 461.
|
Lua
|
bsd-3-clause
|
sheldon/epgp,protomech/epgp-dkp-reloaded,sheldon/epgp,ceason/epgp-tfatf,hayword/tfatf_epgp,ceason/epgp-tfatf,protomech/epgp-dkp-reloaded,hayword/tfatf_epgp
|
4f9f0a53f3ffbe7f43f10da2732b394d6685ac88
|
busted/compatibility.lua
|
busted/compatibility.lua
|
return {
getfenv = getfenv or function(f)
f = (type(f) == 'function' and f or debug.getinfo(f + 1, 'f').func)
local name, value
local up = 0
repeat
up = up + 1
name, value = debug.getupvalue(f, up)
until name == '_ENV' or name == nil
return (name and value or _G)
end,
setfenv = setfenv or function(f, t)
f = (type(f) == 'function' and f or debug.getinfo(f + 1, 'f').func)
local name
local up = 0
repeat
up = up + 1
name = debug.getupvalue(f, up)
until name == '_ENV' or name == nil
if name then
debug.upvaluejoin(f, up, function() return t end, 1)
end
end,
unpack = table.unpack or unpack
}
|
return {
getfenv = getfenv or function(f)
f = (type(f) == 'function' and f or debug.getinfo(f + 1, 'f').func)
local name, value
local up = 0
repeat
up = up + 1
name, value = debug.getupvalue(f, up)
until name == '_ENV' or name == nil
return value
end,
setfenv = setfenv or function(f, t)
f = (type(f) == 'function' and f or debug.getinfo(f + 1, 'f').func)
local name
local up = 0
repeat
up = up + 1
name = debug.getupvalue(f, up)
until name == '_ENV' or name == nil
if name then
debug.upvaluejoin(f, up, function() return name end, 1)
debug.setupvalue(f, up, t)
end
if f ~= 0 then return f end
end,
unpack = table.unpack or unpack
}
|
Fix getfenv/setfenv for Lua 5.2 compatibility
|
Fix getfenv/setfenv for Lua 5.2 compatibility
It is possible for getfenv to return nil for a function with no globals.
Use unique upvalue for setfenv.
|
Lua
|
mit
|
xyliuke/busted,mpeterv/busted,istr/busted,o-lim/busted,sobrinho/busted,Olivine-Labs/busted,DorianGray/busted,leafo/busted,ryanplusplus/busted,nehz/busted
|
eb8dcbc5e9c764d3cfc4e075f900b80ccff4bf6d
|
cmder/powerline_coda.lua
|
cmder/powerline_coda.lua
|
local function get_py_env(env_var)
env = clink.get_env(env_var)
if env then
return env
end
return false
end
local function get_conda_env_filter()
local env = get_py_env("CONDA_DEFAULT_ENV")
if env then
env = addTextWithColor("", env.." ", ansiFgClrYellow, ansiBgClrBlack)
clink.prompt.value = string.gsub(clink.prompt.value, plc_prompt_lambSymbol, env..plc_prompt_lambSymbol)
end
return false
end
clink.prompt.register_filter(get_conda_env_filter, 100)
|
local function get_py_env(env_var)
env = clink.get_env(env_var)
if env then
return env
end
return false
end
local function basename(inputstr)
sep = "\\/"
local last = nil
local t={} ; i=1
for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
last = str
end
return last
end
local function get_conda_env_filter()
local env = get_py_env("CONDA_DEFAULT_ENV")
if env then
env = basename(env)
env = addTextWithColor("", env.." ", ansiFgClrYellow, ansiBgClrBlack)
clink.prompt.value = string.gsub(clink.prompt.value, plc_prompt_lambSymbol, env..plc_prompt_lambSymbol)
end
return false
end
clink.prompt.register_filter(get_conda_env_filter, 100)
|
fix: the env is the full path so shorten it
|
fix: the env is the full path so shorten it
|
Lua
|
mit
|
steveoh/configs,steveoh/configs,steveoh/configs
|
87e5e6ef4610920ddfbf3e5a20f240eb34896c73
|
examples/thread.lua
|
examples/thread.lua
|
--- Turbo.lua Example module
--
-- Copyright 2016 John Abrahamsen
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
local turbo = require "turbo"
local function hard_work(n)
return "This is hard work!"
end
turbo.ioloop.instance():add_callback(function()
local thread = turbo.thread.Thread(function(th)
th:send(hard_work())
th:stop()
end)
local thread2 = turbo.thread.Thread(function(th)
th:send(hard_work())
th:stop()
end)
local data = coroutine.yield(turbo.async.task(
thread.wait_for_data, thread))
print(data)
local data2 = coroutine.yield(turbo.async.task(
thread2.wait_for_data, thread2))
print(data2)
turbo.ioloop.instance():close()
end):start()
|
--- Turbo.lua Example module
--
-- Copyright 2016 John Abrahamsen
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
local turbo = require "turbo"
turbo.ioloop.instance():add_callback(function()
local thread = turbo.thread.Thread(function(th)
th:send("Hello World.")
th:stop()
end)
print(thread:wait_for_data())
thread:wait_for_finish()
turbo.ioloop.instance():close()
end):start()
|
Fixed threading example.
|
Fixed threading example.
|
Lua
|
apache-2.0
|
mniestroj/turbo,kernelsauce/turbo
|
0564872438462e02a36a7120b23e2f2d7454eb11
|
examples/languagemodel.lua
|
examples/languagemodel.lua
|
require 'dp'
--[[command line arguments]]--
cmd = torch.CmdLine()
cmd:text()
cmd:text('Train a Language Model on BillionWords dataset using SoftmaxTree')
cmd:text('Example:')
cmd:text('$> th languagemodel.lua --small --batchSize 512 ')
cmd:text('$> th languagemodel.lua --tiny --batchSize 512 ')
cmd:text('Options:')
cmd:option('--learningRate', 0.1, 'learning rate at t=0')
cmd:option('--maxOutNorm', 0, 'max norm each layers output neuron weights')
cmd:option('--momentum', 0, 'momentum')
cmd:option('--batchSize', 512, 'number of examples per batch')
cmd:option('--type', 'double', 'type: double | float | cuda')
cmd:option('--maxEpoch', 100, 'maximum number of epochs to run')
cmd:option('--maxTries', 30, 'maximum number of epochs to try to find a better local minima for early-stopping')
cmd:option('--dropout', false, 'apply dropout on hidden neurons, requires "nnx" luarock')
cmd:option('--contextSize', 5, 'number of words preceding the target word used to predict the target work')
cmd:option('--inputEmbeddingSize', 100, 'number of neurons per word embedding')
--[[ first hidden layer ]]--
cmd:option('--neuralSize', 200, 'number of hidden units used for first hidden layer (used when --convolution is not used)')
--or
cmd:option('--convolution', false, 'use a Convolution1D instead of Neural for the first hidden layer')
cmd:option('--convOutputSize', 200, 'number of output neurons of the convolutional kernel (outputFrameSize)')
cmd:option('--convKernelSize', 2, 'number of words considered by convolution')
cmd:option('--convKernelStride', 1, 'stride (step size) of the convolution')
cmd:option('--convPoolSize', 2, 'number of words max pooled after convolution')
cmd:option('--convPoolStride', 2, 'stride of the max pooling after the convolution')
cmd:option('--outputEmbeddingSize', 100, 'number of hidden units at softmaxtree')
--[[ output layer ]]--
cmd:option('--softmaxtree', false, 'use the softmaxtree instead of the inefficient (full) softmax')
--[[ data ]]--
cmd:option('--small', false, 'use a small (1/30th) subset of the training set')
cmd:option('--tiny', false, 'use a tiny (1/100th) subset of the training set')
cmd:option('--trainEpochSize', 1000000, 'number of train examples seen between each epoch')
cmd:option('--validEpochSize', 100000, 'number of valid examples used for early stopping and cross-validation')
cmd:text()
opt = cmd:parse(arg or {})
print(opt)
--[[data]]--
local train_file = 'train_data.th7'
if opt.small then
train_file = 'train_small.th7'
elseif opt.tiny then
train_file = 'train_tiny.th7'
end
local datasource = dp.BillionWords{
context_size = opt.contextSize, train_file = train_file
}
--[[Model]]--
if opt.dropout then
require 'nnx'
end
print("Input to first hidden layer has "..
opt.contextSize*opt.inputEmbeddingSize.." neurons.")
local hiddenModel, inputSize
if opt.convolution then
print"Using convolution for first hidden layer"
hiddenModel = dp.Convolution1D{
input_size = opt.inputEmbeddingSize,
output_size = opt.convOutputSize,
kernel_size = opt.convKernelSize,
kernel_stride = opt.convKernelStride,
pool_size = opt.convPoolSize,
pool_stride = opt.convPoolStride,
transfer = nn.Tanh(),
dropout = opt.dropout and nn.Dropout() or nil
}
local nOutputFrame = hiddenModel:nOutputFrame(opt.contextSize)
print("Convolution has "..nOutputFrame.." output Frames")
inputSize = nOutputFrame*opt.convOutputSize
else
hiddenModel = dp.Neural{
input_size = opt.contextSize*opt.inputEmbeddingSize,
output_size = opt.neuralSize,
transfer = nn.Tanh(),
dropout = opt.dropout and nn.Dropout() or nil
}
inputSize = opt.neuralSize
end
print("Input to second hidden layer has size "..inputSize)
local softmax
if opt.softmaxtree then
softmax = dp.SoftmaxTree{
input_size = opt.outputEmbeddingSize,
hierarchy = datasource:hierarchy(),
root_id = 880542,
dropout = opt.dropout and nn.Dropout() or nil
}
else
print("Warning: you are using full SoftMax for last layer, which "..
"is really slow (800,000 x outputEmbeddingSize multiply adds "..
"per example. Try --softmaxtree instead.")
softmax = dp.Neural{
input_size = opt.outputEmbeddingSize,
output_size = table.length(datasource:classes()),
transfer = nn.SoftMax(),
dropout = opt.dropout and nn.Dropout() or nil
}
end
mlp = dp.Sequential{
models = {
dp.Dictionary{
dict_size = datasource:vocabularySize(),
output_size = opt.inputEmbeddingSize
},
hiddenModel,
dp.Neural{
input_size = inputSize,
output_size = opt.outputEmbeddingSize,
transfer = nn.Tanh(),
dropout = opt.dropout and nn.Dropout() or nil
},
softmax
}
}
--[[GPU or CPU]]--
if opt.type == 'cuda' then
print"Using CUDA"
require 'cutorch'
require 'cunn'
mlp:cuda()
end
--[[Propagators]]--
train = dp.Optimizer{
loss = opt.softmaxtree and dp.TreeNLL() or dp.NLL(),
visitor = { -- the ordering here is important:
--dp.Momentum{momentum_factor = opt.momentum},
dp.Learn{
learning_rate = opt.learningRate,
observer = dp.LearningRateSchedule{
schedule = {[200]=0.01, [400]=0.001}
}
}--,
--dp.MaxNorm{max_out_norm = opt.maxOutNorm}
},
feedback = dp.Perplexity(),
sampler = dp.Sampler{ --shuffle sample takes too much mem
epoch_size = opt.trainEpochSize, batch_size = opt.batchSize
},
progress = true
}
valid = dp.Evaluator{
loss = opt.softmaxtree and dp.TreeNLL() or dp.NLL(),
feedback = dp.Perplexity(),
sampler = dp.Sampler{
epoch_size = opt.validEpochSize, batch_size = 1024
},
progress = true
}
test = dp.Evaluator{
loss = opt.softmaxtree and dp.TreeNLL() or dp.NLL(),
feedback = dp.Perplexity(),
sampler = dp.Sampler()
}
--[[Experiment]]--
xp = dp.Experiment{
model = mlp,
optimizer = train,
validator = valid,
tester = test,
observer = {
dp.FileLogger(),
dp.EarlyStopper{max_epochs = opt.maxTries}
},
random_seed = os.time(),
max_epoch = opt.maxEpoch
}
xp:run(datasource)
|
require 'dp'
--[[command line arguments]]--
cmd = torch.CmdLine()
cmd:text()
cmd:text('Train a Language Model on BillionWords dataset using SoftmaxTree')
cmd:text('Example:')
cmd:text('$> th languagemodel.lua --small --batchSize 512 ')
cmd:text('$> th languagemodel.lua --tiny --batchSize 512 ')
cmd:text('Options:')
cmd:option('--learningRate', 0.1, 'learning rate at t=0')
cmd:option('--maxOutNorm', 0, 'max norm each layers output neuron weights')
cmd:option('--momentum', 0, 'momentum')
cmd:option('--batchSize', 512, 'number of examples per batch')
cmd:option('--type', 'double', 'type: double | float | cuda')
cmd:option('--maxEpoch', 100, 'maximum number of epochs to run')
cmd:option('--maxTries', 30, 'maximum number of epochs to try to find a better local minima for early-stopping')
cmd:option('--dropout', false, 'apply dropout on hidden neurons, requires "nnx" luarock')
cmd:option('--contextSize', 5, 'number of words preceding the target word used to predict the target work')
cmd:option('--inputEmbeddingSize', 100, 'number of neurons per word embedding')
--[[ first hidden layer ]]--
cmd:option('--neuralSize', 200, 'number of hidden units used for first hidden layer (used when --convolution is not used)')
--or
cmd:option('--convolution', false, 'use a Convolution1D instead of Neural for the first hidden layer')
cmd:option('--convOutputSize', 200, 'number of output neurons of the convolutional kernel (outputFrameSize)')
cmd:option('--convKernelSize', 2, 'number of words considered by convolution')
cmd:option('--convKernelStride', 1, 'stride (step size) of the convolution')
cmd:option('--convPoolSize', 2, 'number of words max pooled after convolution')
cmd:option('--convPoolStride', 2, 'stride of the max pooling after the convolution')
cmd:option('--outputEmbeddingSize', 100, 'number of hidden units at softmaxtree')
--[[ output layer ]]--
cmd:option('--softmaxtree', false, 'use the softmaxtree instead of the inefficient (full) softmax')
--[[ data ]]--
cmd:option('--small', false, 'use a small (1/30th) subset of the training set')
cmd:option('--tiny', false, 'use a tiny (1/100th) subset of the training set')
cmd:option('--trainEpochSize', 1000000, 'number of train examples seen between each epoch')
cmd:option('--validEpochSize', 100000, 'number of valid examples used for early stopping and cross-validation')
cmd:text()
opt = cmd:parse(arg or {})
print(opt)
--[[data]]--
local train_file = 'train_data.th7'
if opt.small then
train_file = 'train_small.th7'
elseif opt.tiny then
train_file = 'train_tiny.th7'
end
local datasource = dp.BillionWords{
context_size = opt.contextSize, train_file = train_file
}
--[[Model]]--
if opt.dropout then
require 'nnx'
end
print("Input to first hidden layer has "..
opt.contextSize*opt.inputEmbeddingSize.." neurons.")
local hiddenModel, inputSize
if opt.convolution then
print"Using convolution for first hidden layer"
hiddenModel = dp.Convolution1D{
input_size = opt.inputEmbeddingSize,
output_size = opt.convOutputSize,
kernel_size = opt.convKernelSize,
kernel_stride = opt.convKernelStride,
pool_size = opt.convPoolSize,
pool_stride = opt.convPoolStride,
transfer = nn.Tanh(),
dropout = opt.dropout and nn.Dropout() or nil
}
local nOutputFrame = hiddenModel:nOutputFrame(opt.contextSize)
print("Convolution has "..nOutputFrame.." output Frames")
inputSize = nOutputFrame*opt.convOutputSize
else
hiddenModel = dp.Neural{
input_size = opt.contextSize*opt.inputEmbeddingSize,
output_size = opt.neuralSize,
transfer = nn.Tanh(),
dropout = opt.dropout and nn.Dropout() or nil
}
inputSize = opt.neuralSize
end
print("Input to second hidden layer has size "..inputSize)
local softmax
if opt.softmaxtree then
softmax = dp.SoftmaxTree{
input_size = opt.outputEmbeddingSize,
hierarchy = datasource:hierarchy(),
root_id = 880542,
dropout = opt.dropout and nn.Dropout() or nil
}
else
print("Warning: you are using full SoftMax for last layer, which "..
"is really slow (800,000 x outputEmbeddingSize multiply adds "..
"per example. Try --softmaxtree instead.")
softmax = dp.Neural{
input_size = opt.outputEmbeddingSize,
output_size = table.length(datasource:classes()),
transfer = nn.SoftMax(),
dropout = opt.dropout and nn.Dropout() or nil
}
end
mlp = dp.Sequential{
models = {
dp.Dictionary{
dict_size = datasource:vocabularySize(),
output_size = opt.inputEmbeddingSize
},
hiddenModel,
dp.Neural{
input_size = inputSize,
output_size = opt.outputEmbeddingSize,
transfer = nn.Tanh(),
dropout = opt.dropout and nn.Dropout() or nil
},
softmax
}
}
--[[GPU or CPU]]--
if opt.type == 'cuda' then
print"Using CUDA"
require 'cutorch'
require 'cunn'
mlp:cuda()
end
--[[Propagators]]--
train = dp.Optimizer{
loss = opt.softmaxtree and dp.TreeNLL() or dp.NLL(),
visitor = { -- the ordering here is important:
--dp.Momentum{momentum_factor = opt.momentum},
dp.Learn{
learning_rate = opt.learningRate,
observer = dp.LearningRateSchedule{
schedule = {[200]=0.01, [400]=0.001}
}
}--,
--dp.MaxNorm{max_out_norm = opt.maxOutNorm}
},
feedback = dp.Perplexity(),
sampler = dp.Sampler{ --shuffle sample takes too much mem
epoch_size = opt.trainEpochSize, batch_size = opt.batchSize
},
progress = true
}
valid = dp.Evaluator{
loss = opt.softmaxtree and dp.TreeNLL() or dp.NLL(),
feedback = dp.Perplexity(),
sampler = dp.Sampler{
epoch_size = opt.validEpochSize,
batch_size = opt.softmaxtree and 1024 or opt.batchSize
},
progress = true
}
test = dp.Evaluator{
loss = opt.softmaxtree and dp.TreeNLL() or dp.NLL(),
feedback = dp.Perplexity(),
sampler = dp.Sampler{batch_size = opt.softmaxtree and 1024 or opt.batchSize}
}
--[[Experiment]]--
xp = dp.Experiment{
model = mlp,
optimizer = train,
validator = valid,
tester = test,
observer = {
dp.FileLogger(),
dp.EarlyStopper{max_epochs = opt.maxTries}
},
random_seed = os.time(),
max_epoch = opt.maxEpoch
}
xp:run(datasource)
|
fixed languagemodel.lua fullsoftmax bug
|
fixed languagemodel.lua fullsoftmax bug
|
Lua
|
bsd-3-clause
|
fiskio/dp,rickyHong/dptorchLib,sagarwaghmare69/dp,eulerreich/dp,nicholas-leonard/dp,jnhwkim/dp,kracwarlock/dp
|
56dbd189fa33cda4062199d4d4d4702b442a82a7
|
scene/game.lua
|
scene/game.lua
|
--
-- Scena z rozgrywką
--
-- Wymagane moduły
local composer = require( 'composer' )
local app = require( 'lib.app' )
local preference = require( 'preference' )
local fx = require( 'com.ponywolf.ponyfx' )
local deltatime = require( 'lib.deltatime' )
local ball = require( 'scene.game.lib.ball' )
local paddle = require( 'scene.game.lib.paddle' )
local background = require( 'scene.game.lib.background' )
local scoring = require( 'scene.game.lib.score' )
math.randomseed( os.time() )
-- Lokalne zmienne
local mClamp = math.clamp
-- Lokalne zmienne
local squareBall, player, computer
local playerScore, computerScore
local maxScore = 1
local scene = composer.newScene()
local function stretch( object )
transition.chain( object, {time=100, xScale=0.8, yScale=1.2},
{time=100, xScale=1.1, yScale=0.9},
{time=100, xScale=0.95, yScale=1.05},
{time=100, xScale=1, yScale=1} )
end
-- Główna pętla gry
local function loop()
local dt = deltatime.getTime()
squareBall:update( dt )
computer:update( dt )
end
-- Obsługa ruchu paletki gracza
local function drag( event )
if ( event.phase == 'began' ) then
player.isFocus = true
player.markY = player.y
elseif ( player.isFocus ) then
if ( event.phase == 'moved' ) then
player.y = mClamp( event.y - event.yStart + player.markY,
player.height * player.yScale * player.anchorY,
_H - player.height * ( 1 - player.anchorY ) * player.yScale )
elseif ( event.phase == 'ended' or event.phase == 'cancelled' ) then
player.isFocus = false
end
end
return true
end
local function gameOver()
app.playSound( scene.sounds.lost )
local textId = playerScore:get() == maxScore and 'win' or 'lost'
app.removeAllRuntimeEvents()
local screen = display.getCurrentStage()
fx.shake( screen )
timer.performWithDelay( 500, function()
composer.showOverlay("scene.result", { isModal=true,
effect="crossFade", params={textId=textId, newScore=playerScore:get()} } )
end )
end
local function touchEdge( event )
local edge = event.edge
local x = event.x
local y = event.y
app.playSound(scene.sounds.wall)
if ( edge == 'right' ) then
playerScore:add( 1 )
stretch( playerScore )
elseif ( edge == 'left' ) then
computerScore:add( 1 )
stretch( computerScore )
end
-- sprawdza czy mecz dobiegł końca
if ( computerScore:get() == maxScore or playerScore:get() == maxScore ) then
gameOver()
end
end
-- rozpoczyna grę od nowa
function scene:resumeGame()
-- ustawia wybraną piłeczke
local ballInUse = preference:get( 'ballInUse' )
local balls = preference:get( 'balls' )
local offset = 120
-- dodanie piłeczki
squareBall = ball.new( balls[ballInUse].params )
scene.squareBall = squareBall
squareBall:serve()
scene.view:insert( squareBall )
transition.to( scene.board, {transition=easing.outBack, delay=200, time=500, yScale=1} )
transition.to( playerScore, {transition=easing.outBack, time=500, y=_T + 100} )
transition.to( computerScore, {transition=easing.outBack, time=500, y=_T + 100} )
transition.to( player, {transition=easing.outBack, time=500, x=player.width + offset} )
transition.to( computer, {transition=easing.outBack, time=500, x= _W - offset,
onComplete=function()
deltatime.restart()
app.addRuntimeEvents( {'enterFrame', loop, 'touch', drag, 'touchEdge', touchEdge} )
end } )
end
function scene:create( event )
local sceneGroup = self.view
--local offset = 120
local sndDir = 'scene/game/sfx/'
scene.sounds = {
wall = audio.loadSound( sndDir .. 'wall.wav' ),
hit = audio.loadSound( sndDir .. 'hit.wav' ),
lost = audio.loadSound( sndDir .. 'lost.wav' )
}
-- usuwa poprzednią scene
local prevScene = composer.getSceneName( 'previous' )
composer.removeScene( prevScene )
-- dodaje planszę
local board = background.new()
board.yScale = 0.001
scene.board = board
-- dodaje paletkę gracza
player = paddle.new()
scene.player = player
--player.x, player.y = player.width + offset, _CY
player.x, player.y = _L - player.width, _CY
-- dodaje paletkę komputerowego przeciwnika
computer = paddle.new()
scene.computer = computer
--computer.x, computer.y = _W - offset, _CY
computer.x, computer.y = _R + _W + player.width, _CY
-- dodanie obiektu przechowującego wynik dla obu graczy
playerScore = scoring.new()
playerScore.x, playerScore.y = _CX - 100, -_T - player.height
app.setRP( playerScore, 'CenterRight')
computerScore = scoring.new( {align='left'} )
computerScore.x, computerScore.y = _CX + 100, -_T - player.height
app.setRP( computerScore, 'CenterLeft')
-- dodanie obiekty do sceny we właściwej kolejności
sceneGroup:insert( board )
sceneGroup:insert( computer )
sceneGroup:insert( player )
sceneGroup:insert( playerScore )
sceneGroup:insert( computerScore )
end
function scene:show( event )
local sceneGroup = self.view
local phase = event.phase
if ( phase == 'will' ) then
elseif ( phase == 'did' ) then
composer.showOverlay( "scene.info", { isModal=true, effect="crossFade", params={} } )
end
end
function scene:hide( event )
local sceneGroup = self.view
local phase = event.phase
if ( phase == 'will' ) then
elseif ( phase == 'did' ) then
app.removeAllRuntimeEvents()
end
end
function scene:destroy( event )
app.removeAllRuntimeEvents()
audio.stop()
for s,v in pairs( self.sounds ) do
audio.dispose( v )
self.sounds[s] = nil
end
end
scene:addEventListener( 'create', scene )
scene:addEventListener( 'show', scene )
scene:addEventListener( 'hide', scene )
scene:addEventListener( 'destroy', scene )
return scene
|
--
-- Scena z rozgrywką
--
-- Wymagane moduły
local composer = require( 'composer' )
local app = require( 'lib.app' )
local preference = require( 'preference' )
local fx = require( 'com.ponywolf.ponyfx' )
local deltatime = require( 'lib.deltatime' )
local ball = require( 'scene.game.lib.ball' )
local paddle = require( 'scene.game.lib.paddle' )
local background = require( 'scene.game.lib.background' )
local scoring = require( 'scene.game.lib.score' )
math.randomseed( os.time() )
-- Lokalne zmienne
local mClamp = math.clamp
-- Lokalne zmienne
local squareBall, player, computer
local playerScore, computerScore
local maxScore = 1
local scene = composer.newScene()
local function stretch( object )
transition.chain( object, {time=100, xScale=0.8, yScale=1.2},
{time=100, xScale=1.1, yScale=0.9},
{time=100, xScale=0.95, yScale=1.05},
{time=100, xScale=1, yScale=1} )
end
-- Główna pętla gry
local function loop()
local dt = deltatime.getTime()
squareBall:update( dt )
computer:update( dt )
end
-- Obsługa ruchu paletki gracza
local function drag( event )
if ( event.phase == 'began' ) then
player.isFocus = true
player.markY = player.y
elseif ( player.isFocus ) then
if ( event.phase == 'moved' ) then
player.y = mClamp( event.y - event.yStart + player.markY,
player.height * player.yScale * player.anchorY,
_H - player.height * ( 1 - player.anchorY ) * player.yScale )
elseif ( event.phase == 'ended' or event.phase == 'cancelled' ) then
player.isFocus = false
end
end
return true
end
local function gameOver()
app.playSound( scene.sounds.lost )
local textId = playerScore:get() == maxScore and 'win' or 'lost'
app.removeAllRuntimeEvents()
local screen = display.getCurrentStage()
fx.shake( screen )
timer.performWithDelay( 500, function()
composer.showOverlay("scene.result", { isModal=true,
effect="crossFade", params={textId=textId, newScore=playerScore:get()} } )
end )
end
local function touchEdge( event )
local edge = event.edge
local x = event.x
local y = event.y
app.playSound(scene.sounds.wall)
if ( edge == 'right' ) then
playerScore:add( 1 )
stretch( playerScore )
elseif ( edge == 'left' ) then
computerScore:add( 1 )
stretch( computerScore )
end
-- sprawdza czy mecz dobiegł końca
if ( computerScore:get() == maxScore or playerScore:get() == maxScore ) then
gameOver()
end
end
-- rozpoczyna grę od nowa
function scene:resumeGame()
-- ustawia wybraną piłeczke
local ballInUse = preference:get( 'ballInUse' )
local balls = preference:get( 'balls' )
local offset = 120
-- dodanie piłeczki
squareBall = ball.new( balls[ballInUse].params )
scene.squareBall = squareBall
squareBall:serve()
scene.view:insert( squareBall )
transition.to( scene.board, {transition=easing.outBack, delay=200, time=500, yScale=1} )
transition.to( playerScore, {transition=easing.outBack, time=500, y=_T + 100} )
transition.to( computerScore, {transition=easing.outBack, time=500, y=_T + 100} )
transition.to( player, {transition=easing.outBack, time=500, x=player.width + offset} )
transition.to( computer, {transition=easing.outBack, time=500, x= _W - offset,
onComplete=function()
deltatime.restart()
app.addRuntimeEvents( {'enterFrame', loop, 'touch', drag, 'touchEdge', touchEdge} )
end } )
end
function scene:create( event )
local sceneGroup = self.view
local sndDir = 'scene/game/sfx/'
scene.sounds = {
wall = audio.loadSound( sndDir .. 'wall.wav' ),
hit = audio.loadSound( sndDir .. 'hit.wav' ),
lost = audio.loadSound( sndDir .. 'lost.wav' )
}
-- usuwa poprzednią scene
local prevScene = composer.getSceneName( 'previous' )
composer.removeScene( prevScene )
-- dodaje planszę
local board = background.new()
board.yScale = 0.001
scene.board = board
-- dodaje paletkę gracza
player = paddle.new()
scene.player = player
player.x, player.y = _L - player.width, _CY
-- dodaje paletkę komputerowego przeciwnika
computer = paddle.new()
scene.computer = computer
computer.x, computer.y = _R + _W + player.width, _CY
-- dodanie obiektu przechowującego wynik dla obu graczy
playerScore = scoring.new()
playerScore.x, playerScore.y = _CX - 100, _T - player.height
app.setRP( playerScore, 'CenterRight')
computerScore = scoring.new( {align='left'} )
computerScore.x, computerScore.y = _CX + 100, _T - player.height
app.setRP( computerScore, 'CenterLeft')
-- dodanie obiekty do sceny we właściwej kolejności
sceneGroup:insert( board )
sceneGroup:insert( computer )
sceneGroup:insert( player )
sceneGroup:insert( playerScore )
sceneGroup:insert( computerScore )
end
function scene:show( event )
local sceneGroup = self.view
local phase = event.phase
if ( phase == 'will' ) then
elseif ( phase == 'did' ) then
composer.showOverlay( "scene.info", { isModal=true, effect="crossFade", params={} } )
end
end
function scene:hide( event )
local sceneGroup = self.view
local phase = event.phase
if ( phase == 'will' ) then
elseif ( phase == 'did' ) then
app.removeAllRuntimeEvents()
end
end
function scene:destroy( event )
app.removeAllRuntimeEvents()
audio.stop()
for s,v in pairs( self.sounds ) do
audio.dispose( v )
self.sounds[s] = nil
end
end
scene:addEventListener( 'create', scene )
scene:addEventListener( 'show', scene )
scene:addEventListener( 'hide', scene )
scene:addEventListener( 'destroy', scene )
return scene
|
Bug fix: score text partially visible on start
|
Bug fix: score text partially visible on start
|
Lua
|
mit
|
ldurniat/The-Great-Pong,ldurniat/My-Pong-Game
|
b3c82ffb351e75df0ffed06ddd7b9035b0ba362a
|
home/.hammerspoon/jira.lua
|
home/.hammerspoon/jira.lua
|
local utils = require('utils')
local jiraAccount = require ('jiraAccount')
local log = hs.logger.new('init.lua', 'debug')
-- Public part
local jira = {}
-- Returns a Jira URL to browse the given issue Key
function jira.getBrowseUrl(key)
return string.format("%s%s%s", jiraAccount.getBaseUrl(), "browse/", key)
end
-- Returns a Jira URL to log work onto given issue id
function jira.getLogWorkUrl(id)
return string.format("%s%s%s", jiraAccount.getBaseUrl(), "secure/CreateWorklog!default.jspa?id=", id)
end
-- Type JIRA issue browsing base url
function jira.typeBrowseUrl()
local url = jira.getBrowseUrl(utils.getTrimmedSelectedText())
hs.eventtap.keyStrokes(url)
end
-- Type a JIRA bug template
function jira.typeBugTemplate()
local source=[[
# *Steps to reproduce*
##
##
# *Expected result*
##
##
# *Actual*
##
##
# *Extra information*
##
##
]]
hs.eventtap.keyStrokes(source)
end
-- Search the highlighted selection in Request.jira.com
function jira.search()
local url = string.format("%s%s%s%s", jiraAccount.getBaseUrl(), "issues/?jql=text%20~%20%22", utils.getTrimmedSelectedText(), "%22")
log.f("Searching '%s'", url)
-- TODO: if empty, pop-up a chooser
utils.browseUrl(url)
end
-- Browse the issue key currently highlighted selection, or pop up a chooser
function jira.browseIssue()
local key = utils.getTrimmedSelectedText()
if key == "" then
log.f("browseIssue: no selection: invoking graphical chooser")
lookupJiraIssue()
else
-- Does the key starts with only digits ?
local char = string.sub(1,1)
if string.match(char, "^%d") ~= nil then
-- Yes: add the default project prefix
key = jiraAccount.getDefaultProjectPrefix() .. key
end
log.f("browseIssue: browse issue '%s'", key)
utils.browseUrl(jira.getBrowseUrl(key))
end
end
-- Log work for given issue id in browser
function jira.logWork(id)
utils.browseUrl(jira.getLogWorkUrl(id))
end
-- Private part
-- Below from https://github.com/CasperKoning/dothammerspoon/blob/master/jira.lua
-- Jira viewer: (also see https://developer.atlassian.com/jiradev/jira-apis/jira-rest-apis/jira-rest-api-tutorials/jira-rest-api-version-2-tutorial)
function createAuthorisationRequestBody()
return string.format('{ "username": "%s", "password": "%s" }', jiraAccount.getUsername(), jiraAccount.getPassword())
end
function getSession()
log.f("getSession(): entering")
data = createAuthorisationRequestBody()
headers = {["Content-Type"] = "application/json"}
status, body, returnedHeaders = hs.http.post(jiraAccount.getBaseUrl() .. 'rest/auth/latest/session', data, headers)
log.f("getSession(): received status %s, body '%s', headers '%s'", status, body, headers)
if status == 200 then
result = hs.json.decode(body)
session = result["session"]
return session["name"], session["value"]
else
return nil, nil
end
end
function lookupJiraIssue()
sessionName, sessionValue = getSession()
if (sessionName ~= nil and sessionValue ~= nil) then
log.f("lookupJiraIssue(): got a valid session.")
local cookieHeaders = {["cookie"] = sessionName .. "=" .. sessionValue, ["Content-Type"] = "application/json"}
local picker = hs.chooser.new(function(userInput)
if userInput ~= nil then
log.f("chooser: user chose '%s'",userInput)
if userInput["key"] ~= Nil then
local url = jira.getBrowseUrl(userInput["key"])
log.f("chooser: user chose '%s', browsing to '%s'", userInput["key"], url)
hs.execute("open " .. url)
end
end
end)
picker:query(jiraAccount.getDefaultIssueSearch())
picker:queryChangedCallback(
function(query)
log.f("queryChangedCallback(): query is '%s'", query)
if string.len(query) > 3 then
log.f("queryChangedCallback(): query '%s' could be a valid JIRA issue key", query)
hs.http.asyncGet(
getJiraQueryUrl(query),
cookieHeaders,
function(status, body, headers)
log.f("queryChangedCallback(): received status %s, body '%s', headers '%s'", status, body, headers)
if status == 200 then
searchResult = hs.json.decode(body)
if searchResult["fields"] ~= nil then
local results = {}
local key = searchResult["key"]
local summary = searchResult["fields"]["summary"]
table.insert(results, {text = key, subText = summary, key = key})
picker:choices(results)
end
end
end
)
else
log.f("queryChangedCallback(): query '%s' cannot be a valid JIRA issue key", query)
end
end
)
picker:rows(1)
picker:show()
else
log.f("lookupJiraIssue(): could not get a valid session.")
notify = hs.notify.new()
notify:title("Jira")
notify:informativeText("Could not get authorization")
notify:send()
end
end
function getJiraQueryUrl(query)
local url = string.format("%s%s%s", jiraAccount.getBaseUrl(), "rest/api/latest/issue/", query)
log.f("jiraQuey(): return url '%s'", url)
return url
end
return jira
|
local utils = require('utils')
local jiraAccount = require ('jiraAccount')
local log = hs.logger.new('init.lua', 'debug')
-- Public part
local jira = {}
-- Returns a Jira URL to browse the given issue Key
function jira.getBrowseUrl(key)
return string.format("%s%s%s", jiraAccount.getBaseUrl(), "browse/", key)
end
-- Returns a Jira URL to log work onto given issue id
function jira.getLogWorkUrl(id)
return string.format("%s%s%s", jiraAccount.getBaseUrl(), "secure/CreateWorklog!default.jspa?id=", id)
end
-- Type JIRA issue browsing base url
function jira.typeBrowseUrl()
local url = jira.getBrowseUrl(utils.getTrimmedSelectedText())
hs.eventtap.keyStrokes(url)
end
-- Type a JIRA bug template
function jira.typeBugTemplate()
local source=[[
# *Steps to reproduce*
##
##
# *Expected result*
##
##
# *Actual*
##
##
# *Extra information*
##
##
]]
hs.eventtap.keyStrokes(source)
end
-- Search the highlighted selection in Request.jira.com
function jira.search()
local url = string.format("%s%s%s%s", jiraAccount.getBaseUrl(), "issues/?jql=text%20~%20%22", utils.getTrimmedSelectedText(), "%22")
log.f("Searching '%s'", url)
-- TODO: if empty, pop-up a chooser
utils.browseUrl(url)
end
-- Browse the issue key currently highlighted selection, or pop up a chooser
function jira.browseIssue()
local key = utils.getTrimmedSelectedText()
if key == "" then
log.f("browseIssue: no selection: invoking graphical chooser")
lookupJiraIssue()
else
-- Does the key starts with only a digit ?
local c1 = string.sub(key, 1,1)
if string.match(c1, "^%d") ~= nil then
-- Yes: add the default project prefix !
log.f("browseIssue: first char '%s' is a digit, adding prefix '%s'", c1, jiraAccount.getDefaultProjectPrefix())
key = jiraAccount.getDefaultProjectPrefix() .. key
end
log.f("browseIssue: browse issue '%s'", key)
utils.browseUrl(jira.getBrowseUrl(key))
end
end
-- Log work for given issue id in browser
function jira.logWork(id)
utils.browseUrl(jira.getLogWorkUrl(id))
end
-- Private part
-- Below from https://github.com/CasperKoning/dothammerspoon/blob/master/jira.lua
-- Jira viewer: (also see https://developer.atlassian.com/jiradev/jira-apis/jira-rest-apis/jira-rest-api-tutorials/jira-rest-api-version-2-tutorial)
function createAuthorisationRequestBody()
return string.format('{ "username": "%s", "password": "%s" }', jiraAccount.getUsername(), jiraAccount.getPassword())
end
function getSession()
log.f("getSession(): entering")
data = createAuthorisationRequestBody()
headers = {["Content-Type"] = "application/json"}
status, body, returnedHeaders = hs.http.post(jiraAccount.getBaseUrl() .. 'rest/auth/latest/session', data, headers)
log.f("getSession(): received status %s, body '%s', headers '%s'", status, body, headers)
if status == 200 then
result = hs.json.decode(body)
session = result["session"]
return session["name"], session["value"]
else
return nil, nil
end
end
function lookupJiraIssue()
sessionName, sessionValue = getSession()
if (sessionName ~= nil and sessionValue ~= nil) then
log.f("lookupJiraIssue(): got a valid session.")
local cookieHeaders = {["cookie"] = sessionName .. "=" .. sessionValue, ["Content-Type"] = "application/json"}
local picker = hs.chooser.new(function(userInput)
if userInput ~= nil then
log.f("chooser: user chose '%s'",userInput)
if userInput["key"] ~= Nil then
local url = jira.getBrowseUrl(userInput["key"])
log.f("chooser: user chose '%s', browsing to '%s'", userInput["key"], url)
hs.execute("open " .. url)
end
end
end)
picker:query(jiraAccount.getDefaultIssueSearch())
picker:queryChangedCallback(
function(query)
log.f("queryChangedCallback(): query is '%s'", query)
if string.len(query) > 3 then
log.f("queryChangedCallback(): query '%s' could be a valid JIRA issue key", query)
hs.http.asyncGet(
getJiraQueryUrl(query),
cookieHeaders,
function(status, body, headers)
log.f("queryChangedCallback(): received status %s, body '%s', headers '%s'", status, body, headers)
if status == 200 then
searchResult = hs.json.decode(body)
if searchResult["fields"] ~= nil then
local results = {}
local key = searchResult["key"]
local summary = searchResult["fields"]["summary"]
table.insert(results, {text = key, subText = summary, key = key})
picker:choices(results)
end
end
end
)
else
log.f("queryChangedCallback(): query '%s' cannot be a valid JIRA issue key", query)
end
end
)
picker:rows(1)
picker:show()
else
log.f("lookupJiraIssue(): could not get a valid session.")
notify = hs.notify.new()
notify:title("Jira")
notify:informativeText("Could not get authorization")
notify:send()
end
end
function getJiraQueryUrl(query)
local url = string.format("%s%s%s", jiraAccount.getBaseUrl(), "rest/api/latest/issue/", query)
log.f("jiraQuey(): return url '%s'", url)
return url
end
return jira
|
Fixed a glitch when checking whether the selected issue has a Jira project prefix or not.
|
Fixed a glitch when checking whether the selected issue has a Jira project prefix or not.
|
Lua
|
mit
|
maanuair/dotfiles_tmp,maanuair/dotfiles
|
96138c9edb7fa49ccd14fea325d1b50e59e8ce6b
|
hostinfo_runner.lua
|
hostinfo_runner.lua
|
--[[
Copyright 2014 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local HostInfo = require('hostinfo')
local json = require('json')
local exports = {}
local argv = require("options")
.usage('Usage: ')
.describe("x", "host info type to run")
.argv("x:")
exports.run = function()
process.stdout:write("HostInfo Running " .. argv.args.x .. "\n")
local klass = HostInfo.create(argv.args.x)
klass:run(function(err, callback)
process.stdout:write("Serialized Results:\n" .. json.stringify(klass:serialize(), {beautify = true}))
end)
end
return exports
|
--[[
Copyright 2014 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local HostInfo = require('hostinfo')
local json = require('json')
local exports = {}
local argv = require("options")
.usage('Usage: -x [Host Info Type]')
.describe("x", "host info type to run")
.argv("x:")
exports.run = function()
if not argv.args.x then
process.stdout:write(argv._usage .. '\n')
process.exit(0)
end
process.stdout:write("HostInfo Running " .. argv.args.x .. "\n")
local klass = HostInfo.create(argv.args.x)
klass:run(function(err, callback)
process.stdout:write("Serialized Results:\n" .. json.stringify(klass:serialize(), {beautify = true}))
end)
end
return exports
|
fix(host_info_runner): display usage
|
fix(host_info_runner): display usage
|
Lua
|
apache-2.0
|
AlphaStaxLLC/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent
|
4f632c71eba1c0747611076395b6f6d53fe7964e
|
src/soul.lua
|
src/soul.lua
|
local soul = {}
local conversation = require("conversation")
local utils = require("utils")
local lfs = require("lfs")
commands = {}
broadcasts = {}
for file in lfs.dir("commands") do
local command = file:match("^(.+).lua")
if (command) then
local path = "commands." .. command
package.loaded[path] = nil
local status, ret = pcall(require, path)
if (status) then
commands[command] = ret
logger:info("loaded " .. path)
else
logger:error(ret)
end
end
end
soul.tick = function()
local group_list = {
-1001497094866,
-1001126076013,
-1001103633366,
-1001208316368,
-1001487484295
}
if lfs.touch("/home/joshua/.emergency") then
os.execute("rm /home/joshua/.emergency")
for k, v in pairs(group_list) do
local ret = bot.sendMessage{
chat_id = v,
text = "有人向 @SJoshua 发起了紧急联络请求。如果您能够(在线下)联系到 Master 的话,麻烦使用 /emergency_informed 来删除广播信息,非常感谢。"
}
table.insert(broadcasts, {chat_id = v, message_id = ret.result.message_id})
end
end
end
soul.onMessageReceive = function(msg)
msg.text = msg.text:gsub("@" .. bot.info.username, "")
msg.chat.id = math.floor(msg.chat.id)
msg.from.id = math.floor(msg.from.id)
if msg.text:find("/(%S+)@(%S+)[Bb][Oo][Tt]") then
return true
end
if os.time() - msg.date > config.ignore then
return true
end
for k, v in pairs(commands) do
if msg.text:find("^%s*/" .. k) and not msg.text:find("^%s*/" .. k .. "%S") then
if v.limit then
if v.limit.disable then
return bot.sendMessage{
chat_id = msg.chat.id,
text = "Sorry, the command is disabled.",
reply_to_message_id = msg.message_id
}
elseif v.limit.master and msg.from.username ~= config.master then
return bot.sendMessage{
chat_id = msg.chat.id,
text = "Sorry, permission denied.",
reply_to_message_id = msg.message_id
}
elseif (v.limit.match or v.limit.reply) and not ((v.limit.match and msg.text:find(v.limit.match)) or (v.limit.reply and msg.reply_to_message)) then
return commands.help.func(msg, k)
end
end
return v.func(msg)
end
end
for keyword, reply in pairs(conversation) do
local match = false
if type(keyword) == "string" then
match = msg.text:find(keyword)
elseif type(keyword) == "table" then
for i = 1, #keyword do
match = match or msg.text:find(keyword[i])
end
if keyword.reply and not msg.reply_to_message then
match = false
end
elseif type(keyword) == "function" then
match = keyword(msg.text)
end
if match then
local ans, rep
local rep_type = "Markdown"
if type(reply) == "string" then
ans = reply
elseif type(reply) == "table" then
ans = utils.rand(table.unpack(reply))
if reply.reply then
rep = msg.message_id
elseif reply.reply_to_reply and msg.reply_to_message then
rep = msg.reply_to_message.message_id
end
if reply.type then
rep_type = reply.type
end
elseif type(reply) == "function" then
ans = tostring(reply())
end
if ans:find("^sticker#%S-$") then
return bot.sendSticker(msg.chat.id, ans:match("^sticker#(%S-)$"), nil, rep)
elseif ans:find("^document#%S-$") then
return bot.sendDocument(msg.chat.id, ans:match("^document#(%S-)$"), nil, nil, rep)
else
return bot.sendMessage{
chat_id = msg.chat.id,
text = ans,
parse_mode = rep_type,
reply_to_message_id = rep
}
end
end
end
end
soul.ignore = function(msg) end
soul.onEditedMessageReceive = soul.ignore
soul.onLeftChatMembersReceive = soul.ignore
soul.onNewChatMembersReceive = soul.ignore
soul.onPhotoReceive = soul.ignore
soul.onAudioReceive = soul.ignore
soul.onVoiceReceive = soul.ignore
soul.onVideoReceive = soul.ignore
soul.onDocumentReceive = soul.ignore
soul.onGameReceive = soul.ignore
soul.onStickerReceive = soul.ignore
soul.onDiceReceive = soul.ignore
soul.onVideoNoteReceive = soul.ignore
soul.onContactReceive = soul.ignore
soul.onLocationReceive = soul.ignore
soul.onPinnedMessageReceive = soul.ignore
setmetatable(soul, {
__index = function(t, key)
logger:warn("called undefined processer " .. key)
return (function() return false end)
end
})
return soul
|
local soul = {}
local conversation = require("conversation")
local utils = require("utils")
local lfs = require("lfs")
commands = {}
broadcasts = {}
for file in lfs.dir("commands") do
local command = file:match("^(.+).lua")
if (command) then
local path = "commands." .. command
package.loaded[path] = nil
local status, ret = pcall(require, path)
if (status) then
commands[command] = ret
logger:info("loaded " .. path)
else
logger:error(ret)
end
end
end
soul.tick = function()
local group_list = {
-1001497094866,
-1001126076013,
-1001103633366,
-1001208316368,
-1001487484295
}
if lfs.touch("/var/www/server.sforest.in/.emergency") then
os.execute("rm /var/www/server.sforest.in/.emergency")
for k, v in pairs(group_list) do
local ret = bot.sendMessage{
chat_id = v,
text = "有人向 @SJoshua 发起了紧急联络请求。如果您能够(在线下)联系到 Master 的话,麻烦使用 /emergency_informed 来删除广播信息,非常感谢。"
}
table.insert(broadcasts, {chat_id = v, message_id = ret.result.message_id})
end
end
end
soul.onMessageReceive = function(msg)
msg.text = msg.text:gsub("@" .. bot.info.username, "")
msg.chat.id = math.floor(msg.chat.id)
msg.from.id = math.floor(msg.from.id)
if msg.text:find("/(%S+)@(%S+)[Bb][Oo][Tt]") then
return true
end
if os.time() - msg.date > config.ignore then
return true
end
for k, v in pairs(commands) do
if msg.text:find("^%s*/" .. k) and not msg.text:find("^%s*/" .. k .. "%S") then
if v.limit then
if v.limit.disable then
return bot.sendMessage{
chat_id = msg.chat.id,
text = "Sorry, the command is disabled.",
reply_to_message_id = msg.message_id
}
elseif v.limit.master and msg.from.username ~= config.master then
return bot.sendMessage{
chat_id = msg.chat.id,
text = "Sorry, permission denied.",
reply_to_message_id = msg.message_id
}
elseif (v.limit.match or v.limit.reply) and not ((v.limit.match and msg.text:find(v.limit.match)) or (v.limit.reply and msg.reply_to_message)) then
return commands.help.func(msg, k)
end
end
return v.func(msg)
end
end
for keyword, reply in pairs(conversation) do
local match = false
if type(keyword) == "string" then
match = msg.text:find(keyword)
elseif type(keyword) == "table" then
for i = 1, #keyword do
match = match or msg.text:find(keyword[i])
end
if keyword.reply and not msg.reply_to_message then
match = false
end
elseif type(keyword) == "function" then
match = keyword(msg.text)
end
if match then
local ans, rep
local rep_type = "Markdown"
if type(reply) == "string" then
ans = reply
elseif type(reply) == "table" then
ans = utils.rand(table.unpack(reply))
if reply.reply then
rep = msg.message_id
elseif reply.reply_to_reply and msg.reply_to_message then
rep = msg.reply_to_message.message_id
end
if reply.type then
rep_type = reply.type
end
elseif type(reply) == "function" then
ans = tostring(reply())
end
if ans:find("^sticker#%S-$") then
return bot.sendSticker(msg.chat.id, ans:match("^sticker#(%S-)$"), nil, rep)
elseif ans:find("^document#%S-$") then
return bot.sendDocument(msg.chat.id, ans:match("^document#(%S-)$"), nil, nil, rep)
else
return bot.sendMessage{
chat_id = msg.chat.id,
text = ans,
parse_mode = rep_type,
reply_to_message_id = rep
}
end
end
end
end
soul.ignore = function(msg) end
soul.onEditedMessageReceive = soul.ignore
soul.onLeftChatMembersReceive = soul.ignore
soul.onNewChatMembersReceive = soul.ignore
soul.onPhotoReceive = soul.ignore
soul.onAudioReceive = soul.ignore
soul.onVoiceReceive = soul.ignore
soul.onVideoReceive = soul.ignore
soul.onDocumentReceive = soul.ignore
soul.onGameReceive = soul.ignore
soul.onStickerReceive = soul.ignore
soul.onDiceReceive = soul.ignore
soul.onVideoNoteReceive = soul.ignore
soul.onContactReceive = soul.ignore
soul.onLocationReceive = soul.ignore
soul.onPinnedMessageReceive = soul.ignore
setmetatable(soul, {
__index = function(t, key)
logger:warn("called undefined processer " .. key)
return (function() return false end)
end
})
return soul
|
fix(soul): modified .emergency location
|
fix(soul): modified .emergency location
|
Lua
|
apache-2.0
|
SJoshua/Project-Small-R
|
0e32a10d40d8f3cc4662e3602cb730fad695d97e
|
lua/plugins/treesitter.lua
|
lua/plugins/treesitter.lua
|
local nvim = require'nvim'
local load_module = require'tools'.helpers.load_module
local plugins = nvim.plugins
local set_autocmd = nvim.autocmds.set_autocmd
-- local set_command = nvim.commands.set_command
-- local set_mapping = nvim.mappings.set_mapping
local treesitter = load_module'nvim-treesitter.configs'
if treesitter == nil then
return false
end
local ensure_installed = {
'c',
'cpp',
'lua',
'bash',
'python',
-- 'query',
}
local disable = nil
if plugins.semshi ~= nil then
disable = {'python'}
end
if plugins['vim-lsp-cxx-highlight'] ~= nil then
disable = disable == nil and {'c', 'cpp'} or vim.list_extend(disable, {'c', 'cpp'})
end
local commet_txtobj = nil
if plugins['vim-textobj-comment'] == nil then
commet_txtobj = '@comment.outer'
end
treesitter.setup{
ensure_installed = ensure_installed,
indent = {
enable = false
},
highlight = {
enable = true,
disable = disable,
},
textobjects = {
swap = {
enable = true,
swap_next = {
["<leader>a"] = "@parameter.inner",
["<leader>m"] = "@function.outer",
},
swap_previous = {
["<leader><leader>a"] = "@parameter.inner",
["<leader><leader>m"] = "@function.outer",
},
},
select = {
enable = true,
keymaps = {
["af"] = "@conditional.outer",
["if"] = "@conditional.inner",
["am"] = "@function.outer", -- Same as [m, ]m "method"
["im"] = "@function.inner",
["as"] = "@class.outer",
["is"] = "@class.inner",
["ia"] = "@parameter.inner",
["aa"] = "@parameter.inner",
["ir"] = "@loop.inner", -- "repeat" mnemonic
["ar"] = "@loop.outer",
["ac"] = commet_txtobj,
["ic"] = commet_txtobj,
},
},
move = {
enable = true,
goto_next_start = {
["]f"] = "@conditional.outer",
["]m"] = "@function.outer",
["]]"] = "@class.outer",
["]r"] = "@loop.outer",
["]a"] = "@parameter.inner",
["]c"] = "@comment.outer",
},
goto_next_end = {
["]F"] = "@conditional.outer",
["]M"] = "@function.outer",
["]["] = "@class.outer",
["]R"] = "@loop.outer",
["]A"] = "@parameter.inner",
["]C"] = "@comment.outer",
},
goto_previous_start = {
["[f"] = "@conditional.outer",
["[m"] = "@function.outer",
["[["] = "@class.outer",
["[r"] = "@loop.outer",
["[a"] = "@parameter.inner",
["[c"] = "@comment.outer",
},
goto_previous_end = {
["[F"] = "@conditional.outer",
["[M"] = "@function.outer",
["[]"] = "@class.outer",
["[R"] = "@loop.outer",
["[A"] = "@parameter.inner",
["[C"] = "@comment.outer",
},
},
-- lsp_interop = {
-- enable = true,
-- peek_definition_code = {
-- ["df"] = "@function.outer",
-- ["dF"] = "@class.outer",
-- },
-- },
},
refactor = {
-- highlight_current_scope = { enable = true },
smart_rename = {
enable = true,
keymaps = {
smart_rename = "<A-r>",
},
},
highlight_definitions = {
enable = true,
disable = disable,
},
navigation = {
enable = true,
keymaps = {
goto_definition = "<A-d>",
list_definitions = "<A-l>",
-- list_definitions_toc = "<A-t>",
goto_next_usage = "<A-n>",
goto_previous_usage = "<A-N>",
},
},
},
}
local parsers = require'nvim-treesitter.parsers'
local fts = {}
for lang,opts in pairs(parsers.list) do
if parsers.has_parser(lang) then
if opts.filetype ~= nil then
lang = opts.filetype
end
fts[#fts + 1] = lang
if opts.used_by ~= nil then
vim.list_extend(fts, opts.used_by)
end
end
end
if #fts > 0 then
-- TODO: Check module availability for each language
set_autocmd{
event = 'FileType',
pattern = fts,
cmd = 'setlocal foldmethod=expr foldexpr=nvim_treesitter#foldexpr()',
-- cmd = 'setlocal foldmethod=expr foldexpr=nvim_treesitter#foldexpr() indentexpr=nvim_treesitter#indent()',
group = 'TreesitterAutocmds',
}
end
return fts
|
local nvim = require'nvim'
local load_module = require'tools'.helpers.load_module
local plugins = nvim.plugins
local set_autocmd = nvim.autocmds.set_autocmd
-- local set_command = nvim.commands.set_command
-- local set_mapping = nvim.mappings.set_mapping
local treesitter = load_module'nvim-treesitter.configs'
if treesitter == nil then
return false
end
local ensure_installed = {
'c',
'cpp',
'lua',
'bash',
'python',
-- 'query',
}
local disable = nil
if plugins.semshi ~= nil then
disable = {'python'}
end
if plugins['vim-lsp-cxx-highlight'] ~= nil then
disable = disable == nil and {'c', 'cpp'} or vim.list_extend(disable, {'c', 'cpp'})
end
local commet_txtobj = nil
if plugins['vim-textobj-comment'] == nil then
commet_txtobj = '@comment.outer'
end
treesitter.setup{
ensure_installed = ensure_installed,
indent = {
enable = true,
},
highlight = {
enable = true,
disable = disable,
},
textobjects = {
swap = {
enable = true,
swap_next = {
["<leader>a"] = "@parameter.inner",
["<leader>m"] = "@function.outer",
},
swap_previous = {
["<leader><leader>a"] = "@parameter.inner",
["<leader><leader>m"] = "@function.outer",
},
},
select = {
enable = true,
keymaps = {
["af"] = "@conditional.outer",
["if"] = "@conditional.inner",
["am"] = "@function.outer", -- Same as [m, ]m "method"
["im"] = "@function.inner",
["as"] = "@class.outer",
["is"] = "@class.inner",
["ia"] = "@parameter.inner",
["aa"] = "@parameter.inner",
["ir"] = "@loop.inner", -- "repeat" mnemonic
["ar"] = "@loop.outer",
["ac"] = commet_txtobj,
["ic"] = commet_txtobj,
},
},
move = {
enable = true,
goto_next_start = {
["]f"] = "@conditional.outer",
["]m"] = "@function.outer",
["]]"] = "@class.outer",
["]r"] = "@loop.outer",
["]a"] = "@parameter.inner",
["]c"] = "@comment.outer",
},
goto_next_end = {
["]F"] = "@conditional.outer",
["]M"] = "@function.outer",
["]["] = "@class.outer",
["]R"] = "@loop.outer",
["]A"] = "@parameter.inner",
["]C"] = "@comment.outer",
},
goto_previous_start = {
["[f"] = "@conditional.outer",
["[m"] = "@function.outer",
["[["] = "@class.outer",
["[r"] = "@loop.outer",
["[a"] = "@parameter.inner",
["[c"] = "@comment.outer",
},
goto_previous_end = {
["[F"] = "@conditional.outer",
["[M"] = "@function.outer",
["[]"] = "@class.outer",
["[R"] = "@loop.outer",
["[A"] = "@parameter.inner",
["[C"] = "@comment.outer",
},
},
-- lsp_interop = {
-- enable = true,
-- peek_definition_code = {
-- ["df"] = "@function.outer",
-- ["dF"] = "@class.outer",
-- },
-- },
},
refactor = {
-- highlight_current_scope = { enable = true },
smart_rename = {
enable = true,
keymaps = {
smart_rename = "<A-r>",
},
},
highlight_definitions = {
enable = true,
disable = disable,
},
navigation = {
enable = true,
keymaps = {
goto_definition = "<A-d>",
list_definitions = "<A-l>",
goto_next_usage = "<A-n>",
goto_previous_usage = "<A-N>",
-- list_definitions_toc = "<A-t>",
},
},
},
}
local parsers = require'nvim-treesitter.parsers'
local fts = {}
for lang,opts in pairs(parsers.list) do
if parsers.has_parser(lang) then
if opts.filetype ~= nil then
lang = opts.filetype
end
fts[#fts + 1] = lang
if opts.used_by ~= nil then
vim.list_extend(fts, opts.used_by)
end
end
end
if #fts > 0 then
-- TODO: Check module availability for each language
set_autocmd{
event = 'FileType',
pattern = fts,
cmd = 'setlocal foldmethod=expr foldexpr=nvim_treesitter#foldexpr()',
group = 'TreesitterAutocmds',
}
end
return fts
|
fix: Re-enable indent treesitter support
|
fix: Re-enable indent treesitter support
|
Lua
|
mit
|
Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim
|
e060d212cdf6aa3f9b7fd67a8af15739bdd8052d
|
Hydra/API/updates.lua
|
Hydra/API/updates.lua
|
local function normalize(str)
return str:gsub("(%d+)", function(n) return ("%02d"):format(n) end)
end
--- updates.check(fn(isavailable))
--- Checks for an update. Calls the given function with a boolean representing whether a new update is available.
function updates.check(fn)
updates.getversions(function(versions)
table.sort(versions, function(a, b) return normalize(a.number) < normalize(b.number) end)
local hasupdate = normalize(versions[#versions].number) > normalize(updates.currentversion())
fn(hasupdate)
end)
end
--- updates.changelogurl
--- String of the URL that contains the changelog, rendered via Markdown
updates.changelogurl = "https://github.com/sdegutis/hydra/releases"
|
local function normalize(str)
if str == 'v1.0.b99' then -- yeah, i messed up
return '00.00'
else
return str:gsub("(%d+)", function(n) return ("%02d"):format(n) end)
end
end
--- updates.check(fn(isavailable))
--- Checks for an update. Calls the given function with a boolean representing whether a new update is available.
function updates.check(fn)
updates.getversions(function(versions)
table.sort(versions, function(a, b) return normalize(a.number) < normalize(b.number) end)
local hasupdate = normalize(versions[#versions].number) > normalize(updates.currentversion())
fn(hasupdate)
end)
end
--- updates.changelogurl
--- String of the URL that contains the changelog, rendered via Markdown
updates.changelogurl = "https://github.com/sdegutis/hydra/releases"
|
Fix updates (le sigh) for future and past releases.
|
Fix updates (le sigh) for future and past releases.
|
Lua
|
mit
|
CommandPost/CommandPost-App,asmagill/hammerspoon,kkamdooong/hammerspoon,zzamboni/hammerspoon,chrisjbray/hammerspoon,TimVonsee/hammerspoon,knl/hammerspoon,bradparks/hammerspoon,latenitefilms/hammerspoon,Hammerspoon/hammerspoon,Stimim/hammerspoon,tmandry/hammerspoon,CommandPost/CommandPost-App,wsmith323/hammerspoon,latenitefilms/hammerspoon,kkamdooong/hammerspoon,heptal/hammerspoon,latenitefilms/hammerspoon,hypebeast/hammerspoon,heptal/hammerspoon,wvierber/hammerspoon,Habbie/hammerspoon,trishume/hammerspoon,ocurr/hammerspoon,cmsj/hammerspoon,cmsj/hammerspoon,knu/hammerspoon,cmsj/hammerspoon,tmandry/hammerspoon,Stimim/hammerspoon,junkblocker/hammerspoon,dopcn/hammerspoon,Hammerspoon/hammerspoon,Habbie/hammerspoon,nkgm/hammerspoon,heptal/hammerspoon,asmagill/hammerspoon,peterhajas/hammerspoon,bradparks/hammerspoon,asmagill/hammerspoon,junkblocker/hammerspoon,heptal/hammerspoon,chrisjbray/hammerspoon,lowne/hammerspoon,junkblocker/hammerspoon,Stimim/hammerspoon,asmagill/hammerspoon,chrisjbray/hammerspoon,TimVonsee/hammerspoon,hypebeast/hammerspoon,zzamboni/hammerspoon,TimVonsee/hammerspoon,tmandry/hammerspoon,kkamdooong/hammerspoon,peterhajas/hammerspoon,Stimim/hammerspoon,joehanchoi/hammerspoon,bradparks/hammerspoon,wsmith323/hammerspoon,emoses/hammerspoon,joehanchoi/hammerspoon,Habbie/hammerspoon,CommandPost/CommandPost-App,dopcn/hammerspoon,cmsj/hammerspoon,latenitefilms/hammerspoon,junkblocker/hammerspoon,CommandPost/CommandPost-App,ocurr/hammerspoon,Hammerspoon/hammerspoon,heptal/hammerspoon,Habbie/hammerspoon,junkblocker/hammerspoon,bradparks/hammerspoon,joehanchoi/hammerspoon,emoses/hammerspoon,knl/hammerspoon,nkgm/hammerspoon,trishume/hammerspoon,nkgm/hammerspoon,wvierber/hammerspoon,chrisjbray/hammerspoon,knu/hammerspoon,Hammerspoon/hammerspoon,dopcn/hammerspoon,Hammerspoon/hammerspoon,ocurr/hammerspoon,knu/hammerspoon,trishume/hammerspoon,emoses/hammerspoon,zzamboni/hammerspoon,latenitefilms/hammerspoon,knu/hammerspoon,cmsj/hammerspoon,ocurr/hammerspoon,nkgm/hammerspoon,ocurr/hammerspoon,cmsj/hammerspoon,knl/hammerspoon,wvierber/hammerspoon,kkamdooong/hammerspoon,lowne/hammerspoon,hypebeast/hammerspoon,peterhajas/hammerspoon,wsmith323/hammerspoon,zzamboni/hammerspoon,lowne/hammerspoon,wsmith323/hammerspoon,TimVonsee/hammerspoon,zzamboni/hammerspoon,knu/hammerspoon,chrisjbray/hammerspoon,dopcn/hammerspoon,wvierber/hammerspoon,latenitefilms/hammerspoon,peterhajas/hammerspoon,Habbie/hammerspoon,Habbie/hammerspoon,knl/hammerspoon,CommandPost/CommandPost-App,joehanchoi/hammerspoon,zzamboni/hammerspoon,hypebeast/hammerspoon,bradparks/hammerspoon,wvierber/hammerspoon,hypebeast/hammerspoon,nkgm/hammerspoon,asmagill/hammerspoon,knu/hammerspoon,dopcn/hammerspoon,CommandPost/CommandPost-App,lowne/hammerspoon,lowne/hammerspoon,knl/hammerspoon,kkamdooong/hammerspoon,TimVonsee/hammerspoon,Hammerspoon/hammerspoon,Stimim/hammerspoon,wsmith323/hammerspoon,asmagill/hammerspoon,peterhajas/hammerspoon,joehanchoi/hammerspoon,chrisjbray/hammerspoon,emoses/hammerspoon,emoses/hammerspoon
|
19dc2c92454dcc73d4ead8c582266d2961760c6b
|
orange/plugins/waf/api.lua
|
orange/plugins/waf/api.lua
|
local BaseAPI = require("orange.plugins.base_api")
local common_api = require("orange.plugins.common_api")
local stat = require("orange.plugins.waf.stat")
local api = BaseAPI:new("waf-api", 2)
api:merge_apis(common_api("waf"))
api:get("/waf/stat", function(store)
return function(req, res, next)
local max_count = req.query.max_count or 500
local stats = stat.get_all(max_count)
local statistics = {}
for i, s in ipairs(stats) do
local tmp = {
rule_id = s.rule_id,
count = s.count,
}
table_insert(statistics, tmp)
end
local result = {
success = true,
data = {
statistics = statistics
}
}
res:json(result)
end
end)
return api
|
local BaseAPI = require("orange.plugins.base_api")
local common_api = require("orange.plugins.common_api")
local table_insert = table.insert
local stat = require("orange.plugins.waf.stat")
local api = BaseAPI:new("waf-api", 2)
api:merge_apis(common_api("waf"))
api:get("/waf/stat", function(store)
return function(req, res, next)
local max_count = req.query.max_count or 500
local stats = stat.get_all(max_count)
local statistics = {}
for i, s in ipairs(stats) do
local tmp = {
rule_id = s.rule_id,
count = s.count,
}
table_insert(statistics, tmp)
end
local result = {
success = true,
data = {
statistics = statistics
}
}
res:json(result)
end
end)
return api
|
fix: missing table.insert
|
fix: missing table.insert
|
Lua
|
mit
|
thisverygoodhhhh/orange,jxskiss/orange,wuhuatianbao007/orange,thisverygoodhhhh/orange,thisverygoodhhhh/orange,sumory/orange,sumory/orange,wuhuatianbao007/orange,jxskiss/orange,sumory/orange,wuhuatianbao007/orange,jxskiss/orange
|
fe6075f7bbc971ba6c11db46fc8573bf15c8c5dc
|
plugins/get.lua
|
plugins/get.lua
|
local function get_variables_hash(msg)
if msg.to.type == 'channel' then
return 'channel:' .. msg.to.id .. ':variables'
end
if msg.to.type == 'chat' then
return 'chat:' .. msg.to.id .. ':variables'
end
if msg.to.type == 'user' then
return 'user:' .. msg.from.id .. ':variables'
end
end
local function get_value(msg, var_name)
local hash = get_variables_hash(msg)
var_name = var_name:gsub(' ', '_')
if hash then
local value = redis:hget(hash, var_name)
if value then
return value
else
return
end
end
end
local function list_variables(msg)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = ''
for i = 1, #names do
text = text .. names[i]:gsub('_', ' ') .. '\n'
end
return text
end
end
local function run(msg, matches)
if (matches[1]:lower() == 'get' or matches[1]:lower() == 'getlist' or matches[1]:lower() == 'sasha lista') and not matches[2] then
return list_variables(msg)
end
end
local function pre_process(msg, matches)
local vars = list_variables(msg)
if vars ~= nil then
local t = vars:split('\n')
for i, word in pairs(t) do
local temp = word:lower()
if word:lower() ~= 'get' and string.find(msg.text:lower(), temp) then
local value = get_value(msg, word:lower())
if value then
if not string.match(value, "^(.*)user%.(%d+)%.variables(.*)$") and not string.match(value, "^(.*)chat%.(%d+)%.variables(.*)$") and not string.match(value, "^(.*)channel%.(%d+)%.variables(.*)$") then
-- if not media
reply_msg(msg.id, get_value(msg, word:lower()), ok_cb, false)
elseif string.match(value, "^(.*)user%.(%d+)%.variables(.*)%.jpg$") or string.match(value, "^(.*)chat%.(%d+)%.variables(.*)%.jpg$") or string.match(value, "^(.*)channel%.(%d+)%.variables(.*)%.jpg$") then
-- if picture
if io.popen('find ' .. value):read("*all") ~= '' then
send_photo(get_receiver(msg), value, ok_cb, false)
end
elseif string.match(value, "^(.*)user%.(%d+)%.variables(.*)%.ogg$") or string.match(value, "^(.*)chat%.(%d+)%.variables(.*)%.ogg$") or string.match(value, "^(.*)channel%.(%d+)%.variables(.*)%.ogg$") then
-- if audio
if io.popen('find ' .. value):read("*all") ~= '' then
send_audio(get_receiver(msg), value, ok_cb, false)
end
end
end
end
end
end
return msg
end
return {
description = "GET",
patterns =
{
"^[#!/]([Gg][Ee][Tt][Ll][Ii][Ss][Tt])$",
-- getlist
"^[#!/]([Gg][Ee][Tt])$",
"^([Ss][Aa][Ss][Hh][Aa] [Ll][Ii][Ss][Tt][Aa])$",
},
pre_process = pre_process,
run = run,
min_rank = 0
-- usage
-- (#getlist|#get|sasha lista)
}
|
local function get_variables_hash(msg)
if msg.to.type == 'channel' then
return 'channel:' .. msg.to.id .. ':variables'
end
if msg.to.type == 'chat' then
return 'chat:' .. msg.to.id .. ':variables'
end
if msg.to.type == 'user' then
return 'user:' .. msg.from.id .. ':variables'
end
end
local function get_value(msg, var_name)
local hash = get_variables_hash(msg)
var_name = var_name:gsub(' ', '_')
if hash then
local value = redis:hget(hash, var_name)
if value then
return value
else
return
end
end
end
local function list_variables(msg)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = ''
for i = 1, #names do
text = text .. names[i]:gsub('_', ' ') .. '\n'
end
return text
end
end
local function run(msg, matches)
if (matches[1]:lower() == 'get' or matches[1]:lower() == 'getlist' or matches[1]:lower() == 'sasha lista') and not matches[2] then
return list_variables(msg)
end
end
local function pre_process(msg, matches)
if msg.text then
local vars = list_variables(msg)
if vars ~= nil then
local t = vars:split('\n')
for i, word in pairs(t) do
local temp = word:lower()
if word:lower() ~= 'get' and string.find(msg.text:lower(), temp) then
local value = get_value(msg, word:lower())
if value then
if not string.match(value, "^(.*)user%.(%d+)%.variables(.*)$") and not string.match(value, "^(.*)chat%.(%d+)%.variables(.*)$") and not string.match(value, "^(.*)channel%.(%d+)%.variables(.*)$") then
-- if not media
reply_msg(msg.id, get_value(msg, word:lower()), ok_cb, false)
elseif string.match(value, "^(.*)user%.(%d+)%.variables(.*)%.jpg$") or string.match(value, "^(.*)chat%.(%d+)%.variables(.*)%.jpg$") or string.match(value, "^(.*)channel%.(%d+)%.variables(.*)%.jpg$") then
-- if picture
if io.popen('find ' .. value):read("*all") ~= '' then
send_photo(get_receiver(msg), value, ok_cb, false)
end
elseif string.match(value, "^(.*)user%.(%d+)%.variables(.*)%.ogg$") or string.match(value, "^(.*)chat%.(%d+)%.variables(.*)%.ogg$") or string.match(value, "^(.*)channel%.(%d+)%.variables(.*)%.ogg$") then
-- if audio
if io.popen('find ' .. value):read("*all") ~= '' then
send_audio(get_receiver(msg), value, ok_cb, false)
end
end
end
end
end
end
end
return msg
end
return {
description = "GET",
patterns =
{
"^[#!/]([Gg][Ee][Tt][Ll][Ii][Ss][Tt])$",
-- getlist
"^[#!/]([Gg][Ee][Tt])$",
"^([Ss][Aa][Ss][Hh][Aa] [Ll][Ii][Ss][Tt][Aa])$",
},
pre_process = pre_process,
run = run,
min_rank = 0
-- usage
-- (#getlist|#get|sasha lista)
}
|
fix get pre_process
|
fix get pre_process
|
Lua
|
agpl-3.0
|
xsolinsx/AISasha
|
1483cab3e2b6858828a1ca78ee923491be396d81
|
cherry/screens/leaderboard.lua
|
cherry/screens/leaderboard.lua
|
--------------------------------------------------------------------------------
local _ = require 'cherry.libs.underscore'
local gesture = require 'cherry.libs.gesture'
local group = require 'cherry.libs.group'
local http = require 'cherry.libs.http'
local Background = require 'cherry.components.background'
local Text = require 'cherry.components.text'
local json = require 'dkjson'
--------------------------------------------------------------------------------
local scene = _G.composer.newScene()
local selectedButton = nil
local board = nil
local boardData = {}
local CLOSED_Y = 35
local OPEN_Y = 70
local BOARD_CENTER_X = display.contentWidth * 0.5
local BOARD_CENTER_Y = display.contentHeight * 0.5 + 100
local BOARD_WIDTH = display.contentWidth * 0.9
local BOARD_HEIGHT = display.contentHeight * 0.85
--------------------------------------------------------------------------------
local function fetchData(field, next)
display.newText({
parent = board,
text = 'loading...',
font = _G.FONT,
fontSize = 40,
x = BOARD_CENTER_X,
y = BOARD_CENTER_Y
})
local url = App.API_GATEWAY_URL .. '/leaderboard/' .. App.name .. '/' .. field.name
http.get(url, function(event)
local data = json.decode(event.response)
local lines = {}
for _,entry in pairs(data.Items) do
local num = #lines + 1
local position = num
local value = entry[field.name].N
if(num > 1) then
if(lines[num - 1][field.name] == value) then
position = lines[num - 1].position
else
position = lines[num - 1].position + 1
end
end
lines[num] = {
playerName = entry.playerName.S,
playerId = entry.playerId.S,
position = position
}
lines[num][field.name] = value
end
boardData[field.name] = lines
next(field)
end)
end
--------------------------------------------------------------------------------
local function displayData(field, refresh)
local lines = boardData[field.name]
for i, line in pairs(lines) do
local color = '#ffffff'
if(line.playerId == App.user:id()) then
color = '#32cd32'
end
timer.performWithDelay(math.random(100, 700), function()
Text:create({
parent = board,
value = line.position,
x = BOARD_CENTER_X - BOARD_WIDTH * 0.5 + 30,
y = BOARD_CENTER_Y - BOARD_HEIGHT * 0.5 + 50 + (i - 1) * 50,
color = color,
font = _G.FONT,
fontSize = 45,
anchorX = 0,
grow = true
})
end)
timer.performWithDelay(math.random(100, 700), function()
Text:create({
parent = board,
value = line.playerName,
x = BOARD_CENTER_X - BOARD_WIDTH * 0.5 + 80,
y = BOARD_CENTER_Y - BOARD_HEIGHT * 0.5 + 50 + (i - 1) * 50,
color = color,
font = _G.FONT,
fontSize = 45,
anchorX = 0,
grow = true
})
end)
timer.performWithDelay(math.random(100, 700), function()
Text:create({
parent = board,
value = line[field.name],
x = BOARD_CENTER_X + BOARD_WIDTH * 0.5 - 100,
y = BOARD_CENTER_Y - BOARD_HEIGHT * 0.5 + 50 + (i - 1) * 50,
color = color,
font = _G.FONT,
fontSize = 45,
anchorX = 0,
grow = true
})
end)
end
end
--------------------------------------------------------------------------------
local function refreshBoard(field)
if(board) then
group.destroy(board)
end
board = display.newGroup()
App.hud:insert(board)
local bg = display.newRect(
board,
BOARD_CENTER_X,
BOARD_CENTER_Y,
BOARD_WIDTH,
BOARD_HEIGHT
)
bg:setFillColor(0, 0, 0, 0.7)
local fetchAndDisplay = function()
fetchData(field, refreshBoard)
end
if(not boardData[field.name]) then
fetchAndDisplay()
else
displayData(field, fetchAndDisplay)
end
end
--------------------------------------------------------------------------------
local function select(button)
if(selectedButton) then
if(button == selectedButton) then return end
transition.to(selectedButton, {
y = CLOSED_Y,
time = 250,
transition = easing.outBack
})
end
selectedButton = button
transition.to(button, {
y = OPEN_Y,
time = 250,
transition = easing.outBack
})
refreshBoard(button.field)
end
--------------------------------------------------------------------------------
local function drawBackArrow()
local backArrow = display.newImage(
App.hud,
'cherry/assets/images/gui/items/arrow.right.png',
50, 50
)
backArrow.rotation = 180
backArrow:scale(0.6, 0.6)
gesture.onTap(backArrow, function()
Router:open(Router.HOME)
end)
end
--------------------------------------------------------------------------------
local function drawButton(num)
local field = _.defaults(App.scoreFields[num], {
scale = 1
})
----------------------
local button = display.newGroup()
App.hud:insert(button)
button.field = field
button.x = 250 + (num - 1) * 150
button.y = CLOSED_Y
----------------------
display.newImage(
button,
'cherry/assets/images/gui/buttons/tab-vertical.png'
)
----------------------
local icon = display.newImage(
button,
field.image,
0, 10
)
icon:scale(field.scale, field.scale)
----------------------
display.newText({
parent = button,
y = -50,
text = field.label,
font = _G.FONT,
fontSize = 40
})
----------------------
gesture.onTap(button, function()
select(button)
end)
return button
end
--------------------------------------------------------------------------------
function scene:create( event )
end
function scene:show( event )
if ( event.phase == 'did' ) then
boardData = {}
Background:darken()
drawBackArrow()
local buttons = {}
for i = 1, #App.scoreFields do
buttons[i] = drawButton(i)
end
select(buttons[1])
end
end
function scene:hide( event )
end
function scene:destroy( event )
end
--------------------------------------------------------------------------------
scene:addEventListener( 'create', scene )
scene:addEventListener( 'show', scene )
scene:addEventListener( 'hide', scene )
scene:addEventListener( 'destroy', scene )
--------------------------------------------------------------------------------
return scene
|
--------------------------------------------------------------------------------
local _ = require 'cherry.libs.underscore'
local gesture = require 'cherry.libs.gesture'
local group = require 'cherry.libs.group'
local http = require 'cherry.libs.http'
local Background = require 'cherry.components.background'
local Text = require 'cherry.components.text'
local json = require 'dkjson'
--------------------------------------------------------------------------------
local scene = _G.composer.newScene()
local selectedButton = nil
local board = nil
local boardData = {}
local CLOSED_Y = 35
local OPEN_Y = 70
local BOARD_CENTER_X = display.contentWidth * 0.5
local BOARD_CENTER_Y = display.contentHeight * 0.5 + 100
local BOARD_WIDTH = display.contentWidth * 0.9
local BOARD_HEIGHT = display.contentHeight * 0.85
--------------------------------------------------------------------------------
local function fetchData(field, next)
display.newText({
parent = board,
text = 'loading...',
font = _G.FONT,
fontSize = 40,
x = BOARD_CENTER_X,
y = BOARD_CENTER_Y
})
local url = App.API_GATEWAY_URL .. '/leaderboard/' .. App.name .. '/' .. field.name
http.get(url, function(event)
local data = json.decode(event.response)
local lines = {}
for position,entry in pairs(data.Items) do
local num = #lines + 1
local value = entry[field.name].N
if(num > 1 and lines[num - 1][field.name] == value) then
position = lines[num - 1].position
end
lines[num] = {
playerName = entry.playerName.S,
playerId = entry.playerId.S,
position = position
}
lines[num][field.name] = value
end
boardData[field.name] = lines
next(field)
end)
end
--------------------------------------------------------------------------------
local function displayData(field)
local lines = boardData[field.name]
for i, line in pairs(lines) do
local color = '#ffffff'
if(line.playerId == App.user:id()) then
color = '#32cd32'
end
timer.performWithDelay(math.random(100, 700), function()
if(board.field ~= field) then return end
Text:create({
parent = board,
value = line.position,
x = BOARD_CENTER_X - BOARD_WIDTH * 0.5 + 30,
y = BOARD_CENTER_Y - BOARD_HEIGHT * 0.5 + 50 + (i - 1) * 50,
color = color,
font = _G.FONT,
fontSize = 45,
anchorX = 0,
grow = true
})
end)
timer.performWithDelay(math.random(100, 700), function()
if(board.field ~= field) then return end
Text:create({
parent = board,
value = line.playerName,
x = BOARD_CENTER_X - BOARD_WIDTH * 0.5 + 80,
y = BOARD_CENTER_Y - BOARD_HEIGHT * 0.5 + 50 + (i - 1) * 50,
color = color,
font = _G.FONT,
fontSize = 45,
anchorX = 0,
grow = true
})
end)
timer.performWithDelay(math.random(100, 700), function()
if(board.field ~= field) then return end
Text:create({
parent = board,
value = line[field.name],
x = BOARD_CENTER_X + BOARD_WIDTH * 0.5 - 100,
y = BOARD_CENTER_Y - BOARD_HEIGHT * 0.5 + 50 + (i - 1) * 50,
color = color,
font = _G.FONT,
fontSize = 45,
anchorX = 0,
grow = true
})
end)
end
end
--------------------------------------------------------------------------------
local function refreshBoard(field)
if(board) then
group.destroy(board)
end
board = display.newGroup()
board.field = field
App.hud:insert(board)
local bg = display.newRect(
board,
BOARD_CENTER_X,
BOARD_CENTER_Y,
BOARD_WIDTH,
BOARD_HEIGHT
)
bg:setFillColor(0, 0, 0, 0.7)
if(not boardData[field.name]) then
fetchData(field, refreshBoard)
else
displayData(field)
end
end
--------------------------------------------------------------------------------
local function select(button)
if(selectedButton) then
if(button == selectedButton) then return end
transition.to(selectedButton, {
y = CLOSED_Y,
time = 250,
transition = easing.outBack
})
end
selectedButton = button
transition.to(button, {
y = OPEN_Y,
time = 250,
transition = easing.outBack
})
refreshBoard(button.field)
end
--------------------------------------------------------------------------------
local function drawBackArrow()
local backArrow = display.newImage(
App.hud,
'cherry/assets/images/gui/items/arrow.right.png',
50, 50
)
backArrow.rotation = 180
backArrow:scale(0.6, 0.6)
gesture.onTap(backArrow, function()
Router:open(Router.HOME)
end)
end
--------------------------------------------------------------------------------
local function drawButton(num)
local field = _.defaults(App.scoreFields[num], {
scale = 1
})
----------------------
local button = display.newGroup()
App.hud:insert(button)
button.field = field
button.x = 250 + (num - 1) * 150
button.y = CLOSED_Y
----------------------
display.newImage(
button,
'cherry/assets/images/gui/buttons/tab-vertical.png'
)
----------------------
local icon = display.newImage(
button,
field.image,
0, 10
)
icon:scale(field.scale, field.scale)
----------------------
display.newText({
parent = button,
y = -50,
text = field.label,
font = _G.FONT,
fontSize = 40
})
----------------------
gesture.onTap(button, function()
select(button)
end)
return button
end
--------------------------------------------------------------------------------
function scene:create( event )
end
function scene:show( event )
if ( event.phase == 'did' ) then
boardData = {}
Background:darken()
drawBackArrow()
local buttons = {}
for i = 1, #App.scoreFields do
buttons[i] = drawButton(i)
end
select(buttons[1])
end
end
function scene:hide( event )
board.field = nil
end
function scene:destroy( event )
end
--------------------------------------------------------------------------------
scene:addEventListener( 'create', scene )
scene:addEventListener( 'show', scene )
scene:addEventListener( 'hide', scene )
scene:addEventListener( 'destroy', scene )
--------------------------------------------------------------------------------
return scene
|
fixed leaderboard display
|
fixed leaderboard display
|
Lua
|
bsd-3-clause
|
chrisdugne/cherry
|
22e36f97b8195d93e258d673f0684754f20767d7
|
src/base/context.lua
|
src/base/context.lua
|
--
-- base/context.lua
--
-- Provide a context for pulling out values from a configuration set. Each
-- context has an associated list of terms which constrain the values that
-- it will retrieve, i.e. "Windows, "Debug", "x64", and so on.
--
-- The context also provides caching for the values returned from the set.
--
-- TODO: I may roll this functionality up into the container API at some
-- point. If you find yourself using or extending this code for your own
-- work give me a shout before you go too far with it so we can coordinate.
--
-- Copyright (c) 2012-2014 Jason Perkins and the Premake project
--
local p = premake
p.context = {}
local context = p.context
local configset = p.configset
--
-- Create a new context object.
--
-- @param cfgset
-- The configuration set to provide the data from this context.
-- @param environ
-- An optional key-value environment table for token expansion; keys and
-- values provided in this table will be available for tokens to use.
-- @param filename
-- An optional filename, which will limit the fetched results to blocks
-- which specifically match the provided name.
-- @return
-- A new context object.
--
function context.new(cfgset, environ)
local ctx = {}
ctx._cfgset = cfgset
ctx.environ = environ or {}
ctx.terms = {}
-- This base directory is used when expanding path tokens encountered
-- in non-path value; such values will be made relative to this value
-- so the resulting projects will only contain relative paths. It is
-- expected that the creator of the context will set this value using
-- the setbasedir() function.
ctx._basedir = os.getcwd()
-- when a missing field is requested, fetch it from my config
-- set, and then cache the value for future lookups
setmetatable(ctx, context.__mt)
return ctx
end
--
-- Create an extended and uncached context based on another context object.
--
-- @param baseContext
-- The base context to extent
-- @param newEnvVars
-- An optional key-value environment table for token expansion; keys and
-- values provided in this table will be available for tokens to use.
-- @return
-- A new context object.
--
function context.extent(baseContext, newEnvVars)
local ctx = {}
ctx._ctx = baseContext
ctx.environ = newEnvVars or baseContext.environ
ctx.terms = {}
ctx._basedir = baseContext._basedir
setmetatable(ctx, context.__mt_uncached)
return ctx
end
---
-- Add a new key-value pair to refine the context filtering.
--
-- @param ctx
-- The context to be filtered.
-- @param key
-- The new (or an existing) key value.
-- @param value
-- The filtering value for the key.
---
function context.addFilter(ctx, key, value)
if type(value) == "table" then
for i = 1, #value do
value[i] = tostring(value[i]):lower()
end
elseif value ~= nil then
value = tostring(value):lower()
end
ctx.terms[key:lower()] = value
end
--
-- Copies the list of terms from an existing context.
--
-- @param ctx
-- The context to receive the copied terms.
-- @param src
-- The context containing the terms to copy.
--
function context.copyFilters(ctx, src)
ctx.terms = {}
for k,v in pairs(src.terms) do
ctx.terms[k] = v
end
end
--
-- Merges the list of terms from an existing context.
--
-- @param ctx
-- The context to receive the copied terms.
-- @param src
-- The context containing the terms to copy.
--
function context.mergeFilters(ctx, src)
if src.terms ~= nil then
for k, v in pairs(src.terms) do
ctx.terms[k] = table.joinunique(ctx.terms[k] or {}, src.terms[k])
if #ctx.terms[k] == 1 then
ctx.terms[k] = ctx.terms[k][1]
end
end
end
end
--
-- Sets the base directory for path token expansion in non-path fields; such
-- values will be made relative to this path.
--
-- @param ctx
-- The context in which to set the value.
-- @param basedir
-- The new base directory for path token expansion. This should be
-- provided as an absolute path. This may be left nil to simply fetch
-- the current base directory.
-- @return
-- The context's base directory.
--
function context.basedir(ctx, basedir)
ctx._basedir = basedir or ctx._basedir
return ctx._basedir
end
--
-- Compiles the context for better performance. The list of context terms
-- becomes locked down; any subsequent changes are ignored.
--
-- @param ctx
-- The context to compile.
--
function context.compile(ctx)
ctx._cfgset = configset.compile(ctx._cfgset, ctx.terms)
end
--
-- Check to see if a context's underlying configuration set is empty; that
-- is, it does not contain any configuration blocks.
--
-- @param ctx
-- The context to query.
-- @return
-- True if the set does not contain any blocks.
--
function context.empty(ctx)
return configset.empty(ctx._cfgset)
end
--
-- Fetch a value from underlying configuration set.
--
-- @param ctx
-- The context to query.
-- @param key
-- The property key to query.
-- @param onlylocal
-- If true, don't combine values from parent contexts.
-- @return
-- The value of the key, as determined by the configuration set. If
-- there is a corresponding Premake field, and it the field is enabled
-- for tokens, any contained tokens will be expanded.
--
function context.fetchvalue(ctx, key, onlylocal)
if not onlylocal then
local value = rawget(ctx, key)
if value ~= nil then
return value
end
end
-- The underlying configuration set will only hold registered fields.
-- If the requested key doesn't have a corresponding field, it is just
-- a regular value to be stored and fetched from the table.
local field = p.field.get(key)
if not field then
return nil
end
-- If there is a matching field, then go fetch the aggregated value
-- from my configuration set, and then cache it future lookups.
local value = configset.fetch(ctx._cfgset, field, ctx.terms, ctx, onlylocal and ctx._cfgset)
if value then
-- store the result for later lookups
rawset(ctx, key, value)
end
return value
end
context.__mt = {
__index = context.fetchvalue
}
context.__mt_uncached = {
__index = function(ctx, key)
local field = p.field.get(key)
if not field then
return nil
end
local parent = rawget(ctx, '_ctx')
return configset.fetch(parent._cfgset, field, ctx.terms, ctx, nil)
end
}
|
--
-- base/context.lua
--
-- Provide a context for pulling out values from a configuration set. Each
-- context has an associated list of terms which constrain the values that
-- it will retrieve, i.e. "Windows, "Debug", "x64", and so on.
--
-- The context also provides caching for the values returned from the set.
--
-- TODO: I may roll this functionality up into the container API at some
-- point. If you find yourself using or extending this code for your own
-- work give me a shout before you go too far with it so we can coordinate.
--
-- Copyright (c) 2012-2014 Jason Perkins and the Premake project
--
local p = premake
p.context = {}
local context = p.context
local configset = p.configset
--
-- Create a new context object.
--
-- @param cfgset
-- The configuration set to provide the data from this context.
-- @param environ
-- An optional key-value environment table for token expansion; keys and
-- values provided in this table will be available for tokens to use.
-- @param filename
-- An optional filename, which will limit the fetched results to blocks
-- which specifically match the provided name.
-- @return
-- A new context object.
--
function context.new(cfgset, environ)
local ctx = {}
ctx._cfgset = cfgset
ctx.environ = environ or {}
ctx.terms = {}
-- This base directory is used when expanding path tokens encountered
-- in non-path value; such values will be made relative to this value
-- so the resulting projects will only contain relative paths. It is
-- expected that the creator of the context will set this value using
-- the setbasedir() function.
ctx._basedir = os.getcwd()
-- when a missing field is requested, fetch it from my config
-- set, and then cache the value for future lookups
setmetatable(ctx, context.__mt)
return ctx
end
--
-- Create an extended and uncached context based on another context object.
--
-- @param baseContext
-- The base context to extent
-- @param newEnvVars
-- An optional key-value environment table for token expansion; keys and
-- values provided in this table will be available for tokens to use.
-- @return
-- A new context object.
--
function context.extent(baseContext, newEnvVars)
local ctx = {}
ctx._ctx = baseContext
ctx.environ = newEnvVars or baseContext.environ
ctx.terms = {}
ctx._basedir = baseContext._basedir
setmetatable(ctx, context.__mt_uncached)
return ctx
end
---
-- Add a new key-value pair to refine the context filtering.
--
-- @param ctx
-- The context to be filtered.
-- @param key
-- The new (or an existing) key value.
-- @param value
-- The filtering value for the key.
---
function context.addFilter(ctx, key, value)
if type(value) == "table" then
for i = 1, #value do
value[i] = tostring(value[i]):lower()
end
elseif value ~= nil then
value = tostring(value):lower()
end
ctx.terms[key:lower()] = value
end
--
-- Copies the list of terms from an existing context.
--
-- @param ctx
-- The context to receive the copied terms.
-- @param src
-- The context containing the terms to copy.
--
function context.copyFilters(ctx, src)
ctx.terms = {}
for k,v in pairs(src.terms) do
ctx.terms[k] = v
end
end
--
-- Merges the list of terms from an existing context.
--
-- @param ctx
-- The context to receive the copied terms.
-- @param src
-- The context containing the terms to copy.
--
function context.mergeFilters(ctx, src)
for k, v in pairs(src.terms) do
if k == "tags" then
ctx.terms[k] = table.join(ctx.terms[k], v)
else
ctx.terms[k] = v
end
end
end
--
-- Sets the base directory for path token expansion in non-path fields; such
-- values will be made relative to this path.
--
-- @param ctx
-- The context in which to set the value.
-- @param basedir
-- The new base directory for path token expansion. This should be
-- provided as an absolute path. This may be left nil to simply fetch
-- the current base directory.
-- @return
-- The context's base directory.
--
function context.basedir(ctx, basedir)
ctx._basedir = basedir or ctx._basedir
return ctx._basedir
end
--
-- Compiles the context for better performance. The list of context terms
-- becomes locked down; any subsequent changes are ignored.
--
-- @param ctx
-- The context to compile.
--
function context.compile(ctx)
ctx._cfgset = configset.compile(ctx._cfgset, ctx.terms)
end
--
-- Check to see if a context's underlying configuration set is empty; that
-- is, it does not contain any configuration blocks.
--
-- @param ctx
-- The context to query.
-- @return
-- True if the set does not contain any blocks.
--
function context.empty(ctx)
return configset.empty(ctx._cfgset)
end
--
-- Fetch a value from underlying configuration set.
--
-- @param ctx
-- The context to query.
-- @param key
-- The property key to query.
-- @param onlylocal
-- If true, don't combine values from parent contexts.
-- @return
-- The value of the key, as determined by the configuration set. If
-- there is a corresponding Premake field, and it the field is enabled
-- for tokens, any contained tokens will be expanded.
--
function context.fetchvalue(ctx, key, onlylocal)
if not onlylocal then
local value = rawget(ctx, key)
if value ~= nil then
return value
end
end
-- The underlying configuration set will only hold registered fields.
-- If the requested key doesn't have a corresponding field, it is just
-- a regular value to be stored and fetched from the table.
local field = p.field.get(key)
if not field then
return nil
end
-- If there is a matching field, then go fetch the aggregated value
-- from my configuration set, and then cache it future lookups.
local value = configset.fetch(ctx._cfgset, field, ctx.terms, ctx, onlylocal and ctx._cfgset)
if value then
-- store the result for later lookups
rawset(ctx, key, value)
end
return value
end
context.__mt = {
__index = context.fetchvalue
}
context.__mt_uncached = {
__index = function(ctx, key)
local field = p.field.get(key)
if not field then
return nil
end
local parent = rawget(ctx, '_ctx')
return configset.fetch(parent._cfgset, field, ctx.terms, ctx, nil)
end
}
|
Better performance on fix issue #884
|
Better performance on fix issue #884
|
Lua
|
bsd-3-clause
|
dcourtois/premake-core,noresources/premake-core,dcourtois/premake-core,sleepingwit/premake-core,starkos/premake-core,premake/premake-core,noresources/premake-core,starkos/premake-core,premake/premake-core,starkos/premake-core,LORgames/premake-core,TurkeyMan/premake-core,soundsrc/premake-core,Zefiros-Software/premake-core,noresources/premake-core,sleepingwit/premake-core,premake/premake-core,Zefiros-Software/premake-core,mandersan/premake-core,premake/premake-core,mandersan/premake-core,Zefiros-Software/premake-core,dcourtois/premake-core,sleepingwit/premake-core,dcourtois/premake-core,tvandijck/premake-core,LORgames/premake-core,TurkeyMan/premake-core,soundsrc/premake-core,Zefiros-Software/premake-core,Zefiros-Software/premake-core,starkos/premake-core,TurkeyMan/premake-core,noresources/premake-core,dcourtois/premake-core,starkos/premake-core,mandersan/premake-core,premake/premake-core,noresources/premake-core,starkos/premake-core,sleepingwit/premake-core,soundsrc/premake-core,TurkeyMan/premake-core,TurkeyMan/premake-core,tvandijck/premake-core,mandersan/premake-core,LORgames/premake-core,soundsrc/premake-core,tvandijck/premake-core,LORgames/premake-core,tvandijck/premake-core,dcourtois/premake-core,mandersan/premake-core,soundsrc/premake-core,tvandijck/premake-core,premake/premake-core,premake/premake-core,LORgames/premake-core,sleepingwit/premake-core,noresources/premake-core,starkos/premake-core,noresources/premake-core,dcourtois/premake-core
|
b33269e785fbe4541c2b52700181c005066528d9
|
share/lua/playlist/cue.lua
|
share/lua/playlist/cue.lua
|
--[[
Parse CUE files
$Id$
Copyright (C) 2009 Laurent Aimar
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
-- Probe function.
function probe()
if( not string.match( string.upper( vlc.path ), ".CUE$" ) ) then
return false
end
header = vlc.peek( 2048 )
return string.match( header, "FILE.*WAVE%s*[\r\n]+" ) or
string.match( header, "FILE.*AIFF%s*[\r\n]+" ) or
string.match( header, "FILE.*MP3%s*[\r\n]+" )
end
-- Helpers
function cue_string( src )
local sub = string.match( src, "^\"(.*)\".*$" );
if( sub ) then
return sub
end
return string.match( src, "^(%S+).*$" )
end
function cue_path( src )
if( string.match( src, "^/" ) or
string.match( src, "^\\" ) or
string.match( src, "^[%l%u]:\\" ) ) then
return src
end
local path = string.gsub( vlc.strings.decode_uri(vlc.path), '\\', '/' )
local slash = string.find( string.reverse( path ), '/' )
if( path == nil ) then
return src
end
return string.sub( path, 1, -slash-1 ) .. '/' .. src
end
function cue_track( global, track )
if( track.index01 == nil ) then
return nil
end
t = {}
t.path = vlc.strings.make_uri(cue_path( track.file or global.file ))
t.title = track.title
t.album = global.title
t.artist = track.performer or global.performer
t.genre = track.genre or global.genre
t.date = track.date or global.date
t.description = global.comment
t.tracknum = track.num
t.options = { ":start-time=" .. math.floor(track.index01) }
return t
end
function cue_append( tracks, global, track )
local t = cue_track( global, track )
if( t ~= nil ) then
if( #tracks > 0 ) then
local prev = tracks[#tracks]
table.insert( prev.options, ":stop-time=" .. math.floor(track.index01) )
end
table.insert( tracks, t )
end
end
-- Parse function.
function parse()
p = {}
global_data = nil
data = {}
file = nil
while true
do
line = vlc.readline()
if not line then break end
cmd, arg = string.match( line, "^%s*(%S+)%s*(.*)$" )
if( cmd == "REM" and arg ) then
subcmd, value = string.match( arg, "^(%S+)%s*(.*)$" )
if( subcmd == "GENRE" and value ) then
data.genre = cue_string( value )
elseif( subcmd == "DATE" and value ) then
data.date = cue_string( value )
elseif( subcmd == "COMMENT" and value ) then
data.comment = cue_string( value )
end
elseif( cmd == "PERFORMER" and arg ) then
data.performer = cue_string( arg )
elseif( cmd == "TITLE" and arg ) then
data.title = cue_string( arg )
elseif( cmd == "FILE" ) then
file = cue_string( arg )
elseif( cmd == "TRACK" ) then
if( not global_data ) then
global_data = data
else
cue_append( p, global_data, data )
end
data = { file = file, num = string.match( arg, "^(%d+)" ) }
elseif( cmd == "INDEX" ) then
local idx, m, s, f = string.match( arg, "(%d+)%s+(%d+):(%d+):(%d+)" )
if( idx == "01" and m ~= nil and s ~= nil and f ~= nil ) then
data.index01 = m * 60 + s + f / 75
end
end
end
cue_append( p, global_data, data )
return p
end
|
--[[
Parse CUE files
$Id$
Copyright (C) 2009 Laurent Aimar
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
-- Probe function.
function probe()
if( not string.match( string.upper( vlc.path ), ".CUE$" ) ) then
return false
end
header = vlc.peek( 2048 )
return string.match( header, "FILE.*WAVE%s*[\r\n]+" ) or
string.match( header, "FILE.*AIFF%s*[\r\n]+" ) or
string.match( header, "FILE.*MP3%s*[\r\n]+" )
end
-- Helpers
function cue_string( src )
local sub = string.match( src, "^\"(.*)\".*$" );
if( sub ) then
return sub
end
return string.match( src, "^(%S+).*$" )
end
function cue_path( src )
if( string.match( src, "^/" ) or
string.match( src, "^\\" ) or
string.match( src, "^[%l%u]:\\" ) ) then
return vlc.strings.make_uri(src)
end
local slash = string.find( string.reverse( vlc.path ), '/' )
local prefix = vlc.access .. "://" .. string.sub( vlc.path, 1, -slash )
-- FIXME: postfix may not be encoded correctly (esp. slashes)
local postfix = vlc.strings.encode_uri_component(src)
return prefix .. postfix
end
function cue_track( global, track )
if( track.index01 == nil ) then
return nil
end
t = {}
t.path = cue_path( track.file or global.file )
t.title = track.title
t.album = global.title
t.artist = track.performer or global.performer
t.genre = track.genre or global.genre
t.date = track.date or global.date
t.description = global.comment
t.tracknum = track.num
t.options = { ":start-time=" .. math.floor(track.index01) }
return t
end
function cue_append( tracks, global, track )
local t = cue_track( global, track )
if( t ~= nil ) then
if( #tracks > 0 ) then
local prev = tracks[#tracks]
table.insert( prev.options, ":stop-time=" .. math.floor(track.index01) )
end
table.insert( tracks, t )
end
end
-- Parse function.
function parse()
p = {}
global_data = nil
data = {}
file = nil
while true
do
line = vlc.readline()
if not line then break end
cmd, arg = string.match( line, "^%s*(%S+)%s*(.*)$" )
if( cmd == "REM" and arg ) then
subcmd, value = string.match( arg, "^(%S+)%s*(.*)$" )
if( subcmd == "GENRE" and value ) then
data.genre = cue_string( value )
elseif( subcmd == "DATE" and value ) then
data.date = cue_string( value )
elseif( subcmd == "COMMENT" and value ) then
data.comment = cue_string( value )
end
elseif( cmd == "PERFORMER" and arg ) then
data.performer = cue_string( arg )
elseif( cmd == "TITLE" and arg ) then
data.title = cue_string( arg )
elseif( cmd == "FILE" ) then
file = cue_string( arg )
elseif( cmd == "TRACK" ) then
if( not global_data ) then
global_data = data
else
cue_append( p, global_data, data )
end
data = { file = file, num = string.match( arg, "^(%d+)" ) }
elseif( cmd == "INDEX" ) then
local idx, m, s, f = string.match( arg, "(%d+)%s+(%d+):(%d+):(%d+)" )
if( idx == "01" and m ~= nil and s ~= nil and f ~= nil ) then
data.index01 = m * 60 + s + f / 75
end
end
end
cue_append( p, global_data, data )
return p
end
|
cue.lua: fix file path concatenation
|
cue.lua: fix file path concatenation
Use the same approach as in the playlist module
This should fix #5398
Signed-off-by: Jean-Baptiste Kempf <7b85a41a628204b76aba4326273a3ccc74bd009a@videolan.org>
|
Lua
|
lgpl-2.1
|
shyamalschandra/vlc,vlc-mirror/vlc,vlc-mirror/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.1,xkfz007/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,vlc-mirror/vlc,xkfz007/vlc,vlc-mirror/vlc,vlc-mirror/vlc-2.1,krichter722/vlc,xkfz007/vlc,jomanmuk/vlc-2.1,shyamalschandra/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,xkfz007/vlc,jomanmuk/vlc-2.1,xkfz007/vlc,vlc-mirror/vlc,krichter722/vlc,shyamalschandra/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,shyamalschandra/vlc,jomanmuk/vlc-2.2,krichter722/vlc,xkfz007/vlc,shyamalschandra/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,krichter722/vlc,shyamalschandra/vlc,xkfz007/vlc,vlc-mirror/vlc,krichter722/vlc,shyamalschandra/vlc,vlc-mirror/vlc-2.1,krichter722/vlc,vlc-mirror/vlc-2.1,krichter722/vlc
|
94c587855025e9364d43ad14f60d25629e7f95d9
|
TripletCriterion.lua
|
TripletCriterion.lua
|
local TripletCriterion, parent = torch.class('nn.TripletCriterion', 'nn.Criterion')
function TripletCriterion:__init(samples, blocks, norm, margin)
parent.__init(self)
self.norm = norm or 2
self.alpha = margin or 0.2
self.samples = samples or 1 -- use all anchor-positive pairs for (>1)
self.blocks = blocks or 0
if self.samples > 1 then
assert(self.blocks ~= 0)
end
self.dist = torch.Tensor()
self.embeddings = torch.Tensor()
self.loss = torch.Tensor()
end
function TripletCriterion:updateOutput(input, target)
assert(input:dim() == 2, 'input should have 2 dimensions of (batch x embedding)')
assert(input:size(1) >= self.samples*self.blocks)
if input:type() == 'torch.CudaTensor' then
-- kernel call
input.nn.TripletCriterion_updateOutput(self, input, target)
else
local nb_batch = input:size(1)
local length = input:size(2)
local nb_blocks = math.floor(nb_batch/self.samples)
-- calculate distance matrix
self.dist:resize(nb_batch, nb_batch)
for i = 1, nb_batch do
for j = i, nb_batch do
if j == i then
self.dist[i][j] = 0
else
self.dist[i][j] = torch.dist(input[i], input[j], self.norm)
self.dist[j][i] = self.dist[i][j]
end
end
end
-- find pos/neg embeddings indices
-- (i) hard anchor-positive pair
if self.samples == 1 then
self.embeddings:resize(nb_batch, 3)
for i = 1, nb_batch do
local ipos = i
local vpos = 0
local ineg = i
local vneg = math.huge
for j = 1, nb_batch do
if (target[j] == target[i]) and (vpos < self.dist[i][j]) then
ipos = j
vpos = self.dist[i][j]
end
end
for j = 1, nb_batch do
if (target[j] ~= target[i]) and
(vpos < self.dist[i][j]) and
(vneg > self.dist[i][j]) then
ineg = j
vneg = self.dist[i][j]
end
end
self.embeddings[i][1] = i
self.embeddings[i][2] = ipos
self.embeddings[i][3] = ineg
end
-- (ii) all anchor-positive pairs
elseif self.samples > 1 then
-- calculate nb of all pairs
self.embeddings:resize(nb_batch*(self.samples-1), 3):zero()
-- repeat batch (samples-1) times
for i = 0, self.samples-2 do
for j = 0, nb_blocks-1 do
for k = 0, self.samples-1 do
-- pick an element in distance matrix
local row = j*self.samples + k + 1
local col = j*self.samples + i + 1
col = col < row and col or col + 1
-- find positive embedding
local ipos = col
local vpos = self.dist[row][col]
-- find negative embedding
local ineg = row
local vneg = math.huge
for l = self.samples*self.blocks+1, nb_batch do
if target[l] ~= target[row] and
self.dist[row][l] > vpos and
self.dist[row][l] < vneg then
ineg = l
vneg = self.dist[row][l]
end
end
self.embeddings[i*nb_batch + j*self.samples + k + 1][1] = row
self.embeddings[i*nb_batch + j*self.samples + k + 1][2] = ipos
self.embeddings[i*nb_batch + j*self.samples + k + 1][3] = ineg
end
end
end
end
-- compute loss
self.loss:resize(self.embeddings:size(1))
for i = 1, self.embeddings:size(1) do
-- do not penalize if negative is not found
if self.embeddings[i][1] == self.embeddings[i][3] then
self.loss[i] = 0
else
local d_ap = torch.dist(input[self.embeddings[i][1]], input[self.embeddings[i][2]], 2)
local d_an = torch.dist(input[self.embeddings[i][1]], input[self.embeddings[i][3]], 2)
self.loss[i] = math.max(0, d_ap*d_ap + self.alpha - d_an*d_an)
end
end
end
if self.samples > 1 then
self.output = self.loss:sum()/(self.blocks*self.samples*(self.samples-1))
else
self.output = self.loss:sum()/input:size(1)
end
return self.output
end
function TripletCriterion:updateGradInput(input, target)
self:updateOutput(input, target)
if input:type() == 'torch.CudaTensor' then
input.nn.TripletCriterion_updateGradInput(self, input, target)
else
local nb_pairs = self.loss:size(1)
local length = input:size(2)
self.gradInput:resize(nb_pairs, length)
for i = 1, nb_pairs do
if self.loss[i] > 0 then
self.gradInput[i] = (input[self.embeddings[i][3]] - input[self.embeddings[i][2]])*2/nb_pairs
else
self.gradInput[i] = 0
end
end
end
local nb_backwards = math.max(1, self.samples-1)
local nb_batch = input:size(1)
self.gradInput = gradInput:view(nb_backwards, nb_batch, length):sum(1):squeeze()
return self.gradInput
end
|
local TripletCriterion, parent = torch.class('nn.TripletCriterion', 'nn.Criterion')
function TripletCriterion:__init(samples, blocks, norm, margin)
parent.__init(self)
self.norm = norm or 2
self.alpha = margin or 0.2
self.samples = samples or 1 -- use all anchor-positive pairs for (>1)
self.blocks = blocks or 0
if self.samples > 1 then
assert(self.blocks ~= 0)
end
self.dist = torch.Tensor()
self.embeddings = torch.Tensor()
self.loss = torch.Tensor()
end
function TripletCriterion:updateOutput(input, target)
assert(input:dim() == 2, 'input should have 2 dimensions of (batch x embedding)')
assert(input:size(1) >= self.samples*self.blocks)
if input:type() == 'torch.CudaTensor' then
-- kernel call
input.nn.TripletCriterion_updateOutput(self, input, target)
else
local nb_batch = input:size(1)
local length = input:size(2)
--------------------------------------------------------------------------
-- BUG allert
--------------------------------------------------------------------------
local nb_blocks = math.floor(nb_batch/self.samples)
--------------------------------------------------------------------------
-- should be simply nb_batch = self.blocks
-- Otherwise we enter the trash area!
--------------------------------------------------------------------------
-- calculate distance matrix
self.dist:resize(nb_batch, nb_batch)
for i = 1, nb_batch do
for j = i, nb_batch do
if j == i then
self.dist[i][j] = 0
else
self.dist[i][j] = torch.dist(input[i], input[j], self.norm)
self.dist[j][i] = self.dist[i][j]
end
end
end
-- find pos/neg embeddings indices
-- (i) hard anchor-positive pair
if self.samples == 1 then
self.embeddings:resize(nb_batch, 3)
for i = 1, nb_batch do
local ipos = i
local vpos = 0
local ineg = i
local vneg = math.huge
for j = 1, nb_batch do
if (target[j] == target[i]) and (vpos < self.dist[i][j]) then
ipos = j
vpos = self.dist[i][j]
end
end
for j = 1, nb_batch do
if (target[j] ~= target[i]) and
(vpos < self.dist[i][j]) and
(vneg > self.dist[i][j]) then
ineg = j
vneg = self.dist[i][j]
end
end
self.embeddings[i][1] = i
self.embeddings[i][2] = ipos
self.embeddings[i][3] = ineg
end
-- (ii) all anchor-positive pairs
elseif self.samples > 1 then
-- calculate nb of all pairs
self.embeddings:resize(nb_batch*(self.samples-1), 3):zero()
-- repeat batch (samples-1) times
for i = 0, self.samples-2 do
for j = 0, nb_blocks-1 do
for k = 0, self.samples-1 do
-- pick an element in distance matrix
local row = j*self.samples + k + 1
local col = j*self.samples + i + 1
col = col < row and col or col + 1
-- find positive embedding
local ipos = col
local vpos = self.dist[row][col]
-- find negative embedding
local ineg = row
local vneg = math.huge
for l = self.samples*self.blocks+1, nb_batch do
if target[l] ~= target[row] and
self.dist[row][l] > vpos and
self.dist[row][l] < vneg then
ineg = l
vneg = self.dist[row][l]
end
end
self.embeddings[i*nb_batch + j*self.samples + k + 1][1] = row
self.embeddings[i*nb_batch + j*self.samples + k + 1][2] = ipos
self.embeddings[i*nb_batch + j*self.samples + k + 1][3] = ineg
end
end
end
end
-- compute loss
self.loss:resize(self.embeddings:size(1))
for i = 1, self.embeddings:size(1) do
-- do not penalize if negative is not found
if self.embeddings[i][1] == self.embeddings[i][3] then
self.loss[i] = 0
else
local d_ap = torch.dist(input[self.embeddings[i][1]], input[self.embeddings[i][2]], 2)
local d_an = torch.dist(input[self.embeddings[i][1]], input[self.embeddings[i][3]], 2)
self.loss[i] = math.max(0, d_ap*d_ap + self.alpha - d_an*d_an)
end
end
end
if self.samples > 1 then
self.output = self.loss:sum()/(self.blocks*self.samples*(self.samples-1))
else
self.output = self.loss:sum()/input:size(1)
end
return self.output
end
function TripletCriterion:updateGradInput(input, target)
self:updateOutput(input, target)
if input:type() == 'torch.CudaTensor' then
input.nn.TripletCriterion_updateGradInput(self, input, target)
else
local nb_pairs = self.loss:size(1)
local length = input:size(2)
self.gradInput:resize(nb_pairs, length)
for i = 1, nb_pairs do
if self.loss[i] > 0 then
self.gradInput[i] = (input[self.embeddings[i][3]] - input[self.embeddings[i][2]])*2/nb_pairs
else
self.gradInput[i] = 0
end
end
end
local nb_backwards = math.max(1, self.samples-1)
local nb_batch = input:size(1)
self.gradInput = gradInput:view(nb_backwards, nb_batch, length):sum(1):squeeze()
return self.gradInput
end
|
BUG allert
|
BUG allert
|
Lua
|
mit
|
jhjin/triplet-criterion
|
d320951b5279d1068bb588d883c16b4365226677
|
agents/monitoring/tests/agent-protocol/init.lua
|
agents/monitoring/tests/agent-protocol/init.lua
|
local fs = require('fs')
local JSON = require('json')
local AgentProtocol = require('monitoring/lib/protocol/protocol')
local AgentProtocolConnection = require('monitoring/lib/protocol/connection')
local exports = {}
exports['test_handshake_hello'] = function(test, asserts)
fs.readFile('./options.gypi', function(err, data)
if (err) then
p(err)
asserts.is_nil(err)
return
end
local data = fs.readFileSync("./agents/monitoring/tests/agent-protocol/handshake.hello.request.json")
local hello = { }
hello.data = JSON.parse(data)
hello.write = function(_, res)
hello.res = res
end
local agent = AgentProtocol:new(hello.data, hello)
agent:request(hello.data)
response = JSON.parse(hello.res)
-- TODO: asserts.object_equals in bourbon
asserts.equals(response.v, 1)
asserts.equals(response.id, 1)
asserts.equals(response.source, "endpoint")
asserts.equals(response.target, "X")
asserts.equals(response.result, nil)
test.done()
end)
end
return exports
|
local fs = require('fs')
local JSON = require('json')
local AgentProtocol = require('monitoring/lib/protocol/protocol')
local AgentProtocolConnection = require('monitoring/lib/protocol/connection')
local exports = {}
exports['test_handshake_hello'] = function(test, asserts)
fs.readFile('./agents/monitoring/tests/agent-protocol/handshake.hello.request.json', function(err, data)
if (err) then
p(err)
asserts.is_nil(err)
return
end
local hello = { }
hello.data = JSON.parse(data)
hello.write = function(_, res)
hello.res = res
end
local agent = AgentProtocol:new(hello.data, hello)
agent:request(hello.data)
response = JSON.parse(hello.res)
-- TODO: asserts.object_equals in bourbon
asserts.equals(response.v, 1)
asserts.equals(response.id, 1)
asserts.equals(response.source, "endpoint")
asserts.equals(response.target, "X")
asserts.equals(response.result, nil)
test.done()
end)
end
return exports
|
fix filename
|
fix filename
|
Lua
|
apache-2.0
|
kans/zirgo,kans/zirgo,kans/zirgo
|
6ebefb7a3bbd70a942164715f6b79c323144c97d
|
control.lua
|
control.lua
|
require 'util'
require 'gui'
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 {}
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_player_joined_game, function(event)
createPlayerMag(event.player_index)
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
if game.tick % 60 == 0 then
global.hoverboard[index].charge = global.hoverboard[index].charge - 1
end
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
|
require 'util'
require 'gui'
require "stdlib/log/logger"
LOG = Logger.new("MagneticFloor")
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 {}
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_player_joined_game, function(event)
createPlayerMag(event.player_index)
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] == nil then
createPlayerMag(v.index)
end
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
if game.tick % 60 == 0 then
global.hoverboard[index].charge = global.hoverboard[index].charge - 1
end
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 crash bug on loading an existing save
|
fix a crash bug on loading an existing save
|
Lua
|
mit
|
kiba/Factorio-MagneticFloor,kiba/Factorio-MagneticFloor
|
88766a2c0fe267cc65d84ab1bbd526cadfbc213f
|
libs/httpd/luasrc/httpd/handler/luci.lua
|
libs/httpd/luasrc/httpd/handler/luci.lua
|
--[[
HTTP server implementation for LuCI - luci handler
(c) 2008 Steven Barth <steven@midlink.org>
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.httpd.handler.luci", package.seeall)
require("luci.dispatcher")
require("luci.http")
require("luci.http.protocol.date")
local ltn12 = require("luci.ltn12")
Luci = luci.util.class(luci.httpd.module.Handler)
Response = luci.httpd.module.Response
function Luci.__init__(self, limit)
luci.httpd.module.Handler.__init__(self)
self.limit = limit or 5
self.running = {}
setmetatable(self.running, {__mode = "v"})
end
function Luci.handle_head(self, ...)
local response, sourceout = self:handle_get(...)
return response
end
function Luci.handle_post(self, ...)
return self:handle_get(...)
end
function Luci.handle_get(self, request, sourcein, sinkerr)
if self.limit and #self.running >= self.limit then
for k, v in ipairs(self.running) do
if coroutine.status(v) == "dead" then
collectgarbage()
break
end
end
if #self.running >= self.limit then
return self:failure(503, "Overload")
end
end
table.insert(self.running, coroutine.running())
local r = luci.http.Request(
request.env,
sourcein,
sinkerr
)
local res, id, data1, data2 = true, 0, nil, nil
local headers = {}
local status = 200
local active = true
local x = coroutine.create(luci.dispatcher.httpdispatch)
while not id or id < 3 do
coroutine.yield()
res, id, data1, data2 = coroutine.resume(x, r)
if not res then
status = 500
headers["Content-Type"] = "text/plain"
local err = {id}
return Response( status, headers ), function() return table.remove(err) end
end
if id == 1 then
status = data1
elseif id == 2 then
headers[data1] = data2
end
end
local function iter()
local res, id, data = coroutine.resume(x)
if not res then
return nil, id
elseif not id or not active then
return true
elseif id == 5 then
active = false
while (coroutine.resume(x)) do
end
return nil
elseif id == 4 then
return data
end
if coroutine.status(x) == "dead" then
return nil
end
end
return Response(status, headers), iter
end
|
--[[
HTTP server implementation for LuCI - luci handler
(c) 2008 Steven Barth <steven@midlink.org>
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.httpd.handler.luci", package.seeall)
require("luci.dispatcher")
require("luci.http")
require("luci.http.protocol.date")
local ltn12 = require("luci.ltn12")
Luci = luci.util.class(luci.httpd.module.Handler)
Response = luci.httpd.module.Response
function Luci.__init__(self, limit)
luci.httpd.module.Handler.__init__(self)
self.limit = limit or 5
self.running = {}
setmetatable(self.running, {__mode = "k"})
end
function Luci.handle_head(self, ...)
local response, sourceout = self:handle_get(...)
return response
end
function Luci.handle_post(self, ...)
return self:handle_get(...)
end
function Luci.handle_get(self, request, sourcein, sinkerr)
local reaped = false
local running = 0
for _, v in pairs(self.running) do
if v then running = running + 1 end
end
if self.limit and running >= self.limit then
for k, v in ipairs(self.running) do
if coroutine.status(k) == "dead" then
self.running[k] = nil
running = running - 1
reaped = true
end
end
if reaped then collectgarbage() end
if running >= self.limit then
return self:failure(503, "Overload %i/%i" % { running, self.limit } )
end
end
self.running[coroutine.running()] = true
local r = luci.http.Request(
request.env,
sourcein,
sinkerr
)
local res, id, data1, data2 = true, 0, nil, nil
local headers = {}
local status = 200
local active = true
local x = coroutine.create(luci.dispatcher.httpdispatch)
while not id or id < 3 do
coroutine.yield()
res, id, data1, data2 = coroutine.resume(x, r)
if not res then
status = 500
headers["Content-Type"] = "text/plain"
local err = {id}
return Response( status, headers ), function() return table.remove(err) end
end
if id == 1 then
status = data1
elseif id == 2 then
headers[data1] = data2
end
end
local function iter()
local res, id, data = coroutine.resume(x)
if not res then
return nil, id
elseif not id or not active then
return true
elseif id == 5 then
active = false
while (coroutine.resume(x)) do
end
return nil
elseif id == 4 then
return data
end
if coroutine.status(x) == "dead" then
return nil
end
end
return Response(status, headers), iter
end
|
* luci/libs/httpd: fix spurious Overload errors in luci-httpd
|
* luci/libs/httpd: fix spurious Overload errors in luci-httpd
git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@3586 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
zwhfly/openwrt-luci,phi-psi/luci,Flexibity/luci,phi-psi/luci,projectbismark/luci-bismark,zwhfly/openwrt-luci,yeewang/openwrt-luci,projectbismark/luci-bismark,eugenesan/openwrt-luci,gwlim/luci,ch3n2k/luci,freifunk-gluon/luci,vhpham80/luci,yeewang/openwrt-luci,dtaht/cerowrt-luci-3.3,ch3n2k/luci,stephank/luci,ThingMesh/openwrt-luci,projectbismark/luci-bismark,ch3n2k/luci,freifunk-gluon/luci,Flexibity/luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,stephank/luci,zwhfly/openwrt-luci,vhpham80/luci,ch3n2k/luci,freifunk-gluon/luci,saraedum/luci-packages-old,Canaan-Creative/luci,zwhfly/openwrt-luci,stephank/luci,freifunk-gluon/luci,jschmidlapp/luci,saraedum/luci-packages-old,gwlim/luci,projectbismark/luci-bismark,Canaan-Creative/luci,Canaan-Creative/luci,saraedum/luci-packages-old,alxhh/piratenluci,8devices/carambola2-luci,jschmidlapp/luci,alxhh/piratenluci,eugenesan/openwrt-luci,freifunk-gluon/luci,gwlim/luci,ReclaimYourPrivacy/cloak-luci,saraedum/luci-packages-old,ThingMesh/openwrt-luci,projectbismark/luci-bismark,ThingMesh/openwrt-luci,dtaht/cerowrt-luci-3.3,ch3n2k/luci,dtaht/cerowrt-luci-3.3,gwlim/luci,8devices/carambola2-luci,vhpham80/luci,8devices/carambola2-luci,gwlim/luci,phi-psi/luci,saraedum/luci-packages-old,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,dtaht/cerowrt-luci-3.3,projectbismark/luci-bismark,8devices/carambola2-luci,Canaan-Creative/luci,yeewang/openwrt-luci,jschmidlapp/luci,Canaan-Creative/luci,jschmidlapp/luci,saraedum/luci-packages-old,Flexibity/luci,stephank/luci,jschmidlapp/luci,Canaan-Creative/luci,ch3n2k/luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,yeewang/openwrt-luci,phi-psi/luci,zwhfly/openwrt-luci,8devices/carambola2-luci,yeewang/openwrt-luci,vhpham80/luci,alxhh/piratenluci,projectbismark/luci-bismark,dtaht/cerowrt-luci-3.3,yeewang/openwrt-luci,eugenesan/openwrt-luci,jschmidlapp/luci,Flexibity/luci,alxhh/piratenluci,Flexibity/luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,phi-psi/luci,saraedum/luci-packages-old,vhpham80/luci,projectbismark/luci-bismark,gwlim/luci,freifunk-gluon/luci,alxhh/piratenluci,Canaan-Creative/luci,gwlim/luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,ThingMesh/openwrt-luci,ReclaimYourPrivacy/cloak-luci,alxhh/piratenluci,eugenesan/openwrt-luci,phi-psi/luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,stephank/luci,stephank/luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,jschmidlapp/luci,eugenesan/openwrt-luci,Flexibity/luci,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,alxhh/piratenluci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,ch3n2k/luci
|
197717f9920488157eded137c390f137723eb341
|
sandbox/combateffect.lua
|
sandbox/combateffect.lua
|
local Class = require "smee.libs.middleclass"
local CombatEffect = Class "CombatEffect"
local function hasRunOutInstant(effect, roundUpdate)
return true
end
local function hasRunOutDuration(effect, roundUpdate)
if roundUpdate then
effect.duration = duration-1
if duration <= 0 then
return true
end
end
return false
end
local function hasRunOutLasting(effect, roundUpdate)
return false
end
local function effectAddToCurrentFlat(entity, effect)
local unitCmp = entity:getComponent("UnitComponent")
assert(unitCmp, "effect can only be applied on a unit with a unit component")
local targetStat = effect.params.targetStat
unitCmp.base[targetStat] = unitCmp.base[targetStat] + effect:getPower()
end
local function effectAddToCurrentPerc(entity, effect)
local unitCmp = entity:getComponent("UnitComponent")
assert(unitCmp, "effect can only be applied on a unit with a unit component")
local targetStat = effect.params.targetStat
local percToAdd = unitCmp.base[targetStat] * effect:getPower()
unitCmp.base[targetStat] = unitCmp.base[targetStat] + percToAdd
end
local function effectModifyCurrentFlat(entity, effect)
local unitCmp = entity:getComponent("UnitComponent")
assert(unitCmp, "effect can only be applied on a unit with a unit component")
local targetStat = effect.params.targetStat
unitCmp.current[targetStat] = unitCmp.current[targetStat] + effect:getPower()
end
local function effectModifyCurrentPerc(entity, effect)
local unitCmp = entity:getComponent("UnitComponent")
assert(unitCmp, "effect can only be applied on a unit with a unit component")
local targetStat = effect.params.targetStat
local percToAdd = unitCmp.current[targetStat] * effect:getPower()
unitCmp.current[targetStat] = unitCmp.current[targetStat] + percToAdd
end
local function effectModifyMaximumFlat(entity, effect)
local unitCmp = entity:getComponent("UnitComponent")
assert(unitCmp, "effect can only be applied on a unit with a unit component")
local targetStat = effect.params.targetStat
unitCmp.max[targetStat] = unitCmp.max[targetStat] + effect:getPower()
end
local function effectModifyMaximumPerc(entity, effect)
local unitCmp = entity:getComponent("UnitComponent")
assert(unitCmp, "effect can only be applied on a unit with a unit component")
local targetStat = effect.params.targetStat
local percToAdd = unitCmp.max[targetStat] * effect:getPower()
unitCmp.max[targetStat] = unitCmp.max[targetStat] + percToAdd
end
CombatEffect.Type = {
AddToCurrentFlat = "AddToCurrentFlat",
AddToCurrentPerc = "AddToCurrentPerc",
ModifyCurrentFlat = "ModifyCurrentFlat",
ModifyCurrentPerc = "ModifyCurrentPerc",
ModifyMaximumFlat = "ModifyCurrentFlat",
ModifyMaximumPerc = "ModifyMaximumPerc",
Summon = "Summon",
Stun = "Stun",
}
CombatEffect.Application = {
Instant = 1, -- Always has a duration of 0
Interval = 2, -- Over Time
Duration = 4, --
WhileAttached = 8,
}
CombatEffect.hasRunOut = {
CombatEffect.Application.Instant = hasRunOutInstant,
CombatEffect.Application.Interval = hasRunOutDuration,
CombatEffect.Application.Duration = hasRunOutDuration,
CombatEffect.Application.WhileAttached = hasRunOutLasting,
}
CombatEffect.applyEffect = {
CombatEffect.Type.AddToCurrentFlat = effectAddToCurrentFlat,
}
function CombatEffect:initialize()
self.onExpire = {}
self.onEntityDeath = {}
self.onDispel = {}
self.onRoundUpdate = {}
end
function CombatEffect:onExpire(func)
self.onExpire[#self.onExpire+1] = func
end
function CombatEffect:onEntityDeath(func)
self.onEntityDeath[#self.onEntityDeath+1] = func
end
function CombatEffect:onDispel(func)
self.onDispel[#self.onDispel] = func
end
function CombatEffect:onRoundUpdate(func)
self.onRoundUpdate[#self.onRoundUpdate+1] = func
end
function CombatEffect:getPower()
return self.params.power
end
function CombatEffect:apply(entity, roundUpdate)
for i = 1, #self.onRoundUpdate do
self.onRoundUpdate[i](entity, effect)
end
if self.application == CombatEffect.Application.Instant or
self.application == CombatEffect.Application.Interval and roundUpdate or
self.application == CombatEffect.Application.Duration or
self.application == CombatEffect.Application.WhileAttached then
CombatEffect.applyEffect[self.type](entity, self)
end
return CombatEffect.hasRunOut[self.application](self, roundUpdate)
end
|
local Class = require "smee.libs.middleclass"
local CombatEffect = Class "CombatEffect"
local function hasRunOutInstant(effect, roundUpdate)
return true
end
local function hasRunOutDuration(effect, roundUpdate)
if roundUpdate then
effect.duration = duration-1
if duration <= 0 then
return true
end
end
return false
end
local function hasRunOutLasting(effect, roundUpdate)
return false
end
local function effectAddToCurrentFlat(entity, effect)
local unitCmp = entity:getComponent("UnitComponent")
assert(unitCmp, "effect can only be applied on a unit with a unit component")
local targetStat = effect.params.targetStat
unitCmp.base[targetStat] = unitCmp.base[targetStat] + effect:getPower()
end
local function effectAddToCurrentPerc(entity, effect)
local unitCmp = entity:getComponent("UnitComponent")
assert(unitCmp, "effect can only be applied on a unit with a unit component")
local targetStat = effect.params.targetStat
local percToAdd = unitCmp.base[targetStat] * effect:getPower()
unitCmp.base[targetStat] = unitCmp.base[targetStat] + percToAdd
end
local function effectModifyCurrentFlat(entity, effect)
local unitCmp = entity:getComponent("UnitComponent")
assert(unitCmp, "effect can only be applied on a unit with a unit component")
local targetStat = effect.params.targetStat
unitCmp.current[targetStat] = unitCmp.current[targetStat] + effect:getPower()
end
local function effectModifyCurrentPerc(entity, effect)
local unitCmp = entity:getComponent("UnitComponent")
assert(unitCmp, "effect can only be applied on a unit with a unit component")
local targetStat = effect.params.targetStat
local percToAdd = unitCmp.current[targetStat] * effect:getPower()
unitCmp.current[targetStat] = unitCmp.current[targetStat] + percToAdd
end
local function effectModifyMaximumFlat(entity, effect)
local unitCmp = entity:getComponent("UnitComponent")
assert(unitCmp, "effect can only be applied on a unit with a unit component")
local targetStat = effect.params.targetStat
unitCmp.max[targetStat] = unitCmp.max[targetStat] + effect:getPower()
end
local function effectModifyMaximumPerc(entity, effect)
local unitCmp = entity:getComponent("UnitComponent")
assert(unitCmp, "effect can only be applied on a unit with a unit component")
local targetStat = effect.params.targetStat
local percToAdd = unitCmp.max[targetStat] * effect:getPower()
unitCmp.max[targetStat] = unitCmp.max[targetStat] + percToAdd
end
CombatEffect.Type = {
AddToCurrentFlat = "AddToCurrentFlat",
AddToCurrentPerc = "AddToCurrentPerc",
ModifyCurrentFlat = "ModifyCurrentFlat",
ModifyCurrentPerc = "ModifyCurrentPerc",
ModifyMaximumFlat = "ModifyMaximumFlat",
ModifyMaximumPerc = "ModifyMaximumPerc",
Summon = "Summon",
Stun = "Stun",
}
CombatEffect.Application = {
Instant = 1, -- Always has a duration of 0
Interval = 2, -- Over Time
Duration = 4, --
WhileAttached = 8,
}
CombatEffect.hasRunOut = {
[CombatEffect.Application.Instant] = hasRunOutInstant,
[CombatEffect.Application.Interval] = hasRunOutDuration,
[CombatEffect.Application.Duration] = hasRunOutDuration,
[CombatEffect.Application.WhileAttached] = hasRunOutLasting,
}
CombatEffect.applyEffect = {
[CombatEffect.Type.AddToCurrentFlat] = effectAddToCurrentFlat,
}
function CombatEffect:initialize()
self.onExpire = {}
self.onEntityDeath = {}
self.onDispel = {}
self.onRoundUpdate = {}
end
function CombatEffect:onExpire(func)
self.onExpire[#self.onExpire+1] = func
end
function CombatEffect:onEntityDeath(func)
self.onEntityDeath[#self.onEntityDeath+1] = func
end
function CombatEffect:onDispel(func)
self.onDispel[#self.onDispel] = func
end
function CombatEffect:onRoundUpdate(func)
self.onRoundUpdate[#self.onRoundUpdate+1] = func
end
function CombatEffect:getPower()
return self.params.power
end
function CombatEffect:apply(entity, roundUpdate)
for i = 1, #self.onRoundUpdate do
self.onRoundUpdate[i](entity, effect)
end
if self.application == CombatEffect.Application.Instant or
self.application == CombatEffect.Application.Interval and roundUpdate or
self.application == CombatEffect.Application.Duration or
self.application == CombatEffect.Application.WhileAttached then
CombatEffect.applyEffect[self.type](entity, self)
end
return CombatEffect.hasRunOut[self.application](self, roundUpdate)
end
return CombatEffect
|
Minor bugfixes.
|
Minor bugfixes.
|
Lua
|
mit
|
ExcelF/project-navel
|
c05998f28fd7368060c38148079a0cbb2d8ca4af
|
conditions/BuffCount.lua
|
conditions/BuffCount.lua
|
--[[--------------------------------------------------------------------
Ovale Spell Priority
Copyright (C) 2013 Johnny C. Lam
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License in the LICENSE
file accompanying this program.
--]]--------------------------------------------------------------------
local _, Ovale = ...
do
local OvaleCondition = Ovale.OvaleCondition
local OvaleState = Ovale.OvaleState
local Compare = OvaleCondition.Compare
local ParseCondition = OvaleCondition.ParseCondition
local TestValue = OvaleCondition.TestValue
local state = OvaleState.state
--- Get the total count of the given aura across all targets.
-- @name BuffCount
-- @paramsig number or boolean
-- @param id The spell ID of the aura or the name of a spell list.
-- @param operator Optional. Comparison operator: less, atMost, equal, atLeast, more.
-- @param number Optional. The number to compare against.
-- @param any Optional. Sets by whom the aura was applied. If the aura can be applied by anyone, then set any=1.
-- Defaults to any=0.
-- Valid values: 0, 1.
-- @return The total aura count.
-- @return A boolean value for the result of the comparison.
-- @see DebuffCount
local function BuffCount(condition)
local auraId, comparator, limit = condition[1], condition[2], condition[3]
local _, filter, mine = ParseCondition(condition)
local count, startChangeCount, endingChangeCount, startFirst, endingLast = state:AuraCount(auraId, filter, mine)
Ovale:Logf("BuffCount(%d) is %d, %d, %d, %d, %d", auraId, count, startChangeCount, endingChangeCount, startFirst, endingLast)
if count > 0 then
local origin = startChangeCount
local rate = -1 / (endingChangeCount - startChangeCount)
local start, ending = startFirst, endingLast
return TestValue(start, ending, count, origin, rate, comparator, limit)
end
return Compare(count, comparator, limit)
end
OvaleCondition:RegisterCondition("buffcount", false, BuffCount)
OvaleCondition:RegisterCondition("debuffcount", false, BuffCount)
end
|
--[[--------------------------------------------------------------------
Ovale Spell Priority
Copyright (C) 2013, 2014 Johnny C. Lam
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License in the LICENSE
file accompanying this program.
--]]--------------------------------------------------------------------
local _, Ovale = ...
do
local OvaleCondition = Ovale.OvaleCondition
local OvaleState = Ovale.OvaleState
local Compare = OvaleCondition.Compare
local ParseCondition = OvaleCondition.ParseCondition
local TestValue = OvaleCondition.TestValue
local state = OvaleState.state
--- Get the total count of the given aura across all targets.
-- @name BuffCount
-- @paramsig number or boolean
-- @param id The spell ID of the aura or the name of a spell list.
-- @param operator Optional. Comparison operator: less, atMost, equal, atLeast, more.
-- @param number Optional. The number to compare against.
-- @param any Optional. Sets by whom the aura was applied. If the aura can be applied by anyone, then set any=1.
-- Defaults to any=0.
-- Valid values: 0, 1.
-- @return The total aura count.
-- @return A boolean value for the result of the comparison.
-- @see DebuffCount
local function BuffCount(condition)
local auraId, comparator, limit = condition[1], condition[2], condition[3]
local _, filter, mine = ParseCondition(condition)
local count, startChangeCount, endingChangeCount, startFirst, endingLast = state:AuraCount(auraId, filter, mine)
Ovale:Logf("BuffCount(%d) is %s, %s, %s, %s, %s", auraId, count, startChangeCount, endingChangeCount, startFirst, endingLast)
if count > 0 and startChangeCount < math.huge then
local origin = startChangeCount
local rate = -1 / (endingChangeCount - startChangeCount)
local start, ending = startFirst, endingLast
return TestValue(start, ending, count, origin, rate, comparator, limit)
end
return Compare(count, comparator, limit)
end
OvaleCondition:RegisterCondition("buffcount", false, BuffCount)
OvaleCondition:RegisterCondition("debuffcount", false, BuffCount)
end
|
Fix BuffCount() when the buff never expires.
|
Fix BuffCount() when the buff never expires.
git-svn-id: b2bb544abab4b09d60f88077ac82407cb244c9c9@1309 d5049fe3-3747-40f7-a4b5-f36d6801af5f
|
Lua
|
mit
|
Xeltor/ovale,ultijlam/ovale,eXhausted/Ovale,ultijlam/ovale,eXhausted/Ovale,eXhausted/Ovale,ultijlam/ovale
|
3d9d9102ef58f080d0200e73056bf183d6039c5e
|
lib/resty/kafka/producer.lua
|
lib/resty/kafka/producer.lua
|
-- Copyright (C) Dejiang Zhu(doujiang24)
local response = require "resty.kafka.response"
local request = require "resty.kafka.request"
local broker = require "resty.kafka.broker"
local setmetatable = setmetatable
local ngx_sleep = ngx.sleep
local ngx_log = ngx.log
local DEBUG = ngx.DEBUG
local ERR = ngx.ERR
local debug = ngx.config.debug
local ok, new_tab = pcall(require, "table.new")
if not ok then
new_tab = function (narr, nrec) return {} end
end
local _M = new_tab(0, 3)
_M._VERSION = '0.01'
local mt = { __index = _M }
function _M.new(self, broker_list, opts)
local opts = opts or {}
return setmetatable({
correlation_id = 1,
broker_list = broker_list,
topic_partitions = {},
broker_nodes = {},
client_id = opts.client_id or "client",
request_timeout = opts.request_timeout or 2000,
retry_interval = opts.retry_interval or 100, -- ms
max_retry = opts.max_retry or 3,
required_acks = (opts.required_acks and opts.required_acks > 0)
and opts.required_acks or 1,
}, mt)
end
local function correlation_id(self)
local id = (self.correlation_id + 1) % 1073741824 -- 2^30
self.correlation_id = id
return id
end
local function produce_encode(self, topic, messages, index)
local timeout = self.request_timeout
local client_id = self.client_id
local id = correlation_id(self)
local req = request:new(request.ProduceRequest, id, client_id)
--XX hard code for requiredAcks
req:int16(self.required_acks)
req:int32(timeout)
-- XX hard code for topic num
req:int32(1)
req:string(topic)
-- XX hard code for partition, modified in func: send
req:int32(1)
req:int32(0)
-- MessageSetSize and MessageSet
req:message_set(messages, index)
return req
end
local function produce_decode(resp)
local ret = {}
local topic_num = resp:int32()
for i = 1, topic_num do
local topic = resp:string()
local partition_num = resp:int32()
ret[topic] = {}
for j = 1, partition_num do
local partition = resp:int32()
ret[topic][partition] = {
errcode = resp:int16(),
offset = resp:int64(),
}
end
end
return ret
end
local function metadata_encode(self, topic)
local client_id = self.client_id
local id = correlation_id(self)
local req = request:new(request.MetadataRequest, id, client_id)
-- topic num is 1
req:int32(1)
req:string(topic)
return req
end
local function metadata_decode(resp)
local bk_num = resp:int32()
local brokers = new_tab(0, bk_num)
for i = 1, bk_num do
local nodeid = resp:int32();
brokers[nodeid] = {
host = resp:string(),
port = resp:int32(),
}
end
local topic_num = resp:int32()
local topics = new_tab(0, topic_num)
for i = 1, topic_num do
local tp_errcode = resp:int16()
local topic = resp:string()
local partition_num = resp:int32()
local topic_info = {
partitions = new_tab(partition_num, 0),
errcode = tp_errcode,
num = partition_num,
}
for j = 1, partition_num do
local partition_info = new_tab(0, 5)
partition_info.errcode = resp:int16()
partition_info.id = resp:int32()
partition_info.leader = resp:int32()
local repl_num = resp:int32()
partition_info.replicas = new_tab(repl_num, 0)
for m = 1, repl_num do
partition_info.replicas[m] = resp:int32()
end
local isr_num = resp:int32()
partition_info.isr = new_tab(isr_num, 0)
for m = 1, isr_num do
partition_info.isr[m] = resp:int32()
end
topic_info.partitions[j] = partition_info
end
topics[topic] = topic_info
end
return { brokers = brokers, topics = topics }
end
local function _fetch_metadata(self, topic)
local broker_list = self.broker_list
for i = 1, #broker_list do
local host, port = broker_list[i].host, broker_list[i].port
local bk, err = broker:new(host, port)
if not bk then
ngx_log(ERR, "broker connect failed, err:", err, host, port)
else
local req = metadata_encode(self, topic)
local resp, err = bk:send_receive(req)
bk:keepalive()
if not resp then
ngx_log(ERR, "broker metadata failed, err:", err, host, port)
else
local meta = metadata_decode(resp)
local info = meta.topics[topic]
self.topic_partitions[topic] = info
self.broker_nodes = meta.brokers
return info
end
end
end
ngx_log(ERR, "refresh metadata failed")
return nil, "refresh metadata failed"
end
local function fetch_metadata(self, topic)
local partitions = self.topic_partitions[topic]
if partitions then
return partitions
end
return _fetch_metadata(self, topic)
end
local function choose_partition(self, topic)
local partitions, err = fetch_metadata(self, topic)
if not partitions then
return nil, err
end
local partition = partitions.partitions[self.correlation_id % partitions.num + 1]
local id = partition.id
local leader = partition.leader
local config = self.broker_nodes[leader]
local bk, err = broker:new(config.host, config.port)
if not bk then
return nil, err
end
return bk, id
end
function _M.send(self, topic, messages, index)
local req = produce_encode(self, topic, messages, index)
local retry, resp, err = 0
while retry <= self.max_retry do
local broker, partition = choose_partition(self, topic)
if broker then
req:partition(partition)
resp, err = broker:send_receive(req)
broker:keepalive()
if resp then
return produce_decode(resp)
end
end
if debug then
ngx_log(DEBUG, "retry to send messages to kafka server: ", err)
end
ngx_sleep(self.retry_interval / 1000)
fetch_metadata(self, topic, true)
retry = retry + 1
end
return nil, err
end
return _M
|
-- Copyright (C) Dejiang Zhu(doujiang24)
local response = require "resty.kafka.response"
local request = require "resty.kafka.request"
local broker = require "resty.kafka.broker"
local setmetatable = setmetatable
local ngx_sleep = ngx.sleep
local ngx_log = ngx.log
local DEBUG = ngx.DEBUG
local ERR = ngx.ERR
local debug = ngx.config.debug
local ok, new_tab = pcall(require, "table.new")
if not ok then
new_tab = function (narr, nrec) return {} end
end
local _M = new_tab(0, 3)
_M._VERSION = '0.01'
local mt = { __index = _M }
function _M.new(self, broker_list, opts)
local opts = opts or {}
return setmetatable({
correlation_id = 1,
broker_list = broker_list,
topic_partitions = {},
broker_nodes = {},
client_id = opts.client_id or "client",
request_timeout = opts.request_timeout or 2000,
retry_interval = opts.retry_interval or 100, -- ms
max_retry = opts.max_retry or 3,
required_acks = (opts.required_acks and opts.required_acks > 0)
and opts.required_acks or 1,
}, mt)
end
local function correlation_id(self)
local id = (self.correlation_id + 1) % 1073741824 -- 2^30
self.correlation_id = id
return id
end
local function produce_encode(self, topic, messages, index)
local timeout = self.request_timeout
local client_id = self.client_id
local id = correlation_id(self)
local req = request:new(request.ProduceRequest, id, client_id)
--XX hard code for requiredAcks
req:int16(self.required_acks)
req:int32(timeout)
-- XX hard code for topic num
req:int32(1)
req:string(topic)
-- XX hard code for partition, modified in func: send
req:int32(1)
req:int32(0)
-- MessageSetSize and MessageSet
req:message_set(messages, index)
return req
end
local function produce_decode(resp)
local ret = {}
local topic_num = resp:int32()
for i = 1, topic_num do
local topic = resp:string()
local partition_num = resp:int32()
ret[topic] = {}
for j = 1, partition_num do
local partition = resp:int32()
ret[topic][partition] = {
errcode = resp:int16(),
offset = resp:int64(),
}
end
end
return ret
end
local function metadata_encode(self, topic)
local client_id = self.client_id
local id = correlation_id(self)
local req = request:new(request.MetadataRequest, id, client_id)
-- topic num is 1
req:int32(1)
req:string(topic)
return req
end
local function metadata_decode(resp)
local bk_num = resp:int32()
local brokers = new_tab(0, bk_num)
for i = 1, bk_num do
local nodeid = resp:int32();
brokers[nodeid] = {
host = resp:string(),
port = resp:int32(),
}
end
local topic_num = resp:int32()
local topics = new_tab(0, topic_num)
for i = 1, topic_num do
local tp_errcode = resp:int16()
local topic = resp:string()
local partition_num = resp:int32()
local topic_info = {
partitions = new_tab(partition_num, 0),
errcode = tp_errcode,
num = partition_num,
}
for j = 1, partition_num do
local partition_info = new_tab(0, 5)
partition_info.errcode = resp:int16()
partition_info.id = resp:int32()
partition_info.leader = resp:int32()
local repl_num = resp:int32()
partition_info.replicas = new_tab(repl_num, 0)
for m = 1, repl_num do
partition_info.replicas[m] = resp:int32()
end
local isr_num = resp:int32()
partition_info.isr = new_tab(isr_num, 0)
for m = 1, isr_num do
partition_info.isr[m] = resp:int32()
end
topic_info.partitions[j] = partition_info
end
topics[topic] = topic_info
end
return { brokers = brokers, topics = topics }
end
local function _fetch_metadata(self, topic)
local broker_list = self.broker_list
for i = 1, #broker_list do
local host, port = broker_list[i].host, broker_list[i].port
local bk, err = broker:new(host, port)
if not bk then
ngx_log(ERR, "broker connect failed, err:", err, host, port)
else
local req = metadata_encode(self, topic)
local resp, err = bk:send_receive(req)
bk:keepalive()
if not resp then
ngx_log(ERR, "broker metadata failed, err:", err, host, port)
else
local meta = metadata_decode(resp)
local info = meta.topics[topic]
if info.num and info.num > 0 then
self.topic_partitions[topic] = info
self.broker_nodes = meta.brokers
return info
else
ngx_log(ERR, "not found topic: " .. topic)
return nil, "not found topic: " .. topic
end
end
end
end
ngx_log(ERR, "refresh metadata failed")
return nil, "refresh metadata failed"
end
local function fetch_metadata(self, topic)
local partitions = self.topic_partitions[topic]
if partitions then
return partitions
end
return _fetch_metadata(self, topic)
end
local function choose_partition(self, topic)
local partitions, err = fetch_metadata(self, topic)
if not partitions then
return nil, err
end
local partition = partitions.partitions[self.correlation_id % partitions.num + 1]
local id = partition.id
local leader = partition.leader
local config = self.broker_nodes[leader]
local bk, err = broker:new(config.host, config.port)
if not bk then
return nil, err
end
return bk, id
end
function _M.send(self, topic, messages, index)
local req = produce_encode(self, topic, messages, index)
local retry, resp, err = 0
while retry <= self.max_retry do
local broker, partition = choose_partition(self, topic)
if broker then
req:partition(partition)
resp, err = broker:send_receive(req)
broker:keepalive()
if resp then
return produce_decode(resp)
end
else
err = partition
end
if debug then
ngx_log(DEBUG, "retry to send messages to kafka server: ", err)
end
ngx_sleep(self.retry_interval / 1000)
_fetch_metadata(self, topic)
retry = retry + 1
end
return nil, err
end
return _M
|
bugfix: force refresh metadata when retry send; topic may be not existed
|
bugfix: force refresh metadata when retry send; topic may be not existed
|
Lua
|
bsd-3-clause
|
wzb56/lua-resty-kafka,doujiang24/lua-resty-kafka,wangfakang/lua-resty-kafka
|
2f55b44e1e3fd6f53ca43b9127d9dd5c49cc1880
|
xmake/scripts/tools/gcc.lua
|
xmake/scripts/tools/gcc.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 gcc.lua
--
-- load modules
local utils = require("base/utils")
local table = require("base/table")
local string = require("base/string")
local config = require("base/config")
local platform = require("platform/platform")
-- define module: gcc
local gcc = gcc or {}
-- check the given flag
function gcc._check(self, flag)
-- this flag has been checked?
self._CHECK = self._CHECK or {}
if self._CHECK[flag] then
return self._CHECK[flag]
end
-- check it
local result = flag
if 0 ~= os.execute(string.format("%s %s -S -o %s -xc %s > %s 2>&1", self._NAME, flag, xmake._NULDEV, xmake._NULDEV, xmake._NULDEV)) then
result = ""
end
-- trace
utils.verbose("checking for the compiler flags %s ... %s", flag, utils.ifelse(#result ~= 0, "ok", "no"))
-- save it
self._CHECK[flag] = result
-- ok?
return result
end
-- the init function
function gcc.init(self, name)
-- save name
self._NAME = name or "gcc"
-- init mxflags
self.mxflags = { "-fmessage-length=0"
, "-pipe"
, "-fpascal-strings"
, "\"-DIBOutlet=__attribute__((iboutlet))\""
, "\"-DIBOutletCollection(ClassName)=__attribute__((iboutletcollection(ClassName)))\""
, "\"-DIBAction=void)__attribute__((ibaction)\""}
-- init shflags
if name:find("clang") then
self.shflags = { "-dynamiclib", "-fPIC" }
else
self.shflags = { "-shared -Wl,-soname", "-fPIC" }
end
-- suppress warning for the clang
local isclang = false
if name:find("clang") then
isclang = true
self.cxflags = self.cxflags or {}
self.mxflags = self.mxflags or {}
self.asflags = self.asflags or {}
table.join2(self.cxflags, "-Qunused-arguments")
table.join2(self.mxflags, "-Qunused-arguments")
table.join2(self.asflags, "-Qunused-arguments")
end
-- init flags map
self.mapflags =
{
-- vectorexts
["-mmmx"] = self._check
, ["-msse$"] = self._check
, ["-msse2"] = self._check
, ["-msse3"] = self._check
, ["-mssse3"] = self._check
, ["-mavx$"] = self._check
, ["-mavx2"] = self._check
, ["-mfpu=.*"] = self._check
-- warnings
, ["-W1"] = "-Wall"
, ["-W2"] = "-Wall"
, ["-W3"] = "-Wall"
-- strip
, ["-s"] = utils.ifelse(isclang, "-S", "-s")
, ["-S"] = "-S"
-- others
, ["-ftrapv"] = self._check
, ["-fsanitize=address"] = self._check
}
end
-- make the compile command
function gcc.command_compile(self, srcfile, objfile, flags, logfile)
-- redirect
local redirect = ""
if logfile then redirect = string.format(" > %s 2>&1", logfile) end
-- make it
return string.format("%s -c %s -o %s %s%s", self._NAME, flags, objfile, srcfile, redirect)
end
-- make the link command
function gcc.command_link(self, objfiles, targetfile, flags, logfile)
-- redirect
local redirect = ""
if logfile then redirect = string.format(" > %s 2>&1", logfile) end
-- make it
return string.format("%s -o %s %s %s%s", self._NAME, targetfile, objfiles, flags, redirect)
end
-- make the define flag
function gcc.flag_define(self, define)
-- make it
return "-D" .. define:gsub("\"", "\\\"")
end
-- make the undefine flag
function gcc.flag_undefine(self, undefine)
-- make it
return "-U" .. undefine
end
-- make the includedir flag
function gcc.flag_includedir(self, includedir)
-- make it
return "-I" .. includedir
end
-- make the link flag
function gcc.flag_link(self, link)
-- make it
return "-l" .. link
end
-- make the linkdir flag
function gcc.flag_linkdir(self, linkdir)
-- make it
return "-L" .. linkdir
end
-- the main function
function gcc.main(self, cmd)
-- execute it
local ok = os.execute(cmd)
-- ok?
return utils.ifelse(ok == 0, true, false)
end
-- return module: gcc
return gcc
|
--!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 gcc.lua
--
-- load modules
local utils = require("base/utils")
local table = require("base/table")
local string = require("base/string")
local config = require("base/config")
local platform = require("platform/platform")
-- define module: gcc
local gcc = gcc or {}
-- check the given flag
function gcc._check(self, flag)
-- this flag has been checked?
self._CHECK = self._CHECK or {}
if self._CHECK[flag] then
return self._CHECK[flag]
end
-- check it
local result = flag
if 0 ~= os.execute(string.format("%s %s -S -o %s -xc %s > %s 2>&1", self._NAME, flag, xmake._NULDEV, xmake._NULDEV, xmake._NULDEV)) then
result = ""
end
-- trace
utils.verbose("checking for the compiler flags %s ... %s", flag, utils.ifelse(#result ~= 0, "ok", "no"))
-- save it
self._CHECK[flag] = result
-- ok?
return result
end
-- the init function
function gcc.init(self, name)
-- save name
self._NAME = name or "gcc"
-- init mxflags
self.mxflags = { "-fmessage-length=0"
, "-pipe"
, "-fpascal-strings"
, "\"-DIBOutlet=__attribute__((iboutlet))\""
, "\"-DIBOutletCollection(ClassName)=__attribute__((iboutletcollection(ClassName)))\""
, "\"-DIBAction=void)__attribute__((ibaction)\""}
-- init shflags
if name:find("clang") then
self.shflags = { "-dynamiclib", "-fPIC" }
else
self.shflags = { "-shared -Wl,-soname", "-fPIC" }
end
-- suppress warning for the clang
local isclang = false
if name:find("clang") then
isclang = true
self.cxflags = self.cxflags or {}
self.mxflags = self.mxflags or {}
self.asflags = self.asflags or {}
table.join2(self.cxflags, "-Qunused-arguments")
table.join2(self.mxflags, "-Qunused-arguments")
table.join2(self.asflags, "-Qunused-arguments")
end
-- init flags map
self.mapflags =
{
-- vectorexts
["-mmmx"] = self._check
, ["-msse$"] = self._check
, ["-msse2"] = self._check
, ["-msse3"] = self._check
, ["-mssse3"] = self._check
, ["-mavx$"] = self._check
, ["-mavx2"] = self._check
, ["-mfpu=.*"] = self._check
-- warnings
, ["-W1"] = "-Wall"
, ["-W2"] = "-Wall"
, ["-W3"] = "-Wall"
-- strip
, ["-s"] = utils.ifelse(isclang, "-Wl,-S", "-s")
, ["-S"] = utils.ifelse(isclang, "-Wl,-S", "-S")
-- others
, ["-ftrapv"] = self._check
, ["-fsanitize=address"] = self._check
}
end
-- make the compile command
function gcc.command_compile(self, srcfile, objfile, flags, logfile)
-- redirect
local redirect = ""
if logfile then redirect = string.format(" > %s 2>&1", logfile) end
-- make it
return string.format("%s -c %s -o %s %s%s", self._NAME, flags, objfile, srcfile, redirect)
end
-- make the link command
function gcc.command_link(self, objfiles, targetfile, flags, logfile)
-- redirect
local redirect = ""
if logfile then redirect = string.format(" > %s 2>&1", logfile) end
-- make it
return string.format("%s -o %s %s %s%s", self._NAME, targetfile, objfiles, flags, redirect)
end
-- make the define flag
function gcc.flag_define(self, define)
-- make it
return "-D" .. define:gsub("\"", "\\\"")
end
-- make the undefine flag
function gcc.flag_undefine(self, undefine)
-- make it
return "-U" .. undefine
end
-- make the includedir flag
function gcc.flag_includedir(self, includedir)
-- make it
return "-I" .. includedir
end
-- make the link flag
function gcc.flag_link(self, link)
-- make it
return "-l" .. link
end
-- make the linkdir flag
function gcc.flag_linkdir(self, linkdir)
-- make it
return "-L" .. linkdir
end
-- the main function
function gcc.main(self, cmd)
-- execute it
local ok = os.execute(cmd)
-- ok?
return utils.ifelse(ok == 0, true, false)
end
-- return module: gcc
return gcc
|
fix strip flags for clang
|
fix strip flags for clang
|
Lua
|
apache-2.0
|
waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake
|
81785193201eb38dbfe1b9d38f57ffab771810fa
|
nvim/lua/raindev/plugins.lua
|
nvim/lua/raindev/plugins.lua
|
local ensure_packer = function()
local fn = vim.fn
local install_path = fn.stdpath('data')..'/site/pack/packer/start/packer.nvim'
if fn.empty(fn.glob(install_path)) > 0 then
fn.system({'git', 'clone', '--depth', '1', 'https://github.com/wbthomason/packer.nvim', install_path})
vim.cmd [[packadd packer.nvim]]
return true
end
return false
end
local packer_bootstrap = ensure_packer()
return require('packer').startup(function(use)
use {'wbthomason/packer.nvim', config = function()
compile_path = vim.fn.stdpath("data") .. '/plugin/packer_compiled.lua'
end}
use 'cocopon/iceberg.vim'
use 'tpope/vim-surround'
use 'tpope/vim-sleuth'
use 'andymass/vim-matchup'
use 'rust-lang/rust.vim'
use 'udalov/kotlin-vim'
use 'keith/swift.vim'
use {'nvim-treesitter/nvim-treesitter', config = function()
require('nvim-treesitter.configs').setup({
-- If TS highlights are not enabled at all, or disabled via `disable` prop, highlighting will fallback to default Vim syntax highlighting
highlight = {
enable = true,
disable = {'org'}, -- Remove this to use TS highlighter for some of the highlights (Experimental)
additional_vim_regex_highlighting = {'org'}, -- Required since TS highlighter doesn't support all syntax features (conceal)
},
ensure_installed = {'org'},
})
end }
use {'nvim-orgmode/orgmode', config = function()
local orgmode = require('orgmode')
orgmode.setup_ts_grammar()
orgmode.setup({
org_agenda_files = {'~/org/*'},
org_default_notes_file = '~/org/inbox.org',
})
end }
-- Automatically set up your configuration after cloning packer.nvim
-- Put this at the end after all plugins
if packer_bootstrap then
require('packer').sync()
end
end)
|
local ensure_packer = function()
local fn = vim.fn
local install_path = fn.stdpath('data')..'/site/pack/packer/start/packer.nvim'
if fn.empty(fn.glob(install_path)) > 0 then
fn.system({'git', 'clone', '--depth', '1', 'https://github.com/wbthomason/packer.nvim', install_path})
vim.cmd [[packadd packer.nvim]]
return true
end
return false
end
local packer_bootstrap = ensure_packer()
local plugins = function(use)
use 'wbthomason/packer.nvim'
use 'cocopon/iceberg.vim'
use 'tpope/vim-surround'
use 'tpope/vim-sleuth'
use 'andymass/vim-matchup'
use 'rust-lang/rust.vim'
use 'udalov/kotlin-vim'
use 'keith/swift.vim'
use {'nvim-treesitter/nvim-treesitter', config = function()
require('nvim-treesitter.configs').setup({
-- If TS highlights are not enabled at all, or disabled via `disable` prop, highlighting will fallback to default Vim syntax highlighting
highlight = {
enable = true,
disable = {'org'}, -- Remove this to use TS highlighter for some of the highlights (Experimental)
additional_vim_regex_highlighting = {'org'}, -- Required since TS highlighter doesn't support all syntax features (conceal)
},
ensure_installed = {'org'},
})
end }
use {'nvim-orgmode/orgmode', config = function()
local orgmode = require('orgmode')
orgmode.setup_ts_grammar()
orgmode.setup({
org_agenda_files = {'~/org/*'},
org_default_notes_file = '~/org/inbox.org',
})
end }
-- Automatically set up your configuration after cloning packer.nvim
-- Put this at the end after all plugins
if packer_bootstrap then
require('packer').sync()
end
end
return require('packer').startup({plugins, config = {
compile_path = vim.fn.stdpath("data") .. '/site/plugin/packer_compiled.lua'
}})
|
Fix failed attempt to relocate packer compile_path
|
Fix failed attempt to relocate packer compile_path
The configuration has to be supplied early on with the plugin's startup
call, rather than when adding packer to the list of plugins managed by
itself. Also move packer_compiled.lua to ~/.local/share/nvim/site/plugin
as ~/.local/share/nvim itself is not a part of runtimepath.
|
Lua
|
mit
|
raindev/dotfiles
|
88ffeb165b0fc47868d291af6f17f3cbe63eb138
|
lexers/html.lua
|
lexers/html.lua
|
-- Copyright 2006-2017 Mitchell mitchell.att.foicica.com. See LICENSE.
-- HTML LPeg lexer.
local l = require('lexer')
local token, word_match = l.token, l.word_match
local P, R, S, V = lpeg.P, lpeg.R, lpeg.S, lpeg.V
local M = {_NAME = 'html'}
case_insensitive_tags = true
-- Whitespace.
local ws = token(l.WHITESPACE, l.space^1)
-- Comments.
local comment = token(l.COMMENT, '<!--' * (l.any - '-->')^0 * P('-->')^-1)
-- Strings.
local sq_str = l.delimited_range("'")
local dq_str = l.delimited_range('"')
local string = #S('\'"') * l.last_char_includes('=') *
token(l.STRING, sq_str + dq_str)
-- TODO: performance is terrible on large files.
local in_tag = P(function(input, index)
local before = input:sub(1, index - 1)
local s, e = before:find('<[^>]-$'), before:find('>[^<]-$')
if s and e then return s > e and index or nil end
if s then return index end
return input:find('^[^<]->', index) and index or nil
end)
-- Numbers.
local number = #l.digit * l.last_char_includes('=') *
token(l.NUMBER, l.digit^1 * P('%')^-1) --* in_tag
-- Elements.
local known_element = token('element', '<' * P('/')^-1 * word_match({
'a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base',
'bdi', 'bdo', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption',
'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd',
'decorator', 'del', 'details', 'dfn', 'div', 'dl', 'dt', 'element', 'em',
'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2',
'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hr', 'html', 'i', 'iframe', 'img',
'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main',
'map', 'mark', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript',
'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'pre',
'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section',
'select', 'shadow', 'small', 'source', 'spacer', 'spacer', 'span', 'strong',
'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template',
'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul',
'var', 'video', 'wbr'
}, nil, case_insensitive_tags))
local unknown_element = token('unknown_element', '<' * P('/')^-1 * l.word)
local element = known_element + unknown_element
-- Attributes.
local known_attribute = token('attribute', word_match({
'accept', 'accept-charset', 'accesskey', 'action', 'align', 'alt', 'async',
'autocomplete', 'autofocus', 'autoplay', 'bgcolor', 'border', 'buffered',
'challenge', 'charset', 'checked', 'cite', 'class', 'code', 'codebase',
'color', 'cols', 'colspan', 'content', 'contenteditable', 'contextmenu',
'controls', 'coords', 'data', 'data-', 'datetime', 'default', 'defer', 'dir',
'dirname', 'disabled', 'download', 'draggable', 'dropzone', 'enctype', 'for',
'form', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang',
'http-equiv', 'icon', 'id', 'ismap', 'itemprop', 'keytype', 'kind', 'label',
'lang', 'language', 'list', 'loop', 'low', 'manifest', 'max', 'maxlength',
'media', 'method', 'min', 'multiple', 'name', 'novalidate', 'open', 'optimum',
'pattern', 'ping', 'placeholder', 'poster', 'preload', 'pubdate',
'radiogroup', 'readonly', 'rel', 'required', 'reversed', 'role', 'rows',
'rowspan', 'sandbox', 'spellcheck', 'scope', 'scoped', 'seamless', 'selected',
'shape', 'size', 'sizes', 'span', 'src', 'srcdoc', 'srclang', 'start',
'step', 'style', 'summary', 'tabindex', 'target', 'title', 'type', 'usemap',
'value', 'width', 'wrap'
}, '-', case_insensitive_tags) + ((P('data-') + 'aria-') * (l.alnum + '-')^1))
local unknown_attribute = token('unknown_attribute', l.word)
local attribute = (known_attribute + unknown_attribute) * #(l.space^0 * '=')
-- Closing tags.
local tag_close = token('element', P('/')^-1 * '>')
-- Equals.
local equals = token(l.OPERATOR, '=') --* in_tag
-- Entities.
local entity = token('entity', '&' * (l.any - l.space - ';')^1 * ';')
-- Doctype.
local doctype = token('doctype', '<!' *
word_match({'doctype'}, nil, case_insensitive_tags) *
(l.any - '>')^1 * '>')
M._rules = {
{'whitespace', ws},
{'comment', comment},
{'doctype', doctype},
{'element', element},
{'tag_close', tag_close},
{'attribute', attribute},
-- {'equals', equals},
{'string', string},
{'number', number},
{'entity', entity},
}
M._tokenstyles = {
element = l.STYLE_KEYWORD,
unknown_element = l.STYLE_KEYWORD..',italics',
attribute = l.STYLE_TYPE,
unknown_attribute = l.STYLE_TYPE..',italics',
entity = l.STYLE_OPERATOR,
doctype = l.STYLE_COMMENT
}
M._foldsymbols = {
_patterns = {'</?', '/>', '<!%-%-', '%-%->'},
element = {['<'] = 1, ['/>'] = -1, ['</'] = -1},
unknown_element = {['<'] = 1, ['/>'] = -1, ['</'] = -1},
[l.COMMENT] = {['<!--'] = 1, ['-->'] = -1}
}
-- Tags that start embedded languages.
M.embed_start_tag = element *
(ws^1 * attribute * ws^0 * equals * ws^0 * string)^0 *
ws^0 * tag_close
M.embed_end_tag = element * tag_close
-- Embedded CSS.
local css = l.load('css')
local style_element = word_match({'style'}, nil, case_insensitive_tags)
local css_start_rule = #(P('<') * style_element *
('>' + P(function(input, index)
if input:find('^%s+type%s*=%s*(["\'])text/css%1', index) then
return index
end
end))) * M.embed_start_tag -- <style type="text/css">
local css_end_rule = #('</' * style_element * ws^0 * '>') *
M.embed_end_tag -- </style>
l.embed_lexer(M, css, css_start_rule, css_end_rule)
-- Embedded JavaScript.
local js = l.load('javascript')
local script_element = word_match({'script'}, nil, case_insensitive_tags)
local js_start_rule = #(P('<') * script_element *
('>' + P(function(input, index)
if input:find('^%s+type%s*=%s*(["\'])text/javascript%1', index) then
return index
end
end))) * M.embed_start_tag -- <script type="text/javascript">
local js_end_rule = #('</' * script_element * ws^0 * '>') *
M.embed_end_tag -- </script>
l.embed_lexer(M, js, js_start_rule, js_end_rule)
-- Embedded CoffeeScript.
local cs = l.load('coffeescript')
local script_element = word_match({'script'}, nil, case_insensitive_tags)
local cs_start_rule = #(P('<') * script_element * P(function(input, index)
if input:find('^[^>]+type%s*=%s*(["\'])text/coffeescript%1', index) then
return index
end
end)) * M.embed_start_tag -- <script type="text/coffeescript">
local cs_end_rule = #('</' * script_element * ws^0 * '>') *
M.embed_end_tag -- </script>
l.embed_lexer(M, cs, cs_start_rule, cs_end_rule)
return M
|
-- Copyright 2006-2017 Mitchell mitchell.att.foicica.com. See LICENSE.
-- HTML LPeg lexer.
local l = require('lexer')
local token, word_match = l.token, l.word_match
local P, R, S, V = lpeg.P, lpeg.R, lpeg.S, lpeg.V
local M = {_NAME = 'html'}
case_insensitive_tags = true
-- Whitespace.
local ws = token(l.WHITESPACE, l.space^1)
-- Comments.
local comment = token(l.COMMENT, '<!--' * (l.any - '-->')^0 * P('-->')^-1)
-- Strings.
local sq_str = l.delimited_range("'")
local dq_str = l.delimited_range('"')
local string = #S('\'"') * l.last_char_includes('=') *
token(l.STRING, sq_str + dq_str)
-- TODO: performance is terrible on large files.
local in_tag = P(function(input, index)
local before = input:sub(1, index - 1)
local s, e = before:find('<[^>]-$'), before:find('>[^<]-$')
if s and e then return s > e and index or nil end
if s then return index end
return input:find('^[^<]->', index) and index or nil
end)
-- Numbers.
local number = #l.digit * l.last_char_includes('=') *
token(l.NUMBER, l.digit^1 * P('%')^-1) --* in_tag
-- Elements.
local known_element = token('element', '<' * P('/')^-1 * word_match({
'a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base',
'bdi', 'bdo', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption',
'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd',
'decorator', 'del', 'details', 'dfn', 'div', 'dl', 'dt', 'element', 'em',
'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2',
'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hr', 'html', 'i', 'iframe', 'img',
'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main',
'map', 'mark', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript',
'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'pre',
'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section',
'select', 'shadow', 'small', 'source', 'spacer', 'spacer', 'span', 'strong',
'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template',
'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul',
'var', 'video', 'wbr'
}, nil, case_insensitive_tags))
local unknown_element = token('unknown_element', '<' * P('/')^-1 * l.word)
local element = known_element + unknown_element
-- Attributes.
local known_attribute = token('attribute', word_match({
'accept', 'accept-charset', 'accesskey', 'action', 'align', 'alt', 'async',
'autocomplete', 'autofocus', 'autoplay', 'bgcolor', 'border', 'buffered',
'challenge', 'charset', 'checked', 'cite', 'class', 'code', 'codebase',
'color', 'cols', 'colspan', 'content', 'contenteditable', 'contextmenu',
'controls', 'coords', 'data', 'data-', 'datetime', 'default', 'defer', 'dir',
'dirname', 'disabled', 'download', 'draggable', 'dropzone', 'enctype', 'for',
'form', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang',
'http-equiv', 'icon', 'id', 'ismap', 'itemprop', 'keytype', 'kind', 'label',
'lang', 'language', 'list', 'loop', 'low', 'manifest', 'max', 'maxlength',
'media', 'method', 'min', 'multiple', 'name', 'novalidate', 'open', 'optimum',
'pattern', 'ping', 'placeholder', 'poster', 'preload', 'pubdate',
'radiogroup', 'readonly', 'rel', 'required', 'reversed', 'role', 'rows',
'rowspan', 'sandbox', 'spellcheck', 'scope', 'scoped', 'seamless', 'selected',
'shape', 'size', 'sizes', 'span', 'src', 'srcdoc', 'srclang', 'start',
'step', 'style', 'summary', 'tabindex', 'target', 'title', 'type', 'usemap',
'value', 'width', 'wrap'
}, '-', case_insensitive_tags) + ((P('data-') + 'aria-') * (l.alnum + '-')^1))
local unknown_attribute = token('unknown_attribute', l.word)
local attribute = (known_attribute + unknown_attribute) * #(l.space^0 * '=')
-- Closing tags.
local tag_close = token('element', P('/')^-1 * '>')
-- Equals.
local equals = token(l.OPERATOR, '=') --* in_tag
-- Entities.
local entity = token('entity', '&' * (l.any - l.space - ';')^1 * ';')
-- Doctype.
local doctype = token('doctype', '<!' *
word_match({'doctype'}, nil, case_insensitive_tags) *
(l.any - '>')^1 * '>')
M._rules = {
{'whitespace', ws},
{'comment', comment},
{'doctype', doctype},
{'element', element},
{'tag_close', tag_close},
{'attribute', attribute},
-- {'equals', equals},
{'string', string},
{'number', number},
{'entity', entity},
}
M._tokenstyles = {
element = l.STYLE_KEYWORD,
unknown_element = l.STYLE_KEYWORD..',italics',
attribute = l.STYLE_TYPE,
unknown_attribute = l.STYLE_TYPE..',italics',
entity = l.STYLE_OPERATOR,
doctype = l.STYLE_COMMENT
}
M._foldsymbols = {
_patterns = {'</?', '/>', '<!%-%-', '%-%->'},
element = {['<'] = 1, ['/>'] = -1, ['</'] = -1},
unknown_element = {['<'] = 1, ['/>'] = -1, ['</'] = -1},
[l.COMMENT] = {['<!--'] = 1, ['-->'] = -1}
}
-- Tags that start embedded languages.
M.embed_start_tag = element *
(ws^1 * attribute * ws^0 * equals * ws^0 * string)^0 *
ws^0 * tag_close
M.embed_end_tag = element * tag_close
-- Embedded CSS.
local css = l.load('css')
local style_element = word_match({'style'}, nil, case_insensitive_tags)
local css_start_rule = #(P('<') * style_element *
('>' + P(function(input, index)
if input:find('^%s+type%s*=%s*(["\'])text/css%1', index) then
return index
end
end))) * M.embed_start_tag -- <style type="text/css">
local css_end_rule = #('</' * style_element * ws^0 * '>') *
M.embed_end_tag -- </style>
l.embed_lexer(M, css, css_start_rule, css_end_rule)
-- Embedded JavaScript.
local js = l.load('javascript')
local script_element = word_match({'script'}, nil, case_insensitive_tags)
local js_start_rule = #(P('<') * script_element *
('>' + P(function(input, index)
if input:find('^%s+type%s*=%s*(["\'])text/javascript%1', index) then
return index
end
end))) * M.embed_start_tag -- <script type="text/javascript">
local js_end_rule = #('</' * script_element * ws^0 * '>') *
M.embed_end_tag -- </script>
local js_line_comment = '//' * (l.nonnewline_esc - js_end_rule)^0
local js_block_comment = '/*' * (l.any - '*/' - js_end_rule)^0 * P('*/')^-1
js._RULES['comment'] = token(l.COMMENT, js_line_comment + js_block_comment)
l.embed_lexer(M, js, js_start_rule, js_end_rule)
-- Embedded CoffeeScript.
local cs = l.load('coffeescript')
local script_element = word_match({'script'}, nil, case_insensitive_tags)
local cs_start_rule = #(P('<') * script_element * P(function(input, index)
if input:find('^[^>]+type%s*=%s*(["\'])text/coffeescript%1', index) then
return index
end
end)) * M.embed_start_tag -- <script type="text/coffeescript">
local cs_end_rule = #('</' * script_element * ws^0 * '>') *
M.embed_end_tag -- </script>
l.embed_lexer(M, cs, cs_start_rule, cs_end_rule)
return M
|
Fixed detection of "</script>" even within a JavaScript comment; lexers/html.lua
|
Fixed detection of "</script>" even within a JavaScript comment; lexers/html.lua
|
Lua
|
mit
|
rgieseke/scintillua
|
a8b2a09bc5214a28271825d120ef6bbbee1db83c
|
onmt/modules/RIndexLinear.lua
|
onmt/modules/RIndexLinear.lua
|
local RIndexLinear, parent = torch.class('onmt.RIndexLinear', 'nn.Linear')
--[[
MaskLinear is a Linear layer that allows the user to a set a collection of
output row indices. When the row indices are set, the layer will behave like a
Linear layer that output only these rows - all the other ones will be zero.
This is particularily interesting for softmax reduction.
]]--
function RIndexLinear:__init(inputSize, outputSize, bias)
parent.__init(self, inputSize, outputSize, bias)
self.restrictedOutput = torch.Tensor(1)
end
function RIndexLinear:setOutputIndices(rowIndices)
if self.rowIndices ~= rowIndices then
self.rowIndices = rowIndices
if rowIndices then
self.restrictedWeight = self.weight:index(1, rowIndices)
self.restrictedBias = self.bias:index(1, rowIndices)
end
end
end
local function updateAddBuffer(self, input)
local nbatch = input:size(1)
self.addBuffer = self.addBuffer or input.new()
if self.addBuffer:nElement() ~= nbatch then
self.addBuffer:resize(nbatch):fill(1)
end
end
function RIndexLinear:updateOutput(input)
if self.train or not self.rowIndices then
return parent.updateOutput(self, input)
end
if input:dim() == 1 then
self.output:resize(self.weight:size(1)):zero()
self.restrictedOutput:resize(self.restrictedWeight:size(1))
if self.bias then
self.restrictedOutput:copy(self.restrictedBias)
else
self.restrictedOutput:zero()
end
self.restrictedOutput:addmv(1, self.restrictedWeight, input)
self.output:indexCopy(1, self.rowIndices, self.restrictedOutput)
elseif input:dim() == 2 then
local nbatch = input:size(1)
local nElement = self.output:nElement()
self.output:resize(nbatch, self.weight:size(1)):zero()
updateAddBuffer(self, input)
self.restrictedOutput:resize(nbatch, self.restrictedWeight:size(1)):zero()
self.restrictedOutput:addmm(0, self.restrictedOutput, 1, input, self.restrictedWeight:t())
if self.bias then
self.restrictedOutput:addr(1, self.addBuffer, self.restrictedBias)
end
self.output:indexCopy(2, self.rowIndices, self.restrictedOutput)
else
error('input must be vector or matrix')
end
return self.output
end
function RIndexLinear:updateGradInput(input, gradOutput)
if self.gradInput then
if self.rowIndices then
local nElement = self.gradInput:nElement()
self.gradInput:resizeAs(input)
if self.gradInput:nElement() ~= nElement then
self.gradInput:zero()
end
if input:dim() == 1 then
local restrictedGradOutput = gradOutput:index(1, self.rowIndices)
self.gradInput:addmv(0, 1, self.restrictedWeight:t(), restrictedGradOutput)
elseif input:dim() == 2 then
local restrictedGradOutput = gradOutput:index(2, self.rowIndices)
self.gradInput:addmm(0, 1, restrictedGradOutput, self.restrictedWeight)
end
return self.gradInput
else
return parent.updateGradInput(self, input, gradOutput)
end
end
end
|
local RIndexLinear, parent = torch.class('onmt.RIndexLinear', 'nn.Linear')
--[[
MaskLinear is a Linear layer that allows the user to a set a collection of
output row indices. When the row indices are set, the layer will behave like a
Linear layer that output only these rows - all the other ones will be zero.
This is particularily interesting for softmax reduction.
]]--
function RIndexLinear:__init(inputSize, outputSize, bias)
parent.__init(self, inputSize, outputSize, bias)
self.restrictedOutput = torch.Tensor(1)
end
function RIndexLinear:setOutputIndices(rowIndices)
if self.rowIndices ~= rowIndices then
self.rowIndices = rowIndices
if rowIndices then
self.restrictedWeight = self.weight:index(1, rowIndices)
self.restrictedBias = self.bias:index(1, rowIndices)
end
end
end
local function updateAddBuffer(self, input)
local nbatch = input:size(1)
self.addBuffer = self.addBuffer or input.new()
if self.addBuffer:nElement() ~= nbatch then
self.addBuffer:resize(nbatch):fill(1)
end
end
function RIndexLinear:updateOutput(input)
if self.train or not self.rowIndices then
return parent.updateOutput(self, input)
end
if input:dim() == 1 then
self.output:resize(self.weight:size(1)):zero()
self.restrictedOutput:resize(self.restrictedWeight:size(1))
if self.bias then
self.restrictedOutput:copy(self.restrictedBias)
else
self.restrictedOutput:zero()
end
self.restrictedOutput:addmv(1, self.restrictedWeight, input)
self.output:indexCopy(1, self.rowIndices, self.restrictedOutput)
elseif input:dim() == 2 then
local nbatch = input:size(1)
self.output:resize(nbatch, self.weight:size(1)):zero()
updateAddBuffer(self, input)
self.restrictedOutput:resize(nbatch, self.restrictedWeight:size(1)):zero()
self.restrictedOutput:addmm(0, self.restrictedOutput, 1, input, self.restrictedWeight:t())
if self.bias then
self.restrictedOutput:addr(1, self.addBuffer, self.restrictedBias)
end
self.output:indexCopy(2, self.rowIndices, self.restrictedOutput)
else
error('input must be vector or matrix')
end
return self.output
end
function RIndexLinear:updateGradInput(input, gradOutput)
if self.gradInput then
if self.rowIndices then
local nElement = self.gradInput:nElement()
self.gradInput:resizeAs(input)
if self.gradInput:nElement() ~= nElement then
self.gradInput:zero()
end
if input:dim() == 1 then
local restrictedGradOutput = gradOutput:index(1, self.rowIndices)
self.gradInput:addmv(0, 1, self.restrictedWeight:t(), restrictedGradOutput)
elseif input:dim() == 2 then
local restrictedGradOutput = gradOutput:index(2, self.rowIndices)
self.gradInput:addmm(0, 1, restrictedGradOutput, self.restrictedWeight)
end
return self.gradInput
else
return parent.updateGradInput(self, input, gradOutput)
end
end
end
|
fix warning
|
fix warning
|
Lua
|
mit
|
jsenellart/OpenNMT,da03/OpenNMT,OpenNMT/OpenNMT,jsenellart-systran/OpenNMT,OpenNMT/OpenNMT,monsieurzhang/OpenNMT,jungikim/OpenNMT,monsieurzhang/OpenNMT,da03/OpenNMT,jungikim/OpenNMT,jsenellart/OpenNMT,jsenellart/OpenNMT,jsenellart-systran/OpenNMT,jungikim/OpenNMT,da03/OpenNMT,OpenNMT/OpenNMT,jsenellart-systran/OpenNMT,monsieurzhang/OpenNMT
|
4278069b2cc2b08260012cb93b76aaaa6c2284a7
|
defaut/Paladin.lua
|
defaut/Paladin.lua
|
local code = [[
Define(avenging_wrath 31884)
SpellInfo(avenging_wrath duration=20 cd=180 )
SpellAddBuff(avenging_wrath avenging_wrath=1)
Define(blessing_of_kings 20217)
SpellInfo(blessing_of_kings duration=3600 )
SpellAddBuff(blessing_of_kings blessing_of_kings=1)
Define(blessing_of_might 19740)
SpellInfo(blessing_of_might duration=3600 )
SpellAddBuff(blessing_of_might blessing_of_might=1)
Define(crusader_strike 35395)
SpellInfo(crusader_strike holy=-1 cd=4.5 )
Define(divine_storm 53385)
SpellInfo(divine_storm holy=3 )
Define(execution_sentence 114916)
SpellInfo(execution_sentence duration=10 tick=1 )
SpellAddTargetDebuff(execution_sentence execution_sentence=1)
Define(exorcism 879)
SpellInfo(exorcism holy=-1 cd=15 )
Define(glyph_of_double_jeopardy 121027)
SpellInfo(glyph_of_double_jeopardy duration=10 )
SpellAddBuff(glyph_of_double_jeopardy glyph_of_double_jeopardy=1)
Define(guardian_of_ancient_kings 86659)
SpellInfo(guardian_of_ancient_kings duration=12 cd=180 )
SpellAddBuff(guardian_of_ancient_kings guardian_of_ancient_kings=1)
Define(hammer_of_the_righteous 53595)
SpellInfo(hammer_of_the_righteous holy=-1 cd=4.5 )
Define(hammer_of_wrath 24275)
SpellInfo(hammer_of_wrath holy=-0 cd=6 )
Define(inquisition 84963)
SpellInfo(inquisition duration=10 holy=1 )
SpellAddBuff(inquisition inquisition=1)
Define(judgment 20271)
SpellInfo(judgment cd=6 )
Define(rebuke 96231)
SpellInfo(rebuke duration=4 cd=15 )
Define(seal_of_righteousness 20154)
SpellAddBuff(seal_of_righteousness seal_of_righteousness=1)
Define(seal_of_truth 31801)
SpellAddBuff(seal_of_truth seal_of_truth=1)
Define(templars_verdict 85256)
SpellInfo(templars_verdict holy=3 )
AddCheckBox(showwait L(showwait) default)
AddIcon mastery=3 help=main
{
if not InCombat()
{
if not BuffPresent(str_agi_int any=1) Spell(blessing_of_kings)
if not BuffPresent(mastery any=1) and not BuffPresent(str_agi_int any=1) Spell(blessing_of_might)
unless Stance(1) Spell(seal_of_truth)
}
if {BuffExpires(inquisition) or BuffRemains(inquisition) <=2 } and {HolyPower() >=3 or target.DeadIn() <HolyPower() *10 } Spell(inquisition)
if HolyPower() ==5 Spell(templars_verdict)
Spell(hammer_of_wrath usable=1)
if SpellCooldown(hammer_of_wrath) >0 and SpellCooldown(hammer_of_wrath) <=0.2 if CheckBoxOn(showwait) Texture(Spell_nature_timestop)
Spell(exorcism)
if SpellCooldown(exorcism) >0 and SpellCooldown(exorcism) <=0.2 if CheckBoxOn(showwait) Texture(Spell_nature_timestop)
if not {ArmorSetParts(T15 more 4) } and {target.HealthPercent() <=20 or BuffPresent(avenging_wrath) } Spell(judgment)
Spell(crusader_strike)
if SpellCooldown(crusader_strike) >0 and SpellCooldown(crusader_strike) <=0.2 if CheckBoxOn(showwait) Texture(Spell_nature_timestop)
Spell(judgment)
if BuffRemains(inquisition) >4 Spell(templars_verdict)
}
AddIcon mastery=3 help=offgcd
{
if target.IsInterruptible() Spell(rebuke)
if BuffPresent(inquisition) Spell(execution_sentence)
}
AddIcon mastery=3 help=aoe
{
if not InCombat()
{
unless Stance(2) Spell(seal_of_righteousness)
}
if {HolyPower() ==5 } Spell(divine_storm)
Spell(hammer_of_the_righteous)
if BuffPresent(glyph_of_double_jeopardy) focus.Spell(judgment)
if BuffRemains(inquisition) >4 Spell(divine_storm)
}
AddIcon mastery=3 help=cd
{
if BuffPresent(inquisition) Spell(avenging_wrath)
if BuffPresent(avenging_wrath) Spell(guardian_of_ancient_kings)
if BuffPresent(inquisition) { Item(Trinket0Slot usable=1) Item(Trinket1Slot usable=1) }
}
]]
OvaleScripts:RegisterScript("PALADIN", "Ovale", "[5.2] Ovale: Retribution", code)
|
local code = [[
Define(avenging_wrath 31884)
SpellInfo(avenging_wrath duration=20 cd=180 )
SpellAddBuff(avenging_wrath avenging_wrath=1)
Define(blessing_of_kings 20217)
SpellInfo(blessing_of_kings duration=3600 )
SpellAddBuff(blessing_of_kings blessing_of_kings=1)
Define(blessing_of_might 19740)
SpellInfo(blessing_of_might duration=3600 )
SpellAddBuff(blessing_of_might blessing_of_might=1)
Define(crusader_strike 35395)
SpellInfo(crusader_strike holy=-1 cd=4.5 )
Define(divine_storm 53385)
SpellInfo(divine_storm holy=3 )
Define(execution_sentence 114916)
SpellInfo(execution_sentence duration=10 tick=1 )
SpellAddTargetDebuff(execution_sentence execution_sentence=1)
Define(exorcism 879)
SpellInfo(exorcism holy=-1 cd=15 )
Define(exorcism_glyphed 122032)
SpellInfo(exorcism_glyphed holy=-1 cd=15)
Define(glyph_of_double_jeopardy 121027)
SpellInfo(glyph_of_double_jeopardy duration=10 )
SpellAddBuff(glyph_of_double_jeopardy glyph_of_double_jeopardy=1)
Define(guardian_of_ancient_kings 86659)
SpellInfo(guardian_of_ancient_kings duration=12 cd=180 )
SpellAddBuff(guardian_of_ancient_kings guardian_of_ancient_kings=1)
Define(hammer_of_the_righteous 53595)
SpellInfo(hammer_of_the_righteous holy=-1 cd=4.5 )
Define(hammer_of_wrath 24275)
SpellInfo(hammer_of_wrath holy=-0 cd=6 )
Define(inquisition 84963)
SpellInfo(inquisition duration=10 holy=1 )
SpellAddBuff(inquisition inquisition=1)
Define(judgment 20271)
SpellInfo(judgment cd=6 )
Define(rebuke 96231)
SpellInfo(rebuke duration=4 cd=15 )
Define(seal_of_righteousness 20154)
SpellAddBuff(seal_of_righteousness seal_of_righteousness=1)
Define(seal_of_truth 31801)
SpellAddBuff(seal_of_truth seal_of_truth=1)
Define(templars_verdict 85256)
SpellInfo(templars_verdict holy=3 )
Define(glyph_of_mass_exorcism 122028)
AddCheckBox(showwait L(showwait) default)
AddIcon mastery=3 help=main
{
if not InCombat()
{
if not BuffPresent(str_agi_int any=1) Spell(blessing_of_kings)
if not BuffPresent(mastery any=1) and not BuffPresent(str_agi_int any=1) Spell(blessing_of_might)
unless Stance(1) Spell(seal_of_truth)
}
if {BuffExpires(inquisition) or BuffRemains(inquisition) <=2 } and {HolyPower() >=3 or target.DeadIn() <HolyPower() *10 } Spell(inquisition)
if HolyPower() ==5 Spell(templars_verdict)
Spell(hammer_of_wrath usable=1)
if SpellCooldown(hammer_of_wrath) >0 and SpellCooldown(hammer_of_wrath) <=0.2 if CheckBoxOn(showwait) Texture(Spell_nature_timestop)
if Glyph(glyph_of_mass_exorcism no)
{
Spell(exorcism)
if SpellCooldown(exorcism) >0 and SpellCooldown(exorcism) <=0.2 if CheckBoxOn(showwait) Texture(Spell_nature_timestop)
}
if Glyph(glyph_of_mass_exorcism)
{
Spell(exorcism_glyphed)
if SpellCooldown(exorcism_glyphed) >0 and SpellCooldown(exorcism_glyphed) <=0.2 if CheckBoxOn(showwait) Texture(Spell_nature_timestop)
}
if not {ArmorSetParts(T15 more 4) } and {target.HealthPercent() <=20 or BuffPresent(avenging_wrath) } Spell(judgment)
Spell(crusader_strike)
if SpellCooldown(crusader_strike) >0 and SpellCooldown(crusader_strike) <=0.2 if CheckBoxOn(showwait) Texture(Spell_nature_timestop)
Spell(judgment)
if BuffRemains(inquisition) >4 Spell(templars_verdict)
}
AddIcon mastery=3 help=offgcd
{
if target.IsInterruptible() Spell(rebuke)
if BuffPresent(inquisition) Spell(execution_sentence)
}
AddIcon mastery=3 help=aoe
{
if not InCombat()
{
unless Stance(2) Spell(seal_of_righteousness)
}
if {HolyPower() ==5 } Spell(divine_storm)
Spell(hammer_of_the_righteous)
if BuffPresent(glyph_of_double_jeopardy) focus.Spell(judgment)
if BuffRemains(inquisition) >4 Spell(divine_storm)
}
AddIcon mastery=3 help=cd
{
if BuffPresent(inquisition) Spell(avenging_wrath)
if BuffPresent(avenging_wrath) Spell(guardian_of_ancient_kings)
if BuffPresent(inquisition) { Item(Trinket0Slot usable=1) Item(Trinket1Slot usable=1) }
}
]]
OvaleScripts:RegisterScript("PALADIN", "Ovale", "[5.2] Ovale: Retribution", code)
|
Paladin: Apply fixes after SimulationCraft import.
|
Paladin: Apply fixes after SimulationCraft import.
When using the Glyph of Mass Exorcism, the spell ID of Exorcism changes
from 879 to 122032.
git-svn-id: b2bb544abab4b09d60f88077ac82407cb244c9c9@766 d5049fe3-3747-40f7-a4b5-f36d6801af5f
|
Lua
|
mit
|
ultijlam/ovale,Xeltor/ovale,eXhausted/Ovale,ultijlam/ovale,eXhausted/Ovale,eXhausted/Ovale,ultijlam/ovale
|
62095a5df7c4b7a778fa4a84d18b6867c7944ecb
|
ui/Tree.lua
|
ui/Tree.lua
|
--
-- Default method implementations for the tree as a whole. --
--
local Tree = {
w = 0; h = 0;
_focused = 1;
colour = { 255, 255, 255 };
}
Tree.__index = Tree
-- Focus the given node.
function Tree:set_focus(index)
self:focused().focused = false
self._focused = (index-1) % #self.nodes + 1
self:focused().focused = true
end
function Tree:focused()
assert(#self.nodes >= self._focused, "focus %d exceeds internal node list %d", self._focused, #self.nodes)
return self.nodes[self._focused]
end
-- Select the previous visible node.
function Tree:focus_prev()
self:set_focus(self._focused - 1)
self:scroll_to_focused()
end
-- Select the next visible node.
function Tree:focus_next()
self:set_focus(self._focused + 1)
self:scroll_to_focused()
end
function Tree:scroll_up()
self:set_focus(self._focused - (self.h/2):ceil())
self:scroll_to_focused()
end
function Tree:scroll_down()
self:set_focus(self._focused + (self.h/2):ceil())
self:scroll_to_focused()
end
-- Scroll so that the focused element is in the center of the screen, or close to.
function Tree:scroll_to_focused()
if not self.max_h then return end
self.scroll = math.bound(0, self._focused - self.h/2, self.max_h - self.h):floor()
end
-- Return a DFS iterator over all nodes in the tree; yields (node,depth) for
-- each node. The top level has depth 0, not 1.
function Tree:walk(include_collapsed)
local function dfs_walk(tree, depth)
for _,subtree in ipairs(tree) do
coroutine.yield(subtree, depth)
if subtree.expanded or include_collapsed then
dfs_walk(subtree, depth+1)
end
end
end
return coroutine.wrap(dfs_walk),self,0
end
-- Render the entire tree by drawing a titled box, then calling :render on each
-- visible node with appropriate coordinates passed in.
function Tree:render()
tty.colour(unpack(self.colour))
tty.pushwin(self.view)
ui.box(nil, self.name)
local scroll = self.scroll or 0
if self.scroll then
-- render scrollbar
ui.clear({ x=self.view.w-1; y=1; w=1; h=self.view.h-2 }, '┊')
tty.put(self.view.w-1, 1, '┻')
tty.put(self.view.w-1, self.view.h-2, '┳')
local sb_distance = (self.scroll/(self.max_h - self.h)*(self.h - 2 - self.scroll_height)):floor()
ui.clear({ x=self.view.w-1; y=2+sb_distance; w=1; h=self.scroll_height }, '▓') --█
end
for y=1,self.h:min(#self.nodes) do
self.nodes[y+scroll]:render(1, y)
end
tty.popwin()
end
-- Set up the next/prev links
function Tree:refresh()
self.nodes = {}
for node in self:walk() do
table.insert(self.nodes, node)
node._index = #self.nodes
if node.focused then
self._focused = node._index
end
end
end
-- Call an event handler appropriate for a given input event.
-- The search works thus:
-- If there is no self.bindings entry for the event, it is ignored entirely.
-- If the entry is a function, it's called and passed self.
-- If the entry is a string, and the focused node has a method with that name,
-- the method is called.
-- If it's a string and the tree has a method with that name, it's called.
-- In all of the previous three cases, if the function called returns a value,
-- that value is returned.
-- If none of the above cases apply, an error is raised.
function Tree:call_handler(key)
key = self.bindings[key]
if not key then return end
local node = self:focused()
if type(key) == 'function' then
return key(self)
elseif type(node[key]) == 'function' then
return node[key](node)
elseif type(self[key]) == 'function' then
return self[key](self)
else
return error("no handler in tree for %s -- wanted function, got %s (node) and %s (tree)" % {
name, type(node[key]), type(self[key])})
end
end
-- The user has declined to choose a node at all.
function Tree:cancel()
return false
end
-- Run the tree UI loop. Repeatedly render the tree, get input, and call the
-- handler, if any, for that input event. As soon as a handler returns a non-
-- nil value, break out of the loop and return that value.
function Tree:run()
local R
repeat
self:render()
R = self:call_handler(ui.readkey())
until R ~= nil
ui.clear(self.view)
return R
end
return function(t)
return setmetatable(t, Tree)
end
|
--
-- Default method implementations for the tree as a whole. --
--
local Tree = {
w = 0; h = 0;
_focused = 1;
colour = { 255, 255, 255 };
}
Tree.__index = Tree
-- Focus the given node.
function Tree:set_focus(index)
self:focused().focused = false
self._focused = (index-1) % #self.nodes + 1
self:focused().focused = true
end
function Tree:focused()
assert(#self.nodes >= self._focused, "focus %d exceeds internal node list %d", self._focused, #self.nodes)
return self.nodes[self._focused]
end
-- Select the previous visible node.
function Tree:focus_prev()
self:set_focus(self._focused - 1)
self:scroll_to_focused()
end
-- Select the next visible node.
function Tree:focus_next()
self:set_focus(self._focused + 1)
self:scroll_to_focused()
end
function Tree:scroll_up()
self:set_focus(self._focused - (self.h/2):ceil())
self:scroll_to_focused()
end
function Tree:scroll_down()
self:set_focus(self._focused + (self.h/2):ceil())
self:scroll_to_focused()
end
-- Scroll so that the focused element is in the center of the screen, or close to.
function Tree:scroll_to_focused()
if not self.max_h then return end
self.scroll = math.bound(0, self._focused - self.h/2, self.max_h - self.h):floor()
end
-- Return a DFS iterator over all nodes in the tree; yields (node,depth) for
-- each node. The top level has depth 0, not 1.
function Tree:walk(include_collapsed)
local function dfs_walk(tree, depth)
for _,subtree in ipairs(tree) do
coroutine.yield(subtree, depth)
if subtree.expanded or include_collapsed then
dfs_walk(subtree, depth+1)
end
end
end
return coroutine.wrap(dfs_walk),self,0
end
-- Render the entire tree by drawing a titled box, then calling :render on each
-- visible node with appropriate coordinates passed in.
function Tree:render()
tty.colour(unpack(self.colour))
tty.pushwin(self.view)
ui.box(nil, self.name)
local scroll = self.scroll or 0
if self.scroll then
-- render scrollbar
ui.clear({ x=self.view.w-1; y=1; w=1; h=self.view.h-2 }, '┊')
tty.put(self.view.w-1, 1, '┻')
tty.put(self.view.w-1, self.view.h-2, '┳')
local sb_distance = (self.scroll/(self.max_h - self.h)*(self.h - 2 - self.scroll_height)):floor()
ui.clear({ x=self.view.w-1; y=2+sb_distance; w=1; h=self.scroll_height }, '▓') --█
end
for y=1,self.h:min(#self.nodes) do
self.nodes[y+scroll]:render(1, y)
end
tty.popwin()
end
-- Build the list of displayable nodes. Called when the list changes due to nodes
-- being expanded or collapsed.
function Tree:refresh()
self.nodes = {}
for node in self:walk() do
table.insert(self.nodes, node)
node._index = #self.nodes
if node.focused then
self._focused = node._index
end
end
end
-- Call an event handler appropriate for a given input event.
-- The search works thus:
-- If there is no self.bindings entry for the event, it is ignored entirely.
-- If the entry is a function, it's called and passed self.
-- If the entry is a string, and the focused node has a method with that name,
-- the method is called.
-- If it's a string and the tree has a method with that name, it's called.
-- In all of the previous three cases, if the function called returns a value,
-- that value is returned.
-- If none of the above cases apply, an error is raised.
function Tree:call_handler(key)
key = self.bindings[key]
if not key then return end
local node = self:focused()
if type(key) == 'function' then
return key(self)
elseif type(node[key]) == 'function' then
return node[key](node)
elseif type(self[key]) == 'function' then
return self[key](self)
else
return error("no handler in tree for %s -- wanted function, got %s (node) and %s (tree)" % {
name, type(node[key]), type(self[key])})
end
end
-- The user has declined to choose a node at all.
function Tree:cancel()
return false
end
-- Run the tree UI loop. Repeatedly render the tree, get input, and call the
-- handler, if any, for that input event. As soon as a handler returns a non-
-- nil value, break out of the loop and return that value.
function Tree:run()
local R
repeat
self:render()
R = self:call_handler(ui.readkey())
until R ~= nil
ui.clear(self.view)
return R
end
return function(t)
return setmetatable(t, Tree)
end
|
Fix comment in Tree.lua
|
Fix comment in Tree.lua
|
Lua
|
mit
|
ToxicFrog/ttymor
|
b7a7fb0500f7b6038e7a4444d0d67ea92a5f8ce7
|
classes/book.lua
|
classes/book.lua
|
local plain = SILE.require("classes/plain");
local book = plain { id = "book" };
book:loadPackage("masters")
book:defineMaster({ id = "right", firstContentFrame = "content", frames = {
content = { left = "8.3%pw", right = "86%pw", top = "11.6%ph", bottom = "top(footnotes)" },
folio = { left = "left(content)", right = "right(content)", top = "bottom(footnotes)+3%ph", bottom = "bottom(footnotes)+5%ph" },
runningHead = { left = "left(content)", right = "right(content)", top = "top(content)-8%ph", bottom = "top(content)-3%ph" },
footnotes = { left="left(content)", right = "right(content)", height = "0", bottom="83.3%ph"}
}})
book:loadPackage("twoside", { oddPageMaster = "right", evenPageMaster = "left" });
book:mirrorMaster("right", "left")
book:loadPackage("tableofcontents")
if not(SILE.scratch.headers) then SILE.scratch.headers = {}; end
book.pageTemplate = SILE.scratch.masters["right"]
book.init = function(self)
book:loadPackage("footnotes", { insertInto = "footnotes", stealFrom = {"content"} } )
return plain.init(self)
end
book.newPage = function(self)
book:switchPage()
book:newPageInfo()
return plain.newPage(self)
end
book.finish = function ()
book:writeToc()
return plain.finish(book)
end
book.endPage = function(self)
book:moveTocNodes()
if (book:oddPage() and SILE.scratch.headers.right) then
SILE.typesetNaturally(SILE.getFrame("runningHead"), function()
SILE.settings.set("current.parindent", SILE.nodefactory.zeroGlue)
SILE.settings.set("document.lskip", SILE.nodefactory.zeroGlue)
SILE.settings.set("document.rskip", SILE.nodefactory.zeroGlue)
-- SILE.settings.set("typesetter.parfillskip", SILE.nodefactory.zeroGlue)
SILE.process(SILE.scratch.headers.right)
SILE.call("par")
end)
elseif (not(book:oddPage()) and SILE.scratch.headers.left) then
SILE.typesetNaturally(SILE.getFrame("runningHead"), function()
SILE.settings.set("current.parindent", SILE.nodefactory.zeroGlue)
SILE.settings.set("document.lskip", SILE.nodefactory.zeroGlue)
SILE.settings.set("document.rskip", SILE.nodefactory.zeroGlue)
-- SILE.settings.set("typesetter.parfillskip", SILE.nodefactory.zeroGlue)
SILE.process(SILE.scratch.headers.left)
SILE.call("par")
end)
end
return plain.endPage(book);
end;
SILE.registerCommand("left-running-head", function(options, content)
local closure = SILE.settings.wrap()
SILE.scratch.headers.left = function () closure(content) end
end, "Text to appear on the top of the left page");
SILE.registerCommand("right-running-head", function(options, content)
local closure = SILE.settings.wrap()
SILE.scratch.headers.right = function () closure(content) end
end, "Text to appear on the top of the right page");
SILE.registerCommand("book:sectioning", function (options, content)
local content = SU.subContent(content)
local level = SU.required(options, "level", "book:sectioning")
SILE.call("increment-multilevel-counter", {id = "sectioning", level = options.level})
SILE.call("tocentry", {level = options.level}, content)
local lang = SILE.settings.get("document.language")
if options.numbering == nil or options.numbering == "yes" then
if options.prenumber then
if SILE.Commands[options.prenumber..":"..lang] then options.prenumber = options.prenumber..":"..lang end
SILE.call(options.prenumber)
end
SILE.call("show-multilevel-counter", {id="sectioning"})
if options.postnumber then
if SILE.Commands[options.postnumber..":"..lang] then options.postnumber = options.postnumber..":"..lang end
SILE.call(options.postnumber)
end
end
end)
book.registerCommands = function()
plain.registerCommands()
SILE.doTexlike([[%
\define[command=book:chapter:pre]{}%
\define[command=book:chapter:post]{\par}%
\define[command=book:section:post]{ }%
\define[command=book:subsection:post]{ }%
\define[command=book:left-running-head-font]{\font[size=9pt]}%
\define[command=book:right-running-head-font]{\font[size=9pt,style=italic]}%
]])
end
SILE.registerCommand("chapter", function (options, content)
SILE.call("open-double-page")
SILE.call("noindent")
SILE.scratch.headers.right = nil
SILE.call("set-counter", {id = "footnote", value = 1})
SILE.call("book:chapterfont", {}, function()
SILE.call("book:sectioning", {
numbering = options.numbering,
level = 1,
prenumber = "book:chapter:pre",
postnumber = "book:chapter:post"
}, content)
end)
SILE.Commands["book:chapterfont"]({}, content);
SILE.Commands["left-running-head"]({}, function()
SILE.settings.temporarily(function()
SILE.call("book:left-running-head-font")
SILE.process(content)
end)
end)
SILE.call("bigskip")
SILE.call("nofoliosthispage")
end, "Begin a new chapter");
SILE.registerCommand("section", function (options, content)
SILE.typesetter:leaveHmode()
SILE.call("goodbreak")
SILE.call("bigskip")
SILE.call("noindent")
SILE.Commands["book:sectionfont"]({}, function()
SILE.call("book:sectioning", {
numbering = options.numbering,
level = 2,
postnumber = "book:section:post"
}, content)
SILE.process(content)
end)
if not SILE.scratch.counters.folio.off then
SILE.Commands["right-running-head"]({}, function()
SILE.call("book:right-running-head-font")
SILE.call("rightalign", {}, function ()
SILE.settings.temporarily(function()
SILE.call("show-multilevel-counter", {id="sectioning", level =2})
SILE.typesetter:typeset(" ")
SILE.process(content)
end)
end)
end);
end
SILE.call("novbreak")
SILE.call("bigskip")
SILE.call("novbreak")
SILE.typesetter:inhibitLeading()
end, "Begin a new section")
SILE.registerCommand("subsection", function (options, content)
SILE.typesetter:leaveHmode()
SILE.call("goodbreak")
SILE.call("noindent")
SILE.call("medskip")
SILE.Commands["book:subsectionfont"]({}, function()
SILE.call("book:sectioning", {
numbering = options.numbering,
level = 3,
postnumber = "book:subsection:post"
}, content)
SILE.process(content)
end)
SILE.typesetter:leaveHmode()
SILE.call("novbreak")
SILE.call("medskip")
SILE.call("novbreak")
SILE.typesetter:inhibitLeading()
end, "Begin a new subsection")
SILE.registerCommand("book:chapterfont", function (options, content)
SILE.settings.temporarily(function()
SILE.Commands["font"]({weight=800, size="22pt"}, content)
end)
end)
SILE.registerCommand("book:sectionfont", function (options, content)
SILE.settings.temporarily(function()
SILE.Commands["font"]({weight=800, size="15pt"}, content)
end)
end)
SILE.registerCommand("book:subsectionfont", function (options, content)
SILE.settings.temporarily(function()
SILE.Commands["font"]({weight=800, size="12pt"}, content)
end)
end)
return book
|
local plain = SILE.require("classes/plain");
local book = plain { id = "book" };
book:loadPackage("masters")
book:defineMaster({ id = "right", firstContentFrame = "content", frames = {
content = { left = "8.3%pw", right = "86%pw", top = "11.6%ph", bottom = "top(footnotes)" },
folio = { left = "left(content)", right = "right(content)", top = "bottom(footnotes)+3%ph", bottom = "bottom(footnotes)+5%ph" },
runningHead = { left = "left(content)", right = "right(content)", top = "top(content)-8%ph", bottom = "top(content)-3%ph" },
footnotes = { left="left(content)", right = "right(content)", height = "0", bottom="83.3%ph"}
}})
book:loadPackage("twoside", { oddPageMaster = "right", evenPageMaster = "left" });
book:loadPackage("tableofcontents")
if not(SILE.scratch.headers) then SILE.scratch.headers = {}; end
book.init = function(self)
book:mirrorMaster("right", "left")
book.pageTemplate = SILE.scratch.masters["right"]
book:loadPackage("footnotes", { insertInto = "footnotes", stealFrom = {"content"} } )
return plain.init(self)
end
book.newPage = function(self)
book:switchPage()
book:newPageInfo()
return plain.newPage(self)
end
book.finish = function ()
book:writeToc()
return plain.finish(book)
end
book.endPage = function(self)
book:moveTocNodes()
if (book:oddPage() and SILE.scratch.headers.right) then
SILE.typesetNaturally(SILE.getFrame("runningHead"), function()
SILE.settings.set("current.parindent", SILE.nodefactory.zeroGlue)
SILE.settings.set("document.lskip", SILE.nodefactory.zeroGlue)
SILE.settings.set("document.rskip", SILE.nodefactory.zeroGlue)
-- SILE.settings.set("typesetter.parfillskip", SILE.nodefactory.zeroGlue)
SILE.process(SILE.scratch.headers.right)
SILE.call("par")
end)
elseif (not(book:oddPage()) and SILE.scratch.headers.left) then
SILE.typesetNaturally(SILE.getFrame("runningHead"), function()
SILE.settings.set("current.parindent", SILE.nodefactory.zeroGlue)
SILE.settings.set("document.lskip", SILE.nodefactory.zeroGlue)
SILE.settings.set("document.rskip", SILE.nodefactory.zeroGlue)
-- SILE.settings.set("typesetter.parfillskip", SILE.nodefactory.zeroGlue)
SILE.process(SILE.scratch.headers.left)
SILE.call("par")
end)
end
return plain.endPage(book);
end;
SILE.registerCommand("left-running-head", function(options, content)
local closure = SILE.settings.wrap()
SILE.scratch.headers.left = function () closure(content) end
end, "Text to appear on the top of the left page");
SILE.registerCommand("right-running-head", function(options, content)
local closure = SILE.settings.wrap()
SILE.scratch.headers.right = function () closure(content) end
end, "Text to appear on the top of the right page");
SILE.registerCommand("book:sectioning", function (options, content)
local content = SU.subContent(content)
local level = SU.required(options, "level", "book:sectioning")
SILE.call("increment-multilevel-counter", {id = "sectioning", level = options.level})
SILE.call("tocentry", {level = options.level}, content)
local lang = SILE.settings.get("document.language")
if options.numbering == nil or options.numbering == "yes" then
if options.prenumber then
if SILE.Commands[options.prenumber..":"..lang] then options.prenumber = options.prenumber..":"..lang end
SILE.call(options.prenumber)
end
SILE.call("show-multilevel-counter", {id="sectioning"})
if options.postnumber then
if SILE.Commands[options.postnumber..":"..lang] then options.postnumber = options.postnumber..":"..lang end
SILE.call(options.postnumber)
end
end
end)
book.registerCommands = function()
plain.registerCommands()
SILE.doTexlike([[%
\define[command=book:chapter:pre]{}%
\define[command=book:chapter:post]{\par}%
\define[command=book:section:post]{ }%
\define[command=book:subsection:post]{ }%
\define[command=book:left-running-head-font]{\font[size=9pt]}%
\define[command=book:right-running-head-font]{\font[size=9pt,style=italic]}%
]])
end
SILE.registerCommand("chapter", function (options, content)
SILE.call("open-double-page")
SILE.call("noindent")
SILE.scratch.headers.right = nil
SILE.call("set-counter", {id = "footnote", value = 1})
SILE.call("book:chapterfont", {}, function()
SILE.call("book:sectioning", {
numbering = options.numbering,
level = 1,
prenumber = "book:chapter:pre",
postnumber = "book:chapter:post"
}, content)
end)
SILE.Commands["book:chapterfont"]({}, content);
SILE.Commands["left-running-head"]({}, function()
SILE.settings.temporarily(function()
SILE.call("book:left-running-head-font")
SILE.process(content)
end)
end)
SILE.call("bigskip")
SILE.call("nofoliosthispage")
end, "Begin a new chapter");
SILE.registerCommand("section", function (options, content)
SILE.typesetter:leaveHmode()
SILE.call("goodbreak")
SILE.call("bigskip")
SILE.call("noindent")
SILE.Commands["book:sectionfont"]({}, function()
SILE.call("book:sectioning", {
numbering = options.numbering,
level = 2,
postnumber = "book:section:post"
}, content)
SILE.process(content)
end)
if not SILE.scratch.counters.folio.off then
SILE.Commands["right-running-head"]({}, function()
SILE.call("book:right-running-head-font")
SILE.call("rightalign", {}, function ()
SILE.settings.temporarily(function()
SILE.call("show-multilevel-counter", {id="sectioning", level =2})
SILE.typesetter:typeset(" ")
SILE.process(content)
end)
end)
end);
end
SILE.call("novbreak")
SILE.call("bigskip")
SILE.call("novbreak")
SILE.typesetter:inhibitLeading()
end, "Begin a new section")
SILE.registerCommand("subsection", function (options, content)
SILE.typesetter:leaveHmode()
SILE.call("goodbreak")
SILE.call("noindent")
SILE.call("medskip")
SILE.Commands["book:subsectionfont"]({}, function()
SILE.call("book:sectioning", {
numbering = options.numbering,
level = 3,
postnumber = "book:subsection:post"
}, content)
SILE.process(content)
end)
SILE.typesetter:leaveHmode()
SILE.call("novbreak")
SILE.call("medskip")
SILE.call("novbreak")
SILE.typesetter:inhibitLeading()
end, "Begin a new subsection")
SILE.registerCommand("book:chapterfont", function (options, content)
SILE.settings.temporarily(function()
SILE.Commands["font"]({weight=800, size="22pt"}, content)
end)
end)
SILE.registerCommand("book:sectionfont", function (options, content)
SILE.settings.temporarily(function()
SILE.Commands["font"]({weight=800, size="15pt"}, content)
end)
end)
SILE.registerCommand("book:subsectionfont", function (options, content)
SILE.settings.temporarily(function()
SILE.Commands["font"]({weight=800, size="12pt"}, content)
end)
end)
return book
|
Fix race condition in book class (no paper size until init!)
|
Fix race condition in book class (no paper size until init!)
|
Lua
|
mit
|
simoncozens/sile,alerque/sile,alerque/sile,simoncozens/sile,simoncozens/sile,neofob/sile,neofob/sile,neofob/sile,simoncozens/sile,alerque/sile,alerque/sile,neofob/sile
|
cea7c44d8450842a77528d60ddbbb6ed49692816
|
server.lua
|
server.lua
|
-- https://github.com/szym/display
-- Copyright (c) 2015, Szymon Jakubczak (MIT License)
-- Forwards any data POSTed to /events to an event-stream at /events.
-- Serves files from /static otherwise.
local port = tonumber(arg[1]) or 8000
local hostname = arg[2] or '127.0.0.1'
local async = require('async')
local function getMime(ext)
if ext == '.css' then
return 'text/css'
elseif ext == '.js' then
return 'text/javascript'
else
return 'text/html' -- TODO: other mime types
end
end
local subscribers = {}
async.http.listen('http://' .. hostname .. ':' .. port .. '/',
function(req, res, client)
print(req.method, req.url.path)
local resp
if req.url.path == '/events' then
local header = {
['Content-Type'] = 'text/event-stream',
['Cache-Control'] = 'no-cache',
['Connection'] = 'keep-alive',
['Transfer-Encoding'] = 'chunked'
}
if req.method == 'GET' then
res('', header, 200)
table.insert(subscribers, client)
elseif req.method == 'POST' then
local body = req.body
for i=1,#subscribers do
local client = subscribers[i]
assert(type(body) == 'string')
local headlen = 8
client.write(string.format('%x\r\n', #body + headlen))
client.write('data: ') -- 6
client.write(body)
client.write('\n\n') -- 2
client.write('\r\n')
end
res('', {})
else
res('Invalid!', {['Content-Type']='text/html'})
end
else -- serve files from static
local file = req.url.path
if file == '/' or file == '' then
file = '/index.html'
end
local ext = string.match(file, "%.%l%l%l?")
local mime = getMime(ext)
local served = io.open("static/" .. file, 'r')
if served ~= nil then
resp = served:read("*all")
served:close()
else
resp("Not found!")
end
res(resp, {['Content-Type']=mime})
end
end)
print('server listening on http://' .. hostname .. ':' .. port)
async.go()
|
-- https://github.com/szym/display
-- Copyright (c) 2015, Szymon Jakubczak (MIT License)
-- Forwards any data POSTed to /events to an event-stream at /events.
-- Serves files from /static otherwise.
local port = tonumber(arg[1]) or 8000
local hostname = arg[2] or '127.0.0.1'
local async = require('async')
local function getMime(ext)
if ext == '.css' then
return 'text/css'
elseif ext == '.js' then
return 'text/javascript'
else
return 'text/html' -- TODO: other mime types
end
end
local subscribers = {}
async.http.listen('http://' .. hostname .. ':' .. port .. '/',
function(req, res, client)
print(req.method, req.url.path)
local resp
if req.url.path == '/events' then
local header = {
['Content-Type'] = 'text/event-stream',
['Cache-Control'] = 'no-cache',
['Connection'] = 'keep-alive',
['Transfer-Encoding'] = 'chunked'
}
if req.method == 'GET' then
res('', header, 200)
table.insert(subscribers, client)
elseif req.method == 'POST' then
local body = req.body
for i=1,#subscribers do
local client = subscribers[i]
assert(type(body) == 'string')
local headlen = 8
client.write(string.format('%x\r\n', #body + headlen))
client.write('data: ') -- 6
client.write(body)
client.write('\n\n') -- 2
client.write('\r\n')
end
res('', {})
else
res('Invalid!', {['Content-Type']='text/html'})
end
else -- serve files from static
local file = req.url.path
if file == '/' or file == '' then
file = '/index.html'
end
local ext = string.match(file, "%.%l%l%l?")
local mime = getMime(ext)
local served = io.open("static/" .. file, 'r')
if served ~= nil then
resp = served:read("*all")
served:close()
res(resp, {['Content-Type']=mime})
else
res('Not found!', {}, 404)
end
end
end)
print('server listening on http://' .. hostname .. ':' .. port)
async.go()
|
fix handling of not found static files
|
fix handling of not found static files
|
Lua
|
mit
|
szym/display,szym/display,soumith/display,szym/display,soumith/display,soumith/display,soumith/display,szym/display
|
b3fb3d283dc8e2b43c0055e8dbad8d290eaf1cc5
|
src/Command.lua
|
src/Command.lua
|
local Log = require 'Log'
local Command = {}
function Command:new(...)
local o = { command = {...} }
setmetatable(o, self)
self.__index = self
return o
end
function Command:newf(f, ...)
return Command:new(string.format(f, ...))
end
function Command:append(...)
append(self.command, ...)
return self
end
function Command:__tostring()
return table.concat(self.command, ' ')
end
function Command:exists()
return Command:new('command -v', self.command[1]):read()
end
function Command:exec()
local cmdstr = tostring(self) Log.debug1(cmdstr:escape_format())
local ok = os.execute(cmdstr)
if type(ok) == 'number' then
return ok == 0 -- Lua 5.1
else
return ok -- Lua 5.2
end
end
function Command:popen(mode)
local command = tostring(self) Log.debug1(command:escape_format())
return assert(io.popen(command, mode))
end
function Command:lines()
local pipe = self:popen()
local lines = pipe:lines()
return function ()
local line = lines()
if line ~= nil then
return line
else
pipe:close()
end
end
end
function Command:match(pattern)
for line in self:lines() do
local m = line:match(pattern)
if m then return m end
end
end
function Command:aslist()
local pipe = self:popen()
local list = aslist(pipe:lines())
pipe:close()
return list
end
function Command:read(...)
local file = self:popen()
local results = { file:read(...) }
file:close()
return table.unpack(results)
end
return Command
|
local Log = require 'Log'
local Command = {}
function Command:new(...)
local o = { command = {...} }
setmetatable(o, self)
self.__index = self
return o
end
function Command:newf(f, ...)
return Command:new(string.format(f, ...))
end
function Command:append(...)
append(self.command, ...)
return self
end
function Command:__tostring()
return table.concat(self.command, ' ')
end
function Command:exists()
return Command:new('command -v', self.command[1]):read()
end
function Command:exec()
local cmdstr = tostring(self) Log.debug1(cmdstr:escape_format())
local ok, how, status = os.execute(assert(cmdstr))
if type(ok) == 'number' then
return ok == 0 -- Lua 5.1
else
return status == 0 -- Lua 5.2
end
end
function Command:popen(mode)
local command = tostring(self) Log.debug1(command:escape_format())
return assert(io.popen(command, mode))
end
function Command:lines()
local pipe = self:popen()
local lines = pipe:lines()
return function ()
local line = lines()
if line ~= nil then
return line
else
pipe:close()
end
end
end
function Command:match(pattern)
for line in self:lines() do
local m = line:match(pattern)
if m then return m end
end
end
function Command:aslist()
local pipe = self:popen()
local list = aslist(pipe:lines())
pipe:close()
return list
end
function Command:read(...)
local file = self:popen()
local results = { file:read(...) }
file:close()
return table.unpack(results)
end
return Command
|
Fix Command:exec incorrectly propagating return status
|
Fix Command:exec incorrectly propagating return status
This caused the 'build' subcommand to always finish with a 0 status even when the script actually failed.
|
Lua
|
mit
|
bazurbat/jagen
|
0634fac2079fbd0540f62dbd04bcc64412670829
|
JoinTable.lua
|
JoinTable.lua
|
local JoinTable, parent = torch.class('nn.JoinTable', 'nn.Module')
function JoinTable:__init(dimension, nInputDims)
parent.__init(self)
self.size = torch.LongStorage()
self.dimension = dimension
self.gradInput = {}
self.nInputDims = nInputDims
end
function JoinTable:updateOutput(input)
local dimension = self.dimension
if self.nInputDims and input[1]:dim()==(self.nInputDims+1) then
dimension = dimension + 1
end
for i=1,#input do
local currentOutput = input[i]
if i == 1 then
self.size:resize(currentOutput:dim()):copy(currentOutput:size())
else
self.size[dimension] = self.size[dimension]
+ currentOutput:size(dimension)
end
end
self.output:resize(self.size)
local offset = 1
for i=1,#input do
local currentOutput = input[i]
self.output:narrow(dimension, offset,
currentOutput:size(dimension)):copy(currentOutput)
offset = offset + currentOutput:size(dimension)
end
return self.output
end
function JoinTable:updateGradInput(input, gradOutput)
local dimension = self.dimension
if self.nInputDims and input[1]:dim()==(self.nInputDims+1) then
dimension = dimension + 1
end
for i=1,#input do
if self.gradInput[i] == nil then
self.gradInput[i] = input[i].new()
end
self.gradInput[i]:resizeAs(input[i])
end
local offset = 1
for i=1,#input do
local currentOutput = input[i]
local currentGradInput = gradOutput:narrow(dimension, offset,
currentOutput:size(dimension))
self.gradInput[i]:copy(currentGradInput)
offset = offset + currentOutput:size(dimension)
end
return self.gradInput
end
function JoinTable:type(type)
self.gradInput = {}
return parent.type(self, type)
end
|
local JoinTable, parent = torch.class('nn.JoinTable', 'nn.Module')
function JoinTable:__init(dimension, nInputDims)
parent.__init(self)
self.size = torch.LongStorage()
self.dimension = dimension
self.gradInput = {}
self.nInputDims = nInputDims
end
function JoinTable:updateOutput(input)
local dimension = self.dimension
if self.nInputDims and input[1]:dim()==(self.nInputDims+1) then
dimension = dimension + 1
end
for i=1,#input do
local currentOutput = input[i]
if i == 1 then
self.size:resize(currentOutput:dim()):copy(currentOutput:size())
else
self.size[dimension] = self.size[dimension]
+ currentOutput:size(dimension)
end
end
self.output:resize(self.size)
local offset = 1
for i=1,#input do
local currentOutput = input[i]
self.output:narrow(dimension, offset,
currentOutput:size(dimension)):copy(currentOutput)
offset = offset + currentOutput:size(dimension)
end
return self.output
end
function JoinTable:updateGradInput(input, gradOutput)
local dimension = self.dimension
if self.nInputDims and input[1]:dim()==(self.nInputDims+1) then
dimension = dimension + 1
end
for i=1,#input do
if self.gradInput[i] == nil then
self.gradInput[i] = input[i].new()
end
self.gradInput[i]:resizeAs(input[i])
end
-- clear out invalid gradInputs
for i=#input+1, #self.gradInput do
self.gradInput[i] = nil
end
local offset = 1
for i=1,#input do
local currentOutput = input[i]
local currentGradInput = gradOutput:narrow(dimension, offset,
currentOutput:size(dimension))
self.gradInput[i]:copy(currentGradInput)
offset = offset + currentOutput:size(dimension)
end
return self.gradInput
end
function JoinTable:type(type)
self.gradInput = {}
return parent.type(self, type)
end
|
fixes jointable backward bug
|
fixes jointable backward bug
|
Lua
|
bsd-3-clause
|
diz-vara/nn,ominux/nn,abeschneider/nn,mlosch/nn,andreaskoepf/nn,jhjin/nn,zhangxiangxiao/nn,hughperkins/nn,zchengquan/nn,lvdmaaten/nn,eulerreich/nn,lukasc-ch/nn,xianjiec/nn,hery/nn,GregSatre/nn,noa/nn,ivendrov/nn,jzbontar/nn,davidBelanger/nn,jonathantompson/nn,witgo/nn,rotmanmi/nn,Jeffyrao/nn,vgire/nn,elbamos/nn,LinusU/nn,sbodenstein/nn,kmul00/nn,aaiijmrtt/nn,eriche2016/nn,EnjoyHacking/nn,Moodstocks/nn,PraveerSINGH/nn,douwekiela/nn,adamlerer/nn,sagarwaghmare69/nn,Djabbz/nn,apaszke/nn,caldweln/nn,nicholas-leonard/nn,joeyhng/nn,forty-2/nn,clementfarabet/nn,Aysegul/nn,PierrotLC/nn,bartvm/nn,colesbury/nn
|
de455e666dbe2acd415a5e2bd7b631edeed7402f
|
samples/events/index.lua
|
samples/events/index.lua
|
--
-- Stream Server-Sent Events (SSE)
--
content("text/event-stream;charset=utf-8")
setheader("Cache-Control", "no-cache")
setheader("Connection", "keep-alive")
setheader("Access-Control-Allow-Origin", "*")
function event(message)
log("EVENT: " .. message)
print("data: " .. message .. "\n")
flush()
end
function finish()
log("Done streaming events")
print("\n")
flush()
end
function main()
log("Steaming events")
log("Turn off buffering for this to work properly (turn off debug mode)")
-- The following must take < 10 seconds, before the request times out
event("one event")
sleep(2)
event("a second event")
sleep(1)
event("a third event")
sleep(0.2)
event("yet another event")
sleep(1)
event("eventorama!")
sleep(3)
event("done")
finish()
end
main()
|
--
-- Stream Server-Sent Events (SSE)
--
content("text/event-stream;charset=utf-8")
setheader("Cache-Control", "no-cache")
setheader("Connection", "keep-alive")
setheader("Access-Control-Allow-Origin", "*")
function event(message)
log("streaming event: " .. message)
print("data: " .. message .. "\n")
flush()
end
function finish()
print("\n")
flush()
end
function main()
log("Streaming events")
log("Turn off buffering for this to work properly (turn off debug mode)")
-- The following must take < 10 seconds, before the request times out
event("one event")
sleep(0.2)
event("a second event")
sleep(1)
event("a third event")
sleep(2)
event("yet another event")
sleep(1)
event("eventorama!")
sleep(3)
event("done")
finish()
log("Done streaming")
end
main()
|
Fixed a typo. Better comments.
|
Fixed a typo. Better comments.
|
Lua
|
bsd-3-clause
|
xyproto/algernon,xyproto/algernon,xyproto/algernon,xyproto/algernon
|
e5290605c5a88f93810ad9392c670968e471a10a
|
common.lua
|
common.lua
|
--[[
This file is part of ClearTables
@author Paul Norman <penorman@mac.com>
@copyright 2015 Paul Norman, MIT license
]]--
-- Lua primer:
-- cond and "a" or "b" evaluates to a if cond is true, b if cond is false. This
-- is the idiomatic way to do an inline conditional in lua
--- Normalizes a tag value to true/false
-- Typical usage would be on a tag like bridge, tunnel, or shelter which are expected
-- to be yes, no, or unset, but not a tag like oneway which could be
-- yes, no, reverse, or unset.
-- @param v The tag value
-- @return The string true or false, or nil, which is turned into a boolean by PostgreSQL
function yesno (v)
return v ~= nil and ((v == "no" or v == "false") and "false" or "true") or nil
end
--- Normalizes oneway for roads/etc
-- @param v The tag value
-- @return The string true, false, or reverse, or nil which is turned into an enum by PostgreSQL
function oneway (v)
return v ~= nil and (
v == "-1" and "reverse" or (
(v == "no" or v == "false") and "false" or (
"true"
)
)
) or nil
end
--- Drops all objects
-- @return osm2pgsql return to disregard an object as uninteresting
function drop_all (...)
return 1, {}
end
--- Tags which are always polygons
-- TODO: sort by frequency
local unconditional_polygon_keys = {'natural'}
-- TODO: Conditional polygon keys (e.g. waterway=riverbank)
--- Is something an area?
-- @param kv OSM tags
-- @return 1 if area, 0 if linear
function isarea (tags)
-- Handle explicit area tags
if tags["area"] then
return tags["area"] == "yes" and 1 or 0
end
for i,k in ipairs(unconditional_polygon_keys) do
if tags[k] then
return 1
end
end
end
--- Generic handling for a multipolygon
-- @param kv OSM tags
-- @param kv_members OSM tags of relation members
-- @param membercount number of members
-- @param accept function that takes osm keys and returns true if the feature should be in the table
-- @param transform function that takes osm keys and returns tags for the tables
-- @return filter, tags, member_superseded, boundary, polygon, roads
function generic_multipolygon_members (tags, member_tags, membercount, accept, transform)
-- tracks if the relation members are used as a stand-alone way. No old-style
-- MP support, but the array still needs to be returned
members_superseeded = {}
for i = 1, membercount do
members_superseeded[i] = 0
end
if (tags["type"] and tags["type"] == "multipolygon") then
-- Get rid of the MP tag, we've handled it
tags["type"] = nil
-- Is this a feature we want?
if (accept(tags)) then
-- Get the tags for the table
return 0, transform(tags), members_superseeded, 0, 1, 0
end
return 1, {}, members_superseeded, 0, 1, 0
end
return 1, {}, members_superseeded, 0, 0, 0
end
-- Lifted from Penlight. Modified to not handle cases that don't matter here
-- https://github.com/stevedonovan/Penlight/blob/master/lua/pl/tablex.lua
--[[
Copyright (C) 2009 Steve Donovan, David Manura.
Under the MIT license, like the rest of the code here
]]--
--- compare two values.
-- if they are tables, then compare their keys and fields recursively.
-- @within Comparing
-- @param t1 A value
-- @param t2 A value
-- @return true or false
function deepcompare (t1,t2)
local ty1 = type(t1)
local ty2 = type(t2)
if ty1 ~= ty2 then return false end
-- non-table types can be directly compared
if ty1 ~= 'table' then
return t1 == t2
end
for k1 in pairs(t1) do
if t2[k1]==nil then return false end
end
for k2 in pairs(t2) do
if t1[k2]==nil then return false end
end
for k1,v1 in pairs(t1) do
local v2 = t2[k1]
if not deepcompare(v1,v2) then return false end
end
return true
end
|
--[[
This file is part of ClearTables
@author Paul Norman <penorman@mac.com>
@copyright 2015 Paul Norman, MIT license
]]--
-- Lua primer:
-- cond and "a" or "b" evaluates to a if cond is true, b if cond is false. This
-- is the idiomatic way to do an inline conditional in lua
--- Normalizes a tag value to true/false
-- Typical usage would be on a tag like bridge, tunnel, or shelter which are expected
-- to be yes, no, or unset, but not a tag like oneway which could be
-- yes, no, reverse, or unset.
-- @param v The tag value
-- @return The string true or false, or nil, which is turned into a boolean by PostgreSQL
function yesno (v)
return v ~= nil and ((v == "no" or v == "false") and "false" or "true") or nil
end
--- Normalizes oneway for roads/etc
-- @param v The tag value
-- @return The string true, false, or reverse, or nil which is turned into an enum by PostgreSQL
function oneway (v)
return v ~= nil and (
v == "-1" and "reverse" or (
(v == "no" or v == "false") and "false" or (
"true"
)
)
) or nil
end
--- Drops all objects
-- @return osm2pgsql return to disregard an object as uninteresting
function drop_all (...)
return 1, {}
end
--- Tags which are always polygons
-- TODO: sort by frequency
local unconditional_polygon_keys = {'natural'}
-- TODO: Conditional polygon keys (e.g. waterway=riverbank)
--- Is something an area?
-- @param kv OSM tags
-- @return 1 if area, 0 if linear
function isarea (tags)
-- Handle explicit area tags
if tags["area"] then
return tags["area"] == "yes" and 1 or 0
end
for i,k in ipairs(unconditional_polygon_keys) do
if tags[k] then
return 1
end
end
end
--- Generic handling for a multipolygon
-- @param kv OSM tags
-- @param kv_members OSM tags of relation members
-- @param membercount number of members
-- @param accept function that takes osm keys and returns true if the feature should be in the table
-- @param transform function that takes osm keys and returns tags for the tables
-- @return filter, tags, member_superseded, boundary, polygon, roads
function generic_multipolygon_members (tags, member_tags, membercount, accept, transform)
-- tracks if the relation members are used as a stand-alone way. No old-style
-- MP support, but the array still needs to be returned
members_superseeded = {}
for i = 1, membercount do
members_superseeded[i] = 0
end
if (tags["type"] and tags["type"] == "multipolygon") then
-- Get rid of the MP tag, we've handled it
tags["type"] = nil
-- Is this a feature we want?
if (accept(tags)) then
-- Get the tags for the table
return 0, transform(tags), members_superseeded, 0, 1, 0
end
return 1, {}, members_superseeded, 0, 1, 0
end
return 1, {}, members_superseeded, 0, 0, 0
end
-- Lifted from Penlight. Modified to not handle cases that don't matter here
-- https://github.com/stevedonovan/Penlight/blob/master/lua/pl/tablex.lua
--[[
Copyright (C) 2009 Steve Donovan, David Manura.
Under the MIT license, like the rest of the code here
]]--
--- compare two values.
-- if they are tables, then compare their keys and fields recursively.
-- @within Comparing
-- @param t1 A value
-- @param t2 A value
-- @return true or false
function deepcompare (t1,t2)
local ty1 = type(t1)
local ty2 = type(t2)
if ty1 ~= ty2 then return false end
-- non-table types can be directly compared
if ty1 ~= 'table' then
return t1 == t2
end
for k1 in pairs(t1) do
if t2[k1]==nil then return false end
end
for k2 in pairs(t2) do
if t1[k2]==nil then return false end
end
for k1,v1 in pairs(t1) do
local v2 = t2[k1]
if not deepcompare(v1,v2) then return false end
end
return true
end
|
fix oneway formatting
|
fix oneway formatting
|
Lua
|
mit
|
pnorman/ClearTables,ClearTables/ClearTables
|
4166fe7d321e52f3d5b7da79e8374aa1f449e08c
|
love2d/ambientsound.lua
|
love2d/ambientsound.lua
|
require "mapGenerator"
-- world map: lizGame.world.map.*
-- THIS IS ONLY THE SOUND PRODUCED BY THE AMBIENT (TODO the ambient consists of everything that is on the normal world map right now)
-- for sound produced by objects (e.g. the player or a door or an enemy) look at objectsound.lua (NYI)
--[[ possible sound sources:
1. player/selected character <- only this works for now
2. map center <- will be added later
--]]
--[[ possible values for the SoundMap:
0: no sound at all -- other tile or out of map
greater than 0: see MAP_OBJ_... constants in mapGenerator.lua
--]]
function getAmbientSoundGenerator() --not nice but this cannot be part of the namespace "love.sounds.*"
local o = {}
o.soundActive = false
o.listeningRadius = 3 -- this will be used for determining how far a tile may be for the player to hear a sound
o.origX = 0
o.origY = 0
o.soundMap = {}
-- call this method once at initialization and every time the listening radius is changed
o.resetSoundMap = function()
local tempSoundMap = {}
for i = 1,2*o.listeningRadius+1 do
tempSoundMap[i] = {}
for j = 1, 2*o.listeningRadius+1 do
tempSoundMap[i][j] = 0
end
end
o.soundMap = tempSoundMap
end
o.updateSoundMap = function()
o.resetSoundMap()
for i = 1,2*o.listeningRadius+1 do
if i+o.origX-o.listeningRadius < 1 or i+o.origX-o.listeningRadius>lizGame.world.mapWidth then
for j = 1, 2*o.listeningRadius+1 do
o.soundMap[i][j] = 0
end
else
for j = 1, o.listeningRadius+o.origY do
if j+o.origY-o.listeningRadius < 1 or j+o.origY-o.listeningRadius>lizGame.world.mapHeight then
o.soundMap[i][j] = 0
else
local t = MapGenerator.getObject(lizGame.world.mapG,i+o.origX-o.listeningRadius,j+o.origY-o.listeningRadius)
--print ("tile to add:"..t)
--TODO change this when 3D world is implemented
o.soundMap[i][j] = t
--print ("tile added? "..o.soundMap[i][j])
end
end
end
end
end
o.setOrigin = function()
--TODO, default for now: look at pawn #1
local tempx,tempy = lizGame.world.pawns[1].getPosition()
o.origX = math.floor(tempx+0.5)
o.origY = math.floor(tempy+0.5)
end
o.playAmbient = function()
if o.soundActive and lizGame.state == states.GAMEPLAY then
o.setOrigin()
o.updateSoundMap()
local tileAmount = {}
for i=0,9 do
tileAmount[i]=0
end
for i = 1,2*o.listeningRadius+1 do
for j = 1, 2*o.listeningRadius+1 do
--tileAmount[o.soundMap[i][j]] and
local soundMapValue = o.soundMap[i][j]
if i+j>=o.listeningRadius and soundMapValue>0 then
if soundMapValue == 4 then
print("fire might be at "..i+o.origX-o.listeningRadius..", "..j+o.origY-o.listeningRadius)
for k=1,#lizGame.world.fires do
local fire = lizGame.world.fires[k]
print ("looking at fireplace: "..fire.x..", ".. fire.y);
if fire.y == j + o.origY - o.listeningRadius and fire.x == i +o.origX - o.listeningRadius then
print ("found fire")
if lizGame.world.fires[k].state ~= 0 then
tileAmount[soundMapValue] = tileAmount[soundMapValue] + 1
print("burning fire added")
end
break
end
end
else
tileAmount[soundMapValue] = tileAmount[soundMapValue] + 1
end
end
end
end
-- quick algorithm to find the most used tile within listener range
local mostUsed = 0
local mostUsedAmount = 0
local secondMostUsed = 0
for i=1,#tileAmount do
if tileAmount[i]>mostUsedAmount then
secondMostUsed = mostUsed
mostUsedAmount = tileAmount[i]
mostUsed = i
end
--print("Amount of "..i..":"..tileAmount[i])
end
--print("Most used: "..mostUsed..", "..secondMostUsed)
-- play the right music file
if mostUsed == 1 or secondMostUsed == 1 then
love.sounds.playSound("riverLoop1")
else
love.sounds.stopSound("riverLoop1")
end
if mostUsed == 2 or secondMostUsed == 2 then
if love.sounds.soundRandomizer:random(1,100) > 85 then
love.sounds.playSound("birds",nil,love.sounds.soundRandomizer:random(1,3)*0.5)
end
else
love.sounds.stopSound("birds")
end
if mostUsed == 4 or secondMostUsed == 4 then
love.sounds.playSound("fireplace")
-- elseif mostUsed == 5 then
else
love.sounds.stopSound("fireplace")
end
if mostUsed >= 5 or secondMostUsed >=5 then
if love.sounds.soundRandomizer:random(1,100) > 80 then
love.sounds.playSound("bird",nil,love.sounds.soundRandomizer:random(1,3)*0.5)
end
else
love.sounds.stopSound("bird")
end
end
end
return o
end
|
require "mapGenerator"
-- world map: lizGame.world.map.*
-- THIS IS ONLY THE SOUND PRODUCED BY THE AMBIENT (TODO the ambient consists of everything that is on the normal world map right now)
-- for sound produced by objects (e.g. the player or a door or an enemy) look at objectsound.lua (NYI)
--[[ possible sound sources:
1. player/selected character <- only this works for now
2. map center <- will be added later
--]]
--[[ possible values for the SoundMap:
0: no sound at all -- other tile or out of map
greater than 0: see MAP_OBJ_... constants in mapGenerator.lua
--]]
function getAmbientSoundGenerator() --not nice but this cannot be part of the namespace "love.sounds.*"
local o = {}
o.soundActive = false
o.listeningRadius = 3 -- this will be used for determining how far a tile may be for the player to hear a sound
o.origX = 0
o.origY = 0
o.soundMap = {}
-- call this method once at initialization and every time the listening radius is changed
o.resetSoundMap = function()
local tempSoundMap = {}
for i = 1,2*o.listeningRadius+1 do
tempSoundMap[i] = {}
for j = 1, 2*o.listeningRadius+1 do
tempSoundMap[i][j] = 0
end
end
o.soundMap = tempSoundMap
end
o.updateSoundMap = function()
o.resetSoundMap()
for i = 1,2*o.listeningRadius+1 do
if i+o.origX-o.listeningRadius < 1 or i+o.origX-o.listeningRadius>lizGame.world.mapWidth then
for j = 1, 2*o.listeningRadius+1 do
o.soundMap[i][j] = 0
end
else
for j = 1, o.listeningRadius+o.origY do
if j+o.origY-o.listeningRadius < 1 or j+o.origY-o.listeningRadius>lizGame.world.mapHeight then
o.soundMap[i][j] = 0
else
local t = MapGenerator.getObject(lizGame.world.mapG,i+o.origX-o.listeningRadius,j+o.origY-o.listeningRadius)
--print ("tile to add:"..t)
--TODO change this when 3D world is implemented
o.soundMap[i][j] = t
--print ("tile added? "..o.soundMap[i][j])
end
end
end
end
end
o.setOrigin = function()
--TODO, default for now: look at pawn #1
local tempx,tempy = lizGame.world.pawns[1].getPosition()
o.origX = math.floor(tempx+0.5)
o.origY = math.floor(tempy+0.5)
end
o.playAmbient = function()
--print "."
if o.soundActive and lizGame.state == states.GAMEPLAY then
o.setOrigin()
o.updateSoundMap()
local tileAmount = {}
for i=0,9 do
tileAmount[i]=0
end
for i = 1,2*o.listeningRadius+1 do
for j = 1, 2*o.listeningRadius+1 do
--tileAmount[o.soundMap[i][j]] and
local soundMapValue = o.soundMap[i][j]
if i+j>=o.listeningRadius and soundMapValue>0 then
if soundMapValue == 4 then
for k=1,#lizGame.world.fires do
if lizGame.world.fires[k].y == j+o.origY-o.listeningRadius-1 and lizGame.world.fires[k].x == i+o.origX-o.listeningRadius-1 then
if lizGame.world.fires[k].state ~= 0 then
tileAmount[soundMapValue] = tileAmount[soundMapValue] + 1
end
break
end
end
else
tileAmount[soundMapValue] = tileAmount[soundMapValue] + 1
end
end
end
end
-- quick algorithm to find the most used tile within listener range
local mostUsed = 0
local mostUsedAmount = 0
local secondMostUsed = 0
for i=1,#tileAmount do
if tileAmount[i]>mostUsedAmount then
secondMostUsed = mostUsed
mostUsedAmount = tileAmount[i]
mostUsed = i
end
--print("Amount of "..i..":"..tileAmount[i])
end
--print("Most used: "..mostUsed..", "..secondMostUsed)
-- play the right music file
if mostUsed == 1 or secondMostUsed == 1 then
love.sounds.playSound("riverLoop1")
else
love.sounds.stopSound("riverLoop1")
end
if mostUsed == 2 or secondMostUsed == 2 then
if love.sounds.soundRandomizer:random(1,100) > 85 then
love.sounds.playSound("birds",nil,love.sounds.soundRandomizer:random(1,3)*0.5)
end
else
love.sounds.stopSound("birds")
end
if mostUsed == 4 or secondMostUsed == 4 then
love.sounds.playSound("fireplace")
-- elseif mostUsed == 5 then
else
love.sounds.stopSound("fireplace")
end
if mostUsed >= 5 or secondMostUsed >=5 then
if love.sounds.soundRandomizer:random(1,100) > 80 then
love.sounds.playSound("bird",nil,love.sounds.soundRandomizer:random(1,3)*0.5)
end
else
love.sounds.stopSound("bird")
end
end
end
return o
end
|
fix for issue #8 is fixed now and all the comments in the sound file are disabled
|
fix for issue #8 is fixed now and all the comments in the sound file are disabled
Conflicts:
love2d/ambientsound.lua
|
Lua
|
mit
|
nczempin/lizard-journey
|
41bd2a7e8179b30df2cce82ec6af528f63563fa8
|
game/scripts/vscripts/modules/structures/modifier_fountain_aura_enemy.lua
|
game/scripts/vscripts/modules/structures/modifier_fountain_aura_enemy.lua
|
local FOUNTAIN_EFFECTIVE_TIME_THRESHOLD = 2100
local FOUNTAIN_DAMAGE_PER_SECOND_PCT = 5
modifier_fountain_aura_enemy = class({
IsDebuff = function() return true end,
IsPurgable = function() return false end,
GetTexture = function() return "fountain_heal" end,
OnTooltip = function() return FOUNTAIN_DAMAGE_PER_SECOND_PCT end,
GetDisableHealing = function() return 1 end,
})
function modifier_fountain_aura_enemy:DeclareFunctions()
return {
MODIFIER_PROPERTY_DAMAGEOUTGOING_PERCENTAGE,
MODIFIER_PROPERTY_TOOLTIP,
MODIFIER_PROPERTY_DISABLE_HEALING
}
end
-- Each 5m = -5%
function modifier_fountain_aura_enemy:GetModifierDamageOutgoing_Percentage()
local timeLast = GameRules:GetDOTATime(false, true) - FOUNTAIN_EFFECTIVE_TIME_THRESHOLD
local b = math.floor(timeLast / 300) * 5
return -math.max(50 - b, 0)
end
if IsServer() then
function modifier_fountain_aura_enemy:OnCreated(keys)
self.team = keys.team
self:StartIntervalThink(1)
self:OnIntervalThink()
end
function modifier_fountain_aura_enemy:CreateFountainPFX()
local fountain = FindFountain(self.team)
local parent = self:GetParent()
Timers:CreateTimer(0.1, function()
fountain:EmitSound("Ability.LagunaBlade")
if IsValidEntity(parent) then
parent:EmitSound("Ability.LagunaBladeImpact")
local pfx = ParticleManager:CreateParticle("particles/units/heroes/hero_lina/lina_spell_laguna_blade.vpcf", PATTACH_ABSORIGIN, fountain)
ParticleManager:SetParticleControl(pfx, 0, fountain:GetAbsOrigin() + Vector(0,0,224))
ParticleManager:SetParticleControlEnt(pfx, 1, parent, PATTACH_POINT_FOLLOW, "attach_hitloc", parent:GetAbsOrigin(), true)
end
end)
end
function modifier_fountain_aura_enemy:OnIntervalThink()
local parent = self:GetParent()
self:CreateFountainPFX()
if GameRules:GetDOTATime(false, true) < FOUNTAIN_EFFECTIVE_TIME_THRESHOLD then
parent:TrueKill()
else
ApplyDamage({
attacker = FindFountain(self.team),
victim = parent,
damage = parent:GetMaxHealth() * self:OnTooltip() * 0.01,
damage_type = DAMAGE_TYPE_PURE,
damage_flags = DOTA_DAMAGE_FLAG_NO_SPELL_AMPLIFICATION
})
end
end
end
|
local FOUNTAIN_EFFECTIVE_TIME_THRESHOLD = 2100
local FOUNTAIN_DAMAGE_PER_SECOND_PCT = 5
modifier_fountain_aura_enemy = class({
IsDebuff = function() return true end,
IsPurgable = function() return false end,
GetTexture = function() return "fountain_heal" end,
OnTooltip = function() return FOUNTAIN_DAMAGE_PER_SECOND_PCT end,
GetDisableHealing = function() return 1 end,
})
function modifier_fountain_aura_enemy:DeclareFunctions()
return {
MODIFIER_PROPERTY_DAMAGEOUTGOING_PERCENTAGE,
MODIFIER_PROPERTY_TOOLTIP,
MODIFIER_PROPERTY_DISABLE_HEALING
}
end
-- Each 5m = -5%
function modifier_fountain_aura_enemy:GetModifierDamageOutgoing_Percentage()
local timeLast = GameRules:GetDOTATime(false, true) - FOUNTAIN_EFFECTIVE_TIME_THRESHOLD
local b = math.floor(timeLast / 300) * 5
return -math.max(50 - b, 0)
end
if IsServer() then
function modifier_fountain_aura_enemy:OnCreated(keys)
self.team = keys.team
self:StartIntervalThink(1)
self:OnIntervalThink()
end
function modifier_fountain_aura_enemy:CreateFountainPFX()
local fountain = FindFountain(self.team)
local parent = self:GetParent()
Timers:CreateTimer(0.1, function()
fountain:EmitSound("Ability.LagunaBlade")
if IsValidEntity(parent) then
parent:EmitSound("Ability.LagunaBladeImpact")
local pfx = ParticleManager:CreateParticle("particles/units/heroes/hero_lina/lina_spell_laguna_blade.vpcf", PATTACH_ABSORIGIN, fountain)
ParticleManager:SetParticleControl(pfx, 0, fountain:GetAbsOrigin() + Vector(0,0,224))
ParticleManager:SetParticleControlEnt(pfx, 1, parent, PATTACH_POINT_FOLLOW, "attach_hitloc", parent:GetAbsOrigin(), true)
end
end)
end
function modifier_fountain_aura_enemy:OnIntervalThink()
local parent = self:GetParent()
-- Fixes possible exploit, when killing summon before they are completely created,
-- causes infinty spawning loop
if parent:IsWukongsSummon() then return end
self:CreateFountainPFX()
if GameRules:GetDOTATime(false, true) < FOUNTAIN_EFFECTIVE_TIME_THRESHOLD then
parent:TrueKill()
else
ApplyDamage({
attacker = FindFountain(self.team),
victim = parent,
damage = parent:GetMaxHealth() * self:OnTooltip() * 0.01,
damage_type = DAMAGE_TYPE_PURE,
damage_flags = DOTA_DAMAGE_FLAG_NO_SPELL_AMPLIFICATION
})
end
end
end
|
fix(structures): ignore Monkey King's summons by fountains
|
fix(structures): ignore Monkey King's summons by fountains
Fixes #107.
|
Lua
|
mit
|
ark120202/aabs
|
59450ee745df437701279f4498b8325252df68b6
|
string.lua
|
string.lua
|
-- new string-related functions, all of them placed in table string
-- and thus callable with str:foo()
-- split, trim, join, rfind, count, interpolate
-- so you can s:tonumber()
string.tonumber = tonumber
-- python-style string formatting with %
getmetatable("").__mod = function(lhs, rhs)
if type(rhs) == "table" then
return lhs:format(unpack(rhs))
else
return lhs:gsub('%%', '%%%%'):gsub('%%%%', '%%', 1):format(rhs)
end
end
-- string... split(string, pattern. max) - break up string on pattern
-- default value for pattern is to split on whitespace
-- default value for max is infinity
function string.split(s, pat, max)
pat = pat or "%s+"
max = max or nil
local count = 0
local i = 1
local result = { 1 }
local function splitter(sof, eof)
result[#result] = s:sub(result[#result], sof-1)
result[#result+1] = eof
end
if pat == "" then return s end
s:gsub("()"..pat.."()", splitter, max)
result[#result] = s:sub(result[#result], #s)
return unpack(result)
end
-- string trim(string) - remove whitespace from start and end
function string.trim(s)
return s:gsub('^%s*', ''):gsub('%s*$', '')
end
-- string join(seperator, ...) - concatenate strings
function string.join(joiner, ...)
return table.concat({...}, joiner)
end
-- rfind - as string.find() only backwards
function string.rfind (s, pattern, rinit, plain)
-- if rinit is set, we basically trim the last rinit characters from the string
s = s:sub(rinit, -1)
local old_R = {}
local R = { s:find(pattern, 1, plain) }
while true do
if R[1] == nil then return unpack(old_R) end
old_R,R = R,{ s:find(pattern, R[2]+1) }
end
end
-- count - count the number of occurences of a regex
function string.count(s, pattern)
local count = 0
for match in s:gmatch(pattern) do
count = count+1
end
return count
end
-- string.interpolate - take a string with $(...) interpolation expressions in it,
-- and a table of stuff to resolve them in terms of
function string.interpolate(str, data, seeall)
local oldmt
if seeall then
oldmt = getmetatable(data)
setmetatable(data, { __index = getfenv(2) })
end
local function do_interp(key)
key = key:sub(2,-2)
local format = key:match([[|([^|'"%]%[]*)$]])
if format then
key = key:gsub([[|[^|'"%]%[]*$]], "")
end
local sfn = "return "..key
sfn = sfn:interpolate(data)
local fn = setfenv(assert(loadstring(sfn)), data)
if format then
return regex:format(fn())
end
return tostring(fn())
end
local count
repeat
str,count = str:gsub('%$(%b())', do_interp)
until count == 0
if seeall then
setmetatable(data, oldmt)
end
return str
end
|
-- new string-related functions, all of them placed in table string
-- and thus callable with str:foo()
-- split, trim, join, rfind, count, interpolate
-- so you can s:tonumber()
string.tonumber = tonumber
-- python-style string formatting with %
getmetatable("").__mod = function(lhs, rhs)
if type(rhs) == "table" then
return lhs:format(unpack(rhs))
else
return lhs:gsub('%%', '%%%%'):gsub('%%%%', '%%', 1):format(rhs)
end
end
-- string... split(string, pattern. max) - break up string on pattern
-- default value for pattern is to split on whitespace
-- default value for max is infinity
function string.split(s, pat, max)
pat = pat or "%s+"
max = max or nil
local count = 0
local i = 1
local result = { 1 }
local function splitter(sof, eof)
result[#result] = s:sub(result[#result], sof-1)
result[#result+1] = eof
end
if pat == "" then return s end
s:gsub("()"..pat.."()", splitter, max)
result[#result] = s:sub(result[#result], #s)
return unpack(result)
end
-- string trim(string) - remove whitespace from start and end
function string.trim(s)
return s:gsub('^%s*', ''):gsub('%s*$', '')
end
-- string join(seperator, ...) - concatenate strings
function string.join(joiner, ...)
return table.concat({...}, joiner)
end
-- rfind - as string.find() only backwards
function string.rfind (s, pattern, rinit, plain)
-- if rinit is set, we basically trim the last rinit characters from the string
s = s:sub(rinit, -1)
local old_R = {}
local R = { s:find(pattern, 1, plain) }
while true do
if R[1] == nil then return unpack(old_R) end
old_R,R = R,{ s:find(pattern, R[2]+1) }
end
end
-- count - count the number of occurences of a regex
function string.count(s, pattern)
local count = 0
for match in s:gmatch(pattern) do
count = count+1
end
return count
end
-- string.interpolate - take a string with ${...} interpolation expressions in it,
-- and a table of stuff to resolve them in terms of
function string.interpolate(str, data, seeall)
local oldmt
if seeall then
oldmt = getmetatable(data)
setmetatable(data, { __index = getfenv(2) })
end
local function do_interp(key)
key = key:sub(2,-2)
local format = key:match([[|([^|'"%]%[]*)$]])
if format then
key = key:gsub([[|[^|'"%]%[]*$]], "")
end
local sfn = "return "..key
sfn = sfn:interpolate(data)
local fn = assert(load(sfn, "generated interpolator", "t", data))
if format then
return format:format(fn())
end
return tostring(fn())
end
local count
repeat
str,count = str:gsub('%$(%b{})', do_interp)
until count == 0
if seeall then
setmetatable(data, oldmt)
end
return str
end
|
Fix string.interpolate for 5.2
|
Fix string.interpolate for 5.2
|
Lua
|
mit
|
ToxicFrog/luautil
|
edf6ab65633d9d807000acb882ec4ad0df5a42af
|
npc/base/talk.lua
|
npc/base/talk.lua
|
--- Base NPC script for talking NPCs
--
-- This script offers all functions needed to get NPCs to talk.
--
-- Author: Martin Karing
-- $Id$
require("base.common")
require("base.messages")
require("base.class")
require("npc.base.basic")
module("npc.base.talk", package.seeall)
talkNPC = base.class.class(function(self, rootNPC)
if (rootNPC == nil or not rootNPC:is_a(npc.base.basic.baseNPC)) then
return;
end;
self["_parent"] = rootNPC;
self["_entry"] = nil;
self["_cycleText"] = nil;
self["_state"] = 0;
self["_saidNumber"] = nil;
self["_nextCycleText"] = -1;
end);
function talkNPC:addCycleText(germanText, englishText)
if (self._cycleText == nil) then
self._cycleText = base.messages.Messages();
self._parent:addCycle(self);
end;
self._cycleText:addMessage(germanText, englishText);
end;
function talkNPC:addTalkingEntry(newEntry)
if (newEntry == nil or not newEntry:is_a(talkNPCEntry)) then
return;
end;
if (self._entry == nil) then
self._parent:addRecvText(self);
self._entry = {};
end;
newEntry:setParent(self);
table.insert(self._entry, newEntry);
end;
function talkNPC:receiveText(player, text)
local result = false;
table.foreach(self._entry, function(_, entry)
if entry:checkEntry(player, text) then
entry:execute(player);
result = true;
return true;
end;
end);
return result;
end;
function talkNPC:nextCycle(counter)
if (counter >= self._nextCycleText) then
self._nextCycleText = math.random(900, 3000);
local german, english = self._cycleText:getRandomMessage();
thisNPC:talkLanguage(CCharacter.say, CPlayer.german, german);
thisNPC:talkLanguage(CCharacter.say, CPlayer.english, english);
else
self._nextCycleText = self._nextCycleText - counter;
end;
return self._nextCycleText;
end;
talkNPCEntry = base.class.class(function(self)
self["_trigger"] = {};
self["_conditions"] = {};
self["_responses"] = {};
self["_responsesCount"] = 0;
self["_consequences"] = {};
self["_parent"] = nil;
end);
function talkNPCEntry:addTrigger(text)
if (text == nil or type(text) ~= "string") then
return;
end;
text = string.lower(text);
table.insert(self._trigger, text);
end;
function talkNPCEntry:setParent(npc)
local updateFkt = function(_, value)
value:setNPC(npc);
end;
table.foreach(self._conditions, updateFkt);
table.foreach(self._consequences, updateFkt);
self._parent = npc;
end;
function talkNPCEntry:addCondition(condition)
if (condition == nil or not condition:is_a(npc.base.condition.condition.condition)) then
return;
end;
if (self._parent ~= nil) then
condition:setNPC(self._parent);
end;
table.insert(self._conditions, condition);
end;
function talkNPCEntry:addResponse(text)
if (text == nil or type(text) ~= "string") then
return;
end;
table.insert(self._responses, text);
self._responsesCount = self._responsesCount + 1;
end;
function talkNPCEntry:addConsequence(consequence)
if (consequence == nil or not consequence:is_a(npc.base.consequence.consequence.consequence)) then
return;
end;
if (self._parent ~= nil) then
consequence:setNPC(self._parent);
end;
table.insert(self._consequences, consequence);
end;
function talkNPCEntry:checkEntry(player, text)
for _1, pattern in pairs(self._trigger) do
local a, _2, number = string.find(text, pattern);
self._saidNumber = number;
if (a ~= nil) then
local conditionsResult = true;
for _3, condition in pairs(self._conditions) do
if not condition:check(player) then
conditionsResult = false;
break;
end;
end;
if conditionsResult then
return true;
end;
end;
end;
end;
function talkNPCEntry:execute(player)
if (self._responsesCount > 0) then
local selectedResponse = math.random(1, self._responsesCount);
thisNPC:talk(CCharacter.say, self._responses[selectedResponse]);
end;
table.foreach(self._consequences, function(_, consequence)
consequence:perform(player);
end);
end;
function _set_value(value)
if (type(value) == "function") then
return value, 2;
elseif (value == "%NUMBER") then
return nil, 1;
else
return tonumber(value), 0;
end;
end;
function _get_value(npc, value, type)
if (type == 2) then
return value(npc._saidNumber);
elseif (type == 1) then
return npc._saidNumber;
elseif (type == 0) then
return value;
else
return 0;
end;
end;
|
--- Base NPC script for talking NPCs
--
-- This script offers all functions needed to get NPCs to talk.
--
-- Author: Martin Karing
-- $Id$
require("base.common")
require("base.messages")
require("base.class")
require("npc.base.basic")
module("npc.base.talk", package.seeall)
talkNPC = base.class.class(function(self, rootNPC)
if (rootNPC == nil or not rootNPC:is_a(npc.base.basic.baseNPC)) then
return;
end;
self["_parent"] = rootNPC;
self["_entry"] = nil;
self["_cycleText"] = nil;
self["_state"] = 0;
self["_saidNumber"] = nil;
self["_nextCycleText"] = -1;
end);
function talkNPC:addCycleText(germanText, englishText)
if (self._cycleText == nil) then
self._cycleText = base.messages.Messages();
self._parent:addCycle(self);
end;
self._cycleText:addMessage(germanText, englishText);
end;
function talkNPC:addTalkingEntry(newEntry)
if (newEntry == nil or not newEntry:is_a(talkNPCEntry)) then
return;
end;
if (self._entry == nil) then
self._parent:addRecvText(self);
self._entry = {};
end;
newEntry:setParent(self);
table.insert(self._entry, newEntry);
end;
function talkNPC:receiveText(player, text)
local result = false;
table.foreach(self._entry, function(_, entry)
if entry:checkEntry(player, text) then
entry:execute(player);
result = true;
return true;
end;
end);
return result;
end;
function talkNPC:nextCycle(counter)
if (counter >= self._nextCycleText) then
self._nextCycleText = math.random(900, 3000);
local german, english = self._cycleText:getRandomMessage();
thisNPC:talkLanguage(CCharacter.say, CPlayer.german, german);
thisNPC:talkLanguage(CCharacter.say, CPlayer.english, english);
else
self._nextCycleText = self._nextCycleText - counter;
end;
return self._nextCycleText;
end;
talkNPCEntry = base.class.class(function(self)
self["_trigger"] = {};
self["_conditions"] = {};
self["_responses"] = {};
self["_responsesCount"] = 0;
self["_consequences"] = {};
self["_parent"] = nil;
end);
function talkNPCEntry:addTrigger(text)
if (text == nil or type(text) ~= "string") then
return;
end;
text = string.lower(text);
table.insert(self._trigger, text);
end;
function talkNPCEntry:setParent(npc)
local updateFkt = function(_, value)
value:setNPC(npc);
end;
table.foreach(self._conditions, updateFkt);
table.foreach(self._consequences, updateFkt);
self._parent = npc;
end;
function talkNPCEntry:addCondition(condition)
if (condition == nil or not condition:is_a(npc.base.condition.condition.condition)) then
return;
end;
table.insert(self._conditions, condition);
if (self._parent ~= nil) then
condition:setNPC(self._parent);
end;
end;
function talkNPCEntry:addResponse(text)
if (text == nil or type(text) ~= "string") then
return;
end;
table.insert(self._responses, text);
self._responsesCount = self._responsesCount + 1;
end;
function talkNPCEntry:addConsequence(consequence)
if (consequence == nil or not consequence:is_a(npc.base.consequence.consequence.consequence)) then
return;
end;
table.insert(self._consequences, consequence);
if (self._parent ~= nil) then
consequence:setNPC(self._parent);
end;
end;
function talkNPCEntry:checkEntry(player, text)
for _1, pattern in pairs(self._trigger) do
local a, _2, number = string.find(text, pattern);
self._saidNumber = number;
if (a ~= nil) then
local conditionsResult = true;
for _3, condition in pairs(self._conditions) do
if not condition:check(player) then
conditionsResult = false;
break;
end;
end;
if conditionsResult then
return true;
end;
end;
end;
end;
function talkNPCEntry:execute(player)
if (self._responsesCount > 0) then
local selectedResponse = math.random(1, self._responsesCount);
thisNPC:talk(CCharacter.say, self._responses[selectedResponse]);
end;
table.foreach(self._consequences, function(_, consequence)
if consequence then
consequence:perform(player);
end;
end);
end;
function _set_value(value)
if (type(value) == "function") then
return value, 2;
elseif (value == "%NUMBER") then
return nil, 1;
else
return tonumber(value), 0;
end;
end;
function _get_value(npc, value, type)
if (type == 2) then
return value(npc._saidNumber);
elseif (type == 1) then
return npc._saidNumber;
elseif (type == 0) then
return value;
else
return 0;
end;
end;
|
Fixing nil bug in talking framework
|
Fixing nil bug in talking framework
|
Lua
|
agpl-3.0
|
KayMD/Illarion-Content,vilarion/Illarion-Content,Illarion-eV/Illarion-Content,LaFamiglia/Illarion-Content,Baylamon/Illarion-Content
|
d073374d74a8189806ec5ec9c597cce8dfc7f2a0
|
core/webserver.lua
|
core/webserver.lua
|
-- vim: set noexpandtab:
local server = require'http.server'
local new_headers = require "http.headers".new
local lconsole = require'logging.console'
local lfs = require'lfs'
local ivar2 = ...
local log = lconsole()
-- Keep this amount in mem before handler has to read from tmpfile
local BODY_BUFFER_SIZE = 2^17
local timeout = 30
local runningserver
local webserver = {}
local respond = function(stream, res, body, code, headers)
if not code then code = '200' end
if not body then body = '' end
if not headers then headers = {} end
for k, v in pairs(headers) do
res:upsert(k, v)
end
res:upsert(":status", tostring(code))
stream:write_headers(res, false, timeout)
stream:write_body_from_string(body, timeout)
end
local handlerNotFound = function(stream, res)
respond(stream, res, 'Nyet. I am four oh four', 404)
end
local handlers = {
['/favicon.ico'] = handlerNotFound
}
webserver.on_stream = function(myserver, stream)
local ok, err = pcall(function()
local headers = stream:get_headers(30)
stream.headers = {}
local path = '/'
--print('tls', stream:checktls())
local _, peer = stream:peername()
--print('local', stream:localname())
local res = new_headers()
if headers then
for k, v in headers:each() do
if k == ':path' then
path = v
stream.url = v -- for compability
elseif k == ':method' then
stream.method = v -- compability
end
stream.headers[k] = v
end
end
-- Check if X-Real-IP is set, and blindly trust it
if stream.headers['x-real-ip'] then
peer = stream.headers['x-real-ip']
end
-- TODO: check content length and decide if needed
local filename
-- Save body into a temp file
if stream.method == 'POST' then
filename = os.tmpname()
stream.filename = filename
local writer = io.open(filename, 'w')
stream:save_body_to_file(writer, 60*10)
writer:flush()
writer:close()
--- TODO os.execute chmod?
local size = lfs.attributes(filename).size
if size < BODY_BUFFER_SIZE then
local fd = io.open(filename, 'r')
stream.body = fd:read('*a')
fd:close()
end
end
local found
log:info('webserver> "%s %s HTTP/%g" "%s" "%s" "%s"\n',
headers:get(":method") or "",
headers:get(":path") or "",
stream.connection.version,
peer,
headers:get("referer") or "-",
headers:get("user-agent") or "-"
)
for pattern, handler in pairs(handlers) do
if path:match(pattern) then
log:debug('webserver> serving handler :%s', pattern)
found = true
local ok, body, code, response_headers = pcall(handler, ivar2, stream, res)
if not ok then
log:error('webserver> error for URL pattern: %s: %s', pattern, body)
else
-- Handlers can also write to stream directly, so check for body
if body and stream.state ~= 'closed' then -- check if not closed
respond(stream, res, body, code, response_headers)
end
-- Assume handler has already sent response.
end
break
end
end
if not found then
log:info('webserver> returning 404 for request: %s', path)
handlerNotFound(stream, res)
end
if filename then
log:debug('webserver> deleting tmp file: %s', filename)
os.remove(filename)
end
stream:shutdown()
end)
if not ok then
log:error('webserver> error: req %s, err %s', stream, err)
end
end
webserver.start = function(host, port, cq)
if not (host and port) then
return
end
log:info('webserver> starting webserver: %s:%s', host, port)
runningserver = server.listen{
host = host,
port = port,
onstream = webserver.on_stream,
cq = cq,
onerror = function(myserver, context, op, err, errno)
if op == "onstream" and err == 32 then return end
local msg = op .. " on " .. tostring(context) .. " failed"
if err then
msg = msg .. ": " .. tostring(err)
end
log:error('webserver> %s', msg)
end;
}
return runningserver
end
webserver.stop = function()
if(not runningserver) then return end
log:info('webserver> stopping webserver.')
runningserver:close()
end
webserver.regUrl = function(pattern, handler)
log:info('webserver> registering new handler for URL pattern: %s', pattern)
handlers[pattern] = handler
end
webserver.unRegUrl = function(pattern)
log:info('webserver> unregistering handler for URL pattern: %s', pattern)
handlers[pattern] = nil
end
return webserver
|
-- vim: set noexpandtab:
local server = require'http.server'
local new_headers = require "http.headers".new
local lconsole = require'logging.console'
local lfs = require'lfs'
local ivar2 = ...
local log = lconsole()
-- Keep this amount in mem before handler has to read from tmpfile
local BODY_BUFFER_SIZE = 2^17
local timeout = 30
local runningserver
local webserver = {}
local respond = function(stream, res, body, code, headers)
-- don't try to write to idle stream
if stream.state == 'idle' then
return
end
if not code then code = '200' end
if not body then body = '' end
if not headers then headers = {} end
for k, v in pairs(headers) do
res:upsert(k, v)
end
res:upsert(":status", tostring(code))
stream:write_headers(res, false, timeout)
stream:write_body_from_string(body, timeout)
end
local handlerNotFound = function(stream, res)
respond(stream, res, 'Nyet. I am four oh four', 404)
end
local handlers = {
['/favicon.ico'] = handlerNotFound
}
webserver.on_stream = function(myserver, stream)
local ok, err = pcall(function()
local headers = stream:get_headers(30)
stream.headers = {}
local path = '/'
--print('tls', stream:checktls())
local _, peer = stream:peername()
--print('local', stream:localname())
local res = new_headers()
if headers then
for k, v in headers:each() do
if k == ':path' then
path = v
stream.url = v -- for compability
elseif k == ':method' then
stream.method = v -- compability
end
stream.headers[k] = v
end
end
-- Check if X-Real-IP is set, and blindly trust it
if stream.headers['x-real-ip'] then
peer = stream.headers['x-real-ip']
end
-- TODO: check content length and decide if needed
local filename
-- Save body into a temp file
if stream.method == 'POST' then
filename = os.tmpname()
stream.filename = filename
local writer = io.open(filename, 'w')
stream:save_body_to_file(writer, 60*10)
writer:flush()
writer:close()
--- TODO os.execute chmod?
local size = lfs.attributes(filename).size
if size < BODY_BUFFER_SIZE then
local fd = io.open(filename, 'r')
stream.body = fd:read('*a')
fd:close()
end
end
local found
if headers then
log:info('webserver> "%s %s HTTP/%g" "%s" "%s" "%s"\n',
headers:get(":method") or "",
headers:get(":path") or "",
stream.connection.version,
peer,
headers:get("referer") or "-",
headers:get("user-agent") or "-"
)
end
for pattern, handler in pairs(handlers) do
if path:match(pattern) then
log:debug('webserver> serving handler :%s', pattern)
found = true
local ok, body, code, response_headers = pcall(handler, ivar2, stream, res)
if not ok then
log:error('webserver> error for URL pattern: %s: %s', pattern, body)
else
-- Handlers can also write to stream directly, so check for body
if body and stream.state ~= 'closed' then -- check if not closed
respond(stream, res, body, code, response_headers)
end
-- Assume handler has already sent response.
end
break
end
end
if not found then
log:info('webserver> returning 404 for request: %s', path)
handlerNotFound(stream, res)
end
if filename then
log:debug('webserver> deleting tmp file: %s', filename)
os.remove(filename)
end
stream:shutdown()
end)
if not ok then
log:error('webserver> error: req %s, err %s', stream, err)
end
end
webserver.start = function(host, port, cq)
if not (host and port) then
return
end
log:info('webserver> starting webserver: %s:%s', host, port)
runningserver = server.listen{
host = host,
port = port,
onstream = webserver.on_stream,
cq = cq,
onerror = function(myserver, context, op, err, errno)
if op == "onstream" and err == 32 then return end
local msg = op .. " on " .. tostring(context) .. " failed"
if err then
msg = msg .. ": " .. tostring(err)
end
log:error('webserver> %s', msg)
end;
}
return runningserver
end
webserver.stop = function()
if(not runningserver) then return end
log:info('webserver> stopping webserver.')
runningserver:close()
end
webserver.regUrl = function(pattern, handler)
log:info('webserver> registering new handler for URL pattern: %s', pattern)
handlers[pattern] = handler
end
webserver.unRegUrl = function(pattern)
log:info('webserver> unregistering handler for URL pattern: %s', pattern)
handlers[pattern] = nil
end
return webserver
|
webserver: fix bug
|
webserver: fix bug
|
Lua
|
mit
|
torhve/ivar2,torhve/ivar2,torhve/ivar2
|
d124c7e290de49d382d1ee7a663eeb293c1b1aec
|
editor/lib/lua/editor/classes/AssimpMesh.lua
|
editor/lib/lua/editor/classes/AssimpMesh.lua
|
local BaseMesh = require("classes.BaseMesh")
---------------------------------------------------------------------------------
--
-- @type AssimpMesh
--
---------------------------------------------------------------------------------
local AssimpMesh = Class(BaseMesh, "AssimpMesh")
function AssimpMesh:init( size, texture )
BaseMesh.init( self )
self._size = size or 256
self._texture = texture or ''
self._bones = {}
end
---------------------------------------------------------------------------------
function AssimpMesh:setLightNode( node )
local useBakeLight = node.GetBakeLight( node )
local diffusePower = node.GetDiffusePower( node )
local ambientLight = node.GetAmbientLight( node )
local lightDirection = node.GetLightDirection( node )
self.useBakeLight = useBakeLight
self.diffusePower = diffusePower
self.ambientLight = { ambientLight[0], ambientLight[1], ambientLight[2], ambientLight[3] }
self.lightDirection = { lightDirection[0], lightDirection[1], lightDirection[2] }
end
function AssimpMesh:luminosity(r, g, b)
local light = self.ambientLight
return light[1] * r + light[2] * g + light[3] * b
end
---------------------------------------------------------------------------------
function AssimpMesh:setNode( node )
local sz = self._size
self.name = node.name
local vertexFormat = MOAIVertexFormat.new()
vertexFormat:declareCoord( 1, MOAIVertexFormat.GL_FLOAT, 3 )
vertexFormat:declareUV( 2, MOAIVertexFormat.GL_FLOAT, 2 )
vertexFormat:declareColor( 3, MOAIVertexFormat.GL_UNSIGNED_BYTE )
self.vertexFormat = vertexFormat
local vbo = MOAIVertexBuffer.new ()
self.vbo = vbo
local ibo = MOAIIndexBuffer.new ()
self.ibo = ibo
local vtxCount = node.verticesCount
local idxCount = 3 * node.facesCount
self.idxCount = idxCount
ibo:setIndexSize ( 4 )
ibo:reserve ( idxCount * 4 )
print(self.name, "vtxCount", vtxCount)
vbo:reserve ( vtxCount * vertexFormat:getVertexSize ())
for i = 0, vtxCount - 1 do
local vtx = node.vertices [ i ]
local uv = node.texturecoords [ 0 ][ i ]
vbo:writeFloat ( sz * vtx [ 0 ], sz * vtx [ 1 ], sz * vtx [ 2 ])
vbo:writeFloat ( uv [ 0 ], uv [ 1 ])
if self.useBakeLight then
local n = node.normals [ i ]
local ambient = self.ambientLight
local diffuse = self.diffusePower
local luma = math.max(0, self:luminosity ( n [ 0 ], n [ 1 ], n [ 2 ]))
local r = math.min ( 1, ambient [ 1 ] + diffuse * luma )
local g = math.min ( 1, ambient [ 2 ] + diffuse * luma )
local b = math.min ( 1, ambient [ 3 ] + diffuse * luma )
-- vbo:writeColor32 ( 0.5 + 0.5 * n [ 0 ], 0.5 + 0.5 * n [ 1 ], 0.5 + 0.5 * n [ 2 ], 1 )
vbo:writeColor32 ( r, g, b, 1 )
else
vbo:writeColor32 ( 1, 1, 1, 1 )
end
end
for face in python.iter ( node.faces ) do
local sz = sizeOfPythonObject(face)
if sz >= 3 then
ibo:writeU32 ( face [ 0 ], face [ 1 ], face [ 2 ])
else
print("AssimpMesh: FACE is BROKEN!")
end
end
local bones = {}
for bname in python.iter ( node.bonesNames ) do
table.insert(bones, bname)
end
self._bones = bones
local mid = node.materialID
self._materialID = mid
end
---------------------------------------------------------------------------------
function AssimpMesh:createMesh ( option )
local option = option or {}
local vbo = self.vbo
local ibo = self.ibo
local vertexFormat = self.vertexFormat
local mesh = MOAIMesh.new ()
mesh:setVertexBuffer( vbo, vertexFormat )
mesh:setIndexBuffer ( ibo )
mesh:setPrimType ( MOAIMesh.GL_TRIANGLES )
mesh:setShader ( MOAIShaderMgr.getShader( MOAIShaderMgr.MESH_SHADER ) )
mesh:setTotalElements ( self.idxCount )
mesh:setBounds( vbo:computeBounds( vertexFormat ) )
local textureName = self:getTexture()
if textureName then
local texture = ResourceMgr:getTexture( textureName )
mesh:setTexture ( texture )
end
if option.exportBones then
mesh._bones = self._bones
end
if option.exportMaterialID then
mesh._materialID = self._materialID
end
if option.exportBuffers then
mesh._vbo = vbo
mesh._ibo = ibo
end
self.canSave = option.exportMesh
self.mesh = mesh
end
---------------------------------------------------------------------------------
function AssimpMesh:getTexture()
local textureName = self._texture
if not textureName or textureName == '' then
local textureName = self._texturePath
if not textureName then
textureName = editorAssetPath( 'grid.png')
end
end
return textureName
end
---------------------------------------------------------------------------------
return AssimpMesh
|
local BaseMesh = require("classes.BaseMesh")
---------------------------------------------------------------------------------
--
-- @type AssimpMesh
--
---------------------------------------------------------------------------------
local AssimpMesh = Class(BaseMesh, "AssimpMesh")
function AssimpMesh:init( size, texture )
BaseMesh.init( self )
self._size = size or 256
self._texture = texture or ''
self._bones = {}
end
---------------------------------------------------------------------------------
function AssimpMesh:setLightNode( node )
local useBakeLight = node.GetBakeLight( node )
local diffusePower = node.GetDiffusePower( node )
local ambientLight = node.GetAmbientLight( node )
local lightDirection = node.GetLightDirection( node )
self.useBakeLight = useBakeLight
self.diffusePower = diffusePower
self.ambientLight = { ambientLight[0], ambientLight[1], ambientLight[2], ambientLight[3] }
self.lightDirection = { lightDirection[0], lightDirection[1], lightDirection[2] }
end
function AssimpMesh:luminosity(r, g, b)
local light = self.ambientLight
return light[1] * r + light[2] * g + light[3] * b
end
---------------------------------------------------------------------------------
function AssimpMesh:setNode( node )
local sz = self._size
self.name = node.name
local vertexFormat = MOAIVertexFormat.new()
vertexFormat:declareCoord( 1, MOAIVertexFormat.GL_FLOAT, 3 )
vertexFormat:declareUV( 2, MOAIVertexFormat.GL_FLOAT, 2 )
vertexFormat:declareColor( 3, MOAIVertexFormat.GL_UNSIGNED_BYTE )
self.vertexFormat = vertexFormat
local vbo = MOAIVertexBuffer.new ()
self.vbo = vbo
local ibo = MOAIIndexBuffer.new ()
self.ibo = ibo
local vtxCount = node.verticesCount
local idxCount = 3 * node.facesCount
self.idxCount = idxCount
ibo:setIndexSize ( 4 )
ibo:reserve ( idxCount * 4 )
print(self.name, "vtxCount", vtxCount)
vbo:reserve ( vtxCount * vertexFormat:getVertexSize ())
for i = 0, vtxCount - 1 do
local vtx = node.vertices [ i ]
local uv = node.texturecoords [ 0 ][ i ]
vbo:writeFloat ( sz * vtx [ 0 ], sz * vtx [ 1 ], sz * vtx [ 2 ])
vbo:writeFloat ( uv [ 0 ], uv [ 1 ])
if self.useBakeLight then
local n = node.normals [ i ]
local ambient = self.ambientLight
local diffuse = self.diffusePower
local luma = math.max(0, self:luminosity ( n [ 0 ], n [ 1 ], n [ 2 ]))
local r = math.min ( 1, ambient [ 1 ] + diffuse * luma )
local g = math.min ( 1, ambient [ 2 ] + diffuse * luma )
local b = math.min ( 1, ambient [ 3 ] + diffuse * luma )
-- vbo:writeColor32 ( 0.5 + 0.5 * n [ 0 ], 0.5 + 0.5 * n [ 1 ], 0.5 + 0.5 * n [ 2 ], 1 )
vbo:writeColor32 ( r, g, b, 1 )
else
vbo:writeColor32 ( 1, 1, 1, 1 )
end
end
for face in python.iter ( node.faces ) do
local sz = sizeOfPythonObject(face)
if sz >= 3 then
ibo:writeU32 ( face [ 0 ], face [ 1 ], face [ 2 ])
else
print("AssimpMesh: FACE is BROKEN!")
end
end
local bones = {}
for bname in python.iter ( node.bonesNames ) do
table.insert(bones, bname)
end
self._bones = bones
self._materialID = node.materialID
end
---------------------------------------------------------------------------------
function AssimpMesh:createMesh ( option )
local option = option or {}
local vbo = self.vbo
local ibo = self.ibo
local vertexFormat = self.vertexFormat
local mesh = MOAIMesh.new ()
mesh:setVertexBuffer( vbo, vertexFormat )
mesh:setIndexBuffer ( ibo )
mesh:setPrimType ( MOAIMesh.GL_TRIANGLES )
mesh:setShader ( MOAIShaderMgr.getShader( MOAIShaderMgr.MESH_SHADER ) )
mesh:setTotalElements ( self.idxCount )
mesh:setBounds( vbo:computeBounds( vertexFormat ) )
local textureName = self:getTexture()
if textureName then
mesh.textureName = textureName
local texture = ResourceMgr:getTexture( textureName )
mesh:setTexture ( texture )
end
if option.exportBones then
mesh._bones = self._bones
end
if option.exportMaterialID then
mesh._materialID = self._materialID
end
if option.exportBuffers then
mesh._vbo = vbo
mesh._ibo = ibo
end
self.canSave = option.exportMesh
self.mesh = mesh
end
---------------------------------------------------------------------------------
function AssimpMesh:getTexture()
local textureName = self._texture
if not textureName or textureName == '' then
local textureName = self._texturePath
if not textureName then
textureName = editorAssetPath( 'grid.png')
end
end
return textureName
end
---------------------------------------------------------------------------------
return AssimpMesh
|
fix mesh
|
fix mesh
|
Lua
|
mit
|
cloudteampro/juma-editor,cloudteampro/juma-editor,RazielSun/juma-editor,cloudteampro/juma-editor,RazielSun/juma-editor,RazielSun/juma-editor,RazielSun/juma-editor,cloudteampro/juma-editor
|
320a608c36b551edd16a488d3761719d5ef8aeb1
|
service/datacenterd.lua
|
service/datacenterd.lua
|
local skynet = require "skynet"
local command = {}
local database = {}
local wait_queue = {}
local mode = {}
local function query(db, key, ...)
if key == nil then
return db
else
return query(db[key], ...)
end
end
function command.QUERY(key, ...)
local d = database[key]
if d then
return query(d, ...)
end
end
local function update(db, key, value, ...)
if select("#",...) == 0 then
local ret = db[key]
db[key] = value
return ret, value
else
if db[key] == nil then
db[key] = {}
end
return update(db[key], value, ...)
end
end
local function wakeup(db, key1, key2, ...)
if key1 == nil then
return
end
local q = db[key1]
if q == nil then
return
end
if q[mode] == "queue" then
db[key1] = nil
if key2 then
-- throw error because can't wake up a branch
for _,response in ipairs(q) do
response(false)
end
else
return q
end
else
-- it's branch
return wakeup(q , key2, ...)
end
end
function command.UPDATE(...)
local ret, value = update(database, ...)
if ret or value == nil then
return ret
end
local q = wakeup(wait_queue, ...)
if q then
for _, response in ipairs(q) do
response(true,value)
end
end
end
local function waitfor(db, key1, key2, ...)
if key2 == nil then
-- push queue
local q = db[key1]
if q == nil then
q = { [mode] = "queue" }
db[key1] = q
else
assert(q[mode] == "queue")
end
table.insert(q, skynet.response())
else
local q = db[key1]
if q == nil then
q = { [mode] = "branch" }
db[key1] = q
else
assert(q[mode] == "branch")
end
return waitfor(q, key2, ...)
end
end
skynet.start(function()
skynet.dispatch("lua", function (_, _, cmd, ...)
if cmd == "WAIT" then
local ret = command.QUERY(...)
if ret then
skynet.ret(skynet.pack(ret))
else
waitfor(wait_queue, ...)
end
else
local f = assert(command[cmd])
skynet.ret(skynet.pack(f(...)))
end
end)
end)
|
local skynet = require "skynet"
local command = {}
local database = {}
local wait_queue = {}
local mode = {}
local function query(db, key, ...)
if key == nil then
return db
else
return query(db[key], ...)
end
end
function command.QUERY(key, ...)
local d = database[key]
if d then
return query(d, ...)
end
end
local function update(db, key, value, ...)
if select("#",...) == 0 then
local ret = db[key]
db[key] = value
return ret, value
else
if db[key] == nil then
db[key] = {}
end
return update(db[key], value, ...)
end
end
local function wakeup(db, key1, ...)
if key1 == nil then
return
end
local q = db[key1]
if q == nil then
return
end
if q[mode] == "queue" then
db[key1] = nil
if select("#", ...) ~= 1 then
-- throw error because can't wake up a branch
for _,response in ipairs(q) do
response(false)
end
else
return q
end
else
-- it's branch
return wakeup(q , ...)
end
end
function command.UPDATE(...)
local ret, value = update(database, ...)
if ret or value == nil then
return ret
end
local q = wakeup(wait_queue, ...)
if q then
for _, response in ipairs(q) do
response(true,value)
end
end
end
local function waitfor(db, key1, key2, ...)
if key2 == nil then
-- push queue
local q = db[key1]
if q == nil then
q = { [mode] = "queue" }
db[key1] = q
else
assert(q[mode] == "queue")
end
table.insert(q, skynet.response())
else
local q = db[key1]
if q == nil then
q = { [mode] = "branch" }
db[key1] = q
else
assert(q[mode] == "branch")
end
return waitfor(q, key2, ...)
end
end
skynet.start(function()
skynet.dispatch("lua", function (_, _, cmd, ...)
if cmd == "WAIT" then
local ret = command.QUERY(...)
if ret then
skynet.ret(skynet.pack(ret))
else
waitfor(wait_queue, ...)
end
else
local f = assert(command[cmd])
skynet.ret(skynet.pack(f(...)))
end
end)
end)
|
bugfix: datacenter.wait
|
bugfix: datacenter.wait
|
Lua
|
mit
|
plsytj/skynet,bingo235/skynet,KittyCookie/skynet,microcai/skynet,boyuegame/skynet,hongling0/skynet,LiangMa/skynet,ruleless/skynet,MetSystem/skynet,boyuegame/skynet,korialuo/skynet,xinmingyao/skynet,samael65535/skynet,lc412/skynet,Markal128/skynet,hongling0/skynet,LuffyPan/skynet,plsytj/skynet,your-gatsby/skynet,great90/skynet,dymx101/skynet,javachengwc/skynet,liuxuezhan/skynet,leezhongshan/skynet,yunGit/skynet,cmingjian/skynet,bttscut/skynet,ypengju/skynet_comment,asanosoyokaze/skynet,kyle-wang/skynet,great90/skynet,matinJ/skynet,MetSystem/skynet,chuenlungwang/skynet,zhoukk/skynet,harryzeng/skynet,Ding8222/skynet,lawnight/skynet,KAndQ/skynet,pichina/skynet,zzh442856860/skynet,MoZhonghua/skynet,QuiQiJingFeng/skynet,korialuo/skynet,pigparadise/skynet,KAndQ/skynet,wangjunwei01/skynet,vizewang/skynet,JiessieDawn/skynet,ludi1991/skynet,xinjuncoding/skynet,vizewang/skynet,iskygame/skynet,dymx101/skynet,firedtoad/skynet,jxlczjp77/skynet,zhoukk/skynet,wangyi0226/skynet,LuffyPan/skynet,fhaoquan/skynet,xjdrew/skynet,icetoggle/skynet,lc412/skynet,Ding8222/skynet,pigparadise/skynet,harryzeng/skynet,nightcj/mmo,chuenlungwang/skynet,letmefly/skynet,MRunFoss/skynet,sanikoyes/skynet,sundream/skynet,winglsh/skynet,rainfiel/skynet,longmian/skynet,czlc/skynet,zzh442856860/skynet,chfg007/skynet,ruleless/skynet,chuenlungwang/skynet,jiuaiwo1314/skynet,xinjuncoding/skynet,plsytj/skynet,enulex/skynet,wangyi0226/skynet,cdd990/skynet,rainfiel/skynet,lawnight/skynet,KAndQ/skynet,bttscut/skynet,longmian/skynet,firedtoad/skynet,xinmingyao/skynet,enulex/skynet,Zirpon/skynet,ypengju/skynet_comment,lawnight/skynet,puXiaoyi/skynet,catinred2/skynet,felixdae/skynet,hongling0/skynet,fztcjjl/skynet,bingo235/skynet,zhaijialong/skynet,cuit-zhaxin/skynet,samael65535/skynet,wangjunwei01/skynet,cuit-zhaxin/skynet,kebo/skynet,zhoukk/skynet,catinred2/skynet,zhaijialong/skynet,chenjiansnail/skynet,MoZhonghua/skynet,helling34/skynet,pigparadise/skynet,kyle-wang/skynet,cmingjian/skynet,harryzeng/skynet,ilylia/skynet,microcai/skynet,chenjiansnail/skynet,felixdae/skynet,lc412/skynet,xinjuncoding/skynet,cpascal/skynet,nightcj/mmo,sdgdsffdsfff/skynet,zzh442856860/skynet-Note,ag6ag/skynet,ruleless/skynet,cdd990/skynet,asanosoyokaze/skynet,matinJ/skynet,MRunFoss/skynet,leezhongshan/skynet,zzh442856860/skynet-Note,letmefly/skynet,cloudwu/skynet,JiessieDawn/skynet,zhangshiqian1214/skynet,zhouxiaoxiaoxujian/skynet,Zirpon/skynet,puXiaoyi/skynet,bttscut/skynet,ag6ag/skynet,leezhongshan/skynet,zzh442856860/skynet-Note,u20024804/skynet,Zirpon/skynet,zhouxiaoxiaoxujian/skynet,cuit-zhaxin/skynet,zhouxiaoxiaoxujian/skynet,zzh442856860/skynet-Note,your-gatsby/skynet,u20024804/skynet,cloudwu/skynet,fhaoquan/skynet,jiuaiwo1314/skynet,lawnight/skynet,xcjmine/skynet,togolwb/skynet,liuxuezhan/skynet,kyle-wang/skynet,lynx-seu/skynet,pichina/skynet,zzh442856860/skynet,ludi1991/skynet,helling34/skynet,yinjun322/skynet,xjdrew/skynet,sundream/skynet,u20024804/skynet,puXiaoyi/skynet,liuxuezhan/skynet,kebo/skynet,zhangshiqian1214/skynet,catinred2/skynet,cloudwu/skynet,ypengju/skynet_comment,QuiQiJingFeng/skynet,samael65535/skynet,great90/skynet,dymx101/skynet,icetoggle/skynet,wangjunwei01/skynet,sanikoyes/skynet,cdd990/skynet,liuxuezhan/skynet,javachengwc/skynet,felixdae/skynet,chenjiansnail/skynet,letmefly/skynet,bigrpg/skynet,zhaijialong/skynet,sdgdsffdsfff/skynet,matinJ/skynet,KittyCookie/skynet,longmian/skynet,icetoggle/skynet,cpascal/skynet,codingabc/skynet,ilylia/skynet,togolwb/skynet,fhaoquan/skynet,yinjun322/skynet,xcjmine/skynet,Ding8222/skynet,iskygame/skynet,ludi1991/skynet,lynx-seu/skynet,jiuaiwo1314/skynet,ilylia/skynet,korialuo/skynet,Markal128/skynet,togolwb/skynet,ludi1991/skynet,zhangshiqian1214/skynet,boyuegame/skynet,JiessieDawn/skynet,microcai/skynet,xcjmine/skynet,chfg007/skynet,bingo235/skynet,your-gatsby/skynet,xubigshu/skynet,LiangMa/skynet,asanosoyokaze/skynet,yunGit/skynet,cpascal/skynet,helling34/skynet,chfg007/skynet,winglsh/skynet,LuffyPan/skynet,lynx-seu/skynet,xubigshu/skynet,MetSystem/skynet,bigrpg/skynet,letmefly/skynet,gitfancode/skynet,zhangshiqian1214/skynet,iskygame/skynet,ag6ag/skynet,firedtoad/skynet,zhangshiqian1214/skynet,xjdrew/skynet,czlc/skynet,czlc/skynet,MoZhonghua/skynet,MRunFoss/skynet,nightcj/mmo,sdgdsffdsfff/skynet,rainfiel/skynet,cmingjian/skynet,KittyCookie/skynet,javachengwc/skynet,codingabc/skynet,fztcjjl/skynet,codingabc/skynet,fztcjjl/skynet,yunGit/skynet,winglsh/skynet,gitfancode/skynet,kebo/skynet,jxlczjp77/skynet,jxlczjp77/skynet,yinjun322/skynet,sanikoyes/skynet,zhangshiqian1214/skynet,QuiQiJingFeng/skynet,vizewang/skynet,Markal128/skynet,bigrpg/skynet,pichina/skynet,sundream/skynet,enulex/skynet,wangyi0226/skynet,gitfancode/skynet,LiangMa/skynet
|
446368a87bd96af5e49595f25e7aeb6d1f94ee85
|
tests/test-callbacks.lua
|
tests/test-callbacks.lua
|
return require('lib/tap')(function (test)
-- Notes:
-- * When using a callable table as a callback, it will get itself as the first param when it is called.
-- This matches what happens when calling the callable table normally.
-- * expect wraps its argument in a function and returns the function, so expect should not be called on
-- a callable table directly.
test("luv_handle_t: function", function (print, p, expect, uv)
local handle = uv.new_timer()
local function onclose()
p("closed", handle)
end
local function ontimeout()
p("timeout", handle)
uv.close(handle, expect(onclose))
end
uv.timer_start(handle, 10, 0, expect(ontimeout))
end)
test("luv_handle_t: callable table", function (print, p, expect, uv)
local handle = uv.new_timer()
local function onclose(self)
p("closed", self, handle)
end
local onCloseTable = setmetatable({}, {__call=expect(onclose)})
local function ontimeout(self)
p("timeout", self, handle)
uv.close(handle, onCloseTable)
end
local onTimeoutTable = setmetatable({}, {__call=expect(ontimeout)})
uv.timer_start(handle, 10, 0, onTimeoutTable)
end)
test("luv_req_t: function", function (print, p, expect, uv)
local fn = function(err, path)
p(err, path)
end
assert(uv.fs_realpath('.', expect(fn)))
end)
test("luv_req_t: callable table", function (print, p, expect, uv)
local fn = function(self, err, path)
p(self, err, path)
end
local callable = setmetatable({}, {__call=expect(fn)})
assert(uv.fs_realpath('.', callable))
end)
end)
|
return require('lib/tap')(function (test)
-- Notes:
-- * When using a callable table as a callback, it will get itself as the first param when it is called.
-- This matches what happens when calling the callable table normally.
-- * expect wraps its argument in a function and returns the function, so expect should not be called on
-- a callable table directly.
test("luv_handle_t: function", function (print, p, expect, uv)
local handle = uv.new_timer()
local function onclose()
p("closed", handle)
end
local function ontimeout()
p("timeout", handle)
uv.close(handle, expect(onclose))
end
uv.timer_start(handle, 10, 0, expect(ontimeout))
end)
test("luv_handle_t: callable table", function (print, p, expect, uv)
local handle = uv.new_timer()
local function onclose(self)
p("closed", self, handle)
end
local onCloseTable = setmetatable({}, {__call=expect(onclose)})
local function ontimeout(self)
p("timeout", self, handle)
uv.close(handle, onCloseTable)
end
local onTimeoutTable = setmetatable({}, {__call=expect(ontimeout)})
uv.timer_start(handle, 10, 0, onTimeoutTable)
end)
test("luv_req_t: function", function (print, p, expect, uv)
local fn = function(err, stat)
assert(not err)
assert(stat)
end
assert(uv.fs_stat('.', expect(fn)))
end)
test("luv_req_t: callable table", function (print, p, expect, uv)
local callable
local fn = function(self, err, stat)
assert(self == callable)
assert(not err, err)
assert(stat)
end
callable = setmetatable({}, {__call=expect(fn)})
assert(uv.fs_stat('.', callable))
end)
end)
|
Fix test-callbacks when using libuv < 1.8.0
|
Fix test-callbacks when using libuv < 1.8.0
|
Lua
|
apache-2.0
|
luvit/luv,zhaozg/luv,zhaozg/luv,luvit/luv
|
ff48a968578bb5d01f3e019c30ad1647e0ee7bc8
|
tools/release_model.lua
|
tools/release_model.lua
|
require('onmt.init')
local path = require('pl.path')
local cmd = torch.CmdLine()
cmd:option('-model', '', 'trained model file')
cmd:option('-output_model', '', 'released model file')
cmd:option('-gpuid', 0, [[1-based identifier of the GPU to use. CPU is used when the option is < 1]])
cmd:option('-force', false, 'force output model creation')
local opt = cmd:parse(arg)
local function main()
assert(path.exists(opt.model), 'model \'' .. opt.model .. '\' does not exist.')
if opt.output_model:len() == 0 then
if opt.model:sub(-3) == '.t7' then
opt.output_model = opt.model:sub(1, -4) -- copy input model without '.t7' extension
else
opt.output_model = opt.model
end
opt.output_model = opt.output_model .. '_release.t7'
end
if not opt.force then
assert(not path.exists(opt.output_model),
'output model already exists; use -force to overwrite.')
end
if opt.gpuid > 0 then
require('cutorch')
cutorch.setDevice(opt.gpuid)
end
print('Loading model \'' .. opt.model .. '\'...')
local checkpoint
local _, err = pcall(function ()
checkpoint = torch.load(opt.model)
end)
if err then
error('unable to load the model (' .. err .. '). If you are releasing a GPU model, it needs to be loaded on the GPU first (set -gpuid > 0)')
end
print('... done.')
print('Converting model...')
for _, model in pairs(checkpoint.models) do
for _, net in pairs(model.modules) do
net:float()
net:clearState()
end
end
print('... done.')
print('Releasing model \'' .. opt.output_model .. '\'...')
torch.save(opt.output_model, checkpoint)
print('... done.')
end
main()
|
require('onmt.init')
local path = require('pl.path')
local cmd = torch.CmdLine()
cmd:option('-model', '', 'trained model file')
cmd:option('-output_model', '', 'released model file')
cmd:option('-gpuid', 0, [[1-based identifier of the GPU to use. CPU is used when the option is < 1]])
cmd:option('-force', false, 'force output model creation')
local opt = cmd:parse(arg)
local function toCPU(model)
for _, submodule in pairs(model.modules) do
if torch.type(submodule) == 'table' and submodule.modules then
toCPU(submodule)
else
submodule:float()
submodule:clearState()
end
end
end
local function main()
assert(path.exists(opt.model), 'model \'' .. opt.model .. '\' does not exist.')
if opt.output_model:len() == 0 then
if opt.model:sub(-3) == '.t7' then
opt.output_model = opt.model:sub(1, -4) -- copy input model without '.t7' extension
else
opt.output_model = opt.model
end
opt.output_model = opt.output_model .. '_release.t7'
end
if not opt.force then
assert(not path.exists(opt.output_model),
'output model already exists; use -force to overwrite.')
end
if opt.gpuid > 0 then
require('cutorch')
cutorch.setDevice(opt.gpuid)
end
print('Loading model \'' .. opt.model .. '\'...')
local checkpoint
local _, err = pcall(function ()
checkpoint = torch.load(opt.model)
end)
if err then
error('unable to load the model (' .. err .. '). If you are releasing a GPU model, it needs to be loaded on the GPU first (set -gpuid > 0)')
end
print('... done.')
print('Converting model...')
for _, model in pairs(checkpoint.models) do
toCPU(model)
end
print('... done.')
print('Releasing model \'' .. opt.output_model .. '\'...')
torch.save(opt.output_model, checkpoint)
print('... done.')
end
main()
|
Fix release model script for BRNN
|
Fix release model script for BRNN
|
Lua
|
mit
|
monsieurzhang/OpenNMT,da03/OpenNMT,jsenellart/OpenNMT,monsieurzhang/OpenNMT,cservan/OpenNMT_scores_0.2.0,jungikim/OpenNMT,jsenellart/OpenNMT,da03/OpenNMT,srush/OpenNMT,da03/OpenNMT,OpenNMT/OpenNMT,OpenNMT/OpenNMT,monsieurzhang/OpenNMT,jsenellart/OpenNMT,jsenellart-systran/OpenNMT,jungikim/OpenNMT,jsenellart-systran/OpenNMT,OpenNMT/OpenNMT,jungikim/OpenNMT,jsenellart-systran/OpenNMT
|
5a215b90a2d943795897b608a9a85a830826cbae
|
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 timer = require "util.timer";
local xmlns_sm = "urn:xmpp:sm:2";
local sm_attr = { xmlns = xmlns_sm };
local resume_timeout = 300;
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.clone(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
--log("debug", "ACK: h=%s, last=%s", stanza.attr.h or "", origin.last_acknowledged_stanza or "");
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 = st.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, reply);
end
end
end
end
local _destroy_session = sessionmanager.destroy_session;
function sessionmanager.destroy_session(session, err)
if session.smacks then
if not session.resumption_token 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
else
session.hibernating = true;
timer.add_task(resume_timeout, function ()
if session.hibernating then
session.resumption_token = nil;
sessionmanager.destroy_session(session); -- Re-destroy
end
end);
return; -- Postpone destruction for now
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 timer = require "util.timer";
local xmlns_sm = "urn:xmpp:sm:2";
local sm_attr = { xmlns = xmlns_sm };
local resume_timeout = 300;
local max_unacked_stanzas = 0;
module:hook("stream-features",
function (event)
event.features:tag("sm", sm_attr):tag("optional"):up():up();
end);
module:hook("s2s-stream-features",
function (event)
event.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.clone(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
--log("debug", "ACK: h=%s, last=%s", stanza.attr.h or "", origin.last_acknowledged_stanza or "");
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 = st.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, reply);
end
end
end
end
local _destroy_session = sessionmanager.destroy_session;
function sessionmanager.destroy_session(session, err)
if session.smacks then
if not session.resumption_token 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
else
session.hibernating = true;
timer.add_task(resume_timeout, function ()
if session.hibernating then
session.resumption_token = nil;
sessionmanager.destroy_session(session); -- Re-destroy
end
end);
return; -- Postpone destruction for now
end
end
return _destroy_session(session, err);
end
|
mod_smacks: Fixed to use the correct events API.
|
mod_smacks: Fixed to use the correct events API.
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
ab49978eef13fd2f94671cf0673e72cc607a6ebf
|
plugins/mod_tls.lua
|
plugins/mod_tls.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 config = require "core.configmanager";
local create_context = require "core.certmanager".create_context;
local st = require "util.stanza";
local secure_auth_only = module:get_option("c2s_require_encryption") or module:get_option("require_encryption");
local secure_s2s_only = module:get_option("s2s_require_encryption");
local allow_s2s_tls = module:get_option("s2s_allow_encryption") ~= false;
local xmlns_starttls = 'urn:ietf:params:xml:ns:xmpp-tls';
local starttls_attr = { xmlns = xmlns_starttls };
local starttls_proceed = st.stanza("proceed", starttls_attr);
local starttls_failure = st.stanza("failure", starttls_attr);
local c2s_feature = st.stanza("starttls", starttls_attr);
local s2s_feature = st.stanza("starttls", starttls_attr);
if secure_auth_only then c2s_feature:tag("required"):up(); end
if secure_s2s_only then s2s_feature:tag("required"):up(); end
local global_ssl_ctx = prosody.global_ssl_ctx;
local host = hosts[module.host];
local function can_do_tls(session)
if session.type == "c2s_unauthed" then
return session.conn.starttls and host.ssl_ctx_in;
elseif session.type == "s2sin_unauthed" and allow_s2s_tls then
return session.conn.starttls and host.ssl_ctx_in;
elseif session.direction == "outgoing" and allow_s2s_tls then
return session.conn.starttls and host.ssl_ctx;
end
return false;
end
-- Hook <starttls/>
module:hook("stanza/urn:ietf:params:xml:ns:xmpp-tls:starttls", function(event)
local origin = event.origin;
if can_do_tls(origin) then
(origin.sends2s or origin.send)(starttls_proceed);
origin:reset_stream();
local host = origin.to_host or origin.host;
local ssl_ctx = host and hosts[host].ssl_ctx_in or global_ssl_ctx;
origin.conn:starttls(ssl_ctx);
origin.log("debug", "TLS negotiation started for %s...", origin.type);
origin.secure = false;
else
origin.log("warn", "Attempt to start TLS, but TLS is not available on this %s connection", origin.type);
(origin.sends2s or origin.send)(starttls_failure);
origin:close();
end
return true;
end);
-- Advertize stream feature
module:hook("stream-features", function(event)
local origin, features = event.origin, event.features;
if can_do_tls(origin) then
features:add_child(c2s_feature);
end
end);
module:hook("s2s-stream-features", function(event)
local origin, features = event.origin, event.features;
if can_do_tls(origin) then
features:add_child(s2s_feature);
end
end);
-- For s2sout connections, start TLS if we can
module:hook_stanza("http://etherx.jabber.org/streams", "features", function (session, stanza)
module:log("debug", "Received features element");
if can_do_tls(session) and stanza:child_with_ns(xmlns_starttls) then
module:log("%s is offering TLS, taking up the offer...", session.to_host);
session.sends2s("<starttls xmlns='"..xmlns_starttls.."'/>");
return true;
end
end, 500);
module:hook_stanza(xmlns_starttls, "proceed", function (session, stanza)
module:log("debug", "Proceeding with TLS on s2sout...");
session:reset_stream();
local ssl_ctx = session.from_host and hosts[session.from_host].ssl_ctx or global_ssl_ctx;
session.conn:starttls(ssl_ctx);
session.secure = false;
return true;
end);
function module.load()
local global_ssl_config = config.get("*", "core", "ssl");
local ssl_config = config.get(module.host, "core", "ssl");
local base_host = module.host:match("%.(.*)");
if ssl_config == global_ssl_config and hosts[base_host] then
ssl_config = config.get(base_host, "core", "ssl");
end
host.ssl_ctx = create_context(host.host, "client", ssl_config); -- for outgoing connections
host.ssl_ctx_in = create_context(host.host, "server", ssl_config); -- for incoming connections
end
function module.unload()
host.ssl_ctx = nil;
host.ssl_ctx_in = nil;
end
|
-- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local config = require "core.configmanager";
local create_context = require "core.certmanager".create_context;
local st = require "util.stanza";
local secure_auth_only = module:get_option("c2s_require_encryption") or module:get_option("require_encryption");
local secure_s2s_only = module:get_option("s2s_require_encryption");
local allow_s2s_tls = module:get_option("s2s_allow_encryption") ~= false;
local xmlns_starttls = 'urn:ietf:params:xml:ns:xmpp-tls';
local starttls_attr = { xmlns = xmlns_starttls };
local starttls_proceed = st.stanza("proceed", starttls_attr);
local starttls_failure = st.stanza("failure", starttls_attr);
local c2s_feature = st.stanza("starttls", starttls_attr);
local s2s_feature = st.stanza("starttls", starttls_attr);
if secure_auth_only then c2s_feature:tag("required"):up(); end
if secure_s2s_only then s2s_feature:tag("required"):up(); end
local global_ssl_ctx = prosody.global_ssl_ctx;
local host = hosts[module.host];
local function can_do_tls(session)
if session.type == "c2s_unauthed" then
return session.conn.starttls and host.ssl_ctx_in;
elseif session.type == "s2sin_unauthed" and allow_s2s_tls then
return session.conn.starttls and host.ssl_ctx_in;
elseif session.direction == "outgoing" and allow_s2s_tls then
return session.conn.starttls and host.ssl_ctx;
end
return false;
end
-- Hook <starttls/>
module:hook("stanza/urn:ietf:params:xml:ns:xmpp-tls:starttls", function(event)
local origin = event.origin;
if can_do_tls(origin) then
(origin.sends2s or origin.send)(starttls_proceed);
origin:reset_stream();
local host = origin.to_host or origin.host;
local ssl_ctx = host and hosts[host].ssl_ctx_in or global_ssl_ctx;
origin.conn:starttls(ssl_ctx);
origin.log("debug", "TLS negotiation started for %s...", origin.type);
origin.secure = false;
else
origin.log("warn", "Attempt to start TLS, but TLS is not available on this %s connection", origin.type);
(origin.sends2s or origin.send)(starttls_failure);
origin:close();
end
return true;
end);
-- Advertize stream feature
module:hook("stream-features", function(event)
local origin, features = event.origin, event.features;
if can_do_tls(origin) then
features:add_child(c2s_feature);
end
end);
module:hook("s2s-stream-features", function(event)
local origin, features = event.origin, event.features;
if can_do_tls(origin) then
features:add_child(s2s_feature);
end
end);
-- For s2sout connections, start TLS if we can
module:hook_stanza("http://etherx.jabber.org/streams", "features", function (session, stanza)
module:log("debug", "Received features element");
if can_do_tls(session) and stanza:child_with_ns(xmlns_starttls) then
module:log("%s is offering TLS, taking up the offer...", session.to_host);
session.sends2s("<starttls xmlns='"..xmlns_starttls.."'/>");
return true;
end
end, 500);
module:hook_stanza(xmlns_starttls, "proceed", function (session, stanza)
module:log("debug", "Proceeding with TLS on s2sout...");
session:reset_stream();
local ssl_ctx = session.from_host and hosts[session.from_host].ssl_ctx or global_ssl_ctx;
session.conn:starttls(ssl_ctx);
session.secure = false;
return true;
end);
function module.load()
local ssl_config = config.rawget(module.host, "core", "ssl");
if not ssl_config then
local base_host = module.host:match("%.(.*)");
ssl_config = config.get(base_host, "core", "ssl");
end
host.ssl_ctx = create_context(host.host, "client", ssl_config); -- for outgoing connections
host.ssl_ctx_in = create_context(host.host, "server", ssl_config); -- for incoming connections
end
function module.unload()
host.ssl_ctx = nil;
host.ssl_ctx_in = nil;
end
|
mod_tls: Fix for components to more reliably inherit SSL settings from their parenthost (thanks Link Mauve)
|
mod_tls: Fix for components to more reliably inherit SSL settings from their parenthost (thanks Link Mauve)
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
5e39edcb99711053d6767c7e175ab2e6159ae842
|
apicast/src/oauth.lua
|
apicast/src/oauth.lua
|
local env = require 'resty.env'
local router = require 'router'
local apicast_oauth = require 'oauth.apicast_oauth'
local keycloak = require 'oauth.keycloak'
local _M = {
_VERSION = '0.0.2'
}
function _M.new()
local oauth
if keycloak.configured then
oauth = keycloak.new()
else
oauth = apicast_oauth.new()
end
return oauth
end
function _M.router()
-- TODO: use configuration to customize urls
local r = router:new()
oauth = _M.new()
r:get('/authorize', function() oauth:authorize() end)
r:post('/authorize', function() oauth:authorize() end)
-- TODO: only applies to apicast oauth...
r:post('/callback', function() oauth:callback() end)
r:get('/callback', function() oauth:callback() end)
r:post('/oauth/token', function() oauth:get_token() end)
return r
end
function _M.call(method, uri, ...)
local r = _M.router()
local f, params = r:resolve(method or ngx.req.get_method(),
uri or ngx.var.uri,
unpack(... or {}))
return f, params
end
return _M
|
local router = require 'router'
local apicast_oauth = require 'oauth.apicast_oauth'
local keycloak = require 'oauth.keycloak'
local _M = {
_VERSION = '0.0.2'
}
function _M.new()
local oauth
if keycloak.configured then
oauth = keycloak.new()
else
oauth = apicast_oauth.new()
end
return oauth
end
function _M.router()
-- TODO: use configuration to customize urls
local r = router:new()
local oauth = _M.new()
r:get('/authorize', function() oauth:authorize() end)
r:post('/authorize', function() oauth:authorize() end)
-- TODO: only applies to apicast oauth...
r:post('/callback', function() oauth:callback() end)
r:get('/callback', function() oauth:callback() end)
r:post('/oauth/token', function() oauth:get_token() end)
return r
end
function _M.call(method, uri, ...)
local r = _M.router()
local f, params = r:resolve(method or ngx.req.get_method(),
uri or ngx.var.uri,
unpack(... or {}))
return f, params
end
return _M
|
Fix build
|
Fix build
Fix build
|
Lua
|
mit
|
3scale/apicast,3scale/apicast,3scale/docker-gateway,3scale/apicast,3scale/docker-gateway,3scale/apicast
|
bfac5037312e1fa1862c6ded321c8e3974d54a04
|
spec/lexer_spec.lua
|
spec/lexer_spec.lua
|
describe("lexer", function()
local lexer = require("fusion.core.lexer")
it("can do basic assignment", function()
assert.same(lexer:match("a = b;"), {
{ "assignment", {
variable_list = {
{"variable", "a"},
},
expression_list = {
{"variable", "b"}
}
}}
})
end)
it("can do multi value assignment", function()
assert.same(lexer:match("a, b = c, d;"), {
{ "assignment", {
variable_list = {
{"variable", "a"},
{"variable", "b"}
},
expression_list = {
{"variable", "c"},
{"variable", "d"}
}
}}
})
end)
it("can do replacement assignment", function()
assert.same(lexer:match("a, b = b, a;"), {
{ "assignment", {
variable_list = {
{"variable", "a"},
{"variable", "b"}
},
expression_list = {
{"variable", "b"},
{"variable", "a"}
}
}}
})
end)
it("can do complex expressions", function()
assert.same(lexer:match("a = b ^ c + d / e;"), {
{"assignment", {
variable_list = {
{"variable", "a"}
},
expression_list = {{ "expression",
{"expression",
{"variable", "b"},
{"variable", "c"},
operator = "^",
type = "binary"
},
{"expression",
{"variable", "d"},
{"variable", "e"},
operator = "/",
type = "binary"
},
operator = "+",
type = "binary"
}}
}}
})
end)
it("can translate mathematical constants", function()
assert.same(lexer:match("a, b, c = 5, -3, 0xAF;"), {
{"assignment", {
variable_list = {
{"variable", "a"},
{"variable", "b"},
{"variable", "c"}
},
expression_list = {
{"number", "5", type = "base10"},
{"expression",
{"number", "3", type = "base10"},
operator = "-",
type = "unary"
},
{"number", "0xAF", type = "base16"}
}
}}
})
end)
it("can parse a simple function", function()
assert.same(lexer:match("func();"), {{"function_call",
{"variable", "func"}
}})
end)
it("can parse arguments passed to a function", function()
assert.same(lexer:match("func(test, test_two);"), {{"function_call",
{"variable", "func"},
expression_list = {
{"variable", "test"},
{"variable", "test_two"}
}
}})
end)
it("can parse a complex function call", function()
assert.same(lexer:match("table.instance:method<subclass>(argument);"),{{
"function_call",
{"variable", "table", "instance"}, -- tables parse -this- way
{"variable", "method"},
expression_list = {
{"variable", "argument"}
},
has_self = true,
index_class = "subclass"
}})
end)
end)
|
describe("lexer", function()
local lexer = require("fusion.core.lexer")
it("can do basic assignment", function()
assert.same(lexer:match("a = b;"), {
{ "assignment", {
variable_list = {
{"variable", "a"},
},
expression_list = {
{"variable", "b"}
}
}}
})
end)
it("can do multi value assignment", function()
assert.same(lexer:match("a, b = c, d;"), {
{ "assignment", {
variable_list = {
{"variable", "a"},
{"variable", "b"}
},
expression_list = {
{"variable", "c"},
{"variable", "d"}
}
}}
})
end)
it("can do replacement assignment", function()
assert.same(lexer:match("a, b = b, a;"), {
{ "assignment", {
variable_list = {
{"variable", "a"},
{"variable", "b"}
},
expression_list = {
{"variable", "b"},
{"variable", "a"}
}
}}
})
end)
it("can do complex expressions", function()
assert.same(lexer:match("a = (+ (^ b c) (/ d e));"), {
{"assignment", {
variable_list = {
{"variable", "a"}
},
expression_list = {{ "expression",
{"expression",
{"variable", "b"},
{"variable", "c"},
operator = "^",
},
{"expression",
{"variable", "d"},
{"variable", "e"},
operator = "/",
},
operator = "+",
}}
}}
})
end)
it("can translate mathematical constants", function()
assert.same(lexer:match("a, b, c = 5, -3, 0xAF;"), {
{"assignment", {
variable_list = {
{"variable", "a"},
{"variable", "b"},
{"variable", "c"}
},
expression_list = {
{"number", 5, type = "base10"},
{"number", 3, type = "base10", is_negative = true},
{"number", 0xAF, type = "base16"}
}
}}
})
end)
it("can parse a simple function", function()
assert.same(lexer:match("func();"), {{"function_call",
{"variable", "func"}
}})
end)
it("can parse arguments passed to a function", function()
assert.same(lexer:match("func(test, test_two);"), {{"function_call",
{"variable", "func"},
expression_list = {
{"variable", "test"},
{"variable", "test_two"}
}
}})
end)
it("can parse a complex function call", function()
assert.same(lexer:match("table.instance:method<subclass>(argument);"),{{
"function_call",
{"variable", "table", "instance"}, -- tables parse -this- way
{"variable", "method"},
expression_list = {
{"variable", "argument"}
},
has_self = true,
index_class = "subclass"
}})
end)
it("can parse a table", function()
assert.same(lexer:match("a = {1, b = 2, [c] = 3};"), {{"assignment", {
variable_list = {{"variable", "a"}},
expression_list= {
{"table",
{"number", 1, type = "base10"},
{{"number", 2, type = "base10"}, name = "b"},
{{"number", 3, type = "base10"}, index = {"variable", "c"}}
}
}
}}})
end)
end)
|
lexer_spec.lua: fix tests for expressions and add table tests
|
lexer_spec.lua: fix tests for expressions and add table tests
|
Lua
|
mit
|
RyanSquared/FusionScript
|
799fe08a6fe23457544c003a3245f69602149067
|
spec/integration_spec.lua
|
spec/integration_spec.lua
|
describe('integration', function()
local port = '7070'
local url = 'http://localhost:' .. port
local executeCommand = function(command)
local handle = io.popen(command .. ' -s ' .. url)
local result = handle:read('*a')
handle:close()
return result
end
it('should return correct headers', function()
local result = executeCommand('curl --head')
assert.match('HTTP/1%.1 200 OK', result)
assert.match('Content%-Type: text/html', result)
assert.match('Content%-Length: 16', result)
end)
it('should return correct body', function()
local result = executeCommand('curl')
assert.match('Hello, Pegasus', result)
end)
end)
|
describe('integration', function()
local port = '7070'
local url = 'http://localhost:' .. port
local executeCommand = function(command)
local handle = io.popen(command .. ' -s ' .. url)
local result = handle:read('*a')
handle:close()
return result
end
it('should return correct headers', function()
local result = executeCommand('curl --head')
assert.match(result, 'HTTP/1%.1 200 OK')
assert.match(result, 'Content%-Type: text/html')
assert.match(result, 'Content%-Length: 16')
end)
it('should return correct body', function()
assert.match(executeCommand('curl'), 'Hello, Pegasus')
end)
end)
|
fix problem with integration test
|
fix problem with integration test
|
Lua
|
mit
|
EvandroLG/pegasus.lua
|
45b8b3742a88810967d54b3866541c3d2738ffc1
|
lua/settings/init.lua
|
lua/settings/init.lua
|
local api = vim.api
local sys = require('sys')
local nvim = require('nvim')
local plugs = require('nvim').plugs
local parent = require('sys').data
local mkdir = require('nvim').fn.mkdir
local isdirectory = require('nvim').fn.isdirectory
local tools = require('tools')
local function isempty(s)
return (s == nil or s == '') and 1 or 0
end
local dirpaths = {
backup = 'backupdir',
swap = 'directory',
undo = 'undodir',
cache = '',
sessions = '',
}
for dirname,dir_setting in pairs(dirpaths) do
if isdirectory(parent .. '/' .. dirname) == 0 then
mkdir(parent .. '/' .. dirname, 'p')
end
if isempty(dir_setting) == 0 then
nvim.option[dir_setting] = parent .. '/' .. dirname
end
end
nvim.g.lua_complete_omni = 1
nvim.g.c_syntax_for_h = 1
nvim.g.terminal_scrollback_buffer_size = 100000
nvim.option.shada = "!,/1000,'1000,<1000,:1000,s10000,h"
nvim.option.scrollback = -1
nvim.option.softtabstop = -1
nvim.option.shiftwidth = 4
nvim.option.tabstop = 4
nvim.option.updatetime = 1000
nvim.option.sidescrolloff = 5
nvim.option.scrolloff = 1
nvim.option.undolevels = 10000
nvim.option.inccommand = 'split'
nvim.option.winaltkeys = 'no'
nvim.option.virtualedit = 'block'
nvim.option.formatoptions = 'tcqrolnj'
nvim.option.backupcopy = 'yes'
nvim.option.complete = '.,w,b,u,t'
nvim.option.completeopt = 'menuone,preview'
nvim.option.tags = '.git/tags,./tags;,tags'
nvim.option.display = 'lastline,msgsep'
nvim.option.fileformats = 'unix,dos'
nvim.option.wildmenu = true
nvim.option.wildmode = 'full'
nvim.option.showbreak = '↪\\'
nvim.option.listchars = 'tab:▸ ,trail:•,extends:❯,precedes:❮'
nvim.option.sessionoptions = 'buffers,curdir,folds,globals,localoptions,options,resize,tabpages,winpos,winsize'
nvim.option.cpoptions = 'aAceFs_B'
if sys.name == 'windows' then
nvim.option.sessionoptions = nvim.option.sessionoptions .. ',slash,unix'
end
nvim.option.lazyredraw = true
nvim.option.showmatch = true
nvim.option.splitright = true
nvim.option.splitbelow = true
nvim.option.backup = true
nvim.option.undofile = true
nvim.option.termguicolors = true
nvim.option.infercase = true
nvim.option.ignorecase = true
nvim.option.smartindent = true
nvim.option.copyindent = true
nvim.option.expandtab = true
nvim.option.joinspaces = false
nvim.option.showmode = false
nvim.option.visualbell = true
nvim.option.shiftround = true
nvim.option.hidden = true
nvim.option.autowrite = true
nvim.option.autowriteall = true
if nvim.g.gonvim_running ~= nil then
nvim.option.showmode = false
nvim.option.ruler = false
else
nvim.option.titlestring = '%t (%f)'
nvim.option.title = true
end
if nvim.has_version('0.3.3') == 1 then
nvim.option.diffopt = 'internal,filler,vertical,iwhiteall,iwhiteeol,indent-heuristic,algorithm:patience'
else
nvim.option.diffopt = 'filler,vertical,iwhite'
end
nvim.o.grepprg = tools.select_grep(false)
nvim.o.grepformat = tools.select_grep(false, 'grepformat')
-- Windows options
nvim.ex.set('breakindent')
nvim.ex.set('relativenumber')
nvim.ex.set('number')
nvim.ex.set('list')
nvim.ex.set('nowrap')
nvim.ex.set('nofoldenable')
nvim.ex.set('colorcolumn=80')
nvim.ex.set('foldmethod=syntax')
nvim.ex.set('signcolumn=auto')
nvim.ex.set('numberwidth=1')
nvim.ex.set('foldlevel=99')
nvim.ex.set('foldcolumn=0')
nvim.ex.set('fileencoding=utf-8')
local wildignores = {
'*.spl',
'*.aux',
'*.out',
'*.o',
'*.pyc',
'*.gz',
'*.pdf',
'*.sw',
'*.swp',
'*.swap',
'*.com',
'*.exe',
'*.so',
'*/cache/*',
'*/__pycache__/*',
}
local no_backup = {
'.git/*',
'.svn/*',
'.xml',
'*.log',
'*.bin',
'*.7z',
'*.dmg',
'*.gz',
'*.iso',
'*.jar',
'*.rar',
'*.tar',
'*.zip',
'TAGS',
'tags',
'GTAGS',
'COMMIT_EDITMSG',
}
nvim.option.wildignore = table.concat(wildignores, ',')
nvim.option.backupskip = table.concat(no_backup, ',') .. ',' .. table.concat(wildignores, ',')
if nvim.env.SSH_CONNECTION == nil then
nvim.option.mouse = 'a'
nvim.option.clipboard = 'unnamedplus,unnamed'
else
nvim.option.mouse = ''
end
|
local api = vim.api
local sys = require('sys')
local nvim = require('nvim')
local plugs = require('nvim').plugs
local parent = require('sys').data
local mkdir = require('nvim').fn.mkdir
local isdirectory = require('nvim').fn.isdirectory
local tools = require('tools')
local function isempty(s)
return (s == nil or s == '') and 1 or 0
end
local dirpaths = {
backup = 'backupdir',
swap = 'directory',
undo = 'undodir',
cache = '',
sessions = '',
}
for dirname,dir_setting in pairs(dirpaths) do
if isdirectory(parent .. '/' .. dirname) == 0 then
mkdir(parent .. '/' .. dirname, 'p')
end
if isempty(dir_setting) == 0 then
nvim.option[dir_setting] = parent .. '/' .. dirname
end
end
nvim.g.lua_complete_omni = 1
nvim.g.c_syntax_for_h = 1
nvim.g.terminal_scrollback_buffer_size = 100000
nvim.option.shada = "!,/1000,'1000,<1000,:1000,s10000,h"
nvim.option.scrollback = -1
nvim.option.softtabstop = -1
nvim.option.shiftwidth = 4
nvim.option.tabstop = 4
nvim.option.updatetime = 1000
nvim.option.sidescrolloff = 5
nvim.option.scrolloff = 1
nvim.option.undolevels = 10000
nvim.option.inccommand = 'split'
nvim.option.winaltkeys = 'no'
nvim.option.virtualedit = 'block'
nvim.option.formatoptions = 'tcqrolnj'
nvim.option.backupcopy = 'yes'
nvim.option.complete = '.,w,b,u,t'
nvim.option.completeopt = 'menuone,preview'
nvim.option.tags = '.git/tags,./tags;,tags'
nvim.option.display = 'lastline,msgsep'
nvim.option.fileformats = 'unix,dos'
nvim.option.wildmenu = true
nvim.option.wildmode = 'full'
nvim.option.showbreak = '↪\\'
nvim.option.listchars = 'tab:▸ ,trail:•,extends:❯,precedes:❮'
nvim.option.sessionoptions = 'buffers,curdir,folds,globals,localoptions,options,resize,tabpages,winpos,winsize'
nvim.option.cpoptions = 'aAceFs_B'
if sys.name == 'windows' then
nvim.option.sessionoptions = nvim.option.sessionoptions .. ',slash,unix'
end
nvim.option.lazyredraw = true
nvim.option.showmatch = true
nvim.option.splitright = true
nvim.option.splitbelow = true
nvim.option.backup = true
nvim.option.undofile = true
nvim.option.termguicolors = true
nvim.option.infercase = true
nvim.option.ignorecase = true
nvim.option.smartindent = true
nvim.option.copyindent = true
nvim.option.expandtab = true
nvim.option.joinspaces = false
nvim.option.showmode = false
nvim.option.visualbell = true
nvim.option.shiftround = true
nvim.option.hidden = true
nvim.option.autowrite = true
nvim.option.autowriteall = true
nvim.option.fileencoding = 'utf-8'
if nvim.g.gonvim_running ~= nil then
nvim.option.showmode = false
nvim.option.ruler = false
else
nvim.option.titlestring = '%t (%f)'
nvim.option.title = true
end
if nvim.has_version('0.3.3') == 1 then
nvim.option.diffopt = 'internal,filler,vertical,iwhiteall,iwhiteeol,indent-heuristic,algorithm:patience'
else
nvim.option.diffopt = 'filler,vertical,iwhite'
end
nvim.option.grepprg = tools.select_grep(false)
nvim.option.grepformat = tools.select_grep(false, 'grepformat')
if plugs['vim-fugitive'] ~= nil and plugs['vim-airline'] == nil then
nvim.option.statusline = '%<%f %h%m%r%{FugitiveStatusline()}%=%-14.(%l,%c%V%) %P'
end
-- Window options
nvim.wo.breakindent = true
nvim.wo.relativenumber = true
nvim.wo.number = true
nvim.wo.list = true
nvim.wo.wrap = false
nvim.wo.foldenable = false
nvim.wo.colorcolumn = '80'
nvim.wo.foldmethod = 'syntax'
nvim.wo.signcolumn = 'auto'
nvim.wo.numberwidth = 1
nvim.wo.foldlevel = 99
nvim.wo.foldcolumn = 0
local wildignores = {
'*.spl',
'*.aux',
'*.out',
'*.o',
'*.pyc',
'*.gz',
'*.pdf',
'*.sw',
'*.swp',
'*.swap',
'*.com',
'*.exe',
'*.so',
'*/cache/*',
'*/__pycache__/*',
}
local no_backup = {
'.git/*',
'.svn/*',
'.xml',
'*.log',
'*.bin',
'*.7z',
'*.dmg',
'*.gz',
'*.iso',
'*.jar',
'*.rar',
'*.tar',
'*.zip',
'TAGS',
'tags',
'GTAGS',
'COMMIT_EDITMSG',
}
nvim.option.wildignore = table.concat(wildignores, ',')
nvim.option.backupskip = table.concat(no_backup, ',') .. ',' .. table.concat(wildignores, ',')
if nvim.env.SSH_CONNECTION == nil then
nvim.option.mouse = 'a'
nvim.option.clipboard = 'unnamedplus,unnamed'
else
nvim.option.mouse = ''
end
|
fix: Some minor changes to neovim settings
|
fix: Some minor changes to neovim settings
- Add fileencoding to global settings
- Set global grepprg and grepformat options
- Add missing fallback status line
- Change window option settings to nvim.wo instead of nvim.ex.set
|
Lua
|
mit
|
Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim
|
476b73b6375861d09a0a64c22ee5f7c72ab4074c
|
deferrs.lua
|
deferrs.lua
|
local queue = require 'queue'
local fiber = require 'fiber'
local function show_error(str)
box.error(box.error.PROC_LUA, str)
end
if not queue then
show_error("Failed to load queue module")
end
if not queue.tube.deferrs then
queue.start()
end
box.once('deferrs_init', function ()
queue.create_tube('deferrs', 'fifottl')
end)
local function get_task_id(task)
return task[1]
end
local function get_task_data(task)
return task[3]
end
function deferr_put(uid, release_time, data)
local ok, ret = pcall(function(uid, release_time, data)
local delay = release_time - math.floor(fiber.time())
if delay < 0 then
show_error("Invalid release_time found for user " .. uid .. ", data == " .. data)
end
return queue.tube.deferrs:put({ uid, release_time, data }, { delay = delay })
end, uid, release_time, data)
if not ok then
show_error(str) -- unexpected error. Pass it to capron
end
return get_task_id(ret)
end
function deferr_delete(id)
local ok, ret = pcall(function (task_id)
return queue.tube.deferrs:delete(task_id)
end, id)
if not ok then
return nil
end
return get_task_data(ret) -- a tuple: { uid, release_time, data }
end
function deferr_peek(id)
local ok, ret = pcall(function (task_id)
return queue.tube.deferrs:peek(task_id) -- task state will not be changed
end, id)
if not ok then
return nil
end
return get_task_data(ret) -- a tuple: { uid, release_time, data }
end
|
local queue = require 'queue'
local fiber = require 'fiber'
local function show_error(str)
box.error(box.error.PROC_LUA, str)
end
if not queue then
show_error("Failed to load queue module")
end
if not queue.tube.deferrs then
queue.start()
end
box.once('deferrs_init', function ()
queue.create_tube('deferrs', 'fifottl')
end)
local function get_task_id(task)
return task[1]
end
local function get_task_data(task)
return task[3]
end
function deferr_put(uid, release_time, data)
local ok, ret = pcall(function(uid, release_time, data)
local delay = release_time - math.floor(fiber.time())
if delay < 0 then
show_error("Invalid release_time (" .. release_time .. ") found for user (delay < 0), uid == " .. uid .. ", data == " .. data)
end
return queue.tube.deferrs:put({ uid, release_time, data }, { delay = delay })
end, uid, release_time, data)
if not ok then
show_error(ret) -- unexpected error. Pass it to capron
end
return get_task_id(ret)
end
function deferr_delete(id)
local ok, ret = pcall(function (task_id)
return queue.tube.deferrs:delete(task_id)
end, id)
if not ok then
return nil
end
return get_task_data(ret) -- a tuple: { uid, release_time, data }
end
function deferr_peek(id)
local ok, ret = pcall(function (task_id)
return queue.tube.deferrs:peek(task_id) -- task state will not be changed
end, id)
if not ok then
return nil
end
return get_task_data(ret) -- a tuple: { uid, release_time, data }
end
|
deferrs: bug fix
|
deferrs: bug fix
|
Lua
|
bsd-2-clause
|
mailru/tntlua,BHYCHIK/tntlua
|
1412b200473691fc6e61befd0ad6332a146cc4f9
|
display.lua
|
display.lua
|
local disp
local module = { }
local title = "Super Mario Count"
local title_offset = 0
local flash_title = title -- This one will actually be rendered
local flash_until = 0
local width = 128
local height = 64
function get_title_offset(str)
disp:setFont(u8g.font_7x14Br)
w = (disp:getWidth() - disp:getStrWidth(str)) / 2
if w < 0 then
return 0
elseif w > disp:getWidth() / 2 then
return disp:getWidth()
else
return w
end
end
-- setup I2c and connect display
function module.setup()
-- SDA and SCL can be assigned freely to available GPIOs
local sda = 2
local scl = 1
local sla = 0x3c -- 0x3c or 0x3d
i2c.setup(0, sda, scl, i2c.SLOW)
disp = u8g.ssd1306_128x64_i2c(sla)
title_offset = get_title_offset(title)
end
function module.flash_title(str, seconds)
flash_until = tmr.now() + seconds * 1000000 -- µS!
flash_title = str
title_offset = get_title_offset(str)
end
function module.message(str)
disp:firstPage()
repeat
disp:setFontPosTop()
disp:drawStr(0, 20, str)
until disp:nextPage() == false
end
function module.draw(super_mario_count, timer_id)
disp:firstPage()
repeat
disp:setFont(u8g.font_7x14Br)
disp:setFontPosTop()
if flash_time ~= 0 then
local delta = flash_until - tmr.now()
if tmr.now() > flash_until then
flash_title = title
get_title_offset(flash_title)
flash_until = 0
end
end
disp:drawStr(title_offset, 0, flash_title)
disp:setFont(u8g.font_freedoomr25n)
disp:drawStr(50, 60, super_mario_count)
until disp:nextPage() == false
tmr.start(timer_id)
end
function module.display()
return disp
end
return module
|
local disp
local module = { }
local title = "Super Mario Count"
local title_offset = 0
local flash_title = title -- This one will actually be rendered
local flash_until = 0
local width = 128
local height = 64
function get_title_offset(str)
if (disp == nil) then return end -- too soon
disp:setFont(u8g.font_7x14Br)
local w = (disp:getWidth() - disp:getStrWidth(str)) / 2
if w < 0 then
return 0
elseif w > disp:getWidth() / 2 then
return disp:getWidth()
else
return w
end
end
-- setup I2c and connect display
function module.setup()
-- SDA and SCL can be assigned freely to available GPIOs
local sda = 2
local scl = 1
local sla = 0x3c -- 0x3c or 0x3d
i2c.setup(0, sda, scl, i2c.SLOW)
disp = u8g.ssd1306_128x64_i2c(sla)
title_offset = get_title_offset(title)
end
function module.flash_title(str, seconds)
flash_until = tmr.now() + seconds * 1000000 -- µS!
flash_title = str
title_offset = get_title_offset(str)
end
function module.message(str)
disp:firstPage()
repeat
disp:setFontPosTop()
disp:drawStr(0, 20, str)
until disp:nextPage() == false
end
function module.draw(super_mario_count, timer_id)
disp:firstPage()
repeat
disp:setFont(u8g.font_7x14Br)
disp:setFontPosTop()
if flash_time ~= 0 then
local delta = flash_until - tmr.now()
if tmr.now() > flash_until then
flash_title = title
title_offset = get_title_offset(flash_title)
flash_until = 0
end
end
disp:drawStr(title_offset, 0, flash_title)
disp:setFont(u8g.font_freedoomr25n)
disp:drawStr(50, 60, super_mario_count)
until disp:nextPage() == false
tmr.start(timer_id)
end
function module.display()
return disp
end
return module
|
Fix bugs in display
|
Fix bugs in display
|
Lua
|
mit
|
DevLoL/super-mario-count
|
d256656ed6decdebbf65532fdd858062b7638623
|
model/module.lua
|
model/module.lua
|
------------------------------------------------------------------------
--[[ Module ]]--
-- Decorates/Adapts a nn.Module to the dp.Model interface
-- A temporary fix until these are implemented into their own
-- Model subclasses
------------------------------------------------------------------------
local Module, parent = torch.class("dp.Module", "dp.Model")
Module.isModule = true
function Module:__init(config)
config = config or {}
local args, module = xlua.unpack(
{config},
'Module',
'Decorates/Adapts a nn.Module to the dp.Model interface',
{arg='module', type='nn.Module'}
)
self._module = module
-- typename of this model
local typename = _.split(torch.typename(module), '[.]')
typename = string.lower(typename[#typename]) .. 'Adapter'
config.typename = config.typename or typename
parent.__init(self, config)
-- try to guess if module has parameters
local params, gradParams = module:parameters()
assert(not params or #params <= 2, "Error : unknown extra parameters")
if self._tags.hasParams == nil then
if (not params) or (#params == 0) then
self._tags.hasParams = false
else
for i, param in ipairs(params) do
if param:dim() ~= 0 then
self._tags.hasParams = true
break
end
end
end
end
end
function Module:_forward(cstate)
self.ostate.act = self._module:forward(self.istate.act)
end
function Module:_backward(cstate)
self.istate.grad = self._module:backward(
self.istate.act,
self.ostate.grad,
self.gstate.scale
)
end
function Module:zeroGradParameters()
self._module:zeroGradParameters()
end
function Module:type(type)
self._module:type(type)
return parent.type(self, type)
end
function Module:reset()
return self._module:reset()
end
function Module:parameters()
local params = self._params
local module = self._module
if module.weight and module.weight:dim() ~= 0 then
if not params.weight then
params.weight = {}
end
params.weight.param=module.weight
params.weight.grad=module.gradWeight
end
if module.bias and module.bias:dim() ~= 0 then
if not params.bias then
params.bias = {}
end
params.bias.param=module.bias
params.bias.grad=module.gradBias
end
return params
end
|
------------------------------------------------------------------------
--[[ Module ]]--
-- Decorates/Adapts a nn.Module to the dp.Model interface
-- A temporary fix until these are implemented into their own
-- Model subclasses
------------------------------------------------------------------------
local Module, parent = torch.class("dp.Module", "dp.Model")
Module.isModule = true
function Module:__init(config)
local args, module = xlua.unpack(
{config},
'Module',
'Decorates/Adapts a nn.Module to the dp.Model interface',
{arg='module', type='nn.Module'}
)
self._module = module
-- typename of this model
local typename = _.split(torch.typename(module), '[.]')
typename = string.lower(typename[#typename]) .. 'Adapter'
config.typename = config.typename or typename
parent.__init(self, config)
-- try to guess if module has parameters
local params, gradParams = module:parameters()
assert(not params or #params <= 2, "Error : unknown extra parameters")
if self._tags.hasParams == nil then
if (not params) or (#params == 0) then
self._tags.hasParams = false
else
for i, param in ipairs(params) do
if param:dim() ~= 0 then
self._tags.hasParams = true
break
end
end
end
end
end
function Module:_forward(carry)
self.output.act = dp.DataTensor{
data=self._module:forward(self.input.act:feature())
}
end
function Module:_backward(carry)
self.input.grad = self.input.act:featureClone(
self._module:backward(
self.input.act:feature(),
self.output.grad:feature(),
carry.scale
)
)
end
function Module:zeroGradParameters()
self._module:zeroGradParameters()
end
function Module:type(type)
self._module:type(type)
return parent.type(self, type)
end
function Module:reset()
return self._module:reset()
end
function Module:parameters()
local params = {}
local module = self._module
if module.weight and module.weight:dim() ~= 0 then
if not params.weight then
params.weight = {}
end
params.weight.param=module.weight
params.weight.grad=module.gradWeight
end
if module.bias and module.bias:dim() ~= 0 then
if not params.bias then
params.bias = {}
end
params.bias.param=module.bias
params.bias.grad=module.gradBias
end
return params
end
|
fixed dp.Module
|
fixed dp.Module
|
Lua
|
bsd-3-clause
|
sagarwaghmare69/dp,rickyHong/dptorchLib,eulerreich/dp,kracwarlock/dp,jnhwkim/dp,nicholas-leonard/dp,fiskio/dp
|
9ce917b31725236c28f7ace7a38315b87f3cbd59
|
src/main/lua/selectionConverter.lua
|
src/main/lua/selectionConverter.lua
|
function updateClipboard(threadObj)
-- ENCODING among detect, sjis, utf16-be, utf16-le, utf8
local ENCODING = "detect"
-- any positive or negative integer
local STRICTNESS = 20
local hexView = getMemoryViewForm().HexadecimalView
local previousBytes = {}
local handle = io.popen(
"java.exe -jar \"" .. getCheatEngineDir() ..
"autorun\\HexToString.jar\" " ..
"--encoding=" .. ENCODING .. " --strictness=" .. STRICTNESS,
"w"
)
local selectionSize = 0
getMainForm().OnClose = function(sender)
pcall(function()
handle:write("exit")
handle:close()
end)
closeCE()
end
while true do
if hexView.hasSelection then
selectionSize = hexView.SelectionStop-hexView.SelectionStart
local bytes=readBytes(hexView.SelectionStart, selectionSize+1,true)
if bytes ~= nil then
local s = ""
for i = 1, table.getn(bytes) do
s = s .. string.format("%02x", bytes[i])
end
handle:write(s .. "\n")
handle:flush()
previousBytes = bytes
end
end
sleep(300)
end
end
createNativeThread(updateClipboard)
|
function convertHexSelection(threadObj)
local STRATEGIES = {
stabilized = 2 ^ 0,
recurring = 2 ^ 1
}
-- definition: Determines the encoding used to decode the selection.
-- domain: among detect, sjis, utf16-be, utf16-le, utf8
local ENCODING = "detect"
-- definition: Filters converted strings deemed to be garbage.
-- The lower the value, the more garbage there is.
-- The higher the value, the higher the chance to filter actual text.
-- domain: any positive or negative integer
local STRICTNESS = 20
-- definition: Determines at which proportion of the size of the selection
-- the number of differences between the current content of the
-- selection and that of the history is deemed low enough to convert
-- the selection.
-- domain: a real number between 0 and 1
local STABILIZATION_THRESHOLD = 0.005
-- definition: The number of ms to wait before capturing the selection.
-- domain: a positive integer
local REFRESH_DELAY = 50
-- definition: The length of the array containing the previous selections.
-- domain: a strictly positive integer
local HISTORY_SIZE = 6
-- definition: The strategy to use to deem the selection worthy of being
-- converted.
-- STRATEGIES.stabilized waits for the content of the selection to be
-- stable enough, relative to STABILIZATION_THRESHOLD, to convert
-- the selection. The whole history is used to compute the
-- stabilization factor. The bigger the history, the longer the wait
-- for converting the selection.
-- STRATEGIES.recurring does not convert the selection directly, but
-- an array of bytes constructed from the most common bytes at
-- every position of the elements in the history.
-- STRATEGIES.stabilized + STRATEGIES.recurring combines the two.
-- NOTE: if HISTORY_SIZE == 1, the selection is immediatly converted
-- every REFRESH_DELAY ms no matter the strategy.
-- domain: STRATEGIES.stabilized, STRATEGIES.recurring or the sum of the two
local UPDATE_STRATEGY = STRATEGIES.stabilized + STRATEGIES.recurring
local hexView = getMemoryViewForm().HexadecimalView
local history = {}
local recurringHistory = {}
local handle = io.popen(
"java.exe -jar \"" .. getCheatEngineDir() ..
"autorun\\HexToString.jar\" " ..
"--encoding=" .. ENCODING .. " --strictness=" .. STRICTNESS,
"w"
)
local selectionSize = 0
-- determines whether it's worth converting the selection or not
-- returns nil if not
-- returns the array of bytes to use otherwise
getBytes = function(selectionContent)
if selectionContent == nil then
return nil
end
pushFirst(history, selectionContent, HISTORY_SIZE)
local bytes = selectionContent
if band(UPDATE_STRATEGY, STRATEGIES.recurring, 8) > 0 then
bytes = constructHexFromHistory(history)
pushFirst(recurringHistory, bytes, HISTORY_SIZE)
end
if band(UPDATE_STRATEGY, STRATEGIES.stabilized, 8) > 0 then
local differences = 0
if band(UPDATE_STRATEGY, STRATEGIES.recurring, 8) > 0 then
differences = countDifferences(recurringHistory)
else
differences = countDifferences(history)
end
if differences < table.getn(bytes) * STABILIZATION_THRESHOLD then
return bytes
else
return nil
end
end
return bytes
end
getMainForm().OnClose = function(sender)
pcall(function()
handle:write("exit")
handle:close()
end)
closeCE()
end
while true do
if hexView.hasSelection then
selectionSize = hexView.SelectionStop-hexView.SelectionStart
local bytes = getBytes(readBytes(
hexView.SelectionStart,
selectionSize + 1,
true
))
if bytes ~= nil then
local s = ""
for i = 1, table.getn(bytes) do
s = s .. string.format("%02x", bytes[i])
end
handle:write(s .. "\n")
handle:flush()
end
end
sleep(REFRESH_DELAY)
end
end
function getMinSize(tables)
if tables == nil or table.getn(tables) == 0 then
return 0
end
local minSize = table.getn(tables[1]);
for i = 2, table.getn(tables) do
if table.getn(tables[i]) < minSize then
minSize = table.getn(tables[i])
end
end
return minSize
end
function countDifferences(tables)
local differenceCounter = 0;
for i = 1, table.getn(tables) - 1 do
for j = 1, getMinSize(tables) do
if tables[i][j] ~= tables[i + 1][j] then
differenceCounter = differenceCounter + 1
end
end
differenceCounter = differenceCounter
+ math.abs(table.getn(tables[i]) - table.getn(tables[i+1]))
end
return differenceCounter
end
-- binary and on bigEndInd bits
function band(elt1, elt2, bigEndInd)
local a = elt1 % (2 ^ (bigEndInd + 1))
local b = elt2 % (2 ^ (bigEndInd + 1))
local res = 0
for i = 0, bigEndInd do
local powerOfTwo = (2 ^ (bigEndInd - i))
if a / powerOfTwo >= 1 then
a = a - powerOfTwo
if b / powerOfTwo >= 1 then
b = b - powerOfTwo
res = res + powerOfTwo
end
end
end
return res
end
-- constructs a byte array by saving the most frequent byte at a given position
-- using the whole history
function constructHexFromHistory(history)
local res = {}
for j = 1, getMinSize(history) do
local bytesAtI = {}
for i = 1, table.getn(history) do
if bytesAtI[history[i][j]] == nil then
bytesAtI[history[i][j]] = 1
else
bytesAtI[history[i][j]] = bytesAtI[history[i][j]] + 1
end
end
local maxByte = nil
for byte, count in pairs(bytesAtI) do
if maxByte == nil or count > bytesAtI[maxByte] then
maxByte = byte;
end
end
res[j] = maxByte
end
return res
end
function pushFirst(array, elt, maxSize)
table.insert(array, 1, elt)
if table.getn(array) > maxSize then
table.remove(array, maxSize + 1)
end
end
createNativeThread(convertHexSelection)
|
Implement strategies to fix #1 and fix #5
|
Implement strategies to fix #1 and fix #5
The rate and method used to capture the hexadecimal selection are now
configurable.
|
Lua
|
mit
|
MX-Futhark/hook-any-text
|
479ab0ccd0be4b9afbf42c3d135edddaa86b94bf
|
mod_roster_command/mod_roster_command.lua
|
mod_roster_command/mod_roster_command.lua
|
-----------------------------------------------------------
-- mod_roster_command: Manage rosters through prosodyctl
-- version 0.02
-----------------------------------------------------------
-- Copyright (C) 2011 Matthew Wild
-- Copyright (C) 2011 Adam Nielsen
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
-----------------------------------------------------------
-- Workaround for lack of util.startup...
_G.bare_sessions = _G.bare_sessions or {};
local rostermanager = require "core.rostermanager";
local storagemanager = require "core.storagemanager";
local jid = require "util.jid";
local warn = prosodyctl.show_warning;
-- Make a *one-way* subscription. User will see when contact is online,
-- contact will not see when user is online.
function subscribe(user_jid, contact_jid)
local user_username, user_host = jid.split(user_jid);
local contact_username, contact_host = jid.split(contact_jid);
if not hosts[user_host] then
warn("The host '%s' is not configured for this server.", user_host);
return;
end
storagemanager.initialize_host(user_host);
-- Update user's roster to say subscription request is pending...
rostermanager.set_contact_pending_out(user_username, user_host, contact_jid);
if hosts[contact_host] then
if contact_host ~= user_host then
storagemanager.initialize_host(contact_host);
end
-- Update contact's roster to say subscription request is pending...
rostermanager.set_contact_pending_in(contact_username, contact_host, user_jid);
-- Update contact's roster to say subscription request approved...
rostermanager.subscribed(contact_username, contact_host, user_jid);
-- Update user's roster to say subscription request approved...
rostermanager.process_inbound_subscription_approval(user_username, user_host, contact_jid);
end
end
-- Make a mutual subscription between jid1 and jid2. Each JID will see
-- when the other one is online.
function subscribe_both(jid1, jid2)
subscribe(jid1, jid2);
subscribe(jid2, jid1);
end
-- Unsubscribes user from contact (not contact from user, if subscribed).
function unsubscribe(user_jid, contact_jid)
local user_username, user_host = jid.split(user_jid);
local contact_username, contact_host = jid.split(contact_jid);
if not hosts[user_host] then
warn("The host '%s' is not configured for this server.", user_host);
return;
end
storagemanager.initialize_host(user_host);
-- Update user's roster to say subscription is cancelled...
rostermanager.unsubscribe(user_username, user_host, contact_jid);
if hosts[contact_host] then
if contact_host ~= user_host then
storagemanager.initialize_host(contact_host);
end
-- Update contact's roster to say subscription is cancelled...
rostermanager.unsubscribed(contact_username, contact_host, user_jid);
end
end
-- Cancel any subscription in either direction.
function unsubscribe_both(jid1, jid2)
unsubscribe(jid1, jid2);
unsubscribe(jid2, jid1);
end
-- Set the name shown and group used in the contact list
function rename(user_jid, contact_jid, contact_nick, contact_group)
local user_username, user_host = jid.split(user_jid);
if not hosts[user_host] then
warn("The host '%s' is not configured for this server.", user_host);
return;
end
storagemanager.initialize_host(user_host);
-- Load user's roster and find the contact
local roster = rostermanager.load_roster(user_username, user_host);
local item = roster[contact_jid];
if item then
if contact_nick then
item.name = contact_nick;
end
if contact_group then
item.groups = {}; -- Remove from all current groups
item.groups[contact_group] = true;
end
rostermanager.save_roster(user_username, user_host, roster);
end
end
function module.command(arg)
local command = arg[1];
if not command then
warn("Valid subcommands: (un)subscribe(_both) | rename");
return 0;
end
table.remove(arg, 1);
if command == "subscribe" then
subscribe(arg[1], arg[2]);
return 0;
elseif command == "subscribe_both" then
subscribe_both(arg[1], arg[2]);
return 0;
elseif command == "unsubscribe" then
unsubscribe(arg[1], arg[2]);
return 0;
elseif command == "unsubscribe_both" then
unsubscribe_both(arg[1], arg[2]);
return 0;
elseif command == "rename" then
rename(arg[1], arg[2], arg[3], arg[4]);
return 0;
else
warn("Unknown command: %s", command);
return 1;
end
return 0;
end
|
-----------------------------------------------------------
-- mod_roster_command: Manage rosters through prosodyctl
-- version 0.02
-----------------------------------------------------------
-- Copyright (C) 2011 Matthew Wild
-- Copyright (C) 2011 Adam Nielsen
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
-----------------------------------------------------------
if not rawget(_G, "prosodyctl") then
module:log("error", "Do not load this module in Prosody, for correct usage see: http://code.google.com/p/prosody-modules/wiki/mod_roster_command");
module.host = "*";
return;
end
-- Workaround for lack of util.startup...
_G.bare_sessions = _G.bare_sessions or {};
local rostermanager = require "core.rostermanager";
local storagemanager = require "core.storagemanager";
local jid = require "util.jid";
local warn = prosodyctl.show_warning;
-- Make a *one-way* subscription. User will see when contact is online,
-- contact will not see when user is online.
function subscribe(user_jid, contact_jid)
local user_username, user_host = jid.split(user_jid);
local contact_username, contact_host = jid.split(contact_jid);
if not hosts[user_host] then
warn("The host '%s' is not configured for this server.", user_host);
return;
end
storagemanager.initialize_host(user_host);
-- Update user's roster to say subscription request is pending...
rostermanager.set_contact_pending_out(user_username, user_host, contact_jid);
if hosts[contact_host] then
if contact_host ~= user_host then
storagemanager.initialize_host(contact_host);
end
-- Update contact's roster to say subscription request is pending...
rostermanager.set_contact_pending_in(contact_username, contact_host, user_jid);
-- Update contact's roster to say subscription request approved...
rostermanager.subscribed(contact_username, contact_host, user_jid);
-- Update user's roster to say subscription request approved...
rostermanager.process_inbound_subscription_approval(user_username, user_host, contact_jid);
end
end
-- Make a mutual subscription between jid1 and jid2. Each JID will see
-- when the other one is online.
function subscribe_both(jid1, jid2)
subscribe(jid1, jid2);
subscribe(jid2, jid1);
end
-- Unsubscribes user from contact (not contact from user, if subscribed).
function unsubscribe(user_jid, contact_jid)
local user_username, user_host = jid.split(user_jid);
local contact_username, contact_host = jid.split(contact_jid);
if not hosts[user_host] then
warn("The host '%s' is not configured for this server.", user_host);
return;
end
storagemanager.initialize_host(user_host);
-- Update user's roster to say subscription is cancelled...
rostermanager.unsubscribe(user_username, user_host, contact_jid);
if hosts[contact_host] then
if contact_host ~= user_host then
storagemanager.initialize_host(contact_host);
end
-- Update contact's roster to say subscription is cancelled...
rostermanager.unsubscribed(contact_username, contact_host, user_jid);
end
end
-- Cancel any subscription in either direction.
function unsubscribe_both(jid1, jid2)
unsubscribe(jid1, jid2);
unsubscribe(jid2, jid1);
end
-- Set the name shown and group used in the contact list
function rename(user_jid, contact_jid, contact_nick, contact_group)
local user_username, user_host = jid.split(user_jid);
if not hosts[user_host] then
warn("The host '%s' is not configured for this server.", user_host);
return;
end
storagemanager.initialize_host(user_host);
-- Load user's roster and find the contact
local roster = rostermanager.load_roster(user_username, user_host);
local item = roster[contact_jid];
if item then
if contact_nick then
item.name = contact_nick;
end
if contact_group then
item.groups = {}; -- Remove from all current groups
item.groups[contact_group] = true;
end
rostermanager.save_roster(user_username, user_host, roster);
end
end
function module.command(arg)
local command = arg[1];
if not command then
warn("Valid subcommands: (un)subscribe(_both) | rename");
return 0;
end
table.remove(arg, 1);
if command == "subscribe" then
subscribe(arg[1], arg[2]);
return 0;
elseif command == "subscribe_both" then
subscribe_both(arg[1], arg[2]);
return 0;
elseif command == "unsubscribe" then
unsubscribe(arg[1], arg[2]);
return 0;
elseif command == "unsubscribe_both" then
unsubscribe_both(arg[1], arg[2]);
return 0;
elseif command == "rename" then
rename(arg[1], arg[2], arg[3], arg[4]);
return 0;
else
warn("Unknown command: %s", command);
return 1;
end
return 0;
end
|
mod_roster_command: Fix traceback and log error message when loaded into Prosody (thanks epaulin)
|
mod_roster_command: Fix traceback and log error message when loaded into Prosody (thanks epaulin)
|
Lua
|
mit
|
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
|
339f1041d31453e1d75444784f86e7f94e140ba8
|
plugins/invite.lua
|
plugins/invite.lua
|
do
local function callbackres(extra, success, result) -- Callback for res_user in line 27
local user = 'user#id'..result.id
local chat = 'chat#id'..extra.chatid
if is_banned(result.id, extra.chatid) then -- Ignore bans
send_large_msg(chat, 'User is banned.')
elseif is_gbanned(result.id) then -- Ignore globall bans
send_large_msg(chat, 'User is globaly banned.')
else
chat_add_user(chat, user, ok_cb, false) -- Add user on chat
end
end
function run(msg, matches)
local data = load_data(_config.moderation.data)
if not is_realm(msg) then
if data[tostring(msg.to.id)]['settings']['lock_member'] == 'yes' and not is_admin(msg) then
return 'Group is private.'
end
end
if msg.to.type ~= 'chat' then
return
end
if not is_momod(msg) then
return
end
--if not is_admin(msg) then -- For admins only !
--return 'Only admins can invite.'
--end
local cbres_extra = {chatid = msg.to.id}
local username = matches[1]
local username = username:gsub("@","")
res_user(username, callbackres, cbres_extra)
end
return {
patterns = {
"^[!/]invite (.*)$"
},
run = run
}
end
|
do
local function callbackres(extra, success, result) -- Callback for res_user in line 27
local user = 'user#id'..result.id
local chat = 'chat#id'..extra.chatid
if is_banned(result.id, extra.chatid) then -- Ignore bans
send_large_msg(chat, 'User is banned.')
elseif is_gbanned(result.id) then -- Ignore globall bans
send_large_msg(chat, 'User is globaly banned.')
else
chat_add_user(chat, user, ok_cb, false) -- Add user on chat
end
end
function run(msg, matches)
local data = load_data(_config.moderation.data)
if not is_realm(msg) then
if data[tostring(msg.to.id)] and data[tostring(msg.to.id)]['settings']['lock_member'] == 'yes' and not is_admin(msg) then
return 'Group is private.'
end
end
if msg.to.type ~= 'chat' then
return
end
if not is_momod(msg) then
return
end
--if not is_admin(msg) then -- For admins only !
--return 'Only admins can invite.'
--end
local cbres_extra = {chatid = msg.to.id}
local username = matches[1]
local username = username:gsub("@","")
res_user(username, callbackres, cbres_extra)
end
return {
patterns = {
"^[!/]invite (.*)$"
},
run = run
}
end
|
FIX value nil
|
FIX value nil
|
Lua
|
agpl-3.0
|
Creedsteam/SuperCreed,NavidQuick/TeleSurena,MPCTeam/SpiderBot,persianTDT/TDT_BOT,hussian1997/bot-of-iraq,Abbasha/zxcabbasdd3,devwawi/VIP-TEAM_Wawi8,s4jj4d021/TgGuard,goldtgbot/GoldTG,sajjad0098/hitler_TG1,ehsanmoeenasa/mybot,CLiENTProJeCt/FeeDMaN,adel8268adelad/Bot-thebest,SPARKsaeedieckta/spark,Source-advan/hitler_TG1,mohammad2016mr/seed,amir0858/telesuper1,Privateblackl/addsBot,SurenaTeam/TeleSurena,vipbeko/VIPTEAM,teksaw/txw,Mrr619/TDself,bafgh/robati,s4jj4d021/TgGuard,teleRoOt3r/RoOt3r08,ara8586/9900,AnTiSpamTM/antispam,anupritaisno1/Clannadbot,SEEDTEAM/TeleSeed,SeyedKia/alpha,jkhlf85/THETETOO_8,BeyondTeam/TeleBeyond,Iliaaaaa/test,partgit/partbot,haker20154/TeleHelp,HajiMokh/hmhaji,anupritaisno1/Clannadbot,KnightTeam/Knight,HajiMokh/hajimokh,pokerparham/pokerbot,MoonTeamDev/TeleMoon,saman0903/abol0938,KingArmin/TeleIran,dalqak/slf,xsolinsx/AISasha,Mohammadrezar/telediamond,PARADOXTEAM/ParadoxBot,Alireza5928/abedzadeh,MahdiMafia/MAFIA,VIPTEA/vipteam2,cLxiX/SeedBasedBot,AaMegaTeam/AntiSpamV2,hussian1997/hhhuu,SF-TEAM/SF,beko123/DEV_VIP,abolfazl1/sambat,TeleBang/bangtg,kiarashlua/TeleSuper,ioiasff/ghg,jamalroyal995/pishrafte,ghost0099/red,mohammad2016mr/sed,speedteam-github/mega-SPEED,GiantCyber/Giants_TM,aliwar/migmig,sadikalknani/DEV_PRO,anupritaisno1/Clannadbot,primeplus2017/COMING_SOON,AntiSpamTelegram/Anti,mahdipilotts/mahdi,MahdiMafia/MAFIA,AntiSpamBot777/AntiBot,adixcompany/ADiX1,anupritaisno1/Clannadbot,Tele-Sped/Tele-Sped,TeleSudo/TeleRedStar,jdsfhsdbf65/test,ali-iraqi-bot/devil3_bot,Mohammadjkr/spam-bot,kiarashco/Kiava,meysamx0/Crazy,Knight-Team/KnightGuard-OLD-TG,aryangh/XYZ,Gold-Team-Bot/GoldTG,zozaiq18/DevZoma,master00041/maximus_bot,abbas007898/legenderia,SINGLECYBER/CyberSource,bangixy/apibot,MZ597/Mz597,neghabdar/neghabdar,ehsankohansal051/protective,YGS-CO/YGS,Telewolf-cli/TeleCli,alijoooon/melije,nicesource/PS,Milad0S/miladd,morteza1377/titann,Mohammadrezar/DarkDiamond,moj69/m,Alikey2ali/Alitaki5,Bambooir/TeleSeed,iranianboy/group,AaMegaTeam/Security-Tg,anupritaisno1/Clannadbot,Mhdl80/Mentalseed,adixcompany/ad2,devaloosh/VIPTEAM,KratosTeam/terminator,Iliaaaaa/test,aboshosho/aboshosho,teleaqrab/MR,mohammad056/Alvin2,icoowner/icorobot,stuxnettel/my,Sajjadhitler1/hitler_TG1,drslow/love
|
1c749c6914ba8059df7f31a630bfc6a7481e7652
|
utils/_actions/diskSpace.lua
|
utils/_actions/diskSpace.lua
|
local host = require("hs.host")
local fnutils = require("hs.fnutils")
local drawing = require("hs.drawing")
local stext = require("hs.styledtext")
local screen = require("hs.screen")
local disks = require("hs._asm.disks")
local volumesToIgnore = {}
local bytesToGB = 1024 * 1024 * 1024
local module = {}
module.textStyle = {
font = { name = "Menlo", size = 10 },
color = { alpha = 1.0 },
paragraphStyle = { alignment = "center" },
}
module.capacityColor = { list = "x11", name = "orangered" }
module.availableColor = { list = "x11", name = "mediumspringgreen" }
local round = function(number, scale)
scale = scale or 2
return math.floor(number * (10^scale) + .5) / (10^scale)
end
local mt = {}
for k, v in pairs(hs.getObjectMetatable("hs.drawing")) do
mt[k] = function(_, ...) for i = #_, 1, -1 do v(_[i], ...) end return _ end
end
mt.frame = function(_)
local rect = { x = math.huge, y = math.huge, ex = 0, ey = 0 }
for i,v in ipairs(_) do
local r = v:frame()
rect.x = math.min(rect.x, r.x)
rect.y = math.min(rect.y, r.y)
rect.ex = math.max(rect.ex, r.x + r.w)
rect.ey = math.max(rect.ey, r.y + r.h)
end
return { x = rect.x, y = rect.y, h = rect.ey - rect.y, w = rect.ex - rect.x }
end
mt.setTopLeft = function(_, t)
local full = mt.frame(_)
local delta = { x = t.x - full.x, y = t.y - full.y }
for i,v in ipairs(_) do
local r = v:frame()
v:setTopLeft{ x = r.x + delta.x, y = r.y + delta.y }
end
return _
end
module.ignore = function(host, state)
if not host then
local results = {}
for i,v in funutils.sortByKeys(volumesToIgnore) do table.insert(results, v) end
return results
else
if state then
volumesToIgnore[host] = true
else
volumesToIgnore[host] = nil
end
end
end
module.getStats = function()
local results = {}
for i,v in fnutils.sortByKeys(host.volumeInformation()) do
table.insert(results, {
v.NSURLVolumeNameKey,
round(v.NSURLVolumeTotalCapacityKey / bytesToGB),
round(v.NSURLVolumeAvailableCapacityKey / bytesToGB),
})
end
return results
end
module.drawAt = function(x,y)
local results = {}
local height, width, count = 0, 0, 0
local texts = {}
for i,v in ipairs(module.getStats()) do
-- table.insert(texts, v[1].."\nCapacity: "..v[2].." GB\nAvailable: "..v[3].." GB")
table.insert(texts, v[1].."\n"..v[3].." of "..v[2].." GB\nAvailable")
local tmp = drawing.getTextDrawingSize(texts[#texts], module.textStyle)
height, width = math.max(tmp.h, height), math.max(tmp.w, width)
end
width = width + 10
for i,v in ipairs(module.getStats()) do
table.insert(results, drawing.arc({
x = x + 10 + height / 2,
y = y + (height + 10) * count + 10 + height / 2,
}, height / 2, 0, 360 * (v[3] / v[2]))
:setFillColor(module.availableColor)
:setFill(true)
:setStroke(false)
:setAlpha(.7)
)
table.insert(results, drawing.circle{
x = x + 10,
y = y + (height + 10) * count + 10,
h = height,
w = height,
}:setFillColor(module.capacityColor)
:setFill(true)
:setStroke(false)
:setAlpha(.7)
)
table.insert(results, drawing.text({
x = x + height + 20,
y = y + (height + 10) * count + 10,
h = height,
w = width,
}, stext.new(texts[count + 1], module.textStyle))
:wantsLayer(true)
)
count = count + 1
end
table.insert(results, drawing.rectangle{
x = x, y = y, h = (height + 10) * count + 20, w = width + height + 30,
}:setFillColor{ alpha=.7, white = .5 }
:setStrokeColor{ alpha=.5 }
:setFill(true)
:setRoundedRectRadii(5,5)
)
return setmetatable(results, { __index = mt })
end
module.drawings = nil
module.updateDisplay = function()
local output = module.drawAt(22,100)
local frame = output:frame()
local screenFrame = screen.primaryScreen():frame()
frame.y = (screenFrame.y + screenFrame.h) - (frame.h) -- + 22)
output:setTopLeft(frame)
:setLevel(module.geekletInterface.level)
-- :wantsLayer(module.geekletInterface.layer)
:setBehaviorByLabels(module.geekletInterface.behavior)
if module.drawings then module.drawings:delete() end
module.drawings = output
if module.geekletInterface.visible then module.drawings:show() end
end
module.diskWatcher = disks.new(function(t, v)
-- we don't care about the type... it triggers an update either way
module.updateDisplay()
end):start()
module.geekletInterface = setmetatable({
visible = true,
level = drawing.windowLevels.desktopIcon,
behavior = {"default"},
}, {
__index = {
show = function(_)
module.geekletInterface.visible = true
module.drawings:show()
return _
end,
hide = function(_)
module.geekletInterface.visible = false
module.drawings:hide()
return _
end,
delete = function(_)
module.diskWatcher:stop()
module.drawings:delete()
return _
end,
setLevel = function(_, x)
module.geekletInterface.level = x
module.drawings:setLevel(x)
return _
end,
setBehaviorByLabels = function(_, x)
module.geekletInterface.behavior = x
module.drawings:setBehaviorByLabels(x)
return _
end,
orderBelow = function(_, x)
for i = #module.drawings, 2, -1 do
module.drawings[i]:orderBelow(module.drawings[1])
end
return _
end,
}
})
module.updateDisplay()
-- return setmetatable(module, {
-- __gc = function(_)
-- _.geekletInterface:delete()
-- end
-- })
return module
|
local host = require("hs.host")
local fnutils = require("hs.fnutils")
local drawing = require("hs.drawing")
local stext = require("hs.styledtext")
local screen = require("hs.screen")
local disks = require("hs._asm.disks")
local volumesToIgnore = {}
local bytesToGB = 1024 * 1024 * 1024
local module = {}
module.textStyle = {
font = { name = "Menlo", size = 10 },
color = { alpha = 1.0 },
paragraphStyle = { alignment = "center" },
}
module.capacityColor = { list = "x11", name = "orangered" }
module.availableColor = { list = "x11", name = "mediumspringgreen" }
local round = function(number, scale)
scale = scale or 2
return math.floor(number * (10^scale) + .5) / (10^scale)
end
local mt = {}
for k, v in pairs(hs.getObjectMetatable("hs.drawing")) do
mt[k] = function(_, ...) for i = #_, 1, -1 do v(_[i], ...) end return _ end
end
mt.frame = function(_)
local rect = { x = math.huge, y = math.huge, ex = 0, ey = 0 }
for i,v in ipairs(_) do
local r = v:frame()
rect.x = math.min(rect.x, r.x)
rect.y = math.min(rect.y, r.y)
rect.ex = math.max(rect.ex, r.x + r.w)
rect.ey = math.max(rect.ey, r.y + r.h)
end
return { x = rect.x, y = rect.y, h = rect.ey - rect.y, w = rect.ex - rect.x }
end
mt.setTopLeft = function(_, t)
local full = mt.frame(_)
local delta = { x = t.x - full.x, y = t.y - full.y }
for i,v in ipairs(_) do
local r = v:frame()
v:setTopLeft{ x = r.x + delta.x, y = r.y + delta.y }
end
return _
end
module.ignore = function(host, state)
if not host then
local results = {}
for i,v in funutils.sortByKeys(volumesToIgnore) do table.insert(results, v) end
return results
else
if state then
volumesToIgnore[host] = true
else
volumesToIgnore[host] = nil
end
end
end
module.getStats = function()
local results = {}
for i,v in fnutils.sortByKeys(host.volumeInformation()) do
table.insert(results, {
v.NSURLVolumeNameKey,
round(v.NSURLVolumeTotalCapacityKey / bytesToGB),
round(v.NSURLVolumeAvailableCapacityKey / bytesToGB),
})
end
return results
end
module.drawAt = function(x,y)
local results = {}
local height, width, count = 0, 0, 0
local texts = {}
for i,v in ipairs(module.getStats()) do
-- table.insert(texts, v[1].."\nCapacity: "..v[2].." GB\nAvailable: "..v[3].." GB")
table.insert(texts, v[1].."\n"..v[3].." of "..v[2].." GB\nAvailable")
local tmp = drawing.getTextDrawingSize(texts[#texts], module.textStyle)
height, width = math.max(tmp.h, height), math.max(tmp.w, width)
end
width = width + 10
for i,v in ipairs(module.getStats()) do
if v[2] ~= 0 then
table.insert(results, drawing.arc({
x = x + 10 + height / 2,
y = y + (height + 10) * count + 10 + height / 2,
}, height / 2, 0, 360 * (v[3] / v[2]))
:setFillColor(module.availableColor)
:setFill(true)
:setStroke(false)
:setAlpha(.7)
)
end
table.insert(results, drawing.circle{
x = x + 10,
y = y + (height + 10) * count + 10,
h = height,
w = height,
}:setFillColor(module.capacityColor)
:setFill(true)
:setStroke(false)
:setAlpha(.7)
)
table.insert(results, drawing.text({
x = x + height + 20,
y = y + (height + 10) * count + 10,
h = height,
w = width,
}, stext.new(texts[count + 1], module.textStyle))
:wantsLayer(true)
)
count = count + 1
end
table.insert(results, drawing.rectangle{
x = x, y = y, h = (height + 10) * count + 20, w = width + height + 30,
}:setFillColor{ alpha=.7, white = .5 }
:setStrokeColor{ alpha=.5 }
:setFill(true)
:setRoundedRectRadii(5,5)
)
return setmetatable(results, { __index = mt })
end
module.drawings = nil
module.updateDisplay = function()
local output = module.drawAt(22,100)
local frame = output:frame()
local screenFrame = screen.primaryScreen():frame()
frame.y = (screenFrame.y + screenFrame.h) - (frame.h) -- + 22)
output:setTopLeft(frame)
:setLevel(module.geekletInterface.level)
-- :wantsLayer(module.geekletInterface.layer)
:setBehaviorByLabels(module.geekletInterface.behavior)
if module.drawings then module.drawings:delete() end
module.drawings = output
if module.geekletInterface.visible then module.drawings:show() end
end
module.diskWatcher = disks.new(function(t, v)
-- we don't care about the type... it triggers an update either way
module.updateDisplay()
end):start()
module.geekletInterface = setmetatable({
visible = true,
level = drawing.windowLevels.desktopIcon,
behavior = {"default"},
}, {
__index = {
show = function(_)
module.geekletInterface.visible = true
module.drawings:show()
return _
end,
hide = function(_)
module.geekletInterface.visible = false
module.drawings:hide()
return _
end,
delete = function(_)
module.diskWatcher:stop()
module.drawings:delete()
return _
end,
setLevel = function(_, x)
module.geekletInterface.level = x
module.drawings:setLevel(x)
return _
end,
setBehaviorByLabels = function(_, x)
module.geekletInterface.behavior = x
module.drawings:setBehaviorByLabels(x)
return _
end,
orderBelow = function(_, x)
for i = #module.drawings, 2, -1 do
module.drawings[i]:orderBelow(module.drawings[1])
end
return _
end,
}
})
module.updateDisplay()
-- return setmetatable(module, {
-- __gc = function(_)
-- _.geekletInterface:delete()
-- end
-- })
return module
|
fix for when dmg size small enough available size effectively 0... need to scale instead in future update
|
fix for when dmg size small enough available size effectively 0... need to scale instead in future update
|
Lua
|
mit
|
asmagill/hammerspoon-config,asmagill/hammerspoon-config,asmagill/hammerspoon-config
|
1d9cb0c801f565802771e75e4972078d1624391e
|
fusion/core/lexer.lua
|
fusion/core/lexer.lua
|
local pretty = require("pl.pretty");
local re = require("re"); -- vim:set noet sts=0 sw=3 ts=3:
local defs = {}
pattern = re.compile([[
statement_list <- {| (statement ws)* |}
statement_block <- '{' ws statement_list ws '}'
statement <- (
assignment /
function_call
) ws ';' ws / (
statement_block
)
function_call <- {| '' -> 'function_call' (
value ws args /
value ws ':' ws variable ws args -- test
) |}
args <- '(' expression_list? ')'
assignment <- {| '' -> 'assignment'
{| variable_list ws '=' ws expression_list |}
|}
expression_list <- {:expression_list: {|
expression (ws ',' ws expression)*
|} :}
expression <-
value /
{| '' -> 'expression' (
unop ws value /
value ws binop ws expression
) |}
unop <- {:operator: [-!~#] :} {:type: '' -> 'un' :}
binop <- {:operator:
'-' /
'+' /
'*' /
'/'
:} {:type: '' -> 'bi' :}
value <-
literal /
variable /
'(' expression ')'
variable_list <- {:variable_list: {|
variable (ws ',' ws variable)*
|} :}
variable <- {| '' -> 'variable' {[A-Za-z_][A-Za-z0-9_]*} |}
literal <-
{| '' -> 'vararg' { '...' } |} /
number /
string /
{| '' -> 'boolean' { 'true' / 'false' } |} /
{| {'nil' -> 'nil'} |}
number <- {| '' -> 'number' (
base16num /
base10num
) |}
base10num <- {:type: '' -> 'base10' :} {
((integer '.' integer) /
(integer '.') /
('.' integer) /
integer) int_exponent?
}
integer <- [0-9]+
int_exponent <- [eE] [+-]? integer
base16num <- {:type: '' -> 'base16' :} {
'0' [Xx] [0-9A-Fa-f]+ hex_exponent?
}
hex_exponent <- [pP] [+-]? integer
string <- {| dqstring / sqstring / blstring |}
dqstring <- '' -> 'dqstring' '"' { (('\\' .) / ([^\r\n"]))* } '"'
sqstring <- '' -> 'sqstring' "'" { [^\r\n']* } "'"
blstring <- '' -> 'blstring' '[' {:eq: '='* :} '[' blclose
blclose <- ']' =eq ']' / . blclose
ws <- %s*
]], defs);
pretty.dump(pattern:match([[
a = -1;
]]));
|
local pretty = require("pl.pretty");
local re = require("re"); -- vim:set noet sts=0 sw=3 ts=3:
local defs = {}
pattern = re.compile([[
statement_list <- {| (statement ws)* |}
statement_block <- '{' ws statement_list ws '}'
statement <- (
assignment /
function_call
) ws ';' ws / (
statement_block
)
function_call <- {| '' -> 'function_call' (
value ws args /
value ws ':' ws variable ws args -- test
) |}
args <- '(' expression_list? ')'
assignment <- {| '' -> 'assignment'
{| variable_list ws '=' ws expression_list |}
|}
expression_list <- {:expression_list: {|
expression (ws ',' ws expression)*
|} :}
expression <-
binary_expression /
unary_expression /
value
binary_expression <- {| '' -> 'expression'
(unary_expression / value) ws binop ws expression
|}
unary_expression <- {| '' -> 'expression'
unop ws value
|}
unop <- {:operator: [-!~#] :} {:type: '' -> 'un' :}
binop <- {:operator:
'-' /
'+' /
'*' /
'/'
:} {:type: '' -> 'bi' :}
value <-
literal /
variable /
'(' expression ')'
variable_list <- {:variable_list: {|
variable (ws ',' ws variable)*
|} :}
variable <- {| '' -> 'variable' {[A-Za-z_][A-Za-z0-9_]*} |}
literal <-
{| '' -> 'vararg' { '...' } |} /
number /
string /
{| '' -> 'boolean' { 'true' / 'false' } |} /
{| {'nil' -> 'nil'} |}
number <- {| '' -> 'number' (
base16num /
base10num
) |}
base10num <- {:type: '' -> 'base10' :} {
((integer '.' integer) /
(integer '.') /
('.' integer) /
integer) int_exponent?
}
integer <- [0-9]+
int_exponent <- [eE] [+-]? integer
base16num <- {:type: '' -> 'base16' :} {
'0' [Xx] [0-9A-Fa-f]+ hex_exponent?
}
hex_exponent <- [pP] [+-]? integer
string <- {| dqstring / sqstring / blstring |}
dqstring <- '' -> 'dqstring' '"' { (('\\' .) / ([^\r\n"]))* } '"'
sqstring <- '' -> 'sqstring' "'" { [^\r\n']* } "'"
blstring <- '' -> 'blstring' '[' {:eq: '='* :} '[' blclose
blclose <- ']' =eq ']' / . blclose
ws <- %s*
]], defs);
pretty.dump(pattern:match([[
a = #5 + 1;
]]));
|
lexer.lua: fix binary and unary expressions
|
lexer.lua: fix binary and unary expressions
|
Lua
|
mit
|
RyanSquared/FusionScript
|
515688db79c25d344c09daa4a18befea50f1c2ee
|
lib/luvit.lua
|
lib/luvit.lua
|
-- clear some globals
-- This will break lua code written for other lua runtimes
_G.io = nil
_G.os = nil
_G.math = nil
_G.string = nil
_G.coroutine = nil
_G.jit = nil
_G.bit = nil
_G.debug = nil
_G.table = nil
local loadfile = _G.loadfile
_G.loadfile = nil
local dofile = _G.dofile
_G.dofile = nil
_G.print = nil
-- Load libraries used in this file
local Debug = require('debug')
local UV = require('uv')
local Env = require('env')
local Table = require('table')
local Utils = require('utils')
local FS = require('fs')
local TTY = require('tty')
local Emitter = require('emitter')
local Constants = require('constants')
local Path = require('path')
process = Emitter.new()
function process.exit(exit_code)
process:emit('exit', exit_code)
exit_process(exit_code or 0)
end
function process:add_handler_type(name)
local code = Constants[name]
if code then
UV.activate_signal_handler(code)
UV.unref()
end
end
function process:missing_handler_type(name, ...)
if name == "error" then
error(...)
elseif name == "SIGINT" or name == "SIGTERM" then
process.exit()
end
end
process.cwd = getcwd
_G.getcwd = nil
process.argv = argv
_G.argv = nil
local base_path = process.cwd()
-- Hide some stuff behind a metatable
local hidden = {}
setmetatable(_G, {__index=function(table, key)
if key == "__dirname" then
local source = Debug.getinfo(2, "S").source
if source:sub(1,1) == "@" then
return Path.join(base_path, Path.dirname(source:sub(2)))
end
return
elseif key == "__filename" then
local source = Debug.getinfo(2, "S").source
if source:sub(1,1) == "@" then
return Path.join(base_path, source:sub(2))
end
return
else
return hidden[key]
end
end})
local function hide(name)
hidden[name] = _G[name]
_G[name] = nil
end
hide("_G")
hide("exit_process")
-- Ignore sigpipe and exit cleanly on SIGINT and SIGTERM
-- These shouldn't hold open the event loop
UV.activate_signal_handler(Constants.SIGPIPE)
UV.unref()
UV.activate_signal_handler(Constants.SIGINT)
UV.unref()
UV.activate_signal_handler(Constants.SIGTERM)
UV.unref()
-- Load the tty as a pair of pipes
-- But don't hold the event loop open for them
process.stdin = TTY.new(0)
UV.unref()
process.stdout = TTY.new(1)
UV.unref()
local stdout = process.stdout
-- Replace print
function print(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = tostring(arguments[i])
end
stdout:write(Table.concat(arguments, "\t") .. "\n")
end
-- A nice global data dumper
function p(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = Utils.dump(arguments[i])
end
stdout:write(Table.concat(arguments, "\t") .. "\n")
end
-- Add global access to the environment variables using a dynamic table
process.env = setmetatable({}, {
__pairs = function (table)
local keys = Env.keys()
local index = 0
return function (...)
index = index + 1
local name = keys[index]
if name then
return name, table[name]
end
end
end,
__index = function (table, name)
return Env.get(name)
end,
__newindex = function (table, name, value)
if value then
Env.set(name, value, 1)
else
Env.unset(name)
end
end
})
-- This is called by all the event sources from C
-- The user can override it to hook into event sources
function event_source(name, fn, ...)
local args = {...}
return assert(xpcall(function ()
return fn(unpack(args))
end, Debug.traceback))
end
-- tries to load a module at a specified absolute path
-- TODO: make these error messages a little prettier
local function load_module(path, verbose)
local cname = "luaopen_" .. Path.basename(path)
-- Try the exact match first
local fn = loadfile(path)
if fn then return fn end
-- Then try with lua appended
fn = loadfile(path .. ".lua")
if fn then return fn end
-- Then try C addon with luvit appended
fn = package.loadlib(path .. ".luvit", cname)
if fn then return fn end
-- Then Try a folder with init.lua in it
fn = loadfile(path .. "/init.lua")
if fn then return fn end
-- Finally try the same for a C addon
fn = package.loadlib(path .. "/init.luvit", cname)
if fn then return fn end
return "\n\tCannot find module " .. path
end
-- Remove the cwd based loaders, we don't want them
package.loaders[2] = nil
package.loaders[3] = nil
package.loaders[4] = nil
package.path = nil
package.cpath = nil
package.searchpath = nil
package.seeall = nil
package.config = nil
_G.module = nil
-- Write our own loader that does proper relative requires of both lua scripts
-- and binary addons
package.loaders[2] = function (path)
local first = path:sub(1, 1)
-- Absolute requires
if first == "/" then
path = Path.normalize(path)
return load_module(path)
end
-- Relative requires
if first == "." then
local source = Debug.getinfo(3, "S").source
if source:sub(1, 1) == "@" then
path = Path.join(base_path, Path.dirname(source:sub(2)), path)
else
path = Path.join(base_path, path)
end
return load_module(path)
end
-- Bundled module search path
local errors = {}
local source = Debug.getinfo(3, "S").source
local dir
if source:sub(1, 1) == "@" then
dir = Path.join(base_path, Path.dirname(source:sub(2)), '@')
else
dir = Path.join(base_path, '@')
end
repeat
dir = dir:sub(1, dir:find("/[^/]+$") - 1)
local ret = load_module(dir .. "/modules/" .. path)
if type(ret) == "function" then return ret end
errors[#errors + 1] = ret
until #dir == 0
return Table.concat(errors, "")
end
-- Load the file given or start the interactive repl
if process.argv[1] then
dofile(process.argv[1])
else
require('repl')
end
-- Start the event loop
UV.run()
-- trigger exit handlers and exit cleanly
process.exit(0)
|
-- clear some globals
-- This will break lua code written for other lua runtimes
local IO = _G.io -- TODO: implement sync File I/O using libuv
_G.io = nil
_G.os = nil
_G.math = nil
_G.string = nil
_G.coroutine = nil
_G.jit = nil
_G.bit = nil
_G.debug = nil
_G.table = nil
_G.loadfile = nil
_G.dofile = nil
_G.print = nil
-- Load libraries used in this file
local Debug = require('debug')
local UV = require('uv')
local Env = require('env')
local Table = require('table')
local Utils = require('utils')
local FS = require('fs')
local TTY = require('tty')
local Emitter = require('emitter')
local Constants = require('constants')
local Path = require('path')
process = Emitter.new()
function process.exit(exit_code)
process:emit('exit', exit_code)
exit_process(exit_code or 0)
end
function process:add_handler_type(name)
local code = Constants[name]
if code then
UV.activate_signal_handler(code)
UV.unref()
end
end
function process:missing_handler_type(name, ...)
if name == "error" then
error(...)
elseif name == "SIGINT" or name == "SIGTERM" then
process.exit()
end
end
process.cwd = getcwd
_G.getcwd = nil
process.argv = argv
_G.argv = nil
local base_path = process.cwd()
-- Hide some stuff behind a metatable
local hidden = {}
setmetatable(_G, {__index=hidden})
local function hide(name)
hidden[name] = _G[name]
_G[name] = nil
end
hide("_G")
hide("exit_process")
-- Ignore sigpipe and exit cleanly on SIGINT and SIGTERM
-- These shouldn't hold open the event loop
UV.activate_signal_handler(Constants.SIGPIPE)
UV.unref()
UV.activate_signal_handler(Constants.SIGINT)
UV.unref()
UV.activate_signal_handler(Constants.SIGTERM)
UV.unref()
-- Load the tty as a pair of pipes
-- But don't hold the event loop open for them
process.stdin = TTY.new(0)
UV.unref()
process.stdout = TTY.new(1)
UV.unref()
local stdout = process.stdout
-- Replace print
function print(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = tostring(arguments[i])
end
stdout:write(Table.concat(arguments, "\t") .. "\n")
end
-- A nice global data dumper
function p(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = Utils.dump(arguments[i])
end
stdout:write(Table.concat(arguments, "\t") .. "\n")
end
-- Add global access to the environment variables using a dynamic table
process.env = setmetatable({}, {
__pairs = function (table)
local keys = Env.keys()
local index = 0
return function (...)
index = index + 1
local name = keys[index]
if name then
return name, table[name]
end
end
end,
__index = function (table, name)
return Env.get(name)
end,
__newindex = function (table, name, value)
if value then
Env.set(name, value, 1)
else
Env.unset(name)
end
end
})
-- This is called by all the event sources from C
-- The user can override it to hook into event sources
function event_source(name, fn, ...)
local args = {...}
return assert(xpcall(function ()
return fn(unpack(args))
end, Debug.traceback))
end
local global_meta = {__index=_G}
-- TODO: Implement sync I/O using libuv so we don't use this library
function myloadfile(path)
local file, error = IO.open(path, "rb")
if error then return nil, error end
local code = assert(file:read("*all"))
assert(file:close())
local fn = assert(loadstring(code, '@' .. path))
setfenv(fn, setmetatable({
__filename = path,
__dirname = Path.dirname(path)
}, global_meta))
return fn
end
-- tries to load a module at a specified absolute path
-- TODO: make these error messages a little prettier
local function load_module(path, verbose)
local cname = "luaopen_" .. Path.basename(path)
-- Try the exact match first
local fn = myloadfile(path)
if fn then return fn end
-- Then try with lua appended
fn = myloadfile(path .. ".lua")
if fn then return fn end
-- Then try C addon with luvit appended
fn = package.loadlib(path .. ".luvit", cname)
if fn then return fn end
-- Then Try a folder with init.lua in it
fn = myloadfile(path .. "/init.lua")
if fn then return fn end
-- Finally try the same for a C addon
fn = package.loadlib(path .. "/init.luvit", cname)
if fn then return fn end
return "\n\tCannot find module " .. path
end
-- Remove the cwd based loaders, we don't want them
package.loaders[2] = nil
package.loaders[3] = nil
package.loaders[4] = nil
package.path = nil
package.cpath = nil
package.searchpath = nil
package.seeall = nil
package.config = nil
_G.module = nil
-- Write our own loader that does proper relative requires of both lua scripts
-- and binary addons
package.loaders[2] = function (path)
local first = path:sub(1, 1)
-- Absolute requires
if first == "/" then
path = Path.normalize(path)
return load_module(path)
end
-- Relative requires
if first == "." then
local source = Debug.getinfo(3, "S").source
if source:sub(1, 1) == "@" then
path = Path.join(Path.dirname(source:sub(2)), path)
else
path = Path.join(base_path, path)
end
return load_module(path)
end
-- Bundled module search path
local errors = {}
local source = Debug.getinfo(3, "S").source
local dir
if source:sub(1, 1) == "@" then
dir = Path.dirname(source:sub(2)) .. "/@"
else
dir = base_path .. '/@'
end
repeat
dir = dir:sub(1, dir:find("/[^/]+$") - 1)
local ret = load_module(dir .. "/modules/" .. path)
if type(ret) == "function" then return ret end
errors[#errors + 1] = ret
until #dir == 0
return Table.concat(errors, "")
end
-- Load the file given or start the interactive repl
if process.argv[1] then
return assert(xpcall(function ()
assert(myloadfile(Path.resolve(base_path, process.argv[1])))()
end, Debug.traceback))
else
require('repl')
end
-- Start the event loop
UV.run()
-- trigger exit handlers and exit cleanly
process.exit(0)
|
Fix up module loading paths
|
Fix up module loading paths
|
Lua
|
apache-2.0
|
rjeli/luvit,AndrewTsao/luvit,AndrewTsao/luvit,sousoux/luvit,boundary/luvit,bsn069/luvit,sousoux/luvit,sousoux/luvit,boundary/luvit,boundary/luvit,sousoux/luvit,GabrielNicolasAvellaneda/luvit-upstream,luvit/luvit,boundary/luvit,rjeli/luvit,kaustavha/luvit,boundary/luvit,kaustavha/luvit,AndrewTsao/luvit,DBarney/luvit,DBarney/luvit,DBarney/luvit,brimworks/luvit,zhaozg/luvit,GabrielNicolasAvellaneda/luvit-upstream,sousoux/luvit,sousoux/luvit,connectFree/lev,kaustavha/luvit,GabrielNicolasAvellaneda/luvit-upstream,DBarney/luvit,rjeli/luvit,bsn069/luvit,connectFree/lev,zhaozg/luvit,luvit/luvit,boundary/luvit,bsn069/luvit,rjeli/luvit,GabrielNicolasAvellaneda/luvit-upstream
|
9a92efb1439dd0c3090f3caf9d95ff421f04d30a
|
lw-replay.lua
|
lw-replay.lua
|
package.path = package.path..";./?.lua;./?/init.lua;"
require 'config'
require 'irc'
cjson = require 'cjson'
local sleep = require 'socket'.sleep
local s = irc.new{nick = config.nick, username = config.username, realname = config.realname}
s:hook('OnChat', function(user, channel, message)
print(('[%s] %s: %s'):format(channel, user.nick, message))
if message == '.command' then
end
end)
s:connect(config.server)
for i, channel in ipairs(config.channels) do
s:join(channel)
end
s:sendChat('NickServ', 'identify '..config.password)
logs = io.open(config.dataFileName, "r")
lastTime = os.clock()
while true do
s:think()
if os.clock()-lastTime > 5 then
local m = cjson.decode(logs:read('*l'))
print(os.clock(), m[4])
s:sendChat(config.mainChannel, m[4])
sleep(config.refeshRate)
lastTime = os.clock()
end
--sleep((nextMessageTime < config.refeshRate) and nextMessageTime or config.refeshRate)
end
|
package.path = package.path..";./?.lua;./?/init.lua;"
require 'config'
require 'irc'
cjson = require 'cjson'
local sleep = require 'socket'.sleep
local s = irc.new{nick = config.nick, username = config.username, realname = config.realname}
s:hook('OnChat', function(user, channel, message)
if message:match('%.ff') then
speed = message:match('%.ff (.*)')
utcAdjust os.clock()
end
end)
s:connect(config.server)
for i, channel in ipairs(config.channels) do
s:join(channel)
end
s:sendChat('NickServ', 'identify '..config.password)
logs = io.open(config.dataFileName, "r")
m = cjson.decode(logs:read('*l'))
utcAdjust = os.clock()+20+m[2]
while true do
s:think()
if os.clock() > m[2]-utcAdjust then
s:sendChat(config.mainChannel, m[3]:match('(.-)!')..': '..m[4])
sleep(config.refeshRate)
m = cjson.decode(logs:read('*l'))
end
end
|
fixed time
|
fixed time
|
Lua
|
mit
|
Houshalter/lw-replay,Houshalter/lw-replay,Houshalter/lw-replay
|
fd3869ccc68d4853b18baf7fd7a7fb57a6191a34
|
languages/unicode.lua
|
languages/unicode.lua
|
local icu = require("justenoughicu")
local chardata = pl.pretty.load(pl.utils.readfile("lua-libraries/char-def.lua")).characters.data
SILE.nodeMakers.base = pl.class({
_init = function (self, options)
self.contents = {}
self.options = options
self.token = ""
self.lastnode = false
self.lasttype = false
end,
makeToken = function (self)
if #self.contents > 0 then
coroutine.yield(SILE.shaper:formNnode(self.contents, self.token, self.options))
SU.debug("tokenizer", "Token: "..self.token)
self.contents = {}
self.token = ""
self.lastnode = "nnode"
end
end,
addToken = function (self, char, item)
self.token = self.token .. char
table.insert(self.contents, item)
end,
makeGlue = function (self, item)
if SILE.settings.get("typesetter.obeyspaces") or self.lastnode ~= "glue" then
SU.debug("tokenizer", "Space node")
coroutine.yield(SILE.shaper:makeSpaceNode(self.options, item))
end
self.lastnode = "glue"
end,
makePenalty = function (self, p)
if self.lastnode ~= "penalty" and self.lastnode ~= "glue" then
coroutine.yield( SILE.nodefactory.newPenalty({ penalty = p or 0 }) )
end
self.lastnode = "penalty"
end,
iterator = function (_, _)
SU.error("Abstract function nodemaker:iterator called", true)
end,
charData = function (_, char)
local cp = SU.codepoint(char)
if not chardata[cp] then return {} end
return chardata[cp]
end,
isPunctuation = function (self, char)
return self.isPunctuationType[self:charData(char).category]
end,
isSpace = function (self, char)
return self.isSpaceType[self:charData(char).linebreak]
end,
isBreaking = function (self, char)
return self.isBreakingType[self:charData(char).linebreak]
end
})
SILE.nodeMakers.unicode = pl.class({
_base = SILE.nodeMakers.base,
isWordType = { cm = true },
isSpaceType = { sp = true },
isBreakingType = { ba = true, zw = true },
isPunctuationType = { po = true },
dealWith = function (self, item)
local char = item.text
local cp = SU.codepoint(char)
local thistype = chardata[cp] and chardata[cp].linebreak
if self:isSpace(item.text) then
self:makeToken()
self:makeGlue(item)
elseif self:isBreaking(item.text) then
self:addToken(char, item)
self:makeToken()
self:makePenalty(0)
elseif self.lasttype and (self.thistype and thistype ~= lasttype and not self.isWordType[thistype]) then
self:makeToken()
self:addToken(char, item)
else
self:letterspace()
self:addToken(char, item)
end
if not self.isWordType[thistype] then lasttype = chardata[cp] and chardata[cp].linebreak end
self.lasttype = thistype
end,
handleInitialGlue = function (self, items)
local i = 1
while i <= #items do
local item = items[i]
if self:isSpace(item.text) then self:makeGlue(item) else break end
i = i + 1
end
return i, items
end,
letterspace = function (self)
if not SILE.settings.get("document.letterspaceglue") then return end
if self.token then self:makeToken() end
if self.lastnode and self.lastnode ~= "glue" then
local w = SILE.settings.get("document.letterspaceglue").width
SU.debug("tokenizer", "Letter space glue: "..w)
coroutine.yield(SILE.nodefactory.newKern({ width = w }))
self.lastnode = "glue"
end
end,
isICUBreakHere = function (_, chunks, item)
return chunks[1] and (item.index >= chunks[1].index)
end,
handleICUBreak = function (self, chunks, item)
-- The ICU library has told us there is a breakpoint at
-- this index. We need to...
local bp = chunks[1]
-- ... remove this breakpoint (and any out of order ones)
-- from the ICU breakpoints array so that chunks[1] is
-- the next index point for comparison against the string...
while chunks[1] and item.index >= chunks[1].index do
table.remove(chunks, 1)
end
-- ...decide which kind of breakpoint we have here and
-- handle it appropriately.
if bp.type == "word" then
self:handleWordBreak(item)
elseif bp.type == "line" then
self:handleLineBreak(item, bp.subtype)
end
return chunks
end,
handleWordBreak = function (self, item)
self:makeToken()
if self:isSpace(item.text) then
-- Spacing word break
self:makeGlue(item)
else -- a word break which isn't a space
self:addToken(item.text, item)
end
end,
handleLineBreak = function (self, item, subtype)
-- Because we are in charge of paragraphing, we
-- will override space-type line breaks, and treat
-- them just as ordinary word spaces.
if self:isSpace(item.text) then
self:handleWordBreak(item)
return
end
-- But explicit line breaks we will turn into
-- soft and hard breaks.
self:makeToken()
self:makePenalty(subtype == "soft" and 0 or -1000)
self:addToken(item.text, item)
end,
iterator = function (self, items)
local fulltext = ""
for i = 1, #items do
fulltext = fulltext .. items[i].text
end
local chunks = { icu.breakpoints(fulltext, self.options.language) }
table.remove(chunks, 1)
return coroutine.wrap(function ()
local i
i, self.items = self:handleInitialGlue(items)
for j = i, #items do
self.i = j
self.item = self.items[self.i]
if self:isICUBreakHere(chunks, self.item) then
chunks = self:handleICUBreak(chunks, self.item)
else
self:dealWith(self.item)
end
end
self:makeToken()
end)
end
})
|
local icu = require("justenoughicu")
local chardata = pl.pretty.load(pl.utils.readfile("lua-libraries/char-def.lua")).characters.data
-- luacheck: globals lasttype
-- XXX - this is wrong and broken, but is also confusing. See bug #687
SILE.nodeMakers.base = pl.class({
_init = function (self, options)
self.contents = {}
self.options = options
self.token = ""
self.lastnode = false
self.lasttype = false
end,
makeToken = function (self)
if #self.contents > 0 then
coroutine.yield(SILE.shaper:formNnode(self.contents, self.token, self.options))
SU.debug("tokenizer", "Token: "..self.token)
self.contents = {}
self.token = ""
self.lastnode = "nnode"
end
end,
addToken = function (self, char, item)
self.token = self.token .. char
table.insert(self.contents, item)
end,
makeGlue = function (self, item)
if SILE.settings.get("typesetter.obeyspaces") or self.lastnode ~= "glue" then
SU.debug("tokenizer", "Space node")
coroutine.yield(SILE.shaper:makeSpaceNode(self.options, item))
end
self.lastnode = "glue"
end,
makePenalty = function (self, p)
if self.lastnode ~= "penalty" and self.lastnode ~= "glue" then
coroutine.yield( SILE.nodefactory.newPenalty({ penalty = p or 0 }) )
end
self.lastnode = "penalty"
end,
iterator = function (_, _)
SU.error("Abstract function nodemaker:iterator called", true)
end,
charData = function (_, char)
local cp = SU.codepoint(char)
if not chardata[cp] then return {} end
return chardata[cp]
end,
isPunctuation = function (self, char)
return self.isPunctuationType[self:charData(char).category]
end,
isSpace = function (self, char)
return self.isSpaceType[self:charData(char).linebreak]
end,
isBreaking = function (self, char)
return self.isBreakingType[self:charData(char).linebreak]
end
})
SILE.nodeMakers.unicode = pl.class({
_base = SILE.nodeMakers.base,
isWordType = { cm = true },
isSpaceType = { sp = true },
isBreakingType = { ba = true, zw = true },
isPunctuationType = { po = true },
dealWith = function (self, item)
local char = item.text
local cp = SU.codepoint(char)
local thistype = chardata[cp] and chardata[cp].linebreak
if self:isSpace(item.text) then
self:makeToken()
self:makeGlue(item)
elseif self:isBreaking(item.text) then
self:addToken(char, item)
self:makeToken()
self:makePenalty(0)
elseif self.lasttype and (self.thistype and thistype ~= lasttype and not self.isWordType[thistype]) then
self:makeToken()
self:addToken(char, item)
else
self:letterspace()
self:addToken(char, item)
end
if not self.isWordType[thistype] then lasttype = chardata[cp] and chardata[cp].linebreak end
self.lasttype = thistype
end,
handleInitialGlue = function (self, items)
local i = 1
while i <= #items do
local item = items[i]
if self:isSpace(item.text) then self:makeGlue(item) else break end
i = i + 1
end
return i, items
end,
letterspace = function (self)
if not SILE.settings.get("document.letterspaceglue") then return end
if self.token then self:makeToken() end
if self.lastnode and self.lastnode ~= "glue" then
local w = SILE.settings.get("document.letterspaceglue").width
SU.debug("tokenizer", "Letter space glue: "..w)
coroutine.yield(SILE.nodefactory.newKern({ width = w }))
self.lastnode = "glue"
end
end,
isICUBreakHere = function (_, chunks, item)
return chunks[1] and (item.index >= chunks[1].index)
end,
handleICUBreak = function (self, chunks, item)
-- The ICU library has told us there is a breakpoint at
-- this index. We need to...
local bp = chunks[1]
-- ... remove this breakpoint (and any out of order ones)
-- from the ICU breakpoints array so that chunks[1] is
-- the next index point for comparison against the string...
while chunks[1] and item.index >= chunks[1].index do
table.remove(chunks, 1)
end
-- ...decide which kind of breakpoint we have here and
-- handle it appropriately.
if bp.type == "word" then
self:handleWordBreak(item)
elseif bp.type == "line" then
self:handleLineBreak(item, bp.subtype)
end
return chunks
end,
handleWordBreak = function (self, item)
self:makeToken()
if self:isSpace(item.text) then
-- Spacing word break
self:makeGlue(item)
else -- a word break which isn't a space
self:addToken(item.text, item)
end
end,
handleLineBreak = function (self, item, subtype)
-- Because we are in charge of paragraphing, we
-- will override space-type line breaks, and treat
-- them just as ordinary word spaces.
if self:isSpace(item.text) then
self:handleWordBreak(item)
return
end
-- But explicit line breaks we will turn into
-- soft and hard breaks.
self:makeToken()
self:makePenalty(subtype == "soft" and 0 or -1000)
self:addToken(item.text, item)
end,
iterator = function (self, items)
local fulltext = ""
for i = 1, #items do
fulltext = fulltext .. items[i].text
end
local chunks = { icu.breakpoints(fulltext, self.options.language) }
table.remove(chunks, 1)
return coroutine.wrap(function ()
local i
i, self.items = self:handleInitialGlue(items)
for j = i, #items do
self.i = j
self.item = self.items[self.i]
if self:isICUBreakHere(chunks, self.item) then
chunks = self:handleICUBreak(chunks, self.item)
else
self:dealWith(self.item)
end
end
self:makeToken()
end)
end
})
|
style(languages): Make luacheck happy
|
style(languages): Make luacheck happy
This is a mess, but it’s a *known* mess. See bug #687
|
Lua
|
mit
|
alerque/sile,alerque/sile,alerque/sile,alerque/sile
|
73368d5593848cc3643b7453155989374d69aa26
|
kong/pdk/private/phases.lua
|
kong/pdk/private/phases.lua
|
local bit = require "bit"
local band = bit.band
local fmt = string.format
local ngx_get_phase = ngx.get_phase
local PHASES = {
--init = 0x00000001,
init_worker = 0x00000001,
certificate = 0x00000002,
--set = 0x00000004,
rewrite = 0x00000010,
access = 0x00000020,
balancer = 0x00000040,
response = 0x00000080,
--content = 0x00000100,
header_filter = 0x00000200,
body_filter = 0x00000400,
--timer = 0x00001000,
log = 0x00002000,
preread = 0x00004000,
error = 0x01000000,
admin_api = 0x10000000,
cluster_listener = 0x00000100,
}
do
local t = {}
for k, v in pairs(PHASES) do
t[k] = v
end
local n = 0
for k, v in pairs(t) do
n = n + 1
PHASES[v] = k
end
PHASES.n = n
end
local function new_phase(...)
return bit.bor(...)
end
local function get_phases_names(phases)
local names = {}
local n = 1
for _ = 1, PHASES.n do
if band(phases, n) ~= 0 and PHASES[n] then
table.insert(names, PHASES[n])
end
n = bit.lshift(n, 1)
end
return names
end
local function check_phase(accepted_phases)
if not kong or not kong.ctx then
-- no _G.kong, we are likely in tests
return
end
local current_phase = ngx.ctx.KONG_PHASE
if not current_phase then
if ngx_get_phase() == "content" then
-- treat custom content blocks as the Admin API
current_phase = PHASES.admin_api
else
error(fmt("no phase in ngx.ctx.KONG_PHASE, (need one of %s)",
table.concat(get_phases_names(accepted_phases), ", ")))
end
end
if band(current_phase, accepted_phases) ~= 0 then
return
end
local current_phase_name = PHASES[current_phase] or "'unknown phase'"
local accepted_phases_names = get_phases_names(accepted_phases)
error(fmt("function cannot be called in %s phase (only in: %s)",
current_phase_name,
table.concat(accepted_phases_names, ", ")))
end
local function check_not_phase(rejected_phases)
if not kong or not kong.ctx then
-- no _G.kong, we are likely in tests
return
end
local current_phase = ngx.ctx.KONG_PHASE
if not current_phase then
error("no phase in ngx.ctx.KONG_PHASE")
end
if band(current_phase, rejected_phases) == 0 then
return
end
local current_phase_name = PHASES[current_phase] or "'unknown phase'"
local rejected_phases_names = get_phases_names(rejected_phases)
error(fmt("function cannot be called in %s phase (can be called in any " ..
"phases except: %s)",
current_phase_name,
table.concat(rejected_phases_names, ", ")))
end
-- Exact phases + convenience aliases
local public_phases = setmetatable({
request = new_phase(PHASES.rewrite,
PHASES.access,
PHASES.response,
PHASES.header_filter,
PHASES.body_filter,
PHASES.log,
PHASES.error,
PHASES.admin_api,
PHASES.cluster_listener),
}, {
__index = function(t, k)
error("unknown phase or phase alias: " .. k)
end
})
for k, v in pairs(PHASES) do
public_phases[k] = v
end
return {
new = new_phase,
check = check_phase,
check_not = check_not_phase,
phases = public_phases,
}
|
local bit = require "bit"
local band = bit.band
local fmt = string.format
local ngx_get_phase = ngx.get_phase
local PHASES = {
--init = 0x00000001,
init_worker = 0x00000001,
certificate = 0x00000002,
--set = 0x00000004,
rewrite = 0x00000010,
access = 0x00000020,
balancer = 0x00000040,
response = 0x00000080,
--content = 0x00000100,
header_filter = 0x00000200,
body_filter = 0x00000400,
--timer = 0x00001000,
log = 0x00002000,
preread = 0x00004000,
error = 0x01000000,
admin_api = 0x10000000,
cluster_listener = 0x00000100,
}
do
local t = {}
for k, v in pairs(PHASES) do
t[k] = v
end
for k, v in pairs(t) do
PHASES[v] = k
end
-- max lshift limit, 2^30 = 0x40000000
PHASES.n = 30
end
local function new_phase(...)
return bit.bor(...)
end
local function get_phases_names(phases)
local names = {}
local n = 1
for _ = 1, PHASES.n do
if band(phases, n) ~= 0 and PHASES[n] then
table.insert(names, PHASES[n])
end
n = bit.lshift(n, 1)
end
return names
end
local function check_phase(accepted_phases)
if not kong or not kong.ctx then
-- no _G.kong, we are likely in tests
return
end
local current_phase = ngx.ctx.KONG_PHASE
if not current_phase then
if ngx_get_phase() == "content" then
-- treat custom content blocks as the Admin API
current_phase = PHASES.admin_api
else
error(fmt("no phase in ngx.ctx.KONG_PHASE, (need one of %s)",
table.concat(get_phases_names(accepted_phases), ", ")))
end
end
if band(current_phase, accepted_phases) ~= 0 then
return
end
local current_phase_name = PHASES[current_phase] or "'unknown phase'"
local accepted_phases_names = get_phases_names(accepted_phases)
error(fmt("function cannot be called in %s phase (only in: %s)",
current_phase_name,
table.concat(accepted_phases_names, ", ")))
end
local function check_not_phase(rejected_phases)
if not kong or not kong.ctx then
-- no _G.kong, we are likely in tests
return
end
local current_phase = ngx.ctx.KONG_PHASE
if not current_phase then
error("no phase in ngx.ctx.KONG_PHASE")
end
if band(current_phase, rejected_phases) == 0 then
return
end
local current_phase_name = PHASES[current_phase] or "'unknown phase'"
local rejected_phases_names = get_phases_names(rejected_phases)
error(fmt("function cannot be called in %s phase (can be called in any " ..
"phases except: %s)",
current_phase_name,
table.concat(rejected_phases_names, ", ")))
end
-- Exact phases + convenience aliases
local public_phases = setmetatable({
request = new_phase(PHASES.rewrite,
PHASES.access,
PHASES.response,
PHASES.header_filter,
PHASES.body_filter,
PHASES.log,
PHASES.error,
PHASES.admin_api,
PHASES.cluster_listener),
}, {
__index = function(t, k)
error("unknown phase or phase alias: " .. k)
end
})
for k, v in pairs(PHASES) do
public_phases[k] = v
end
return {
new = new_phase,
check = check_phase,
check_not = check_not_phase,
phases = public_phases,
}
|
fix(pdk) get_phases_names returns correct phase value for all phases (#8208)
|
fix(pdk) get_phases_names returns correct phase value for all phases (#8208)
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
82bf1abfc1e9343fa1d9e5b2812c8b7919c1da8b
|
premake4.lua
|
premake4.lua
|
solution "alloy"
configurations { "Debug", "Release" }
-- get data from shell
LLVM_OPTIONS = "--system-libs --libs "
LLVM_CONFIG = "core analysis executionengine jit interpreter native "
LLVM_CFLAGS = "$(" .. "llvm-config --cflags " .. LLVM_OPTIONS .. LLVM_CONFIG .. ")"
LLVM_LFLAGS = "$(" .. "llvm-config --ldflags " .. LLVM_OPTIONS .. LLVM_CONFIG .. ")"
-- common settings
defines { "_GNU_SOURCE", "__STDC_LIMIT_MACROS", "__STDC_CONSTANT_MACROS" }
buildoptions { LLVM_CFLAGS, "-pthread", "-xc" }
includedirs { "includes" }
links { "dl", "ncurses", "z" }
linkoptions { LLVM_LFLAGS, "-pthread", "-Wl,--as-needed -ltinfo" }
configuration "Debug"
flags { "Symbols", "ExtraWarnings", "FatalWarnings" }
configuration "Release"
buildoptions { "-march=native", "-O2" }
-- compiler
project "alloyc"
kind "ConsoleApp"
language "C++" -- because LLVM is a bitchling
files { "src/*.c", "src/*.h" }
|
solution "alloy"
configurations { "Debug", "Release" }
-- missing function
if not os.outputof then
function os.outputof(cmd)
local pipe = io.popen(cmd)
local result = pipe:read('*a')
pipe:close()
result = result:gsub ("\n", " ")
return result
end
end
-- get data from shell
LLVM_OPTIONS = "--system-libs --libs "
LLVM_CFLAGS = os.outputof ("llvm-config --cflags ")
LLVM_LFLAGS = os.outputof ("llvm-config --ldflags " .. LLVM_OPTIONS .. "all")
-- sanitize inputs
-- LLVM_CFLAGS = string.gsub (LLVM_CFLAGS, "\n", " ")
-- LLVM_LFLAGS = string.gsub (LLVM_LFLAGS, "\n", " ")
-- common settings
defines { "_GNU_SOURCE", "__STDC_LIMIT_MACROS", "__STDC_CONSTANT_MACROS" }
buildoptions { LLVM_CFLAGS, "-pthread", "-xc", "-O0" }
includedirs { "includes" }
links { "dl" }
linkoptions { LLVM_LFLAGS, "-pthread" }
if os.is ("linux") then
linkoptions { "-Wl,--as-needed -ltinfo" }
end
configuration "Debug"
flags { "Symbols", "ExtraWarnings" }
configuration "Release"
buildoptions { "-march=native", "-O2" }
-- compiler
project "alloyc"
kind "ConsoleApp"
language "C++" -- because LLVM is a bitchling
files { "src/*.c", "src/*.h" }
|
fix various premake/makefile/LLVM errors
|
fix various premake/makefile/LLVM errors
|
Lua
|
mit
|
8l/ark-c,8l/ark-c,naegelejd/ark,8l/ark-c,naegelejd/ark,naegelejd/ark
|
30824ce0d6b6c50c503ca5a8f94425dab9dd75f1
|
test_scripts/Polices/Validation_of_PolicyTables/Check_count_of_removals_for_bad_behavior_too_many_pending_requests.lua
|
test_scripts/Polices/Validation_of_PolicyTables/Check_count_of_removals_for_bad_behavior_too_many_pending_requests.lua
|
---------------------------------------------------------------------------------------------
-- See APPLINK-23481, APPLINK-16207
-- Requirement summary:
-- [Policies] "usage_and_error_counts" and "count_of_removals_for_bad_behavior" update
--
-- Description:
-- In case an application has been unregistered with any of:
-- -> TOO_MANY_PENDING_REQUESTS,
-- -> TOO_MANY_REQUESTS,
-- -> REQUEST_WHILE_IN_NONE_HMI_LEVEL resultCodes,
-- Policy Manager must increment "count_of_removals_for_bad_behavior" section value
-- of Local Policy Table for the corresponding application.
-- Pre-conditions:
-- a. SDL and HMI are started
-- b. application with appID is in any HMILevel other than NONE
-- Action:
-- Application is sending more requests than AppTimeScaleMaxRequests in AppRequestsTimeScale milliseconds:
-- appID->AnyRPC()
-- Expected:
-- 1. Application is unregistered:
-- SDL->appID: OnAppUnregistered(TO_MANY_REQUESTS)
-- Expected:
-- 3. PoliciesManager increments value of <count_of_removals_for_bad_behavior>
-- Thic
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
config.defaultProtocolVersion = 2
--[[ Required Shared libraries ]]
local commonSteps = require('user_modules/shared_testcases/commonSteps')
local commonFunctions = require('user_modules/shared_testcases/commonFunctions')
local mobile_session = require('mobile_session')
local Preconditions = require('user_modules/shared_testcases/commonPreconditions')
-- local variables
local count_of_requests = 10
local HMIAppID
--[[ General Precondition before ATF start ]]
commonSteps:DeleteLogsFileAndPolicyTable()
--[[ General Settings for configuration ]]
Test = require('connecttest')
require('cardinalities')
require('user_modules/AppTypes')
-- Precondition: application is activate
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test.Precondition_StopSDL()
StopSDL()
end
function Test.ChangeIniFile( )
Preconditions:BackupFile("smartDeviceLink.ini")
-- change AppTimeScaleMaxRequests and AppRequestsTimeScale
commonFunctions:write_parameter_to_smart_device_link_ini("AppTimeScaleMaxRequests", count_of_requests)
commonFunctions:write_parameter_to_smart_device_link_ini("AppRequestsTimeScale", 30000)
end
function Test.Precondition_StartSDL()
StartSDL(config.pathToSDL, config.ExitOnCrash)
end
function Test:Precondition_initHMI()
self:initHMI()
end
function Test:Precondition_initHMI_onReady()
self:initHMI_onReady()
end
function Test:Precondition_ConnectMobile()
self:connectMobile()
end
function Test:Precondition_StartSession()
self.mobileSession = mobile_session.MobileSession(self, self.mobileConnection)
end
function Test:RegisterApp()
self.mobileSession:StartService(7)
:Do(function (_,_)
local correlationId = self.mobileSession:SendRPC("RegisterAppInterface", config.application1.registerAppInterfaceParams)
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered")
:Do(function(_,data)
HMIAppID = data.params.application.appID
end)
EXPECT_RESPONSE(correlationId, { success = true })
EXPECT_NOTIFICATION("OnPermissionsChange")
end)
end
function Test:ActivateAppInFull()
commonSteps:ActivateAppInSpecificLevel(self,HMIAppID)
end
--[[ end of Preconditions ]]
function Test:Send_TOO_MANY_REQUESTS()
local count_of_sending_requests = count_of_requests + 10
for i = 1, count_of_sending_requests do
self.mobileSession:SendRPC("AddCommand",
{
cmdID = i,
menuParams =
{
position = 0,
menuName ="Command"..tostring(i)
}
})
end
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppUnregistered")
--mobile side: expect notification
EXPECT_NOTIFICATION("OnAppInterfaceUnregistered", {reason = "TOO_MANY_REQUESTS"})
end
function Test:RegisterApp2()
local correlationId = self.mobileSession:SendRPC("RegisterAppInterface", config.application1.registerAppInterfaceParams)
EXPECT_RESPONSE(correlationId, { success = false, resultCode = "TOO_MANY_PENDING_REQUESTS" })
end
function Test:Check_TOO_MANY_REQUESTS_in_DB()
local db_path = config.pathToSDL.."storage/policy.sqlite"
local sql_query = "SELECT count_of_removals_for_bad_behavior FROM app_level WHERE application_id = '" .. config.application1.registerAppInterfaceParams.appID .. "'"
local exp_result = 2
if commonFunctions:is_db_contains(db_path, sql_query, exp_result) == false then
self:FailTestCase("DB doesn't include expected value")
end
end
function Test.Postcondition_Stop_SDL()
StopSDL()
end
function Test.RestoreIniFile()
Preconditions:RestoreFile("smartDeviceLink.ini")
end
return Test
|
---------------------------------------------------------------------------------------------
-- Requirement summary:
-- [Policies] "usage_and_error_counts" and "count_of_removals_for_bad_behavior" update
--
-- Description:
-- In case an application has been unregistered with any of:
-- -> TOO_MANY_PENDING_REQUESTS,
-- -> TOO_MANY_REQUESTS,
-- -> REQUEST_WHILE_IN_NONE_HMI_LEVEL resultCodes,
-- Policy Manager must increment "count_of_removals_for_bad_behavior" section value
-- of Local Policy Table for the corresponding application.
-- Pre-conditions:
-- a. SDL and HMI are started
-- b. Application with appID is in any HMILevel other than NONE
-- Action:
-- Application is sending more requests than AppTimeScaleMaxRequests in AppRequestsTimeScale milliseconds:
-- appID->AnyRPC()
-- Expected:
-- Application is unregistered: SDL->appID: OnAppUnregistered(TOO_MANY_REQUESTS)
-- PoliciesManager increments value of <count_of_removals_for_bad_behavior>
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
config.defaultProtocolVersion = 2
--[[ Required Shared libraries ]]
local commonSteps = require('user_modules/shared_testcases/commonSteps')
local commonFunctions = require('user_modules/shared_testcases/commonFunctions')
local commonPreconditions = require("user_modules/shared_testcases/commonPreconditions")
local commonTestCases = require("user_modules/shared_testcases/commonTestCases")
-- local variables
local count_of_requests = 10
local start_time = 0
local finish_time = 0
--[[ General Precondition before ATF start ]]
commonFunctions:SDLForceStop()
commonSteps:DeleteLogsFileAndPolicyTable()
--[[ General Settings for configuration ]]
Test = require('connecttest')
require('cardinalities')
require('user_modules/AppTypes')
commonPreconditions:BackupFile("smartDeviceLink.ini")
commonFunctions:write_parameter_to_smart_device_link_ini("FrequencyCount", count_of_requests)
commonFunctions:write_parameter_to_smart_device_link_ini("FrequencyTime", "5000")
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test:ActivateApp()
local requestId1 = self.hmiConnection:SendRequest("SDL.ActivateApp", { appID = self.applications[config.application1.registerAppInterfaceParams.appName] })
EXPECT_HMIRESPONSE(requestId1)
:Do(function(_, d1)
if d1.result.isSDLAllowed ~= true then
local requestId2 = self.hmiConnection:SendRequest("SDL.GetUserFriendlyMessage", { language = "EN-US", messageCodes = { "DataConsent" } })
EXPECT_HMIRESPONSE(requestId2)
:Do(function()
self.hmiConnection:SendNotification("SDL.OnAllowSDLFunctionality", { allowed = true, source = "GUI", device = { id = config.deviceMAC, name = "127.0.0.1" } })
EXPECT_HMICALL("BasicCommunication.ActivateApp")
:Do(function(_, d2)
self.hmiConnection:SendResponse(d2.id,"BasicCommunication.ActivateApp", "SUCCESS", { })
self.mobileSession:ExpectNotification("OnHMIStatus", { hmiLevel = "FULL", audioStreamingState = "AUDIBLE", systemContext = "MAIN" })
end)
end)
end
end)
end
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
local received = false
function Test:RegisterNotification()
self.mobileSession:ExpectNotification("OnAppInterfaceUnregistered")
:Do(function(_, d)
if d.payload.reason == "TOO_MANY_REQUESTS" then
received = true
end
end)
:Pin()
:Times(AnyNumber())
end
local numRq = 0
local numRs = 0
function Test.DelayBefore()
commonTestCases:DelayedExp(5000)
RUN_AFTER(function() start_time = timestamp() end, 5000)
end
for i = 1, count_of_requests + 1 do
Test["RPC_" .. string.format("%02d", i)] = function(self)
commonTestCases:DelayedExp(50)
if not received then
local cid = self.mobileSession:SendRPC("ListFiles", { })
numRq = numRq + 1
if numRq <= count_of_requests then
EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS" })
:Do(function() numRs = numRs + 1 end)
end
end
end
end
function Test.DelayAfter()
finish_time = timestamp()
commonTestCases:DelayedExp(5000)
end
function Test:CheckTimeOut()
local processing_time = finish_time - start_time
print("Processing time: " .. processing_time)
if processing_time > 5000 then
self:FailTestCase("Processing time is more than 5 sec.")
end
end
function Test:CheckAppIsUnregistered()
print("Number of Sent RPCs: " .. numRq)
print("Number of Responses: " .. numRs)
if not received then
self:FailTestCase("OnAppInterfaceUnregistered(TOO_MANY_REQUESTS) is not received")
else
print("OnAppInterfaceUnregistered(TOO_MANY_REQUESTS) is received")
end
end
function Test:CheckRAINoSuccess()
local corId = self.mobileSession:SendRPC("RegisterAppInterface", config.application1.registerAppInterfaceParams)
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered"):Times(0)
self.mobileSession:ExpectResponse(corId, { success = false, resultCode = "TOO_MANY_PENDING_REQUESTS" }):Times(1)
self.mobileSession:ExpectNotification("OnHMIStatus"):Times(0)
self.mobileSession:ExpectNotification("OnPermissionsChange"):Times(0)
commonTestCases:DelayedExp(3000)
end
function Test:Check_TOO_MANY_REQUESTS_in_DB()
local db_path = commonPreconditions:GetPathToSDL() .. "storage/policy.sqlite"
local sql_query = "SELECT count_of_removals_for_bad_behavior FROM app_level WHERE application_id = '" .. config.application1.registerAppInterfaceParams.appID .. "'"
local exp_result = {"1"}
-- local act_result = commonFunctions:get_data_policy_sql(db_path, sql_query)
-- commonFunctions:printTable(act_result)
if commonFunctions:is_db_contains(db_path, sql_query, exp_result) == false then
self:FailTestCase("DB doesn't include expected value")
end
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test.RestoreFiles()
commonPreconditions:RestoreFile("smartDeviceLink.ini")
end
function Test.StopSDL()
StopSDL()
end
return Test
|
Fix script
|
Fix script
|
Lua
|
bsd-3-clause
|
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
|
3aaad4086837536984c96b5841889a52d7ea0a18
|
tests/test-colors.lua
|
tests/test-colors.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 utils = require('utils')
local dump = utils.dump
local strip = utils.strip
require('tap')(function (test)
test("Recursive values", function ()
local data = {a="value"}
data.data = data
local out = dump(data)
local stripped = strip(out)
print("recursive", out, dump(stripped))
assert(string.match(stripped, "{ a = 'value', data = table: 0x%x+ }"))
end)
test("string escapes", function ()
local tests = {
'\000\001\002\003\004\005\006\a\b\t\n\v\f\r\014\015', "'\\000\\001\\002\\003\\004\\005\\006\\a\\b\\t\\n\\v\\f\\r\\014\\015'",
'\016\017\018\019\020\021\022\023\024\025\026\027\028\029\030\031', "'\\016\\017\\018\\019\\020\\021\\022\\023\\024\\025\\026\\027\\028\\029\\030\\031'",
' !"#$%&\'()*+,-./', '\' !"#$%&\\\'()*+,-./\'',
'0123456789:;<=>?', "'0123456789:;<=>?'",
'@ABCDEFGHIJKLMNO', "'@ABCDEFGHIJKLMNO'",
'PQRSTUVWXYZ[\\]^_', "'PQRSTUVWXYZ[\\\\]^_'",
'`abcdefghijklmno', "'`abcdefghijklmno'",
'pqrstuvwxyz{|}', "'pqrstuvwxyz{|}'",
}
for i = 1, 16, 2 do
local out = dump(tests[i])
local stripped = strip(out)
print(out, dump(stripped))
assert(stripped == tests[i + 1])
end
end)
test("Smart quotes in string escapes", function ()
local tests = {
"It's a wonderful life",
'"It\'s a wonderful life"',
'To "quote" or not to "quote"...',
'\'To "quote" or not to "quote"...\'',
"I've always liked \"quotes\".",
'\'I\\\'ve always liked "quotes".\'',
}
for i = 1, 6, 2 do
local out = dump(tests[i])
local stripped = strip(out)
print(out, dump(stripped))
assert(stripped == tests[i + 1])
end
end)
test("Color mode switching", function ()
local data = {42,true,"A\nstring"}
utils.loadColors(false)
local plain = dump(data)
utils.loadColors()
print("plain", plain, dump(plain))
assert(plain == "{ 42, true, 'A\\nstring' }")
utils.loadColors(16)
local colored = dump(data)
utils.loadColors()
print("colored", colored, dump(colored))
assert(colored == "\027[1;30m{ \027[0m\027[1;33m42\027[0m\027[1;30m, \027[0m\027[0;33mtrue\027[0m\027[1;30m, \027[0m\027[1;32m'\027[0;32mA\027[1;32m\\n\027[0;32mstring\027[1;32m'\027[0m \027[1;30m}\027[0m")
utils.loadColors(256)
local super = dump(data)
utils.loadColors()
print("super", super, dump(super))
assert(super == "\027[38;5;247m{ \027[0m\027[38;5;202m42\027[0m\027[38;5;240m, \027[0m\027[38;5;220mtrue\027[0m\027[38;5;240m, \027[0m\027[38;5;40m'\027[38;5;34mA\027[38;5;46m\\n\027[38;5;34mstring\027[38;5;40m'\027[0m \027[38;5;247m}\027[0m")
end)
end)
|
--[[
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 utils = require('utils')
local dump = utils.dump
local strip = utils.strip
require('tap')(function (test)
test("Recursive values", function ()
local data = {a="value"}
data.data = data
local out = dump(data)
local stripped = strip(out)
print("recursive", out, dump(stripped))
-- iteration order is not consistent, so we need to check either ordering
local matches = string.match(stripped, "{ a = 'value', data = table: 0x%x+ }") ~= nil
matches = matches or string.match(stripped, "{ data = table: 0x%x+, a = 'value' }") ~= nil
assert(matches)
end)
test("string escapes", function ()
local tests = {
'\000\001\002\003\004\005\006\a\b\t\n\v\f\r\014\015', "'\\000\\001\\002\\003\\004\\005\\006\\a\\b\\t\\n\\v\\f\\r\\014\\015'",
'\016\017\018\019\020\021\022\023\024\025\026\027\028\029\030\031', "'\\016\\017\\018\\019\\020\\021\\022\\023\\024\\025\\026\\027\\028\\029\\030\\031'",
' !"#$%&\'()*+,-./', '\' !"#$%&\\\'()*+,-./\'',
'0123456789:;<=>?', "'0123456789:;<=>?'",
'@ABCDEFGHIJKLMNO', "'@ABCDEFGHIJKLMNO'",
'PQRSTUVWXYZ[\\]^_', "'PQRSTUVWXYZ[\\\\]^_'",
'`abcdefghijklmno', "'`abcdefghijklmno'",
'pqrstuvwxyz{|}', "'pqrstuvwxyz{|}'",
}
for i = 1, 16, 2 do
local out = dump(tests[i])
local stripped = strip(out)
print(out, dump(stripped))
assert(stripped == tests[i + 1])
end
end)
test("Smart quotes in string escapes", function ()
local tests = {
"It's a wonderful life",
'"It\'s a wonderful life"',
'To "quote" or not to "quote"...',
'\'To "quote" or not to "quote"...\'',
"I've always liked \"quotes\".",
'\'I\\\'ve always liked "quotes".\'',
}
for i = 1, 6, 2 do
local out = dump(tests[i])
local stripped = strip(out)
print(out, dump(stripped))
assert(stripped == tests[i + 1])
end
end)
test("Color mode switching", function ()
local data = {42,true,"A\nstring"}
utils.loadColors(false)
local plain = dump(data)
utils.loadColors()
print("plain", plain, dump(plain))
assert(plain == "{ 42, true, 'A\\nstring' }")
utils.loadColors(16)
local colored = dump(data)
utils.loadColors()
print("colored", colored, dump(colored))
assert(colored == "\027[1;30m{ \027[0m\027[1;33m42\027[0m\027[1;30m, \027[0m\027[0;33mtrue\027[0m\027[1;30m, \027[0m\027[1;32m'\027[0;32mA\027[1;32m\\n\027[0;32mstring\027[1;32m'\027[0m \027[1;30m}\027[0m")
utils.loadColors(256)
local super = dump(data)
utils.loadColors()
print("super", super, dump(super))
assert(super == "\027[38;5;247m{ \027[0m\027[38;5;202m42\027[0m\027[38;5;240m, \027[0m\027[38;5;220mtrue\027[0m\027[38;5;240m, \027[0m\027[38;5;40m'\027[38;5;34mA\027[38;5;46m\\n\027[38;5;34mstring\027[38;5;40m'\027[0m \027[38;5;247m}\027[0m")
end)
end)
|
Fix test-colors not being deterministic
|
Fix test-colors not being deterministic
Previously was relying on consistent iteration order in dump, which can't be relied on
|
Lua
|
apache-2.0
|
luvit/luvit,zhaozg/luvit,luvit/luvit,zhaozg/luvit
|
992b348f97f4dd78e1eb233da06dfba27e44e67a
|
neovim/lua/plugin/lspconfig.lua
|
neovim/lua/plugin/lspconfig.lua
|
local lsp_status = require('lsp-status')
lsp_status.register_progress()
require('lsp_signature').setup({
bind = true,
toggle_key = '<C-h>',
})
local function on_attach(client, bufnr)
vim.bo[bufnr].omnifunc = 'v:lua.vim.lsp.omnifunc'
require('which-key').register({
n = {
name = '+lsp',
d = { '<cmd>lua vim.lsp.buf.definition()<cr>', 'Definition' },
D = { '<cmd>lua vim.lsp.buf.declaration()<cr>', 'Declaration' },
t = { '<cmd>lua vim.lsp.buf.type_definition()<cr>', 'Type definition' },
i = { '<cmd>lua vim.lsp.buf.implementation()<cr>', 'Implementation' },
r = { '<cmd>lua vim.lsp.buf.references()<cr>', 'References' },
['[d'] = { '<cmd>lua vim.lsp.diagnostic.goto_prev()<cr>', 'Prev diagnostics' },
[']d'] = { '<cmd>lua vim.lsp.diagnostic.goto_next()<cr>', 'Prev diagnostics' },
w = {
name = 'workspaces',
a = { '<cmd>lua vim.lsp.buf.add_workspace_folder()<cr>', 'Add workspace' },
r = { '<cmd>lua vim.lsp.buf.remove_workspace_folder()<cr>', 'Remove workspace' },
l = { '<cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<cr>', 'List workspaces' },
},
a = {
name = 'Actions',
r = { '<cmd>lua vim.lsp.buf.rename()<cr>', 'Rename' },
c = { '<cmd>CodeActionMenu<cr>', 'Code action' },
C = { '<cmd>lua vim.lsp.buf.code_action()<cr>', 'Code action' },
e = { '<cmd>lua vim.lsp.diagnostic.show_line_diagnostics()<cr>', 'Line diagnostics' },
},
s = { [[<cmd>lua require('telescope.builtin').lsp_document_symbols()<cr>]], 'Symbols' },
q = { '<cmd>lua vim.lsp.diagnostic.set_loclist()<cr>', 'To loclist' },
},
}, {
prefix = '<leader>',
buffer = bufnr,
})
local function map(key, action)
vim.api.nvim_buf_set_keymap(bufnr, 'n', key, action, { noremap = true, silent = true })
end
map('K', '<cmd>lua vim.lsp.buf.hover()<cr>')
map('<C-h>', '<cmd>lua vim.lsp.buf.signature_help()<cr>')
vim.cmd([[
augroup lsp_buf_format
au! BufWritePre <buffer>
autocmd BufWritePre <buffer> lua vim.lsp.buf.formatting_sync()
augroup END
]])
lsp_status.on_attach(client)
end
local capabilities = vim.lsp.protocol.make_client_capabilities()
capabilities = vim.tbl_extend('keep', capabilities, lsp_status.capabilities)
capabilities = require('cmp_nvim_lsp').update_capabilities(capabilities)
local nvim_lsp = require('lspconfig')
local null_ls = require('null-ls')
null_ls.config({
sources = {
null_ls.builtins.formatting.stylua,
},
})
nvim_lsp['null-ls'].setup({
capabilities = capabilities,
on_attach = on_attach,
})
-- {{{ LUA
local sumneko_root_path = vim.fn.getenv('HOME') .. '/lua-language-server'
local sumneko_binary = sumneko_root_path .. '/bin/Linux/lua-language-server'
local runtime_path = vim.split(package.path, ';')
table.insert(runtime_path, 'lua/?.lua')
table.insert(runtime_path, 'lua/?/init.lua')
table.insert(runtime_path, 'lua/plugin/?.lua')
nvim_lsp.sumneko_lua.setup({
cmd = { sumneko_binary, '-E', sumneko_root_path .. '/main.lua' },
on_attach = on_attach,
capabilities = capabilities,
settings = {
Lua = {
runtime = {
version = 'LuaJIT',
path = runtime_path,
},
diagnostics = {
globals = { 'vim' },
},
workspace = {
library = vim.api.nvim_get_runtime_file('', true),
},
telemetry = {
enable = false,
},
},
},
})
-- }}}
|
local lsp_status = require('lsp-status')
lsp_status.register_progress()
require('lsp_signature').setup({
bind = true,
toggle_key = '<C-h>',
})
local function on_attach(client, bufnr)
vim.bo[bufnr].omnifunc = 'v:lua.vim.lsp.omnifunc'
require('which-key').register({
n = {
name = '+lsp',
d = { '<cmd>lua vim.lsp.buf.definition()<cr>', 'Definition' },
D = { '<cmd>lua vim.lsp.buf.declaration()<cr>', 'Declaration' },
t = { '<cmd>lua vim.lsp.buf.type_definition()<cr>', 'Type definition' },
i = { '<cmd>lua vim.lsp.buf.implementation()<cr>', 'Implementation' },
r = { '<cmd>lua vim.lsp.buf.references()<cr>', 'References' },
['[d'] = { '<cmd>lua vim.lsp.diagnostic.goto_prev()<cr>', 'Prev diagnostics' },
[']d'] = { '<cmd>lua vim.lsp.diagnostic.goto_next()<cr>', 'Prev diagnostics' },
w = {
name = 'workspaces',
a = { '<cmd>lua vim.lsp.buf.add_workspace_folder()<cr>', 'Add workspace' },
r = { '<cmd>lua vim.lsp.buf.remove_workspace_folder()<cr>', 'Remove workspace' },
l = { '<cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<cr>', 'List workspaces' },
},
a = {
name = 'Actions',
r = { '<cmd>lua vim.lsp.buf.rename()<cr>', 'Rename' },
c = { '<cmd>CodeActionMenu<cr>', 'Code action' },
C = { '<cmd>lua vim.lsp.buf.code_action()<cr>', 'Code action' },
e = { '<cmd>lua vim.lsp.diagnostic.show_line_diagnostics()<cr>', 'Line diagnostics' },
},
s = { [[<cmd>lua require('telescope.builtin').lsp_document_symbols()<cr>]], 'Symbols' },
q = { '<cmd>lua vim.lsp.diagnostic.set_loclist()<cr>', 'To loclist' },
},
}, {
prefix = '<leader>',
buffer = bufnr,
})
local function map(key, action)
vim.api.nvim_buf_set_keymap(bufnr, 'n', key, action, { noremap = true, silent = true })
end
map('K', '<cmd>lua vim.lsp.buf.hover()<cr>')
map('<C-h>', '<cmd>lua vim.lsp.buf.signature_help()<cr>')
vim.cmd([[
augroup lsp_buf_format
au! BufWritePre <buffer>
autocmd BufWritePre <buffer> lua vim.lsp.buf.formatting_sync()
augroup END
]])
lsp_status.on_attach(client)
end
local capabilities = vim.lsp.protocol.make_client_capabilities()
capabilities = vim.tbl_extend('keep', capabilities, lsp_status.capabilities)
capabilities = require('cmp_nvim_lsp').update_capabilities(capabilities)
local nvim_lsp = require('lspconfig')
local null_ls = require('null-ls')
null_ls.config({
sources = {
null_ls.builtins.formatting.stylua,
},
})
nvim_lsp['null-ls'].setup({
capabilities = capabilities,
on_attach = on_attach,
})
-- {{{ LUA
local sumneko_root_path = vim.fn.getenv('HOME') .. '/lua-language-server'
local sumneko_binary = sumneko_root_path .. '/bin/Linux/lua-language-server'
local runtime_path = vim.split(package.path, ';')
table.insert(runtime_path, 'lua/?.lua')
table.insert(runtime_path, 'lua/?/init.lua')
table.insert(runtime_path, 'lua/plugin/?.lua')
nvim_lsp.sumneko_lua.setup({
cmd = { sumneko_binary, '-E', sumneko_root_path .. '/main.lua' },
on_attach = on_attach,
capabilities = capabilities,
settings = {
Lua = {
runtime = {
version = 'LuaJIT',
path = runtime_path,
},
diagnostics = {
globals = { 'vim' },
},
workspace = {
library = vim.api.nvim_get_runtime_file('', true),
},
telemetry = {
enable = false,
},
completion = { callSnippet = 'Replace' },
},
},
})
-- }}}
|
Fix completion snippet for lua
|
Fix completion snippet for lua
|
Lua
|
mit
|
MPogoda/dotfiles
|
0814fd90b422af25d815ac73a5be87c152e19d86
|
src/apps/bridge/flooding.lua
|
src/apps/bridge/flooding.lua
|
-- Use of this source code is governed by the Apache 2.0 license; see COPYING.
-- This class derives from lib.bridge.base and implements the simplest
-- possible bridge, which floods a packet arriving on a port to all
-- destination ports within its scope according to the split-horizon
-- topology.
module(..., package.seeall)
local bridge_base = require("apps.bridge.base").bridge
local packet = require("core.packet")
local link = require("core.link")
local empty, receive, transmit = link.empty, link.receive, link.transmit
local clone = packet.clone
bridge = subClass(bridge_base)
bridge._name = "flooding bridge"
function bridge:new (arg)
return bridge:superClass().new(self, arg)
end
function bridge:push()
local src_ports = self._src_ports
local dst_ports = self._dst_ports
local output = self.output
local i = 1
while src_ports[i] do
local src_port = src_ports[i]
local l_in = self.input[src_port]
while not empty(l_in) do
local ports = dst_ports[src_port]
local p = receive(l_in)
transmit(output[ports[1]], p)
local j = 2
while ports[j] do
transmit(output[ports[j]], clone(p))
j = j + 1
end
end
i = i + 1
end
end
|
-- Use of this source code is governed by the Apache 2.0 license; see COPYING.
-- This class derives from lib.bridge.base and implements the simplest
-- possible bridge, which floods a packet arriving on a port to all
-- destination ports within its scope according to the split-horizon
-- topology.
module(..., package.seeall)
local bridge_base = require("apps.bridge.base").bridge
local packet = require("core.packet")
local link = require("core.link")
local empty, receive, transmit = link.empty, link.receive, link.transmit
local clone = packet.clone
bridge = subClass(bridge_base)
bridge._name = "flooding bridge"
function bridge:new (arg)
return bridge:superClass().new(self, arg)
end
function bridge:push()
local ports = self._ports
local dst_ports = self._dst_ports
local i = 1
while ports[i] do
local l_in = ports[i].l_in
while not empty(l_in) do
local dst = dst_ports[i]
local p = receive(l_in)
transmit(ports[dst[1]].l_out, p)
local j = 2
while dst[j] do
transmit(ports[dst[j]].l_out, clone(p))
j = j + 1
end
end
i = i + 1
end
end
|
apps.bridge.flooding: Fix regression introduced by 4b4b8ad / #638.
|
apps.bridge.flooding: Fix regression introduced by 4b4b8ad / #638.
|
Lua
|
apache-2.0
|
kbara/snabb,dpino/snabbswitch,snabbco/snabb,wingo/snabb,wingo/snabb,eugeneia/snabb,wingo/snabb,Igalia/snabbswitch,wingo/snabbswitch,wingo/snabbswitch,dpino/snabb,snabbco/snabb,snabbco/snabb,alexandergall/snabbswitch,alexandergall/snabbswitch,mixflowtech/logsensor,Igalia/snabb,alexandergall/snabbswitch,Igalia/snabb,snabbco/snabb,Igalia/snabbswitch,snabbco/snabb,dpino/snabbswitch,snabbco/snabb,wingo/snabb,eugeneia/snabb,eugeneia/snabb,SnabbCo/snabbswitch,eugeneia/snabb,alexandergall/snabbswitch,dpino/snabb,Igalia/snabbswitch,eugeneia/snabbswitch,eugeneia/snabb,eugeneia/snabbswitch,alexandergall/snabbswitch,snabbco/snabb,Igalia/snabb,kbara/snabb,SnabbCo/snabbswitch,mixflowtech/logsensor,heryii/snabb,dpino/snabb,wingo/snabb,heryii/snabb,Igalia/snabb,Igalia/snabbswitch,dpino/snabb,dpino/snabbswitch,SnabbCo/snabbswitch,dpino/snabb,alexandergall/snabbswitch,heryii/snabb,eugeneia/snabbswitch,kbara/snabb,mixflowtech/logsensor,mixflowtech/logsensor,Igalia/snabb,eugeneia/snabbswitch,heryii/snabb,alexandergall/snabbswitch,Igalia/snabbswitch,eugeneia/snabb,alexandergall/snabbswitch,Igalia/snabb,Igalia/snabb,SnabbCo/snabbswitch,dpino/snabb,wingo/snabb,kbara/snabb,heryii/snabb,eugeneia/snabb,dpino/snabb,eugeneia/snabb,mixflowtech/logsensor,dpino/snabbswitch,kbara/snabb,wingo/snabbswitch,snabbco/snabb,Igalia/snabb,kbara/snabb,wingo/snabbswitch,heryii/snabb
|
651117438ab71cbbe9b0690fa413bb75d1ef9f07
|
tests/libs/tap.lua
|
tests/libs/tap.lua
|
--[[
Copyright 2014 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.
--]]
exports.name = "luvit/tap"
exports.version = "0.1.1"
exports.dependencies = {
"luvit/pretty-print@1.0.2"
}
exports.license = "Apache 2"
exports.homepage = "https://github.com/luvit/luvit/blob/master/tests/libs/tap.lua"
exports.description = "Libuv loop based test runner with tap output."
exports.tags = {"test", "tap"}
local uv = require('uv')
local colorize = require('pretty-print').colorize
-- Capture output from global print and prefix with two spaces
local print = _G.print
_G.print = function (...)
local n = select('#', ...)
local arguments = {...}
for i = 1, n do
arguments[i] = tostring(arguments[i])
end
local text = table.concat(arguments, "\t")
text = " " .. string.gsub(text, "\n", "\n ")
print(text)
end
local tests = {};
local function run()
local passed = 0
if #tests < 1 then
error("No tests specified!")
end
print("1.." .. #tests)
for i = 1, #tests do
local test = tests[i]
local cwd = uv.cwd()
local preexisting = {}
uv.walk(function (handle)
preexisting[handle] = true
end)
print("\n# Starting Test: " .. colorize("highlight", test.name))
local pass, err = xpcall(function ()
local expected = 0
local err
local function expect(fn, count)
expected = expected + (count or 1)
return function (...)
expected = expected - 1
local success, ret = pcall(fn, ...)
if not success then err = ret end
collectgarbage()
return ret
end
end
test.fn(expect)
collectgarbage()
uv.run()
collectgarbage()
if err then error(err) end
if expected > 0 then
error("Missing " .. expected .. " expected call" .. (expected == 1 and "" or "s"))
elseif expected < 0 then
error("Found " .. -expected .. " unexpected call" .. (expected == -1 and "" or "s"))
end
collectgarbage()
local unclosed = 0
uv.walk(function (handle)
if preexisting[handle] then return end
unclosed = unclosed + 1
print("UNCLOSED", handle)
end)
if unclosed > 0 then
error(unclosed .. " unclosed handle" .. (unclosed == 1 and "" or "s"))
end
if uv.cwd() ~= cwd then
error("Test moved cwd from " .. cwd .. " to " .. uv.cwd())
end
collectgarbage()
end, debug.traceback)
-- Flush out any more opened handles
uv.stop()
uv.walk(function (handle)
if preexisting[handle] or uv.is_closing(handle) then return end
uv.close(handle)
end)
-- Wait for the close calls to finish
uv.run()
-- Reset the cwd if the script changed it.
uv.chdir(cwd)
if pass then
print("ok " .. i .. " " .. colorize("success", test.name))
passed = passed + 1
else
_G.print(colorize("err", err))
print("not ok " .. i .. " " .. colorize("failure", test.name))
end
end
local failed = #tests - passed
if failed == 0 then
print("# All tests passed")
else
print("#" .. failed .. " failed test" .. (failed == 1 and "" or "s"))
end
-- Close all then handles, including stdout
uv.walk(uv.close)
uv.run()
os.exit(-failed)
end
local single = true
local prefix
local function tap(suite)
if type(suite) == "function" then
-- Pass in suite directly for single mode
suite(function (name, fn)
if prefix then
name = prefix .. ' - ' .. name
end
tests[#tests + 1] = {
name = name,
fn = fn
}
end)
prefix = nil
elseif type(suite) == "string" then
prefix = suite
single = false
else
-- Or pass in false to collect several runs of tests
-- And then pass in true in a later call to flush tests queue.
single = suite
end
if single then run() end
end
return tap
|
--[[
Copyright 2014 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.
--]]
exports.name = "luvit/tap"
exports.version = "0.1.1"
exports.dependencies = {
"luvit/pretty-print@1.0.2"
}
exports.license = "Apache 2"
exports.homepage = "https://github.com/luvit/luvit/blob/master/tests/libs/tap.lua"
exports.description = "Libuv loop based test runner with tap output."
exports.tags = {"test", "tap"}
local uv = require('uv')
local colorize = require('pretty-print').colorize
-- Capture output from global print and prefix with two spaces
local print = _G.print
_G.print = function (...)
local n = select('#', ...)
local arguments = {...}
for i = 1, n do
arguments[i] = tostring(arguments[i])
end
local text = table.concat(arguments, "\t")
text = " " .. string.gsub(text, "\n", "\n ")
print(text)
end
local tests = {};
local function run()
local passed = 0
if #tests < 1 then
error("No tests specified!")
end
print("1.." .. #tests)
for i = 1, #tests do
local test = tests[i]
local cwd = uv.cwd()
local preexisting = {}
uv.walk(function (handle)
preexisting[handle] = true
end)
print("\n# Starting Test: " .. colorize("highlight", test.name))
local pass, err = xpcall(function ()
local expected = 0
local err
local function expect(fn, count)
expected = expected + (count or 1)
return function (...)
expected = expected - 1
local success, ret = pcall(fn, ...)
if not success then err = ret end
collectgarbage()
return ret
end
end
test.fn(expect)
collectgarbage()
uv.run()
collectgarbage()
if err then error(err) end
if expected > 0 then
error("Missing " .. expected .. " expected call" .. (expected == 1 and "" or "s"))
elseif expected < 0 then
error("Found " .. -expected .. " unexpected call" .. (expected == -1 and "" or "s"))
end
collectgarbage()
local unclosed = 0
uv.walk(function (handle)
if preexisting[handle] then return end
unclosed = unclosed + 1
print("UNCLOSED", handle)
end)
if unclosed > 0 then
error(unclosed .. " unclosed handle" .. (unclosed == 1 and "" or "s"))
end
if uv.cwd() ~= cwd then
error("Test moved cwd from " .. cwd .. " to " .. uv.cwd())
end
collectgarbage()
end, debug.traceback)
-- Flush out any more opened handles
uv.stop()
uv.walk(function (handle)
if preexisting[handle] or uv.is_closing(handle) then return end
uv.close(handle)
end)
-- Wait for the close calls to finish
uv.run()
-- Reset the cwd if the script changed it.
uv.chdir(cwd)
if pass then
print("ok " .. i .. " " .. colorize("success", test.name))
passed = passed + 1
else
_G.print(colorize("err", err))
print("not ok " .. i .. " " .. colorize("failure", test.name))
end
end
local failed = #tests - passed
if failed == 0 then
print("# All tests passed")
else
print("#" .. failed .. " failed test" .. (failed == 1 and "" or "s"))
end
-- Close all then handles, including stdout
uv.walk(function(handle)
if not uv.is_closing(handle) then uv.close(handle) end
end)
uv.run()
os.exit(-failed)
end
local single = true
local prefix
local function tap(suite)
if type(suite) == "function" then
-- Pass in suite directly for single mode
suite(function (name, fn)
if prefix then
name = prefix .. ' - ' .. name
end
tests[#tests + 1] = {
name = name,
fn = fn
}
end)
prefix = nil
elseif type(suite) == "string" then
prefix = suite
single = false
else
-- Or pass in false to collect several runs of tests
-- And then pass in true in a later call to flush tests queue.
single = suite
end
if single then run() end
end
return tap
|
tap: check for closing handles in shutdown
|
tap: check for closing handles in shutdown
fix #839
|
Lua
|
apache-2.0
|
zhaozg/luvit,luvit/luvit,zhaozg/luvit,luvit/luvit
|
039370c2fc95443ef2564fa03ce90e514d5f08f4
|
src/spy.lua
|
src/spy.lua
|
-- module will return spy table, and register its assertions with the main assert engine
local assert = require('luassert.assert')
local util = require('luassert.util')
-- Spy metatable
local spy_mt = {
__call = function(self, ...)
local arguments = {...}
arguments.n = select('#',...) -- add argument count for trailing nils
table.insert(self.calls, util.deepcopy(arguments))
local function get_returns(...)
local returnvals = {...}
returnvals.n = select('#',...) -- add argument count for trailing nils
table.insert(self.returnvals, util.deepcopy(returnvals))
return ...
end
return get_returns(self.callback(...))
end
}
local spy -- must make local before defining table, because table contents refers to the table (recursion)
spy = {
new = function(callback)
if not util.callable(callback) then
error("Cannot spy on type '" .. type(callback) .. "', only on functions or callable elements", 2)
end
local s = setmetatable({
calls = {},
returnvals = {},
callback = callback,
target_table = nil, -- these will be set when using 'spy.on'
target_key = nil,
revert = function(self)
if not self.reverted then
if self.target_table and self.target_key then
self.target_table[self.target_key] = self.callback
end
self.reverted = true
end
return self.callback
end,
clear = function(self)
self.calls = {}
self.returnvals = {}
return self
end,
called = function(self, times, compare)
if times or compare then
local compare = compare or function(count, expected) return count == expected end
return compare(#self.calls, times), #self.calls
end
return (#self.calls > 0), #self.calls
end,
called_with = function(self, args)
return util.matchargs(self.calls, args) ~= nil
end,
returned_with = function(self, args)
return util.matchargs(self.returnvals, args) ~= nil
end
}, spy_mt)
assert:add_spy(s) -- register with the current state
return s
end,
is_spy = function(object)
return type(object) == "table" and getmetatable(object) == spy_mt
end,
on = function(target_table, target_key)
local s = spy.new(target_table[target_key])
target_table[target_key] = s
-- store original data
s.target_table = target_table
s.target_key = target_key
return s
end
}
local function set_spy(state, arguments, level)
state.payload = arguments[1]
if arguments[2] ~= nil then
state.failure_message = arguments[2]
end
end
local function returned_with(state, arguments, level)
local payload = rawget(state, "payload")
if payload and payload.returned_with then
return state.payload:returned_with(arguments)
else
error("'returned_with' must be chained after 'spy(aspy)'")
end
end
local function called_with(state, arguments, level)
local payload = rawget(state, "payload")
if payload and payload.called_with then
return state.payload:called_with(arguments)
else
error("'called_with' must be chained after 'spy(aspy)'")
end
end
local function called(state, arguments, level, compare)
local num_times = arguments[1]
if not num_times and not state.mod then
state.mod = true
num_times = 0
end
local payload = rawget(state, "payload")
if payload and type(payload) == "table" and payload.called then
local result, count = state.payload:called(num_times, compare)
arguments[1] = tostring(num_times or ">0")
util.tinsert(arguments, 2, tostring(count))
arguments.nofmt = arguments.nofmt or {}
arguments.nofmt[1] = true
arguments.nofmt[2] = true
return result
elseif payload and type(payload) == "function" then
error("When calling 'spy(aspy)', 'aspy' must not be the original function, but the spy function replacing the original")
else
error("'called' must be chained after 'spy(aspy)'")
end
end
local function called_at_least(state, arguments, level)
local level = (level or 1) + 1
return called(state, arguments, level, function(count, expected) return count >= expected end)
end
local function called_at_most(state, arguments, level)
local level = (level or 1) + 1
return called(state, arguments, level, function(count, expected) return count <= expected end)
end
local function called_more_than(state, arguments, level)
local level = (level or 1) + 1
return called(state, arguments, level, function(count, expected) return count > expected end)
end
local function called_less_than(state, arguments, level)
local level = (level or 1) + 1
return called(state, arguments, level, function(count, expected) return count < expected end)
end
assert:register("modifier", "spy", set_spy)
assert:register("assertion", "returned_with", returned_with, "assertion.returned_with.positive", "assertion.returned_with.negative")
assert:register("assertion", "called_with", called_with, "assertion.called_with.positive", "assertion.called_with.negative")
assert:register("assertion", "called", called, "assertion.called.positive", "assertion.called.negative")
assert:register("assertion", "called_at_least", called_at_least, "assertion.called_at_least.positive", "assertion.called_less_than.positive")
assert:register("assertion", "called_at_most", called_at_most, "assertion.called_at_most.positive", "assertion.called_more_than.positive")
assert:register("assertion", "called_more_than", called_more_than, "assertion.called_more_than.positive", "assertion.called_at_most.positive")
assert:register("assertion", "called_less_than", called_less_than, "assertion.called_less_than.positive", "assertion.called_at_least.positive")
return setmetatable(spy, {
__call = function(self, ...)
return spy.new(...)
end
})
|
-- module will return spy table, and register its assertions with the main assert engine
local assert = require('luassert.assert')
local util = require('luassert.util')
-- Spy metatable
local spy_mt = {
__call = function(self, ...)
local arguments = {...}
arguments.n = select('#',...) -- add argument count for trailing nils
table.insert(self.calls, util.deepcopy(arguments))
local function get_returns(...)
local returnvals = {...}
returnvals.n = select('#',...) -- add argument count for trailing nils
table.insert(self.returnvals, util.deepcopy(returnvals))
return ...
end
return get_returns(self.callback(...))
end
}
local spy -- must make local before defining table, because table contents refers to the table (recursion)
spy = {
new = function(callback)
if not util.callable(callback) then
error("Cannot spy on type '" .. type(callback) .. "', only on functions or callable elements", 2)
end
local s = setmetatable({
calls = {},
returnvals = {},
callback = callback,
target_table = nil, -- these will be set when using 'spy.on'
target_key = nil,
revert = function(self)
if not self.reverted then
if self.target_table and self.target_key then
self.target_table[self.target_key] = self.callback
end
self.reverted = true
end
return self.callback
end,
clear = function(self)
self.calls = {}
self.returnvals = {}
return self
end,
called = function(self, times, compare)
if times or compare then
local compare = compare or function(count, expected) return count == expected end
return compare(#self.calls, times), #self.calls
end
return (#self.calls > 0), #self.calls
end,
called_with = function(self, args)
return util.matchargs(self.calls, args) ~= nil
end,
returned_with = function(self, args)
return util.matchargs(self.returnvals, args) ~= nil
end
}, spy_mt)
assert:add_spy(s) -- register with the current state
return s
end,
is_spy = function(object)
return type(object) == "table" and getmetatable(object) == spy_mt
end,
on = function(target_table, target_key)
local s = spy.new(target_table[target_key])
target_table[target_key] = s
-- store original data
s.target_table = target_table
s.target_key = target_key
return s
end
}
local function set_spy(state, arguments, level)
state.payload = arguments[1]
if arguments[2] ~= nil then
state.failure_message = arguments[2]
end
end
local function returned_with(state, arguments, level)
local level = (level or 1) + 1
local payload = rawget(state, "payload")
if payload and payload.returned_with then
return state.payload:returned_with(arguments)
else
error("'returned_with' must be chained after 'spy(aspy)'", level)
end
end
local function called_with(state, arguments, level)
local level = (level or 1) + 1
local payload = rawget(state, "payload")
if payload and payload.called_with then
return state.payload:called_with(arguments)
else
error("'called_with' must be chained after 'spy(aspy)'", level)
end
end
local function called(state, arguments, level, compare)
local level = (level or 1) + 1
local num_times = arguments[1]
if not num_times and not state.mod then
state.mod = true
num_times = 0
end
local payload = rawget(state, "payload")
if payload and type(payload) == "table" and payload.called then
local result, count = state.payload:called(num_times, compare)
arguments[1] = tostring(num_times or ">0")
util.tinsert(arguments, 2, tostring(count))
arguments.nofmt = arguments.nofmt or {}
arguments.nofmt[1] = true
arguments.nofmt[2] = true
return result
elseif payload and type(payload) == "function" then
error("When calling 'spy(aspy)', 'aspy' must not be the original function, but the spy function replacing the original", level)
else
error("'called' must be chained after 'spy(aspy)'", level)
end
end
local function called_at_least(state, arguments, level)
local level = (level or 1) + 1
return called(state, arguments, level, function(count, expected) return count >= expected end)
end
local function called_at_most(state, arguments, level)
local level = (level or 1) + 1
return called(state, arguments, level, function(count, expected) return count <= expected end)
end
local function called_more_than(state, arguments, level)
local level = (level or 1) + 1
return called(state, arguments, level, function(count, expected) return count > expected end)
end
local function called_less_than(state, arguments, level)
local level = (level or 1) + 1
return called(state, arguments, level, function(count, expected) return count < expected end)
end
assert:register("modifier", "spy", set_spy)
assert:register("assertion", "returned_with", returned_with, "assertion.returned_with.positive", "assertion.returned_with.negative")
assert:register("assertion", "called_with", called_with, "assertion.called_with.positive", "assertion.called_with.negative")
assert:register("assertion", "called", called, "assertion.called.positive", "assertion.called.negative")
assert:register("assertion", "called_at_least", called_at_least, "assertion.called_at_least.positive", "assertion.called_less_than.positive")
assert:register("assertion", "called_at_most", called_at_most, "assertion.called_at_most.positive", "assertion.called_more_than.positive")
assert:register("assertion", "called_more_than", called_more_than, "assertion.called_more_than.positive", "assertion.called_at_most.positive")
assert:register("assertion", "called_less_than", called_less_than, "assertion.called_less_than.positive", "assertion.called_at_least.positive")
return setmetatable(spy, {
__call = function(self, ...)
return spy.new(...)
end
})
|
Fix internal assertion error levels for spies
|
Fix internal assertion error levels for spies
|
Lua
|
mit
|
ZyX-I/luassert,mpeterv/luassert,o-lim/luassert
|
846795bd6e86b676f02d816465b27bf56fd1ebcb
|
src/haka/lua/rule.lua
|
src/haka/lua/rule.lua
|
-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
local class = require('class')
local check = require('check')
local module = {}
module.rules = {}
function haka.rule_summary()
local total = 0
for event, listeners in pairs(haka.context.connections) do
haka.log.info("core", "%d rule(s) on event '%s'", #listeners, event.name)
total = total + #listeners
end
if total == 0 then
haka.log.warning("core", "no registered rule\n")
else
haka.log.info("core", "%d rule(s) registered\n", total)
end
end
function haka.rule(r)
check.assert(type(r) == 'table', "rule parameter must be a table")
check.assert(r.hook, "no hook defined for rule")
check.assert(class.isa(r.hook, haka.event.Event), "rule hook must be an event")
check.assert(type(r.eval) == 'function', "rule eval function expected")
check.assert(not r.options or type(r.options) == 'table', "rule options should be table")
local loc = debug.getinfo(2, 'nSl')
r.location = string.format("%s:%d", loc.short_src, loc.currentline)
r.type = 'simple'
table.insert(module.rules, r)
haka.context.connections:register(r.hook, r.eval, r.options or {})
end
function haka.console.rules()
local ret = {}
for _, rule in pairs(module.rules) do
table.insert(ret, {
name=rule.name,
event=rule.hook.name,
location=rule.location,
type=rule.type
})
end
return ret
end
-- Load interactive.lua as a different file to allow to compile it
-- with the debugging information
require("interactive")
return module
|
-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
local class = require('class')
local check = require('check')
local module = {}
local log = haka.log_section("core")
module.rules = {}
function haka.rule_summary()
local total = 0
for event, listeners in pairs(haka.context.connections) do
log.info("%d rule(s) on event '%s'", #listeners, event.name)
total = total + #listeners
end
if total == 0 then
log.warning("no registered rule\n")
else
log.info("%d rule(s) registered\n", total)
end
end
function haka.rule(r)
check.assert(type(r) == 'table', "rule parameter must be a table")
check.assert(r.hook, "no hook defined for rule")
check.assert(class.isa(r.hook, haka.event.Event), "rule hook must be an event")
check.assert(type(r.eval) == 'function', "rule eval function expected")
check.assert(not r.options or type(r.options) == 'table', "rule options should be table")
local loc = debug.getinfo(2, 'nSl')
r.location = string.format("%s:%d", loc.short_src, loc.currentline)
r.type = 'simple'
table.insert(module.rules, r)
haka.context.connections:register(r.hook, r.eval, r.options or {})
end
function haka.console.rules()
local ret = {}
for _, rule in pairs(module.rules) do
table.insert(ret, {
name=rule.name,
event=rule.hook.name,
location=rule.location,
type=rule.type
})
end
return ret
end
-- Load interactive.lua as a different file to allow to compile it
-- with the debugging information
require("interactive")
return module
|
Fix log message
|
Fix log message
Update the rule reporting to match the new logging API.
|
Lua
|
mpl-2.0
|
nabilbendafi/haka,LubyRuffy/haka,haka-security/haka,lcheylus/haka,lcheylus/haka,nabilbendafi/haka,haka-security/haka,nabilbendafi/haka,haka-security/haka,Wingless-Archangel/haka,LubyRuffy/haka,lcheylus/haka,Wingless-Archangel/haka
|
fe5b2f413b94623117322d2d1775f19fb998138d
|
plugins/mod_message.lua
|
plugins/mod_message.lua
|
local full_sessions = full_sessions;
local bare_sessions = bare_sessions;
local jid_bare = require "util.jid".bare;
local user_exists = require "core.usermanager".user_exists;
local offlinemanager = require "core.offlinemanager";
local function select_top_resources(user)
local priority = 0;
local recipients = {};
for _, session in pairs(user.sessions) do -- find resource with greatest priority
if session.presence then
-- TODO check active privacy list for session
local p = session.priority;
if p > priority then
priority = p;
recipients = {session};
elseif p == priority then
t_insert(recipients, session);
end
end
end
return recipients;
end
local function process_to_bare(bare, origin, stanza)
local user = bare_sessions[bare];
local t = stanza.attr.type;
if t == "error" then
-- discard
elseif t == "groupchat" then
origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
elseif t == "headline" then
if user then
for _, session in pairs(user.sessions) do
if session.presence and session.priority >= 0 then
session.send(stanza);
end
end
end -- current policy is to discard headlines if no recipient is available
else -- chat or normal message
if user then -- some resources are connected
local recipients = select_top_resources(user);
if #recipients > 0 then
for i=1,#recipients do
recipients[i].send(stanza);
end
return true;
end
end
-- no resources are online
local node, host = jid_split(bare);
if user_exists(node, host) then
-- TODO apply the default privacy list
offlinemanager.store(node, host, stanza);
else
origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
end
end
return true;
end
module:hook("message/full", function(data)
-- message to full JID recieved
local origin, stanza = data.origin, data.stanza;
local session = full_sessions[stanza.attr.to];
if session then
-- TODO fire post processing event
session.send(stanza);
return true;
else -- resource not online
return process_to_bare(jid_bare(stanza.attr.to), origin, stanza);
end
end);
module:hook("message/bare", function(data)
-- message to bare JID recieved
local origin, stanza = data.origin, data.stanza;
return process_to_bare(stanza.attr.to or (origin.username..'@'..origin.host), origin, stanza);
end);
|
local full_sessions = full_sessions;
local bare_sessions = bare_sessions;
local jid_bare = require "util.jid".bare;
local jid_split = require "util.jid".split;
local user_exists = require "core.usermanager".user_exists;
local offlinemanager = require "core.offlinemanager";
local t_insert = table.insert;
local function select_top_resources(user)
local priority = 0;
local recipients = {};
for _, session in pairs(user.sessions) do -- find resource with greatest priority
if session.presence then
-- TODO check active privacy list for session
local p = session.priority;
if p > priority then
priority = p;
recipients = {session};
elseif p == priority then
t_insert(recipients, session);
end
end
end
return recipients;
end
local function process_to_bare(bare, origin, stanza)
local user = bare_sessions[bare];
local t = stanza.attr.type;
if t == "error" then
-- discard
elseif t == "groupchat" then
origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
elseif t == "headline" then
if user then
for _, session in pairs(user.sessions) do
if session.presence and session.priority >= 0 then
session.send(stanza);
end
end
end -- current policy is to discard headlines if no recipient is available
else -- chat or normal message
if user then -- some resources are connected
local recipients = select_top_resources(user);
if #recipients > 0 then
for i=1,#recipients do
recipients[i].send(stanza);
end
return true;
end
end
-- no resources are online
local node, host = jid_split(bare);
if user_exists(node, host) then
-- TODO apply the default privacy list
offlinemanager.store(node, host, stanza);
else
origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
end
end
return true;
end
module:hook("message/full", function(data)
-- message to full JID recieved
local origin, stanza = data.origin, data.stanza;
local session = full_sessions[stanza.attr.to];
if session then
-- TODO fire post processing event
session.send(stanza);
return true;
else -- resource not online
return process_to_bare(jid_bare(stanza.attr.to), origin, stanza);
end
end);
module:hook("message/bare", function(data)
-- message to bare JID recieved
local origin, stanza = data.origin, data.stanza;
return process_to_bare(stanza.attr.to or (origin.username..'@'..origin.host), origin, stanza);
end);
|
mod_message: Fix global access
|
mod_message: Fix global access
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
794a436d86d0c5ab4540780ff569f2877452c89c
|
mods/bucket/init.lua
|
mods/bucket/init.lua
|
-- Minetest 0.4 mod: bucket
-- See README.txt for licensing and other information.
minetest.register_alias("bucket", "bucket:bucket_empty")
minetest.register_alias("bucket_water", "bucket:bucket_water")
minetest.register_alias("bucket_lava", "bucket:bucket_lava")
minetest.register_craft({
output = 'bucket:bucket_empty 1',
recipe = {
{'default:steel_ingot', '', 'default:steel_ingot'},
{'', 'default:steel_ingot', ''},
}
})
bucket = {}
bucket.liquids = {}
local function check_protection(pos, name, text)
if minetest.is_protected(pos, name) then
minetest.log("action", (name ~= "" and name or "A mod")
.. " tried to " .. text
.. " at protected position "
.. minetest.pos_to_string(pos)
.. " with a bucket")
minetest.record_protection_violation(pos, name)
return true
end
return false
end
-- Register a new liquid
-- source = name of the source node
-- flowing = name of the flowing node
-- itemname = name of the new bucket item (or nil if liquid is not takeable)
-- inventory_image = texture of the new bucket item (ignored if itemname == nil)
-- This function can be called from any mod (that depends on bucket).
function bucket.register_liquid(source, flowing, itemname, inventory_image, name)
bucket.liquids[source] = {
source = source,
flowing = flowing,
itemname = itemname,
}
bucket.liquids[flowing] = bucket.liquids[source]
if itemname ~= nil then
minetest.register_craftitem(itemname, {
description = name,
inventory_image = inventory_image,
stack_max = 1,
liquids_pointable = true,
on_place = function(itemstack, user, pointed_thing)
-- Must be pointing to node
if pointed_thing.type ~= "node" then
return
end
local node = minetest.get_node_or_nil(pointed_thing.under)
local ndef
if node then
ndef = minetest.registered_nodes[node.name]
end
-- Call on_rightclick if the pointed node defines it
if ndef and ndef.on_rightclick and
user and not user:get_player_control().sneak then
return ndef.on_rightclick(
pointed_thing.under,
node, user,
itemstack) or itemstack
end
local place_liquid = function(pos, node, source, flowing)
if check_protection(pos,
user and user:get_player_name() or "",
"place "..source) then
return
end
minetest.add_node(pos, {name=source})
end
-- Check if pointing to a buildable node
if ndef and ndef.buildable_to then
-- buildable; replace the node
place_liquid(pointed_thing.under, node,
source, flowing)
else
-- not buildable to; place the liquid above
-- check if the node above can be replaced
local node = minetest.get_node_or_nil(pointed_thing.above)
if node and minetest.registered_nodes[node.name].buildable_to then
place_liquid(pointed_thing.above,
node, source,
flowing)
else
-- do not remove the bucket with the liquid
return
end
end
return {name="bucket:bucket_empty"}
end
})
end
end
minetest.register_craftitem("bucket:bucket_empty", {
description = "Empty Bucket",
inventory_image = "bucket.png",
stack_max = 99,
liquids_pointable = true,
on_use = function(itemstack, user, pointed_thing)
-- Must be pointing to node
if pointed_thing.type ~= "node" then
return
end
-- Check if pointing to a liquid source
local node = minetest.get_node(pointed_thing.under)
local liquiddef = bucket.liquids[node.name]
local item_count = user:get_wielded_item():get_count()
if liquiddef ~= nil
and liquiddef.itemname ~= nil
and node.name == liquiddef.source then
if check_protection(pointed_thing.under,
user:get_player_name(),
"take ".. node.name) then
return
end
-- default set to return filled bucket
local giving_back = liquiddef.itemname
-- check if holding more than 1 empty bucket
if item_count > 1 then
-- if space in inventory add filled bucked, otherwise drop as item
local inv = user:get_inventory()
if inv:room_for_item("main", {name=liquiddef.itemname}) then
inv:add_item("main", liquiddef.itemname)
else
local pos = user:getpos()
pos.y = math.floor(pos.y + 0.5)
core.add_item(pos, liquiddef.itemname)
end
-- set to return empty buckets minus 1
giving_back = "bucket:bucket_empty "..tostring(item_count-1)
end
minetest.add_node(pointed_thing.under, {name="air"})
return ItemStack(giving_back)
end
end,
})
bucket.register_liquid(
"default:water_source",
"default:water_flowing",
"bucket:bucket_water",
"bucket_water.png",
"Water Bucket"
)
bucket.register_liquid(
"default:lava_source",
"default:lava_flowing",
"bucket:bucket_lava",
"bucket_lava.png",
"Lava Bucket"
)
minetest.register_craft({
type = "fuel",
recipe = "bucket:bucket_lava",
burntime = 60,
replacements = {{"bucket:bucket_lava", "bucket:bucket_empty"}},
})
|
-- Minetest 0.4 mod: bucket
-- See README.txt for licensing and other information.
minetest.register_alias("bucket", "bucket:bucket_empty")
minetest.register_alias("bucket_water", "bucket:bucket_water")
minetest.register_alias("bucket_lava", "bucket:bucket_lava")
minetest.register_craft({
output = 'bucket:bucket_empty 1',
recipe = {
{'default:steel_ingot', '', 'default:steel_ingot'},
{'', 'default:steel_ingot', ''},
}
})
bucket = {}
bucket.liquids = {}
local function check_protection(pos, name, text)
if minetest.is_protected(pos, name) then
minetest.log("action", (name ~= "" and name or "A mod")
.. " tried to " .. text
.. " at protected position "
.. minetest.pos_to_string(pos)
.. " with a bucket")
minetest.record_protection_violation(pos, name)
return true
end
return false
end
-- Register a new liquid
-- source = name of the source node
-- flowing = name of the flowing node
-- itemname = name of the new bucket item (or nil if liquid is not takeable)
-- inventory_image = texture of the new bucket item (ignored if itemname == nil)
-- This function can be called from any mod (that depends on bucket).
function bucket.register_liquid(source, flowing, itemname, inventory_image, name)
bucket.liquids[source] = {
source = source,
flowing = flowing,
itemname = itemname,
}
bucket.liquids[flowing] = bucket.liquids[source]
if itemname ~= nil then
minetest.register_craftitem(itemname, {
description = name,
inventory_image = inventory_image,
stack_max = 1,
liquids_pointable = true,
on_place = function(itemstack, user, pointed_thing)
-- Must be pointing to node
if pointed_thing.type ~= "node" then
return
end
local node = minetest.get_node_or_nil(pointed_thing.under)
local ndef
if node then
ndef = minetest.registered_nodes[node.name]
end
-- Call on_rightclick if the pointed node defines it
if ndef and ndef.on_rightclick and
user and not user:get_player_control().sneak then
return ndef.on_rightclick(
pointed_thing.under,
node, user,
itemstack) or itemstack
end
local place_liquid = function(pos, node, source, flowing)
if check_protection(pos,
user and user:get_player_name() or "",
"place "..source) then
return
end
minetest.add_node(pos, {name=source})
end
-- Check if pointing to a buildable node
if ndef and ndef.buildable_to then
-- buildable; replace the node
place_liquid(pointed_thing.under, node,
source, flowing)
else
-- not buildable to; place the liquid above
-- check if the node above can be replaced
local node = minetest.get_node_or_nil(pointed_thing.above)
if node and minetest.registered_nodes[node.name].buildable_to then
place_liquid(pointed_thing.above,
node, source,
flowing)
else
-- do not remove the bucket with the liquid
return
end
end
return {name="bucket:bucket_empty"}
end
})
end
end
minetest.register_craftitem("bucket:bucket_empty", {
description = "Empty Bucket",
inventory_image = "bucket.png",
stack_max = 99,
liquids_pointable = true,
on_use = function(itemstack, user, pointed_thing)
-- Must be pointing to node
if pointed_thing.type ~= "node" then
return
end
-- Check if pointing to a liquid source
local node = minetest.get_node(pointed_thing.under)
local liquiddef = bucket.liquids[node.name]
local item_count = user:get_wielded_item():get_count()
if liquiddef ~= nil
and liquiddef.itemname ~= nil
and node.name == liquiddef.source then
if check_protection(pointed_thing.under,
user:get_player_name(),
"take ".. node.name) then
return
end
-- default set to return filled bucket
local giving_back = liquiddef.itemname
-- check if holding more than 1 empty bucket
if item_count > 1 then
-- if space in inventory add filled bucked, otherwise drop as item
local inv = user:get_inventory()
if inv:room_for_item("main", {name=liquiddef.itemname}) then
inv:add_item("main", liquiddef.itemname)
else
local pos = user:getpos()
pos.y = math.floor(pos.y + 0.5)
core.add_item(pos, liquiddef.itemname)
end
-- set to return empty buckets minus 1
giving_back = "bucket:bucket_empty "..tostring(item_count-1)
end
minetest.add_node(pointed_thing.under, {name="air"})
return ItemStack(giving_back)
end
end,
})
bucket.register_liquid(
"default:water_source",
"default:water_flowing",
"bucket:bucket_water",
"bucket_water.png",
"Water Bucket"
)
bucket.register_liquid(
"default:lava_source",
"default:lava_flowing",
"bucket:bucket_lava",
"bucket_lava.png",
"Lava Bucket"
)
minetest.register_craft({
type = "fuel",
recipe = "bucket:bucket_lava",
burntime = 60,
replacements = {{"bucket:bucket_lava", "bucket:bucket_empty"}},
})
|
Fix bucket code indentation
|
Fix bucket code indentation
|
Lua
|
lgpl-2.1
|
evrooije/beerarchy,evrooije/beerarchy,evrooije/beerarchy
|
a038717a448cfe129cec70a7f6f4bcb056e22700
|
examples/repl.lua
|
examples/repl.lua
|
#!/bin/sh
_=[[
exec lua -i "$0" "$@"
]]
--
-- Interactive Lua session with a Twitter client logged in.
-- It uses pl.pretty and custom __tostring methods to display the returned data.
--
local cfg = require "_config"()
pl = require "pl.import_into" ()
pretty = pl.pretty
twitter = require "luatwit"
objects = require "luatwit.objects"
-- initialize the twitter client
oauth_params = twitter.load_keys(cfg.app_keys, cfg.user_keys)
client = twitter.api.new(oauth_params)
-- pretty print for resource items
client.resources._resource_base.__tostring = pl.pretty.write
-- pretty print for tweets
function client.objects.tweet:__tostring()
return "<" .. self.user.screen_name .. "> " .. self.text
end
-- pretty print for DMs
function client.objects.dm:__tostring()
return "<" .. self.sender.screen_name .. "> (to: " .. self.recipient.screen_name .. ") " .. self.text
end
-- pretty print for user profiles
local user_tmpl =
[[Name: @$screen_name ($name)
Bio: $description
Location: $location
Followers: $followers_count, Following: $friends_count, Listed: $listed_count
Tweets: $statuses_count
---]]
function client.objects.user:__tostring()
return (user_tmpl:gsub("$([%w_]+)", self))
end
-- used to display object lists
local function list_tostring(self)
local res = {}
for i, item in ipairs(self) do
res[#res + 1] = i .. ": " .. tostring(item)
end
return table.concat(res, "\n") .. "\n"
end
-- writes the contents of a table to a file
function table_save(tbl, filename)
filename = filename or "tw.out"
pretty.dump(tbl, filename)
return tbl
end
-- add default __tostring methods to all objects
for name, _ in pairs(objects) do
local obj = client.objects[name]
if not obj.__tostring then
obj.__tostring = name:match("_list$") and list_tostring or pretty.write
end
obj.save = obj.save or table_save
end
-- avoid headers spam
client.objects.headers.__tostring = nil
-- lists the keys of a table and the type of its values
function keys(obj)
if type(obj) ~= "table" then
print(tostring(obj) .. " = " .. type(obj))
return
end
for k, v in pairs(obj) do
print(tostring(k) .. " = " .. type(v))
end
end
-- finds a resource item with the specified api path
function get_resource(path)
for name, decl in pairs(client.resources) do
if decl.path == path then
return decl
end
end
end
|
#!/bin/sh
_=[[
exec lua -i "$0" "$@"
]]
--
-- Interactive Lua session with a Twitter client logged in.
-- It uses pl.pretty and custom __tostring methods to display the returned data.
--
local cfg = require "_config"()
pl = require "pl.import_into" ()
pretty = pl.pretty
twitter = require "luatwit"
objects = require "luatwit.objects"
-- initialize the twitter client
oauth_params = twitter.load_keys(cfg.app_keys, cfg.user_keys)
client = twitter.api.new(oauth_params)
-- pretty print for resource items
client.resources._resource_base.__tostring = pl.pretty.write
-- pretty print for tweets
function client.objects.tweet:__tostring()
return "<" .. self.user.screen_name .. "> " .. self.text
end
-- pretty print for DMs
function client.objects.dm:__tostring()
return "<" .. self.sender.screen_name .. "> (to: " .. self.recipient.screen_name .. ") " .. self.text
end
-- pretty print for user profiles
local user_tmpl =
[[Name: @$screen_name ($name)
Bio: $description
Location: $location
Followers: $followers_count, Following: $friends_count, Listed: $listed_count
Tweets: $statuses_count
---]]
function client.objects.user:__tostring()
return (user_tmpl:gsub("$([%w_]+)", self))
end
-- used to display object lists
local function list_tostring(self)
local res = {}
for i, item in ipairs(self) do
res[#res + 1] = i .. ": " .. tostring(item)
end
return table.concat(res, "\n") .. "\n"
end
-- writes the contents of a table to a file
function table_save(tbl, filename)
filename = filename or "tw.out"
pretty.dump(tbl, filename)
return tbl
end
-- add default __tostring methods to all objects
for name, _ in pairs(objects) do
local obj = client.objects[name]
if not obj.__tostring then
obj.__tostring = name:match("_list$") and list_tostring or pretty.write
end
obj.save = obj.save or table_save
end
-- lists the keys of a table and the type of its values
function keys(obj)
if type(obj) ~= "table" then
print(tostring(obj) .. " = " .. type(obj))
return
end
for k, v in pairs(obj) do
print(tostring(k) .. " = " .. type(v))
end
end
-- finds a resource item with the specified api path
function get_resource(path)
for name, decl in pairs(client.resources) do
if decl.path == path then
return decl
end
end
end
|
fixed examples/repl
|
fixed examples/repl
|
Lua
|
mit
|
darkstalker/LuaTwit
|
2a8948cdc83c78a943cc4c9dceb2cf25ba063c3c
|
BIOS/init.lua
|
BIOS/init.lua
|
--The BIOS should control the system of LIKO-12 and load the peripherals--
--For now it's just a simple BIOS to get LIKO-12 working.
local DevMode = love.filesystem.exists("devmode.txt")
local FThread --File tracking thread
local _LIKO_Version, _LIKO_Old = _LVer.magor..".".._LVer.minor..".".._LVer.patch..".".._LVer.build
if love.filesystem.exists(".version") then
_LIKO_Old = love.filesystem.read(".version")
if _LIKO_Old == _LIKO_Version then
_LIKO_Old = false
end
else
love.filesystem.write(".version",tostring(_LIKO_Version))
end
--Require the engine libraries--
local events = require("Engine.events")
local coreg = require("Engine.coreg")
local function splitFilePath(path) return path:match("(.-)([^\\/]-%.?([^%.\\/]*))$") end --A function to split path to path, name, extension.
local Peripherals = {} --The loaded peripherals chunks.
local APIS = {} --The initialized peripherals apis.
local yAPIS = {} --The initialized peripherals yielding apis.
local Mounted = {} --The mounted peripherals list and types.
local Handled = {} --The handled peripherals functions.
local Devkits = {} --The mounted peripherals devkits.
--A function to load the peripherals.
local function indexPeripherals(path)
local files = love.filesystem.getDirectoryItems(path)
for k,filename in ipairs(files) do
if love.filesystem.isDirectory(path..filename) then
if love.filesystem.exists(path..filename.."/init.lua") then
local chunk, err = love.filesystem.load(path..filename.."/init.lua")
if not chunk then Peripherals[filename] = "Err: "..tostring(err) else
Peripherals[filename] = chunk(path..filename.."/") end
end
else
local p, n, e = splitFilePath(path..filename)
if e == "lua" then
local chunk, err = love.filesystem.load(path..n)
if not chunk then Peripherals[n:sub(0,-5)] = "Err: "..tostring(err) else
Peripherals[n:sub(0,-5)] = chunk(path) end
end
end
end
end
indexPeripherals("/Peripherals/") --Index and Load the peripherals
--Initializes a specific peripheral, and mount it under a specific name.
--Peripheral, Err = P(PeriheralName, MountedName, ConfigTabel)
local function P(per,m,conf)
if not per then return false, "Should provide peripheral name" end
if type(per) ~= "string" then return false, "Peripheral name should be a string, provided "..type(per) end
if not Peripherals[per] then return false, "'"..per.."' Peripheral doesn't exists" end
if type(Peripherals[per]) == "string" then return false, "Compile "..Peripherals[per] end
local m = m or per
if type(m) ~= "string" then return false, "Mounting name should be a string, provided "..type(m) end
if Mounted[m] then return false, "Mounting name '"..m.."' is already taken" end
local conf = conf or {}
if type(conf) ~= "table" then return false, "Configuration table should be a table, provided "..type(conf) end
events:group(per..":"..m)
local success, API, yAPI, devkit = pcall(Peripherals[per],conf)
events:group()
if success then
APIS[m] = API or {} --The direct API
yAPIS[m] = yAPI or {} --The yielding API
Mounted[m] = per --The peripheral type
Devkits[m] = devkit or {} --The peripheral Devkit.
else
API = "Init Err: "..tostring(API)
end
return success, API, yAPI, devkit
end
--Initialize a peripheral, and crash LIKO-12 if failed.
local function PA(...)
local ok, api, yapi, devkit = P(...)
if ok then
return api, yapi, devkit
else
return error(tostring(api))
end
end
--BIOS APIS--
do
Mounted.BIOS = "BIOS"
APIS.BIOS = {}
yAPIS.BIOS = {}
--Returns a list of mounted peripherals and their types.
function yAPIS.BIOS.Peripherals()
local pList = {}
for mountName, pType in pairs(Mounted) do
pList[mountName] = pType
end
return true, pList
end
--Returns the handled APIS, that can be used directly.
function yAPIS.BIOS.HandledAPIS()
local hAPIS = {}
for mountName,funcList in pairs(Handled) do
hAPIS[mountName] = {}
for funcName, func in pairs(funcList) do
hAPIS[mountName][funcName] = func
end
end
return true, hAPIS
end
--Returns the list of available peripheral functions, and their type (Direct,Yield)
function yAPIS.BIOS.PeripheralFunctions(mountName)
if type(mountName) ~= "string" then return false, "MountName should be a string, provided: "..type(mountName) end
if not Mounted[mountName] then return false, "No mounted peripheral '"..mountName"..'" end
local funcList = {}
for funcName, func in pairs(APIS[mountName]) do
funcList[funcName] = "Direct"
end
for funcName, func in pairs(yAPIS[mountName]) do
funcList[funcName] = "Yield"
end
return true, funcList
end
end
--The BIOS config sandbox
local bconfSandbox = {
P=P, PA=PA,
error=error, assert=assert,
_OS = love.system.getOS()
}
--Load and execute the bios config
local bconfChunk = love.filesystem.load("BIOS/bconf.lua")
setfenv(bconfChunk, bconfSandbox)
bconfChunk()
--Register yielding APIS
for mountName, yAPI in pairs(yAPIS) do
coreg:register(yAPI,mountName)
end
--Create handled functions
for mountName, pType in pairs(Mounted) do
Handled[mountName] = {}
for funcName, func in pairs(APIS[mountName]) do
Handled[mountName][funcName] = func
end
for funcName, func in pairs(yAPIS[mountName]) do
local funcCommand = mountName..":"..funcName
Handled[mountName][funcName] = function(...)
local respond = {coroutine.yield(funcCommand,...)}
if respond[1] then
return select(2,unpack(respond))
else
return error(tostring(respond[2]))
end
end
end
end
--Bootup the POST chunk
local POST = love.filesystem.load("/BIOS/post.lua")
local POSTCo = coroutine.create(POST)
coreg:setCoroutine(POSTCo, _G)
coreg:resumeCoroutine(Handled)
|
--The BIOS should control the system of LIKO-12 and load the peripherals--
--For now it's just a simple BIOS to get LIKO-12 working.
local DevMode = love.filesystem.exists("devmode.txt")
local _LIKO_Version, _LIKO_Old = _LVer.magor..".".._LVer.minor..".".._LVer.patch..".".._LVer.build
if love.filesystem.exists(".version") then
_LIKO_Old = love.filesystem.read(".version")
if _LIKO_Old == _LIKO_Version then
_LIKO_Old = false
end
else
love.filesystem.write(".version",tostring(_LIKO_Version))
end
--Require the engine libraries--
local events = require("Engine.events")
local coreg = require("Engine.coreg")
local function splitFilePath(path) return path:match("(.-)([^\\/]-%.?([^%.\\/]*))$") end --A function to split path to path, name, extension.
local Peripherals = {} --The loaded peripherals chunks.
local APIS = {} --The initialized peripherals apis.
local yAPIS = {} --The initialized peripherals yielding apis.
local Mounted = {} --The mounted peripherals list and types.
local Handled = {} --The handled peripherals functions.
local Devkits = {} --The mounted peripherals devkits.
--A function to load the peripherals.
local function indexPeripherals(path)
local files = love.filesystem.getDirectoryItems(path)
for k,filename in ipairs(files) do
if love.filesystem.isDirectory(path..filename) then
if love.filesystem.exists(path..filename.."/init.lua") then
local chunk, err = love.filesystem.load(path..filename.."/init.lua")
if not chunk then Peripherals[filename] = "Err: "..tostring(err) else
Peripherals[filename] = chunk(path..filename.."/") end
end
else
local p, n, e = splitFilePath(path..filename)
if e == "lua" then
local chunk, err = love.filesystem.load(path..n)
if not chunk then Peripherals[n:sub(0,-5)] = "Err: "..tostring(err) else
Peripherals[n:sub(0,-5)] = chunk(path) end
end
end
end
end
indexPeripherals("/Peripherals/") --Index and Load the peripherals
--Initializes a specific peripheral, and mount it under a specific name.
--Peripheral, Err = P(PeriheralName, MountedName, ConfigTabel)
local function P(per,m,conf)
if not per then return false, "Should provide peripheral name" end
if type(per) ~= "string" then return false, "Peripheral name should be a string, provided "..type(per) end
if not Peripherals[per] then return false, "'"..per.."' Peripheral doesn't exists" end
if type(Peripherals[per]) == "string" then return false, "Compile "..Peripherals[per] end
local m = m or per
if type(m) ~= "string" then return false, "Mounting name should be a string, provided "..type(m) end
if Mounted[m] then return false, "Mounting name '"..m.."' is already taken" end
local conf = conf or {}
if type(conf) ~= "table" then return false, "Configuration table should be a table, provided "..type(conf) end
events:group(per..":"..m)
local success, API, yAPI, devkit = pcall(Peripherals[per],conf)
events:group()
if success then
APIS[m] = API or {} --The direct API
yAPIS[m] = yAPI or {} --The yielding API
Mounted[m] = per --The peripheral type
Devkits[m] = devkit or {} --The peripheral Devkit.
else
API = "Init Err: "..tostring(API)
end
return success, API, yAPI, devkit
end
--Initialize a peripheral, and crash LIKO-12 if failed.
local function PA(...)
local ok, api, yapi, devkit = P(...)
if ok then
return api, yapi, devkit
else
return error(tostring(api))
end
end
--BIOS APIS--
do
Mounted.BIOS = "BIOS"
APIS.BIOS = {}
yAPIS.BIOS = {}
--Returns a list of mounted peripherals and their types.
function yAPIS.BIOS.Peripherals()
local pList = {}
for mountName, pType in pairs(Mounted) do
pList[mountName] = pType
end
return true, pList
end
--Returns the handled APIS, that can be used directly.
function yAPIS.BIOS.HandledAPIS()
local hAPIS = {}
for mountName,funcList in pairs(Handled) do
hAPIS[mountName] = {}
for funcName, func in pairs(funcList) do
hAPIS[mountName][funcName] = func
end
end
return true, hAPIS
end
--Returns the list of available peripheral functions, and their type (Direct,Yield)
function yAPIS.BIOS.PeripheralFunctions(mountName)
if type(mountName) ~= "string" then return false, "MountName should be a string, provided: "..type(mountName) end
if not Mounted[mountName] then return false, "No mounted peripheral '"..mountName"..'" end
local funcList = {}
for funcName, func in pairs(APIS[mountName]) do
funcList[funcName] = "Direct"
end
for funcName, func in pairs(yAPIS[mountName]) do
funcList[funcName] = "Yield"
end
return true, funcList
end
--Returns LIKO-12 Version
function yAPIS.BIOS.getVersion()
return true, _LIKO_Version, _LIKO_Old
end
end
--The BIOS config sandbox
local bconfSandbox = {
P=P, PA=PA,
error=error, assert=assert,
_OS = love.system.getOS()
}
--Load and execute the bios config
local bconfChunk = love.filesystem.load("BIOS/bconf.lua")
setfenv(bconfChunk, bconfSandbox)
bconfChunk()
--Register yielding APIS
for mountName, yAPI in pairs(yAPIS) do
coreg:register(yAPI,mountName)
end
--Create handled functions
for mountName, pType in pairs(Mounted) do
Handled[mountName] = {}
for funcName, func in pairs(APIS[mountName]) do
Handled[mountName][funcName] = func
end
for funcName, func in pairs(yAPIS[mountName]) do
local funcCommand = mountName..":"..funcName
Handled[mountName][funcName] = function(...)
local respond = {coroutine.yield(funcCommand,...)}
if respond[1] then
return select(2,unpack(respond))
else
return error(tostring(respond[2]))
end
end
end
end
--Bootup the POST chunk
local POST = love.filesystem.load("/BIOS/post.lua")
local POSTCo = coroutine.create(POST)
coreg:setCoroutine(POSTCo)
coreg:resumeCoroutine(Handled,Devkits)
|
Various fixes
|
Various fixes
Former-commit-id: 98e189265dd44059af2f358a9dea83033dbe4a88
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
b4b2056c0430c76f9e398c03b5b6856f79c0cc0e
|
src/caching/null.lua
|
src/caching/null.lua
|
local Cache = {}
local mt = {__index = Cache}
local function new()
return setmetatable({}, mt)
end
function Cache:add(key, value, expiration)
assert(type(key) == 'string')
assert(value ~= nil)
assert(expiration == nil or type(expiration) == 'number')
return true
end
function Cache:set(key, value, expiration)
assert(type(key) == 'string')
assert(value ~= nil)
assert(expiration == nil or type(expiration) == 'number')
return true
end
function Cache:replace(key, value, expiration)
assert(type(key) == 'string')
assert(value ~= nil)
assert(expiration == nil or type(expiration) == 'number')
return true
end
function Cache:get(key)
assert(type(key) == 'string')
return nil
end
function Cache:get_multi(keys)
assert(type(keys) == 'table')
return {}
end
function Cache:append(key, value)
assert(type(key) == 'string')
assert(type(value) == 'string')
return true
end
function Cache:prepend(key, value)
assert(type(key) == 'string')
assert(type(value) == 'string')
return true
end
function Cache:delete(key)
assert(type(key) == 'string')
return true
end
function Cache:touch(key, expiration)
assert(type(key) == 'string')
assert(expiration == nil or type(expiration) == 'number')
return true
end
function Cache:incr(key, offset)
assert(type(key) == 'string')
assert(type(offset) == 'number')
return true
end
function Cache:decr(key, offset)
assert(type(key) == 'string')
assert(type(offset) == 'number')
return true
end
function Cache:exist(key)
assert(type(key) == 'string')
return false
end
return {
new = new
}
|
local Cache = {}
local mt = {__index = Cache}
local function new()
return setmetatable({}, mt)
end
function Cache:add(key, value, expiration)
assert(type(key) == 'string')
assert(value ~= nil)
assert(expiration == nil or type(expiration) == 'number')
return true
end
function Cache:set(key, value, expiration)
assert(type(key) == 'string')
assert(value ~= nil)
assert(expiration == nil or type(expiration) == 'number')
return true
end
function Cache:replace(key, value, expiration)
assert(type(key) == 'string')
assert(value ~= nil)
assert(expiration == nil or type(expiration) == 'number')
return true
end
function Cache:get(key)
assert(type(key) == 'string')
return nil
end
function Cache:get_multi(keys)
assert(type(keys) == 'table')
return {}
end
function Cache:append(key, value)
assert(type(key) == 'string')
assert(type(value) == 'string')
return true
end
function Cache:prepend(key, value)
assert(type(key) == 'string')
assert(type(value) == 'string')
return true
end
function Cache:delete(key)
assert(type(key) == 'string')
return true
end
function Cache:touch(key, expiration)
assert(type(key) == 'string')
assert(expiration == nil or type(expiration) == 'number')
return true
end
function Cache:incr(key, offset)
assert(type(key) == 'string')
assert(offset == nil or type(offset) == 'number')
return true
end
function Cache:decr(key, offset)
assert(type(key) == 'string')
assert(offset == nil or type(offset) == 'number')
return true
end
function Cache:exist(key)
assert(type(key) == 'string')
return false
end
return {
new = new
}
|
Fixed assert for offset in null cache incr/decr.
|
Fixed assert for offset in null cache incr/decr.
|
Lua
|
mit
|
akornatskyy/lucid
|
588fb1e006718d9b6100ba6b8056a7ad95d091cf
|
script/c800000041.lua
|
script/c800000041.lua
|
--CH キング・アーサー
function c800000041.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,aux.XyzFilterFunctionF(c,aux.FilterBoolFunction(Card.IsRace,RACE_WARRIOR),4),2)
c:EnableReviveLimit()
--destroy replace
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetCode(EFFECT_DESTROY_REPLACE)
e1:SetRange(LOCATION_MZONE)
e1:SetTarget(c800000041.reptg)
e1:SetOperation(c800000041.atkop)
c:RegisterEffect(e1)
end
function c800000041.reptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_EFFECT) and e:GetHandler():IsReason(REASON_BATTLE) end
if Duel.SelectYesNo(tp,aux.Stringid(110000000,9)) then
e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_EFFECT)
e:GetHandler():RegisterFlagEffect(800000041,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1)
return true
else return false end
end
function c800000041.atkop(e,tp,eg,ep,ev,re,r,rp)
Duel.BreakEffect()
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetReset(RESET_EVENT+0x1ff0000)
e1:SetValue(500)
e:GetHandler():RegisterEffect(e1)
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
Duel.Damage(1-tp,500,REASON_EFFECT)
end
|
--CH キング・アーサー
function c800000041.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,aux.XyzFilterFunctionF(c,aux.FilterBoolFunction(Card.IsRace,RACE_WARRIOR),4),2)
c:EnableReviveLimit()
--destroy replace
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetCode(EFFECT_DESTROY_REPLACE)
e1:SetRange(LOCATION_MZONE)
e1:SetTarget(c800000041.reptg)
e1:SetOperation(c800000041.repop)
c:RegisterEffect(e1)
--atkup & damage
local e2=Effect.CreateEffect(c)
e2:SetCategory(CATEGORY_ATKCHANGE+CATEGORY_DAMAGE)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e2:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DAMAGE_CAL)
e2:SetCode(800000041)
e2:SetTarget(c800000041.atktg)
e2:SetOperation(c800000041.atkop)
c:RegisterEffect(e2)
end
function c800000041.reptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_EFFECT) and e:GetHandler():IsReason(REASON_BATTLE) end
if Duel.SelectYesNo(tp,aux.Stringid(800000041,1)) then
e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_EFFECT)
return true
else return false end
end
function c800000041.repop(e,tp,eg,ep,ev,re,r,rp)
Duel.RaiseSingleEvent(e:GetHandler(),800000041,e,0,0,tp,nil)
end
function c800000041.atktg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetTargetPlayer(1-tp)
Duel.SetTargetParam(500)
Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,500)
end
function c800000041.atkop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if not c:IsFaceup() or not c:IsRelateToEffect(e) then return end
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetReset(RESET_EVENT+0x1ff0000)
e1:SetValue(500)
e:GetHandler():RegisterEffect(e1)
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
Duel.Damage(p,d,REASON_EFFECT)
end
|
fix
|
fix
fixed Effect type
|
Lua
|
mit
|
SuperAndroid17/DevProLauncher,Tic-Tac-Toc/DevProLauncher,sidschingis/DevProLauncher
|
4877d78d32a3db0f832ee4b92cce33f9238e309e
|
twilio.capability.lua
|
twilio.capability.lua
|
local jwt = require 'jwt'
local _scopes = {}
local _authToken = ""
local _accountSid = ""
local _clientName = ""
function initialize(accountSid, authToken)
_authToken = authToken
_accountSid = accountSid
end
function allowClientIncoming(clientName)
if (clientName:match("%W")) then
error("Only alphanumeric characters allowed in client name.")
end
if (clientName:len() == 0) then
error("Client name must not be a zero length string.")
end
_clientName = clientName
allow("client", "incoming", nil)
end
function allowClientOutgoing(appSid, appParams)
params = { ["appSid"]=appSid, ["appParams"]=appParams }
allow("client", "outgoing", params)
end
function generateToken(ttlSeconds)
scopeStrings = {}
for scopeCount=1, #_scopes do
scope = _scopes[scopeCount]
scopeStrings[#scopeStrings+1] = scopeToString(scope, _clientName)
end
payload = {
scope = table.concat(scopeStrings, " "),
iss = _accountSid,
exp = os.time() + ttlSeconds
}
result = jwt.encode(payload, _authToken, "HS256");
return result
end
function allow(service, privilage, params)
_scopes[#_scopes+1] = {
["service"]=service,
["privilage"]=privilage,
["params"]=params
}
end
function scopeToString(scope, clientName)
uri = string.format("scope:%s:%s", scope["service"], scope["privilage"])
if (clientName~="") then
if (scope["params"]==nil) then
scope["params"] = { ["clientName"] = clientName }
else
params = scope["params"]
params["clientName"] = clientName
end
end
if (scope["params"]~=nil) then
query = ""
params = scope["params"]
for key,item in pairs(params) do
if (query~="") then
query = query.."&"
end
value = item
if (type(item)=="table") then
print("Getting nested")
nestedValue = "";
-- loop through the nested objects and create a new value
for nestedKey,nestedItem in pairs(item) do
-- if nestedValue is not empty append an &
if (query~="") then
nestedValue = nestedValue .. urlEncode("&")
end
nestedValue = string.format("%s%s=%s",nestedValue, nestedKey, neestedItem)
end
value = urlEncode(nestedValue)
end
query = string.format("%s%s=%s", query, key, value)
end
uri = uri .. "?" .. query
end
return uri
end
function urlEncode(str)
if (str) then
str = string.gsub (str, "\n", "\r\n")
str = string.gsub (str, "([^%w ])",
function (c) return string.format ("%%%02X", string.byte(c)) end)
str = string.gsub (str, " ", "+")
end
return str
end
return { initialize = initialize,
allowClientIncoming = allowClientIncoming,
allowClientOutgoing = allowClientOutgoing,
generateToken = generateToken
}
|
local jwt = require 'jwt'
local _scopes = {}
local _authToken = ""
local _accountSid = ""
local _clientName = ""
local initialize = function(accountSid, authToken)
_authToken = authToken
_accountSid = accountSid
end
local allowClientIncoming = function(clientName)
if (clientName:match("%W")) then
error("Only alphanumeric characters allowed in client name.")
end
if (clientName:len() == 0) then
error("Client name must not be a zero length string.")
end
_clientName = clientName
allow("client", "incoming", nil)
end
local allowClientOutgoing = function(appSid, appParams)
params = { ["appSid"]=appSid, ["appParams"]=appParams }
allow("client", "outgoing", params)
end
local generateToken = function(ttlSeconds)
scopeStrings = {}
for scopeCount=1, #_scopes do
scope = _scopes[scopeCount]
scopeStrings[#scopeStrings+1] = scopeToString(scope, _clientName)
end
payload = {
scope = table.concat(scopeStrings, " "),
iss = _accountSid,
exp = os.time() + ttlSeconds
}
result = jwt.encode(payload, _authToken, "HS256");
return result
end
function allow(service, privilage, params)
_scopes[#_scopes+1] = {
["service"]=service,
["privilage"]=privilage,
["params"]=params
}
end
function scopeToString(scope, clientName)
uri = string.format("scope:%s:%s", scope["service"], scope["privilage"])
if (clientName~="") then
if (scope["params"]==nil) then
scope["params"] = { ["clientName"] = clientName }
else
params = scope["params"]
params["clientName"] = clientName
end
end
if (scope["params"]~=nil) then
query = ""
params = scope["params"]
for key,item in pairs(params) do
if (query~="") then
query = query.."&"
end
value = item
if (type(item)=="table") then
print("Getting nested")
nestedValue = "";
-- loop through the nested objects and create a new value
for nestedKey,nestedItem in pairs(item) do
-- if nestedValue is not empty append an &
if (query~="") then
nestedValue = nestedValue .. urlEncode("&")
end
nestedValue = string.format("%s%s=%s",nestedValue, nestedKey, neestedItem)
end
value = urlEncode(nestedValue)
end
query = string.format("%s%s=%s", query, key, value)
end
uri = uri .. "?" .. query
end
return uri
end
function urlEncode(str)
if (str) then
str = string.gsub (str, "\n", "\r\n")
str = string.gsub (str, "([^%w ])",
function (c) return string.format ("%%%02X", string.byte(c)) end)
str = string.gsub (str, " ", "+")
end
return str
end
return { initialize = initialize,
allowClientIncoming = allowClientIncoming,
allowClientOutgoing = allowClientOutgoing,
generateToken = generateToken
}
|
Fixing reference
|
Fixing reference
|
Lua
|
bsd-3-clause
|
robertbrook/lib,thejeshgn/lib
|
3b8e5a8064b4d359ab691369ace524c9b5b87575
|
ClassNLLCriterion.lua
|
ClassNLLCriterion.lua
|
local THNN = require 'nn.THNN'
local ClassNLLCriterion, parent = torch.class('nn.ClassNLLCriterion', 'nn.Criterion')
function ClassNLLCriterion:__init(weights, sizeAverage)
parent.__init(self)
if sizeAverage ~= nil then
self.sizeAverage = sizeAverage
else
self.sizeAverage = true
end
if weights then
assert(weights:dim() == 1, "weights input should be 1-D Tensor")
self.weights = weights
end
self.output_tensor = torch.zeros(1)
self.total_weight_tensor = torch.ones(1)
self.target = torch.zeros(1):long()
end
function ClassNLLCriterion:__len()
if (self.weights) then
return #self.weights
else
return 0
end
end
function ClassNLLCriterion:updateOutput(input, target)
if type(target) == 'number' then
if torch.typename(input):find('torch%.Cuda.*Tensor') then
self.target = torch.CudaLongTensor and self.target:cudaLong() or self.target:cuda()
else
self.target = self.target:long()
end
self.target[1] = target
elseif torch.typename(input):find('torch%.Cuda.*Tensor') then
self.target = torch.CudaLongTensor and target:cudaLong() or target
else
self.target = target:long()
end
input.THNN.ClassNLLCriterion_updateOutput(
input:cdata(),
self.target:cdata(),
self.output_tensor:cdata(),
self.sizeAverage,
THNN.optionalTensor(self.weights),
self.total_weight_tensor:cdata()
)
self.output = self.output_tensor[1]
return self.output, self.total_weight_tensor[1]
end
function ClassNLLCriterion:updateGradInput(input, target)
if type(target) == 'number' then
if torch.typename(input):find('torch%.Cuda.*Tensor') then
self.target = torch.CudaLongTensor and self.target:cudaLong() or self.target:cuda()
else
self.target = self.target:long()
end
self.target[1] = target
elseif torch.typename(input):find('torch%.Cuda.*Tensor') then
self.target = torch.CudaLongTensor and target:cudaLong() or target
else
self.target = target:long()
end
self.gradInput:resizeAs(input):zero()
input.THNN.ClassNLLCriterion_updateGradInput(
input:cdata(),
self.target:cdata(),
self.gradInput:cdata(),
self.sizeAverage,
THNN.optionalTensor(self.weights),
self.total_weight_tensor:cdata()
)
return self.gradInput
end
|
local THNN = require 'nn.THNN'
local ClassNLLCriterion, parent = torch.class('nn.ClassNLLCriterion', 'nn.Criterion')
function ClassNLLCriterion:__init(weights, sizeAverage)
parent.__init(self)
if sizeAverage ~= nil then
self.sizeAverage = sizeAverage
else
self.sizeAverage = true
end
if weights then
assert(weights:dim() == 1, "weights input should be 1-D Tensor")
self.weights = weights
end
self.output_tensor = torch.zeros(1)
self.total_weight_tensor = torch.ones(1)
self.target = torch.zeros(1):long()
end
function ClassNLLCriterion:__len()
if (self.weights) then
return #self.weights
else
return 0
end
end
function ClassNLLCriterion:updateOutput(input, target)
if type(target) == 'number' then
if torch.typename(input):find('torch%.Cuda.*Tensor') then
self.target = torch.CudaLongTensor and self.target:cudaLong() or self.target:cuda()
else
self.target = self.target:long()
end
self.target:resize(1)
self.target[1] = target
elseif torch.typename(input):find('torch%.Cuda.*Tensor') then
self.target = torch.CudaLongTensor and target:cudaLong() or target
else
self.target = target:long()
end
input.THNN.ClassNLLCriterion_updateOutput(
input:cdata(),
self.target:cdata(),
self.output_tensor:cdata(),
self.sizeAverage,
THNN.optionalTensor(self.weights),
self.total_weight_tensor:cdata()
)
self.output = self.output_tensor[1]
return self.output, self.total_weight_tensor[1]
end
function ClassNLLCriterion:updateGradInput(input, target)
if type(target) == 'number' then
if torch.typename(input):find('torch%.Cuda.*Tensor') then
self.target = torch.CudaLongTensor and self.target:cudaLong() or self.target:cuda()
else
self.target = self.target:long()
end
self.target:resize(1)
self.target[1] = target
elseif torch.typename(input):find('torch%.Cuda.*Tensor') then
self.target = torch.CudaLongTensor and target:cudaLong() or target
else
self.target = target:long()
end
self.gradInput:resizeAs(input):zero()
input.THNN.ClassNLLCriterion_updateGradInput(
input:cdata(),
self.target:cdata(),
self.gradInput:cdata(),
self.sizeAverage,
THNN.optionalTensor(self.weights),
self.total_weight_tensor:cdata()
)
return self.gradInput
end
|
fixing bug in ClassNLLCriterion for single targets
|
fixing bug in ClassNLLCriterion for single targets
|
Lua
|
bsd-3-clause
|
colesbury/nn,apaszke/nn,nicholas-leonard/nn,joeyhng/nn,sagarwaghmare69/nn
|
11754df4459a827924d728f3f15f62a7ba48c312
|
lua/functions.lua
|
lua/functions.lua
|
-- global variable for xml lib
xml = require('LuaXml')
-- select words above threshold size and add to a table
function big_words(str, thresh)
local r = {}
for i,word in pairs(str_split(str, " ")) do
if word:len() >= thresh then
r[#r+1] = word
end
end
return r
end
-- split function borrowed from http://lua-users.org/wiki/SplitJoin
function str_split(str, sep)
if str == nil then
return {}
else
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]*)", sep)
str:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
end
-- merge all but first (max-1) entries in table returned by str_split
function str_split_max(str, sep, max)
local t1 = {}
for i,v in pairs(str_split(str, sep)) do
if #t1 < max then
t1[i] = v
else
t1[#t1] = t1[#t1]..sep..v
end
end
return t1
end
-- helper function for xml parsing
function getNodes(t,nodeName,first)
local returnNodes = {}
for i,v in pairs(t) do
if type(v) == "table" and v[0] == nodeName then
if first then
if type(v) == "table" then
v.getNodes = getNodes
end
return v
end
table.insert(returnNodes,v)
end
end
return returnNodes
end
-- trim leading or trailing spaces
function cleanSpace(s)
return s:gsub("^ +",""):gsub(" +$","")
end
|
-- global variable for xml lib
xml = require('LuaXml')
-- select words above threshold size and add to a table
function big_words(str, thresh)
local r = {}
for i,word in pairs(str_split(str, " ")) do
if word:len() >= thresh then
r[#r+1] = word
end
end
return r
end
-- split string by separator
function str_split(str, sep)
if str == nil then
return {}
else
local sep, fields = sep or " ", {}
local str = str.." "
local index = 1
while index <= str:len() do
local piece_end = str:find(sep, index)
if piece_end == nil then
piece_end = str:len()
end
fields[#fields+1] = str:sub(index, piece_end - 1)
index = piece_end + 1
end
return fields
end
end
-- merge all but first (max-1) entries in table returned by str_split
function str_split_max(str, sep, max)
local t1 = {}
for i,v in pairs(str_split(str, sep)) do
if #t1 < max then
t1[i] = v
else
t1[#t1] = t1[#t1]..sep..v
end
end
return t1
end
-- helper function for xml parsing
function getNodes(t,nodeName,first)
local returnNodes = {}
for i,v in pairs(t) do
if type(v) == "table" and v[0] == nodeName then
if first then
if type(v) == "table" then
v.getNodes = getNodes
end
return v
end
table.insert(returnNodes,v)
end
end
return returnNodes
end
-- trim leading or trailing spaces
function cleanSpace(s)
return s:gsub("^ +",""):gsub(" +$","")
end
|
real bugfix for issue #1
|
real bugfix for issue #1
|
Lua
|
mit
|
wetfish/denice,pielover88888/denice
|
c34f58657e369b7fed5b6288c0267eb88694e9a8
|
argcheck.lua
|
argcheck.lua
|
local env = require 'argcheck.env' -- retrieve argcheck environement
env.istype = function(obj, typename)
if (typename == "Dataframe") then
return torch.isTypeOf(obj, Dataframe)
end
-- Either a number or string
if (typename == "number|string") then
return torch.type(obj) == "number" or
torch.type(obj) == "string"
end
-- Either a number or boolean
if (typename == "number|boolean") then
return torch.type(obj) == "number" or
torch.type(obj) == "boolean"
end
-- Either a boolean or string
if (typename == "string|boolean") then
return torch.type(obj) == "boolean" or
torch.type(obj) == "string"
end
if (typename == "number|string|boolean") then
return torch.type(obj) == "boolean" or
torch.type(obj) == "string" or
torch.type(obj) == "number"
end
if (typename == "number|string|boolean|nan") then
return torch.type(obj) == "boolean" or
torch.type(obj) == "string" or
torch.type(obj) == "number" or
isnan(obj)
end
if (typename == "number|boolean|nan") then
return torch.type(obj) == "boolean" or
torch.type(obj) == "number" or
isnan(obj)
end
-- Either a Df_Dict or boolean
if (typename == "Df_Dict|boolean") then
return torch.type(obj) == "boolean" or
torch.type(obj) == "Df_Dict"
end
-- Either a Df_Dict or string
if (typename == "Df_Dict|string") then
return torch.type(obj) == "string" or
torch.type(obj) == "Df_Dict"
end
-- Only numerical tensors count
if (typename == "torch.*Tensor") then
-- regular expressions don't work therefore this
return torch.type(obj) == "torch.IntTensor" or
torch.type(obj) == "torch.FloatTensor" or
torch.type(obj) == "torch.DoubleTensor"
end
return torch.type(obj) == typename
end
|
local env = require 'argcheck.env' -- retrieve argcheck environement
env.istype = function(obj, typename)
if (typename == "Dataframe") then
return torch.isTypeOf(obj, Dataframe)
end
-- Either a number or string
if (typename == "number|string") then
return torch.type(obj) == "number" or
torch.type(obj) == "string"
end
-- Either a number or boolean
if (typename == "number|boolean") then
return torch.type(obj) == "number" or
torch.type(obj) == "boolean"
end
-- Either a boolean or string
if (typename == "string|boolean") then
return torch.type(obj) == "boolean" or
torch.type(obj) == "string"
end
if (typename == "number|string|boolean") then
return torch.type(obj) == "boolean" or
torch.type(obj) == "string" or
torch.type(obj) == "number"
end
if (typename == "number|string|boolean|nan") then
return torch.type(obj) == "boolean" or
torch.type(obj) == "string" or
torch.type(obj) == "number" or
isnan(obj)
end
if (typename == "number|boolean|nan") then
return torch.type(obj) == "boolean" or
torch.type(obj) == "number" or
isnan(obj)
end
if (typename == "Df_Array|boolean") then
return torch.type(obj) == "boolean" or
torch.type(obj) == "Df_Array"
end
-- Either a Df_Dict or boolean
if (typename == "Df_Dict|boolean") then
return torch.type(obj) == "boolean" or
torch.type(obj) == "Df_Dict"
end
-- Either a Df_Dict or string
if (typename == "Df_Dict|string") then
return torch.type(obj) == "string" or
torch.type(obj) == "Df_Dict"
end
-- Only numerical tensors count
if (typename == "torch.*Tensor") then
-- regular expressions don't work therefore this
return torch.type(obj) == "torch.IntTensor" or
torch.type(obj) == "torch.FloatTensor" or
torch.type(obj) == "torch.DoubleTensor"
end
return torch.type(obj) == typename
end
|
Fixed missing Df_Array|boolean argcheck
|
Fixed missing Df_Array|boolean argcheck
|
Lua
|
mit
|
AlexMili/torch-dataframe
|
b9b84651e297d4b1e2994920bfc1dbf886602c39
|
spec/02-kong_storage_spec.lua
|
spec/02-kong_storage_spec.lua
|
local storage = require("kong.plugins.acme.storage.kong")
local helpers = require "spec.helpers"
for _, strategy in helpers.each_strategy() do
describe("Plugin: acme (storage.kong) [#" .. strategy .. "]", function()
local _, db
lazy_setup(function()
_, db = helpers.get_db_utils(strategy, {
"certificates",
"snis",
"cluster_events",
"acme_storage",
}, { "acme", })
db.acme_storage:truncate()
end)
describe("new", function()
it("returns no error", function()
local a = storage.new()
assert.not_nil(a)
end)
end)
describe("set", function()
ngx.update_time()
local key = tostring(ngx.now()) .. "set"
it("returns no error", function()
local a = storage.new()
local err = a:set(key, "set")
assert.is_nil(err)
err = a:set(key, "set2")
assert.is_nil(err)
end)
end)
describe("get", function()
ngx.update_time()
local key = tostring(ngx.now()) .. "get"
it("returns no error", function()
local a = storage.new()
local v, err
err = a:set(key, "get")
assert.is_nil(err)
v, err = a:get(key)
assert.is_nil(err)
assert.same("get", v)
err = a:set(key, "get2")
assert.is_nil(err)
v, err = a:get(key)
assert.is_nil(err)
assert.same("get2", v)
end)
end)
describe("delete", function()
ngx.update_time()
local key = tostring(ngx.now()) .. "delete"
it("returns no error", function()
local a = storage.new()
local v, err
err = a:set(key, "delete")
assert.not_nil(a)
assert.is_nil(err)
v, err = a:get(key)
assert.is_nil(err)
assert.same("delete", v)
err = a:delete(key)
assert.is_nil(err)
assert.same("delete", v)
v, err = a:get(key)
assert.is_nil(err)
assert.is_nil(v)
end)
end)
describe("set with ttl", function()
ngx.update_time()
local key = tostring(ngx.now()) .. "setttl"
local a = storage.new()
local err, v
it("returns no error", function()
err = a:set(key, "setttl", 1)
assert.is_nil(err)
v, err = a:get(key, "setttl")
assert.is_nil(err)
assert.same("setttl", v)
end)
it("cleans up expired key", function()
ngx.sleep(1)
v, err = a:get(key, "setttl")
assert.is_nil(err)
assert.is_nil(v)
end)
end)
describe("add with ttl", function()
ngx.update_time()
local key = tostring(ngx.now()) .. "addttl"
local a = storage.new()
local err, v
it("returns no error", function()
err = a:add(key, "add")
assert.is_nil(err)
v, err = a:get(key)
assert.is_nil(err)
assert.same("add", v)
end)
it("errors when key exists", function()
err = a:add(key, "add2")
assert.same("exists", err)
v, err = a:get(key)
assert.is_nil(err)
assert.same("add", v)
end)
end)
describe("add with ttl", function()
ngx.update_time()
local key = tostring(ngx.now()) .. "addttl"
local a = storage.new()
local err, v
it("returns no error", function()
err = a:add(key, "addttl", 1)
assert.is_nil(err)
v, err = a:get(key, "addttl")
assert.is_nil(err)
assert.same("addttl", v)
end)
it("cleans up expired key", function()
ngx.sleep(1)
v, err = a:get(key, "addttl")
assert.is_nil(err)
assert.is_nil(v)
end)
end)
describe("list", function()
ngx.update_time()
local prefix = tostring(ngx.now()) .. "list_"
local a = storage.new()
local err, keys
for i=1,10,1 do
err = a:set(prefix .. tostring(i), " ")
assert.is_nil(err)
end
it("returns all keys with no parameter", function()
keys, err = a:list()
assert.is_nil(err)
assert.not_nil(keys)
table.sort(keys)
local rows = db.acme_storage:page(100)
local expected_keys = {}
for i, row in ipairs(rows) do
expected_keys[i] = row.key
end
table.sort(expected_keys)
assert.same(expected_keys, keys)
end)
it("returns keys with given prefix", function()
keys, err = a:list(prefix)
assert.is_nil(err)
assert.not_nil(keys)
assert.same(10, #keys)
end)
it("returns empty table if no match", function()
keys, err = a:list(prefix .. "_")
assert.is_nil(err)
assert.not_nil(keys)
assert.same(0, #keys)
end)
end)
end)
end
|
local storage = require("kong.plugins.acme.storage.kong")
local helpers = require "spec.helpers"
for _, strategy in helpers.each_strategy() do
describe("Plugin: acme (storage.kong) [#" .. strategy .. "]", function()
local _, db
lazy_setup(function()
_, db = helpers.get_db_utils(strategy, {
"certificates",
"snis",
"cluster_events",
"acme_storage",
}, { "acme", })
db.acme_storage:truncate()
end)
describe("new", function()
it("returns no error", function()
local a = storage.new()
assert.not_nil(a)
end)
end)
describe("set", function()
ngx.update_time()
local key = tostring(ngx.now()) .. "set"
it("returns no error", function()
local a = storage.new()
local err = a:set(key, "set")
assert.is_nil(err)
err = a:set(key, "set2")
assert.is_nil(err)
end)
end)
describe("get", function()
ngx.update_time()
local key = tostring(ngx.now()) .. "get"
it("returns no error", function()
local a = storage.new()
local v, err
err = a:set(key, "get")
assert.is_nil(err)
v, err = a:get(key)
assert.is_nil(err)
assert.same("get", v)
err = a:set(key, "get2")
assert.is_nil(err)
v, err = a:get(key)
assert.is_nil(err)
assert.same("get2", v)
end)
end)
describe("delete", function()
ngx.update_time()
local key = tostring(ngx.now()) .. "delete"
it("returns no error", function()
local a = storage.new()
local v, err
err = a:set(key, "delete")
assert.not_nil(a)
assert.is_nil(err)
v, err = a:get(key)
assert.is_nil(err)
assert.same("delete", v)
err = a:delete(key)
assert.is_nil(err)
assert.same("delete", v)
v, err = a:get(key)
assert.is_nil(err)
assert.is_nil(v)
end)
end)
describe("set with ttl", function()
ngx.update_time()
local key = tostring(ngx.now()) .. "setttl"
local a = storage.new()
local err, v
it("returns no error", function()
err = a:set(key, "setttl", 1)
assert.is_nil(err)
v, err = a:get(key)
assert.is_nil(err)
assert.same("setttl", v)
end)
it("cleans up expired key", function()
ngx.sleep(1)
v, err = a:get(key)
assert.is_nil(err)
assert.is_nil(v)
end)
end)
describe("add without ttl", function()
ngx.update_time()
local key = tostring(ngx.now()) .. "add"
local a = storage.new()
local err, v
it("returns no error", function()
err = a:add(key, "add")
assert.is_nil(err)
v, err = a:get(key)
assert.is_nil(err)
assert.same("add", v)
end)
it("errors when key exists", function()
err = a:add(key, "add2")
assert.same("exists", err)
v, err = a:get(key)
assert.is_nil(err)
assert.same("add", v)
end)
end)
describe("add with ttl", function()
ngx.update_time()
local key = tostring(ngx.now()) .. "addttl"
local a = storage.new()
local err, v
it("returns no error", function()
err = a:add(key, "addttl", 1)
assert.is_nil(err)
v, err = a:get(key)
assert.is_nil(err)
assert.same("addttl", v)
end)
it("cleans up expired key", function()
ngx.sleep(1)
v, err = a:get(key)
assert.is_nil(err)
assert.is_nil(v)
end)
end)
describe("list", function()
ngx.update_time()
local prefix = tostring(ngx.now()) .. "list_"
local a = storage.new()
local err, keys
for i=1,10,1 do
err = a:set(prefix .. tostring(i), " ")
assert.is_nil(err)
end
it("returns all keys with no parameter", function()
keys, err = a:list()
assert.is_nil(err)
assert.not_nil(keys)
table.sort(keys)
local rows = db.acme_storage:page(100)
local expected_keys = {}
for i, row in ipairs(rows) do
expected_keys[i] = row.key
end
table.sort(expected_keys)
assert.same(expected_keys, keys)
end)
it("returns keys with given prefix", function()
keys, err = a:list(prefix)
assert.is_nil(err)
assert.not_nil(keys)
assert.same(10, #keys)
end)
it("returns empty table if no match", function()
keys, err = a:list(prefix .. "_")
assert.is_nil(err)
assert.not_nil(keys)
assert.same(0, #keys)
end)
end)
end)
end
|
fix(acme) fix typo in tests (#5)
|
fix(acme) fix typo in tests (#5)
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
fb22235aac0f9c0e42ab6876f0516cee9445a11f
|
ardivink.lua
|
ardivink.lua
|
ci = require("ci")
--godi = require("godi")
oasis = require("oasis")
git = require("git")
ci.init()
-- godi.init()
git.init()
oasis.init()
--godi.bootstrap("3.12")
--godi.update()
--godi.upgrade()
--godi.build_many(
-- {"godi-findlib",
-- "godi-ocaml-fileutils",
-- "godi-ocaml-data-notation",
-- "godi-ocaml-expect",
-- "godi-ounit",
-- "apps-ocamlmod",
-- "apps-ocamlify"})
oasis.std_process("--enable-tests")
git.create_tag(oasis.package_version())
|
ci = require("ci")
--godi = require("godi")
oasis = require("oasis")
git = require("git")
ci.init()
-- godi.init()
ci.prependenv("PATH", "/usr/opt/godi/bin")
ci.prependenv("PATH", "/usr/opt/godi/sbin")
git.init()
oasis.init()
--godi.bootstrap("3.12")
--godi.update()
--godi.upgrade()
--godi.build_many(
-- {"godi-findlib",
-- "godi-ocaml-fileutils",
-- "godi-ocaml-data-notation",
-- "godi-ocaml-expect",
-- "godi-ounit",
-- "apps-ocamlmod",
-- "apps-ocamlify"})
oasis.std_process("--enable-tests")
git.create_tag(oasis.package_version())
|
Fix path for GODI installation on deci.
|
Fix path for GODI installation on deci.
|
Lua
|
lgpl-2.1
|
jpdeplaix/oasis,jpdeplaix/oasis,gerdstolpmann/oasis,madroach/oasis,jpdeplaix/oasis,madroach/oasis,Chris00/oasis,gerdstolpmann/oasis,diml/oasis,RadicalZephyr/oasis,Chris00/oasis,Chris00/oasis,RadicalZephyr/oasis,gerdstolpmann/oasis,diml/oasis
|
24bff8935338438e11ae1c88b94fef203e0de960
|
spec/os_spec.lua
|
spec/os_spec.lua
|
describe('lift.os', function()
local WAIT = 100 -- how much to wait for a process to finish
if os.getenv('CI') then
WAIT = 200
end
local os = require 'lift.os'
local ls = require 'lift.string'
local async = require 'lift.async'
local config = require 'lift.config'
local su = require 'spec.util'
it('offers sh() to execute a shell command', su.async(function()
local out, err = assert(os.sh'echo Hello world!|cat')
assert.equal('Hello world!\n', out)
assert.equal('', err)
out, err = assert(os.sh[[lua -e "io.write'Hello from stdout'"]])
assert.equal('Hello from stdout', out)
assert.equal('', err)
out, err = assert(os.sh[[lua -e "io.stderr:write'Hello from stderr'"]])
assert.equal('', out)
assert.equal('Hello from stderr', err)
out, err = os.sh'invalid_cmd error'
assert.Nil(out)
assert.match('shell command failed', err)
end))
describe("child processes", function()
it("can be started with spawn()", su.async(function()
local c = assert(os.spawn{file = config.LUA_EXE_PATH, '-e', 'os.exit(7)',
stdin = 'ignore', stdout = 'ignore', stderr = 'ignore'})
assert.is_number(c.pid)
assert.is_nil(c.status)
assert.is_nil(c.signal)
async.sleep(WAIT)
assert.equal(7, c.status)
assert.equal(0, c.signal)
end))
it("can be terminated with :kill()", su.async(function()
local c = assert(os.spawn{file = 'sleep', '3',
stdin = 'ignore', stdout = 'ignore', stderr = 'ignore'})
assert.is_number(c.pid)
assert.is_nil(c.status)
assert.is_nil(c.signal)
c:kill()
async.sleep(WAIT)
assert.equal(15, c.signal) -- sigterm
assert.error(function() c:kill() end,
'process:kill() called after process termination')
end))
it("can inherit fds from parent and be waited for", su.async(function()
local c = assert(os.spawn{file = config.LUA_EXE_PATH,
'-e', 'print[[Hello from child process]]',
stdin = 'ignore', stdout = 'inherit', stderr = 'inherit'})
assert.Nil(c.status)
c:wait()
assert.equal(0, c.status, c.signal)
end))
it("can be waited for with a timeout", su.async(function()
-- with enough time
local c = assert(os.spawn{file = config.LUA_EXE_PATH,
'-e', 'print[[this is fast]]',
stdin = 'ignore', stdout = 'ignore', stderr = 'ignore'})
assert.Nil(c.status)
local status, signal = c:wait(300)
assert.equal(0, status, signal)
-- without enough time
c = assert(os.spawn{file = 'sleep', '5',
stdin = 'ignore', stdout = 'ignore', stderr = 'ignore'})
assert.Nil(c.status)
status, signal = c:wait(300)
c:kill()
assert.False(status)
assert.equal(signal, 'timed out')
end))
it("can be read from (stdout, stderr)", su.async(function()
local c = assert(os.spawn{file = config.LUA_EXE_PATH,
'-e', 'print[[Hello world]]', stdin = 'ignore'})
assert.Nil(c:try_read())
assert.Nil(c.stderr:try_read())
c:wait() -- await exit before reading
assert.equal('Hello world\n', ls.native_to_lf(c:try_read()))
assert.Nil(c.stderr:try_read())
end))
it("can be written to (stdin) and read from (stdout)", su.async(function()
local c = assert(os.spawn{file = 'cat'})
c:write('One')
c.stdin:write('Two')
c:write() -- shuts down stdin, causing 'cat' to exit
assert.Nil(c.stdout:try_read())
assert.Nil(c.stderr:try_read())
c:wait() -- await exit before reading
local sb = {c:try_read(), c:try_read()}
assert.equal('OneTwo', table.concat(sb))
assert.Nil(c.stderr:try_read())
end))
it("can be written to (stdin) and read from (stderr)", su.async(function()
local c = assert(os.spawn{file = 'lua',
'-e', 'io.stderr:write(io.read())', stdout = 'ignore'})
c:write('Hello from stderr')
c:write() -- shuts down stdin, causing the process to exit
assert.Nil(c.stdout)
assert.Nil(c.stderr:try_read())
c:wait() -- await exit before reading
assert.equal('Hello from stderr', c.stderr:try_read())
end))
it("can be written to (stdin) and read from (stdout) synchronously", su.async(function()
local c = assert(os.spawn{file = 'cat'})
c:write('One')
c.stdin:write('Two')
assert.equal('OneTwo', c:read())
c:write('Three')
assert.equal('Three', c:read())
c:write()
assert.Nil(c:read())
assert.Nil(c.stderr:read())
end))
it("can be piped to another process", su.async(function()
local echo1 = assert(os.spawn{file = config.LUA_EXE_PATH,
'-e', 'io.write[[OneTwoThree]]', stdin = 'ignore'})
local echo2 = assert(os.spawn{file = config.LUA_EXE_PATH,
'-e', 'io.write[[FourFive]]', stdin = 'ignore'})
local cat1 = assert(os.spawn{file = 'cat'})
local cat2 = assert(os.spawn{file = 'cat'})
cat1:pipe(cat2)
echo1:pipe(cat1, true) -- pipe to cat1 and keep cat1 open
echo1.stdout:wait_end()
echo2:pipe(cat1) -- pipe to cat1 and shut down cat1
echo2.stdout:wait_end()
local sb = {cat2:read(), cat2:read()}
assert.equal('OneTwoThreeFourFive', table.concat(sb))
end))
end)
end)
|
describe('lift.os', function()
local WAIT = 100 -- how much to wait for a process to finish
if os.getenv('CI') then
WAIT = 200
end
local os = require 'lift.os'
local ls = require 'lift.string'
local async = require 'lift.async'
local config = require 'lift.config'
local su = require 'spec.util'
it('offers sh() to execute a shell command', su.async(function()
local out, err = assert(os.sh'echo Hello world!|cat')
assert.equal('Hello world!\n', out)
assert.equal('', err)
out, err = assert(os.sh[[lua -e "io.write'Hello from stdout'"]])
assert.equal('Hello from stdout', out)
assert.equal('', err)
out, err = assert(os.sh[[lua -e "io.stderr:write'Hello from stderr'"]])
assert.equal('', out)
assert.equal('Hello from stderr', err)
out, err = os.sh'invalid_cmd error'
assert.Nil(out)
assert.match('shell command failed', err)
end))
describe("child processes", function()
it("can be started with spawn()", su.async(function()
local c = assert(os.spawn{file = config.LUA_EXE_PATH, '-e', 'os.exit(7)',
stdin = 'ignore', stdout = 'ignore', stderr = 'ignore'})
assert.is_number(c.pid)
assert.is_nil(c.status)
assert.is_nil(c.signal)
async.sleep(WAIT)
assert.equal(7, c.status)
assert.equal(0, c.signal)
end))
it("can be terminated with :kill()", su.async(function()
local c = assert(os.spawn{file = 'sleep', '3',
stdin = 'ignore', stdout = 'ignore', stderr = 'ignore'})
assert.is_number(c.pid)
assert.is_nil(c.status)
assert.is_nil(c.signal)
c:kill()
async.sleep(WAIT)
assert.equal(15, c.signal) -- sigterm
assert.error(function() c:kill() end,
'process:kill() called after process termination')
end))
it("can inherit fds from parent and be waited for", su.async(function()
local c = assert(os.spawn{file = config.LUA_EXE_PATH,
'-e', 'print[[Hello from child process]]',
stdin = 'ignore', stdout = 'inherit', stderr = 'inherit'})
assert.Nil(c.status)
c:wait()
assert.equal(0, c.status, c.signal)
end))
it("can be waited for with a timeout", su.async(function()
-- with enough time
local c = assert(os.spawn{file = config.LUA_EXE_PATH,
'-e', 'print[[this is fast]]',
stdin = 'ignore', stdout = 'ignore', stderr = 'ignore'})
assert.Nil(c.status)
local status, signal = c:wait(300)
assert.equal(0, status, signal)
-- without enough time
c = assert(os.spawn{file = 'sleep', '5',
stdin = 'ignore', stdout = 'ignore', stderr = 'ignore'})
assert.Nil(c.status)
status, signal = c:wait(300)
c:kill()
assert.False(status)
assert.equal(signal, 'timed out')
end))
it("can be read from (stdout, stderr)", su.async(function()
local c = assert(os.spawn{file = config.LUA_EXE_PATH,
'-e', 'print[[Hello world]]', stdin = 'ignore'})
assert.Nil(c:try_read())
assert.Nil(c.stderr:try_read())
c:wait() -- await exit before reading
assert.equal('Hello world\n', ls.native_to_lf(c:try_read()))
assert.Nil(c.stderr:try_read())
end))
it("can be written to (stdin) and read from (stdout)", su.async(function()
local c = assert(os.spawn{file = 'cat'})
c:write('One')
c.stdin:write('Two')
c:write() -- shuts down stdin, causing 'cat' to exit
assert.Nil(c.stdout:try_read())
assert.Nil(c.stderr:try_read())
c:wait() -- await exit before reading
local sb = {c:try_read()}
sb[#sb+1] = c:try_read()
assert.equal('OneTwo', table.concat(sb))
assert.Nil(c.stderr:try_read())
end))
it("can be written to (stdin) and read from (stderr)", su.async(function()
local c = assert(os.spawn{file = 'lua',
'-e', 'io.stderr:write(io.read())', stdout = 'ignore'})
c:write('Hello from stderr')
c:write() -- shuts down stdin, causing the process to exit
assert.Nil(c.stdout)
assert.Nil(c.stderr:try_read())
c:wait() -- await exit before reading
assert.equal('Hello from stderr', c.stderr:try_read())
end))
it("can be written to (stdin) and read from (stdout) synchronously", su.async(function()
local c = assert(os.spawn{file = 'cat'})
c:write('One')
c.stdin:write('Two')
assert.equal('OneTwo', c:read())
c:write('Three')
assert.equal('Three', c:read())
c:write()
assert.Nil(c:read())
assert.Nil(c.stderr:read())
end))
it("can be piped to another process", su.async(function()
local echo1 = assert(os.spawn{file = config.LUA_EXE_PATH,
'-e', 'io.write[[OneTwoThree]]', stdin = 'ignore'})
local echo2 = assert(os.spawn{file = config.LUA_EXE_PATH,
'-e', 'io.write[[FourFive]]', stdin = 'ignore'})
local cat1 = assert(os.spawn{file = 'cat'})
local cat2 = assert(os.spawn{file = 'cat'})
cat1:pipe(cat2)
echo1:pipe(cat1, true) -- pipe to cat1 and keep cat1 open
echo1.stdout:wait_end()
echo2:pipe(cat1) -- pipe to cat1 and shut down cat1
echo2.stdout:wait_end()
local sb = {cat2:read()}
sb[#sb+1] = cat2:read()
assert.equal('OneTwoThreeFourFive', table.concat(sb))
end))
end)
end)
|
Fix test
|
Fix test
|
Lua
|
mit
|
tbastos/lift
|
0ad80ec34f1ac0a4c267ce84fcb0c5ac4d579a14
|
org_v1/indri_query.lua
|
org_v1/indri_query.lua
|
-- TODO allow refining results (indri can query a given document set, the results)
-- TODO fix rendering of spots with long "strong" strings, #od(new driver)
local curses = require("curses") -- from lua posix
local QueryEnvironment = require("indri_queryenvironment")
curses.initscr()
curses.cbreak()
curses.nl(0)
curses.echo(0)
curses.start_color()
curses.use_default_colors()
-- highlighted word in snippet
curses.init_pair(1, curses.COLOR_WHITE, -1)
-- default colors
curses.init_pair(2, -1, -1)
-- selected title
curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_GREEN)
local stdscr = curses.stdscr() -- global
stdscr:keypad(true)
local maxy, maxx = stdscr:getmaxyx() -- global
local indexes = {"../email_v1_index"} -- global
function printWithBold(snippet, maxChars)
while true do
local strongPos = snippet:find("<strong>")
-- just print it if it's out of our range
if not strongPos or strongPos >= maxChars then
stdscr:addstr(snippet, maxChars)
snippet = snippet:sub(maxChars)
maxChars = 0
break
end
local strongString = snippet:sub(strongPos + #"<strong>")
strongString = strongString:sub(1, strongString:find("</strong>") - 1)
local charsTilStrongEnd = strongPos + #strongString - 1
if charsTilStrongEnd < maxChars then
-- case #1 snippet include bold will fit
stdscr:addstr(snippet:sub(1, strongPos - 1))
stdscr:attron(curses.A_BOLD)
stdscr:attron(curses.color_pair(1))
stdscr:addstr(strongString)
stdscr:attron(curses.color_pair(2))
stdscr:attroff(curses.A_BOLD)
maxChars = maxChars - charsTilStrongEnd
snippet = snippet:sub(snippet:find("</strong>") + #"</strong>")
elseif strongPos < maxChars then
-- case #2 only snippet without bold will fit
stdscr:addstr(snippet:sub(1, strongPos - 1))
maxChars = maxChars - strongPos
snippet = snippet:sub(strongPos)
end
end
return snippet, maxChars
end
function showPage(pageNum, pageMinIndex, qr, selectedItem)
local nextLine
clear_screen()
if pageMinIndex[pageNum] == nil then
-- first time we see this page, it's going forward
pageMinIndex[pageNum] = qr.position
else
-- re-visting a page
qr.position = pageMinIndex[pageNum]
end
for i = 3, maxy - 4 do
stdscr:move(i, 0)
if nextLine then
printWithBold(nextLine, maxx - 2)
nextLine = nil
else
local entry = qr:nextRawEntry()
if entry == nil then
break
end
local snippet = entry.snippet
snippet = snippet:gsub("<strong>...</strong>", "...")
snippet = snippet:gsub("<", "<")
snippet = snippet:gsub(">", ">")
snippet = snippet:gsub("&", "&")
local totalChars = maxx - 1 -- chars we have left (rename this var)
if entry.position == selectedItem then
stdscr:attron(curses.color_pair(3))
end
stdscr:addstr(string.format("%4d ", entry.position))
totalChars = totalChars - 5
local titleChars = math.floor(maxx * 0.3)
stdscr:addstr(entry.title, titleChars)
stdscr:attron(curses.color_pair(2))
totalChars = totalChars - titleChars
stdscr:move(i, maxx - totalChars)
stdscr:addstr("| ")
totalChars = totalChars - 2
snippet = printWithBold(snippet, totalChars)
if #snippet > 10 then
nextLine = string.rep(" ", maxx - totalChars) .. snippet
end
end
end
local status = string.format("query: %s results: %d-%d (of %d) page: %d",
qr.queryString,
pageMinIndex[pageNum],
qr.position - 1,
qr.count,
pageNum)
stdscr:mvaddstr(1, 0, status)
stdscr:refresh()
end
function doQuery()
-- create query input window
local qInput = curses.newwin(3, 40, maxy / 2, (maxx / 2) - 20)
qInput:box("|", "-")
qInput:mvaddstr(1, 3, "Query: ")
qInput:refresh()
-- accept query input
curses.cbreak(0)
curses.echo(1)
local queryString = qInput:getstr()
curses.cbreak()
curses.echo(0)
-- remove query input window
qInput:clear()
qInput:refresh()
qInput:close()
-- cancel if no input entered
if queryString == "" then
return
end
-- begin indri query
local qe = QueryEnvironment.new()
qe:addIndex(indexes[1])
local qr = qe:query(queryString)
-- mapping of page->minResultIndex
local pageMinIndex = {1}
local currentPage = 1
local selectedItem = 1
-- show first page
showPage(currentPage, pageMinIndex, qr, selectedItem)
-- process commands
while true do
local k = stdscr:getch()
local keyname = curses.keyname(k)
if keyname == "q" then
break
elseif keyname == "KEY_NPAGE" then
if qr.position < qr.count then
currentPage = currentPage + 1
selectedItem = qr.position
showPage(currentPage, pageMinIndex, qr, selectedItem)
end
elseif keyname == "KEY_PPAGE" then
if currentPage > 1 then
currentPage = currentPage - 1
selectedItem = pageMinIndex[currentPage]
showPage(currentPage, pageMinIndex, qr, selectedItem)
end
elseif keyname == "KEY_DOWN" then
if selectedItem + 1 < qr.position then
selectedItem = selectedItem + 1
-- redisplaying the whole page, maybe not the most efficient
showPage(currentPage, pageMinIndex, qr, selectedItem)
end
elseif keyname == "KEY_UP" then
if selectedItem > pageMinIndex[currentPage] then
selectedItem = selectedItem - 1
showPage(currentPage, pageMinIndex, qr, selectedItem)
end
end
end
qe:close()
end
function clear_screen()
local title = "Indri Query"
stdscr:clear()
stdscr:move(0, 0)
local dashCount = ((maxx - 2) - #title) / 2
for i = 1, dashCount do
stdscr:addch("-")
end
stdscr:addstr(" " .. title .. " ")
for i = 1, dashCount do
stdscr:addch("-")
end
stdscr:mvaddstr(maxy - 1, 0, "q: query x: exit ")
stdscr:mvaddstr(2, 0, ("-"):rep(maxx - 1))
stdscr:refresh()
end
function main()
while true do
clear_screen()
local k = string.char(stdscr:getch())
if k == "x" then
curses.endwin()
print("Done!")
return
elseif k == "q" then
doQuery()
end
end
end
local status, err = pcall(main)
curses.endwin()
if err then
print(err)
end
|
-- TODO allow refining results (indri can query a given document set, the results)
-- TODO fix rendering of spots with long "strong" strings, #od(new driver)
local curses = require("curses") -- from lua posix
local QueryEnvironment = require("indri_queryenvironment")
curses.initscr()
curses.cbreak()
curses.nl(0)
curses.echo(0)
curses.start_color()
curses.use_default_colors()
-- highlighted word in snippet
curses.init_pair(1, curses.COLOR_WHITE, -1)
-- default colors
curses.init_pair(2, -1, -1)
-- selected title
curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_GREEN)
local stdscr = curses.stdscr() -- global
stdscr:keypad(true)
local maxy, maxx = stdscr:getmaxyx() -- global
local indexes = {"../email_v1_index"} -- global
function printWithBold(snippet, maxChars)
while maxChars > 0 do
local strongPos = snippet:find("<strong>")
-- just print it if it's out of our range
if not strongPos or strongPos >= maxChars then
stdscr:addstr(snippet, maxChars)
snippet = snippet:sub(maxChars + 1)
maxChars = 0
break
end
local strongString = snippet:sub(strongPos + #"<strong>")
strongString = strongString:sub(1, strongString:find("</strong>") - 1)
local charsTilStrongEnd = (strongPos - 1) + #strongString
if charsTilStrongEnd <= maxChars then
-- case #1 snippet including highlighted string will fit
stdscr:addstr(snippet:sub(1, strongPos - 1))
stdscr:attron(curses.A_BOLD)
stdscr:attron(curses.color_pair(1))
stdscr:addstr(strongString)
stdscr:attron(curses.color_pair(2))
stdscr:attroff(curses.A_BOLD)
maxChars = maxChars - charsTilStrongEnd
snippet = snippet:sub(snippet:find("</strong>") + #"</strong>")
else
-- case #2 only snippet without bold will fit
stdscr:addstr(snippet:sub(1, strongPos - 1), maxChars)
maxChars = maxChars - (strongPos - 1)
snippet = snippet:sub(strongPos)
end
end
return snippet, maxChars
end
function showPage(pageNum, pageMinIndex, qr, selectedItem)
local nextLine
clear_screen()
if pageMinIndex[pageNum] == nil then
-- first time we see this page, it's going forward
pageMinIndex[pageNum] = qr.position
else
-- re-visting a page
qr.position = pageMinIndex[pageNum]
end
for i = 3, maxy - 4 do
stdscr:move(i, 0)
if nextLine then
printWithBold(nextLine, maxx - 2)
nextLine = nil
else
local entry = qr:nextRawEntry()
if entry == nil then
break
end
local snippet = entry.snippet
snippet = snippet:gsub("<strong>...</strong>", "...")
snippet = snippet:gsub("<", "<")
snippet = snippet:gsub(">", ">")
snippet = snippet:gsub("&", "&")
local totalChars = maxx -- chars we have left (rename this var)
if entry.position == selectedItem then
stdscr:attron(curses.color_pair(3))
end
stdscr:addstr(string.format("%4d ", entry.position))
totalChars = totalChars - 5
local titleChars = math.floor(maxx * 0.3)
stdscr:addstr(entry.title, titleChars)
stdscr:attron(curses.color_pair(2))
totalChars = totalChars - titleChars
stdscr:move(i, maxx - totalChars)
stdscr:addstr("| ")
totalChars = totalChars - 2
snippet = printWithBold(snippet, totalChars - 2)
if #snippet > 10 then
nextLine = string.rep(" ", maxx - totalChars) .. snippet
end
end
end
local status = string.format("query: %s results: %d-%d (of %d) page: %d",
qr.queryString,
pageMinIndex[pageNum],
qr.position - 1,
qr.count,
pageNum)
stdscr:mvaddstr(1, 0, status)
stdscr:refresh()
end
function doQuery()
-- create query input window
local qInput = curses.newwin(3, 40, maxy / 2, (maxx / 2) - 20)
qInput:box("|", "-")
qInput:mvaddstr(1, 3, "Query: ")
qInput:refresh()
-- accept query input
curses.cbreak(0)
curses.echo(1)
local queryString = qInput:getstr()
curses.cbreak()
curses.echo(0)
-- remove query input window
qInput:clear()
qInput:refresh()
qInput:close()
-- cancel if no input entered
if queryString == "" then
return
end
-- begin indri query
local qe = QueryEnvironment.new()
qe:addIndex(indexes[1])
local qr = qe:query(queryString)
-- mapping of page->minResultIndex
local pageMinIndex = {1}
local currentPage = 1
local selectedItem = 1
-- show first page
showPage(currentPage, pageMinIndex, qr, selectedItem)
-- process commands
while true do
local k = stdscr:getch()
local keyname = curses.keyname(k)
-- debug the keyname
--stdscr:mvaddstr(0, 0, string.format("< %s >", keyname))
if keyname == "q" then
break
elseif keyname == "KEY_NPAGE" then
if qr.position < qr.count then
currentPage = currentPage + 1
selectedItem = qr.position
showPage(currentPage, pageMinIndex, qr, selectedItem)
end
elseif keyname == "KEY_PPAGE" then
if currentPage > 1 then
currentPage = currentPage - 1
selectedItem = pageMinIndex[currentPage]
showPage(currentPage, pageMinIndex, qr, selectedItem)
end
elseif keyname == "KEY_DOWN" then
if selectedItem + 1 < qr.position then
selectedItem = selectedItem + 1
-- redisplaying the whole page, maybe not the most efficient
showPage(currentPage, pageMinIndex, qr, selectedItem)
end
elseif keyname == "KEY_UP" then
if selectedItem > pageMinIndex[currentPage] then
selectedItem = selectedItem - 1
showPage(currentPage, pageMinIndex, qr, selectedItem)
end
elseif keyname == "^J" then
-- TODO display item in separate window
end
end
qe:close()
end
function clear_screen()
local title = "Indri Query"
stdscr:clear()
stdscr:move(0, 0)
local dashCount = ((maxx - 2) - #title) / 2
for i = 1, dashCount do
stdscr:addch("-")
end
stdscr:addstr(" " .. title .. " ")
for i = 1, dashCount do
stdscr:addch("-")
end
stdscr:mvaddstr(maxy - 1, 0, "q: query x: exit ")
stdscr:mvaddstr(2, 0, ("-"):rep(maxx - 1))
stdscr:refresh()
end
function main()
while true do
clear_screen()
local k = string.char(stdscr:getch())
if k == "x" then
curses.endwin()
print("Done!")
return
elseif k == "q" then
doQuery()
end
end
end
local status, err = pcall(main)
curses.endwin()
if err then
print(err)
end
|
fix char alginments
|
fix char alginments
|
Lua
|
mit
|
jbalint/indri_stuff,jbalint/indri_stuff,jbalint/indri_stuff
|
7350b4c8be670bb26ac505df040cc3266c6c74b8
|
util/httpstream.lua
|
util/httpstream.lua
|
local coroutine = coroutine;
local tonumber = tonumber;
local deadroutine = coroutine.create(function() end);
coroutine.resume(deadroutine);
module("httpstream")
local function parser(success_cb, parser_type, options_cb)
local data = coroutine.yield();
local function readline()
local pos = data:find("\r\n", nil, true);
while not pos do
data = data..coroutine.yield();
pos = data:find("\r\n", nil, true);
end
local r = data:sub(1, pos-1);
data = data:sub(pos+2);
return r;
end
local function readlength(n)
while #data < n do
data = data..coroutine.yield();
end
local r = data:sub(1, n);
data = data:sub(n + 1);
return r;
end
local function readheaders()
local headers = {}; -- read headers
while true do
local line = readline();
if line == "" then break; end -- headers done
local key, val = line:match("^([^%s:]+): *(.*)$");
if not key then coroutine.yield("invalid-header-line"); end -- TODO handle multi-line and invalid headers
key = key:lower();
headers[key] = headers[key] and headers[key]..","..val or val;
end
return headers;
end
if not parser_type or parser_type == "server" then
while true do
-- read status line
local status_line = readline();
local method, path, httpversion = status_line:match("^(%S+)%s+(%S+)%s+HTTP/(%S+)$");
if not method then coroutine.yield("invalid-status-line"); end
-- TODO parse url
local headers = readheaders();
-- read body
local len = tonumber(headers["content-length"]);
len = len or 0; -- TODO check for invalid len
local body = readlength(len);
success_cb({
method = method;
path = path;
httpversion = httpversion;
headers = headers;
body = body;
});
end
elseif parser_type == "client" then
while true do
-- read status line
local status_line = readline();
local httpversion, status_code, reason_phrase = status_line:match("^HTTP/(%S+)%s+(%d%d%d)%s+(.*)$");
if not httpversion then coroutine.yield("invalid-status-line"); end
local headers = readheaders();
-- read body
local have_body = not
( (options_cb and options_cb().method == "HEAD")
or (status_code == 204 or status_code == 304 or status_code == 301)
or (status_code >= 100 and status_code < 200) );
local body;
if have_body then
local len = tonumber(headers["content-length"]);
if len then -- TODO check for invalid len
body = readlength(len);
else -- read to end
repeat
local newdata = coroutine.yield();
data = data..newdata;
until newdata == "";
body, data = data, "";
end
end
success_cb({
code = status_code;
responseversion = httpversion;
responseheaders = headers;
body = body;
});
end
else coroutine.yield("unknown-parser-type"); end
end
function new(success_cb, error_cb, parser_type, options_cb)
local co = coroutine.create(parser);
coroutine.resume(co, success_cb, parser_type, options_cb)
return {
feed = function(self, data)
if not data then
if parser_type == "client" then coroutine.resume(co, ""); end
co = deadroutine;
return error_cb();
end
local success, result = coroutine.resume(co, data);
if result then
co = deadroutine;
return error_cb(result);
end
end;
};
end
return _M;
|
local coroutine = coroutine;
local tonumber = tonumber;
local deadroutine = coroutine.create(function() end);
coroutine.resume(deadroutine);
module("httpstream")
local function parser(success_cb, parser_type, options_cb)
local data = coroutine.yield();
local function readline()
local pos = data:find("\r\n", nil, true);
while not pos do
data = data..coroutine.yield();
pos = data:find("\r\n", nil, true);
end
local r = data:sub(1, pos-1);
data = data:sub(pos+2);
return r;
end
local function readlength(n)
while #data < n do
data = data..coroutine.yield();
end
local r = data:sub(1, n);
data = data:sub(n + 1);
return r;
end
local function readheaders()
local headers = {}; -- read headers
while true do
local line = readline();
if line == "" then break; end -- headers done
local key, val = line:match("^([^%s:]+): *(.*)$");
if not key then coroutine.yield("invalid-header-line"); end -- TODO handle multi-line and invalid headers
key = key:lower();
headers[key] = headers[key] and headers[key]..","..val or val;
end
return headers;
end
if not parser_type or parser_type == "server" then
while true do
-- read status line
local status_line = readline();
local method, path, httpversion = status_line:match("^(%S+)%s+(%S+)%s+HTTP/(%S+)$");
if not method then coroutine.yield("invalid-status-line"); end
-- TODO parse url
local headers = readheaders();
-- read body
local len = tonumber(headers["content-length"]);
len = len or 0; -- TODO check for invalid len
local body = readlength(len);
success_cb({
method = method;
path = path;
httpversion = httpversion;
headers = headers;
body = body;
});
end
elseif parser_type == "client" then
while true do
-- read status line
local status_line = readline();
local httpversion, status_code, reason_phrase = status_line:match("^HTTP/(%S+)%s+(%d%d%d)%s+(.*)$");
status_code = tonumber(status_code);
if not status_code then coroutine.yield("invalid-status-line"); end
local headers = readheaders();
-- read body
local have_body = not
( (options_cb and options_cb().method == "HEAD")
or (status_code == 204 or status_code == 304 or status_code == 301)
or (status_code >= 100 and status_code < 200) );
local body;
if have_body then
local len = tonumber(headers["content-length"]);
if len then -- TODO check for invalid len
body = readlength(len);
else -- read to end
repeat
local newdata = coroutine.yield();
data = data..newdata;
until newdata == "";
body, data = data, "";
end
end
success_cb({
code = status_code;
responseversion = httpversion;
responseheaders = headers;
body = body;
});
end
else coroutine.yield("unknown-parser-type"); end
end
function new(success_cb, error_cb, parser_type, options_cb)
local co = coroutine.create(parser);
coroutine.resume(co, success_cb, parser_type, options_cb)
return {
feed = function(self, data)
if not data then
if parser_type == "client" then coroutine.resume(co, ""); end
co = deadroutine;
return error_cb();
end
local success, result = coroutine.resume(co, data);
if result then
co = deadroutine;
return error_cb(result);
end
end;
};
end
return _M;
|
util.httpstream: Fixed a possible string to number comparison error.
|
util.httpstream: Fixed a possible string to number comparison error.
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
8178cc6846714d7ecd86dca205c856ea092e2db2
|
item/rings.lua
|
item/rings.lua
|
-- UPDATE common SET com_script = 'item.rings' WHERE com_itemid IN (68, 277, 278, 279, 280, 281, 282);
require("item.general.jewel")
require("content.jewelbonus")
module("item.rings", package.seeall, package.seeall(item.general.jewel))
function MoveItemAfterMove( User, SourceItem, TargetItem )
--User:inform("in move");
stoneNr,stoneStr=content.jewelbonus.getBonus(TargetItem);
--User:inform("bla");
if stoneNr>0 then -- obviously a gem was inserted!
if ((TargetItem.itempos==7) or (TargetItem.itempos==8)) then -- put on a finger
content.jewelbonus.giveBonus(User,TargetItem); -- now raise corresponding attribute(s) and start LTE
elseif ((SourceItem.itempos==7) or (SourceItem.itempos==8)) then -- taken off of a finger
content.jewelbonus.takeBonus(User,SourceItem,stoneNr,stoneStr); -- now lower corresponding attribute(s) and remove/change LTE
end
--User:inform("blubb");
end
end
|
-- UPDATE common SET com_script = 'item.rings' WHERE com_itemid IN (68, 277, 278, 279, 280, 281, 282);
require("item.general.jewel")
require("content.jewelbonus")
module("item.rings", package.seeall)
function MoveItemAfterMove( User, SourceItem, TargetItem )
--User:inform("in move");
stoneNr,stoneStr=content.jewelbonus.getBonus(TargetItem);
--User:inform("bla");
if stoneNr>0 then -- obviously a gem was inserted!
if ((TargetItem.itempos==7) or (TargetItem.itempos==8)) then -- put on a finger
if ((SourceItem.itempos == 7) or (SourceItem.itempos==8)) then
-- no change
else
content.jewelbonus.giveBonus(User,TargetItem); -- now raise corresponding attribute(s) and start LTE
end
elseif ((SourceItem.itempos==7) or (SourceItem.itempos==8)) then -- taken off of a finger
content.jewelbonus.takeBonus(User,SourceItem,stoneNr,stoneStr); -- now lower corresponding attribute(s) and remove/change LTE
end
--User:inform("blubb");
end
end
function LookAtItem(User,Item)
item.general.jewel.LookAtItem(User,Item);
end
|
Uber-Exploit Fix
|
Uber-Exploit Fix
|
Lua
|
agpl-3.0
|
Illarion-eV/Illarion-Content,vilarion/Illarion-Content,Baylamon/Illarion-Content,LaFamiglia/Illarion-Content,KayMD/Illarion-Content
|
fdae3d3603f551a59a9452bef93345460272da7b
|
kong/cache.lua
|
kong/cache.lua
|
local kong_mlcache = require "kong.mlcache"
local type = type
local max = math.max
local ngx_log = ngx.log
local ngx_now = ngx.now
local ERR = ngx.ERR
local NOTICE = ngx.NOTICE
local DEBUG = ngx.DEBUG
local SHM_CACHE = "kong_cache"
--[[
Hypothesis
----------
Item size: 1024 bytes
Max memory limit: 500 MiBs
LRU size must be: (500 * 2^20) / 1024 = 512000
Floored: 500.000 items should be a good default
--]]
local LRU_SIZE = 5e5
local _init
local function log(lvl, ...)
return ngx_log(lvl, "[DB cache] ", ...)
end
-- Temporary fix to convert soft callback errors into hard ones.
-- FIXME: use upstream mlcache lib instead of local copy
local soft_to_hard
do
local s2h_cache = setmetatable({}, { __mode = "k" })
local function create_wrapper(cb)
s2h_cache[cb] = function(...)
local result, err = cb(...)
if err then
error(err)
end
return result
end
return s2h_cache[cb]
end
soft_to_hard = function(cb)
return s2h_cache[cb] or create_wrapper(cb)
end
end
local _M = {}
local mt = { __index = _M }
function _M.new(opts)
if _init then
return error("kong.cache was already created")
end
-- opts validation
opts = opts or {}
if not opts.cluster_events then
return error("opts.cluster_events is required")
end
if not opts.worker_events then
return error("opts.worker_events is required")
end
if opts.propagation_delay and type(opts.propagation_delay) ~= "number" then
return error("opts.propagation_delay must be a number")
end
if opts.ttl and type(opts.ttl) ~= "number" then
return error("opts.ttl must be a number")
end
if opts.neg_ttl and type(opts.neg_ttl) ~= "number" then
return error("opts.neg_ttl must be a number")
end
if opts.resty_lock_opts and type(opts.resty_lock_opts) ~= "table" then
return error("opts.resty_lock_opts must be a table")
end
local mlcache, err = kong_mlcache.new(SHM_CACHE, opts.worker_events, {
lru_size = LRU_SIZE,
ttl = max(opts.ttl or 3600, 0),
neg_ttl = max(opts.neg_ttl or 300, 0),
resty_lock_opts = opts.resty_lock_opts,
})
if not mlcache then
return nil, "failed to instantiate mlcache: " .. err
end
local self = {
propagation_delay = max(opts.propagation_delay or 0, 0),
cluster_events = opts.cluster_events,
mlcache = mlcache,
}
local ok, err = self.cluster_events:subscribe("invalidations", function(key)
log(DEBUG, "received invalidate event from cluster for key: '", key, "'")
self:invalidate_local(key)
end)
if not ok then
return nil, "failed to subscribe to invalidations cluster events " ..
"channel: " .. err
end
_init = true
return setmetatable(self, mt)
end
function _M:get(key, opts, cb, ...)
if type(key) ~= "string" then
return error("key must be a string")
end
--log(DEBUG, "get from key: ", key)
local v, err = self.mlcache:get(key, opts, soft_to_hard(cb), ...)
if err then
return nil, "failed to get from node cache: " .. err
end
return v
end
function _M:probe(key)
if type(key) ~= "string" then
return error("key must be a string")
end
local ttl, err, v = self.mlcache:probe(key)
if err then
return nil, "failed to probe from node cache: " .. err
end
return ttl, nil, v
end
function _M:invalidate_local(key)
if type(key) ~= "string" then
return error("key must be a string")
end
log(DEBUG, "invalidating (local): '", key, "'")
local ok, err = self.mlcache:delete(key)
if not ok then
log(ERR, "failed to delete entity from node cache: ", err)
end
end
function _M:invalidate(key)
if type(key) ~= "string" then
return error("key must be a string")
end
self:invalidate_local(key)
local nbf
if self.propagation_delay > 0 then
nbf = ngx_now() + self.propagation_delay
end
log(DEBUG, "broadcasting (cluster) invalidation for key: '", key, "' ",
"with nbf: '", nbf or "none", "'")
local ok, err = self.cluster_events:broadcast("invalidations", key, nbf)
if not ok then
log(ERR, "failed to broadcast cached entity invalidation: ", err)
end
end
function _M:purge()
log(NOTICE, "purging (local) cache")
local ok, err = self.mlcache:purge()
if not ok then
log(ERR, "failed to purge cache: ", err)
end
end
return _M
|
local kong_mlcache = require "kong.mlcache"
local type = type
local max = math.max
local ngx_log = ngx.log
local ngx_now = ngx.now
local ERR = ngx.ERR
local NOTICE = ngx.NOTICE
local DEBUG = ngx.DEBUG
local SHM_CACHE = "kong_cache"
--[[
Hypothesis
----------
Item size: 1024 bytes
Max memory limit: 500 MiBs
LRU size must be: (500 * 2^20) / 1024 = 512000
Floored: 500.000 items should be a good default
--]]
local LRU_SIZE = 5e5
local _init
local function log(lvl, ...)
return ngx_log(lvl, "[DB cache] ", ...)
end
-- Temporary fix to convert soft callback errors into hard ones.
-- FIXME: use upstream mlcache lib instead of local copy
local soft_to_hard
do
local s2h_cache = setmetatable({}, { __mode = "k" })
local function create_wrapper(key, cb)
s2h_cache[key] = function(...)
local result, err = cb(...)
if err then
error(err)
end
return result
end
return s2h_cache[key]
end
soft_to_hard = function(key, cb)
return s2h_cache[key] or create_wrapper(key, cb)
end
end
local _M = {}
local mt = { __index = _M }
function _M.new(opts)
if _init then
return error("kong.cache was already created")
end
-- opts validation
opts = opts or {}
if not opts.cluster_events then
return error("opts.cluster_events is required")
end
if not opts.worker_events then
return error("opts.worker_events is required")
end
if opts.propagation_delay and type(opts.propagation_delay) ~= "number" then
return error("opts.propagation_delay must be a number")
end
if opts.ttl and type(opts.ttl) ~= "number" then
return error("opts.ttl must be a number")
end
if opts.neg_ttl and type(opts.neg_ttl) ~= "number" then
return error("opts.neg_ttl must be a number")
end
if opts.resty_lock_opts and type(opts.resty_lock_opts) ~= "table" then
return error("opts.resty_lock_opts must be a table")
end
local mlcache, err = kong_mlcache.new(SHM_CACHE, opts.worker_events, {
lru_size = LRU_SIZE,
ttl = max(opts.ttl or 3600, 0),
neg_ttl = max(opts.neg_ttl or 300, 0),
resty_lock_opts = opts.resty_lock_opts,
})
if not mlcache then
return nil, "failed to instantiate mlcache: " .. err
end
local self = {
propagation_delay = max(opts.propagation_delay or 0, 0),
cluster_events = opts.cluster_events,
mlcache = mlcache,
}
local ok, err = self.cluster_events:subscribe("invalidations", function(key)
log(DEBUG, "received invalidate event from cluster for key: '", key, "'")
self:invalidate_local(key)
end)
if not ok then
return nil, "failed to subscribe to invalidations cluster events " ..
"channel: " .. err
end
_init = true
return setmetatable(self, mt)
end
function _M:get(key, opts, cb, ...)
if type(key) ~= "string" then
return error("key must be a string")
end
--log(DEBUG, "get from key: ", key)
local v, err = self.mlcache:get(key, opts, soft_to_hard(key, cb), ...)
if err then
return nil, "failed to get from node cache: " .. err
end
return v
end
function _M:probe(key)
if type(key) ~= "string" then
return error("key must be a string")
end
local ttl, err, v = self.mlcache:probe(key)
if err then
return nil, "failed to probe from node cache: " .. err
end
return ttl, nil, v
end
function _M:invalidate_local(key)
if type(key) ~= "string" then
return error("key must be a string")
end
log(DEBUG, "invalidating (local): '", key, "'")
local ok, err = self.mlcache:delete(key)
if not ok then
log(ERR, "failed to delete entity from node cache: ", err)
end
end
function _M:invalidate(key)
if type(key) ~= "string" then
return error("key must be a string")
end
self:invalidate_local(key)
local nbf
if self.propagation_delay > 0 then
nbf = ngx_now() + self.propagation_delay
end
log(DEBUG, "broadcasting (cluster) invalidation for key: '", key, "' ",
"with nbf: '", nbf or "none", "'")
local ok, err = self.cluster_events:broadcast("invalidations", key, nbf)
if not ok then
log(ERR, "failed to broadcast cached entity invalidation: ", err)
end
end
function _M:purge()
log(NOTICE, "purging (local) cache")
local ok, err = self.mlcache:purge()
if not ok then
log(ERR, "failed to purge cache: ", err)
end
end
return _M
|
fix(cache) do not use callback as hard-error wrapper keys
|
fix(cache) do not use callback as hard-error wrapper keys
Part of the fixes for #3277 for a regression introduced in
de6390e34c5301aa4c965d52f08e00ab81f91efa.
While the soft_to_hard error wrapper tries its best to be GC-friendly by
not keeping references on the DB cache callbacks as they are used as keys
to index their corresponding soft_to_hard_error wrappers.
Unfortunately, because the created closure holds a reference to the
callback itself, said callback cannot be garbage-collected.
This is especially troublesome for callbacks that are generated on the
fly, like so:
local cache, err = cache:get("key", opts, function()
return "cached value"
end)
The above anonymous function should be garbage-collected, but the
soft_to_hard_error still holds a reference to it.
This example could be observed prior to the parent commit, in which we
replaced the cache callback to not create a function on the fly anymore.
The drawback of this change is a larger memory footprint, the same
cache callback will result in several copies of the same
soft_to_hard_error function, if they are invoked with several caching
keys.
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong,Mashape/kong
|
5d036a1d6da663bf82f62f40072a20a3d2614310
|
tests/3drender/render.lua
|
tests/3drender/render.lua
|
require "sprite"
local maf = require "maf"
local PI = math.pi
local std = stead
local render = {
}
render.__index = render
local scene = {
}
scene.__index = scene
local object = {
}
object.__index = object
function render.object()
local o = {
shapes = {}
}
setmetatable(o, object)
return o
end
function object:circle(x, y, r, col)
table.insert(self.shapes, { t = 'circle', x = x, y = y, r = r, col = col })
return self
end
function object:render(screen, fov, x, y, z)
local pos = x
if type(x) == 'number' then
pos = maf.vec3(x, y, z)
end
local w, h = screen:size()
local xc = math.floor(w / 2)
local yc = math.floor(h / 2)
for k, o in ipairs(self.shapes) do
if o.t == 'circle' and pos.z ~= 0 then
local nx = fov * (pos.x + o.x) / pos.z
local ny = fov * (pos.y + o.y) / pos.z
local nr = (o.r) / pos.z
screen:circle(xc + nx, yc - ny, nr, std.unpack(o.col))
end
end
end
function render.vec3(x, y, z)
return maf.vec3(x, y, z)
end
function render.scene()
local o = {
objects = {}
}
setmetatable(o, scene)
o:rotate(0, 0)
o:camera(0, 0, 0)
o:setfov(PI / 4)
return o
end
function scene:setfov(fov)
self.fov = fov
end
function scene:look(angle, x, y, z)
local q = maf.rotation()
q:between(maf.vec3(0, 0, 1), x, y, z)
self.quat = q
end
function scene:rotate(hangle, vangle)
local qh = maf.rotation()
qh:angleAxis(hangle, 0, 1, 0)
local qv = maf.rotation()
qv:angleAxis(vangle, 1, 0, 0)
local qq = maf.rotation()
qv:mul(qh, qq)
self.quat = qq
return qq * maf.vec3(0, 0, 1)
end
function scene:camera(x, y, z)
local coord = x
if type(x) == 'number' then
coord = maf.vec3(x, y, z)
end
self.position = coord
end
function scene:render(screen)
local current_scene = {}
for k, o in ipairs(self.objects) do
local ncoord = (o.pos - self.position):rotate(self.quat)
table.insert(current_scene, { o = o.o, pos = ncoord })
end
table.sort(current_scene, function(a, b)
return a.pos.z > b.pos.z
end)
for k, o in ipairs(current_scene) do
if o.pos.z > 0 then
o.o:render(screen, self.fov, o.pos)
print(o.pos.x, o.pos.y, o.pos.z)
end
end
end
function scene:place(object, x, y, z)
local coord = x
if type(x) == 'number' then
coord = maf.vec3(x, y, z)
end
table.insert(self.objects, { o = object, pos = coord })
end
return render
|
require "sprite"
local maf = require "maf"
local PI = math.pi
local std = stead
local render = {
}
render.__index = render
local scene = {
}
scene.__index = scene
local object = {
}
object.__index = object
function render.object()
local o = {
shapes = {}
}
setmetatable(o, object)
return o
end
function object:circle(x, y, r, col)
table.insert(self.shapes, { t = 'circle', x = x, y = y, r = r, col = col })
return self
end
function object:render(screen, fov, x, y, z)
local pos = x
if type(x) == 'number' then
pos = maf.vec3(x, y, z)
end
local w, h = screen:size()
local xc = math.floor(w / 2)
local yc = math.floor(h / 2)
for k, o in ipairs(self.shapes) do
if o.t == 'circle' and pos.z ~= 0 then
local nx = fov * (pos.x + o.x) / pos.z
local ny = fov * (pos.y + o.y) / pos.z
local nr = (o.r) / pos.z
screen:circle(xc + nx, yc - ny, nr, std.unpack(o.col))
end
end
end
function render.vec3(x, y, z)
return maf.vec3(x, y, z)
end
function render.scene()
local o = {
objects = {}
}
setmetatable(o, scene)
o:rotate(0, 0)
o:camera(0, 0, 0)
o:setfov(PI / 4)
return o
end
function scene:setfov(fov)
self.fov = fov
end
function scene:look(angle, x, y, z)
local q = maf.rotation()
q:between(maf.vec3(0, 0, 1), x, y, z)
self.quat = q
end
function scene:rotate(hangle, vangle)
local qh = maf.rotation()
qh:angleAxis(hangle, 0, 1, 0)
local qv = maf.rotation()
qv:angleAxis(vangle, 1, 0, 0)
local qq = maf.rotation()
qv:mul(qh, qq)
self.quat = qq
local v = qq * maf.vec3(0, 0, 1)
v.y = - v.y
v.x = - v.x
return v
end
function scene:camera(x, y, z)
local coord = x
if type(x) == 'number' then
coord = maf.vec3(x, y, z)
end
self.position = coord
end
function scene:render(screen)
local current_scene = {}
for k, o in ipairs(self.objects) do
local ncoord = (o.pos - self.position):rotate(self.quat)
table.insert(current_scene, { o = o.o, pos = ncoord })
end
table.sort(current_scene, function(a, b)
return a.pos.z > b.pos.z
end)
for k, o in ipairs(current_scene) do
if o.pos.z > 0 then
o.o:render(screen, self.fov, o.pos)
print(o.pos.x, o.pos.y, o.pos.z)
end
end
end
function scene:place(object, x, y, z)
local coord = x
if type(x) == 'number' then
coord = maf.vec3(x, y, z)
end
table.insert(self.objects, { o = object, pos = coord })
end
return render
|
vector fix
|
vector fix
|
Lua
|
mit
|
gl00my/stead3
|
560b3f813abb6037c414e34dc5554cd4e719e7e0
|
src/selectionimageutils/src/Client/SelectionImageUtils.lua
|
src/selectionimageutils/src/Client/SelectionImageUtils.lua
|
--- Provides a utility method to clearing selection images with blank values.
-- @module SelectionImageUtils
-- @author Quenty
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local DialogTemplatesClient = require("DialogTemplatesClient")
local SelectionImageUtils = {}
function SelectionImageUtils.overrideWithBlank(button)
local selectionImage = DialogTemplatesClient:Clone("BlankSelectionImageObjectTemplate")
button.SelectionImageObject = selectionImage
return selectionImage
end
return SelectionImageUtils
|
--- Provides a utility method to clearing selection images with blank values.
-- @module SelectionImageUtils
-- @author Quenty
local SelectionImageUtils = {}
function SelectionImageUtils.overrideWithBlank(button)
local selectionImage = Instance.new("ImageLabel")
selectionImage.Image = ""
selectionImage.Size = UDim2.new(0, 100, 0, 100)
selectionImage.BackgroundTransparency = 1
selectionImage.BorderSizePixel = 0
selectionImage.Visible = true
selectionImage.Name = "SelectionImage"
button.SelectionImageObject = selectionImage
return selectionImage
end
return SelectionImageUtils
|
fix: Make SelectionImageUtils not use dialog templates (bad dependency)
|
fix: Make SelectionImageUtils not use dialog templates (bad dependency)
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
119526eb9cc25a481edd0f5346b92b5efe96587e
|
libs_sb/chonsole/exts/gl.lua
|
libs_sb/chonsole/exts/gl.lua
|
local engineTextures = {
-- atlases
"$units",
"$units1",
"$units2",
-- cubemaps
"$specular",
"$reflection",
"$map_reflection",
"$sky_reflection",
-- specials
"$shadow",
"$heightmap",
-- SMF-maps
"$grass",
"$detail",
"$minimap",
"$shading",
"$normals",
-- SSMF-maps
"$ssmf_normals",
"$ssmf_specular",
"$ssmf_splat_distr",
"$ssmf_splat_detail",
"$ssmf_splat_normals:0",
"$ssmf_splat_normals:1",
"$ssmf_splat_normals:2",
"$ssmf_splat_normals:3",
"$ssmf_sky_refl",
"$ssmf_emission",
"$ssmf_parallax",
"$info",
"$info_losmap",
"$info_mtlmap",
"$info_hgtmap",
"$info_blkmap",
"$extra",
"$extra_losmap",
"$extra_mtlmap",
"$extra_hgtmap",
"$extra_blkmap",
"$map_gb_nt",
"$map_gb_dt",
"$map_gb_st",
"$map_gb_et",
"$map_gb_mt",
"$map_gb_zt",
"$map_gbuffer_normtex",
"$map_gbuffer_difftex",
"$map_gbuffer_spectex",
"$map_gbuffer_emittex",
"$map_gbuffer_misctex",
"$map_gbuffer_zvaltex",
"$mdl_gb_nt",
"$mdl_gb_dt",
"$mdl_gb_st",
"$mdl_gb_et",
"$mdl_gb_mt",
"$mdl_gb_zt",
"$model_gbuffer_normtex",
"$model_gbuffer_difftex",
"$model_gbuffer_spectex",
"$model_gbuffer_emittex",
"$model_gbuffer_misctex",
"$model_gbuffer_zvaltex",
"$font" ,
"$smallfont",
"$fontsmall",
}
local GL_LUMINANCE32F_ARB = 0x8818
commands = {
{
command = "texture",
description = i18n("texture_desc", {default="Displays various OpenGL textures"}),
cheat = false,
suggestions = function(cmd, cmdParts)
local suggestions = {}
local param = cmdParts[2]
for _, engineTexture in pairs(engineTextures) do
if param == nil or param == "" or engineTexture:starts(param) then
table.insert(suggestions, {
command = "/texture " .. engineTexture,
text = engineTexture,
description = value
})
end
end
return suggestions
end,
exec = function(command, cmdParts)
if #cmdParts < 3 then
return
end
delayGL = function()
local succ, err = pcall(function()
Spring.Echo(command)
local texture = cmdParts[2]
local outputFile = cmdParts[3]
local texInfo = gl.TextureInfo(texture)
if texInfo == nil or texInfo.xsize == -1 then
return
end
local format
if texture == "$heightmap" then
if Platform.osFamily ~= "Windows" or cmdParts[4] == 'luminance' then
format = GL_LUMINANCE32F_ARB
end
end
local fboTex = gl.CreateTexture(texInfo.xsize, texInfo.ysize, {
format = format,
border = false,
min_filter = GL.LINEAR,
mag_filter = GL.LINEAR,
wrap_s = GL.CLAMP_TO_EDGE,
wrap_t = GL.CLAMP_TO_EDGE,
fbo = true,
})
gl.Texture(texture)
gl.RenderToTexture(fboTex,
function()
gl.TexRect(-1,-1, 1, 1)
end)
gl.Texture(false)
gl.RenderToTexture(fboTex, gl.SaveImage, 0, 0, texInfo.xsize, texInfo.ysize, outputFile)
gl.DeleteTexture(fboTex)
Spring.Log("Chonsole", LOG.NOTICE, 'Exported texture: ' ..
tostring(cmdParts[2]).. ' to file: ' .. tostring(cmdParts[3]))
end)
if not succ then
Spring.Log("Chonsole", LOG.ERROR, 'Failed to export texture: ' ..
tostring(cmdParts[2]).. ' to file: ' .. tostring(cmdParts[3]))
Spring.Log("Chonsole", LOG.ERROR, err)
end
end
end,
},
}
|
local engineTextures = {
-- atlases
"$units",
"$units1",
"$units2",
-- cubemaps
"$specular",
"$reflection",
"$map_reflection",
"$sky_reflection",
-- specials
"$shadow",
"$heightmap",
-- SMF-maps
"$grass",
"$detail",
"$minimap",
"$shading",
"$normals",
-- SSMF-maps
"$ssmf_normals",
"$ssmf_specular",
"$ssmf_splat_distr",
"$ssmf_splat_detail",
"$ssmf_splat_normals:0",
"$ssmf_splat_normals:1",
"$ssmf_splat_normals:2",
"$ssmf_splat_normals:3",
"$ssmf_sky_refl",
"$ssmf_emission",
"$ssmf_parallax",
"$info",
"$info_losmap",
"$info_mtlmap",
"$info_hgtmap",
"$info_blkmap",
"$extra",
"$extra_losmap",
"$extra_mtlmap",
"$extra_hgtmap",
"$extra_blkmap",
"$map_gb_nt",
"$map_gb_dt",
"$map_gb_st",
"$map_gb_et",
"$map_gb_mt",
"$map_gb_zt",
"$map_gbuffer_normtex",
"$map_gbuffer_difftex",
"$map_gbuffer_spectex",
"$map_gbuffer_emittex",
"$map_gbuffer_misctex",
"$map_gbuffer_zvaltex",
"$mdl_gb_nt",
"$mdl_gb_dt",
"$mdl_gb_st",
"$mdl_gb_et",
"$mdl_gb_mt",
"$mdl_gb_zt",
"$model_gbuffer_normtex",
"$model_gbuffer_difftex",
"$model_gbuffer_spectex",
"$model_gbuffer_emittex",
"$model_gbuffer_misctex",
"$model_gbuffer_zvaltex",
"$font" ,
"$smallfont",
"$fontsmall",
}
local GL_LUMINANCE32F_ARB = 0x8818
commands = {
{
command = "texture",
description = i18n("texture_desc", {default="Displays various OpenGL textures"}),
cheat = false,
suggestions = function(cmd, cmdParts)
local suggestions = {}
local param = cmdParts[2]
for _, engineTexture in pairs(engineTextures) do
if param == nil or param == "" or engineTexture:starts(param) then
table.insert(suggestions, {
command = "/texture " .. engineTexture,
text = engineTexture,
description = value
})
end
end
return suggestions
end,
exec = function(command, cmdParts)
if #cmdParts < 3 then
return
end
delayGL = function()
local succ, err = pcall(function()
Spring.Echo(command)
local texture = cmdParts[2]
local outputFile = cmdParts[3]
local texInfo = gl.TextureInfo(texture)
if texInfo == nil or texInfo.xsize == -1 then
return
end
local format
local useGrayscale16bit = false
if texture == "$heightmap" then
format = GL_LUMINANCE32F_ARB
if Platform.osFamily ~= "Windows" or cmdParts[4] == '16bit' then
useGrayscale16bit = true
end
end
local fboTex = gl.CreateTexture(texInfo.xsize, texInfo.ysize, {
format = format,
border = false,
min_filter = GL.LINEAR,
mag_filter = GL.LINEAR,
wrap_s = GL.CLAMP_TO_EDGE,
wrap_t = GL.CLAMP_TO_EDGE,
fbo = true,
})
gl.Texture(texture)
gl.RenderToTexture(fboTex,
function()
gl.TexRect(-1,-1, 1, 1)
end)
gl.Texture(false)
gl.RenderToTexture(fboTex, gl.SaveImage, 0, 0, texInfo.xsize, texInfo.ysize, outputFile, {grayscale16bit = useGrayscale16bit})
gl.DeleteTexture(fboTex)
Spring.Log("Chonsole", LOG.NOTICE, 'Exported texture: ' ..
tostring(cmdParts[2]).. ' to file: ' .. tostring(cmdParts[3]))
end)
if not succ then
Spring.Log("Chonsole", LOG.ERROR, 'Failed to export texture: ' ..
tostring(cmdParts[2]).. ' to file: ' .. tostring(cmdParts[3]))
Spring.Log("Chonsole", LOG.ERROR, err)
end
end
end,
},
}
|
fix heightmap output
|
fix heightmap output
|
Lua
|
mit
|
Spring-SpringBoard/SpringBoard-Core,Spring-SpringBoard/SpringBoard-Core
|
726f9762186506e68778c536d7370d693cb5e7bf
|
commands/init.lua
|
commands/init.lua
|
local core = require("core")()
local prompt = require("prompt")(require("pretty-print"))
local fs = require("coro-fs")
local env = require("env")
local log = require("log").log
local pathJoin = require("luvi").path.join
local cwd = require('uv').cwd()
local sprintf = require("string").format
local config = core.config
local function getOutput()
local output = prompt("Output to package.lua (1), or a init.lua (2)?")
-- response was blank, run again
if not output then
return getOutput()
end
-- fail on any other options
if not output:match('[1-2]') then
log("Error", "You must select a valid option. [1 or 2]")
return getOutput()
else
if output == "1" then
output = "package.lua"
log("Creating", "package.lua")
elseif output == "2" then
output = "init.lua"
log("Creating", "init.lua")
end
end
return output
end
local output = getOutput()
local home = env.get("HOME") or env.get("HOMEPATH") or ""
local ini
local function getConfig(name)
ini = ini or fs.readFile(pathJoin(home, ".gitconfig"))
if not ini then return end
local section
for line in ini:gmatch("[^\n]+") do
local s = line:match("^%[([^%]]+)%]$")
if s then
section = s
else
local key, value = line:match("^%s*(%w+)%s*=%s*(.+)$")
if key and section .. "." .. key == name then
if tonumber(value) then return tonumber(value) end
if value == "true" then return true end
if value == "false" then return false end
return value
end
end
end
end
-- trim and wrap words in quotes
function makeTags(csv)
local tags = "{ "
for word in csv:gmatch('([^,]+)') do
tags = tags .. "\"" .. word:gsub("^%s*(.-)%s*$", "%1") .. "\", "
end
-- trim trailing comma and space
tags = tags:sub(0, (#tags - 2))
return tags .. " }"
end
local projectName = prompt("Project Name", config["username"] .. "/project-name")
local projectVersion = prompt("Version", "0.0.1")
local projectDescription = prompt("Description", "A simple description of my little package.")
local projectTags = makeTags(prompt("Tags (Comma Separated)", "lua, lit, luvit"))
local authorName = prompt("Author Name", getConfig("user.name"))
local authorEmail = prompt("Author Email", getConfig("user.email"))
local projectLicense = prompt("License", "MIT")
local projectHomepage = prompt("Homepage", "https://github.com/" .. projectName)
local data = ""
if output == "init.lua" then
local init = [[
exports.name = %q
exports.version = %q
exports.dependencies = {}
exports.description = %q
exports.tags = %s
exports.license = %q
exports.author = { name = %q, email = %q }
exports.homepage = %q
]]
data = sprintf(init, projectName, projectVersion, projectDescription, projectTags, authorName, authorEmail, projectLicense, projectHomepage)
elseif output == "package.lua" then
local package = [[
return {
name = %q,
version = %q,
description = %q,
tags = %s,
license = %q,
author = { name = %q, email = %q },
homepage = %q,
dependencies = {},
files = {
"**.lua",
"!test*"
}
}
]]
data = sprintf(package, projectName, projectVersion, projectDescription, projectTags, authorName, authorEmail, projectLicense, projectHomepage)
end
-- give us a preview
print("\n" .. data .. "\n")
local message = "Enter to continue"
local finish = prompt("Is this ok?", message)
if finish == message then
local data, err = fs.writeFile(cwd .. "/" .. output, data)
if err == nil then
log("Complete", "Created a new " .. output .. " file.")
else
log("Error", "Could not write file.")
end
else
log("Aborted", "No files will be written")
end
|
local core = require("core")()
local prompt = require("prompt")(require("pretty-print"))
local fs = require("coro-fs")
local env = require("env")
local log = require("log").log
local pathJoin = require("luvi").path.join
local cwd = require('uv').cwd()
local sprintf = require("string").format
local config = core.config
local function getOutput()
local output = prompt("Output to package.lua (1), or a init.lua (2)?")
-- response was blank, run again
if not output then
return getOutput()
end
-- fail on any other options
if not output:match('[1-2]') then
log("Error", "You must select a valid option. [1 or 2]")
return getOutput()
else
if output == "1" then
output = "package.lua"
log("Creating", "package.lua")
elseif output == "2" then
output = "init.lua"
log("Creating", "init.lua")
end
end
return output
end
local output = getOutput()
local home = env.get("HOME") or env.get("HOMEPATH") or ""
local ini
local function getConfig(name)
ini = ini or fs.readFile(pathJoin(home, ".gitconfig"))
if not ini then return end
local section
for line in ini:gmatch("[^\n]+") do
local s = line:match("^%[([^%]]+)%]$")
if s then
section = s
else
local key, value = line:match("^%s*(%w+)%s*=%s*(.+)$")
if key and section .. "." .. key == name then
if tonumber(value) then return tonumber(value) end
if value == "true" then return true end
if value == "false" then return false end
return value
end
end
end
end
-- trim and wrap words in quotes
function makeTags(csv)
local tags = "{ "
for word in csv:gmatch('([^,]+)') do
tags = tags .. "\"" .. word:gsub("^%s*(.-)%s*$", "%1") .. "\", "
end
-- trim trailing comma and space
tags = tags:sub(0, (#tags - 2))
return tags .. " }"
end
local projectName = prompt("Project Name", config["username"] .. "/project-name")
local projectVersion = prompt("Version", "0.0.1")
local projectDescription = prompt("Description", "A simple description of my little package.")
local projectTags = makeTags(prompt("Tags (Comma Separated)", "lua, lit, luvit"))
local authorName = prompt("Author Name", getConfig("user.name"))
local authorEmail = prompt("Author Email", getConfig("user.email"))
local projectLicense = prompt("License", "MIT")
local projectHomepage = prompt("Homepage", "https://github.com/" .. projectName)
local data = ""
if output == "init.lua" then
local init = [[
exports.name = %q
exports.version = %q
exports.dependencies = {}
exports.description = %q
exports.tags = %s
exports.license = %q
exports.author = { name = %q, email = %q }
exports.homepage = %q
]]
data = sprintf(init, projectName, projectVersion, projectDescription, projectTags, projectLicense, authorName, authorEmail, projectHomepage)
elseif output == "package.lua" then
local package = [[
return {
name = %q,
version = %q,
description = %q,
tags = %s,
license = %q,
author = { name = %q, email = %q },
homepage = %q,
dependencies = {},
files = {
"**.lua",
"!test*"
}
}
]]
data = sprintf(package, projectName, projectVersion, projectDescription, projectTags, projectLicense, authorName, authorEmail, projectHomepage)
end
-- give us a preview
print("\n" .. data .. "\n")
local message = "Enter to continue"
local finish = prompt("Is this ok?", message)
if finish == message then
local data, err = fs.writeFile(cwd .. "/" .. output, data)
if err == nil then
log("Complete", "Created a new " .. output .. " file.")
else
log("Error", "Could not write file.")
end
else
log("Aborted", "No files will be written")
end
|
init: Fix ordering of parameters in package metadata
|
init: Fix ordering of parameters in package metadata
- Fixes #133
|
Lua
|
apache-2.0
|
james2doyle/lit,zhaozg/lit,squeek502/lit,luvit/lit
|
42916ddf5670aa2d9e6f71c17a5241bd9846c25a
|
MMOCoreORB/bin/scripts/managers/player_creation_manager.lua
|
MMOCoreORB/bin/scripts/managers/player_creation_manager.lua
|
--Should all created players start with God Mode? 1 = yes, 0 = no
freeGodMode = 0;
--How many cash credits new characters start with after creating a character (changed during test phase, normal value is 100)
startingCash = 100
--startingCash = 100000
--How many bank credits new characters start with after creating a character (changed during test phase, normal value is 1000)
startingBank = 1000
--startingBank = 100000
--How many skill points a new characters start with
skillPoints = 250
professions = {
"combat_brawler",
"combat_marksman",
"crafting_artisan",
"jedi",
"outdoors_scout",
"science_medic",
"social_entertainer"
}
cdefPistol = "object/weapon/ranged/pistol/pistol_cdef.iff"
cdefRifle = "object/weapon/ranged/rifle/rifle_cdef.iff"
cdefCarbine = "object/weapon/ranged/carbine/carbine_cdef.iff"
survivalKnife = "object/weapon/melee/knife/knife_survival.iff"
generic_tool = "object/tangible/crafting/station/generic_tool.iff"
mineral_tool = "object/tangible/survey_tool/survey_tool_mineral.iff"
chemical_tool = "object/tangible/survey_tool/survey_tool_liquid.iff"
slitherhorn = "object/tangible/instrument/slitherhorn.iff"
maroj_melon = "object/tangible/food/foraged/foraged_fruit_s1.iff"
professionSpecificItems = {
combat_brawler = { survivalKnife },
combat_marksman = { cdefPistol, cdefCarbine, cdefRifle },
crafting_artisan = { cdefPistol, survivalKnife, generic_tool, mineral_tool, chemical_tool },
jedi = { },
outdoors_scout = { cdefPistol, generic_tool},
science_medic = { cdefPistol, generic_tool, survivalKnife },
social_entertainer = { cdefPistol, survivalKnife, slitherhorn }
}
commonStartingItems = { maroj_melon }
|
--Should all created players start with God Mode? 1 = yes, 0 = no
freeGodMode = 0;
--How many cash credits new characters start with after creating a character (changed during test phase, normal value is 100)
startingCash = 100
--startingCash = 100000
--How many bank credits new characters start with after creating a character (changed during test phase, normal value is 1000)
startingBank = 1000
--startingBank = 100000
--How many skill points a new characters start with
skillPoints = 250
professions = {
"combat_brawler",
"combat_marksman",
"crafting_artisan",
"jedi",
"outdoors_scout",
"science_medic",
"social_entertainer"
}
marksmanPistol = "object/weapon/ranged/pistol/pistol_cdef.iff"
marksmanRifle = "object/weapon/ranged/rifle/rifle_cdef.iff"
marksmanCarbine = "object/weapon/ranged/carbine/carbine_cdef.iff"
brawlerOneHander = "object/weapon/melee/knife/knife_stone.iff"
brawlerTwoHander = "object/weapon/melee/axe/axe_heavy_duty.iff"
brawlerPolearm = "object/weapon/melee/polearm/lance_staff_wood_s1.iff"
survivalKnife = "object/weapon/melee/knife/knife_survival.iff"
genericTool = "object/tangible/crafting/station/genericTool.iff"
foodTool = "object/tangible/crafting/station/foodTool.iff"
mineralTool = "object/tangible/surveyTool/surveyTool_mineral.iff"
chemicalTool = "object/tangible/surveyTool/surveyTool_liquid.iff"
slitherhorn = "object/tangible/instrument/slitherhorn.iff"
marojMelon = "object/tangible/food/foraged/foraged_fruit_s1.iff"
professionSpecificItems = {
combat_brawler = { brawlerOneHander, brawlerTwoHander, brawlerPolearm },
combat_marksman = { marksmanPistol, marksmanCarbine, marksmanRifle },
crafting_artisan = { genericTool, mineralTool, chemicalTool },
jedi = { },
outdoors_scout = { genericTool },
science_medic = { foodTool },
social_entertainer = { slitherhorn }
}
commonStartingItems = { marojMelon, survivalKnife }
|
(unstable) [fixed] novice profession starting items
|
(unstable) [fixed] novice profession starting items
git-svn-id: e4cf3396f21da4a5d638eecf7e3b4dd52b27f938@5725 c3d1530f-68f5-4bd0-87dc-8ef779617e40
|
Lua
|
agpl-3.0
|
Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo
|
e251af033a26afc90b73f05ebeafd9481274e1a4
|
src/logfactory/LogCreator.lua
|
src/logfactory/LogCreator.lua
|
local LogCreator = {};
-- ------------------------------------------------
-- Constants
-- ------------------------------------------------
local GIT_COMMAND = 'git log --reverse --numstat --pretty=format:"info: %an|%ae|%ct" --name-status --no-merges';
local LOG_FOLDER = 'logs/';
local LOG_FILE = '/log.txt';
local INFO_FILE = '/info.lua';
-- ------------------------------------------------
-- Public Functions
-- ------------------------------------------------
---
-- Creates a git log if git is available and no log has been
-- created in the target folder yet.
-- @param projectname
-- @param path
--
function LogCreator.createGitLog(projectname, path, force)
if not force and love.filesystem.isFile(LOG_FOLDER .. projectname .. LOG_FILE) then
io.write('Git log for ' .. projectname .. ' already exists!\r\n');
else
io.write('Writing log for ' .. projectname .. '.\r\n');
love.filesystem.createDirectory(LOG_FOLDER .. projectname);
local cmd = 'cd "' .. path .. '" && ' .. GIT_COMMAND;
local handle = io.popen(cmd);
love.filesystem.write(LOG_FOLDER .. projectname .. LOG_FILE, handle:read('*all'));
handle:close();
io.write('Done!\r\n');
end
end
function LogCreator.createInfoFile(projectname, path, force)
if not force and love.filesystem.isFile(LOG_FOLDER .. projectname .. INFO_FILE) then
io.write('Info file for ' .. projectname .. ' already exists!\r\n');
elseif love.system.getOS() ~= 'Windows' then
local fileContent = '';
fileContent = fileContent .. 'return {\r\n';
-- Project name.
fileContent = fileContent .. ' name = "' .. projectname .. '",\r\n';
-- First commit.
local handle = io.popen('cd "' .. path .. '" && git log --pretty=format:%ct|tail -1');
fileContent = fileContent .. ' firstCommit = ' .. handle:read('*a'):gsub('[%s]+', '') .. ',\r\n';
handle:close();
-- Latest commit.
local handle = io.popen('cd "' .. path .. '" && git log --pretty=format:%ct|head -1');
fileContent = fileContent .. ' latestCommit = ' .. handle:read('*a'):gsub('[%s]+', '') .. ',\r\n';
handle:close();
-- Number of commits.
local handle = io.popen('cd "' .. path .. '" && git rev-list HEAD --count');
fileContent = fileContent .. ' totalCommits = ' .. handle:read('*a'):gsub('[%s]+', '') .. '\r\n';
handle:close();
fileContent = fileContent .. '};\r\n';
love.filesystem.write(LOG_FOLDER .. projectname .. INFO_FILE, fileContent);
end
end
-- ------------------------------------------------
-- Getters
-- ------------------------------------------------
---
-- Checks if git is available on the system.
--
function LogCreator.isGitAvailable()
return os.execute('git version') == 0;
end
return LogCreator;
|
local LogCreator = {};
-- ------------------------------------------------
-- Constants
-- ------------------------------------------------
local GIT_COMMAND = 'git -C "'
local LOG_COMMAND = '" log --reverse --numstat --pretty=format:"info: %an|%ae|%ct" --name-status --no-merges';
local LOG_FOLDER = 'logs/';
local LOG_FILE = '/log.txt';
local INFO_FILE = '/info.lua';
-- ------------------------------------------------
-- Public Functions
-- ------------------------------------------------
---
-- Creates a git log if git is available and no log has been
-- created in the target folder yet.
-- @param projectname
-- @param path
--
function LogCreator.createGitLog(projectname, path, force)
if not force and love.filesystem.isFile(LOG_FOLDER .. projectname .. LOG_FILE) then
io.write('Git log for ' .. projectname .. ' already exists!\r\n');
else
io.write('Writing log for ' .. projectname .. '.\r\n');
love.filesystem.createDirectory(LOG_FOLDER .. projectname);
local cmd = GIT_COMMAND .. path .. LOG_COMMAND;
local handle = io.popen(cmd);
love.filesystem.write(LOG_FOLDER .. projectname .. LOG_FILE, handle:read('*all'));
handle:close();
io.write('Done!\r\n');
end
end
function LogCreator.createInfoFile(projectname, path, force)
if not force and love.filesystem.isFile(LOG_FOLDER .. projectname .. INFO_FILE) then
io.write('Info file for ' .. projectname .. ' already exists!\r\n');
elseif love.system.getOS() ~= 'Windows' then
local fileContent = '';
fileContent = fileContent .. 'return {\r\n';
-- Project name.
fileContent = fileContent .. ' name = "' .. projectname .. '",\r\n';
-- First commit.
local handle = io.popen('cd "' .. path .. '" && git log --pretty=format:%ct|tail -1');
fileContent = fileContent .. ' firstCommit = ' .. handle:read('*a'):gsub('[%s]+', '') .. ',\r\n';
handle:close();
-- Latest commit.
local handle = io.popen('cd "' .. path .. '" && git log --pretty=format:%ct|head -1');
fileContent = fileContent .. ' latestCommit = ' .. handle:read('*a'):gsub('[%s]+', '') .. ',\r\n';
handle:close();
-- Number of commits.
local handle = io.popen('cd "' .. path .. '" && git rev-list HEAD --count');
fileContent = fileContent .. ' totalCommits = ' .. handle:read('*a'):gsub('[%s]+', '') .. '\r\n';
handle:close();
fileContent = fileContent .. '};\r\n';
love.filesystem.write(LOG_FOLDER .. projectname .. INFO_FILE, fileContent);
end
end
-- ------------------------------------------------
-- Getters
-- ------------------------------------------------
---
-- Checks if git is available on the system.
--
function LogCreator.isGitAvailable()
return os.execute('git version') == 0;
end
return LogCreator;
|
Fix #31 - Directly pass the repository's path to the git command
|
Fix #31 - Directly pass the repository's path to the git command
|
Lua
|
mit
|
rm-code/logivi
|
6eef75d6cae94cc0b224d73a3c07038856f501ab
|
core/src/ffluci/sgi/webuci.lua
|
core/src/ffluci/sgi/webuci.lua
|
--[[
FFLuCI - SGI-Module for Haserl
Description:
Server Gateway Interface for Haserl
FileId:
$Id$
License:
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
module("ffluci.sgi.webuci", package.seeall)
-- HTTP interface
-- Returns a table of all COOKIE, GET and POST Parameters
function ffluci.http.formvalues()
return webuci.vars
end
-- Gets form value from key
function ffluci.http.formvalue(key, default)
return ffluci.http.formvalues()[key] or default
end
-- Gets a table of values with a certain prefix
function ffluci.http.formvaluetable(prefix)
local vals = {}
prefix = prefix and prefix .. "." or "."
for k, v in pairs(ffluci.http.formvalues()) do
if k:find(prefix, 1, true) == 1 then
vals[k:sub(#prefix + 1)] = v
end
end
return vals
end
-- Returns the path info
function ffluci.http.get_path_info()
return webuci.PATH_INFO
end
-- Returns the User's IP
function ffluci.http.get_remote_addr()
return webuci.REMOTE_ADDR
end
-- Returns the request URI
function ffluci.http.get_request_uri()
return webuci.REQUEST_URI
end
-- Returns the script name
function ffluci.http.get_script_name()
return webuci.SCRIPT_NAME
end
-- Asks the browser to redirect to "url"
function ffluci.http.redirect(url, qs)
if qs then
url = url .. "?" .. qs
end
ffluci.http.set_status(302, "Found")
print("Location: " .. url .. "\n")
end
-- Set Content-Type
function ffluci.http.set_content_type(type)
print("Content-Type: "..type.."\n")
end
-- Sets HTTP-Status-Header
function ffluci.http.set_status(code, message)
print(webuci.REQUEST_METHOD .. " " .. tostring(code) .. " " .. message)
end
|
--[[
FFLuCI - SGI-Module for Haserl
Description:
Server Gateway Interface for Haserl
FileId:
$Id$
License:
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
module("ffluci.sgi.webuci", package.seeall)
local status_set = false
-- HTTP interface
-- Returns a table of all COOKIE, GET and POST Parameters
function ffluci.http.formvalues()
return webuci.vars
end
-- Gets form value from key
function ffluci.http.formvalue(key, default)
return ffluci.http.formvalues()[key] or default
end
-- Gets a table of values with a certain prefix
function ffluci.http.formvaluetable(prefix)
local vals = {}
prefix = prefix and prefix .. "." or "."
for k, v in pairs(ffluci.http.formvalues()) do
if k:find(prefix, 1, true) == 1 then
vals[k:sub(#prefix + 1)] = v
end
end
return vals
end
-- Returns the path info
function ffluci.http.get_path_info()
return webuci.PATH_INFO
end
-- Returns the User's IP
function ffluci.http.get_remote_addr()
return webuci.REMOTE_ADDR
end
-- Returns the request URI
function ffluci.http.get_request_uri()
return webuci.REQUEST_URI
end
-- Returns the script name
function ffluci.http.get_script_name()
return webuci.SCRIPT_NAME
end
-- Asks the browser to redirect to "url"
function ffluci.http.redirect(url, qs)
if qs then
url = url .. "?" .. qs
end
ffluci.http.set_status(302, "Found")
print("Location: " .. url .. "\n")
end
-- Set Content-Type
function ffluci.http.set_content_type(type)
if not status_set then
ffluci.http.set_status(200, "OK")
end
print("Content-Type: "..type.."\n")
end
-- Sets HTTP-Status-Header
function ffluci.http.set_status(code, message)
print(webuci.SERVER_PROTOCOL .. " " .. tostring(code) .. " " .. message)
status_set = true
end
|
* Fixed ffluci.sgi.webuci
|
* Fixed ffluci.sgi.webuci
|
Lua
|
apache-2.0
|
deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci
|
9c88f0993aa4612c5b2c81f1abeb16b8aa4d18ad
|
strictness.lua
|
strictness.lua
|
-- ================================================================
-- "strictness" tracks declaration and assignment of globals in Lua
-- Copyright (c) 2013 Roland Y., MIT License
-- v0.1.0 - compatible Lua 5.1, 5.2
-- ================================================================
local setmetatable = setmetatable
local getmetatable = getmetatable
local type = type
local rawget = rawget
local rawset = rawset
local unpack = unpack
local error = error
local getfenv = getfenv
-- ===================
-- Private helpers
-- ===================
-- Lua reserved keywords
local luaKeyword = {
['and'] = true, ['break'] = true, ['do'] = true,
['else'] = true, ['elseif'] = true, ['end'] = true ,
['false'] = true, ['for'] = true, ['function'] = true,
['if'] = true, ['in'] = true, ['local'] = true ,
['nil'] = true, ['not'] = true , ['or'] = true,
['repeat'] = true, ['return'] = true, ['then'] = true ,
['true'] = true , ['until'] = true , ['while'] = true,
}
-- Register for declared globals, defined as a table
-- with weak values.
local declared_globals = setmetatable({},{__mode = 'v'})
-- The global env _G metatable
local _G_mt
-- A custom error function
local function err(msg, level) return error(msg, level or 3) end
-- Custom assert with error level depth
local function assert(cond, msg, level)
if not cond then
return err(msg, level or 4)
end
end
-- Custom argument type assertion helper
local function assert_type(var, expected_type, argn, level)
local var_type = type(var)
assert(var_type == expected_type,
('Bad argument #%d to global (%s expected, got %s)')
:format(argn or 1, expected_type, var_type), level)
end
-- Checks in the register if the given global was declared
local function is_declared(varname)
return declared_globals[varname]
end
-- Checks if the passed-in string can be a valid Lua identifier
local function is_valid_identifier(iden)
return iden:match('^[%a_]+[%w_]*$') and not luaKeyword[iden]
end
-- ==========================
-- Module functions
-- ==========================
-- Allows the declaration of passed in varnames
local function declare_global(...)
local vars = {...}
assert(#vars > 0,
'bad argument #1 to global (expected strings, got nil)')
for i,varname in ipairs({...}) do
assert_type(varname, 'string',i, 5)
assert(is_valid_identifier(varname),
('bad argument #%d to global. "%s" is not a valid Lua identifier')
:format(i, varname))
declared_globals[varname] = true
end
end
-- Allows the given function to write globals
local function declare_global_func(f)
assert_type(f, 'function', nil, 5)
return function(...)
local old_index, old_newindex = _G_mt.__index, _G_mt.__newindex
_G_mt.__index, _G_mt.__newindex = nil, nil
local results = {f(...)}
_G_mt.__index, _G_mt.__newindex = old_index, old_newindex
return unpack(results)
end
end
-- ==========================
-- Locking the global env _G
-- ==========================
do
-- Catches the current env
local ENV = _VERSION:match('5.2') and _G or getfenv()
-- Preserves a possible existing metatable for the current env
_G_mt = getmetatable(ENV)
if not _G_mt then
_G_mt = {}
setmetatable(ENV,_G_mt)
end
-- Locks access to undeclared globals
_G_mt.__index = function(env, varname)
if not is_declared(varname) then
err(('Attempt to read undeclared global variable "%s"')
:format(varname))
end
return rawget(env, varname)
end
-- Locks assignment of undeclared globals
_G_mt.__newindex = function(env, varname, value)
if not is_declared(varname) then
err(('Attempt to assign undeclared global variable "%s"')
:format(varname))
end
rawset(env, varname, value)
end
rawset(ENV, 'global', declare_global)
rawset(ENV, 'globalize', declare_global_func)
end
|
-- ================================================================
-- "strictness" tracks declaration and assignment of globals in Lua
-- Copyright (c) 2013 Roland Y., MIT License
-- v0.1.0 - compatible Lua 5.1, 5.2
-- ================================================================
local setmetatable = setmetatable
local getmetatable = getmetatable
local type = type
local rawget = rawget
local rawset = rawset
local unpack = unpack
local error = error
local getfenv = getfenv
-- ===================
-- Private helpers
-- ===================
-- Detecting Lua52
local _LUA52 = _VERSION:match('5.2')
-- Lua reserved keywords
local luaKeyword = {
['and'] = true, ['break'] = true, ['do'] = true,
['else'] = true, ['elseif'] = true, ['end'] = true ,
['false'] = true, ['for'] = true, ['function'] = true,
['if'] = true, ['in'] = true, ['local'] = true ,
['nil'] = true, ['not'] = true , ['or'] = true,
['repeat'] = true, ['return'] = true, ['then'] = true ,
['true'] = true , ['until'] = true , ['while'] = true,
}
if _LUA52 then
luaKeyword['goto'] = true
end
-- Register for declared globals, defined as a table
-- with weak values.
local declared_globals = setmetatable({},{__mode = 'v'})
-- The global env _G metatable
local _G_mt
-- A custom error function
local function err(msg, level) return error(msg, level or 3) end
-- Custom assert with error level depth
local function assert(cond, msg, level)
if not cond then
return err(msg, level or 4)
end
end
-- Custom argument type assertion helper
local function assert_type(var, expected_type, argn, level)
local var_type = type(var)
assert(var_type == expected_type,
('Bad argument #%d to global (%s expected, got %s)')
:format(argn or 1, expected_type, var_type), level)
end
-- Checks in the register if the given global was declared
local function is_declared(varname)
return declared_globals[varname]
end
-- Checks if the passed-in string can be a valid Lua identifier
local function is_valid_identifier(iden)
return iden:match('^[%a_]+[%w_]*$') and not luaKeyword[iden]
end
-- ==========================
-- Module functions
-- ==========================
-- Allows the declaration of passed in varnames
local function declare_global(...)
local vars = {...}
assert(#vars > 0,
'bad argument #1 to global (expected strings, got nil)')
for i,varname in ipairs({...}) do
assert_type(varname, 'string',i, 5)
assert(is_valid_identifier(varname),
('bad argument #%d to global. "%s" is not a valid Lua identifier')
:format(i, varname))
declared_globals[varname] = true
end
end
-- Allows the given function to write globals
local function declare_global_func(f)
assert_type(f, 'function', nil, 5)
return function(...)
local old_index, old_newindex = _G_mt.__index, _G_mt.__newindex
_G_mt.__index, _G_mt.__newindex = nil, nil
local results = {f(...)}
_G_mt.__index, _G_mt.__newindex = old_index, old_newindex
return unpack(results)
end
end
-- ==========================
-- Locking the global env _G
-- ==========================
do
-- Catches the current env
local ENV = _LUA52 and _G or getfenv()
-- Preserves a possible existing metatable for the current env
_G_mt = getmetatable(ENV)
if not _G_mt then
_G_mt = {}
setmetatable(ENV,_G_mt)
end
-- Locks access to undeclared globals
_G_mt.__index = function(env, varname)
if not is_declared(varname) then
err(('Attempt to read undeclared global variable "%s"')
:format(varname))
end
return rawget(env, varname)
end
-- Locks assignment of undeclared globals
_G_mt.__newindex = function(env, varname, value)
if not is_declared(varname) then
err(('Attempt to assign undeclared global variable "%s"')
:format(varname))
end
rawset(env, varname, value)
end
rawset(ENV, 'global', declare_global)
rawset(ENV, 'globalize', declare_global_func)
end
|
goto is reserved with Lua5.2, fixes #2, thanks to @lua4web
|
goto is reserved with Lua5.2, fixes #2, thanks to @lua4web
|
Lua
|
mit
|
Yonaba/strictness
|
632d2cc42919725fb5abe8f23baef72a3d29f0ec
|
monster/base/spells/base.lua
|
monster/base/spells/base.lua
|
--[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
local common = require("base.common")
local character = require("base.character")
local chr_reg = require("lte.chr_reg")
local M = {}
function M.dealMagicDamage(target, damange)
if damange < 1 then return end
-- Check for damage + 1 to avoid the case that a regular hit lowers the hitpoints down to 1 and directly sends a
-- character to the brink of death.
if character.IsPlayer(target) and character.WouldDie(target, damange + 1) then
if character.AtBrinkOfDeath(target) then
if target:isAdmin() then
chr_reg.stallRegeneration(target, 0)
end
character.Kill(target)
else
-- Character would die.
character.ToBrinkOfDeath(target)
common.TalkNLS(target, Character.say, "#me geht zu Boden.", "#me falls to the ground.")
if not target:isAdmin() then --Admins don't want to get paralysed!
common.ParalyseCharacter(target, 2, false, true)
end
local timeFactor = 1 -- See lte.chr_reg
chr_reg.stallRegeneration(target, 60 / timeFactor)
end
else
target:increaseAttrib("hitpoints", -damange)
end
end
function M.isValidTarget(char)
local noAttackQuestProgress = char:getQuestProgress(36)
if noAttackQuestProgress ~= 0 then
return false
end
local hitPoints = char:increaseAttrib("hitpoints", 0)
return hitPoints > 0
end
function M.getSpellResistence(char)
local willpower = char:increaseAttrib("willpower", 0);
local minResistence = willpower;
local maxResistence = willpower * 2;
return common.Limit(Random.uniform(minResistence, maxResistence) / 80.0, 0, 1);
end
-- Check if the line of sight is free from large objects that obstruct the view
function M.isLineOfSightFree(startPos, targetPos)
local blockList = world:LoS(startPos, targetPos)
for _, obstruction in pairs(blockList) do
if obstruction.TYPE == "ITEM" then
return false
end
end
return true
end
return M
|
--[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
local common = require("base.common")
local character = require("base.character")
local chr_reg = require("lte.chr_reg")
local M = {}
function M.dealMagicDamage(target, damange)
if damange < 1 then return end
-- Check for damage + 1 to avoid the case that a regular hit lowers the hitpoints down to 1 and directly sends a
-- character to the brink of death.
if character.IsPlayer(target) and character.WouldDie(target, damange + 1) then
if character.AtBrinkOfDeath(target) then
if target:isAdmin() then
chr_reg.stallRegeneration(target, 0)
end
character.Kill(target)
else
-- Character would die.
character.ToBrinkOfDeath(target)
common.TalkNLS(target, Character.say, "#me geht zu Boden.", "#me falls to the ground.")
if not target:isAdmin() then --Admins don't want to get paralysed!
common.ParalyseCharacter(target, 2, false, true)
end
local timeFactor = 1 -- See lte.chr_reg
chr_reg.stallRegeneration(target, 60 / timeFactor)
end
else
target:increaseAttrib("hitpoints", -damange)
target:inform("Dmg: "..damange.."!");
end
end
function M.isValidTarget(char)
local noAttackQuestProgress = char:getQuestProgress(36)
if noAttackQuestProgress ~= 0 then
return false
end
local hitPoints = char:increaseAttrib("hitpoints", 0)
return hitPoints > 0
end
function M.getSpellResistence(char)
local willpower = char:increaseAttrib("willpower", 0);
local minResistence = willpower;
local maxResistence = willpower * 2;
return common.Limit(Random.uniform(minResistence, maxResistence) / 80.0, 0, 1);
end
-- Check if the line of sight is free from large objects that obstruct the view
function M.isLineOfSightFree(startPos, targetPos)
local blockList = world:LoS(startPos, targetPos)
for _, obstruction in pairs(blockList) do
if obstruction.TYPE == "ITEM" then
return false
end
end
return true
end
return M
|
Verify bug fix
|
Verify bug fix
|
Lua
|
agpl-3.0
|
Illarion-eV/Illarion-Content,KayMD/Illarion-Content,Baylamon/Illarion-Content,vilarion/Illarion-Content
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.