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
d65a90312b7188a0a2e35a2ff070e6d26d3d40d7
ceryx/nginx/lualib/router.lua
ceryx/nginx/lualib/router.lua
local host = ngx.var.host local is_not_https = (ngx.var.scheme ~= "https") local cache = ngx.shared.ceryx local settings_key = prefix .. ":settings:" .. host local enforce_https, flags = cache:get(host .. ":enforce_https") if enforce_https == nil then local res, flags = red:hget(settings_key, "enforce_https") enforce_https = tonumber(res) cache:set(host .. ":enforce_https", enforce_https, 5) end if enforce_https and is_not_https then return ngx.redirect("https://" .. host .. ngx.var.request_uri, ngx.HTTP_MOVED_PERMANENTLY) end -- Check if key exists in local cache res, flags = cache:get(host) if res then ngx.var.container_url = res return end local redis = require "resty.redis" local red = redis:new() red:set_timeout(100) -- 100 ms local redis_host = os.getenv("CERYX_REDIS_HOST") if not redis_host then redis_host = "127.0.0.1" end local redis_port = os.getenv("CERYX_REDIS_PORT") if not redis_port then redis_port = 6379 end local redis_password = os.getenv("CERYX_REDIS_PASSWORD") if not redis_password then redis_password = nil end local res, err = red:connect(redis_host, redis_port) -- Return if could not connect to Redis if not res then return ngx.exit(ngx.HTTP_BAD_GATEWAY) end if redis_password then local res, err = red:auth(redis_password) if not res then ngx.ERR("Failed to authenticate Redis: ", err) return end end -- Construct Redis key local prefix = os.getenv("CERYX_REDIS_PREFIX") if not prefix then prefix = "ceryx" end local key = prefix .. ":routes:" .. host -- Try to get target for host res, err = red:get(key) if not res or res == ngx.null then -- Construct Redis key for $wildcard key = prefix .. ":routes:$wildcard" res, err = red:get(key) if not res or res == ngx.null then return ngx.exit(ngx.HTTP_BAD_GATEWAY) end ngx.var.container_url = res return end -- Save found key to local cache for 5 seconds cache:set(host, res, 5) ngx.var.container_url = res
local host = ngx.var.host local is_not_https = (ngx.var.scheme ~= "https") local cache = ngx.shared.ceryx local prefix = os.getenv("CERYX_REDIS_PREFIX") if not prefix then prefix = "ceryx" end local settings_key = prefix .. ":settings:" .. host local enforce_https, flags = cache:get(host .. ":enforce_https") if enforce_https == nil then local res, flags = red:hget(settings_key, "enforce_https") enforce_https = tonumber(res) cache:set(host .. ":enforce_https", enforce_https, 5) end if enforce_https and is_not_https then return ngx.redirect("https://" .. host .. ngx.var.request_uri, ngx.HTTP_MOVED_PERMANENTLY) end -- Check if key exists in local cache res, flags = cache:get(host) if res then ngx.var.container_url = res return end local redis = require "resty.redis" local red = redis:new() red:set_timeout(100) -- 100 ms local redis_host = os.getenv("CERYX_REDIS_HOST") if not redis_host then redis_host = "127.0.0.1" end local redis_port = os.getenv("CERYX_REDIS_PORT") if not redis_port then redis_port = 6379 end local redis_password = os.getenv("CERYX_REDIS_PASSWORD") if not redis_password then redis_password = nil end local res, err = red:connect(redis_host, redis_port) -- Return if could not connect to Redis if not res then return ngx.exit(ngx.HTTP_BAD_GATEWAY) end if redis_password then local res, err = red:auth(redis_password) if not res then ngx.ERR("Failed to authenticate Redis: ", err) return end end -- Construct Redis key local key = prefix .. ":routes:" .. host -- Try to get target for host res, err = red:get(key) if not res or res == ngx.null then -- Construct Redis key for $wildcard key = prefix .. ":routes:$wildcard" res, err = red:get(key) if not res or res == ngx.null then return ngx.exit(ngx.HTTP_BAD_GATEWAY) end ngx.var.container_url = res return end -- Save found key to local cache for 5 seconds cache:set(host, res, 5) ngx.var.container_url = res
Move `prefix` declaration higher
Move `prefix` declaration higher
Lua
mit
sourcelair/ceryx,huayl/ceryx,sourcelair/ceryx,huayl/ceryx,sourcelair/ceryx,huayl/ceryx
61651c213e6ddb2b4389cddfa867022ca56e3f26
ceryx/nginx/lualib/https.lua
ceryx/nginx/lualib/https.lua
auto_ssl = (require "resty.auto-ssl").new() local redis = require "ceryx.redis" local routes = require "ceryx.routes" -- Define a function to determine which SNI domains to automatically handle -- and register new certificates for. Defaults to not allowing any domains, -- so this must be configured. auto_ssl:set( "allow_domain", function(domain) local host = domain local target = routes.getTargetForSource(host) if target == nil then return target end return true end ) -- Set the resty-auto-ssl storage to Redis, using the CERYX_* env variables auto_ssl:set("storage_adapter", "resty.auto-ssl.storage_adapters.redis") auto_ssl:set( "redis", { host = redis.host, port = redis.port } ) auto_ssl:init() require "resty.core"
auto_ssl = (require "resty.auto-ssl").new() local redis = require "ceryx.redis" local routes = require "ceryx.routes" -- Define a function to determine which SNI domains to automatically handle -- and register new certificates for. Defaults to not allowing any domains, -- so this must be configured. auto_ssl:set( "allow_domain", function(domain) local redisClient = redis:client() local host = domain local target = routes.getTargetForSource(host, redisClient) if target == nil then return target end return true end ) -- Set the resty-auto-ssl storage to Redis, using the CERYX_* env variables auto_ssl:set("storage_adapter", "resty.auto-ssl.storage_adapters.redis") auto_ssl:set( "redis", { host = redis.host, port = redis.port } ) auto_ssl:init() require "resty.core"
Fix empty Redis client in auto HTTPS certificates
Fix empty Redis client in auto HTTPS certificates
Lua
mit
huayl/ceryx,huayl/ceryx,sourcelair/ceryx,sourcelair/ceryx,sourcelair/ceryx,huayl/ceryx
b22406e7747b276137fbd3ffd299b71a8ec2d03e
npc/base/trade.lua
npc/base/trade.lua
--- Base NPC script for trader NPCs -- -- This script offers the functions that are required to turn a NPC into a trader -- -- Author: Martin Karing require("base.class") require("base.common") require("base.messages") require("base.money") require("npc.base.basic") module("npc.base.trade", package.seeall) tradeNPC = 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["_sellItems"] = nil; self["_buyItems"] = nil; self["_notEnoughMoneyMsg"] = base.messages.Messages(); self["_dialogClosedMsg"] = base.messages.Messages(); self["_dialogClosedNoTradeMsg"] = base.messages.Messages(); end); function tradeNPC:addItem(item) if (item == nil or not item:is_a(tradeNPCItem)) then return; end; if (item._type == "sell") then if (self._sellItems == nil) then self._sellItems = {}; end; table.insert(self._sellItems, item); elseif (item._type == "buyPrimary" or item._type == "buySecondary") then if (self._buyItems == nil) then self._buyItems = {}; end; table.insert(self._buyItems, item); end; end; function tradeNPC:addNotEnoughMoneyMsg(msgGerman, msgEnglish) self._notEnoughMoneyMsg:addMessage(msgGerman, msgEnglish); end; function tradeNPC:addDialogClosedMsg(msgGerman, msgEnglish) self._dialogClosedMsg:addMessage(msgGerman, msgEnglish); end; function tradeNPC:addDialogClosedNoTradeMsg(msgGerman, msgEnglish) self._dialogClosedNoTradeMsg:addMessage(msgGerman, msgEnglish); end; function tradeNPC:showDialog(npcChar, player) local anyTradeAction = false; local callback = function(dialog) local result = dialog:getResult() if result == MerchantDialog.playerSells then self:buyItemFromPlayer(npcChar, player, dialog:getSaleItem()); anyTradeAction = true; else if result == MerchantDialog.playerBuys then self:sellItemToPlayer(npcChar, player, dialog:getPurchaseIndex(), dialog:getPurchaseAmount()); anyTradeAction = true; elseif (not anyTradeAction and self._dialogClosedNoTradeMsg:hasMessages()) then local msgGerman, msgEnglish = self._dialogClosedNoTradeMsg:getRandomMessage(); npcChar:talkLanguage(Character.say, Player.german, msgGerman); npcChar:talkLanguage(Character.say, Player.english, msgEnglish); elseif (self._dialogClosedMsg:hasMessages()) then local msgGerman, msgEnglish = self._dialogClosedMsg:getRandomMessage(); npcChar:talkLanguage(Character.say, Player.german, msgGerman); npcChar:talkLanguage(Character.say, Player.english, msgEnglish); end; end; end; local dialog = MerchantDialog(base.common.GetNLS(player, "Handel", "Trade"), callback) table.foreach(self._sellItems, function(_, item) item:addToDialog(player, dialog); end); table.foreach(self._buyItems, function(_, item) item:addToDialog(player, dialog); end); player:requestMerchantDialog(dialog) end; local function isFittingItem(tradeItem, boughtItem) if (tradeItem._itemId ~= boughtItem.id) then return false; end; if (tradeItem._data ~= nil and tradeItem._data ~= boughtItem.data) then return false; end; return true; end; function tradeNPC:buyItemFromPlayer(npcChar, player, boughtItem) for index, item in pairs(self._buyItems) do if isFittingItem(item, boughtItem) then local price = item._price * boughtItem.number; if world:erase(boughtItem, boughtItem.number) then base.money.GiveMoneyToChar(player, price); end; break; end; end end; function tradeNPC:sellItemToPlayer(npcChar, player, itemIndex, amount) local item = self._sellItems[itemIndex]; if (item == nil) then base.common.InformNLS(player, "Ein Fehler ist beim Kauf des Items aufgetreten", "And error occurred while buying the item"); return; end; if (base.money.CharHasMoney(player, item._price * amount)) then base.money.TakeMoneyFromChar(player, item._price * amount); local notCreated = player:createItem(item._itemId, amount, item._quality, item._data); if (notCreated > 0) then world:createItemFromId(item._itemId, amount, player.pos, true, item._quality, item._data); end; elseif (self._notEnoughMoneyMsg:hasMessages()) then local msgGerman, msgEnglish = self._notEnoughMoneyMsg:getRandomMessage(); npcChar:talkLanguage(Character.say, Player.german, msgGerman); npcChar:talkLanguage(Character.say, Player.english, msgEnglish); end; end; tradeNPCItem = base.class.class(function(self, id, itemType, nameDe, nameEn, price, stack, quality, data) if (id == nil or id <= 0) then error("Invalid ItemID for trade item"); end; if (itemType ~= "sell" and itemType ~= "buyPrimary" and itemType ~= "buySecondary") then error("Invalid type for trade item"); end; self["_itemId"] = id; self["_type"] = itemType; if (nameDe == nil or nameEn == nil) then self["_nameDe"] = world:getItemName(id, Player.german); self["_nameEn"] = world:getItemName(id, Player.english); else self["_nameDe"] = nameDe; self["_nameEn"] = nameEn; end; if (price == nil) then if (itemType == "sell") then self["_price"] = world:getItemStatsFromId(id).Worth * 100; elseif (itemType == "buyPrimary") then self["_price"] = world:getItemStatsFromId(id).Worth * 10; elseif (itemType == "buySecondary") then self["_price"] = world:getItemStatsFromId(id).Worth * 5; end; else self["_price"] = price; end; if (itemType == "sell" and stack ~= nil) then self["_stack"] = stack; else self["_stack"] = nil; end; if (quality ~= nil or itemType ~= "sell") then self["_quality"] = quality; else self["_quality"] = 580; end; if (data ~= nil or itemType ~= "sell") then self["_data"] = data; else self["_data"] = 0; end; end); function tradeNPCItem:addToDialog(player, dialog) local name = base.common.GetNLS(player, self._nameDe, self._nameEn); if (self._type == "sell") then if (self._stack == nil) then dialog:addOffer(self._itemId, name, self._price); else dialog:addOffer(self._itemId, name, self._price, self._stack); end; elseif (self._type == "buyPrimary") then dialog:addPrimaryRequest(self._itemId, name, self._price); else dialog:addSecondaryRequest(self._itemId, name, self._price) end; end;
--- Base NPC script for trader NPCs -- -- This script offers the functions that are required to turn a NPC into a trader -- -- Author: Martin Karing require("base.class") require("base.common") require("base.messages") require("base.money") require("npc.base.basic") module("npc.base.trade", package.seeall) tradeNPC = 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["_sellItems"] = {}; self["_buyItems"] = {}; self["_notEnoughMoneyMsg"] = base.messages.Messages(); self["_dialogClosedMsg"] = base.messages.Messages(); self["_dialogClosedNoTradeMsg"] = base.messages.Messages(); end); function tradeNPC:addItem(item) if (item == nil or not item:is_a(tradeNPCItem)) then return; end; if (item._type == "sell") then table.insert(self._sellItems, item); elseif (item._type == "buyPrimary" or item._type == "buySecondary") then table.insert(self._buyItems, item); end; end; function tradeNPC:addNotEnoughMoneyMsg(msgGerman, msgEnglish) self._notEnoughMoneyMsg:addMessage(msgGerman, msgEnglish); end; function tradeNPC:addDialogClosedMsg(msgGerman, msgEnglish) self._dialogClosedMsg:addMessage(msgGerman, msgEnglish); end; function tradeNPC:addDialogClosedNoTradeMsg(msgGerman, msgEnglish) self._dialogClosedNoTradeMsg:addMessage(msgGerman, msgEnglish); end; function tradeNPC:showDialog(npcChar, player) local anyTradeAction = false; local callback = function(dialog) local result = dialog:getResult() if result == MerchantDialog.playerSells then self:buyItemFromPlayer(npcChar, player, dialog:getSaleItem()); anyTradeAction = true; else if result == MerchantDialog.playerBuys then self:sellItemToPlayer(npcChar, player, dialog:getPurchaseIndex(), dialog:getPurchaseAmount()); anyTradeAction = true; elseif (not anyTradeAction and self._dialogClosedNoTradeMsg:hasMessages()) then local msgGerman, msgEnglish = self._dialogClosedNoTradeMsg:getRandomMessage(); npcChar:talkLanguage(Character.say, Player.german, msgGerman); npcChar:talkLanguage(Character.say, Player.english, msgEnglish); elseif (self._dialogClosedMsg:hasMessages()) then local msgGerman, msgEnglish = self._dialogClosedMsg:getRandomMessage(); npcChar:talkLanguage(Character.say, Player.german, msgGerman); npcChar:talkLanguage(Character.say, Player.english, msgEnglish); end; end; end; local dialog = MerchantDialog(base.common.GetNLS(player, "Handel", "Trade"), callback) table.foreach(self._sellItems, function(_, item) item:addToDialog(player, dialog); end); table.foreach(self._buyItems, function(_, item) item:addToDialog(player, dialog); end); player:requestMerchantDialog(dialog) end; local function isFittingItem(tradeItem, boughtItem) if (tradeItem._itemId ~= boughtItem.id) then return false; end; if (tradeItem._data ~= nil and tradeItem._data ~= boughtItem.data) then return false; end; return true; end; function tradeNPC:buyItemFromPlayer(npcChar, player, boughtItem) for index, item in pairs(self._buyItems) do if isFittingItem(item, boughtItem) then local price = item._price * boughtItem.number; if world:erase(boughtItem, boughtItem.number) then base.money.GiveMoneyToChar(player, price); end; break; end; end end; function tradeNPC:sellItemToPlayer(npcChar, player, itemIndex, amount) local item = self._sellItems[itemIndex]; if (item == nil) then base.common.InformNLS(player, "Ein Fehler ist beim Kauf des Items aufgetreten", "And error occurred while buying the item"); return; end; if (base.money.CharHasMoney(player, item._price * amount)) then base.money.TakeMoneyFromChar(player, item._price * amount); local notCreated = player:createItem(item._itemId, amount, item._quality, item._data); if (notCreated > 0) then world:createItemFromId(item._itemId, amount, player.pos, true, item._quality, item._data); end; elseif (self._notEnoughMoneyMsg:hasMessages()) then local msgGerman, msgEnglish = self._notEnoughMoneyMsg:getRandomMessage(); npcChar:talkLanguage(Character.say, Player.german, msgGerman); npcChar:talkLanguage(Character.say, Player.english, msgEnglish); end; end; tradeNPCItem = base.class.class(function(self, id, itemType, nameDe, nameEn, price, stack, quality, data) if (id == nil or id <= 0) then error("Invalid ItemID for trade item"); end; if (itemType ~= "sell" and itemType ~= "buyPrimary" and itemType ~= "buySecondary") then error("Invalid type for trade item"); end; self["_itemId"] = id; self["_type"] = itemType; if (nameDe == nil or nameEn == nil) then self["_nameDe"] = world:getItemName(id, Player.german); self["_nameEn"] = world:getItemName(id, Player.english); else self["_nameDe"] = nameDe; self["_nameEn"] = nameEn; end; if (price == nil) then if (itemType == "sell") then self["_price"] = world:getItemStatsFromId(id).Worth * 100; elseif (itemType == "buyPrimary") then self["_price"] = world:getItemStatsFromId(id).Worth * 10; elseif (itemType == "buySecondary") then self["_price"] = world:getItemStatsFromId(id).Worth * 5; end; else self["_price"] = price; end; if (itemType == "sell" and stack ~= nil) then self["_stack"] = stack; else self["_stack"] = nil; end; if (quality ~= nil or itemType ~= "sell") then self["_quality"] = quality; else self["_quality"] = 580; end; if (data ~= nil or itemType ~= "sell") then self["_data"] = data; else self["_data"] = 0; end; end); function tradeNPCItem:addToDialog(player, dialog) local name = base.common.GetNLS(player, self._nameDe, self._nameEn); if (self._type == "sell") then if (self._stack == nil) then dialog:addOffer(self._itemId, name, self._price); else dialog:addOffer(self._itemId, name, self._price, self._stack); end; elseif (self._type == "buyPrimary") then dialog:addPrimaryRequest(self._itemId, name, self._price); else dialog:addSecondaryRequest(self._itemId, name, self._price) end; end;
Bugfix for the trading NPCs
Bugfix for the trading NPCs
Lua
agpl-3.0
vilarion/Illarion-Content,Illarion-eV/Illarion-Content,Baylamon/Illarion-Content,LaFamiglia/Illarion-Content,KayMD/Illarion-Content
82e42547b4a5710e0b8175c94b9f9e9a4aea5558
src/extensions/cp/apple/finalcutpro/main/TimelineToolbar.lua
src/extensions/cp/apple/finalcutpro/main/TimelineToolbar.lua
--- === cp.apple.finalcutpro.main.TimelineToolbar === --- --- Timeline Toolbar -------------------------------------------------------------------------------- -- -- EXTENSIONS: -- -------------------------------------------------------------------------------- local require = require -------------------------------------------------------------------------------- -- CommandPost Extensions: -------------------------------------------------------------------------------- local axutils = require("cp.ui.axutils") local prop = require("cp.prop") local RadioButton = require("cp.ui.RadioButton") local StaticText = require("cp.ui.StaticText") local TimelineAppearance = require("cp.apple.finalcutpro.main.TimelineAppearance") -------------------------------------------------------------------------------- -- Local Lua Functions: -------------------------------------------------------------------------------- local cache = axutils.cache local childFromLeft, childFromRight = axutils.childFromLeft, axutils.childFromRight local childMatching, childWithID = axutils.childMatching, axutils.childWithID local childWithRole = axutils.childWithRole -------------------------------------------------------------------------------- -- -- THE MODULE: -- -------------------------------------------------------------------------------- local TimelineToolbar = {} -- TODO: Add documentation function TimelineToolbar.new(parent) local o = prop.extend({_parent = parent}, TimelineToolbar) -- TODO: Add documentation local UI = prop(function(self) return axutils.cache(self, "_ui", function() return childWithRole(self:parent():UI(), "AXGroup") -- _NS:237 in FCPX 10.4 end) end) prop.bind(o) { UI = UI, -- TODO: Add documentation isShowing = UI:mutate(function(original) return original() ~= nil end), -- TODO: Add documentation -- Contains buttons relating to mouse skimming behaviour: skimmingGroupUI = UI:mutate(function(original, self) return cache(self, "_skimmingGroup", function() return childFromRight(original(), 1, function(element) -- _NS:179 in FCPX 10.4 return element:attributeValue("AXRole") == "AXGroup" end) end) end), -- TODO: Add documentation effectsGroupUI = UI:mutate(function(original, self) return cache(self, "_effectsGroup", function() return childWithRole(original(), "AXRadioGroup") -- _NS:166 in FCPX 10.4 end) end) } return o end -- TODO: Add documentation function TimelineToolbar:parent() return self._parent end -- TODO: Add documentation function TimelineToolbar:app() return self:parent():app() end ----------------------------------------------------------------------- -- -- THE TOOLBAR ITEMS: -- ----------------------------------------------------------------------- --- cp.apple.finalcutpro.main.TimelineToolbar:title() -> cp.ui.StaticText --- Method --- Returns the title [StaticText](cp.ui.StaticText.md) from the Timeline Titlebar. --- --- Parameters: --- * None. --- --- Returns: --- * The [StaticText](cp.ui.StaticText.md) containing the title. function TimelineToolbar:title() if not self._title then self._title = StaticText(self, self.UI:mutate(function(original) return cache(self, "_titleUI", function() return childFromLeft(original(), 1, StaticText.matches) end) end)) end return self._title end -- TODO: Add documentation function TimelineToolbar:appearance() if not self._appearance then self._appearance = TimelineAppearance.new(self) end return self._appearance end -- TODO: Add documentation function TimelineToolbar:effectsToggle() if not self._effectsToggle then self._effectsToggle = RadioButton(self, function() local effectsGroup = self:effectsGroupUI() return effectsGroup and effectsGroup[1] end) end return self._effectsToggle end -- TODO: Add documentation function TimelineToolbar:transitionsToggle() if not self._transitionsToggle then self._transitionsToggle = RadioButton(self, function() local effectsGroup = self:effectsGroupUI() return effectsGroup and effectsGroup[2] end) end return self._transitionsToggle end return TimelineToolbar
--- === cp.apple.finalcutpro.main.TimelineToolbar === --- --- Timeline Toolbar -------------------------------------------------------------------------------- -- -- EXTENSIONS: -- -------------------------------------------------------------------------------- local require = require -------------------------------------------------------------------------------- -- CommandPost Extensions: -------------------------------------------------------------------------------- local axutils = require("cp.ui.axutils") local prop = require("cp.prop") local RadioButton = require("cp.ui.RadioButton") local StaticText = require("cp.ui.StaticText") local TimelineAppearance = require("cp.apple.finalcutpro.main.TimelineAppearance") -------------------------------------------------------------------------------- -- Local Lua Functions: -------------------------------------------------------------------------------- local cache = axutils.cache local childFromLeft, childFromRight = axutils.childFromLeft, axutils.childFromRight local childWithRole = axutils.childWithRole -------------------------------------------------------------------------------- -- -- THE MODULE: -- -------------------------------------------------------------------------------- local TimelineToolbar = {} -- TODO: Add documentation function TimelineToolbar.new(parent) local o = prop.extend({_parent = parent}, TimelineToolbar) -- TODO: Add documentation local UI = prop(function(self) return axutils.cache(self, "_ui", function() return childWithRole(self:parent():UI(), "AXGroup") -- _NS:237 in FCPX 10.4 end) end) prop.bind(o) { UI = UI, -- TODO: Add documentation isShowing = UI:mutate(function(original) return original() ~= nil end), -- TODO: Add documentation -- Contains buttons relating to mouse skimming behaviour: skimmingGroupUI = UI:mutate(function(original, self) return cache(self, "_skimmingGroup", function() return childFromRight(original(), 1, function(element) -- _NS:179 in FCPX 10.4 return element:attributeValue("AXRole") == "AXGroup" end) end) end), -- TODO: Add documentation effectsGroupUI = UI:mutate(function(original, self) return cache(self, "_effectsGroup", function() return childWithRole(original(), "AXRadioGroup") -- _NS:166 in FCPX 10.4 end) end) } return o end -- TODO: Add documentation function TimelineToolbar:parent() return self._parent end -- TODO: Add documentation function TimelineToolbar:app() return self:parent():app() end ----------------------------------------------------------------------- -- -- THE TOOLBAR ITEMS: -- ----------------------------------------------------------------------- --- cp.apple.finalcutpro.main.TimelineToolbar:title() -> cp.ui.StaticText --- Method --- Returns the title [StaticText](cp.ui.StaticText.md) from the Timeline Titlebar. --- --- Parameters: --- * None. --- --- Returns: --- * The [StaticText](cp.ui.StaticText.md) containing the title. function TimelineToolbar:title() if not self._title then self._title = StaticText(self, self.UI:mutate(function(original) return cache(self, "_titleUI", function() return childFromLeft(original(), 1, StaticText.matches) end) end)) end return self._title end -- TODO: Add documentation function TimelineToolbar:appearance() if not self._appearance then self._appearance = TimelineAppearance.new(self) end return self._appearance end -- TODO: Add documentation function TimelineToolbar:effectsToggle() if not self._effectsToggle then self._effectsToggle = RadioButton(self, function() local effectsGroup = self:effectsGroupUI() return effectsGroup and effectsGroup[1] end) end return self._effectsToggle end -- TODO: Add documentation function TimelineToolbar:transitionsToggle() if not self._transitionsToggle then self._transitionsToggle = RadioButton(self, function() local effectsGroup = self:effectsGroupUI() return effectsGroup and effectsGroup[2] end) end return self._transitionsToggle end return TimelineToolbar
#1509
#1509 - Fixed @stickler-ci errors
Lua
mit
fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost
3e83230c445f43bede23e679d8777b5e9225eb1b
src/extensions/cp/apple/finalcutpro/main/SecondaryWindow.lua
src/extensions/cp/apple/finalcutpro/main/SecondaryWindow.lua
--- === cp.apple.finalcutpro.main.SecondaryWindow === --- --- Secondary Window Module. -------------------------------------------------------------------------------- -- -- EXTENSIONS: -- -------------------------------------------------------------------------------- local require = require -------------------------------------------------------------------------------- -- Logger: -------------------------------------------------------------------------------- -- local log = require("hs.logger").new("secondaryWindow") -------------------------------------------------------------------------------- -- CommandPost Extensions: -------------------------------------------------------------------------------- local axutils = require("cp.ui.axutils") local Window = require("cp.ui.Window") local go = require("cp.rx.go") local Do, If = go.Do, go.If local class = require("middleclass") local lazy = require("cp.lazy") -------------------------------------------------------------------------------- -- -- THE MODULE: -- -------------------------------------------------------------------------------- local SecondaryWindow = class("SecondaryWindow"):include(lazy) --- cp.apple.finalcutpro.main.SecondaryWindow.matches(element) -> boolean --- Function --- Checks to see if an element matches what we think it should be. --- --- Parameters: --- * element - An `axuielementObject` to check. --- --- Returns: --- * `true` if matches otherwise `false` function SecondaryWindow.static.matches(element) if element ~= nil and element:attributeValue("AXModal") == false then local children = element:attributeValue("AXChildren") return children and #children == 1 and children[1]:attributeValue("AXRole") == "AXSplitGroup" end return false end --- cp.apple.finalcutpro.main.SecondaryWindow(app) -> SecondaryWindow --- Constructor --- Creates a new `SecondaryWindow` instance. --- --- Parameters: --- * app - The `cp.apple.finalcutpro` object. --- --- Returns: --- * A new `SecondaryWindow` object. function SecondaryWindow:initialize(app) self._app = app end function SecondaryWindow:app() return self._app end function SecondaryWindow.lazy.method:window() return Window(self:app().app, self.UI) end function SecondaryWindow.lazy.prop:UI() return self:app().windowsUI:mutate(function(original) return axutils.cache(self, "_ui", function() return axutils.childMatching(original(), SecondaryWindow.matches) end, SecondaryWindow.matches) end) end --- cp.apple.finalcutpro.main.SecondaryWindow.hsWindow <cp.prop: hs.window; read-only; live> --- Field --- The `hs.window` instance for the window, or `nil` if it can't be found. function SecondaryWindow.lazy.prop:hsWindow() return self:window().hsWindow end --- cp.apple.finalcutpro.main.SecondaryWindow.isShowing <cp.prop: boolean; read-only; live> --- Field --- Is `true` if the window is visible. function SecondaryWindow.lazy.prop:isShowing() return self:window().visible end --- cp.apple.finalcutpro.main.SecondaryWindow.isFullScreen <cp.prop: boolean; live> --- Field --- Is `true` if the window is full-screen. function SecondaryWindow.lazy.prop:isFullScreen() return self:window().fullScreen end --- cp.apple.finalcutpro.main.SecondaryWindow.frame <cp.prop: frame> --- Field --- The current position (x, y, width, height) of the window. function SecondaryWindow.lazy.prop:frame() return self:window().frame end --- cp.apple.finalcutpro.main.SecondaryWindow.rootGroupUI <cp.prop: hs._asm.axuielement; read-only; live> --- Field --- The root UI element on the window. function SecondaryWindow.lazy.prop:rootGroupUI() return self.UI:mutate(function(original) return axutils.cache(self, "_rootGroup", function() local ui = original() return ui and axutils.childWithRole(ui, "AXSplitGroup") end) end) end --- cp.apple.finalcutpro.main.SecondaryWindow.viewerGroupUI <cp.prop: hs._asm.axuielement; read-only; live> --- Field --- The UI element that will contain the `Viewer` if it's on the Secondary Window. function SecondaryWindow.lazy.prop:viewerGroupUI() return self.rootGroupUI end --- cp.apple.finalcutpro.main.SecondaryWindow.browserGroupUI <cp.prop: hs._asm.axuielement; read-only; live> --- Field --- The UI element that will contain the `Browser` if it's on the Secondary Window. function SecondaryWindow.lazy.prop:browserGroupUI() return self.rootGroupUI end --- cp.apple.finalcutpro.main.SecondaryWindow.timelineGroupUI <cp.prop: hs._asm.axuielement; read-only; live> --- Field --- The UI element that will contain the `Timeline` if it's on the Secondary Window. function SecondaryWindow.lazy.prop:timelineGroupUI() return self.rootGroupUI:mutate(function(original) return axutils.cache(self, "_timelineGroup", function() -- for some reason, the Timeline is burried under three levels local root = original() if root and root[1] and root[1][1] then return root[1][1] end end) end) end --- cp.apple.finalcutpro.main.SecondaryWindow:app() -> App --- Method --- Returns the app instance representing Final Cut Pro. --- --- Parameters: --- * None --- --- Returns: --- * App function SecondaryWindow:app() return self._app end --- cp.apple.finalcutpro.main.SecondaryWindow:window() -> cp.ui.Window --- Method --- Returns the `Window` instance. --- --- Parameters: --- * None --- --- Returns: --- * The `Window` instance. function SecondaryWindow:window() return self._window end --- cp.apple.finalcutpro.main.SecondaryWindow:show() -> SecondaryWindow --- Method --- Show the Secondary Window. --- --- Parameters: --- * None --- --- Returns: --- * The `SecondaryWindow` object. function SecondaryWindow:show() -------------------------------------------------------------------------------- -- Currently just ensures the app is running. -- Determine if there are any scenarios where we need to force this. -------------------------------------------------------------------------------- self:app():show() return self end --- cp.apple.finalcutpro.main.SecondaryWindow:doShow() -> cp.rx.go.Statement --- Method --- A [Statement](cp.rx.go.Statement) that shows the Secondary Window. --- --- Parameters: --- * None --- --- Returns: --- * The `SecondaryWindow` object. function SecondaryWindow.lazy.method:doShow() return Do(self:app():doShow()) :Then( If(self.isShowing):Is(false) :Then(self:window():doFocus()) :TimeoutAfter(1000, "Unable to focus on Secondary Window.") ) :Label("SecondaryWindow:doShow") end return SecondaryWindow
--- === cp.apple.finalcutpro.main.SecondaryWindow === --- --- Secondary Window Module. -------------------------------------------------------------------------------- -- -- EXTENSIONS: -- -------------------------------------------------------------------------------- local require = require -------------------------------------------------------------------------------- -- Logger: -------------------------------------------------------------------------------- -- local log = require("hs.logger").new("secondaryWindow") -------------------------------------------------------------------------------- -- CommandPost Extensions: -------------------------------------------------------------------------------- local axutils = require("cp.ui.axutils") local Window = require("cp.ui.Window") local go = require("cp.rx.go") local Do, If = go.Do, go.If local class = require("middleclass") local lazy = require("cp.lazy") -------------------------------------------------------------------------------- -- -- THE MODULE: -- -------------------------------------------------------------------------------- local SecondaryWindow = class("SecondaryWindow"):include(lazy) --- cp.apple.finalcutpro.main.SecondaryWindow.matches(element) -> boolean --- Function --- Checks to see if an element matches what we think it should be. --- --- Parameters: --- * element - An `axuielementObject` to check. --- --- Returns: --- * `true` if matches otherwise `false` function SecondaryWindow.static.matches(element) if element ~= nil and element:attributeValue("AXModal") == false then local children = element:attributeValue("AXChildren") return children and #children == 1 and children[1]:attributeValue("AXRole") == "AXSplitGroup" end return false end --- cp.apple.finalcutpro.main.SecondaryWindow(app) -> SecondaryWindow --- Constructor --- Creates a new `SecondaryWindow` instance. --- --- Parameters: --- * app - The `cp.apple.finalcutpro` object. --- --- Returns: --- * A new `SecondaryWindow` object. function SecondaryWindow:initialize(app) self._app = app end function SecondaryWindow:app() return self._app end function SecondaryWindow.lazy.method:window() return Window(self:app().app, self.UI) end function SecondaryWindow.lazy.prop:UI() return self:app().windowsUI:mutate(function(original) return axutils.cache(self, "_ui", function() return axutils.childMatching(original(), SecondaryWindow.matches) end, SecondaryWindow.matches) end) end --- cp.apple.finalcutpro.main.SecondaryWindow.hsWindow <cp.prop: hs.window; read-only; live> --- Field --- The `hs.window` instance for the window, or `nil` if it can't be found. function SecondaryWindow.lazy.prop:hsWindow() return self:window().hsWindow end --- cp.apple.finalcutpro.main.SecondaryWindow.isShowing <cp.prop: boolean; read-only; live> --- Field --- Is `true` if the window is visible. function SecondaryWindow.lazy.prop:isShowing() return self:window().visible end --- cp.apple.finalcutpro.main.SecondaryWindow.isFullScreen <cp.prop: boolean; live> --- Field --- Is `true` if the window is full-screen. function SecondaryWindow.lazy.prop:isFullScreen() return self:window().fullScreen end --- cp.apple.finalcutpro.main.SecondaryWindow.frame <cp.prop: frame> --- Field --- The current position (x, y, width, height) of the window. function SecondaryWindow.lazy.prop:frame() return self:window().frame end --- cp.apple.finalcutpro.main.SecondaryWindow.rootGroupUI <cp.prop: hs._asm.axuielement; read-only; live> --- Field --- The root UI element on the window. function SecondaryWindow.lazy.prop:rootGroupUI() return self.UI:mutate(function(original) return axutils.cache(self, "_rootGroup", function() local ui = original() return ui and axutils.childWithRole(ui, "AXSplitGroup") end) end) end --- cp.apple.finalcutpro.main.SecondaryWindow.viewerGroupUI <cp.prop: hs._asm.axuielement; read-only; live> --- Field --- The UI element that will contain the `Viewer` if it's on the Secondary Window. function SecondaryWindow.lazy.prop:viewerGroupUI() return self.rootGroupUI end --- cp.apple.finalcutpro.main.SecondaryWindow.browserGroupUI <cp.prop: hs._asm.axuielement; read-only; live> --- Field --- The UI element that will contain the `Browser` if it's on the Secondary Window. function SecondaryWindow.lazy.prop:browserGroupUI() return self.rootGroupUI end --- cp.apple.finalcutpro.main.SecondaryWindow.timelineGroupUI <cp.prop: hs._asm.axuielement; read-only; live> --- Field --- The UI element that will contain the `Timeline` if it's on the Secondary Window. function SecondaryWindow.lazy.prop:timelineGroupUI() return self.rootGroupUI:mutate(function(original) return axutils.cache(self, "_timelineGroup", function() -- for some reason, the Timeline is burried under three levels local root = original() if root and root[1] and root[1][1] then return root[1][1] end end) end) end --- cp.apple.finalcutpro.main.SecondaryWindow:app() -> App --- Method --- Returns the app instance representing Final Cut Pro. --- --- Parameters: --- * None --- --- Returns: --- * App function SecondaryWindow:app() return self._app end --- cp.apple.finalcutpro.main.SecondaryWindow:show() -> SecondaryWindow --- Method --- Show the Secondary Window. --- --- Parameters: --- * None --- --- Returns: --- * The `SecondaryWindow` object. function SecondaryWindow:show() -------------------------------------------------------------------------------- -- Currently just ensures the app is running. -- Determine if there are any scenarios where we need to force this. -------------------------------------------------------------------------------- self:app():show() return self end --- cp.apple.finalcutpro.main.SecondaryWindow:doShow() -> cp.rx.go.Statement --- Method --- A [Statement](cp.rx.go.Statement) that shows the Secondary Window. --- --- Parameters: --- * None --- --- Returns: --- * The `SecondaryWindow` object. function SecondaryWindow.lazy.method:doShow() return Do(self:app():doShow()) :Then( If(self.isShowing):Is(false) :Then(self:window():doFocus()) :TimeoutAfter(1000, "Unable to focus on Secondary Window.") ) :Label("SecondaryWindow:doShow") end return SecondaryWindow
* Fixed bug with duplicate `SecondaryWindow:window()` method
* Fixed bug with duplicate `SecondaryWindow:window()` method
Lua
mit
CommandPost/CommandPost,fcpxhacks/fcpxhacks,fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost
df8334c8069aba6cffb4d090f7c854607aa4aa2b
data.lua
data.lua
-- -- Manages encoder/decoder data matrices. -- local data = torch.class("data") function data:__init(opt, data_file) local f = hdf5.open(data_file, 'r') self.source = f:read('source'):all() self.target = f:read('target'):all() self.target_output = f:read('target_output'):all() self.target_l = f:read('target_l'):all() --max target length each batch self.target_l_all = f:read('target_l_all'):all() self.target_l_all:add(-1) self.batch_l = f:read('batch_l'):all() self.source_l = f:read('batch_w'):all() --max source length each batch if opt.start_symbol == 0 then self.source_l:add(-2) self.source = self.source[{{},{2, self.source:size(2)-1}}] end self.batch_idx = f:read('batch_idx'):all() self.target_size = f:read('target_size'):all()[1] self.source_size = f:read('source_size'):all()[1] self.target_nonzeros = f:read('target_nonzeros'):all() if opt.use_chars_enc == 1 then self.source_char = f:read('source_char'):all() self.char_size = f:read('char_size'):all()[1] self.char_length = self.source_char:size(3) end if opt.use_chars_dec == 1 then self.target_char = f:read('target_char'):all() self.char_size = f:read('char_size'):all()[1] self.char_length = self.target_char:size(3) end self.length = self.batch_l:size(1) self.seq_length = self.target:size(2) self.batches = {} local max_source_l = self.source_l:max() local source_l_rev = torch.ones(max_source_l):long() for i = 1, max_source_l do source_l_rev[i] = max_source_l - i + 1 end for i = 1, self.length do local source_i, target_i local target_output_i = self.target_output:sub(self.batch_idx[i],self.batch_idx[i] +self.batch_l[i]-1, 1, self.target_l[i]) local target_l_i = self.target_l_all:sub(self.batch_idx[i], self.batch_idx[i]+self.batch_l[i]-1) if opt.use_chars_enc == 1 then source_i = self.source_char:sub(self.batch_idx[i], self.batch_idx[i] + self.batch_l[i]-1, 1, self.source_l[i]):transpose(1,2):contiguous() else source_i = self.source:sub(self.batch_idx[i], self.batch_idx[i]+self.batch_l[i]-1, 1, self.source_l[i]):transpose(1,2) end if opt.reverse_src == 1 then source_i = source_i:index(1, source_l_rev[{{max_source_l-self.source_l[i]+1, max_source_l}}]) end if opt.use_chars_dec == 1 then target_i = self.target_char:sub(self.batch_idx[i], self.batch_idx[i] + self.batch_l[i]-1, 1, self.target_l[i]):transpose(1,2):contiguous() else target_i = self.target:sub(self.batch_idx[i], self.batch_idx[i]+self.batch_l[i]-1, 1, self.target_l[i]):transpose(1,2) end table.insert(self.batches, {target_i, target_output_i:transpose(1,2), self.target_nonzeros[i], source_i, self.batch_l[i], self.target_l[i], self.source_l[i], target_l_i}) end end function data:size() return self.length end function data.__index(self, idx) if type(idx) == "string" then return data[idx] else local target_input = self.batches[idx][1] local target_output = self.batches[idx][2] local nonzeros = self.batches[idx][3] local source_input = self.batches[idx][4] local batch_l = self.batches[idx][5] local target_l = self.batches[idx][6] local source_l = self.batches[idx][7] local target_l_all = self.batches[idx][8] if opt.gpuid >= 0 then --if multi-gpu, source lives in gpuid1, rest on gpuid2 cutorch.setDevice(opt.gpuid) source_input = source_input:cuda() if opt.gpuid2 >= 0 then cutorch.setDevice(opt.gpuid2) end target_input = target_input:cuda() target_output = target_output:cuda() target_l_all = target_l_all:cuda() end return {target_input, target_output, nonzeros, source_input, batch_l, target_l, source_l, target_l_all} end end return data
-- -- Manages encoder/decoder data matrices. -- local data = torch.class("data") function data:__init(opt, data_file) local f = hdf5.open(data_file, 'r') self.source = f:read('source'):all() self.target = f:read('target'):all() self.target_output = f:read('target_output'):all() self.target_l = f:read('target_l'):all() --max target length each batch self.target_l_all = f:read('target_l_all'):all() self.target_l_all:add(-1) self.batch_l = f:read('batch_l'):all() self.source_l = f:read('batch_w'):all() --max source length each batch if opt.start_symbol == 0 then self.source_l:add(-2) self.source = self.source[{{},{2, self.source:size(2)-1}}] end self.batch_idx = f:read('batch_idx'):all() self.target_size = f:read('target_size'):all()[1] self.source_size = f:read('source_size'):all()[1] self.target_nonzeros = f:read('target_nonzeros'):all() if opt.use_chars_enc == 1 then self.source_char = f:read('source_char'):all() self.char_size = f:read('char_size'):all()[1] self.char_length = self.source_char:size(3) if opt.start_symbol == 0 then self.source_char = self.source_char[{{}, {2, self.source_char:size(2)-1}}] end end if opt.use_chars_dec == 1 then self.target_char = f:read('target_char'):all() self.char_size = f:read('char_size'):all()[1] self.char_length = self.target_char:size(3) end self.length = self.batch_l:size(1) self.seq_length = self.target:size(2) self.batches = {} local max_source_l = self.source_l:max() local source_l_rev = torch.ones(max_source_l):long() for i = 1, max_source_l do source_l_rev[i] = max_source_l - i + 1 end for i = 1, self.length do local source_i, target_i local target_output_i = self.target_output:sub(self.batch_idx[i],self.batch_idx[i] +self.batch_l[i]-1, 1, self.target_l[i]) local target_l_i = self.target_l_all:sub(self.batch_idx[i], self.batch_idx[i]+self.batch_l[i]-1) if opt.use_chars_enc == 1 then source_i = self.source_char:sub(self.batch_idx[i], self.batch_idx[i] + self.batch_l[i]-1, 1, self.source_l[i]):transpose(1,2):contiguous() else source_i = self.source:sub(self.batch_idx[i], self.batch_idx[i]+self.batch_l[i]-1, 1, self.source_l[i]):transpose(1,2) end if opt.reverse_src == 1 then source_i = source_i:index(1, source_l_rev[{{max_source_l-self.source_l[i]+1, max_source_l}}]) end if opt.use_chars_dec == 1 then target_i = self.target_char:sub(self.batch_idx[i], self.batch_idx[i] + self.batch_l[i]-1, 1, self.target_l[i]):transpose(1,2):contiguous() else target_i = self.target:sub(self.batch_idx[i], self.batch_idx[i]+self.batch_l[i]-1, 1, self.target_l[i]):transpose(1,2) end table.insert(self.batches, {target_i, target_output_i:transpose(1,2), self.target_nonzeros[i], source_i, self.batch_l[i], self.target_l[i], self.source_l[i], target_l_i}) end end function data:size() return self.length end function data.__index(self, idx) if type(idx) == "string" then return data[idx] else local target_input = self.batches[idx][1] local target_output = self.batches[idx][2] local nonzeros = self.batches[idx][3] local source_input = self.batches[idx][4] local batch_l = self.batches[idx][5] local target_l = self.batches[idx][6] local source_l = self.batches[idx][7] local target_l_all = self.batches[idx][8] if opt.gpuid >= 0 then --if multi-gpu, source lives in gpuid1, rest on gpuid2 cutorch.setDevice(opt.gpuid) source_input = source_input:cuda() if opt.gpuid2 >= 0 then cutorch.setDevice(opt.gpuid2) end target_input = target_input:cuda() target_output = target_output:cuda() target_l_all = target_l_all:cuda() end return {target_input, target_output, nonzeros, source_input, batch_l, target_l, source_l, target_l_all} end end return data
fix start symbol and chars
fix start symbol and chars
Lua
mit
jungikim/OpenNMT,da03/OpenNMT,harvardnlp/seq2seq-attn,jsenellart-systran/OpenNMT,srush/OpenNMT,jungikim/OpenNMT,OpenNMT/OpenNMT,jeffreyling/seq2seq-hard,jeffreyling/seq2seq-hard,monsieurzhang/OpenNMT,jeffreyling/seq2seq-hard,da03/OpenNMT,jsenellart/OpenNMT,dabbler0/seq2seq-comparison,jungikim/OpenNMT,OpenNMT/OpenNMT,monsieurzhang/OpenNMT,jsenellart-systran/OpenNMT,OpenNMT/OpenNMT,jsenellart/OpenNMT,monsieurzhang/OpenNMT,cservan/OpenNMT_scores_0.2.0,da03/OpenNMT,jsenellart/OpenNMT,jsenellart-systran/OpenNMT,dabbler0/seq2seq-comparison
0476e3b19ebddd598d309d738696dbb048f1c4bf
MMOCoreORB/bin/scripts/managers/jedi/village/village_jedi_manager_township.lua
MMOCoreORB/bin/scripts/managers/jedi/village/village_jedi_manager_township.lua
local ObjectManager = require("managers.object.object_manager") local ScreenPlay = require("screenplays.screenplay") -- Utils. local Logger = require("utils.logger") require("utils.helpers") VillageJediManagerTownship = ScreenPlay:new { screenplayName = "VillageJediManagerTownship" } VILLAGE_PHASE_ONE = 1 VILLAGE_PHASE_TWO = 2 VILLAGE_PHASE_THREE = 3 VILLAGE_PHASE_FOUR = 4 VILLAGE_TOTAL_NUMBER_OF_PHASES = 4 local VILLAGE_PHASE_CHANGE_TIME = 120 * 1000 -- Testing value. --local VILLAGE_PHASE_CHANGE_TIME = 3 * 7 * 24 * 60 * 60 * 1000 -- Three Weeks. -- Key is the mobile name, value is the spawn parameters. VillagerMobilesPhaseOne = { quharek = {name="quharek",respawn=60, x=5373, z=78, y=-4181, header=0, cellid=0}, whip = {name="whip",respawn=60, x=5283, z=78, y=-4226, header=0, cellid=0}, captain_sarguillo = {name="captain_sarguillo",respawn=60, x=5313, z=78,y= -4161, header=0, cellid=0}, sivarra_mechaux = {name="sivarra_mechaux",respawn=60, x=5391, z=78, y=-4075, header=0, cellid=0} } VillagerMobiles = { paemos = {name="paemos",respawn=60, x=5289, z=78, y=-4149, header=240, cellid=0}, noldan = {name="noldan",respawn=60, x=5243, z=78, y=-4224, header=0, cellid=0} } -- Set the current Village Phase for the first time. function VillageJediManagerTownship.setCurrentPhaseInit() local phaseChange = hasServerEvent("VillagePhaseChange") if (phaseChange == false) then VillageJediManagerTownship.setCurrentPhase(VILLAGE_PHASE_ONE) createServerEvent(VILLAGE_PHASE_CHANGE_TIME, "VillageJediManagerTownship", "switchToNextPhase", "VillagePhaseChange") end end -- Set the current Village Phase. function VillageJediManagerTownship.setCurrentPhase(nextPhase) setQuestStatus("Village:CurrentPhase", nextPhase) end function VillageJediManagerTownship.getCurrentPhase() return getQuestStatus("Village:CurrentPhase") end function VillageJediManagerTownship:switchToNextPhase() local currentPhase = VillageJediManagerTownship.getCurrentPhase() VillageJediManagerTownship:despawnMobiles(currentPhase) currentPhase = currentPhase + 1 % VILLAGE_TOTAL_NUMBER_OF_PHASES VillageJediManagerTownship.setCurrentPhase(currentPhase) VillageJediManagerTownship:spawnMobiles(currentPhase) -- Schedule another persistent event. if (not hasServerEvent("VillagePhaseChange")) then createServerEvent(VILLAGE_PHASE_CHANGE_TIME, "VillageJediManagerTownship", "switchToNextPhase", "VillagePhaseChange") end end function VillageJediManagerTownship:start() if (isZoneEnabled("dathomir")) then Logger:log("Starting the Village Township Screenplay.", LT_INFO) VillageJediManagerTownship.setCurrentPhaseInit() VillageJediManagerTownship:spawnMobiles(VillageJediManagerTownship.getCurrentPhase()) end end -- Spawning functions. function VillageJediManagerTownship:spawnMobiles(pCurrentPhase) foreach(VillagerMobiles, function(mobile) local theSpawnedMobile = spawnMobile("dathomir", mobile.name, mobile.respawn, mobile.x, mobile.z, mobile.y, mobile.header, mobile.cellid) Logger:log("Spawning a Village NPC at " .. mobile.x .. " - " .. mobile.y, LT_INFO) ObjectManager.withSceneObject(theSpawnedMobile, function(villageMobile) writeData("village:npc:oid:" .. mobile.name, villageMobile:getObjectID()) Logger:log("Saving a Village NPC with a objectID of " .. villageMobile:getObjectID(), LT_INFO) end) end) if (pCurrentPhase == VILLAGE_PHASE_ONE) then foreach(VillagerMobilesPhaseOne, function(mobile) local theSpawnedMobile = spawnMobile("dathomir", mobile.name, mobile.respawn, mobile.x, mobile.z, mobile.y, mobile.header, mobile.cellid) Logger:log("Spawning a Village NPC at " .. mobile.x .. " - " .. mobile.y, LT_INFO) ObjectManager.withSceneObject(theSpawnedMobile, function(villageMobile) writeData("village:npc:oid:" .. mobile.name, villageMobile:getObjectID()) Logger:log("Saving a Village NPC with a objectID of " .. villageMobile:getObjectID(), LT_INFO) end) end) end end -- Despawn and cleanup all possible mobiles. function VillageJediManagerTownship:despawnMobiles(pCurrentPhase) foreach(VillagerMobiles, function(mobile) local objectID = readData("village:npc:oid:".. mobile.name) local spawnedLookup = getSceneObject(objectID) ObjectManager.withSceneObject(spawnedLookup, function(villageMobile) villageMobile:destroyObjectFromWorld() villageMobile:destroyObjectFromDatabase() deleteData("village:npc:oid:".. mobile.name) Logger:log("Despawning " .. mobile.name, LT_INFO) end) end) foreach(VillagerMobilesPhaseOne, function(mobile) local objectID = readData("village:npc:oid:".. mobile.name) local spawnedLookup = getSceneObject(objectID) ObjectManager.withSceneObject(spawnedLookup, function(villageMobile) villageMobile:destroyObjectFromWorld() villageMobile:destroyObjectFromDatabase() deleteData("village:npc:oid:".. mobile.name) Logger:log("Despawning " .. mobile.name, LT_INFO) end) end) end registerScreenPlay("VillageJediManagerTownship", true) return VillageJediManagerTownship
local ObjectManager = require("managers.object.object_manager") local ScreenPlay = require("screenplays.screenplay") -- Utils. local Logger = require("utils.logger") require("utils.helpers") VillageJediManagerTownship = ScreenPlay:new { screenplayName = "VillageJediManagerTownship" } VILLAGE_PHASE_ONE = 1 VILLAGE_PHASE_TWO = 2 VILLAGE_PHASE_THREE = 3 VILLAGE_PHASE_FOUR = 4 VILLAGE_TOTAL_NUMBER_OF_PHASES = 4 local VILLAGE_PHASE_CHANGE_TIME = 24 * 60 * 60 * 1000 -- Testing value. --local VILLAGE_PHASE_CHANGE_TIME = 3 * 7 * 24 * 60 * 60 * 1000 -- Three Weeks. -- Key is the mobile name, value is the spawn parameters. VillagerMobilesPhaseOne = { quharek = {name="quharek",respawn=60, x=5373, z=78, y=-4181, header=0, cellid=0}, whip = {name="whip",respawn=60, x=5283, z=78, y=-4226, header=0, cellid=0}, captain_sarguillo = {name="captain_sarguillo",respawn=60, x=5313, z=78,y= -4161, header=0, cellid=0}, sivarra_mechaux = {name="sivarra_mechaux",respawn=60, x=5391, z=78, y=-4075, header=0, cellid=0} } VillagerMobiles = { paemos = {name="paemos",respawn=60, x=5289, z=78, y=-4149, header=240, cellid=0}, noldan = {name="noldan",respawn=60, x=5243, z=78, y=-4224, header=0, cellid=0} } -- Set the current Village Phase for the first time. function VillageJediManagerTownship.setCurrentPhaseInit() local phaseChange = hasServerEvent("VillagePhaseChange") if (phaseChange == false) then VillageJediManagerTownship.setCurrentPhase(VILLAGE_PHASE_ONE) createServerEvent(VILLAGE_PHASE_CHANGE_TIME, "VillageJediManagerTownship", "switchToNextPhase", "VillagePhaseChange") end end -- Set the current Village Phase. function VillageJediManagerTownship.setCurrentPhase(nextPhase) setQuestStatus("Village:CurrentPhase", nextPhase) end function VillageJediManagerTownship.getCurrentPhase() return getQuestStatus("Village:CurrentPhase") end function VillageJediManagerTownship:switchToNextPhase() local currentPhase = VillageJediManagerTownship.getCurrentPhase() VillageJediManagerTownship:despawnMobiles(currentPhase) currentPhase = currentPhase + 1 if currentPhase > VILLAGE_TOTAL_NUMBER_OF_PHASES then currentPhase = 1 end VillageJediManagerTownship.setCurrentPhase(currentPhase) VillageJediManagerTownship:spawnMobiles(currentPhase, false) Logger:log("Switching village phase to " .. currentPhase, LT_INFO) -- Schedule another persistent event. if (not hasServerEvent("VillagePhaseChange")) then createServerEvent(VILLAGE_PHASE_CHANGE_TIME, "VillageJediManagerTownship", "switchToNextPhase", "VillagePhaseChange") end end function VillageJediManagerTownship:start() if (isZoneEnabled("dathomir")) then Logger:log("Starting the Village Township Screenplay.", LT_INFO) VillageJediManagerTownship.setCurrentPhaseInit() VillageJediManagerTownship:spawnMobiles(VillageJediManagerTownship.getCurrentPhase(), true) end end -- Spawning functions. function VillageJediManagerTownship:spawnMobiles(pCurrentPhase, spawnStaticMobs) if (spawnStaticMobs == true) then foreach(VillagerMobiles, function(mobile) local theSpawnedMobile = spawnMobile("dathomir", mobile.name, mobile.respawn, mobile.x, mobile.z, mobile.y, mobile.header, mobile.cellid) Logger:log("Spawning a Village Static NPC at " .. mobile.x .. " - " .. mobile.y, LT_INFO) ObjectManager.withSceneObject(theSpawnedMobile, function(villageMobile) writeData("village:npc:oid:" .. mobile.name, villageMobile:getObjectID()) Logger:log("Saving a Village Static NPC with a objectID of " .. villageMobile:getObjectID(), LT_INFO) end) end) end if (pCurrentPhase == VILLAGE_PHASE_ONE) then foreach(VillagerMobilesPhaseOne, function(mobile) local theSpawnedMobile = spawnMobile("dathomir", mobile.name, mobile.respawn, mobile.x, mobile.z, mobile.y, mobile.header, mobile.cellid) Logger:log("Spawning a Village Phase One NPC at " .. mobile.x .. " - " .. mobile.y, LT_INFO) ObjectManager.withSceneObject(theSpawnedMobile, function(villageMobile) writeData("village:npc:oid:" .. mobile.name, villageMobile:getObjectID()) Logger:log("Saving a Village Phase One NPC with a objectID of " .. villageMobile:getObjectID(), LT_INFO) end) end) end end -- Despawn and cleanup all possible mobiles. function VillageJediManagerTownship:despawnMobiles(pCurrentPhase) foreach(VillagerMobilesPhaseOne, function(mobile) local objectID = readData("village:npc:oid:" .. mobile.name) local spawnedLookup = getSceneObject(objectID) ObjectManager.withSceneObject(spawnedLookup, function(villageMobile) villageMobile:destroyObjectFromWorld() deleteData("village:npc:oid:" .. mobile.name) Logger:log("Despawning " .. mobile.name, LT_INFO) end) end) end registerScreenPlay("VillageJediManagerTownship", true) return VillageJediManagerTownship
[Fixed] village phase changing [Changed] frequency of village phase change [Changed] static village mobs no longer despawn and respawn during village phase change
[Fixed] village phase changing [Changed] frequency of village phase change [Changed] static village mobs no longer despawn and respawn during village phase change Change-Id: I843114baf53fbef363fe212975bb0e70996f3f39
Lua
agpl-3.0
Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo
0aaf386b39c3f199542e3d5eae4263b55d4b68ca
mod_webpresence/mod_webpresence.lua
mod_webpresence/mod_webpresence.lua
module:depends("http"); local jid_split = require "util.jid".prepped_split; local b64 = require "util.encodings".base64.encode; local sha1 = require "util.hashes".sha1; local stanza = require "util.stanza".stanza; local json = require "util.json".encode_ordered; local function require_resource(name) local icon_path = module:get_option_string("presence_icons", "icons"); local f, err = module:load_resource(icon_path.."/"..name); if f then return f:read("*a"); end module:log("warn", "Failed to open image file %s", icon_path..name); return ""; end local statuses = { online = {}, away = {}, xa = {}, dnd = {}, chat = {}, offline = {} }; local function handle_request(event, path) local status, message; local jid, type = path:match("([^/]+)/?(.*)$"); if jid then local user, host = jid_split(jid); if host and not user then user, host = host, event.request.headers.host; if host then host = host:gsub(":%d+$", ""); end end if user and host then local user_sessions = hosts[host] and hosts[host].sessions[user]; if user_sessions then status = user_sessions.top_resources[1]; if status and status.presence then message = status.presence:child_with_name("status"); status = status.presence:child_with_name("show"); if not status then status = "online"; else status = status:get_text(); end if message then message = message:get_text(); end end end end end status = status or "offline"; if type == "" then type = "image" end; statuses[status].image = function() return { status_code = 200, headers = { content_type = "image/png" }, body = require_resource("status_"..status..".png") }; end; statuses[status].html = function() local jid_hash = sha1(jid, true); return { status_code = 200, headers = { content_type = "text/html" }, body = [[<!DOCTYPE html>]].. tostring( stanza("html") :tag("head") :tag("title"):text("XMPP Status Page for "..jid):up():up() :tag("body") :tag("div", { id = jid_hash.."_status", class = "xmpp_status" }) :tag("img", { id = jid_hash.."_img", class = "xmpp_status_image xmpp_status_"..status, src = "data:image/png;base64,"..b64(require_resource("status_"..status..".png")) }):up() :tag("span", { id = jid_hash.."_status_name", class = "xmpp_status_name" }) :text("\194\160"..status):up() :tag("span", { id = jid_hash.."_status_message", class = "xmpp_status_message" }) :text(message and "\194\160"..message.."" or "") ) }; end; statuses[status].text = function() return { status_code = 200, headers = { content_type = "text/plain" }, body = status }; end; statuses[status].message = function() return { status_code = 200, headers = { content_type = "text/plain" }, body = (message and message or "") }; end; statuses[status].json = function() return { status_code = 200, headers = { content_type = "application/json" }, body = json({ jid = jid, show = status, status = (message and message or "null") }) }; end; statuses[status].xml = function() return { status_code = 200, headers = { content_type = "application/xml" }, body = [[<?xml version="1.0" encoding="utf-8"?>]].. tostring( stanza("result") :tag("jid"):text(jid):up() :tag("show"):text(status):up() :tag("status"):text(message) ) }; end return statuses[status][type](); end module:provides("http", { default_path = "/status"; route = { ["GET /*"] = handle_request; }; });
module:depends("http"); local jid_split = require "util.jid".prepped_split; local b64 = require "util.encodings".base64.encode; local sha1 = require "util.hashes".sha1; local stanza = require "util.stanza".stanza; local json = require "util.json".encode_ordered; local function require_resource(name) local icon_path = module:get_option_string("presence_icons", "icons"); local f, err = module:load_resource(icon_path.."/"..name); if f then return f:read("*a"); end module:log("warn", "Failed to open image file %s", icon_path..name); return ""; end local statuses = { online = {}, away = {}, xa = {}, dnd = {}, chat = {}, offline = {} }; local function handle_request(event, path) local status, message; local jid, type = path:match("([^/]+)/?(.*)$"); if jid then local user, host = jid_split(jid); if host and not user then user, host = host, event.request.headers.host; if host then host = host:gsub(":%d+$", ""); end end if user and host then local user_sessions = hosts[host] and hosts[host].sessions[user]; if user_sessions then status = user_sessions.top_resources[1]; if status and status.presence then message = status.presence:child_with_name("status"); status = status.presence:child_with_name("show"); if not status then status = "online"; else status = status:get_text(); end if message then message = message:get_text(); end end end end end status = status or "offline"; statuses[status].image = function() return { status_code = 200, headers = { content_type = "image/png" }, body = require_resource("status_"..status..".png") }; end; statuses[status].html = function() local jid_hash = sha1(jid, true); return { status_code = 200, headers = { content_type = "text/html" }, body = [[<!DOCTYPE html>]].. tostring( stanza("html") :tag("head") :tag("title"):text("XMPP Status Page for "..jid):up():up() :tag("body") :tag("div", { id = jid_hash.."_status", class = "xmpp_status" }) :tag("img", { id = jid_hash.."_img", class = "xmpp_status_image xmpp_status_"..status, src = "data:image/png;base64,"..b64(require_resource("status_"..status..".png")) }):up() :tag("span", { id = jid_hash.."_status_name", class = "xmpp_status_name" }) :text("\194\160"..status):up() :tag("span", { id = jid_hash.."_status_message", class = "xmpp_status_message" }) :text(message and "\194\160"..message.."" or "") ) }; end; statuses[status].text = function() return { status_code = 200, headers = { content_type = "text/plain" }, body = status }; end; statuses[status].message = function() return { status_code = 200, headers = { content_type = "text/plain" }, body = (message and message or "") }; end; statuses[status].json = function() return { status_code = 200, headers = { content_type = "application/json" }, body = json({ jid = jid, show = status, status = (message and message or "null") }) }; end; statuses[status].xml = function() return { status_code = 200, headers = { content_type = "application/xml" }, body = [[<?xml version="1.0" encoding="utf-8"?>]].. tostring( stanza("result") :tag("jid"):text(jid):up() :tag("show"):text(status):up() :tag("status"):text(message) ) }; end if ((type == "") or (not statuses[status][type])) then type = "image" end; return statuses[status][type](); end module:provides("http", { default_path = "/status"; route = { ["GET /*"] = handle_request; }; });
mod_webpresence: fixed render-type handling (thanks to biszkopcik and Zash)
mod_webpresence: fixed render-type handling (thanks to biszkopcik and Zash)
Lua
mit
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
f4cf7efaa69c6a08fe469741c1f4f1c7334727cd
mod_register_url/mod_register_url.lua
mod_register_url/mod_register_url.lua
-- Registration Redirect module for Prosody -- -- Redirects IP addresses not in the whitelist to a web page to complete the registration. local st = require "util.stanza"; function reg_redirect(event) local ip_wl = module:get_option("registration_whitelist") or { "127.0.0.1" }; local url = module:get_option("registration_url"); local no_wl = module:get_option("no_registration_whitelist") or false; if type(no_wl) ~= boolean then no_wl = false end local test_ip = false; if not no_wl then for i,ip in ipairs(ip_wl) do if event.origin.ip == ip then test_ip = true; end break; end end if not test_ip and url ~= nil or no_wl and url ~= nil then local reply = st.reply(event.stanza); reply:tag("query", {xmlns = "jabber:iq:register"}) :tag("instructions"):text("Please visit "..url.." to register an account on this server."):up() :tag("x", {xmlns = "jabber:x:oob"}):up() :tag("url"):text(url):up(); event.origin.send(reply); return true; end end module:hook("stanza/iq/jabber:iq:register:query", reg_redirect, 10);
-- Registration Redirect module for Prosody -- -- Redirects IP addresses not in the whitelist to a web page to complete the registration. local st = require "util.stanza"; function reg_redirect(event) local ip_wl = module:get_option("registration_whitelist") or { "127.0.0.1" }; local url = module:get_option("registration_url"); local no_wl = module:get_option_boolean("no_registration_whitelist", false); local test_ip = false; if not no_wl then for i,ip in ipairs(ip_wl) do if event.origin.ip == ip then test_ip = true; end break; end end if not test_ip and url ~= nil or no_wl and url ~= nil then local reply = st.reply(event.stanza); reply:tag("query", {xmlns = "jabber:iq:register"}) :tag("instructions"):text("Please visit "..url.." to register an account on this server."):up() :tag("x", {xmlns = "jabber:x:oob"}):up() :tag("url"):text(url):up(); event.origin.send(reply); return true; end end module:hook("stanza/iq/jabber:iq:register:query", reg_redirect, 10);
mod_register_url: minor fix.
mod_register_url: minor fix.
Lua
mit
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
62e0a6b927b2bc88412ada235d9e09654495bf9e
MMOCoreORB/bin/scripts/object/tangible/wearables/apron/apron_porcellus.lua
MMOCoreORB/bin/scripts/object/tangible/wearables/apron/apron_porcellus.lua
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_tangible_wearables_apron_apron_porcellus = object_tangible_wearables_apron_shared_apron_porcellus:new { playerRaces = { "object/creature/player/bothan_male.iff", "object/creature/player/bothan_female.iff", "object/creature/player/human_male.iff", "object/creature/player/human_female.iff", "object/creature/player/moncal_male.iff", "object/creature/player/moncal_female.iff", "object/creature/player/rodian_male.iff", "object/creature/player/rodian_female.iff", "object/creature/player/sullustan_male.iff", "object/creature/player/sullustan_female.iff", "object/creature/player/trandoshan_male.iff", "object/creature/player/trandoshan_female.iff", "object/creature/player/twilek_male.iff", "object/creature/player/twilek_female.iff", "object/creature/player/zabrak_male.iff", "object/creature/player/zabrak_female.iff", "object/mobile/vendor/aqualish_female.iff", "object/mobile/vendor/aqualish_male.iff", "object/mobile/vendor/bith_female.iff", "object/mobile/vendor/bith_male.iff", "object/mobile/vendor/bothan_female.iff", "object/mobile/vendor/bothan_male.iff", "object/mobile/vendor/devaronian_male.iff", "object/mobile/vendor/gran_male.iff", "object/mobile/vendor/human_female.iff", "object/mobile/vendor/human_male.iff", "object/mobile/vendor/ishi_tib_male.iff", "object/mobile/vendor/moncal_female.iff", "object/mobile/vendor/moncal_male.iff", "object/mobile/vendor/nikto_male.iff", "object/mobile/vendor/quarren_male.iff", "object/mobile/vendor/rodian_female.iff", "object/mobile/vendor/rodian_male.iff", "object/mobile/vendor/sullustan_female.iff", "object/mobile/vendor/sullustan_male.iff", "object/mobile/vendor/trandoshan_female.iff", "object/mobile/vendor/trandoshan_male.iff", "object/mobile/vendor/twilek_female.iff", "object/mobile/vendor/twilek_male.iff", "object/mobile/vendor/weequay_male.iff", "object/mobile/vendor/wookiee_female.iff", "object/mobile/vendor/wookiee_male.iff", "object/mobile/vendor/zabrak_female.iff", "object/mobile/vendor/zabrak_male.iff", }, } ObjectTemplates:addTemplate(object_tangible_wearables_apron_apron_porcellus, "object/tangible/wearables/apron/apron_porcellus.iff")
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_tangible_wearables_apron_apron_porcellus = object_tangible_wearables_apron_shared_apron_porcellus:new { playerRaces = { "object/creature/player/bothan_male.iff", "object/creature/player/bothan_female.iff", "object/creature/player/human_male.iff", "object/creature/player/human_female.iff", "object/creature/player/ithorian_male.iff", "object/creature/player/ithorian_female.iff", "object/creature/player/moncal_male.iff", "object/creature/player/moncal_female.iff", "object/creature/player/rodian_male.iff", "object/creature/player/rodian_female.iff", "object/creature/player/sullustan_male.iff", "object/creature/player/sullustan_female.iff", "object/creature/player/trandoshan_male.iff", "object/creature/player/trandoshan_female.iff", "object/creature/player/twilek_male.iff", "object/creature/player/twilek_female.iff", "object/creature/player/wookiee_male.iff", "object/creature/player/wookiee_female.iff", "object/creature/player/zabrak_male.iff", "object/creature/player/zabrak_female.iff", "object/mobile/vendor/aqualish_female.iff", "object/mobile/vendor/aqualish_male.iff", "object/mobile/vendor/bith_female.iff", "object/mobile/vendor/bith_male.iff", "object/mobile/vendor/bothan_female.iff", "object/mobile/vendor/bothan_male.iff", "object/mobile/vendor/devaronian_male.iff", "object/mobile/vendor/gran_male.iff", "object/mobile/vendor/human_female.iff", "object/mobile/vendor/human_male.iff", "object/mobile/vendor/ishi_tib_male.iff", "object/mobile/vendor/moncal_female.iff", "object/mobile/vendor/moncal_male.iff", "object/mobile/vendor/nikto_male.iff", "object/mobile/vendor/quarren_male.iff", "object/mobile/vendor/rodian_female.iff", "object/mobile/vendor/rodian_male.iff", "object/mobile/vendor/sullustan_female.iff", "object/mobile/vendor/sullustan_male.iff", "object/mobile/vendor/trandoshan_female.iff", "object/mobile/vendor/trandoshan_male.iff", "object/mobile/vendor/twilek_female.iff", "object/mobile/vendor/twilek_male.iff", "object/mobile/vendor/weequay_male.iff", "object/mobile/vendor/wookiee_female.iff", "object/mobile/vendor/wookiee_male.iff", "object/mobile/vendor/zabrak_female.iff", "object/mobile/vendor/zabrak_male.iff", }, } ObjectTemplates:addTemplate(object_tangible_wearables_apron_apron_porcellus, "object/tangible/wearables/apron/apron_porcellus.iff")
[fixed] Crafting Apron quest reward now able to be worn by Ithorians & Wookiees, Mantis 6238
[fixed] Crafting Apron quest reward now able to be worn by Ithorians & Wookiees, Mantis 6238 Change-Id: I0d972ec5a434ccd2c21385bdd6b8a4afb1fbc7d2
Lua
agpl-3.0
Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo
7750c760ecc8e4bbd1f16aca94b0e5628cfead3b
lua/starfall/libs_sh/hook.lua
lua/starfall/libs_sh/hook.lua
------------------------------------------------------------------------------- -- Hook library ------------------------------------------------------------------------------- --- Deals with hooks -- @shared local hook_library, _ = SF.Libraries.Register("hook") local registered_instances = {} --- Sets a hook function function hook_library.add(hookname, name, func) SF.CheckType(hookname,"string") SF.CheckType(name,"string") if func then SF.CheckType(func,"function") else return end local inst = SF.instance local hooks = inst.hooks[hookname:lower()] if not hooks then hooks = {} inst.hooks[hookname:lower()] = hooks end hooks[name] = func registered_instances[inst] = true end --- Run a hook -- @shared -- @param hookname The hook name -- @param ... arguments function hook_library.run(hookname, ...) SF.CheckType(hookname,"string") local instance = SF.instance local lower = hookname:lower() if instance.hooks[lower] then for k,v in pairs( instance.hooks[lower] ) do local ok, tbl, traceback = instance:runWithOps(v, ...)--instance:runFunction( v ) if not ok and instance.runOnError then instance.runOnError( tbl[1] ) hook_library.remove( hookname, k ) elseif next(tbl) ~= nil then return unpack( tbl ) end end end end --- Remove a hook -- @shared -- @param hookname The hook name -- @param name The unique name for this hook function hook_library.remove( hookname, name ) SF.CheckType(hookname,"string") SF.CheckType(name,"string") local instance = SF.instance local lower = hookname:lower() if instance.hooks[lower] then instance.hooks[lower][name] = nil if not next(instance.hooks[lower]) then instance.hooks[lower] = nil end end if not next(instance.hooks) then registered_instances[instance] = nil end end SF.Libraries.AddHook("deinitialize",function(instance) registered_instances[instance] = nil end) SF.Libraries.AddHook("cleanup",function(instance,name,func,err) if name == "_runFunction" and err == true then registered_instances[instance] = nil instance.hooks = {} end end) --[[ local blocked_types = { PhysObj = true, NPC = true, } local function wrap( value ) if type(value) == "table" then return setmetatable( {}, {__metatable = "table", __index = value, __newindex = function() end} ) elseif blocked_types[type(value)] then return nil else return SF.WrapObject( value ) or value end end -- Helper function for hookAdd local function wrapArguments( ... ) local t = {...} return wrap(t[1]), wrap(t[2]), wrap(t[3]), wrap(t[4]), wrap(t[5]), wrap(t[6]) end ]] local wrapArguments = SF.Sanitize --local run = SF.RunScriptHook local function run( hookname, customfunc, ... ) for instance,_ in pairs( registered_instances ) do if instance.hooks[hookname] then for name, func in pairs( instance.hooks[hookname] ) do local ok, ret = instance:runFunctionT( func, ... ) if ok and customfunc then return customfunc( instance, ret ) end end end end end local hooks = {} --- Add a GMod hook so that SF gets access to it -- @shared -- @param hookname The hook name. In-SF hookname will be lowercased -- @param customfunc Optional custom function function SF.hookAdd( hookname, customfunc ) hooks[#hooks+1] = hookname local lower = hookname:lower() hook.Add( hookname, "SF_" .. hookname, function(...) return run( lower, customfunc, wrapArguments( ... ) ) end) end --- Gets a list of all available hooks -- @shared function hook_library.getList() return setmetatable({},{__metatable = "table", __index = hooks, __newindex = function() end}) end local add = SF.hookAdd if SERVER then -- Server hooks add( "GravGunOnPickedUp" ) add( "GravGunOnDropped" ) add( "OnPhysgunFreeze" ) add( "OnPhysgunReload" ) add( "PlayerDeath" ) add( "PlayerDisconnected" ) add( "PlayerInitialSpawn" ) add( "PlayerSpawn" ) add( "PlayerLeaveVehicle" ) add( "PlayerSay", function( instance, args ) if args then return args[1] end end ) add( "PlayerSpray" ) add( "PlayerUse" ) add( "PlayerSwitchFlashlight" ) else -- Client hooks -- todo end -- Shared hooks -- Player hooks add( "PlayerHurt" ) add( "PlayerNoClip" ) add( "KeyPress" ) add( "KeyRelease" ) add( "GravGunPunt" ) add( "PhysgunPickup" ) add( "PhysgunDrop" ) -- Entity hooks add( "OnEntityCreated" ) add( "EntityRemoved" ) -- Other add( "EndEntityDriving" ) add( "StartEntityDriving" )
------------------------------------------------------------------------------- -- Hook library ------------------------------------------------------------------------------- --- Deals with hooks -- @shared local hook_library, _ = SF.Libraries.Register("hook") local registered_instances = {} --- Sets a hook function function hook_library.add(hookname, name, func) SF.CheckType(hookname,"string") SF.CheckType(name,"string") if func then SF.CheckType(func,"function") else return end local inst = SF.instance local hooks = inst.hooks[hookname:lower()] if not hooks then hooks = {} inst.hooks[hookname:lower()] = hooks end hooks[name] = func registered_instances[inst] = true end --- Run a hook -- @shared -- @param hookname The hook name -- @param ... arguments function hook_library.run(hookname, ...) SF.CheckType(hookname,"string") local instance = SF.instance local lower = hookname:lower() if instance.hooks[lower] then for k,v in pairs( instance.hooks[lower] ) do local ok, tbl, traceback = instance:runWithOps(v, ...)--instance:runFunction( v ) if not ok and instance.runOnError then instance.runOnError( tbl[1] ) hook_library.remove( hookname, k ) elseif next(tbl) ~= nil then return unpack( tbl ) end end end end --- Remove a hook -- @shared -- @param hookname The hook name -- @param name The unique name for this hook function hook_library.remove( hookname, name ) SF.CheckType(hookname,"string") SF.CheckType(name,"string") local instance = SF.instance local lower = hookname:lower() if instance.hooks[lower] then instance.hooks[lower][name] = nil if not next(instance.hooks[lower]) then instance.hooks[lower] = nil end end if not next(instance.hooks) then registered_instances[instance] = nil end end SF.Libraries.AddHook("deinitialize",function(instance) registered_instances[instance] = nil end) SF.Libraries.AddHook("cleanup",function(instance,name,func,err) if name == "_runFunction" and err == true then registered_instances[instance] = nil instance.hooks = {} end end) --[[ local blocked_types = { PhysObj = true, NPC = true, } local function wrap( value ) if type(value) == "table" then return setmetatable( {}, {__metatable = "table", __index = value, __newindex = function() end} ) elseif blocked_types[type(value)] then return nil else return SF.WrapObject( value ) or value end end -- Helper function for hookAdd local function wrapArguments( ... ) local t = {...} return wrap(t[1]), wrap(t[2]), wrap(t[3]), wrap(t[4]), wrap(t[5]), wrap(t[6]) end ]] local wrapArguments = SF.Sanitize --local run = SF.RunScriptHook local function run( hookname, customfunc, ... ) for instance,_ in pairs( registered_instances ) do if instance.hooks[hookname] then for name, func in pairs( instance.hooks[hookname] ) do local ok, ret = instance:runFunctionT( func, ... ) if ok and customfunc then local a,b,c,d,e,f,g,h = customfunc( instance, ret ) if a ~= nil then return a,b,c,d,e,f,g,h end end end end end end local hooks = {} --- Add a GMod hook so that SF gets access to it -- @shared -- @param hookname The hook name. In-SF hookname will be lowercased -- @param customfunc Optional custom function function SF.hookAdd( hookname, customfunc ) hooks[#hooks+1] = hookname local lower = hookname:lower() hook.Add( hookname, "SF_" .. hookname, function(...) return run( lower, customfunc, wrapArguments( ... ) ) end) end --- Gets a list of all available hooks -- @shared function hook_library.getList() return setmetatable({},{__metatable = "table", __index = hooks, __newindex = function() end}) end local add = SF.hookAdd if SERVER then -- Server hooks add( "GravGunOnPickedUp" ) add( "GravGunOnDropped" ) add( "OnPhysgunFreeze" ) add( "OnPhysgunReload" ) add( "PlayerDeath" ) add( "PlayerDisconnected" ) add( "PlayerInitialSpawn" ) add( "PlayerSpawn" ) add( "PlayerLeaveVehicle" ) add( "PlayerSay", function( instance, args ) if args then return args[1] end end ) add( "PlayerSpray" ) add( "PlayerUse" ) add( "PlayerSwitchFlashlight" ) else -- Client hooks -- todo end -- Shared hooks -- Player hooks add( "PlayerHurt" ) add( "PlayerNoClip" ) add( "KeyPress" ) add( "KeyRelease" ) add( "GravGunPunt" ) add( "PhysgunPickup" ) add( "PhysgunDrop" ) -- Entity hooks add( "OnEntityCreated" ) add( "EntityRemoved" ) -- Other add( "EndEntityDriving" ) add( "StartEntityDriving" )
fixed hooks that could return something always returning something
fixed hooks that could return something always returning something which was preventing other hooks of the same type from being called
Lua
bsd-3-clause
Ingenious-Gaming/Starfall,Xandaros/Starfall,Xandaros/Starfall,Jazzelhawk/Starfall,Ingenious-Gaming/Starfall,INPStarfall/Starfall,Jazzelhawk/Starfall,INPStarfall/Starfall
68832dc6f28cbc10d9861d8202382689984e06ef
src/builtin/macros.lua
src/builtin/macros.lua
-- Extra macros for automating proof construction using Lua. -- This macro creates the syntax-sugar -- name bindings ',' expr -- For a function f with signature -- f : ... (A : Type) ... (Pi x : A, ...) -- -- farity is the arity of f -- typepos is the position of (A : Type) argument -- lambdapos is the position of the (Pi x : A, ...) argument -- -- Example: suppose we invoke -- -- binder_macro("for", Const("ForallIntro"), 3, 1, 3) -- -- Then, the macro expression -- -- for x y : Int, H x y -- -- produces the expression -- -- ForallIntro Int _ (fun x : Int, ForallIntro Int _ (fun y : Int, H x y)) -- -- The _ are placeholders (aka) holes that will be filled by the Lean -- elaborator. function binder_macro(name, f, farity, typepos, lambdapos) local precedence = 0 macro(name, { macro_arg.Parameters, macro_arg.Comma, macro_arg.Expr }, function (env, bindings, body) local r = body for i = #bindings, 1, -1 do local bname = bindings[i][1] local btype = bindings[i][2] local args = {} args[#args + 1] = f for j = 1, farity, 1 do if j == typepos then args[#args + 1] = btype elseif j == lambdapos then args[#args + 1] = fun(bname, btype, r) else args[#args + 1] = mk_placeholder() end end r = mk_app(unpack(args)) end return r end, precedence) end -- The following macro is used to create nary versions of operators such as MP and ForallElim. -- Example: suppose we invoke -- -- nary_macro("mp", Const("MP"), 4) -- -- Then, the macro expression -- -- mp Foo H1 H2 H3 -- -- produces the expression -- -- (MP (MP (MP Foo H1) H2) H3) function nary_macro(name, f, farity) local bin_app = function(e1, e2) local args = {} args[#args + 1] = f for i = 1, farity - 2, 1 do args[#args + 1] = mk_placeholder() end args[#args + 1] = e1 args[#args + 1] = e2 return mk_app(unpack(args)) end macro(name, { macro_arg.Expr, macro_arg.Expr, macro_arg.Exprs }, function (env, e1, e2, rest) local r = bin_app(e1, e2) for i = 1, #rest do r = bin_app(r, rest[i]) end return r end) end binder_macro("take", Const({"forall", "intro"}), 3, 1, 3) binder_macro("assume", Const("discharge"), 3, 1, 3) nary_macro("instantiate", Const({"forall", "elim"}), 4) -- ExistsElim syntax-sugar -- Example: -- Assume we have the following two axioms -- Axiom Ax1: exists x y, P x y -- Axiom Ax2: forall x y, not P x y -- Now, the following macro expression -- obtain (a b : Nat) (H : P a b) from Ax1, -- have false : absurd H (instantiate Ax2 a b) -- expands to -- exists::elim Ax1 -- (fun (a : Nat) (Haux : ...), -- exists::elim Haux -- (fun (b : Na) (H : P a b), -- have false : absurd H (instantiate Ax2 a b) macro("obtain", { macro_arg.Parameters, macro_arg.Comma, macro_arg.Id, macro_arg.Expr, macro_arg.Comma, macro_arg.Expr }, function (env, bindings, fromid, exPr, body) local n = #bindings if n < 2 then error("invalid 'obtain' expression at least two bindings must be provided") end if fromid ~= name("from") then error("invalid 'obtain' expression, 'from' keyword expected, got '" .. tostring(fromid) .. "'") end local exElim = mk_constant({"exists", "elim"}) local H_name = bindings[n][1] local H_type = bindings[n][2] local a_name = bindings[n-1][1] local a_type = bindings[n-1][2] for i = n - 2, 1, -1 do local Haux = name("obtain", "macro", "H", i) body = mk_app(exElim, mk_placeholder(), mk_placeholder(), mk_placeholder(), mk_constant(Haux), fun(a_name, a_type, fun(H_name, H_type, body))) H_name = Haux H_type = mk_placeholder() a_name = bindings[i][1] a_type = bindings[i][2] -- We added a new binding, so we must lift free vars body = body:lift_free_vars(0, 1) end -- exPr occurs after the bindings, so it is in the context of them. -- However, this is not the case for ExistsElim. -- So, we must lower the free variables there exPr = exPr:lower_free_vars(n, n) return mk_app(exElim, mk_placeholder(), mk_placeholder(), mk_placeholder(), exPr, fun(a_name, a_type, fun(H_name, H_type, body))) end, 0)
-- Extra macros for automating proof construction using Lua. -- This macro creates the syntax-sugar -- name bindings ',' expr -- For a function f with signature -- f : ... (A : Type) ... (Pi x : A, ...) -- -- farity is the arity of f -- typepos is the position of (A : Type) argument -- lambdapos is the position of the (Pi x : A, ...) argument -- -- Example: suppose we invoke -- -- binder_macro("take", Const({"forall", "intro"}), 3, 1, 3) -- -- Then, the macro expression -- -- take x y : Int, H x y -- -- produces the expression -- -- forall::intro Int _ (fun x : Int, forall::intro Int _ (fun y : Int, H x y)) -- -- The _ are placeholders (aka) holes that will be filled by the Lean -- elaborator. function binder_macro(name, f, farity, typepos, lambdapos) local precedence = 0 macro(name, { macro_arg.Parameters, macro_arg.Comma, macro_arg.Expr }, function (env, bindings, body) local r = body for i = #bindings, 1, -1 do local bname = bindings[i][1] local btype = bindings[i][2] local args = {} args[#args + 1] = f for j = 1, farity, 1 do if j == typepos then args[#args + 1] = btype elseif j == lambdapos then args[#args + 1] = fun(bname, btype, r) else args[#args + 1] = mk_placeholder() end end r = mk_app(unpack(args)) end return r end, precedence) end -- The following macro is used to create nary versions of operators such as mp. -- Example: suppose we invoke -- -- nary_macro("mp'", Const("mp"), 4) -- -- Then, the macro expression -- -- mp' Foo H1 H2 H3 -- -- produces the expression -- -- (mp (mp (mp Foo H1) H2) H3) function nary_macro(name, f, farity) local bin_app = function(e1, e2) local args = {} args[#args + 1] = f for i = 1, farity - 2, 1 do args[#args + 1] = mk_placeholder() end args[#args + 1] = e1 args[#args + 1] = e2 return mk_app(unpack(args)) end macro(name, { macro_arg.Expr, macro_arg.Expr, macro_arg.Exprs }, function (env, e1, e2, rest) local r = bin_app(e1, e2) for i = 1, #rest do r = bin_app(r, rest[i]) end return r end) end binder_macro("take", Const({"forall", "intro"}), 3, 1, 3) binder_macro("assume", Const("discharge"), 3, 1, 3) nary_macro("instantiate", Const({"forall", "elim"}), 4) -- ExistsElim syntax-sugar -- Example: -- Assume we have the following two axioms -- Axiom Ax1: exists x y, P x y -- Axiom Ax2: forall x y, not P x y -- Now, the following macro expression -- obtain (a b : Nat) (H : P a b) from Ax1, -- have false : absurd H (instantiate Ax2 a b) -- expands to -- exists::elim Ax1 -- (fun (a : Nat) (Haux : ...), -- exists::elim Haux -- (fun (b : Na) (H : P a b), -- have false : absurd H (instantiate Ax2 a b) macro("obtain", { macro_arg.Parameters, macro_arg.Comma, macro_arg.Id, macro_arg.Expr, macro_arg.Comma, macro_arg.Expr }, function (env, bindings, fromid, exPr, body) local n = #bindings if n < 2 then error("invalid 'obtain' expression at least two bindings must be provided") end if fromid ~= name("from") then error("invalid 'obtain' expression, 'from' keyword expected, got '" .. tostring(fromid) .. "'") end local exElim = mk_constant({"exists", "elim"}) local H_name = bindings[n][1] local H_type = bindings[n][2] local a_name = bindings[n-1][1] local a_type = bindings[n-1][2] for i = n - 2, 1, -1 do local Haux = name("obtain", "macro", "H", i) body = mk_app(exElim, mk_placeholder(), mk_placeholder(), mk_placeholder(), mk_constant(Haux), fun(a_name, a_type, fun(H_name, H_type, body))) H_name = Haux H_type = mk_placeholder() a_name = bindings[i][1] a_type = bindings[i][2] -- We added a new binding, so we must lift free vars body = body:lift_free_vars(0, 1) end -- exPr occurs after the bindings, so it is in the context of them. -- However, this is not the case for ExistsElim. -- So, we must lower the free variables there exPr = exPr:lower_free_vars(n, n) return mk_app(exElim, mk_placeholder(), mk_placeholder(), mk_placeholder(), exPr, fun(a_name, a_type, fun(H_name, H_type, body))) end, 0)
fix(builtin/macros): comments
fix(builtin/macros): comments Signed-off-by: Leonardo de Moura <7610bae85f2b530654cc716772f1fe653373e892@microsoft.com>
Lua
apache-2.0
dselsam/lean,soonhokong/lean-osx,javra/lean,rlewis1988/lean,fpvandoorn/lean,soonhokong/travis_test,htzh/lean,leanprover/lean,fgdorais/lean,fgdorais/lean,soonhokong/lean-windows,leodemoura/lean,digama0/lean,johoelzl/lean,levnach/lean,leodemoura/lean,leanprover-community/lean,rlewis1988/lean,fpvandoorn/lean,codyroux/lean0.1,c-cube/lean,UlrikBuchholtz/lean,avigad/lean,leodemoura/lean,leanprover-community/lean,codyroux/lean0.1,sp3ctum/lean,Kha/lean,javra/lean,htzh/lean,fpvandoorn/lean,eigengrau/lean,leodemoura/lean,johoelzl/lean,johoelzl/lean,fpvandoorn/lean,htzh/lean,avigad/lean,fpvandoorn/lean2,leodemoura/lean,codyroux/lean0.1,rlewis1988/lean,eigengrau/lean,htzh/lean,javra/lean,digama0/lean,dselsam/lean,sp3ctum/lean,fpvandoorn/lean2,fpvandoorn/lean,leanprover-community/lean,c-cube/lean,fpvandoorn/lean2,leanprover/lean,Kha/lean,sp3ctum/lean,Kha/lean,dselsam/lean,fgdorais/lean,soonhokong/lean-osx,soonhokong/lean,johoelzl/lean,sp3ctum/lean,Kha/lean,dselsam/lean,sp3ctum/lean,soonhokong/lean,soonhokong/lean-windows,levnach/lean,fpvandoorn/lean2,javra/lean,c-cube/lean,leanprover-community/lean,soonhokong/lean-osx,dselsam/lean,leanprover/lean,digama0/lean,soonhokong/lean-osx,soonhokong/travis_test,fgdorais/lean,fgdorais/lean,fpvandoorn/lean,eigengrau/lean,UlrikBuchholtz/lean,rlewis1988/lean,eigengrau/lean,soonhokong/lean,fgdorais/lean,levnach/lean,soonhokong/lean-osx,leanprover-community/lean,Kha/lean,digama0/lean,avigad/lean,UlrikBuchholtz/lean,johoelzl/lean,digama0/lean,soonhokong/lean,rlewis1988/lean,leanprover-community/lean,levnach/lean,avigad/lean,UlrikBuchholtz/lean,soonhokong/travis_test,rlewis1988/lean,soonhokong/lean,avigad/lean,Kha/lean,htzh/lean,soonhokong/travis_test,leanprover/lean,c-cube/lean,codyroux/lean0.1,leanprover/lean,c-cube/lean,javra/lean,soonhokong/lean-windows,UlrikBuchholtz/lean,fpvandoorn/lean2,dselsam/lean,avigad/lean,eigengrau/lean,digama0/lean,leanprover/lean,soonhokong/lean-windows,soonhokong/lean-windows,levnach/lean,leodemoura/lean,johoelzl/lean
067f791794d7a430eba1c597bee0d4d8ed743815
app/spacer/run.lua
app/spacer/run.lua
local json = require "cjson" local routes = require "routes" local env = os.getenv('SPACER_ENV') ngx.req.read_body() local path = ngx.var.uri local method = ngx.var.request_method local module = nil for i, route in ipairs(routes) do if route[1] == method and route[2] == path then module = route[3] end end if module == nil then ngx.status = ngx.HTTP_NOT_FOUND ngx.say(json.encode({["error"] = "not found"})) return ngx.exit(ngx.HTTP_OK) end local ok, func = pcall(require, module) if not ok then -- `func` will be the error message if error occured ngx.log(ngx.ERR, func) if string.find(func, "not found") then ngx.status = ngx.HTTP_NOT_FOUND else ngx.status = ngx.ERROR end if env == 'production' then func = 'Internal Server Error' end ngx.say(json.encode({["error"] = func})) return ngx.exit(ngx.HTTP_OK) end local body = ngx.req.get_body_data() local event = {} if body then event.body = json.decode(body) end local context = {} function context.error (err) error({t = "error", err = err}) end function context.fatal (err) error(err) end local ok, ret = pcall(func, event, context) if not ok then if ret.t == "error" then -- user error ngx.status = ngx.HTTP_BAD_REQUEST ngx.say(json.encode({["error"] = ret.err})) ngx.log(ngx.ERR, ret.err) return ngx.exit(ngx.HTTP_OK) else -- unknown exception -- TODO: don't return exception in production if env == 'production' then ret = 'We\'re sorry, something went wrong' end ngx.status = ngx.ERROR ngx.say(json.encode({["error"] = ret})) ngx.log(ngx.ERR, ret) return ngx.exit(ngx.HTTP_OK) end end ngx.say(json.encode({data = ret}))
local json = require "cjson" local routes = require "routes" local env = os.getenv('SPACER_ENV') ngx.req.read_body() local path = ngx.var.uri local method = ngx.var.request_method local module = nil for i, route in ipairs(routes) do if route[1] == method and route[2] == path then module = route[3] end end if module == nil then ngx.status = 404 ngx.say(json.encode({["error"] = "not found"})) return ngx.exit(ngx.HTTP_OK) end local ok, func = pcall(require, module) if not ok then -- `func` will be the error message if error occured ngx.log(ngx.ERR, func) if string.find(func, "not found") then ngx.status = 404 else ngx.status = 500 end if env == 'production' then func = 'Internal Server Error' end ngx.say(json.encode({["error"] = func})) return ngx.exit(ngx.HTTP_OK) end local body = ngx.req.get_body_data() local event = {} if body then event.body = json.decode(body) end local context = {} function context.error (err) error({t = "error", err = err}) end function context.fatal (err) error(err) end local ok, ret = pcall(func, event, context) if not ok then if ret.t == "error" then -- user error ngx.status = 400 ngx.say(json.encode({["error"] = ret.err})) ngx.log(ngx.ERR, ret.err) return ngx.exit(ngx.HTTP_OK) else -- unknown exception -- TODO: don't return exception in production if env == 'production' then ret = 'We\'re sorry, something went wrong' end ngx.status = 500 ngx.say(json.encode({["error"] = ret})) ngx.log(ngx.ERR, ret) return ngx.exit(ngx.HTTP_OK) end end ngx.say(json.encode({data = ret}))
fix status code
fix status code
Lua
mit
poga/spacer,poga/spacer,poga/spacer
5911e4e9d5523c705a9291e731d673a3d6750b01
gumbo/dom/Document.lua
gumbo/dom/Document.lua
local Element = require "gumbo.dom.Element" local Text = require "gumbo.dom.Text" local Comment = require "gumbo.dom.Comment" local util = require "gumbo.dom.util" local Document = util.merge("Node", "NonElementParentNode", { type = "document", nodeName = "#document", nodeType = 9, contentType = "text/html", characterSet = "UTF-8", URL = "about:blank" }) local getters = {} function getters:documentURI() return self.URL end function getters:firstChild() return self.childNodes[1] end function getters:lastChild() local cnodes = self.childNodes return cnodes[#cnodes] end function getters:compatMode() if self.quirksMode == "quirks" then return "BackCompat" else return "CSS1Compat" end end function Document:__index(k) if type(k) == "number" then return self.childNodes[k] end local field = Document[k] if field then return field else local getter = getters[k] if getter then return getter(self) end end end -- The createElement(localName) method must run the these steps: -- -- 1. If localName does not match the Name production, throw an -- "InvalidCharacterError" exception. (http://www.w3.org/TR/xml/#NT-Name) -- 2. If the context object is an HTML document, let localName be -- converted to ASCII lowercase. -- 3. Let interface be the element interface for localName and the HTML -- namespace. -- 4. Return a new element that implements interface, with no attributes, -- namespace set to the HTML namespace, local name set to localName, and -- node document set to the context object. -- -- <http://www.w3.org/TR/dom/#dom-document-createelement> -- function Document:createElement(localName) -- TODO: Handle type(localName) ~= "string" if not string.find(localName, "^[A-Za-z:_][A-Za-z0-9:_.-]*$") then return error("InvalidCharacterError") end if self.doctype.name == "html" then -- TODO: Handle self.doctype == nil localName = localName:lower() end -- TODO: Set namespace and nodeDocument fields return setmetatable({tag = localName}, Element) end -- The createTextNode(data) method must return a new Text node with its -- data set to data and node document set to the context object. -- -- Note: No check is performed that data consists of characters that match -- the Char production. -- -- <http://www.w3.org/TR/dom/#dom-document-createtextnode> -- function Document:createTextNode(data) return setmetatable({text = data}, Text) end -- The createComment(data) method must return a new Comment node with its -- data set to data and node document set to the context object. -- -- Note: No check is performed that data consists of characters that match the -- Char production or that it contains two adjacent hyphens or ends with -- a hyphen. -- -- <http://www.w3.org/TR/dom/#dom-document-createcomment> -- function Document:createComment(data) return setmetatable({text = data}, Comment) end return Document
local Element = require "gumbo.dom.Element" local Text = require "gumbo.dom.Text" local Comment = require "gumbo.dom.Comment" local util = require "gumbo.dom.util" local Document = util.merge("Node", "NonElementParentNode", { type = "document", nodeName = "#document", nodeType = 9, contentType = "text/html", characterSet = "UTF-8", URL = "about:blank" }) local getters = {} function getters:documentURI() return self.URL end function getters:firstChild() return self.childNodes[1] end function getters:lastChild() local cnodes = self.childNodes return cnodes[#cnodes] end function getters:compatMode() if self.quirksMode == "quirks" then return "BackCompat" else return "CSS1Compat" end end function Document:__index(k) if type(k) == "number" then return self.childNodes[k] end local field = Document[k] if field then return field else local getter = getters[k] if getter then return getter(self) end end end function Document:createElement(localName) if not string.find(localName, "^[A-Za-z:_][A-Za-z0-9:_.-]*$") then return error("InvalidCharacterError") end return setmetatable({localName = localName:lower()}, Element) end function Document:createTextNode(data) return setmetatable({data = data}, Text) end function Document:createComment(data) return setmetatable({data = data}, Comment) end return Document
Fix Document.create* methods
Fix Document.create* methods
Lua
apache-2.0
craigbarnes/lua-gumbo,craigbarnes/lua-gumbo,craigbarnes/lua-gumbo
8c1d109555a32453174ace1d328fd6fe32c735c3
src/pasta/app.lua
src/pasta/app.lua
local mnemonic = require("mnemonic") local arc4random = require("arc4random") local crypto = require("crypto") local lapis = require("lapis") local model = require("pasta.models") local config = require("lapis.config").get() local app = lapis.Application() local function makeToken(nwords) local words = mnemonic.randomWords(nwords, arc4random.random) return table.concat(words, '-') end local function makeHash(token) return crypto.digest('SHA256', token) end app:get("schema", "/schema", function() model.create_schema() end) app:get("index", "/", function() return {render = require "pasta.views.index"} end) app:post("create", "/create", function(request) local token = makeToken(config.nwords_short) local p = model.Pasta:create { hash = makeHash(token), self_burning = false, filename = 'TODO.txt', content = request.params.content, password = 'TODO', } if not p then return "Failed to create paste" end local url = request:url_for("view_pasta", {token=token}) return {redirect_to = url} end) app:get("view_pasta", "/:token", function(request) request.token = request.params.token request.hash = makeHash(request.token) request.p = model.Pasta:find(request.hash) if not request.p then return "No such pasta" end request.p_content = request.p.content return {render = require "pasta.views.view_pasta"} end) return app
local mnemonic = require("mnemonic") local arc4random = require("arc4random") local crypto = require("crypto") local lapis = require("lapis") local model = require("pasta.models") local config = require("lapis.config").get() local app = lapis.Application() local function makeToken(nwords) local words = mnemonic.randomWords(nwords, arc4random.random) return table.concat(words, '-') end local function makeHash(token) local text = config.hash_secret1 .. token .. config.hash_secret2 return crypto.digest('SHA256', text) end app:get("schema", "/schema", function() model.create_schema() end) app:get("index", "/", function() return {render = require "pasta.views.index"} end) app:post("create", "/create", function(request) local token = makeToken(config.nwords_short) local p = model.Pasta:create { hash = makeHash(token), self_burning = false, filename = 'TODO.txt', content = request.params.content, password = 'TODO', } if not p then return "Failed to create paste" end local url = request:url_for("view_pasta", {token=token}) return {redirect_to = url} end) app:get("view_pasta", "/:token", function(request) request.token = request.params.token request.hash = makeHash(request.token) request.p = model.Pasta:find(request.hash) if not request.p then return "No such pasta" end request.p_content = request.p.content return {render = require "pasta.views.view_pasta"} end) return app
implement prefix, suffix added to hashed string
implement prefix, suffix added to hashed string
Lua
mit
starius/pasta,starius/pasta,starius/pasta
9aa795bf6d89b664b417765ef53dbd6f5a3c480b
npc/base/condition/state.lua
npc/base/condition/state.lua
-- $Id$ require("base.class") require("npc.base.condition.condition") module("npc.base.condition.state", package.seeall) state = base.class.class(npc.base.condition.condition.condition, function(self, comp, value) npc.base.condition.condition.condition:init(self); self["value"], self["valuetype"] = npc.base.talk._set_value(value); if (comp == "=") then self["check"] = _state_helper_equal; elseif (comp == "<>" or comp == "!=" or comp == "~=") then self["check"] = _state_helper_notequal; elseif (comp == "<=" or comp == "=<") then self["check"] = _state_helper_lesserequal; elseif (comp == ">=" or comp == "=>") then self["check"] = _state_helper_greaterequal; elseif (comp == ">") then self["check"] = _state_helper_greater; elseif (comp == "<") then self["check"] = _state_helper_lesser; else -- unkonwn comparator end; end); function _state_helper_equal(self, _) local value = npc.base.talk._get_value(self.npc, self.value, self.valuetype); return (value == self.npc._state) end; function _state_helper_notequal(self, _) local value = npc.base.talk._get_value(self.npc, self.value, self.valuetype); return (value ~= self.npc._state) end; function _state_helper_lesserequal(self, _) local value = npc.base.talk._get_value(self.npc, self.value, self.valuetype); return (value <= self.npc._state) end; function _state_helper_greaterequal(self, _) local value = npc.base.talk._get_value(self.npc, self.value, self.valuetype); return (value >= self.npc._state) end; function _state_helper_lesser(self, _) local value = npc.base.talk._get_value(self.npc, self.value, self.valuetype); thisNPC:talk(Character.say, "value = "..value); thisNPC:talk(Character.say, "state = "..self.npc._state); return (value < self.npc._state) end; function _state_helper_greater(self, _) local value = npc.base.talk._get_value(self.npc, self.value, self.valuetype); return (value > self.npc._state) end;
-- $Id$ require("base.class") require("npc.base.condition.condition") module("npc.base.condition.state", package.seeall) state = base.class.class(npc.base.condition.condition.condition, function(self, comp, value) npc.base.condition.condition.condition:init(self); self["value"], self["valuetype"] = npc.base.talk._set_value(value); if (comp == "=") then self["check"] = _state_helper_equal; elseif (comp == "<>" or comp == "!=" or comp == "~=") then self["check"] = _state_helper_notequal; elseif (comp == "<=" or comp == "=<") then self["check"] = _state_helper_lesserequal; elseif (comp == ">=" or comp == "=>") then self["check"] = _state_helper_greaterequal; elseif (comp == ">") then self["check"] = _state_helper_greater; elseif (comp == "<") then self["check"] = _state_helper_lesser; else -- unkonwn comparator end; end); function _state_helper_equal(self, _) local value = npc.base.talk._get_value(self.npc, self.value, self.valuetype); return (value == self.npc._state) end; function _state_helper_notequal(self, _) local value = npc.base.talk._get_value(self.npc, self.value, self.valuetype); return (value ~= self.npc._state) end; function _state_helper_lesserequal(self, _) local value = npc.base.talk._get_value(self.npc, self.value, self.valuetype); return (self.npc._state <= value) end; function _state_helper_greaterequal(self, _) local value = npc.base.talk._get_value(self.npc, self.value, self.valuetype); return (self.npc._state >= value) end; function _state_helper_lesser(self, _) local value = npc.base.talk._get_value(self.npc, self.value, self.valuetype); return (self.npc._state < value) end; function _state_helper_greater(self, _) local value = npc.base.talk._get_value(self.npc, self.value, self.valuetype); return (self.npc._state > value) end;
Removed bug with state in easyNPC
Removed bug with state in easyNPC
Lua
agpl-3.0
Baylamon/Illarion-Content,LaFamiglia/Illarion-Content,Illarion-eV/Illarion-Content,KayMD/Illarion-Content,vilarion/Illarion-Content
83e7ac63002d19bb1348b581716a8b96fdbac70b
applications/luci-polipo/luasrc/model/cbi/polipo.lua
applications/luci-polipo/luasrc/model/cbi/polipo.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Aleksandar Krsteski <alekrsteski@gmail.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("polipo") -- General section s = m:section(NamedSection, "general", "polipo") -- General settings s:option(Flag, "enabled", translate("enable")) s:option(Value, "proxyAddress") s:option(Value, "proxyPort").optional = true s:option(DynamicList, "allowedClients") s:option(Flag, "logSyslog") s:option(Value, "logFacility"):depends("logSyslog", "1") v = s:option(Value, "logFile") v:depends("logSyslog", "") v.rmempty = true s:option(Value, "chunkHighMark") -- DNS and proxy settings s:option(Value, "dnsNameServer").optional = true s:option(Value, "parentProxy").optional = true s:option(Value, "parentAuthCredentials").optional = true l = s:option(ListValue, "dnsQueryIPv6") l.optional = true l.default = "happily" l:value("") l:value("true") l:value("reluctantly") l:value("happily") l:value("false") l = s:option(ListValue, "dnsUseGethostbyname") l.optional = true l.default = "reluctantly" l:value("") l:value("true") l:value("reluctantly") l:value("happily") l:value("false") -- Dsik cache section s = m:section(NamedSection, "cache", "polipo") -- Dsik cache settings s:option(Value, "diskCacheRoot").rmempty = true s:option(Flag, "cacheIsShared") s:option(Value, "diskCacheTruncateSize").optional = true s:option(Value, "diskCacheTruncateTime").optional = true s:option(Value, "diskCacheUnlinkTime").optional = true -- Poor man's multiplexing section s = m:section(NamedSection, "pmm", "polipo") s:option(Value, "pmmSize").rmempty = true s:option(Value, "pmmFirstSize").optional = true return m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Aleksandar Krsteski <alekrsteski@gmail.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("polipo", translate("Polipo"), translate("Polipo is a small and fast caching web proxy.")) -- General section s = m:section(NamedSection, "general", "polipo", translate("Proxy")) s:tab("general", translate("General Settings")) s:tab("dns", translate("DNS and Query Settings")) s:tab("proxy", translate("Parent Proxy")) s:tab("logging", translate("Logging and RAM")) -- General settings s:taboption("general", Flag, "enabled", translate("enable")) o = s:taboption("general", Value, "proxyAddress", translate("Listen address"), translate("The interface on which Polipo will listen. To listen on all " .. "interfaces use 0.0.0.0 or :: (IPv6).")) o.placeholder = "0.0.0.0" o.datatype = "ipaddr" o = s:taboption("general", Value, "proxyPort", translate("Listen port"), translate("Port on which Polipo will listen")) o.optional = true o.placeholder = "8123" o.datatype = "port" o = s:taboption("general", DynamicList, "allowedClients", translate("Allowed clients"), translate("When listen address is set to 0.0.0.0 or :: (IPv6), you must " .. "list clients that are allowed to connect. The format is IP address " .. "or network address (192.168.1.123, 192.168.1.0/24, " .. "2001:660:116::/48 (IPv6))")) o.datatype = "ipaddr" o.placeholder = "0.0.0.0/0" -- DNS settings dns = s:taboption("dns", Value, "dnsNameServer", translate("DNS server address"), translate("Set the DNS server address to use, if you want Polipo to use " .. "different DNS server than the host system.")) dns.optional = true dns.datatype = "ipaddr" l = s:taboption("dns", ListValue, "dnsQueryIPv6", translate("Query DNS for IPv6")) l.default = "happily" l:value("true", translate("Query only IPv6")) l:value("happily", translate("Query IPv4 and IPv6, prefer IPv6")) l:value("reluctantly", translate("Query IPv4 and IPv6, prefer IPv4")) l:value("false", translate("Do not query IPv6")) l = s:taboption("dns", ListValue, "dnsUseGethostbyname", translate("Query DNS by hostname")) l.default = "reluctantly" l:value("true", translate("Always use system DNS resolver")) l:value("happily", translate("Query DNS directly, for unknown hosts fall back " .. "to system resolver")) l:value("reluctantly", translate("Query DNS directly, fallback to system resolver")) l:value("false", translate("Never use system DNS resolver")) -- Proxy settings o = s:taboption("proxy", Value, "parentProxy", translate("Parent proxy address"), translate("Parent proxy address (in host:port format), to which Polipo " .. "will forward the requests.")) o.optional = true o.datatype = "ipaddr" o = s:taboption("proxy", Value, "parentAuthCredentials", translate("Parent proxy authentication"), translate("Basic HTTP authentication supported. Provide username and " .. "password in username:password format.")) o.optional = true o.placeholder = "username:password" -- Logging s:taboption("logging", Flag, "logSyslog", translate("Log to syslog")) s:taboption("logging", Value, "logFacility", translate("Syslog facility")):depends("logSyslog", "1") v = s:taboption("logging", Value, "logFile", translate("Log file location"), translate("Use of external storage device is recommended, because the " .. "log file is written frequently and can grow considerably.")) v:depends("logSyslog", "") v.rmempty = true o = s:taboption("logging", Value, "chunkHighMark", translate("In RAM cache size (in bytes)"), translate("How much RAM should Polipo use for its cache.")) o.datatype = "uinteger" -- Disk cache section s = m:section(NamedSection, "cache", "polipo", translate("On-Disk Cache")) s:tab("general", translate("General Settings")) s:tab("advanced", translate("Advanced Settings")) -- Disk cache settings s:taboption("general", Value, "diskCacheRoot", translate("Disk cache location"), translate("Location where polipo will cache files permanently. Use of " .. "external storage devices is recommended, because the cache can " .. "grow considerably. Leave it empty to disable on-disk " .. "cache.")).rmempty = true s:taboption("general", Flag, "cacheIsShared", translate("Shared cache"), translate("Enable if cache (proxy) is shared by multiple users.")) o = s:taboption("advanced", Value, "diskCacheTruncateSize", translate("Truncate cache files size (in bytes)"), translate("Size to which cached files should be truncated")) o.optional = true o.placeholder = "1048576" o.datatype = "uinteger" o = s:taboption("advanced", Value, "diskCacheTruncateTime", translate("Truncate cache files time"), translate("Time after which cached files will be truncated")) o.optional = true o.placeholder = "4d12h" o = s:taboption("advanced", Value, "diskCacheUnlinkTime", translate("Delete cache files time"), translate("Time after which cached files will be deleted")) o.optional = true o.placeholder = "32d" -- Poor man's multiplexing section s = m:section(NamedSection, "pmm", "polipo", translate("Poor Man's Multiplexing"), translate("Poor Man's Multiplexing (PMM) is a technique that simulates " .. "multiplexing by requesting an instance in multiple segments. It " .. "tries to lower the latency caused by the weakness of HTTP " .. "protocol. NOTE: some sites may not work with PMM enabled.")) s:option(Value, "pmmSize", translate("PMM segments size (in bytes)"), translate("To enable PMM, PMM segment size must be set to some " .. "positive value.")).rmempty = true s:option(Value, "pmmFirstSize", translate("First PMM segment size (in bytes)"), translate("Size of the first PMM segment. If not defined, it defaults " .. "to twice the PMM segment size.")).rmempty = true return m
applications/luci-polipo: fix polipo page
applications/luci-polipo: fix polipo page git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@6613 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
mzguanglin/LuCI,mzguanglin/LuCI,mzguanglin/LuCI,mzguanglin/LuCI,mzguanglin/LuCI,mzguanglin/LuCI
468d2c7767081c3a011911b44249267aaf977b89
mod_statistics/prosodytop.lua
mod_statistics/prosodytop.lua
local curses = require "curses"; local server = require "net.server_select"; local timer = require "util.timer"; assert(curses.timeout, "Incorrect version of curses library. Try 'sudo luarocks install luaposix'"); local top = require "top"; function main() local stdscr = curses.stdscr() -- it's a userdatum --stdscr:clear(); local view = top.new({ stdscr = stdscr; prosody = { up_since = os.time() }; conn_list = {}; }); timer.add_task(0.01, function () local ch = stdscr:getch(); if ch then if stdscr:getch() == 410 then view:resized(); else curses.ungetch(ch); end end return 0.2; end); timer.add_task(0, function () view:draw(); return 1; end); --[[ posix.signal(28, function () table.insert(view.conn_list, { jid = "WINCH" }); --view:draw(); end); ]] -- Fake socket object around stdin local stdin = { getfd = function () return 0; end; dirty = function (self) return false; end; settimeout = function () end; send = function (_, d) return #d, 0; end; close = function () end; receive = function (_, patt) local ch = stdscr:getch(); if ch >= 0 and ch <=255 then return string.char(ch); elseif ch == 410 then view:resized(); else table.insert(view.conn_list, { jid = tostring(ch) }); --FIXME end return ""; end }; local function on_incoming(stdin, text) -- TODO: Handle keypresses if text:lower() == "q" then os.exit(); end end stdin = server.wrapclient(stdin, "stdin", 0, { onincoming = on_incoming, ondisconnect = function () end }, "*a"); local function handle_line(line) local e = { STAT = function (name) return function (value) view:update_stat(name, value); end end; SESS = function (id) return function (jid) return function (stats) view:update_session(id, jid, stats); end end end; }; local chunk = assert(loadstring(line)); setfenv(chunk, e); chunk(); end local stats_listener = {}; function stats_listener.onconnect(conn) --stdscr:mvaddstr(6, 0, "CONNECTED"); end local partial; function stats_listener.onincoming(conn, data) --print("DATA", data) if partial then partial, data = nil, partial..data; end if not data:match("\n") then partial = data; return; end local lastpos = 1; for line, pos in data:gmatch("([^\n]+)\n()") do lastpos = pos; handle_line(line); end if lastpos == #data then partial = nil; else partial = data:sub(lastpos); end end function stats_listener.ondisconnect(conn, err) stdscr:mvaddstr(6, 0, "DISCONNECTED: "..(err or "unknown")); end local conn = require "socket".tcp(); assert(conn:connect("localhost", 5782)); handler = server.wrapclient(conn, "localhost", 5279, stats_listener, "*a"); end return { run = function () --os.setlocale("UTF-8", "all") curses.initscr() curses.cbreak() curses.echo(false) -- not noecho ! curses.nl(false) -- not nonl ! curses.timeout(0); local ok, err = pcall(main); --while true do stdscr:getch() end --stdscr:endwin() if ok then ok, err = xpcall(server.loop, debug.traceback); end curses.endwin(); --stdscr:refresh(); if not ok then print(err); end print"DONE" end; };
local curses = require "curses"; local server = require "net.server_select"; local timer = require "util.timer"; assert(curses.timeout, "Incorrect version of curses library. Try 'sudo luarocks install luaposix'"); local top = require "top"; function main() local stdscr = curses.stdscr() -- it's a userdatum --stdscr:clear(); local view = top.new({ stdscr = stdscr; prosody = { up_since = os.time() }; conn_list = {}; }); timer.add_task(0.01, function () local ch = stdscr:getch(); if ch then if stdscr:getch() == 410 then view:resized(); else curses.ungetch(ch); end end return 0.2; end); timer.add_task(0, function () view:draw(); return 1; end); --[[ posix.signal(28, function () table.insert(view.conn_list, { jid = "WINCH" }); --view:draw(); end); ]] -- Fake socket object around stdin local stdin = { getfd = function () return 0; end; dirty = function (self) return false; end; settimeout = function () end; send = function (_, d) return #d, 0; end; close = function () end; receive = function (_, patt) local ch = stdscr:getch(); if ch >= 0 and ch <=255 then return string.char(ch); elseif ch == 410 then view:resized(); else table.insert(view.conn_list, { jid = tostring(ch) }); --FIXME end return ""; end }; local function on_incoming(stdin, text) -- TODO: Handle keypresses if text:lower() == "q" then os.exit(); end end stdin = server.wrapclient(stdin, "stdin", 0, { onincoming = on_incoming, ondisconnect = function () end }, "*a"); local function handle_line(line) local e = { STAT = function (name) return function (value) view:update_stat(name, value); end end; SESS = function (id) return function (jid) return function (stats) view:update_session(id, jid, stats); end end end; }; local chunk = assert(loadstring(line)); setfenv(chunk, e); chunk(); end local stats_listener = {}; function stats_listener.onconnect(conn) --stdscr:mvaddstr(6, 0, "CONNECTED"); end local partial = ""; function stats_listener.onincoming(conn, data) --print("DATA", data) data = partial..data; local lastpos = 1; for line, pos in data:gmatch("([^\n]+)\n()") do lastpos = pos; handle_line(line); end partial = data:sub(lastpos); end function stats_listener.ondisconnect(conn, err) stdscr:mvaddstr(6, 0, "DISCONNECTED: "..(err or "unknown")); end local conn = require "socket".tcp(); assert(conn:connect("localhost", 5782)); handler = server.wrapclient(conn, "localhost", 5279, stats_listener, "*a"); end return { run = function () --os.setlocale("UTF-8", "all") curses.initscr() curses.cbreak() curses.echo(false) -- not noecho ! curses.nl(false) -- not nonl ! curses.timeout(0); local ok, err = pcall(main); --while true do stdscr:getch() end --stdscr:endwin() if ok then ok, err = xpcall(server.loop, debug.traceback); end curses.endwin(); --stdscr:refresh(); if not ok then print(err); end print"DONE" end; };
mod_statistics/prosodytop.lua: Simplify and fix buffering and line separation (thanks Ge0rG)
mod_statistics/prosodytop.lua: Simplify and fix buffering and line separation (thanks Ge0rG)
Lua
mit
asdofindia/prosody-modules,softer/prosody-modules,either1/prosody-modules,olax/prosody-modules,mardraze/prosody-modules,asdofindia/prosody-modules,mardraze/prosody-modules,olax/prosody-modules,cryptotoad/prosody-modules,NSAKEY/prosody-modules,iamliqiang/prosody-modules,amenophis1er/prosody-modules,brahmi2/prosody-modules,vfedoroff/prosody-modules,mardraze/prosody-modules,1st8/prosody-modules,jkprg/prosody-modules,obelisk21/prosody-modules,softer/prosody-modules,NSAKEY/prosody-modules,crunchuser/prosody-modules,vince06fr/prosody-modules,iamliqiang/prosody-modules,brahmi2/prosody-modules,syntafin/prosody-modules,cryptotoad/prosody-modules,dhotson/prosody-modules,stephen322/prosody-modules,vfedoroff/prosody-modules,softer/prosody-modules,either1/prosody-modules,iamliqiang/prosody-modules,apung/prosody-modules,syntafin/prosody-modules,asdofindia/prosody-modules,cryptotoad/prosody-modules,vfedoroff/prosody-modules,iamliqiang/prosody-modules,apung/prosody-modules,dhotson/prosody-modules,apung/prosody-modules,either1/prosody-modules,BurmistrovJ/prosody-modules,jkprg/prosody-modules,brahmi2/prosody-modules,guilhem/prosody-modules,heysion/prosody-modules,amenophis1er/prosody-modules,vince06fr/prosody-modules,LanceJenkinZA/prosody-modules,amenophis1er/prosody-modules,drdownload/prosody-modules,vfedoroff/prosody-modules,drdownload/prosody-modules,obelisk21/prosody-modules,guilhem/prosody-modules,mmusial/prosody-modules,syntafin/prosody-modules,guilhem/prosody-modules,heysion/prosody-modules,mmusial/prosody-modules,prosody-modules/import,LanceJenkinZA/prosody-modules,joewalker/prosody-modules,asdofindia/prosody-modules,crunchuser/prosody-modules,stephen322/prosody-modules,1st8/prosody-modules,asdofindia/prosody-modules,amenophis1er/prosody-modules,LanceJenkinZA/prosody-modules,olax/prosody-modules,NSAKEY/prosody-modules,crunchuser/prosody-modules,heysion/prosody-modules,olax/prosody-modules,joewalker/prosody-modules,heysion/prosody-modules,NSAKEY/prosody-modules,mmusial/prosody-modules,drdownload/prosody-modules,BurmistrovJ/prosody-modules,LanceJenkinZA/prosody-modules,either1/prosody-modules,Craige/prosody-modules,1st8/prosody-modules,BurmistrovJ/prosody-modules,apung/prosody-modules,drdownload/prosody-modules,stephen322/prosody-modules,softer/prosody-modules,crunchuser/prosody-modules,cryptotoad/prosody-modules,Craige/prosody-modules,obelisk21/prosody-modules,vince06fr/prosody-modules,joewalker/prosody-modules,mardraze/prosody-modules,dhotson/prosody-modules,cryptotoad/prosody-modules,guilhem/prosody-modules,either1/prosody-modules,mmusial/prosody-modules,Craige/prosody-modules,mardraze/prosody-modules,1st8/prosody-modules,dhotson/prosody-modules,iamliqiang/prosody-modules,mmusial/prosody-modules,amenophis1er/prosody-modules,BurmistrovJ/prosody-modules,prosody-modules/import,syntafin/prosody-modules,prosody-modules/import,LanceJenkinZA/prosody-modules,stephen322/prosody-modules,1st8/prosody-modules,crunchuser/prosody-modules,joewalker/prosody-modules,jkprg/prosody-modules,brahmi2/prosody-modules,vince06fr/prosody-modules,vfedoroff/prosody-modules,prosody-modules/import,apung/prosody-modules,stephen322/prosody-modules,softer/prosody-modules,brahmi2/prosody-modules,olax/prosody-modules,drdownload/prosody-modules,guilhem/prosody-modules,dhotson/prosody-modules,jkprg/prosody-modules,joewalker/prosody-modules,obelisk21/prosody-modules,Craige/prosody-modules,syntafin/prosody-modules,jkprg/prosody-modules,vince06fr/prosody-modules,NSAKEY/prosody-modules,prosody-modules/import,BurmistrovJ/prosody-modules,heysion/prosody-modules,Craige/prosody-modules,obelisk21/prosody-modules
0c10fda8439759353f394fb719bc6d1e2c8e5ec4
MMOCoreORB/bin/scripts/screenplays/tasks/nitra_vendallan.lua
MMOCoreORB/bin/scripts/screenplays/tasks/nitra_vendallan.lua
nitra_vendallan_missions = { { missionType = "escort", primarySpawns = { { npcTemplate = "nitra_vendallan_imp", planetName = "tatooine", npcName = "Dienn Biktor (a Imperial Non-Comm defector)" } }, secondarySpawns = {}, itemSpawns = {}, rewards = { { rewardType = "faction", faction = "rebel", amount = 100 }, } }, { missionType = "escort", primarySpawns = { { npcTemplate = "nitra_vendallan_imp2", planetName = "tatooine", npcName = "Nitra Vendallan (a Weaponsmith)" } }, secondarySpawns = {}, itemSpawns = {}, rewards = { { rewardType = "faction", faction = "rebel", amount = 250 }, } }, } npcMapNitraVendallan = { { spawnData = { planetName = "tatooine", npcTemplate = "nitra_vendallan", x = -2.95305, z = 0.40827, y = -9.30713, direction = 12.2342, cellID = 1213345, position = STAND }, worldPosition = { x = 134.7, y = -5347.1 }, npcNumber = 1, stfFile = "@static_npc/tatooine/nitra_vendallan", missions = nitra_vendallan_missions }, } NitraVendallan = ThemeParkLogic:new { numberOfActs = 1, npcMap = npcMapNitraVendallan, permissionMap = {}, className = "NitraVendallan", screenPlayState = "nitra_vendallan_quest", distance = 1000, missionDescriptionStf = "", missionCompletionMessageStf = "", faction = FACTIONREBEL } registerScreenPlay("NitraVendallan", true) nitra_vendallan_mission_giver_conv_handler = mission_giver_conv_handler:new { themePark = NitraVendallan } nitra_vendallan_mission_target_conv_handler = mission_target_conv_handler:new { themePark = NitraVendallan }
nitra_vendallan_missions = { { missionType = "escort", primarySpawns = { { npcTemplate = "nitra_vendallan_imp", planetName = "tatooine", npcName = "Drenn Biktor (an Imperial Non-Comm defector)" } }, secondarySpawns = {}, itemSpawns = {}, rewards = { { rewardType = "faction", faction = "rebel", amount = 100 }, } }, { missionType = "escort", primarySpawns = { { npcTemplate = "nitra_vendallan_imp2", planetName = "tatooine", npcName = "Vil Sembian" } }, secondarySpawns = {}, itemSpawns = {}, rewards = { { rewardType = "faction", faction = "rebel", amount = 250 }, } }, } npcMapNitraVendallan = { { spawnData = { planetName = "tatooine", npcTemplate = "nitra_vendallan", x = -2.95305, z = 0.40827, y = -9.30713, direction = 12.2342, cellID = 1213345, position = STAND }, worldPosition = { x = 134.7, y = -5347.1 }, npcNumber = 1, stfFile = "@static_npc/tatooine/nitra_vendallan", hasWaypointNames = "no", missions = nitra_vendallan_missions }, } NitraVendallan = ThemeParkLogic:new { numberOfActs = 1, npcMap = npcMapNitraVendallan, permissionMap = {}, className = "NitraVendallan", screenPlayState = "nitra_vendallan_quest", distance = 1000, missionDescriptionStf = "", missionCompletionMessageStf = "", faction = FACTIONREBEL } registerScreenPlay("NitraVendallan", true) nitra_vendallan_mission_giver_conv_handler = mission_giver_conv_handler:new { themePark = NitraVendallan } nitra_vendallan_mission_target_conv_handler = mission_target_conv_handler:new { themePark = NitraVendallan }
[Fixed] waypoint names and escort target names for Nitra Vendallan task - mantis 4893
[Fixed] waypoint names and escort target names for Nitra Vendallan task - mantis 4893 Change-Id: I93d9c3036cf1e6b7323e52882f8c3fd426231a94
Lua
agpl-3.0
lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo
d770a0cab9393ed17bf0c48e08af293db164a424
lua/tchildren.lua
lua/tchildren.lua
local getChildren = function (id, level, result) local list = cmsgpack.unpack(redis.call('get', prefix .. id)) return list -- for i, v in ipairs(list) do -- local cid = v[1] -- local childCount = v[2] -- local item = { cid, childCount } -- if childCount > 0 and level ~= 0 then -- getChildren(cid, level - 1, item) -- end -- result[#result + 1] = item -- end -- return result end local level = ARGV[argIndex + 1] if level then level = tonumber(level) if level == 0 then return nil end else level = -1 end return getChildren(id, level, {})
local getChildren = function (id, level, result) local list = cmsgpack.unpack(redis.call('get', prefix .. id)) for i, v in ipairs(list) do local cid = v[1] local childCount = v[2] local item = { cid, childCount } if childCount > 0 and level ~= 0 then getChildren(cid, level - 1, item) end result[#result + 1] = item end return result end local level = ARGV[argIndex + 1] if level then level = tonumber(level) if level == 0 then return nil end else level = -1 end return getChildren(id, level, {})
Fix tchildren
Fix tchildren
Lua
mit
shimohq/ioredis-tree
6fb48f8c57b0ed6f0fb4aef8a8e0d35a8d4bc826
src/program/config/data_format/data_format.lua
src/program/config/data_format/data_format.lua
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(..., package.seeall) local lib = require("core.lib") local schema = require("lib.yang.schema") local yang_data = require("lib.yang.data") -- Number of spaces a tab should consist of when indenting config. local tab_spaces = 2 local function print_level(level, ...) io.write(string.rep(" ", level * tab_spaces)) print(...) end local function union_type(union) local rtn for _, t in pairs(union.argument_type.union) do if rtn then rtn = rtn .. " | " .. t.argument_string else rtn = t.argument_string end end return rtn end local function comment(opts) local comments = {} if opts.mandatory == true then comments[#comments + 1] = "mandatory" end if opts.key then comments[#comments + 1] = "key" end if opts.range then comments[#comments + 1] = "between " .. opts.range end local rtn = nil for n, c in pairs(comments) do if n == 1 then rtn = "// " .. c else rtn = rtn .. " " .. c end end return rtn end local function display_leaf(level, keyword, argument, opts) if argument == "union" then argument = union_type(node) end local comments if opts then comments = comment(opts) end local str = keyword .. " ".. argument .. ";" if comments then print_level(level, str .. " " .. comments) else print_level(level, str) end end local function show_usage(status) print(require("program.config.data_format.README_inc")) main.exit(status) end -- Contains verious option handling code. local options = {} function options.key(keys) return function (name) for _, k in pairs(keys) do if name == k then return true end end return false end end function options.mandatory(name, node) if node.mandatory then return node.mandatory end end function options.range(name, node) if node.argument_type.range then return node.argument_type.range.argument_string end return nil end -- Contains the handlers which know how to describe certain data node types. local describers = {} local function describe(level, name, node, ...) local err = "Unknown node type: "..node.type assert(describers[node.type], err)(level, name, node, ...) end local function describe_members(node, level, ...) if level == nil then level = 0 end for name, n in pairs(node.members) do describe(level, name, n, ...) end end function describers.scalar(level, name, node, is_key) local opts = {} if is_key then opts.key = is_key(name, node) end opts.mandatory = options.mandatory(name, node) opts.range = options.range(name, node) display_leaf(level, name, node.argument_type.argument_string, opts) end function describers.table(level, name, node) if node.keys then print_level( level, "// List: this nested structure is repeated with (a) unique key(s)" ) end print_level(level, name.." {") describe_members(node, level + 1, options.key(node.keys)) print_level(level, "}") end function describers.struct(level, name, node) print_level(level, name.." {") describe_members(node, level + 1) print_level(level, "}") end function describers.array(level, name, node) print_level( level, "// Array: made by repeating the keyword followed by each element" ) display_leaf(level, name, node.element_type.argument_string) end local function parse_args(args) local handlers = {} handlers.h = function() show_usage(0) end args = lib.dogetopt(args, handlers, "h", {help="h"}) if #args <= 0 then show_usage(1) end return unpack(args) end function run(args) local yang_module = parse_args(args) -- Fetch and parse the schema module. local s = schema.parse_schema_file(yang_module) local grammar = yang_data.data_grammar_from_schema(s) describe_members(grammar) end
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(..., package.seeall) local lib = require("core.lib") local schema = require("lib.yang.schema") local yang_data = require("lib.yang.data") -- Number of spaces a tab should consist of when indenting config. local tab_spaces = 2 local function print_level(level, ...) io.write(string.rep(" ", level * tab_spaces)) print(...) end local function union_type(union) local rtn for _, t in pairs(union.argument_type.union) do if rtn then rtn = rtn .. " | " .. t.argument_string else rtn = t.argument_string end end return rtn end local function comment(opts) local comments = {} if opts.mandatory == true then comments[#comments + 1] = "mandatory" end if opts.key then comments[#comments + 1] = "key" end if opts.range then comments[#comments + 1] = "between " .. opts.range end local rtn = nil for n, c in pairs(comments) do if n == 1 then rtn = "// " .. c else rtn = rtn .. " " .. c end end return rtn end local function display_leaf(level, keyword, argument, opts) if argument == "union" then argument = union_type(node) end local comments if opts then comments = comment(opts) end local str = keyword .. " ".. argument .. ";" if comments then print_level(level, str .. " " .. comments) else print_level(level, str) end end local function show_usage(status) print(require("program.config.data_format.README_inc")) main.exit(status) end -- Contains verious option handling code. local options = {} function options.key(keys) return function (name) for _, k in pairs(keys) do if name == k then return true end end return false end end function options.range(name, node) if node.argument_type.range then return node.argument_type.range.argument_string end return nil end -- Contains the handlers which know how to describe certain data node types. local describers = {} local function describe(level, name, node, ...) local err = "Unknown node type: "..node.type assert(describers[node.type], err)(level, name, node, ...) end local function describe_members(node, level, ...) if level == nil then level = 0 end for name, n in pairs(node.members) do describe(level, name, n, ...) end end function describers.scalar(level, name, node, is_key) local opts = {} if is_key then opts.key = is_key(name, node) end opts.mandatory = node.mandatory opts.range = options.range(name, node) display_leaf(level, name, node.argument_type.argument_string, opts) end function describers.table(level, name, node) print_level(level, "// List, key(s) must be unique.") print_level(level, name.." {") describe_members(node, level + 1, options.key(node.keys)) print_level(level, "}") end function describers.struct(level, name, node) print_level(level, name.." {") describe_members(node, level + 1) print_level(level, "}") end function describers.array(level, name, node) print_level(level, "// Array, multiple elements by repeating the statement.") display_leaf(level, name, node.element_type.argument_string) end local function parse_args(args) local handlers = {} handlers.h = function() show_usage(0) end args = lib.dogetopt(args, handlers, "h", {help="h"}) if #args ~= 0 then show_usage(1) end return unpack(args) end function run(args) local yang_module = parse_args(args) -- Fetch and parse the schema module. local s = schema.parse_schema_file(yang_module) local grammar = yang_data.data_grammar_from_schema(s) describe_members(grammar) end
Fix some small code cosmeic issues
Fix some small code cosmeic issues
Lua
apache-2.0
alexandergall/snabbswitch,alexandergall/snabbswitch,eugeneia/snabb,Igalia/snabb,eugeneia/snabb,snabbco/snabb,Igalia/snabb,eugeneia/snabbswitch,eugeneia/snabbswitch,snabbco/snabb,Igalia/snabb,alexandergall/snabbswitch,SnabbCo/snabbswitch,heryii/snabb,alexandergall/snabbswitch,snabbco/snabb,eugeneia/snabb,eugeneia/snabb,snabbco/snabb,dpino/snabb,dpino/snabb,Igalia/snabb,Igalia/snabb,Igalia/snabb,heryii/snabb,Igalia/snabbswitch,Igalia/snabbswitch,dpino/snabb,Igalia/snabbswitch,dpino/snabbswitch,eugeneia/snabbswitch,eugeneia/snabb,eugeneia/snabb,alexandergall/snabbswitch,snabbco/snabb,alexandergall/snabbswitch,dpino/snabb,snabbco/snabb,Igalia/snabb,dpino/snabbswitch,Igalia/snabbswitch,heryii/snabb,dpino/snabb,Igalia/snabb,snabbco/snabb,Igalia/snabbswitch,dpino/snabbswitch,SnabbCo/snabbswitch,dpino/snabb,alexandergall/snabbswitch,SnabbCo/snabbswitch,eugeneia/snabb,heryii/snabb,eugeneia/snabb,dpino/snabbswitch,SnabbCo/snabbswitch,eugeneia/snabbswitch,dpino/snabb,snabbco/snabb,heryii/snabb,alexandergall/snabbswitch,heryii/snabb
2aec1cfaa90e1f885410ff3c2eed4f70186c2eb2
xmake/modules/package/tools/xmake.lua
xmake/modules/package/tools/xmake.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-2020, TBOOX Open Source Group. -- -- @author ruki -- @file xmake.lua -- -- imports import("core.base.option") -- get configs function _get_configs(package, configs) local configs = configs or {} local cflags = table.join(table.wrap(package:config("cflags")), get_config("cflags")) local cxflags = table.join(table.wrap(package:config("cxflags")), get_config("cxflags")) local cxxflags = table.join(table.wrap(package:config("cxxflags")), get_config("cxxflags")) local asflags = table.join(table.wrap(package:config("asflags")), get_config("asflags")) local ldflags = table.join(table.wrap(package:config("ldflags")), get_config("ldflags")) if package:is_plat("windows") then local vs_runtime = package:config("vs_runtime") if vs_runtime then local vs_runtime_cxflags = "/" .. vs_runtime .. (package:debug() and "d" or "") if cxflags then cxflags = cxflags .. " " .. vs_runtime_cxflags else cxflags = vs_runtime_cxflags end end end table.insert(configs, "--mode=" .. (package:debug() and "debug" or "release")) if cflags then table.insert(configs, "--cflags=" .. os.args(table.concat(cflags, ' '))) end if cxflags then table.insert(configs, "--cxflags=" .. os.args(table.concat(cxflags, ' '))) end if cxxflags then table.insert(configs, "--cxxflags=" .. os.args(table.concat(cxxflags, ' '))) end if asflags then table.insert(configs, "--asflags=" .. os.args(table.concat(asflags, ' '))) end if ldflags then table.insert(configs, "--ldflags=" .. os.args(table.concat(ldflags, ' '))) end return configs end -- init arguments and inherit some global options from the parent xmake function _init_argv(...) local argv = {...} for _, name in ipairs({"diagnosis", "verbose", "quiet", "yes", "confirm", "root"}) do local value = option.get(name) if type(value) == "boolean" then table.insert(argv, "--" .. name) elseif value ~= nil then table.insert(argv, "--" .. name .. "=" .. value) end end return argv end -- install package function install(package, configs) -- inherit builtin configs local argv = _init_argv("f", "-y", "-c") local names = {"plat", "arch", "ndk", "ndk_sdkver", "vs", "mingw", "sdk", "bin", "cross", "ld", "sh", "ar", "cc", "cxx", "mm", "mxx"} for _, name in ipairs(names) do local value = get_config(name) if value ~= nil then table.insert(argv, "--" .. name .. "=" .. tostring(value)) end end -- pass configurations for name, value in pairs(_get_configs(package, configs)) do value = tostring(value):trim() if type(name) == "number" then if value ~= "" then table.insert(argv, value) end else table.insert(argv, "--" .. name .. "=" .. value) end end os.vrunv("xmake", argv) -- do build argv = _init_argv() os.vrunv("xmake", argv) -- do install argv = _init_argv("install", "-y", "-o", package:installdir()) os.vrunv("xmake", argv) end
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-2020, TBOOX Open Source Group. -- -- @author ruki -- @file xmake.lua -- -- imports import("core.base.option") -- get configs function _get_configs(package, configs) local configs = configs or {} local cflags = table.join(table.wrap(package:config("cflags")), get_config("cflags")) local cxflags = table.join(table.wrap(package:config("cxflags")), get_config("cxflags")) local cxxflags = table.join(table.wrap(package:config("cxxflags")), get_config("cxxflags")) local asflags = table.join(table.wrap(package:config("asflags")), get_config("asflags")) local ldflags = table.join(table.wrap(package:config("ldflags")), get_config("ldflags")) if package:is_plat("windows") then local vs_runtime = package:config("vs_runtime") if vs_runtime then local vs_runtime_cxflags = "/" .. vs_runtime .. (package:debug() and "d" or "") table.insert(cxflags, vs_runtime_cxflags) end end table.insert(configs, "--mode=" .. (package:debug() and "debug" or "release")) if cflags then table.insert(configs, "--cflags=" .. os.args(table.concat(cflags, ' '))) end if cxflags then table.insert(configs, "--cxflags=" .. os.args(table.concat(cxflags, ' '))) end if cxxflags then table.insert(configs, "--cxxflags=" .. os.args(table.concat(cxxflags, ' '))) end if asflags then table.insert(configs, "--asflags=" .. os.args(table.concat(asflags, ' '))) end if ldflags then table.insert(configs, "--ldflags=" .. os.args(table.concat(ldflags, ' '))) end return configs end -- init arguments and inherit some global options from the parent xmake function _init_argv(...) local argv = {...} for _, name in ipairs({"diagnosis", "verbose", "quiet", "yes", "confirm", "root"}) do local value = option.get(name) if type(value) == "boolean" then table.insert(argv, "--" .. name) elseif value ~= nil then table.insert(argv, "--" .. name .. "=" .. value) end end return argv end -- install package function install(package, configs) -- inherit builtin configs local argv = _init_argv("f", "-y", "-c") local names = {"plat", "arch", "ndk", "ndk_sdkver", "vs", "mingw", "sdk", "bin", "cross", "ld", "sh", "ar", "cc", "cxx", "mm", "mxx"} for _, name in ipairs(names) do local value = get_config(name) if value ~= nil then table.insert(argv, "--" .. name .. "=" .. tostring(value)) end end -- pass configurations for name, value in pairs(_get_configs(package, configs)) do value = tostring(value):trim() if type(name) == "number" then if value ~= "" then table.insert(argv, value) end else table.insert(argv, "--" .. name .. "=" .. value) end end os.vrunv("xmake", argv) -- do build argv = _init_argv() os.vrunv("xmake", argv) -- do install argv = _init_argv("install", "-y", "-o", package:installdir()) os.vrunv("xmake", argv) end
fix tools/xmake
fix tools/xmake
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
61c7157a66b4bbce7d110cc0de8164bd2bd57798
modules/luci-mod-freifunk/luasrc/model/cbi/freifunk/basics.lua
modules/luci-mod-freifunk/luasrc/model/cbi/freifunk/basics.lua
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2011 Manuel Munz <freifunk at somakoma de> -- Licensed to the public under the Apache License 2.0. local fs = require "nixio.fs" local util = require "luci.util" local uci = require "luci.model.uci".cursor() local profiles = "/etc/config/profile_*" m = Map("freifunk", translate ("Community")) c = m:section(NamedSection, "community", "public", nil, translate("These are the basic settings for your local wireless community. These settings define the default values for the wizard and DO NOT affect the actual configuration of the router.")) community = c:option(ListValue, "name", translate ("Community")) community.rmempty = false local profile for profile in fs.glob(profiles) do local name = uci:get_first(profile, "community", "name") or "?" community:value(profile, name) end n = Map("system", translate("Basic system settings")) function n.on_after_commit(self) luci.http.redirect(luci.dispatcher.build_url("admin", "freifunk", "basics")) end b = n:section(TypedSection, "system") b.anonymous = true hn = b:option(Value, "hostname", translate("Hostname")) hn.rmempty = false hn.datatype = "hostname" loc = b:option(Value, "location", translate("Location")) loc.rmempty = false loc.datatype = "minlength(1)" lat = b:option(Value, "latitude", translate("Latitude"), translate("e.g.") .. " 48.12345") lat.datatype = "float" lat.rmempty = false lon = b:option(Value, "longitude", translate("Longitude"), translate("e.g.") .. " 10.12345") lon.datatype = "float" lon.rmempty = false --[[ Opens an OpenStreetMap iframe or popup Makes use of resources/OSMLatLon.htm and htdocs/resources/osm.js ]]-- local class = util.class local ff = uci:get("freifunk", "community", "name") or "" local co = "profile_" .. ff local deflat = uci:get_first("system", "system", "latitude") or uci:get_first(co, "community", "latitude") or 52 local deflon = uci:get_first("system", "system", "longitude") or uci:get_first(co, "community", "longitude") or 10 local zoom = 12 if ( deflat == 52 and deflon == 10 ) then zoom = 4 end OpenStreetMapLonLat = luci.util.class(AbstractValue) function OpenStreetMapLonLat.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/osmll_value" self.latfield = nil self.lonfield = nil self.centerlat = "" self.centerlon = "" self.zoom = "0" self.width = "100%" --popups will ignore the %-symbol, "100%" is interpreted as "100" self.height = "600" self.popup = false self.displaytext="OpenStreetMap" --text on button, that loads and displays the OSMap self.hidetext="X" -- text on button, that hides OSMap end osm = b:option(OpenStreetMapLonLat, "latlon", translate("Find your coordinates with OpenStreetMap"), translate("Select your location with a mouse click on the map. The map will only show up if you are connected to the Internet.")) osm.latfield = "latitude" osm.lonfield = "longitude" osm.centerlat = uci:get_first("system", "system", "latitude") or deflat osm.centerlon = uci:get_first("system", "system", "longitude") or deflon osm.zoom = zoom osm.width = "100%" osm.height = "600" osm.popup = false osm.displaytext=translate("Show OpenStreetMap") osm.hidetext=translate("Hide OpenStreetMap") return m, n
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2011 Manuel Munz <freifunk at somakoma de> -- Licensed to the public under the Apache License 2.0. local fs = require "nixio.fs" local util = require "luci.util" local uci = require "luci.model.uci".cursor() local profiles = "/etc/config/profile_*" m = Map("freifunk", translate ("Community")) c = m:section(NamedSection, "community", "public", nil, translate("These are the basic settings for your local wireless community. These settings define the default values for the wizard and DO NOT affect the actual configuration of the router.")) community = c:option(ListValue, "name", translate ("Community")) community.rmempty = false local profile for profile in fs.glob(profiles) do local name = uci:get_first(profile, "community", "name") or "?" community:value(string.gsub(profile, "/etc/config/profile_", ""), name) end n = Map("system", translate("Basic system settings")) function n.on_after_commit(self) luci.http.redirect(luci.dispatcher.build_url("admin", "freifunk", "basics")) end b = n:section(TypedSection, "system") b.anonymous = true hn = b:option(Value, "hostname", translate("Hostname")) hn.rmempty = false hn.datatype = "hostname" loc = b:option(Value, "location", translate("Location")) loc.rmempty = false loc.datatype = "minlength(1)" lat = b:option(Value, "latitude", translate("Latitude"), translate("e.g.") .. " 48.12345") lat.datatype = "float" lat.rmempty = false lon = b:option(Value, "longitude", translate("Longitude"), translate("e.g.") .. " 10.12345") lon.datatype = "float" lon.rmempty = false --[[ Opens an OpenStreetMap iframe or popup Makes use of resources/OSMLatLon.htm and htdocs/resources/osm.js ]]-- local class = util.class local ff = uci:get("freifunk", "community", "name") or "" local co = "profile_" .. ff local deflat = uci:get_first("system", "system", "latitude") or uci:get_first(co, "community", "latitude") or 52 local deflon = uci:get_first("system", "system", "longitude") or uci:get_first(co, "community", "longitude") or 10 local zoom = 12 if ( deflat == 52 and deflon == 10 ) then zoom = 4 end OpenStreetMapLonLat = luci.util.class(AbstractValue) function OpenStreetMapLonLat.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/osmll_value" self.latfield = nil self.lonfield = nil self.centerlat = "" self.centerlon = "" self.zoom = "0" self.width = "100%" --popups will ignore the %-symbol, "100%" is interpreted as "100" self.height = "600" self.popup = false self.displaytext="OpenStreetMap" --text on button, that loads and displays the OSMap self.hidetext="X" -- text on button, that hides OSMap end osm = b:option(OpenStreetMapLonLat, "latlon", translate("Find your coordinates with OpenStreetMap"), translate("Select your location with a mouse click on the map. The map will only show up if you are connected to the Internet.")) osm.latfield = "latitude" osm.lonfield = "longitude" osm.centerlat = uci:get_first("system", "system", "latitude") or deflat osm.centerlon = uci:get_first("system", "system", "longitude") or deflon osm.zoom = zoom osm.width = "100%" osm.height = "600" osm.popup = false osm.displaytext=translate("Show OpenStreetMap") osm.hidetext=translate("Hide OpenStreetMap") return m, n
luci-mod-freifunk: fix lookup of community-name
luci-mod-freifunk: fix lookup of community-name restore the lookup of the freifunk community-name stored in uci "freifunk.community.name". In https://github.com/openwrt/luci/commit/9780ee382e72f8a5fb69e337a3fcc51fc0914883 the value changed to the complete path of the community-profile, e.g. "/etc/config/profile_berlin". This causes lookup problems on other pages, like "mod-freifunk -> overview -> index" (view/freifunk/index.htm line37, line 54). And as the option suggests it's the community-name not the community-profile path. Signed-off-by: e0502648f5939f049f9f4747cb7ed6242a3eef23@geroedel.de
Lua
apache-2.0
kuoruan/lede-luci,shangjiyu/luci-with-extra,artynet/luci,nmav/luci,openwrt-es/openwrt-luci,remakeelectric/luci,Noltari/luci,nmav/luci,oneru/luci,chris5560/openwrt-luci,chris5560/openwrt-luci,kuoruan/luci,hnyman/luci,openwrt/luci,kuoruan/luci,wongsyrone/luci-1,aa65535/luci,chris5560/openwrt-luci,rogerpueyo/luci,chris5560/openwrt-luci,shangjiyu/luci-with-extra,openwrt/luci,taiha/luci,Wedmer/luci,teslamint/luci,remakeelectric/luci,wongsyrone/luci-1,Wedmer/luci,openwrt/luci,taiha/luci,cshore-firmware/openwrt-luci,cshore/luci,rogerpueyo/luci,lbthomsen/openwrt-luci,Noltari/luci,daofeng2015/luci,cshore-firmware/openwrt-luci,daofeng2015/luci,wongsyrone/luci-1,remakeelectric/luci,shangjiyu/luci-with-extra,teslamint/luci,tobiaswaldvogel/luci,nmav/luci,nmav/luci,Wedmer/luci,openwrt/luci,kuoruan/lede-luci,LuttyYang/luci,bittorf/luci,artynet/luci,Wedmer/luci,mumuqz/luci,mumuqz/luci,oneru/luci,artynet/luci,tobiaswaldvogel/luci,Noltari/luci,openwrt-es/openwrt-luci,daofeng2015/luci,Noltari/luci,LuttyYang/luci,981213/luci-1,openwrt/luci,tobiaswaldvogel/luci,taiha/luci,981213/luci-1,chris5560/openwrt-luci,kuoruan/lede-luci,kuoruan/luci,bittorf/luci,hnyman/luci,taiha/luci,nmav/luci,teslamint/luci,teslamint/luci,openwrt/luci,hnyman/luci,nmav/luci,daofeng2015/luci,Wedmer/luci,981213/luci-1,daofeng2015/luci,tobiaswaldvogel/luci,cshore/luci,mumuqz/luci,daofeng2015/luci,aa65535/luci,oneru/luci,Noltari/luci,cshore-firmware/openwrt-luci,kuoruan/luci,aa65535/luci,teslamint/luci,oneru/luci,daofeng2015/luci,bittorf/luci,rogerpueyo/luci,shangjiyu/luci-with-extra,tobiaswaldvogel/luci,hnyman/luci,remakeelectric/luci,hnyman/luci,artynet/luci,chris5560/openwrt-luci,mumuqz/luci,cshore-firmware/openwrt-luci,aa65535/luci,cshore/luci,mumuqz/luci,lbthomsen/openwrt-luci,remakeelectric/luci,shangjiyu/luci-with-extra,taiha/luci,rogerpueyo/luci,chris5560/openwrt-luci,981213/luci-1,LuttyYang/luci,artynet/luci,nmav/luci,openwrt-es/openwrt-luci,kuoruan/luci,LuttyYang/luci,cshore-firmware/openwrt-luci,wongsyrone/luci-1,openwrt-es/openwrt-luci,981213/luci-1,cshore/luci,openwrt-es/openwrt-luci,cshore/luci,lbthomsen/openwrt-luci,kuoruan/lede-luci,tobiaswaldvogel/luci,LuttyYang/luci,taiha/luci,rogerpueyo/luci,wongsyrone/luci-1,hnyman/luci,Noltari/luci,rogerpueyo/luci,rogerpueyo/luci,openwrt-es/openwrt-luci,kuoruan/lede-luci,lbthomsen/openwrt-luci,openwrt-es/openwrt-luci,Wedmer/luci,tobiaswaldvogel/luci,remakeelectric/luci,lbthomsen/openwrt-luci,rogerpueyo/luci,aa65535/luci,kuoruan/luci,artynet/luci,kuoruan/luci,lbthomsen/openwrt-luci,cshore/luci,mumuqz/luci,Noltari/luci,oneru/luci,981213/luci-1,oneru/luci,oneru/luci,tobiaswaldvogel/luci,openwrt/luci,bittorf/luci,bittorf/luci,daofeng2015/luci,oneru/luci,nmav/luci,LuttyYang/luci,artynet/luci,remakeelectric/luci,aa65535/luci,cshore-firmware/openwrt-luci,aa65535/luci,LuttyYang/luci,hnyman/luci,openwrt/luci,Wedmer/luci,Noltari/luci,chris5560/openwrt-luci,shangjiyu/luci-with-extra,kuoruan/lede-luci,cshore/luci,teslamint/luci,shangjiyu/luci-with-extra,artynet/luci,teslamint/luci,Wedmer/luci,artynet/luci,Noltari/luci,kuoruan/lede-luci,wongsyrone/luci-1,nmav/luci,cshore-firmware/openwrt-luci,aa65535/luci,lbthomsen/openwrt-luci,bittorf/luci,hnyman/luci,bittorf/luci,bittorf/luci,cshore-firmware/openwrt-luci,lbthomsen/openwrt-luci,shangjiyu/luci-with-extra,teslamint/luci,wongsyrone/luci-1,kuoruan/luci,mumuqz/luci,taiha/luci,cshore/luci,taiha/luci,981213/luci-1,openwrt-es/openwrt-luci,mumuqz/luci,LuttyYang/luci,wongsyrone/luci-1,remakeelectric/luci,kuoruan/lede-luci
5a36e5427f2eb9c7d0d91f0b2c69ae3292b34bc9
frontend/document/picdocument.lua
frontend/document/picdocument.lua
local Document = require("document/document") local DrawContext = require("ffi/drawcontext") local pic = nil local PicDocument = Document:new{ _document = false, dc_null = DrawContext.new() } function PicDocument:init() if not pic then pic = require("ffi/pic") end ok, self._document = pcall(pic.openDocument, self.file) if not ok then error("Failed to open jpeg image") end self.info.has_pages = true self.info.configurable = false self:readMetadata() end function PicDocument:readMetadata() self.info.number_of_pages = 1 end function PicDocument:register(registry) registry:addProvider("jpeg", "application/jpeg", self) registry:addProvider("jpg", "application/jpeg", self) end return PicDocument
local Document = require("document/document") local DrawContext = require("ffi/drawcontext") local pic = nil local PicDocument = Document:new{ _document = false, dc_null = DrawContext.new() } function PicDocument:init() if not pic then pic = require("ffi/pic") end ok, self._document = pcall(pic.openDocument, self.file) if not ok then error("Failed to open jpeg image") end self.info.has_pages = true self.info.configurable = false self:_readMetadata() end function PicDocument:getUsedBBox(pageno) return { x0 = 0, y0 = 0, x1 = self._document.width, y1 = self._document.height } end function PicDocument:register(registry) registry:addProvider("jpeg", "application/jpeg", self) registry:addProvider("jpg", "application/jpeg", self) end return PicDocument
fixes for picdocument
fixes for picdocument picdocument didn't use the document API correctly
Lua
agpl-3.0
houqp/koreader,Frenzie/koreader,ashhher3/koreader,pazos/koreader,NickSavage/koreader,lgeek/koreader,poire-z/koreader,koreader/koreader,ashang/koreader,poire-z/koreader,chrox/koreader,NiLuJe/koreader,Hzj-jie/koreader,Frenzie/koreader,apletnev/koreader,noname007/koreader,chihyang/koreader,mwoz123/koreader,frankyifei/koreader,robert00s/koreader,koreader/koreader,mihailim/koreader,NiLuJe/koreader,Markismus/koreader
f8082bc7c17d2e1db595823f63c3a6c57cdb75dd
BIOS/migrate080.lua
BIOS/migrate080.lua
--Migrating script from LIKO-12 0.8.0 and earlier. local HandledAPIS = ... --Peripherals local GPU = HandledAPIS.GPU local CPU = HandledAPIS.CPU local fs = HandledAPIS.HDD --Filesystem identity local nIdentity = love.filesystem.getIdentity() local oIdentity = "liko12" --Helper functions local function msg(...) GPU._systemMessage(table.concat({...}),3600,0,7) CPU.sleep(0) end --Activate old identity local function activate() love.filesystem.setIdentity(oIdentity) end --Deactivate old identity local function deactivate() love.filesystem.setIdentity(nIdentity) end --Directories indexing function. local function index(path,list,ext,rec) if not love.filesystem.getInfo(path) then return end for _,file in ipairs(love.filesystem.getDirectoryItems(path)) do if love.filesystem.getInfo(path..file).type == "file" then if not ext or file:sub(-#ext,-1) == ext then list[#list + 1] = path..file end elseif rec then index(path..file.."/",list,ext,rec) end end end --Start migrating msg("Migrating your old data (0%)...") local Data = {} --The files in the D drive. local Screenshots = {} --The .png files in the appdata folder. local GIFs = {} --The .gif files in the appdata folder. local Shaders = {} --The GPU shaders. activate() index("/",Screenshots,".png") index("/Screenshots",Screenshots,".png",true) index("/",GIFs,".gif") index("/GIF Recordings/",GIFs,".gif",true) index("/Shaders/",Shaders,false,true) index("/drives/D/",Data,false,true) if love.filesystem.getInfo("/drives/C/user.json") then Data[#Data + 1] = "/drives/C/user.json" end deactivate() local total = #Screenshots + #GIFs + #Shaders + #Data local processed = 0 local function progress(skip) if not skip then processed = processed + 1 end msg("Migrating your old data (",math.floor((processed/total)*100),"%)...") end for i=1, #Data do local src = Data[i] local dst = "/D"..src:sub(3,-1) activate() local data = love.filesystem.read(src) deactivate() love.filesystem.createDirectory(fs.getDirectory(dst)) love.filesystem.write(dst,data) progress() end for i=1, #Shaders do local path = Shaders[i] activate() local data = love.filesystem.read(path) deactivate() love.filesystem.createDirectory(fs.getDirectory(path)) love.filesystem.write(path,data) progress() end for i=1, #GIFs do local src = GIFs[i] local dst = src:sub(1,16) == "/GIF Recordings/" and src or "/GIF Recordings"..src activate() local data = love.filesystem.read(src) deactivate() love.filesystem.createDirectory(fs.getDirectory(dst)) love.filesystem.write(dst,data) progress() end for i=1, #Screenshots do local src = Screenshots[i] local dst = src:sub(1,13) == "/Screenshots/" and src or "/Screenshots"..src activate() local data = love.filesystem.read(src) deactivate() love.filesystem.createDirectory(fs.getDirectory(dst)) love.filesystem.write(dst,data) progress() end activate() if love.filesystem.getInfo(".version") then love.filesystem.remove(".version") end if love.filesystem.getInfo("Miscellaneous/.version") then love.filesystem.remove("Miscellaneous/.version") end deactivate() GPU._systemMessage("",0)
--Migrating script from LIKO-12 0.8.0 and earlier. local HandledAPIS = ... --Peripherals local GPU = HandledAPIS.GPU local CPU = HandledAPIS.CPU local fs = HandledAPIS.HDD --Filesystem identity local nIdentity = love.filesystem.getIdentity() local oIdentity = "liko12" --Helper functions local function msg(...) GPU._systemMessage(table.concat({...}),3600,0,7) CPU.sleep(0) end --Activate old identity local function activate() love.filesystem.setIdentity(oIdentity) end --Deactivate old identity local function deactivate() love.filesystem.setIdentity(nIdentity) end --Directories indexing function. local function index(path,list,ext,rec) if not love.filesystem.getInfo(path) then return end for _,file in ipairs(love.filesystem.getDirectoryItems(path)) do local info = love.filesystem.getInfo(path..file) if info and info.type == "file" then if not ext or file:sub(-#ext,-1) == ext then list[#list + 1] = path..file end elseif info and rec then index(path..file.."/",list,ext,rec) end end end --Start migrating msg("Migrating your old data (0%)...") local Data = {} --The files in the D drive. local Screenshots = {} --The .png files in the appdata folder. local GIFs = {} --The .gif files in the appdata folder. local Shaders = {} --The GPU shaders. activate() index("/",Screenshots,".png") index("/Screenshots",Screenshots,".png",true) index("/",GIFs,".gif") index("/GIF Recordings/",GIFs,".gif",true) index("/Shaders/",Shaders,false,true) index("/drives/D/",Data,false,true) if love.filesystem.getInfo("/drives/C/user.json") then Data[#Data + 1] = "/drives/C/user.json" end deactivate() local total = #Screenshots + #GIFs + #Shaders + #Data local processed = 0 local function progress(skip) if not skip then processed = processed + 1 end msg("Migrating your old data (",math.floor((processed/total)*100),"%)...") end for i=1, #Data do local src = Data[i] local dst = "/D"..src:sub(3,-1) activate() local data = love.filesystem.read(src) deactivate() love.filesystem.createDirectory(fs.getDirectory(dst)) love.filesystem.write(dst,data) progress() end for i=1, #Shaders do local path = Shaders[i] activate() local data = love.filesystem.read(path) deactivate() love.filesystem.createDirectory(fs.getDirectory(path)) love.filesystem.write(path,data) progress() end for i=1, #GIFs do local src = GIFs[i] local dst = src:sub(1,16) == "/GIF Recordings/" and src or "/GIF Recordings"..src activate() local data = love.filesystem.read(src) deactivate() love.filesystem.createDirectory(fs.getDirectory(dst)) love.filesystem.write(dst,data) progress() end for i=1, #Screenshots do local src = Screenshots[i] if src ~= "/icon.png" then local dst = src:sub(1,13) == "/Screenshots/" and src or "/Screenshots"..src activate() local data = love.filesystem.read(src) deactivate() love.filesystem.createDirectory(fs.getDirectory(dst)) love.filesystem.write(dst,data) progress() end end activate() if love.filesystem.getInfo(".version") then love.filesystem.remove(".version") end if love.filesystem.getInfo("Miscellaneous/.version") then love.filesystem.remove("Miscellaneous/.version") end deactivate() GPU._systemMessage("",0)
Tiny fix in the migrating script.
Tiny fix in the migrating script. Former-commit-id: 0fa1f32098f9d2776d8686064a16cd4a5ede7995
Lua
mit
RamiLego4Game/LIKO-12
e97dc6d38007d8b93cf138328963f2789a642527
test/lua/unit/url.lua
test/lua/unit/url.lua
-- URL parser tests context("URL check functions", function() local mpool = require("rspamd_mempool") local url = require("rspamd_url") local logger = require("rspamd_logger") local ffi = require("ffi") ffi.cdef[[ void rspamd_url_init (const char *tld_file); unsigned ottery_rand_range(unsigned top); ]] local pool = mpool.create() local test_dir = string.gsub(debug.getinfo(1).source, "^@(.+/)[^/]+$", "%1") ffi.C.rspamd_url_init(string.format('%s/%s', test_dir, "test_tld.dat")) test("Extract urls from text", function() local cases = { {"test.com text", {"test.com", nil}}, {"test.com. text", {"test.com", nil}}, {"mailto:A.User@example.com text", {"example.com", "A.User"}}, {"http://Тест.Рф:18 text", {"тест.рф", nil}}, {"http://user:password@тест2.РФ:18 text", {"тест2.рф", "user"}}, {"somebody@example.com", {"example.com", "somebody"}}, {"https://127.0.0.1/abc text", {"127.0.0.1", nil}}, {"https://127.0.0.1 text", {"127.0.0.1", nil}}, {"https://[::1]:1", {"::1", nil}}, {"https://user:password@[::1]:1", {"::1", nil}}, {"https://user:password@[::1]", {"::1", nil}}, {"https://user:password@[::1]/1", {"::1", nil}}, } for _,c in ipairs(cases) do local res = url.create(pool, c[1]) assert_not_nil(res, "cannot parse " .. c[1]) local t = res:to_table() --local s = logger.slog("%1 -> %2", c[1], t) --print(s) assert_not_nil(t, "cannot convert to table " .. c[1]) assert_equal(c[2][1], t['host']) if c[2][2] then assert_equal(c[2][2], t['user']) end end end) pool:destroy() end)
-- URL parser tests context("URL check functions", function() local mpool = require("rspamd_mempool") local url = require("rspamd_url") local logger = require("rspamd_logger") local ffi = require("ffi") ffi.cdef[[ void rspamd_url_init (const char *tld_file); unsigned ottery_rand_range(unsigned top); ]] local test_dir = string.gsub(debug.getinfo(1).source, "^@(.+/)[^/]+$", "%1") ffi.C.rspamd_url_init(string.format('%s/%s', test_dir, "test_tld.dat")) test("Extract urls from text", function() local pool = mpool.create() local cases = { {"test.com text", {"test.com", nil}}, {"test.com. text", {"test.com", nil}}, {"mailto:A.User@example.com text", {"example.com", "A.User"}}, {"http://Тест.Рф:18 text", {"тест.рф", nil}}, {"http://user:password@тест2.РФ:18 text", {"тест2.рф", "user"}}, {"somebody@example.com", {"example.com", "somebody"}}, {"https://127.0.0.1/abc text", {"127.0.0.1", nil}}, {"https://127.0.0.1 text", {"127.0.0.1", nil}}, {"https://[::1]:1", {"::1", nil}}, {"https://user:password@[::1]:1", {"::1", nil}}, {"https://user:password@[::1]", {"::1", nil}}, {"https://user:password@[::1]/1", {"::1", nil}}, } for _,c in ipairs(cases) do local res = url.create(pool, c[1]) assert_not_nil(res, "cannot parse " .. c[1]) local t = res:to_table() --local s = logger.slog("%1 -> %2", c[1], t) --print(s) assert_not_nil(t, "cannot convert to table " .. c[1]) assert_equal(c[2][1], t['host']) if c[2][2] then assert_equal(c[2][2], t['user']) end end pool:destroy() end) end)
Fix closure lifetime in tests.
Fix closure lifetime in tests.
Lua
apache-2.0
minaevmike/rspamd,dark-al/rspamd,andrejzverev/rspamd,dark-al/rspamd,awhitesong/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,minaevmike/rspamd,AlexeySa/rspamd,dark-al/rspamd,andrejzverev/rspamd,amohanta/rspamd,AlexeySa/rspamd,minaevmike/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,awhitesong/rspamd,dark-al/rspamd,AlexeySa/rspamd,amohanta/rspamd,amohanta/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,amohanta/rspamd,minaevmike/rspamd,awhitesong/rspamd,awhitesong/rspamd,andrejzverev/rspamd,dark-al/rspamd,minaevmike/rspamd,andrejzverev/rspamd,minaevmike/rspamd,amohanta/rspamd,AlexeySa/rspamd,minaevmike/rspamd,minaevmike/rspamd,minaevmike/rspamd,andrejzverev/rspamd
d1c1639b754efe2d63c38165e708f340a35c9289
aspects/nvim/files/.config/nvim/lua/wincent/mappings/leader.lua
aspects/nvim/files/.config/nvim/lua/wincent/mappings/leader.lua
local leader = {} local number_flag = 'wincent_number' local cycle_numbering = function() local relativenumber = vim.wo.relativenumber local number = vim.wo.number -- Cycle through: -- - relativenumber + number -- - number (only) -- - no numbering if (vim.deep_equal({relativenumber, number}, {true, true})) then relativenumber, number = false, true elseif (vim.deep_equal({relativenumber, number}, {false, true})) then relativenumber, number = false, false elseif (vim.deep_equal({relativenumber, number}, {false, false})) then relativenumber, number = true, true elseif (vim.deep_equal({relativenumber, number}, {true, false})) then relativenumber, number = false, true end vim.wo.relativenumber = relativenumber vim.wo.number = number -- Leave a mark so that other functions can check to see if the user has -- overridden the settings for this window. vim.w[number_flag] = true end -- Based on: http://vim.wikia.com/wiki/Identify_the_syntax_highlighting_group_used_at_the_cursor local get_highlight_group = function() local pos = vim.api.nvim_win_get_cursor(0) local line = pos[1] local col = pos[2] local synID = vim.fn.synID local synIDattr = vim.fn.synIDattr local synIDtrans = vim.fn.synIDtrans return ( 'hi<' .. synIDattr(synID(line, col, true), 'name') .. '> trans<' .. synIDattr(synID(line, col, false), 'name') .. '> lo<' .. synIDattr(synIDtrans(synID(line, col, true)), 'name') .. '>' ) end local jump = function(mapping) local key = vim.api.nvim_replace_termcodes(mapping, true, false, true) local previous_file = vim.api.nvim_buf_get_name(0) local previous_row, previous_column = unpack(vim.api.nvim_win_get_cursor(0)) local limit = 100 while limit > 0 do vim.api.nvim_feedkeys(key, 'n', true) local next_file = vim.api.nvim_buf_get_name(0) local next_row, next_column = unpack(vim.api.nvim_win_get_cursor(0)) if next_file ~= previous_file then -- We successfully moved to the next file; we're done. return elseif next_row == previous_row and next_column == previous_column then -- We're at the end of the jumplist; we're done. print('No more jumps!') return end previous_file = next_file previous_row = next_row previous_column = next_column limit = limit - 1 end print('Jump limit exceeded! (Aborting)') end local jump_in_file = function () jump('<F6>') end local jump_out_file = function () jump('<C-o>') end -- TODO: split into files leader.cycle_numbering = cycle_numbering leader.get_highlight_group = get_highlight_group leader.jump_in_file = jump_in_file leader.jump_out_file = jump_out_file leader.number_flag = number_flag return leader
local leader = {} local number_flag = 'wincent_number' local cycle_numbering = function() local relativenumber = vim.wo.relativenumber local number = vim.wo.number -- Cycle through: -- - relativenumber + number -- - number (only) -- - no numbering if (vim.deep_equal({relativenumber, number}, {true, true})) then relativenumber, number = false, true elseif (vim.deep_equal({relativenumber, number}, {false, true})) then relativenumber, number = false, false elseif (vim.deep_equal({relativenumber, number}, {false, false})) then relativenumber, number = true, true elseif (vim.deep_equal({relativenumber, number}, {true, false})) then relativenumber, number = false, true end vim.wo.relativenumber = relativenumber vim.wo.number = number -- Leave a mark so that other functions can check to see if the user has -- overridden the settings for this window. vim.w[number_flag] = true end -- Based on: http://vim.wikia.com/wiki/Identify_the_syntax_highlighting_group_used_at_the_cursor local get_highlight_group = function() local pos = vim.api.nvim_win_get_cursor(0) local line = pos[1] local col = pos[2] local synID = vim.fn.synID local synIDattr = vim.fn.synIDattr local synIDtrans = vim.fn.synIDtrans return ( 'hi<' .. synIDattr(synID(line, col, true), 'name') .. '> trans<' .. synIDattr(synID(line, col, false), 'name') .. '> lo<' .. synIDattr(synIDtrans(synID(line, col, true)), 'name') .. '>' ) end local jump = function(mapping) local key = vim.api.nvim_replace_termcodes(mapping, true, false, true) local previous_file = vim.api.nvim_buf_get_name(0) local previous_row, previous_column = unpack(vim.api.nvim_win_get_cursor(0)) local limit = 100 local step step = function () vim.api.nvim_feedkeys(key, 'n', true) -- Need small delay for feedkeys side-effects to finalize. vim.defer_fn(function() local next_file = vim.api.nvim_buf_get_name(0) local next_row, next_column = unpack(vim.api.nvim_win_get_cursor(0)) if next_file ~= previous_file then -- We successfully moved to the next file; we're done. return elseif next_row == previous_row and next_column == previous_column then -- BUG: if the mark points at an invalid line number (can easily happen -- in .git/COMMIT_EDITMSG, for example) we may bail here because line -- number won't change — to be really robust we'd need to parse :jumps -- output print('No more jumps!') return elseif limit < 0 then print('Jump limit exceeded! (Aborting)') return end previous_file = next_file previous_row = next_row previous_column = next_column limit = limit - 1 -- Recurse. step() end, 0) end step() end local jump_in_file = function () jump('<C-i>') end local jump_out_file = function () jump('<C-o>') end -- TODO: split into files leader.cycle_numbering = cycle_numbering leader.get_highlight_group = get_highlight_group leader.jump_in_file = jump_in_file leader.jump_out_file = jump_out_file leader.number_flag = number_flag return leader
fix(nvim): make jump list step function to overcome feedkeys latency
fix(nvim): make jump list step function to overcome feedkeys latency As mentioned in the parent commit, we have to wait a bit to actually see the effects of the feedkeys call. But as noted in the "BUG:" comment, this is still edge-casey enough that I probably have to resort to parsing the `:jumps` output in order to reliably detect forwards progress (and if I am going to do that, maybe I can dispense with reading the buffer name entirely and just enqueue a number of feedkeys calls directly; maybe even a single call containing repeated presses).
Lua
unlicense
wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent
1fa82a793721a8cd1696e6053a0351188b706f31
protocols/core/luasrc/model/cbi/admin_network/proto_dhcp.lua
protocols/core/luasrc/model/cbi/admin_network/proto_dhcp.lua
--[[ LuCI - Lua Configuration Interface Copyright 2011 Jo-Philipp Wich <xm@subsignal.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 ]]-- local map, section, net = ... local ifc = net:get_interface() local hostname, accept_ra, send_rs local bcast, no_gw, no_dns, dns, metric, clientid, vendorclass hostname = section:taboption("general", Value, "hostname", translate("Hostname to send when requesting DHCP")) hostname.placeholder = luci.sys.hostname() hostname.datatype = "hostname" if luci.model.network:has_ipv6() then accept_ra = s:taboption("general", Flag, "accept_ra", translate("Accept router advertisements")) accept_ra.default = accept_ra.enabled send_rs = s:taboption("general", Flag, "send_rs", translate("Send router solicitations")) send_rs.default = send_rs.disabled send_rs:depends("accept_ra", "") end bcast = section:taboption("advanced", Flag, "broadcast", translate("Use broadcast flag"), translate("Required for certain ISPs, e.g. Charter with DOCSIS 3")) bcast.default = bcast.disabled no_gw = section:taboption("advanced", Flag, "gateway", translate("Use default gateway"), translate("If unchecked, no default route is configured")) no_gw.default = no_gw.enabled function no_gw.cfgvalue(...) return Flag.cfgvalue(...) == "0.0.0.0" and "0" or "1" end function no_gw.write(self, section, value) if value == "1" then m:set(section, "gateway", nil) else m:set(section, "gateway", "0.0.0.0") end end no_dns = section:taboption("advanced", Flag, "_no_dns", translate("Use DNS servers advertised by peer"), translate("If unchecked, the advertised DNS server addresses are ignored")) no_dns.default = no_dns.enabled function no_dns.cfgvalue(self, section) local addr for addr in luci.util.imatch(m:get(section, "dns")) do return self.disabled end return self.enabled end function no_dns.remove(self, section) return m:del(section, "dns") end function no_dns.write() end dns = section:taboption("advanced", DynamicList, "dns", translate("Use custom DNS servers")) dns:depends("_no_dns", "") dns.datatype = "ipaddr" dns.cast = "string" metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger" metric:depends("gateway", "1") clientid = section:taboption("advanced", Value, "clientid", translate("Client ID to send when requesting DHCP")) vendorclass = section:taboption("advanced", Value, "vendorid", translate("Vendor Class to send when requesting DHCP")) macaddr = section:taboption("advanced", Value, "macaddr", translate("Override MAC address")) macaddr.placeholder = ifc and ifc:mac() or "00:00:00:00:00:00" macaddr.datatype = "macaddr" mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU")) mtu.placeholder = "1500" mtu.datatype = "max(1500)"
--[[ LuCI - Lua Configuration Interface Copyright 2011-2012 Jo-Philipp Wich <xm@subsignal.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 ]]-- local map, section, net = ... local ifc = net:get_interface() local hostname, accept_ra, send_rs local bcast, no_gw, peerdns, dns, metric, clientid, vendorclass hostname = section:taboption("general", Value, "hostname", translate("Hostname to send when requesting DHCP")) hostname.placeholder = luci.sys.hostname() hostname.datatype = "hostname" if luci.model.network:has_ipv6() then accept_ra = s:taboption("general", Flag, "accept_ra", translate("Accept router advertisements")) accept_ra.default = accept_ra.enabled send_rs = s:taboption("general", Flag, "send_rs", translate("Send router solicitations")) send_rs.default = send_rs.disabled send_rs:depends("accept_ra", "") end bcast = section:taboption("advanced", Flag, "broadcast", translate("Use broadcast flag"), translate("Required for certain ISPs, e.g. Charter with DOCSIS 3")) bcast.default = bcast.disabled no_gw = section:taboption("advanced", Flag, "gateway", translate("Use default gateway"), translate("If unchecked, no default route is configured")) no_gw.default = no_gw.enabled function no_gw.cfgvalue(...) return Flag.cfgvalue(...) == "0.0.0.0" and "0" or "1" end function no_gw.write(self, section, value) if value == "1" then m:set(section, "gateway", nil) else m:set(section, "gateway", "0.0.0.0") end end peerdns = section:taboption("advanced", Flag, "peerdns", translate("Use DNS servers advertised by peer"), translate("If unchecked, the advertised DNS server addresses are ignored")) peerdns.default = peerdns.enabled dns = section:taboption("advanced", DynamicList, "dns", translate("Use custom DNS servers")) dns:depends("peerdns", "") dns.datatype = "ipaddr" dns.cast = "string" metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger" metric:depends("gateway", "1") clientid = section:taboption("advanced", Value, "clientid", translate("Client ID to send when requesting DHCP")) vendorclass = section:taboption("advanced", Value, "vendorid", translate("Vendor Class to send when requesting DHCP")) macaddr = section:taboption("advanced", Value, "macaddr", translate("Override MAC address")) macaddr.placeholder = ifc and ifc:mac() or "00:00:00:00:00:00" macaddr.datatype = "macaddr" mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU")) mtu.placeholder = "1500" mtu.datatype = "max(1500)"
protocols/core: fix peerdns option for dhcp proto
protocols/core: fix peerdns option for dhcp proto
Lua
apache-2.0
jorgifumi/luci,shangjiyu/luci-with-extra,slayerrensky/luci,palmettos/cnLuCI,chris5560/openwrt-luci,obsy/luci,aa65535/luci,mumuqz/luci,981213/luci-1,kuoruan/lede-luci,tcatm/luci,lcf258/openwrtcn,daofeng2015/luci,Noltari/luci,deepak78/new-luci,jorgifumi/luci,schidler/ionic-luci,obsy/luci,thess/OpenWrt-luci,dwmw2/luci,artynet/luci,Wedmer/luci,zhaoxx063/luci,maxrio/luci981213,jlopenwrtluci/luci,cshore/luci,david-xiao/luci,teslamint/luci,palmettos/test,david-xiao/luci,nwf/openwrt-luci,981213/luci-1,remakeelectric/luci,Sakura-Winkey/LuCI,lbthomsen/openwrt-luci,oneru/luci,oyido/luci,oyido/luci,Noltari/luci,palmettos/test,sujeet14108/luci,aircross/OpenWrt-Firefly-LuCI,Kyklas/luci-proto-hso,hnyman/luci,aa65535/luci,RedSnake64/openwrt-luci-packages,LuttyYang/luci,joaofvieira/luci,hnyman/luci,MinFu/luci,nmav/luci,teslamint/luci,remakeelectric/luci,Noltari/luci,jlopenwrtluci/luci,NeoRaider/luci,openwrt/luci,forward619/luci,Noltari/luci,tcatm/luci,openwrt-es/openwrt-luci,openwrt/luci,forward619/luci,ReclaimYourPrivacy/cloak-luci,jlopenwrtluci/luci,NeoRaider/luci,zhaoxx063/luci,Wedmer/luci,deepak78/new-luci,shangjiyu/luci-with-extra,oyido/luci,zhaoxx063/luci,jorgifumi/luci,Hostle/luci,db260179/openwrt-bpi-r1-luci,bright-things/ionic-luci,nmav/luci,RuiChen1113/luci,palmettos/test,deepak78/new-luci,dismantl/luci-0.12,nwf/openwrt-luci,bright-things/ionic-luci,fkooman/luci,RedSnake64/openwrt-luci-packages,aa65535/luci,lbthomsen/openwrt-luci,kuoruan/luci,cshore-firmware/openwrt-luci,urueedi/luci,oneru/luci,kuoruan/lede-luci,kuoruan/lede-luci,florian-shellfire/luci,oyido/luci,db260179/openwrt-bpi-r1-luci,cshore-firmware/openwrt-luci,jchuang1977/luci-1,taiha/luci,schidler/ionic-luci,schidler/ionic-luci,jchuang1977/luci-1,hnyman/luci,zhaoxx063/luci,db260179/openwrt-bpi-r1-luci,taiha/luci,shangjiyu/luci-with-extra,bittorf/luci,fkooman/luci,artynet/luci,LazyZhu/openwrt-luci-trunk-mod,ff94315/luci-1,taiha/luci,remakeelectric/luci,tobiaswaldvogel/luci,forward619/luci,david-xiao/luci,Wedmer/luci,wongsyrone/luci-1,lcf258/openwrtcn,db260179/openwrt-bpi-r1-luci,slayerrensky/luci,dismantl/luci-0.12,cshore/luci,maxrio/luci981213,Hostle/luci,harveyhu2012/luci,joaofvieira/luci,florian-shellfire/luci,MinFu/luci,shangjiyu/luci-with-extra,male-puppies/luci,schidler/ionic-luci,ff94315/luci-1,Hostle/luci,aircross/OpenWrt-Firefly-LuCI,keyidadi/luci,artynet/luci,Kyklas/luci-proto-hso,shangjiyu/luci-with-extra,keyidadi/luci,ollie27/openwrt_luci,remakeelectric/luci,jchuang1977/luci-1,lcf258/openwrtcn,rogerpueyo/luci,oyido/luci,RedSnake64/openwrt-luci-packages,palmettos/cnLuCI,LazyZhu/openwrt-luci-trunk-mod,urueedi/luci,slayerrensky/luci,opentechinstitute/luci,marcel-sch/luci,openwrt/luci,oneru/luci,kuoruan/luci,openwrt-es/openwrt-luci,taiha/luci,openwrt-es/openwrt-luci,aa65535/luci,thesabbir/luci,Hostle/luci,marcel-sch/luci,Kyklas/luci-proto-hso,deepak78/new-luci,jchuang1977/luci-1,Wedmer/luci,Kyklas/luci-proto-hso,Hostle/luci,tcatm/luci,Hostle/openwrt-luci-multi-user,daofeng2015/luci,RuiChen1113/luci,jchuang1977/luci-1,urueedi/luci,Hostle/luci,obsy/luci,joaofvieira/luci,chris5560/openwrt-luci,thesabbir/luci,lcf258/openwrtcn,bright-things/ionic-luci,artynet/luci,LazyZhu/openwrt-luci-trunk-mod,nmav/luci,rogerpueyo/luci,cappiewu/luci,Noltari/luci,981213/luci-1,palmettos/test,jlopenwrtluci/luci,kuoruan/lede-luci,thess/OpenWrt-luci,dwmw2/luci,tobiaswaldvogel/luci,ollie27/openwrt_luci,daofeng2015/luci,teslamint/luci,dwmw2/luci,NeoRaider/luci,Sakura-Winkey/LuCI,thesabbir/luci,florian-shellfire/luci,palmettos/test,wongsyrone/luci-1,kuoruan/luci,hnyman/luci,NeoRaider/luci,jlopenwrtluci/luci,ff94315/luci-1,fkooman/luci,lbthomsen/openwrt-luci,urueedi/luci,maxrio/luci981213,wongsyrone/luci-1,joaofvieira/luci,slayerrensky/luci,schidler/ionic-luci,keyidadi/luci,ollie27/openwrt_luci,artynet/luci,cshore-firmware/openwrt-luci,cshore/luci,keyidadi/luci,tobiaswaldvogel/luci,LazyZhu/openwrt-luci-trunk-mod,marcel-sch/luci,tobiaswaldvogel/luci,sujeet14108/luci,openwrt/luci,artynet/luci,Hostle/openwrt-luci-multi-user,db260179/openwrt-bpi-r1-luci,lcf258/openwrtcn,zhaoxx063/luci,981213/luci-1,opentechinstitute/luci,RedSnake64/openwrt-luci-packages,aircross/OpenWrt-Firefly-LuCI,opentechinstitute/luci,Hostle/openwrt-luci-multi-user,palmettos/cnLuCI,Sakura-Winkey/LuCI,ReclaimYourPrivacy/cloak-luci,jchuang1977/luci-1,dismantl/luci-0.12,tcatm/luci,wongsyrone/luci-1,thesabbir/luci,lbthomsen/openwrt-luci,nwf/openwrt-luci,david-xiao/luci,teslamint/luci,Wedmer/luci,aa65535/luci,RedSnake64/openwrt-luci-packages,aa65535/luci,male-puppies/luci,palmettos/test,fkooman/luci,obsy/luci,MinFu/luci,cshore/luci,bittorf/luci,nmav/luci,bittorf/luci,obsy/luci,urueedi/luci,db260179/openwrt-bpi-r1-luci,ReclaimYourPrivacy/cloak-luci,joaofvieira/luci,cshore-firmware/openwrt-luci,Hostle/openwrt-luci-multi-user,nmav/luci,981213/luci-1,urueedi/luci,jchuang1977/luci-1,LuttyYang/luci,nmav/luci,Sakura-Winkey/LuCI,oneru/luci,aircross/OpenWrt-Firefly-LuCI,teslamint/luci,openwrt/luci,chris5560/openwrt-luci,Kyklas/luci-proto-hso,thess/OpenWrt-luci,MinFu/luci,teslamint/luci,maxrio/luci981213,kuoruan/luci,dwmw2/luci,RedSnake64/openwrt-luci-packages,fkooman/luci,jorgifumi/luci,mumuqz/luci,MinFu/luci,cappiewu/luci,Sakura-Winkey/LuCI,cappiewu/luci,wongsyrone/luci-1,david-xiao/luci,opentechinstitute/luci,RedSnake64/openwrt-luci-packages,kuoruan/lede-luci,cshore/luci,RuiChen1113/luci,maxrio/luci981213,oneru/luci,nwf/openwrt-luci,cshore/luci,schidler/ionic-luci,slayerrensky/luci,opentechinstitute/luci,maxrio/luci981213,slayerrensky/luci,chris5560/openwrt-luci,NeoRaider/luci,chris5560/openwrt-luci,joaofvieira/luci,db260179/openwrt-bpi-r1-luci,ReclaimYourPrivacy/cloak-luci,MinFu/luci,openwrt-es/openwrt-luci,oneru/luci,RuiChen1113/luci,florian-shellfire/luci,cshore-firmware/openwrt-luci,david-xiao/luci,RuiChen1113/luci,nwf/openwrt-luci,artynet/luci,lcf258/openwrtcn,aircross/OpenWrt-Firefly-LuCI,LazyZhu/openwrt-luci-trunk-mod,sujeet14108/luci,chris5560/openwrt-luci,hnyman/luci,jorgifumi/luci,NeoRaider/luci,Wedmer/luci,schidler/ionic-luci,nmav/luci,forward619/luci,lcf258/openwrtcn,hnyman/luci,obsy/luci,harveyhu2012/luci,lbthomsen/openwrt-luci,keyidadi/luci,marcel-sch/luci,cappiewu/luci,981213/luci-1,tobiaswaldvogel/luci,wongsyrone/luci-1,cappiewu/luci,jlopenwrtluci/luci,rogerpueyo/luci,fkooman/luci,hnyman/luci,kuoruan/luci,Noltari/luci,remakeelectric/luci,keyidadi/luci,forward619/luci,bittorf/luci,male-puppies/luci,openwrt-es/openwrt-luci,thesabbir/luci,kuoruan/luci,florian-shellfire/luci,male-puppies/luci,deepak78/new-luci,dwmw2/luci,Sakura-Winkey/LuCI,dismantl/luci-0.12,aircross/OpenWrt-Firefly-LuCI,ff94315/luci-1,palmettos/test,openwrt/luci,jlopenwrtluci/luci,mumuqz/luci,thesabbir/luci,ff94315/luci-1,bright-things/ionic-luci,deepak78/new-luci,aircross/OpenWrt-Firefly-LuCI,marcel-sch/luci,male-puppies/luci,bittorf/luci,harveyhu2012/luci,thess/OpenWrt-luci,ff94315/luci-1,oyido/luci,cappiewu/luci,LuttyYang/luci,taiha/luci,cshore/luci,fkooman/luci,sujeet14108/luci,sujeet14108/luci,david-xiao/luci,opentechinstitute/luci,openwrt-es/openwrt-luci,jchuang1977/luci-1,ff94315/luci-1,dismantl/luci-0.12,jorgifumi/luci,shangjiyu/luci-with-extra,981213/luci-1,cshore-firmware/openwrt-luci,fkooman/luci,Wedmer/luci,harveyhu2012/luci,zhaoxx063/luci,taiha/luci,maxrio/luci981213,cappiewu/luci,lbthomsen/openwrt-luci,florian-shellfire/luci,teslamint/luci,Kyklas/luci-proto-hso,NeoRaider/luci,Sakura-Winkey/LuCI,joaofvieira/luci,schidler/ionic-luci,Noltari/luci,kuoruan/lede-luci,obsy/luci,forward619/luci,Hostle/openwrt-luci-multi-user,zhaoxx063/luci,mumuqz/luci,florian-shellfire/luci,bright-things/ionic-luci,aa65535/luci,RuiChen1113/luci,deepak78/new-luci,harveyhu2012/luci,tcatm/luci,LazyZhu/openwrt-luci-trunk-mod,obsy/luci,thesabbir/luci,nmav/luci,bright-things/ionic-luci,thess/OpenWrt-luci,bittorf/luci,opentechinstitute/luci,ReclaimYourPrivacy/cloak-luci,kuoruan/luci,artynet/luci,openwrt-es/openwrt-luci,Noltari/luci,ollie27/openwrt_luci,shangjiyu/luci-with-extra,Hostle/openwrt-luci-multi-user,rogerpueyo/luci,lcf258/openwrtcn,ReclaimYourPrivacy/cloak-luci,daofeng2015/luci,chris5560/openwrt-luci,marcel-sch/luci,sujeet14108/luci,Wedmer/luci,palmettos/cnLuCI,Hostle/luci,ollie27/openwrt_luci,nwf/openwrt-luci,maxrio/luci981213,slayerrensky/luci,MinFu/luci,mumuqz/luci,mumuqz/luci,nwf/openwrt-luci,RuiChen1113/luci,ollie27/openwrt_luci,kuoruan/luci,wongsyrone/luci-1,cappiewu/luci,jorgifumi/luci,male-puppies/luci,dwmw2/luci,sujeet14108/luci,hnyman/luci,Hostle/openwrt-luci-multi-user,LuttyYang/luci,taiha/luci,Noltari/luci,cshore-firmware/openwrt-luci,LuttyYang/luci,tcatm/luci,marcel-sch/luci,RuiChen1113/luci,ff94315/luci-1,lbthomsen/openwrt-luci,urueedi/luci,bittorf/luci,wongsyrone/luci-1,thesabbir/luci,rogerpueyo/luci,ReclaimYourPrivacy/cloak-luci,forward619/luci,Hostle/openwrt-luci-multi-user,dismantl/luci-0.12,bright-things/ionic-luci,remakeelectric/luci,oneru/luci,ReclaimYourPrivacy/cloak-luci,harveyhu2012/luci,rogerpueyo/luci,openwrt/luci,oyido/luci,palmettos/cnLuCI,sujeet14108/luci,dwmw2/luci,ollie27/openwrt_luci,male-puppies/luci,LazyZhu/openwrt-luci-trunk-mod,teslamint/luci,remakeelectric/luci,remakeelectric/luci,thess/OpenWrt-luci,LuttyYang/luci,kuoruan/lede-luci,cshore-firmware/openwrt-luci,aa65535/luci,david-xiao/luci,opentechinstitute/luci,palmettos/test,NeoRaider/luci,thess/OpenWrt-luci,mumuqz/luci,cshore/luci,marcel-sch/luci,mumuqz/luci,tobiaswaldvogel/luci,keyidadi/luci,nwf/openwrt-luci,tobiaswaldvogel/luci,florian-shellfire/luci,forward619/luci,keyidadi/luci,zhaoxx063/luci,rogerpueyo/luci,palmettos/cnLuCI,jorgifumi/luci,daofeng2015/luci,tcatm/luci,lcf258/openwrtcn,joaofvieira/luci,chris5560/openwrt-luci,oyido/luci,lcf258/openwrtcn,bittorf/luci,Sakura-Winkey/LuCI,LuttyYang/luci,MinFu/luci,palmettos/cnLuCI,urueedi/luci,dismantl/luci-0.12,LazyZhu/openwrt-luci-trunk-mod,bright-things/ionic-luci,db260179/openwrt-bpi-r1-luci,tcatm/luci,artynet/luci,rogerpueyo/luci,harveyhu2012/luci,male-puppies/luci,jlopenwrtluci/luci,Hostle/luci,tobiaswaldvogel/luci,thess/OpenWrt-luci,lbthomsen/openwrt-luci,nmav/luci,kuoruan/lede-luci,Kyklas/luci-proto-hso,LuttyYang/luci,oneru/luci,daofeng2015/luci,openwrt/luci,deepak78/new-luci,daofeng2015/luci,palmettos/cnLuCI,slayerrensky/luci,shangjiyu/luci-with-extra,daofeng2015/luci,dwmw2/luci,openwrt-es/openwrt-luci,taiha/luci,ollie27/openwrt_luci
6ba5a6a824a9501430bbd4163824b75f5f12f797
src/cancellabledelay/src/Shared/cancellableDelay.lua
src/cancellabledelay/src/Shared/cancellableDelay.lua
--[=[ A version of task.delay that can be cancelled. Soon to be useless. @class cancellableDelay ]=] --[=[ @function cancellableDelay @param timeoutInSeconds number @param func function @param ... any -- Args to pass into the function @return function? -- Can be used to cancel @within cancellableDelay ]=] local function cancellableDelay(timeoutInSeconds, func, ...) assert(type(timeoutInSeconds) == "number", "Bad timeoutInSeconds") assert(type(func) == "function", "Bad func") local args = table.pack(...) local running task.spawn(function() running = coroutine.running() task.wait(timeoutInSeconds) func(table.unpack(args, 1, args.n)) end) return function() if running then coroutine.close(running) running = nil args = nil end end end return cancellableDelay
--[=[ A version of task.delay that can be cancelled. Soon to be useless. @class cancellableDelay ]=] --[=[ @function cancellableDelay @param timeoutInSeconds number @param func function @param ... any -- Args to pass into the function @return function? -- Can be used to cancel @within cancellableDelay ]=] local function cancellableDelay(timeoutInSeconds, func, ...) assert(type(timeoutInSeconds) == "number", "Bad timeoutInSeconds") assert(type(func) == "function", "Bad func") local args = table.pack(...) local running task.spawn(function() running = coroutine.running() task.wait(timeoutInSeconds) func(table.unpack(args, 1, args.n)) end) return function() if running then -- selene: allow(incorrect_standard_library_use) coroutine.close(running) running = nil args = nil end end end return cancellableDelay
style: Fix linter
style: Fix linter
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
f953eb8650073a3da5b551239c87e8d9391bc858
src/maid/src/Shared/Maid.lua
src/maid/src/Shared/Maid.lua
--[=[ Manages the cleaning of events and other things. Useful for encapsulating state and make deconstructors easy. See the [Five Powerful Code Patterns talk](https://developer.roblox.com/en-us/videos/5-powerful-code-patterns-behind-top-roblox-games) for a more in-depth look at Maids in top games. ```lua local maid = Maid.new() maid:GiveTask(function() print("Cleaning up") end) maid:GiveTask(workspace.ChildAdded:Connect(print)) -- Disconnects all events, and executes all functions maid:DoCleaning() ``` @class Maid ]=] -- luacheck: pop local Maid = {} Maid.ClassName = "Maid" --[=[ Constructs a new Maid object ```lua local maid = Maid.new() ``` @return Maid ]=] function Maid.new() return setmetatable({ _tasks = {} }, Maid) end --[=[ Returns true if the class is a maid, and false otherwise. ```lua print(Maid.isMaid(Maid.new())) --> true print(Maid.isMaid(nil)) --> false ``` @param value any @return boolean ]=] function Maid.isMaid(value) return type(value) == "table" and value.ClassName == "Maid" end --[=[ Returns Maid[key] if not part of Maid metatable ```lua local maid = Maid.new() maid._current = Instance.new("Part") print(maid._current) --> Part maid._current = nil print(maid._current) --> nil ``` @param index any @return MaidTask ]=] function Maid:__index(index) if Maid[index] then return Maid[index] else return self._tasks[index] end end --[=[ Add a task to clean up. Tasks given to a maid will be cleaned when maid[index] is set to a different value. Task cleanup is such that if the task is an event, it is disconnected. If it is an object, it is destroyed. ``` Maid[key] = (function) Adds a task to perform Maid[key] = (event connection) Manages an event connection Maid[key] = (thread) Manages a thread Maid[key] = (Maid) Maids can act as an event connection, allowing a Maid to have other maids to clean up. Maid[key] = (Object) Maids can cleanup objects with a `Destroy` method Maid[key] = nil Removes a named task. ``` @param index any @param newTask MaidTask ]=] function Maid:__newindex(index, newTask) if Maid[index] ~= nil then error(("Cannot use '%s' as a Maid key"):format(tostring(index)), 2) end local tasks = self._tasks local oldTask = tasks[index] if oldTask == newTask then return end tasks[index] = newTask if oldTask then if type(oldTask) == "function" then oldTask() elseif typeof(oldTask) == "RBXScriptConnection" then oldTask:Disconnect() elseif oldTask.Destroy then oldTask:Destroy() end end end --[=[ Gives a task to the maid for cleanup, but uses an incremented number as a key. @param task MaidTask -- An item to clean @return number -- taskId ]=] function Maid:GiveTask(task) if not task then error("Task cannot be false or nil", 2) end local taskId = #self._tasks+1 self[taskId] = task if type(task) == "table" and (not task.Destroy) then warn("[Maid.GiveTask] - Gave table task without .Destroy\n\n" .. debug.traceback()) end return taskId end --[=[ Gives a promise to the maid for clean. @param promise Promise<T> @return Promise<T> ]=] function Maid:GivePromise(promise) if not promise:IsPending() then return promise end local newPromise = promise.resolved(promise) local id = self:GiveTask(newPromise) -- Ensure GC newPromise:Finally(function() self[id] = nil end) return newPromise end --[=[ Cleans up all tasks and removes them as entries from the Maid. :::note Signals that are already connected are always disconnected first. After that any signals added during a cleaning phase will be disconnected at random times. ::: :::tip DoCleaning() may be recursively invoked. This allows the you to ensure that tasks or other tasks. Each task will be executed once. However, adding tasks while cleaning is not generally a good idea, as if you add a function that adds itself, this will loop indefinitely. ::: ]=] function Maid:DoCleaning() local tasks = self._tasks -- Disconnect all events first as we know this is safe for index, job in pairs(tasks) do if typeof(job) == "RBXScriptConnection" then tasks[index] = nil job:Disconnect() end end -- Clear out tasks table completely, even if clean up tasks add more tasks to the maid local index, job = next(tasks) while job ~= nil do tasks[index] = nil if type(job) == "function" then job() elseif type(job) == "thread" then task.cancel(job) elseif typeof(job) == "RBXScriptConnection" then job:Disconnect() elseif job.Destroy then job:Destroy() end index, job = next(tasks) end end --[=[ Alias for [Maid.DoCleaning()](/api/Maid#DoCleaning) @function Destroy @within Maid ]=] Maid.Destroy = Maid.DoCleaning return Maid
--[=[ Manages the cleaning of events and other things. Useful for encapsulating state and make deconstructors easy. See the [Five Powerful Code Patterns talk](https://developer.roblox.com/en-us/videos/5-powerful-code-patterns-behind-top-roblox-games) for a more in-depth look at Maids in top games. ```lua local maid = Maid.new() maid:GiveTask(function() print("Cleaning up") end) maid:GiveTask(workspace.ChildAdded:Connect(print)) -- Disconnects all events, and executes all functions maid:DoCleaning() ``` @class Maid ]=] -- luacheck: pop local Maid = {} Maid.ClassName = "Maid" --[=[ Constructs a new Maid object ```lua local maid = Maid.new() ``` @return Maid ]=] function Maid.new() return setmetatable({ _tasks = {} }, Maid) end --[=[ Returns true if the class is a maid, and false otherwise. ```lua print(Maid.isMaid(Maid.new())) --> true print(Maid.isMaid(nil)) --> false ``` @param value any @return boolean ]=] function Maid.isMaid(value) return type(value) == "table" and value.ClassName == "Maid" end --[=[ Returns Maid[key] if not part of Maid metatable ```lua local maid = Maid.new() maid._current = Instance.new("Part") print(maid._current) --> Part maid._current = nil print(maid._current) --> nil ``` @param index any @return MaidTask ]=] function Maid:__index(index) if Maid[index] then return Maid[index] else return self._tasks[index] end end --[=[ Add a task to clean up. Tasks given to a maid will be cleaned when maid[index] is set to a different value. Task cleanup is such that if the task is an event, it is disconnected. If it is an object, it is destroyed. ``` Maid[key] = (function) Adds a task to perform Maid[key] = (event connection) Manages an event connection Maid[key] = (thread) Manages a thread Maid[key] = (Maid) Maids can act as an event connection, allowing a Maid to have other maids to clean up. Maid[key] = (Object) Maids can cleanup objects with a `Destroy` method Maid[key] = nil Removes a named task. ``` @param index any @param newTask MaidTask ]=] function Maid:__newindex(index, newTask) if Maid[index] ~= nil then error(("Cannot use '%s' as a Maid key"):format(tostring(index)), 2) end local tasks = self._tasks local oldTask = tasks[index] if oldTask == newTask then return end tasks[index] = newTask if oldTask then if type(oldTask) == "function" then oldTask() elseif type(oldTask) == "thread" then task.cancel(oldTask) elseif typeof(oldTask) == "RBXScriptConnection" then oldTask:Disconnect() elseif oldTask.Destroy then oldTask:Destroy() end end end --[=[ Gives a task to the maid for cleanup, but uses an incremented number as a key. @param task MaidTask -- An item to clean @return number -- taskId ]=] function Maid:GiveTask(task) if not task then error("Task cannot be false or nil", 2) end local taskId = #self._tasks+1 self[taskId] = task if type(task) == "table" and (not task.Destroy) then warn("[Maid.GiveTask] - Gave table task without .Destroy\n\n" .. debug.traceback()) end return taskId end --[=[ Gives a promise to the maid for clean. @param promise Promise<T> @return Promise<T> ]=] function Maid:GivePromise(promise) if not promise:IsPending() then return promise end local newPromise = promise.resolved(promise) local id = self:GiveTask(newPromise) -- Ensure GC newPromise:Finally(function() self[id] = nil end) return newPromise end --[=[ Cleans up all tasks and removes them as entries from the Maid. :::note Signals that are already connected are always disconnected first. After that any signals added during a cleaning phase will be disconnected at random times. ::: :::tip DoCleaning() may be recursively invoked. This allows the you to ensure that tasks or other tasks. Each task will be executed once. However, adding tasks while cleaning is not generally a good idea, as if you add a function that adds itself, this will loop indefinitely. ::: ]=] function Maid:DoCleaning() local tasks = self._tasks -- Disconnect all events first as we know this is safe for index, job in pairs(tasks) do if typeof(job) == "RBXScriptConnection" then tasks[index] = nil job:Disconnect() end end -- Clear out tasks table completely, even if clean up tasks add more tasks to the maid local index, job = next(tasks) while job ~= nil do tasks[index] = nil if type(job) == "function" then job() elseif type(job) == "thread" then task.cancel(job) elseif typeof(job) == "RBXScriptConnection" then job:Disconnect() elseif job.Destroy then job:Destroy() end index, job = next(tasks) end end --[=[ Alias for [Maid.DoCleaning()](/api/Maid#DoCleaning) @function Destroy @within Maid ]=] Maid.Destroy = Maid.DoCleaning return Maid
fix: Maid tasks cancel old threads upon rewrite
fix: Maid tasks cancel old threads upon rewrite
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
20473407b1494e89ff991a4d1b620c77fd9c4d22
kernel/turtle/ttl2flr.lua
kernel/turtle/ttl2flr.lua
-- convert turtle ontologies to F-Logic/Flora-2 local ttl2flr = {} local turtleparse = require("turtleparse") local __dump = require("pl.pretty").dump -- no default prefix support in Flora-2, so we save it here and -- substitute it upon encountering it local __DEFAULT_PREFIX_URI local function __printPrefix(p) if p.name == "" then __DEFAULT_PREFIX_URI = p.uri else print(string.format(":- iriprefix{%s='%s'}.", p.name, p.uri)) end end -- convert a resource (UriRef, Qname) string value for Flora-2 local function __rsrc2str(r) if r.type == "UriRef" then return string.format("\"%s\"^^\\iri", r.uri) elseif r.type == "Qname" then local n = r.name -- dcterms has "dcterms:ISO639-2" if n:find("-") then -- TODO make this more robustly handle forbidden chars in F-atoms n = "'" .. n .. "'" end if r.prefix == "" then assert(__DEFAULT_PREFIX_URI, "Default prefix encountered, but none defined") return string.format("\"%s%s\"^^\\iri", __DEFAULT_PREFIX_URI, n) end return string.format("%s#%s", r.prefix, n) else __dump(r) error("Unknown resource") end end -- convert an object (resource or literal (TypedString)) to a string -- value for Flora-2 local function __obj2str(o) -- TODO need proper string processing if type(o) == "string" then return '"' .. o:gsub('"', '\\"') .. '"' elseif o.type == "TypedString" then local t if o.datatype.type == "UriRef" then t = o.datatype.uri:gsub("http://www.w3.org/2001/XMLSchema", "xsd") elseif o.datatype.type == "Qname" then t = string.format("%s#%s", o.datatype.prefix, o.datatype.name) else __dump(o) error("Unknown datatype type") end return string.format("\"%s\"^^%s", o.value, t) elseif o.type == "Collection" then local strval = "{" for idx, v in ipairs(o.values) do local strv = __obj2str(v) if strval == "{" then strval = strval .. strv else strval = strval .. ", " .. strv end end return strval .. "}" else return __rsrc2str(o) end end if true then -- run script --local f = io.open("/home/jbalint/Dropbox/important/org/rdf/other/rdf.ttl", "r") local f = io.open("/home/jbalint/Dropbox/important/org/rdf/nepomuk/nie.ttl", "r") local content = f:read("*all") f:close() local s = turtleparse.parse(content) __dump(s) for idx, el in ipairs(s) do if el.type == "Prefix" then __printPrefix(el) elseif el.subject then -- a statement print("") local sub = __rsrc2str(el.subject) for idx2, pred in ipairs(el.preds) do local verb = pred.verb for idx3, obj in ipairs(pred.objects) do if verb == "a" then print(string.format("%s:%s.", sub, __rsrc2str(obj))) else print(string.format("%s[%s -> %s].", sub, __rsrc2str(verb), __obj2str(obj))) end end if pred.objects.preds then -- A bit more complicated to represent nested objects -- as we can't reference the skolem symbol from several -- statements local nested = "\\#" local preds = "[" for idx3, pred2 in ipairs(pred.objects.preds) do for idx4, obj in ipairs(pred2.objects) do if pred2.verb == "a" then nested = nested .. ":" .. __rsrc2str(obj) else local newpred = string.format("%s -> %s", __rsrc2str(pred2.verb), __obj2str(obj)) if preds == "[" then preds = preds .. newpred else preds = preds .. ", " .. newpred end end end end print(string.format("%s[%s -> %s%s].", sub, __rsrc2str(verb), nested, preds .. "]")) end end end end end return ttl2flr
-- convert turtle ontologies to F-Logic/Flora-2 local ttl2flr = {} local turtleparse = require("turtleparse") local __dump = require("pl.pretty").dump -- no default prefix support in Flora-2, so we save it here and -- substitute it upon encountering it local __DEFAULT_PREFIX_URI -- prefix index necessary to expand Qnames with a prefix only and no -- name local __PREFIXES = {} local function __printPrefix(p) if p.name == "" then __DEFAULT_PREFIX_URI = p.uri else __PREFIXES[p.name] = p.uri print(string.format(":- iriprefix{%s='%s'}.", p.name, p.uri)) end end -- convert a resource (UriRef, Qname) string value for Flora-2 local function __rsrc2str(r) if r.type == "UriRef" then return string.format("\"%s\"^^\\iri", r.uri) elseif r.type == "Qname" then local n = r.name -- prefix only and no name if n == "" then assert(__PREFIXES[r.prefix], "Prefix must be defined: " .. r.prefix) return string.format("\"%s\"^^\\iri", __PREFIXES[r.prefix]) -- dcterms has "dcterms:ISO639-2" elseif n:find("-") then -- TODO make this more robustly handle forbidden chars in F-atoms n = "'" .. n .. "'" end if r.prefix == "" then assert(__DEFAULT_PREFIX_URI, "Default prefix encountered, but none defined") return string.format("\"%s%s\"^^\\iri", __DEFAULT_PREFIX_URI, n) end return string.format("%s#%s", r.prefix, n) else __dump(r) error("Unknown resource") end end -- convert an object (resource or literal (TypedString)) to a string -- value for Flora-2 local function __obj2str(o) -- TODO need proper string processing if type(o) == "string" then return '"' .. o:gsub('"', '\\"') .. '"' elseif o.type == "TypedString" then local t if o.datatype.type == "UriRef" then t = o.datatype.uri:gsub("http://www.w3.org/2001/XMLSchema", "xsd") elseif o.datatype.type == "Qname" then t = string.format("%s#%s", o.datatype.prefix, o.datatype.name) else __dump(o) error("Unknown datatype type") end return string.format("\"%s\"^^%s", o.value, t) elseif o.type == "Collection" then local strval = "{" for idx, v in ipairs(o.values) do local strv = __obj2str(v) if strval == "{" then strval = strval .. strv else strval = strval .. ", " .. strv end end return strval .. "}" else return __rsrc2str(o) end end if true then -- run script --local f = io.open("/home/jbalint/Dropbox/important/org/rdf/other/rdf.ttl", "r") --local f = io.open("/home/jbalint/Dropbox/important/org/rdf/nepomuk/v1.1.ttl", "r") local f = io.open("/home/jbalint/sw/stardog-2.1.3/export-2014-06-06-3.ttl", "r") local content = f:read("*all") f:close() local s = turtleparse.parse(content) __dump(s) for idx, el in ipairs(s) do if el.type == "Prefix" then __printPrefix(el) elseif el.subject then -- a statement print("") local sub = __rsrc2str(el.subject) for idx2, pred in ipairs(el.preds) do local verb = pred.verb for idx3, obj in ipairs(pred.objects) do if verb == "a" then print(string.format("%s:%s.", sub, __rsrc2str(obj))) else print(string.format("%s[%s -> %s].", sub, __rsrc2str(verb), __obj2str(obj))) end end if pred.objects.preds then -- A bit more complicated to represent nested objects -- as we can't reference the skolem symbol from several -- statements local nested = "\\#" local preds = "[" for idx3, pred2 in ipairs(pred.objects.preds) do for idx4, obj in ipairs(pred2.objects) do if pred2.verb == "a" then nested = nested .. ":" .. __rsrc2str(obj) else local newpred = string.format("%s -> %s", __rsrc2str(pred2.verb), __obj2str(obj)) if preds == "[" then preds = preds .. newpred else preds = preds .. ", " .. newpred end end end end print(string.format("%s[%s -> %s%s].", sub, __rsrc2str(verb), nested, preds .. "]")) end end end end end return ttl2flr
add expansion of prefix-only qnames to turtle to flora script
add expansion of prefix-only qnames to turtle to flora script
Lua
mit
jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico
89ad7bb65176dfd25c2780844e415f924fd1255d
nvim/.config/nvim/lua/configs.lua
nvim/.config/nvim/lua/configs.lua
-- nvim-treesitter require "nvim-treesitter.configs".setup { ensure_installed = "all", highlight = {enable = true}, refactor = { highlight_definitions = {enable = false}, highlight_current_scope = {enable = false} }, textobjects = { select = { enable = true, keymaps = { ["af"] = "@function.outer", ["if"] = "@function.inner", ["ac"] = "@class.outer", ["ic"] = "@class.inner" } } }, playground = { enable = true, disable = {}, updatetime = 500, -- Debounced time for highlighting nodes in the playground from source code persist_queries = false -- Whether the query persists across vim sessions } } -- lsp local lsp_attach = function(client) require "diagnostic".on_attach(client) require "lsp-status".on_attach(client) end require "nvim_lsp".pyls.setup {on_attach = lsp_attach} require "nvim_lsp".rust_analyzer.setup {on_attach = lsp_attach} require "nvim_lsp".html.setup {on_attach = lsp_attach} -- npm install -g vscode-html-languageserver-bin require "nvim_lsp".tsserver.setup {on_attach = lsp_attach} require "nvim_lsp".vimls.setup {on_attach = lsp_attach} -- npm install -g vim-language-server require "nvim_lsp".gopls.setup {on_attach = lsp_attach} require "nvim_lsp".bashls.setup {filetypes = {"sh", "zsh"}, on_attach = lsp_attach} require "nvim_lsp".cssls.setup {on_attach = lsp_attach} -- npm install -g vscode-css-languageserver-bin require "nvim_lsp".dockerls.setup {on_attach = lsp_attach} -- npm install -g dockerfile-language-server-nodejs require "nvim_lsp".sumneko_lua.setup { on_attach = lsp_attach, cmd = { "/Users/meain/.cache/nvim/nvim_lsp/sumneko_lua/lua-language-server/bin/macOS/lua-language-server", "-E", "/Users/meain/.cache/nvim/nvim_lsp/sumneko_lua/lua-language-server/main.lua" } } -- lsp status require "lsp-status".register_progress()
-- nvim-treesitter require "nvim-treesitter.configs".setup { ensure_installed = "all", highlight = {enable = true}, refactor = { highlight_definitions = {enable = false}, highlight_current_scope = {enable = false} }, textobjects = { select = { enable = true, keymaps = { ["af"] = "@function.outer", ["if"] = "@function.inner", ["ac"] = "@class.outer", ["ic"] = "@class.inner" } } }, playground = { enable = true, disable = {}, updatetime = 500, -- Debounced time for highlighting nodes in the playground from source code persist_queries = false -- Whether the query persists across vim sessions } } -- lsp local lsp_attach = function(client) require "diagnostic".on_attach(client) require "lsp-status".on_attach(client) end require "nvim_lsp".pyls.setup {on_attach = lsp_attach} require "nvim_lsp".rust_analyzer.setup {on_attach = lsp_attach} require "nvim_lsp".html.setup {on_attach = lsp_attach} -- npm install -g vscode-html-languageserver-bin require "nvim_lsp".tsserver.setup {on_attach = lsp_attach} require "nvim_lsp".vimls.setup {on_attach = lsp_attach} -- npm install -g vim-language-server require "nvim_lsp".gopls.setup {on_attach = lsp_attach} require "nvim_lsp".bashls.setup {filetypes = {"sh", "zsh"}, on_attach = lsp_attach} require "nvim_lsp".cssls.setup {on_attach = lsp_attach} -- npm install -g vscode-css-languageserver-bin require "nvim_lsp".dockerls.setup {on_attach = lsp_attach} -- npm install -g dockerfile-language-server-nodejs require "nvim_lsp".sumneko_lua.setup { on_attach = lsp_attach, settings = { Lua = { diagnostics = {enable = true, globals = {"hs", "vim", "describe", "it", "before_each", "after_each"}} } }, cmd = { "/Users/meain/.cache/nvim/nvim_lsp/sumneko_lua/lua-language-server/bin/macOS/lua-language-server", "-E", "/Users/meain/.cache/nvim/nvim_lsp/sumneko_lua/lua-language-server/main.lua" } } -- lsp status require "lsp-status".register_progress()
[nvim] fix lua diagnostics
[nvim] fix lua diagnostics
Lua
mit
meain/dotfiles,meain/dotfiles,meain/dotfiles,meain/dotfiles,meain/dotfiles,meain/dotfiles
f70bae058083f2dd46106fd5e405b5f1ca57b42f
otouto/plugins/tagesschau_eil.lua
otouto/plugins/tagesschau_eil.lua
local tagesschau_eil = {} tagesschau_eil.command = 'eil <sub/del>' function tagesschau_eil:init(config) tagesschau_eil.triggers = utilities.triggers(self.info.username, config.cmd_pat):t('eil', true).table tagesschau_eil.doc = [[* ]]..config.cmd_pat..[[eil* _sub_: Eilmeldungen abonnieren *]]..config.cmd_pat..[[eil* _del_: Eilmeldungen deabonnieren *]]..config.cmd_pat..[[eil* _sync_: Nach neuen Eilmeldungen prüfen (nur Superuser)]] end local makeOurDate = function(dateString) local pattern = "(%d+)%-(%d+)%-(%d+)T(%d+)%:(%d+)%:(%d+)" local year, month, day, hours, minutes, seconds = dateString:match(pattern) return day..'.'..month..'.'..year..' um '..hours..':'..minutes..':'..seconds end local url = 'http://www.tagesschau.de/api' local hash = 'telegram:tagesschau' function tagesschau_eil:abonnieren(id) if redis:sismember(hash..':subs', id) == false then redis:sadd(hash..':subs', id) return '*Eilmeldungen abonniert.*' else return 'Die Eilmeldungen wurden hier bereits abonniert.' end end function tagesschau_eil:deabonnieren(id) if redis:sismember(hash..':subs', id) == true then redis:srem(hash..':subs', id) return '*Eilmeldungen deabonniert.*' else return 'Die Eilmeldungen wurden hier noch nicht abonniert.' end end function tagesschau_eil:action(msg, config) local input = utilities.input(msg.text) if not input then if msg.reply_to_message and msg.reply_to_message.text then input = msg.reply_to_message.text else utilities.send_message(msg.chat.id, tagesschau_eil.doc, true, msg.message_id, true) return end end local id = "user#id" .. msg.from.id if msg.chat.type == 'channel' then print('Kanäle werden momentan nicht unterstützt') end if msg.chat.type == 'group' or msg.chat.type == 'supergroup' then id = 'chat#id'..msg.chat.id end if input:match('(sub)$') then local output = tagesschau_eil:abonnieren(id) utilities.send_reply(msg, output, true) elseif input:match('(del)$') then local output = tagesschau_eil:deabonnieren(id) utilities.send_reply(msg, output, true) elseif input:match('(sync)$') then if not is_sudo(msg, config) then utilities.send_reply(msg, config.errors.sudo) return end tagesschau_eil:cron() end return end function tagesschau_eil:cron() -- print('EIL: Prüfe...') local last_eil = redis:get(hash..':last_entry') local res,code = http.request(url) if code ~= 200 then return end local data = json.decode(res) if not data then return end if data.error then return end if data.breakingnews[1] then if data.breakingnews[1].date ~= last_eil then local title = '#EIL: <b>'..data.breakingnews[1].headline..'</b>' local news = data.breakingnews[1].shorttext or '' local posted_at = makeOurDate(data.breakingnews[1].date)..' Uhr' local post_url = string.gsub(data.breakingnews[1].details, '/api/', '/') local post_url = string.gsub(post_url, '.json', '.html') local eil = title..'\n<i>'..posted_at..'</i>\n'..news redis:set(hash..':last_entry', data.breakingnews[1].date) for _,user in pairs(redis:smembers(hash..':subs')) do local user = string.gsub(user, 'chat%#id', '') local user = string.gsub(user, 'user%#id', '') utilities.send_message(user, eil, true, nil, 'HTML', '{"inline_keyboard":[[{"text":"Eilmeldung aufrufen","url":"'..post_url..'"}]]}') end end end end return tagesschau_eil
local tagesschau_eil = {} tagesschau_eil.command = 'eil <sub/del>' function tagesschau_eil:init(config) tagesschau_eil.triggers = utilities.triggers(self.info.username, config.cmd_pat):t('eil', true).table tagesschau_eil.doc = [[* ]]..config.cmd_pat..[[eil* _sub_: Eilmeldungen abonnieren *]]..config.cmd_pat..[[eil* _del_: Eilmeldungen deabonnieren *]]..config.cmd_pat..[[eil* _sync_: Nach neuen Eilmeldungen prüfen (nur Superuser)]] end local makeOurDate = function(dateString) local pattern = "(%d+)%-(%d+)%-(%d+)T(%d+)%:(%d+)%:(%d+)" local year, month, day, hours, minutes, seconds = dateString:match(pattern) return day..'.'..month..'.'..year..' um '..hours..':'..minutes..':'..seconds end local url = 'http://www.tagesschau.de/api' local hash = 'telegram:tagesschau' function tagesschau_eil:abonnieren(id) if redis:sismember(hash..':subs', id) == false then redis:sadd(hash..':subs', id) return '*Eilmeldungen abonniert.*' else return 'Die Eilmeldungen wurden hier bereits abonniert.' end end function tagesschau_eil:deabonnieren(id) if redis:sismember(hash..':subs', id) == true then redis:srem(hash..':subs', id) return '*Eilmeldungen deabonniert.*' else return 'Die Eilmeldungen wurden hier noch nicht abonniert.' end end function tagesschau_eil:action(msg, config) local input = utilities.input(msg.text) if not input then if msg.reply_to_message and msg.reply_to_message.text then input = msg.reply_to_message.text else utilities.send_message(msg.chat.id, tagesschau_eil.doc, true, msg.message_id, true) return end end local id = "user#id" .. msg.from.id if msg.chat.type == 'channel' then print('Kanäle werden momentan nicht unterstützt') end if msg.chat.type == 'group' or msg.chat.type == 'supergroup' then id = 'chat#id'..msg.chat.id end if input:match('(sub)$') then local output = tagesschau_eil:abonnieren(id) utilities.send_reply(msg, output, true) elseif input:match('(del)$') then local output = tagesschau_eil:deabonnieren(id) utilities.send_reply(msg, output, true) elseif input:match('(sync)$') then if not is_sudo(msg, config) then utilities.send_reply(msg, config.errors.sudo) return end tagesschau_eil:cron() end return end function tagesschau_eil:cron() -- print('EIL: Prüfe...') local last_eil = redis:get(hash..':last_entry') local res,code = http.request(url) if code ~= 200 then return end local data = json.decode(res) if not data then return end if data == "error" then return end if data.error then return end if data.breakingnews[1] then if data.breakingnews[1].date ~= last_eil then local title = '#EIL: <b>'..data.breakingnews[1].headline..'</b>' local news = data.breakingnews[1].shorttext or '' local posted_at = makeOurDate(data.breakingnews[1].date)..' Uhr' local post_url = string.gsub(data.breakingnews[1].details, '/api/', '/') local post_url = string.gsub(post_url, '.json', '.html') local eil = title..'\n<i>'..posted_at..'</i>\n'..news redis:set(hash..':last_entry', data.breakingnews[1].date) for _,user in pairs(redis:smembers(hash..':subs')) do local user = string.gsub(user, 'chat%#id', '') local user = string.gsub(user, 'user%#id', '') utilities.send_message(user, eil, true, nil, 'HTML', '{"inline_keyboard":[[{"text":"Eilmeldung aufrufen","url":"'..post_url..'"}]]}') end end end end return tagesschau_eil
Tagesschau-EIL: Richtiger Fix
Tagesschau-EIL: Richtiger Fix
Lua
agpl-3.0
Brawl345/Brawlbot-v2
0e3136f424075c8b5c97151f493e04f4235d8b62
modules/corelib/table.lua
modules/corelib/table.lua
-- @docclass table function table.dump(t, depth) if not depth then depth = 0 end for k,v in pairs(t) do str = (' '):rep(depth * 2) .. k .. ': ' if type(v) ~= "table" then print(str .. tostring(v)) else print(str) table.dump(v, depth+1) end end end function table.copy(t) local res = {} for k,v in pairs(t) do if type(v) == "table" then res[k] = table.copy(v) else res[k] = v end end return res end function table.selectivecopy(t, keys) local res = { } for i,v in ipairs(keys) do res[v] = t[v] end return res end function table.merge(t, src) for k,v in pairs(src) do t[k] = v end end function table.find(t, value) for k,v in pairs(t) do if v == value then return k end end end function table.contains(t, value) return table.find(t, value) ~= nil end function table.findKey(t, key) if t and type(t) == 'table' then for k,v in pairs(t) do if k == key then return k end end end end function table.hasKey(t, key) return table.findKey(t, key) ~= nil end function table.removevalue(t, value) for k,v in pairs(t) do if v == value then table.remove(t, k) break end end end function table.compare(t, other) if #t ~= #other then return false end for k,v in pairs(t) do if v ~= other[k] then return false end end return true end function table.empty(t) if t and type(t) == 'table' then return next(t) == nil end return true end
-- @docclass table function table.dump(t, depth) if not depth then depth = 0 end for k,v in pairs(t) do str = (' '):rep(depth * 2) .. k .. ': ' if type(v) ~= "table" then print(str .. tostring(v)) else print(str) table.dump(v, depth+1) end end end function table.copy(t) local res = {} for k,v in pairs(t) do res[k] = v end return res end function table.recursivecopy(t) local res = {} for k,v in pairs(t) do if type(v) == "table" then res[k] = table.recursivecopy(v) else res[k] = v end end return res end function table.selectivecopy(t, keys) local res = { } for i,v in ipairs(keys) do res[v] = t[v] end return res end function table.merge(t, src) for k,v in pairs(src) do t[k] = v end end function table.find(t, value) for k,v in pairs(t) do if v == value then return k end end end function table.contains(t, value) return table.find(t, value) ~= nil end function table.findKey(t, key) if t and type(t) == 'table' then for k,v in pairs(t) do if k == key then return k end end end end function table.hasKey(t, key) return table.findKey(t, key) ~= nil end function table.removevalue(t, value) for k,v in pairs(t) do if v == value then table.remove(t, k) break end end end function table.compare(t, other) if #t ~= #other then return false end for k,v in pairs(t) do if v ~= other[k] then return false end end return true end function table.empty(t) if t and type(t) == 'table' then return next(t) == nil end return true end
Fix stackoverflow caused by new table.copy
Fix stackoverflow caused by new table.copy
Lua
mit
Cavitt/otclient_mapgen,kwketh/otclient,dreamsxin/otclient,gpedro/otclient,EvilHero90/otclient,dreamsxin/otclient,gpedro/otclient,dreamsxin/otclient,Radseq/otclient,kwketh/otclient,Radseq/otclient,gpedro/otclient,Cavitt/otclient_mapgen,EvilHero90/otclient
c8f56589f724fa42b06d07b29c2d79822705e4d6
game/scripts/vscripts/heroes/structures/healer_bottle_filling.lua
game/scripts/vscripts/heroes/structures/healer_bottle_filling.lua
LinkLuaModifier("modifier_healer_bottle_filling", "heroes/structures/healer_bottle_filling.lua", LUA_MODIFIER_MOTION_NONE) LinkLuaModifier("modifier_healer_bottle_filling_effect", "heroes/structures/healer_bottle_filling.lua", LUA_MODIFIER_MOTION_NONE) LinkLuaModifier("modifier_healer_bottle_filling_delay", "heroes/structures/healer_bottle_filling.lua", LUA_MODIFIER_MOTION_NONE) healer_bottle_filling = class({ GetIntrinsicModifierName = function() return "modifier_healer_bottle_filling" end, }) modifier_healer_bottle_filling = class({ IsPurgable = function() return false end, IsHidden = function() return true end, }) function modifier_healer_bottle_filling:GetAuraRadius() return self:GetAbility():GetSpecialValueFor("aura_radius") end function modifier_healer_bottle_filling:GetAuraSearchTeam() return self:GetAbility():GetAbilityTargetTeam() end function modifier_healer_bottle_filling:GetAuraSearchType() return self:GetAbility():GetAbilityTargetType() end function modifier_healer_bottle_filling:GetAuraSearchFlags() return self:GetAbility():GetAbilityTargetFlags() end function modifier_healer_bottle_filling:IsAura() return true end function modifier_healer_bottle_filling:GetModifierAura() return "modifier_healer_bottle_filling_effect" end modifier_healer_bottle_filling_effect = class({ IsHidden = function() return true end, IsPurgable = function() return false end, }) if IsServer() then function modifier_healer_bottle_filling_effect:OnCreated() local parent = self:GetParent() for i = 0, 11 do local item = parent:GetItemInSlot(i) if item and item:GetAbilityName() == "item_bottle_arena" then if parent:IsCourier() or parent:HasModifier("modifier_healer_bottle_filling_delay") then return end item:SetCurrentCharges(3) local duration = self:GetAbility():GetSpecialValueFor('bottle_refill_cooldown') local ability = self:GetAbility() parent:AddNewModifier(ability:GetCaster(), ability, "modifier_healer_bottle_filling_delay", {duration = duration}) end end end end modifier_healer_bottle_filling_delay = class({ IsDebuff = function() return true end, IsPurgable = function() return false end, })
LinkLuaModifier("modifier_healer_bottle_filling", "heroes/structures/healer_bottle_filling.lua", LUA_MODIFIER_MOTION_NONE) LinkLuaModifier("modifier_healer_bottle_filling_delay", "heroes/structures/healer_bottle_filling.lua", LUA_MODIFIER_MOTION_NONE) healer_bottle_filling = class({ GetIntrinsicModifierName = function() return "modifier_healer_bottle_filling" end, }) modifier_healer_bottle_filling = class({ IsPurgable = function() return false end, IsHidden = function() return true end, }) if IsServer() then function modifier_healer_bottle_filling:OnCreated() self:StartIntervalThink(1) self:OnIntervalThink() end function modifier_healer_bottle_filling:OnIntervalThink() local caster = self:GetCaster() local ability = self:GetAbility() local modifier = "modifier_healer_bottle_filling_delay" local radius = ability:GetSpecialValueFor("aura_radius") local delay_duration = ability:GetSpecialValueFor('bottle_refill_cooldown') for _,v in ipairs(FindUnitsInRadius(caster:GetTeamNumber(), caster:GetAbsOrigin(), nil, radius, DOTA_UNIT_TARGET_TEAM_FRIENDLY, DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_NONE, FIND_ANY_ORDER, false)) do if v:HasModifier("modifier_healer_bottle_filling_delay") then return end for i = 0, 11 do local item = v:GetItemInSlot(i) if item and item:GetAbilityName() == "item_bottle_arena" then item:SetCurrentCharges(item:GetCurrentCharges()+1) v:EmitSound("DOTA_Item.MagicWand.Activate") if item:GetCurrentCharges() == 3 then v:AddNewModifier(ability:GetCaster(), ability, "modifier_healer_bottle_filling_delay", {duration = delay_duration}) end end end end end end modifier_healer_bottle_filling_delay = class({ IsDebuff = function() return true end, IsPurgable = function() return false end, })
fix(abilities): shrine bottle filling ability worked incorrectly
fix(abilities): shrine bottle filling ability worked incorrectly
Lua
mit
ark120202/aabs
85ac740f488cb343fb337ee0eedb9ab9bc520ad9
kong/dao/error.lua
kong/dao/error.lua
-- DAOs need more specific error objects, specifying if the error is due -- to the schema, the database connection, a constraint violation etc, so the -- caller can take actions based on the error type. -- -- We will test this object and might create a KongError class too -- if successful and needed. -- -- Ideally, those errors could switch from having a type, to having an error -- code. -- -- @author thibaultcha local error_mt = {} error_mt.__index = error_mt -- Returned the `message` property as a string if it is already one, -- for format it as a string if it is a table. -- @return the formatted `message` property function error_mt:print_message() if type(self.message) == "string" then return self.message elseif type(self.message) == "table" then local errors = {} for k, v in pairs(self.message) do table.insert(errors, k..": "..v) end return table.concat(errors, " | ") end end -- Allow a DaoError to be printed -- @return the formatted `message` property function error_mt:__tostring() return self:print_message() end -- Allow a DaoError to be concatenated -- @return the formatted and concatenated `message` property function error_mt.__concat(a, b) if getmetatable(a) == error_mt then return a:print_message() .. b else return a .. b:print_message() end end local mt = { -- Constructor -- @param err A raw error, typically returned by lua-resty-cassandra (string) -- @param err_type An error type from constants, will be set as a key with 'true' -- value on the returned error for fast comparison when dealing -- with this error. -- @return A DaoError with the error_mt metatable __call = function (self, err, err_type) if err == nil then return nil end local t = { [err_type] = true, message = tostring(err) } return setmetatable(t, error_mt) end } return setmetatable({}, mt)
-- DAOs need more specific error objects, specifying if the error is due -- to the schema, the database connection, a constraint violation etc, so the -- caller can take actions based on the error type. -- -- We will test this object and might create a KongError class too -- if successful and needed. -- -- Ideally, those errors could switch from having a type, to having an error -- code. -- -- @author thibaultcha local error_mt = {} error_mt.__index = error_mt -- Returned the `message` property as a string if it is already one, -- for format it as a string if it is a table. -- @return the formatted `message` property function error_mt:print_message() if type(self.message) == "string" then return self.message elseif type(self.message) == "table" then local errors = {} for k, v in pairs(self.message) do table.insert(errors, k..": "..v) end return table.concat(errors, " | ") end end -- Allow a DaoError to be printed -- @return the formatted `message` property function error_mt:__tostring() return self:print_message() end -- Allow a DaoError to be concatenated -- @return the formatted and concatenated `message` property function error_mt.__concat(a, b) if getmetatable(a) == error_mt then return a:print_message() .. b else return a .. b:print_message() end end local mt = { -- Constructor -- @param err A raw error, typically returned by lua-resty-cassandra (string) -- @param type An error type from constants, will be set as a key with 'true' -- value on the returned error for fast comparison when dealing -- with this error. -- @return A DaoError with the error_mt metatable __call = function (self, err, type) if err == nil then return nil end local t = { [type] = true, message = err } return setmetatable(t, error_mt) end } return setmetatable({}, mt)
Revert "fix: comply to resty-cassandra's new errors"
Revert "fix: comply to resty-cassandra's new errors" This reverts commit 7692c244e300feb5d686f71caf025a909951afc9.
Lua
apache-2.0
isdom/kong,Kong/kong,vzaramel/kong,Kong/kong,jebenexer/kong,beauli/kong,kyroskoh/kong,vzaramel/kong,xvaara/kong,ccyphers/kong,ind9/kong,rafael/kong,jerizm/kong,Kong/kong,ejoncas/kong,li-wl/kong,ejoncas/kong,streamdataio/kong,ind9/kong,akh00/kong,Vermeille/kong,smanolache/kong,ajayk/kong,icyxp/kong,streamdataio/kong,Mashape/kong,shiprabehera/kong,salazar/kong,rafael/kong,isdom/kong,kyroskoh/kong
4bfb08c7aa73695e1126caaf79d824abc26c6111
[resources]/GTWpolice/data.lua
[resources]/GTWpolice/data.lua
--[[ ******************************************************************************** Project owner: RageQuit community Project name: GTW-RPG Developers: Mr_Moose Source code: https://github.com/GTWCode/GTW-RPG/ Bugtracker: http://forum.404rq.com/bug-reports/ Suggestions: http://forum.404rq.com/mta-servers-development/ Version: Open source License: BSD 2-Clause Status: Stable release ******************************************************************************** ]]-- -- Government color local r,g,b = 110,110,110 -- May be outdated, stored here temporary function restore_weapons( plr ) -- Remove and restore weapons setElementData( plr, "onWorkDuty", false ) end addCommandHandler( "endwork", restore_weapons ) addEvent( "acorp_onEndWork", true ) addEventHandler( "acorp_onEndWork", root, restore_weapons ) -- List of prison cells cells = { -- PD_ID, interior, dimension, x, y, z, rotation -- LSPD [1]={ "LSPD", 6, 0, 264, 77.5, 1001.5, 271.39666748047, 1 }, [2]={ "LSPD", 6, 1, 264, 77.5, 1001.5, 271.39666748047, 1 }, [3]={ "LSPD", 6, 2, 264, 77.5, 1001.5, 271.39666748047, 1 }, [4]={ "LSPD", 6, 0, 264, 82.3, 1001.5, 271.39666748047, 1 }, [5]={ "LSPD", 6, 1, 264, 82.3, 1001.5, 271.39666748047, 1 }, [6]={ "LSPD", 6, 2, 264, 82.3, 1001.5, 271.39666748047, 1 }, [7]={ "LSPD", 6, 0, 264, 87.1, 1001.5, 271.39666748047, 1 }, [8]={ "LSPD", 6, 1, 264, 87.1, 1001.5, 271.39666748047, 1 }, [9]={ "LSPD", 6, 2, 264, 87.1, 1001.5, 271.39666748047, 1 }, -- SFPD [10]={ "SFPD", 10, 0, 227, 111, 999.5, 0, 2 }, [11]={ "SFPD", 10, 0, 223, 111, 999.5, 0, 2 }, [12]={ "SFPD", 10, 0, 219, 111, 999.5, 0, 2 }, [13]={ "SFPD", 10, 0, 215, 111, 999.5, 0, 2 }, [14]={ "SFPD", 10, 1, 227, 111, 999.5, 0, 2 }, [15]={ "SFPD", 10, 1, 223, 111, 999.5, 0, 2 }, [16]={ "SFPD", 10, 1, 219, 111, 999.5, 0, 2 }, [17]={ "SFPD", 10, 1, 215, 111, 999.5, 0, 2 }, -- LVPD [18]={ "LVPD", 3, 0, 198.27734375, 161, 1003.1, 0, 3 }, [19]={ "LVPD", 3, 0, 193.87890625, 175, 1003.1, 180, 3 }, [20]={ "LVPD", 3, 0, 198.27734375, 175, 1003.1, 180, 3 }, [21]={ "LVPD", 3, 1, 198.27734375, 161, 1003.1, 0, 3 }, [22]={ "LVPD", 3, 1, 193.87890625, 175, 1003.1, 180, 3 }, [23]={ "LVPD", 3, 1, 198.27734375, 175, 1003.1, 180, 3 }, -- Fort Carson [24]={ "FCPD", 5, 1, 318, 312, 999.4, 270, 4 }, [25]={ "FCPD", 5, 1, 318, 316, 999.4, 270, 4 }, -- El Quebrados [26]={ "EQPD", 5, 0, 318, 312, 999.4, 270, 5 }, [27]={ "EQPD", 5, 0, 318, 316, 999.4, 270, 5 }, -- Angel pine [28]={ "APPD", 5, 2, 318, 312, 999.4, 270, 6 }, [29]={ "APPD", 5, 2, 318, 316, 999.4, 270, 6 }, -- Jail [30]={ "LSPD", 0, 0, -3028, 2360, 6.26, 180, 1 }, [31]={ "LSPD", 0, 0, -2975, 2204, 0.8, 270, 1 }, } blips = { -- x, y, z [1]={ 1554.888671875, -1676.361328125, 16.1953125 }, [2]={ 608.1591796875, -1464.5869140625, 14.475978851318 }, [3]={ 3189.169921875, -1986.0263671875, 12.162068367004 }, [4]={ 2339.080078125, 2458.01171875, 14.96875 }, [5]={ -1606.740234375, 713.4453125, 13.466968536377 }, [6]={ -214.4169921875, 979.3056640625, 19.33715057373 }, [7]={ -1394.369140625, 2631.3583984375, 56.92106628418 }, [8]={ -2161.7001953125, -2385.3994140625, 30.7 } } -- Marker and blips data marker = {{ }} blipList = {{ }} -- Sync timers lastAnim = {} prisonerSyncTimers = {} -- Define emergency lights timer light2 = {} light1 = {} -- Define a table indexed by cops telling how many arrests he got arrested_players = { } -- Define law lawTeams = { ["Staff"] = true, ["Government"] = true, ["Emergency service"] = true } -- Define police vehlices (cars and helicopters including army, swat, sapd and fbi) policeVehicles = { [596]=true, [597]=true, [598]=true, [599]=true, [490]=true, [528]=true, [523]=true, [427]=true, [432]=true, [601]=true, [428]=true, [433]=true, [470]=true, [497]=true, [425]=true, [520]=true } -- Emergency lights vehicles fireVehicles = { [407]=true, [544]=true } medicVehicles = { [416]=true } trainVeh = { [449]=true, [537]=true, [538]=true, [569]=true, [570]=true }
--[[ ******************************************************************************** Project owner: RageQuit community Project name: GTW-RPG Developers: Mr_Moose Source code: https://github.com/GTWCode/GTW-RPG/ Bugtracker: http://forum.404rq.com/bug-reports/ Suggestions: http://forum.404rq.com/mta-servers-development/ Version: Open source License: BSD 2-Clause Status: Stable release ******************************************************************************** ]]-- -- Government color local r,g,b = 110,110,110 -- May be outdated, stored here temporary function restore_weapons( plr ) -- Remove and restore weapons setElementData( plr, "onWorkDuty", false ) end addCommandHandler( "endwork", restore_weapons ) addEvent( "acorp_onEndWork", true ) addEventHandler( "acorp_onEndWork", root, restore_weapons ) -- List of prison cells cells = { -- PD_ID, interior, dimension, x, y, z, rotation -- LSPD [1]={ "LSPD", 6, 0, 264, 77.5, 1001.5, 271.39666748047, 1 }, [2]={ "LSPD", 6, 1, 264, 77.5, 1001.5, 271.39666748047, 1 }, [3]={ "LSPD", 6, 2, 264, 77.5, 1001.5, 271.39666748047, 1 }, [4]={ "LSPD", 6, 0, 264, 82.3, 1001.5, 271.39666748047, 1 }, [5]={ "LSPD", 6, 1, 264, 82.3, 1001.5, 271.39666748047, 1 }, [6]={ "LSPD", 6, 2, 264, 82.3, 1001.5, 271.39666748047, 1 }, [7]={ "LSPD", 6, 0, 264, 87.1, 1001.5, 271.39666748047, 1 }, [8]={ "LSPD", 6, 1, 264, 87.1, 1001.5, 271.39666748047, 1 }, [9]={ "LSPD", 6, 2, 264, 87.1, 1001.5, 271.39666748047, 1 }, -- SFPD [10]={ "SFPD", 10, 0, 227, 111, 999.5, 0, 2 }, [11]={ "SFPD", 10, 0, 223, 111, 999.5, 0, 2 }, [12]={ "SFPD", 10, 0, 219, 111, 999.5, 0, 2 }, [13]={ "SFPD", 10, 0, 215, 111, 999.5, 0, 2 }, [14]={ "SFPD", 10, 1, 227, 111, 999.5, 0, 2 }, [15]={ "SFPD", 10, 1, 223, 111, 999.5, 0, 2 }, [16]={ "SFPD", 10, 1, 219, 111, 999.5, 0, 2 }, [17]={ "SFPD", 10, 1, 215, 111, 999.5, 0, 2 }, -- LVPD [18]={ "LVPD", 3, 0, 198.27734375, 161, 1003.1, 0, 3 }, [19]={ "LVPD", 3, 0, 193.87890625, 175, 1003.1, 180, 3 }, [20]={ "LVPD", 3, 0, 198.27734375, 175, 1003.1, 180, 3 }, [21]={ "LVPD", 3, 1, 198.27734375, 161, 1003.1, 0, 3 }, [22]={ "LVPD", 3, 1, 193.87890625, 175, 1003.1, 180, 3 }, [23]={ "LVPD", 3, 1, 198.27734375, 175, 1003.1, 180, 3 }, -- Fort Carson [24]={ "FCPD", 5, 1, 318, 312, 999.4, 270, 4 }, [25]={ "FCPD", 5, 1, 318, 316, 999.4, 270, 4 }, -- El Quebrados [26]={ "EQPD", 5, 0, 318, 312, 999.4, 270, 5 }, [27]={ "EQPD", 5, 0, 318, 316, 999.4, 270, 5 }, -- Angel pine [28]={ "APPD", 5, 2, 318, 312, 999.4, 270, 6 }, [29]={ "APPD", 5, 2, 318, 316, 999.4, 270, 6 }, -- Jail [30]={ "LSPD", 0, 0, -3028, 2360, 6.26, 180, 1 }, [31]={ "LSPD", 0, 0, -2975, 2204, 0.8, 270, 1 }, } blips = { -- x, y, z [1]={ 1554.888671875, -1676.361328125, 16.1953125 }, [2]={ 608.1591796875, -1464.5869140625, 14.475978851318 }, [3]={ 3189.169921875, -1986.0263671875, 12.162068367004 }, [4]={ 2339.080078125, 2458.01171875, 14.96875 }, [5]={ -1606.740234375, 713.4453125, 13.466968536377 }, [6]={ -214.4169921875, 979.3056640625, 19.33715057373 }, [7]={ -1394.369140625, 2631.3583984375, 56.92106628418 }, [8]={ -2161.7001953125, -2385.3994140625, 30.7 } } -- Marker and blips data marker = {{ }} blipList = {{ }} -- Sync timers lastAnim = {} prisonerSyncTimers = {} -- Define emergency lights timer light2 = {} light1 = {} -- Define a table indexed by cops telling how many arrests he got arrested_players = { } -- Define law lawTeams = { ["Staff"] = true, ["Government"] = true, ["Emergency service"] = true } -- Define police vehlices (cars and helicopters including army, swat, sapd and fbi) policeVehicles = { [596]=true, [597]=true, [598]=true, [599]=true, [490]=true, [528]=true, [523]=true, [427]=true, [432]=true, [601]=true, [428]=true, [433]=true, [470]=true, [497]=true, [425]=true, [520]=true } -- Emergency lights vehicles fireVehicles = { [407]=true, [544]=true } medicVehicles = { [416]=true } trainVeh = { [449]=true, [537]=true, [538]=true, [569]=true, [570]=true }
[Misc] Fixed indentation in data
[Misc] Fixed indentation in data
Lua
bsd-2-clause
GTWCode/GTW-RPG,SpRoXx/GTW-RPG,SpRoXx/GTW-RPG,GTWCode/GTW-RPG,404rq/GTW-RPG,404rq/GTW-RPG,GTWCode/GTW-RPG,404rq/GTW-RPG
28ceebd001ce3e368adc3a4a773f2fa9473088ba
lib/acid/redis.lua
lib/acid/redis.lua
local resty_redis = require("resty.redis") local strutil = require("acid.strutil") local rpc_logging = require("acid.rpc_logging") local to_str = strutil.to_str local _M = {} local mt = { __index = _M } local function get_redis_cli(self) local redis_cli, err_msg = resty_redis:new() if redis_cli == nil then return nil, nil, 'NewRedisError', err_msg end redis_cli:set_timeout(self.timeout) local ok, err_msg = redis_cli:connect( self.ip, self.port ) if ok == nil then return nil, 'ConnectRedisError', err_msg end return redis_cli end local function run_redis_cmd(self, cmd, ...) local args = {...} local log_entry = rpc_logging.new_entry('redis', { ip = self.ip, port = self.port, uri = to_str(cmd, ':', args[1])}) local redis_cli, err_code, err_msg = get_redis_cli(self) rpc_logging.set_time(log_entry, 'upstream', 'conn') if err_code ~= nil then rpc_logging.set_err(log_entry, err_code) rpc_logging.add_log(log_entry) return nil, err_code, err_msg end local val, err_msg = redis_cli[cmd](redis_cli, ... ) rpc_logging.set_time(log_entry, 'upstream', 'recv') if val == nil or err_msg ~= nil then rpc_logging.set_err(log_entry, err_msg) rpc_logging.add_log(log_entry) return nil, 'RunRedisCMDError', to_str('cmd: ', cmd, ', err: ', err_msg) end local itv = log_entry.upstream.time.conn + log_entry.upstream.time.recv if itv >= self.min_log_time then rpc_logging.add_log(log_entry) end if self.keepalive_timeout ~= nil then redis_cli:set_keepalive(self.keepalive_timeout, self.keepalive_size) end return val end function _M.new(_, ip, port, opts) local opts = opts or {} local obj = { ip = ip, port = port, timeout = opts.timeout or 1000, retry_count = opts.retry_count or 1, keepalive_size = opts.keepalive_size, keepalive_timeout = opts.keepalive_timeout, min_log_time = opts.min_log_time or 0.005, } return setmetatable( obj, mt ) end function _M.retry(self, n) self.retry_count = n return self end function _M.transaction(self, cmds) local ok, err_code, err_msg = self:multi() if err_code ~= nil then return nil, err_code, err_msg end if ok ~= 'OK' then return nil, 'RunRedisCMDError', 'multi no reply with the string OK' end for _, cmd_and_args in ipairs(cmds) do local cmd, cmd_args = unpack(cmd_and_args) local rst, err_code, err_msg = self[cmd](self, unpack(cmd_args or {})) if err_code ~= nil then self['discard'](self) return nil, err_code, err_msg end if rst ~= 'QUEUED' then self['discard'](self) return nil, 'RunRedisCMDError', cmd .. ' no reply with the string QUEUED' end end local multi_rst, err_code, err_msg = self['exec'](self) if err_code ~= nil then self['discard'](self) return nil, err_code, err_msg end return multi_rst end setmetatable(_M, {__index = function(_, cmd) local method = function (self, ...) local val, err_code, err_msg for ii = 1, self.retry_count, 1 do val, err_code, err_msg = run_redis_cmd(self, cmd, ...) if err_code == nil then return val, nil, nil end ngx.log(ngx.WARN, to_str('redis retry ', ii, ' error. ', err_code, ':', err_msg)) end return nil, err_code, err_msg end _M[cmd] = method return method end}) return _M
local resty_redis = require("resty.redis") local strutil = require("acid.strutil") local rpc_logging = require("acid.rpc_logging") local to_str = strutil.to_str local _M = { _VERSION = "0.1" } local mt = { __index = _M } local function get_redis_cli(self) local redis_cli, err_msg = resty_redis:new() if redis_cli == nil then return nil, 'NewRedisError', err_msg end redis_cli:set_timeout(self.timeout) local ok, err_msg = redis_cli:connect( self.ip, self.port ) if ok == nil then return nil, 'ConnectRedisError', err_msg end return redis_cli end local function run_redis_cmd(self, cmd, ...) local args = {...} local log_entry = rpc_logging.new_entry('redis', { ip = self.ip, port = self.port, uri = to_str(cmd, ':', args[1])}) local redis_cli, err_code, err_msg = get_redis_cli(self) rpc_logging.set_time(log_entry, 'upstream', 'conn') if err_code ~= nil then rpc_logging.set_err(log_entry, err_code) rpc_logging.add_log(log_entry) return nil, err_code, err_msg end local val, err_msg = redis_cli[cmd](redis_cli, ... ) rpc_logging.set_time(log_entry, 'upstream', 'recv') if val == nil or err_msg ~= nil then rpc_logging.set_err(log_entry, err_msg) rpc_logging.add_log(log_entry) return nil, 'RunRedisCMDError', to_str('cmd: ', cmd, ', err: ', err_msg) end local itv = log_entry.upstream.time.conn + log_entry.upstream.time.recv if itv >= self.min_log_time then rpc_logging.add_log(log_entry) end if self.keepalive_timeout ~= nil then redis_cli:set_keepalive(self.keepalive_timeout, self.keepalive_size) end return val end function _M.new(_, ip, port, opts) local opts = opts or {} local obj = { ip = ip, port = port, timeout = opts.timeout or 1000, retry_count = opts.retry_count or 1, keepalive_size = opts.keepalive_size, keepalive_timeout = opts.keepalive_timeout, min_log_time = opts.min_log_time or 0.005, } return setmetatable( obj, mt ) end function _M.retry(self, n) self.retry_count = n return self end function _M.transaction(self, cmds) local ok, err_code, err_msg = self:multi() if err_code ~= nil then return nil, err_code, err_msg end if ok ~= 'OK' then return nil, 'RunRedisCMDError', 'multi no reply with the string OK' end for _, cmd_and_args in ipairs(cmds) do local cmd, cmd_args = unpack(cmd_and_args) local rst, err_code, err_msg = self[cmd](self, unpack(cmd_args or {})) if err_code ~= nil then self:discard() return nil, err_code, err_msg end if rst ~= 'QUEUED' then self:discard() return nil, 'RunRedisCMDError', cmd .. ' no reply with the string QUEUED' end end local multi_rst, err_code, err_msg = self:exec() if err_code ~= nil then self:discard() return nil, err_code, err_msg end return multi_rst end setmetatable(_M, {__index = function(_, cmd) local method = function (self, ...) local val, err_code, err_msg for ii = 1, self.retry_count, 1 do val, err_code, err_msg = run_redis_cmd(self, cmd, ...) if err_code == nil then return val, nil, nil end ngx.log(ngx.WARN, to_str('redis retry ', ii, ' error. ', err_code, ':', err_msg)) end return nil, err_code, err_msg end _M[cmd] = method return method end}) return _M
fix redis.lua
fix redis.lua
Lua
mit
baishancloud/lua-acid,baishancloud/lua-acid,baishancloud/lua-acid
a1efc24d20691810b7f82108cbee79f584332f80
otouto/plugins/gdrive.lua
otouto/plugins/gdrive.lua
local gdrive = {} local utilities = require('otouto.utilities') local https = require('ssl.https') local ltn12 = require('ltn12') local json = require('dkjson') local bindings = require('otouto.bindings') function gdrive:init(config) if not cred_data.google_apikey then print('Missing config value: google_apikey.') print('gdrive.lua will not be enabled.') return end gdrive.triggers = { "docs.google.com/(.*)/d/([A-Za-z0-9-_-]+)", "drive.google.com/(.*)/d/([A-Za-z0-9-_-]+)", "drive.google.com/(open)%?id=([A-Za-z0-9-_-]+)" } end local apikey = cred_data.google_apikey local BASE_URL = 'https://www.googleapis.com/drive/v2' function gdrive:get_drive_document_data (docid) local apikey = cred_data.google_apikey local url = BASE_URL..'/files/'..docid..'?key='..apikey..'&fields=id,title,mimeType,ownerNames,exportLinks,fileExtension' local res,code = https.request(url) local res = string.gsub(res, 'image/', '') local res = string.gsub(res, 'application/', '') if code ~= 200 then return nil end local data = json.decode(res) return data end function gdrive:send_drive_document_data(data, self, msg) local title = data.title local mimetype = data.mimeType local id = data.id local owner = data.ownerNames[1] local text = '"'..title..'", freigegeben von '..owner if data.exportLinks then if data.exportLinks.png then local image_url = data.exportLinks.png utilities.send_typing(self, msg.chat.id, 'upload_photo') local file = download_to_file(image_url, 'photo.png') utilities.send_photo(self, msg.chat.id, file, text, msg.message_id) return else local pdf_url = data.exportLinks.pdf utilities.send_typing(self, msg.chat.id, 'upload_document') local file = download_to_file(pdf_url, 'document.pdf') utilities.send_document(self, msg.chat.id, file, text, msg.message_id) return end else local get_file_url = 'https://drive.google.com/uc?id='..id local keyboard = '{"inline_keyboard":[[{"text":"Direktlink","url":"'..get_file_url..'"}]]}' local ext = data.fileExtension if mimetype == "png" or mimetype == "jpg" or mimetype == "jpeg" or mimetype == "gif" or mimetype == "webp" then local respbody = {} local options = { url = get_file_url, sink = ltn12.sink.table(respbody), redirect = false } local response = {https.request(options)} -- luasec doesn't support 302 redirects, so we must contact gdrive again local code = response[2] local headers = response[3] local file_url = headers.location if ext == "jpg" or ext == "jpeg" or ext == "png" then utilities.send_typing(self, msg.chat.id, 'upload_photo') local file = download_to_file(file_url, 'photo.'..ext) utilities.send_photo(self, msg.chat.id, file, text, msg.message_id, keyboard) return else utilities.send_typing(self, msg.chat.id, 'upload_document') local file = download_to_file(file_url, 'document.'..ext) utilities.send_document(self, msg.chat.id, file, text, msg.message_id, keyboard) return end else local text = '*'..title..'*, freigegeben von _'..owner..'_' utilities.send_reply(self, msg, text, true, keyboard) return end end end function gdrive:action(msg, config, matches) local docid = matches[2] local data = gdrive:get_drive_document_data(docid) if not data then utilities.send_reply(self, msg, config.errors.connection) return end gdrive:send_drive_document_data(data, self, msg) return end return gdrive
local gdrive = {} local utilities = require('otouto.utilities') local https = require('ssl.https') local ltn12 = require('ltn12') local json = require('dkjson') local bindings = require('otouto.bindings') function gdrive:init(config) if not cred_data.google_apikey then print('Missing config value: google_apikey.') print('gdrive.lua will not be enabled.') return end gdrive.triggers = { "docs.google.com/(.*)/d/([A-Za-z0-9-_-]+)", "drive.google.com/(.*)/d/([A-Za-z0-9-_-]+)", "drive.google.com/(open)%?id=([A-Za-z0-9-_-]+)" } end local apikey = cred_data.google_apikey local BASE_URL = 'https://www.googleapis.com/drive/v3' local apikey = cred_data.google_apikey function gdrive:get_drive_document_data (docid) local url = BASE_URL..'/files/'..docid..'?key='..apikey..'&fields=id,name,mimeType,owners,fullFileExtension' local res, code = https.request(url) local res = string.gsub(res, 'image/', '') -- snip mimetype local res = string.gsub(res, 'application/', '') if code ~= 200 then return nil end local data = json.decode(res) return data end function gdrive:send_drive_document_data(data, self, msg) local title = data.name local mimetype = data.mimeType local id = data.id local owner = data.owners[1].displayName local text = '"'..title..'", freigegeben von '..owner if mimetype:match('google') then -- if document is Google document (like a Spreadsheet) if mimetype:match('drawing') then -- Drawing local image_url = BASE_URL..'/files/'..id..'/export?key='..apikey..'&mimeType=image/png' utilities.send_typing(self, msg.chat.id, 'upload_photo') local file = download_to_file(image_url, 'export.png') utilities.send_photo(self, msg.chat.id, file, text, msg.message_id) return else local pdf_url = BASE_URL..'/files/'..id..'/export?key='..apikey..'&mimeType=application/pdf' utilities.send_typing(self, msg.chat.id, 'upload_document') local file = download_to_file(pdf_url, 'document.pdf') utilities.send_document(self, msg.chat.id, file, text, msg.message_id) return end else local get_file_url = 'https://drive.google.com/uc?id='..id local keyboard = '{"inline_keyboard":[[{"text":"Direktlink","url":"'..get_file_url..'"}]]}' local ext = data.fullFileExtension if mimetype == "png" or mimetype == "jpg" or mimetype == "jpeg" or mimetype == "gif" or mimetype == "webp" then local respbody = {} local options = { url = get_file_url, sink = ltn12.sink.table(respbody), redirect = false } local response = {https.request(options)} -- luasec doesn't support 302 redirects, so we must contact gdrive again local code = response[2] local headers = response[3] local file_url = headers.location if ext == "jpg" or ext == "jpeg" or ext == "png" then utilities.send_typing(self, msg.chat.id, 'upload_photo') local file = download_to_file(file_url, 'photo.'..ext) utilities.send_photo(self, msg.chat.id, file, text, msg.message_id, keyboard) return else utilities.send_typing(self, msg.chat.id, 'upload_document') local file = download_to_file(file_url, 'document.'..ext) utilities.send_document(self, msg.chat.id, file, text, msg.message_id, keyboard) return end else local text = '*'..title..'*, freigegeben von _'..owner..'_' utilities.send_reply(self, msg, text, true, keyboard) return end end end function gdrive:action(msg, config, matches) local docid = matches[2] local data = gdrive:get_drive_document_data(docid) if not data then utilities.send_reply(self, msg, config.errors.connection) return end gdrive:send_drive_document_data(data, self, msg) return end return gdrive
- GDrive: Migriere zu API Version 3, Fix #7
- GDrive: Migriere zu API Version 3, Fix #7
Lua
agpl-3.0
Brawl345/Brawlbot-v2
8b333c82f19d3d436eb24d3a41d05935e0d4c96a
Modules/Utility/os.lua
Modules/Utility/os.lua
-- to use: local os = require(this_script) -- Adds an os.date() function back to the Roblox os table! -- @author Narrev -- Abbreviated tables have been left in for now. Could be replaced with dayNames[wday + 1]:sub(1,3) -- local timeZone = math.ceil( os.difftime(os.time(), tick()) / 3600) -- timeZoneDiff = os.date("*t", os.time()).hour - os.date("*t").hour local firstRequired = os.time() return { help = function(...) return [[Note: Padding can be turned off by putting a '_' between '%' and the letter toggles padding os.date("*t") returns a table with the following indices: hour 14 min 36 wday 1 year 2003 yday 124 month 5 sec 33 day 4 String reference: %a abbreviated weekday name (e.g., Wed) %A full weekday name (e.g., Wednesday) %b abbreviated month name (e.g., Sep) %B full month name (e.g., September) %c date and time (e.g., 09/16/98 23:48:10) %d day of the month (16) [01-31] %H hour, using a 24-hour clock (23) [00-23] %I hour, using a 12-hour clock (11) [01-12] %j day of year [01-365] %M minute (48) [00-59] %m month (09) [01-12] %n New-line character ('\n') %p either "am" or "pm" ('_' makes it uppercase) %r 12-hour clock time * 02:55:02 pm %R 24-hour HH:MM time, equivalent to %H:%M 14:55 %S second (10) [00-61] %t Horizontal-tab character ('\t') %T Basically %r but without seconds (HH:MM AM), equivalent to %I:%M %p 2:55 pm %u ISO 8601 weekday as number with Monday as 1 (1-7) 4 %w weekday (3) [0-6 = Sunday-Saturday] %x date (e.g., 09/16/98) %X time (e.g., 23:48:10) %Y full year (1998) %y two-digit year (98) [00-99] %% the character `%´]] end; date = function(optString, unix) -- Precise! local stringPassed = false if not (optString == nil and unix == nil) then if type(optString) == "number" or optString:match("/Date%((%d+)") or optString:match("%d+\-%d+\-%d+T%d+:%d+:[%d%.]+.+") then -- if they didn't pass a non unix time unix, optString = optString elseif type(optString) == "string" then assert(optString:find("*t") or optString:find("%%"), "Invalid string passed to os.date") unix, optString = optString:find("^!") and os.time() or unix, optString:find("^!") and optString:sub(2) or optString stringPassed = true end if type(unix) == "string" then if unix:match("/Date%((%d+)") then -- This is for a certain JSON compatibility. It works the same even if you don't need it unix = unix:match("/Date%((%d+)") / 1000 elseif unix:match("%d+\-%d+\-%d+T%d+:%d+:[%d%.]+.+") then -- Untested MarketPlaceService compatibility -- This part of the script is untested local year, month, day, hour, minute, second = unix:match("(%d+)\-(%d+)\-(%d+)T(%d+):(%d+):([%d%.]+).+") unix = os.time{year = year, month = month, day = day, hour = hour, minute = minute, second = second} end end end local dayAlign = unix == 0 and 1 or 0 local unix = type(unix) == "number" and unix + dayAlign or tick() local dayCount = function(yr) return (yr % 4 == 0 and (yr % 100 ~= 0 or yr % 400 == 0)) and 366 or 365 end local year = 1970 local days = math.ceil(unix / 86400) local wday = math.floor( (days + 3) % 7 ) -- Jan 1, 1970 was a thursday, so we add 3 local dayNames = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"} local dayNamesAbbr = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"} local monthsAbbr = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"} local months, month = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"} local suffixes = {"st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "st"} local hours = math.floor(unix / 3600 % 24) local minutes = math.floor(unix / 60 % 60) local seconds = math.floor(unix % 60) - dayAlign -- Calculate year and days into that year while days > dayCount(year) do days = days - dayCount(year) year = year + 1 end local yDay = days -- Subtract amount of days from each month until we find what month we are in and what day in that month for monthIndex, daysInMonth in ipairs{31,(dayCount(year) - 337),31,30,31,30,31,31,30,31,30,31} do if days - daysInMonth <= 0 then month = monthIndex break end days = days - daysInMonth end local padded = function(num) return string.format("%02d", num) end if stringPassed then local returner = optString :gsub("%%c", "%%x %%X") :gsub("%%_c", "%%_x %%_X") :gsub("%%x", "%%m/%%d/%%y") :gsub("%%_x", "%%_m/%%_d/%%y") :gsub("%%X", "%%H:%%M:%%S") :gsub("%%_X", "%%_H:%%M:%%S") :gsub("%%T", "%%I:%%M %%p") :gsub("%%_T", "%%_I:%%M %%p") :gsub("%%r", "%%I:%%M:%%S %%p") :gsub("%%_r", "%%_I:%%M:%%S %%p") :gsub("%%R", "%%H:%%M") :gsub("%%_R", "%%_H:%%M") :gsub("%%a", dayNamesAbbr[wday + 1]) :gsub("%%A", dayNames[wday + 1]) :gsub("%%b", monthsAbbr[month]) :gsub("%%B", months[month]) :gsub("%%d", padded(days)) :gsub("%%_d", days) :gsub("%%H", padded(hours)) :gsub("%%_H", hours) :gsub("%%I", padded(hours > 12 and hours - 12 or hours == 0 and 12 or hours)) :gsub("%%_I", hours > 12 and hours - 12 or hours == 0 and 12 or hours) :gsub("%%j", padded(yDay)) :gsub("%%_j", yDay) :gsub("%%M", padded(minutes)) :gsub("%%_M", minutes) :gsub("%%m", padded(month)) :gsub("%%_m", month) :gsub("%%n","\n") :gsub("%%p", hours >= 12 and "pm" or "am") :gsub("%%_p", hours >= 12 and "PM" or "AM") :gsub("%%S", padded(seconds)) :gsub("%%_S", seconds) :gsub("%%t", "\t") :gsub("%%u", wday == 0 and 7 or wday) :gsub("%%w", wday) :gsub("%%Y", year) :gsub("%%y", padded(year % 100)) :gsub("%%_y", year % 100) :gsub("%%%%", "%%") return returner -- We declare returner and then return it because we don't want to return the second value of the last gsub function end return {year = year, month = month, day = days, yday = yDay, wday = wday, hour = hours, min = minutes, sec = seconds} end; time = function(...) return os.time(...) end; difftime = function(...) return os.difftime(...) end; clock = function(...) return os.difftime(os.time(), firstRequired) end; }
-- to use: local os = require(this_script) -- Adds an os.date() function back to the Roblox os table! -- @author Narrev -- Abbreviated tables have been left in for now. Could be replaced with dayNames[wday + 1]:sub(1,3) -- local timeZone = math.ceil( os.difftime(os.time(), tick()) / 3600) -- timeZoneDiff = os.date("*t", os.time()).hour - os.date("*t").hour -- add day suffixes local firstRequired = os.time() return { help = function(...) return [[Note: Padding can be turned off by putting a '_' between '%' and the letter toggles padding os.date("*t") returns a table with the following indices: hour 14 min 36 wday 1 year 2003 yday 124 month 5 sec 33 day 4 String reference: %a abbreviated weekday name (e.g., Wed) %A full weekday name (e.g., Wednesday) %b abbreviated month name (e.g., Sep) %B full month name (e.g., September) %c date and time (e.g., 09/16/98 23:48:10) %d day of the month (16) [01-31] %H hour, using a 24-hour clock (23) [00-23] %I hour, using a 12-hour clock (11) [01-12] %j day of year [01-365] %M minute (48) [00-59] %m month (09) [01-12] %n New-line character ('\n') %p either "am" or "pm" ('_' makes it uppercase) %r 12-hour clock time * 02:55:02 pm %R 24-hour HH:MM time, equivalent to %H:%M 14:55 %s day suffix %S second (10) [00-61] %t Horizontal-tab character ('\t') %T Basically %r but without seconds (HH:MM AM), equivalent to %I:%M %p 2:55 pm %u ISO 8601 weekday as number with Monday as 1 (1-7) 4 %w weekday (3) [0-6 = Sunday-Saturday] %x date (e.g., 09/16/98) %X time (e.g., 23:48:10) %Y full year (1998) %y two-digit year (98) [00-99] %% the character `%´]] end; date = function(optString, unix) -- Precise! local stringPassed = false if not (optString == nil and unix == nil) then if type(optString) == "number" or optString:match("/Date%((%d+)") or optString:match("%d+\-%d+\-%d+T%d+:%d+:[%d%.]+.+") then -- if they didn't pass a non unix time unix, optString = optString elseif type(optString) == "string" then assert(optString:find("*t") or optString:find("%%"), "Invalid string passed to os.date") unix, optString = optString:find("^!") and os.time() or unix, optString:find("^!") and optString:sub(2) or optString stringPassed = true end if type(unix) == "string" then if unix:match("/Date%((%d+)") then -- This is for a certain JSON compatibility. It works the same even if you don't need it unix = unix:match("/Date%((%d+)") / 1000 elseif unix:match("%d+\-%d+\-%d+T%d+:%d+:[%d%.]+.+") then -- Untested MarketPlaceService compatibility -- This part of the script is untested local year, month, day, hour, minute, second = unix:match("(%d+)\-(%d+)\-(%d+)T(%d+):(%d+):([%d%.]+).+") unix = os.time{year = year, month = month, day = day, hour = hour, minute = minute, second = second} end end end local dayAlign = unix == 0 and 1 or 0 local unix = type(unix) == "number" and unix + dayAlign or tick() local dayCount = function(yr) return (yr % 4 == 0 and (yr % 100 ~= 0 or yr % 400 == 0)) and 366 or 365 end local year = 1970 local days = math.ceil(unix / 86400) local wday = math.floor( (days + 3) % 7 ) -- Jan 1, 1970 was a thursday, so we add 3 local dayNames = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"} local dayNamesAbbr = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"} local monthsAbbr = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"} local months, month = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"} local suffixes = {"st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "st"} local hours = math.floor(unix / 3600 % 24) local minutes = math.floor(unix / 60 % 60) local seconds = math.floor(unix % 60) - dayAlign -- Calculate year and days into that year while days > dayCount(year) do days = days - dayCount(year) year = year + 1 end local yDay = days -- Subtract amount of days from each month until we find what month we are in and what day in that month for monthIndex, daysInMonth in ipairs{31,(dayCount(year) - 337),31,30,31,30,31,31,30,31,30,31} do if days - daysInMonth <= 0 then month = monthIndex break end days = days - daysInMonth end local padded = function(num) return string.format("%02d", num) end if stringPassed then local returner = optString :gsub("%%c", "%%x %%X") :gsub("%%_c", "%%_x %%_X") :gsub("%%x", "%%m/%%d/%%y") :gsub("%%_x", "%%_m/%%_d/%%y") :gsub("%%X", "%%H:%%M:%%S") :gsub("%%_X", "%%_H:%%M:%%S") :gsub("%%T", "%%I:%%M %%p") :gsub("%%_T", "%%_I:%%M %%p") :gsub("%%r", "%%I:%%M:%%S %%p") :gsub("%%_r", "%%_I:%%M:%%S %%p") :gsub("%%R", "%%H:%%M") :gsub("%%_R", "%%_H:%%M") :gsub("%%a", dayNamesAbbr[wday + 1]) :gsub("%%A", dayNames[wday + 1]) :gsub("%%b", monthsAbbr[month]) :gsub("%%B", months[month]) :gsub("%%d", padded(days)) :gsub("%%_d", days) :gsub("%%H", padded(hours)) :gsub("%%_H", hours) :gsub("%%I", padded(hours > 12 and hours - 12 or hours == 0 and 12 or hours)) :gsub("%%_I", hours > 12 and hours - 12 or hours == 0 and 12 or hours) :gsub("%%j", padded(yDay)) :gsub("%%_j", yDay) :gsub("%%M", padded(minutes)) :gsub("%%_M", minutes) :gsub("%%m", padded(month)) :gsub("%%_m", month) :gsub("%%n","\n") :gsub("%%p", hours >= 12 and "pm" or "am") :gsub("%%_p", hours >= 12 and "PM" or "AM") :gsub("%%s", suffixes[days]) :gsub("%%S", padded(seconds)) :gsub("%%_S", seconds) :gsub("%%t", "\t") :gsub("%%u", wday == 0 and 7 or wday) :gsub("%%w", wday) :gsub("%%Y", year) :gsub("%%y", padded(year % 100)) :gsub("%%_y", year % 100) :gsub("%%%%", "%%") return returner -- We declare returner and then return it because we don't want to return the second value of the last gsub function end return {year = year, month = month, day = days, yday = yDay, wday = wday, hour = hours, min = minutes, sec = seconds} end; time = function(...) return os.time(...) end; difftime = function(...) return os.difftime(...) end; clock = function(...) return os.difftime(os.time(), firstRequired) end; }
Added "%s" to be day suffix
Added "%s" to be day suffix
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
b89ca8c01458cae36ab4ce5c7ccb19cf69e14777
mods/mobs/init.lua
mods/mobs/init.lua
-- Mob Api dofile(minetest.get_modpath("mobs").."/api.lua") -- Animals dofile(minetest.get_modpath("mobs").."/chicken.lua") -- JKmurray dofile(minetest.get_modpath("mobs").."/cow.lua") -- KrupnoPavel dofile(minetest.get_modpath("mobs").."/rat.lua") -- PilzAdam dofile(minetest.get_modpath("mobs").."/sheep.lua") -- PilzAdam dofile(minetest.get_modpath("mobs").."/warthog.lua") -- KrupnoPavel dofile(minetest.get_modpath("mobs").."/bee.lua") -- KrupnoPavel dofile(minetest.get_modpath("mobs").."/bunny.lua") -- ExeterDad dofile(minetest.get_modpath("mobs").."/kitten.lua") -- Jordach/BFD dofile(minetest.get_modpath("mobs").."/ghoat.lua") -- ??? -- Monsters dofile(minetest.get_modpath("mobs").."/sarangay.lua") -- Kalabasa dofile(minetest.get_modpath("mobs").."/dirtmonster.lua") -- PilzAdam dofile(minetest.get_modpath("mobs").."/dungeonmaster.lua") -- PilzAdam dofile(minetest.get_modpath("mobs").."/oerkki.lua") -- PilzAdam dofile(minetest.get_modpath("mobs").."/sandmonster.lua") -- PilzAdam dofile(minetest.get_modpath("mobs").."/stonemonster.lua") -- PilzAdam dofile(minetest.get_modpath("mobs").."/treemonster.lua") -- PilzAdam dofile(minetest.get_modpath("mobs").."/wolf.lua") -- PilzAdam --dofile(minetest.get_modpath("mobs").."/dog-can-help.lua") -- ??? --dofile(minetest.get_modpath("mobs").."/lava_flan.lua") -- Zeg9 --Remplaced by Lava Slime dofile(minetest.get_modpath("mobs").."/mese_monster.lua") -- Zeg9 dofile(minetest.get_modpath("mobs").."/spider.lua") -- AspireMint dofile(minetest.get_modpath("mobs").."/greenslimes.lua") -- davedevils/TomasJLuis/TenPlus1 dofile(minetest.get_modpath("mobs").."/lavaslimes.lua") -- davedevils/TomasJLuis/TenPlus1 dofile(minetest.get_modpath("mobs").."/zombie.lua") -- ??? dofile(minetest.get_modpath("mobs").."/yeti.lua") -- ??? --dofile(minetest.get_modpath("mobs").."/minotaur.lua") -- ??? -- begin slimes mobs compatibility changes -- cannot find mesecons?, craft glue instead if not minetest.get_modpath("mesecons_materials") then minetest.register_craftitem(":mesecons_materials:glue", { image = "jeija_glue.png", description = "Glue", }) end if minetest.setting_get("log_mods") then minetest.log("action", "Slimes loaded") end -- end slimes mobs compatibility changes -- NPC dofile(minetest.get_modpath("mobs").."/npc.lua") -- TenPlus1 -- Creeper (fast impl by davedevils) dofile(minetest.get_modpath("mobs").."/creeper.lua") -- Meat & Cooked Meat minetest.register_craftitem("mobs:meat_raw", { description = "Raw Meat", inventory_image = "mobs_meat_raw.png", on_use = minetest.item_eat(3), }) minetest.register_craftitem("mobs:meat", { description = "Meat", inventory_image = "mobs_meat.png", on_use = minetest.item_eat(8), }) minetest.register_craft({ type = "cooking", output = "mobs:meat", recipe = "mobs:meat_raw", cooktime = 5, }) -- Golden Lasso minetest.register_tool("mobs:magic_lasso", { description = "Magic Lasso (right-click animal to put in inventory)", inventory_image = "mobs_magic_lasso.png", }) minetest.register_craft({ output = "mobs:magic_lasso", recipe = { {"farming:string", "default:gold_lump", "farming:string"}, {"default:gold_lump", "default:diamondblock", "default:gold_lump"}, {"farming:string", "default:gold_lump", "farming:string"}, } }) if minetest.setting_get("log_mods") then minetest.log("action", "mobs loaded") end
-- Mob Api dofile(minetest.get_modpath("mobs").."/api.lua") -- Animals dofile(minetest.get_modpath("mobs").."/chicken.lua") -- JKmurray dofile(minetest.get_modpath("mobs").."/cow.lua") -- KrupnoPavel dofile(minetest.get_modpath("mobs").."/rat.lua") -- PilzAdam dofile(minetest.get_modpath("mobs").."/sheep.lua") -- PilzAdam dofile(minetest.get_modpath("mobs").."/warthog.lua") -- KrupnoPavel dofile(minetest.get_modpath("mobs").."/bee.lua") -- KrupnoPavel dofile(minetest.get_modpath("mobs").."/bunny.lua") -- ExeterDad dofile(minetest.get_modpath("mobs").."/kitten.lua") -- Jordach/BFD dofile(minetest.get_modpath("mobs").."/ghoat.lua") -- ??? -- Monsters dofile(minetest.get_modpath("mobs").."/dirtmonster.lua") -- PilzAdam dofile(minetest.get_modpath("mobs").."/dungeonmaster.lua") -- PilzAdam dofile(minetest.get_modpath("mobs").."/oerkki.lua") -- PilzAdam dofile(minetest.get_modpath("mobs").."/sandmonster.lua") -- PilzAdam dofile(minetest.get_modpath("mobs").."/stonemonster.lua") -- PilzAdam dofile(minetest.get_modpath("mobs").."/treemonster.lua") -- PilzAdam dofile(minetest.get_modpath("mobs").."/wolf.lua") -- PilzAdam --dofile(minetest.get_modpath("mobs").."/dog-can-help.lua") -- ??? --dofile(minetest.get_modpath("mobs").."/lava_flan.lua") -- Zeg9 --Remplaced by Lava Slime dofile(minetest.get_modpath("mobs").."/mese_monster.lua") -- Zeg9 dofile(minetest.get_modpath("mobs").."/spider.lua") -- AspireMint dofile(minetest.get_modpath("mobs").."/greenslimes.lua") -- davedevils/TomasJLuis/TenPlus1 dofile(minetest.get_modpath("mobs").."/lavaslimes.lua") -- davedevils/TomasJLuis/TenPlus1 dofile(minetest.get_modpath("mobs").."/zombie.lua") -- ??? dofile(minetest.get_modpath("mobs").."/yeti.lua") -- ??? dofile(minetest.get_modpath("mobs").."/minotaur.lua") -- Kalabasa -- begin slimes mobs compatibility changes -- cannot find mesecons?, craft glue instead if not minetest.get_modpath("mesecons_materials") then minetest.register_craftitem(":mesecons_materials:glue", { image = "jeija_glue.png", description = "Glue", }) end if minetest.setting_get("log_mods") then minetest.log("action", "Slimes loaded") end -- end slimes mobs compatibility changes -- NPC dofile(minetest.get_modpath("mobs").."/npc.lua") -- TenPlus1 -- Creeper (fast impl by davedevils) dofile(minetest.get_modpath("mobs").."/creeper.lua") -- Meat & Cooked Meat minetest.register_craftitem("mobs:meat_raw", { description = "Raw Meat", inventory_image = "mobs_meat_raw.png", on_use = minetest.item_eat(3), }) minetest.register_craftitem("mobs:meat", { description = "Meat", inventory_image = "mobs_meat.png", on_use = minetest.item_eat(8), }) minetest.register_craft({ type = "cooking", output = "mobs:meat", recipe = "mobs:meat_raw", cooktime = 5, }) -- Golden Lasso minetest.register_tool("mobs:magic_lasso", { description = "Magic Lasso (right-click animal to put in inventory)", inventory_image = "mobs_magic_lasso.png", }) minetest.register_craft({ output = "mobs:magic_lasso", recipe = { {"farming:string", "default:gold_lump", "farming:string"}, {"default:gold_lump", "default:diamondblock", "default:gold_lump"}, {"farming:string", "default:gold_lump", "farming:string"}, } }) if minetest.setting_get("log_mods") then minetest.log("action", "mobs loaded") end
Fix minotaur problem dofile on init.lua
Fix minotaur problem dofile on init.lua
Lua
unlicense
MinetestForFun/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,sys4-fr/server-minetestforfun,Coethium/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Ombridride/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Coethium/server-minetestforfun,Ombridride/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Coethium/server-minetestforfun
f45f4120ab5e8bf8df0034fb1aae63d1a1c8877a
lib/hump/class.lua
lib/hump/class.lua
--[[ Copyright (c) 2010-2011 Matthias Richter Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]]-- local function __NULL__() end -- class "inheritance" by copying functions local function inherit(class, interface, ...) if not interface or type(interface) ~= "table" then return end -- __index and construct are not overwritten as for them class[name] is defined for name, func in pairs(interface) do if not class[name] and type(func) == "function" then class[name] = func end end for super in pairs(interface.__is_a) do class.__is_a[super] = true end inherit(class, ...) end -- class builder local function new(args) local super = {} local name = '<unnamed class>' local constructor = args or __NULL__ if type(args) == "table" then -- nasty hack to check if args.inherits is a table of classes or a class or nil super = (args.inherits or {}).__is_a and {args.inherits} or args.inherits or {} name = args.name or name constructor = args[1] or __NULL__ end assert(type(constructor) == "function", 'constructor has to be nil or a function') -- build class local class = {} class.__index = class class.__tostring = function() return ("<instance of %s>"):format(tostring(class)) end class.construct, class.Construct = constructor or __NULL__, constructor or __NULL__ class.Construct = class.construct class.inherit, class.Inherit = inherit, inherit class.__is_a = {[class] = true} class.is_a = function(self, other) return not not self.__is_a[other] end -- intercept assignment in global environment to infer the class name if not (args and args.name) then local env, env_meta, interceptor = getfenv(0), getmetatable(getfenv(0)), {} function interceptor:__newindex(key, value) if value == class then local name = tostring(key) getmetatable(class).__tostring = function() return name end end -- restore old metatable and insert value setmetatable(env, env_meta) if env.global then env.global(key) end -- handle 'strict' module env[key] = value end setmetatable(env, interceptor) end -- inherit superclasses (see above) inherit(class, unpack(super)) -- syntactic sugar local meta = { __call = function(self, ...) local obj = {} self.construct(obj, ...) return setmetatable(obj, self) end, __tostring = function() return name end } return setmetatable(class, meta) end -- the module return setmetatable({new = new, inherit = inherit}, {__call = function(_,...) return new(...) end})
--[[ Copyright (c) 2010-2011 Matthias Richter Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]]-- local function __NULL__() end -- class "inheritance" by copying functions local function inherit(class, interface, ...) if not interface or type(interface) ~= "table" then return end -- __index and construct are not overwritten as for them class[name] is defined for name, func in pairs(interface) do if not class[name] and type(func) == "function" then class[name] = func end end for super in pairs(interface.__is_a) do class.__is_a[super] = true end inherit(class, ...) end -- class builder local function new(args) local super = {} local name = '<unnamed class>' local constructor = args or __NULL__ if type(args) == "table" then -- nasty hack to check if args.inherits is a table of classes or a class or nil super = (args.inherits or {}).__is_a and {args.inherits} or args.inherits or {} name = args.name or name constructor = args[1] or __NULL__ end assert(type(constructor) == "function", 'constructor has to be nil or a function') -- build class local class = {} class.__index = class class.__tostring = function() return ("<instance of %s>"):format(tostring(class)) end class.construct, class.Construct = constructor or __NULL__, constructor or __NULL__ class.Construct = class.construct class.inherit, class.Inherit = inherit, inherit class.__is_a = {[class] = true} class.is_a = function(self, other) return not not self.__is_a[other] end -- intercept assignment in global environment to infer the class name if not (args and args.name) then local env, env_meta, interceptor = getfenv(0), getmetatable(getfenv(0)), {} function interceptor:__newindex(key, value) if value == class then local name = tostring(key) getmetatable(class).__tostring = function() return name end end -- restore old metatable and insert value setmetatable(env, env_meta) if env.global then env.global(key) end -- handle 'strict' module env[key] = value end setmetatable(env, interceptor) end -- inherit superclasses (see above) inherit(class, unpack(super)) -- syntactic sugar local meta = { __call = function(self, ...) local obj = setmetatable({}, self) self.construct(obj, ...) return obj end, __tostring = function() return name end } return setmetatable(class, meta) end -- the module return setmetatable({new = new, inherit = inherit}, {__call = function(_,...) return new(...) end})
fix class members not callable from constructor
fix class members not callable from constructor
Lua
mit
scottcs/wyx
35a1a9069de09d1bb94c272cc2860c9096344f29
Engine/coreg.lua
Engine/coreg.lua
--Corouting Registry: this file is responsible for providing LIKO12 it's api-- local coreg = {reg={},stack={}} local sandbox = require("Engine.sandbox") --Returns the current active coroutine if exists function coreg:getCoroutine() return self.co, self.coglob end --Sets the current active coroutine function coreg:setCoroutine(co,glob) self.co = co or self.co self.coglob = glob or self.coglob return self end --Push the current coroutine to the coroutine stack, -- and set the current coroutine to nil function coreg:pushCoroutine() table.insert(self.stack,self.co) self.co = nil end --Pop a coroutine from the coroutine stack. function coreg:popCoroutine() if #self.stack < 1 then return error("No coroutines in the stack") end self.co = self.stack[1] for i=2,#self.stack do self.stack[i-1] = self.stack[i] end self.stack[#self.stack] = nil end --Call a function with the coroutine system plugged (A sub-coroutine) function coreg:subCoroutine(func,...) self:pushCoroutine() self.co = coroutine.create(func) return self:resumeCoroutine(...) end --Resumes the current active coroutine if exists. function coreg:resumeCoroutine(...) local lastargs = {...} while true do if not self.co or coroutine.status(self.co) == "dead" then return end local args = {coroutine.resume(self.co,unpack(lastargs))} if not args[1] then error(args[2]) end --Should have a better error handelling if coroutine.status(self.co) == "dead" and #self.stack >= 1 then --Hook system lastargs = args self:popCoroutine() else if not args[2] then self.os = nil; return end args = {self:trigger(select(2,unpack(args)))} if not args[1] then lastargs = args elseif not(type(args[1]) == "number" and args[1] == 2) then lastargs = {true,select(2,unpack(args))} else break end end end end --Sandbox a function with the current coroutine environment. function coreg:sandbox(f) if self.co and self.coglob then setfenv(f,self.coglob) return end local GLOB = sandbox(self) --Create a new sandbox. setfenv(f,GLOB) return GLOB end --Register a value to a specific key. --If the value is a table, then the values in the table will be registered at key:tableValueKey --If the value is a function, then it will be called instantly, and it must return true as the first argument to tell that it ran successfully. --Else, the value will be returned to the liko12 code. function coreg:register(value,key) local key = key or "none" if type(value) == "table" then for k,v in pairs(value) do self.reg[key..":"..k] = v end end self.reg[key] = value end --Trigger a value in a key. --If the value is a function, then it will call it instant. --Else, it will return the value. --Notice that the first return value is a number of "did it ran successfully", if false, the second return value is the error message. --Also the first return value could be also a number that specifies how should the coroutine resume (true boolean defaults to 1) --Corouting resumming codes: 1: resume instantly, 2: stop resuming (Will be yeild later, like when love.update is called). function coreg:trigger(key,...) local key = key or "none" if type(self.reg[key]) == "nil" then return false, "error, key not found !" end if type(self.reg[key]) == "function" then return self.reg[key](...) else return true, self.reg[key] end end --Returns the value registered in a specific key. --Returns: value then the given key. function coreg:get(key) local key = key or "none" return self.reg[key], key end --Returns a table containing the list of the registered keys. --list[key] = type function coreg:index() local list = {} for k,v in pairs(self.reg) do list[k] = type(v) end return list end --Returns a clone of the registry table. function coreg:registry() local reg = {} for k,v in pairs(self.reg) do reg[k] = v end return reg end return coreg
--Corouting Registry: this file is responsible for providing LIKO12 it's api-- local coreg = {reg={},stack={}} local sandbox = require("Engine.sandbox") --Returns the current active coroutine if exists function coreg:getCoroutine() return self.co, self.coglob end --Sets the current active coroutine function coreg:setCoroutine(co,glob) self.co = co or self.co self.coglob = glob or self.coglob return self end --Push the current coroutine to the coroutine stack, -- and set the current coroutine to nil function coreg:pushCoroutine() table.insert(self.stack,self.co) self.co = nil end --Pop a coroutine from the coroutine stack. function coreg:popCoroutine() if #self.stack < 1 then return error("No coroutines in the stack") end self.co = self.stack[1] for i=2,#self.stack do self.stack[i-1] = self.stack[i] end self.stack[#self.stack] = nil end --Call a function with the coroutine system plugged (A sub-coroutine) function coreg:subCoroutine(func) self:pushCoroutine() self.co = coroutine.create(func) end --Resumes the current active coroutine if exists. function coreg:resumeCoroutine(...) local lastargs = {...} while true do if not self.co or coroutine.status(self.co) == "dead" then return end local args = {coroutine.resume(self.co,unpack(lastargs))} if not args[1] then error(args[2]) end --Should have a better error handelling if coroutine.status(self.co) == "dead" and #self.stack >= 1 then --Hook system lastargs = args self:popCoroutine() else if not args[2] then self.os = nil; return end args = {self:trigger(select(2,unpack(args)))} if not args[1] then lastargs = args elseif not(type(args[1]) == "number" and args[1] == 2) then lastargs = args else break end end end end --Sandbox a function with the current coroutine environment. function coreg:sandbox(f) if self.co and self.coglob then setfenv(f,self.coglob) return end local GLOB = sandbox(self) --Create a new sandbox. setfenv(f,GLOB) return GLOB end --Register a value to a specific key. --If the value is a table, then the values in the table will be registered at key:tableValueKey --If the value is a function, then it will be called instantly, and it must return true as the first argument to tell that it ran successfully. --Else, the value will be returned to the liko12 code. function coreg:register(value,key) local key = key or "none" if type(value) == "table" then for k,v in pairs(value) do self.reg[key..":"..k] = v end end self.reg[key] = value end --Trigger a value in a key. --If the value is a function, then it will call it instant. --Else, it will return the value. --Notice that the first return value is a number of "did it ran successfully", if false, the second return value is the error message. --Also the first return value could be also a number that specifies how should the coroutine resume (true boolean defaults to 1) --Corouting resumming codes: 1: resume instantly, 2: stop resuming (Will be yeild later, like when love.update is called). function coreg:trigger(key,...) local key = key or "none" if type(self.reg[key]) == "nil" then return false, "error, key not found !" end if type(self.reg[key]) == "function" then return self.reg[key](...) else return true, self.reg[key] end end --Returns the value registered in a specific key. --Returns: value then the given key. function coreg:get(key) local key = key or "none" return self.reg[key], key end --Returns a table containing the list of the registered keys. --list[key] = type function coreg:index() local list = {} for k,v in pairs(self.reg) do list[k] = type(v) end return list end --Returns a clone of the registry table. function coreg:registry() local reg = {} for k,v in pairs(self.reg) do reg[k] = v end return reg end return coreg
Bugfix & Optimization
Bugfix & Optimization
Lua
mit
RamiLego4Game/LIKO-12
9fcfe12143916a5c6b1ad209311c5b67679ad41f
LookupTable.lua
LookupTable.lua
local LookupTable, parent = torch.class('nn.LookupTable', 'nn.Module') LookupTable.__version = 4 function LookupTable:__init(nIndex, nOutput) parent.__init(self) self.weight = torch.Tensor(nIndex, nOutput) self.gradWeight = torch.Tensor(nIndex, nOutput):zero() self._count = torch.IntTensor() self._input = torch.LongTensor() self.shouldScaleGradByFreq = false self:reset() end function LookupTable:accUpdateOnly() self.gradWeight = nil return self end function LookupTable:scaleGradByFreq() self.shouldScaleGradByFreq = true return self end function LookupTable:reset(stdv) stdv = stdv or 1 self.weight:normal(0, stdv) end function LookupTable:makeInputContiguous(input) -- make sure input is a contiguous torch.LongTensor if (not input:isContiguous()) or torch.type(input) ~= torch.type(self._input) then self.copiedInput = true self._input:resize(input:size()):copy(input) return self._input end self.copiedInput = false return input end function LookupTable:updateOutput(input) input = self:makeInputContiguous(input) if input:dim() == 1 then self.output:index(self.weight, 1, input) elseif input:dim() == 2 then self.output:index(self.weight, 1, input:view(-1)) self.output = self.output:view(input:size(1), input:size(2), self.weight:size(2)) else error("input must be a vector or matrix") end return self.output end function LookupTable:accGradParameters(input, gradOutput, scale) self.gradWeight.nn.LookupTable_accGradParameters(self, self.copiedInput and self._input or input, gradOutput, scale) end function LookupTable:type(type) parent.type(self, type) if type == 'torch.CudaTensor' then -- CUDA uses _sorted and _indices temporary tensors self._sorted = self.weight.new() self._indices = self.weight.new() else -- self._count and self._input should only be converted if using Cuda self._count = torch.IntTensor() self._input = torch.LongTensor() end return self end -- we do not need to accumulate parameters when sharing LookupTable.sharedAccUpdateGradParameters = LookupTable.accUpdateGradParameters
local LookupTable, parent = torch.class('nn.LookupTable', 'nn.Module') LookupTable.__version = 4 function LookupTable:__init(nIndex, nOutput) parent.__init(self) self.weight = torch.Tensor(nIndex, nOutput) self.gradWeight = torch.Tensor(nIndex, nOutput):zero() self._count = torch.IntTensor() self._input = torch.LongTensor() self.shouldScaleGradByFreq = false self:reset() end function LookupTable:accUpdateOnly() self.gradWeight = nil return self end function LookupTable:scaleGradByFreq() self.shouldScaleGradByFreq = true return self end function LookupTable:reset(stdv) stdv = stdv or 1 self.weight:normal(0, stdv) end function LookupTable:makeInputContiguous(input) -- make sure input is a contiguous torch.LongTensor if (not input:isContiguous()) or torch.type(input) ~= torch.type(self._input) then self.copiedInput = true self._input:resize(input:size()):copy(input) return self._input end self.copiedInput = false return input end function LookupTable:updateOutput(input) input = self:makeInputContiguous(input) if input:dim() == 1 then self.output:index(self.weight, 1, input) elseif input:dim() == 2 then self.output:index(self.weight, 1, input:view(-1)) self.output = self.output:view(input:size(1), input:size(2), self.weight:size(2)) else error("input must be a vector or matrix") end return self.output end function LookupTable:accGradParameters(input, gradOutput, scale) input = self.copiedInput and self._input or input if input:dim() == 2 then input = input:view(-1) elseif input:dim() ~= 1 then error("input must be a vector or matrix") end self.gradWeight.nn.LookupTable_accGradParameters(self, input, gradOutput, scale) end function LookupTable:type(type) parent.type(self, type) if type == 'torch.CudaTensor' then -- CUDA uses _sorted and _indices temporary tensors self._sorted = self.weight.new() self._indices = self.weight.new() else -- self._count and self._input should only be converted if using Cuda self._count = torch.IntTensor() self._input = torch.LongTensor() end return self end -- we do not need to accumulate parameters when sharing LookupTable.sharedAccUpdateGradParameters = LookupTable.accUpdateGradParameters
Fix CUDA LookupTable with 2D inputs.
Fix CUDA LookupTable with 2D inputs. The CUDA version of LookupTable was incorrect for 2D inputs. This fixes it by viewing 2D inputs as a 1D tensor.
Lua
bsd-3-clause
hery/nn,sbodenstein/nn,forty-2/nn,douwekiela/nn,davidBelanger/nn,caldweln/nn,jhjin/nn,andreaskoepf/nn,xianjiec/nn,eriche2016/nn,hughperkins/nn,PierrotLC/nn,GregSatre/nn,apaszke/nn,elbamos/nn,EnjoyHacking/nn,nicholas-leonard/nn,fmassa/nn,rotmanmi/nn,abeschneider/nn,jzbontar/nn,ominux/nn,mys007/nn,noa/nn,lvdmaaten/nn,kmul00/nn,jonathantompson/nn,witgo/nn,ivendrov/nn,eulerreich/nn,aaiijmrtt/nn,lukasc-ch/nn,Aysegul/nn,Moodstocks/nn,diz-vara/nn,Jeffyrao/nn,vgire/nn,sagarwaghmare69/nn,zchengquan/nn,PraveerSINGH/nn,bartvm/nn,szagoruyko/nn,adamlerer/nn,joeyhng/nn,zhangxiangxiao/nn,LinusU/nn,colesbury/nn,mlosch/nn,Djabbz/nn,clementfarabet/nn
33514ed2ca7711253a27820c4a7717e74be16630
lua/effects/warpcore_breach/init.lua
lua/effects/warpcore_breach/init.lua
local matRefraction = Material( "refract_ring" ) local tMats = {} tMats.Glow1 = Material("sprites/light_glow02") --tMats.Glow1 = Material("models/roller/rollermine_glow") tMats.Glow2 = Material("sprites/yellowflare") tMats.Glow3 = Material("sprites/redglow2") for _,mat in pairs(tMats) do mat:SetInt("$spriterendermode",9) mat:SetInt("$ignorez",1) mat:SetInt("$illumfactor",8) end -- --------------------------------------------------------- -- Init( data table ) -- --------------------------------------------------------- function EFFECT:Init( data ) self.Position = data:GetOrigin() self.Position.z = self.Position.z + 4 self.TimeLeft = CurTime() + 7.6 self.GAlpha = 254 self.GSize = 100 self.CloudHeight = data:GetScale() self.Refract = 0 self.Size = 24 if render.GetDXLevel() <= 81 then matRefraction = Material( "effects/strider_pinch_dudv" ) end self.SplodeDist = 700 self.BlastSpeed = 3500 self.lastThink = 0 self.MinSplodeTime = CurTime() + self.CloudHeight/self.BlastSpeed self.MaxSplodeTime = CurTime() + 6 self.GroundPos = self.Position - Vector(0,0,self.CloudHeight) local Pos = self.Position self.smokeparticles = {} self.Emitter = ParticleEmitter( Pos ) --moving fire plumes for i=1, math.ceil(26) do local vecang = VectorRand()*8 local spawnpos = Pos + 64*vecang for k=5,26 do local particle = self.Emitter:Add( "particles/flamelet"..math.random(1,5), spawnpos - vecang*9*k) particle:SetVelocity(vecang*math.Rand(-80,-100)) particle:SetDieTime( math.Rand( 8, 16 ) ) particle:SetStartAlpha( math.Rand(230, 250) ) particle:SetStartSize( k*math.Rand( 13, 15 ) ) particle:SetEndSize( k*math.Rand( 17, 19 ) ) particle:SetRoll( math.Rand( 20, 80 ) ) particle:SetRollDelta( math.random( -1, 1 ) ) particle:SetColor(20, math.random(20,60), math.random(100,255)) -- Removed Mar 19, 2015 particle:VelocityDecay( true ) end end --central fire plumes for i=1, math.ceil(26) do local vecang = VectorRand()*8 local spawnpos = Pos + 256*vecang for k=5,26 do local particle = self.Emitter:Add( "particles/flamelet"..math.random(1,5), spawnpos - vecang*9*k) particle:SetVelocity(vecang*math.Rand(2,3)) particle:SetDieTime( math.Rand( 4, 12 ) ) particle:SetStartAlpha( math.Rand(230, 250) ) particle:SetStartSize( k*math.Rand( 13, 15 ) ) particle:SetEndSize( k*math.Rand( 17, 19 ) ) particle:SetRoll( math.Rand( 20, 80 ) ) particle:SetRollDelta( math.random( -1, 1 ) ) particle:SetColor(100, math.random(100,128), math.random(230,255)) -- Removed Mar 19, 2015 particle:VelocityDecay( true ) end end self.vecang = VectorRand() end -- --------------------------------------------------------- -- THINK -- --------------------------------------------------------- function EFFECT:Think( ) local Pos = self.Position local timeleft = self.TimeLeft - CurTime() if timeleft > 0 then local ftime = FrameTime() self.GAlpha = self.GAlpha - 10.5*ftime self.GSize = self.GSize - 0.12*timeleft*ftime self.Size = self.Size + 1200*ftime self.Refract = self.Refract + 1.3*ftime --shock ring if (self.Size < 8000) then local spawndist = self.Size local NumPuffs = spawndist / 80 local ang = self.vecang:Angle() for i=1, NumPuffs do ang:RotateAroundAxis(ang:Up(), (360/NumPuffs)) local newang = ang:Forward() local spawnpos = (Pos + (newang * spawndist)) local particle = self.Emitter:Add( "particles/flamelet"..math.random(1,5), spawnpos) -- particle:SetVelocity(vecang*math.Rand(2,3)) particle:SetVelocity(Vector(0, 0, 0)) particle:SetDieTime( 2 ) particle:SetStartAlpha( math.Rand(230, 250) ) particle:SetStartSize( 20*math.Rand( 13, 15 ) ) particle:SetEndSize( math.Rand( 17, 19 ) ) particle:SetRoll( math.Rand( 20, 80 ) ) particle:SetRollDelta( math.random( -1, 1 ) ) particle:SetColor(20, math.random(20,60), math.random(100,255)) -- Removed Mar 19, 2015 particle:VelocityDecay( true ) end end return true else self.Emitter:Finish() return false end end -- ------------------------------------------------------- -- Draw the effect -- ------------------------------------------------------- function EFFECT:Render( ) local startpos = self.Position --Base glow render.SetMaterial(tMats.Glow1) render.DrawSprite(startpos, 400*self.GSize,90*self.GSize,Color(80, math.random(80,90), math.random(230,255),self.GAlpha)) render.DrawSprite(startpos, 70*self.GSize,280*self.GSize,Color(80, math.random(80,90), math.random(240,255),0.7*self.GAlpha)) --shockwave if self.Size < 32768 then local Distance = EyePos():Distance( self:GetPos() ) local Pos = self:GetPos() + (EyePos() - self:GetPos()):GetNormal() * Distance * (self.Refract^(0.3)) * 0.8 matRefraction:SetMaterialFloat( "$refractamount", math.sin( self.Refract * math.pi ) * 0.1 ) render.SetMaterial( matRefraction ) render.UpdateRefractTexture() render.DrawSprite( Pos, self.Size, self.Size ) end end
local matRefraction = Material( "refract_ring" ) local tMats = {} tMats.Glow1 = Material("sprites/light_glow02") --tMats.Glow1 = Material("models/roller/rollermine_glow") tMats.Glow2 = Material("sprites/yellowflare") tMats.Glow3 = Material("sprites/redglow2") for _,mat in pairs(tMats) do mat:SetInt("$spriterendermode",9) mat:SetInt("$ignorez",1) mat:SetInt("$illumfactor",8) end -- --------------------------------------------------------- -- Init( data table ) -- --------------------------------------------------------- function EFFECT:Init( data ) self.Position = data:GetOrigin() self.Position.z = self.Position.z + 4 self.TimeLeft = CurTime() + 7.6 self.GAlpha = 254 self.GSize = 100 self.CloudHeight = data:GetScale() self.Refract = 0 self.Size = 24 if render.GetDXLevel() <= 81 then matRefraction = Material( "effects/strider_pinch_dudv" ) end self.SplodeDist = 700 self.BlastSpeed = 3500 self.lastThink = 0 self.MinSplodeTime = CurTime() + self.CloudHeight/self.BlastSpeed self.MaxSplodeTime = CurTime() + 6 self.GroundPos = self.Position - Vector(0,0,self.CloudHeight) local Pos = self.Position self.smokeparticles = {} self.Emitter = ParticleEmitter( Pos ) self.vecang = VectorRand() -- Moved here to avoid race condition. --moving fire plumes for i=1, math.ceil(26) do local vecang = VectorRand()*8 local spawnpos = Pos + 64*vecang for k=5,26 do local particle = self.Emitter:Add( "particles/flamelet"..math.random(1,5), spawnpos - vecang*9*k) particle:SetVelocity(vecang*math.Rand(-80,-100)) particle:SetDieTime( math.Rand( 8, 16 ) ) particle:SetStartAlpha( math.Rand(230, 250) ) particle:SetStartSize( k*math.Rand( 13, 15 ) ) particle:SetEndSize( k*math.Rand( 17, 19 ) ) particle:SetRoll( math.Rand( 20, 80 ) ) particle:SetRollDelta( math.random( -1, 1 ) ) particle:SetColor(20, math.random(20,60), math.random(100,255)) -- Removed Mar 19, 2015 particle:VelocityDecay( true ) end end --central fire plumes for i=1, math.ceil(26) do local vecang = VectorRand()*8 local spawnpos = Pos + 256*vecang for k=5,26 do local particle = self.Emitter:Add( "particles/flamelet"..math.random(1,5), spawnpos - vecang*9*k) particle:SetVelocity(vecang*math.Rand(2,3)) particle:SetDieTime( math.Rand( 4, 12 ) ) particle:SetStartAlpha( math.Rand(230, 250) ) particle:SetStartSize( k*math.Rand( 13, 15 ) ) particle:SetEndSize( k*math.Rand( 17, 19 ) ) particle:SetRoll( math.Rand( 20, 80 ) ) particle:SetRollDelta( math.random( -1, 1 ) ) particle:SetColor(100, math.random(100,128), math.random(230,255)) -- Removed Mar 19, 2015 particle:VelocityDecay( true ) end end end -- --------------------------------------------------------- -- THINK -- --------------------------------------------------------- function EFFECT:Think( ) local Pos = self.Position local timeleft = self.TimeLeft - CurTime() if timeleft > 0 then local ftime = FrameTime() self.GAlpha = self.GAlpha - 10.5*ftime self.GSize = self.GSize - 0.12*timeleft*ftime self.Size = self.Size + 1200*ftime self.Refract = self.Refract + 1.3*ftime --shock ring if (self.Size < 8000) then local spawndist = self.Size local NumPuffs = spawndist / 80 local ang = self.vecang:Angle() for i=1, NumPuffs do ang:RotateAroundAxis(ang:Up(), (360/NumPuffs)) local newang = ang:Forward() local spawnpos = (Pos + (newang * spawndist)) local particle = self.Emitter:Add( "particles/flamelet"..math.random(1,5), spawnpos) -- particle:SetVelocity(vecang*math.Rand(2,3)) particle:SetVelocity(Vector(0, 0, 0)) particle:SetDieTime( 2 ) particle:SetStartAlpha( math.Rand(230, 250) ) particle:SetStartSize( 20*math.Rand( 13, 15 ) ) particle:SetEndSize( math.Rand( 17, 19 ) ) particle:SetRoll( math.Rand( 20, 80 ) ) particle:SetRollDelta( math.random( -1, 1 ) ) particle:SetColor(20, math.random(20,60), math.random(100,255)) -- Removed Mar 19, 2015 particle:VelocityDecay( true ) end end return true else self.Emitter:Finish() return false end end -- ------------------------------------------------------- -- Draw the effect -- ------------------------------------------------------- function EFFECT:Render( ) local startpos = self.Position --Base glow render.SetMaterial(tMats.Glow1) render.DrawSprite(startpos, 400*self.GSize,90*self.GSize,Color(80, math.random(80,90), math.random(230,255),self.GAlpha)) render.DrawSprite(startpos, 70*self.GSize,280*self.GSize,Color(80, math.random(80,90), math.random(240,255),0.7*self.GAlpha)) --shockwave if self.Size < 32768 then local Distance = EyePos():Distance( self:GetPos() ) local Pos = self:GetPos() + (EyePos() - self:GetPos()):GetNormal() * Distance * (self.Refract^(0.3)) * 0.8 matRefraction:SetMaterialFloat( "$refractamount", math.sin( self.Refract * math.pi ) * 0.1 ) render.SetMaterial( matRefraction ) render.UpdateRefractTexture() render.DrawSprite( Pos, self.Size, self.Size ) end end
Fix warpcore_breach race condition
Fix warpcore_breach race condition
Lua
apache-2.0
N3X15/spacebuild
8443b091a930ea84338a764f16747b2b3c3b6898
packages/tate.lua
packages/tate.lua
local pdf = require("justenoughlibtexpdf") SILE.tateFramePrototype = SILE.framePrototype { direction = "TTB-RTL", enterHooks = { function (self) self.oldtypesetter = SILE.typesetter pdf.setdirmode(1) SILE.typesetter.leadingFor = function(self, v) v.height = SILE.toPoints("1zw") return SILE.settings.get("document.parskip") end SILE.typesetter.breakIntoLines = SILE.require("packages/break-firstfit") end }, leaveHooks = { function (self) SILE.typesetter = self.oldtypesetter pdf.setdirmode(0) end } } SILE.newTateFrame = function ( spec ) return SILE.newFrame(spec, SILE.tateFramePrototype) end SILE.registerCommand("tate-frame", function (options, content) SILE.documentState.thisPageTemplate.frames[options.id] = SILE.newTateFrame(options); end, "Declares (or re-declares) a frame on this page.") local swap = function (x) local w = x.width x.width = SILE.length.new({}) + x.height x.height = type(w) == "table" and w.length or w end local outputLatinInTate = function (self, typesetter, line) -- My baseline moved typesetter.frame:advanceWritingDirection(SILE.toPoints("-0.5zw")) typesetter.frame:advancePageDirection(SILE.toPoints("0.25zw")) local horigin = typesetter.frame.state.cursorX local vorigin = -typesetter.frame.state.cursorY self:oldOutputYourself(typesetter,line) typesetter.frame.state.cursorY = -vorigin typesetter.frame:advanceWritingDirection(self.height) -- My baseline moved typesetter.frame:advanceWritingDirection(SILE.toPoints("0.5zw") ) typesetter.frame:advancePageDirection(- SILE.toPoints("0.25zw")) end local outputTateChuYoko = function (self, typesetter, line) -- My baseline moved local vorigin = -typesetter.frame.state.cursorY typesetter.frame:advanceWritingDirection(self.height) typesetter.frame:advancePageDirection(0.5 * self.width.length) pdf.setdirmode(0) self:oldOutputYourself(typesetter,line) pdf.setdirmode(1) typesetter.frame.state.cursorY = -vorigin typesetter.frame:advanceWritingDirection(self.height) -- My baseline moved -- typesetter.frame:advanceWritingDirection(SILE.toPoints("1zw") ) typesetter.frame:advancePageDirection(-0.5 * self.width.length) end -- Eventually will be automatically called by script detection, but for now -- called manually SILE.registerCommand("latin-in-tate", function (options, content) local nodes local oldT = SILE.typesetter local prevDirection = oldT.frame.direction if oldT.frame:writingDirection() ~= "TTB" then return SILE.process(content) end SILE.require("packages/rotate") SILE.settings.temporarily(function() local latinT = SILE.defaultTypesetter {} latinT.frame = oldT.frame latinT:initState() SILE.typesetter = latinT SILE.settings.set("document.language", "xx") SILE.settings.set("font.direction", "LTR") SILE.process(content) nodes = SILE.typesetter.state.nodes for i=1,#nodes do if nodes[i]:isUnshaped() then nodes[i] = nodes[i]:shape() end end SILE.typesetter.frame.direction = prevDirection end) SILE.typesetter = oldT SILE.typesetter:pushGlue({ width = SILE.length.new({length = SILE.toPoints("0.5zw"), stretch = SILE.toPoints("0.25zw"), shrink = SILE.toPoints("0.25zw") }) }) for i = 1,#nodes do if SILE.typesetter.frame:writingDirection() ~= "TTB" then SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes+1] = nodes[i] elseif nodes[i]:isGlue() then nodes[i].width = nodes[i].width SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes+1] = nodes[i] elseif nodes[i].width > 0 then SILE.call("hbox", {}, function () SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes+1] = nodes[i] end) local n = SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] n.oldOutputYourself = n.outputYourself n.outputYourself = outputLatinInTate swap(n) end end end, "Typeset rotated Western text in vertical Japanese") SILE.registerCommand("tate-chu-yoko", function (options, content) if SILE.typesetter.frame:writingDirection() ~= "TTB" then return SILE.process(content) end SILE.typesetter:pushGlue({ width = SILE.length.new({length = SILE.toPoints("0.5zw"), stretch = SILE.toPoints("0.25zw"), shrink = SILE.toPoints("0.25zw") }) }) SILE.settings.temporarily(function() SILE.settings.set("document.language", "xx") SILE.settings.set("font.direction", "LTR") SILE.call("hbox", {}, content) local n = SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] n.oldOutputYourself = n.outputYourself n.outputYourself = outputTateChuYoko end) SILE.typesetter:pushGlue({ width = SILE.length.new({length = SILE.toPoints("0.5zw"), stretch = SILE.toPoints("0.25zw"), shrink = SILE.toPoints("0.25zw") }) }) end)
local pdf = require("justenoughlibtexpdf") SILE.tateFramePrototype = SILE.framePrototype { direction = "TTB-RTL", enterHooks = { function (self) self.oldtypesetter = SILE.typesetter SILE.typesetter.leadingFor = function(self, v) v.height = SILE.toPoints("1zw") return SILE.settings.get("document.parskip") end SILE.typesetter.breakIntoLines = SILE.require("packages/break-firstfit") end }, leaveHooks = { function (self) SILE.typesetter = self.oldtypesetter end } } SILE.newTateFrame = function ( spec ) return SILE.newFrame(spec, SILE.tateFramePrototype) end SILE.registerCommand("tate-frame", function (options, content) SILE.documentState.thisPageTemplate.frames[options.id] = SILE.newTateFrame(options); end, "Declares (or re-declares) a frame on this page.") local swap = function (x) local w = x.width x.width = SILE.length.new({}) + x.height x.height = type(w) == "table" and w.length or w end local outputLatinInTate = function (self, typesetter, line) -- My baseline moved typesetter.frame:advanceWritingDirection(SILE.toPoints("-0.5zw")) typesetter.frame:advancePageDirection(SILE.toPoints("0.25zw")) local horigin = typesetter.frame.state.cursorX local vorigin = -typesetter.frame.state.cursorY self:oldOutputYourself(typesetter,line) typesetter.frame.state.cursorY = -vorigin typesetter.frame:advanceWritingDirection(self:lineContribution()) -- My baseline moved typesetter.frame:advanceWritingDirection(SILE.toPoints("0.5zw") ) typesetter.frame:advancePageDirection(- SILE.toPoints("0.25zw")) end local outputTateChuYoko = function (self, typesetter, line) -- My baseline moved local vorigin = -typesetter.frame.state.cursorY typesetter.frame:advanceWritingDirection(self:lineContribution()) typesetter.frame:advancePageDirection(0.5 * self.width.length) self:oldOutputYourself(typesetter,line) typesetter.frame.state.cursorY = -vorigin typesetter.frame:advanceWritingDirection(self:lineContribution()) -- My baseline moved -- typesetter.frame:advanceWritingDirection(SILE.toPoints("1zw") ) typesetter.frame:advancePageDirection(-0.5 * self.width.length) end -- Eventually will be automatically called by script detection, but for now -- called manually SILE.registerCommand("latin-in-tate", function (options, content) local nodes local oldT = SILE.typesetter local prevDirection = oldT.frame.direction if oldT.frame:writingDirection() ~= "TTB" then return SILE.process(content) end SILE.require("packages/rotate") SILE.settings.temporarily(function() local latinT = SILE.defaultTypesetter {} latinT.frame = oldT.frame latinT:initState() SILE.typesetter = latinT SILE.settings.set("document.language", "xx") SILE.settings.set("font.direction", "LTR") SILE.process(content) nodes = SILE.typesetter.state.nodes for i=1,#nodes do if nodes[i]:isUnshaped() then nodes[i] = nodes[i]:shape() end end SILE.typesetter.frame.direction = prevDirection end) SILE.typesetter = oldT SILE.typesetter:pushGlue({ width = SILE.length.new({length = SILE.toPoints("0.5zw"), stretch = SILE.toPoints("0.25zw"), shrink = SILE.toPoints("0.25zw") }) }) for i = 1,#nodes do if SILE.typesetter.frame:writingDirection() ~= "TTB" then SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes+1] = nodes[i] elseif nodes[i]:isGlue() then nodes[i].width = nodes[i].width SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes+1] = nodes[i] elseif nodes[i].width > 0 then SILE.call("hbox", {}, function () SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes+1] = nodes[i] end) local n = SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] n.oldOutputYourself = n.outputYourself n.outputYourself = outputLatinInTate n.misfit = true end end end, "Typeset rotated Western text in vertical Japanese") SILE.registerCommand("tate-chu-yoko", function (options, content) if SILE.typesetter.frame:writingDirection() ~= "TTB" then return SILE.process(content) end SILE.typesetter:pushGlue({ width = SILE.length.new({length = SILE.toPoints("0.5zw"), stretch = SILE.toPoints("0.25zw"), shrink = SILE.toPoints("0.25zw") }) }) SILE.settings.temporarily(function() SILE.settings.set("document.language", "xx") SILE.settings.set("font.direction", "LTR") SILE.call("hbox", {}, content) local n = SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] n.misfit = false n.oldOutputYourself = n.outputYourself n.outputYourself = outputTateChuYoko end) SILE.typesetter:pushGlue({ width = SILE.length.new({length = SILE.toPoints("0.5zw"), stretch = SILE.toPoints("0.25zw"), shrink = SILE.toPoints("0.25zw") }) }) end)
This package is still somewhat broken, but these fixes are probably correct.
This package is still somewhat broken, but these fixes are probably correct.
Lua
mit
anthrotype/sile,anthrotype/sile,anthrotype/sile,simoncozens/sile,alerque/sile,alerque/sile,neofob/sile,anthrotype/sile,simoncozens/sile,alerque/sile,neofob/sile,alerque/sile,simoncozens/sile,simoncozens/sile,neofob/sile,neofob/sile
5f0a102a906c213d1094438ebbaf82c9d4324a82
test_scripts/Policies/build_options/103_ATF_Timeout_wait_response_PTU_PROPRIETARY.lua
test_scripts/Policies/build_options/103_ATF_Timeout_wait_response_PTU_PROPRIETARY.lua
--------------------------------------------------------------------------------------------- -- Requirements summary: -- [PolicyTableUpdate] Timeout to wait a response on PTU -- -- Description: -- SDL should request PTU in app is registered and getting device consent -- 1. Used preconditions -- SDL is built with "-DEXTENDED_POLICY: PROPRIETARY" flag -- 2. Performed steps -- Application is registered. -- PTU is requested. -- -- Expected result: -- To define the timeout to wait a response on PTU, Policies manager must refer PTS -- "module_config" section, key <timeout_after_x_seconds>. --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonSteps = require('user_modules/shared_testcases/commonSteps') local commonFunctions = require('user_modules/shared_testcases/commonFunctions') local testCasesForPolicyTableSnapshot = require('user_modules/shared_testcases/testCasesForPolicyTableSnapshot') local commonPreconditions = require('user_modules/shared_testcases/commonPreconditions') local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable') --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() testCasesForPolicyTable.Delete_Policy_table_snapshot() commonPreconditions:Connecttest_without_ExitBySDLDisconnect_WithoutOpenConnectionRegisterApp("connecttest_ConnectMobile.lua") --ToDo: shall be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed config.defaultProtocolVersion = 2 --[[ General Settings for configuration ]] Test = require('user_modules/connecttest_ConnectMobile') require('cardinalities') require('user_modules/AppTypes') local mobile_session = require('mobile_session') --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test:Precondition_ConnectMobile() self:connectMobile() end function Test:Precondition_StartSession() self.mobileSession = mobile_session.MobileSession(self, self.mobileConnection) self.mobileSession:StartService(7) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_PTS_Timeout_wait_response_PTU() local correlationId = self.mobileSession:SendRPC("RegisterAppInterface", config.application1.registerAppInterfaceParams) EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered") :Do(function(_,data) self.HMIAppID = data.params.application.appID end) self.mobileSession:ExpectResponse(correlationId, { success = true, resultCode = "SUCCESS" }) self.mobileSession:ExpectNotification("OnHMIStatus", {hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE", systemContext = "MAIN"}) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATE_NEEDED"}) EXPECT_HMICALL("BasicCommunication.PolicyUpdate", {file = "/tmp/fs/mp/images/ivsu_cache/sdl_snapshot.json"}) :Do(function(_,data) self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {}) end) :ValidIf(function(_,data) local timeout_after_x_seconds_preloaded = testCasesForPolicyTableSnapshot:get_data_from_Preloaded_PT("module_config.timeout_after_x_seconds") local timeout_after_x_seconds = testCasesForPolicyTableSnapshot:get_data_from_PTS("module_config.timeout_after_x_seconds") if(timeout_after_x_seconds_preloaded ~= timeout_after_x_seconds) then commonFunctions:printError("Error: PTS: timeout_after_x_seconds = "..data.params.timeout.."ms is not as expected. Expected: "..timeout_after_x_seconds_preloaded.."ms.") return false else if(data.params.timeout ~= timeout_after_x_seconds) then commonFunctions:printError("Error: data.params.timeout = "..data.params.timeout.."ms. Expected: "..timeout_after_x_seconds.."ms.") return false else return true end end end) end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_StopSDL() StopSDL() end return Test
--------------------------------------------------------------------------------------------- -- Requirements summary: -- [PolicyTableUpdate] Timeout to wait a response on PTU -- -- Description: -- SDL should request PTU in app is registered and getting device consent -- 1. Used preconditions -- SDL is built with "-DEXTENDED_POLICY: PROPRIETARY" flag -- 2. Performed steps -- Application is registered. -- PTU is requested. -- -- Expected result: -- To define the timeout to wait a response on PTU, Policies manager must refer PTS -- "module_config" section, key <timeout_after_x_seconds>. --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonSteps = require('user_modules/shared_testcases/commonSteps') local commonFunctions = require('user_modules/shared_testcases/commonFunctions') local testCasesForPTS = require('user_modules/shared_testcases/testCasesForPolicyTableSnapshot') local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable') local mobile_session = require('mobile_session') --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() testCasesForPolicyTable.Delete_Policy_table_snapshot() --ToDo: shall be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed config.defaultProtocolVersion = 2 --[[ General Settings for configuration ]] Test = require('user_modules/dummy_connecttest') require('cardinalities') require('user_modules/AppTypes') local default_app_params = config.application1.registerAppInterfaceParams --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test:Start_SDL() self:runSDL() commonFunctions:waitForSDLStart(self):Do(function() self:initHMI():Do(function() commonFunctions:userPrint(35, "HMI initialized") self:initHMI_onReady():Do(function () commonFunctions:userPrint(35, "HMI is ready") self:connectMobile():Do(function () commonFunctions:userPrint(35, "Mobile Connected") end) end) end) end) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_PTS_Timeout_wait_response_PTU() self.mobileSession = mobile_session.MobileSession(self, self.mobileConnection) local on_rpc_service_started = self.mobileSession:StartRPC() on_rpc_service_started:Do(function() local correlationId = self.mobileSession:SendRPC("RegisterAppInterface", default_app_params) EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered"):Do(function(_,data) self.HMIAppID = data.params.application.appID end) self.mobileSession:ExpectResponse(correlationId, { success = true, resultCode = "SUCCESS" }) self.mobileSession:ExpectNotification("OnHMIStatus", {hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE", systemContext = "MAIN"}) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATE_NEEDED"}) EXPECT_HMICALL("BasicCommunication.PolicyUpdate", {file = "/tmp/fs/mp/images/ivsu_cache/sdl_snapshot.json"}) :Do(function(_,data) self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {}) end) :ValidIf(function(_,data) local timeout_after_x_seconds_preloaded = testCasesForPTS:get_data_from_Preloaded_PT("module_config.timeout_after_x_seconds") local timeout_after_x_seconds = testCasesForPTS:get_data_from_PTS("module_config.timeout_after_x_seconds") if(timeout_after_x_seconds_preloaded ~= timeout_after_x_seconds) then commonFunctions:printError("Error: PTS: timeout_after_x_seconds = "..data.params.timeout.. "ms is not as expected. Expected: "..timeout_after_x_seconds_preloaded.."ms.") return false else if(data.params.timeout ~= timeout_after_x_seconds) then commonFunctions:printError("Error: data.params.timeout = "..data.params.timeout.. "ms. Expected: "..timeout_after_x_seconds.."ms.") return false else return true end end end) end) end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_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
16d3c4c1d665f732c36a1b4d23ee745b6dd12a79
source/game/map.lua
source/game/map.lua
-------------------------------------------------------------------------------- -- map.lua - Defines a map which manages the construction of the hex grid and the path within -------------------------------------------------------------------------------- require "source/pathfinder" require "source/utilities/vector" Map = flower.class() function Map:init(t) -- Copy all data members of the table as member variables for k, d in pairs(t) do self[k] = d end -- Try to load the map if not self:load() then if self.file ~= nil then print("Cannot Load Map: " .. self.file) else print("Cannot Load Map: nil") end end end function Map:load(file) self.file = self.file or file if not (self.file and io.fileExists(self.file)) then return false end self.map = dofile(self.file) self.width = self.map.width or self.width self.height = self.map.height or self.height self.grid = flower.MapImage(self.texture, self.width, self.height, self.tileWidth, self.tileHeight, self.radius) self.grid:setShape(MOAIGridSpace.HEX_SHAPE) self.grid:setLayer(self.layer) self.selectedImage = flower.SheetImage(self.texture) self.selectedImage:setTileSize(self.tileWidth, self.tileHeight) self.selectedImage:setLayer(self.layer) -- TODO: Fix these numbers self.selectedImage:setScl(self.height / self.tileHeight / 1.3, self.height / self.tileHeight / 1.3) self.selectedImage:setPiv(self.radius / 2, self.radius / 2) self.selectedImage:setColor(0.2, 0.2, 0.2, 1) self.selectedImage:setVisible(false) if type(self.map.tiles) == "table" then for i = 1,self.width do for j = 1,self.height do self.grid.grid:setTile(i, j, self.map.default_tile) end end for k, data in pairs(self.map.tiles) do for j, pos in ipairs(data) do self.grid.grid:setTile(pos[1], pos[2], k) end end elseif type(self.map.tiles) == "string" then -- Load file from stream local fileStream = MOAIFileStream.new() if not fileStream:open(self.map.tiles, MOAIFileStream.READ) then return false end self.grid.grid:streamTilesIn(fileStream) fileStream:close() self.spawnTiles = {} self.targetPosition = {} for i = 1,self.width do for j = 1,self.height do local tile = self.grid.grid:getTile(i, j) if tile == TILE_TYPES.TARGET then self.targetPosition[1], self.targetPosition[2] = i, j elseif tile == TILE_TYPES.SPAWN then table.insert(self.spawnTiles, {i, j}) end end end else return false end -- TODO: make this a bit more dynamic local function validTileCallback(tile) return tile == TILE_TYPES.ENEMY or tile == TILE_TYPES.TARGET or tile == TILE_TYPES.SPAWN end -- Find path in the map if self:isPathDynamic() then self.path = findPath(self:getMOAIGrid(), vector{self.targetPosition[1], self.targetPosition[2]}, validTileCallback) else self.path = self.map.paths[1] self.targetPosition = self.path[#self.path] end return true end function Map:isTileSelected() return self.tileSelected end -- TODO: need to center the selected tile function Map:selectTile(pos) local worldPos = self:gridToScreenSpace(pos, MOAIGridSpace.TILE_LEFT_TOP) self.selectedImage:setVisible(true) self.selectedImage:setIndex(self.grid:getTile(pos[1], pos[2])) self.selectedImage:setPos(worldPos[1], worldPos[2]) self.tileSelected = true end function Map:unselectTile() self.selectedImage:setVisible(false) self.tileSelected = false end function Map:randomStartingPosition() local startPosition = not self:isPathDynamic() and self.path[1] if not startPosition then local randomIndex = math.random(1, #self.spawnTiles) startPosition = self.spawnTiles[randomIndex] end return self:gridToScreenSpace(startPosition) end function Map:screenToGridSpace(x, y, layer) local prop = self:getGrid() x, y = layer:wndToWorld(x, y) x, y = prop:worldToModel(x, y) return vector{self:getMOAIGrid():locToCoord(x, y)} end function Map:gridToScreenSpace(pos, alignment) alignment = alignment or MOAIGridSpace.TILE_CENTER if type(pos) == "table" then return vector{self:getMOAIGrid():getTileLoc(pos[1], pos[2], alignment)} elseif type(pos) == "number" then return self:getMOAIGrid():getTileLoc(pos, 0, alignment) end end -- Returns true if the path was found using a pathfinder function Map:isPathDynamic() if self.map.paths then return false end return true end function Map:clearTile(pos) self:setTile(pos, TILE_TYPES.EMPTY) end function Map:setTile(pos, index) self:getGrid():setTile(pos[1], pos[2], index) end function Map:getTile(pos) return self:getGrid():getTile(pos[1], pos[2]) end function Map:getPath() return self.path end function Map:getWaves() return self.map.waves end -- TODO: remove these methods to return the grid function Map:getGrid() return self.grid end function Map:getMOAIGrid() return self:getGrid().grid end function Map:setLayer(layer) self.layer = layer self.grid:setLayer(self.layer) self.selectedImage:setLayer(self.layer) end function Map:resetTowers(towers) for i = 1,self.width do for j = 1,self.height do local pos = vector({i, j}) local tile = self:getTile(pos) if towers[Tower.serialize_pos(pos)] == nil then if tile == TILE_TYPES.YELLOW or tile == TILE_TYPES.RED or tile == TILE_TYPES.GREEN or tile == TILE_TYPES.BLUE then self:setTile(pos, TILE_TYPES.EMPTY) end else self:setTile(pos, towers[Tower.serialize_pos(pos)].type.id) end end end end
-------------------------------------------------------------------------------- -- map.lua - Defines a map which manages the construction of the hex grid and the path within -------------------------------------------------------------------------------- require "source/pathfinder" require "source/utilities/vector" Map = flower.class() function Map:init(t) -- Copy all data members of the table as member variables for k, d in pairs(t) do self[k] = d end -- Try to load the map if not self:load() then if self.file ~= nil then print("Cannot Load Map: " .. self.file) else print("Cannot Load Map: nil") end end end function Map:load(file) self.file = self.file or file if not (self.file and io.fileExists(self.file)) then return false end self.map = dofile(self.file) self.width = self.map.width or self.width self.height = self.map.height or self.height self.grid = flower.MapImage(self.texture, self.width, self.height, self.tileWidth, self.tileHeight, self.radius) self.grid:setShape(MOAIGridSpace.HEX_SHAPE) self.grid:setLayer(self.layer) self.selectedImage = flower.SheetImage(self.texture) self.selectedImage:setTileSize(self.tileWidth, self.tileHeight) self.selectedImage:setLayer(self.layer) -- TODO: Fix these numbers self.selectedImage:setScl(self.height / self.tileHeight / 1.3, self.height / self.tileHeight / 1.3) self.selectedImage:setPiv(self.radius / 2, self.radius / 2) self.selectedImage:setColor(0.2, 0.2, 0.2, 1) self.selectedImage:setVisible(false) if type(self.map.tiles) == "table" then for i = 1,self.width do for j = 1,self.height do self.grid.grid:setTile(i, j, self.map.default_tile) end end for k, data in pairs(self.map.tiles) do for j, pos in ipairs(data) do self.grid.grid:setTile(pos[1], pos[2], k) end end elseif type(self.map.tiles) == "string" then -- Load file from stream local fileStream = MOAIFileStream.new() if not fileStream:open(self.map.tiles, MOAIFileStream.READ) then return false end self.grid.grid:streamTilesIn(fileStream) fileStream:close() self.spawnTiles = {} self.targetPosition = {} for i = 1,self.width do for j = 1,self.height do local tile = self.grid.grid:getTile(i, j) if tile == TILE_TYPES.TARGET then self.targetPosition[1], self.targetPosition[2] = i, j elseif tile == TILE_TYPES.SPAWN then table.insert(self.spawnTiles, {i, j}) end end end else return false end -- TODO: make this a bit more dynamic local function validTileCallback(tile) return tile == TILE_TYPES.ENEMY or tile == TILE_TYPES.TARGET or tile == TILE_TYPES.SPAWN end -- Find path in the map if self:isPathDynamic() then self.path = findPath(self:getMOAIGrid(), vector{self.targetPosition[1], self.targetPosition[2]}, validTileCallback) else self.path = self.map.paths[1] self.targetPosition = self.path[#self.path] end return true end function Map:isTileSelected() return self.tileSelected end -- TODO: need to center the selected tile function Map:selectTile(pos) local worldPos = self:gridToScreenSpace(pos, MOAIGridSpace.TILE_LEFT_TOP) self.selectedImage:setVisible(true) self.selectedImage:setIndex(self.grid:getTile(pos[1], pos[2])) self.selectedImage:setPos(worldPos[1], worldPos[2]) self.tileSelected = true end function Map:unselectTile() self.selectedImage:setVisible(false) self.tileSelected = false end function Map:randomStartingPosition() local startPosition = not self:isPathDynamic() and self.path[1] if not startPosition then local randomIndex = math.random(1, #self.spawnTiles) startPosition = self.spawnTiles[randomIndex] end return self:gridToScreenSpace(startPosition) end function Map:screenToGridSpace(x, y, layer) local prop = self:getGrid() x, y = layer:wndToWorld(x, y) x, y = prop:worldToModel(x, y) return vector{self:getMOAIGrid():locToCoord(x, y)} end function Map:gridToScreenSpace(pos, alignment) alignment = alignment or MOAIGridSpace.TILE_CENTER if type(pos) == "table" then return vector{self:getMOAIGrid():getTileLoc(pos[1], pos[2], alignment)} elseif type(pos) == "number" then return self:getMOAIGrid():getTileLoc(pos, 0, alignment) end end -- Returns true if the path was found using a pathfinder function Map:isPathDynamic() if self.map.paths then return false end return true end function Map:clearTile(pos) self:setTile(pos, TILE_TYPES.EMPTY) end function Map:setTile(pos, index) self:getGrid():setTile(pos[1], pos[2], index) end function Map:getTile(pos) return self:getGrid():getTile(pos[1], pos[2]) end function Map:getPath() return self.path end function Map:getWaves() return self.map.waves end -- TODO: remove these methods to return the grid function Map:getGrid() return self.grid end function Map:getMOAIGrid() return self:getGrid().grid end function Map:setLayer(layer) self.layer = layer self.grid:setLayer(self.layer) self.selectedImage:setLayer(self.layer) end function Map:resetTowers(towers) for i = 1,self.width do for j = 1,self.height do local pos = vector({i, j}) local tile = self:getTile(pos) if towers[Tower.serialize_pos(pos)] == nil then if tile ~= TILE_TYPES.EMPTY and tile ~= TILE_TYPES.ENEMY and tile ~= TILE_TYPES.VOID then self:setTile(pos, TILE_TYPES.EMPTY) end else self:setTile(pos, towers[Tower.serialize_pos(pos)].type.id) end end end end
Fixed placing towers in multiplayer.
Fixed placing towers in multiplayer.
Lua
mit
BryceMehring/Hexel
b18a98b3740896bec6e7e55b4a2bd4430aced0fb
spec/resty/openssl/bio_spec.lua
spec/resty/openssl/bio_spec.lua
local _M = require('resty.openssl.bio') describe('OpenSSL BIO', function() describe('.new', function() it('returns cdata', function() assert.equal('cdata', type(_M.new())) end) end) describe(':write', function() it('writes data to bio', function() local bio = _M.new() local str = 'foobar' assert(bio:write(str)) assert.equal(str, bio:read()) end) it('requires a string', function() local bio = _M.new() assert.has_error(function () bio:write() end, 'expected string') end) it('requires non empty string', function() local bio = _M.new() assert.has_error(function () bio:write('') end, 'expected value, got nil') end) end) end)
local _M = require('resty.openssl.bio') describe('OpenSSL BIO', function() describe('.new', function() it('returns cdata', function() assert.equal('cdata', type(_M.new())) end) end) describe(':write', function() it('writes data to bio', function() local bio = _M.new() local str = 'foobar' assert(bio:write(str)) assert.equal(str, bio:read()) end) it('requires a string', function() local bio = _M.new() assert.has_error(function () bio:write() end, 'expected string') end) it('requires non empty string', function() local bio = _M.new() assert.same(bio:write(""), 0) end) end) end)
[test] Fix ssl test due library change
[test] Fix ssl test due library change Due to the update on the image the ssl library return 0 instead of error. Signed-off-by: Eloy Coto <2a8acc28452926ceac4d9db555411743254cf5f9@gmail.com>
Lua
mit
3scale/apicast,3scale/apicast,3scale/apicast,3scale/docker-gateway,3scale/apicast,3scale/docker-gateway
21d78cc8910699791fda1828f1dffa8514364099
src/copas/copas.lua
src/copas/copas.lua
------------------------------------------------------------------------------- -- Copas - Coroutine Oriented Portable Asynchronous Services -- -- Offers a dispatcher and socket operations based on coroutines. -- Usage: -- copas.addserver(server, handler) -- copas.loop() -- copas.flush - flushes the writing buffer if necessary -- copas.receive - receives data from a socket -- copas.send - sends data through a buffered socket -- -- Authors: Andre Carregal and Javier Guerra -- Contributors: Diego Nehab, Mike Pall and David Burgess -- Copyright 2005 - Kepler Project (www.keplerproject.org) ------------------------------------------------------------------------------- require "socket" module "copas" -- Meta information is public even begining with an "_" _COPYRIGHT = "Copyright (C) 2004-2005 Kepler Project" _DESCRIPTION = "Coroutine Oriented Portable Asynchronous Services" _NAME = "Copas" _VERSION = "1.0 Beta" ------------------------------------------------------------------------------- -- Simple set implementation based on LuaSocket's tinyirc.lua example ------------------------------------------------------------------------------- local function _newset() local reverse = {} local set = {} setmetatable(set, { __index = { insert = function(set, value) table.insert(set, value) reverse[value] = table.getn(set) end, remove = function(set, value) if not reverse[value] then return end local last = table.getn(set) if last > 1 then -- replaces the removed value with the last one local index = reverse[value] local newvalue = set[last] set[index] = newvalue reverse[newvalue] = index end table.setn(set, last - 1) -- cleans up the garbage reverse[value] = nil set[last] = nil end, }}) return set end local _servers = _newset() local _reading = _newset() -- sockets currently being read local _writing = _newset() -- sockets currently being written ------------------------------------------------------------------------------- -- Coroutine based socket I/O functions. -- -- Writing operations are buffered to allow a nicer distribution of yields ------------------------------------------------------------------------------- local _buffer = {} -- reads a pattern from a client and yields to the reading set on timeouts function receive(client, pattern) local s, err, part pattern = pattern or "*l" repeat s, err, part = client:receive(pattern, part) -- print ("copas.receive", client, pattern, s, err, part) if s or err ~= "timeout" then return s, err end coroutine.yield(client, _reading) until false end -- sends data to a client. The operation is buffered and -- yields to the writing set on timeouts function send(client, data) if _buffer[client] == nil then _buffer[client] = "" end if data then _buffer[client] = _buffer[client]..data end if (math.random(100) > 90) or string.len(_buffer[client]) > 2048 then flush(client) end end -- sends a client buffer yielding to writing on timeouts local function _sendBuffer(client) local s, err local from = 1 local sent = 0 repeat from = from + sent s, err, sent = client:send(_buffer[client], from) if s or err ~= "timeout" then return s, err end coroutine.yield(client, _writing) until false end -- flushes a client write buffer function flush(client) if _buffer[client] == nil then _buffer[client] = "" end _sendBuffer(client) _buffer[client] = nil end -- wraps a socket to use Copas methods local _skt_mt = {__index = { send = function (self, data) return send (self.socket, data) end, receive = function (self, pattern) return receive (self.socket, pattern) end, flush = function (self) return flush (self.socket) end, }} function skt_wrap (skt) return setmetatable ({socket = skt}, _skt_mt) end ------------------------------------------------------------------------------- -- Thread handling ------------------------------------------------------------------------------- local _threads = {} -- maps sockets and coroutines -- accepts a connection on socket input local function _accept(input, handler) local client = input:accept() if client then client:settimeout(0) _threads[client] = coroutine.create(handler) _reading:insert(client) end return client end -- handle threads on a queue local function _tick (skt) local co = _threads[skt] -- queue:remove (skt) local status, res, new_q = coroutine.resume(co, skt) if not status then error(res) end if not res then -- remove the coroutine from the running threads _threads[skt] = nil flush(skt) skt:close() elseif new_q then new_q:insert (res) else -- still missing error handling here end end ------------------------------------------------------------------------------- -- Adds a server/handler pair to Copas dispatcher ------------------------------------------------------------------------------- function addserver(server, handler, timeout) server:settimeout(timeout or 0.1) _servers[server] = handler _reading:insert(server) end ------------------------------------------------------------------------------- -- tasks registering ------------------------------------------------------------------------------- local _tasks = {} function addtask (tsk) -- lets tasks call the default _tick() tsk.def_tick = _tick _tasks [tsk] = true end local function tasks () return next, _tasks end ------------------------------------------------------------------------------- -- main tasks: manage readable and writable socket sets ------------------------------------------------------------------------------- -- a task to check ready to read events local _readable_t = {} function _readable_t:events () local i = 0 return function () i = i+1 return self._evs [i] end end function _readable_t:tick (input) local handler = _servers[input] if handler then input = _accept(input, handler) end _reading:remove (input) self.def_tick (input) end addtask (_readable_t) -- a task to check ready to write events local _writable_t = {} function _writable_t:events () local i = 0 return function () i = i+1 return self._evs [i] end end function _writable_t:tick (output) _writing:remove (output) self.def_tick (output) end addtask (_writable_t) local function _select () local err _readable_t._evs, _writable_t._evs, err = socket.select(_reading, _writing) return err end ------------------------------------------------------------------------------- -- Dispatcher loop. -- Listen to client requests and handles them ------------------------------------------------------------------------------- function loop() local err while true do err = _select () if err then error(err) end for tsk in tasks() do for ev in tsk:events () do tsk:tick (ev) end end end end
------------------------------------------------------------------------------- -- Copas - Coroutine Oriented Portable Asynchronous Services -- -- Offers a dispatcher and socket operations based on coroutines. -- Usage: -- copas.addserver(server, handler) -- copas.loop() -- copas.flush - flushes the writing buffer if necessary -- copas.receive - receives data from a socket -- copas.send - sends data through a buffered socket -- -- Authors: Andre Carregal and Javier Guerra -- Contributors: Diego Nehab, Mike Pall and David Burgess -- Copyright 2005 - Kepler Project (www.keplerproject.org) ------------------------------------------------------------------------------- require "socket" module "copas" -- Meta information is public even begining with an "_" _COPYRIGHT = "Copyright (C) 2004-2005 Kepler Project" _DESCRIPTION = "Coroutine Oriented Portable Asynchronous Services" _NAME = "Copas" _VERSION = "1.0 Beta" ------------------------------------------------------------------------------- -- Simple set implementation based on LuaSocket's tinyirc.lua example ------------------------------------------------------------------------------- local function _newset() local reverse = {} local set = {} setmetatable(set, { __index = { insert = function(set, value) table.insert(set, value) reverse[value] = table.getn(set) end, remove = function(set, value) if not reverse[value] then return end local last = table.getn(set) if last > 1 then -- replaces the removed value with the last one local index = reverse[value] local newvalue = set[last] set[index] = newvalue reverse[newvalue] = index end table.setn(set, last - 1) -- cleans up the garbage reverse[value] = nil set[last] = nil end, }}) return set end local _servers = _newset() local _reading = _newset() -- sockets currently being read local _writing = _newset() -- sockets currently being written ------------------------------------------------------------------------------- -- Coroutine based socket I/O functions. -- -- Writing operations are buffered to allow a nicer distribution of yields ------------------------------------------------------------------------------- local _buffer = {} -- reads a pattern from a client and yields to the reading set on timeouts function receive(client, pattern) local s, err, part pattern = pattern or "*l" repeat s, err, part = client:receive(pattern, part) if s or err ~= "timeout" then return s, err end coroutine.yield(client, _reading) until false end -- sends data to a client. The operation is buffered and -- yields to the writing set on timeouts function send(client, data) if _buffer[client] == nil then _buffer[client] = "" end if data then _buffer[client] = _buffer[client]..data end if (math.random(100) > 90) or string.len(_buffer[client]) > 2048 then flush(client) end end -- sends a client buffer yielding to writing on timeouts local function _sendBuffer(client) local s, err local from = 1 local sent = 0 repeat from = from + sent s, err, sent = client:send(_buffer[client], from) if s or err ~= "timeout" then return s, err end coroutine.yield(client, _writing) until false end -- flushes a client write buffer function flush(client) if _buffer[client] == nil then _buffer[client] = "" end _sendBuffer(client) _buffer[client] = nil end -- wraps a socket to use Copas methods local _skt_mt = {__index = { send = function (self, data) return send (self.socket, data) end, receive = function (self, pattern) return receive (self.socket, pattern) end, flush = function (self) return flush (self.socket) end, }} function wrap (skt) return setmetatable ({socket = skt}, _skt_mt) end ------------------------------------------------------------------------------- -- Thread handling ------------------------------------------------------------------------------- local _threads = {} -- maps sockets and coroutines -- accepts a connection on socket input local function _accept(input, handler) local client = input:accept() if client then client:settimeout(0) _threads[client] = coroutine.create(handler) _reading:insert(client) end return client end -- handle threads on a queue local function _tick (skt) local co = _threads[skt] local status, res, new_q = coroutine.resume(co, skt) if not status then error(res) end if not res then -- remove the coroutine from the running threads _threads[skt] = nil flush(skt) skt:close() elseif new_q then new_q:insert (res) else -- still missing error handling here end end ------------------------------------------------------------------------------- -- Adds a server/handler pair to Copas dispatcher ------------------------------------------------------------------------------- function addserver(server, handler, timeout) server:settimeout(timeout or 0.1) _servers[server] = handler _reading:insert(server) end ------------------------------------------------------------------------------- -- tasks registering ------------------------------------------------------------------------------- local _tasks = {} function addtask (tsk) -- lets tasks call the default _tick() tsk.def_tick = _tick _tasks [tsk] = true end local function tasks () return next, _tasks end ------------------------------------------------------------------------------- -- main tasks: manage readable and writable socket sets ------------------------------------------------------------------------------- -- a task to check ready to read events local _readable_t = {} function _readable_t:events () local i = 0 return function () i = i+1 return self._evs [i] end end function _readable_t:tick (input) local handler = _servers[input] if handler then input = _accept(input, handler) end _reading:remove (input) self.def_tick (input) end addtask (_readable_t) -- a task to check ready to write events local _writable_t = {} function _writable_t:events () local i = 0 return function () i = i+1 return self._evs [i] end end function _writable_t:tick (output) _writing:remove (output) self.def_tick (output) end addtask (_writable_t) local function _select () local err _readable_t._evs, _writable_t._evs, err = socket.select(_reading, _writing) return err end ------------------------------------------------------------------------------- -- Dispatcher loop. -- Listen to client requests and handles them ------------------------------------------------------------------------------- function loop() local err while true do err = _select () if err then error(err) end for tsk in tasks() do for ev in tsk:events () do tsk:tick (ev) end end end end
fixed function naming
fixed function naming
Lua
mit
keplerproject/copas
b59b4ade064b796c0798ab968b73bb8b207ddd7c
Interface/AddOns/RayUI/libs/cargBags/mixins-add/rayui.scaffold.lua
Interface/AddOns/RayUI/libs/cargBags/mixins-add/rayui.scaffold.lua
local addon, ns = ... local cargBags = ns.cargBags local function noop() end local function ItemButton_Scaffold(self) self:SetSize(RayUI[1].db.Bags.bagSize, RayUI[1].db.Bags.bagSize) local name = self:GetName() self.Icon = _G[name.."IconTexture"] self.Count = _G[name.."Count"] self.Cooldown = _G[name.."Cooldown"] self.Quest = _G[name.."IconQuestTexture"] self.Border = _G[name.."NormalTexture"] self.Icon:SetTexCoord(.08, .92, .08, .92) if not self.itemLevel and RayUI[1].db.Bags.itemLevel then self.itemLevel = self:CreateFontString(nil, "OVERLAY") self.itemLevel:SetPoint("TOPRIGHT", 1, -2) self.itemLevel:FontTemplate(nil, nil, "OUTLINE") end if not self.border then local border = CreateFrame("Frame", nil, self) border:SetAllPoints() border:SetFrameLevel(self:GetFrameLevel()+1) self.border = border self.border:CreateBorder() RayUI[1]:GetModule("Skins"):CreateBackdropTexture(self, 0.6) end end local function IsItemEligibleForItemLevelDisplay(classID, subClassID, equipLoc, rarity) if ((classID == 3 and subClassID == 11) --Artifact Relics or (equipLoc ~= nil and equipLoc ~= "" and equipLoc ~= "INVTYPE_BAG" and equipLoc ~= "INVTYPE_QUIVER" and equipLoc ~= "INVTYPE_TABARD")) and (rarity and rarity > 1) then return true end return false end local function ItemButton_Update(self, item) self.Icon:SetTexture(item.texture or self.bgTex) if(item.count and item.count > 1) then self.Count:SetText(item.count >= 1e3 and "*" or item.count) self.Count:Show() else self.Count:Hide() end self.count = item.count -- Thank you Blizz for not using local variables >.> (BankFrame.lua @ 234 ) -- self.Quest:Hide() self:UpdateCooldown(item) self:UpdateLock(item) if (item.link) then if RayUI[1]:IsItemUnusable(item.link) then SetItemButtonTextureVertexColor(self, RED_FONT_COLOR.r, RED_FONT_COLOR.g, RED_FONT_COLOR.b) else SetItemButtonTextureVertexColor(self, 1, 1, 1) end if item.questID and not item.questActive then self.Icon:SetInside() self:StyleButton() self:SetBackdropColor(0, 0, 0) self.border:SetBackdropBorderColor(1.0, 0.2, 0.2) elseif item.questID or item.isQuestItem then self.Icon:SetInside() self:StyleButton() self:SetBackdropColor(0, 0, 0) self.border:SetBackdropBorderColor(1.0, 0.2, 0.2) elseif item.rarity and item.rarity > 1 then local r, g, b = GetItemQualityColor(item.rarity) self.Icon:SetInside() self:StyleButton() self:SetBackdropColor(0, 0, 0) self.border:SetBackdropBorderColor(r, g, b) else self.Icon:SetAllPoints() self:StyleButton(true) self:SetBackdropColor(0, 0, 0, 0, 0) self.border:SetBackdropBorderColor(unpack(RayUI[1]["media"].bordercolor)) end else self.Icon:SetAllPoints() self:StyleButton(true) self:SetBackdropColor(0, 0, 0, 0) self.border:SetBackdropBorderColor(unpack(RayUI[1]["media"].bordercolor)) end if (self.JunkIcon) then if (item.rarity) and (item.rarity == LE_ITEM_QUALITY_POOR and not item.noValue) then self.JunkIcon:Show() else self.JunkIcon:Hide() end end if (self.UpgradeIcon) then local itemIsUpgrade = IsContainerItemAnUpgrade(item.bagID, item.slotID) if itemIsUpgrade == nil then self.UpgradeIcon:SetShown(false) else self.UpgradeIcon:SetShown(itemIsUpgrade) end end if(C_NewItems.IsNewItem(item.bagID, item.slotID)) then ActionButton_ShowOverlayGlow(self) else ActionButton_HideOverlayGlow(self) end if RayUI[1].db.Bags.itemLevel then self.itemLevel:SetText("") local clink = GetContainerItemLink(item.bagID, item.slotID) if (clink) then local itemEquipLoc, _, _, itemClassID, itemSubClassID = select(9, GetItemInfo(clink)) local iLvl = GetDetailedItemLevelInfo(clink) local r, g, b = GetItemQualityColor(item.rarity) if iLvl and IsItemEligibleForItemLevelDisplay(itemClassID, itemSubClassID, itemEquipLoc, item.rarity) then if iLvl >= 1 then self.itemLevel:SetText(iLvl) self.itemLevel:SetTextColor(r, g, b) end end end end if(self.OnUpdate) then self:OnUpdate(item) end end local function ItemButton_UpdateCooldown(self, item) if(item.cdEnable == 1 and item.cdStart and item.cdStart > 0) then self.Cooldown:SetCooldown(item.cdStart, item.cdFinish) self.Cooldown:Show() else self.Cooldown:Hide() end if(self.OnUpdateCooldown) then self:OnUpdateCooldown(item) end end local function ItemButton_UpdateLock(self, item) self.Icon:SetDesaturated(item.locked) if(self.OnUpdateLock) then self:OnUpdateLock(item) end end local function ItemButton_OnEnter(self) ActionButton_HideOverlayGlow(self) end cargBags:RegisterScaffold("RayUI", function(self) self.bgTex = nil --! @property bgTex <string> Texture used as a background if no item is in the slot self.CreateFrame = ItemButton_CreateFrame self.Scaffold = ItemButton_Scaffold self.Update = ItemButton_Update self.UpdateCooldown = ItemButton_UpdateCooldown self.UpdateLock = ItemButton_UpdateLock self.UpdateQuest = ItemButton_Update self.OnEnter = ItemButton_OnEnter self.OnLeave = ItemButton_OnLeave end)
local addon, ns = ... local cargBags = ns.cargBags local function noop() end local function ItemButton_Scaffold(self) self:SetSize(RayUI[1].db.Bags.bagSize, RayUI[1].db.Bags.bagSize) local name = self:GetName() self.Icon = _G[name.."IconTexture"] self.Count = _G[name.."Count"] self.Cooldown = _G[name.."Cooldown"] self.Quest = _G[name.."IconQuestTexture"] self.Border = _G[name.."NormalTexture"] self.Icon:SetTexCoord(.08, .92, .08, .92) if not self.itemLevel and RayUI[1].db.Bags.itemLevel then self.itemLevel = self:CreateFontString(nil, "OVERLAY") self.itemLevel:SetPoint("TOPRIGHT", 1, -2) self.itemLevel:FontTemplate(nil, nil, "OUTLINE") end if not self.border then local border = CreateFrame("Frame", nil, self) border:SetAllPoints() border:SetFrameLevel(self:GetFrameLevel()+1) self.border = border self.border:CreateBorder() RayUI[1]:GetModule("Skins"):CreateBackdropTexture(self, 0.6) end end local function IsItemEligibleForItemLevelDisplay(classID, subClassID, equipLoc, rarity) if ((classID == 3 and subClassID == 11) --Artifact Relics or (equipLoc ~= nil and equipLoc ~= "" and equipLoc ~= "INVTYPE_BAG" and equipLoc ~= "INVTYPE_QUIVER" and equipLoc ~= "INVTYPE_TABARD")) and (rarity and rarity > 1) then return true end return false end local function ItemButton_Update(self, item) self.Icon:SetTexture(item.texture or self.bgTex) if(item.count and item.count > 1) then self.Count:SetText(item.count >= 1e3 and "*" or item.count) self.Count:Show() else self.Count:Hide() end self.count = item.count -- Thank you Blizz for not using local variables >.> (BankFrame.lua @ 234 ) -- self.Quest:Hide() self:UpdateCooldown(item) self:UpdateLock(item) if (item.link) then if RayUI[1]:IsItemUnusable(item.link) then SetItemButtonTextureVertexColor(self, RED_FONT_COLOR.r, RED_FONT_COLOR.g, RED_FONT_COLOR.b) else SetItemButtonTextureVertexColor(self, 1, 1, 1) end if item.questID and not item.questActive then self.Icon:SetInside() self:StyleButton() self:SetBackdropColor(0, 0, 0) self.border:SetBackdropBorderColor(1.0, 0.2, 0.2) elseif item.questID or item.isQuestItem then self.Icon:SetInside() self:StyleButton() self:SetBackdropColor(0, 0, 0) self.border:SetBackdropBorderColor(1.0, 0.2, 0.2) elseif item.rarity and item.rarity > 1 then local r, g, b = GetItemQualityColor(item.rarity) self.Icon:SetInside() self:StyleButton() self:SetBackdropColor(0, 0, 0) self.border:SetBackdropBorderColor(r, g, b) else self.Icon:SetAllPoints() self:StyleButton(true) self:SetBackdropColor(0, 0, 0, 0, 0) self.border:SetBackdropBorderColor(unpack(RayUI[1]["media"].bordercolor)) end else self.Icon:SetAllPoints() self:StyleButton(true) self:SetBackdropColor(0, 0, 0, 0) self.border:SetBackdropBorderColor(unpack(RayUI[1]["media"].bordercolor)) end if (self.JunkIcon) then if (item.rarity) and (item.rarity == LE_ITEM_QUALITY_POOR and not item.noValue) then self.JunkIcon:Show() else self.JunkIcon:Hide() end end if (self.UpgradeIcon) then local itemIsUpgrade = IsContainerItemAnUpgrade(item.bagID, item.slotID) if itemIsUpgrade == nil then self.UpgradeIcon:SetShown(false) else self.UpgradeIcon:SetShown(itemIsUpgrade) end end if(C_NewItems.IsNewItem(item.bagID, item.slotID)) then ActionButton_ShowOverlayGlow(self) else ActionButton_HideOverlayGlow(self) end if RayUI[1].db.Bags.itemLevel then self.itemLevel:SetText("") local clink = GetContainerItemLink(item.bagID, item.slotID) if (clink) then local itemEquipLoc, _, _, itemClassID, itemSubClassID = select(9, GetItemInfo(clink)) local iLvl = GetDetailedItemLevelInfo(clink) local r, g, b if(item.rarity) then r, g, b = GetItemQualityColor(item.rarity); end if iLvl and IsItemEligibleForItemLevelDisplay(itemClassID, itemSubClassID, itemEquipLoc, item.rarity) then if iLvl >= 1 then self.itemLevel:SetText(iLvl) self.itemLevel:SetTextColor(r, g, b) end end end end if(self.OnUpdate) then self:OnUpdate(item) end end local function ItemButton_UpdateCooldown(self, item) if(item.cdEnable == 1 and item.cdStart and item.cdStart > 0) then self.Cooldown:SetCooldown(item.cdStart, item.cdFinish) self.Cooldown:Show() else self.Cooldown:Hide() end if(self.OnUpdateCooldown) then self:OnUpdateCooldown(item) end end local function ItemButton_UpdateLock(self, item) self.Icon:SetDesaturated(item.locked) if(self.OnUpdateLock) then self:OnUpdateLock(item) end end local function ItemButton_OnEnter(self) ActionButton_HideOverlayGlow(self) end cargBags:RegisterScaffold("RayUI", function(self) self.bgTex = nil --! @property bgTex <string> Texture used as a background if no item is in the slot self.CreateFrame = ItemButton_CreateFrame self.Scaffold = ItemButton_Scaffold self.Update = ItemButton_Update self.UpdateCooldown = ItemButton_UpdateCooldown self.UpdateLock = ItemButton_UpdateLock self.UpdateQuest = ItemButton_Update self.OnEnter = ItemButton_OnEnter self.OnLeave = ItemButton_OnLeave end)
fix #8
fix #8
Lua
mit
fgprodigal/RayUI
d8ad70581787c01857bde16180689d3f9e29767a
src/base/detoken.lua
src/base/detoken.lua
-- -- detoken.lua -- -- Expands tokens. -- -- Copyright (c) 2011-2014 Jason Perkins and the Premake project -- premake.detoken = {} local p = premake local detoken = p.detoken -- -- Expand tokens in a value. -- -- @param value -- The value containing the tokens to be expanded. -- @param environ -- An execution environment for any token expansion. This is a list of -- key-value pairs that will be inserted as global variables into the -- token expansion runtime environment. -- @param field -- The definition of the field which stores the value. -- @param basedir -- If provided, path tokens encountered in non-path fields (where -- field.paths is set to false) will be made relative to this location. -- @return -- The value with any contained tokens expanded. -- function detoken.expand(value, environ, field, basedir) field = field or {} -- fetch the path variable from the action, if needed local varMap = {} if field.pathVars then local action = p.action.current() if action then varMap = action.pathVars or {} end end -- enable access to the global environment setmetatable(environ, {__index = _G}) function expandtoken(token, e) -- convert the token into a function to execute local func, err = loadstring("return " .. token) if not func then return nil, err end -- give the function access to the project objects setfenv(func, e) -- run it and get the result local result = func() or "" -- If the result is an absolute path, and it is being inserted into -- a NON-path value, I need to make it relative to the project that -- will contain it. Otherwise I ended up with an absolute path in -- the generated project, and it can no longer be moved around. local isAbs = path.isabsolute(result) if isAbs and not field.paths and basedir then result = path.getrelative(basedir, result) end -- If this token is in my path variable mapping table, replace the -- value with the one from the map. This needs to go here because -- I don't want to make the result relative, but I don't want the -- absolute path handling below. if varMap[token] then result = varMap[token] if type(result) == "function" then result = result(e) end isAbs = path.isabsolute(result) end -- If the result is an absolute path, and it is being inserted into -- a path value, place a special marker at the start of it. After -- all results have been processed, I can look for these markers to -- find the last absolute path expanded. -- -- Example: the value "/home/user/myprj/%{cfg.objdir}" expands to: -- "/home/user/myprj//home/user/myprj/obj/Debug". -- -- By inserting a marker this becomes: -- "/home/user/myprj/[\0]/home/user/myprj/obj/Debug". -- -- I can now trim everything before the marker to get the right -- result, which should always be the last absolute path specified: -- "/home/user/myprj/obj/Debug" if isAbs and field.paths then result = "\0" .. result end return result end function expandvalue(value, e) if type(value) ~= "string" then return value end local count repeat value, count = value:gsub("%%{(.-)}", function(token) local result, err = expandtoken(token:gsub("\\", "\\\\"), e) if not result then error(err, 0) end return result end) until count == 0 -- if a path, look for a split out embedded absolute paths if field.paths then local i, j repeat i, j = value:find("\0") if i then value = value:sub(i + 1) end until not i end return value end function recurse(value, e) if type(value) == "table" then local res_table = {} for k, v in pairs(value) do if tonumber(k) ~= nil then res_table[k] = recurse(v, e) else local nk = recurse(k, e); res_table[nk] = recurse(v, e) end end return res_table else return expandvalue(value, e) end end return recurse(value, environ) end
-- -- detoken.lua -- -- Expands tokens. -- -- Copyright (c) 2011-2014 Jason Perkins and the Premake project -- premake.detoken = {} local p = premake local detoken = p.detoken -- -- Expand tokens in a value. -- -- @param value -- The value containing the tokens to be expanded. -- @param environ -- An execution environment for any token expansion. This is a list of -- key-value pairs that will be inserted as global variables into the -- token expansion runtime environment. -- @param field -- The definition of the field which stores the value. -- @param basedir -- If provided, path tokens encountered in non-path fields (where -- field.paths is set to false) will be made relative to this location. -- @return -- The value with any contained tokens expanded. -- function detoken.expand(value, environ, field, basedir) field = field or {} -- fetch the path variable from the action, if needed local varMap = {} if field.pathVars then local action = p.action.current() if action then varMap = action.pathVars or {} end end -- enable access to the global environment setmetatable(environ, {__index = _G}) function expandtoken(token, e) -- convert the token into a function to execute local func, err = loadstring("return " .. token) if not func then print("load error:", err) return nil, err end -- give the function access to the project objects setfenv(func, e) -- run it and get the result local success, result = pcall(func) if not success then err = result result = nil else err = nil end -- If the result is an absolute path, and it is being inserted into -- a NON-path value, I need to make it relative to the project that -- will contain it. Otherwise I ended up with an absolute path in -- the generated project, and it can no longer be moved around. local isAbs = false if result ~= nil then isAbs = path.isabsolute(result) if isAbs and not field.paths and basedir then result = path.getrelative(basedir, result) end end -- If this token is in my path variable mapping table, replace the -- value with the one from the map. This needs to go here because -- I don't want to make the result relative, but I don't want the -- absolute path handling below. if varMap[token] then err = nil result = varMap[token] if type(result) == "function" then success, result = pcall(result, e) if not success then return nil, result end end isAbs = path.isabsolute(result) end -- If the result is an absolute path, and it is being inserted into -- a path value, place a special marker at the start of it. After -- all results have been processed, I can look for these markers to -- find the last absolute path expanded. -- -- Example: the value "/home/user/myprj/%{cfg.objdir}" expands to: -- "/home/user/myprj//home/user/myprj/obj/Debug". -- -- By inserting a marker this becomes: -- "/home/user/myprj/[\0]/home/user/myprj/obj/Debug". -- -- I can now trim everything before the marker to get the right -- result, which should always be the last absolute path specified: -- "/home/user/myprj/obj/Debug" if result ~= nil and isAbs and field.paths then result = "\0" .. result end return result, err end function expandvalue(value, e) if type(value) ~= "string" then return value end local count repeat value, count = value:gsub("%%{(.-)}", function(token) local result, err = expandtoken(token:gsub("\\", "\\\\"), e) if err then error(err .. " in token: " .. token, 0) end if not result then error("Token returned nil, it may not exist: " .. token, 0) end return result end) until count == 0 -- if a path, look for a split out embedded absolute paths if field.paths then local i, j repeat i, j = value:find("\0") if i then value = value:sub(i + 1) end until not i end return value end function recurse(value, e) if type(value) == "table" then local res_table = {} for k, v in pairs(value) do if tonumber(k) ~= nil then res_table[k] = recurse(v, e) else local nk = recurse(k, e); res_table[nk] = recurse(v, e) end end return res_table else return expandvalue(value, e) end end return recurse(value, environ) end
fix detoken.
fix detoken.
Lua
bsd-3-clause
CodeAnxiety/premake-core,soundsrc/premake-core,Zefiros-Software/premake-core,noresources/premake-core,noresources/premake-core,noresources/premake-core,aleksijuvani/premake-core,Zefiros-Software/premake-core,starkos/premake-core,mandersan/premake-core,noresources/premake-core,Blizzard/premake-core,tvandijck/premake-core,TurkeyMan/premake-core,martin-traverse/premake-core,CodeAnxiety/premake-core,noresources/premake-core,xriss/premake-core,noresources/premake-core,premake/premake-core,sleepingwit/premake-core,resetnow/premake-core,Blizzard/premake-core,soundsrc/premake-core,jstewart-amd/premake-core,TurkeyMan/premake-core,LORgames/premake-core,premake/premake-core,xriss/premake-core,starkos/premake-core,Blizzard/premake-core,jstewart-amd/premake-core,mandersan/premake-core,starkos/premake-core,aleksijuvani/premake-core,Blizzard/premake-core,lizh06/premake-core,bravnsgaard/premake-core,sleepingwit/premake-core,Blizzard/premake-core,mendsley/premake-core,mendsley/premake-core,mendsley/premake-core,CodeAnxiety/premake-core,soundsrc/premake-core,tvandijck/premake-core,martin-traverse/premake-core,soundsrc/premake-core,dcourtois/premake-core,premake/premake-core,TurkeyMan/premake-core,starkos/premake-core,xriss/premake-core,lizh06/premake-core,LORgames/premake-core,resetnow/premake-core,resetnow/premake-core,xriss/premake-core,Zefiros-Software/premake-core,LORgames/premake-core,jstewart-amd/premake-core,sleepingwit/premake-core,dcourtois/premake-core,Zefiros-Software/premake-core,tvandijck/premake-core,LORgames/premake-core,martin-traverse/premake-core,soundsrc/premake-core,dcourtois/premake-core,CodeAnxiety/premake-core,CodeAnxiety/premake-core,mandersan/premake-core,LORgames/premake-core,bravnsgaard/premake-core,bravnsgaard/premake-core,premake/premake-core,martin-traverse/premake-core,lizh06/premake-core,resetnow/premake-core,Blizzard/premake-core,premake/premake-core,jstewart-amd/premake-core,bravnsgaard/premake-core,mandersan/premake-core,aleksijuvani/premake-core,TurkeyMan/premake-core,jstewart-amd/premake-core,starkos/premake-core,sleepingwit/premake-core,xriss/premake-core,tvandijck/premake-core,dcourtois/premake-core,mendsley/premake-core,bravnsgaard/premake-core,starkos/premake-core,tvandijck/premake-core,dcourtois/premake-core,Zefiros-Software/premake-core,resetnow/premake-core,mendsley/premake-core,dcourtois/premake-core,starkos/premake-core,aleksijuvani/premake-core,mandersan/premake-core,noresources/premake-core,TurkeyMan/premake-core,premake/premake-core,dcourtois/premake-core,aleksijuvani/premake-core,premake/premake-core,sleepingwit/premake-core,lizh06/premake-core
9ba69b8674d756940b85156ff80e09169a44002b
MMOCoreORB/bin/scripts/mobile/spawn/tatooine_starter_small_town.lua
MMOCoreORB/bin/scripts/mobile/spawn/tatooine_starter_small_town.lua
tatooine_starter_creatures = { wanderRadius = 10, commandLevel = 0, type = LAIR, maxSpawnLimit = 256, lairSpawns = { { lairTemplateName = "tatooine_kreetle_lair_neutral_small", spawnLimit = -1, minDifficulty = 2, maxDifficulty = 4, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_rockmite_swarm_neutral_none", spawnLimit = -1, minDifficulty = 2, maxDifficulty = 4, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_womprat_lair_neutral_small", spawnLimit = -1, minDifficulty = 2, maxDifficulty = 4, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_evil_settlement_neutral_medium_theater", spawnLimit = -1, minDifficulty = 2, maxDifficulty = 5, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_moisture_settler_neutral_medium_theater", spawnLimit = -1, minDifficulty = 3, maxDifficulty = 5, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_kreetle_over_swarming_neutral_medium_boss_02", spawnLimit = -1, minDifficulty = 4, maxDifficulty = 6, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_gorg_herd_neutral_none", spawnLimit = -1, minDifficulty = 4, maxDifficulty = 6, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_eopie_lair_neutral_small", spawnLimit = -1, minDifficulty = 5, maxDifficulty = 7, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_sevorrt_lair_neutral_medium", spawnLimit = -1, minDifficulty = 5, maxDifficulty = 7, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_gorg_glutton_neutral_none", spawnLimit = -1, minDifficulty = 5, maxDifficulty = 7, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_diseased_bocatt_lair_neutral_medium", spawnLimit = -1, minDifficulty = 5, maxDifficulty = 8, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_cu_pa_lair_neutral_medium", spawnLimit = -1, minDifficulty = 7, maxDifficulty = 10, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_alkhara_bandit_patrol_neutral_none", spawnLimit = -1, minDifficulty = 8, maxDifficulty = 11, numberToSpawn = 0, weighting = 15, size = 25 } } } addLairGroup("tatooine_starter_creatures", tatooine_starter_creatures);
tatooine_starter_small_town = { wanderRadius = 10, commandLevel = 0, type = LAIR, maxSpawnLimit = 256, lairSpawns = { { lairTemplateName = "tatooine_kreetle_lair_neutral_small", spawnLimit = -1, minDifficulty = 2, maxDifficulty = 4, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_rockmite_swarm_neutral_none", spawnLimit = -1, minDifficulty = 2, maxDifficulty = 4, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_womprat_lair_neutral_small", spawnLimit = -1, minDifficulty = 2, maxDifficulty = 4, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_evil_settlement_neutral_medium_theater", spawnLimit = -1, minDifficulty = 2, maxDifficulty = 5, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_moisture_settler_neutral_medium_theater", spawnLimit = -1, minDifficulty = 3, maxDifficulty = 5, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_kreetle_over_swarming_neutral_medium_boss_02", spawnLimit = -1, minDifficulty = 4, maxDifficulty = 6, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_gorg_herd_neutral_none", spawnLimit = -1, minDifficulty = 4, maxDifficulty = 6, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_eopie_lair_neutral_small", spawnLimit = -1, minDifficulty = 5, maxDifficulty = 7, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_sevorrt_lair_neutral_medium", spawnLimit = -1, minDifficulty = 5, maxDifficulty = 7, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_gorg_glutton_neutral_none", spawnLimit = -1, minDifficulty = 5, maxDifficulty = 7, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_diseased_bocatt_lair_neutral_medium", spawnLimit = -1, minDifficulty = 5, maxDifficulty = 8, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_cu_pa_lair_neutral_medium", spawnLimit = -1, minDifficulty = 7, maxDifficulty = 10, numberToSpawn = 0, weighting = 15, size = 25 }, { lairTemplateName = "tatooine_alkhara_bandit_patrol_neutral_none", spawnLimit = -1, minDifficulty = 8, maxDifficulty = 11, numberToSpawn = 0, weighting = 15, size = 25 } } } addLairGroup("tatooine_starter_small_town", tatooine_starter_small_town);
[Fixed] SpawnGroup error
[Fixed] SpawnGroup error Change-Id: I36f9e22819fa36944d7226d0a683addc19f8788a
Lua
agpl-3.0
Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo
e60d5106c7ba8b66fcb34656f36f222776363fd3
src/httpd_req.lua
src/httpd_req.lua
local module = ... local httpdRequestHandler = { method = nil, query = { }, path = nil, contentType = nil, body = nil } local function httpdRequest(data) local _, _, method, path, query = string.find(data, '([A-Z]+) (.+)?(.+) HTTP') if method == nil then _, _, method, path = string.find(data, '([A-Z]+) (.+) HTTP') end if query ~= nil then query = string.gsub(query, '%%(%x%x)', function(x) string.char(tonumber(x, 16)) end) for k, v in string.gmatch(query, '([^&]+)=([^&]*)&*') do httpdRequestHandler.query[k] = v end end httpdRequestHandler.method = method httpdRequestHandler.path = path httpdRequestHandler.contentType = string.match(data, "Content%-Type: ([%w/-]+)") httpdRequestHandler.body = string.sub(data, string.find(data, "\r\n\r\n", 1, true), #data) if httpdRequestHandler.contentType == "application/json" then httpdRequestHandler.body = sjson.decode(httpdRequestHandler.body) end return httpdRequestHandler end return function(data) package.loaded[module] = nil module = nil return httpdRequest(data) end
local module = ... local httpdRequestHandler = { method = nil, query = { }, path = nil, contentType = nil, body = nil } local function httpdRequest(data) local _, _, method, path, query = string.find(data, '([A-Z]+) (.+)?(.+) HTTP') if method == nil then _, _, method, path = string.find(data, '([A-Z]+) (.+) HTTP') end if query ~= nil then query = string.gsub(query, '%%(%x%x)', function(x) string.char(tonumber(x, 16)) end) for k, v in string.gmatch(query, '([^&]+)=([^&]*)&*') do httpdRequestHandler.query[k] = v end end httpdRequestHandler.method = method httpdRequestHandler.path = path httpdRequestHandler.contentType = string.match(data, "Content%-Type: ([%w/-]+)") payload = string.find(data, "\r\n\r\n", 1, true) if payload ~= nil then httpdRequestHandler.body = string.sub(data, payload, #data) end if httpdRequestHandler.contentType == "application/json" then httpdRequestHandler.body = sjson.decode(httpdRequestHandler.body) end return httpdRequestHandler end return function(data) package.loaded[module] = nil module = nil return httpdRequest(data) end
Fix to handle nil payload in request data
Fix to handle nil payload in request data Error below occurs when a rouge request is received from an unknown origin on my network. Heap: 28320 UPnP: Sent SSDP NOTIFY PANIC: unprotected error in call to Lua API (/opt/nodemcu-firmware/local/fs/httpd_req.lua:26: bad argument #2 to 'sub' (number expected, got nil)) Ran the patched code (including else statement to track occurrences) for 72 hours with no recurrence.
Lua
apache-2.0
konnected-io/konnected-security,konnected-io/konnected-security
a393c4e1652dcbe23107a907c0d1927832f8b2c1
src/basset_db_predict.lua
src/basset_db_predict.lua
#!/usr/bin/env th require 'hdf5' require 'convnet_io' require 'postprocess' ---------------------------------------------------------------- -- parse arguments ---------------------------------------------------------------- cmd = torch.CmdLine() cmd:text() cmd:text('DNA ConvNet response to DB motifs') cmd:text() cmd:text('Arguments') cmd:argument('motifs_file') cmd:argument('model_file') cmd:argument('data_file') cmd:argument('out_file') cmd:text() cmd:text('Options:') cmd:option('-batch_size', 256, 'Maximum batch size') cmd:option('-cuda', false, 'Run on GPGPU') opt = cmd:parse(arg) -- fix seed torch.manualSeed(1) cuda = opt.cuda require 'convnet' ---------------------------------------------------------------- -- load data ---------------------------------------------------------------- local convnet_params = torch.load(opt.model_file) local convnet = ConvNet:__init() convnet:load(convnet_params) convnet.model:evaluate() -- open HDF5 and get test sequences local data_open = hdf5.open(opt.data_file, 'r') local test_seqs = data_open:read('test_in'):all() local num_seqs = (#test_seqs)[1] local seq_len = (#test_seqs)[4] local seq_mid = seq_len/2 - 5 local motifs_open = hdf5.open(opt.motifs_file, 'r') local motifs = motifs_open:all() local num_motifs = 0 for mid, _ in pairs(motifs) do num_motifs = num_motifs + 1 end print(motifs[tostring(num_motifs-1)]) ---------------------------------------------------------------- -- predict ---------------------------------------------------------------- -- make initial predictions local preds, scores, reprs = convnet:predict_repr(test_seqs, opt.batch_size, true) -- initialize difference storage local num_targets = (#preds)[2] local scores_diffs = torch.Tensor(num_motifs, num_targets) local reprs_diffs = {} for l = 1,#reprs do reprs_diffs[l] = torch.Tensor(num_motifs, (#reprs[l])[2]) end -- compute score mean and variance local scores_means = scores:mean(1):squeeze() local scores_stds = scores:std(1):squeeze() -- compute hidden unit means local reprs_means = {} for l = 1,#reprs do if reprs[l]:nDimension() == 2 then -- fully connected reprs_means[l] = reprs[l]:mean(1):squeeze() else -- convolution reprs_means[l] = reprs[l]:mean(3):mean(1):squeeze() end end -- TEMP for mi = 1,num_motifs do -- for mi = 1,10 do print(mi) -- copy the test seqs local test_seqs_motif = test_seqs:clone() -- access motif local motif = motifs[tostring(mi)] for si = 1,num_seqs do -- sample a motif sequence for pi = 1,(#motif)[2] do -- choose a random nt local r = torch.uniform() local nt = 1 local psum = motif[nt][pi] while psum < r do nt = nt + 1 psum = psum + motif[nt][pi] end -- set the nt for ni = 1,4 do test_seqs_motif[si][ni][1][seq_mid+pi] = 0 end test_seqs_motif[si][nt][1][seq_mid+pi] = 1 end end -- predict local mpreds, mscores, mreprs = convnet:predict_repr(test_seqs_motif, opt.batch_size, true) -- compute stats local mscores_means = mscores:mean(1):squeeze() local mreprs_means = {} for l = 1,#reprs do if mreprs[l]:nDimension() == 2 then -- fully connected mreprs_means[l] = mreprs[l]:mean(1):squeeze() else -- convolution mreprs_means[l] = mreprs[l]:mean(3):mean(1):squeeze() end end -- save difference scores_diffs[mi] = mscores_means - scores_means -- compute a statistical test? -- repr difference for l = 1,#reprs do reprs_diffs[l][mi] = mreprs_means[l] - reprs_means[l] end end ---------------------------------------------------------------- -- dump to file, load into python ---------------------------------------------------------------- local hdf_out = hdf5.open(opt.out_file, 'w') hdf_out:write('scores', scores_diffs) for l = 1,#reprs_diffs do local repr_name = string.format("reprs%d", l) hdf_out:write(repr_name, reprs_diffs[l]) end hdf_out:close()
#!/usr/bin/env th require 'hdf5' require 'convnet_io' require 'postprocess' ---------------------------------------------------------------- -- parse arguments ---------------------------------------------------------------- cmd = torch.CmdLine() cmd:text() cmd:text('DNA ConvNet response to DB motifs') cmd:text() cmd:text('Arguments') cmd:argument('motifs_file') cmd:argument('model_file') cmd:argument('data_file') cmd:argument('out_file') cmd:text() cmd:text('Options:') cmd:option('-batch_size', 256, 'Maximum batch size') cmd:option('-cuda', false, 'Run on GPGPU') opt = cmd:parse(arg) -- fix seed torch.manualSeed(1) cuda = opt.cuda require 'convnet' ---------------------------------------------------------------- -- load data ---------------------------------------------------------------- local convnet_params = torch.load(opt.model_file) local convnet = ConvNet:__init() convnet:load(convnet_params) convnet.model:evaluate() -- open HDF5 and get test sequences local data_open = hdf5.open(opt.data_file, 'r') local test_seqs = data_open:read('test_in'):all() local num_seqs = (#test_seqs)[1] local seq_len = (#test_seqs)[4] local seq_mid = seq_len/2 - 5 local motifs_open = hdf5.open(opt.motifs_file, 'r') local motifs = motifs_open:all() local num_motifs = 0 for mid, _ in pairs(motifs) do num_motifs = num_motifs + 1 end ---------------------------------------------------------------- -- predict ---------------------------------------------------------------- -- make initial predictions local preds, scores, reprs = convnet:predict_repr(test_seqs, opt.batch_size, true) -- initialize difference storage local num_targets = (#preds)[2] local scores_diffs = torch.Tensor(num_motifs, num_targets) local reprs_diffs = {} for l = 1,#reprs do reprs_diffs[l] = torch.Tensor(num_motifs, (#reprs[l])[2]) end -- compute score mean and variance local scores_means = scores:mean(1):squeeze() local scores_stds = scores:std(1):squeeze() -- compute hidden unit means local reprs_means = {} for l = 1,#reprs do if reprs[l]:nDimension() == 2 then -- fully connected reprs_means[l] = reprs[l]:mean(1):squeeze() else -- convolution reprs_means[l] = reprs[l]:mean(3):mean(1):squeeze() end end -- for each motif for mi = 1,num_motifs do print(mi) -- copy the test seqs local test_seqs_motif = test_seqs:clone() -- access motif local motif = motifs[tostring(mi)] for si = 1,num_seqs do -- sample a motif sequence for pi = 1,(#motif)[2] do -- choose a random nt local r = torch.uniform() - 0.0001 local nt = 1 local psum = motif[nt][pi] while psum < r do nt = nt + 1 psum = psum + motif[nt][pi] end -- set the nt for ni = 1,4 do test_seqs_motif[si][ni][1][seq_mid+pi] = 0 end test_seqs_motif[si][nt][1][seq_mid+pi] = 1 end end -- predict local mpreds, mscores, mreprs = convnet:predict_repr(test_seqs_motif, opt.batch_size, true) -- compute stats local mscores_means = mscores:mean(1):squeeze() local mreprs_means = {} for l = 1,#reprs do if mreprs[l]:nDimension() == 2 then -- fully connected mreprs_means[l] = mreprs[l]:mean(1):squeeze() else -- convolution mreprs_means[l] = mreprs[l]:mean(3):mean(1):squeeze() end end -- save difference scores_diffs[mi] = mscores_means - scores_means -- compute a statistical test? -- repr difference for l = 1,#reprs do reprs_diffs[l][mi] = mreprs_means[l] - reprs_means[l] end end ---------------------------------------------------------------- -- dump to file, load into python ---------------------------------------------------------------- local hdf_out = hdf5.open(opt.out_file, 'w') hdf_out:write('scores', scores_diffs) for l = 1,#reprs_diffs do local repr_name = string.format("reprs%d", l) hdf_out:write(repr_name, reprs_diffs[l]) end hdf_out:close()
random 1.0 bug
random 1.0 bug
Lua
mit
davek44/Basset,davek44/Basset
7cf18e3bce0cea8ec8abf7f03b64ba5b11770039
illarionserver/npc/base/guards_static.lua
illarionserver/npc/base/guards_static.lua
require("base.factions") require("base.common") require("content.guards") require("content.areas") module("npc.base.guards_static", package.seeall) -- modes to define how players are handled. Monsters are always attacked (TO DO, for now: warp only) ACTION_NONE = 0; -- do nothing at all ACTION_PASSIVE = 1; -- if in attackmode, warp away ACTION_HOSTILE = 2; -- warp away ACTION_AGGRESSIVE = 3; -- attack (TO DO) ACTION_PASSAGE = 4; -- let this person pass, even if he is memeber of a hostile group (only for individuals, not for factions) --- Checks for chars in range and handles them (warp) -- @param guard The character struct of the guard NPC function CheckForEnemies(guard) -- check for hostile monsters local monsterList = world:getMonstersInRangeOf(guard.pos, content.guards.Guards[guard.name].radius); local warpedMonster = false; for i,mon in pairs(monsterList) do if (content.areas.PointInArea(mon.pos,content.guards.Guards[guard.name].areaName)) then if ( not base.common.IsMonsterDocile(mon:getMonsterType()) ) then -- TODO call help -- for now only warp warpedMonster = true; Warp(guard, mon); end end end if (warpedMonster) then guard:talk(Character.say, "Weg mit dir, widerliche Kreatur!", "Go away, nasty creature!"); end -- check for player characters local charList = world:getPlayersInRangeOf(guard.pos, content.guards.Guards[guard.name].radius); local warpedPlayers = false; local hittedPlayers = false; for i,char in pairs(charList) do if (content.areas.PointInArea(char.pos,content.guards.Guards[guard.name].areaName)) then local mode = GetMode(char, content.guards.Guards[guard.name].faction); if (mode == ACTION_AGGRESSIVE) then -- spawn monster guards -- TODO -- for now: just hit and warp local hitValue = -1000; char:increaseAttrib("hitpoints", hitValue); hittedPlayers = true; warpedPlayers = true; Warp(guard, char); elseif (mode == ACTION_HOSTILE or (mode == ACTION_PASSIVE and char.attackmode)) then -- warp warpedPlayers = true; Warp(guard, char); end end end if (warpedPlayers) then guard:talk(Character.say, "Pass blo auf! Wir brauchen hier kein Gesindel.", "You'd better watch out! We don't need such lowlifes here."); end if (hittedPlayers) then world:makeSound(3, guard.pos); end end --- get the mode for this faction depending on the char's faction or his individual mode -- @param char The character whose faction is to be checked -- @param thisFaction The faction ID of the guard function GetMode(char, thisFaction) if char:isAdmin() then return ACTION_NONE; end local individualMode = GetIndividualMode(char, thisFaction) local f = base.factions.getFaction(char).tid; local factionMode = GetModeByFaction(thisFaction, f); return math.max(individualMode, factionMode) end -- return the mode of the character; check also for temporary mode -- @param char The character whose faction is to be checked -- @param thisFaction The faction ID of the guard function GetIndividualMode(char, thisFaction) local modeList = {} local daysList = {} modeList["Cadomyr"] = 191; daysList["Cadomyr"] = 192 modeList["Runewick"] = 193; daysList["Runewick"] = 194 modeList["Galmair"] = 195; daysList["Cadomyr"] = 196 local factionName = base.factions.getTownNameByID(thisFaction) local mode = char:getQuestProgress(modeList[factionName]) local days, setTime = char:getQuestProgress(daysList[factionName]) if mode > 4 then debug("[Error] "..char.name.." ("..char.id..") had a higher quest value than allowed. Reset to 0.") mode = 0 char:setQuestProgress(mode,0) end if days ~= 0 then local daysInSec = (days/3)*24*60*60 if (world:getTime("unix") - setTime >= daysInSec) then return 0 end end return mode end --- get the mode for this faction by the other (hostile) faction -- @param thisFaction The faction ID of the guard -- @param otherFaction The faction ID that is to be checked function GetModeByFaction(thisFaction, otherFaction) local found, mode = ScriptVars:find("Mode_".. thisFaction); if not found then InitMode(thisFaction); return GetModeByFaction(thisFaction, otherFaction); end mode = mode % (10^(otherFaction+1)); mode = math.floor(mode / 10^otherFaction); return mode; end --- set the mode for all guards of this faction -- @param thisFaction The faction ID of the guard -- @param otherFaction The faction ID whose mode is to be changed -- @param newMode The new mode, e.g. ACTION_NONE function SetMode(thisFaction, otherFaction, newMode) -- get mode for all factions local found, modeAll = ScriptVars:find("Mode_".. thisFaction); local oldMode = 0; if not found then InitMode(thisFaction); SetMode(thisFaction, otherFaction, newMode); return; else -- calculate the old mode for the otherFaction oldMode = modeAll % (10^(otherFaction+1)); oldMode = math.floor(oldMode / 10^otherFaction); end -- subtract old mode modeAll = modeAll - (oldMode * 10^(otherFaction)); -- add new mode modeAll = modeAll + (newMode * 10^(otherFaction)); -- set ScriptVar again modeAll = math.max(0,math.min(9999, modeAll)); -- must not be negative & exceed 9999 (3 towns + outcasts) ScriptVars:set("Mode_".. thisFaction, modeAll); end --- initialize the mode for all factions, only the current faction gets access -- @param thisFaction The faction ID of the current faction function InitMode(thisFaction) ScriptVars:set("Mode_".. thisFaction, 0); SetMode(thisFaction, thisFaction, ACTION_NONE); local factions = {0,1,2,3}; for _,f in pairs(factions) do if (thisFaction ~= f) then SetMode(thisFaction, f, ACTION_HOSTILE); end end end --- warp the char to the defined warp position -- @param guard The guard that warps the char -- @param char The char that will be warped function Warp(guard, char) char:warp(content.guards.Guards[guard.name].warpPos); base.common.InformNLS(char, "Du wurdest soeben von einer Wache der Stadt verwiesen.", "You've just been expelled from the town by a guard."); end function NextCycle(NpcChar) content.guards.InitGuards(); if (CheckCount == nil) then CheckCount = {}; elseif (CheckCount[NpcChar.id] == nil) then CheckCount[NpcChar.id] = 0; elseif (CheckCount[NpcChar.id] == 5) then if (content.guards.Guards~=nil) then CheckForEnemies(NpcChar); end CheckCount[NpcChar.id] = 0; else CheckCount[NpcChar.id] = CheckCount[NpcChar.id] + 1; end end --[[ -- ## REPLACE THE nextCycle FUNCTION AND ADD THE REQUIREMENT IN THE LUA CODE OF EACH GUARD ## require("npc.base.guards_static") function nextCycle(npcChar) mainNPC:nextCycle(npcChar); npc.base.guards_static.NextCycle(npcChar); end; ]]
require("base.factions") require("base.common") require("content.guards") require("content.areas") module("npc.base.guards_static", package.seeall) -- modes to define how players are handled. Monsters are always attacked (TO DO, for now: warp only) ACTION_NONE = 0; -- do nothing at all ACTION_PASSIVE = 1; -- if in attackmode, warp away ACTION_HOSTILE = 2; -- warp away ACTION_AGGRESSIVE = 3; -- attack (TO DO) ACTION_PASSAGE = 4; -- let this person pass, even if he is memeber of a hostile group (only for individuals, not for factions) --- Checks for chars in range and handles them (warp) -- @param guard The character struct of the guard NPC function CheckForEnemies(guard) -- check for hostile monsters local monsterList = world:getMonstersInRangeOf(guard.pos, content.guards.Guards[guard.name].radius); local warpedMonster = false; for i,mon in pairs(monsterList) do if (content.areas.PointInArea(mon.pos,content.guards.Guards[guard.name].areaName)) then if ( not base.common.IsMonsterDocile(mon:getMonsterType()) ) then -- TODO call help -- for now only warp warpedMonster = true; Warp(guard, mon); end end end if (warpedMonster) then guard:talk(Character.say, "Weg mit dir, widerliche Kreatur!", "Go away, nasty creature!"); end -- check for player characters local charList = world:getPlayersInRangeOf(guard.pos, content.guards.Guards[guard.name].radius); local warpedPlayers = false; local hittedPlayers = false; for i,char in pairs(charList) do if (content.areas.PointInArea(char.pos,content.guards.Guards[guard.name].areaName)) then local mode = GetMode(char, content.guards.Guards[guard.name].faction); if (mode == ACTION_AGGRESSIVE) then -- spawn monster guards -- TODO -- for now: just hit and warp local hitValue = -1000; char:increaseAttrib("hitpoints", hitValue); hittedPlayers = true; warpedPlayers = true; Warp(guard, char); elseif (mode == ACTION_HOSTILE or (mode == ACTION_PASSIVE and char.attackmode)) then -- warp warpedPlayers = true; Warp(guard, char); end end end if (warpedPlayers) then guard:talk(Character.say, "Pass blo auf! Wir brauchen hier kein Gesindel.", "You'd better watch out! We don't need such lowlifes here."); end if (hittedPlayers) then world:makeSound(3, guard.pos); end end --- get the mode for this faction depending on the char's faction or his individual mode -- @param char The character whose faction is to be checked -- @param thisFaction The faction ID of the guard function GetMode(char, thisFaction) if char:isAdmin() and not char.name=="Jupiter" then return ACTION_NONE; end local individualMode = GetIndividualMode(char, thisFaction) local f = base.factions.getFaction(char).tid; local factionMode = GetModeByFaction(thisFaction, f); return math.max(individualMode, factionMode) end -- return the mode of the character; check also for temporary mode -- @param char The character whose faction is to be checked -- @param thisFaction The faction ID of the guard function GetIndividualMode(char, thisFaction) local modeList = {} local daysList = {} modeList["Cadomyr"] = 191; daysList["Cadomyr"] = 192 modeList["Runewick"] = 193; daysList["Runewick"] = 194 modeList["Galmair"] = 195; daysList["Galmair"] = 196 local factionName = base.factions.getTownNameByID(thisFaction) local mode = char:getQuestProgress(modeList[factionName]) local days, setTime = char:getQuestProgress(daysList[factionName]) if mode > 4 then debug("[Error] "..char.name.." ("..char.id..") had a higher quest value than allowed. Reset to 0.") mode = 0 char:setQuestProgress(mode,0) end if days ~= 0 then local daysInSec = (days/3)*24*60*60 if (world:getTime("unix") - setTime >= daysInSec) then return 0 end end return mode end --- get the mode for this faction by the other (hostile) faction -- @param thisFaction The faction ID of the guard -- @param otherFaction The faction ID that is to be checked function GetModeByFaction(thisFaction, otherFaction) local found, mode = ScriptVars:find("Mode_".. thisFaction); if not found then InitMode(thisFaction); return GetModeByFaction(thisFaction, otherFaction); end mode = mode % (10^(otherFaction+1)); mode = math.floor(mode / 10^otherFaction); return mode; end --- set the mode for all guards of this faction -- @param thisFaction The faction ID of the guard -- @param otherFaction The faction ID whose mode is to be changed -- @param newMode The new mode, e.g. ACTION_NONE function SetMode(thisFaction, otherFaction, newMode) -- get mode for all factions local found, modeAll = ScriptVars:find("Mode_".. thisFaction); local oldMode = 0; if not found then InitMode(thisFaction); SetMode(thisFaction, otherFaction, newMode); return; else -- calculate the old mode for the otherFaction oldMode = modeAll % (10^(otherFaction+1)); oldMode = math.floor(oldMode / 10^otherFaction); end -- subtract old mode modeAll = modeAll - (oldMode * 10^(otherFaction)); -- add new mode modeAll = modeAll + (newMode * 10^(otherFaction)); -- set ScriptVar again modeAll = math.max(0,math.min(9999, modeAll)); -- must not be negative & exceed 9999 (3 towns + outcasts) ScriptVars:set("Mode_".. thisFaction, modeAll); end --- initialize the mode for all factions, only the current faction gets access -- @param thisFaction The faction ID of the current faction function InitMode(thisFaction) ScriptVars:set("Mode_".. thisFaction, 0); SetMode(thisFaction, thisFaction, ACTION_NONE); local factions = {0,1,2,3}; for _,f in pairs(factions) do if (thisFaction ~= f) then SetMode(thisFaction, f, ACTION_HOSTILE); end end end --- warp the char to the defined warp position -- @param guard The guard that warps the char -- @param char The char that will be warped function Warp(guard, char) char:warp(content.guards.Guards[guard.name].warpPos); base.common.InformNLS(char, "Du wurdest soeben von einer Wache der Stadt verwiesen.", "You've just been expelled from the town by a guard."); end function NextCycle(NpcChar) content.guards.InitGuards(); if (CheckCount == nil) then CheckCount = {}; elseif (CheckCount[NpcChar.id] == nil) then CheckCount[NpcChar.id] = 0; elseif (CheckCount[NpcChar.id] == 5) then if (content.guards.Guards~=nil) then CheckForEnemies(NpcChar); end CheckCount[NpcChar.id] = 0; else CheckCount[NpcChar.id] = CheckCount[NpcChar.id] + 1; end end --[[ -- ## REPLACE THE nextCycle FUNCTION AND ADD THE REQUIREMENT IN THE LUA CODE OF EACH GUARD ## require("npc.base.guards_static") function nextCycle(npcChar) mainNPC:nextCycle(npcChar); npc.base.guards_static.NextCycle(npcChar); end; ]]
Hotfix for static guards
Hotfix for static guards
Lua
agpl-3.0
LaFamiglia/Illarion-Content,vilarion/Illarion-Content,KayMD/Illarion-Content,Baylamon/Illarion-Content,Illarion-eV/Illarion-Content
be38a3af16cda0c7db8022aeb080f208696bd0ad
src/npge/util/threads.lua
src/npge/util/threads.lua
-- lua-npge, Nucleotide PanGenome explorer (Lua module) -- Copyright (C) 2014-2015 Boris Nagaev -- See the LICENSE file for terms of use. -- see https://github.com/moteus/lua-llthreads2 -- WARNING target executable must be linked against pthread -- Otherwise memory errors occur -- LD_PRELOAD=/lib/x86_64-linux-gnu/libpthread.so.0 lua ... local workerCode = [[ local config = require 'npge.config' config:load(%q) return xpcall(function() %s end, function(message) return message .. '\n' .. debug.traceback() end) ]] local spawnWorkers = function(generator, workers, conf) local llthreads2 = require "llthreads2" local threads = {} for _, code in ipairs(generator(workers)) do local code1 = workerCode:format(conf, code) local thread = llthreads2.new(code1) thread:start() table.insert(threads, thread) end return threads end local collectResults = function(collector, threads) local errors = {} local results = {} for _, thread in ipairs(threads) do local _, status, result = thread:join() if status then table.insert(results, result) else table.insert(errors, result) end end assert(#errors == 0, "Errors in threads: " .. table.concat(errors, "\n")) return collector(results) end -- run an action with threads. -- Arguments: -- - generator is a function, which gets number of threads and -- returns an array of codes to be run in threads. -- - collector is a function, which gets an array of results -- threads one after another, and returns final result, -- which is returned from this function. return function(generator, collector) local config = require 'npge.config' local workers = config.util.WORKERS local has_llthreads2 = pcall(require, "llthreads2") if workers == 1 or not has_llthreads2 then local loadstring = require 'npge.util.loadstring' local code = generator(1)[1] local result = assert(loadstring(code)()) return collector({result}) end local config = require 'npge.config' local conf = config:save() local threads = spawnWorkers(generator, workers, conf) return collectResults(collector, threads) end
-- lua-npge, Nucleotide PanGenome explorer (Lua module) -- Copyright (C) 2014-2015 Boris Nagaev -- See the LICENSE file for terms of use. -- see https://github.com/moteus/lua-llthreads2 -- WARNING target executable must be linked against pthread -- Otherwise memory errors occur -- LD_PRELOAD=/lib/x86_64-linux-gnu/libpthread.so.0 lua ... local workerCode = [[ local config = require 'npge.config' config:load(%q) return xpcall(function() %s end, function(message) return message .. '\n' .. debug.traceback() end) ]] local spawnWorkers = function(generator, workers, conf) local llthreads2 = require "llthreads2" local threads = {} for _, code in ipairs(generator(workers)) do local code1 = workerCode:format(conf, code) local thread = llthreads2.new(code1) thread:start() table.insert(threads, thread) end return threads end local collectResults = function(collector, threads) local errors = {} local results = {} for _, thread in ipairs(threads) do local _, status, result = thread:join() if status then -- if result is nil, do table.insert does nothing table.insert(results, result) else table.insert(errors, result) end end assert(#errors == 0, "Errors in threads: " .. table.concat(errors, "\n")) return collector(results) end -- run an action with threads. -- Arguments: -- - generator is a function, which gets number of threads and -- returns an array of codes to be run in threads. -- - collector is a function, which gets an array of results -- threads one after another, and returns final result, -- which is returned from this function. return function(generator, collector) local config = require 'npge.config' local workers = config.util.WORKERS local has_llthreads2 = pcall(require, "llthreads2") if workers == 1 or not has_llthreads2 then local loadstring = require 'npge.util.loadstring' local code = generator(1)[1] local result = loadstring(code)() return collector({result}) end local config = require 'npge.config' local conf = config:save() local threads = spawnWorkers(generator, workers, conf) return collectResults(collector, threads) end
threads: don't assert that generator produces smth
threads: don't assert that generator produces smth fix #4
Lua
mit
starius/lua-npge,npge/lua-npge,starius/lua-npge,starius/lua-npge,npge/lua-npge,npge/lua-npge
1e416eefc71f64c0529cdc86a7a60374b5efcc9b
specs/subsets_and_batches_spec.lua
specs/subsets_and_batches_spec.lua
require 'lfs' require 'torch' -- Make sure that directory structure is always the same if (string.match(lfs.currentdir(), "/specs$")) then lfs.chdir("..") end -- Include Dataframe lib paths.dofile('init.lua') -- Go into specs so that the loading of CSV:s is the same as always lfs.chdir("specs") describe("Loading batch process", function() local fake_loader = function(row) return torch.Tensor({1, 2}) end a = Dataframe("./data/realistic_29_row_data.csv") a:create_subsets() it("Raises an error if create_subsets hasn't be called",function() assert.has.error(function() a:reset_subsets() end) end) it("Initializes with random order for training and linear for the other", function() torch.manualSeed(0) a:reset_subsets() local order = 0 assert.are.equal(a["/train"].subsets.samper, 'permutation') assert.are.equal(a["/test"].subsets.samper, 'linear') assert.are.equal(a["/validate"].subsets.samper, 'linear') end) describe("In action",function() a:create_subsets() it("Loads batches",function() local data, label = a["/train"]: get_batch{no_lines = 5}: to_tensor{ load_data_fn = fake_loader } assert.is.equal(data:size(1), 5)-- "The data has invalid rows" assert.is.equal(data:size(2), 2)-- "The data has invalid columns" assert.is.equal(label:size(1), 5)--"The labels have invalid size" end) it("Doesn't load all cases",function() local batch_size = 6 local count = 0 local batch, reset for i=1,(math.ceil(a["/train"]:size(1)/batch_size) + 1) do batch, reset = a["/train"]:get_batch{no_lines = batch_size} if (batch == nil) then break end count = count + batch:size(1) end assert.are.equal(count, a["/train"]:size(1)) assert.is_true(reset) a["/train"]:reset_sampler() batch, reset = a["/train"]:get_batch{no_lines = -1} assert.are.equal(batch:size(1), a["/train"]:size(1)) assert.is_true(reset) end) -- TODO: Add tests for custom subset splits and samplers end) end)
require 'lfs' require 'torch' -- Make sure that directory structure is always the same if (string.match(lfs.currentdir(), "/specs$")) then lfs.chdir("..") end -- Include Dataframe lib paths.dofile('init.lua') -- Go into specs so that the loading of CSV:s is the same as always lfs.chdir("specs") describe("Loading dataframe and creaing adequate subsets", function() it("Raises an error if create_subsets hasn't be called",function() local a = Dataframe("./data/realistic_29_row_data.csv") assert.has.error(function() a:reset_subsets() end) end) it("Initializes with random order for training and linear for the other", function() local a = Dataframe("./data/realistic_29_row_data.csv") a:create_subsets() assert.are.equal(a.subsets.samplers["train"], 'permutation', "Train init failed") assert.are.equal(a.subsets.samplers["validate"], 'linear', "Validate init failed") assert.are.equal(a.subsets.samplers["test"], 'linear', "Test init failed") end) it("Check that the initialized subset sizes are correct for default subsets", function() local a = Dataframe("./data/realistic_29_row_data.csv") a:create_subsets() assert.are.equal(a["/test"]:size(1) + a["/train"]:size(1) + a["/validate"]:size(1), a:size(1), "Number of cases don't match") -- as the full dataset must be used per definition one of the elements may not -- exactly be of expected length. We therefore have to look for sizes that -- are within no_of_subset - 1 from eachother assert.is_true( math.abs(a["/train"]:size(1) - math.floor(a:size(1) * .7)) <= 2, ("Train size fail - %d is not within 2 from expected %d"): format(a["/train"]:size(1), math.floor(a:size(1) * .7))) assert.is_true( math.abs(a["/validate"]:size(1) - math.floor(a:size(1) * .2)) <= 2, ("Validate size fail - %d is not within 2 from expected %d"): format(a["/validate"]:size(1), math.floor(a:size(1) * .2))) assert.is_true( math.abs(a["/test"]:size(1) - math.floor(a:size(1) * .1)) <= 2, ("Test size fail - %d is not within 2 from expected %d"): format(a["/test"]:size(1), math.floor(a:size(1) * .1))) end) end) describe("Test if we can get a batch with data and labels",function() local fake_loader = function(row) return torch.Tensor({1, 2}) end local a = Dataframe("./data/realistic_29_row_data.csv") a:create_subsets() it("Checkk that we get reasonable formatted data back",function() local data, label = a["/train"]: get_batch{no_lines = 5}: to_tensor{ load_data_fn = fake_loader } assert.is.equal(data:size(1), 5)-- "The data has invalid rows" assert.is.equal(data:size(2), 2)-- "The data has invalid columns" assert.is.equal(label:size(1), 5)--"The labels have invalid size" end) it("Check that we get all cases when running with the a sampler that requires resetting", function() a["/train"]:reset_sampler() local batch_size = 6 local count = 0 local batch, reset -- Run for over an epoch for i=1,(math.ceil(a["/train"]:size(1)/batch_size) + 1) do batch, reset = a["/train"]:get_batch{no_lines = batch_size} if (batch == nil) then break end count = count + batch:size(1) end assert.are.equal(count, a["/train"]:size(1)) assert.is_true(reset, "The reset should be set to true after 1 epoch") a["/train"]:reset_sampler() batch, reset = a["/train"]:get_batch{no_lines = -1} assert.are.equal(batch:size(1), a["/train"]:size(1)) assert.is_true(reset) end) -- TODO: Add tests for custom subset splits and samplers end)
Cleaned and fixed specs so that they now all pass
Cleaned and fixed specs so that they now all pass
Lua
mit
AlexMili/torch-dataframe
c2b85d65f7ac9edadddc3bf64bd38d8609ab30d8
lib/pkg/gdb.lua
lib/pkg/gdb.lua
return { source = { type = 'dist', location = 'http://ftp.gnu.org/gnu/gdb/gdb-7.9.tar.xz', sha256sum = '9b315651a16528f7af8c7d8284699fb0c965df316cc7339bb0b7bae335848392' }, build = { type = 'GNU', options = { '--target=$pkg_build_system', '--program-transform-name=', '--disable-binutils', '--disable-etc', '--disable-gas', '--disable-gold', '--disable-gprof', '--disable-gdbserver', '--disable-readline', '--with-system-readline', '--with-zlib' } } }
return { source = { type = 'dist', location = 'http://ftp.gnu.org/gnu/gdb/gdb-7.9.tar.xz', sha256sum = '9b315651a16528f7af8c7d8284699fb0c965df316cc7339bb0b7bae335848392' }, build = { type = 'GNU', unset_cflags = true, options = { '--build=x86_64-linux-gnu', '--host=x86_64-linux-gnu', '--target=$pkg_build_system', '--program-transform-name=', '--disable-binutils', '--disable-etc', '--disable-gas', '--disable-gold', '--disable-gprof', '--disable-gdbserver', '--disable-readline', '--with-system-readline', '--with-system-zlib', } } }
Fix gdb pkg
Fix gdb pkg
Lua
mit
bazurbat/jagen
5ed89427ef25a503cbb6cb40d4c545ef0007e28b
src/hs/finalcutpro/main/Viewer.lua
src/hs/finalcutpro/main/Viewer.lua
local log = require("hs.logger").new("timline") local inspect = require("hs.inspect") local just = require("hs.just") local axutils = require("hs.finalcutpro.axutils") local PrimaryWindow = require("hs.finalcutpro.main.PrimaryWindow") local SecondaryWindow = require("hs.finalcutpro.main.SecondaryWindow") local Viewer = {} function Viewer.matches(element) -- Viewers have a single 'AXContents' element local contents = element:attributeValue("AXContents") return contents and #contents == 1 and contents[1]:attributeValue("AXRole") == "AXSplitGroup" and #(contents[1]) > 0 end function Viewer:new(app, eventViewer) o = { _app = app, _eventViewer = eventViewer } setmetatable(o, self) self.__index = self return o end function Viewer:app() return self._app end function Viewer:isEventViewer() return self._eventViewer end function Viewer:isMainViewer() return not self._eventViewer end function Viewer:isOnSecondary() local ui = self:UI() return ui and SecondaryWindow.matches(ui:window()) end function Viewer:isOnPrimary() local ui = self:UI() return ui and PrimaryWindow.matches(ui:window()) end ----------------------------------------------------------------------- ----------------------------------------------------------------------- --- BROWSER UI ----------------------------------------------------------------------- ----------------------------------------------------------------------- function Viewer:UI() return axutils.cache(self, "_ui", function() local app = self:app() if self:isMainViewer() then return self:findViewerUI(app:secondaryWindow(), app:primaryWindow()) else return self:findEventViewerUI(app:secondaryWindow(), app:primaryWindow()) end end, Viewer.matches) end ----------------------------------------------------------------------- ----------------------------------------------------------------------- --- VIEWER UI ----------------------------------------------------------------------- ----------------------------------------------------------------------- function Viewer:findViewerUI(...) for i = 1,select("#", ...) do local window = select(i, ...) if window then local top = window:viewerGroupUI() local ui = nil if top then for i,child in ipairs(top) do -- There can be two viwers enabled if Viewer.matches(child) then -- Both the event viewer and standard viewer have the ID, so pick the right-most one if ui == nil or ui:position().x < child:position().x then ui = child end end end end if ui then return ui end end end return nil end ----------------------------------------------------------------------- ----------------------------------------------------------------------- --- EVENT VIEWER UI ----------------------------------------------------------------------- ----------------------------------------------------------------------- function Viewer:findEventViewerUI(...) for i = 1,select("#", ...) do local window = select(i, ...) if window then local top = window:viewerGroupUI() local ui = nil local viewerCount = 0 for i,child in ipairs(top) do -- There can be two viwers enabled if Viewer.matches(child) then viewerCount = viewerCount + 1 -- Both the event viewer and standard viewer have the ID, so pick the left-most one if ui == nil or ui:position().x > child:position().x then ui = child end end end -- Can only be the event viewer if there are two viewers. if viewerCount == 2 then return ui end end end return nil end function Viewer:isShowing() return self:UI() ~= nil end function Viewer:showOnPrimary() local menuBar = self:app():menuBar() -- if the browser is on the secondary, we need to turn it off before enabling in primary menuBar:uncheckMenu("Window", "Show in Secondary Display", "Viewers") if self:isEventViewer() then -- Enable the Event Viewer menuBar:checkMenu("Window", "Show in Workspace", "Event Viewer") end return self end function Viewer:showOnSecondary() local menuBar = self:app():menuBar() menuBar:checkMenu("Window", "Show in Secondary Display", "Viewers") if self:isEventViewer() then -- Enable the Event Viewer menuBar:checkMenu("Window", "Show in Workspace", "Event Viewer") end return self end function Viewer:hide() local menuBar = self:app():menuBar() if self:isEventViewer() then -- Uncheck it from the primary workspace menuBar:uncheckMenu("Window", "Show in Workspace", "Event Viewer") elseif self:isOnSecondary() then -- The Viewer can only be hidden from the Secondary Display menuBar:uncheckMenu("Window", "Show in Secondary Display", "Viewers") end return self end function Viewer:topToolbarUI() return axutils.cache(self, "_topToolbar", function() local ui = self:UI() if ui then for i,child in ipairs(ui) do if axutils.childWith(child, "AXIdentifier", "_NS:16") then return child end end end return nil end) end function Viewer:bottomToolbarUI() return axutils.cache(self, "_bottomToolbar", function() local ui = self:UI() if ui then for i,child in ipairs(ui) do if axutils.childWith(child, "AXIdentifier", "_NS:31") then return child end end end return nil end) end function Viewer:hasPlayerControls() return self:bottomToolbarUI() ~= nil end function Viewer:formatUI() return axutils.cache(self, "_format", function() local ui = self:topToolbarUI() return ui and axutils.childWith(ui, "AXIdentifier", "_NS:274") end) end function Viewer:getFormat() local format = self:formatUI() return format and format:value() end function Viewer:getFramerate() local format = self:getFormat() local framerate = format and string.match(format, ' %d%d%.?%d?%d?[pi]') return framerate and tonumber(string.sub(framerate, 1,-2)) end function Viewer:getTitle() local titleText = axutils.childWithID(self:topToolbarUI(), "_NS:16") return titleText and titleText:value() end return Viewer
local log = require("hs.logger").new("timline") local inspect = require("hs.inspect") local just = require("hs.just") local axutils = require("hs.finalcutpro.axutils") local PrimaryWindow = require("hs.finalcutpro.main.PrimaryWindow") local SecondaryWindow = require("hs.finalcutpro.main.SecondaryWindow") local Viewer = {} function Viewer.matches(element) -- Viewers have a single 'AXContents' element local contents = element:attributeValue("AXContents") return contents and #contents == 1 and contents[1]:attributeValue("AXRole") == "AXSplitGroup" and #(contents[1]) > 0 end function Viewer:new(app, eventViewer) o = { _app = app, _eventViewer = eventViewer } setmetatable(o, self) self.__index = self return o end function Viewer:app() return self._app end function Viewer:isEventViewer() return self._eventViewer end function Viewer:isMainViewer() return not self._eventViewer end function Viewer:isOnSecondary() local ui = self:UI() return ui and SecondaryWindow.matches(ui:window()) end function Viewer:isOnPrimary() local ui = self:UI() return ui and PrimaryWindow.matches(ui:window()) end ----------------------------------------------------------------------- ----------------------------------------------------------------------- --- BROWSER UI ----------------------------------------------------------------------- ----------------------------------------------------------------------- function Viewer:UI() return axutils.cache(self, "_ui", function() local app = self:app() if self:isMainViewer() then return self:findViewerUI(app:secondaryWindow(), app:primaryWindow()) else return self:findEventViewerUI(app:secondaryWindow(), app:primaryWindow()) end end, Viewer.matches) end ----------------------------------------------------------------------- ----------------------------------------------------------------------- --- VIEWER UI ----------------------------------------------------------------------- ----------------------------------------------------------------------- function Viewer:findViewerUI(...) for i = 1,select("#", ...) do local window = select(i, ...) if window then local top = window:viewerGroupUI() local ui = nil if top then for i,child in ipairs(top) do -- There can be two viwers enabled if Viewer.matches(child) then -- Both the event viewer and standard viewer have the ID, so pick the right-most one if ui == nil or ui:position().x < child:position().x then ui = child end end end end if ui then return ui end end end return nil end ----------------------------------------------------------------------- ----------------------------------------------------------------------- --- EVENT VIEWER UI ----------------------------------------------------------------------- ----------------------------------------------------------------------- function Viewer:findEventViewerUI(...) for i = 1,select("#", ...) do local window = select(i, ...) if window then local top = window:viewerGroupUI() local ui = nil local viewerCount = 0 if top then for i,child in ipairs(top) do -- There can be two viwers enabled if Viewer.matches(child) then viewerCount = viewerCount + 1 -- Both the event viewer and standard viewer have the ID, so pick the left-most one if ui == nil or ui:position().x > child:position().x then ui = child end end end end -- Can only be the event viewer if there are two viewers. if viewerCount == 2 then return ui end end end return nil end function Viewer:isShowing() return self:UI() ~= nil end function Viewer:showOnPrimary() local menuBar = self:app():menuBar() -- if the browser is on the secondary, we need to turn it off before enabling in primary menuBar:uncheckMenu("Window", "Show in Secondary Display", "Viewers") if self:isEventViewer() then -- Enable the Event Viewer menuBar:checkMenu("Window", "Show in Workspace", "Event Viewer") end return self end function Viewer:showOnSecondary() local menuBar = self:app():menuBar() menuBar:checkMenu("Window", "Show in Secondary Display", "Viewers") if self:isEventViewer() then -- Enable the Event Viewer menuBar:checkMenu("Window", "Show in Workspace", "Event Viewer") end return self end function Viewer:hide() local menuBar = self:app():menuBar() if self:isEventViewer() then -- Uncheck it from the primary workspace menuBar:uncheckMenu("Window", "Show in Workspace", "Event Viewer") elseif self:isOnSecondary() then -- The Viewer can only be hidden from the Secondary Display menuBar:uncheckMenu("Window", "Show in Secondary Display", "Viewers") end return self end function Viewer:topToolbarUI() return axutils.cache(self, "_topToolbar", function() local ui = self:UI() if ui then for i,child in ipairs(ui) do if axutils.childWith(child, "AXIdentifier", "_NS:16") then return child end end end return nil end) end function Viewer:bottomToolbarUI() return axutils.cache(self, "_bottomToolbar", function() local ui = self:UI() if ui then for i,child in ipairs(ui) do if axutils.childWith(child, "AXIdentifier", "_NS:31") then return child end end end return nil end) end function Viewer:hasPlayerControls() return self:bottomToolbarUI() ~= nil end function Viewer:formatUI() return axutils.cache(self, "_format", function() local ui = self:topToolbarUI() return ui and axutils.childWith(ui, "AXIdentifier", "_NS:274") end) end function Viewer:getFormat() local format = self:formatUI() return format and format:value() end function Viewer:getFramerate() local format = self:getFormat() local framerate = format and string.match(format, ' %d%d%.?%d?%d?[pi]') return framerate and tonumber(string.sub(framerate, 1,-2)) end function Viewer:getTitle() local titleText = axutils.childWithID(self:topToolbarUI(), "_NS:16") return titleText and titleText:value() end return Viewer
#197 * Fixed bug with Viewer discovery in certain circumstances.
#197 * Fixed bug with Viewer discovery in certain circumstances.
Lua
mit
CommandPost/CommandPost,cailyoung/CommandPost,cailyoung/CommandPost,fcpxhacks/fcpxhacks,fcpxhacks/fcpxhacks,CommandPost/CommandPost,cailyoung/CommandPost,CommandPost/CommandPost
22971961d47e5c7be5882af8f3d3271588495772
src/lua/medium.lua
src/lua/medium.lua
-- medium.lua -- Network access medium. -- Copyright 2012 Snabb GmbH. See the file COPYING for license details. module(...,package.seeall) -- Shared memory medium. SHM = {} function SHM:new (filename) local new = { first = true, shm = fabric.open_shm(shmfilename) } setmetatable(new, {__index = self}) return new end function SHM:transmit (packet) local ring = self.shm.host2vm if not shm.full(ring) then C.memcpy(ring.packets[ring.tail].data, packet.data, packet.length) ring.packets[ring.tail].length = packet.length shm.advance_tail(ring) return true else return false end end function SHM:receive () local ring = self.shm.vm2host if shm.available(ring) then if self.first then self.first = false else shm.advance_head(ring) end return shm.packet(ring) else return nil end end -- Null medium. Null = {} function Null:new () local new = {} setmetatable(new, {__index = self}) return new end function Null:transmit (packet) return true end function Null:receive () return nil end
-- medium.lua -- Network access medium. -- Copyright 2012 Snabb GmbH. See the file COPYING for license details. module(...,package.seeall) local ffi = require("ffi") local fabric = ffi.load("fabric") -- Shared memory medium. SHM = {} function SHM:new (filename) local new = { first = true, shm = fabric.open_shm(filename) } setmetatable(new, {__index = self}) return new end function SHM:transmit (packet) local ring = self.shm.host2vm if not shm.full(ring) then C.memcpy(ring.packets[ring.tail].data, packet.data, packet.length) ring.packets[ring.tail].length = packet.length shm.advance_tail(ring) return true else return false end end function SHM:receive () local ring = self.shm.vm2host if shm.available(ring) then if self.first then self.first = false else shm.advance_head(ring) end return shm.packet(ring) else return nil end end -- Null medium. Null = {} function Null:new () local new = {} setmetatable(new, {__index = self}) return new end function Null:transmit (packet) return true end function Null:receive () return nil end
medium.lua: Fix small bugs in the SHM medium.
medium.lua: Fix small bugs in the SHM medium.
Lua
apache-2.0
snabbnfv-goodies/snabbswitch,kbara/snabb,javierguerragiraldez/snabbswitch,plajjan/snabbswitch,wingo/snabbswitch,andywingo/snabbswitch,alexandergall/snabbswitch,dpino/snabb,SnabbCo/snabbswitch,mixflowtech/logsensor,snabbco/snabb,wingo/snabb,plajjan/snabbswitch,alexandergall/snabbswitch,lukego/snabbswitch,dwdm/snabbswitch,dpino/snabb,xdel/snabbswitch,xdel/snabbswitch,alexandergall/snabbswitch,kbara/snabb,pirate/snabbswitch,aperezdc/snabbswitch,virtualopensystems/snabbswitch,dpino/snabb,eugeneia/snabbswitch,wingo/snabb,eugeneia/snabb,Igalia/snabbswitch,Igalia/snabbswitch,lukego/snabbswitch,heryii/snabb,eugeneia/snabb,plajjan/snabbswitch,fhanik/snabbswitch,hb9cwp/snabbswitch,Igalia/snabb,Igalia/snabbswitch,kellabyte/snabbswitch,eugeneia/snabb,alexandergall/snabbswitch,dpino/snabbswitch,Igalia/snabb,eugeneia/snabb,mixflowtech/logsensor,aperezdc/snabbswitch,justincormack/snabbswitch,lukego/snabbswitch,hb9cwp/snabbswitch,fhanik/snabbswitch,heryii/snabb,javierguerragiraldez/snabbswitch,lukego/snabb,alexandergall/snabbswitch,alexandergall/snabbswitch,fhanik/snabbswitch,virtualopensystems/snabbswitch,Igalia/snabbswitch,eugeneia/snabb,wingo/snabb,dpino/snabb,pavel-odintsov/snabbswitch,pirate/snabbswitch,Igalia/snabbswitch,snabbco/snabb,eugeneia/snabbswitch,snabbco/snabb,plajjan/snabbswitch,eugeneia/snabbswitch,lukego/snabb,snabbco/snabb,mixflowtech/logsensor,Igalia/snabb,aperezdc/snabbswitch,justincormack/snabbswitch,eugeneia/snabb,eugeneia/snabb,wingo/snabb,Igalia/snabb,kellabyte/snabbswitch,dpino/snabb,eugeneia/snabb,lukego/snabbswitch,aperezdc/snabbswitch,Igalia/snabb,kbara/snabb,wingo/snabbswitch,hb9cwp/snabbswitch,alexandergall/snabbswitch,wingo/snabb,virtualopensystems/snabbswitch,lukego/snabb,pirate/snabbswitch,wingo/snabb,SnabbCo/snabbswitch,snabbco/snabb,dpino/snabb,snabbnfv-goodies/snabbswitch,justincormack/snabbswitch,Igalia/snabb,snabbnfv-goodies/snabbswitch,lukego/snabb,snabbco/snabb,xdel/snabbswitch,heryii/snabb,kbara/snabb,SnabbCo/snabbswitch,dpino/snabb,dwdm/snabbswitch,Igalia/snabb,heryii/snabb,mixflowtech/logsensor,SnabbCo/snabbswitch,andywingo/snabbswitch,heryii/snabb,heryii/snabb,pavel-odintsov/snabbswitch,mixflowtech/logsensor,wingo/snabbswitch,snabbco/snabb,alexandergall/snabbswitch,dpino/snabbswitch,pavel-odintsov/snabbswitch,kellabyte/snabbswitch,andywingo/snabbswitch,kbara/snabb,andywingo/snabbswitch,wingo/snabbswitch,dpino/snabbswitch,Igalia/snabb,eugeneia/snabbswitch,dpino/snabbswitch,snabbnfv-goodies/snabbswitch,justincormack/snabbswitch,hb9cwp/snabbswitch,dwdm/snabbswitch,snabbco/snabb,kbara/snabb,javierguerragiraldez/snabbswitch
be457ce8aef5dba38ab61f46e9d1f5e46d4dfdbd
src/nodes/door.lua
src/nodes/door.lua
local Gamestate = require 'vendor/gamestate' local Tween = require 'vendor/tween' local anim8 = require 'vendor/anim8' local sound = require 'vendor/TEsound' local Door = {} Door.__index = Door function Door.new(node, collider) local door = {} setmetatable(door, Door) door.level = node.properties.level --if you can go to a level, setup collision detection --otherwise, it's just a location reference if door.level then door.player_touched = false door.bb = collider:addRectangle(node.x, node.y, node.width, node.height) door.bb.node = door collider:setPassive(door.bb) end door.instant = node.properties.instant door.warpin = node.properties.warpin door.button = node.properties.button and node.properties.button or 'UP' door.to = node.properties.to door.height = node.height door.width = node.width door.node = node door.hideable = node.properties.hideable == 'true' -- generic support for hidden doors if door.hideable then door.hidden = true door.sprite = love.graphics.newImage('images/' .. node.properties.sprite .. '.png') door.sprite_width = tonumber( node.properties.sprite_width ) door.sprite_height = tonumber( node.properties.sprite_height ) door.grid = anim8.newGrid( door.sprite_width, door.sprite_height, door.sprite:getWidth(), door.sprite:getHeight()) door.animode = node.properties.animode and node.properties.animode or 'once' door.anispeed = node.properties.anispeed and tonumber( node.properties.anispeed ) or 1 door.aniframes = node.properties.aniframes and node.properties.aniframes or '1,1' door.animation = anim8.newAnimation(door.animode, door.grid(door.aniframes), door.anispeed) door.position_hidden = { x = node.x + ( node.properties.offset_hidden_x and tonumber( node.properties.offset_hidden_x ) or 0 ), y = node.y + ( node.properties.offset_hidden_y and tonumber( node.properties.offset_hidden_y ) or 0 ) } door.position_shown = { x = node.x + ( node.properties.offset_shown_x and tonumber( node.properties.offset_shown_x ) or 0 ), y = node.y + ( node.properties.offset_shown_y and tonumber( node.properties.offset_shown_y ) or 0 ) } door.position = deepcopy(door.position_hidden) door.movetime = node.properties.movetime and tonumber(node.properties.movetime) or 1 end return door end function Door:switch(player) local _, _, _, wy2 = self.bb:bbox() local _, _, _, py2 = player.bb:bbox() if player.currently_held and player.currently_held.unuse then player.currently_held:unuse('sound_off') end self.player_touched = false if math.abs(wy2 - py2) > 10 or player.jumping then return end local level = Gamestate.get(self.level) local current = Gamestate.currentState() if current == level then level.player.position = { -- Copy, or player position corrupts entrance data x = level.doors[ self.to ].x + level.doors[ self.to ].node.width / 2 - level.player.width / 2, y = level.doors[ self.to ].y + level.doors[ self.to ].node.height - level.player.height } return end if self.level == 'overworld' then Gamestate.switch(self.level, self.to) else Gamestate.switch(self.level, self.to) end end function Door:collide(node) if self.hideable and self.hidden then return end if not node.isPlayer then return end if self.instant then self:switch(node) end end function Door:keypressed( button, player) if player.freeze or player.dead then return end if self.hideable and self.hidden then return end if button == self.button then self:switch(player) end end -- everything below this is required for hidden doors function Door:show() if self.hideable and self.hidden then self.hidden = false sound.playSfx( 'reveal' ) Tween.start( self.movetime, self.position, self.position_shown ) end end function Door:hide() if self.hideable and not self.hidden then self.hidden = true sound.playSfx( 'unreveal' ) Tween.start( self.movetime, self.position, self.position_hidden ) end end function Door:update(dt) if self.animation then self.animation:update(dt) end end function Door:draw() if not self.hideable then return end self.animation:draw(self.sprite, self.position.x, self.position.y) end return Door
local Gamestate = require 'vendor/gamestate' local Tween = require 'vendor/tween' local anim8 = require 'vendor/anim8' local sound = require 'vendor/TEsound' local Door = {} Door.__index = Door function Door.new(node, collider) local door = {} setmetatable(door, Door) door.level = node.properties.level --if you can go to a level, setup collision detection --otherwise, it's just a location reference if door.level then door.player_touched = false door.bb = collider:addRectangle(node.x, node.y, node.width, node.height) door.bb.node = door collider:setPassive(door.bb) end door.instant = node.properties.instant door.warpin = node.properties.warpin door.button = node.properties.button and node.properties.button or 'UP' door.to = node.properties.to door.height = node.height door.width = node.width door.node = node door.hideable = node.properties.hideable == 'true' -- generic support for hidden doors if door.hideable then door.hidden = true door.sprite = love.graphics.newImage('images/' .. node.properties.sprite .. '.png') door.sprite_width = tonumber( node.properties.sprite_width ) door.sprite_height = tonumber( node.properties.sprite_height ) door.grid = anim8.newGrid( door.sprite_width, door.sprite_height, door.sprite:getWidth(), door.sprite:getHeight()) door.animode = node.properties.animode and node.properties.animode or 'once' door.anispeed = node.properties.anispeed and tonumber( node.properties.anispeed ) or 1 door.aniframes = node.properties.aniframes and node.properties.aniframes or '1,1' door.animation = anim8.newAnimation(door.animode, door.grid(door.aniframes), door.anispeed) door.position_hidden = { x = node.x + ( node.properties.offset_hidden_x and tonumber( node.properties.offset_hidden_x ) or 0 ), y = node.y + ( node.properties.offset_hidden_y and tonumber( node.properties.offset_hidden_y ) or 0 ) } door.position_shown = { x = node.x + ( node.properties.offset_shown_x and tonumber( node.properties.offset_shown_x ) or 0 ), y = node.y + ( node.properties.offset_shown_y and tonumber( node.properties.offset_shown_y ) or 0 ) } door.position = deepcopy(door.position_hidden) door.movetime = node.properties.movetime and tonumber(node.properties.movetime) or 1 end return door end function Door:switch(player) local _, _, _, wy2 = self.bb:bbox() local _, _, _, py2 = player.bb:bbox() if player.currently_held and player.currently_held.unuse then player.currently_held:unuse('sound_off') elseif player.currently_held then player:drop() end self.player_touched = false if math.abs(wy2 - py2) > 10 or player.jumping then return end local level = Gamestate.get(self.level) local current = Gamestate.currentState() if current == level then level.player.position = { -- Copy, or player position corrupts entrance data x = level.doors[ self.to ].x + level.doors[ self.to ].node.width / 2 - level.player.width / 2, y = level.doors[ self.to ].y + level.doors[ self.to ].node.height - level.player.height } return end if self.level == 'overworld' then Gamestate.switch(self.level, self.to) else Gamestate.switch(self.level, self.to) end end function Door:collide(node) if self.hideable and self.hidden then return end if not node.isPlayer then return end if self.instant then self:switch(node) end end function Door:keypressed( button, player) if player.freeze or player.dead then return end if self.hideable and self.hidden then return end if button == self.button then self:switch(player) end end -- everything below this is required for hidden doors function Door:show() if self.hideable and self.hidden then self.hidden = false sound.playSfx( 'reveal' ) Tween.start( self.movetime, self.position, self.position_shown ) end end function Door:hide() if self.hideable and not self.hidden then self.hidden = true sound.playSfx( 'unreveal' ) Tween.start( self.movetime, self.position, self.position_hidden ) end end function Door:update(dt) if self.animation then self.animation:update(dt) end end function Door:draw() if not self.hideable then return end self.animation:draw(self.sprite, self.position.x, self.position.y) end return Door
fixed pot holding bug
fixed pot holding bug
Lua
mit
hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-server-lua
1469877b1eefc7fabfe32a36070330e62bbef892
tools/biosnoop.lua
tools/biosnoop.lua
#!/usr/bin/env bcc-lua --[[ Copyright 2016 GitHub, Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local program = [[ #include <uapi/linux/ptrace.h> #include <linux/blkdev.h> struct val_t { u32 pid; char name[TASK_COMM_LEN]; }; struct data_t { u32 pid; u64 rwflag; u64 delta; u64 sector; u64 len; u64 ts; char disk_name[DISK_NAME_LEN]; char name[TASK_COMM_LEN]; }; BPF_HASH(start, struct request *); BPF_HASH(infobyreq, struct request *, struct val_t); BPF_PERF_OUTPUT(events); // cache PID and comm by-req int trace_pid_start(struct pt_regs *ctx, struct request *req) { struct val_t val = {}; if (bpf_get_current_comm(&val.name, sizeof(val.name)) == 0) { val.pid = bpf_get_current_pid_tgid(); infobyreq.update(&req, &val); } return 0; } // time block I/O int trace_req_start(struct pt_regs *ctx, struct request *req) { u64 ts; ts = bpf_ktime_get_ns(); start.update(&req, &ts); return 0; } // output int trace_req_completion(struct pt_regs *ctx, struct request *req) { u64 *tsp, delta; u32 *pidp = 0; struct val_t *valp; struct data_t data ={}; u64 ts; // fetch timestamp and calculate delta tsp = start.lookup(&req); if (tsp == 0) { // missed tracing issue return 0; } ts = bpf_ktime_get_ns(); data.delta = ts - *tsp; data.ts = ts / 1000; valp = infobyreq.lookup(&req); if (valp == 0) { data.len = req->__data_len; strcpy(data.name,"?"); } else { data.pid = valp->pid; data.len = req->__data_len; data.sector = req->__sector; bpf_probe_read(&data.name, sizeof(data.name), valp->name); bpf_probe_read(&data.disk_name, sizeof(data.disk_name), req->rq_disk->disk_name); } if (req->cmd_flags & REQ_WRITE) { data.rwflag=1; } else { data.rwflag=0; } events.perf_submit(ctx,&data,sizeof(data)); start.delete(&req); infobyreq.delete(&req); return 0; } ]] local ffi = require("ffi") return function(BPF, utils) local bpf = BPF:new{text=program} bpf:attach_kprobe{event="blk_account_io_start", fn_name="trace_pid_start"} bpf:attach_kprobe{event="blk_start_request", fn_name="trace_req_start"} bpf:attach_kprobe{event="blk_mq_start_request", fn_name="trace_req_start"} bpf:attach_kprobe{event="blk_account_io_completion", fn_name="trace_req_completion"} print("%-14s %-14s %-6s %-7s %-2s %-9s %-7s %7s" % {"TIME(s)", "COMM", "PID", "DISK", "T", "SECTOR", "BYTES", "LAT(ms)"}) local rwflg = "" local start_ts = 0 local prev_ts = 0 local delta = 0 local function print_event(cpu, event) local val = -1 local event_pid = event.pid local event_delta = tonumber(event.delta) local event_sector = tonumber(event.sector) local event_len = tonumber(event.len) local event_ts = tonumber(event.ts) local event_disk_name = ffi.string(event.disk_name) local event_name = ffi.string(event.name) if event.rwflag == 1 then rwflg = "W" end if event.rwflag == 0 then rwflg = "R" end if not event_name:match("%?") then val = event_sector end if start_ts == 0 then prev_ts = start_ts end if start_ts == 1 then delta = delta + (event_ts - prev_ts) end print("%-14.9f %-14.14s %-6s %-7s %-2s %-9s %-7s %7.2f" % { delta / 1000000, event_name, event_pid, event_disk_name, rwflg, val, event_len, event_delta / 1000000}) prev_ts = event_ts start_ts = 1 end local TASK_COMM_LEN = 16 -- linux/sched.h local DISK_NAME_LEN = 32 -- linux/genhd.h bpf:get_table("events"):open_perf_buffer(print_event, [[ struct { uint32_t pid; uint64_t rwflag; uint64_t delta; uint64_t sector; uint64_t len; uint64_t ts; char disk_name[$]; char name[$]; } ]], {DISK_NAME_LEN, TASK_COMM_LEN}, 64) bpf:kprobe_poll_loop() end
#!/usr/bin/env bcc-lua --[[ Copyright 2016 GitHub, Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local program = [[ #include <uapi/linux/ptrace.h> #include <linux/blkdev.h> struct val_t { u32 pid; char name[TASK_COMM_LEN]; }; struct data_t { u32 pid; u64 rwflag; u64 delta; u64 sector; u64 len; u64 ts; char disk_name[DISK_NAME_LEN]; char name[TASK_COMM_LEN]; }; BPF_HASH(start, struct request *); BPF_HASH(infobyreq, struct request *, struct val_t); BPF_PERF_OUTPUT(events); // cache PID and comm by-req int trace_pid_start(struct pt_regs *ctx, struct request *req) { struct val_t val = {}; if (bpf_get_current_comm(&val.name, sizeof(val.name)) == 0) { val.pid = bpf_get_current_pid_tgid(); infobyreq.update(&req, &val); } return 0; } // time block I/O int trace_req_start(struct pt_regs *ctx, struct request *req) { u64 ts; ts = bpf_ktime_get_ns(); start.update(&req, &ts); return 0; } // output int trace_req_completion(struct pt_regs *ctx, struct request *req) { u64 *tsp, delta; u32 *pidp = 0; struct val_t *valp; struct data_t data ={}; u64 ts; // fetch timestamp and calculate delta tsp = start.lookup(&req); if (tsp == 0) { // missed tracing issue return 0; } ts = bpf_ktime_get_ns(); data.delta = ts - *tsp; data.ts = ts / 1000; valp = infobyreq.lookup(&req); if (valp == 0) { data.len = req->__data_len; strcpy(data.name,"?"); } else { data.pid = valp->pid; data.len = req->__data_len; data.sector = req->__sector; bpf_probe_read(&data.name, sizeof(data.name), valp->name); bpf_probe_read(&data.disk_name, sizeof(data.disk_name), req->rq_disk->disk_name); } /* * The following deals with a kernel version change (in mainline 4.7, although * it may be backported to earlier kernels) with how block request write flags * are tested. We handle both pre- and post-change versions here. Please avoid * kernel version tests like this as much as possible: they inflate the code, * test, and maintenance burden. */ #ifdef REQ_WRITE data.rwflag = !!(req->cmd_flags & REQ_WRITE); #elif defined(REQ_OP_SHIFT) data.rwflag = !!((req->cmd_flags >> REQ_OP_SHIFT) == REQ_OP_WRITE); #else data.rwflag = !!((req->cmd_flags & REQ_OP_MASK) == REQ_OP_WRITE); #endif events.perf_submit(ctx,&data,sizeof(data)); start.delete(&req); infobyreq.delete(&req); return 0; } ]] local ffi = require("ffi") return function(BPF, utils) local bpf = BPF:new{text=program} bpf:attach_kprobe{event="blk_account_io_start", fn_name="trace_pid_start"} bpf:attach_kprobe{event="blk_start_request", fn_name="trace_req_start"} bpf:attach_kprobe{event="blk_mq_start_request", fn_name="trace_req_start"} bpf:attach_kprobe{event="blk_account_io_completion", fn_name="trace_req_completion"} print("%-14s %-14s %-6s %-7s %-2s %-9s %-7s %7s" % {"TIME(s)", "COMM", "PID", "DISK", "T", "SECTOR", "BYTES", "LAT(ms)"}) local rwflg = "" local start_ts = 0 local prev_ts = 0 local delta = 0 local function print_event(cpu, event) local val = -1 local event_pid = event.pid local event_delta = tonumber(event.delta) local event_sector = tonumber(event.sector) local event_len = tonumber(event.len) local event_ts = tonumber(event.ts) local event_disk_name = ffi.string(event.disk_name) local event_name = ffi.string(event.name) if event.rwflag == 1 then rwflg = "W" end if event.rwflag == 0 then rwflg = "R" end if not event_name:match("%?") then val = event_sector end if start_ts == 0 then prev_ts = start_ts end if start_ts == 1 then delta = delta + (event_ts - prev_ts) end print("%-14.9f %-14.14s %-6s %-7s %-2s %-9s %-7s %7.2f" % { delta / 1000000, event_name, event_pid, event_disk_name, rwflg, val, event_len, event_delta / 1000000}) prev_ts = event_ts start_ts = 1 end local TASK_COMM_LEN = 16 -- linux/sched.h local DISK_NAME_LEN = 32 -- linux/genhd.h bpf:get_table("events"):open_perf_buffer(print_event, [[ struct { uint32_t pid; uint64_t rwflag; uint64_t delta; uint64_t sector; uint64_t len; uint64_t ts; char disk_name[$]; char name[$]; } ]], {DISK_NAME_LEN, TASK_COMM_LEN}, 64) bpf:kprobe_poll_loop() end
Port fix of biosnoop to the Lua version
Port fix of biosnoop to the Lua version
Lua
apache-2.0
mcaleavya/bcc,mcaleavya/bcc,iovisor/bcc,brendangregg/bcc,iovisor/bcc,brendangregg/bcc,tuxology/bcc,brendangregg/bcc,mcaleavya/bcc,tuxology/bcc,iovisor/bcc,brendangregg/bcc,mcaleavya/bcc,iovisor/bcc,iovisor/bcc,tuxology/bcc,tuxology/bcc,tuxology/bcc,mcaleavya/bcc,brendangregg/bcc
59aef367cd8942299d0d96205cb778280135bb06
mods/forceload/init.lua
mods/forceload/init.lua
local _pts = minetest.pos_to_string function minetest.pos_to_string(pos) if not pos then return "(-,-,-)" end return _pts(pos) end -- Makes sure that force load areas are handled correctly function ForceloadManager(filetoopen, hide_file_errors) local blocks = {} if filetoopen ~= nil then local file = io.open(filetoopen, "r") if file then local table = minetest.deserialize(file:read("*all")) file:close() if type(table) == "table" then blocks = table end elseif not hide_file_errors then minetest.log("error", "File "..filetoopen.." does not exist!") end end for i = 1, #blocks do if not minetest.forceload_block(blocks[i]) then minetest.log("error", "Failed to load block " .. minetest.pos_to_string(blocks[i])) end end return { _blocks = blocks, load = function(self, pos) if minetest.forceload_block(pos) then table.insert(self._blocks, vector.new(pos)) return true end minetest.log("error", "Failed to load block " .. minetest.pos_to_string(pos)) return false end, unload = function(self, pos) for i = 1, #self._blocks do if vector.equals(pos, self._blocks[i]) then minetest.forceload_free_block(pos) table.remove(self._blocks, i) return true end end return false end, save = function(self, filename) local file = io.open(filename, "w") if file then file:write(minetest.serialize(self._blocks)) file:close() end end, verify = function(self) return self:verify_each(function(pos, block) local name = "ignore" if block ~= nil then name = block.name end if name == "ignore" then if not pos.last or elapsed_time > pos.last + 15 then pos.last = elapsed_time if not minetest.forceload_block(pos) then minetest.log("error", "Failed to force load " .. minetest.pos_to_string(pos)) pos.remove = true end end return false elseif name == "forceload:anchor" then pos.last = elapsed_time return true else minetest.log("error", minetest.pos_to_string(pos) .. " shouldn't be loaded") pos.remove = true return false end end) end, verify_each = function(self, func) local not_loaded = {} for i = 1, #self._blocks do local res = minetest.get_node(self._blocks[i]) if not func(self._blocks[i], res) then --[[table.insert(not_loaded, { pos = self._blocks[i], i = i, b = res })]]-- end end return not_loaded end, clean = function(self) local i = 1 while i <= #self._blocks do if self._blocks[i].remove then minetest.forceload_free_block(self._blocks[i]) table.remove(self._blocks, i) else i = i + 1 end end end } end local flm = ForceloadManager(minetest.get_worldpath().."/flm.json", true) minetest.register_privilege("forceload", "Allows players to use forceload block anchors") minetest.register_node("forceload:anchor",{ description = "Block Anchor", walkable = false, tiles = {"forceload_anchor.png"}, groups = {cracky = 3, oddly_breakable_by_hand = 2}, after_destruct = function(pos) flm:unload(pos) flm:save(minetest.get_worldpath().."/flm.json") end, after_place_node = function(pos, placer) if not minetest.check_player_privs(placer:get_player_name(), {forceload = true}) then minetest.chat_send_player(placer:get_player_name(), "The forceload privilege is required to do that.") elseif flm:load(pos) then flm:save(minetest.get_worldpath().."/flm.json") return end minetest.set_node(pos, {name="air"}) return true end }) minetest.register_craft({ output = "forceload:anchor", recipe = { {"default:mese_crystal", "default:mese_crystal", "default:mese_crystal"}, {"default:mese_crystal", "wool:blue", "default:mese_crystal"}, {"default:mese_crystal", "default:mese_crystal", "default:mese_crystal"} } }) local elapsed_time = 0 local count = 0 minetest.register_globalstep(function(dtime) count = count + dtime elapsed_time = elapsed_time + dtime if count > 5 then count = 0 --print("Verifying...") flm:verify() flm:clean() end end)
local _pts = minetest.pos_to_string function minetest.pos_to_string(pos) if not pos then return "(-,-,-)" end return _pts(pos) end local elapsed_time = 0 -- Makes sure that force load areas are handled correctly function ForceloadManager(filetoopen, hide_file_errors) local blocks = {} if filetoopen ~= nil then local file = io.open(filetoopen, "r") if file then local table = minetest.deserialize(file:read("*all")) file:close() if type(table) == "table" then blocks = table end elseif not hide_file_errors then minetest.log("error", "File "..filetoopen.." does not exist!") end end for i = 1, #blocks do if not minetest.forceload_block(blocks[i]) then minetest.log("error", "Failed to load block " .. minetest.pos_to_string(blocks[i])) end end return { _blocks = blocks, load = function(self, pos) if minetest.forceload_block(pos) then table.insert(self._blocks, vector.new(pos)) return true end minetest.log("error", "Failed to load block " .. minetest.pos_to_string(pos)) return false end, unload = function(self, pos) for i = 1, #self._blocks do if vector.equals(pos, self._blocks[i]) then minetest.forceload_free_block(pos) table.remove(self._blocks, i) return true end end return false end, save = function(self, filename) local file = io.open(filename, "w") if file then file:write(minetest.serialize(self._blocks)) file:close() end end, verify = function(self) return self:verify_each(function(pos, block) local name = "ignore" if block ~= nil then name = block.name end if name == "ignore" then if not pos.last or elapsed_time > pos.last + 15 then pos.last = elapsed_time if not minetest.forceload_block(pos) then minetest.log("error", "Failed to force load " .. minetest.pos_to_string(pos)) pos.remove = true end end return false elseif name == "forceload:anchor" then pos.last = elapsed_time return true else minetest.log("error", minetest.pos_to_string(pos) .. " shouldn't be loaded") pos.remove = true return false end end) end, verify_each = function(self, func) local not_loaded = {} for i = 1, #self._blocks do local res = minetest.get_node(self._blocks[i]) if not func(self._blocks[i], res) then --[[table.insert(not_loaded, { pos = self._blocks[i], i = i, b = res })]]-- end end return not_loaded end, clean = function(self) local i = 1 while i <= #self._blocks do if self._blocks[i].remove then minetest.forceload_free_block(self._blocks[i]) table.remove(self._blocks, i) else i = i + 1 end end end } end local flm = ForceloadManager(minetest.get_worldpath().."/flm.json", true) minetest.register_privilege("forceload", "Allows players to use forceload block anchors") minetest.register_node("forceload:anchor",{ description = "Block Anchor", walkable = false, tiles = {"forceload_anchor.png"}, groups = {cracky = 3, oddly_breakable_by_hand = 2}, after_destruct = function(pos) flm:unload(pos) flm:save(minetest.get_worldpath().."/flm.json") end, after_place_node = function(pos, placer) if not minetest.check_player_privs(placer:get_player_name(), {forceload = true}) then minetest.chat_send_player(placer:get_player_name(), "The forceload privilege is required to do that.") elseif flm:load(pos) then flm:save(minetest.get_worldpath().."/flm.json") return end minetest.set_node(pos, {name="air"}) return true end }) minetest.register_craft({ output = "forceload:anchor", recipe = { {"default:mese_crystal", "default:mese_crystal", "default:mese_crystal"}, {"default:mese_crystal", "wool:blue", "default:mese_crystal"}, {"default:mese_crystal", "default:mese_crystal", "default:mese_crystal"} } }) local count = 0 minetest.register_globalstep(function(dtime) count = count + dtime elapsed_time = elapsed_time + dtime if count > 5 then count = 0 --print("Verifying...") flm:verify() flm:clean() end end)
fix global var in forceload
fix global var in forceload
Lua
unlicense
MinetestForFun/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Ombridride/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,paly2/minetest-minetestforfun-server,Coethium/server-minetestforfun,crabman77/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Coethium/server-minetestforfun,Ombridride/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,crabman77/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,paly2/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Coethium/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server
192e57cc758640c64d011c90fe625700240672f8
plugins/set.lua
plugins/set.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 return false end local function set_value(msg, name, value) if (not name or not value) then return lang_text('errorTryAgain') end local hash = get_variables_hash(msg) if hash then redis:hset(hash, name, value) return name .. lang_text('saved') end end local function set_media(msg, name) if not name then return lang_text('errorTryAgain') end local hash = get_variables_hash(msg) if hash then redis:hset(hash, 'waiting', name) return lang_text('sendMedia') end end local function callback(extra, success, result) if success and result then local file if extra.media == 'photo' then file = 'data/savedmedia/' .. extra.hash .. extra.name .. '.jpg' elseif extra.media == 'audio' then file = 'data/savedmedia/' .. extra.hash .. extra.name .. '.ogg' end file = file:gsub(':', '.') print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) redis:hset(extra.hash, extra.name, file) redis:hdel(extra.hash, 'waiting') print(file) send_large_msg(extra.receiver, lang_text('mediaSaved') .. extra.hash .. ' - ' .. extra.name .. ' - ' .. extra.receiver) else send_large_msg(extra.receiver, lang_text('mediaSaved') .. extra.hash .. ' - ' .. extra.name .. ' - ' .. extra.receiver) end end local function run(msg, matches) local hash = get_variables_hash(msg) if msg.media then if hash then local name = redis:hget(hash, 'waiting') if name then if is_momod(msg) then if msg.media.type == 'photo' then return load_photo(msg.id, callback, { receiver = get_receiver(msg), hash = hash, name = name, media = msg.media.type }) elseif msg.media.type == 'audio' then return load_document(msg.id, callback, { receiver = get_receiver(msg), hash = hash, name = name, media = msg.media.type }) end else return lang_text('require_mod') end end return else return lang_text('nothingToSet') end end if matches[1]:lower() == 'cancel' or matches[1]:lower() == 'sasha annulla' or matches[1]:lower() == 'annulla' then if is_momod(msg) then redis:hdel(hash, 'waiting') return lang_text('cancelled') else return lang_text('require_mod') end elseif matches[1]:lower() == 'setmedia' or matches[1]:lower() == 'sasha setta media' or matches[1]:lower() == 'setta media' then if is_momod(msg) then local name = string.sub(matches[2]:lower(), 1, 50) return set_media(msg, name) else return lang_text('require_mod') end elseif matches[1]:lower() == 'set' or matches[1]:lower() == 'sasha setta' or matches[1]:lower() == 'setta' then if string.match(matches[3], '[Aa][Uu][Tt][Oo][Ee][Xx][Ee][Cc]') then return lang_text('autoexecDenial') end if is_momod(msg) then local name = string.sub(matches[2]:lower(), 1, 50) local value = string.sub(matches[3], 1, 4096) return set_value(msg, name, value) else return lang_text('require_mod') end end end local function pre_process(msg) if not msg.text and msg.media then msg.text = '[' .. msg.media.type .. ']' end return msg end return { description = "SET", patterns = { "^[#!/]([Ss][Ee][Tt]) ([^%s]+) (.+)$", "^[#!/]([Ss][Ee][Tt][Mm][Ee][Dd][Ii][Aa]) ([^%s]+)$", "^[#!/]([Cc][Aa][Nn][Cc][Ee][Ll])$", "%[(photo)%]", "%[(audio)%]", -- set "^([Ss][Aa][Ss][Hh][Aa] [Ss][Ee][Tt][Tt][Aa]) ([^%s]+) (.+)$", "^([Ss][Ee][Tt][Tt][Aa]) ([^%s]+) (.+)$", -- setmedia "^([Ss][Aa][Ss][Hh][Aa] [Ss][Ee][Tt][Tt][Aa] [Mm][Ee][Dd][Ii][Aa]) ([^%s]+)$", "^([Ss][Ee][Tt][Tt][Aa] [Mm][Ee][Dd][Ii][Aa]) ([^%s]+)$", -- cancel "^([Ss][Aa][Ss][Hh][Aa] [Aa][Nn][Nn][Uu][Ll][Ll][Aa])$", "^([Aa][Nn][Nn][Uu][Ll][Ll][Aa])$", }, run = run, min_rank = 1 -- usage -- MOD -- (#set|[sasha] setta) <var_name> <text> -- (#setmedia|[sasha] setta media) <var_name> -- (#cancel|[sasha] annulla) }
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 return false end local function set_value(msg, name, value) if (not name or not value) then return lang_text('errorTryAgain') end local hash = get_variables_hash(msg) if hash then redis:hset(hash, name, value) return name .. lang_text('saved') end end local function set_media(msg, name) if not name then return lang_text('errorTryAgain') end local hash = get_variables_hash(msg) if hash then redis:hset(hash, 'waiting', name) return lang_text('sendMedia') end end local function callback(extra, success, result) if success and result then local file if extra.media == 'photo' then file = 'data/savedmedia/' .. extra.hash .. extra.name .. '.jpg' elseif extra.media == 'audio' then file = 'data/savedmedia/' .. extra.hash .. extra.name .. '.ogg' end file = file:gsub(':', '.') print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) redis:hset(extra.hash, extra.name, file) redis:hdel(extra.hash, 'waiting') print(file) send_large_msg(extra.receiver, lang_text('mediaSaved')) else send_large_msg(extra.receiver, lang_text('errorDownloading') .. extra.hash .. ' - ' .. extra.name .. ' - ' .. extra.receiver) end end local function run(msg, matches) local hash = get_variables_hash(msg) if msg.media then if hash then local name = redis:hget(hash, 'waiting') if name then if is_momod(msg) then if msg.media.type == 'photo' then return load_photo(msg.id, callback, { receiver = get_receiver(msg), hash = hash, name = name, media = msg.media.type }) elseif msg.media.type == 'audio' then return load_document(msg.id, callback, { receiver = get_receiver(msg), hash = hash, name = name, media = msg.media.type }) end else return lang_text('require_mod') end end return else return lang_text('nothingToSet') end end if matches[1]:lower() == 'cancel' or matches[1]:lower() == 'sasha annulla' or matches[1]:lower() == 'annulla' then if is_momod(msg) then redis:hdel(hash, 'waiting') return lang_text('cancelled') else return lang_text('require_mod') end elseif matches[1]:lower() == 'setmedia' or matches[1]:lower() == 'sasha setta media' or matches[1]:lower() == 'setta media' then if is_momod(msg) then local name = string.sub(matches[2]:lower(), 1, 50) return set_media(msg, name) else return lang_text('require_mod') end elseif matches[1]:lower() == 'set' or matches[1]:lower() == 'sasha setta' or matches[1]:lower() == 'setta' then if string.match(matches[3], '[Aa][Uu][Tt][Oo][Ee][Xx][Ee][Cc]') then return lang_text('autoexecDenial') end if is_momod(msg) then local name = string.sub(matches[2]:lower(), 1, 50) local value = string.sub(matches[3], 1, 4096) return set_value(msg, name, value) else return lang_text('require_mod') end end end local function pre_process(msg) if not msg.text and msg.media then msg.text = '[' .. msg.media.type .. ']' end return msg end return { description = "SET", patterns = { "^[#!/]([Ss][Ee][Tt]) ([^%s]+) (.+)$", "^[#!/]([Ss][Ee][Tt][Mm][Ee][Dd][Ii][Aa]) ([^%s]+)$", "^[#!/]([Cc][Aa][Nn][Cc][Ee][Ll])$", "%[(photo)%]", "%[(audio)%]", -- set "^([Ss][Aa][Ss][Hh][Aa] [Ss][Ee][Tt][Tt][Aa]) ([^%s]+) (.+)$", "^([Ss][Ee][Tt][Tt][Aa]) ([^%s]+) (.+)$", -- setmedia "^([Ss][Aa][Ss][Hh][Aa] [Ss][Ee][Tt][Tt][Aa] [Mm][Ee][Dd][Ii][Aa]) ([^%s]+)$", "^([Ss][Ee][Tt][Tt][Aa] [Mm][Ee][Dd][Ii][Aa]) ([^%s]+)$", -- cancel "^([Ss][Aa][Ss][Hh][Aa] [Aa][Nn][Nn][Uu][Ll][Ll][Aa])$", "^([Aa][Nn][Nn][Uu][Ll][Ll][Aa])$", }, run = run, min_rank = 1 -- usage -- MOD -- (#set|[sasha] setta) <var_name> <text> -- (#setmedia|[sasha] setta media) <var_name> -- (#cancel|[sasha] annulla) }
fix setmedia
fix setmedia
Lua
agpl-3.0
xsolinsx/AISasha
2521e2e8f5eea7e4351830b316e19b2f24cc2f7f
config/micro/plugins/fzf/fzf.lua
config/micro/plugins/fzf/fzf.lua
VERSION = "1.0.5" function fzf() if TermEmuSupported then local err = RunTermEmulator("fzf", false, true, "fzf.fzfOutput") if err ~= nil then messenger:Error(err) end else local output, err = RunInteractiveShell("fzf", false, true) if err ~= nil then messenger:Error(err) else local strings = import("strings") CurView():Open(strings.TrimSpace(output)) end end end function fzfOutput(output) local strings = import("strings") CurView():Open(strings.TrimSpace(output)) end MakeCommand("fzf", "fzf.fzf", 0)
VERSION = "1.0.5" function fzf() if TermEmuSupported then local err = RunTermEmulator("fzf", false, true, "fzf.fzfOutput") if err ~= nil then messenger:Error(err) end else local output, err = RunInteractiveShell("fzf", false, true) if err ~= nil then messenger:Error(err) else fzfOutput(output) end end end function fzfOutput(output) local strings = import("strings") output = strings.TrimSpace(output) if output ~= "" then CurView():Open(output) end end MakeCommand("fzf", "fzf.fzf", 0)
Fixed issue where aborting fzf would unload the currently loaded file
Fixed issue where aborting fzf would unload the currently loaded file
Lua
mit
scottbilas/dotfiles,scottbilas/dotfiles,scottbilas/dotfiles,scottbilas/dotfiles
64305139aeee8f47e675fa2e310d5a4244751d68
core/sile.lua
core/sile.lua
SILE = {} SILE.version = "0.9.5-unreleased" SILE.utilities = require("core/utilities") SU = SILE.utilities SILE.inputs = {} SILE.Commands = {} SILE.debugFlags = {} SILE.nodeMakers = {} SILE.tokenizers = {} loadstring = loadstring or load -- 5.3 compatibility if not unpack then unpack = table.unpack end -- 5.3 compatibility std = require("std") lfs = require("lfs") if (os.getenv("SILE_COVERAGE")) then require("luacov") end SILE.documentState = std.object {} SILE.scratch = {} SILE.length = require("core/length") require("core/parserbits") require("core/measurements") require("core/baseclass") SILE.nodefactory = require("core/nodefactory") require("core/settings") require("core/inputs-texlike") require("core/inputs-xml") require("core/inputs-common") require("core/papersizes") require("core/colorparser") require("core/pagebuilder") require("core/typesetter") require("core/hyphenator-liang") require("core/languages") require("core/font") SILE.frameParser = require("core/frameparser") SILE.linebreak = require("core/break") require("core/frame") SILE.init = function() if not SILE.backend then if pcall(function () require("justenoughharfbuzz") end) then SILE.backend = "libtexpdf" else SU.error("libtexpdf backend not available!") end end if SILE.backend == "libtexpdf" then require("core/harfbuzz-shaper") require("core/libtexpdf-output") end if SILE.dolua then _, err = pcall(SILE.dolua) if err then error(err) end end end SILE.require = function (dependency, pathprefix) local file = SILE.resolveFile(dependency..".lua", pathprefix) if file then return require(file:gsub(".lua$","")) end return require(dependency) end SILE.parseArguments = function() local parser = std.optparse ("SILE "..SILE.version..[[ Usage: sile [options] file.sil|file.xml The SILE typesetter reads a single input file in either SIL or XML format to generate an output in PDF format. The output will be writted to the same name as the input file with the extention changed to .pdf. Options: -b, --backend=VALUE choose an alternative output backend -d, --debug=VALUE debug SILE's operation -e, --evaluate=VALUE evaluate some Lua code before processing file -o, --output=[FILE] explicitly set output file name -I, --include=[FILE] include a class or SILE file before processing input --help display this help, then exit --version display version information, then exit ]]) parser:on ('--', parser.finished) _G.unparsed, _G.opts = parser:parse(_G.arg) -- Turn slashes around in the event we get passed a path from a Windows shell if _G.unparsed[1] then SILE.masterFilename = _G.unparsed[1]:gsub("\\", "/") end SILE.debugFlags = {} if opts.backend then SILE.backend = opts.backend end if opts.debug then for k,v in ipairs(std.string.split(opts.debug, ",")) do SILE.debugFlags[v] = 1 end end if opts.evaluate then SILE.dolua,err = loadstring(opts.evaluate) if err then SU.error(err) end end if opts.output then SILE.outputFilename = opts.output end if opts.include then SILE.preamble = opts.include end end function SILE.initRepl () SILE._repl = require 'repl.console' local has_linenoise = pcall(require, 'linenoise') if has_linenoise then SILE._repl:loadplugin 'linenoise' else -- XXX check that we're not receiving input from a non-tty local has_rlwrap = os.execute('which rlwrap >/dev/null 2>/dev/null') == 0 if has_rlwrap and not os.getenv 'LUA_REPL_RLWRAP' then local command = 'LUA_REPL_RLWRAP=1 rlwrap' local index = 0 while arg[index - 1] do index = index - 1 end while arg[index] do command = string.format('%s %q', command, arg[index]) index = index + 1 end os.execute(command) return end end SILE._repl:loadplugin 'history' SILE._repl:loadplugin 'completion' SILE._repl:loadplugin 'autoreturn' SILE._repl:loadplugin 'rcfile' end function SILE.repl() if not SILE._repl then SILE.initRepl() end SILE._repl:run() end function SILE.readFile(filename) SILE.currentlyProcessingFile = filename filename = SILE.resolveFile(filename) if not filename then SU.error("Could not find file") end if lfs.attributes(filename).mode ~= "file" then SU.error(filename.." isn't a file, it's a "..lfs.attributes(filename).mode.."!") end local file, err = io.open(filename) if not file then print("Could not open "..filename..": "..err) return end io.write("<"..filename..">\n") -- Sniff first few bytes local sniff = file:read("*l") or "" file:seek("set", 0) local inputsOrder = {} for n in pairs(SILE.inputs) do if SILE.inputs[n].order then table.insert(inputsOrder, n) end end table.sort(inputsOrder,function(a,b) return SILE.inputs[a].order < SILE.inputs[b].order end) for i = 1,#inputsOrder do local input = SILE.inputs[inputsOrder[i]] if input.appropriate(filename, sniff) then input.process(filename) return end end SU.error("No input processor available for "..filename.." (should never happen)",1) end local function file_exists (filename) local file = io.open(filename, "r") if file ~= nil then return io.close(file) else return false end end -- Sort through possible places files could be function SILE.resolveFile(filename, pathprefix) local candidates = {} -- Start with the raw file name as given prefixed with a path if requested if pathprefix then candidates[#candidates+1] = std.io.catfile(pathprefix, filename) end -- Also check the raw file name without a path candidates[#candidates+1] = filename -- Iterate through the directory of the master file, the SILE_PATH variable, and the current directory -- Check for prefixed paths first, then the plain path in that fails if SILE.masterFilename then local dirname = SILE.masterFilename:match("(.-)[^%/]+$") for path in SU.gtoke(dirname..";"..tostring(os.getenv("SILE_PATH")), ";") do if path.string and path.string ~= "nil" then if pathprefix then candidates[#candidates+1] = std.io.catfile(path.string, pathprefix, filename) end candidates[#candidates+1] = std.io.catfile(path.string, filename) end end end -- Return the first candidate that exists, also checking the .sil suffix for i, v in pairs(candidates) do if file_exists(v) then return v end if file_exists(v..".sil") then return v .. ".sil" end end -- If we got here then no files existed even resembling the requested one return nil end function SILE.call(cmd, options, content) SILE.currentCommand = content if not SILE.Commands[cmd] then SU.error("Unknown command "..cmd) end SILE.Commands[cmd](options or {}, content or {}) end return SILE
SILE = {} SILE.version = "0.9.5-unreleased" SILE.utilities = require("core/utilities") SU = SILE.utilities SILE.inputs = {} SILE.Commands = {} SILE.debugFlags = {} SILE.nodeMakers = {} SILE.tokenizers = {} loadstring = loadstring or load -- 5.3 compatibility if not unpack then unpack = table.unpack end -- 5.3 compatibility std = require("std") lfs = require("lfs") if (os.getenv("SILE_COVERAGE")) then require("luacov") end SILE.documentState = std.object {} SILE.scratch = {} SILE.length = require("core/length") require("core/parserbits") require("core/measurements") require("core/baseclass") SILE.nodefactory = require("core/nodefactory") require("core/settings") require("core/inputs-texlike") require("core/inputs-xml") require("core/inputs-common") require("core/papersizes") require("core/colorparser") require("core/pagebuilder") require("core/typesetter") require("core/hyphenator-liang") require("core/languages") require("core/font") SILE.frameParser = require("core/frameparser") SILE.linebreak = require("core/break") require("core/frame") SILE.init = function() if not SILE.backend then if pcall(function () require("justenoughharfbuzz") end) then SILE.backend = "libtexpdf" else SU.error("libtexpdf backend not available!") end end if SILE.backend == "libtexpdf" then require("core/harfbuzz-shaper") require("core/libtexpdf-output") end if SILE.dolua then _, err = pcall(SILE.dolua) if err then error(err) end end end SILE.require = function (dependency, pathprefix) local file = SILE.resolveFile(dependency..".lua", pathprefix) if file then return require(file:gsub(".lua$","")) end if pathprefix then local status, lib = pcall(require, std.io.catfile(pathprefix, dependency)) return status and lib or require(dependency) end return require(dependency) end SILE.parseArguments = function() local parser = std.optparse ("SILE "..SILE.version..[[ Usage: sile [options] file.sil|file.xml The SILE typesetter reads a single input file in either SIL or XML format to generate an output in PDF format. The output will be writted to the same name as the input file with the extention changed to .pdf. Options: -b, --backend=VALUE choose an alternative output backend -d, --debug=VALUE debug SILE's operation -e, --evaluate=VALUE evaluate some Lua code before processing file -o, --output=[FILE] explicitly set output file name -I, --include=[FILE] include a class or SILE file before processing input --help display this help, then exit --version display version information, then exit ]]) parser:on ('--', parser.finished) _G.unparsed, _G.opts = parser:parse(_G.arg) -- Turn slashes around in the event we get passed a path from a Windows shell if _G.unparsed[1] then SILE.masterFilename = _G.unparsed[1]:gsub("\\", "/") end SILE.debugFlags = {} if opts.backend then SILE.backend = opts.backend end if opts.debug then for k,v in ipairs(std.string.split(opts.debug, ",")) do SILE.debugFlags[v] = 1 end end if opts.evaluate then SILE.dolua,err = loadstring(opts.evaluate) if err then SU.error(err) end end if opts.output then SILE.outputFilename = opts.output end if opts.include then SILE.preamble = opts.include end end function SILE.initRepl () SILE._repl = require 'repl.console' local has_linenoise = pcall(require, 'linenoise') if has_linenoise then SILE._repl:loadplugin 'linenoise' else -- XXX check that we're not receiving input from a non-tty local has_rlwrap = os.execute('which rlwrap >/dev/null 2>/dev/null') == 0 if has_rlwrap and not os.getenv 'LUA_REPL_RLWRAP' then local command = 'LUA_REPL_RLWRAP=1 rlwrap' local index = 0 while arg[index - 1] do index = index - 1 end while arg[index] do command = string.format('%s %q', command, arg[index]) index = index + 1 end os.execute(command) return end end SILE._repl:loadplugin 'history' SILE._repl:loadplugin 'completion' SILE._repl:loadplugin 'autoreturn' SILE._repl:loadplugin 'rcfile' end function SILE.repl() if not SILE._repl then SILE.initRepl() end SILE._repl:run() end function SILE.readFile(filename) SILE.currentlyProcessingFile = filename filename = SILE.resolveFile(filename) if not filename then SU.error("Could not find file") end if lfs.attributes(filename).mode ~= "file" then SU.error(filename.." isn't a file, it's a "..lfs.attributes(filename).mode.."!") end local file, err = io.open(filename) if not file then print("Could not open "..filename..": "..err) return end io.write("<"..filename..">\n") -- Sniff first few bytes local sniff = file:read("*l") or "" file:seek("set", 0) local inputsOrder = {} for n in pairs(SILE.inputs) do if SILE.inputs[n].order then table.insert(inputsOrder, n) end end table.sort(inputsOrder,function(a,b) return SILE.inputs[a].order < SILE.inputs[b].order end) for i = 1,#inputsOrder do local input = SILE.inputs[inputsOrder[i]] if input.appropriate(filename, sniff) then input.process(filename) return end end SU.error("No input processor available for "..filename.." (should never happen)",1) end local function file_exists (filename) local file = io.open(filename, "r") if file ~= nil then return io.close(file) else return false end end -- Sort through possible places files could be function SILE.resolveFile(filename, pathprefix) local candidates = {} -- Start with the raw file name as given prefixed with a path if requested if pathprefix then candidates[#candidates+1] = std.io.catfile(pathprefix, filename) end -- Also check the raw file name without a path candidates[#candidates+1] = filename -- Iterate through the directory of the master file, the SILE_PATH variable, and the current directory -- Check for prefixed paths first, then the plain path in that fails if SILE.masterFilename then local dirname = SILE.masterFilename:match("(.-)[^%/]+$") for path in SU.gtoke(dirname..";"..tostring(os.getenv("SILE_PATH")), ";") do if path.string and path.string ~= "nil" then if pathprefix then candidates[#candidates+1] = std.io.catfile(path.string, pathprefix, filename) end candidates[#candidates+1] = std.io.catfile(path.string, filename) end end end -- Return the first candidate that exists, also checking the .sil suffix for i, v in pairs(candidates) do if file_exists(v) then return v end if file_exists(v..".sil") then return v .. ".sil" end end -- If we got here then no files existed even resembling the requested one return nil end function SILE.call(cmd, options, content) SILE.currentCommand = content if not SILE.Commands[cmd] then SU.error("Unknown command "..cmd) end SILE.Commands[cmd](options or {}, content or {}) end return SILE
Fix requires path by protecting the one that might fail
Fix requires path by protecting the one that might fail
Lua
mit
simoncozens/sile,simoncozens/sile,neofob/sile,alerque/sile,simoncozens/sile,alerque/sile,alerque/sile,alerque/sile,simoncozens/sile,neofob/sile,neofob/sile,neofob/sile
99e0da52b65e7549a660616b111e294c313315e3
frontend/ui/reader/readerdictionary.lua
frontend/ui/reader/readerdictionary.lua
require "ui/device" require "ui/widget/dict" ReaderDictionary = EventListener:new{} function ReaderDictionary:init() JSON = require("JSON") end function ReaderDictionary:onLookupWord(word) self:stardictLookup(word) end function ReaderDictionary:stardictLookup(word) DEBUG("lookup word:", word) if word then -- strip punctuation characters around selected word word = string.gsub(word, "^%p+", '') word = string.gsub(word, "%p+$", '') DEBUG("stripped word:", word) -- escape quotes and other funny characters in word local std_out = io.popen("./sdcv --utf8-input --utf8-output -nj "..("%q"):format(word), "r") local results_str = std_out:read("*all") if results_str then --DEBUG("result str:", word, results_str) local ok, results = pcall(JSON.decode, JSON, results_str) --DEBUG("lookup result table:", word, results) self:showDict(results) end end end function ReaderDictionary:showDict(results) if results and results[1] then DEBUG("showing quick lookup dictionary window") UIManager:show(DictQuickLookup:new{ ui = self.ui, dialog = self.dialog, results = results, dictionary = self.default_dictionary, width = Screen:getWidth() - scaleByDPI(120), height = Screen:getHeight()*0.43, }) end end function ReaderDictionary:onUpdateDefaultDict(dict) DEBUG("make default dictionary:", dict) self.default_dictionary = dict end function ReaderDictionary:onReadSettings(config) self.default_dictionary = config:readSetting("default_dictionary") end function ReaderDictionary:onCloseDocument() self.ui.doc_settings:saveSetting("default_dictionary", self.default_dictionary) end
require "ui/device" require "ui/widget/dict" ReaderDictionary = EventListener:new{} function ReaderDictionary:init() JSON = require("JSON") end function ReaderDictionary:onLookupWord(word) self:stardictLookup(word) end function ReaderDictionary:stardictLookup(word) DEBUG("lookup word:", word) if word then -- strip punctuation characters around selected word word = string.gsub(word, "^%p+", '') word = string.gsub(word, "%p+$", '') DEBUG("stripped word:", word) -- escape quotes and other funny characters in word local std_out = io.popen("./sdcv --utf8-input --utf8-output -nj "..("%q"):format(word), "r") local results_str = nil if std_out then results_str = std_out:read("*all") end if results_str then --DEBUG("result str:", word, results_str) local ok, results = pcall(JSON.decode, JSON, results_str) --DEBUG("lookup result table:", word, results) self:showDict(results) end end end function ReaderDictionary:showDict(results) if results and results[1] then DEBUG("showing quick lookup dictionary window") UIManager:show(DictQuickLookup:new{ ui = self.ui, dialog = self.dialog, results = results, dictionary = self.default_dictionary, width = Screen:getWidth() - scaleByDPI(120), height = Screen:getHeight()*0.43, }) end end function ReaderDictionary:onUpdateDefaultDict(dict) DEBUG("make default dictionary:", dict) self.default_dictionary = dict end function ReaderDictionary:onReadSettings(config) self.default_dictionary = config:readSetting("default_dictionary") end function ReaderDictionary:onCloseDocument() self.ui.doc_settings:saveSetting("default_dictionary", self.default_dictionary) end
check json output before decoding This should fix #332.
check json output before decoding This should fix #332.
Lua
agpl-3.0
apletnev/koreader,robert00s/koreader,poire-z/koreader,koreader/koreader,chrox/koreader,noname007/koreader,pazos/koreader,mihailim/koreader,lgeek/koreader,mwoz123/koreader,frankyifei/koreader,Hzj-jie/koreader,NiLuJe/koreader,ashhher3/koreader,NiLuJe/koreader,houqp/koreader,NickSavage/koreader,ashang/koreader,Markismus/koreader,Frenzie/koreader,Frenzie/koreader,poire-z/koreader,koreader/koreader,chihyang/koreader
b944e2fb58b130a01ec70dd7314ed540e970f58a
samples/bin2png.lua
samples/bin2png.lua
require 'cutorch' require 'image' d = 70 h = 370 w = 1226 print('Writing left.png') left = torch.FloatTensor(torch.FloatStorage('left.bin')):view(1, d, h, w):cuda() _, left_ = left:min(2) image.save('left.png', left_[1]:float():div(d)) print('Writing right.png') right = torch.FloatTensor(torch.FloatStorage('right.bin')):view(1, d, h, w):cuda() _, right_ = right:min(2) image.save('right.png', right_[1]:float():div(d)) print('Writing disp.png') disp = torch.FloatTensor(torch.FloatStorage('disp.bin')):view(1, 1, h, w) image.save('disp.png', disp[1]:div(d))
require 'cutorch' require 'image' d = 70 h = 370 w= 1226 function fromfile(fname) local size = io.open(fname):seek('end') local x = torch.FloatTensor(torch.FloatStorage(fname, false, size / 4)) local nan_mask = x:ne(x) x[nan_mask] = 1e38 return x end print('Writing left.png') left = fromfile('left.bin'):view(1, d, h, w) _, left_ = left:min(2) image.save('left.png', left_[1]:float():div(d)) print('Writing right.png') right = fromfile('right.bin'):view(1, d, h, w) _, right_ = right:min(2) image.save('right.png', right_[1]:float():div(d)) print('Writing disp.png') disp = fromfile('disp.bin'):view(1, 1, h, w) image.save('disp.png', disp[1]:div(d))
Fix bin2png to work with new torch
Fix bin2png to work with new torch
Lua
bsd-2-clause
jzbontar/mc-cnn,jzbontar/mc-cnn,jzbontar/mc-cnn
d2e2bdca71ce15a7b7cc86304a6c32d6a034aa9d
state/play.lua
state/play.lua
--[[-- PLAY STATE ---- Play the game. --]]-- local st = GameState.new() local math_floor, math_max, math_min = math.floor, math.max, math.min -- Camera local Camera = require 'lib.hump.camera' local vector = require 'lib.hump.vector' -- Time Manager local TimeManager = require 'pud.time.TimeManager' local TimedObject = require 'pud.time.TimedObject' -- map builder local LevelDirector = require 'pud.level.LevelDirector' -- level view local TileLevelView = require 'pud.level.TileLevelView' -- events local OpenDoorEvent = require 'pud.event.OpenDoorEvent' local GameStartEvent = require 'pud.event.GameStartEvent' local MapUpdateFinishedEvent = require 'pud.event.MapUpdateFinishedEvent' -- some defaults local TILESIZE = 32 local MAPW, MAPH = 100, 100 local _mapTileW, _mapTileH function st:init() end function st:enter() self._timeManager = TimeManager() local player = TimedObject() local dragon = TimedObject() local ifrit = TimedObject() player.name = 'Player' dragon.name = 'Dragon' ifrit.name = 'Ifrit' local test = false function player:OpenDoorEvent(e) if test then print('player') print(tostring(e)) end end function dragon:onEvent(e) if test then print('dragon') print(tostring(e)) end end function ifrit:onEvent(e) if test then print('ifrit') print(tostring(e)) end end function player:getSpeed(ap) return 1 end function player:doAction(ap) GameEvent:notify(GameStartEvent(), 234, ap) return 2 end function dragon:getSpeed(ap) return 1.03 end function dragon:doAction(ap) return 5 end function ifrit:getSpeed(ap) return 1.27 end function ifrit:doAction(ap) GameEvent:push(OpenDoorEvent(self.name)) return 2 end local function ifritOpenDoorCB(e) ifrit:onEvent(e) end GameEvent:register(player, OpenDoorEvent) GameEvent:register(ifritOpenDoorCB, OpenDoorEvent) GameEvent:register(dragon, GameStartEvent) self._timeManager:register(player, 3) self._timeManager:register(dragon, 3) self._timeManager:register(ifrit, 3) self:_generateMap(true) end function st:_generateMap(fromFile) if self._map then self._map:destroy() end local builder if fromFile then local FileMapBuilder = require 'pud.level.FileMapBuilder' local mapfiles = {'test'} local mapfile = mapfiles[math.random(1,#mapfiles)] builder = FileMapBuilder(mapfile) else local SimpleGridMapBuilder = require 'pud.level.SimpleGridMapBuilder' builder = SimpleGridMapBuilder(MAPW,MAPH, 10,10, 20,35) end self._map = LevelDirector:generateStandard(builder) builder:destroy() print(self._map) local w, h = self._map:getSize() _mapTileW, _mapTileH = w*TILESIZE, h*TILESIZE if self._view then self._view:destroy() end self._view = TileLevelView(w, h) self._view:registerEvents() self._startVector = vector(math_floor(_mapTileW/2), math_floor(_mapTileH/2)) if not self._cam then self._cam = Camera(self._startVector, 1) end self:_correctCam() end local _accum = 0 local _count = 0 local TICK = 0.01 function st:update(dt) _accum = _accum + dt if _accum > TICK then _count = _count + 1 _accum = _accum - TICK self._timeManager:tick() if _count % 100 == 0 and self._map then GameEvent:push(MapUpdateFinishedEvent(self._map)) end end end function st:draw() self._cam:predraw() self._view:draw() self._cam:postdraw() end function st:leave() self._timeManager:destroy() self._timeManager = nil self._view:destroy() self._view = nil end -- correct the camera values after moving function st:_correctCam() local wmin = math_floor((WIDTH/2)/self._cam.zoom + 0.5) local wmax = _mapTileW - wmin if self._cam.pos.x > wmax then self._cam.pos.x = wmax end if self._cam.pos.x < wmin then self._cam.pos.x = wmin end local hmin = math_floor((HEIGHT/2)/self._cam.zoom + 0.5) local hmax = _mapTileH - hmin if self._cam.pos.y > hmax then self._cam.pos.y = hmax end if self._cam.pos.y < hmin then self._cam.pos.y = hmin end end function st:keypressed(key, unicode) switch(key) { escape = function() love.event.push('q') end, m = function() self:_generateMap() end, f = function() self:_generateMap(true) end, -- camera left = function() if not self._cam then return end local amt = vector(-TILESIZE/self._cam.zoom, 0) self._cam:translate(amt) self:_correctCam() end, right = function() if not self._cam then return end local amt = vector(TILESIZE/self._cam.zoom, 0) self._cam:translate(amt) self:_correctCam() end, up = function() if not self._cam then return end local amt = vector(0, -TILESIZE/self._cam.zoom) self._cam:translate(amt) self:_correctCam() end, down = function() if not self._cam then return end local amt = vector(0, TILESIZE/self._cam.zoom) self._cam:translate(amt) self:_correctCam() end, pageup = function() if not self._cam then return end self._cam.zoom = math_max(0.25, self._cam.zoom * (1/2)) self:_correctCam() end, pagedown = function() if not self._cam then return end self._cam.zoom = math_min(1, self._cam.zoom * 2) self:_correctCam() end, home = function() if not self._cam then return end self._cam.zoom = 1 self._cam.pos = self._startVector self:_correctCam() end, } end return st
--[[-- PLAY STATE ---- Play the game. --]]-- local st = GameState.new() local math_floor, math_max, math_min = math.floor, math.max, math.min -- Camera local Camera = require 'lib.hump.camera' local vector = require 'lib.hump.vector' -- Time Manager local TimeManager = require 'pud.time.TimeManager' local TimedObject = require 'pud.time.TimedObject' -- map builder local LevelDirector = require 'pud.level.LevelDirector' -- level view local TileLevelView = require 'pud.level.TileLevelView' -- events local OpenDoorEvent = require 'pud.event.OpenDoorEvent' local GameStartEvent = require 'pud.event.GameStartEvent' local MapUpdateFinishedEvent = require 'pud.event.MapUpdateFinishedEvent' -- some defaults local TILESIZE = 32 local MAPW, MAPH = 100, 100 local _mapTileW, _mapTileH function st:init() end function st:enter() self._keyDelay, self._keyInterval = love.keyboard.getKeyRepeat() love.keyboard.setKeyRepeat(200, 25) self._timeManager = TimeManager() local player = TimedObject() local dragon = TimedObject() local ifrit = TimedObject() player.name = 'Player' dragon.name = 'Dragon' ifrit.name = 'Ifrit' local test = false function player:OpenDoorEvent(e) if test then print('player') print(tostring(e)) end end function dragon:onEvent(e) if test then print('dragon') print(tostring(e)) end end function ifrit:onEvent(e) if test then print('ifrit') print(tostring(e)) end end function player:getSpeed(ap) return 1 end function player:doAction(ap) GameEvent:notify(GameStartEvent(), 234, ap) return 2 end function dragon:getSpeed(ap) return 1.03 end function dragon:doAction(ap) return 5 end function ifrit:getSpeed(ap) return 1.27 end function ifrit:doAction(ap) GameEvent:push(OpenDoorEvent(self.name)) return 2 end local function ifritOpenDoorCB(e) ifrit:onEvent(e) end GameEvent:register(player, OpenDoorEvent) GameEvent:register(ifritOpenDoorCB, OpenDoorEvent) GameEvent:register(dragon, GameStartEvent) self._timeManager:register(player, 3) self._timeManager:register(dragon, 3) self._timeManager:register(ifrit, 3) self:_generateMap(true) end function st:_generateMap(fromFile) if self._map then self._map:destroy() end local builder if fromFile then local FileMapBuilder = require 'pud.level.FileMapBuilder' local mapfiles = {'test'} local mapfile = mapfiles[math.random(1,#mapfiles)] builder = FileMapBuilder(mapfile) else local SimpleGridMapBuilder = require 'pud.level.SimpleGridMapBuilder' builder = SimpleGridMapBuilder(MAPW,MAPH, 10,10, 20,35) end self._map = LevelDirector:generateStandard(builder) builder:destroy() print(self._map) local w, h = self._map:getSize() _mapTileW, _mapTileH = w*TILESIZE, h*TILESIZE if self._view then self._view:destroy() end self._view = TileLevelView(w, h) self._view:registerEvents() local startX = math_floor(w/2+0.5)*TILESIZE - math_floor(TILESIZE/2) local startY = math_floor(h/2+0.5)*TILESIZE - math_floor(TILESIZE/2) self._startVector = vector(startX, startY) if not self._cam then self._cam = Camera(self._startVector, 1) end self._cam.pos = self._startVector self:_correctCam() end local _accum = 0 local _count = 0 local TICK = 0.01 function st:update(dt) _accum = _accum + dt if _accum > TICK then _count = _count + 1 _accum = _accum - TICK self._timeManager:tick() if _count % 100 == 0 and self._map then GameEvent:push(MapUpdateFinishedEvent(self._map)) end end end function st:draw() self._cam:predraw() self._view:draw() self._cam:postdraw() -- temporary center square local size = self._cam.zoom * TILESIZE local x = math_floor(WIDTH/2)-math_floor(size/2) local y = math_floor(HEIGHT/2)-math_floor(size/2) love.graphics.setColor(0, 1, 0) love.graphics.rectangle('line', x, y, size, size) end function st:leave() love.keyboard.setKeyRepeat(self._keyDelay, self._keyInterval) self._timeManager:destroy() self._timeManager = nil self._view:destroy() self._view = nil end -- correct the camera values after moving function st:_correctCam() local wmin = math_floor(TILESIZE/2) local wmax = _mapTileW - wmin if self._cam.pos.x > wmax then self._cam.pos.x = wmax end if self._cam.pos.x < wmin then self._cam.pos.x = wmin end local hmin = wmin local hmax = _mapTileH - hmin if self._cam.pos.y > hmax then self._cam.pos.y = hmax end if self._cam.pos.y < hmin then self._cam.pos.y = hmin end end function st:keypressed(key, unicode) switch(key) { escape = function() love.event.push('q') end, m = function() self:_generateMap() end, f = function() self:_generateMap(true) end, -- camera left = function() if not self._cam then return end local amt = vector(-TILESIZE/self._cam.zoom, 0) self._cam:translate(amt) self:_correctCam() end, right = function() if not self._cam then return end local amt = vector(TILESIZE/self._cam.zoom, 0) self._cam:translate(amt) self:_correctCam() end, up = function() if not self._cam then return end local amt = vector(0, -TILESIZE/self._cam.zoom) self._cam:translate(amt) self:_correctCam() end, down = function() if not self._cam then return end local amt = vector(0, TILESIZE/self._cam.zoom) self._cam:translate(amt) self:_correctCam() end, pageup = function() if not self._cam then return end self._cam.zoom = math_max(0.25, self._cam.zoom * (1/2)) self:_correctCam() end, pagedown = function() if not self._cam then return end self._cam.zoom = math_min(1, self._cam.zoom * 2) self:_correctCam() end, home = function() if not self._cam then return end self._cam.zoom = 1 self._cam.pos = self._startVector self:_correctCam() end, } end return st
add keydelay and fix startX and startY
add keydelay and fix startX and startY
Lua
mit
scottcs/wyx
672d29fbcc3ff31b7459ef4486da7f2f42037a24
frontend/device/wakeupmgr.lua
frontend/device/wakeupmgr.lua
--[[-- RTC wakeup interface. Many devices can schedule hardware wakeups with a real time clock alarm. On embedded devices this can typically be easily manipulated by the user through `/sys/class/rtc/rtc0/wakealarm`. Some, like the Kobo Aura H2O, can only schedule wakeups through ioctl. See @{ffi.rtc} for implementation details. See also: <https://linux.die.net/man/4/rtc>. --]] local RTC = require("ffi/rtc") local logger = require("logger") --[[-- WakeupMgr base class. @table WakeupMgr --]] local WakeupMgr = { dev_rtc = "/dev/rtc0", -- RTC device _task_queue = {}, -- Table with epoch at which to schedule the task and the function to be scheduled. } --[[-- Initiate a WakeupMgr instance. @usage local WakeupMgr = require("device/wakeupmgr") local wakeup_mgr = WakeupMgr:new{ -- The default is `/dev/rtc0`, but some devices have more than one RTC. -- You might therefore need to use `/dev/rtc1`, etc. dev_rtc = "/dev/rtc0", } --]] function WakeupMgr:new(o) o = o or {} setmetatable(o, self) self.__index = self if o.init then o:init() end return o end --[[-- Add a task to the queue. @todo Group by type to avoid useless wakeups. For example, maintenance, sync, and shutdown. I'm not sure if the distinction between maintenance and sync makes sense but it's wifi on vs. off. --]] function WakeupMgr:addTask(seconds_from_now, callback) if not type(seconds_from_now) == "number" and not type(callback) == "function" then return end local epoch = RTC:secondsFromNowToEpoch(seconds_from_now) logger.info("WakeupMgr: scheduling wakeup for:", seconds_from_now, epoch) local old_upcoming_task = (self._task_queue[1] or {}).epoch table.insert(self._task_queue, { epoch = epoch, callback = callback, }) --- @todo Binary insert? This table should be so small that performance doesn't matter. -- It might be useful to have that available as a utility function regardless. table.sort(self._task_queue, function(a, b) return a.epoch < b.epoch end) local new_upcoming_task = self._task_queue[1].epoch if not old_upcoming_task or (new_upcoming_task < old_upcoming_task) then self:setWakeupAlarm(self._task_queue[1].epoch) end end --[[-- Remove task from queue. This method removes a task by either index, scheduled time or callback. @int idx Task queue index. Mainly useful within this module. @int epoch The epoch for when this task is scheduled to wake up. Normally the preferred method for outside callers. @int callback A scheduled callback function. Store a reference for use with anonymous functions. --]] function WakeupMgr:removeTask(idx, epoch, callback) if not type(idx) == "number" and not type(epoch) == "number" and not type(callback) == "function" then return end if #self._task_queue < 1 then return end for k, v in ipairs(self._task_queue) do if k == idx or epoch == v.epoch or callback == v.callback then table.remove(self._task_queue, k) return true end end end --[[-- Execute wakeup action. This method should be called by the device resume logic in case of a scheduled wakeup. It checks if the wakeup was scheduled by us using @{validateWakeupAlarmByProximity}, executes the task, and schedules the next wakeup if any. @treturn bool --]] function WakeupMgr:wakeupAction() if #self._task_queue > 0 then local task = self._task_queue[1] if self:validateWakeupAlarmByProximity(task.epoch) then task.callback() self:removeTask(1) if self._task_queue[1] then -- Set next scheduled wakeup, if any. self:setWakeupAlarm(self._task_queue[1].epoch) end return true else return false end end end --[[-- Set wakeup alarm. Simple wrapper for @{ffi.rtc.setWakeupAlarm}. --]] function WakeupMgr:setWakeupAlarm(epoch, enabled) return RTC:setWakeupAlarm(epoch, enabled) end --[[-- Unset wakeup alarm. Simple wrapper for @{ffi.rtc.unsetWakeupAlarm}. --]] function WakeupMgr:unsetWakeupAlarm() return RTC:unsetWakeupAlarm() end --[[-- Get wakealarm as set by us. Simple wrapper for @{ffi.rtc.getWakeupAlarm}. --]] function WakeupMgr:getWakeupAlarm() return RTC:getWakeupAlarm() end --[[-- Get RTC wakealarm from system. Simple wrapper for @{ffi.rtc.getWakeupAlarm}. --]] function WakeupMgr:getWakeupAlarmSys() return RTC:getWakeupAlarmSys() end --[[-- Validate wakeup alarm. Checks if we set the alarm. Simple wrapper for @{ffi.rtc.validateWakeupAlarmByProximity}. --]] function WakeupMgr:validateWakeupAlarmByProximity() return RTC:validateWakeupAlarmByProximity() end --[[-- Check if a wakeup is scheduled. Simple wrapper for @{ffi.rtc.isWakeupAlarmScheduled}. --]] function WakeupMgr:isWakeupAlarmScheduled() local wakeup_scheduled = RTC:isWakeupAlarmScheduled() logger.dbg("isWakeupAlarmScheduled", wakeup_scheduled) return wakeup_scheduled end return WakeupMgr
--[[-- RTC wakeup interface. Many devices can schedule hardware wakeups with a real time clock alarm. On embedded devices this can typically be easily manipulated by the user through `/sys/class/rtc/rtc0/wakealarm`. Some, like the Kobo Aura H2O, can only schedule wakeups through ioctl. See @{ffi.rtc} for implementation details. See also: <https://linux.die.net/man/4/rtc>. --]] local RTC = require("ffi/rtc") local logger = require("logger") --[[-- WakeupMgr base class. @table WakeupMgr --]] local WakeupMgr = { dev_rtc = "/dev/rtc0", -- RTC device _task_queue = {}, -- Table with epoch at which to schedule the task and the function to be scheduled. } --[[-- Initiate a WakeupMgr instance. @usage local WakeupMgr = require("device/wakeupmgr") local wakeup_mgr = WakeupMgr:new{ -- The default is `/dev/rtc0`, but some devices have more than one RTC. -- You might therefore need to use `/dev/rtc1`, etc. dev_rtc = "/dev/rtc0", } --]] function WakeupMgr:new(o) o = o or {} setmetatable(o, self) self.__index = self if o.init then o:init() end return o end --[[-- Add a task to the queue. @todo Group by type to avoid useless wakeups. For example, maintenance, sync, and shutdown. I'm not sure if the distinction between maintenance and sync makes sense but it's wifi on vs. off. --]] function WakeupMgr:addTask(seconds_from_now, callback) if not type(seconds_from_now) == "number" and not type(callback) == "function" then return end local epoch = RTC:secondsFromNowToEpoch(seconds_from_now) logger.info("WakeupMgr: scheduling wakeup for:", seconds_from_now, epoch) local old_upcoming_task = (self._task_queue[1] or {}).epoch table.insert(self._task_queue, { epoch = epoch, callback = callback, }) --- @todo Binary insert? This table should be so small that performance doesn't matter. -- It might be useful to have that available as a utility function regardless. table.sort(self._task_queue, function(a, b) return a.epoch < b.epoch end) local new_upcoming_task = self._task_queue[1].epoch if not old_upcoming_task or (new_upcoming_task < old_upcoming_task) then self:setWakeupAlarm(self._task_queue[1].epoch) end end --[[-- Remove task from queue. This method removes a task by either index, scheduled time or callback. @int idx Task queue index. Mainly useful within this module. @int epoch The epoch for when this task is scheduled to wake up. Normally the preferred method for outside callers. @int callback A scheduled callback function. Store a reference for use with anonymous functions. --]] function WakeupMgr:removeTask(idx, epoch, callback) if not type(idx) == "number" and not type(epoch) == "number" and not type(callback) == "function" then return end if #self._task_queue < 1 then return end for k, v in ipairs(self._task_queue) do if k == idx or epoch == v.epoch or callback == v.callback then table.remove(self._task_queue, k) return true end end end --[[-- Execute wakeup action. This method should be called by the device resume logic in case of a scheduled wakeup. It checks if the wakeup was scheduled by us using @{validateWakeupAlarmByProximity}, executes the task, and schedules the next wakeup if any. @treturn bool --]] function WakeupMgr:wakeupAction() if #self._task_queue > 0 then local task = self._task_queue[1] if self:validateWakeupAlarmByProximity(task.epoch) then task.callback() self:removeTask(1) if self._task_queue[1] then -- Set next scheduled wakeup, if any. self:setWakeupAlarm(self._task_queue[1].epoch) end return true else return false end end end --[[-- Set wakeup alarm. Simple wrapper for @{ffi.rtc.setWakeupAlarm}. --]] function WakeupMgr:setWakeupAlarm(epoch, enabled) return RTC:setWakeupAlarm(epoch, enabled) end --[[-- Unset wakeup alarm. Simple wrapper for @{ffi.rtc.unsetWakeupAlarm}. --]] function WakeupMgr:unsetWakeupAlarm() return RTC:unsetWakeupAlarm() end --[[-- Get wakealarm as set by us. Simple wrapper for @{ffi.rtc.getWakeupAlarm}. --]] function WakeupMgr:getWakeupAlarm() return RTC:getWakeupAlarm() end --[[-- Get RTC wakealarm from system. Simple wrapper for @{ffi.rtc.getWakeupAlarm}. --]] function WakeupMgr:getWakeupAlarmSys() return RTC:getWakeupAlarmSys() end --[[-- Validate wakeup alarm. Checks if we set the alarm. Simple wrapper for @{ffi.rtc.validateWakeupAlarmByProximity}. --]] function WakeupMgr:validateWakeupAlarmByProximity(task_alarm_epoch, proximity) return RTC:validateWakeupAlarmByProximity(task_alarm_epoch, proximity) end --[[-- Check if a wakeup is scheduled. Simple wrapper for @{ffi.rtc.isWakeupAlarmScheduled}. --]] function WakeupMgr:isWakeupAlarmScheduled() local wakeup_scheduled = RTC:isWakeupAlarmScheduled() logger.dbg("isWakeupAlarmScheduled", wakeup_scheduled) return wakeup_scheduled end return WakeupMgr
[fix] WakeupMgr: pass through task epoch for proximity check
[fix] WakeupMgr: pass through task epoch for proximity check
Lua
agpl-3.0
koreader/koreader,pazos/koreader,Frenzie/koreader,poire-z/koreader,poire-z/koreader,mwoz123/koreader,NiLuJe/koreader,mihailim/koreader,koreader/koreader,NiLuJe/koreader,Hzj-jie/koreader,Frenzie/koreader,Markismus/koreader
f43a9d826b6e979bbfd38d31a6edf6f46160a9c2
bin/toc2breaks.lua
bin/toc2breaks.lua
#!/usr/bin/env lua local project = os.getenv("PROJECT") local basename = arg[1] local tocfile = io.open(arg[2], "r") if not tocfile then return false end local doc = tocfile:read("*a") tocfile:close() local toc = assert(loadstring(doc))() local yaml = require("yaml") local meta = yaml.loadpath(arg[3]) local share = "https://nextcloud.alerque.com/" .. (meta.nextcloudshare and "index.php/s/" .. meta.nextcloudshare .. "/download?path=%2F&files=" or "remote.php/webdav/viachristus/" .. project .. "/") local infofile = io.open(arg[4], "w") if not infofile then return false end local infow = function (str, endpar) str = str or "" endpar = endpar and "\n" or "" infofile:write(str .. "\n" .. endpar) end infow("TITLE:") infow(meta.title, true) infow("SUBTITLE:") infow(meta.subtitle, true) for k, v in ipairs(meta.creator) do if v.role == "author" then meta.author = v.text end end infow("AUTHOR:" ) infow(meta.author, true) infow("ABSTRACT:") infow(meta.abstract, true) infow("SINGLE PDF:") local out = basename .. "-uygulama-cikti.pdf" infow(share .. out, true) infow("MEDIA:") local out = basename .. "-kare-pankart.jpg" infow(share .. out, true) local out = basename .. "-genis-pankart.jpg" infow(share .. out, true) local out = basename .. "-bant-pankart.jpg" infow(share .. out, true) local labels = {} local breaks = {} if #toc > 0 then -- Label the first chunk before we skip to the content labels[1] = toc[1].label[1] -- Drop the first TOC entry, the top of the file will be 1 table.remove(toc, 1) local lastpage = 1 breaks = { 1 } -- Get a table of major (more that 2 pages apart) TOC entries for i, tocentry in pairs(toc) do local pageno = tonumber(tocentry.pageno) if pageno > lastpage + 2 then table.insert(breaks, pageno) labels[#breaks] = tocentry.label[1] lastpage = pageno else labels[#breaks] = labels[#breaks] .. ", " .. tocentry.label[1] end end -- Convert the table to page rages suitable for pdftk for i, v in pairs(breaks) do if i ~= 1 then breaks[i-1] = breaks[i-1] .. "-" .. v - 1 end end breaks[#breaks] = breaks[#breaks] .. "-end" end -- Output a list suitable for shell script parsing for i, v in pairs(breaks) do local n = string.format("%03d", i - 1) local out = basename .. "-uygulama-cikti-" .. n .. ".pdf" -- Fieds expected by makefile to pass to pdftk print(v, out) -- Human readable info for copy/paste to the church app infow("CHUNK " .. i - 1 .. ":") infow(labels[i]) infow(share .. out, true) end infofile:close()
#!/usr/bin/env lua local project = os.getenv("PROJECT") local basename = arg[1] .. "/app/" .. arg[1] local tocfile = io.open(arg[2], "r") if not tocfile then return false end local doc = tocfile:read("*a") tocfile:close() local toc = assert(loadstring(doc))() local yaml = require("yaml") local meta = yaml.loadpath(arg[3]) local share = "https://yayinlar.viachristus.com/" local infofile = io.open(arg[4], "w") if not infofile then return false end local infow = function (str, endpar) str = str or "" endpar = endpar and "\n" or "" infofile:write(str .. "\n" .. endpar) end infow("TITLE:") infow(meta.title, true) infow("SUBTITLE:") infow(meta.subtitle, true) for k, v in ipairs(meta.creator) do if v.role == "author" then meta.author = v.text end end infow("AUTHOR:" ) infow(meta.author, true) infow("ABSTRACT:") infow(meta.abstract, true) infow("SINGLE PDF:") local out = basename .. "-uygulama-cikti.pdf" infow(share .. out, true) infow("MEDIA:") local out = basename .. "-kare-pankart.jpg" infow(share .. out, true) local out = basename .. "-genis-pankart.jpg" infow(share .. out, true) local out = basename .. "-bant-pankart.jpg" infow(share .. out, true) local labels = {} local breaks = {} if #toc > 0 then -- Label the first chunk before we skip to the content labels[1] = toc[1].label[1] -- Drop the first TOC entry, the top of the file will be 1 table.remove(toc, 1) local lastpage = 1 breaks = { 1 } -- Get a table of major (more that 2 pages apart) TOC entries for i, tocentry in pairs(toc) do local pageno = tonumber(tocentry.pageno) if pageno > lastpage + 2 then table.insert(breaks, pageno) labels[#breaks] = tocentry.label[1] lastpage = pageno else labels[#breaks] = labels[#breaks] .. ", " .. tocentry.label[1] end end -- Convert the table to page rages suitable for pdftk for i, v in pairs(breaks) do if i ~= 1 then breaks[i-1] = breaks[i-1] .. "-" .. v - 1 end end breaks[#breaks] = breaks[#breaks] .. "-end" end -- Output a list suitable for shell script parsing for i, v in pairs(breaks) do local n = string.format("%03d", i - 1) local out = basename .. "-uygulama-cikti-" .. n .. ".pdf" -- Fieds expected by makefile to pass to pdftk print(v, out) -- Human readable info for copy/paste to the church app infow("CHUNK " .. i - 1 .. ":") infow(labels[i]) infow(share .. out, true) end infofile:close()
Fix Nextcloud share link in app meta data output
Fix Nextcloud share link in app meta data output
Lua
agpl-3.0
alerque/casile,alerque/casile,alerque/casile,alerque/casile,alerque/casile
c0cafb51b39669f72783eecbebb574f9f23e7668
src/gui/Button.lua
src/gui/Button.lua
-------------------------------------------------------------------------------- -- -- -- -------------------------------------------------------------------------------- local Group = require("core.Group") local Event = require("core.Event") local UIEvent = require("gui.UIEvent") local UIObjectBase = require("gui.UIObjectBase") local ButtonAnimations = require("gui.ButtonAnimations") local Button = class(UIObjectBase, Group) --- -- Example usage -- Button can be initialized in declarative way -- Button { -- normalSprite = Sprite("normal.png"), -- activeSprite = Sprite("active.png"), -- disabledSprite = Sprite("disabled.png"), -- label = Label("Button", 200, 100, "Verdana.ttf", 24), -- onClick = function(e) print("click") end, -- animations = {ButtonAnimations.Bounce()}, -- toggle = false, -- } Button.propertyOrder = { size = 2, label = 2, layer = 3, } function Button:init(params) Group.init(self) UIObjectBase.init(self, params) assert(self.normalSprite) if table.empty(self.animations) then self:addAnimation(ButtonAnimations.Change()) end self:initEventListeners() self:setEnabled(true) self:setActive(false) end function Button:initEventListeners() self:addEventListener(Event.TOUCH_DOWN, self.onTouchDown, self) self:addEventListener(Event.TOUCH_UP, self.onTouchUp, self) self:addEventListener(Event.TOUCH_MOVE, self.onTouchMove, self) self:addEventListener(Event.TOUCH_CANCEL, self.onTouchCancel, self) end --- -- -- function Button:setNormalSprite(sprite) if self.normalSprite then self:removeChild(self.normalSprite) self.normalSprite = nil end if sprite then self:addChild(sprite) self.normalSprite = sprite end end --- -- -- function Button:setActiveSprite(sprite) if self.activeSprite then self:removeChild(self.activeSprite) self.activeSprite = nil end if sprite then self:addChild(sprite) self.activeSprite = sprite end end --- -- -- function Button:setDisabledSprite(sprite) if self.disabledSprite then self:removeChild(self.disabledSprite) self.disabledSprite = nil end if sprite then self:addChild(sprite) self.disabledSprite = sprite end end --- -- -- function Button:setSize(width, height) Group.setSize(self, width, height) if self.normalSprite then self.normalSprite:setBounds(-0.5 * width, -0.5 * height, 0, 0.5 * width, 0.5 * height, 0) end if self.activeSprite then self.activeSprite:setBounds(-0.5 * width, -0.5 * height, 0, 0.5 * width, 0.5 * height, 0) end end --- -- -- function Button:setLabel(label) if self.label then self:removeChild(self.label) self.label = nil end if label then self:addChild(label) self.label = label end end --- -- -- function Button:setEnabled(value) self.enabled = value if value then self:dispatchEvent(UIEvent.ENABLE) else self:dispatchEvent(UIEvent.DISABLE) end end --- -- -- function Button:setActive(value) self.active = value if value then self:dispatchEvent(UIEvent.DOWN) else self:dispatchEvent(UIEvent.UP) end end --- -- -- function Button:setAnimations(...) local animList = {...} if self.animations then for animCalss, anim in pairs(self.animations) do anim:setButton(nil) end end self.animations = {} for i, anim in ipairs(animList) do self:addAnimation(anim) end end --- -- -- function Button:addAnimation(animation) -- use animation class as key -- so there are only one animation of each type if not self.animations then self.animations = {} end if self.animations[animation] then self:removeAnimation(animation) end animation:setButton(self) self.animations[animation.__class] = animation end --- -- -- function Button:removeAnimation(animation) self.animations[animation]:setButton(nil) end --- -- -- function Button:onTouchDown(event) event:stop() if not self.enabled or self._touchDownIdx ~= nil then return end self._touchDownIdx = event.idx self:setActive(true) end --- -- -- function Button:onTouchMove(event) event:stop() if self._touchDownIdx ~= event.idx then return end local inside = self.normalSprite:inside(event.wx, event.wy, 0) if inside ~= self.active then self:setActive(inside) end if inside then return end self:dispatchEvent(UIEvent.CANCEL) end --- -- -- function Button:onTouchUp(event) event:stop() if self._touchDownIdx ~= event.idx then return end self._touchDownIdx = nil self:setActive(false) if not self.normalSprite:inside(event.wx, event.wy, 0) then return end if self.toggle then self:setEnabled(not self.enabled) if self.onToggle then self.onToggle(self.enabled) end else self:dispatchEvent(UIEvent.CLICK) if self.onClick then self.onClick() end end end --- -- -- function Button:onTouchCancel(event) event:stop() if self._touchDownIdx ~= event.idx then return end self._touchDownIdx = nil if not self.toggle then self:dispatchEvent(UIEvent.CANCEL) end end return Button
-------------------------------------------------------------------------------- -- -- -- -------------------------------------------------------------------------------- local Group = require("core.Group") local Event = require("core.Event") local UIEvent = require("gui.UIEvent") local UIObjectBase = require("gui.UIObjectBase") local ButtonAnimations = require("gui.ButtonAnimations") local Button = class(UIObjectBase, Group) --- -- Example usage -- Button can be initialized in declarative way -- Button { -- normalSprite = Sprite("normal.png"), -- activeSprite = Sprite("active.png"), -- disabledSprite = Sprite("disabled.png"), -- label = Label("Button", 200, 100, "Verdana.ttf", 24), -- onClick = function(e) print("click") end, -- animations = {ButtonAnimations.Bounce()}, -- toggle = false, -- } Button.propertyOrder = { size = 2, label = 2, layer = 3, } function Button:init(params) Group.init(self) UIObjectBase.init(self, params) assert(self.normalSprite) if table.empty(self.animations) then self:addAnimation(ButtonAnimations.Change()) end self:initEventListeners() self:setEnabled(true) self:setActive(false) end function Button:initEventListeners() self:addEventListener(Event.TOUCH_DOWN, self.onTouchDown, self) self:addEventListener(Event.TOUCH_UP, self.onTouchUp, self) self:addEventListener(Event.TOUCH_MOVE, self.onTouchMove, self) self:addEventListener(Event.TOUCH_CANCEL, self.onTouchCancel, self) end --- -- -- function Button:setNormalSprite(sprite) if self.normalSprite then self:removeChild(self.normalSprite) self.normalSprite = nil end if sprite then self:addChild(sprite) self.normalSprite = sprite end end --- -- -- function Button:setActiveSprite(sprite) if self.activeSprite then self:removeChild(self.activeSprite) self.activeSprite = nil end if sprite then self:addChild(sprite) self.activeSprite = sprite end end --- -- -- function Button:setDisabledSprite(sprite) if self.disabledSprite then self:removeChild(self.disabledSprite) self.disabledSprite = nil end if sprite then self:addChild(sprite) self.disabledSprite = sprite end end --- -- -- function Button:setSize(width, height) Group.setSize(self, width, height) if self.normalSprite then self.normalSprite:setBounds(-0.5 * width, -0.5 * height, 0, 0.5 * width, 0.5 * height, 0) end if self.activeSprite then self.activeSprite:setBounds(-0.5 * width, -0.5 * height, 0, 0.5 * width, 0.5 * height, 0) end end --- -- -- function Button:setLabel(label) if self.label then self:removeChild(self.label) self.label = nil end if label then self:addChild(label) self.label = label end end --- -- -- function Button:setEnabled(value) self.enabled = value if value then self:dispatchEvent(UIEvent.ENABLE) else self:dispatchEvent(UIEvent.DISABLE) end end --- -- -- function Button:setActive(value) self.active = value if value then self:dispatchEvent(UIEvent.DOWN) else self:dispatchEvent(UIEvent.UP) end end --- -- -- function Button:setAnimations(...) local animList = {...} if self.animations then for animCalss, anim in pairs(self.animations) do anim:setButton(nil) end end self.animations = {} for i, anim in ipairs(animList) do self:addAnimation(anim) end end --- -- -- function Button:addAnimation(animation) -- use animation class as key -- so there are only one animation of each type if not self.animations then self.animations = {} end if self.animations[animation] then self:removeAnimation(animation) end animation:setButton(self) self.animations[animation.__class] = animation end --- -- -- function Button:removeAnimation(animation) self.animations[animation]:setButton(nil) end --- -- -- function Button:onTouchDown(event) event:stop() if not self.enabled or self._touchDownIdx ~= nil then return end if not self.normalSprite:inside(event.wx, event.wy, 0) then return end self._touchDownIdx = event.idx self:setActive(true) end --- -- -- function Button:onTouchMove(event) event:stop() if self._touchDownIdx ~= event.idx then return end local inside = self.normalSprite:inside(event.wx, event.wy, 0) if inside ~= self.active then self:setActive(inside) end if inside then return end self:dispatchEvent(UIEvent.CANCEL) end --- -- -- function Button:onTouchUp(event) event:stop() if self._touchDownIdx ~= event.idx then return end self._touchDownIdx = nil self:setActive(false) if not self.normalSprite:inside(event.wx, event.wy, 0) then return end if self.toggle then self:setEnabled(not self.enabled) if self.onToggle then self.onToggle(self.enabled) end else self:dispatchEvent(UIEvent.CLICK) if self.onClick then self.onClick() end end end --- -- -- function Button:onTouchCancel(event) event:stop() if self._touchDownIdx ~= event.idx then return end self._touchDownIdx = nil if not self.toggle then self:dispatchEvent(UIEvent.CANCEL) end end return Button
fix button onTouchDown to take into account normal sprite size
fix button onTouchDown to take into account normal sprite size
Lua
mit
Vavius/moai-framework,Vavius/moai-framework
61efd0371ed4d524dd751a569d6f271b60eb9b6f
lua/framework/graphics/model.lua
lua/framework/graphics/model.lua
--=========== Copyright © 2018, Planimeter, All rights reserved. =============-- -- -- Purpose: -- --============================================================================-- require( "class" ) local assimp = require( "assimp" ) local ffi = require( "ffi" ) local bit = require( "bit" ) local GL = require( "opengl" ) local physfs = require( "physicsfs" ) class( "framework.graphics.model" ) local model = framework.graphics.model local function processMesh( self, mesh ) local stride = ( 3 + 3 + 3 + 2 ) local vertices = ffi.new( "GLfloat[?]", stride * mesh.mNumVertices ) for i = 0, mesh.mNumVertices - 1 do do vertices[stride * i + 0] = mesh.mVertices[i].x vertices[stride * i + 1] = mesh.mVertices[i].y vertices[stride * i + 2] = mesh.mVertices[i].z end if ( mesh.mNormals ~= nil ) then vertices[stride * i + 3] = mesh.mNormals[i].x vertices[stride * i + 4] = mesh.mNormals[i].y vertices[stride * i + 5] = mesh.mNormals[i].z end if ( mesh.mTangents ~= nil ) then vertices[stride * i + 6] = mesh.mTangents[i].x vertices[stride * i + 7] = mesh.mTangents[i].y vertices[stride * i + 8] = mesh.mTangents[i].z end if ( mesh.mTextureCoords[0] ~= nil ) then vertices[stride * i + 9] = mesh.mTextureCoords[0][i].x vertices[stride * i + 10] = mesh.mTextureCoords[0][i].y end end require( "framework.graphics.mesh" ) return framework.graphics.mesh( vertices, mesh.mNumVertices ) end local function processNode( self, node ) for i = 0, node.mNumMeshes - 1 do local mesh = self.scene.mMeshes[node.mMeshes[i]] table.insert( self.meshes, processMesh( self, mesh ) ) end for i = 0, node.mNumChildren - 1 do processNode( self, node.mChildren[i] ) end end local function PHYSFSReadProc( self, buffer, size, count ) local file = ffi.cast( "void *", self.UserData ) return physfs.PHYSFS_read( file, buffer, size, count ) end local function PHYSFSWriteProc( self, buffer, size, count ) local file = ffi.cast( "void *", self.UserData ) return physfs.PHYSFS_write( file, buffer, size, count ) end local function PHYSFSTellProc( self ) local file = ffi.cast( "void *", self.UserData ) return physfs.PHYSFS_tell( file ) end local function PHYSFSFileSizeProc( self ) local file = ffi.cast( "void *", self.UserData ) return physfs.PHYSFS_fileLength( file ) end local function PHYSFSSeekProc( self, offset, whence ) local file = ffi.cast( "void *", self.UserData ) local ret = physfs.PHYSFS_seek( file, offset ) if ( ret ~= 0 ) then return ffi.C.aiReturn_SUCCESS else -- TODO: Return ffi.C.aiReturn_OUTOFMEMORY return ffi.C.aiReturn_FAILURE end end local function PHYSFSFlushProc( self ) local file = ffi.cast( "void *", self.UserData ) physfs.PHYSFS_flush( file ) end local function PHYSFSOpenProc( self, filename, mode ) local file = ffi.new( "struct aiFile" ) file.ReadProc = PHYSFSReadProc file.WriteProc = PHYSFSWriteProc file.TellProc = PHYSFSTellProc file.FileSizeProc = PHYSFSFileSizeProc file.SeekProc = PHYSFSSeekProc file.FlushProc = PHYSFSFlushProc file.UserData = ffi.cast( "void *", physfs.PHYSFS_openRead( filename ) ) return file end local function PHYSFSCloseProc( self, file ) physfs.PHYSFS_close( ffi.cast( "void *", file.UserData ) ) end local function getPHYSFSFileIO() if ( model._fileIO ) then return model._fileIO end local fileIO = ffi.new( "struct aiFileIO" ) fileIO.OpenProc = PHYSFSOpenProc fileIO.CloseProc = PHYSFSCloseProc model._fileIO = fileIO return fileIO end function model:model( filename ) self.scene = assimp.aiImportFileEx( filename, bit.bor( ffi.C.aiProcess_CalcTangentSpace, ffi.C.aiProcess_GenNormals, ffi.C.aiProcess_Triangulate, ffi.C.aiProcess_GenUVCoords, ffi.C.aiProcess_SortByPType ), getPHYSFSFileIO() ) if ( self.scene == nil ) then error( ffi.string( assimp.aiGetErrorString() ), 3 ) end self.meshes = {} if ( self.scene.mRootNode ~= nil ) then processNode( self, self.scene.mRootNode ) end setproxy( self ) end function model:draw( x, y, r, sx, sy, ox, oy, kx, ky ) for _, mesh in ipairs( self.meshes ) do framework.graphics.draw( mesh, x, y, r, sx, sy, ox, oy, kx, ky ) end end function model:__gc() assimp.aiReleaseImport( self.scene ) end
--=========== Copyright © 2018, Planimeter, All rights reserved. =============-- -- -- Purpose: -- --============================================================================-- require( "class" ) local assimp = require( "assimp" ) local ffi = require( "ffi" ) local bit = require( "bit" ) local GL = require( "opengl" ) local physfs = require( "physicsfs" ) class( "framework.graphics.model" ) local model = framework.graphics.model local function processMesh( self, mesh ) local stride = ( 3 + 3 + 3 + 2 ) local vertices = ffi.new( "GLfloat[?]", stride * mesh.mNumVertices ) for i = 0, mesh.mNumVertices - 1 do do vertices[stride * i + 0] = mesh.mVertices[i].x vertices[stride * i + 1] = mesh.mVertices[i].y vertices[stride * i + 2] = mesh.mVertices[i].z end if ( mesh.mNormals ~= nil ) then vertices[stride * i + 3] = mesh.mNormals[i].x vertices[stride * i + 4] = mesh.mNormals[i].y vertices[stride * i + 5] = mesh.mNormals[i].z end if ( mesh.mTangents ~= nil ) then vertices[stride * i + 6] = mesh.mTangents[i].x vertices[stride * i + 7] = mesh.mTangents[i].y vertices[stride * i + 8] = mesh.mTangents[i].z end if ( mesh.mTextureCoords[0] ~= nil ) then vertices[stride * i + 9] = mesh.mTextureCoords[0][i].x vertices[stride * i + 10] = mesh.mTextureCoords[0][i].y end end require( "framework.graphics.mesh" ) return framework.graphics.mesh( vertices, mesh.mNumVertices ) end local function processNode( self, node ) for i = 0, node.mNumMeshes - 1 do local mesh = self.scene.mMeshes[node.mMeshes[i]] table.insert( self.meshes, processMesh( self, mesh ) ) end for i = 0, node.mNumChildren - 1 do processNode( self, node.mChildren[i] ) end end local function PHYSFSReadProc( self, buffer, size, count ) local file = ffi.cast( "void *", self.UserData ) return physfs.PHYSFS_read( file, buffer, size, count ) end local function PHYSFSWriteProc( self, buffer, size, count ) local file = ffi.cast( "void *", self.UserData ) return physfs.PHYSFS_write( file, buffer, size, count ) end local function PHYSFSTellProc( self ) local file = ffi.cast( "void *", self.UserData ) return physfs.PHYSFS_tell( file ) end local function PHYSFSFileSizeProc( self ) local file = ffi.cast( "void *", self.UserData ) return physfs.PHYSFS_fileLength( file ) end local function PHYSFSSeekProc( self, offset, whence ) local file = ffi.cast( "void *", self.UserData ) local ret = physfs.PHYSFS_seek( file, offset ) if ( ret ~= 0 ) then return ffi.C.aiReturn_SUCCESS else -- TODO: Return ffi.C.aiReturn_OUTOFMEMORY return ffi.C.aiReturn_FAILURE end end local function PHYSFSFlushProc( self ) local file = ffi.cast( "void *", self.UserData ) physfs.PHYSFS_flush( file ) end local function PHYSFSOpenProc( self, filename, mode ) local file = ffi.new( "struct aiFile" ) file.ReadProc = PHYSFSReadProc file.WriteProc = PHYSFSWriteProc file.TellProc = PHYSFSTellProc file.FileSizeProc = PHYSFSFileSizeProc file.SeekProc = PHYSFSSeekProc file.FlushProc = PHYSFSFlushProc local handle = physfs.PHYSFS_openRead( filename ) file.UserData = ffi.cast( "void *", handle ) if ( handle ~= nil ) then return file end end local function PHYSFSCloseProc( self, file ) physfs.PHYSFS_close( ffi.cast( "void *", file.UserData ) ) end local function getPHYSFSFileIO() if ( model._fileIO ) then return model._fileIO end local fileIO = ffi.new( "struct aiFileIO" ) fileIO.OpenProc = PHYSFSOpenProc fileIO.CloseProc = PHYSFSCloseProc model._fileIO = fileIO return fileIO end function model:model( filename ) self.scene = assimp.aiImportFileEx( filename, bit.bor( ffi.C.aiProcess_CalcTangentSpace, ffi.C.aiProcess_GenNormals, ffi.C.aiProcess_Triangulate, ffi.C.aiProcess_GenUVCoords, ffi.C.aiProcess_SortByPType ), getPHYSFSFileIO() ) if ( self.scene == nil ) then error( ffi.string( assimp.aiGetErrorString() ), 3 ) end self.meshes = {} if ( self.scene.mRootNode ~= nil ) then processNode( self, self.scene.mRootNode ) end setproxy( self ) end function model:draw( x, y, r, sx, sy, ox, oy, kx, ky ) for _, mesh in ipairs( self.meshes ) do framework.graphics.draw( mesh, x, y, r, sx, sy, ox, oy, kx, ky ) end end function model:__gc() assimp.aiReleaseImport( self.scene ) end
Fix PHYSFSOpenProc error handling
Fix PHYSFSOpenProc error handling
Lua
mit
Planimeter/lgameframework,Planimeter/lgameframework,Planimeter/lgameframework
57b8ecd44c38bd975a5cdaad5bf9937bc23b9275
toshiba.lua
toshiba.lua
dofile("urlcode.lua") dofile("table_show.lua") local url_count = 0 local tries = 0 local item_type = os.getenv('item_type') local item_value = os.getenv('item_value') local downloaded = {} local addedtolist = {} read_file = function(file) if file then local f = assert(io.open(file)) local data = f:read("*all") f:close() return data else return "" end end wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason) local url = urlpos["url"]["url"] local html = urlpos["link_expect_html"] if downloaded[url] == true or addedtolist[url] == true then return false end if (downloaded[url] ~= true or addedtolist[url] ~= true) then if string.match(urlpos["url"]["host"], "toshiba%.com") and string.match(url, "[^0-9]"..item_value.."[a-z0-9][a-z0-9]") and not string.match(url, "[^0-9]"..item_value.."[a-z0-9][a-z0-9][a-z0-9]") then addedtolist[url] = true return true elseif html == 0 then addedtolist[url] = true return true else return false end end end wget.callbacks.get_urls = function(file, url, is_css, iri) local urls = {} local html = nil if downloaded[url] ~= true then downloaded[url] = true end local function check(url) if (downloaded[url] ~= true and addedtolist[url] ~= true) and (string.match(url, "https?://cdgenp01%.csd%.toshiba%.com/") or (string.match(string.match(url, "https?://([^/]+)"), "toshiba%.com") and string.match(url, "[^0-9]"..item_value.."[a-z0-9][a-z0-9]") and not string.match(url, "[^0-9]"..item_value.."[a-z0-9][a-z0-9][a-z0-9]"))) then if string.match(url, "&amp;") then table.insert(urls, { url=string.gsub(url, "&amp;", "&") }) addedtolist[url] = true addedtolist[string.gsub(url, "&amp;", "&")] = true else table.insert(urls, { url=url }) addedtolist[url] = true end end end if string.match(string.match(url, "https?://([^/]+)/"), "toshiba%.com") and string.match(url, "[^0-9]"..item_value.."[a-z0-9][a-z0-9]") and not string.match(url, "[^0-9]"..item_value.."[a-z0-9][a-z0-9][a-z0-9]") then html = read_file(file) for newurl in string.gmatch(html, '"(https?://[^"]+)"') do check(newurl) end for newurl in string.gmatch(html, '("/[^"]+)"') do if string.match(newurl, '"//') then check(string.gsub(newurl, '"//', 'http://')) elseif not string.match(newurl, '"//') then check(string.match(url, "(https?://[^/]+)/")..string.match(newurl, '"(/.+)')) end end for newurl in string.gmatch(html, "('/[^']+)'") do if string.match(newurl, "'//") then check(string.gsub(newurl, "'//", "http://")) elseif not string.match(newurl, "'//") then check(string.match(url, "(https?://[^/]+)/")..string.match(newurl, "'(/.+)")) end end end return urls end wget.callbacks.httploop_result = function(url, err, http_stat) -- NEW for 2014: Slightly more verbose messages because people keep -- complaining that it's not moving or not working status_code = http_stat["statcode"] url_count = url_count + 1 io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n") io.stdout:flush() if (status_code >= 200 and status_code <= 399) then if string.match(url.url, "https://") then local newurl = string.gsub(url.url, "https://", "http://") downloaded[newurl] = true else downloaded[url.url] = true end end if status_code >= 500 or (status_code >= 400 and status_code ~= 404 and status_code ~= 403) then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 6 then io.stdout:write("\nI give up...\n") io.stdout:flush() tries = 0 return wget.actions.ABORT else return wget.actions.CONTINUE end elseif status_code == 0 then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 6 then io.stdout:write("\nI give up...\n") io.stdout:flush() tries = 0 return wget.actions.ABORT else return wget.actions.CONTINUE end end tries = 0 local sleep_time = 0 if sleep_time > 0.001 then os.execute("sleep " .. sleep_time) end return wget.actions.NOTHING end
dofile("urlcode.lua") dofile("table_show.lua") local url_count = 0 local tries = 0 local item_type = os.getenv('item_type') local item_value = os.getenv('item_value') local downloaded = {} local addedtolist = {} read_file = function(file) if file then local f = assert(io.open(file)) local data = f:read("*all") f:close() return data else return "" end end wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason) local url = urlpos["url"]["url"] local html = urlpos["link_expect_html"] if downloaded[url] == true or addedtolist[url] == true then return false end if (downloaded[url] ~= true or addedtolist[url] ~= true) then if string.match(urlpos["url"]["host"], "toshiba%.com") and string.match(url, "[^0-9]"..item_value.."[a-z0-9][a-z0-9]") and not string.match(url, "[^0-9]"..item_value.."[a-z0-9][a-z0-9][a-z0-9]") then addedtolist[url] = true return true elseif html == 0 then addedtolist[url] = true return true else return false end end end wget.callbacks.get_urls = function(file, url, is_css, iri) local urls = {} local html = nil if downloaded[url] ~= true then downloaded[url] = true end local function check(url) if (downloaded[url] ~= true and addedtolist[url] ~= true) and (string.match(url, "https?://cdgenp01%.csd%.toshiba%.com/") or (string.match(string.match(url, "https?://([^/]+)"), "toshiba%.com") and string.match(url, "[^0-9]"..item_value.."[a-z0-9][a-z0-9]") and not string.match(url, "[^0-9]"..item_value.."[a-z0-9][a-z0-9][a-z0-9]"))) then if string.match(url, "&amp;") then table.insert(urls, { url=string.gsub(url, "&amp;", "&") }) addedtolist[url] = true addedtolist[string.gsub(url, "&amp;", "&")] = true else table.insert(urls, { url=url }) addedtolist[url] = true end end end if string.match(string.match(url, "https?://([^/]+)/"), "toshiba%.com") and string.match(url, "[^0-9]"..item_value.."[a-z0-9][a-z0-9]") and not (string.match(url, "[^0-9]"..item_value.."[a-z0-9][a-z0-9][a-z0-9]") or string.match(url, "https?://cdgenp01%.csd%.toshiba%.com/")) then html = read_file(file) for newurl in string.gmatch(html, '"(https?://[^"]+)"') do check(newurl) end for newurl in string.gmatch(html, '("/[^"]+)"') do if string.match(newurl, '"//') then check(string.gsub(newurl, '"//', 'http://')) elseif not string.match(newurl, '"//') then check(string.match(url, "(https?://[^/]+)/")..string.match(newurl, '"(/.+)')) end end for newurl in string.gmatch(html, "('/[^']+)'") do if string.match(newurl, "'//") then check(string.gsub(newurl, "'//", "http://")) elseif not string.match(newurl, "'//") then check(string.match(url, "(https?://[^/]+)/")..string.match(newurl, "'(/.+)")) end end end return urls end wget.callbacks.httploop_result = function(url, err, http_stat) -- NEW for 2014: Slightly more verbose messages because people keep -- complaining that it's not moving or not working status_code = http_stat["statcode"] url_count = url_count + 1 io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n") io.stdout:flush() if (status_code >= 200 and status_code <= 399) then if string.match(url.url, "https://") then local newurl = string.gsub(url.url, "https://", "http://") downloaded[newurl] = true else downloaded[url.url] = true end end if status_code >= 500 or (status_code >= 400 and status_code ~= 404 and status_code ~= 403) then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 6 then io.stdout:write("\nI give up...\n") io.stdout:flush() tries = 0 return wget.actions.ABORT else return wget.actions.CONTINUE end elseif status_code == 0 then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 6 then io.stdout:write("\nI give up...\n") io.stdout:flush() tries = 0 return wget.actions.ABORT else return wget.actions.CONTINUE end end tries = 0 local sleep_time = 0 if sleep_time > 0.001 then os.execute("sleep " .. sleep_time) end return wget.actions.NOTHING end
toshiba.lua: fix
toshiba.lua: fix
Lua
unlicense
ArchiveTeam/toshiba-grab,ArchiveTeam/toshiba-grab
a72591806e100e65bea6c985dc7d43c9e1da97e3
openLuup/hag.lua
openLuup/hag.lua
#!/usr/bin/env wsapi.cgi --module(..., package.seeall) local ABOUT = { NAME = "upnp.control.hag", VERSION = "2016.06.09", DESCRIPTION = "a handler for redirected port_49451 /upnp/control/hag requests", AUTHOR = "@akbooer", COPYRIGHT = "(c) 2013-2016 AKBooer", DOCUMENTATION = "https://github.com/akbooer/openLuup/tree/master/Documentation", } -- see: http://wiki.micasaverde.com/index.php/ModifyUserData -- 2016.06.05 add scene processing (for AltUI long scene POST requests) -- 2016.06.09 make 'run' a local function and export module table explicitly local xml = require "openLuup.xml" local json = require "openLuup.json" local luup = require "openLuup.luup" local scenes = require "openLuup.scenes" local _log -- defined from WSAPI environment as wsapi.error:write(...) in run() method. --[[ The request is a POST with xml CONTENT_LENGTH = 681, CONTENT_TYPE = "text/xml;charset=UTF-8", <s:envelope s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> <s:body> <u:modifyuserdata xmlns:u="urn:schemas-micasaverde-org:service:HomeAutomationGateway:1"> <inuserdata>{...some JSON structure...}</inuserdata> <DataFormat>json</DataFormat> </u:modifyuserdata> </s:body> </s:envelope> JSON structure contains: { InstalledPlugins = {}, PluginSettings = {}, StartupCode = "...", devices = {}, rooms = {}, scenes = {}, sections = {}, users = {} } --]] local function run(wsapi_env) local response = "OK" local headers = { ["Content-type"] = "text/plain" } _log = function (...) wsapi_env.error:write(...) end -- set up the log output, note colon syntax local function iterator() -- one-shot 'iterator', returns response, then nil local x = response response = nil return x end local content = wsapi_env.input.read () local x = xml.decode(content) local m = xml.extract(x, "s:Envelope", "s:Body", "u:ModifyUserData") [1] or {} -- unpack one-element list if m.DataFormat == "json" and m.inUserData then local j,msg = json.decode (m.inUserData) if not j then response = msg _log (msg) else -- Startup if j.StartupCode then luup.attr_set ("StartupCode", j.StartupCode) _log "modified StartupCode" end -- Scenes if j.scenes then -- 2016.06.05 for name, scene in pairs (j.scenes) do local id = tonumber (scene.id) if id >= 1e6 then scene.id = nil end -- remove bogus scene number local new_scene, msg = scenes.create (scene) id = tonumber (scene.id) -- may have changed if id and new_scene then luup.scenes[id] = new_scene -- slot into scenes table _log ("modified scene #" .. id) else response = msg _log (msg) break end end end -- also devices, sections, rooms, users... end else -- not yet implemented _log (content) end return 200, headers, iterator end ----- return { ABOUT = ABOUT, run = run, } -----
#!/usr/bin/env wsapi.cgi module(..., package.seeall) local ABOUT = { NAME = "upnp.control.hag", VERSION = "2016.06.09", DESCRIPTION = "a handler for redirected port_49451 /upnp/control/hag requests", AUTHOR = "@akbooer", COPYRIGHT = "(c) 2013-2016 AKBooer", DOCUMENTATION = "https://github.com/akbooer/openLuup/tree/master/Documentation", } -- see: http://wiki.micasaverde.com/index.php/ModifyUserData -- 2016.06.05 add scene processing (for AltUI long scene POST requests) local xml = require "openLuup.xml" local json = require "openLuup.json" local luup = require "openLuup.luup" local scenes = require "openLuup.scenes" local _log -- defined from WSAPI environment as wsapi.error:write(...) in run() method. --[[ The request is a POST with xml CONTENT_LENGTH = 681, CONTENT_TYPE = "text/xml;charset=UTF-8", <s:envelope s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> <s:body> <u:modifyuserdata xmlns:u="urn:schemas-micasaverde-org:service:HomeAutomationGateway:1"> <inuserdata>{...some JSON structure...}</inuserdata> <DataFormat>json</DataFormat> </u:modifyuserdata> </s:body> </s:envelope> JSON structure contains: { InstalledPlugins = {}, PluginSettings = {}, StartupCode = "...", devices = {}, rooms = {}, scenes = {}, sections = {}, users = {} } --]] function run(wsapi_env) local response = "OK" local headers = { ["Content-type"] = "text/plain" } _log = function (...) wsapi_env.error:write(...) end -- set up the log output, note colon syntax local function iterator() -- one-shot 'iterator', returns response, then nil local x = response response = nil return x end local content = wsapi_env.input.read () local x = xml.decode(content) local m = xml.extract(x, "s:Envelope", "s:Body", "u:ModifyUserData") [1] or {} -- unpack one-element list if m.DataFormat == "json" and m.inUserData then local j,msg = json.decode (m.inUserData) if not j then response = msg _log (msg) else -- Startup if j.StartupCode then luup.attr_set ("StartupCode", j.StartupCode) _log "modified StartupCode" end -- Scenes if j.scenes then -- 2016.06.05 for name, scene in pairs (j.scenes) do local id = tonumber (scene.id) if id >= 1e6 then scene.id = nil end -- remove bogus scene number local new_scene, msg = scenes.create (scene) id = tonumber (scene.id) -- may have changed if id and new_scene then luup.scenes[id] = new_scene -- slot into scenes table _log ("modified scene #" .. id) else response = msg _log (msg) break end end end -- also devices, sections, rooms, users... end else -- not yet implemented _log (content) end return 200, headers, iterator end -----
hot-fix-hag-run-entry-point
hot-fix-hag-run-entry-point - undo previous change (incompatible with WSAPI connector)
Lua
apache-2.0
akbooer/openLuup
734e4feede4f2c61209ebd197c51939062a6ca57
main.lua
main.lua
#!/usr/bin/env lua --[[ Main entry to launch test cases. --]] function round(num, idp) local mult = 10^(idp or 3) return math.floor(num * mult + 0.5) / mult end function average(nums) local sum = 0 for i = 1, #nums do sum = sum + nums[i] end return sum / #nums end function runtest(func, times) local begin = os.clock() for i = 1, times or 100000 do func() end local endtm = os.clock() return round(endtm - begin) end function dotest(cases, times) for i = 1, #cases do local case = cases[i] io.stdout:write(string.format("Case %d: %s ", i, case.name)) case.t = {} for j = 1, 5 do io.stdout:write(".") io.stdout:flush() collectgarbage() local runtime = runtest(case.entry, times) case.t[#case.t + 1] = runtime end print() end print("ID", "Case name", "t1", "t2", "t3", "t4", "t5", "avg.", "%") local base = 0 for i = 1, #cases do local case = cases[i] local t, avg = case.t, average(case.t) if i == 1 then base = avg end local per = avg / base print(i, case.name, t[1], t[2], t[3], t[4], t[5], avg, round(100*per,2) .. "%") end print("----------------") end function dotimes(t, jt) local basetimes = 1000 local times = t or 1 if is_luajit() then times = times * (jt or 100) end return basetimes * times end local function check_enviroment() local is_luajit = not (nil == jit) local o = { ["Syntax version"] = _VERSION, ["Is LuaJIT"] = is_luajit, ["LuaJIT version"] = is_luajit and jit.version or "No LuaJIT", } return o end local function load_test_case() package.path = package.path .. ";./src/?.lua" local cases = require "src.init" return cases end local function usage(interpreter, executable) print("Usage:") print(string.format(" %s %s command [args...]", interpreter, executable)) print() print("Commands:") print(" env Show lua environment information.") print(" list List all test cases.") print(" run [cases ...] Run test cases given. Run all cases if args is missing.") end local function cmd_do_env() local env_info = check_enviroment() print("Environment information:") for k, v in pairs(env_info) do print(string.format(" - %s: %s", k, tostring(v))) end end local function cmd_do_list() local cases = load_test_case() local title = string.format(" %4s %-20s %-60s %s", "No.", "Name", "Description", "Count of cases") local l = string.rep("-", 1 + #title) print(title) print(l) for i, m in cases.each() do print(string.format(" %4d %-20s %-60s %d", i, m.name, m.desc, #m.cases)) end end local function cmd_do_run(names) local cases = load_test_case() local env_info = check_enviroment() local run_all = false if #names <= 0 or names[1] == "all" then names = cases.all_names end print("Running environment") print(string.format("Lua syntax version %s, LuaJIT=%s", env_info["Syntax version"], env_info["Is LuaJIT"])) print(string.rep("=", 60)) for _, name in ipairs(names) do local c = cases.fetch(name) if nil == c then print(string.format("Test case '%s' not found", name)) else local entries = c.cases print(string.format("Running test '%s' ......", c.name)) dotest(entries) end end end local function main() if nil == arg[1] then usage(arg[-1], arg[0]) return end local cmd = arg[1] if "env" == cmd then cmd_do_env() elseif "list" == cmd then cmd_do_list() elseif "run" == cmd then local names = {} for i = 2, #arg, 1 do names[i - 1] = arg[i] end cmd_do_run(names) end end main()
#!/usr/bin/env lua --[[ Main entry to launch test cases. --]] function round(num, idp) local mult = 10^(idp or 3) return math.floor(num * mult + 0.5) / mult end function average(nums) local sum = 0 for i = 1, #nums do sum = sum + nums[i] end return sum / #nums end function runtest(func, times) local begin = os.clock() for i = 1, times or 100000 do func() end local endtm = os.clock() return round(endtm - begin) end function dotest(cases, times) for i = 1, #cases do local case = cases[i] io.stdout:write(string.format("Case %d: %s ", i, case.name)) case.t = {} for j = 1, 5 do io.stdout:write(".") io.stdout:flush() collectgarbage() local runtime = runtest(case.entry, times) case.t[#case.t + 1] = runtime end print() end print("ID", "Case name", "t1", "t2", "t3", "t4", "t5", "avg.", "%") local base = 0 for i = 1, #cases do local case = cases[i] local t, avg = case.t, average(case.t) if i == 1 then base = avg end local per = avg / base print(i, case.name, t[1], t[2], t[3], t[4], t[5], avg, round(100*per,2) .. "%") end print("----------------") end function dotimes(t, jt) local basetimes = 1000 local times = t or 1 if is_luajit() then times = times * (jt or 100) end return basetimes * times end local function check_enviroment() local is_luajit = not (nil == jit) local o = { ["Syntax version"] = _VERSION, ["Is LuaJIT"] = is_luajit, ["LuaJIT version"] = is_luajit and jit.version or "No LuaJIT", } return o end local function load_test_case() package.path = package.path .. ";./src/?.lua" local cases = require "src.init" return cases end local function usage(interpreter, executable) print("Usage:") print(string.format(" %s %s command [args...]", interpreter, executable)) print() print("Commands:") print(" env Show lua environment information.") print(" list List all test cases.") print(" run [cases ...] Run test cases given. Run all cases if args is missing.") end local function cmd_do_env() local env_info = check_enviroment() print("Environment information:") for k, v in pairs(env_info) do print(string.format(" - %s: %s", k, tostring(v))) end end local function cmd_do_list() local cases = load_test_case() local title = string.format(" %4s %-20s %-60s %s", "No.", "Name", "Description", "Count of cases") local l = string.rep("-", 1 + #title) print(title) print(l) for i, m in cases.each() do print(string.format(" %4d %-20s %-60s %d", i, m.name, m.desc, #m.cases)) end end local function cmd_do_run(names) local cases = load_test_case() local env_info = check_enviroment() local run_all = false if #names <= 0 or names[1] == "all" then names = cases.all_names end print("Running environment") print(string.format("Lua syntax version %s, LuaJIT=%s", tostring(env_info["Syntax version"]), tostring(env_info["Is LuaJIT"]))) print(string.rep("=", 60)) for _, name in ipairs(names) do local c = cases.fetch(name) if nil == c then print(string.format("Test case '%s' not found", name)) else local entries = c.cases print(string.format("Running test '%s' ......", c.name)) dotest(entries) end end end local function main() if nil == arg[1] then usage(arg[-1], arg[0]) return end local cmd = arg[1] if "env" == cmd then cmd_do_env() elseif "list" == cmd then cmd_do_list() elseif "run" == cmd then local names = {} for i = 2, #arg, 1 do names[i - 1] = arg[i] end cmd_do_run(names) end end main()
Fix bug on lua 5.1
Fix bug on lua 5.1
Lua
bsd-2-clause
flily/lua-performance
3cd3b2381ac629ef8eb1c65a888b7ba099c8579b
profile17.lua
profile17.lua
box.cfg{listen = 3301} box.once('init', function() profile_space = box.schema.space.create('profile', {id = 1}) profile_space:create_index('primary', { type = 'hash', parts = {1, 'unsigned'} }) box.schema.user.grant('guest', 'read,write,execute', 'universe') end) log = require('log') local function store_profile(profile) return box.space.profile:replace({profile.uid, profile.data}) end local function load_profile(user_id) local tup = box.space.profile:select(user_id) if #tup == 0 then return nil end local profile = {} profile.uid = user_id profile.data = tup[1][2] return profile end local function create_new_profile(user_id) local profile = {} profile.uid = user_id profile.data = {} return profile end local function set_profile_key(profile, key, value) if value == '' then value = nil end profile.data[key] = value end local function cast_profile_to_return_format(profile) return {profile.uid, profile.data} end function profile_delete(user_id) box.space.profile:delete(user_id) end function profile_get_all(user_id) local profile = load_profile(user_id) return cast_profile_to_return_format(profile) end function profile_multiset(user_id, ...) local pref_list = {...} if #pref_list == 0 then error('No keys passed') end if #pref_list % 2 ~= 0 then error('Not even number of arguments') end local profile = load_profile(user_id) if not profile then profile = create_new_profile(user_id) end local i, pref_key = next(pref_list) local i, pref_value = next(pref_list, i) while pref_key ~= nil and pref_value ~= nil do set_profile_key(profile, pref_key, pref_value) i, pref_key = next(pref_list, i) i, pref_value = next(pref_list, i) end store_profile(profile) return cast_profile_to_return_format(profile) end function profile_set(user_id, key, value) return profile_multiset(user_id, key, value) end
-- Tuple of profile has always 2 fields. -- Field 1 -- user-id -- Field 2 -- key/value dict. Key is always a number. box.cfg{listen = 3301} box.once('init', function() profile_space = box.schema.space.create('profile', {id = 1}) profile_space:create_index('primary', { type = 'tree', parts = {1, 'unsigned'}, unique = true }) box.schema.user.grant('guest', 'read,write,execute', 'universe') end) msgpack = require('msgpack') -- Cast internal profile format to the format, requested by client-side. local function cast_profile_to_return_format(profile) setmetatable(profile.data, msgpack.map_mt) -- If we doesnt call this, we will receive an array with many nulls, not map. return {profile.uid, profile.data} end local function store_profile(profile) -- We dont want to store empty profiles. Save space. if #profile.data == 0 then return box.space.profile:delete(profile.uid) end setmetatable(profile.data, msgpack.map_mt) -- If we doesnt call this, we will store an array with many nulls, not map. return box.space.profile:replace({profile.uid, profile.data}) end local function create_new_profile(user_id) local profile = {} profile.uid = user_id profile.data = {} return profile end local function load_profile(user_id) local tup = box.space.profile:select(user_id) -- In case no profile found, operate it as profile without keys/values if #tup == 0 then return create_new_profile(user_id) end local profile = {} profile.uid = user_id profile.data = tup[1][2] -- Index 1 is because we have only 1 tuple with such userid (index is unique). Second field of tuple is key/value dict. return profile end local function set_profile_key(profile, key, value) -- Do not store empty keys. We want to save space. if value == '' then value = nil end profile.data[key] = value end -- function profile_delete delete profile. Returns nothing function profile_delete(user_id) box.space.profile:delete(user_id) end -- function profile_get_all returns full profile function profile_get_all(user_id) local profile = load_profile(user_id) return cast_profile_to_return_format(profile) end -- function profile_multiget returns only requested keys from profile. Accepts user_id and then several keys function profile_multiget(user_id, ...) -- First of all, make hash of needed keys local pref_list = {...} local pref_hash = {} for k, v in ipairs(pref_list) do pref_hash[v] = true end local profile = load_profile(user_id) -- Create a copy of profile. We select few keys, so it is faster to copy only needed keys, then clear not needed keys local profile_copy = create_new_profile(profile.uid) for k, v in pairs(profile.data) do if pref_hash[k] then profile_copy.data[k] = v end end return cast_profile_to_return_format(profile_copy) end -- function profile_multiset accepts user_id and then key, value, key, value, key, value, ... Returns full updated profile. function profile_multiset(user_id, ...) local pref_list = {...} if #pref_list % 2 ~= 0 then error('Not even number of arguments') end local profile = load_profile(user_id) -- In case of no keys were passed, just return full profile if #pref_list == 0 then return cast_profile_to_return_format(profile) end local i, pref_key = next(pref_list) local i, pref_value = next(pref_list, i) -- iterate all passed key/value pairs from arguments while pref_key ~= nil and pref_value ~= nil do set_profile_key(profile, pref_key, pref_value) i, pref_key = next(pref_list, i) i, pref_value = next(pref_list, i) end store_profile(profile) return cast_profile_to_return_format(profile) end -- function profile_set set only one key. Returns full updated profile function profile_set(user_id, key, value) return profile_multiset(user_id, key, value) end
Fixes and new features
Fixes and new features
Lua
bsd-2-clause
BHYCHIK/tntlua
de3b918ae5e9a8a1a8405dd8f9e39ccbea69701e
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 not msg:match("epgp standby") then return end local member = msg:match("epgp standby ([^ ]+)") if member then member = member:sub(1,1):upper()..member:sub(2):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"):Announce( 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 -- We're going to capitalize the name of the player if it's needed anyway. msg = msg:lower() if msg:sub(1, 12) ~= 'epgp standby' then return end local member = msg:match("epgp standby ([^ ]+)") if member then member = member:sub(1,1):upper()..member:sub(2):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"):Announce( 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
Make whisper commands case insensitive.
Make whisper commands case insensitive. This fixes issue 453. Thanks Trond!
Lua
bsd-3-clause
hayword/tfatf_epgp,hayword/tfatf_epgp,sheldon/epgp,ceason/epgp-tfatf,protomech/epgp-dkp-reloaded,sheldon/epgp,protomech/epgp-dkp-reloaded,ceason/epgp-tfatf
e35c2b10da1609fc86e065bb5ea136fb1de576ea
util/prosodyctl.lua
util/prosodyctl.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 encodings = require "util.encodings"; local stringprep = encodings.stringprep; local storagemanager = require "core.storagemanager"; local usermanager = require "core.usermanager"; local signal = require "util.signal"; local set = require "util.set"; local lfs = require "lfs"; local pcall = pcall; local type = type; local nodeprep, nameprep = stringprep.nodeprep, stringprep.nameprep; local io, os = io, os; local print = print; local tostring, tonumber = tostring, tonumber; local CFG_SOURCEDIR = _G.CFG_SOURCEDIR; local _G = _G; local prosody = prosody; module "prosodyctl" -- UI helpers function show_message(msg, ...) print(msg:format(...)); end function show_warning(msg, ...) print(msg:format(...)); end function show_usage(usage, desc) print("Usage: ".._G.arg[0].." "..usage); if desc then print(" "..desc); end end function getchar(n) local stty_ret = os.execute("stty raw -echo 2>/dev/null"); local ok, char; if stty_ret == 0 then ok, char = pcall(io.read, n or 1); os.execute("stty sane"); else ok, char = pcall(io.read, "*l"); if ok then char = char:sub(1, n or 1); end end if ok then return char; end end function getline() local ok, line = pcall(io.read, "*l"); if ok then return line; end end function getpass() local stty_ret = os.execute("stty -echo 2>/dev/null"); if stty_ret ~= 0 then io.write("\027[08m"); -- ANSI 'hidden' text attribute end local ok, pass = pcall(io.read, "*l"); if stty_ret == 0 then os.execute("stty sane"); else io.write("\027[00m"); end io.write("\n"); if ok then return pass; end end function show_yesno(prompt) io.write(prompt, " "); local choice = getchar():lower(); io.write("\n"); if not choice:match("%a") then choice = prompt:match("%[.-(%U).-%]$"); if not choice then return nil; end end return (choice == "y"); end function read_password() local password; while true do io.write("Enter new password: "); password = getpass(); if not password then show_message("No password - cancelled"); return; end io.write("Retype new password: "); if getpass() ~= password then if not show_yesno [=[Passwords did not match, try again? [Y/n]]=] then return; end else break; end end return password; end function show_prompt(prompt) io.write(prompt, " "); local line = getline(); line = line and line:gsub("\n$",""); return (line and #line > 0) and line or nil; end -- Server control function adduser(params) local user, host, password = nodeprep(params.user), nameprep(params.host), params.password; if not user then return false, "invalid-username"; elseif not host then return false, "invalid-hostname"; end local host = prosody.hosts[host]; if not host then return false, "no-such-host"; end local provider = host.users; if not(provider) or provider.name == "null" then usermanager.initialize_host(host); end storagemanager.initialize_host(host); local ok, errmsg = usermanager.create_user(user, password, host); if not ok then return false, errmsg; end return true; end function user_exists(params) local user, host, password = nodeprep(params.user), nameprep(params.host), params.password; local provider = prosody.hosts[host].users; if not(provider) or provider.name == "null" then usermanager.initialize_host(host); end storagemanager.initialize_host(host); return usermanager.user_exists(user, host); end function passwd(params) if not _M.user_exists(params) then return false, "no-such-user"; end return _M.adduser(params); end function deluser(params) if not _M.user_exists(params) then return false, "no-such-user"; end params.password = nil; return _M.adduser(params); end function getpid() local pidfile = config.get("*", "core", "pidfile"); if not pidfile then return false, "no-pidfile"; end local modules_enabled = set.new(config.get("*", "core", "modules_enabled")); if not modules_enabled:contains("posix") then return false, "no-posix"; end local file, err = io.open(pidfile, "r+"); if not file then return false, "pidfile-read-failed", err; end local locked, err = lfs.lock(file, "w"); if locked then file:close(); return false, "pidfile-not-locked"; end local pid = tonumber(file:read("*a")); file:close(); if not pid then return false, "invalid-pid"; end return true, pid; end function isrunning() local ok, pid, err = _M.getpid(); if not ok then if pid == "pidfile-read-failed" or pid == "pidfile-not-locked" then -- Report as not running, since we can't open the pidfile -- (it probably doesn't exist) return true, false; end return ok, pid; end return true, signal.kill(pid, 0) == 0; end function start() local ok, ret = _M.isrunning(); if not ok then return ok, ret; end if ret then return false, "already-running"; end if not CFG_SOURCEDIR then os.execute("./prosody"); else os.execute(CFG_SOURCEDIR.."/../../bin/prosody"); end return true; end function stop() local ok, ret = _M.isrunning(); if not ok then return ok, ret; end if not ret then return false, "not-running"; end local ok, pid = _M.getpid() if not ok then return false, pid; end signal.kill(pid, signal.SIGTERM); return true; end function reload() local ok, ret = _M.isrunning(); if not ok then return ok, ret; end if not ret then return false, "not-running"; end local ok, pid = _M.getpid() if not ok then return false, pid; end signal.kill(pid, signal.SIGHUP); return true; 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 encodings = require "util.encodings"; local stringprep = encodings.stringprep; local storagemanager = require "core.storagemanager"; local usermanager = require "core.usermanager"; local signal = require "util.signal"; local set = require "util.set"; local lfs = require "lfs"; local pcall = pcall; local nodeprep, nameprep = stringprep.nodeprep, stringprep.nameprep; local io, os = io, os; local print = print; local tostring, tonumber = tostring, tonumber; local CFG_SOURCEDIR = _G.CFG_SOURCEDIR; local _G = _G; local prosody = prosody; module "prosodyctl" -- UI helpers function show_message(msg, ...) print(msg:format(...)); end function show_warning(msg, ...) print(msg:format(...)); end function show_usage(usage, desc) print("Usage: ".._G.arg[0].." "..usage); if desc then print(" "..desc); end end function getchar(n) local stty_ret = os.execute("stty raw -echo 2>/dev/null"); local ok, char; if stty_ret == 0 then ok, char = pcall(io.read, n or 1); os.execute("stty sane"); else ok, char = pcall(io.read, "*l"); if ok then char = char:sub(1, n or 1); end end if ok then return char; end end function getpass() local stty_ret = os.execute("stty -echo 2>/dev/null"); if stty_ret ~= 0 then io.write("\027[08m"); -- ANSI 'hidden' text attribute end local ok, pass = pcall(io.read, "*l"); if stty_ret == 0 then os.execute("stty sane"); else io.write("\027[00m"); end io.write("\n"); if ok then return pass; end end function show_yesno(prompt) io.write(prompt, " "); local choice = getchar():lower(); io.write("\n"); if not choice:match("%a") then choice = prompt:match("%[.-(%U).-%]$"); if not choice then return nil; end end return (choice == "y"); end function read_password() local password; while true do io.write("Enter new password: "); password = getpass(); if not password then show_message("No password - cancelled"); return; end io.write("Retype new password: "); if getpass() ~= password then if not show_yesno [=[Passwords did not match, try again? [Y/n]]=] then return; end else break; end end return password; end -- Server control function adduser(params) local user, host, password = nodeprep(params.user), nameprep(params.host), params.password; if not user then return false, "invalid-username"; elseif not host then return false, "invalid-hostname"; end local host_session = prosody.hosts[host]; if not host_session then return false, "no-such-host"; end local provider = host_session.users; if not(provider) or provider.name == "null" then usermanager.initialize_host(host); end storagemanager.initialize_host(host); local ok, errmsg = usermanager.create_user(user, password, host); if not ok then return false, errmsg; end return true; end function user_exists(params) local user, host, password = nodeprep(params.user), nameprep(params.host), params.password; local provider = prosody.hosts[host].users; if not(provider) or provider.name == "null" then usermanager.initialize_host(host); end storagemanager.initialize_host(host); return usermanager.user_exists(user, host); end function passwd(params) if not _M.user_exists(params) then return false, "no-such-user"; end return _M.adduser(params); end function deluser(params) if not _M.user_exists(params) then return false, "no-such-user"; end params.password = nil; return _M.adduser(params); end function getpid() local pidfile = config.get("*", "core", "pidfile"); if not pidfile then return false, "no-pidfile"; end local modules_enabled = set.new(config.get("*", "core", "modules_enabled")); if not modules_enabled:contains("posix") then return false, "no-posix"; end local file, err = io.open(pidfile, "r+"); if not file then return false, "pidfile-read-failed", err; end local locked, err = lfs.lock(file, "w"); if locked then file:close(); return false, "pidfile-not-locked"; end local pid = tonumber(file:read("*a")); file:close(); if not pid then return false, "invalid-pid"; end return true, pid; end function isrunning() local ok, pid, err = _M.getpid(); if not ok then if pid == "pidfile-read-failed" or pid == "pidfile-not-locked" then -- Report as not running, since we can't open the pidfile -- (it probably doesn't exist) return true, false; end return ok, pid; end return true, signal.kill(pid, 0) == 0; end function start() local ok, ret = _M.isrunning(); if not ok then return ok, ret; end if ret then return false, "already-running"; end if not CFG_SOURCEDIR then os.execute("./prosody"); else os.execute(CFG_SOURCEDIR.."/../../bin/prosody"); end return true; end function stop() local ok, ret = _M.isrunning(); if not ok then return ok, ret; end if not ret then return false, "not-running"; end local ok, pid = _M.getpid() if not ok then return false, pid; end signal.kill(pid, signal.SIGTERM); return true; end function reload() local ok, ret = _M.isrunning(); if not ok then return ok, ret; end if not ret then return false, "not-running"; end local ok, pid = _M.getpid() if not ok then return false, pid; end signal.kill(pid, signal.SIGHUP); return true; end
util.prosodyctl: Fix variable name clash introduced in 55ef5d83d00a (thanks chris)
util.prosodyctl: Fix variable name clash introduced in 55ef5d83d00a (thanks chris)
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
98c2dacec249a312bae93ca0d14e21bf734a3ddd
scripts/root.lua
scripts/root.lua
include("srv_data\scripts\spawns\cities\JDT01.lua"); include("srv_data\scripts\warps\cities\JDT01.lua"); include("srv_data\scripts\npcs\cities\JDT01.lua"); include("srv_data\scripts\mobs\cities\JDT01.lua"); include("srv_data\scripts\spawns\cities\JPT01.lua"); include("srv_data\scripts\warps\cities\JPT01.lua"); include("srv_data\scripts\npcs\cities\JPT01.lua"); include("srv_data\scripts\mobs\cities\JPT01.lua"); include("srv_data\scripts\spawns\fields\JG06.lua"); include("srv_data\scripts\npcs\fields\JG06.lua"); include("srv_data\scripts\spawns\fields\title_jpt.lua"); include("srv_data\scripts\spawns\pvp\JPVP01.lua"); include("srv_data\scripts\npcs\pvp\JPVP01.lua"); include("srv_data\scripts\spawns\pvp\JPVP02.lua"); include("srv_data\scripts\npcs\pvp\JPVP02.lua"); include("srv_data\scripts\spawns\pvp\JPVP04.lua"); include("srv_data\scripts\spawns\pvp\JPVP05.lua"); include("srv_data\scripts\npcs\pvp\JPVP05.lua"); include("srv_data\scripts\spawns\fields\jg08.lua"); include("srv_data\scripts\npcs\fields\jg08.lua"); include("srv_data\scripts\mobs\fields\jg08.lua"); include("srv_data\scripts\spawns\fields\jg09.lua"); include("srv_data\scripts\npcs\fields\jg09.lua"); include("srv_data\scripts\mobs\fields\jg09.lua"); include("srv_data\scripts\spawns\fields\jg10.lua"); include("srv_data\scripts\npcs\fields\jg10.lua"); include("srv_data\scripts\mobs\fields\jg10.lua"); include("srv_data\scripts\spawns\fields\agit01.lua"); include("srv_data\scripts\npcs\fields\agit01.lua"); include("srv_data\scripts\spawns\fields\jmov01.lua"); include("srv_data\scripts\spawns\fields\JG07.lua"); include("srv_data\scripts\npcs\fields\JG07.lua"); include("srv_data\scripts\mobs\fields\JG07.lua"); include("srv_data\scripts\spawns\fields\JD01.lua"); include("srv_data\scripts\warps\fields\JD01.lua"); include("srv_data\scripts\npcs\fields\JD01.lua"); include("srv_data\scripts\mobs\fields\JD01.lua"); include("srv_data\scripts\spawns\fields\JG01.lua"); include("srv_data\scripts\warps\fields\JG01.lua"); include("srv_data\scripts\npcs\fields\JG01.lua"); include("srv_data\scripts\mobs\fields\JG01.lua"); include("srv_data\scripts\spawns\fields\JG02.lua"); include("srv_data\scripts\warps\fields\JG02.lua"); include("srv_data\scripts\npcs\fields\JG02.lua"); include("srv_data\scripts\mobs\fields\JG02.lua"); include("srv_data\scripts\spawns\fields\JD02.lua"); include("srv_data\scripts\warps\fields\JD02.lua"); include("srv_data\scripts\npcs\fields\JD02.lua"); include("srv_data\scripts\mobs\fields\JD02.lua"); include("srv_data\scripts\spawns\fields\JG03.lua"); include("srv_data\scripts\warps\fields\JG03.lua"); include("srv_data\scripts\npcs\fields\JG03.lua"); include("srv_data\scripts\mobs\fields\JG03.lua"); include("srv_data\scripts\spawns\fields\JG04.lua"); include("srv_data\scripts\warps\fields\JG04.lua"); include("srv_data\scripts\npcs\fields\JG04.lua"); include("srv_data\scripts\mobs\fields\JG04.lua"); include("srv_data\scripts\spawns\fields\JG05.lua"); include("srv_data\scripts\warps\fields\JG05.lua"); include("srv_data\scripts\npcs\fields\JG05.lua"); include("srv_data\scripts\mobs\fields\JG05.lua"); include("srv_data\scripts\spawns\fields\JD03.lua"); include("srv_data\scripts\warps\fields\JD03.lua"); include("srv_data\scripts\npcs\fields\JD03.lua"); include("srv_data\scripts\mobs\fields\JD03.lua"); include("srv_data\scripts\spawns\fields\JZ01_1.lua"); include("srv_data\scripts\warps\fields\JZ01_1.lua"); include("srv_data\scripts\mobs\fields\JZ01_1.lua"); include("srv_data\scripts\spawns\fields\JZ01_2.lua"); include("srv_data\scripts\warps\fields\JZ01_2.lua"); include("srv_data\scripts\mobs\fields\JZ01_2.lua"); include("srv_data\scripts\spawns\fields\JZ01_3.lua"); include("srv_data\scripts\warps\fields\JZ01_3.lua"); include("srv_data\scripts\mobs\fields\JZ01_3.lua"); include("srv_data\scripts\spawns\fields\Sum_Event.lua"); include("srv_data\scripts\warps\fields\Sum_Event.lua"); include("srv_data\scripts\npcs\fields\Sum_Event.lua"); include("srv_data\scripts\mobs\fields\Sum_Event.lua"); include("srv_data\scripts\spawns\fields\Win_Event.lua"); include("srv_data\scripts\npcs\fields\Win_Event.lua"); include("srv_data\scripts\spawns\fields\mudojang.lua"); include("srv_data\scripts\warps\fields\mudojang.lua"); include("srv_data\scripts\npcs\fields\mudojang.lua"); include("srv_data\scripts\spawns\cities\LMT01.lua"); include("srv_data\scripts\warps\cities\LMT01.lua"); include("srv_data\scripts\npcs\cities\LMT01.lua"); include("srv_data\scripts\mobs\cities\LMT01.lua"); include("srv_data\scripts\spawns\fields\lp01.lua"); include("srv_data\scripts\warps\fields\lp01.lua"); include("srv_data\scripts\mobs\fields\lp01.lua"); include("srv_data\scripts\spawns\fields\lp02.lua"); include("srv_data\scripts\warps\fields\lp02.lua"); include("srv_data\scripts\mobs\fields\lp02.lua"); include("srv_data\scripts\spawns\fields\LP03.lua"); include("srv_data\scripts\warps\fields\LP03.lua"); include("srv_data\scripts\npcs\fields\LP03.lua"); include("srv_data\scripts\mobs\fields\LP03.lua"); include("srv_data\scripts\spawns\fields\LP04.lua"); include("srv_data\scripts\warps\fields\LP04.lua"); include("srv_data\scripts\mobs\fields\LP04.lua"); include("srv_data\scripts\spawns\fields\LZ01.lua"); include("srv_data\scripts\warps\fields\LZ01.lua"); include("srv_data\scripts\mobs\fields\LZ01.lua"); include("srv_data\scripts\spawns\fields\LZ02.lua"); include("srv_data\scripts\warps\fields\LZ02.lua"); include("srv_data\scripts\mobs\fields\LZ02.lua"); include("srv_data\scripts\spawns\pvp\LPVP01.lua"); include("srv_data\scripts\warps\pvp\LPVP01.lua"); include("srv_data\scripts\mobs\pvp\LPVP01.lua");
include("spawns/cities/JDT01.lua"); include("warps/cities/JDT01.lua"); include("npcs/cities/JDT01.lua"); include("mobs/cities/JDT01.lua"); include("spawns/cities/JPT01.lua"); include("warps/cities/JPT01.lua"); include("npcs/cities/JPT01.lua"); include("mobs/cities/JPT01.lua"); include("spawns/fields/JG06.lua"); include("npcs/fields/JG06.lua"); include("spawns/fields/title_jpt.lua"); include("spawns/pvp/JPVP01.lua"); include("npcs/pvp/JPVP01.lua"); include("spawns/pvp/JPVP02.lua"); include("npcs/pvp/JPVP02.lua"); include("spawns/pvp/JPVP04.lua"); include("spawns/pvp/JPVP05.lua"); include("npcs/pvp/JPVP05.lua"); include("spawns/fields/jg08.lua"); include("npcs/fields/jg08.lua"); include("mobs/fields/jg08.lua"); include("spawns/fields/jg09.lua"); include("npcs/fields/jg09.lua"); include("mobs/fields/jg09.lua"); include("spawns/fields/jg10.lua"); include("npcs/fields/jg10.lua"); include("mobs/fields/jg10.lua"); include("spawns/fields/agit01.lua"); include("npcs/fields/agit01.lua"); include("spawns/fields/jmov01.lua"); include("spawns/fields/JG07.lua"); include("npcs/fields/JG07.lua"); include("mobs/fields/JG07.lua"); include("spawns/fields/JD01.lua"); include("warps/fields/JD01.lua"); include("npcs/fields/JD01.lua"); include("mobs/fields/JD01.lua"); include("spawns/fields/JG01.lua"); include("warps/fields/JG01.lua"); include("npcs/fields/JG01.lua"); include("mobs/fields/JG01.lua"); include("spawns/fields/JG02.lua"); include("warps/fields/JG02.lua"); include("npcs/fields/JG02.lua"); include("mobs/fields/JG02.lua"); include("spawns/fields/JD02.lua"); include("warps/fields/JD02.lua"); include("npcs/fields/JD02.lua"); include("mobs/fields/JD02.lua"); include("spawns/fields/JG03.lua"); include("warps/fields/JG03.lua"); include("npcs/fields/JG03.lua"); include("mobs/fields/JG03.lua"); include("spawns/fields/JG04.lua"); include("warps/fields/JG04.lua"); include("npcs/fields/JG04.lua"); include("mobs/fields/JG04.lua"); include("spawns/fields/JG05.lua"); include("warps/fields/JG05.lua"); include("npcs/fields/JG05.lua"); include("mobs/fields/JG05.lua"); include("spawns/fields/JD03.lua"); include("warps/fields/JD03.lua"); include("npcs/fields/JD03.lua"); include("mobs/fields/JD03.lua"); include("spawns/fields/JZ01_1.lua"); include("warps/fields/JZ01_1.lua"); include("mobs/fields/JZ01_1.lua"); include("spawns/fields/JZ01_2.lua"); include("warps/fields/JZ01_2.lua"); include("mobs/fields/JZ01_2.lua"); include("spawns/fields/JZ01_3.lua"); include("warps/fields/JZ01_3.lua"); include("mobs/fields/JZ01_3.lua"); include("spawns/fields/Sum_Event.lua"); include("warps/fields/Sum_Event.lua"); include("npcs/fields/Sum_Event.lua"); include("mobs/fields/Sum_Event.lua"); include("spawns/fields/Win_Event.lua"); include("npcs/fields/Win_Event.lua"); include("spawns/fields/mudojang.lua"); include("warps/fields/mudojang.lua"); include("npcs/fields/mudojang.lua"); include("spawns/cities/LMT01.lua"); include("warps/cities/LMT01.lua"); include("npcs/cities/LMT01.lua"); include("mobs/cities/LMT01.lua"); include("spawns/fields/lp01.lua"); include("warps/fields/lp01.lua"); include("mobs/fields/lp01.lua"); include("spawns/fields/lp02.lua"); include("warps/fields/lp02.lua"); include("mobs/fields/lp02.lua"); include("spawns/fields/LP03.lua"); include("warps/fields/LP03.lua"); include("npcs/fields/LP03.lua"); include("mobs/fields/LP03.lua"); include("spawns/fields/LP04.lua"); include("warps/fields/LP04.lua"); include("mobs/fields/LP04.lua"); include("spawns/fields/LZ01.lua"); include("warps/fields/LZ01.lua"); include("mobs/fields/LZ01.lua"); include("spawns/fields/LZ02.lua"); include("warps/fields/LZ02.lua"); include("mobs/fields/LZ02.lua"); include("spawns/pvp/LPVP01.lua"); include("warps/pvp/LPVP01.lua"); include("mobs/pvp/LPVP01.lua");
Fixed paths in root.lua
Fixed paths in root.lua
Lua
apache-2.0
dev-osrose/osIROSE-new,RavenX8/osIROSE-new,dev-osrose/osIROSE-new,RavenX8/osIROSE-new,dev-osrose/osIROSE-new,RavenX8/osIROSE-new
d6a409c0c6a448134758d443144e36474db3c7be
luapak/luarocks/cfg_extra.lua
luapak/luarocks/cfg_extra.lua
local cfg = require 'luarocks.cfg' local fs = require 'luapak.fs' local site_config = require 'luapak.luarocks.site_config' local utils = require 'luapak.utils' local basename = fs.basename local fmt = string.format local getenv = os.getenv local starts_with = utils.starts_with local MSVC = cfg.is_platform('win32') and not cfg.is_platform('mingw32') if not cfg.shared_lib_extension then cfg.shared_lib_extension = cfg.lib_extension end if not cfg.static_lib_extension then cfg.static_lib_extension = MSVC and 'lib' or 'a' end if not cfg.variables.AR then cfg.variables.AR = MSVC and 'lib' or 'ar' end if not cfg.variables.RANLIB then cfg.variables.RANLIB = 'ranlib' end if not cfg.variables.STRIP then cfg.variables.STRIP = 'strip' end -- LUALIB for MSVC is already defined in cfg.lua. if not cfg.variables.LUALIB and not MSVC then cfg.variables.LUALIB = fmt('liblua%s.%s', cfg.lua_version:gsub('%.', ''), cfg.lib_extension) end if cfg.is_platform('windows') then local fake_prefix = site_config.LUAROCKS_FAKE_PREFIX for name, value in pairs(cfg.variables) do -- Don't use bundled tools (set in luarocks.cfg). if starts_with(fake_prefix, value) then cfg.variables[name] = basename(value) end end end -- Allow to override the named variables by environment. for _, name in ipairs { 'AR', 'CC', 'CMAKE', 'CFLAGS', 'LD', 'LDFLAGS', 'MAKE', 'RANLIB', 'STRIP' } do local value = getenv(name) if value then cfg.variables[name] = value end end -- Allow to override any uppercase variable by environment. -- To avoid clashes with common variables like PWD, environment variables -- must be prefixed with "LUAROCKS_". -- Note: If, for example, both CFLAGS and LUAROCKS_CFLAGS is defined, -- then the prefixed one is used. for name, _ in pairs(cfg.variables) do local prefix = starts_with('LUAROCKS', name) and '' or 'LUAROCKS_' local value = getenv(prefix..name) if value then cfg.variables[name] = value end end return cfg
local cfg = require 'luarocks.cfg' local fs = require 'luapak.fs' local site_config = require 'luapak.luarocks.site_config' local utils = require 'luapak.utils' local basename = fs.basename local fmt = string.format local getenv = os.getenv local starts_with = utils.starts_with local MSVC = cfg.is_platform('win32') and not cfg.is_platform('mingw32') if not cfg.shared_lib_extension then cfg.shared_lib_extension = cfg.lib_extension end if not cfg.static_lib_extension then cfg.static_lib_extension = MSVC and 'lib' or 'a' end if not cfg.variables.AR then cfg.variables.AR = MSVC and 'lib' or 'ar' end if not cfg.variables.RANLIB then cfg.variables.RANLIB = 'ranlib' end if not cfg.variables.STRIP then cfg.variables.STRIP = 'strip' end -- LUALIB for MSVC is already defined in cfg.lua. if not cfg.variables.LUALIB and not MSVC then cfg.variables.LUALIB = fmt('liblua%s.%s', cfg.lua_version:gsub('%.', ''), cfg.lib_extension) end if cfg.is_platform('windows') then local fake_prefix = site_config.LUAROCKS_FAKE_PREFIX for name, value in pairs(cfg.variables) do -- Don't use bundled tools (set in luarocks.cfg). if starts_with(fake_prefix, value) then cfg.variables[name] = basename(value) end -- MSYS2/MinGW does not use mingw32- prefix. if starts_with('mingw32-', value) then cfg.variables[name] = value:gsub('^mingw32%-', '') end end end -- Allow to override the named variables by environment. for _, name in ipairs { 'AR', 'CC', 'CMAKE', 'CFLAGS', 'LD', 'LDFLAGS', 'MAKE', 'RANLIB', 'STRIP' } do local value = getenv(name) if value then cfg.variables[name] = value end end -- Allow to override any uppercase variable by environment. -- To avoid clashes with common variables like PWD, environment variables -- must be prefixed with "LUAROCKS_". -- Note: If, for example, both CFLAGS and LUAROCKS_CFLAGS is defined, -- then the prefixed one is used. for name, _ in pairs(cfg.variables) do local prefix = starts_with('LUAROCKS', name) and '' or 'LUAROCKS_' local value = getenv(prefix..name) if value then cfg.variables[name] = value end end return cfg
Remove mingw32- prefix from gcc/make, MSYS2/MinGW does not use it
Remove mingw32- prefix from gcc/make, MSYS2/MinGW does not use it
Lua
mit
jirutka/luapak,jirutka/luapak
4c6c238792e27297ec9c2626a237d1f76d9df8b2
src/FileManager.lua
src/FileManager.lua
local FileManager = {}; -- ------------------------------------------------ -- Local Variables -- ------------------------------------------------ local extensions = {}; local sortedList = {}; local totalFiles = 0; local colors; -- ------------------------------------------------ -- Local Functions -- ------------------------------------------------ --- -- Sorts the list of extensions and sorts them based on the amount of files -- which currently exist in the repository. -- local function createSortedList() for k in pairs( sortedList ) do sortedList[k] = nil; end for _, tbl in pairs( extensions ) do sortedList[#sortedList + 1] = tbl; end table.sort( sortedList, function( a, b ) return a.amount > b.amount; end); end -- ------------------------------------------------ -- Public Functions -- ------------------------------------------------ --- -- Adds a new file belonging to a certain extension to the list. If the -- extension doesn't exist yet we allocate a new table for it. -- @param ext (string) The extension to add a new file for. -- @return (table) The table containing RGB values for this extension. -- @return (string) The extension string. -- function FileManager.add( ext ) if not extensions[ext] then extensions[ext] = {}; extensions[ext].extension = ext; extensions[ext].amount = 0; extensions[ext].color = colors[ext] or { r = love.math.random( 0, 255 ), g = love.math.random( 0, 255 ), b = love.math.random( 0, 255 ) }; end extensions[ext].amount = extensions[ext].amount + 1; totalFiles = totalFiles + 1; createSortedList( extensions ); return extensions[ext].color, ext; end --- -- Decrements the counter for a certain extension. If there are no more files -- of that extension, it will remove it from the table. -- @param ext (string) The extension to remove a file from. -- function FileManager.remove( ext ) if not extensions[ext] then error( 'Tried to remove the non existing file extension "' .. ext .. '".' ); end extensions[ext].amount = extensions[ext].amount - 1; totalFiles = totalFiles - 1; if extensions[ext].amount == 0 then extensions[ext] = nil; end createSortedList( extensions ); end --- -- Resets the state of the FileManager. -- function FileManager.reset() extensions = {}; sortedList = {}; totalFiles = 0; colors = nil; end -- ------------------------------------------------ -- Getters -- ------------------------------------------------ --- -- Gets the color table for a certain file extension. -- @param ext (string) The extension to return the color for. -- @return (table) A table containing the RGB values for the extension. -- function FileManager.getColor( ext ) return extensions[ext].color; end --- -- Returns the sorted list of file extensions. -- @return (table) The sorted list of file extensions. -- function FileManager.getSortedList() return sortedList; end --- -- Returns the total amount of files in the repository. -- @return (number) The total amount of files in the repository. -- function FileManager.getTotalFiles() return totalFiles; end -- ------------------------------------------------ -- Setters -- ------------------------------------------------ --- -- Sets the default color table. This can be used to specify colors for -- certain extensions (instead of randomly creating them). -- @param ncol (table) The table containing RGBA values belonging to a certain -- file extension. -- function FileManager.setColorTable( ncol ) colors = ncol; end -- ------------------------------------------------ -- Return Module -- ------------------------------------------------ return FileManager;
local FileManager = {}; -- ------------------------------------------------ -- Local Variables -- ------------------------------------------------ local extensions = {}; local sortedList = {}; local totalFiles = 0; local colors; -- ------------------------------------------------ -- Local Functions -- ------------------------------------------------ --- -- Sorts the list of extensions and sorts them based on the amount of files -- which currently exist in the repository. -- local function createSortedList() for k in pairs( sortedList ) do sortedList[k] = nil; end for _, tbl in pairs( extensions ) do sortedList[#sortedList + 1] = tbl; end table.sort( sortedList, function( a, b ) return a.amount > b.amount; end); end --- -- Creates a new custom color for the extension if it doesn't have one yet. -- @param ext (string) The extension to add a new file for. -- @return (table) A table containing the RGB values for this extension. -- local function assignColor( ext ) if not colors[ext] then colors[ext] = { r = love.math.random( 0, 255 ), g = love.math.random( 0, 255 ), b = love.math.random( 0, 255 ) }; end return colors[ext]; end -- ------------------------------------------------ -- Public Functions -- ------------------------------------------------ --- -- Adds a new file belonging to a certain extension to the list. If the -- extension doesn't exist yet we allocate a new table for it. -- @param ext (string) The extension to add a new file for. -- @return (table) The table containing RGB values for this extension. -- @return (string) The extension string. -- function FileManager.add( ext ) if not extensions[ext] then extensions[ext] = {}; extensions[ext].extension = ext; extensions[ext].amount = 0; extensions[ext].color = assignColor( ext ); end extensions[ext].amount = extensions[ext].amount + 1; totalFiles = totalFiles + 1; createSortedList( extensions ); return extensions[ext].color, ext; end --- -- Decrements the counter for a certain extension. If there are no more files -- of that extension, it will remove it from the table. -- @param ext (string) The extension to remove a file from. -- function FileManager.remove( ext ) if not extensions[ext] then error( 'Tried to remove the non existing file extension "' .. ext .. '".' ); end extensions[ext].amount = extensions[ext].amount - 1; totalFiles = totalFiles - 1; if extensions[ext].amount == 0 then extensions[ext] = nil; end createSortedList( extensions ); end --- -- Resets the state of the FileManager. -- function FileManager.reset() extensions = {}; sortedList = {}; totalFiles = 0; colors = nil; end -- ------------------------------------------------ -- Getters -- ------------------------------------------------ --- -- Gets the color table for a certain file extension. -- @param ext (string) The extension to return the color for. -- @return (table) A table containing the RGB values for the extension. -- function FileManager.getColor( ext ) return extensions[ext].color; end --- -- Returns the sorted list of file extensions. -- @return (table) The sorted list of file extensions. -- function FileManager.getSortedList() return sortedList; end --- -- Returns the total amount of files in the repository. -- @return (number) The total amount of files in the repository. -- function FileManager.getTotalFiles() return totalFiles; end -- ------------------------------------------------ -- Setters -- ------------------------------------------------ --- -- Sets the default color table. This can be used to specify colors for -- certain extensions (instead of randomly creating them). -- @param ncol (table) The table containing RGBA values belonging to a certain -- file extension. -- function FileManager.setColorTable( ncol ) colors = ncol; end -- ------------------------------------------------ -- Return Module -- ------------------------------------------------ return FileManager;
Fix faulty creation of new custom colors
Fix faulty creation of new custom colors Custom colors are now also stored in the colors table of the FileManager. We only create a new color table if an extension doesn't have one assigned yet. Fixes #70.
Lua
mit
rm-code/logivi
96a985abd51726e01aeb7f8944d44892dd31b8c0
SparseLinear.lua
SparseLinear.lua
local THNN = require 'nn.THNN' local SparseLinear, parent = torch.class('nn.SparseLinear', 'nn.Module') function SparseLinear:__init(inputSize, outputSize) parent.__init(self) self.weightDecay = 0 self.weight = torch.Tensor(outputSize, inputSize):zero() self.bias = torch.Tensor(outputSize):zero() self.gradWeight = torch.Tensor(outputSize, inputSize):zero() self.gradBias = torch.Tensor(outputSize):zero() self.lastInput = nil self.cudaBuffer = torch.Tensor() if torch.getnumthreads() > 1 and outputSize >= 128 then self.shardBuffer = torch.Tensor(outputSize, torch.getnumthreads()) end -- state self.gradInput:resize(inputSize) self.output:resize(outputSize) self:reset() end function SparseLinear:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else stdv = 1./math.sqrt(self.weight:size(2)) end if nn.oldSeed then for i=1,self.weight:size(1) do self.weight:select(1, i):apply(function() return torch.uniform(-stdv, stdv) end) self.bias[i] = torch.uniform(-stdv, stdv) * 0.000001 end else self.weight:uniform(-stdv, stdv) self.bias:uniform(-stdv, stdv):mul(0.000001) end end function SparseLinear:updateOutput(input) input.THNN.SparseLinear_updateOutput( input:cdata(), self.output:cdata(), self.weight:cdata(), self.bias:cdata(), self.cudaBuffer:cdata(), THNN.optionalTensor(self.shardBuffer) ) return self.output end function SparseLinear:accGradParameters(input, gradOutput, scale) if not self.lastInput then self.lastInput = input:clone() else self.lastInput:resizeAs(input):copy(input) end input.THNN.SparseLinear_accGradParameters( input:cdata(), gradOutput:cdata(), self.gradWeight:cdata(), self.gradBias:cdata(), self.weight:cdata(), self.bias:cdata(), self.weightDecay or 0, scale or 1 ) end function SparseLinear:updateGradInput(input, gradOutput) if self.gradInput then input.THNN.SparseLinear_updateGradInput( input:cdata(), gradOutput:cdata(), self.gradInput:cdata(), self.weight:cdata() ) return self.gradInput end end function SparseLinear:updateParameters(learningRate) if self.lastInput then self.lastInput.THNN.SparseLinear_updateParameters( self.weight:cdata(), self.bias:cdata(), self.gradWeight:cdata(), self.gradBias:cdata(), self.lastInput:cdata(), learningRate ) else parent.updateParameters(self, learningRate) end end function SparseLinear:zeroGradParameters() if self.lastInput then self.lastInput.THNN.SparseLinear_zeroGradParameters( self.gradWeight:cdata(), self.gradBias:cdata(), self.lastInput:cdata() ) else parent.zeroGradParameters(self) end end function SparseLinear:clearState() if self.lastInput then self.lastInput:set() end return parent.clearState(self) end
local THNN = require 'nn.THNN' local SparseLinear, parent = torch.class('nn.SparseLinear', 'nn.Module') function SparseLinear:__init(inputSize, outputSize) parent.__init(self) self.weightDecay = 0 self.weight = torch.Tensor(outputSize, inputSize):zero() self.bias = torch.Tensor(outputSize):zero() self.gradWeight = torch.Tensor(outputSize, inputSize):zero() self.gradBias = torch.Tensor(outputSize):zero() self.lastInput = nil if torch.getnumthreads() > 1 and outputSize >= 128 then self.shardBuffer = torch.Tensor(outputSize, torch.getnumthreads()) end -- state self.gradInput:resize(inputSize) self.output:resize(outputSize) self:reset() end function SparseLinear:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else stdv = 1./math.sqrt(self.weight:size(2)) end if nn.oldSeed then for i=1,self.weight:size(1) do self.weight:select(1, i):apply(function() return torch.uniform(-stdv, stdv) end) self.bias[i] = torch.uniform(-stdv, stdv) * 0.000001 end else self.weight:uniform(-stdv, stdv) self.bias:uniform(-stdv, stdv):mul(0.000001) end end function SparseLinear:updateOutput(input) self.cudaBuffer = self.cudaBuffer or input.new() input.THNN.SparseLinear_updateOutput( input:cdata(), self.output:cdata(), self.weight:cdata(), self.bias:cdata(), self.cudaBuffer:cdata(), THNN.optionalTensor(self.shardBuffer) ) return self.output end function SparseLinear:accGradParameters(input, gradOutput, scale) if not self.lastInput then self.lastInput = input:clone() else self.lastInput:resizeAs(input):copy(input) end input.THNN.SparseLinear_accGradParameters( input:cdata(), gradOutput:cdata(), self.gradWeight:cdata(), self.gradBias:cdata(), self.weight:cdata(), self.bias:cdata(), self.weightDecay or 0, scale or 1 ) end function SparseLinear:updateGradInput(input, gradOutput) if self.gradInput then input.THNN.SparseLinear_updateGradInput( input:cdata(), gradOutput:cdata(), self.gradInput:cdata(), self.weight:cdata() ) return self.gradInput end end function SparseLinear:updateParameters(learningRate) if self.lastInput then self.lastInput.THNN.SparseLinear_updateParameters( self.weight:cdata(), self.bias:cdata(), self.gradWeight:cdata(), self.gradBias:cdata(), self.lastInput:cdata(), learningRate ) else parent.updateParameters(self, learningRate) end end function SparseLinear:zeroGradParameters() if self.lastInput then self.lastInput.THNN.SparseLinear_zeroGradParameters( self.gradWeight:cdata(), self.gradBias:cdata(), self.lastInput:cdata() ) else parent.zeroGradParameters(self) end end function SparseLinear:clearState() if self.lastInput then self.lastInput:set() end if self.cudaBuffer then self.cudaBuffer:set() end return parent.clearState(self) end
sparse linear back-compatibility fix
sparse linear back-compatibility fix
Lua
bsd-3-clause
colesbury/nn,caldweln/nn,jonathantompson/nn,PraveerSINGH/nn,elbamos/nn,nicholas-leonard/nn,jhjin/nn,joeyhng/nn,eriche2016/nn,sagarwaghmare69/nn,apaszke/nn,diz-vara/nn,kmul00/nn,xianjiec/nn
1c854a6bc488bb77b9d9d9afc3e499fd39dd85ab
GameServer/Content/Data/LeagueSandbox-Default/Champions/Ezreal/Q.lua
GameServer/Content/Data/LeagueSandbox-Default/Champions/Ezreal/Q.lua
Vector2 = require 'Vector2' -- include 2d vector lib function finishCasting() local current = Vector2:new(getOwnerX(), getOwnerY()) local to = (Vector2:new(getSpellToX(), getSpellToY()) - current):normalize() local range = to * 1150 local trueCoords = current + range addProjectile("EzrealMysticShotMissile", trueCoords.x, trueCoords.y) addBuff("Haste", 10.0, 1, getOwner(), getOwner()) end function applyEffects() dealPhysicalDamage(getEffectValue(0)+getOwner():getStats():getTotalAd()+(0.4*getOwner():getStats():getTotalAp())) -- TODO this can be fetched from projectile inibin "HitEffectName" addParticleTarget("Ezreal_mysticshot_tar.troy", getTarget()) destroyProjectile() end
Vector2 = require 'Vector2' -- include 2d vector lib function onFinishCasting() local current = Vector2:new(getOwnerX(), getOwnerY()) local to = (Vector2:new(getSpellToX(), getSpellToY()) - current):normalize() local range = to * 1150 local trueCoords = current + range addProjectile("EzrealMysticShotMissile", trueCoords.x, trueCoords.y) addBuff("Haste", 10.0, 1, getOwner(), getOwner()) printChat("You used Q"); end function applyEffects() dealPhysicalDamage(getEffectValue(0)+getOwner():getStats():getTotalAd()+(0.4*getOwner():getStats():getTotalAp())) -- TODO this can be fetched from projectile inibin "HitEffectName" addParticleTarget("Ezreal_mysticshot_tar.troy", getTarget()) destroyProjectile() end
Now works!
Now works! Now this skill works. But it has a bug: Depending in which direction you shoot it sometimes the shot appears from the "space" or "nothing"
Lua
agpl-3.0
LeagueSandbox/GameServer
98f6f91fcf3fd497478e6e989725e67707f36c3e
src/premake4.lua
src/premake4.lua
if _OPTIONS.os == nil then error('Please specify your target os!') end apps = {'scml'} for k, app in pairs(apps) do solution(app) configurations { "debug", "release" } location "../gen/proj" configuration("windows") targetdir( "../win32/compilers" ) configuration("macosx") targetdir( "../osx/compilers" ) configuration("linux") targetdir( "../linux/compilers" ) flags { "Symbols", "NoRTTI", "NoEditAndContinue", "NoExceptions", "NoPCH" } project(app) kind "ConsoleApp" language "C++" files { "app/"..app.."/**.h", "app/"..app.."/**.cpp" } configuration "debug" defines { "DEBUG" } configuration "release" defines { "RELEASE" } flags { "Optimize" } end
if _OPTIONS.os == nil then error('Please specify your target os!') end apps = {'scml'} for k, app in pairs(apps) do solution(app) configurations { "debug", "release" } location "../gen/proj" configuration("windows") targetdir( "../win32/Don't Starve Mod Tools/compilers" ) configuration("macosx") targetdir( "../osx/Don't Starve Mod Tools/compilers" ) configuration("linux") targetdir( "../linux/Don't Starve Mod Tools/compilers" ) flags { "Symbols", "NoRTTI", "NoEditAndContinue", "NoExceptions", "NoPCH" } project(app) kind "ConsoleApp" language "C++" files { "app/"..app.."/**.h", "app/"..app.."/**.cpp" } configuration "debug" defines { "DEBUG" } configuration "release" defines { "RELEASE" } flags { "Optimize" } end
Fixed premake script to point to new output directory.
Fixed premake script to point to new output directory.
Lua
mit
kleientertainment/ds_mod_tools,kleientertainment/ds_mod_tools,kleientertainment/ds_mod_tools,kleientertainment/ds_mod_tools
fd5357e311989ce1c3849931571e5a26565420d2
base/parser.lua
base/parser.lua
require("base.symbols") require("base.token") require("base.node") require("base.util") if not Flang then Flang = {} end Parser = {} Flang.Parser = Parser Parser.__index = Parser function Parser:new(o) if not o then error("nil constructor!") end o = { lexer = o.lexer } o.current_token = lexer:get() o.prev_token = nil setmetatable(o, self) self.__index = self return o end function Parser:error(msg) error(msg) end --[[ Compare the current token with the input token type. If the match, then "eat" the current token and assign the next token to "self.current_token". Else, throw an exception ;) Note: self.prev_token can also be thought of as "the last eaten token" ]] function Parser:eat(token_type) if (self.current_token.type == token_type) then self.prev_token = self.current_token self.current_token = self.lexer:get() else self:error("Expected " .. dq(token_type) .. " but got " .. dq(self.current_token.type) .. " at L" .. self.current_token.lineIndex .. ":C" .. self.current_token.columnIndex) end end ----------------------------------------------------------------------- -- AST generation ----------------------------------------------------------------------- --[[ FLANG 0.0.1 LANGUAGE DEFINITION program : statement | (statement)* statement : assignment_statement | empty assignment_statement : variable ASSIGN expr empty : expr : term ((PLUS | MINUS) term)* term : factor ((MUL | DIV) factor)* factor : PLUS factor | MINUS factor | NUMBER | LPAREN expr RPAREN | variable | boolean variable : IDENTIFIER boolean : (TRUE | FALSE) ]] function Parser:empty() -- Intentional no-op return Node.NoOp() end function Parser:boolean() -- boolean : (TRUE | FALSE) if (token.type == Symbols.TRUE) then self:eat(Symbols.TRUE) return Node.Boolean(self.prev_token) elseif (token.type == Symbols.FALSE) then self:eat(Symbols.FALSE) return Node.Boolean(self.prev_token) end end function Parser:variable() -- variable : IDENTIFIER -- Note that we use the current token since we haven't eaten yet! node = Node.Variable(self.current_token) self:eat(Symbols.IDENTIFIER) return node end function Parser:factor() token = self.current_token if (token.type == Symbols.NUMBER) then -- NUMBER self:eat(Symbols.NUMBER) return Node.Number(self.prev_token) elseif (token.type == Symbols.PLUS) then -- ( PLUS ) factor self:eat(Symbols.PLUS) return Node.UnaryOperator(self.prev_token, self:factor()) elseif (token.type == Symbols.MINUS) then -- ( MINUS ) factor self:eat(Symbols.MINUS) return Node.UnaryOperator(self.prev_token, self:factor()) elseif (token.type == Symbols.LPAREN) then -- ( expr ) self:eat(Symbols.LPAREN) node = self:expr() self:eat(Symbols.RPAREN) return node elseif (token.type == Symbols.TRUE or token.type == Symbols.FALSE) then return self:boolean() end self:error("Nothing to factor.") end function Parser:term() node = self:factor() while (self.current_token.type == Symbols.MUL or self.current_token.type == Symbols.DIV) do token = self.current_token if (token.type == Symbols.MUL) then self:eat(Symbols.MUL) elseif (token.type == Symbols.DIV) then self:eat(Symbols.DIV) end -- recursively build up the AST node = Node.BinaryOperator(node, self.prev_token, self:factor()) end return node end function Parser:expr() node = self:term() while (self.current_token.type == Symbols.PLUS or self.current_token.type == Symbols.MINUS) do token = self.current_token if (token.type == Symbols.PLUS) then self:eat(Symbols.PLUS) elseif (token.type == Symbols.MINUS) then self:eat(Symbols.MINUS) end -- recursively build up the AST node = Node.BinaryOperator(node, self.prev_token, self:term()) end return node end function Parser:assignment_statement() -- assignment_statement : variable ASSIGN expr left = self:variable() self:eat(Symbols.EQUALS) right = self:expr() node = Node.Assign(left, self.prev_token, right) return node end function Parser:statement() --[[ statement : assignment_statement | empty ]] token = self.current_token if (token.type == Symbols.IDENTIFIER) then node = self:assignment_statement() else node = self:empty() end return node end function Parser:program() --[[ program : statement | (statement)* ]] parentNode = Node.Program() -- parse as long as we can while self.current_token.type ~= Symbols.EOF do node = self:statement() count = parentNode.num_children parentNode.children[count] = node parentNode.num_children = count + 1 -- If no valid statement can be found, then exit with nothing if (node.type == Node.NO_OP_TYPE) then print("No valid statement found. Exiting parser.") break end end return parentNode end ----------------------------------------------------------------------- -- Public interface ----------------------------------------------------------------------- function Parser:parse() return self:program() end
require("base.symbols") require("base.token") require("base.node") require("base.util") if not Flang then Flang = {} end Parser = {} Flang.Parser = Parser Parser.__index = Parser function Parser:new(o) if not o then error("nil constructor!") end o = { lexer = o.lexer } o.current_token = lexer:get() o.prev_token = nil setmetatable(o, self) self.__index = self return o end function Parser:error(msg) error(msg) end --[[ Compare the current token with the input token type. If the match, then "eat" the current token and assign the next token to "self.current_token". Else, throw an exception ;) Note: self.prev_token can also be thought of as "the last eaten token" ]] function Parser:eat(token_type) if (self.current_token.type == token_type) then self.prev_token = self.current_token self.current_token = self.lexer:get() else self:error("Expected " .. dq(token_type) .. " but got " .. dq(self.current_token.type) .. " at L" .. self.current_token.lineIndex .. ":C" .. self.current_token.columnIndex) end end ----------------------------------------------------------------------- -- AST generation ----------------------------------------------------------------------- --[[ FLANG 0.0.1 LANGUAGE DEFINITION program : statement | (statement)* statement : assignment_statement | empty assignment_statement : variable ASSIGN expr empty : expr : term ((PLUS | MINUS) term)* term : factor ((MUL | DIV) factor)* factor : PLUS factor | MINUS factor | NUMBER | LPAREN expr RPAREN | variable | boolean variable : IDENTIFIER boolean : (TRUE | FALSE) ]] function Parser:empty() -- Intentional no-op return Node.NoOp() end function Parser:boolean() -- boolean : (TRUE | FALSE) if (token.type == Symbols.TRUE) then self:eat(Symbols.TRUE) return Node.Boolean(self.prev_token) elseif (token.type == Symbols.FALSE) then self:eat(Symbols.FALSE) return Node.Boolean(self.prev_token) end end function Parser:variable() -- variable : IDENTIFIER -- Note that we use the current token since we haven't eaten yet! node = Node.Variable(self.current_token) self:eat(Symbols.IDENTIFIER) return node end function Parser:factor() token = self.current_token if (token.type == Symbols.NUMBER) then -- NUMBER self:eat(Symbols.NUMBER) return Node.Number(self.prev_token) elseif (token.type == Symbols.PLUS) then -- ( PLUS ) factor self:eat(Symbols.PLUS) return Node.UnaryOperator(self.prev_token, self:factor()) elseif (token.type == Symbols.MINUS) then -- ( MINUS ) factor self:eat(Symbols.MINUS) return Node.UnaryOperator(self.prev_token, self:factor()) elseif (token.type == Symbols.LPAREN) then -- ( expr ) self:eat(Symbols.LPAREN) node = self:expr() self:eat(Symbols.RPAREN) return node elseif (token.type == Symbols.IDENTIFIER) then node = self:variable() return node elseif (token.type == Symbols.TRUE or token.type == Symbols.FALSE) then return self:boolean() end self:error("Nothing to factor. Token: "..dq(token)) end function Parser:term() node = self:factor() while (self.current_token.type == Symbols.MUL or self.current_token.type == Symbols.DIV) do token = self.current_token if (token.type == Symbols.MUL) then self:eat(Symbols.MUL) elseif (token.type == Symbols.DIV) then self:eat(Symbols.DIV) end -- recursively build up the AST node = Node.BinaryOperator(node, self.prev_token, self:factor()) end return node end function Parser:expr() node = self:term() while (self.current_token.type == Symbols.PLUS or self.current_token.type == Symbols.MINUS) do token = self.current_token if (token.type == Symbols.PLUS) then self:eat(Symbols.PLUS) elseif (token.type == Symbols.MINUS) then self:eat(Symbols.MINUS) end -- recursively build up the AST node = Node.BinaryOperator(node, self.prev_token, self:term()) end return node end function Parser:assignment_statement() -- assignment_statement : variable ASSIGN expr left = self:variable() self:eat(Symbols.EQUALS) right = self:expr() node = Node.Assign(left, self.prev_token, right) return node end function Parser:statement() --[[ statement : assignment_statement | empty ]] token = self.current_token if (token.type == Symbols.IDENTIFIER) then node = self:assignment_statement() else node = self:empty() end return node end function Parser:program() --[[ program : statement | (statement)* ]] parentNode = Node.Program() -- parse as long as we can while self.current_token.type ~= Symbols.EOF do node = self:statement() count = parentNode.num_children parentNode.children[count] = node parentNode.num_children = count + 1 -- If no valid statement can be found, then exit with nothing if (node.type == Node.NO_OP_TYPE) then print("No valid statement found. Exiting parser.") break end end return parentNode end ----------------------------------------------------------------------- -- Public interface ----------------------------------------------------------------------- function Parser:parse() return self:program() end
fixed variables lol
fixed variables lol
Lua
mit
radixdev/flang
9bf809f99a84db896e2a3312711c1d45c212e691
asyncoperations.lua
asyncoperations.lua
local table = table module "irc" local meta = _META function meta:send(fmt, ...) local bytes, err = self.socket:send(fmt:format(...) .. "\r\n") if bytes then return end if err ~= "timeout" and err ~= "wantwrite" then self:invoke("OnDisconnect", err, true) self:shutdown() error(err, errlevel) end end local function clean(str) return str:gsub("[\r\n:]", "") end function meta:sendChat(target, msg) self:send("PRIVMSG %s :%s", clean(target), clean(msg)) end function meta:sendNotice(target, msg) self:send("NOTICE %s :%s", clean(target), clean(msg)) end function meta:join(channel, key) if key then self:send("JOIN %s :%s", clean(channel), clean(key)) else self:send("JOIN %s", clean(channel)) end end function meta:part(channel) channel = clean(channel) self:send("PART %s", channel) if self.track_users then self.channels[channel] = nil end end function meta:trackUsers(b) self.track_users = b if not b then for k,v in pairs(self.channels) do self.channels[k] = nil end end end function meta:setMode(t) local target = t.target or self.nick local mode = "" local add, rem = t.add, t.remove assert(add or rem, "table contains neither 'add' nor 'remove'") if add then mode = table.concat{"+", add} end if rem then mode = table.concat{mode, "-", rem} end self:send("MODE %s %s", clean(target), clean(mode)) end
local table = table module "irc" local meta = _META function meta:send(fmt, ...) local bytes, err = self.socket:send(fmt:format(...) .. "\r\n") if bytes then return end if err ~= "timeout" and err ~= "wantwrite" then self:invoke("OnDisconnect", err, true) self:shutdown() error(err, errlevel) end end local function clean(str) return str:gsub("[\r\n:]", "") end function meta:sendChat(target, msg) -- Split the message into segments if it includes newlines. for line in msg:gmatch("([^\r\n]+)") self:send("PRIVMSG %s :%s", clean(target), msg) end end function meta:sendNotice(target, msg) -- Split the message into segments if it includes newlines. for line in msg:gmatch("([^\r\n]+)") self:send("NOTICE %s :%s", clean(target), msg) end end function meta:join(channel, key) if key then self:send("JOIN %s :%s", clean(channel), clean(key)) else self:send("JOIN %s", clean(channel)) end end function meta:part(channel) channel = clean(channel) self:send("PART %s", channel) if self.track_users then self.channels[channel] = nil end end function meta:trackUsers(b) self.track_users = b if not b then for k,v in pairs(self.channels) do self.channels[k] = nil end end end function meta:setMode(t) local target = t.target or self.nick local mode = "" local add, rem = t.add, t.remove assert(add or rem, "table contains neither 'add' nor 'remove'") if add then mode = table.concat{"+", add} end if rem then mode = table.concat{mode, "-", rem} end self:send("MODE %s %s", clean(target), clean(mode)) end
Fixing regressions in sendChat and sendNotice.
Fixing regressions in sendChat and sendNotice. Fixing: Incorrect handling of newlines in message. Fixing: Cleaning ':' from message.
Lua
mit
JakobOvrum/LuaIRC,wolfy1339/LuaIRC
85c1ed546384ce99d5ebb09f661cafb7421e47ee
Shilke2D/Core/Timer.lua
Shilke2D/Core/Timer.lua
--[[--- Timer class is the equivalent of as3 Timer. Each timer can be scheduled to run multiple times, even infinite. It's possible to register as listener for timer events. A Timer can be started, stopped and paused --]] Timer = class(EventDispatcher,IAnimatable) --[[--- Timer initialization. @param delay the duration of each countdown @param repeatCount the number of iteration. Defaul is 1. 0 or negative values means Infinite --]] function Timer:init(delay,repeatCount) EventDispatcher.init(self) self.delay = delay self.repeatCount = repeatCount or 1 self:reset() end ---Starts the timer, if it is not already running. function Timer:start() self.running = true end ---Stops the timer, if it is running. function Timer:stop() self.running = false end --[[--- Stops the timer, if it is running. Sets the currentCount property and the elapsedTime property back to 0, like the reset button of a stopwatch, to --]] function Timer:reset() self.running = false self.currentCount = 0 self.elapsedTime = 0 end ---IAnimatable update method function Timer:advanceTime(deltaTime) if self.running then self.elapsedTime = self.elapsedTime + deltaTime if self.elapsedTime >= self.delay then self.elapsedTime = self.elapsedTime - self.delay self.currentCount = self.currentCount + 1 self:dispatchEvent(TimerEvent(Event.TIMER, self.currentCount)) if self.repeatCount <= 0 or self.currentCount >= self.repeatCount then self:dispatchEvent(Event(Event.REMOVE_FROM_JUGGLER)) self.running = false end end end end
--[[--- Timer class is the equivalent of as3 Timer. Each timer can be scheduled to run multiple times, even infinite. It's possible to register as listener for timer events. A Timer can be started, stopped and paused --]] Timer = class(EventDispatcher,IAnimatable) --[[--- Timer initialization. @param delay the duration of each countdown @param repeatCount the number of iteration. Defaul is 1. 0 or negative values means Infinite --]] function Timer:init(delay,repeatCount) EventDispatcher.init(self) self.delay = delay self.repeatCount = repeatCount or 1 self:reset() end ---Starts the timer, if it is not already running. function Timer:start() self.running = true end ---Stops the timer, if it is running. function Timer:stop() self.running = false end --[[--- Stops the timer, if it is running. Sets the currentCount property and the elapsedTime property back to 0, like the reset button of a stopwatch, to --]] function Timer:reset() self.running = false self.currentCount = 0 self.elapsedTime = 0 end ---IAnimatable update method function Timer:advanceTime(deltaTime) if self.running then self.elapsedTime = self.elapsedTime + deltaTime if self.elapsedTime >= self.delay then self.elapsedTime = self.elapsedTime - self.delay self.currentCount = self.currentCount + 1 local timerEvent = ObjectPool.getObj(TimerEvent) timerEvent.repeatCount = self.currentCount self:dispatchEvent(timerEvent) ObjectPool.recycleObj(timerEvent) if self.repeatCount <= 0 or self.currentCount >= self.repeatCount then self:dispatchEventByType(Event.REMOVE_FROM_JUGGLER) self.running = false end end end end
Timer fixes and event optimization
Timer fixes and event optimization - fixed wrong timer event definition - remove_from_juggler and timer events are now pooled
Lua
mit
Shrike78/Shilke2D
46b578f2e0545098620e675796bf2066e8b51c48
test/testlib.lua
test/testlib.lua
-- Testlib.lua Library -- Provides a set of master functions for the test framework. -- Requires a valid config.lua to work. -- Requires luaunit to deliver correct test results. -- Some slaves need to return a boolean value for correct test results. -- Available functions: -- - testlib.setRuntime() -- -- Set the runtime for all slaves called -- - testlib.masterSingle() -- -- Starts a slave for all available cards -- -- (Called functions: slave(dev,card)) -- - testlib.masterPairSingle() -- -- Start two slave for each available card pairing -- -- (Called functions: slave(rxDev, txDev, rxCard, txCard)) -- - testlib.masterPairMulti() -- -- Start two pairs of slaves for each available card pairing -- -- (Called functions: slave1(rxDev, txDev), slave2(rxDev, txDev, slave1return)) local testlib = {} local dpdk = require "dpdk" local tconfig = require "tconfig" local timer = require "timer" local device = require "device" local luaunit = require "luaunit" local log = require "log" testlib.wait = 10 Tests = {} function testlib.getRuntime() return testlib.wait end -- Set the runtime for all slaves | default 10 seconds function testlib.setRuntime( value ) testlib.wait = value log:info("Runtime set to " .. testlib:getRuntime() .. " seconds.") end -- Start one slave on every available device function testlib.masterSingle() local cards = tconfig.cards() local devs = {} for i=1 , #cards do devs[ i ] = device.config{ port = cards[ i ][ 1 ] , rxQueues = 2 , txQueues = 2 } end device.waitForLinks() local runtime = timer:new( testlib:getRuntime() ) log:info("Current runtime set to " .. testlib:getRuntime() .. " seconds.") -- Iterates over all devices to do the following: -- - Start a slave with the device as input -- - Check the output of the slave if it equals true for i = 1, #cards do Tests[ "Tested device: " .. cards[ i ][ 1 ] ] = function() log:info( "Testing device: " .. cards[ i ][ 1 ] ) local result = slave( devs[ i ] , cards[ i ] ) dpdk.waitForSlaves() luaunit.assertTrue( result ) end end os.exit( luaunit.LuaUnit.run() ) end -- Start two slaves for every pairing function testlib.masterPairSingle() local cards = tconfig.cards() local pairs = tconfig.pairs() local devs = {} local devInf = {} for i = 1 , #pairs , 2 do devs[ i ] = device.config{ port = cards[ pairs[ i ][ 1 ] + 1 ][ 1 ] , rxQueues = 2 , txQueues = 2 } devInf[ i ] = cards[ pairs[ i ][ 1 ] ] devs[ i + 1 ] = device.config{ port = cards[ pairs[ i ][ 2 ] + 1 ][ 1 ] , rxQueue = 2 , txQueue = 2 } devInf[ i + 1 ] = cards[ pairs[ i ][ 2 ] ] end device.waitForLinks() for i=1, #devs,2 do Tests[ "Tested device: " .. i ] = function() log:info( "Testing device: " .. cards[ pairs[ i ][ 1 ] + 1 ][ 1 ] ) local result = slave( devs[ i ], devs[ i + 1 ] , devInf[ i ] , devInf[ i + 1 ] ) luaunit.assertTrue( result ) end Tests[ "Tested device: " .. i ] = function() log:info( "Testing device: " .. cards[ pairs[ i ][ 1 ] + 1 ][ 1 ] ) local result = slave( devs[ i + 1 ], devs[ i ] , devInf[ i + 1 ] , devInf[ i ] ) luaunit.assertTrue( result ) end end os.exit( luaunit.LuaUnit.run() ) end -- Start two pairs of slaves for every available decive pairing function testlib.masterPairMulti() local cards = tconfig.cards() local pairs = tconfig.pairs() local devs = {} for i = 1 , #pairs , 2 do devs[ i ] = device.config{ port = cards[ pairs[ i ][ 1 ] + 1 ][ 1 ] , rxQueues = 2 , txQueues = 2 } devs[ i + 1 ] = device.config{ port = cards[ pairs[ i ][ 2 ] + 1 ][ 1 ] , rxQueue = 2 , txQueue = 2 } end device.waitForLinks() -- Iterates over all pairings to do the following: -- - Start two pairs of slaves for every device pairing -- - Every pair consists of the same pair of slaves -- - The devices are switched in the second call -- - The first slave receives both devices and returns a value, that will be passed to the second slave -- - The second slave receives both devices and the return value of the first slave -- - Checks the output of the second slave if it equals true for i=1, #devs,2 do Tests[ "Tested device: " .. i ] = function() log:info( "Testing device: " .. cards[ pairs[ i ][ 1 ] + 1 ][ 1 ] ) local result1 = slave1( devs[ i ] , devs[ i + 1 ] ) local result2 = slave2( devs[ i + 1 ] , devs[ i ] , result1 ) luaunit.assertTrue( result2 ) end Tests[ "Tested device: " .. i + 1 ] = function () log:info( "Testing device: " .. cards[ pairs[ i ][ 1 ] + 1 ][ 1 ] ) local result1 = slave1( devs[ i + 1 ] , devs[ i ] ) local result2 = slave2( devs[ i ] , devs[ i + 1 ] , result1 ) luaunit.assertTrue( result2 ) end end os.exit( luaunit.LuaUnit.run() ) end return testlib
-- Testlib.lua Library -- Provides a set of master functions for the test framework. -- Requires a valid config.lua to work. -- Requires luaunit to deliver correct test results. -- Some slaves need to return a boolean value for correct test results. -- Available functions: -- - testlib.setRuntime() -- -- Set the runtime for all slaves called -- - testlib.masterSingle() -- -- Starts a slave for all available cards -- -- (Called functions: slave(dev,card)) -- - testlib.masterPairSingle() -- -- Start two slave for each available card pairing -- -- (Called functions: slave(rxDev, txDev, rxCard, txCard)) -- - testlib.masterPairMulti() -- -- Start two pairs of slaves for each available card pairing -- -- (Called functions: slave1(rxDev, txDev), slave2(rxDev, txDev, slave1return)) local testlib = {} local dpdk = require "dpdk" local tconfig = require "tconfig" local timer = require "timer" local device = require "device" local luaunit = require "luaunit" local log = require "log" testlib.wait = 10 Tests = {} function testlib.getRuntime() return testlib.wait end -- Set the runtime for all slaves | default 10 seconds function testlib.setRuntime( value ) testlib.wait = value log:info("Runtime set to " .. testlib:getRuntime() .. " seconds.") end -- Start one slave on every available device function testlib.masterSingle() local cards = tconfig.cards() local devs = {} for i=1 , #cards do devs[ i ] = device.config{ port = cards[ i ][ 1 ] , rxQueues = 2 , txQueues = 2 } end device.waitForLinks() local runtime = timer:new( testlib:getRuntime() ) log:info("Current runtime set to " .. testlib:getRuntime() .. " seconds.") -- Iterates over all devices to do the following: -- - Start a slave with the device as input -- - Check the output of the slave if it equals true for i = 1 , #cards do Tests[ "Tested device: " .. cards[ i ][ 1 ] ] = function() log:info( "Testing device: " .. cards[ i ][ 1 ] ) local result = slave( devs[ i ] , cards[ i ] ) dpdk.waitForSlaves() luaunit.assertTrue( result ) end end os.exit( luaunit.LuaUnit.run() ) end -- Start two slaves for every pairing function testlib.masterPairSingle() local cards = tconfig.cards() local pairs = tconfig.pairs() local devs = {} local devInf = {} for i = 1 , #pairs do devs[ i ] = device.config{ port = cards[ pairs[ i ][ 1 ] + 1 ][ 1 ] , rxQueues = 2 , txQueues = 2 } devInf[ i ] = cards[ pairs[ i ][ 1 ] ] devs[ i + 1 ] = device.config{ port = cards[ pairs[ i ][ 2 ] + 1 ][ 1 ] , rxQueue = 2 , txQueue = 2 } devInf[ i + 1 ] = cards[ pairs[ i ][ 2 ] ] end device.waitForLinks() for i=1 , #devs , 2 do Tests[ "Tested device: " .. i ] = function() log:info( "Testing device: " .. cards[ pairs[ i ][ 1 ] + 1 ][ 1 ] .. " (" .. cards[ pairs[ i ][ 2 ] + 1 ][ 1 ] .. ")" ) local result = slave( devs[ i ] , devs[ i + 1 ] , devInf[ i ] , devInf[ i + 1 ] ) luaunit.assertTrue( result ) end Tests[ "Tested device: " .. i + 1 ] = function() log:info( "Testing device: " .. cards[ pairs[ i ][ 2 ] + 1 ][ 1 ] .. " (" .. cards[ pairs [ i ][ 1 ] + 1 ][ 1 ] .. ")" ) local result = slave( devs[ i + 1 ] , devs[ i ] , devInf[ i + 1 ] , devInf[ i ] ) luaunit.assertTrue( result ) end end os.exit( luaunit.LuaUnit.run() ) end -- Start two pairs of slaves for every available decive pairing function testlib.masterPairMulti() local cards = tconfig.cards() local pairs = tconfig.pairs() local devs = {} for i = 1 , #pairs do devs[ i ] = device.config{ port = cards[ pairs[ i ][ 1 ] + 1 ][ 1 ] , rxQueues = 2 , txQueues = 2 } devs[ i + 1 ] = device.config{ port = cards[ pairs[ i ][ 2 ] + 1 ][ 1 ] , rxQueue = 2 , txQueue = 2 } end device.waitForLinks() -- Iterates over all pairings to do the following: -- - Start two pairs of slaves for every device pairing -- - Every pair consists of the same pair of slaves -- - The devices are switched in the second call -- - The first slave receives both devices and returns a value, that will be passed to the second slave -- - The second slave receives both devices and the return value of the first slave -- - Checks the output of the second slave if it equals true for i=1, #devs,2 do Tests[ "Tested device: " .. i ] = function() log:info( "Testing device: " .. cards[ pairs[ i ][ 1 ] + 1 ][ 1 ] ) local result1 = slave1( devs[ i ] , devs[ i + 1 ] ) local result2 = slave2( devs[ i + 1 ] , devs[ i ] , result1 ) luaunit.assertTrue( result2 ) end Tests[ "Tested device: " .. i + 1 ] = function () log:info( "Testing device: " .. cards[ pairs[ i ][ 1 ] + 1 ][ 1 ] ) local result1 = slave1( devs[ i + 1 ] , devs[ i ] ) local result2 = slave2( devs[ i ] , devs[ i + 1 ] , result1 ) luaunit.assertTrue( result2 ) end end os.exit( luaunit.LuaUnit.run() ) end return testlib
Bugfix
Bugfix
Lua
mit
gallenmu/MoonGen,emmericp/MoonGen,NetronomeMoongen/MoonGen,atheurer/MoonGen,bmichalo/MoonGen,bmichalo/MoonGen,dschoeffm/MoonGen,gallenmu/MoonGen,scholzd/MoonGen,dschoeffm/MoonGen,gallenmu/MoonGen,duk3luk3/MoonGen,scholzd/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,bmichalo/MoonGen,duk3luk3/MoonGen,atheurer/MoonGen,gallenmu/MoonGen,bmichalo/MoonGen,gallenmu/MoonGen,NetronomeMoongen/MoonGen,duk3luk3/MoonGen,NetronomeMoongen/MoonGen,dschoeffm/MoonGen,emmericp/MoonGen,scholzd/MoonGen,emmericp/MoonGen,gallenmu/MoonGen,atheurer/MoonGen
30dbcb53dc7eca477a512a9b680cc6595754210e
agents/monitoring/tests/net/init.lua
agents/monitoring/tests/net/init.lua
local table = require('table') local async = require('async') local ConnectionStream = require('monitoring/default/client/connection_stream').ConnectionStream local misc = require('monitoring/default/util/misc') local helper = require('../helper') local timer = require('timer') local fixtures = require('../fixtures') local constants = require('constants') local consts = require('../../default/util/constants') local Endpoint = require('../../default/endpoint').Endpoint local path = require('path') local exports = {} local child exports['test_reconnects'] = function(test, asserts) local options = { datacenter = 'test', stateDirectory = './tests', host = "127.0.0.1", port = 50061, tls = { rejectUnauthorized = false } } local client = ConnectionStream:new('id', 'token', 'guid', options) local clientEnd = 0 local reconnect = 0 client:on('client_end', function(err) clientEnd = clientEnd + 1 end) client:on('reconnect', function(err) reconnect = reconnect + 1 end) async.series({ function(callback) child = helper.start_server(callback) end, function(callback) client:on('handshake_success', misc.nCallbacks(callback, 3)) local endpoints = {} for _, address in pairs(fixtures.TESTING_AGENT_ENDPOINTS) do -- split ip:port table.insert(endpoints, Endpoint:new(address)) end client:createConnections(endpoints, function() end) end, function(callback) helper.stop_server(child) client:on('reconnect', counterTrigger(3, callback)) end, function(callback) child = helper.start_server(function() client:on('handshake_success', counterTrigger(3, callback)) end) end, }, function() helper.stop_server(child) asserts.ok(clientEnd > 0) asserts.ok(reconnect > 0) test.done() end) end exports['test_upgrades'] = function(test, asserts) local options, client, endpoints -- Override the default download path consts.DEFAULT_DOWNLOAD_PATH = path.join('.', 'tmp') options = { datacenter = 'test', stateDirectory = './tests', host = "127.0.0.1", port = 50061, tls = { rejectUnauthorized = false } } endpoints = get_endpoints() async.series({ function(callback) child = helper.start_server(callback) end, function(callback) client = ConnectionStream:new('id', 'token', 'guid', options) client:on('handshake_success', misc.nCallbacks(callback, 3)) client:createConnections(endpoints, function() end) end, function(callback) callback = misc.nCallbacks(callback, 4) client:on('binary_upgrade.found', callback) client:on('bundle_upgrade.found', callback) client:on('bundle_upgrade.error', callback) client:on('binary_upgrade.error', callback) client:getUpgrade():forceUpgradeCheck() end }, function() helper.stop_server(child) client:done() test.done() end) end return exports
local table = require('table') local async = require('async') local ConnectionStream = require('monitoring/default/client/connection_stream').ConnectionStream local misc = require('monitoring/default/util/misc') local helper = require('../helper') local timer = require('timer') local fixtures = require('../fixtures') local constants = require('constants') local consts = require('../../default/util/constants') local Endpoint = require('../../default/endpoint').Endpoint local path = require('path') local exports = {} local child function counterTrigger(trigger, callback) local counter = 0 return function() counter = counter + 1 if counter == trigger then callback() end end end exports['test_reconnects'] = function(test, asserts) local options = { datacenter = 'test', stateDirectory = './tests', host = "127.0.0.1", port = 50061, tls = { rejectUnauthorized = false } } local client = ConnectionStream:new('id', 'token', 'guid', options) local clientEnd = 0 local reconnect = 0 client:on('client_end', function(err) clientEnd = clientEnd + 1 end) client:on('reconnect', function(err) reconnect = reconnect + 1 end) async.series({ function(callback) child = helper.start_server(callback) end, function(callback) client:on('handshake_success', misc.nCallbacks(callback, 3)) local endpoints = {} for _, address in pairs(fixtures.TESTING_AGENT_ENDPOINTS) do -- split ip:port table.insert(endpoints, Endpoint:new(address)) end client:createConnections(endpoints, function() end) end, function(callback) helper.stop_server(child) client:on('reconnect', counterTrigger(3, callback)) end, function(callback) child = helper.start_server(function() client:on('handshake_success', counterTrigger(3, callback)) end) end, }, function() helper.stop_server(child) asserts.ok(clientEnd > 0) asserts.ok(reconnect > 0) test.done() end) end exports['test_upgrades'] = function(test, asserts) local options, client, endpoints -- Override the default download path consts.DEFAULT_DOWNLOAD_PATH = path.join('.', 'tmp') options = { datacenter = 'test', stateDirectory = './tests', host = "127.0.0.1", port = 50061, tls = { rejectUnauthorized = false } } endpoints = get_endpoints() async.series({ function(callback) child = helper.start_server(callback) end, function(callback) client = ConnectionStream:new('id', 'token', 'guid', options) client:on('handshake_success', misc.nCallbacks(callback, 3)) client:createConnections(endpoints, function() end) end, function(callback) callback = misc.nCallbacks(callback, 4) client:on('binary_upgrade.found', callback) client:on('bundle_upgrade.found', callback) client:on('bundle_upgrade.error', callback) client:on('binary_upgrade.error', callback) client:getUpgrade():forceUpgradeCheck() end }, function() helper.stop_server(child) client:done() test.done() end) end return exports
fix merge on counterTrigger
fix merge on counterTrigger
Lua
apache-2.0
kaustavha/rackspace-monitoring-agent,cp16net/virgo-base,christopherjwang/rackspace-monitoring-agent,cp16net/virgo-base,virgo-agent-toolkit/rackspace-monitoring-agent,cp16net/virgo-base,virgo-agent-toolkit/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,cp16net/virgo-base,AlphaStaxLLC/rackspace-monitoring-agent,cp16net/virgo-base,christopherjwang/rackspace-monitoring-agent
5e0c49345a8a0701c84f8d220bbdd3b9d28ba580
mods/boats/init.lua
mods/boats/init.lua
-- -- Helper functions -- local function is_water(pos) local nn = minetest.get_node(pos).name return minetest.get_item_group(nn, "water") ~= 0 end local function get_sign(i) if i == 0 then return 0 else return i/math.abs(i) end end local function get_velocity(v, yaw, y) local x = -math.sin(yaw)*v local z = math.cos(yaw)*v return {x=x, y=y, z=z} end local function get_v(v) return math.sqrt(v.x^2+v.z^2) end -- -- Boat entity -- local boat = { physical = true, collisionbox = {-0.6,-0.4,-0.6, 0.6,0.3,0.6}, visual = "mesh", mesh = "boat.x", textures = {"default_wood.png"}, driver = nil, v = 0, last_v = 0, } function boat.on_rightclick(self, clicker) if not clicker or not clicker:is_player() then return end local name = clicker:get_player_name() if self.driver and clicker == self.driver then self.driver = nil clicker:set_detach() default.player_attached[name] = false default.player_set_animation(clicker, "stand" , 30) elseif not self.driver then self.driver = clicker clicker:set_attach(self.object, "", {x=0,y=11,z=-3}, {x=0,y=0,z=0}) default.player_attached[name] = true minetest.after(0.2, function() default.player_set_animation(clicker, "sit" , 30) end) self.object:setyaw(clicker:get_look_yaw()-math.pi/2) end end function boat.on_activate(self, staticdata, dtime_s) self.object:set_armor_groups({immortal=1}) if staticdata then self.v = tonumber(staticdata) end self.last_v = self.v end function boat.get_staticdata() return tostring(v) end function boat.on_punch(self, puncher, time_from_last_punch, tool_capabilities, direction) puncher:set_detach() self.object:remove() if puncher and puncher:is_player() and not minetest.setting_getbool("creative_mode") then puncher:get_inventory():add_item("main", "boats:boat") end end function boat.on_step(self, dtime) self.v = get_v(self.object:getvelocity())*get_sign(self.v) if self.driver then local ctrl = self.driver:get_player_control() local yaw = self.object:getyaw() if ctrl.up then self.v = self.v+0.1 end if ctrl.down then self.v = self.v-0.08 end if ctrl.left then if ctrl.down then self.object:setyaw(yaw-math.pi/120-dtime*math.pi/120) else self.object:setyaw(yaw+math.pi/120+dtime*math.pi/120) end end if ctrl.right then if ctrl.down then self.object:setyaw(yaw+math.pi/120+dtime*math.pi/120) else self.object:setyaw(yaw-math.pi/120-dtime*math.pi/120) end end end local velo = self.object:getvelocity() if self.v == 0 and velo.x == 0 and velo.z == 0 then return end local s = get_sign(self.v) self.v = self.v - 0.02*s if s ~= get_sign(self.v) then self.object:setvelocity({x=0, y=0, z=0}) self.v = 0 return end if math.abs(self.v) > 4.5 then self.v = 4.5*get_sign(self.v) end local p = self.object:getpos() p.y = p.y-0.5 local new_velo = {x=0,y=0,z=0} local new_acce = {x=0,y=0,z=0} if not is_water(p) then if minetest.registered_nodes[minetest.env:get_node(p).name].walkable then self.v = 0 end new_acce = {x=0, y=-10, z=0} new_velo = get_velocity(self.v, self.object:getyaw(), self.object:getvelocity().y) else p.y = p.y+1 if is_water(p) then new_acce = {x=0, y=3, z=0} local y = self.object:getvelocity().y if y > 2 then y = 2 end if y < 0 then self.object:setacceleration({x=0, y=10, z=0}) end new_velo = get_velocity(self.v, self.object:getyaw(), y) else new_acce = {x=0, y=0, z=0} if math.abs(self.object:getvelocity().y) < 1 then local pos = self.object:getpos() pos.y = math.floor(pos.y)+0.5 self.object:setpos(pos) new_velo = get_velocity(self.v, self.object:getyaw(), 0) else new_velo = get_velocity(self.v, self.object:getyaw(), self.object:getvelocity().y) end end end self.object:setvelocity(new_velo) self.object:setacceleration(new_acce) end minetest.register_entity("boats:boat", boat) minetest.register_craftitem("boats:boat", { description = "Boat", inventory_image = "boat_inventory.png", wield_image = "boat_wield.png", wield_scale = {x=2, y=2, z=1}, liquids_pointable = true, on_place = function(itemstack, placer, pointed_thing) if pointed_thing.type ~= "node" then return end if not is_water(pointed_thing.under) then return end pointed_thing.under.y = pointed_thing.under.y+0.5 minetest.add_entity(pointed_thing.under, "boats:boat") if not minetest.setting_getbool("creative_mode") then itemstack:take_item() end return itemstack end, }) minetest.register_craft({ output = "boats:boat", recipe = { {"", "", ""}, {"group:wood", "", "group:wood"}, {"group:wood", "group:wood", "group:wood"}, }, })
-- -- Helper functions -- local function is_water(pos) local nn = minetest.get_node(pos).name return minetest.get_item_group(nn, "water") ~= 0 end local function get_sign(i) if i == 0 then return 0 else return i/math.abs(i) end end local function get_velocity(v, yaw, y) local x = -math.sin(yaw)*v local z = math.cos(yaw)*v return {x=x, y=y, z=z} end local function get_v(v) return math.sqrt(v.x^2+v.z^2) end -- -- Boat entity -- local boat = { physical = true, collisionbox = {-0.6,-0.4,-0.6, 0.6,0.3,0.6}, visual = "mesh", mesh = "boat.x", textures = {"default_wood.png"}, driver = nil, v = 0, last_v = 0, removed = false } function boat.on_rightclick(self, clicker) if not clicker or not clicker:is_player() then return end local name = clicker:get_player_name() if self.driver and clicker == self.driver then self.driver = nil clicker:set_detach() default.player_attached[name] = false default.player_set_animation(clicker, "stand" , 30) elseif not self.driver then self.driver = clicker clicker:set_attach(self.object, "", {x=0,y=11,z=-3}, {x=0,y=0,z=0}) default.player_attached[name] = true minetest.after(0.2, function() default.player_set_animation(clicker, "sit" , 30) end) self.object:setyaw(clicker:get_look_yaw()-math.pi/2) end end function boat.on_activate(self, staticdata, dtime_s) self.object:set_armor_groups({immortal=1}) if staticdata then self.v = tonumber(staticdata) end self.last_v = self.v end function boat.get_staticdata() return tostring(v) end function boat.on_punch(self, puncher, time_from_last_punch, tool_capabilities, direction) if not puncher or not puncher:is_player() or self.removed then return end puncher:set_detach() default.player_attached[puncher:get_player_name()] = false self.removed = true -- delay remove to ensure player is detached minetest.after(0.1,function() self.object:remove() end) if not minetest.setting_getbool("creative_mode") then puncher:get_inventory():add_item("main", "boats:boat") end end function boat.on_step(self, dtime) self.v = get_v(self.object:getvelocity())*get_sign(self.v) if self.driver then local ctrl = self.driver:get_player_control() local yaw = self.object:getyaw() if ctrl.up then self.v = self.v+0.1 end if ctrl.down then self.v = self.v-0.08 end if ctrl.left then if ctrl.down then self.object:setyaw(yaw-math.pi/120-dtime*math.pi/120) else self.object:setyaw(yaw+math.pi/120+dtime*math.pi/120) end end if ctrl.right then if ctrl.down then self.object:setyaw(yaw+math.pi/120+dtime*math.pi/120) else self.object:setyaw(yaw-math.pi/120-dtime*math.pi/120) end end end local velo = self.object:getvelocity() if self.v == 0 and velo.x == 0 and velo.z == 0 then return end local s = get_sign(self.v) self.v = self.v - 0.02*s if s ~= get_sign(self.v) then self.object:setvelocity({x=0, y=0, z=0}) self.v = 0 return end if math.abs(self.v) > 4.5 then self.v = 4.5*get_sign(self.v) end local p = self.object:getpos() p.y = p.y-0.5 local new_velo = {x=0,y=0,z=0} local new_acce = {x=0,y=0,z=0} if not is_water(p) then if minetest.registered_nodes[minetest.env:get_node(p).name].walkable then self.v = 0 end new_acce = {x=0, y=-10, z=0} new_velo = get_velocity(self.v, self.object:getyaw(), self.object:getvelocity().y) else p.y = p.y+1 if is_water(p) then new_acce = {x=0, y=3, z=0} local y = self.object:getvelocity().y if y > 2 then y = 2 end if y < 0 then self.object:setacceleration({x=0, y=10, z=0}) end new_velo = get_velocity(self.v, self.object:getyaw(), y) else new_acce = {x=0, y=0, z=0} if math.abs(self.object:getvelocity().y) < 1 then local pos = self.object:getpos() pos.y = math.floor(pos.y)+0.5 self.object:setpos(pos) new_velo = get_velocity(self.v, self.object:getyaw(), 0) else new_velo = get_velocity(self.v, self.object:getyaw(), self.object:getvelocity().y) end end end self.object:setvelocity(new_velo) self.object:setacceleration(new_acce) end minetest.register_entity("boats:boat", boat) minetest.register_craftitem("boats:boat", { description = "Boat", inventory_image = "boat_inventory.png", wield_image = "boat_wield.png", wield_scale = {x=2, y=2, z=1}, liquids_pointable = true, on_place = function(itemstack, placer, pointed_thing) if pointed_thing.type ~= "node" then return end if not is_water(pointed_thing.under) then return end pointed_thing.under.y = pointed_thing.under.y+0.5 minetest.add_entity(pointed_thing.under, "boats:boat") if not minetest.setting_getbool("creative_mode") then itemstack:take_item() end return itemstack end, }) minetest.register_craft({ output = "boats:boat", recipe = { {"", "", ""}, {"group:wood", "", "group:wood"}, {"group:wood", "group:wood", "group:wood"}, }, })
Fix boats again
Fix boats again
Lua
lgpl-2.1
evrooije/beerarchy,evrooije/beerarchy,evrooije/beerarchy
509947c28e742e1c47931a455f9fe4da7bb5a967
plugins/lastfm.lua
plugins/lastfm.lua
if not config.lastfm_api_key then print('Missing config value: lastfm_api_key.') print('lastfm.lua will not be enabled.') return end local command = 'lastfm' local doc = [[``` /np [username] Returns what you are or were last listening to. If you specify a username, info will be returned for that username. /fmset <username> Sets your last.fm username. Otherwise, /np will use your Telegram username. Use "/fmset -" to delete it. ```]] local triggers = { '^/lastfm[@'..bot.username..']*', '^/np[@'..bot.username..']*', '^/fmset[@'..bot.username..']*' } local action = function(msg) lastfm = load_data('lastfm.json') local input = msg.text:input() if string.match(msg.text, '^/lastfm') then sendReply(msg, doc:sub(10)) return elseif string.match(msg.text, '^/fmset') then if not input then sendMessage(msg.chat.id, doc, true, msg.message_id, true) elseif input == '-' then lastfm[msg.from.id_str] = nil sendReply(msg, 'Your last.fm username has been forgotten.') else lastfm[msg.from.id_str] = input sendReply(msg, 'Your last.fm username has been set to "' .. input .. '".') end save_data('lastfm.json', lastfm) return end local url = 'http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&format=json&limit=1&api_key=' .. config.lastfm_api_key .. '&user=' local username local output = '' if input then username = input elseif lastfm[msg.from.id_str] then username = lastfm[msg.from.id_str] elseif msg.from.username then username = msg.from.username output = '\n\nYour username has been set to ' .. username .. '.\nTo change it, use /fmset <username>.' lastfm[msg.from.id_str] = username save_data('lastfm.json', lastfm) else sendReply(msg, 'Please specify your last.fm username or set it with /fmset.') return end url = url .. URL.escape(username) jstr, res = HTTPS.request(url) if res ~= 200 then sendReply(msg, config.errors.connection) return end local jdat = JSON.decode(jstr) if jdat.error then sendReply(msg, config.errors.results) return end local jdat = jdat.recenttracks.track[1] or jdat.recenttracks.track if not jdat then sendReply(msg, 'No history for this user.' .. output) return end local message = input or msg.from.first_name message = '🎵 ' .. message if jdat['@attr'] and jdat['@attr'].nowplaying then message = message .. ' is currently listening to:\n' else message = message .. ' last listened to:\n' end local title = jdat.name or 'Unknown' local artist = 'Unknown' if jdat.artist then artist = jdat.artist['#text'] end message = message .. title .. ' - ' .. artist .. output sendMessage(msg.chat.id, message) end return { action = action, triggers = triggers, doc = doc, command = command }
if not config.lastfm_api_key then print('Missing config value: lastfm_api_key.') print('lastfm.lua will not be enabled.') return end local command = 'lastfm' local doc = [[``` /np [username] Returns what you are or were last listening to. If you specify a username, info will be returned for that username. /fmset <username> Sets your last.fm username. Otherwise, /np will use your Telegram username. Use "/fmset -" to delete it. ```]] local triggers = { '^/lastfm[@'..bot.username..']*', '^/np[@'..bot.username..']*', '^/fmset[@'..bot.username..']*' } local action = function(msg) lastfm = load_data('lastfm.json') local input = msg.text:input() if string.match(msg.text, '^/lastfm') then sendMessage(msg.chat.id, doc, true, msg.message_id, true) return elseif string.match(msg.text, '^/fmset') then if not input then sendMessage(msg.chat.id, doc, true, msg.message_id, true) elseif input == '-' then lastfm[msg.from.id_str] = nil sendReply(msg, 'Your last.fm username has been forgotten.') else lastfm[msg.from.id_str] = input sendReply(msg, 'Your last.fm username has been set to "' .. input .. '".') end save_data('lastfm.json', lastfm) return end local url = 'http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&format=json&limit=1&api_key=' .. config.lastfm_api_key .. '&user=' local username local output = '' if input then username = input elseif lastfm[msg.from.id_str] then username = lastfm[msg.from.id_str] elseif msg.from.username then username = msg.from.username output = '\n\nYour username has been set to ' .. username .. '.\nTo change it, use /fmset <username>.' lastfm[msg.from.id_str] = username save_data('lastfm.json', lastfm) else sendReply(msg, 'Please specify your last.fm username or set it with /fmset.') return end url = url .. URL.escape(username) jstr, res = HTTPS.request(url) if res ~= 200 then sendReply(msg, config.errors.connection) return end local jdat = JSON.decode(jstr) if jdat.error then sendReply(msg, config.errors.results) return end local jdat = jdat.recenttracks.track[1] or jdat.recenttracks.track if not jdat then sendReply(msg, 'No history for this user.' .. output) return end local message = input or msg.from.first_name message = '🎵 ' .. message if jdat['@attr'] and jdat['@attr'].nowplaying then message = message .. ' is currently listening to:\n' else message = message .. ' last listened to:\n' end local title = jdat.name or 'Unknown' local artist = 'Unknown' if jdat.artist then artist = jdat.artist['#text'] end message = message .. title .. ' - ' .. artist .. output sendMessage(msg.chat.id, message) end return { action = action, triggers = triggers, doc = doc, command = command }
lastfm bugfix
lastfm bugfix
Lua
agpl-3.0
topkecleon/otouto,Brawl345/Brawlbot-v2,barreeeiroo/BarrePolice,bb010g/otouto,TiagoDanin/SiD
c697df1762d7f374160fb2d789e2f64bd241a986
plugins/fortune.lua
plugins/fortune.lua
-- Requires that the "fortune" program is installed on your computer. local s = io.popen('fortune'):read('*all') if s:match('fortune: command not found') or ('fortune: not found') then print('fortune is not installed on this computer.') print('fortune.lua will not be enabled.') return end local command = 'fortune' local doc = '`Returns a UNIX fortune.`' local triggers = { '^/fortune[@'..bot.username..']*' } local action = function(msg) local message = io.popen('fortune'):read('*all') sendMessage(msg.chat.id, message) end return { action = action, triggers = triggers, doc = doc, command = command }
-- Requires that the "fortune" program is installed on your computer. local s = io.popen('fortune'):read('*all') if s:match('not found$') then print('fortune is not installed on this computer.') print('fortune.lua will not be enabled.') return end local command = 'fortune' local doc = '`Returns a UNIX fortune.`' local triggers = { '^/fortune[@'..bot.username..']*' } local action = function(msg) local message = io.popen('fortune'):read('*all') sendMessage(msg.chat.id, message) end return { action = action, triggers = triggers, doc = doc, command = command }
better fix to fortune.lua
better fix to fortune.lua
Lua
agpl-3.0
topkecleon/otouto,TiagoDanin/SiD,Brawl345/Brawlbot-v2,barreeeiroo/BarrePolice,bb010g/otouto
d34301e6d471c1c7e35f9772fac5b8a4187c8e58
net/http/parser.lua
net/http/parser.lua
local tonumber = tonumber; local assert = assert; local url_parse = require "socket.url".parse; local urldecode = require "util.http".urldecode; local function preprocess_path(path) path = urldecode((path:gsub("//+", "/"))); if path:sub(1,1) ~= "/" then path = "/"..path; end local level = 0; for component in path:gmatch("([^/]+)/") do if component == ".." then level = level - 1; elseif component ~= "." then level = level + 1; end if level < 0 then return nil; end end return path; end local httpstream = {}; function httpstream.new(success_cb, error_cb, parser_type, options_cb) local client = true; if not parser_type or parser_type == "server" then client = false; else assert(parser_type == "client", "Invalid parser type"); end local buf = ""; local chunked, chunk_size, chunk_start; local state = nil; local packet; local len; local have_body; local error; return { feed = function(self, data) if error then return nil, "parse has failed"; end if not data then -- EOF if state and client and not len then -- reading client body until EOF packet.body = buf; success_cb(packet); elseif buf ~= "" then -- unexpected EOF error = true; return error_cb(); end return; end buf = buf..data; while #buf > 0 do if state == nil then -- read request local index = buf:find("\r\n\r\n", nil, true); if not index then return; end -- not enough data local method, path, httpversion, status_code, reason_phrase; local first_line; local headers = {}; for line in buf:sub(1,index+1):gmatch("([^\r\n]+)\r\n") do -- parse request if first_line then local key, val = line:match("^([^%s:]+): *(.*)$"); if not key then error = true; return error_cb("invalid-header-line"); end -- TODO handle multi-line and invalid headers key = key:lower(); headers[key] = headers[key] and headers[key]..","..val or val; else first_line = line; if client then httpversion, status_code, reason_phrase = line:match("^HTTP/(1%.[01]) (%d%d%d) (.*)$"); status_code = tonumber(status_code); if not status_code then error = true; return error_cb("invalid-status-line"); end 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) ); else method, path, httpversion = line:match("^(%w+) (%S+) HTTP/(1%.[01])$"); if not method then error = true; return error_cb("invalid-status-line"); end end end end if not first_line then error = true; return error_cb("invalid-status-line"); end chunked = have_body and headers["transfer-encoding"] == "chunked"; len = tonumber(headers["content-length"]); -- TODO check for invalid len if client then -- FIXME handle '100 Continue' response (by skipping it) if not have_body then len = 0; end packet = { code = status_code; httpversion = httpversion; headers = headers; body = have_body and "" or nil; -- COMPAT the properties below are deprecated responseversion = httpversion; responseheaders = headers; }; else local parsed_url; if path:byte() == 47 then -- starts with / local _path, _query = path:match("([^?]*).?(.*)"); if _query == "" then _query = nil; end parsed_url = { path = _path, query = _query }; else parsed_url = url_parse(path); if not(parsed_url and parsed_url.path) then error = true; return error_cb("invalid-url"); end end path = preprocess_path(parsed_url.path); headers.host = parsed_url.host or headers.host; len = len or 0; packet = { method = method; url = parsed_url; path = path; httpversion = httpversion; headers = headers; body = nil; }; end buf = buf:sub(index + 4); state = true; end if state then -- read body if client then if chunked then if not buf:find("\r\n", nil, true) then return; end -- not enough data if not chunk_size then chunk_size, chunk_start = buf:match("^(%x+)[^\r\n]*\r\n()"); chunk_size = chunk_size and tonumber(chunk_size, 16); if not chunk_size then error = true; return error_cb("invalid-chunk-size"); end end if chunk_size == 0 and buf:find("\r\n\r\n", chunk_start-2, true) then state, chunk_size = nil, nil; buf = buf:gsub("^.-\r\n\r\n", ""); -- This ensure extensions and trailers are stripped success_cb(packet); elseif #buf - chunk_start + 2 >= chunk_size then -- we have a chunk packet.body = packet.body..buf:sub(chunk_start, chunk_start + chunk_size); buf = buf:sub(chunk_start + chunk_size + 2); chunk_size, chunk_start = nil, nil; else -- Partial chunk remaining break; end elseif len and #buf >= len then packet.body, buf = buf:sub(1, len), buf:sub(len + 1); state = nil; success_cb(packet); else break; end elseif #buf >= len then packet.body, buf = buf:sub(1, len), buf:sub(len + 1); state = nil; success_cb(packet); else break; end end end end; }; end return httpstream;
local tonumber = tonumber; local assert = assert; local url_parse = require "socket.url".parse; local urldecode = require "util.http".urldecode; local function preprocess_path(path) path = urldecode((path:gsub("//+", "/"))); if path:sub(1,1) ~= "/" then path = "/"..path; end local level = 0; for component in path:gmatch("([^/]+)/") do if component == ".." then level = level - 1; elseif component ~= "." then level = level + 1; end if level < 0 then return nil; end end return path; end local httpstream = {}; function httpstream.new(success_cb, error_cb, parser_type, options_cb) local client = true; if not parser_type or parser_type == "server" then client = false; else assert(parser_type == "client", "Invalid parser type"); end local buf = ""; local chunked, chunk_size, chunk_start; local state = nil; local packet; local len; local have_body; local error; return { feed = function(self, data) if error then return nil, "parse has failed"; end if not data then -- EOF if state and client and not len then -- reading client body until EOF packet.body = buf; success_cb(packet); elseif buf ~= "" then -- unexpected EOF error = true; return error_cb(); end return; end buf = buf..data; while #buf > 0 do if state == nil then -- read request local index = buf:find("\r\n\r\n", nil, true); if not index then return; end -- not enough data local method, path, httpversion, status_code, reason_phrase; local first_line; local headers = {}; for line in buf:sub(1,index+1):gmatch("([^\r\n]+)\r\n") do -- parse request if first_line then local key, val = line:match("^([^%s:]+): *(.*)$"); if not key then error = true; return error_cb("invalid-header-line"); end -- TODO handle multi-line and invalid headers key = key:lower(); headers[key] = headers[key] and headers[key]..","..val or val; else first_line = line; if client then httpversion, status_code, reason_phrase = line:match("^HTTP/(1%.[01]) (%d%d%d) (.*)$"); status_code = tonumber(status_code); if not status_code then error = true; return error_cb("invalid-status-line"); end 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) ); else method, path, httpversion = line:match("^(%w+) (%S+) HTTP/(1%.[01])$"); if not method then error = true; return error_cb("invalid-status-line"); end end end end if not first_line then error = true; return error_cb("invalid-status-line"); end chunked = have_body and headers["transfer-encoding"] == "chunked"; len = tonumber(headers["content-length"]); -- TODO check for invalid len if client then -- FIXME handle '100 Continue' response (by skipping it) if not have_body then len = 0; end packet = { code = status_code; httpversion = httpversion; headers = headers; body = have_body and "" or nil; -- COMPAT the properties below are deprecated responseversion = httpversion; responseheaders = headers; }; else local parsed_url; if path:byte() == 47 then -- starts with / local _path, _query = path:match("([^?]*).?(.*)"); if _query == "" then _query = nil; end parsed_url = { path = _path, query = _query }; else parsed_url = url_parse(path); if not(parsed_url and parsed_url.path) then error = true; return error_cb("invalid-url"); end end path = preprocess_path(parsed_url.path); headers.host = parsed_url.host or headers.host; len = len or 0; packet = { method = method; url = parsed_url; path = path; httpversion = httpversion; headers = headers; body = nil; }; end buf = buf:sub(index + 4); state = true; end if state then -- read body if client then if chunked then if not buf:find("\r\n", nil, true) then return; end -- not enough data if not chunk_size then chunk_size, chunk_start = buf:match("^(%x+)[^\r\n]*\r\n()"); chunk_size = chunk_size and tonumber(chunk_size, 16); if not chunk_size then error = true; return error_cb("invalid-chunk-size"); end end if chunk_size == 0 and buf:find("\r\n\r\n", chunk_start-2, true) then state, chunk_size = nil, nil; buf = buf:gsub("^.-\r\n\r\n", ""); -- This ensure extensions and trailers are stripped success_cb(packet); elseif #buf - chunk_start + 2 >= chunk_size then -- we have a chunk print(chunk_start, chunk_size, ("%q"):format(buf)) packet.body = packet.body..buf:sub(chunk_start, chunk_start + (chunk_size-1)); buf = buf:sub(chunk_start + chunk_size + 2); chunk_size, chunk_start = nil, nil; else -- Partial chunk remaining break; end elseif len and #buf >= len then packet.body, buf = buf:sub(1, len), buf:sub(len + 1); state = nil; success_cb(packet); else break; end elseif #buf >= len then packet.body, buf = buf:sub(1, len), buf:sub(len + 1); state = nil; success_cb(packet); else break; end end end end; }; end return httpstream;
net.http.parser: Fix off-by-one error in chunked encoding parser
net.http.parser: Fix off-by-one error in chunked encoding parser
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
702a42a1acbce5f014d5cec0e20b994a7bd5d3f4
util/stanza.lua
util/stanza.lua
local t_insert = table.insert; local t_remove = table.remove; local s_format = string.format; local tostring = tostring; local setmetatable = setmetatable; local pairs = pairs; local ipairs = ipairs; local type = type; local next = next; local print = print; local unpack = unpack; local s_gsub = string.gsub; local debug = debug; local log = require "util.logger".init("stanza"); module "stanza" stanza_mt = {}; stanza_mt.__index = stanza_mt; function stanza(name, attr) local stanza = { name = name, attr = attr or {}, tags = {}, last_add = {}}; return setmetatable(stanza, stanza_mt); end function stanza_mt:query(xmlns) return self:tag("query", { xmlns = xmlns }); end function stanza_mt:tag(name, attrs) local s = stanza(name, attrs); (self.last_add[#self.last_add] or self):add_direct_child(s); t_insert(self.last_add, s); return self; end function stanza_mt:text(text) (self.last_add[#self.last_add] or self):add_direct_child(text); return self; end function stanza_mt:up() t_remove(self.last_add); return self; end function stanza_mt:add_direct_child(child) if type(child) == "table" then t_insert(self.tags, child); end t_insert(self, child); end function stanza_mt:add_child(child) (self.last_add[#self.last_add] or self):add_direct_child(child); return self; end function stanza_mt:child_with_name(name) for _, child in ipairs(self) do if child.name == name then return child; end end end function stanza_mt:children() local i = 0; return function (a) i = i + 1 local v = a[i] if v then return v; end end, self, i; end function stanza_mt:childtags() local i = 0; return function (a) i = i + 1 local v = self.tags[i] if v then return v; end end, self.tags[1], i; end do local xml_entities = { ["'"] = "&apos;", ["\""] = "&quot;", ["<"] = "&lt;", [">"] = "&gt;", ["&"] = "&amp;" }; function xml_escape(s) return s_gsub(s, "['&<>\"]", xml_entities); end end local xml_escape = xml_escape; function stanza_mt.__tostring(t) local children_text = ""; for n, child in ipairs(t) do if type(child) == "string" then children_text = children_text .. xml_escape(child); else children_text = children_text .. tostring(child); end end local attr_string = ""; if t.attr then for k, v in pairs(t.attr) do if type(k) == "string" then attr_string = attr_string .. s_format(" %s='%s'", k, tostring(v)); end end end return s_format("<%s%s>%s</%s>", t.name, attr_string, children_text, t.name); end function stanza_mt.__add(s1, s2) return s1:add_direct_child(s2); end do local id = 0; function new_id() id = id + 1; return "lx"..id; end end function preserialize(stanza) local s = { name = stanza.name, attr = stanza.attr }; for _, child in ipairs(stanza) do if type(child) == "table" then t_insert(s, preserialize(child)); else t_insert(s, child); end end return s; end function deserialize(stanza) -- Set metatable if stanza then setmetatable(stanza, stanza_mt); for _, child in ipairs(stanza) do if type(child) == "table" then deserialize(child); end end if not stanza.tags then -- Rebuild tags local tags = {}; for _, child in ipairs(stanza) do if type(child) == "table" then t_insert(tags, child); end end stanza.tags = tags; end end return stanza; end function message(attr, body) if not body then return stanza("message", attr); else return stanza("message", attr):tag("body"):text(body); end end function iq(attr) if attr and not attr.id then attr.id = new_id(); end return stanza("iq", attr or { id = new_id() }); end function reply(orig) return stanza(orig.name, orig.attr and { to = orig.attr.from, from = orig.attr.to, id = orig.attr.id, type = ((orig.name == "iq" and "result") or orig.attr.type) }); end function error_reply(orig, type, condition, message, clone) local t = reply(orig); t.attr.type = "error"; -- TODO use clone t:tag("error", {type = type}) :tag(condition, {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"}):up(); if (message) then t:tag("text"):text(message):up(); end return t; -- stanza ready for adding app-specific errors end function presence(attr) return stanza("presence", attr); end return _M;
local t_insert = table.insert; local t_remove = table.remove; local s_format = string.format; local tostring = tostring; local setmetatable = setmetatable; local pairs = pairs; local ipairs = ipairs; local type = type; local next = next; local print = print; local unpack = unpack; local s_gsub = string.gsub; local debug = debug; local log = require "util.logger".init("stanza"); module "stanza" stanza_mt = {}; stanza_mt.__index = stanza_mt; function stanza(name, attr) local stanza = { name = name, attr = attr or {}, tags = {}, last_add = {}}; return setmetatable(stanza, stanza_mt); end function stanza_mt:query(xmlns) return self:tag("query", { xmlns = xmlns }); end function stanza_mt:tag(name, attrs) local s = stanza(name, attrs); (self.last_add[#self.last_add] or self):add_direct_child(s); t_insert(self.last_add, s); return self; end function stanza_mt:text(text) (self.last_add[#self.last_add] or self):add_direct_child(text); return self; end function stanza_mt:up() t_remove(self.last_add); return self; end function stanza_mt:add_direct_child(child) if type(child) == "table" then t_insert(self.tags, child); end t_insert(self, child); end function stanza_mt:add_child(child) (self.last_add[#self.last_add] or self):add_direct_child(child); return self; end function stanza_mt:child_with_name(name) for _, child in ipairs(self) do if child.name == name then return child; end end end function stanza_mt:children() local i = 0; return function (a) i = i + 1 local v = a[i] if v then return v; end end, self, i; end function stanza_mt:childtags() local i = 0; return function (a) i = i + 1 local v = self.tags[i] if v then return v; end end, self.tags[1], i; end do local xml_entities = { ["'"] = "&apos;", ["\""] = "&quot;", ["<"] = "&lt;", [">"] = "&gt;", ["&"] = "&amp;" }; function xml_escape(s) return s_gsub(s, "['&<>\"]", xml_entities); end end local xml_escape = xml_escape; function stanza_mt.__tostring(t) local children_text = ""; for n, child in ipairs(t) do if type(child) == "string" then children_text = children_text .. xml_escape(child); else children_text = children_text .. tostring(child); end end local attr_string = ""; if t.attr then for k, v in pairs(t.attr) do if type(k) == "string" then attr_string = attr_string .. s_format(" %s='%s'", k, tostring(v)); end end end return s_format("<%s%s>%s</%s>", t.name, attr_string, children_text, t.name); end function stanza_mt.__add(s1, s2) return s1:add_direct_child(s2); end do local id = 0; function new_id() id = id + 1; return "lx"..id; end end function preserialize(stanza) local s = { name = stanza.name, attr = stanza.attr }; for _, child in ipairs(stanza) do if type(child) == "table" then t_insert(s, preserialize(child)); else t_insert(s, child); end end return s; end function deserialize(stanza) -- Set metatable if stanza then setmetatable(stanza, stanza_mt); for _, child in ipairs(stanza) do if type(child) == "table" then deserialize(child); end end if not stanza.tags then -- Rebuild tags local tags = {}; for _, child in ipairs(stanza) do if type(child) == "table" then t_insert(tags, child); end end stanza.tags = tags; end if not stanza.last_add then stanza.last_add = {}; end end return stanza; end function message(attr, body) if not body then return stanza("message", attr); else return stanza("message", attr):tag("body"):text(body); end end function iq(attr) if attr and not attr.id then attr.id = new_id(); end return stanza("iq", attr or { id = new_id() }); end function reply(orig) return stanza(orig.name, orig.attr and { to = orig.attr.from, from = orig.attr.to, id = orig.attr.id, type = ((orig.name == "iq" and "result") or orig.attr.type) }); end function error_reply(orig, type, condition, message, clone) local t = reply(orig); t.attr.type = "error"; -- TODO use clone t:tag("error", {type = type}) :tag(condition, {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"}):up(); if (message) then t:tag("text"):text(message):up(); end return t; -- stanza ready for adding app-specific errors end function presence(attr) return stanza("presence", attr); end return _M;
Fixed stanza deserialization
Fixed stanza deserialization
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
957a45add382519442ce6171109c92d94978021b
src/lib/yang/stream.lua
src/lib/yang/stream.lua
module(..., package.seeall) local ffi = require("ffi") local S = require("syscall") local lib = require("core.lib") local function round_up(x, y) return y*math.ceil(x/y) end function open_output_byte_stream(filename) local fd, err = S.open(filename, "creat, wronly, trunc", "rusr, wusr, rgrp, roth") if not fd then error("error opening output file "..filename..": "..tostring(err)) end local ret = { written = 0, name = filename } function ret:close() fd:close() end function ret:error(msg) self:close() error('while writing file '..filename..': '..msg) end function ret:write(ptr, size) assert(size) ptr = ffi.cast("uint8_t*", ptr) local to_write = size while to_write > 0 do local written, err = S.write(fd, ptr, to_write) if not written then self:error(err) end ptr = ptr + written self.written = self.written + written to_write = to_write - written end end function ret:write_ptr(ptr) self:align(ffi.alignof(ptr)) self:write(ptr, ffi.sizeof(ptr)) end function ret:rewind() fd:seek(0, 'set') ret.written = 0 -- more of a position at this point end function ret:write_array(ptr, type, count) self:align(ffi.alignof(type)) self:write(ptr, ffi.sizeof(type) * count) end function ret:align(alignment) local padding = round_up(self.written, alignment) - self.written self:write(string.rep(' ', padding), padding) end return ret end local function mktemp(name, mode) if not mode then mode = "rusr, wusr, rgrp, roth" end -- FIXME: If nothing seeds math.random, this produces completely -- predictable numbers. local t = math.random(1e7) local tmpnam, fd, err for i = t, t+10 do tmpnam = name .. '.' .. i fd, err = S.open(tmpnam, "creat, wronly, excl", mode) if fd then fd:close() return tmpnam, nil end i = i + 1 end return nil, err end function open_temporary_output_byte_stream(target) local tmp_file, err = mktemp(target) if not tmp_file then local dir = lib.dirname(target) error("failed to create temporary file in "..dir..": "..tostring(err)) end local stream = open_output_byte_stream(tmp_file) function stream:close_and_rename() self:close() local res, err = S.rename(tmp_file, target) if not res then error("failed to rename "..tmp_file.." to "..target..": "..err) end end return stream end -- FIXME: Try to copy file into huge pages? function open_input_byte_stream(filename) local fd, err = S.open(filename, "rdonly") if not fd then return error("error opening "..filename..": "..tostring(err)) end local stat = S.fstat(fd) local size = stat.size local mem, err = S.mmap(nil, size, 'read, write', 'private', fd, 0) fd:close() if not mem then error("mmap failed: " .. tostring(err)) end mem = ffi.cast("uint8_t*", mem) local pos = 0 local ret = { name=filename, mtime_sec=stat.st_mtime, mtime_nsec=stat.st_mtime_nsec } function ret:close() -- FIXME: Currently we don't unmap any memory. -- S.munmap(mem, size) mem, pos = nil, nil end function ret:error(msg) error('while reading file '..filename..': '..msg) end function ret:read(count) assert(count >= 0) local ptr = mem + pos pos = pos + count if pos > size then self:error('unexpected EOF') end return ptr end function ret:align(alignment) self:read(round_up(pos, alignment) - pos) end function ret:seek(new_pos) if new_pos == nil then return pos end assert(new_pos >= 0) assert(new_pos <= size) pos = new_pos end function ret:read_ptr(type) ret:align(ffi.alignof(type)) return ffi.cast(ffi.typeof('$*', type), ret:read(ffi.sizeof(type))) end function ret:read_array(type, count) ret:align(ffi.alignof(type)) return ffi.cast(ffi.typeof('$*', type), ret:read(ffi.sizeof(type) * count)) end function ret:read_char() return ffi.string(ret:read(1), 1) end function ret:read_string() return ffi.string(ret:read(size - pos), size - pos) end function ret:as_text_stream(len) local end_pos = size if len then end_pos = pos + len end return { name = ret.name, mtime_sec = ret.mtime_sec, mtime_nsec = ret.mtime_nsec, read = function(self, n) assert(n==1) if pos == end_pos then return nil end return ret:read_char() end, close = function() ret:close() end } end return ret end -- You're often better off using Lua's built-in files. This is here -- because it gives a file-like object whose FD you can query, for -- example to get its mtime. function open_input_text_stream(filename) return open_input_byte_stream(filename):as_text_stream() end
module(..., package.seeall) local ffi = require("ffi") local S = require("syscall") local lib = require("core.lib") local function round_up(x, y) return y*math.ceil(x/y) end function open_output_byte_stream(filename) local fd, err = S.open(filename, "creat, wronly, trunc", "rusr, wusr, rgrp, roth") if not fd then error("error opening output file "..filename..": "..tostring(err)) end local ret = { written = 0, name = filename } function ret:close() fd:close() end function ret:error(msg) self:close() error('while writing file '..filename..': '..msg) end function ret:write(ptr, size) assert(size) ptr = ffi.cast("uint8_t*", ptr) local to_write = size while to_write > 0 do local written, err = S.write(fd, ptr, to_write) if not written then self:error(err) end ptr = ptr + written self.written = self.written + written to_write = to_write - written end end function ret:write_ptr(ptr) self:align(ffi.alignof(ptr)) self:write(ptr, ffi.sizeof(ptr)) end function ret:rewind() fd:seek(0, 'set') ret.written = 0 -- more of a position at this point end function ret:write_array(ptr, type, count) self:align(ffi.alignof(type)) self:write(ptr, ffi.sizeof(type) * count) end function ret:align(alignment) local padding = round_up(self.written, alignment) - self.written self:write(string.rep(' ', padding), padding) end return ret end local function mktemp(name, mode) if not mode then mode = "rusr, wusr, rgrp, roth" end -- FIXME: If nothing seeds math.random, this produces completely -- predictable numbers. local t = math.random(1e7) local tmpnam, fd, err for i = t, t+10 do tmpnam = name .. '.' .. i fd, err = S.open(tmpnam, "creat, wronly, excl", mode) if fd then fd:close() return tmpnam, nil end i = i + 1 end return nil, err end function open_temporary_output_byte_stream(target) local tmp_file, err = mktemp(target) if not tmp_file then local dir = lib.dirname(target) error("failed to create temporary file in "..dir..": "..tostring(err)) end local stream = open_output_byte_stream(tmp_file) function stream:close_and_rename() self:close() local res, err = S.rename(tmp_file, target) if not res then error("failed to rename "..tmp_file.." to "..target..": "..err) end end return stream end -- FIXME: Try to copy file into huge pages? function open_input_byte_stream(filename) local fd, err = S.open(filename, "rdonly") if not fd then return error("error opening "..filename..": "..tostring(err)) end local stat = S.fstat(fd) local size = stat.size local mem, err = S.mmap(nil, size, 'read, write', 'private', fd, 0) fd:close() if not mem then error("mmap failed: " .. tostring(err)) end mem = ffi.cast("uint8_t*", mem) local pos = 0 local ret = { name=filename, mtime_sec=stat.st_mtime, mtime_nsec=stat.st_mtime_nsec } function ret:close() -- FIXME: Currently we don't unmap any memory. -- S.munmap(mem, size) mem, pos = nil, nil end function ret:error(msg) error('while reading file '..filename..': '..msg) end function ret:read(count) assert(count >= 0) local ptr = mem + pos pos = pos + count if pos > size then self:error('unexpected EOF') end return ptr end function ret:align(alignment) self:read(round_up(pos, alignment) - pos) end function ret:seek(new_pos) if new_pos == nil then return pos end assert(new_pos >= 0) assert(new_pos <= size) pos = new_pos end function ret:read_ptr(type) ret:align(ffi.alignof(type)) return ffi.cast(ffi.typeof('$*', type), ret:read(ffi.sizeof(type))) end function ret:read_array(type, count) ret:align(ffi.alignof(type)) return ffi.cast(ffi.typeof('$*', type), ret:read(ffi.sizeof(type) * count)) end function ret:read_char() return ffi.string(ret:read(1), 1) end function ret:read_string() local count = size - pos return ffi.string(ret:read(count), count) end function ret:as_text_stream(len) local end_pos = size if len then end_pos = pos + len end return { name = ret.name, mtime_sec = ret.mtime_sec, mtime_nsec = ret.mtime_nsec, read = function(self, n) assert(n==1) if pos == end_pos then return nil end return ret:read_char() end, close = function() ret:close() end } end return ret end -- You're often better off using Lua's built-in files. This is here -- because it gives a file-like object whose FD you can query, for -- example to get its mtime. function open_input_text_stream(filename) return open_input_byte_stream(filename):as_text_stream() end
Fix yang source parser bug for file streams
Fix yang source parser bug for file streams
Lua
apache-2.0
Igalia/snabbswitch,SnabbCo/snabbswitch,dpino/snabbswitch,alexandergall/snabbswitch,Igalia/snabb,dpino/snabbswitch,SnabbCo/snabbswitch,snabbco/snabb,Igalia/snabb,heryii/snabb,snabbco/snabb,dpino/snabbswitch,alexandergall/snabbswitch,Igalia/snabb,eugeneia/snabb,eugeneia/snabbswitch,SnabbCo/snabbswitch,heryii/snabb,alexandergall/snabbswitch,dpino/snabb,heryii/snabb,eugeneia/snabb,Igalia/snabb,alexandergall/snabbswitch,alexandergall/snabbswitch,eugeneia/snabb,eugeneia/snabb,eugeneia/snabbswitch,Igalia/snabb,dpino/snabb,snabbco/snabb,dpino/snabbswitch,dpino/snabb,snabbco/snabb,dpino/snabb,alexandergall/snabbswitch,Igalia/snabbswitch,Igalia/snabb,SnabbCo/snabbswitch,Igalia/snabb,Igalia/snabbswitch,dpino/snabb,Igalia/snabb,dpino/snabb,heryii/snabb,eugeneia/snabb,heryii/snabb,eugeneia/snabb,eugeneia/snabbswitch,snabbco/snabb,heryii/snabb,snabbco/snabb,dpino/snabb,eugeneia/snabb,Igalia/snabbswitch,snabbco/snabb,alexandergall/snabbswitch,alexandergall/snabbswitch,snabbco/snabb,eugeneia/snabb,eugeneia/snabbswitch,Igalia/snabbswitch
73b06a777daf394da901133d7695258cdb4c2973
[resources]/GTWcore/misc/s_data.lua
[resources]/GTWcore/misc/s_data.lua
--[[ ******************************************************************************** Project owner: RageQuit community Project name: GTW-RPG Developers: Mr_Moose Source code: https://github.com/GTWCode/GTW-RPG/ Bugtracker: http://forum.404rq.com/bug-reports/ Suggestions: http://forum.404rq.com/mta-servers-development/ Version: Open source License: BSD 2-Clause Status: Stable release ******************************************************************************** ]]-- --[[ Load player data ]]-- function load_data(plr) -- Make sure we have a vaplid player element if not plr or not isElement(plr) or getElementType(plr) ~= "player" then return end -- Get and validate player account local acc = getPlayerAccount(plr) if not acc or isGuestAccount(acc) then return end -- Load money in pocket setPlayerMoney(plr, tonumber(getAccountData(acc, "GTWdata.money")) or 0) -- Restore rotation local rotX = getAccountData(acc, "GTWdata.loc.rot.x") or 0 local rotY = getAccountData(acc, "GTWdata.loc.rot.y") or 0 local rotZ = getAccountData(acc, "GTWdata.loc.rot.z") or 0 setElementRotation(plr, rotX, rotY, rotZ) -- Load team and nametag colors local tagR = getAccountData(acc, "GTWdata.col.r") local tagG = getAccountData(acc, "GTWdata.col.g") local tagB = getAccountData(acc, "GTWdata.col.b") setPlayerNametagColor(plr, tagR or 255, tagG or 255, tagB or 255) -- Load skind or set a random one if not available local rnd_skin = math.random(20,46) setElementModel(plr, getAccountData(acc, "GTWdata.skin.current") or rnd_skin) setAccountData(acc, "clothes.boughtSkin", getAccountData(acc, "GTWdata.skin.current") or rnd_skin) -- Load and set team and occupation setPlayerTeam(plr, getTeamFromName(getAccountData(acc, "GTWdata.team.occupation") or "Unemployed")) setElementData(plr, "Occupation", getAccountData(acc, "GTWdata.team.occupation.sub") or "") -- Load wanted level and violent time exports.GTWwanted:setWl(plr, (tonumber(getAccountData(acc, "GTWdata.wanted")) or 0), (tonumber(getAccountData(acc, "GTWdata.wanted.viol")) or 0)) setElementInterior(plr, getAccountData(acc, "GTWdata.loc.int") or 0) setElementDimension(plr, getAccountData(acc, "GTWdata.loc.dim") or 0) -- Load health and armor setElementHealth(plr, getAccountData(acc, "GTWdata.health") or 100) setPedArmor(plr, getAccountData(acc, "GTWdata.armor") or 0) -- Assuming first login, hand out start money and setup basic defaults local play_time = getAccountData(acc, "GTWdata.playtime") or 0 if not play_time then setPlayerMoney(plr, 1337) setAccountData(acc, "GTWdata.playtime", 0) end -- Load weapons and stats for k=1, 12 do local weapon = tonumber(getAccountData(acc, "GTWdata.weapon."..tostring(k)) or 0) local ammo = tonumber(getAccountData(acc, "GTWdata.ammo."..tostring(k)) or 0) local stat = tonumber(getAccountData(acc, "GTWdata.weapon.stats."..tostring(k+68)) or 0) -- Set weapon, saved amount of ammo and stats giveWeapon(plr, weapon, ammo, false) setPedStat(plr, (k+68), stat) end -- Apply jetpack and other advantages if staff applyStaffAdvantage(source) -- Jail player if arrested if getAccountData(acc, "GTWdata.police.isArrested") == "YES" then local wl,viol = exports.GTWwanted:getWl(plr) local j_time = math.floor(wl*1000*10) exports.GTWjail:Jail(plr, math.floor(j_time/1000), "LSPD") end -- Mark first spawn as valid setElementData(source, "GTWdata.isFirstSpawn", nil) end --[[ Save player data ]]-- function save_data(plr) -- Make sure we have a vaplid player element if not plr or not isElement(plr) or getElementType(plr) ~= "player" then return end -- Get and validate player account local acc = getPlayerAccount(plr) if not acc or isGuestAccount(acc) then return end -- Save the money in pocket first setAccountData(acc, "GTWdata.money", getPlayerMoney(plr) or 0) -- Move on to location data local x,y,z = getElementPosition(plr) setAccountData(acc, "GTWdata.loc.x", x) setAccountData(acc, "GTWdata.loc.y", y) setAccountData(acc, "GTWdata.loc.z", z) -- And rotation data local rotX,rotY,rotZ = getElementRotation(plr) setAccountData(acc, "GTWdata.loc.rot.x", rotX) setAccountData(acc, "GTWdata.loc.rot.y", rotY) setAccountData(acc, "GTWdata.loc.rot.z", rotZ) -- Do not forget interior and dimension setAccountData(acc, "GTWdata.loc.int", getElementInterior(plr) or 0) setAccountData(acc, "GTWdata.loc.dim", getElementDimension(plr) or 0) -- Save current skin for the next login setAccountData(acc, "GTWdata.skin.current", getElementModel(plr) or 0) -- Save wanted level and violent time setAccountData(acc, "GTWdata.wanted", getElementData(plr, "Wanted") or 0) setAccountData(acc, "GTWdata.wanted.viol", getElementData(plr, "violent_time" or 0)) -- Team, occupation and team colors local plr_team = getPlayerTeam(plr) or getTeamFromName("Unemployed") local r,g,b = getTeamColor(plr_team) setAccountData(acc, "GTWdata.team.occupation", getTeamName(plr_team)) setAccountData(acc, "GTWdata.team.occupation.sub", getElementData(plr, "Occupation") or "") setAccountData(acc, "GTWdata.col.r", r) setAccountData(acc, "GTWdata.col.g", g) setAccountData(acc, "GTWdata.col.b", b) -- Save current health and armor setAccountData(acc, "GTWdata.health", getElementHealth(plr)) setAccountData(acc, "GTWdata.armor", getPedArmor(plr)) -- Weapons, ammo and weapon stats for k=1, 12 do local stat_wep = getPedStat(plr, (k+68)) setAccountData(acc, "GTWdata.weapon.stats."..tostring((k+68)), stat_wep) local weapon = getPedWeapon(plr, k) setPedWeaponSlot(plr, k) local ammo = getPedTotalAmmo(plr, k) -- Save data fetched earlier setAccountData(acc, "GTWdata.weapon."..tostring(k), weapon) setAccountData(acc, "GTWdata.ammo."..tostring(k), ammo) end -- Skip these --setAccountData(playeraccount, "GTWdata.loc.city", city) --setAccountData(playeraccount, "GTWdata.gear.type", gearType) --setAccountData(playeraccount, "GTWdata.lawbanned", lawban) --setAccountData(playeraccount, "GTWdata.is.worker", isWorker) end
--[[ ******************************************************************************** Project owner: RageQuit community Project name: GTW-RPG Developers: Mr_Moose Source code: https://github.com/GTWCode/GTW-RPG/ Bugtracker: http://forum.404rq.com/bug-reports/ Suggestions: http://forum.404rq.com/mta-servers-development/ Version: Open source License: BSD 2-Clause Status: Stable release ******************************************************************************** ]]-- --[[ Load player data ]]-- function load_data(plr) -- Make sure we have a vaplid player element if not plr or not isElement(plr) or getElementType(plr) ~= "player" then return end -- Get and validate player account local acc = getPlayerAccount(plr) if not acc or isGuestAccount(acc) then return end -- Load money in pocket setPlayerMoney(plr, tonumber(getAccountData(acc, "GTWdata.money")) or 0) -- Restore rotation local rotX = getAccountData(acc, "GTWdata.loc.rot.x") or 0 local rotY = getAccountData(acc, "GTWdata.loc.rot.y") or 0 local rotZ = getAccountData(acc, "GTWdata.loc.rot.z") or 0 setElementRotation(plr, rotX, rotY, rotZ) -- Load team and nametag colors local tagR = getAccountData(acc, "GTWdata.col.r") local tagG = getAccountData(acc, "GTWdata.col.g") local tagB = getAccountData(acc, "GTWdata.col.b") setPlayerNametagColor(plr, tagR or 255, tagG or 255, tagB or 255) -- Load skind or set a random one if not available local rnd_skin = math.random(20,46) setElementModel(plr, getAccountData(acc, "GTWdata.skin.current") or rnd_skin) setAccountData(acc, "clothes.boughtSkin", getAccountData(acc, "GTWdata.skin.current") or rnd_skin) -- Load and set team and occupation setPlayerTeam(plr, getTeamFromName(getAccountData(acc, "GTWdata.team.occupation") or "Unemployed")) setElementData(plr, "Occupation", getAccountData(acc, "GTWdata.team.occupation.sub") or "") -- Load wanted level and violent time exports.GTWwanted:setWl(plr, (tonumber(getAccountData(acc, "GTWdata.wanted")) or 0), (tonumber(getAccountData(acc, "GTWdata.wanted.viol")) or 0)) setElementInterior(plr, getAccountData(acc, "GTWdata.loc.int") or 0) setElementDimension(plr, getAccountData(acc, "GTWdata.loc.dim") or 0) -- Load health and armor setElementHealth(plr, getAccountData(acc, "GTWdata.health") or 100) setPedArmor(plr, getAccountData(acc, "GTWdata.armor") or 0) -- Assuming first login, hand out start money and setup basic defaults local play_time = getAccountData(acc, "GTWdata.playtime") or 0 if not play_time then setPlayerMoney(plr, 1337) setAccountData(acc, "GTWdata.playtime", 0) end -- Load weapons and stats for k=1, 12 do local weapon = tonumber(getAccountData(acc, "GTWdata.weapon."..tostring(k)) or 0) local ammo = tonumber(getAccountData(acc, "GTWdata.ammo."..tostring(k)) or 0) local stat = tonumber(getAccountData(acc, "GTWdata.weapon.stats."..tostring(k+68)) or 0) -- Set weapon, saved amount of ammo and stats giveWeapon(plr, weapon, ammo, false) setPedStat(plr, (k+68), stat) end -- Apply jetpack and other advantages if staff applyStaffAdvantage(source) -- Jail player if arrested if getAccountData(acc, "GTWdata.police.isArrested") == "YES" then local wl,viol = exports.GTWwanted:getWl(plr) local j_time = math.floor(wl*1000*10) exports.GTWjail:Jail(plr, math.floor(j_time/1000), "LSPD") end -- Mark first spawn as valid setElementData(source, "GTWdata.isFirstSpawn", nil) end --[[ Save player data ]]-- function save_data(plr) -- Make sure we have a vaplid player element if not plr or not isElement(plr) or getElementType(plr) ~= "player" then return end -- Get and validate player account local acc = getPlayerAccount(plr) if not acc or isGuestAccount(acc) then return end -- Save the money in pocket first setAccountData(acc, "GTWdata.money", getPlayerMoney(plr) or 0) -- Move on to location data local x,y,z = getElementPosition(plr) setAccountData(acc, "GTWdata.loc.x", x) setAccountData(acc, "GTWdata.loc.y", y) setAccountData(acc, "GTWdata.loc.z", z) -- And rotation data local rotX,rotY,rotZ = getElementRotation(plr) setAccountData(acc, "GTWdata.loc.rot.x", rotX) setAccountData(acc, "GTWdata.loc.rot.y", rotY) setAccountData(acc, "GTWdata.loc.rot.z", rotZ) -- Do not forget interior and dimension setAccountData(acc, "GTWdata.loc.int", getElementInterior(plr) or 0) setAccountData(acc, "GTWdata.loc.dim", getElementDimension(plr) or 0) -- Save current skin for the next login setAccountData(acc, "GTWdata.skin.current", getElementModel(plr) or 0) -- Save wanted level and violent time setAccountData(acc, "GTWdata.wanted", getElementData(plr, "Wanted") or 0) setAccountData(acc, "GTWdata.wanted.viol", getElementData(plr, "violent_time" or 0)) -- Team, occupation and team colors local plr_team = getPlayerTeam(plr) or getTeamFromName("Unemployed") local r,g,b = getTeamColor(plr_team) setAccountData(acc, "GTWdata.team.occupation", getTeamName(plr_team)) setAccountData(acc, "GTWdata.team.occupation.sub", getElementData(plr, "Occupation") or "") setAccountData(acc, "GTWdata.col.r", r) setAccountData(acc, "GTWdata.col.g", g) setAccountData(acc, "GTWdata.col.b", b) -- Save current health and armor setAccountData(acc, "GTWdata.health", getElementHealth(plr)) setAccountData(acc, "GTWdata.armor", getPedArmor(plr)) -- Weapons, ammo and weapon stats local tmp_slot = getPedWeaponSlot(plr) for k=1, 12 do local stat_wep = getPedStat(plr, (k+68)) setAccountData(acc, "GTWdata.weapon.stats."..tostring((k+68)), stat_wep) local weapon = getPedWeapon(plr, k) setPedWeaponSlot(plr, k) local ammo = getPedTotalAmmo(plr, k) -- Save data fetched earlier setAccountData(acc, "GTWdata.weapon."..tostring(k), weapon) setAccountData(acc, "GTWdata.ammo."..tostring(k), ammo) end setPedWeaponSlot(plr, tmp_slot) -- Skip these --setAccountData(playeraccount, "GTWdata.loc.city", city) --setAccountData(playeraccount, "GTWdata.gear.type", gearType) --setAccountData(playeraccount, "GTWdata.lawbanned", lawban) --setAccountData(playeraccount, "GTWdata.is.worker", isWorker) end
[Patch] Fixed random switching to RPG
[Patch] Fixed random switching to RPG Weapon slots wasn't reset properly after saving weapons, the code pretty much explains itself.
Lua
bsd-2-clause
404rq/GTW-RPG,GTWCode/GTW-RPG,404rq/GTW-RPG,GTWCode/GTW-RPG,GTWCode/GTW-RPG,404rq/GTW-RPG
99600c057b98a53e079639aa89215a4921aced36
MMOCoreORB/bin/scripts/mobile/creatures.lua
MMOCoreORB/bin/scripts/mobile/creatures.lua
Creature = { objectName = "", socialGroup = "", pvpFaction = "", faction = "", level = 0, chanceHit = 0.000000, damageMin = 0, damageMax = 0, range = 0, baseXp = 0, baseHAM = 0, armor = 0, resists = {0,0,0,0,0,0,0,0,0}, meatType = "", meatAmount = 0, hideType = "", hideAmount = 0, boneType = "", boneAmount = 0, milk = 0, tamingChance = 0.000000, ferocity = 0, pvpBitmask = NONE, creatureBitmask = NONE, diet = 0, scale = 1.0, templates = {}, lootGroups = {}, weapons = {}, attacks = {}, conversationTemplate = "", optionsBitmask = 128 } function Creature:new (o) o = o or { } setmetatable(o, self) self.__index = self return o end CreatureTemplates = { } function CreatureTemplates:addCreatureTemplate(obj, file) if (obj == nil) then print("null template specified for " .. file) else addTemplate(file, obj) end end function getCreatureTemplate(crc) return CreatureTemplates[crc] end function merge(a, ...) r = a for j,k in ipairs(arg) do table.foreach(k, function(i,v)table.insert(r,v) end ) end return r end includeFile("creatureskills.lua") includeFile("conversation.lua") includeFile("serverobjects.lua")
Creature = { objectName = "", socialGroup = "", pvpFaction = "", faction = "", level = 0, chanceHit = 0.000000, damageMin = 0, damageMax = 0, range = 0, baseXp = 0, baseHAM = 0, armor = 0, resists = {0,0,0,0,0,0,0,0,0}, meatType = "", meatAmount = 0, hideType = "", hideAmount = 0, boneType = "", boneAmount = 0, milk = 0, tamingChance = 0.000000, ferocity = 0, pvpBitmask = NONE, creatureBitmask = NONE, diet = 0, scale = 1.0, templates = {}, lootGroups = {}, weapons = {}, attacks = {}, conversationTemplate = "", optionsBitmask = 128 } function Creature:new (o) o = o or { } setmetatable(o, self) self.__index = self return o end CreatureTemplates = { } function CreatureTemplates:addCreatureTemplate(obj, file) if (obj == nil) then print("null template specified for " .. file) else addTemplate(file, obj) end end function getCreatureTemplate(crc) return CreatureTemplates[crc] end function deepcopy(t) local u = { } for k, v in pairs(t) do u[k] = v end return setmetatable(u, getmetatable(t)) end function merge(a, ...) local r = deepcopy(a) for j,k in ipairs(arg) do table.foreach(k, function(i,v)table.insert(r,v) end ) end return r end includeFile("creatureskills.lua") includeFile("conversation.lua") includeFile("serverobjects.lua")
[fixed] deepcopy of attacks
[fixed] deepcopy of attacks git-svn-id: c34995188cc7e843f8a799edec2d9d4b36f36456@4982 c3d1530f-68f5-4bd0-87dc-8ef779617e40
Lua
agpl-3.0
lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo
635299359c5ed0e78f397d113477a4fab0707827
lib/px/utils/pxtimer.lua
lib/px/utils/pxtimer.lua
--------------------------------------------- -- PerimeterX(www.perimeterx.com) Nginx plugin ---------------------------------------------- local M = {} function M.application(px_configutraion_table) local config_builder = require("px.utils.config_builder"); local px_config = config_builder.load(px_configutraion_table) local pxclient = require ("px.utils.pxclient").load(px_config) local px_logger = require ("px.utils.pxlogger").load(px_config) local px_constants = require("px.utils.pxconstants") local buffer = require "px.utils.pxbuffer" local px_commom_utils = require('px.utils.pxcommonutils') local ngx_timer_at = ngx.timer.at function send_initial_enforcer_telemetry() if px_config == nil or not px_config.px_enabled then px_logger.debug("module is disabled, skipping enforcer telemetry") return end if px_config.px_appId == 'PX_APP_ID' then return end local details = {} details.px_config = px_commom_utils.filter_config(px_config); details.update_reason = 'initial_config' pxclient.send_enforcer_telmetry(details); end function init_remote_config() if px_config == nil or not px_config.px_enabled then px_logger.debug("module is disabled, skipping remote config") return end if px_config.px_appId == 'PX_APP_ID' then return end if px_config.dynamic_configurations then require("px.utils.config_loader").load(px_config) end end function submit_on_timer() if px_config == nil or not px_config.px_enabled then px_logger.debug("module is disabled, skipping submit timer") return end local ok, err = ngx_timer_at(1, submit_on_timer) if not ok then px_logger.debug("Failed to schedule submit timer: " .. err) end local buflen = buffer.getBufferLength() if buflen > 0 then pcall(pxclient.submit, buffer.dumpEvents(), px_constants.ACTIVITIES_PATH) end return end -- Init async activities submit_on_timer() -- Enforcer telemerty first init local ok, err = ngx_timer_at(1, send_initial_enforcer_telemetry) if not ok then px_logger.debug("Failed to schedule telemetry on init: " .. err) end -- Init Remote configuration local ok, err = ngx_timer_at(1, init_remote_config) if not ok then px_logger.error("Failed to init remote config: " .. err) end end return M
--------------------------------------------- -- PerimeterX(www.perimeterx.com) Nginx plugin ---------------------------------------------- local M = {} function M.application(px_configutraion_table) local config_builder = require("px.utils.config_builder"); local px_config = config_builder.load(px_configutraion_table) local pxclient = require ("px.utils.pxclient").load(px_config) local px_logger = require ("px.utils.pxlogger").load(px_config) local px_constants = require("px.utils.pxconstants") local buffer = require "px.utils.pxbuffer" local px_commom_utils = require('px.utils.pxcommonutils') local ngx_timer_at = ngx.timer.at function send_initial_enforcer_telemetry() if px_config == nil or not px_config.px_enabled then px_logger.debug("module is disabled, skipping enforcer telemetry") return end if px_config.px_appId == 'PX_APP_ID' then return end local details = {} details.px_config = px_commom_utils.filter_config(px_config); details.update_reason = 'initial_config' pxclient.send_enforcer_telmetry(details); end function init_remote_config() if px_config == nil or not px_config.px_enabled then px_logger.debug("module is disabled, skipping remote config") return end if px_config.px_appId == 'PX_APP_ID' then return end if px_config.dynamic_configurations then require("px.utils.config_loader").load(px_config) end end function submit_on_timer() if px_config == nil or not px_config.px_enabled then px_logger.debug("module is disabled, skipping submit timer") return end local ok, err = ngx_timer_at(1, submit_on_timer) if not ok then px_logger.debug("Failed to schedule submit timer: " .. err) end local buflen = buffer.getBufferLength() if buflen > 0 then pcall(pxclient.submit, buffer.dumpEvents(), px_constants.ACTIVITIES_PATH) end return end -- Init async activities submit_on_timer() -- Enforcer telemerty first init local ok, err = ngx_timer_at(1, send_initial_enforcer_telemetry) if not ok then px_logger.debug("Failed to schedule telemetry on init: " .. err) end -- Init Remote configuration local ok, err = ngx_timer_at(1, init_remote_config) if not ok then px_logger.error("Failed to init remote config: " .. err) end end return M
fixed line indents pxtimer.lua
fixed line indents pxtimer.lua
Lua
mit
PerimeterX/perimeterx-nginx-plugin