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
9549cbc14ebd941d3cc1b934d410a5d9ddf34af6
UCDsafeZones/client.lua
UCDsafeZones/client.lua
local LS = createColTube(1181, -1324, 10, 30, 10) -- All Saints Hospital local LS2 = createColRectangle(1980, -1454, 125, 80) -- Jefferson Hospital local SF = createColRectangle(-2745, 576, 135, 100) -- SF Hospital local LV = createColPolygon(1559, 1801, 1559, 1801, 1558, 1910, 1674, 1910, 1681, 1806) -- LV Hospital local sZone = {LS, JF, SF1, LV} function isElementWithinSafeZone(element) if not isElement(element) then return false end if (element.dimension ~= 0 or element.interior ~= 0) then return false end for i, sZone in pairs(sZone) do if (isElementWithinColShape(element, sZone)) then return true end end return false end function zoneEntry(element, matchingDimension) if (element ~= localPlayer or not matchingDimension) then return end if (isControlEnabled("aim_weapon") and localPlayer.team ~= "Admins") then toggleControl("aim_weapon", false) toggleControl("fire", false) end --exports.UCDdx:new("You have entered a safe zone", 50, 200, 70) exports.UCDdx:add("Safe Zone", 0, 255, 0) end function zoneExit(element, matchingDimension) if (element ~= localPlayer or not matchingDimension) then return end --exports.UCDdx:new("You have left a safe zone", 50, 200, 70) exports.UCDdx:del("Safe Zone") end for i, sZone in pairs(sZone) do addEventHandler("onClientColShapeHit", sZone, zoneEntry) addEventHandler("onClientColShapeLeave", sZone, zoneExit) end function cancelDmg() if (isElementWithinSafeZone(localPlayer)) then if (getPlayerWantedLevel(localPlayer) > 0) then return end cancelEvent() end end addEventHandler("onClientPlayerDamage", root, cancelDmg)
local LS = createColTube(1181, -1324, 10, 30, 10) -- All Saints Hospital local LS2 = createColRectangle(1980, -1454, 125, 80) -- Jefferson Hospital local SF = createColRectangle(-2745, 576, 135, 100) -- SF Hospital local LV = createColPolygon(1559, 1801, 1559, 1801, 1558, 1910, 1674, 1910, 1681, 1806) -- LV Hospital local sZone = {LS, JF, SF1, LV} function isElementWithinSafeZone(element) if not isElement(element) then return false end if (element.dimension ~= 0 or element.interior ~= 0) then return false end for i, sZone in pairs(sZone) do if (isElementWithinColShape(element, sZone)) then return true end end return false end function zoneEntry(element, matchingDimension) if (element ~= localPlayer or not matchingDimension) then return end if (isControlEnabled("aim_weapon") and localPlayer.team ~= "Admins") then toggleControl("aim_weapon", false) toggleControl("fire", false) end --exports.UCDdx:new("You have entered a safe zone", 50, 200, 70) exports.UCDdx:add("safezone", "Safe Zone", 0, 255, 0) end function zoneExit(element, matchingDimension) if (element ~= localPlayer or not matchingDimension) then return end --exports.UCDdx:new("You have left a safe zone", 50, 200, 70) exports.UCDdx:del("safezone") end for i, sZone in pairs(sZone) do addEventHandler("onClientColShapeHit", sZone, zoneEntry) addEventHandler("onClientColShapeLeave", sZone, zoneExit) end function cancelDmg() if (isElementWithinSafeZone(source)) then if (getPlayerWantedLevel(source) > 0) then return end cancelEvent() end end addEventHandler("onClientPlayerDamage", root, cancelDmg, true, "high")
UCDsafeZones
UCDsafeZones - Fixed it to work with new dx side bar.
Lua
mit
nokizorque/ucd,nokizorque/ucd
68fde66cb434bda810076ac128d46ab6f53c979d
MMOCoreORB/bin/scripts/mobile/lair/naboo_peko_peko_giant_pair_neutral_none.lua
MMOCoreORB/bin/scripts/mobile/lair/naboo_peko_peko_giant_pair_neutral_none.lua
naboo_peko_peko_giant_pair_neutral_none = Lair:new { mobiles = {{"giant_peko_peko", 0}}, spawnLimit = 15, buildingsVeryEasy = {"object/tangible/lair/peko_peko/lair_peko_peko_grassland.iff"}, buildingsEasy = {"object/tangible/lair/peko_peko/lair_peko_peko_grassland.iff"}, buildingsMedium = {"object/tangible/lair/peko_peko/lair_peko_peko_grassland.iff"}, buildingsHard = {"object/tangible/lair/peko_peko/lair_peko_peko_grassland.iff"}, buildingsVeryHard = {"object/tangible/lair/peko_peko/lair_peko_peko_grassland.iff"}, } addLairTemplate("naboo_peko_peko_giant_pair_neutral_none", naboo_peko_peko_giant_pair_neutral_none)
naboo_peko_peko_giant_pair_neutral_none = Lair:new { mobiles = {{"giant_peko_peko", 0}}, spawnLimit = 15, buildingsVeryEasy = {"object/tangible/lair/base/poi_all_lair_bones_large_evil_fire_red.iff"}, buildingsEasy = {"object/tangible/lair/base/poi_all_lair_bones_large_evil_fire_red.iff"}, buildingsMedium = {"object/tangible/lair/base/poi_all_lair_bones_large_evil_fire_red.iff"}, buildingsHard = {"object/tangible/lair/base/poi_all_lair_bones_large_evil_fire_red.iff"}, buildingsVeryHard = {"object/tangible/lair/base/poi_all_lair_bones_large_evil_fire_red.iff"} } addLairTemplate("naboo_peko_peko_giant_pair_neutral_none", naboo_peko_peko_giant_pair_neutral_none)
[Fixed] mantis 3970 giant peko peko lair
[Fixed] mantis 3970 giant peko peko lair Change-Id: Idedba8a4eb00bcd97c4bb5851fabef528479a9fd
Lua
agpl-3.0
lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,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
9f69c4be20a38583cd928644c47c1f5165aae380
fontchooser.lua
fontchooser.lua
require "rendertext" require "keys" require "graphics" FontChooser = { -- font for displaying file/dir names face = freetype.newBuiltinFace("sans", 25), fhash = "s25", -- font for page title tface = freetype.newBuiltinFace("Helvetica-BoldOblique", 30), tfhash = "hbo30", -- font for paging display sface = freetype.newBuiltinFace("sans", 16), sfhash = "s16", -- title height title_H = 45, -- spacing between lines spacing = 40, -- foot height foot_H = 27, -- state buffer fonts = {"sans", "cjk", "mono", "Courier", "Courier-Bold", "Courier-Oblique", "Courier-BoldOblique", "Helvetica", "Helvetica-Oblique", "Helvetica-BoldOblique", "Times-Roman", "Times-Bold", "Times-Italic", "Times-BoldItalic",}, items = 14, page = 1, current = 1, oldcurrent = 0, } function FontChooser:init() clearglyphcache() self.items = #self.fonts end function FontChooser:choose(ypos, height) local perpage = math.floor(height / self.spacing) - 2 local pagedirty = true local markerdirty = false local prevItem = function () if self.current == 1 then if self.page > 1 then self.current = perpage self.page = self.page - 1 pagedirty = true end else self.current = self.current - 1 markerdirty = true end end local nextItem = function () if self.current == perpage then if self.page < (self.items / perpage) then self.current = 1 self.page = self.page + 1 pagedirty = true end else if self.page ~= math.floor(self.items / perpage) + 1 or self.current + (self.page-1)*perpage < self.items then self.current = self.current + 1 markerdirty = true end end end while true do if pagedirty then -- draw menu title fb.bb:paintRect(30, ypos + 10, fb.bb:getWidth() - 60, self.title_H, 5) x = fb.bb:getWidth() - 220 -- move text to the right y = ypos + self.title_H renderUtf8Text(fb.bb, x, y, self.tface, self.tfhash, "Fonts Menu", true) -- draw font items fb.bb:paintRect(0, ypos + self.title_H + 10, fb.bb:getWidth(), height - self.title_H, 0) local c for c = 1, perpage do local i = (self.page - 1) * perpage + c if i <= self.items then y = ypos + self.title_H + (self.spacing * c) renderUtf8Text(fb.bb, 50, y, self.face, self.fhash, self.fonts[i], true) end end -- draw footer y = ypos + self.title_H + (self.spacing * perpage) + self.foot_H x = (fb.bb:getWidth() / 2) - 50 renderUtf8Text(fb.bb, x, y, self.sface, self.sfhash, "Page "..self.page.." of "..(math.floor(self.items / perpage)+1), true) markerdirty = true end if markerdirty then if not pagedirty then if self.oldcurrent > 0 then y = ypos + self.title_H + (self.spacing * self.oldcurrent) + 10 fb.bb:paintRect(30, y, fb.bb:getWidth() - 60, 3, 0) fb:refresh(1, 30, y, fb.bb:getWidth() - 60, 3) end end -- draw new marker line y = ypos + self.title_H + (self.spacing * self.current) + 10 fb.bb:paintRect(30, y, fb.bb:getWidth() - 60, 3, 15) if not pagedirty then fb:refresh(1, 30, y, fb.bb:getWidth() - 60, 3) end self.oldcurrent = self.current markerdirty = false end if pagedirty then fb:refresh(0, 0, ypos, fb.bb:getWidth(), height) pagedirty = false end local ev = input.waitForEvent() if ev.type == EV_KEY and ev.value == EVENT_VALUE_KEY_PRESS then ev.code = adjustFWKey(ev.code) if ev.code == KEY_FW_UP then prevItem() elseif ev.code == KEY_FW_DOWN then nextItem() elseif ev.code == KEY_PGFWD then if self.page < (self.items / perpage) then if self.current + self.page*perpage > self.items then self.current = self.items - self.page*perpage end self.page = self.page + 1 pagedirty = true else self.current = self.items - (self.page-1)*perpage markerdirty = true end elseif ev.code == KEY_PGBCK then if self.page > 1 then self.page = self.page - 1 pagedirty = true else self.current = 1 markerdirty = true end elseif ev.code == KEY_ENTER or ev.code == KEY_FW_PRESS then local newface = self.fonts[perpage*(self.page-1)+self.current] return newface elseif ev.code == KEY_BACK then return nil end end end end
require "rendertext" require "keys" require "graphics" FontChooser = { -- font for displaying file/dir names face = freetype.newBuiltinFace("sans", 25), fhash = "s25", -- font for page title tface = freetype.newBuiltinFace("Helvetica-BoldOblique", 30), tfhash = "hbo30", -- font for paging display sface = freetype.newBuiltinFace("sans", 16), sfhash = "s16", -- title height title_H = 45, -- spacing between lines spacing = 40, -- foot height foot_H = 27, -- state buffer fonts = {"sans", "cjk", "mono", "Courier", "Courier-Bold", "Courier-Oblique", "Courier-BoldOblique", "Helvetica", "Helvetica-Oblique", "Helvetica-BoldOblique", "Times-Roman", "Times-Bold", "Times-Italic", "Times-BoldItalic",}, items = 14, page = 1, current = 1, oldcurrent = 0, } function FontChooser:init() clearglyphcache() self.items = #self.fonts end function FontChooser:choose(ypos, height) local perpage = math.floor(height / self.spacing) - 2 local pagedirty = true local markerdirty = false local prevItem = function () if self.current == 1 then if self.page > 1 then self.current = perpage self.page = self.page - 1 pagedirty = true end else self.current = self.current - 1 markerdirty = true end end local nextItem = function () if self.current == perpage then if self.page < (self.items / perpage) then self.current = 1 self.page = self.page + 1 pagedirty = true end else if self.page ~= math.floor(self.items / perpage) + 1 or self.current + (self.page-1)*perpage < self.items then self.current = self.current + 1 markerdirty = true end end end while true do if pagedirty then -- draw menu title fb.bb:paintRect(0, ypos, fb.bb:getWidth(), self.title_H + 10, 0) fb.bb:paintRect(30, ypos + 10, fb.bb:getWidth() - 60, self.title_H, 5) x = fb.bb:getWidth() - 220 -- move text to the right y = ypos + self.title_H renderUtf8Text(fb.bb, x, y, self.tface, self.tfhash, "Fonts Menu", true) -- draw font items fb.bb:paintRect(0, ypos + self.title_H + 10, fb.bb:getWidth(), height - self.title_H, 0) local c for c = 1, perpage do local i = (self.page - 1) * perpage + c if i <= self.items then y = ypos + self.title_H + (self.spacing * c) renderUtf8Text(fb.bb, 50, y, self.face, self.fhash, self.fonts[i], true) end end -- draw footer y = ypos + self.title_H + (self.spacing * perpage) + self.foot_H x = (fb.bb:getWidth() / 2) - 50 renderUtf8Text(fb.bb, x, y, self.sface, self.sfhash, "Page "..self.page.." of "..(math.floor(self.items / perpage)+1), true) markerdirty = true end if markerdirty then if not pagedirty then if self.oldcurrent > 0 then y = ypos + self.title_H + (self.spacing * self.oldcurrent) + 10 fb.bb:paintRect(30, y, fb.bb:getWidth() - 60, 3, 0) fb:refresh(1, 30, y, fb.bb:getWidth() - 60, 3) end end -- draw new marker line y = ypos + self.title_H + (self.spacing * self.current) + 10 fb.bb:paintRect(30, y, fb.bb:getWidth() - 60, 3, 15) if not pagedirty then fb:refresh(1, 30, y, fb.bb:getWidth() - 60, 3) end self.oldcurrent = self.current markerdirty = false end if pagedirty then fb:refresh(0, 0, ypos, fb.bb:getWidth(), height) pagedirty = false end local ev = input.waitForEvent() if ev.type == EV_KEY and ev.value == EVENT_VALUE_KEY_PRESS then ev.code = adjustFWKey(ev.code) if ev.code == KEY_FW_UP then prevItem() elseif ev.code == KEY_FW_DOWN then nextItem() elseif ev.code == KEY_PGFWD then if self.page < (self.items / perpage) then if self.current + self.page*perpage > self.items then self.current = self.items - self.page*perpage end self.page = self.page + 1 pagedirty = true else self.current = self.items - (self.page-1)*perpage markerdirty = true end elseif ev.code == KEY_PGBCK then if self.page > 1 then self.page = self.page - 1 pagedirty = true else self.current = 1 markerdirty = true end elseif ev.code == KEY_ENTER or ev.code == KEY_FW_PRESS then local newface = self.fonts[perpage*(self.page-1)+self.current] return newface elseif ev.code == KEY_BACK then return nil end end end end
fix: fill space above title background
fix: fill space above title background
Lua
agpl-3.0
Frenzie/koreader-base,NiLuJe/koreader-base,houqp/koreader-base,apletnev/koreader-base,apletnev/koreader-base,Hzj-jie/koreader-base,koreader/koreader,Hzj-jie/koreader,mwoz123/koreader,Hzj-jie/koreader-base,koreader/koreader-base,Frenzie/koreader,frankyifei/koreader-base,chrox/koreader,Frenzie/koreader-base,NickSavage/koreader,Frenzie/koreader,koreader/koreader-base,Frenzie/koreader-base,NiLuJe/koreader-base,mihailim/koreader,ashhher3/koreader,NiLuJe/koreader,Hzj-jie/koreader-base,houqp/koreader-base,houqp/koreader,frankyifei/koreader-base,poire-z/koreader,houqp/koreader-base,koreader/koreader-base,chihyang/koreader,apletnev/koreader-base,Hzj-jie/koreader-base,lgeek/koreader,poire-z/koreader,frankyifei/koreader-base,apletnev/koreader,koreader/koreader-base,koreader/koreader,noname007/koreader,Frenzie/koreader-base,frankyifei/koreader-base,frankyifei/koreader,robert00s/koreader,NiLuJe/koreader-base,pazos/koreader,NiLuJe/koreader,houqp/koreader-base,NiLuJe/koreader-base,ashang/koreader,apletnev/koreader-base,Markismus/koreader
a7d4a468c48308f83d1c0274a37ab84d8da7be97
LuaLibrary/MTATD.lua
LuaLibrary/MTATD.lua
----------------------------------------------------------- -- PROJECT: MTA:TD - Test and Debug Framework -- -- LICENSE: See LICENSE in top level directory -- PURPOSE: Shared across all MTA:TD modules ------------------------------------------------------------ MTATD = {} MTATD.Host = "localhost" MTATD.Port = "51237" -- Class micro framework MTATD.Class = setmetatable({}, { __call = function(self) return setmetatable({}, { __index = self }) end }) function MTATD.Class:new(...) local obj = setmetatable({}, { __index = self }) if obj.constructor then obj:constructor(...) end end function MTATD.Class:delete(...) if self.destructor then self:destructor(...) end end -- Entrypoint function function initMTATD() MTATD.Backend:new(MTATD.Host, MTATD.Port) end -- Exitpoint function function destroyMTATD() MTATD.Backend:delete() end
----------------------------------------------------------- -- PROJECT: MTA:TD - Test and Debug Framework -- -- LICENSE: See LICENSE in top level directory -- PURPOSE: Shared across all MTA:TD modules ------------------------------------------------------------ MTATD = {} MTATD.Host = "localhost" MTATD.Port = "51237" -- Class micro framework MTATD.Class = setmetatable({}, { __call = function(self) return setmetatable({}, { __index = self }) end }) function MTATD.Class:new(...) local obj = setmetatable({}, { __index = self }) if obj.constructor then obj:constructor(...) end end function MTATD.Class:delete(...) if self.destructor then self:destructor(...) end end -- Entrypoint function local backend function initMTATD() backend = MTATD.Backend:new(MTATD.Host, MTATD.Port) end -- Exitpoint function function destroyMTATD() backend:delete() end
Fix error on shutdown
Fix error on shutdown
Lua
mit
Jusonex/MTATD,Jusonex/MTATD,Jusonex/MTATD
2ec2b896e3f08722ef41761daa0a4ba6086f2372
src/npge/alignment/goodSlices.lua
src/npge/alignment/goodSlices.lua
-- lua-npge, Nucleotide PanGenome explorer (Lua module) -- Copyright (C) 2014-2015 Boris Nagaev -- See the LICENSE file for terms of use. -- Arguments: -- 1. list of column statuses (true is good column) -- 2. min_length (integer) -- 3. min_end (integer) -- number of begin and end good columns -- 4. min_identity (from 0.0 to 1.0) -- Results: -- 1. List of good slices -- Each slice is a table { start = ... , stop() = ... } -- Indices start and stop start from 0 return function(good_col, min_length, min_end, min_identity) assert(min_length >= min_end) local block_length = #good_col -- convert values in good_col to 0 or 1 local good_col1 = {} for i = 1, #good_col do good_col1[i] = good_col[i] and 1 or 0 end -- class Slice local slice_mt local function Slice(start, length) local self = {} self.start = start self.length = length return setmetatable(self, slice_mt) end slice_mt = { stop = function(self) return self.start + self.length - 1 end, -- compare by length __lt = function(self, other) return self.length < other.length or (self.length == other.length and self.start < other.start) end, overlaps = function(self, other) if other.start <= self.start and self.start <= other:stop() then return true end if other.start <= self:stop() and self:stop() <= other:stop() then return true end return false end, exclude = function(self, other) local start1 = self.start local stop1 = self:stop() if other.start <= self.start and self.start <= other:stop() then start1 = other:stop() + 1 end if other.start <= self:stop() and self:stop() <= other:stop() then stop1 = other.start - 1 end local length1 = stop1 - start1 + 1 return Slice(start1, length1) end, strip = function(self) if not self:valid() then return self end local start1 = self.start local stop1 = self:stop() -- begin local good_count = 0 for i = start1, start1 + min_end - 1 do good_count = good_count + good_col1[i + 1] end while good_count < min_end and start1 < stop1 do good_count = good_count - good_col1[start1 + 1] start1 = start1 + 1 local new_pos = start1 + min_end - 1 good_count = good_count + good_col1[new_pos + 1] end -- end local good_count = 0 for i = stop1, stop1 - min_end + 1, -1 do good_count = good_count + good_col1[i + 1] end while good_count < min_end and start1 < stop1 do good_count = good_count - good_col1[stop1 + 1] stop1 = stop1 - 1 local new_pos = stop1 - min_end + 1 good_count = good_count + good_col1[new_pos + 1] end -- result local length1 = stop1 - start1 + 1 return Slice(start1, length1) end, valid = function(self) return self.length >= min_length and self.start >= 0 and self:stop() < block_length end, } slice_mt.__index = slice_mt -- Return if identity (good_count / min_length) is good local identity = require 'npge.alignment.identity' local less = require 'npge.block.identity'.less local min_good = min_length * min_identity local function goodIdentity(good_count) return not less(good_count, min_good) end -- Return list of statuses of slices of length min_length local function findGoodSlices() local good_slice = {} local good_count = 0 for i = 1, min_length do good_count = good_count + good_col1[i] end good_slice[1] = goodIdentity(good_count) for new_pos = min_length + 1, block_length do local old_pos = new_pos - min_length good_count = good_count + good_col1[new_pos] good_count = good_count - good_col1[old_pos] local start = old_pos + 1 good_slice[start] = goodIdentity(good_count) end return good_slice end -- Return list of joined slices local function joinSlices(good_slice) local slices0 = {} local last_slice for i = 1, block_length - min_length + 1 do if good_slice[i] then if i > 1 and good_slice[i - 1] then -- increase previous slice assert(#slices0 > 0) last_slice.length = last_slice.length + 1 else -- add new slice last_slice = Slice(i - 1, min_length) table.insert(slices0, last_slice) end end end local slices = {} for _, slice in ipairs(slices0) do slice = slice:strip() if slice:valid() then table.insert(slices, slice) end end return slices end local function maxSlice(slices) local result = slices[1] for _, slice in ipairs(slices) do if slice > result then result = slice end end return result end -- Exclude selected slice from slices, return new slices local function excludeSlice(slices, selected) local slices1 = {} for _, slice in ipairs(slices) do if not slice:overlaps(selected) then table.insert(slices1, slice) else slice = slice:exclude(selected):strip() if slice:valid() then table.insert(slices1, slice) end end end return slices1 end local good_slice = findGoodSlices() local slices = joinSlices(good_slice) local result = {} while #slices > 0 do local selected = maxSlice(slices) if selected.length >= min_length then table.insert(result, selected) slices = excludeSlice(slices, selected) end end return result end
-- lua-npge, Nucleotide PanGenome explorer (Lua module) -- Copyright (C) 2014-2015 Boris Nagaev -- See the LICENSE file for terms of use. -- Arguments: -- 1. list of column statuses (true is good column) -- 2. min_length (integer) -- 3. min_end (integer) -- number of begin and end good columns -- 4. min_identity (from 0.0 to 1.0) -- Results: -- 1. List of good slices -- Each slice is a table { start = ... , stop() = ... } -- Indices start and stop start from 0 return function(good_col, min_length, min_end, min_identity) assert(min_length >= min_end) local block_length = #good_col -- convert values in good_col to 0 or 1 local good_col1 = {} for i = 1, #good_col do good_col1[i] = good_col[i] and 1 or 0 end -- class Slice local slice_mt local function Slice(start, length) local self = {} self.start = start self.length = length return setmetatable(self, slice_mt) end slice_mt = { stop = function(self) return self.start + self.length - 1 end, -- compare by length __lt = function(self, other) return self.length < other.length or (self.length == other.length and self.start < other.start) end, overlaps = function(self, other) if other.start <= self.start and self.start <= other:stop() then return true end if other.start <= self:stop() and self:stop() <= other:stop() then return true end return false end, exclude = function(self, other) local start1 = self.start local stop1 = self:stop() if other.start <= self.start and self.start <= other:stop() then start1 = other:stop() + 1 end if other.start <= self:stop() and self:stop() <= other:stop() then stop1 = other.start - 1 end local length1 = stop1 - start1 + 1 return Slice(start1, length1) end, strip = function(self) if not self:valid() then return self end local start1 = self.start local stop1 = self:stop() -- begin local good_count = 0 for i = start1, start1 + min_end - 1 do good_count = good_count + good_col1[i + 1] end while good_count < min_end and start1 + min_end - 1 < stop1 do good_count = good_count - good_col1[start1 + 1] start1 = start1 + 1 local new_pos = start1 + min_end - 1 good_count = good_count + good_col1[new_pos + 1] end -- end local good_count = 0 for i = stop1, stop1 - min_end + 1, -1 do good_count = good_count + good_col1[i + 1] end while good_count < min_end and start1 + min_end - 1 < stop1 do good_count = good_count - good_col1[stop1 + 1] stop1 = stop1 - 1 local new_pos = stop1 - min_end + 1 good_count = good_count + good_col1[new_pos + 1] end -- result local length1 = stop1 - start1 + 1 return Slice(start1, length1) end, valid = function(self) return self.length >= min_length and self.start >= 0 and self:stop() < block_length end, } slice_mt.__index = slice_mt -- Return if identity (good_count / min_length) is good local identity = require 'npge.alignment.identity' local less = require 'npge.block.identity'.less local min_good = min_length * min_identity local function goodIdentity(good_count) return not less(good_count, min_good) end -- Return list of statuses of slices of length min_length local function findGoodSlices() local good_slice = {} local good_count = 0 for i = 1, min_length do good_count = good_count + good_col1[i] end good_slice[1] = goodIdentity(good_count) for new_pos = min_length + 1, block_length do local old_pos = new_pos - min_length good_count = good_count + good_col1[new_pos] good_count = good_count - good_col1[old_pos] local start = old_pos + 1 good_slice[start] = goodIdentity(good_count) end return good_slice end -- Return list of joined slices local function joinSlices(good_slice) local slices0 = {} local last_slice for i = 1, block_length - min_length + 1 do if good_slice[i] then if i > 1 and good_slice[i - 1] then -- increase previous slice assert(#slices0 > 0) last_slice.length = last_slice.length + 1 else -- add new slice last_slice = Slice(i - 1, min_length) table.insert(slices0, last_slice) end end end local slices = {} for _, slice in ipairs(slices0) do slice = slice:strip() if slice:valid() then table.insert(slices, slice) end end return slices end local function maxSlice(slices) local result = slices[1] for _, slice in ipairs(slices) do if slice > result then result = slice end end return result end -- Exclude selected slice from slices, return new slices local function excludeSlice(slices, selected) local slices1 = {} for _, slice in ipairs(slices) do if not slice:overlaps(selected) then table.insert(slices1, slice) else slice = slice:exclude(selected):strip() if slice:valid() then table.insert(slices1, slice) end end end return slices1 end local good_slice = findGoodSlices() local slices = joinSlices(good_slice) local result = {} while #slices > 0 do local selected = maxSlice(slices) if selected.length >= min_length then table.insert(result, selected) slices = excludeSlice(slices, selected) end end return result end
goodSlices: fix out-of-range error
goodSlices: fix out-of-range error > local new_pos = start1 + min_end - 1 This line used to cause an error, if start1 is too close to end.
Lua
mit
npge/lua-npge,npge/lua-npge,starius/lua-npge,starius/lua-npge,npge/lua-npge,starius/lua-npge
3e70a85e5e61bde55112c06266dc9f22d20c8802
premake4.lua
premake4.lua
if not _ACTION then _ACTION="vs2010" end isPOSIX = false isVisualStudio = false if _ACTION == "vs2002" or _ACTION == "vs2003" or _ACTION == "vs2005" or _ACTION == "vs2008" or _ACTION == "vs2010" then isVisualStudio = true end if _ACTION == "codeblocks" then isPosix = true end solution "TaskScheduler" language "C++" location ( "Build/" .. _ACTION ) flags {"NoManifest", "ExtraWarnings", "StaticRuntime", "NoMinimalRebuild", "FloatFast", "EnableSSE2" } optimization_flags = { "OptimizeSpeed" } targetdir("Bin") local config_list = { "Release", "Debug", } local platform_list = { "x32", "x64" } configurations(config_list) platforms(platform_list) -- CONFIGURATIONS configuration "Release" defines { "NDEBUG" } flags { "Symbols", optimization_flags } configuration "Debug" defines { "_DEBUG" } flags { "Symbols" } configuration "x32" libdirs { "$(DXSDK_DIR)/Lib/x86" } if isVisualStudio then buildoptions { "/wd4127" } else buildoptions { "-std=c++11" } end configuration "x64" libdirs { "$(DXSDK_DIR)/Lib/x64" } if isVisualStudio then buildoptions { "/wd4127" } else buildoptions { "-std=c++11" } end -- give each configuration/platform a unique output directory for _, config in ipairs(config_list) do for _, plat in ipairs(platform_list) do configuration { config, plat } objdir ( "build/" .. _ACTION .. "/tmp/" .. config .. "-" .. plat ) end end -- SUBPROJECTS project "TaskScheduler" flags {"NoPCH"} kind "ConsoleApp" files { "Src/**.*", } includedirs { "Squish" } links { "UnitTest++", "Squish" } project "UnitTest++" kind "StaticLib" defines { "_CRT_SECURE_NO_WARNINGS" } files { "TestFramework/UnitTest++/**.*", } if isPosix then excludes { "TestFramework/UnitTest++/Win32/**.*" } else excludes { "TestFramework/UnitTest++/Posix/**.*" } end project "Squish" kind "StaticLib" defines { "_CRT_SECURE_NO_WARNINGS" } files { "Squish/**.*", } includedirs { "Squish" }
if not _ACTION then _ACTION="vs2010" end isPOSIX = false isVisualStudio = false if _ACTION == "vs2002" or _ACTION == "vs2003" or _ACTION == "vs2005" or _ACTION == "vs2008" or _ACTION == "vs2010" then isVisualStudio = true end if _ACTION == "codeblocks" then isPosix = true end solution "TaskScheduler" language "C++" location ( "Build/" .. _ACTION ) flags {"NoManifest", "ExtraWarnings", "StaticRuntime", "NoMinimalRebuild", "FloatFast", "EnableSSE2" } optimization_flags = { "OptimizeSpeed" } targetdir("Bin") local config_list = { "Release", "Debug", } local platform_list = { "x32", "x64" } configurations(config_list) platforms(platform_list) -- CONFIGURATIONS configuration "Release" defines { "NDEBUG" } flags { "Symbols", optimization_flags } configuration "Debug" defines { "_DEBUG" } flags { "Symbols" } configuration "x32" libdirs { "$(DXSDK_DIR)/Lib/x86" } if isVisualStudio then buildoptions { "/wd4127" } else buildoptions { "-std=c++11" } end configuration "x64" libdirs { "$(DXSDK_DIR)/Lib/x64" } if isVisualStudio then buildoptions { "/wd4127" } else buildoptions { "-std=c++11" } end -- give each configuration/platform a unique output directory for _, config in ipairs(config_list) do for _, plat in ipairs(platform_list) do configuration { config, plat } objdir ( "build/" .. _ACTION .. "/tmp/" .. config .. "-" .. plat ) end end -- SUBPROJECTS project "TaskScheduler" flags {"NoPCH"} kind "ConsoleApp" files { "Src/**.*", } includedirs { "Squish" } links { "UnitTest++", "Squish" } if isPosix then links { "pthread" } end project "UnitTest++" kind "StaticLib" defines { "_CRT_SECURE_NO_WARNINGS" } files { "TestFramework/UnitTest++/**.*", } if isPosix then excludes { "TestFramework/UnitTest++/Win32/**.*" } else excludes { "TestFramework/UnitTest++/Posix/**.*" } end project "Squish" kind "StaticLib" defines { "_CRT_SECURE_NO_WARNINGS" } files { "Squish/**.*", } includedirs { "Squish" }
Fixed UniTest++, Squish and TaskScheduler compilation for POSIX systems
Fixed UniTest++, Squish and TaskScheduler compilation for POSIX systems
Lua
mit
vr3d/TaskScheduler,galek/TaskScheduler,galek/TaskScheduler,vr3d/TaskScheduler,SergeyMakeev/TaskScheduler,vr3d/TaskScheduler,SergeyMakeev/TaskScheduler,galek/TaskScheduler
34eb9c691a55a90d3100ef4a70b211b26367317c
src/actions/vstudio/vs2010_nuget.lua
src/actions/vstudio/vs2010_nuget.lua
-- -- vs2010_nuget.lua -- Generate a NuGet packages.config file. -- Copyright (c) 2016 Jason Perkins and the Premake project -- premake.vstudio.nuget2010 = {} local p = premake local vstudio = p.vstudio local nuget2010 = p.vstudio.nuget2010 local cs2005 = p.vstudio.cs2005 local packageAPIInfos = {} -- -- These functions take the package string as an argument and give you -- information about it. -- function nuget2010.packageId(package) return package:sub(0, package:find(":") - 1) end function nuget2010.packageVersion(package) return package:sub(package:find(":") + 1, -1) end function nuget2010.packageFramework(prj) if p.project.isdotnet(prj) then local cfg = p.project.getfirstconfig(prj) local action = premake.action.current() local framework = cfg.dotnetframework or action.vstudio.targetFramework return cs2005.formatNuGetFrameworkVersion(framework) else return "native" end end function nuget2010.packageAPIInfo(prj, package) local id = nuget2010.packageId(package) local version = nuget2010.packageVersion(package) if not packageAPIInfos[package] then local packageAPIInfo = {} printf("Examining NuGet package '%s'...", id) io.flush() local response, err, code = http.get(string.format("https://api.nuget.org/v3/registration1/%s/index.json", id:lower())) if err ~= "OK" then if code == 404 then p.error("NuGet package '%s' for project '%s' couldn't be found in the repository", id, prj.name) else p.error("NuGet API error (%d)\n%s", code, err) end end response, err = json.decode(response) if not response then p.error("Failed to decode NuGet API response (%s)", err) end if not response.items or #response.items == 0 then p.error("Failed to understand NuGet API response (package '%s' contains no root-level items)", id) end if not response.items[1].items or #response.items[1].items == 0 then p.error("Failed to understand NuGet API response (root-level item for package '%s' contains no subitems)", id) end local subitems = response.items[1].items local versions = {} for _, item in ipairs(subitems) do if not item.catalogEntry then p.error("Failed to understand NuGet API response (subitem of package '%s' has no catalogEntry)", id) end if not item.catalogEntry.version then p.error("Failed to understand NuGet API response (subitem of package '%s' has no catalogEntry.version)", id) end if not item.catalogEntry["@id"] then p.error("Failed to understand NuGet API response (subitem of package '%s' has no catalogEntry['@id'])", id) end -- Check this URL just in case. We don't want to be making -- requests to anywhere else. if item.catalogEntry["@id"]:find("https://api.nuget.org/") ~= 1 then p.error("Failed to understand NuGet API response (catalogEntry['@id'] was not a NuGet API URL)", id) end table.insert(versions, item.catalogEntry.version) end if not table.contains(versions, version) then local options = table.translate(versions, function(value) return "'" .. value .. "'" end) options = table.concat(options, ", ") p.error("'%s' is not a valid version for NuGet package '%s' (options are: %s)", version, id, options) end for _, item in ipairs(subitems) do if item.catalogEntry.version == version then local response, err, code = http.get(item.catalogEntry["@id"]) if err ~= "OK" then if code == 404 then p.error("NuGet package '%s' version '%s' couldn't be found in the repository even though the API reported that it exists", id, prj.name) else p.error("NuGet API error (%d)\n%s", code, err) end end response, err = json.decode(response) if not response then p.error("Failed to decode NuGet API response (%s)", err) end if not response.verbatimVersion and not response.version then p.error("Failed to understand NuGet API response (package '%s' version '%s' has no verbatimVersion or version)", id, version) end packageAPIInfo.verbatimVersion = response.verbatimVersion packageAPIInfo.version = response.version -- C++ packages don't have this, but C# packages have a -- packageEntries field that lists all the files in the -- package. We need to look at this to figure out what -- DLLs to reference in the project file. if prj.language == "C#" and not response.packageEntries then p.error("NuGet package '%s' has no file listing. This package might be too old to be using this API or it's not a .NET Framework package at all.", id) end if prj.language == "C#" then packageAPIInfo.packageEntries = {} for _, item in ipairs(response.packageEntries) do if not item.fullName then p.error("Failed to understand NuGet API response (package '%s' version '%s' packageEntry has no fullName)", id, version) end table.insert(packageAPIInfo.packageEntries, path.translate(item.fullName)) end if #packageAPIInfo.packageEntries == 0 then p.error("NuGet package '%s' file listing is empty", id) end end break end end packageAPIInfos[package] = packageAPIInfo end return packageAPIInfos[package] end -- -- Generates the packages.config file. -- function nuget2010.generatePackagesConfig(prj) if #prj.nuget > 0 then p.w('<?xml version="1.0" encoding="utf-8"?>') p.push('<packages>') for _, package in ipairs(prj.nuget) do p.x('<package id="%s" version="%s" targetFramework="%s" />', nuget2010.packageId(package), nuget2010.packageVersion(package), nuget2010.packageFramework(prj)) end p.pop('</packages>') end end
-- -- vs2010_nuget.lua -- Generate a NuGet packages.config file. -- Copyright (c) 2016 Jason Perkins and the Premake project -- premake.vstudio.nuget2010 = {} local p = premake local vstudio = p.vstudio local nuget2010 = p.vstudio.nuget2010 local cs2005 = p.vstudio.cs2005 local packageAPIInfos = {} -- -- These functions take the package string as an argument and give you -- information about it. -- function nuget2010.packageId(package) return package:sub(0, package:find(":") - 1) end function nuget2010.packageVersion(package) return package:sub(package:find(":") + 1, -1) end function nuget2010.packageFramework(prj) if p.project.isdotnet(prj) then local cfg = p.project.getfirstconfig(prj) local action = premake.action.current() local framework = cfg.dotnetframework or action.vstudio.targetFramework return cs2005.formatNuGetFrameworkVersion(framework) else return "native" end end function nuget2010.packageAPIInfo(prj, package) local id = nuget2010.packageId(package) local version = nuget2010.packageVersion(package) if not packageAPIInfos[package] then local packageAPIInfo = {} printf("Examining NuGet package '%s'...", id) io.flush() local response, err, code = http.get(string.format("https://api.nuget.org/v3/registration1/%s/index.json", id:lower())) if err ~= "OK" then if code == 404 then p.error("NuGet package '%s' for project '%s' couldn't be found in the repository", id, prj.name) else p.error("NuGet API error (%d)\n%s", code, err) end end response, err = json.decode(response) if not response then p.error("Failed to decode NuGet API response (%s)", err) end if not response.items or #response.items == 0 then p.error("Failed to understand NuGet API response (package '%s' contains no root-level items)", id) end if not response.items[1].items or #response.items[1].items == 0 then p.error("Failed to understand NuGet API response (root-level item for package '%s' contains no subitems)", id) end local subitems = response.items[1].items local versions = {} for _, item in ipairs(subitems) do if not item.catalogEntry then p.error("Failed to understand NuGet API response (subitem of package '%s' has no catalogEntry)", id) end if not item.catalogEntry.version then p.error("Failed to understand NuGet API response (subitem of package '%s' has no catalogEntry.version)", id) end if not item.catalogEntry["@id"] then p.error("Failed to understand NuGet API response (subitem of package '%s' has no catalogEntry['@id'])", id) end -- Check this URL just in case. We don't want to be making -- requests to anywhere else. if item.catalogEntry["@id"]:find("https://api.nuget.org/") ~= 1 then p.error("Failed to understand NuGet API response (catalogEntry['@id'] was not a NuGet API URL)", id) end table.insert(versions, item.catalogEntry.version) end if not table.contains(versions, version) then local options = table.translate(versions, function(value) return "'" .. value .. "'" end) options = table.concat(options, ", ") p.error("'%s' is not a valid version for NuGet package '%s' (options are: %s)", version, id, options) end for _, item in ipairs(subitems) do if item.catalogEntry.version == version then local response, err, code = http.get(item.catalogEntry["@id"]) if err ~= "OK" then if code == 404 then p.error("NuGet package '%s' version '%s' couldn't be found in the repository even though the API reported that it exists", id, version) else p.error("NuGet API error (%d)\n%s", code, err) end end response, err = json.decode(response) if not response then p.error("Failed to decode NuGet API response (%s)", err) end if not response.verbatimVersion and not response.version then p.error("Failed to understand NuGet API response (package '%s' version '%s' has no verbatimVersion or version)", id, version) end packageAPIInfo.verbatimVersion = response.verbatimVersion packageAPIInfo.version = response.version -- C++ packages don't have this, but C# packages have a -- packageEntries field that lists all the files in the -- package. We need to look at this to figure out what -- DLLs to reference in the project file. if prj.language == "C#" and not response.packageEntries then p.error("NuGet package '%s' version '%s' has no file listing. This package might be too old to be using this API or it might be a C++ package instead of a .NET Framework package.", id, response.version) end if prj.language == "C#" then packageAPIInfo.packageEntries = {} for _, item in ipairs(response.packageEntries) do if not item.fullName then p.error("Failed to understand NuGet API response (package '%s' version '%s' packageEntry has no fullName)", id, version) end table.insert(packageAPIInfo.packageEntries, path.translate(item.fullName)) end if #packageAPIInfo.packageEntries == 0 then p.error("NuGet package '%s' file listing is empty", id) end end break end end packageAPIInfos[package] = packageAPIInfo end return packageAPIInfos[package] end -- -- Generates the packages.config file. -- function nuget2010.generatePackagesConfig(prj) if #prj.nuget > 0 then p.w('<?xml version="1.0" encoding="utf-8"?>') p.push('<packages>') for _, package in ipairs(prj.nuget) do p.x('<package id="%s" version="%s" targetFramework="%s" />', nuget2010.packageId(package), nuget2010.packageVersion(package), nuget2010.packageFramework(prj)) end p.pop('</packages>') end end
Fix certain NuGet API error messages
Fix certain NuGet API error messages
Lua
bsd-3-clause
TurkeyMan/premake-core,dcourtois/premake-core,Blizzard/premake-core,noresources/premake-core,sleepingwit/premake-core,Blizzard/premake-core,premake/premake-core,premake/premake-core,tvandijck/premake-core,sleepingwit/premake-core,Zefiros-Software/premake-core,sleepingwit/premake-core,starkos/premake-core,soundsrc/premake-core,dcourtois/premake-core,soundsrc/premake-core,sleepingwit/premake-core,dcourtois/premake-core,mandersan/premake-core,sleepingwit/premake-core,bravnsgaard/premake-core,dcourtois/premake-core,Blizzard/premake-core,aleksijuvani/premake-core,noresources/premake-core,bravnsgaard/premake-core,noresources/premake-core,aleksijuvani/premake-core,soundsrc/premake-core,starkos/premake-core,tvandijck/premake-core,aleksijuvani/premake-core,Zefiros-Software/premake-core,LORgames/premake-core,soundsrc/premake-core,tvandijck/premake-core,mandersan/premake-core,noresources/premake-core,Blizzard/premake-core,TurkeyMan/premake-core,TurkeyMan/premake-core,TurkeyMan/premake-core,mendsley/premake-core,dcourtois/premake-core,starkos/premake-core,LORgames/premake-core,noresources/premake-core,LORgames/premake-core,Zefiros-Software/premake-core,starkos/premake-core,mandersan/premake-core,LORgames/premake-core,LORgames/premake-core,mendsley/premake-core,premake/premake-core,Blizzard/premake-core,dcourtois/premake-core,bravnsgaard/premake-core,mendsley/premake-core,starkos/premake-core,Zefiros-Software/premake-core,Zefiros-Software/premake-core,soundsrc/premake-core,mandersan/premake-core,bravnsgaard/premake-core,noresources/premake-core,mendsley/premake-core,bravnsgaard/premake-core,dcourtois/premake-core,starkos/premake-core,premake/premake-core,mandersan/premake-core,mendsley/premake-core,premake/premake-core,Blizzard/premake-core,premake/premake-core,aleksijuvani/premake-core,TurkeyMan/premake-core,starkos/premake-core,premake/premake-core,tvandijck/premake-core,noresources/premake-core,tvandijck/premake-core,aleksijuvani/premake-core
a37e05784be5580b143233554ad69b227b156bcb
vi_entry.lua
vi_entry.lua
local M = {} local redux = require'textredux' local function ve_refresh(buf) buf:add_text(buf.data.prompt, redux.core.style.error) buf:add_text(buf.data.text, redux.core.style.comment) buf:goto_pos(buf.data.pos + #buf.data.prompt) end -- Return a saved version of splits so that we can regenerate them. local function save_splits(splits) if splits[1] and splits[2] then -- it's a split splits[1] = save_splits(splits[1]) splits[2] = save_splits(splits[2]) return splits else return splits.buffer end end local function save_views() local split_views = ui:get_split_table() return save_splits(split_views) end local function unsplit_all() while #_VIEWS > 1 do view:unsplit() end end local function restore_into(v, saved) if saved[1] and saved[2] then -- restore the split first, second = v:split(saved.vertical) first.size = saved.size restore_into(first, saved[1]) restore_into(second, saved[2]) else if _BUFFERS[saved] then v:goto_buffer(_BUFFERS[saved]) else ui.print("Buffer not found:", saved.filename, saved) for k,v in pairs(_BUFFERS) do if type(v) == 'table' then ui.print(k,v, v.filename) else ui.print(k,v) end end end end end -- Restore split state, but with the current buffer on the bottom line. local function restore_saved(saved) old, new = view:split() old.size = ui.size[2] - 4 restore_into(old,saved) return new end local function common_prefix(s1, s2) local len = #s1 if #s2 < len then len = #s2 end local prefixlen = 0 for i=1,len do if s1:sub(i,i) == s2:sub(i,i) then prefixlen = i else break end end return s1:sub(1, prefixlen) end local ve_keys = { ['\t'] = function() local buf = buffer._textredux if not buf.data.complete then return end local t = buf.data.text local pos = buffer.current_pos - #buf.data.prompt local preceding = t:sub(1, pos) local startpos, to_complete, endpos = preceding:match("^.-()(%S*)()$") local first_word = t:match("^(%S*)") local completions = buf.data.complete(to_complete, first_word) --[[] ui.print("#completions: "..tostring(#completions)) for k,v in ipairs(completions) do ui.print(" "..v) end --[[]] if #completions == 1 then local repl = completions[1] t = t:sub(1, startpos-1) .. repl .. t:sub(endpos) buf.data.text = t buf.data.pos = startpos + #repl - 1 buf:refresh() elseif #completions > 1 then -- See if there's a common prefix local prefix = completions[1] for i=2,#completions do prefix = common_prefix(prefix, completions[i]) if #prefix == 0 then break end end if #prefix > #to_complete then t = t:sub(1, startpos-1) .. prefix .. t:sub(endpos) buf.data.text = t buf.data.pos = startpos + #prefix - 1 buf:refresh() end end end, ['\b'] = function() local buf = buffer._textredux local t = buf.data.text local pos = buffer.current_pos - #buf.data.prompt if pos >= 1 then t = t:sub(1, pos-1) .. t:sub(pos+1, -1) buf.data.text = t buf.data.pos = pos - 1 buf:refresh() end end, cu = function() -- Clear to start of line local buf = buffer._textredux local t = buf.data.text local pos = buffer.current_pos - #buf.data.prompt if pos > 0 then t = t:sub(pos+1, -1) buf.data.text = t buf.data.pos = 0 buf:refresh() end end, esc = function() local buf = buffer._textredux local saved = buf.data.saved buf:close() unsplit_all() restore_into(view,saved) end, ['\r'] = function() local buf = buffer._textredux local saved = buf.data.saved local cmd = buf:get_text():sub(#buf.data.prompt + 1) local handler = buf.data.handler buf:close() unsplit_all() restore_into(view,saved) handler(cmd) end } local function set_key(k) ve_keys[k] = function() local buf = buffer._textredux local t = buf.data.text local pos = buffer.current_pos - #buf.data.prompt t = t:sub(1, pos) .. k .. t:sub(pos+1, -1) buf.data.text = t buf.data.pos = pos + 1 buf:refresh() end end local function set_key_range(first, last) local i = string.byte(first) while i <= string.byte(last) do set_key(string.char(i)) i = i + 1 end end -- Set all ASCII printable keys to just insert. set_key_range(' ', '\x7e') function M.enter_mode(prompt, handler, complete) local buf = redux.core.buffer.new('entry') buf.on_refresh = ve_refresh buf.keys = ve_keys buf.data = { prompt=prompt, text = '', pos=#prompt, handler=handler, complete=complete, } local saved = save_views() unsplit_all() local new, old --first, second = view:split() local newview = restore_saved(saved) newview.size = ui.size[2] - 4 ui.goto_view(_VIEWS[newview]) buf.data.saved = saved buf:show() end return M
local M = {} local redux = require'textredux' local function ve_refresh(buf) -- Disable fold margin buffer.margin_width_n[2] = 0 buf:add_text(buf.data.prompt, redux.core.style.error) buf:add_text(buf.data.text, redux.core.style.comment) buf:goto_pos(buf.data.pos + #buf.data.prompt) if buf.data.completions then local cs = buf.data.completions local count = #buf.data.completions buf:append_text('\n') if count > 10 then count = 10 end for i=1,count do buf:append_text(cs[i].."\n", redux.core.style.string) end local lines = buf.line_count if lines > 6 then lines = 6 end view.size = ui.size[2] - 4 - (lines-1) else -- go back to one line if necessary view.size = ui.size[2] - 4 end end -- Return a saved version of splits so that we can regenerate them. local function save_splits(splits) if splits[1] and splits[2] then -- it's a split splits[1] = save_splits(splits[1]) splits[2] = save_splits(splits[2]) return splits else return { buffer=splits.buffer, current=(splits == view) } end end local function save_views() local split_views = ui:get_split_table() return save_splits(split_views) end local function unsplit_all() while #_VIEWS > 1 do view:unsplit() end end -- Returns the view which should be current, or nil local function restore_into(v, saved) if saved[1] and saved[2] then local cur1, cur2 -- restore the split first, second = v:split(saved.vertical) first.size = saved.size cur1 = restore_into(first, saved[1]) cur2 = restore_into(second, saved[2]) -- return current if found in theis branch return cur1 or cur2 else local buf = saved.buffer if _BUFFERS[buf] then v:goto_buffer(_BUFFERS[buf]) if saved.current then return v end else ui.print("Buffer not found:", buf.filename, buf) for k,v in pairs(_BUFFERS) do if type(v) == 'table' then ui.print(k,v, v.filename) else ui.print(k,v) end end end end end -- Restore split state, but with the current buffer on the bottom line. local function restore_saved(saved) local old, new = view:split() old.size = ui.size[2] - 4 local cur = restore_into(old,saved) return new, cur end local function common_prefix(s1, s2) local len = #s1 if #s2 < len then len = #s2 end local prefixlen = 0 for i=1,len do if s1:sub(i,i) == s2:sub(i,i) then prefixlen = i else break end end return s1:sub(1, prefixlen) end -- expand=nil/false means only show completions, don't update buffer. local function complete_now(expand) local buf = buffer._textredux if not buf.data.complete then return end buf.data.completions = nil local t = buf.data.text local pos = buf.data.pos local preceding = t:sub(1, pos) local startpos, to_complete, endpos = preceding:match("^.-()(%S*)()$") local first_word = t:match("^(%S*)") local completions = buf.data.complete(to_complete, first_word) --[[] ui.print("#completions: "..tostring(#completions)) for k,v in ipairs(completions) do ui.print(" "..v) end --[[]] if #completions == 1 and expand then local repl = completions[1] t = t:sub(1, startpos-1) .. repl .. t:sub(endpos) buf.data.text = t buf.data.pos = startpos + #repl - 1 buf:refresh() elseif #completions >= 1 then -- See if there's a common prefix local prefix = "" if expand then prefix = completions[1] for i=2,#completions do prefix = common_prefix(prefix, completions[i]) if #prefix == 0 then break end end end if #prefix > #to_complete then t = t:sub(1, startpos-1) .. prefix .. t:sub(endpos) buf.data.text = t buf.data.pos = startpos + #prefix - 1 buf:refresh() else -- No common prefix, so show completions. buf.data.completions = completions buf:refresh() end end end local ve_keys = { ['\t'] = function() complete_now(true) end, ['\b'] = function() local buf = buffer._textredux local t = buf.data.text local pos = buffer.current_pos - #buf.data.prompt if pos >= 1 then t = t:sub(1, pos-1) .. t:sub(pos+1, -1) buf.data.text = t buf.data.pos = pos - 1 buf:refresh() end end, cu = function() -- Clear to start of line local buf = buffer._textredux local t = buf.data.text local pos = buffer.current_pos - #buf.data.prompt if pos > 0 then t = t:sub(pos+1, -1) buf.data.text = t buf.data.pos = 0 buf:refresh() end end, esc = function() local buf = buffer._textredux local saved = buf.data.saved buf:close() unsplit_all() local newcur = restore_into(view,saved) if newcur and _VIEWS[newcur] then ui.goto_view(_VIEWS[newcur]) end end, ['\r'] = function() local buf = buffer._textredux local saved = buf.data.saved local cmd = buf:get_text():sub(#buf.data.prompt + 1) local handler = buf.data.handler buf:close() unsplit_all() local newcur = restore_into(view,saved) if newcur and _VIEWS[newcur] then ui.goto_view(_VIEWS[newcur]) end handler(cmd) end } local function set_key(k) ve_keys[k] = function() local buf = buffer._textredux local t = buf.data.text local pos = buffer.current_pos - #buf.data.prompt t = t:sub(1, pos) .. k .. t:sub(pos+1, -1) buf.data.text = t buf.data.pos = pos + 1 if buf.data.completions then complete_now() end buf:refresh() end end local function set_key_range(first, last) local i = string.byte(first) while i <= string.byte(last) do set_key(string.char(i)) i = i + 1 end end -- Set all ASCII printable keys to just insert. set_key_range(' ', '\x7e') function M.enter_mode(prompt, handler, complete) local buf = redux.core.buffer.new('entry') buf.on_refresh = ve_refresh buf.keys = ve_keys buf.data = { prompt=prompt, text = '', pos=#prompt, handler=handler, complete=complete, } local saved = save_views() unsplit_all() local new, old --first, second = view:split() local newview, prevcur = restore_saved(saved) newview.size = ui.size[2] - 4 ui.goto_view(_VIEWS[newview]) buf.data.saved = saved buf:show() end return M
Entry mode update: * Show completions when more than one (and no prefix) * Remember what the last view was, and restore that. * Narrow the completions when typing and a list is visible.
Entry mode update: * Show completions when more than one (and no prefix) * Remember what the last view was, and restore that. * Narrow the completions when typing and a list is visible.
Lua
mit
erig0/textadept-vi,jugglerchris/textadept-vi,jugglerchris/textadept-vi
b00a6980caad362d45f30f119d1e84ea88538f09
DebRes-1-glitch.lua
DebRes-1-glitch.lua
--[[ Crea una tabella in cui sono presenti tutte le debolezze e resistenze di un Pokémon Glitch di prima generazione. Per i Pokémon glitch con più forme (Missigno.), crea solo le tabelle effettivamente diverse, inserendo nel titolo tutte le forme che condividono la stessa. Può essere chiamato con il nome di un Pokémon, es: {{#invoke: DebRes/1glitch | DebRes | 'M (00) }} Se un glitch con lo stesso nome compare in più giochi il modulo crea automaticamente una tabella diversa per ogni gioco in cui ha debolezze e resistenze diverse richiamandolo con solo il nome (ATTENZIONE: non crea una tabella per ogni combinazione di tipi diversa ma per ogni combinazione di debolezze e resistenze diversa) --]] local dr = {} local mw = require('mw') local w = require('Wikilib') local data = require("Wikilib-data") local list = require('Wikilib-lists') local oop = require('Wikilib-oop') local tab = require('Wikilib-tables') local sig = require("Wikilib-sigle") local drp = require('DebRes') local et = require('EffTipi-1-glitch') local glitch = require("Glitch-data") --[[ Questa classe rappresenta una tabella di efficacia tipi di prima generazione. Primariamente, contiene informazioni riguardo l'efficacia dei vari tipi di attacchi contro un certo Pokémon, ovvero contro una certa combinazione di tipi; oltre a ciò, possiede le righe che compongono il footer. --]] local EffTable = oop.makeClass(drp.EffTable) --[[ Tutti i possibili moltiplicatori dell'efficacia --]] EffTable.allEff = { 0, 0.25, 0.5, 1, 2, 4, -- Standard } --[[ Override di addLabel per inserire il nome del gioco invece della sigla --]] EffTable.addLabel = function(this, label) if type(label) == 'table' then this.labels = table.merge(this.labels, label) else table.insert(this.labels, sig.gamesName(label, '/')) end end --[[ Contiene le stringhe utili per il footer --]] EffTable.FooterStrings = { -- Testo se il Pokémon ha tipi diversi da quelli dell'efficacia CHANGETYPE = "\n* Nonostante questo Pokémon sia di tipo ${typeOr}, subisce danni come se fosse di tipo ${typeEff}", -- Link ad un tipo TYPE = '[[${type1} (tipo)|${type1}]]', -- Link ad un doppio tipo DUALTYPE = '[[${type1} (tipo)|${type1}]]/[[${type2} (tipo)|${type2}]]' } --[[ Costruttore della classe: ha in ingresso il nome del Pokémon, nella forma nome + sigla gioco, e, opzionalmente, il nome esteso dell gioco --]] EffTable.new = function(name, game) local this = setmetatable(EffTable.super.super.new(), EffTable) if game then name = name:gsub('(.*)'..game..'$', '%1') -- se viene passato il gioco, il glitch ha più -- forme, quindi bisogna aggiungere la label this:addLabel(game) else game = tab.deepSearch(glitch, name) end local data = glitch[game][tab.deepSearch(glitch[game], name)] local types = data.typeEffectiveness and mw.clone(data.typeEffectiveness) or {data.type1, data.type2} if not types[2] then types[2] = types[1] end types = table.map(types, string.lower) -- Colori per la stampa this:createColors({type1 = data.type1, type2 = data.type2}) --[[ Per ogni possibile efficacia, se vi sono tipi che la hanno, inserisce una table con i loro nomi all'indice dell'efficacia stessa --]] for k, eff in ipairs(EffTable.allEff) do local types = et.difesa(eff, types[1], types[2]) if #types > 0 then --[[ I tipi devono essere ordinati per il confronto e la conversione a stringa --]] table.sort(types) this[eff] = types end end --[[ Contiene l'unica possibile riga del footer (se c'è) --]] this.footer = {} if data.typeEffectiveness then table.insert(this.footer, string.interp(EffTable.FooterStrings.CHANGETYPE, { typeOr = string.interp(data.type2 and EffTable.FooterStrings.DUALTYPE or EffTable.FooterStrings.TYPE, { type1 = data.type1, type2 = data.type2 }), typeEff = string.interp(data.typeEffectiveness[2] and EffTable.FooterStrings.DUALTYPE or EffTable.FooterStrings.TYPE, { type1 = data.typeEffectiveness[1], type2 = data.typeEffectiveness[2] }) } )) end return this end --[[ Funzione d'interfaccia al wikicode: prende in ingresso il nome di un Pokémon glitch e genera le table dell'efficacia tipi di prima generazione. Se il Pokémon ha più forme, ritorna una table per ogni forma, tutte collassabili con solo quella della forma base estesa al caricamento della pagina. --]] dr.debRes = function(frame) local p = tab.map(mw.clone(frame.args), w.trim) local games = {} local name = mw.text.decode(p[1]) --[[ controlla se il glitch esiste in più giochi, e nel caso prepara una table con l'elenco dei giochi --]] for game, glitches in pairs(glitch) do if tab.deepSearch(glitches, name) then table.insert(games, game) end end -- Crea altData a partire da games local altData if #games > 1 then altData = { gamesOrder = {}, names = {} } for k, v in ipairs(games) do table.insert(altData.gamesOrder, v) altData.names[v] = v end -- Ordina altData.gamesOrder in modo da avere prima i giochi più vecchi table.sort(altData.gamesOrder , function (a, b) return tab.search(data.gamesChron, string.lower(a)) < tab.search(data.gamesChron, string.lower(b)) end) end return list.makeFormsLabelledBoxes({ name = name, makeBox = EffTable.new, printBoxes = EffTable.printEffTables, altData = altData }) end dr.DebRes, dr.debres = dr.debRes, dr.debRes print(dr.DebRes{args=arg}) -- return dr
--[[ Crea una tabella in cui sono presenti tutte le debolezze e resistenze di un Pokémon Glitch di prima generazione. Per i Pokémon glitch con più forme (Missigno.), crea solo le tabelle effettivamente diverse, inserendo nel titolo tutte le forme che condividono la stessa. Può essere chiamato con il nome di un Pokémon, es: {{#invoke: DebRes/1glitch | DebRes | 'M (00) }} Se un glitch con lo stesso nome compare in più giochi il modulo crea automaticamente una tabella diversa per ogni gioco in cui ha debolezze e resistenze diverse richiamandolo con solo il nome (ATTENZIONE: non crea una tabella per ogni combinazione di tipi diversa ma per ogni combinazione di debolezze e resistenze diversa) --]] local dr = {} local mw = require('mw') local w = require('Wikilib') local data = require("Wikilib-data") local list = require('Wikilib-lists') local oop = require('Wikilib-oop') local tab = require('Wikilib-tables') local sig = require('Wikilib-sigle') local drp = require('DebRes') local et = require('EffTipi-1-glitch') local glitch = require("Glitch-data") --[[ Questa classe rappresenta una tabella di efficacia tipi di prima generazione. Primariamente, contiene informazioni riguardo l'efficacia dei vari tipi di attacchi contro un certo Pokémon, ovvero contro una certa combinazione di tipi; oltre a ciò, possiede le righe che compongono il footer. --]] local EffTable = oop.makeClass(drp.EffTable) --[[ Tutti i possibili moltiplicatori dell'efficacia --]] EffTable.allEff = { 0, 0.25, 0.5, 1, 2, 4, -- Standard } --[[ Override di addLabel per inserire il nome del gioco invece della sigla --]] EffTable.addLabel = function(this, label) if type(label) == 'table' then this.labels = table.merge(this.labels, label) else table.insert(this.labels, sig.gamesName(label, '/')) end end --[[ Contiene le stringhe utili per il footer --]] EffTable.FooterStrings = { -- Testo se il Pokémon ha tipi diversi da quelli dell'efficacia CHANGETYPE = "\n* Nonostante questo Pokémon sia di tipo ${typeOr}, subisce danni come se fosse di tipo ${typeEff}", -- Link ad un tipo TYPE = '[[${type1} (tipo)|${type1}]]', -- Link ad un doppio tipo DUALTYPE = '[[${type1} (tipo)|${type1}]]/[[${type2} (tipo)|${type2}]]' } --[[ Costruttore della classe: ha in ingresso il nome del Pokémon, nella forma nome + sigla gioco, e, opzionalmente, il nome esteso dell gioco --]] EffTable.new = function(name, game) local this = setmetatable(EffTable.super.super.new(), EffTable) if game then name = name:gsub('(.*)'..game..'$', '%1') -- se viene passato il gioco, il glitch ha più -- forme, quindi bisogna aggiungere la label this:addLabel(game) else game = tab.deepSearch(glitch, name) end local data = glitch[game][tab.deepSearch(glitch[game], name)] local types = data.typeEffectiveness and mw.clone(data.typeEffectiveness) or {data.type1, data.type2} if not types[2] then types[2] = types[1] end types = table.map(types, string.lower) -- Colori per la stampa this:createColors({type1 = data.type1, type2 = data.type2}) --[[ Per ogni possibile efficacia, se vi sono tipi che la hanno, inserisce una table con i loro nomi all'indice dell'efficacia stessa --]] for k, eff in ipairs(EffTable.allEff) do local types = et.difesa(eff, types[1], types[2]) if #types > 0 then --[[ I tipi devono essere ordinati per il confronto e la conversione a stringa --]] table.sort(types) this[eff] = types end end --[[ Contiene l'unica possibile riga del footer (se c'è) --]] this.footer = {} if data.typeEffectiveness then table.insert(this.footer, string.interp(EffTable.FooterStrings.CHANGETYPE, { typeOr = string.interp(data.type2 and EffTable.FooterStrings.DUALTYPE or EffTable.FooterStrings.TYPE, { type1 = data.type1, type2 = data.type2 }), typeEff = string.interp(data.typeEffectiveness[2] and EffTable.FooterStrings.DUALTYPE or EffTable.FooterStrings.TYPE, { type1 = data.typeEffectiveness[1], type2 = data.typeEffectiveness[2] }) } )) end return this end --[[ Funzione d'interfaccia al wikicode: prende in ingresso il nome di un Pokémon glitch e genera le table dell'efficacia tipi di prima generazione. Se il Pokémon ha più forme, ritorna una table per ogni forma, tutte collassabili con solo quella della forma base estesa al caricamento della pagina. --]] dr.debRes = function(frame) local p = tab.map(mw.clone(frame.args), w.trim) local games = {} local name = mw.text.decode(p[1]) --[[ controlla se il glitch esiste in più giochi, e nel caso prepara una table con l'elenco dei giochi --]] if p[2] or p.game then table.insert(games, p[2] or p.game) else for game, glitches in pairs(glitch) do if tab.deepSearch(glitches, name) then table.insert(games, game) end end end -- Crea altData a partire da games local altData if #games > 1 then altData = { gamesOrder = {}, names = {} } for k, v in ipairs(games) do table.insert(altData.gamesOrder, v) altData.names[v] = v end -- Ordina altData.gamesOrder in modo da avere prima i giochi più vecchi table.sort(altData.gamesOrder , function (a, b) return tab.search(data.gamesChron, string.lower(a)) < tab.search(data.gamesChron, string.lower(b)) end) end return list.makeFormsLabelledBoxes({ name = name, makeBox = EffTable.new, printBoxes = EffTable.printEffTables, altData = altData }) end dr.DebRes, dr.debres = dr.debRes, dr.debRes print(dr.DebRes{args=arg}) -- return dr
Minor bugfix, added possibility to get the table of a single game
Minor bugfix, added possibility to get the table of a single game
Lua
cc0-1.0
pokemoncentral/wiki-lua-modules
5da941263971cedfec3363a7edcab9c3fa90fddb
premake5.lua
premake5.lua
local CPPSHARP_DIR = "CppSharp/" local NEWTONSOFT_DIR = "Newtonsoft.Json.6.0.8/lib/net45/", solution "LLDBSharp" configurations { "Debug", "Release" } platforms { "x32", "x64" } flags { "Symbols" } project "LLDBBSharpGen" kind "ConsoleApp" language "C#" files { "*.cs" } links { CPPSHARP_DIR .. "CppSharp", CPPSHARP_DIR .. "CppSharp.AST", CPPSHARP_DIR .. "CppSharp.Parser.CSharp", CPPSHARP_DIR .. "CppSharp.Generator", } project "LLDBSharp" kind "SharedLib" language "C#" files { "LLDBSharp/*.cs" } flags { "Unsafe" } project "LLDBSharpExample" kind "ConsoleApp" language "C#" flags { "Unsafe" } files { "Example.cs" } links { "LLDBSharp" }
local CPPSHARP_DIR = "CppSharp/" local NEWTONSOFT_DIR = "Newtonsoft.Json.6.0.8/lib/net45/" action = _ACTION or "" builddir = path.getabsolute("./" .. action); libdir = path.join(builddir, "lib", "%{cfg.buildcfg}_%{cfg.platform}"); solution "LLDBSharp" configurations { "Debug", "Release" } platforms { "x32", "x64" } flags { "Symbols" } location (builddir) objdir (path.join(builddir, "obj")) targetdir (libdir) project "LLDBSharpGen" kind "ConsoleApp" language "C#" files { "LLDBSharpGen.cs" } links { "System.Core", CPPSHARP_DIR .. "CppSharp", CPPSHARP_DIR .. "CppSharp.AST", CPPSHARP_DIR .. "CppSharp.Parser.CSharp", CPPSHARP_DIR .. "CppSharp.Generator", } project "LLDBSharp" kind "SharedLib" language "C#" files { "LLDBSharp/*.cs" } flags { "Unsafe" } project "LLDBSharpExample" kind "ConsoleApp" language "C#" flags { "Unsafe" } files { "Example.cs" } links { "System.Core", "LLDBSharp" } project "NativeLib" kind "SharedLib" language "C++" files { "tests/Native.cpp" } links { "c" } project "Managed" kind "ConsoleApp" language "C#" files { "tests/Managed.cs" } links { "System" }
Premake build fixes.
Premake build fixes.
Lua
mit
tritao/LLDBSharp,tritao/LLDBSharp
f43cbc74e6dc01c46b4cc704a52e6a336c3bb818
frontend/device/kobo/device.lua
frontend/device/kobo/device.lua
local Generic = require("device/generic/device") local Geom = require("ui/geometry") local dbg = require("dbg") local function yes() return true end local Kobo = Generic:new{ model = "Kobo", isKobo = yes, isTouchDevice = yes, -- all of them are -- most Kobos have X/Y switched for the touch screen touch_switch_xy = true, -- most Kobos have also mirrored X coordinates touch_mirrored_x = true, -- enforce protrait mode on Kobos: isAlwaysPortrait = yes, } -- TODO: hasKeys for some devices? -- Kobo Touch: local KoboTrilogy = Kobo:new{ model = "Kobo_trilogy", needsTouchScreenProbe = yes, touch_switch_xy = false, hasKeys = yes, } -- Kobo Mini: local KoboPixie = Kobo:new{ model = "Kobo_pixie", display_dpi = 200, -- bezel: viewport = Geom:new{x=0, y=2, w=596, h=794}, } -- Kobo Aura H2O: local KoboDahlia = Kobo:new{ model = "Kobo_dahlia", hasFrontlight = yes, touch_phoenix_protocol = true, display_dpi = 265, -- the bezel covers the top 11 pixels: viewport = Geom:new{x=0, y=11, w=1080, h=1429}, } -- Kobo Aura HD: local KoboDragon = Kobo:new{ model = "Kobo_dragon", hasFrontlight = yes, display_dpi = 265, } -- Kobo Glo: local KoboKraken = Kobo:new{ model = "Kobo_kraken", hasFrontlight = yes, display_dpi = 212, } -- Kobo Aura: local KoboPhoenix = Kobo:new{ model = "Kobo_phoenix", hasFrontlight = yes, touch_phoenix_protocol = true, display_dpi = 212, -- the bezel covers 12 pixels at the bottom: viewport = Geom:new{x=0, y=0, w=758, h=1012}, } -- Kobo Glo HD: local KoboAlyssum = Kobo:new{ model = "Kobo_alyssum", hasFrontlight = yes, touch_phoenix_protocol = true, touch_alyssum_protocol = true, display_dpi = 300, } function Kobo:init() self.screen = require("ffi/framebuffer_mxcfb"):new{device = self, debug = dbg} self.powerd = require("device/kobo/powerd"):new{device = self} self.input = require("device/input"):new{ device = self, event_map = { [59] = "Power_SleepCover", [90] = "Light", [102] = "Home", [116] = "Power", } } Generic.init(self) self.input.open("/dev/input/event0") -- Light button and sleep slider self.input.open("/dev/input/event1") if not self.needsTouchScreenProbe() then self:initEventAdjustHooks() else -- if touch probe is required, we postpone EventAdjustHook -- initialization to when self:touchScreenProbe is called self.touchScreenProbe = function() -- if user has not set KOBO_TOUCH_MIRRORED yet if KOBO_TOUCH_MIRRORED == nil then local switch_xy = G_reader_settings:readSetting("kobo_touch_switch_xy") -- and has no probe before if switch_xy == nil then local TouchProbe = require("utils/kobo_touch_probe") local UIManager = require("ui/uimanager") UIManager:show(TouchProbe:new{}) UIManager:run() -- assuming TouchProbe sets kobo_touch_switch_xy config switch_xy = G_reader_settings:readSetting("kobo_touch_switch_xy") end self.touch_switch_xy = switch_xy end self:initEventAdjustHooks() end end end function Kobo:initEventAdjustHooks() -- it's called KOBO_TOUCH_MIRRORED in defaults.lua, but what it -- actually did in its original implementation was to switch X/Y. -- NOTE: for kobo touch, adjustTouchSwitchXY needs to be called before -- adjustTouchMirrorX if (self.touch_switch_xy and not KOBO_TOUCH_MIRRORED) or (not self.touch_switch_xy and KOBO_TOUCH_MIRRORED) then self.input:registerEventAdjustHook(self.input.adjustTouchSwitchXY) end if self.touch_mirrored_x then self.input:registerEventAdjustHook( self.input.adjustTouchMirrorX, -- FIXME: what if we change the screen protrait mode? self.screen:getWidth() ) end if self.touch_alyssum_protocol then self.input:registerEventAdjustHook(self.input.adjustTouchAlyssum) end if self.touch_phoenix_protocol then self.input.handleTouchEv = self.input.handleTouchEvPhoenix end end function Kobo:getCodeName() -- Try to get it from the env first local codename = os.getenv("PRODUCT") -- If that fails, run the script ourselves if not codename then local std_out = io.popen("/bin/kobo_config.sh 2>/dev/null", "r") codename = std_out:read() std_out:close() end return codename end function Kobo:getFirmwareVersion() local version_file = io.open("/mnt/onboard/.kobo/version", "r") self.firmware_rev = string.sub(version_file:read(),24,28) version_file:close() end function Kobo:suspend() os.execute("./suspend.sh") end function Kobo:resume() os.execute("echo 0 > /sys/power/state-extended") -- HACK: wait a bit for the kernel to catch up os.execute("sleep 0.1") -- cf. #1862, I can reliably break IR touch input on resume... if os.getenv("FROM_NICKEL") == "true" then local f = io.open("/sys/devices/virtual/input/input1/neocmd", "r") if f ~= nil then io.close(f) os.execute("echo 'a' > /sys/devices/virtual/input/input1/neocmd") end end end -------------- device probe ------------ local codename = Kobo:getCodeName() if codename == "dahlia" then return KoboDahlia elseif codename == "dragon" then return KoboDragon elseif codename == "kraken" then return KoboKraken elseif codename == "phoenix" then return KoboPhoenix elseif codename == "trilogy" then return KoboTrilogy elseif codename == "pixie" then return KoboPixie elseif codename == "alyssum" then return KoboAlyssum else error("unrecognized Kobo model "..codename) end
local Generic = require("device/generic/device") local Geom = require("ui/geometry") local dbg = require("dbg") local function yes() return true end local Kobo = Generic:new{ model = "Kobo", isKobo = yes, isTouchDevice = yes, -- all of them are -- most Kobos have X/Y switched for the touch screen touch_switch_xy = true, -- most Kobos have also mirrored X coordinates touch_mirrored_x = true, -- enforce protrait mode on Kobos: isAlwaysPortrait = yes, } -- TODO: hasKeys for some devices? -- Kobo Touch: local KoboTrilogy = Kobo:new{ model = "Kobo_trilogy", needsTouchScreenProbe = yes, touch_switch_xy = false, hasKeys = yes, } -- Kobo Mini: local KoboPixie = Kobo:new{ model = "Kobo_pixie", display_dpi = 200, -- bezel: viewport = Geom:new{x=0, y=2, w=596, h=794}, } -- Kobo Aura H2O: local KoboDahlia = Kobo:new{ model = "Kobo_dahlia", hasFrontlight = yes, touch_phoenix_protocol = true, display_dpi = 265, -- the bezel covers the top 11 pixels: viewport = Geom:new{x=0, y=11, w=1080, h=1429}, } -- Kobo Aura HD: local KoboDragon = Kobo:new{ model = "Kobo_dragon", hasFrontlight = yes, display_dpi = 265, } -- Kobo Glo: local KoboKraken = Kobo:new{ model = "Kobo_kraken", hasFrontlight = yes, display_dpi = 212, } -- Kobo Aura: local KoboPhoenix = Kobo:new{ model = "Kobo_phoenix", hasFrontlight = yes, touch_phoenix_protocol = true, display_dpi = 212, -- the bezel covers 12 pixels at the bottom: viewport = Geom:new{x=0, y=0, w=758, h=1012}, } -- Kobo Glo HD: local KoboAlyssum = Kobo:new{ model = "Kobo_alyssum", hasFrontlight = yes, touch_phoenix_protocol = true, touch_alyssum_protocol = true, display_dpi = 300, } function Kobo:init() self.screen = require("ffi/framebuffer_mxcfb"):new{device = self, debug = dbg} self.powerd = require("device/kobo/powerd"):new{device = self} self.input = require("device/input"):new{ device = self, event_map = { [59] = "Power_SleepCover", [90] = "Light", [102] = "Home", [116] = "Power", } } Generic.init(self) self.input.open("/dev/input/event0") -- Light button and sleep slider self.input.open("/dev/input/event1") if not self.needsTouchScreenProbe() then self:initEventAdjustHooks() else -- if touch probe is required, we postpone EventAdjustHook -- initialization to when self:touchScreenProbe is called self.touchScreenProbe = function() -- if user has not set KOBO_TOUCH_MIRRORED yet if KOBO_TOUCH_MIRRORED == nil then local switch_xy = G_reader_settings:readSetting("kobo_touch_switch_xy") -- and has no probe before if switch_xy == nil then local TouchProbe = require("utils/kobo_touch_probe") local UIManager = require("ui/uimanager") UIManager:show(TouchProbe:new{}) UIManager:run() -- assuming TouchProbe sets kobo_touch_switch_xy config switch_xy = G_reader_settings:readSetting("kobo_touch_switch_xy") end self.touch_switch_xy = switch_xy end self:initEventAdjustHooks() end end end function Kobo:initEventAdjustHooks() -- it's called KOBO_TOUCH_MIRRORED in defaults.lua, but what it -- actually did in its original implementation was to switch X/Y. -- NOTE: for kobo touch, adjustTouchSwitchXY needs to be called before -- adjustTouchMirrorX if (self.touch_switch_xy and not KOBO_TOUCH_MIRRORED) or (not self.touch_switch_xy and KOBO_TOUCH_MIRRORED) then self.input:registerEventAdjustHook(self.input.adjustTouchSwitchXY) end if self.touch_mirrored_x then self.input:registerEventAdjustHook( self.input.adjustTouchMirrorX, -- FIXME: what if we change the screen protrait mode? self.screen:getWidth() ) end if self.touch_alyssum_protocol then self.input:registerEventAdjustHook(self.input.adjustTouchAlyssum) end if self.touch_phoenix_protocol then self.input.handleTouchEv = self.input.handleTouchEvPhoenix end end function Kobo:getCodeName() -- Try to get it from the env first local codename = os.getenv("PRODUCT") -- If that fails, run the script ourselves if not codename then local std_out = io.popen("/bin/kobo_config.sh 2>/dev/null", "r") codename = std_out:read() std_out:close() end return codename end function Kobo:getFirmwareVersion() local version_file = io.open("/mnt/onboard/.kobo/version", "r") self.firmware_rev = string.sub(version_file:read(),24,28) version_file:close() end function Kobo:suspend() os.execute("./suspend.sh") end function Kobo:resume() os.execute("echo 0 > /sys/power/state-extended") -- HACK: wait a bit for the kernel to catch up os.execute("sleep 0.1") -- cf. #1862, I can reliably break IR touch input on resume... -- cf. also #1943 for the rationale behind applying this workaorund in every case... local f = io.open("/sys/devices/virtual/input/input1/neocmd", "r") if f ~= nil then io.close(f) os.execute("echo 'a' > /sys/devices/virtual/input/input1/neocmd") end end -------------- device probe ------------ local codename = Kobo:getCodeName() if codename == "dahlia" then return KoboDahlia elseif codename == "dragon" then return KoboDragon elseif codename == "kraken" then return KoboKraken elseif codename == "phoenix" then return KoboPhoenix elseif codename == "trilogy" then return KoboTrilogy elseif codename == "pixie" then return KoboPixie elseif codename == "alyssum" then return KoboAlyssum else error("unrecognized Kobo model "..codename) end
Always forcibly wake the H2O IR grid on wakeup
Always forcibly wake the H2O IR grid on wakeup Fix #1862 Fix #1943
Lua
agpl-3.0
NiLuJe/koreader,houqp/koreader,apletnev/koreader,NickSavage/koreader,Frenzie/koreader,chihyang/koreader,frankyifei/koreader,mihailim/koreader,Markismus/koreader,pazos/koreader,lgeek/koreader,poire-z/koreader,koreader/koreader,Frenzie/koreader,mwoz123/koreader,robert00s/koreader,NiLuJe/koreader,koreader/koreader,Hzj-jie/koreader,poire-z/koreader
ef51dd4da207f5e92d70d16f96c9401222e8e495
premake4.lua
premake4.lua
if not _ACTION then _ACTION="vs2010" end isPOSIX = false isVisualStudio = false if _ACTION == "vs2002" or _ACTION == "vs2003" or _ACTION == "vs2005" or _ACTION == "vs2008" or _ACTION == "vs2010" then isVisualStudio = true end if _ACTION == "codeblocks" then isPosix = true end solution "TaskScheduler" language "C++" location ( "Build/" .. _ACTION ) flags {"NoManifest", "ExtraWarnings", "StaticRuntime", "NoMinimalRebuild", "FloatFast", "EnableSSE2" } optimization_flags = { "OptimizeSpeed" } targetdir("Bin") local config_list = { "Release", "Debug", } local platform_list = { "x32", "x64" } configurations(config_list) platforms(platform_list) -- CONFIGURATIONS configuration "Release" defines { "NDEBUG" } flags { "Symbols", optimization_flags } configuration "Debug" defines { "_DEBUG" } flags { "Symbols" } configuration "x32" libdirs { "$(DXSDK_DIR)/Lib/x86" } if isVisualStudio then buildoptions { "/wd4127" } else buildoptions { "-std=c++11" } end configuration "x64" libdirs { "$(DXSDK_DIR)/Lib/x64" } if isVisualStudio then buildoptions { "/wd4127" } else buildoptions { "-std=c++11" } end -- give each configuration/platform a unique output directory for _, config in ipairs(config_list) do for _, plat in ipairs(platform_list) do configuration { config, plat } objdir ( "build/" .. _ACTION .. "/tmp/" .. config .. "-" .. plat ) end end -- SUBPROJECTS project "Tests" flags {"NoPCH"} kind "ConsoleApp" files { "Tests/**.*", } includedirs { "Squish", "Scheduler/Include", "TestFramework/UnitTest++" } if isPosix then excludes { "Src/Platform/Windows/**.*" } else excludes { "Src/Platform/Posix/**.*" } end links { "UnitTest++", "Squish", "TaskScheduler" } if isPosix then links { "pthread" } end project "TaskScheduler" kind "StaticLib" flags {"NoPCH"} files { "Scheduler/**.*", } includedirs { "Squish", "Scheduler/Include", "TestFramework/UnitTest++" } if isPosix then excludes { "Src/Platform/Windows/**.*" } else excludes { "Src/Platform/Posix/**.*" } end project "UnitTest++" kind "StaticLib" defines { "_CRT_SECURE_NO_WARNINGS" } files { "TestFramework/UnitTest++/**.*", } if isPosix then excludes { "TestFramework/UnitTest++/Win32/**.*" } else excludes { "TestFramework/UnitTest++/Posix/**.*" } end project "Squish" kind "StaticLib" defines { "_CRT_SECURE_NO_WARNINGS" } files { "Squish/**.*", } includedirs { "Squish" }
if not _ACTION then _ACTION="vs2010" end isPOSIX = false isVisualStudio = false if _ACTION == "vs2002" or _ACTION == "vs2003" or _ACTION == "vs2005" or _ACTION == "vs2008" or _ACTION == "vs2010" then isVisualStudio = true end if _ACTION == "codeblocks" then isPosix = true end solution "TaskScheduler" language "C++" location ( "Build/" .. _ACTION ) flags {"NoManifest", "ExtraWarnings", "StaticRuntime", "NoMinimalRebuild", "FloatFast", "EnableSSE2" } optimization_flags = { "OptimizeSpeed" } targetdir("Bin") local config_list = { "Release", "Debug", } local platform_list = { "x32", "x64" } configurations(config_list) platforms(platform_list) -- CONFIGURATIONS configuration "Release" defines { "NDEBUG" } flags { "Symbols", optimization_flags } configuration "Debug" defines { "_DEBUG" } flags { "Symbols" } configuration "x32" libdirs { "$(DXSDK_DIR)/Lib/x86" } if isVisualStudio then buildoptions { "/wd4127" } else buildoptions { "-std=c++11" } end configuration "x64" libdirs { "$(DXSDK_DIR)/Lib/x64" } if isVisualStudio then buildoptions { "/wd4127" } else buildoptions { "-std=c++11" } end -- give each configuration/platform a unique output directory for _, config in ipairs(config_list) do for _, plat in ipairs(platform_list) do configuration { config, plat } objdir ( "build/" .. _ACTION .. "/tmp/" .. config .. "-" .. plat ) end end -- SUBPROJECTS project "Tests" flags {"NoPCH"} kind "ConsoleApp" files { "Tests/**.*", } includedirs { "Squish", "Scheduler/Include", "TestFramework/UnitTest++" } if isPosix then excludes { "Src/Platform/Windows/**.*" } else excludes { "Src/Platform/Posix/**.*" } end links { "UnitTest++", "Squish", "TaskScheduler" } if isPosix then links { "pthread" } end project "TaskScheduler" kind "StaticLib" flags {"NoPCH"} files { "Scheduler/**.*", } includedirs { "Squish", "Scheduler/Include", "TestFramework/UnitTest++" } if isPosix then excludes { "Src/Platform/Windows/**.*" } else excludes { "Src/Platform/Posix/**.*" } end project "UnitTest++" kind "StaticLib" defines { "_CRT_SECURE_NO_WARNINGS" } files { "TestFramework/UnitTest++/**.cpp", "TestFramework/UnitTest++/**.h", } if isPosix then excludes { "TestFramework/UnitTest++/Win32/**.*" } else excludes { "TestFramework/UnitTest++/Posix/**.*" } end project "Squish" kind "StaticLib" defines { "_CRT_SECURE_NO_WARNINGS" } files { "Squish/**.*", } includedirs { "Squish" }
Fixed project generator script.
Fixed project generator script. Remove added by mistake *.vcxproj, *.vcxproj.user from UnitTest++ project.
Lua
mit
vr3d/TaskScheduler,galek/TaskScheduler,galek/TaskScheduler,galek/TaskScheduler,SergeyMakeev/TaskScheduler,SergeyMakeev/TaskScheduler,vr3d/TaskScheduler,vr3d/TaskScheduler
7f9b3efc8c7d347b28c8af9ba32043b7629c69fb
share/lua/sd/icecast.lua
share/lua/sd/icecast.lua
--[[ $Id$ Copyright © 2010 VideoLAN and AUTHORS Authors: Fabio Ritrovato <sephiroth87 at videolan dot org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] require "simplexml" function descriptor() return { title="Icecast Radio Directory" } end function main() local tree = simplexml.parse_url("http://dir.xiph.org/yp.xml") for _, station in ipairs( tree.children ) do simplexml.add_name_maps( station ) local station_name = station.children_map["server_name"][1].children[1] if station_name == "Unspecified name" or station_name == "" then station_name = station.children_map["listen_url"][1].children[1] end vlc.sd.add_item( {path=station.children_map["listen_url"][1].children[1], title=station_name, genre=station.children_map["genre"][1].children[1], nowplaying=station.children_map["current_song"][1].children[1], meta={["Icecast"]={["Bitrate"]=station.children_map["bitrate"][1].children[1]; ["Server type"]=station.children_map["server_type"][1].children[1]}}} ) end end
--[[ $Id$ Copyright © 2010 VideoLAN and AUTHORS Authors: Fabio Ritrovato <sephiroth87 at videolan dot org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] require "simplexml" function descriptor() return { title="Icecast Radio Directory" } end function main() local tree = simplexml.parse_url("http://dir.xiph.org/yp.xml") for _, station in ipairs( tree.children ) do simplexml.add_name_maps( station ) local station_name = station.children_map["server_name"][1].children[1] if station_name == "Unspecified name" or station_name == "" then station_name = station.children_map["listen_url"][1].children[1] end vlc.sd.add_item( {path=station.children_map["listen_url"][1].children[1], title=station_name, genre=station.children_map["genre"][1].children[1], nowplaying=station.children_map["current_song"][1].children[1], meta={ ["Icecast Bitrate"]=station.children_map["bitrate"][1].children[1]; ["Icecast Server Type"]=station.children_map["server_type"][1].children[1]; }} ) end end
lua: icecast: fix icecast meta import
lua: icecast: fix icecast meta import
Lua
lgpl-2.1
shyamalschandra/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,shyamalschandra/vlc,jomanmuk/vlc-2.1,krichter722/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc,vlc-mirror/vlc,krichter722/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,xkfz007/vlc,jomanmuk/vlc-2.2,xkfz007/vlc,xkfz007/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.1,xkfz007/vlc,krichter722/vlc,xkfz007/vlc,jomanmuk/vlc-2.2,krichter722/vlc,jomanmuk/vlc-2.1,xkfz007/vlc,vlc-mirror/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,krichter722/vlc,xkfz007/vlc,shyamalschandra/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,vlc-mirror/vlc-2.1,krichter722/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,krichter722/vlc,shyamalschandra/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc,jomanmuk/vlc-2.1
9e69438ac517bdb38827d11b247f0f758ac17dcb
xmake/modules/core/tools/ml.lua
xmake/modules/core/tools/ml.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 ml.lua -- -- imports import("private.tools.vstool") -- init it -- -- @see https://docs.microsoft.com/en-us/cpp/assembler/masm/ml-and-ml64-command-line-reference -- function init(self) -- init asflags if self:program():find("64") then self:set("asflags", "-nologo") else self:set("asflags", "-nologo", "-Gd") end -- init flags map self:set("mapflags", { -- symbols ["-g"] = "-Z7" , ["-fvisibility=.*"] = "" -- warnings , ["-W1"] = "-W1" , ["-W2"] = "-W2" , ["-W3"] = "-W3" , ["-Wall"] = "-W3" -- /W level Sets the warning level, where level = 0, 1, 2, or 3. , ["-Wextra"] = "-W3" , ["-Weverything"] = "-W3" , ["-Werror"] = "-WX" , ["%-Wno%-error=.*"] = "" -- others , ["-ftrapv"] = "" , ["-fsanitize=address"] = "" }) end -- make the warning flag function nf_warning(self, level) -- the maps local maps = { none = "-w" , less = "-W1" , more = "-W3" , all = "-W3" , everything = "-W3" , error = "-WX" } -- make it return maps[level] end -- make the define flag function nf_define(self, macro) return "-D" .. macro end -- make the undefine flag function nf_undefine(self, macro) return "-U" .. macro end -- make the includedir flag function nf_includedir(self, dir) return "-I" .. os.args(dir) end -- make the compile arguments list function _compargv1(self, sourcefile, objectfile, flags) return self:program(), table.join("-c", flags, "-Fo" .. os.args(objectfile), sourcefile) end -- compile the source file function _compile1(self, sourcefile, objectfile, dependinfo, flags) -- ensure the object directory os.mkdir(path.directory(objectfile)) try { function () -- use vstool to compile and enable vs_unicode_output @see https://github.com/xmake-io/xmake/issues/528 vstool.runv(_compargv1(self, sourcefile, objectfile, flags)) end, catch { function (errors) -- use link/stdout as errors first from vstool.iorunv() if type(errors) == "table" then local errs = errors.stdout or "" if #errs:trim() == 0 then errs = errors.stderr or "" end errors = errs end os.raise(tostring(errors)) end } } end -- make the compile arguments list function compargv(self, sourcefiles, objectfile, flags) -- only support single source file now assert(type(sourcefiles) ~= "table", "'object:sources' not support!") -- for only single source file return _compargv1(self, sourcefiles, objectfile, flags) end -- compile the source file function compile(self, sourcefiles, objectfile, dependinfo, flags) -- only support single source file now assert(type(sourcefiles) ~= "table", "'object:sources' not support!") -- for only single source file _compile1(self, sourcefiles, objectfile, dependinfo, flags) 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 ml.lua -- -- imports import("private.tools.vstool") -- init it -- -- @see https://docs.microsoft.com/en-us/cpp/assembler/masm/ml-and-ml64-command-line-reference -- function init(self) -- init asflags if self:program():find("64") then self:set("asflags", "-nologo") else self:set("asflags", "-nologo", "-Gd") end -- init flags map self:set("mapflags", { -- symbols ["-g"] = "-Z7" , ["-fvisibility=.*"] = "" -- warnings , ["-W1"] = "-W1" , ["-W2"] = "-W2" , ["-W3"] = "-W3" , ["-Wall"] = "-W3" -- /W level Sets the warning level, where level = 0, 1, 2, or 3. , ["-Wextra"] = "-W3" , ["-Weverything"] = "-W3" , ["-Werror"] = "-WX" , ["%-Wno%-error=.*"] = "" -- others , ["-ftrapv"] = "" , ["-fsanitize=address"] = "" }) end -- make the warning flag function nf_warning(self, level) -- the maps local maps = { none = "-w" , less = "-W1" , more = "-W3" , all = "-W3" , everything = "-W3" , error = "-WX" } -- make it return maps[level] end -- make the define flag function nf_define(self, macro) return "-D" .. macro end -- make the undefine flag function nf_undefine(self, macro) return "-U" .. macro end -- make the includedir flag function nf_includedir(self, dir) return "-I" .. os.args(dir) end -- make the compile arguments list function _compargv1(self, sourcefile, objectfile, flags) return self:program(), table.join("-c", flags, "-Fo" .. os.args(objectfile), sourcefile) end -- compile the source file function _compile1(self, sourcefile, objectfile, dependinfo, flags) -- ensure the object directory os.mkdir(path.directory(objectfile)) try { function () -- @note we need not uses vstool.runv to enable unicode output for ml.exe os.runv(_compargv1(self, sourcefile, objectfile, flags)) end, catch { function (errors) -- use link/stdout as errors first from vstool.iorunv() if type(errors) == "table" then local errs = errors.stdout or "" if #errs:trim() == 0 then errs = errors.stderr or "" end errors = errs end os.raise(tostring(errors)) end } } end -- make the compile arguments list function compargv(self, sourcefiles, objectfile, flags) -- only support single source file now assert(type(sourcefiles) ~= "table", "'object:sources' not support!") -- for only single source file return _compargv1(self, sourcefiles, objectfile, flags) end -- compile the source file function compile(self, sourcefiles, objectfile, dependinfo, flags) -- only support single source file now assert(type(sourcefiles) ~= "table", "'object:sources' not support!") -- for only single source file _compile1(self, sourcefiles, objectfile, dependinfo, flags) end
fix ml error output
fix ml error output
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
2dc86e274f373041b9dd48c23dab4857398dca0e
libs/core/luasrc/model/wireless.lua
libs/core/luasrc/model/wireless.lua
--[[ LuCI - Wireless model Copyright 2009 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 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 pairs, i18n, uci, math = pairs, luci.i18n, luci.model.uci, math local iwi = require "iwinfo" local utl = require "luci.util" local uct = require "luci.model.uci.bind" module "luci.model.wireless" local ub = uct.bind("wireless") local st, ifs function init(cursor) cursor:unload("wireless") cursor:load("wireless") ub:init(cursor) st = uci.cursor_state() ifs = { } local count = 0 ub.uci:foreach("wireless", "wifi-iface", function(s) count = count + 1 local id = "%s.network%d" %{ s.device, count } ifs[id] = { id = id, sid = s['.name'], count = count } local dev = st:get("wireless", s['.name'], "ifname") or st:get("wireless", s['.name'], "device") local wtype = dev and iwi.type(dev) if dev and wtype then ifs[id].winfo = iwi[wtype] ifs[id].wdev = dev end end) end function get_device(self, dev) return device(dev) end function get_network(self, id) if ifs[id] then return network(ifs[id].sid) else local n for n, _ in pairs(ifs) do if ifs[n].sid == id then return network(id) end end end end function shortname(self, iface) if iface.wdev and iface.winfo then return "%s %q" %{ i18n.translate("a_s_if_iwmode_" .. iface:active_mode(), iface.winfo.mode(iface.wdev)), iface:active_ssid() or "(hidden)" } else return iface:name() end end function get_i18n(self, iface) if iface.wdev and iface.winfo then return "%s: %s %q (%s)" %{ i18n.translate("a_s_if_wifinet", "Wireless Network"), i18n.translate("a_s_if_iwmode_" .. iface:active_mode(), iface.winfo.mode(iface.wdev)), iface:active_ssid() or "(hidden)", iface.wdev } else return "%s: %q" %{ i18n.translate("a_s_if_wifinet", "Wireless Network"), iface:name() } end end function rename_network(self, old, new) local i for i, _ in pairs(ifs) do if ifs[i].network == old then ifs[i].network = new end end ub.uci:foreach("wireless", "wifi-iface", function(s) if s.network == old then if new then ub.uci:set("wireless", s['.name'], "network", new) else ub.uci:delete("wireless", s['.name'], "network") end end end) end function del_network(self, old) return self:rename_network(old, nil) end function find_interfaces(self, iflist, brlist) local iface for iface, _ in pairs(ifs) do iflist[iface] = ifs[iface] end end function ignore_interface(self, iface) if ifs and ifs[iface] then return false else return iwi.type(iface) and true or false end end function add_interface(self, net, iface) if ifs and ifs[iface] and ifs[iface].sid then ub.uci:set("wireless", ifs[iface].sid, "network", net:name()) ifs[iface].network = net:name() return true end return false end function del_interface(self, net, iface) if ifs and ifs[iface] and ifs[iface].sid then ub.uci:delete("wireless", ifs[iface].sid, "network") --return true end return false end device = ub:section("wifi-device") device:property("type") device:property("channel") device:property("disabled") function device.name(self) return self.sid end function device.get_networks(self) local nets = { } ub.uci:foreach("wireless", "wifi-iface", function(s) if s.device == self:name() then nets[#nets+1] = network(s['.name']) end end) return nets end network = ub:section("wifi-iface") network:property("mode") network:property("ssid") network:property("bssid") network:property("network") function network._init(self, sid) local count = 0 ub.uci:foreach("wireless", "wifi-iface", function(s) count = count + 1 return s['.name'] ~= sid end) local dev = st:get("wireless", sid, "ifname") or st:get("wireless", sid, "device") if dev then self.id = "%s.network%d" %{ dev, count } local wtype = iwi.type(dev) if dev and wtype then self.winfo = iwi[wtype] self.wdev = dev end end end function network.name(self) return self.id end function network.ifname(self) return self.wdev end function network.get_device(self) if self.device then return device(self.device) end end function network.active_mode(self) local m = self.winfo and self.winfo.mode(self.wdev) if m == "Master" or m == "Auto" then m = "ap" elseif m == "Ad-Hoc" then m = "adhoc" elseif m == "Client" then m = "sta" elseif m then m = m:lower() else m = self:mode() end return m or "ap" end function network.active_mode_i18n(self) return i18n.translate("a_s_if_iwmode_" .. self:active_mode()) end function network.active_ssid(self) return self.winfo and self.winfo.ssid(self.wdev) or self:ssid() end function network.active_bssid(self) return self.winfo and self.winfo.bssid(self.wdev) or self:bssid() or "00:00:00:00:00:00" end function network.signal(self) return self.winfo and self.winfo.signal(self.wdev) or 0 end function network.noise(self) return self.winfo and self.winfo.noise(self.wdev) or 0 end function network.signal_level(self) if self:active_bssid() ~= "00:00:00:00:00:00" then local signal = self:signal() local noise = self:noise() if signal > 0 and noise > 0 then local snr = -1 * (noise - signal) return math.floor(snr / 5) else return 0 end else return -1 end end function network.signal_percent(self) local qc = self.winfo and self.winfo.quality(self.wdev) or 0 local qm = self.winfo and self.winfo.quality_max(self.wdev) or 0 if qc > 0 and qm > 0 then return math.floor((100 / qm) * qc) else return 0 end end
--[[ LuCI - Wireless model Copyright 2009 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 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 pairs, i18n, uci, math = pairs, luci.i18n, luci.model.uci, math local iwi = require "iwinfo" local utl = require "luci.util" local uct = require "luci.model.uci.bind" module "luci.model.wireless" local ub = uct.bind("wireless") local st, ifs function init(cursor) cursor:unload("wireless") cursor:load("wireless") ub:init(cursor) st = uci.cursor_state() ifs = { } local count = 0 ub.uci:foreach("wireless", "wifi-iface", function(s) count = count + 1 local id = "%s.network%d" %{ s.device, count } ifs[id] = { id = id, sid = s['.name'], count = count } local dev = st:get("wireless", s['.name'], "ifname") or st:get("wireless", s['.name'], "device") local wtype = dev and iwi.type(dev) if dev and wtype then ifs[id].winfo = iwi[wtype] ifs[id].wdev = dev end end) end function get_device(self, dev) return device(dev) end function get_devices(self) local devs = { } ub.uci:foreach("wireless", "wifi-device", function(s) devs[#devs+1] = device(s['.name']) end) return devs end function get_network(self, id) if ifs[id] then return network(ifs[id].sid) else local n for n, _ in pairs(ifs) do if ifs[n].sid == id then return network(id) end end end end function shortname(self, iface) if iface.wdev and iface.winfo then return "%s %q" %{ i18n.translate("a_s_if_iwmode_" .. iface:active_mode(), iface.winfo.mode(iface.wdev)), iface:active_ssid() or "(hidden)" } else return iface:name() end end function get_i18n(self, iface) if iface.wdev and iface.winfo then return "%s: %s %q (%s)" %{ i18n.translate("a_s_if_wifinet", "Wireless Network"), i18n.translate("a_s_if_iwmode_" .. iface:active_mode(), iface.winfo.mode(iface.wdev)), iface:active_ssid() or "(hidden)", iface.wdev } else return "%s: %q" %{ i18n.translate("a_s_if_wifinet", "Wireless Network"), iface:name() } end end function del_network(self, id) if ifs[id] then ub.uci:delete("wireless", ifs[id].sid) ifs[id] = nil else local n for n, _ in pairs(ifs) do if ifs[n].sid == id then ub.uci:delete("wireless", id) ifs[n] = nil end end end end function find_interfaces(self, iflist, brlist) local iface for iface, _ in pairs(ifs) do iflist[iface] = ifs[iface] end end function ignore_interface(self, iface) if ifs and ifs[iface] then return false else return iwi.type(iface) and true or false end end function add_interface(self, net, iface) if ifs and ifs[iface] and ifs[iface].sid then ub.uci:set("wireless", ifs[iface].sid, "network", net:name()) ifs[iface].network = net:name() return true end return false end function del_interface(self, net, iface) if ifs and ifs[iface] and ifs[iface].sid then ub.uci:delete("wireless", ifs[iface].sid, "network") --return true end return false end device = ub:section("wifi-device") device:property("type") device:property("channel") device:property_bool("disabled") function device.name(self) return self.sid end function device.is_up(self) local rv = false if not self:disabled() then st:foreach("wireless", "wifi-iface", function(s) if s.device == self:name() and s.up == "1" then rv = true return false end end) end return rv end function device.get_networks(self) local nets = { } ub.uci:foreach("wireless", "wifi-iface", function(s) if s.device == self:name() then nets[#nets+1] = network(s['.name']) end end) return nets end network = ub:section("wifi-iface") network:property("mode") network:property("ssid") network:property("bssid") network:property("network") function network._init(self, sid) local count = 0 ub.uci:foreach("wireless", "wifi-iface", function(s) count = count + 1 return s['.name'] ~= sid end) local dev = st:get("wireless", sid, "ifname") or st:get("wireless", sid, "device") if dev then self.id = "%s.network%d" %{ dev, count } local wtype = iwi.type(dev) if dev and wtype then self.winfo = iwi[wtype] self.wdev = dev end end end function network.name(self) return self.id end function network.ifname(self) return self.wdev end function network.get_device(self) if self.device then return device(self.device) end end function network.is_up(self) return (st:get("wireless", self.sid, "up") == "1") end function network.active_mode(self) local m = self.winfo and self.winfo.mode(self.wdev) if m == "Master" or m == "Auto" then m = "ap" elseif m == "Ad-Hoc" then m = "adhoc" elseif m == "Client" then m = "sta" elseif m then m = m:lower() else m = self:mode() end return m or "ap" end function network.active_mode_i18n(self) return i18n.translate("a_s_if_iwmode_" .. self:active_mode()) end function network.active_ssid(self) return self.winfo and self.winfo.ssid(self.wdev) or self:ssid() end function network.active_bssid(self) return self.winfo and self.winfo.bssid(self.wdev) or self:bssid() or "00:00:00:00:00:00" end function network.active_encryption(self) return self.winfo and self.winfo.enctype(self.wdev) or "-" end function network.assoclist(self) return self.winfo and self.winfo.assoclist(self.wdev) or { } end function network.frequency(self) local freq = self.winfo and self.winfo.frequency(self.wdev) return freq and freq > 0 and "%.03f" % (freq / 1000) end function network.bitrate(self) local rate = self.winfo and self.winfo.bitrate(self.wdev) return rate and rate > 0 and (rate / 1000) end function network.channel(self) return self.winfo and self.winfo.channel(self.wdef) end function network.signal(self) return self.winfo and self.winfo.signal(self.wdev) or 0 end function network.noise(self) return self.winfo and self.winfo.noise(self.wdev) or 0 end function network.signal_level(self, s, n) if self:active_bssid() ~= "00:00:00:00:00:00" then local signal = s or self:signal() local noise = n or self:noise() if signal < 0 and noise < 0 then local snr = -1 * (noise - signal) return math.floor(snr / 5) else return 0 end else return -1 end end function network.signal_percent(self) local qc = self.winfo and self.winfo.quality(self.wdev) or 0 local qm = self.winfo and self.winfo.quality_max(self.wdev) or 0 if qc > 0 and qm > 0 then return math.floor((100 / qm) * qc) else return 0 end end
libs/core: extend and fix luci.model.wireless
libs/core: extend and fix luci.model.wireless
Lua
apache-2.0
deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci
d99569894a2ef259782acfe7b1e8754ff2bb900b
lua/wincent/commandt/private/ui.lua
lua/wincent/commandt/private/ui.lua
-- SPDX-FileCopyrightText: Copyright 2022-present Greg Hurrell and contributors. -- SPDX-License-Identifier: BSD-2-Clause local ui = {} local MatchListing = require('wincent.commandt.private.match_listing').MatchListing local Prompt = require('wincent.commandt.private.prompt').Prompt local cmdline_enter_autocmd = nil local current_finder = nil -- Reference to avoid premature garbage collection. local match_listing = nil local prompt = nil -- Reverses `list` in place. local reverse = function(list) local i = 1 local j = #list while i < j do list[i], list[j] = list[j], list[i] i = i + 1 j = j - 1 end end -- TODO: reasons to delete a window -- 1. [DONE] user explicitly closes it with ESC -- 2. [DONE] user explicitly accepts a selection -- 3. [DONE] user navigates out of the window (WinLeave) -- 4. [DONE] user uses a Vim command to close the window or the buffer -- (we get this "for free" kind of thanks to WinLeave happening as soon as you -- do anything that would move you out) local close = function() if match_listing then match_listing:close() match_listing = nil end if prompt then prompt:close() prompt = nil end if cmdline_enter_autocmd ~= nil then vim.api.nvim_del_autocmd(cmdline_enter_autocmd) cmdline_enter_autocmd = nil end end -- TODO save/restore global options, like `hlsearch' (which we want to turn off -- temporarily when our windows are visible) — either that, or figure out how to -- make the highlighting not utterly suck. -- in any case, review the list at ruby/command-t/lib/command-t/match_window.rb ui.show = function(finder, options) -- TODO validate options current_finder = finder assert(current_finder) -- Avoid Lua warning about unused local. match_listing = MatchListing.new({ height = options.height, margin = options.margin, position = options.position, selection_highlight = options.selection_highlight, }) match_listing:show() local results = nil local selected = nil prompt = Prompt.new({ height = options.height, mappings = options.mappings, margin = options.margin, name = options.name, on_change = function(query) results = finder.run(query) if #results == 0 then selected = nil else if options.order == 'reverse' then reverse(results) selected = #results else selected = 1 end end match_listing:update(results, { selected = selected }) end, on_leave = close, -- TODO: decide whether we want an `index`, a string, or just to base it off -- our notion of current selection on_open = function(kind) close() if results and #results > 0 then finder.open(results[selected], kind) end end, on_select = function(choice) if results and #results > 0 then if choice.absolute then if choice.absolute > 0 then selected = math.min(choice.absolute, #results) elseif choice.absolute < 0 then selected = math.max(#results + choice.absolute + 1, 1) else -- Absolute "middle". selected = math.min(math.floor(#results / 2) + 1, #results) end elseif choice.relative then if choice.relative > 0 then selected = math.min(selected + choice.relative, #results) else selected = math.max(selected + choice.relative, 1) end end match_listing:select(selected) end end, position = options.position, }) prompt:show() if cmdline_enter_autocmd == nil then cmdline_enter_autocmd = vim.api.nvim_create_autocmd('CmdlineEnter', { callback = close, }) end end return ui
-- SPDX-FileCopyrightText: Copyright 2022-present Greg Hurrell and contributors. -- SPDX-License-Identifier: BSD-2-Clause local ui = {} local MatchListing = require('wincent.commandt.private.match_listing').MatchListing local Prompt = require('wincent.commandt.private.prompt').Prompt local cmdline_enter_autocmd = nil local current_finder = nil -- Reference to avoid premature garbage collection. local current_window = nil local match_listing = nil local prompt = nil -- Reverses `list` in place. local reverse = function(list) local i = 1 local j = #list while i < j do list[i], list[j] = list[j], list[i] i = i + 1 j = j - 1 end end -- TODO: reasons to delete a window -- 1. [DONE] user explicitly closes it with ESC -- 2. [DONE] user explicitly accepts a selection -- 3. [DONE] user navigates out of the window (WinLeave) -- 4. [DONE] user uses a Vim command to close the window or the buffer -- (we get this "for free" kind of thanks to WinLeave happening as soon as you -- do anything that would move you out) local close = function() if match_listing then match_listing:close() match_listing = nil end if prompt then prompt:close() prompt = nil end if cmdline_enter_autocmd ~= nil then vim.api.nvim_del_autocmd(cmdline_enter_autocmd) cmdline_enter_autocmd = nil end if current_window then vim.api.nvim_set_current_win(current_window) current_window = nil end end -- TODO save/restore global options, like `hlsearch' (which we want to turn off -- temporarily when our windows are visible) — either that, or figure out how to -- make the highlighting not utterly suck. -- in any case, review the list at ruby/command-t/lib/command-t/match_window.rb ui.show = function(finder, options) -- TODO validate options current_finder = finder current_window = vim.api.nvim_get_current_win() assert(current_finder) -- Avoid Lua warning about unused local. match_listing = MatchListing.new({ height = options.height, margin = options.margin, position = options.position, selection_highlight = options.selection_highlight, }) match_listing:show() local results = nil local selected = nil prompt = Prompt.new({ height = options.height, mappings = options.mappings, margin = options.margin, name = options.name, on_change = function(query) results = finder.run(query) if #results == 0 then selected = nil else if options.order == 'reverse' then reverse(results) selected = #results else selected = 1 end end match_listing:update(results, { selected = selected }) end, on_leave = close, -- TODO: decide whether we want an `index`, a string, or just to base it off -- our notion of current selection on_open = function(kind) close() if results and #results > 0 then -- Defer, to give autocommands a chance to run. local result = results[selected] vim.defer_fn(function() finder.open(result, kind) end, 0) end end, on_select = function(choice) if results and #results > 0 then if choice.absolute then if choice.absolute > 0 then selected = math.min(choice.absolute, #results) elseif choice.absolute < 0 then selected = math.max(#results + choice.absolute + 1, 1) else -- Absolute "middle". selected = math.min(math.floor(#results / 2) + 1, #results) end elseif choice.relative then if choice.relative > 0 then selected = math.min(selected + choice.relative, #results) else selected = math.max(selected + choice.relative, 1) end end match_listing:select(selected) end end, position = options.position, }) prompt:show() if cmdline_enter_autocmd == nil then cmdline_enter_autocmd = vim.api.nvim_create_autocmd('CmdlineEnter', { callback = close, }) end end return ui
fix(lua): restore current window before running open command
fix(lua): restore current window before running open command Remember the current window before going to the UI, then restore it when coming back. Otherwise, we end up always opening in the topmost/leftmost split, because that is where Neovim is going to put the focus when we close. Likewise if we dismiss the UI without choosing an item, we would go back to the topmost/leftmost split. Not sure if I need to defer until after the autocommands run or not, but it doesn't seem like it hurts to do so, so using `defer_fn()` for that. Still not solved: my custom autocommands don't cope well with the UI being dismissed without actually opening an item. Focus goes back to the window you came from, but the syntax etc doesn't get reapplied. Will dig into that later.
Lua
bsd-2-clause
wincent/command-t,wincent/command-t,wincent/command-t
f2f04961049d477ed0d3f5dd13cc12eb706bb4a3
Peripherals/HDD.lua
Peripherals/HDD.lua
local events = require("Engine.events") --A function that calculates the total size of a directory local function calcSize(dir) local total = 0 local files = love.filesystem.getDirectoryItems(dir) for k,filename in ipairs(files) do if love.filesystem.isDirectory(dir..filename) then total = total + calcSize(path..filename.."/") else total = total + love.filesystem.getSize(dir..filename) end end return total end return function(config) --A function that creates a new HDD peripheral. --Pre-init-- if not love.filesystem.exists("/drives") then love.filesystem.createDirectory("/drives") end --Create the folder that holds virtual drives. local drives = {} --Load the virtual hdds configurations-- if not config["C"] then config["C"] = 1024*1024 * 12 end --Defaults to 12 Megabyte for letter, size in pairs(config) do if not love.filesystem.exists("/drives/"..letter) then love.filesystem.createDirectory("/drives/"..letter) --Create the drive directory if doesn't exists drives[letter] = {size = size, usage = 0} --It's a new empty drive ! else drives[letter] = {size = size, usage = calcSize("/drives/"..letter)} --Register the drive end end --The api starts here-- local HDD = {} local ad = "C" --The active drive letter --Returns a list of the available drives. function HDD.drivers() local dlist = {} for k,v in ipairs(drives) do dlist[k] = {size=drives[k].size,usage=drives[k].usage} end return true,dlist end --Sets or gets the current active drive. function HDD.drive(letter) if letter then if type(letter) ~= "string" then return false, "The drive letter must be a string, provided: "..type(letter) end --Error if not drives[letter] then return false, "The drive '"..letter.."' doesn't exists" end ad = letter --Set the active drive letter. return true --It ran successfully else return true, ad end end function HDD.write(fname,data,size) if type(fname) ~= "string" then return false, "Filename must be a string, provided: "..type(fname) end --Error if type(data) == "nil" then return false, "Should provide the data to write" end local data = tostring(data) if type(size) ~= "number" and size then return false, "Size must be a number, provided: "..type(size) end local path = "/drives/"..ad.."/"..fname local oldsize = (love.filesystem.exists(path) and love.filesystem.isFile(path)) and love.filesystem.getSize(path) or 0 --Old file size. local file,err = love.filesystem.newFile(path,"w") if not file then return false,err end --Error file:write(data,size) --Write to the file (without saving) local newsize = file:getSize() --The size of the new file if drives[ad].size < ((drives[ad].usage - oldsize) + newsize) then file:close() return false, "No more enough space" end --Error file:flush() --Save the new file file:close() --Close the file drives[ad].usage = (drives[ad].usage - oldsize) + newsize --Update the usage return true, newsize end function HDD.read(fname,size) if type(fname) ~= "string" then return false, "Filename must be a string, provided: "..type(fname) end --Error if type(size) ~= "number" and size then return false, "Size must be a number, provided: "..type(size) end --Error local data, err = love.filesystem.read("/drives/"..ad.."/"..fname,size) if data then return true,data else return false,err end end function HDD.getSize(fname) if type(fname) ~= "string" then return false, "Filename must be a string, provided: "..type(fname) end --Error return love.filesystem.getSize("/drives/"..ad.."/"..fname) end function HDD.exists(fname) if type(fname) ~= "string" then return false, "File/Folder name must be a string, provided: "..type(fname) end --Error return true, love.filesystem.exists("/drives/"..ad.."/"..fname) end function HDD.newFolder(fname) if type(fname) ~= "string" then return false, "Foldername must be a string, provided: "..type(fname) end --Error return love.filesystem.createDirectory("/drives/"..ad.."/"..fname) end function HDD.isFile(fname) if type(fname) ~= "string" then return false, "Filename must be a string, provided: "..type(fname) end --Error local path = "/drives/"..ad.."/"..fname if not love.filesystem.exists(path) then return false, "The file doesn't exists" end --Error return true, love.filesystem.isFile(path) end function HDD.isDirrctory(fname) if type(fname) ~= "string" then return false, "Foldername must be a string, provided: "..type(fname) end --Error local path = "/drives/"..ad.."/"..fname if not love.filesystem.exists(path) then return false, "The folder doesn't exists" end --Error return true, love.filesystem.isDirectory(path) end function HDD.getDirectoryItems(fname) if type(fname) ~= "string" then return false, "Foldername must be a string, provided: "..type(fname) end --Error local path = "/drives/"..ad.."/"..fname if not love.filesystem.exists(path) then return false, "Folder doesn't exists" end --Error if not love.filesystem.isDirectory(path) then return false, "Provided a path to a file instead of a folder" end --Error return true, love.filesystem.getDirectoryItems(path) end return HDD end
local events = require("Engine.events") --A function that calculates the total size of a directory local function calcSize(dir) local total = 0 local files = love.filesystem.getDirectoryItems(dir) for k,filename in ipairs(files) do if love.filesystem.isDirectory(dir.."/"..filename) then total = total + calcSize(dir.."/"..filename.."/") else total = total + love.filesystem.getSize(dir.."/"..filename) end end return total end return function(config) --A function that creates a new HDD peripheral. --Pre-init-- if not love.filesystem.exists("/drives") then love.filesystem.createDirectory("/drives") end --Create the folder that holds virtual drives. local drives = {} --Load the virtual hdds configurations-- if not config["C"] then config["C"] = 1024*1024 * 12 end --Defaults to 12 Megabyte for letter, size in pairs(config) do if not love.filesystem.exists("/drives/"..letter) then love.filesystem.createDirectory("/drives/"..letter) --Create the drive directory if doesn't exists drives[letter] = {size = size, usage = 0} --It's a new empty drive ! else drives[letter] = {size = size, usage = calcSize("/drives/"..letter)} --Register the drive end end --The api starts here-- local HDD = {} local ad = "C" --The active drive letter --Returns a list of the available drives. function HDD.drivers() local dlist = {} for k,v in ipairs(drives) do dlist[k] = {size=drives[k].size,usage=drives[k].usage} end return true,dlist end --Sets or gets the current active drive. function HDD.drive(letter) if letter then if type(letter) ~= "string" then return false, "The drive letter must be a string, provided: "..type(letter) end --Error if not drives[letter] then return false, "The drive '"..letter.."' doesn't exists" end ad = letter --Set the active drive letter. return true --It ran successfully else return true, ad end end function HDD.write(fname,data,size) if type(fname) ~= "string" then return false, "Filename must be a string, provided: "..type(fname) end --Error if type(data) == "nil" then return false, "Should provide the data to write" end local data = tostring(data) if type(size) ~= "number" and size then return false, "Size must be a number, provided: "..type(size) end local path = "/drives/"..ad.."/"..fname local oldsize = (love.filesystem.exists(path) and love.filesystem.isFile(path)) and love.filesystem.getSize(path) or 0 --Old file size. local file,err = love.filesystem.newFile(path,"w") if not file then return false,err end --Error file:write(data,size) --Write to the file (without saving) local newsize = file:getSize() --The size of the new file if drives[ad].size < ((drives[ad].usage - oldsize) + newsize) then file:close() return false, "No more enough space" end --Error file:flush() --Save the new file file:close() --Close the file drives[ad].usage = (drives[ad].usage - oldsize) + newsize --Update the usage return true, newsize end function HDD.read(fname,size) if type(fname) ~= "string" then return false, "Filename must be a string, provided: "..type(fname) end --Error if type(size) ~= "number" and size then return false, "Size must be a number, provided: "..type(size) end --Error local data, err = love.filesystem.read("/drives/"..ad.."/"..fname,size) if data then return true,data else return false,err end end function HDD.load(fname) if type(fname) ~= "string" then return false, "Filename must be a string, provided: "..type(fname) end --Error local chunk, err = love.filesystem.load("/drives/"..ad.."/"..fname) return true, chunk, err end function HDD.getSize(fname) if type(fname) ~= "string" then return false, "Filename must be a string, provided: "..type(fname) end --Error return love.filesystem.getSize("/drives/"..ad.."/"..fname) end function HDD.exists(fname) if type(fname) ~= "string" then return false, "File/Folder name must be a string, provided: "..type(fname) end --Error return true, love.filesystem.exists("/drives/"..ad.."/"..fname) end function HDD.newFolder(fname) if type(fname) ~= "string" then return false, "Foldername must be a string, provided: "..type(fname) end --Error return love.filesystem.createDirectory("/drives/"..ad.."/"..fname) end function HDD.isFile(fname) if type(fname) ~= "string" then return false, "Filename must be a string, provided: "..type(fname) end --Error local path = "/drives/"..ad.."/"..fname if not love.filesystem.exists(path) then return false, "The file doesn't exists" end --Error return true, love.filesystem.isFile(path) end function HDD.isDirrctory(fname) if type(fname) ~= "string" then return false, "Foldername must be a string, provided: "..type(fname) end --Error local path = "/drives/"..ad.."/"..fname if not love.filesystem.exists(path) then return false, "The folder doesn't exists" end --Error return true, love.filesystem.isDirectory(path) end function HDD.getDirectoryItems(fname) if type(fname) ~= "string" then return false, "Foldername must be a string, provided: "..type(fname) end --Error local path = "/drives/"..ad.."/"..fname if not love.filesystem.exists(path) then return false, "Folder doesn't exists" end --Error if not love.filesystem.isDirectory(path) then return false, "Provided a path to a file instead of a folder" end --Error return true, love.filesystem.getDirectoryItems(path) end return HDD end
Bugfixes + HDD.load
Bugfixes + HDD.load
Lua
mit
RamiLego4Game/LIKO-12
58b252456c849439758bb50d457079ab5fe140a7
modules/admin-full/luasrc/model/cbi/admin_network/network.lua
modules/admin-full/luasrc/model/cbi/admin_network/network.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local fs = require "nixio.fs" m = Map("network", translate("Interfaces")) m:section(SimpleSection).template = "admin_network/iface_overview" -- Show ATM bridge section if we have the capabilities if fs.access("/usr/sbin/br2684ctl") then atm = m:section(TypedSection, "atm-bridge", translate("ATM Bridges"), translate("ATM bridges expose encapsulated ethernet in AAL5 " .. "connections as virtual Linux network interfaces which can " .. "be used in conjunction with DHCP or PPP to dial into the " .. "provider network.")) atm.addremove = true atm.anonymous = true atm.create = function(self, section) local sid = TypedSection.create(self, section) local max_unit = -1 m.uci:foreach("network", "atm-bridge", function(s) local u = tonumber(s.unit) if u ~= nil and u > max_unit then max_unit = u end end) m.uci:set("network", sid, "unit", max_unit + 1) m.uci:set("network", sid, "atmdev", 0) m.uci:set("network", sid, "encaps", "llc") m.uci:set("network", sid, "payload", "bridged") m.uci:set("network", sid, "vci", 35) m.uci:set("network", sid, "vpi", 8) return sid end atm:tab("general", translate("General Setup")) atm:tab("advanced", translate("Advanced Settings")) vci = atm:taboption("general", Value, "vci", translate("ATM Virtual Channel Identifier (VCI)")) vpi = atm:taboption("general", Value, "vpi", translate("ATM Virtual Path Identifier (VPI)")) encaps = atm:taboption("general", ListValue, "encaps", translate("Encapsulation mode")) encaps:value("llc", translate("LLC")) encaps:value("vc", translate("VC-Mux")) atmdev = atm:taboption("advanced", Value, "atmdev", translate("ATM device number")) unit = atm:taboption("advanced", Value, "unit", translate("Bridge unit number")) payload = atm:taboption("advanced", ListValue, "payload", translate("Forwarding mode")) payload:value("bridged", translate("bridged")) payload:value("routed", translate("routed")) else m.pageaction = false end return m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local fs = require "nixio.fs" m = Map("network", translate("Interfaces")) m.pageaction = false m:section(SimpleSection).template = "admin_network/iface_overview" -- Show ATM bridge section if we have the capabilities if fs.access("/usr/sbin/br2684ctl") then atm = m:section(TypedSection, "atm-bridge", translate("ATM Bridges"), translate("ATM bridges expose encapsulated ethernet in AAL5 " .. "connections as virtual Linux network interfaces which can " .. "be used in conjunction with DHCP or PPP to dial into the " .. "provider network.")) atm.addremove = true atm.anonymous = true atm.create = function(self, section) local sid = TypedSection.create(self, section) local max_unit = -1 m.uci:foreach("network", "atm-bridge", function(s) local u = tonumber(s.unit) if u ~= nil and u > max_unit then max_unit = u end end) m.uci:set("network", sid, "unit", max_unit + 1) m.uci:set("network", sid, "atmdev", 0) m.uci:set("network", sid, "encaps", "llc") m.uci:set("network", sid, "payload", "bridged") m.uci:set("network", sid, "vci", 35) m.uci:set("network", sid, "vpi", 8) return sid end atm:tab("general", translate("General Setup")) atm:tab("advanced", translate("Advanced Settings")) vci = atm:taboption("general", Value, "vci", translate("ATM Virtual Channel Identifier (VCI)")) vpi = atm:taboption("general", Value, "vpi", translate("ATM Virtual Path Identifier (VPI)")) encaps = atm:taboption("general", ListValue, "encaps", translate("Encapsulation mode")) encaps:value("llc", translate("LLC")) encaps:value("vc", translate("VC-Mux")) atmdev = atm:taboption("advanced", Value, "atmdev", translate("ATM device number")) unit = atm:taboption("advanced", Value, "unit", translate("Bridge unit number")) payload = atm:taboption("advanced", ListValue, "payload", translate("Forwarding mode")) payload:value("bridged", translate("bridged")) payload:value("routed", translate("routed")) m.pageaction = true end local network = require "luci.model.network" if network:has_ipv6() then local s = m:section(NamedSection, "globals", "globals", translate("Global network options")) local o = s:option(Value, "ula_prefix", translate("IPv6 ULA-Prefix")) o.datatype = "ip6addr" o.rmempty = true m.pageaction = true end return m
Add support for changing ULA prefix
Add support for changing ULA prefix
Lua
apache-2.0
ReclaimYourPrivacy/cloak-luci,deepak78/new-luci,nmav/luci,oneru/luci,thess/OpenWrt-luci,taiha/luci,thesabbir/luci,ReclaimYourPrivacy/cloak-luci,schidler/ionic-luci,forward619/luci,nmav/luci,LuttyYang/luci,LuttyYang/luci,wongsyrone/luci-1,deepak78/new-luci,db260179/openwrt-bpi-r1-luci,Wedmer/luci,deepak78/new-luci,david-xiao/luci,shangjiyu/luci-with-extra,daofeng2015/luci,dwmw2/luci,bright-things/ionic-luci,forward619/luci,daofeng2015/luci,sujeet14108/luci,zhaoxx063/luci,kuoruan/luci,david-xiao/luci,RedSnake64/openwrt-luci-packages,openwrt/luci,artynet/luci,mumuqz/luci,fkooman/luci,jchuang1977/luci-1,jchuang1977/luci-1,lcf258/openwrtcn,aa65535/luci,Kyklas/luci-proto-hso,forward619/luci,cappiewu/luci,obsy/luci,rogerpueyo/luci,maxrio/luci981213,wongsyrone/luci-1,openwrt/luci,cshore-firmware/openwrt-luci,Hostle/openwrt-luci-multi-user,bittorf/luci,marcel-sch/luci,florian-shellfire/luci,urueedi/luci,sujeet14108/luci,wongsyrone/luci-1,lcf258/openwrtcn,maxrio/luci981213,MinFu/luci,lcf258/openwrtcn,thesabbir/luci,keyidadi/luci,hnyman/luci,Hostle/luci,Wedmer/luci,nmav/luci,jchuang1977/luci-1,remakeelectric/luci,tobiaswaldvogel/luci,marcel-sch/luci,openwrt/luci,db260179/openwrt-bpi-r1-luci,oneru/luci,chris5560/openwrt-luci,kuoruan/lede-luci,bright-things/ionic-luci,ollie27/openwrt_luci,remakeelectric/luci,Kyklas/luci-proto-hso,chris5560/openwrt-luci,openwrt-es/openwrt-luci,db260179/openwrt-bpi-r1-luci,maxrio/luci981213,rogerpueyo/luci,NeoRaider/luci,joaofvieira/luci,nmav/luci,rogerpueyo/luci,Hostle/luci,daofeng2015/luci,david-xiao/luci,Kyklas/luci-proto-hso,Sakura-Winkey/LuCI,taiha/luci,tobiaswaldvogel/luci,981213/luci-1,schidler/ionic-luci,teslamint/luci,hnyman/luci,cshore/luci,maxrio/luci981213,Noltari/luci,harveyhu2012/luci,kuoruan/lede-luci,palmettos/test,aa65535/luci,aircross/OpenWrt-Firefly-LuCI,hnyman/luci,remakeelectric/luci,sujeet14108/luci,Hostle/luci,oyido/luci,palmettos/test,RedSnake64/openwrt-luci-packages,aircross/OpenWrt-Firefly-LuCI,tobiaswaldvogel/luci,zhaoxx063/luci,cappiewu/luci,bittorf/luci,bright-things/ionic-luci,jlopenwrtluci/luci,bittorf/luci,sujeet14108/luci,florian-shellfire/luci,ReclaimYourPrivacy/cloak-luci,RedSnake64/openwrt-luci-packages,981213/luci-1,tcatm/luci,joaofvieira/luci,chris5560/openwrt-luci,keyidadi/luci,cshore-firmware/openwrt-luci,schidler/ionic-luci,florian-shellfire/luci,Noltari/luci,cshore/luci,kuoruan/lede-luci,palmettos/cnLuCI,MinFu/luci,LuttyYang/luci,LazyZhu/openwrt-luci-trunk-mod,urueedi/luci,joaofvieira/luci,palmettos/cnLuCI,david-xiao/luci,ff94315/luci-1,NeoRaider/luci,nwf/openwrt-luci,keyidadi/luci,harveyhu2012/luci,oyido/luci,slayerrensky/luci,Sakura-Winkey/LuCI,RuiChen1113/luci,cshore/luci,Wedmer/luci,nwf/openwrt-luci,teslamint/luci,cappiewu/luci,lcf258/openwrtcn,db260179/openwrt-bpi-r1-luci,bright-things/ionic-luci,dismantl/luci-0.12,fkooman/luci,maxrio/luci981213,schidler/ionic-luci,ollie27/openwrt_luci,schidler/ionic-luci,ReclaimYourPrivacy/cloak-luci,tcatm/luci,jchuang1977/luci-1,dismantl/luci-0.12,openwrt-es/openwrt-luci,kuoruan/luci,daofeng2015/luci,NeoRaider/luci,harveyhu2012/luci,mumuqz/luci,cappiewu/luci,oyido/luci,male-puppies/luci,RedSnake64/openwrt-luci-packages,obsy/luci,slayerrensky/luci,keyidadi/luci,artynet/luci,lbthomsen/openwrt-luci,marcel-sch/luci,MinFu/luci,taiha/luci,kuoruan/lede-luci,sujeet14108/luci,keyidadi/luci,aircross/OpenWrt-Firefly-LuCI,Hostle/luci,daofeng2015/luci,nwf/openwrt-luci,cshore/luci,deepak78/new-luci,palmettos/cnLuCI,jlopenwrtluci/luci,cshore-firmware/openwrt-luci,teslamint/luci,MinFu/luci,artynet/luci,cappiewu/luci,oyido/luci,opentechinstitute/luci,harveyhu2012/luci,ollie27/openwrt_luci,Hostle/openwrt-luci-multi-user,thess/OpenWrt-luci,cappiewu/luci,keyidadi/luci,nmav/luci,palmettos/cnLuCI,zhaoxx063/luci,wongsyrone/luci-1,jorgifumi/luci,openwrt/luci,chris5560/openwrt-luci,david-xiao/luci,bittorf/luci,palmettos/test,openwrt-es/openwrt-luci,slayerrensky/luci,jlopenwrtluci/luci,jlopenwrtluci/luci,hnyman/luci,florian-shellfire/luci,teslamint/luci,obsy/luci,artynet/luci,lbthomsen/openwrt-luci,RuiChen1113/luci,palmettos/cnLuCI,palmettos/test,Kyklas/luci-proto-hso,palmettos/cnLuCI,Noltari/luci,ff94315/luci-1,ollie27/openwrt_luci,jorgifumi/luci,MinFu/luci,male-puppies/luci,Wedmer/luci,nwf/openwrt-luci,bright-things/ionic-luci,maxrio/luci981213,ReclaimYourPrivacy/cloak-luci,Hostle/openwrt-luci-multi-user,aircross/OpenWrt-Firefly-LuCI,Sakura-Winkey/LuCI,jchuang1977/luci-1,Kyklas/luci-proto-hso,ff94315/luci-1,Sakura-Winkey/LuCI,openwrt-es/openwrt-luci,rogerpueyo/luci,fkooman/luci,Hostle/openwrt-luci-multi-user,urueedi/luci,urueedi/luci,mumuqz/luci,kuoruan/lede-luci,urueedi/luci,sujeet14108/luci,dwmw2/luci,thesabbir/luci,Kyklas/luci-proto-hso,ff94315/luci-1,ollie27/openwrt_luci,fkooman/luci,thess/OpenWrt-luci,db260179/openwrt-bpi-r1-luci,mumuqz/luci,Hostle/openwrt-luci-multi-user,marcel-sch/luci,openwrt/luci,harveyhu2012/luci,jorgifumi/luci,aircross/OpenWrt-Firefly-LuCI,RuiChen1113/luci,chris5560/openwrt-luci,marcel-sch/luci,ReclaimYourPrivacy/cloak-luci,forward619/luci,NeoRaider/luci,cshore-firmware/openwrt-luci,Hostle/luci,thess/OpenWrt-luci,Sakura-Winkey/LuCI,deepak78/new-luci,dwmw2/luci,thesabbir/luci,cshore/luci,jorgifumi/luci,daofeng2015/luci,keyidadi/luci,joaofvieira/luci,forward619/luci,RuiChen1113/luci,kuoruan/luci,hnyman/luci,forward619/luci,zhaoxx063/luci,obsy/luci,slayerrensky/luci,opentechinstitute/luci,tobiaswaldvogel/luci,aa65535/luci,LuttyYang/luci,NeoRaider/luci,Hostle/openwrt-luci-multi-user,palmettos/test,cshore-firmware/openwrt-luci,joaofvieira/luci,cappiewu/luci,981213/luci-1,shangjiyu/luci-with-extra,urueedi/luci,remakeelectric/luci,deepak78/new-luci,sujeet14108/luci,jlopenwrtluci/luci,lbthomsen/openwrt-luci,deepak78/new-luci,ff94315/luci-1,RuiChen1113/luci,nmav/luci,lbthomsen/openwrt-luci,slayerrensky/luci,jlopenwrtluci/luci,remakeelectric/luci,Wedmer/luci,openwrt-es/openwrt-luci,florian-shellfire/luci,artynet/luci,Hostle/openwrt-luci-multi-user,bittorf/luci,Hostle/luci,rogerpueyo/luci,LazyZhu/openwrt-luci-trunk-mod,thesabbir/luci,wongsyrone/luci-1,rogerpueyo/luci,Sakura-Winkey/LuCI,ollie27/openwrt_luci,thesabbir/luci,remakeelectric/luci,chris5560/openwrt-luci,joaofvieira/luci,oneru/luci,david-xiao/luci,thesabbir/luci,male-puppies/luci,kuoruan/lede-luci,RedSnake64/openwrt-luci-packages,ReclaimYourPrivacy/cloak-luci,jlopenwrtluci/luci,opentechinstitute/luci,ollie27/openwrt_luci,palmettos/cnLuCI,tcatm/luci,sujeet14108/luci,LuttyYang/luci,ff94315/luci-1,bright-things/ionic-luci,RuiChen1113/luci,shangjiyu/luci-with-extra,obsy/luci,marcel-sch/luci,981213/luci-1,Kyklas/luci-proto-hso,harveyhu2012/luci,teslamint/luci,cshore/luci,jorgifumi/luci,Noltari/luci,ff94315/luci-1,opentechinstitute/luci,hnyman/luci,dismantl/luci-0.12,joaofvieira/luci,keyidadi/luci,openwrt-es/openwrt-luci,lbthomsen/openwrt-luci,bright-things/ionic-luci,ollie27/openwrt_luci,MinFu/luci,aa65535/luci,nwf/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,oneru/luci,cappiewu/luci,fkooman/luci,harveyhu2012/luci,nmav/luci,tcatm/luci,nwf/openwrt-luci,lcf258/openwrtcn,florian-shellfire/luci,nwf/openwrt-luci,NeoRaider/luci,zhaoxx063/luci,oyido/luci,slayerrensky/luci,mumuqz/luci,deepak78/new-luci,kuoruan/luci,wongsyrone/luci-1,fkooman/luci,Noltari/luci,tobiaswaldvogel/luci,lcf258/openwrtcn,shangjiyu/luci-with-extra,Noltari/luci,palmettos/test,dwmw2/luci,NeoRaider/luci,taiha/luci,db260179/openwrt-bpi-r1-luci,db260179/openwrt-bpi-r1-luci,tcatm/luci,remakeelectric/luci,MinFu/luci,kuoruan/lede-luci,lcf258/openwrtcn,teslamint/luci,oneru/luci,shangjiyu/luci-with-extra,Hostle/luci,LuttyYang/luci,aircross/OpenWrt-Firefly-LuCI,jorgifumi/luci,fkooman/luci,slayerrensky/luci,dismantl/luci-0.12,thess/OpenWrt-luci,dismantl/luci-0.12,openwrt/luci,cshore-firmware/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,oyido/luci,zhaoxx063/luci,dismantl/luci-0.12,tcatm/luci,dwmw2/luci,shangjiyu/luci-with-extra,tcatm/luci,slayerrensky/luci,cshore/luci,LazyZhu/openwrt-luci-trunk-mod,opentechinstitute/luci,Hostle/luci,kuoruan/luci,Hostle/openwrt-luci-multi-user,thess/OpenWrt-luci,oyido/luci,Wedmer/luci,cshore-firmware/openwrt-luci,palmettos/test,RuiChen1113/luci,taiha/luci,aa65535/luci,Wedmer/luci,joaofvieira/luci,aa65535/luci,zhaoxx063/luci,oneru/luci,lbthomsen/openwrt-luci,RuiChen1113/luci,kuoruan/luci,oneru/luci,oyido/luci,male-puppies/luci,mumuqz/luci,MinFu/luci,kuoruan/luci,dwmw2/luci,LazyZhu/openwrt-luci-trunk-mod,david-xiao/luci,lbthomsen/openwrt-luci,maxrio/luci981213,forward619/luci,981213/luci-1,male-puppies/luci,taiha/luci,tcatm/luci,obsy/luci,lcf258/openwrtcn,openwrt/luci,jlopenwrtluci/luci,male-puppies/luci,chris5560/openwrt-luci,oneru/luci,taiha/luci,marcel-sch/luci,dwmw2/luci,shangjiyu/luci-with-extra,jchuang1977/luci-1,LuttyYang/luci,thess/OpenWrt-luci,forward619/luci,cshore-firmware/openwrt-luci,dismantl/luci-0.12,florian-shellfire/luci,teslamint/luci,Noltari/luci,mumuqz/luci,fkooman/luci,artynet/luci,tobiaswaldvogel/luci,daofeng2015/luci,openwrt-es/openwrt-luci,florian-shellfire/luci,kuoruan/luci,palmettos/test,tobiaswaldvogel/luci,urueedi/luci,bittorf/luci,shangjiyu/luci-with-extra,marcel-sch/luci,opentechinstitute/luci,nwf/openwrt-luci,jorgifumi/luci,urueedi/luci,schidler/ionic-luci,hnyman/luci,LuttyYang/luci,thess/OpenWrt-luci,artynet/luci,david-xiao/luci,chris5560/openwrt-luci,obsy/luci,jorgifumi/luci,nmav/luci,male-puppies/luci,artynet/luci,taiha/luci,lcf258/openwrtcn,kuoruan/lede-luci,981213/luci-1,mumuqz/luci,RedSnake64/openwrt-luci-packages,Wedmer/luci,daofeng2015/luci,LazyZhu/openwrt-luci-trunk-mod,jchuang1977/luci-1,schidler/ionic-luci,ff94315/luci-1,rogerpueyo/luci,male-puppies/luci,wongsyrone/luci-1,aa65535/luci,ReclaimYourPrivacy/cloak-luci,Noltari/luci,obsy/luci,remakeelectric/luci,aa65535/luci,wongsyrone/luci-1,bright-things/ionic-luci,981213/luci-1,lbthomsen/openwrt-luci,db260179/openwrt-bpi-r1-luci,palmettos/cnLuCI,schidler/ionic-luci,thesabbir/luci,teslamint/luci,openwrt-es/openwrt-luci,opentechinstitute/luci,openwrt/luci,cshore/luci,NeoRaider/luci,nmav/luci,opentechinstitute/luci,Sakura-Winkey/LuCI,rogerpueyo/luci,dwmw2/luci,lcf258/openwrtcn,jchuang1977/luci-1,bittorf/luci,maxrio/luci981213,zhaoxx063/luci,bittorf/luci,LazyZhu/openwrt-luci-trunk-mod,hnyman/luci,Sakura-Winkey/LuCI,Noltari/luci,tobiaswaldvogel/luci,RedSnake64/openwrt-luci-packages,artynet/luci,LazyZhu/openwrt-luci-trunk-mod
2c16488e493c7a8309f24d832fa2e9665405569b
src/program/config/listen/listen.lua
src/program/config/listen/listen.lua
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(..., package.seeall) local S = require("syscall") local ffi = require("ffi") local rpc = require("lib.yang.rpc") local data = require("lib.yang.data") local path_lib = require("lib.yang.path") local common = require("program.config.common") local json_lib = require("program.config.json") local function validate_value(schema_name, revision_date, path, value_str) local parser = common.data_parser(schema_name, path) local value = parser(value_str) return common.serialize_config(value, schema_name, path) end local request_handlers = {} function request_handlers.get(schema_name, revision_date, path) return {method='get-config', args={schema=schema_name, revision=revision_date, path=path}} end function request_handlers.get_state(schema_name, revision_date, path) return {method='get-state', args={schema=schema_name, revision=revision_date, path=path}} end function request_handlers.set(schema_name, revision_date, path, value) assert(value ~= nil) local config = validate_value(schema_name, revision_date, path, value) return {method='set-config', args={schema=schema_name, revision=revision_date, path=path, config=config}} end function request_handlers.add(schema_name, revision_date, path, value) assert(value ~= nil) local config = validate_value(schema_name, revision_date, path, value) return {method='add-config', args={schema=schema_name, revision=revision_date, path=path, config=config}} end function request_handlers.remove(schema_name, revision_date, path) return {method='remove-config', args={schema=schema_name, revision=revision_date, path=path}} end local function read_request(client, schema_name, revision_date) local json = json_lib.read_json_object(client) local id, verb, path = assert(json.id), assert(json.verb), assert(json.path) path = path_lib.normalize_path(path) local handler = assert(request_handlers[data.normalize_id(verb)]) local req = handler(schema_name, revision_date, path, json.value) local function print_reply(reply) local output = json_lib.buffered_output() json_lib.write_json_object(output, {id=id, status='ok', value=reply.config}) output:flush(S.stdout) end return req, print_reply end local function attach_listener(leader, caller, schema_name, revision_date) local msg, parse_reply = rpc.prepare_call( caller, 'attach-listener', {schema=schema_name, revision=revision_date}) common.send_message(leader, msg) return parse_reply(common.recv_message(leader)) end function run(args) args = common.parse_command_line(args, { command='listen' }) local caller = rpc.prepare_caller('snabb-config-leader-v1') local leader = common.open_socket_or_die(args.instance_id) attach_listener(leader, caller, args.schema_name, args.revision_date) local client = json_lib.buffered_input(S.stdin) local pollfds = S.types.t.pollfds({ {fd=leader, events="in"}, {fd=client, events="in"}}) local pending_replies = {} while true do if client:avail() == 0 then assert(S.poll(pollfds, -1)) end for _,pfd in ipairs(pollfds) do if pfd.fd == leader:getfd() then if pfd.ERR or pfd.HUP then while #pending_replies > 0 do local have_reply = table.remove(pending_replies) have_reply(common.recv_message(leader)) end io.stderr:write('Leader hung up\n') main.exit(1) elseif pfd.IN then assert(#pending_replies > 0) local have_reply = table.remove(pending_replies) have_reply(common.recv_message(leader)) end pfd.revents = 0 elseif pfd.fd == client:getfd() then if pfd.ERR or pfd.HUP or pfd.NVAL then io.stderr:write('Client hung up\n') main.exit(0) end if pfd.IN then -- The JSON objects sent to us by the client can have -- whitespace between them. Make sure we don't block -- expecting a new datum when really it was just the -- remote side sending whitespace. (Calling peek() -- causes the buffer to fill, which itself shouldn't -- block given the IN flag in the revents.) client:peek() json_lib.drop_buffered_whitespace(client) end while client:avail() > 0 do local request, print_reply = read_request(client, args.schema_name, args.revision_date) json_lib.drop_buffered_whitespace(client) local msg, parse_reply = rpc.prepare_call( caller, request.method, request.args) local function have_reply(msg) return print_reply(parse_reply(msg)) end common.send_message(leader, msg) table.insert(pending_replies, 1, have_reply) end pfd.revents = 0 else error('unreachable') end end end end
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(..., package.seeall) local S = require("syscall") local ffi = require("ffi") local rpc = require("lib.yang.rpc") local data = require("lib.yang.data") local path_lib = require("lib.yang.path") local common = require("program.config.common") local json_lib = require("program.config.json") local function validate_value(schema_name, revision_date, path, value_str) local parser = common.data_parser(schema_name, path) local value = parser(value_str) return common.serialize_config(value, schema_name, path) end local request_handlers = {} function request_handlers.get(schema_name, revision_date, path) return {method='get-config', args={schema=schema_name, revision=revision_date, path=path}} end function request_handlers.get_state(schema_name, revision_date, path) return {method='get-state', args={schema=schema_name, revision=revision_date, path=path}} end function request_handlers.set(schema_name, revision_date, path, value) assert(value ~= nil) local config = validate_value(schema_name, revision_date, path, value) return {method='set-config', args={schema=schema_name, revision=revision_date, path=path, config=config}} end function request_handlers.add(schema_name, revision_date, path, value) assert(value ~= nil) local config = validate_value(schema_name, revision_date, path, value) return {method='add-config', args={schema=schema_name, revision=revision_date, path=path, config=config}} end function request_handlers.remove(schema_name, revision_date, path) return {method='remove-config', args={schema=schema_name, revision=revision_date, path=path}} end local function read_request(client, schema_name, revision_date) local json = json_lib.read_json_object(client) local id, verb, path = assert(json.id), assert(json.verb), assert(json.path) path = path_lib.normalize_path(path) local handler = assert(request_handlers[data.normalize_id(verb)]) local req = handler(schema_name, revision_date, path, json.value) local function print_reply(reply) local output = json_lib.buffered_output() local value if verb == 'get' then value = reply.config elseif verb == 'get-state' then value = reply.state end json_lib.write_json_object(output, {id=id, status='ok', value=value}) output:flush(S.stdout) end return req, print_reply end local function attach_listener(leader, caller, schema_name, revision_date) local msg, parse_reply = rpc.prepare_call( caller, 'attach-listener', {schema=schema_name, revision=revision_date}) common.send_message(leader, msg) return parse_reply(common.recv_message(leader)) end function run(args) args = common.parse_command_line(args, { command='listen' }) local caller = rpc.prepare_caller('snabb-config-leader-v1') local leader = common.open_socket_or_die(args.instance_id) attach_listener(leader, caller, args.schema_name, args.revision_date) local client = json_lib.buffered_input(S.stdin) local pollfds = S.types.t.pollfds({ {fd=leader, events="in"}, {fd=client, events="in"}}) local pending_replies = {} while true do if client:avail() == 0 then assert(S.poll(pollfds, -1)) end for _,pfd in ipairs(pollfds) do if pfd.fd == leader:getfd() then if pfd.ERR or pfd.HUP then while #pending_replies > 0 do local have_reply = table.remove(pending_replies) have_reply(common.recv_message(leader)) end io.stderr:write('Leader hung up\n') main.exit(1) elseif pfd.IN then assert(#pending_replies > 0) local have_reply = table.remove(pending_replies) have_reply(common.recv_message(leader)) end pfd.revents = 0 elseif pfd.fd == client:getfd() then if pfd.ERR or pfd.HUP or pfd.NVAL then io.stderr:write('Client hung up\n') main.exit(0) end if pfd.IN then -- The JSON objects sent to us by the client can have -- whitespace between them. Make sure we don't block -- expecting a new datum when really it was just the -- remote side sending whitespace. (Calling peek() -- causes the buffer to fill, which itself shouldn't -- block given the IN flag in the revents.) client:peek() json_lib.drop_buffered_whitespace(client) end while client:avail() > 0 do local request, print_reply = read_request(client, args.schema_name, args.revision_date) json_lib.drop_buffered_whitespace(client) local msg, parse_reply = rpc.prepare_call( caller, request.method, request.args) local function have_reply(msg) return print_reply(parse_reply(msg)) end common.send_message(leader, msg) table.insert(pending_replies, 1, have_reply) end pfd.revents = 0 else error('unreachable') end end end end
Fix snabb config listen for get-state.
Fix snabb config listen for get-state.
Lua
apache-2.0
alexandergall/snabbswitch,alexandergall/snabbswitch,Igalia/snabb,eugeneia/snabb,eugeneia/snabb,snabbco/snabb,Igalia/snabb,dpino/snabb,eugeneia/snabbswitch,heryii/snabb,Igalia/snabbswitch,eugeneia/snabbswitch,snabbco/snabb,dpino/snabb,dpino/snabb,alexandergall/snabbswitch,alexandergall/snabbswitch,heryii/snabb,alexandergall/snabbswitch,Igalia/snabb,dpino/snabb,alexandergall/snabbswitch,Igalia/snabb,eugeneia/snabb,heryii/snabb,dpino/snabb,eugeneia/snabb,snabbco/snabb,heryii/snabb,snabbco/snabb,eugeneia/snabb,SnabbCo/snabbswitch,heryii/snabb,eugeneia/snabbswitch,SnabbCo/snabbswitch,Igalia/snabbswitch,dpino/snabb,alexandergall/snabbswitch,dpino/snabbswitch,snabbco/snabb,Igalia/snabb,eugeneia/snabbswitch,dpino/snabbswitch,SnabbCo/snabbswitch,dpino/snabb,dpino/snabbswitch,eugeneia/snabb,eugeneia/snabb,Igalia/snabb,Igalia/snabbswitch,Igalia/snabb,dpino/snabbswitch,Igalia/snabbswitch,SnabbCo/snabbswitch,snabbco/snabb,Igalia/snabbswitch,Igalia/snabb,snabbco/snabb,snabbco/snabb,alexandergall/snabbswitch,eugeneia/snabb,heryii/snabb
c359986d237b305c7a77980ca6386c7d7e35bdb5
plugins/id.lua
plugins/id.lua
local function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = result.peer_id local chatname = result.print_name local text = str2emoji(":busts_in_silhouette:")..' IDs for chat '..chatname ..' ('..chat_id..')\n' ..'There are '..result.members_num..' members' ..'\n---------\n' i = 0 for k,v in pairs(result.members) do i = i+1 text = text .. i .. ". " .. string.gsub(v.print_name, "_", " ") .. " (" .. v.peer_id .. ")\n" end send_large_msg(receiver, text) end local function returnidschan(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = cb_extra.peer_id local chatname = cb_extra.print_name local text = str2emoji(":busts_in_silhouette:")..' IDs for chat '..chatname ..' ('..string.gsub(chat_id, "channel#id", "")..')\n' ..'\n---------\n' i = 0 for k,v in pairs(result) do i = i+1 text = text .. i .. ". " .. string.gsub(v.print_name, "_", " ") .. " (" .. v.peer_id .. ")\n" end send_large_msg(receiver, text) end local function username_id(cb_extra, success, result) local receiver = cb_extra.receiver local qusername = cb_extra.qusername local is_chan = cb_extra.is_chan local text = str2emoji(":no_entry_sign:")..' User @'..qusername..' does not exist!' if success then if result.peer_type == 'channel' then text = str2emoji(":id:")..' ID for group/channel\n'..str2emoji(":busts_in_silhouette:")..' @'..qusername..' : '..result.peer_id else text = str2emoji(":id:")..' ID for user\n'..str2emoji(":bust_in_silhouette:")..' @'..qusername..' : '..result.peer_id end end send_large_msg(receiver, text) end local function id_by_reply(cb_extra, success, result) local username if result.from.username then username = '@'..result.from.username else username = result.from.print_name end send_large_msg(cb_extra, str2emoji(":id:")..' ID for user\n'..str2emoji(":bust_in_silhouette:")..' '..username..' : '..result.from.peer_id) end local function run(msg, matches) local receiver = get_receiver(msg) if matches[1] == "!id" then local text = str2emoji(":bust_in_silhouette:")..' Name: '.. string.gsub(user_print_name(msg.from),'_', ' ') text = text..'\n'..str2emoji(":id:")..' ID: ' .. msg.from.id if is_chat_msg(msg) then text = text .. "\n"..str2emoji(":busts_in_silhouette:").." You are in group " .. string.gsub(user_print_name(msg.to), '_', ' ') text = text .. " (ID: " .. msg.to.id .. ")" end return text elseif matches[1] == "#id" then if msg.reply_id then get_message(msg.reply_id, id_by_reply, get_receiver(msg)) return nil end return nil elseif matches[1] == "chat" then -- !ids? (chat) (%d+) if matches[2] then local group = string.gsub(matches[2], 'chat#id', '') group = string.gsub(group, 'channel#id', '') if is_mod(msg.from.id, group) then local chat = matches[2] if string.starts(chat, "chat#id") then return chat_info(chat, returnids, {receiver=receiver}) end if string.starts(chat, "channel#id") then return channel_get_users(chat, returnidschan, {peer_id=matches[2], print_name="", receiver=receiver}) end return str2emoji(":no_entry_sign:").." Invalid ID." else return str2emoji(":no_entry_sign:").." You cannot lookup the IDs from that group." end else if not is_chat_msg(msg) then return str2emoji(":no_entry_sign:").." You are not in a group." end local chat = get_receiver(msg) if not is_chan_msg(msg) then chat_info(chat, returnids, {receiver=receiver}) else channel_get_users(chat, returnidschan, {peer_id=msg.to.id, print_name=string.gsub(user_print_name(msg.to), '_', ' '), receiver=receiver}) end end else local qusername = string.gsub(matches[1], "@", "") local chat = get_receiver(msg) resolve_username(qusername, username_id, {receiver=receiver, qusername=qusername, is_chan=is_chan_msg(msg)}) end end return { description = "Know your id or the id of a chat members.", usage = { "!id: Return your ID and the chat id if you are in one.", "!ids chat: Return the IDs of the current chat members.", "!ids chat chat#id<chat_id>: Return the IDs of the <chat_id> members.", "!ids chat channel#id<channel_id>: Return the IDs of the <channel_id> (supergroup) members.", "!id <username> : Return the id from username given." }, patterns = { "^!id$", "^#id$", "^!ids? (chat) (.*)$", "^!ids? (chat)$", "^!id (.*)$" }, run = run }
local function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = result.peer_id local chatname = result.print_name local text = str2emoji(":busts_in_silhouette:")..' IDs for chat '..chatname ..' ('..chat_id..')\n' ..'There are '..result.members_num..' members' ..'\n---------\n' i = 0 for k,v in pairs(result.members) do i = i+1 text = text .. i .. ". " .. string.gsub(v.print_name, "_", " ") .. " (" .. v.peer_id .. ")\n" end send_large_msg(receiver, text) end local function returnidschan(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = cb_extra.peer_id local chatname = cb_extra.print_name local text = str2emoji(":busts_in_silhouette:")..' IDs for chat '..chatname ..' ('..string.gsub(chat_id, "channel#id", "")..')\n' ..'\n---------\n' i = 0 for k,v in pairs(result) do i = i+1 if v.print_name ~= nil then text = text .. i .. ". " .. string.gsub(v.print_name, "_", " ") .. " (" .. v.peer_id .. ")\n" else text = text .. i .. ". " .. "?" .. " (" .. v.peer_id .. ")\n" end end send_large_msg(receiver, text) end local function username_id(cb_extra, success, result) local receiver = cb_extra.receiver local qusername = cb_extra.qusername local is_chan = cb_extra.is_chan local text = str2emoji(":no_entry_sign:")..' User @'..qusername..' does not exist!' if success then if result.peer_type == 'channel' then text = str2emoji(":id:")..' ID for group/channel\n'..str2emoji(":busts_in_silhouette:")..' @'..qusername..' : '..result.peer_id else text = str2emoji(":id:")..' ID for user\n'..str2emoji(":bust_in_silhouette:")..' @'..qusername..' : '..result.peer_id end end send_large_msg(receiver, text) end local function id_by_reply(cb_extra, success, result) local username if result.from.username then username = '@'..result.from.username else username = result.from.print_name end send_large_msg(cb_extra, str2emoji(":id:")..' ID for user\n'..str2emoji(":bust_in_silhouette:")..' '..username..' : '..result.from.peer_id) end local function run(msg, matches) local receiver = get_receiver(msg) if matches[1] == "!id" then local text = str2emoji(":bust_in_silhouette:")..' Name: '.. string.gsub(user_print_name(msg.from),'_', ' ') text = text..'\n'..str2emoji(":id:")..' ID: ' .. msg.from.id if is_chat_msg(msg) then text = text .. "\n"..str2emoji(":busts_in_silhouette:").." You are in group " .. string.gsub(user_print_name(msg.to), '_', ' ') text = text .. " (ID: " .. msg.to.id .. ")" end return text elseif matches[1] == "#id" then if msg.reply_id then get_message(msg.reply_id, id_by_reply, get_receiver(msg)) return nil end return nil elseif matches[1] == "chat" then -- !ids? (chat) (%d+) if matches[2] then local group = string.gsub(matches[2], 'chat#id', '') group = string.gsub(group, 'channel#id', '') if is_mod(msg.from.id, group) then local chat = matches[2] if string.starts(chat, "chat#id") then return chat_info(chat, returnids, {receiver=receiver}) end if string.starts(chat, "channel#id") then return channel_get_users(chat, returnidschan, {peer_id=matches[2], print_name="", receiver=receiver}) end return str2emoji(":no_entry_sign:").." Invalid ID." else return str2emoji(":no_entry_sign:").." You cannot lookup the IDs from that group." end else if not is_chat_msg(msg) then return str2emoji(":no_entry_sign:").." You are not in a group." end local chat = get_receiver(msg) if not is_chan_msg(msg) then chat_info(chat, returnids, {receiver=receiver}) else channel_get_users(chat, returnidschan, {peer_id=msg.to.id, print_name=string.gsub(user_print_name(msg.to), '_', ' '), receiver=receiver}) end end else local qusername = string.gsub(matches[1], "@", "") local chat = get_receiver(msg) resolve_username(qusername, username_id, {receiver=receiver, qusername=qusername, is_chan=is_chan_msg(msg)}) end end return { description = "Know your id or the id of a chat members.", usage = { "!id: Return your ID and the chat id if you are in one.", "!ids chat: Return the IDs of the current chat members.", "!ids chat chat#id<chat_id>: Return the IDs of the <chat_id> members.", "!ids chat channel#id<channel_id>: Return the IDs of the <channel_id> (supergroup) members.", "!id <username> : Return the id from username given." }, patterns = { "^!id$", "^#id$", "^!ids? (chat) (.*)$", "^!ids? (chat)$", "^!id (.*)$" }, run = run }
Fix member listing
Fix member listing In API mode working even with supergroups with over 200 members.
Lua
mit
KevinGuarnati/controllore,KevinGuarnati/controllore
909a4f89e48e983245e3597e67fae9caa04f792b
BIOS/init.lua
BIOS/init.lua
--The BIOS should control the system of LIKO-12 and load the peripherals-- --For now it's just a simple BIOS to get LIKO-12 working. --Require the engine libraries-- local events = require("Engine.events") local coreg = require("Engine.coreg") local function splitFilePath(path) return path:match("(.-)([^\\/]-%.?([^%.\\/]*))$") end --A function to split path to path, name, extension. local Peripherals = {} --The loaded peripherals. local MPer = {} --Mounted and initialized peripherals. --A function to load the peripherals. local function indexPeripherals(path) local files = love.filesystem.getDirectoryItems(path) for k,filename in ipairs(files) do if love.filesystem.isDirectory(path..filename) then indexPeripherals(path..filename.."/") else local p, n, e = splitFilePath(path..filename) if e == "lua" then local chunk, err = love.filesystem.load(path..n) if not chunk then Peripherals[n:sub(0,-5)] = "Err: "..tostring(err) else Peripherals[n:sub(0,-5)] = chunk() end end end end end indexPeripherals("/Peripherals/") --Index and Load the peripherals --Peripheral, Err = P(PeriheralName, MountedName, ConfigTabel) local function P(per,m,conf) if not per then return false, "Should provide peripheral name" end if type(per) ~= "string" then return false, "Peripheral name should be a string, provided "..type(per) end if not Peripherals[per] then return false, "'"..per.."' Peripheral doesn't exists" end if type(Peripherals[per]) == "string" then return false, "Compile "..Peripherals[per] end local m = m or per if type(m) ~= "string" then return false, "Mounting name should be a string, provided "..type(m) end if MPer[m] then return false, "Mounting name '"..m.."' is already taken" end local conf = conf or {} if type(conf) ~= "table" then return false, "Configuration table should be a table, provided "..type(conf) end local success, peripheral = pcall(Peripherals[per],conf) if success then MPer[m] = peripheral coreg:register(peripheral,m) else peripheral = "Init Err: "..peripheral end return success, peripheral end if not love.filesystem.exists("/bconf.lua") then love.filesystem.write("/bconf.lua",love.filesystem.read("/BIOS/bconf.lua")) end local bconfC, bconfErr = love.filesystem.load("/bconf.lua") if not bconfC then bconfC = love.filesystem.load("/BIOS/bconf.lua") end --Load the default BConfig setfenv(bconfC,{P = P}) --BConfig sandboxing local success, bconfRErr = pcall(bconfC) if not success then bconfC = love.filesystem.load("/BIOS/bconf.lua") setfenv(bconfC,{P = P}) --BConfig sandboxing bconfC() end --Load the default BConfig local function exe(...) --Excute a LIKO12 api function (to handle errors) local args = {...} if args[1] then local nargs = {} for k,v in pairs(args) do --Clone the args, removing the first one if type(k) == "number" then nargs[k-1] = v else nargs[k] = v end end return unpack(nargs) else return error(args[2]) end end local function flushOS(os,path) local h = MPer.HDD local path = path or "/" local files = love.filesystem.getDirectoryItems("/OS/"..os..path) for k,v in pairs(files) do if love.filesystem.isDirectory("/OS/"..os..path..v) then flushOS(os,path..v.."/") else h.drive("C") --Opereating systems are installed on C drive h.write(path..v,love.filesystem.read("/OS/"..os..path..v)) end end end --No OS Screen local function noOS() if MPer.GPU then flushOS("CartOS") --Should be replaced by a gui else flushOS("CartOS") end end local function startCoroutine() if not MPer.HDD then return end local h = MPer.HDD exe(h.drive("C")) if not exe(h.exists("/boot.lua")) then noOS() end local chunk, err = loadstring(h.read("/boot.lua")) if not chunk then error(err) end coreg:sandboxCoroutine(chunk) local co = coroutine.create(chunk) coreg:setCoroutine(co) --For peripherals to use. end --POST screen if MPer.GPU then --If there is an initialized gpu local g = MPer.GPU g.color(8) local chars = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","-","_","@","#","$","&","*","!","+","=","%"} --48x16 Terminal Size function drawAnim() g.clear() for x=1,48 do for y=1,16 do math.randomseed(os.clock()*os.time()*x) g.color(math.floor(math.random(2,16))) g.printCursor(x,y) math.randomseed(os.clock()*os.time()*y) local c = chars[math.floor(math.random(1,#chars))] if math.random(0,20) % 2 == 0 then c = c:upper() end g.print(c) end end end g.clear() local timer = 0 local stage = 1 events:register("love:update",function(dt) if stage == 6 then --Create the coroutine startCoroutine() stage = 7 --So coroutine don't get duplicated end if stage < 6 then timer = timer + dt if timer > 0.25 then timer = timer -0.25 stage = stage +1 if stage < 5 then drawAnim() elseif stage == 5 then g.clear() end end end end) else --Incase the gpu doesn't exists (Then can't enter the bios nor do the boot animation startCoroutine() end --[[local GPU = Peripherals.GPU({_ClearOnRender=true}) --Create a new GPU --FPS display events:register("love:update",function(dt) love.window.setTitle("LIKO-12 FPS: "..love.timer.getFPS()) end) --Debug Draw-- GPU.points(1,1, 192,1, 192,128, 1,128, 8) GPU.points(0,1, 193,1, 193,128, 0,128, 3) GPU.points(1,0, 192,0, 192,129, 1,129, 3) GPU.rect(2,2, 190,126, true, 12) GPU.line(2,2,191,2,191,127,2,127,2,2,12) GPU.line(2,2, 191,127, 9) GPU.line(191, 2,2,127, 9) GPU.rect(10,42,10,10,false,9) GPU.rect(10,30,10,10,false,9) GPU.rect(10,30,10,10,true,8) GPU.points(10,10, 10,19, 19,19, 19,10, 8)]]
--The BIOS should control the system of LIKO-12 and load the peripherals-- --For now it's just a simple BIOS to get LIKO-12 working. --Require the engine libraries-- local events = require("Engine.events") local coreg = require("Engine.coreg") local function splitFilePath(path) return path:match("(.-)([^\\/]-%.?([^%.\\/]*))$") end --A function to split path to path, name, extension. local Peripherals = {} --The loaded peripherals. local MPer = {} --Mounted and initialized peripherals. --A function to load the peripherals. local function indexPeripherals(path) local files = love.filesystem.getDirectoryItems(path) for k,filename in ipairs(files) do if love.filesystem.isDirectory(path..filename) then indexPeripherals(path..filename.."/") else local p, n, e = splitFilePath(path..filename) if e == "lua" then local chunk, err = love.filesystem.load(path..n) if not chunk then Peripherals[n:sub(0,-5)] = "Err: "..tostring(err) else Peripherals[n:sub(0,-5)] = chunk() end end end end end indexPeripherals("/Peripherals/") --Index and Load the peripherals --Peripheral, Err = P(PeriheralName, MountedName, ConfigTabel) local function P(per,m,conf) if not per then return false, "Should provide peripheral name" end if type(per) ~= "string" then return false, "Peripheral name should be a string, provided "..type(per) end if not Peripherals[per] then return false, "'"..per.."' Peripheral doesn't exists" end if type(Peripherals[per]) == "string" then return false, "Compile "..Peripherals[per] end local m = m or per if type(m) ~= "string" then return false, "Mounting name should be a string, provided "..type(m) end if MPer[m] then return false, "Mounting name '"..m.."' is already taken" end local conf = conf or {} if type(conf) ~= "table" then return false, "Configuration table should be a table, provided "..type(conf) end local success, peripheral = pcall(Peripherals[per],conf) if success then MPer[m] = peripheral coreg:register(peripheral,m) else peripheral = "Init Err: "..peripheral end return success, peripheral end if not love.filesystem.exists("/bconf.lua") or true then love.filesystem.write("/bconf.lua",love.filesystem.read("/BIOS/bconf.lua")) end local bconfC, bconfErr, bconfDErr = love.filesystem.load("/bconf.lua") if not bconfC then bconfC, bconfDErr = love.filesystem.load("/BIOS/bconf.lua") end --Load the default BConfig if not bconfC then error(bconfDErr) end setfenv(bconfC,{P = P,error=error,assert=assert}) --BConfig sandboxing local success, bconfRErr = pcall(bconfC) if not success then bconfC, err = love.filesystem.load("/BIOS/bconf.lua") if not bconfC then error(err) end setfenv(bconfC,{P = P,error=error,assert=assert}) --BConfig sandboxing bconfC() end --Load the default BConfig coreg:register(function() local list = {} for per, funcs in pairs(MPer) do list[per] = {} for name, func in pairs(funcs) do table.insert(list[per],name) end end return true, list end,"BIOS:listPeripherals") local function exe(...) --Excute a LIKO12 api function (to handle errors) local args = {...} if args[1] then local nargs = {} for k,v in ipairs(args) do --Clone the args, removing the first one nargs[k-1] = v end return unpack(nargs) else return error(args[2]) end end local function flushOS(os,path) local h = MPer.HDD local path = path or "/" local files = love.filesystem.getDirectoryItems("/OS/"..os..path) for k,v in pairs(files) do if love.filesystem.isDirectory("/OS/"..os..path..v) then flushOS(os,path..v.."/") else exe(h.drive("C")) --Opereating systems are installed on C drive exe(h.write(path..v,love.filesystem.read("/OS/"..os..path..v))) end end end --No OS Screen local function noOS() if MPer.GPU then flushOS("CartOS") --Should be replaced by a gui else flushOS("CartOS") end end local function startCoroutine() if not MPer.HDD then return error("No HDD Periphrtal") end local h = MPer.HDD exe(h.drive("C")) if not exe(h.exists("/boot.lua")) and false then noOS() end local chunk, err = exe(h.load("/boot.lua")) if not chunk then error(err) end coreg:sandboxCoroutine(chunk) local co = coroutine.create(chunk) coreg:setCoroutine(co) --For peripherals to use. coreg:resumeCoroutine() end --POST screen if MPer.GPU then --If there is an initialized gpu local g = MPer.GPU g.color(8) local chars = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","-","_","@","#","$","&","*","!","+","=","%"} --48x16 Terminal Size function drawAnim() g.clear() for x=1,48 do for y=1,16 do math.randomseed(os.clock()*os.time()*x) g.color(math.floor(math.random(2,16))) g.printCursor(x,y) math.randomseed(os.clock()*os.time()*y) local c = chars[math.floor(math.random(1,#chars))] if math.random(0,20) % 2 == 0 then c = c:upper() end g.print(c) end end end g.clear() local timer = 0 local stage = 1 events:register("love:update",function(dt) if stage == 8 then --Create the coroutine g.color(8) g.clear(1) g.printCursor(1,1) startCoroutine() stage = 9 --So coroutine don't get duplicated end if stage < 8 then timer = timer + dt if timer > 0.25 then timer = timer -0.25 stage = stage +1 if stage < 6 then drawAnim() elseif stage == 6 then g.clear() end end end end) else --Incase the gpu doesn't exists (Then can't enter the bios nor do the boot animation startCoroutine() end --[[local GPU = Peripherals.GPU({_ClearOnRender=true}) --Create a new GPU --FPS display events:register("love:update",function(dt) love.window.setTitle("LIKO-12 FPS: "..love.timer.getFPS()) end) --Debug Draw-- GPU.points(1,1, 192,1, 192,128, 1,128, 8) GPU.points(0,1, 193,1, 193,128, 0,128, 3) GPU.points(1,0, 192,0, 192,129, 1,129, 3) GPU.rect(2,2, 190,126, true, 12) GPU.line(2,2,191,2,191,127,2,127,2,2,12) GPU.line(2,2, 191,127, 9) GPU.line(191, 2,2,127, 9) GPU.rect(10,42,10,10,false,9) GPU.rect(10,30,10,10,false,9) GPU.rect(10,30,10,10,true,8) GPU.points(10,10, 10,19, 19,19, 19,10, 8)]]
Bugfixes + OS booting :D
Bugfixes + OS booting :D
Lua
mit
RamiLego4Game/LIKO-12
fa8df8f767effc272167351357894a0002145a04
put/project.lua
put/project.lua
-- Project project "put" location ("build\\" .. platform_dir) kind "StaticLib" language "C++" libdirs { "../pen/lib/" .. platform_dir, "../put/bullet/lib/" .. platform_dir, } includedirs { "..\\pen\\include\\common", "..\\pen\\include\\" .. platform_dir, "..\\pen\\include\\" .. renderer_dir, "..\\put\\bullet\\src\\", "..\\pen\\third_party\\imgui", "..\\pen\\third_party", } if _ACTION == "vs2017" or _ACTION == "vs2015" then systemversion("8.1:10.1") end files { "include\\**.h", "source\\**.cpp", "..\\pen\\third_party\\imgui\\*.cpp", "..\\pen\\third_party\\imgui\\*.h", } includedirs { "include" } configuration "Debug" defines { "DEBUG" } flags { "WinMain" } symbols "On" targetdir ("lib/" .. platform_dir) targetname "put_d" links { "bullet_monolithic_ploop" } configuration "Release" defines { "NDEBUG" } flags { "WinMain", "OptimizeSpeed" } targetdir ("lib/" .. platform_dir) targetname "put" links { "bullet_monolithic_ploo" }
-- Project project "put" location ("build\\" .. platform_dir) kind "StaticLib" language "C++" libdirs { "../pen/lib/" .. platform_dir, "../put/bullet/lib/" .. platform_dir, } includedirs { "..\\pen\\include\\common", "..\\pen\\include\\" .. platform_dir, "..\\pen\\include\\" .. renderer_dir, "..\\put\\bullet\\src\\", "..\\pen\\third_party\\imgui", "..\\pen\\third_party", } if _ACTION == "vs2017" or _ACTION == "vs2015" then systemversion("8.1:10.1") end files { "include\\**.h", "source\\**.cpp", "..\\pen\\third_party\\imgui\\*.cpp", "..\\pen\\third_party\\imgui\\*.h", } includedirs { "include" } configuration "Debug" defines { "DEBUG" } flags { "WinMain" } symbols "On" targetdir ("lib/" .. platform_dir) targetname "put_d" configuration "Release" defines { "NDEBUG" } flags { "WinMain", "OptimizeSpeed" } targetdir ("lib/" .. platform_dir) targetname "put"
compile fix
compile fix
Lua
mit
polymonster/pmtech,polymonster/pmtech,polymonster/pmtech,polymonster/pmtech,polymonster/pmtech,polymonster/pmtech
0cd73706d7683bbb12331d997baa718d1f228724
mod_ircd/mod_ircd.lua
mod_ircd/mod_ircd.lua
local irc_listener = { default_port = 6667, default_mode = "*l" }; local sessions = {}; local commands = {}; local nicks = {}; local st = require "util.stanza"; local conference_server = module:get_option("conference_server") or "conference.jabber.org"; local function irc_close_session(session) session.conn:close(); end function irc_listener.onincoming(conn, data) local session = sessions[conn]; if not session then session = { conn = conn, host = module.host, reset_stream = function () end, close = irc_close_session, log = logger.init("irc"..(conn.id or "1")), roster = {} }; sessions[conn] = session; function session.data(data) module:log("debug", "Received: %s", data); local command, args = data:match("^%s*([^ ]+) *(.*)%s*$"); if not command then module:log("warn", "Invalid command: %s", data); return; end command = command:upper(); module:log("debug", "Received command: %s", command); if commands[command] then local ret = commands[command](session, args); if ret then session.send(ret.."\r\n"); end end end function session.send(data) module:log("debug", "sending: %s", data); return conn:write(data.."\r\n"); end end if data then session.data(data); end end function irc_listener.ondisconnect(conn, error) module:log("debug", "Client disconnected"); sessions[conn] = nil; end function commands.NICK(session, nick) nick = nick:match("^[%w_]+"); if nicks[nick] then session.send(":"..session.host.." 433 * The nickname "..nick.." is already in use"); return; end nicks[nick] = session; session.nick = nick; session.full_jid = nick.."@"..module.host.."/ircd"; session.type = "c2s"; module:log("debug", "Client bound to %s", session.full_jid); session.send(":"..session.host.." 001 "..session.nick.." :Welcome to XMPP via the "..session.host.." gateway "..session.nick); end local joined_mucs = {}; function commands.JOIN(session, channel) if not joined_mucs[channel] then joined_mucs[channel] = { occupants = {}, sessions = {} }; end joined_mucs[channel].sessions[session] = true; local join_stanza = st.presence({ from = session.full_jid, to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick }); core_process_stanza(session, join_stanza); session.send(":"..session.nick.." JOIN :"..channel); session.send(":"..session.host.." 332 "..session.nick.." "..channel.." :Connection in progress..."); session.send(":"..session.host.." 353 "..session.nick.." = "..channel.." :"..session.nick); session.send(":"..session.host.." 366 "..session.nick.." "..channel.." :End of /NAMES list."); end function commands.PART(session, channel) local channel, part_message = channel:match("^([^:]+):?(.*)$"); channel = channel:match("^([%S]*)"); core_process_stanza(session, st.presence{ type = "unavailable", from = session.full_jid, to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick }:tag("status"):text(part_message)); session.send(":"..session.nick.." PART :"..channel); end function commands.PRIVMSG(session, message) local who, message = message:match("^(%S+) :(.+)$"); if joined_mucs[who] then core_process_stanza(session, st.message{to=who:gsub("^#", "").."@"..conference_server, type="groupchat"}:tag("body"):text(message)); end end function commands.PING(session, server) session.send(":"..session.host..": PONG "..server); end function commands.WHO(session, channel) if joined_mucs[channel] then for nick in pairs(joined_mucs[channel].occupants) do --n=MattJ 91.85.191.50 irc.freenode.net MattJ H :0 Matthew Wild session.send(":"..session.host.." 352 "..session.nick.." "..channel.." "..nick.." "..nick.." "..session.host.." "..nick.." H :0 "..nick); end session.send(":"..session.host.." 315 "..session.nick.." "..channel.. " :End of /WHO list"); end end function commands.MODE(session, channel) session.send(":"..session.host.." 324 "..session.nick.." "..channel.." +J"); end --- Component (handle stanzas from the server for IRC clients) function irc_component(origin, stanza) local from, from_bare = stanza.attr.from, jid.bare(stanza.attr.from); local from_node = "#"..jid.split(stanza.attr.from); if joined_mucs[from_node] and from_bare == from then -- From room itself local joined_muc = joined_mucs[from_node]; if stanza.name == "message" then local subject = stanza:get_child("subject"); if subject then local subject_text = subject:get_text(); for session in pairs(joined_muc.sessions) do session.send(":"..session.host.." 332 "..session.nick.." "..from_node.." :"..subject_text); end end end elseif joined_mucs[from_node] then -- From room occupant local joined_muc = joined_mucs[from_node]; local nick = select(3, jid.split(from)):gsub(" ", "_"); if stanza.name == "presence" then local what; if not stanza.attr.type then if joined_muc.occupants[nick] then return; end joined_muc.occupants[nick] = true; what = "JOIN"; else joined_muc.occupants[nick] = nil; what = "PART"; end for session in pairs(joined_muc.sessions) do if nick ~= session.nick then session.send(":"..nick.."!"..nick.." "..what.." :"..from_node); end end elseif stanza.name == "message" then local body = stanza:get_child("body"); local hasdelay = stanza:get_child("delay", "urn:xmpp:delay"); if body then for session in pairs(joined_muc.sessions) do if nick ~= session.nick or hasdelay then session.send(":"..nick.." PRIVMSG "..from_node.." :"..body:get_text()); end end end end end end require "core.componentmanager".register_component(module.host, irc_component); prosody.events.add_handler("server-stopping", function (shutdown) module:log("debug", "Closing IRC connections prior to shutdown"); for channel, joined_muc in pairs(joined_mucs) do for session in pairs(joined_muc.sessions) do core_process_stanza(session, st.presence{ type = "unavailable", from = session.full_jid, to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick } :tag("status") :text("Connection closed: Server is shutting down"..(shutdown.reason and (": "..shutdown.reason) or ""))); session:close(); end end end); require "net.connlisteners".register("irc", irc_listener); require "net.connlisteners".start("irc", { port = module:get_option("port") });
local irc_listener = { default_port = 6667, default_mode = "*l" }; local sessions = {}; local commands = {}; local nicks = {}; local st = require "util.stanza"; local conference_server = module:get_option("conference_server") or "conference.jabber.org"; local function irc_close_session(session) session.conn:close(); end function irc_listener.onincoming(conn, data) local session = sessions[conn]; if not session then session = { conn = conn, host = module.host, reset_stream = function () end, close = irc_close_session, log = logger.init("irc"..(conn.id or "1")), roster = {} }; sessions[conn] = session; function session.data(data) module:log("debug", "Received: %s", data); local command, args = data:match("^%s*([^ ]+) *(.*)%s*$"); if not command then module:log("warn", "Invalid command: %s", data); return; end command = command:upper(); module:log("debug", "Received command: %s", command); if commands[command] then local ret = commands[command](session, args); if ret then session.send(ret.."\r\n"); end end end function session.send(data) module:log("debug", "sending: %s", data); return conn:write(data.."\r\n"); end end if data then session.data(data); end end function irc_listener.ondisconnect(conn, error) module:log("debug", "Client disconnected"); sessions[conn] = nil; end function commands.NICK(session, nick) nick = nick:match("^[%w_]+"); if nicks[nick] then session.send(":"..session.host.." 433 * The nickname "..nick.." is already in use"); return; end nicks[nick] = session; session.nick = nick; session.full_jid = nick.."@"..module.host.."/ircd"; session.type = "c2s"; module:log("debug", "Client bound to %s", session.full_jid); session.send(":"..session.host.." 001 "..session.nick.." :Welcome to XMPP via the "..session.host.." gateway "..session.nick); end local joined_mucs = {}; function commands.JOIN(session, channel) if not joined_mucs[channel] then joined_mucs[channel] = { occupants = {}, sessions = {} }; end joined_mucs[channel].sessions[session] = true; local join_stanza = st.presence({ from = session.full_jid, to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick }); core_process_stanza(session, join_stanza); session.send(":"..session.nick.." JOIN :"..channel); session.send(":"..session.host.." 332 "..session.nick.." "..channel.." :Connection in progress..."); session.send(":"..session.host.." 353 "..session.nick.." = "..channel.." :"..session.nick); session.send(":"..session.host.." 366 "..session.nick.." "..channel.." :End of /NAMES list."); end function commands.PART(session, channel) local channel, part_message = channel:match("^([^:]+):?(.*)$"); channel = channel:match("^([%S]*)"); core_process_stanza(session, st.presence{ type = "unavailable", from = session.full_jid, to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick }:tag("status"):text(part_message)); session.send(":"..session.nick.." PART :"..channel); end function commands.PRIVMSG(session, message) local who, message = message:match("^(%S+) :(.+)$"); if joined_mucs[who] then core_process_stanza(session, st.message{to=who:gsub("^#", "").."@"..conference_server, type="groupchat"}:tag("body"):text(message)); end end function commands.PING(session, server) session.send(":"..session.host..": PONG "..server); end function commands.WHO(session, channel) if joined_mucs[channel] then for nick in pairs(joined_mucs[channel].occupants) do --n=MattJ 91.85.191.50 irc.freenode.net MattJ H :0 Matthew Wild session.send(":"..session.host.." 352 "..session.nick.." "..channel.." "..nick.." "..nick.." "..session.host.." "..nick.." H :0 "..nick); end session.send(":"..session.host.." 315 "..session.nick.." "..channel.. " :End of /WHO list"); end end function commands.MODE(session, channel) session.send(":"..session.host.." 324 "..session.nick.." "..channel.." +J"); end --- Component (handle stanzas from the server for IRC clients) function irc_component(origin, stanza) local from, from_bare = stanza.attr.from, jid.bare(stanza.attr.from); local from_node = "#"..jid.split(stanza.attr.from); if joined_mucs[from_node] and from_bare == from then -- From room itself local joined_muc = joined_mucs[from_node]; if stanza.name == "message" then local subject = stanza:get_child("subject"); if subject then local subject_text = subject:get_text(); for session in pairs(joined_muc.sessions) do session.send(":"..session.host.." 332 "..session.nick.." "..from_node.." :"..subject_text); end end end elseif joined_mucs[from_node] then -- From room occupant local joined_muc = joined_mucs[from_node]; local nick = select(3, jid.split(from)):gsub(" ", "_"); if stanza.name == "presence" then local what; if not stanza.attr.type then if joined_muc.occupants[nick] then return; end joined_muc.occupants[nick] = true; what = "JOIN"; else joined_muc.occupants[nick] = nil; what = "PART"; end for session in pairs(joined_muc.sessions) do if nick ~= session.nick then session.send(":"..nick.."!"..nick.." "..what.." :"..from_node); end end elseif stanza.name == "message" then local body = stanza:get_child("body"); body = body and body:get_text() or ""; local hasdelay = stanza:get_child("delay", "urn:xmpp:delay"); if body ~= "" then for session in pairs(joined_muc.sessions) do if nick ~= session.nick or hasdelay then session.send(":"..nick.." PRIVMSG "..from_node.." :"..body); end end end end end end require "core.componentmanager".register_component(module.host, irc_component); prosody.events.add_handler("server-stopping", function (shutdown) module:log("debug", "Closing IRC connections prior to shutdown"); for channel, joined_muc in pairs(joined_mucs) do for session in pairs(joined_muc.sessions) do core_process_stanza(session, st.presence{ type = "unavailable", from = session.full_jid, to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick } :tag("status") :text("Connection closed: Server is shutting down"..(shutdown.reason and (": "..shutdown.reason) or ""))); session:close(); end end end); require "net.connlisteners".register("irc", irc_listener); require "net.connlisteners".start("irc", { port = module:get_option("port") });
mod_ircd: Fixed handling of empty <body/> elements.
mod_ircd: Fixed handling of empty <body/> elements.
Lua
mit
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
cbaa12fe71fafacc60596ba6fe21f54267ca525a
util/set.lua
util/set.lua
module "set" function new(list) local items = {}; local set = { items = items }; function set:add(set, item) items[item] = true; end function set:contains(set, item) return items[item] end function set:items(set) return items; end function set:remove(set, item) items[item] = nil; end function set:add_list(set, list) for _, item in ipairs(list) do items[item] = true; end end function set:include(set, otherset) for item in pairs(otherset) do items[item] = true; end end function set:exclude(set, otherset) for item in pairs(otherset) do items[item] = nil; end end return set; end function union(set1, set2) local set = new(); local items = set.items; for item in pairs(set1.items) do items[item] = true; end for item in pairs(set2.items) do items[item] = true; end return set; end function difference(set1, set2) local set = new(); local items = set.items; for item in pairs(set1.items) do items[item] = true; end for item in pairs(set2.items) do items[item] = nil; end return set; end return _M;
local ipairs, pairs = ipairs, pairs; module "set" function new(list) local items = {}; local set = { items = items }; function set:add(item) items[item] = true; end function set:contains(item) return items[item]; end function set:items() return items; end function set:remove(item) items[item] = nil; end function set:add_list(list) for _, item in ipairs(list) do items[item] = true; end end function set:include(otherset) for item in pairs(otherset) do items[item] = true; end end function set:exclude(otherset) for item in pairs(otherset) do items[item] = nil; end end if list then set:add_list(list); end return set; end function union(set1, set2) local set = new(); local items = set.items; for item in pairs(set1.items) do items[item] = true; end for item in pairs(set2.items) do items[item] = true; end return set; end function difference(set1, set2) local set = new(); local items = set.items; for item in pairs(set1.items) do items[item] = true; end for item in pairs(set2.items) do items[item] = nil; end return set; end return _M;
util.set: Fix to make constructor work, and functions defined correctly
util.set: Fix to make constructor work, and functions defined correctly
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
0613ab16c14faf046c164d09e89e987df28c5371
packages/rotate.lua
packages/rotate.lua
local pdf = require("justenoughlibtexpdf") local enter = function (self) if not self.rotate then return end local x = -math.rad(self.rotate) -- Keep center point the same pdf:gsave() local cx = self:left():tonumber() local cy = -self:bottom():tonumber() pdf.setmatrix(1, 0, 0, 1, cx + math.sin(x) * self:height():tonumber(), cy) pdf.setmatrix(math.cos(x), math.sin(x), -math.sin(x), math.cos(x), 0, 0) pdf.setmatrix(1, 0, 0, 1, -cx, -cy) end local leave = function(self) if not self.rotate then return end pdf:grestore() end if SILE.typesetter.frame then enter(SILE.typesetter.frame) table.insert(SILE.typesetter.frame.leaveHooks, leave) end table.insert(SILE.framePrototype.enterHooks, enter) table.insert(SILE.framePrototype.leaveHooks, leave) -- What is the width, depth and height of a rectangle width w and height h rotated by angle theta? -- rect1 = Rectangle[{0, 0}, {w, h}] -- {{xmin, xmax}, {ymin, ymax}} = Refine[RegionBounds[TransformedRegion[rect1, -- RotationTransform[theta, {w/2,h/2}]]], -- w > 0 && h > 0 && theta > 0 && theta < 2 Pi ] -- PiecewiseExpand[xmax - xmin] -- \[Piecewise] -w Cos[theta]-h Sin[theta] Sin[theta]<=0&&Cos[theta]<=0 -- w Cos[theta]-h Sin[theta] Sin[theta]<=0&&Cos[theta]>0 -- -w Cos[theta]+h Sin[theta] Sin[theta]>0&&Cos[theta]<=0 -- w Cos[theta]+h Sin[theta] True local outputRotatedHbox = function (self, typesetter, line) local origbox = self.value.orig local x = self.value.theta -- Find origin of untransformed hbox local save = typesetter.frame.state.cursorX typesetter.frame.state.cursorX = typesetter.frame.state.cursorX - (origbox.width.length-self.width)/2 local horigin = (typesetter.frame.state.cursorX + origbox.width.length / 2):tonumber() local vorigin = -(typesetter.frame.state.cursorY + origbox.height / 2):tonumber() pdf:gsave() pdf.setmatrix(1, 0, 0, 1, horigin, vorigin) pdf.setmatrix(math.cos(x), math.sin(x), -math.sin(x), math.cos(x), 0, 0) pdf.setmatrix(1, 0, 0, 1, -horigin, -vorigin) origbox:outputYourself(typesetter, line) pdf:grestore() typesetter.frame.state.cursorX = save typesetter.frame:advanceWritingDirection(self.width) end SILE.registerCommand("rotate", function(options, content) local angle = SU.required(options, "angle", "rotate command") local theta = -math.rad(angle) local origbox = SILE.call("hbox", {}, content) SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] = nil local h = origbox.height + origbox.depth local w = origbox.width.length local st = math.sin(theta) local ct = math.cos(theta) local height, width, depth if st <= 0 and ct <= 0 then width = -w * ct - h * st height = 0.5*(h-h*ct-w*st) depth = 0.5*(h+h*ct+w*st) elseif st <=0 and ct > 0 then width = w * ct - h * st height = 0.5*(h+h*ct-w*st) depth = 0.5*(h-h*ct+w*st) elseif st > 0 and ct <= 0 then width = -w * ct + h * st height = 0.5*(h-h*ct+w*st) depth = 0.5*(h+h*ct-w*st) else width = w * ct + h * st height = 0.5*(h+h*ct+w*st) depth = 0.5*(h-h*ct-w*st) end depth = -depth if depth < 0 then depth = 0 end SILE.typesetter:pushHbox({ value = { orig = origbox, theta = theta}, height = height, width = width, depth = depth, outputYourself= outputRotatedHbox }) end) return { documentation = [[\begin{document} The \code{rotate} package allows you to rotate things. You can rotate entire frames, by adding the \code{rotate=<angle>} declaration to your frame declaration, and you can rotate any content by issuing the command \code{\\rotate[angle=<angle>]\{...\}}, where \code{<angle>} is measured in degrees. Content which is rotated is placed in a box and rotated. The height and width of the rotated box is measured, and then put into the normal horizontal list for typesetting. The effect of this is that space is reserved around the rotated content. The best way to understand this is by example: here is some text rotated by \rotate[angle=10]{ten}, \rotate[angle=20]{twenty} and \rotate[angle=40]{forty} degrees. The previous line was produced by the following code: \begin{verbatim} \line here is some text rotated by \\rotate[angle=10]\{ten\}, \\rotate[angle=20]\{twenty\} and \\rotate[angle=40]\{forty\} degrees. \line \end{verbatim} \end{document}]] }
local pdf = require("justenoughlibtexpdf") local enter = function (self) if not self.rotate then return end local x = -math.rad(self.rotate) -- Keep center point the same pdf:gsave() local cx = self:left():tonumber() local cy = -self:bottom():tonumber() pdf.setmatrix(1, 0, 0, 1, cx + math.sin(x) * self:height():tonumber(), cy) pdf.setmatrix(math.cos(x), math.sin(x), -math.sin(x), math.cos(x), 0, 0) pdf.setmatrix(1, 0, 0, 1, -cx, -cy) end local leave = function(self) if not self.rotate then return end pdf:grestore() end if SILE.typesetter.frame then enter(SILE.typesetter.frame) table.insert(SILE.typesetter.frame.leaveHooks, leave) end table.insert(SILE.framePrototype.enterHooks, enter) table.insert(SILE.framePrototype.leaveHooks, leave) -- What is the width, depth and height of a rectangle width w and height h rotated by angle theta? -- rect1 = Rectangle[{0, 0}, {w, h}] -- {{xmin, xmax}, {ymin, ymax}} = Refine[RegionBounds[TransformedRegion[rect1, -- RotationTransform[theta, {w/2,h/2}]]], -- w > 0 && h > 0 && theta > 0 && theta < 2 Pi ] -- PiecewiseExpand[xmax - xmin] -- \[Piecewise] -w Cos[theta]-h Sin[theta] Sin[theta]<=0&&Cos[theta]<=0 -- w Cos[theta]-h Sin[theta] Sin[theta]<=0&&Cos[theta]>0 -- -w Cos[theta]+h Sin[theta] Sin[theta]>0&&Cos[theta]<=0 -- w Cos[theta]+h Sin[theta] True local outputRotatedHbox = function (self, typesetter, line) local origbox = self.value.orig local x = self.value.theta -- Find origin of untransformed hbox local save = typesetter.frame.state.cursorX typesetter.frame.state.cursorX = typesetter.frame.state.cursorX - (origbox.width.length-self.width)/2 local horigin = (typesetter.frame.state.cursorX + origbox.width.length / 2):tonumber() local vorigin = -(typesetter.frame.state.cursorY + origbox.height / 2):tonumber() SILE.outputters.libtexpdf._init() pdf:gsave() pdf.setmatrix(1, 0, 0, 1, horigin, vorigin) pdf.setmatrix(math.cos(x), math.sin(x), -math.sin(x), math.cos(x), 0, 0) pdf.setmatrix(1, 0, 0, 1, -horigin, -vorigin) origbox:outputYourself(typesetter, line) pdf:grestore() typesetter.frame.state.cursorX = save typesetter.frame:advanceWritingDirection(self.width) end SILE.registerCommand("rotate", function(options, content) local angle = SU.required(options, "angle", "rotate command") local theta = -math.rad(angle) local origbox = SILE.call("hbox", {}, content) SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] = nil local h = origbox.height + origbox.depth local w = origbox.width.length local st = math.sin(theta) local ct = math.cos(theta) local height, width, depth if st <= 0 and ct <= 0 then width = -w * ct - h * st height = 0.5*(h-h*ct-w*st) depth = 0.5*(h+h*ct+w*st) elseif st <=0 and ct > 0 then width = w * ct - h * st height = 0.5*(h+h*ct-w*st) depth = 0.5*(h-h*ct+w*st) elseif st > 0 and ct <= 0 then width = -w * ct + h * st height = 0.5*(h-h*ct+w*st) depth = 0.5*(h+h*ct-w*st) else width = w * ct + h * st height = 0.5*(h+h*ct+w*st) depth = 0.5*(h-h*ct-w*st) end depth = -depth if depth < 0 then depth = 0 end SILE.typesetter:pushHbox({ value = { orig = origbox, theta = theta}, height = height, width = width, depth = depth, outputYourself= outputRotatedHbox }) end) return { documentation = [[\begin{document} The \code{rotate} package allows you to rotate things. You can rotate entire frames, by adding the \code{rotate=<angle>} declaration to your frame declaration, and you can rotate any content by issuing the command \code{\\rotate[angle=<angle>]\{...\}}, where \code{<angle>} is measured in degrees. Content which is rotated is placed in a box and rotated. The height and width of the rotated box is measured, and then put into the normal horizontal list for typesetting. The effect of this is that space is reserved around the rotated content. The best way to understand this is by example: here is some text rotated by \rotate[angle=10]{ten}, \rotate[angle=20]{twenty} and \rotate[angle=40]{forty} degrees. The previous line was produced by the following code: \begin{verbatim} \line here is some text rotated by \\rotate[angle=10]\{ten\}, \\rotate[angle=20]\{twenty\} and \\rotate[angle=40]\{forty\} degrees. \line \end{verbatim} \end{document}]] }
fix(packages): Assure PDF initialization first-output can be rotated
fix(packages): Assure PDF initialization first-output can be rotated
Lua
mit
alerque/sile,alerque/sile,alerque/sile,alerque/sile
bcf9ac4b1c9b5455abc18f3b59c4725acbcba9c0
mod_muc_intercom/mod_muc_intercom.lua
mod_muc_intercom/mod_muc_intercom.lua
-- Relay messages between rooms -- By Kim Alvefur <zash@zash.se> local host_session = prosody.hosts[module.host]; local st_msg = require "util.stanza".message; local jid = require "util.jid"; function check_message(data) local origin, stanza = data.origin, data.stanza; local muc_rooms = host_session.muc and host_session.muc.rooms; if not muc_rooms then return; end local this_room = muc_rooms[stanza.attr.to]; if not this_room then return; end -- no such room local from_room_jid = this_room._jid_nick[stanza.attr.from]; if not from_room_jid then return; end -- no such nick local from_room, from_host, from_nick = jid.split(from_room_jid); local body = stanza:get_child("body"); body = body and body:get_text(); -- I feel like I want to do `or ""` there :/ local target_room, message = body:match("^@([^:]+):(.*)"); if not target_room or not message then return; end if target_room == from_room then return; end -- don't route to itself module:log("debug", "target room is %s", target_room); local bare_room = jid.join(target_room, from_host); if not muc_rooms[bare_room] then return; end -- TODO send a error module:log("info", "message from %s in %s to %s", from_nick, from_room, target_room); local sender = jid.join(target_room, module.host, from_room .. "/" .. from_nick); local forward_stanza = st_msg({from = sender, to = bare_room, type = "groupchat"}, message); module:log("debug", "broadcasting message to target room"); muc_rooms[bare_room]:broadcast_message(forward_stanza); end module:hook("message/bare", check_message);
-- Relay messages between rooms -- By Kim Alvefur <zash@zash.se> local host_session = prosody.hosts[module.host]; local st_msg = require "util.stanza".message; local jid = require "util.jid"; function check_message(data) local origin, stanza = data.origin, data.stanza; local muc_rooms = host_session.muc and host_session.muc.rooms; if not muc_rooms then return; end local this_room = muc_rooms[stanza.attr.to]; if not this_room then return; end -- no such room local from_room_jid = this_room._jid_nick[stanza.attr.from]; if not from_room_jid then return; end -- no such nick local from_room, from_host, from_nick = jid.split(from_room_jid); local body = stanza:get_child("body"); if not body then return; end -- No body, like topic changes body = body and body:get_text(); -- I feel like I want to do `or ""` there :/ local target_room, message = body:match("^@([^:]+):(.*)"); if not target_room or not message then return; end if target_room == from_room then return; end -- don't route to itself module:log("debug", "target room is %s", target_room); local bare_room = jid.join(target_room, from_host); if not muc_rooms[bare_room] then return; end -- TODO send a error module:log("info", "message from %s in %s to %s", from_nick, from_room, target_room); local sender = jid.join(target_room, module.host, from_room .. "/" .. from_nick); local forward_stanza = st_msg({from = sender, to = bare_room, type = "groupchat"}, message); module:log("debug", "broadcasting message to target room"); muc_rooms[bare_room]:broadcast_message(forward_stanza); end module:hook("message/bare", check_message);
mod_muc_intercom: Fix traceback on topic changes
mod_muc_intercom: Fix traceback on topic changes
Lua
mit
vince06fr/prosody-modules,cryptotoad/prosody-modules,stephen322/prosody-modules,dhotson/prosody-modules,obelisk21/prosody-modules,stephen322/prosody-modules,LanceJenkinZA/prosody-modules,amenophis1er/prosody-modules,crunchuser/prosody-modules,vince06fr/prosody-modules,vince06fr/prosody-modules,obelisk21/prosody-modules,prosody-modules/import,BurmistrovJ/prosody-modules,joewalker/prosody-modules,vfedoroff/prosody-modules,LanceJenkinZA/prosody-modules,either1/prosody-modules,olax/prosody-modules,dhotson/prosody-modules,crunchuser/prosody-modules,crunchuser/prosody-modules,guilhem/prosody-modules,Craige/prosody-modules,syntafin/prosody-modules,NSAKEY/prosody-modules,1st8/prosody-modules,heysion/prosody-modules,mmusial/prosody-modules,mardraze/prosody-modules,guilhem/prosody-modules,amenophis1er/prosody-modules,vfedoroff/prosody-modules,syntafin/prosody-modules,LanceJenkinZA/prosody-modules,heysion/prosody-modules,BurmistrovJ/prosody-modules,apung/prosody-modules,olax/prosody-modules,crunchuser/prosody-modules,guilhem/prosody-modules,asdofindia/prosody-modules,Craige/prosody-modules,either1/prosody-modules,cryptotoad/prosody-modules,asdofindia/prosody-modules,NSAKEY/prosody-modules,iamliqiang/prosody-modules,olax/prosody-modules,Craige/prosody-modules,mardraze/prosody-modules,drdownload/prosody-modules,dhotson/prosody-modules,BurmistrovJ/prosody-modules,joewalker/prosody-modules,1st8/prosody-modules,amenophis1er/prosody-modules,olax/prosody-modules,heysion/prosody-modules,either1/prosody-modules,brahmi2/prosody-modules,heysion/prosody-modules,asdofindia/prosody-modules,drdownload/prosody-modules,syntafin/prosody-modules,olax/prosody-modules,joewalker/prosody-modules,mmusial/prosody-modules,joewalker/prosody-modules,obelisk21/prosody-modules,drdownload/prosody-modules,prosody-modules/import,iamliqiang/prosody-modules,1st8/prosody-modules,crunchuser/prosody-modules,mmusial/prosody-modules,guilhem/prosody-modules,softer/prosody-modules,Craige/prosody-modules,1st8/prosody-modules,iamliqiang/prosody-modules,NSAKEY/prosody-modules,BurmistrovJ/prosody-modules,either1/prosody-modules,stephen322/prosody-modules,BurmistrovJ/prosody-modules,Craige/prosody-modules,LanceJenkinZA/prosody-modules,brahmi2/prosody-modules,apung/prosody-modules,asdofindia/prosody-modules,jkprg/prosody-modules,softer/prosody-modules,drdownload/prosody-modules,vfedoroff/prosody-modules,prosody-modules/import,prosody-modules/import,NSAKEY/prosody-modules,vfedoroff/prosody-modules,asdofindia/prosody-modules,apung/prosody-modules,obelisk21/prosody-modules,LanceJenkinZA/prosody-modules,syntafin/prosody-modules,brahmi2/prosody-modules,iamliqiang/prosody-modules,joewalker/prosody-modules,syntafin/prosody-modules,softer/prosody-modules,mmusial/prosody-modules,cryptotoad/prosody-modules,mardraze/prosody-modules,mmusial/prosody-modules,cryptotoad/prosody-modules,stephen322/prosody-modules,guilhem/prosody-modules,prosody-modules/import,apung/prosody-modules,iamliqiang/prosody-modules,brahmi2/prosody-modules,jkprg/prosody-modules,cryptotoad/prosody-modules,jkprg/prosody-modules,stephen322/prosody-modules,mardraze/prosody-modules,vince06fr/prosody-modules,jkprg/prosody-modules,dhotson/prosody-modules,dhotson/prosody-modules,vince06fr/prosody-modules,1st8/prosody-modules,apung/prosody-modules,vfedoroff/prosody-modules,softer/prosody-modules,amenophis1er/prosody-modules,mardraze/prosody-modules,either1/prosody-modules,drdownload/prosody-modules,softer/prosody-modules,jkprg/prosody-modules,brahmi2/prosody-modules,obelisk21/prosody-modules,NSAKEY/prosody-modules,heysion/prosody-modules,amenophis1er/prosody-modules
0ff777f3d5aa1310689acfbd67cde556f51bdb8d
mod_pastebin/mod_pastebin.lua
mod_pastebin/mod_pastebin.lua
local st = require "util.stanza"; local httpserver = require "net.httpserver"; local uuid_new = require "util.uuid".generate; local os_time = os.time; local t_insert, t_remove = table.insert, table.remove; local add_task = require "util.timer".add_task; local length_threshold = config.get(module.host, "core", "pastebin_threshold") or 500; local line_threshold = config.get(module.host, "core", "pastebin_line_threshold") or 4; local base_url = config.get(module.host, "core", "pastebin_url"); -- Seconds a paste should live for in seconds (config is in hours), default 24 hours local expire_after = math.floor((config.get(module.host, "core", "pastebin_expire_after") or 24) * 3600); local trigger_string = config.get(module.host, "core", "pastebin_trigger"); trigger_string = (trigger_string and trigger_string .. " "); local pastes = {}; local default_headers = { ["Content-Type"] = "text/plain; charset=utf-8" }; local xmlns_xhtmlim = "http://jabber.org/protocol/xhtml-im"; local xmlns_xhtml = "http://www.w3.org/1999/xhtml"; function pastebin_text(text) local uuid = uuid_new(); pastes[uuid] = { body = text, time = os_time(), headers = default_headers }; pastes[#pastes+1] = uuid; if not pastes[2] then -- No other pastes, give the timer a kick add_task(expire_after, expire_pastes); end return base_url..uuid; end function handle_request(method, body, request) local pasteid = request.url.path:match("[^/]+$"); if not pasteid or not pastes[pasteid] then return "Invalid paste id, perhaps it expired?"; end --module:log("debug", "Received request, replying: %s", pastes[pasteid].text); return pastes[pasteid]; end function check_message(data) local origin, stanza = data.origin, data.stanza; local body, bodyindex, htmlindex; for k,v in ipairs(stanza) do if v.name == "body" then body, bodyindex = v, k; elseif v.name == "html" and v.attr.xmlns == xmlns_xhtmlim then htmlindex = k; end end if not body then return; end body = body:get_text(); --module:log("debug", "Body(%s) length: %d", type(body), #(body or "")); if body and ( (#body > length_threshold) or (trigger_string and body:find(trigger_string, 1, true) == 1) or (select(2, body:gsub("\n", "%0")) >= line_threshold) ) then if trigger_string then body = body:gsub("^" .. trigger_string, "", 1); end local url = pastebin_text(body); module:log("debug", "Pasted message as %s", url); --module:log("debug", " stanza[bodyindex] = %q", tostring( stanza[bodyindex])); stanza[bodyindex][1] = url; local html = st.stanza("html", { xmlns = xmlns_xhtmlim }):tag("body", { xmlns = xmlns_xhtml }); html:tag("p"):text(body:sub(1,150):gsub("[\128-\255]+$", "")):up(); html:tag("a", { href = url }):text("[...]"):up(); stanza[htmlindex or #stanza+1] = html; end end module:hook("message/bare", check_message); function expire_pastes(time) time = time or os_time(); -- COMPAT with 0.5 if pastes[1] then pastes[pastes[1]] = nil; t_remove(pastes, 1); if pastes[1] then return (expire_after - (time - pastes[pastes[1]].time)) + 1; end end end local ports = config.get(module.host, "core", "pastebin_ports") or { 5280 }; for _, options in ipairs(ports) do local port, base, ssl, interface = 5280, "pastebin", false, nil; if type(options) == "number" then port = options; elseif type(options) == "table" then port, base, ssl, interface = options.port or 5280, options.path or "pastebin", options.ssl or false, options.interface; elseif type(options) == "string" then base = options; end base_url = base_url or ("http://"..module:get_host()..(port ~= 80 and (":"..port) or "").."/"..base.."/"); httpserver.new{ port = port, base = base, handler = handle_request, ssl = ssl } end
local st = require "util.stanza"; local httpserver = require "net.httpserver"; local uuid_new = require "util.uuid".generate; local os_time = os.time; local t_insert, t_remove = table.insert, table.remove; local add_task = require "util.timer".add_task; local function drop_invalid_utf8(seq) local start = seq:byte(); module:log("utf8: %d, %d", start, #seq); if (start <= 223 and #seq < 2) or (start >= 224 and start <= 239 and #seq < 3) or (start >= 240 and start <= 244 and #seq < 4) or (start > 244) then return ""; end return seq; end local length_threshold = config.get(module.host, "core", "pastebin_threshold") or 500; local line_threshold = config.get(module.host, "core", "pastebin_line_threshold") or 4; local base_url = config.get(module.host, "core", "pastebin_url"); -- Seconds a paste should live for in seconds (config is in hours), default 24 hours local expire_after = math.floor((config.get(module.host, "core", "pastebin_expire_after") or 24) * 3600); local trigger_string = config.get(module.host, "core", "pastebin_trigger"); trigger_string = (trigger_string and trigger_string .. " "); local pastes = {}; local default_headers = { ["Content-Type"] = "text/plain; charset=utf-8" }; local xmlns_xhtmlim = "http://jabber.org/protocol/xhtml-im"; local xmlns_xhtml = "http://www.w3.org/1999/xhtml"; function pastebin_text(text) local uuid = uuid_new(); pastes[uuid] = { body = text, time = os_time(), headers = default_headers }; pastes[#pastes+1] = uuid; if not pastes[2] then -- No other pastes, give the timer a kick add_task(expire_after, expire_pastes); end return base_url..uuid; end function handle_request(method, body, request) local pasteid = request.url.path:match("[^/]+$"); if not pasteid or not pastes[pasteid] then return "Invalid paste id, perhaps it expired?"; end --module:log("debug", "Received request, replying: %s", pastes[pasteid].text); return pastes[pasteid]; end function check_message(data) local origin, stanza = data.origin, data.stanza; local body, bodyindex, htmlindex; for k,v in ipairs(stanza) do if v.name == "body" then body, bodyindex = v, k; elseif v.name == "html" and v.attr.xmlns == xmlns_xhtmlim then htmlindex = k; end end if not body then return; end body = body:get_text(); --module:log("debug", "Body(%s) length: %d", type(body), #(body or "")); if body and ( (#body > length_threshold) or (trigger_string and body:find(trigger_string, 1, true) == 1) or (select(2, body:gsub("\n", "%0")) >= line_threshold) ) then if trigger_string then body = body:gsub("^" .. trigger_string, "", 1); end local url = pastebin_text(body); module:log("debug", "Pasted message as %s", url); --module:log("debug", " stanza[bodyindex] = %q", tostring( stanza[bodyindex])); stanza[bodyindex][1] = url; local html = st.stanza("html", { xmlns = xmlns_xhtmlim }):tag("body", { xmlns = xmlns_xhtml }); html:tag("p"):text(body:sub(1,150):gsub("[\194-\244][\128-\191]*$", drop_invalid_utf8)):up(); html:tag("a", { href = url }):text("[...]"):up(); stanza[htmlindex or #stanza+1] = html; end end module:hook("message/bare", check_message); function expire_pastes(time) time = time or os_time(); -- COMPAT with 0.5 if pastes[1] then pastes[pastes[1]] = nil; t_remove(pastes, 1); if pastes[1] then return (expire_after - (time - pastes[pastes[1]].time)) + 1; end end end local ports = config.get(module.host, "core", "pastebin_ports") or { 5280 }; for _, options in ipairs(ports) do local port, base, ssl, interface = 5280, "pastebin", false, nil; if type(options) == "number" then port = options; elseif type(options) == "table" then port, base, ssl, interface = options.port or 5280, options.path or "pastebin", options.ssl or false, options.interface; elseif type(options) == "string" then base = options; end base_url = base_url or ("http://"..module:get_host()..(port ~= 80 and (":"..port) or "").."/"..base.."/"); httpserver.new{ port = port, base = base, handler = handle_request, ssl = ssl } end
mod_pastebin: Better fix for stripping truncated UFT-8 sequences
mod_pastebin: Better fix for stripping truncated UFT-8 sequences
Lua
mit
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
40d4e8521aa90986812c4b3744ad2ceb4e2623ce
data/pipelines/film_grain.lua
data/pipelines/film_grain.lua
local film_grain_shader = nil function postprocess(env, transparent_phase, ldr_buffer, gbuffer0, gbuffer1, gbuffer_depth, shadowmap) if not enabled then return ldr_buffer end if transparent_phase ~= "post_tonemap" then return ldr_buffer end local res = env.createRenderbuffer(1, 1, true, "rgba8") env.beginBlock("film_grain") if film_grain_shader == nil then film_grain_shader = env.preloadShader("pipelines/film_grain.shd") end env.blending("") env.setRenderTargets(0, res) env.drawArray(0, 4, film_grain_shader, { u_source = ldr_buffer }) env.endBlock() return res end function awake() if _G["postprocesses"] == nil then _G["postprocesses"] = {} end table.insert(_G["postprocesses"], postprocess) end function onDestroy() for i, v in ipairs(_G["postprocesses"]) do if v == postprocess then table.remove(_G["postprocesses"], i) break; end end end
local film_grain_shader = nil function postprocess(env, transparent_phase, ldr_buffer, gbuffer0, gbuffer1, gbuffer_depth, shadowmap) if not enabled then return ldr_buffer end if transparent_phase ~= "post_tonemap" then return ldr_buffer end local res = env.createRenderbuffer(1, 1, true, "rgba8", "film_grain") env.beginBlock("film_grain") if film_grain_shader == nil then film_grain_shader = env.preloadShader("pipelines/film_grain.shd") end env.setRenderTargets(0, res) env.drawArray(0, 4, film_grain_shader, { ldr_buffer }, {}, {}, { depth_test = false, blending = ""} ) env.endBlock() return res end function awake() if _G["postprocesses"] == nil then _G["postprocesses"] = {} end table.insert(_G["postprocesses"], postprocess) end function onDestroy() for i, v in ipairs(_G["postprocesses"]) do if v == postprocess then table.remove(_G["postprocesses"], i) break; end end end
fixed film grain
fixed film grain
Lua
mit
JakubLukas/LumixEngine,JakubLukas/LumixEngine,JakubLukas/LumixEngine
c3ae76873129ba03108dfee433028740cbfd975b
tools/utils/BPE.lua
tools/utils/BPE.lua
local unicode = require 'tools.utils.unicode' local BPE = torch.class('BPE') function BPE:__init(opt) self.split = string.split -- to be able to run the code without torch if not self.split then self.split = function(t, sep) local fields = {} local pattern = string.format("([^%s]+)", sep) t:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end end self.codes = {} local f = assert(io.open(opt.bpe_model, "r")) self.EOT_marker = opt.EOT_marker self.BOT_marker = opt.BOT_marker self.joiner_new = opt.joiner_new self.joiner_annotate = opt.joiner_annotate local t = f:read("*line") local options = self.split(t, ";") if (#options == 3) then self.prefix = options[1] == "true" self.suffix = options[2] == "true" self.case_insensitive = options[3] == "true" t = f:read("*line") else self.prefix = opt.bpe_mode == "prefix" or opt.bpe_mode == "both" self.suffix = opt.bpe_mode == "suffix" or opt.bpe_mode == "both" self.case_insensitive = opt.bpe_case_insensitive end local i = 1 while not(t == nil) do local l = self.split(t, " ") if #l == 2 then self.codes[t] = i i = i + 1 end t=f:read("*line") end end local function getPairs(word) local pairs = {} for i = 1, #word-1, 1 do table.insert(pairs, word[i] .. ' ' .. word[i+1]) end return pairs end local function str2word(l, case_insensitive) local word = {} for v, c in unicode.utf8_iter(l) do if (case_insensitive) then local lu, lc = unicode.getLower(v) if lu then c = lc end end table.insert(word, c) end return word end function BPE:minPair(pairsTable) local mintmp = 100000 local minpair = '' for i = 1, #pairsTable, 1 do local pair_cur = pairsTable[i] if self.codes[pair_cur] then local scoretmp = self.codes[pair_cur] if (scoretmp < mintmp) then mintmp = scoretmp minpair = pair_cur end end end return minpair end function BPE:encode(l) local word = str2word(l, self.case_insensitive) if #word == 1 then word[1] = l return word end if self.prefix then table.insert(word, 1, self.BOT_marker) end if self.suffix then table.insert(word, self.EOT_marker) end local pairs = getPairs(word) while true do local bigram = self:minPair(pairs) if bigram == '' then break end bigram = self.split(bigram, ' ') local new_word = {} local merge = false for _, xx in ipairs(word) do if (merge) then if xx == bigram[2] then table.insert(new_word, bigram[1] .. bigram[2]) merge = false elseif xx == bigram[1] then table.insert(new_word, bigram[1]) else table.insert(new_word, bigram[1]) table.insert(new_word, xx) merge = false end else if bigram[1] == xx then merge = true else table.insert(new_word, xx) end end end if merge then table.insert(new_word, bigram[1]) end word = new_word if #word == 1 then break else pairs = getPairs(word) end end if self.suffix then if word[#word] == self.EOT_marker then table.remove(word, #word) elseif string.sub(word[#word],-string.len(self.EOT_marker)) == self.EOT_marker then word[#word] = string.sub(word[#word], 1, -string.len(self.EOT_marker)-1) end end if self.prefix then if word[1] == self.BOT_marker then table.remove(word, 1) elseif string.sub(word[1], 1, string.len(self.BOT_marker)) == self.BOT_marker then word[1] = string.sub(word[1], string.len(self.BOT_marker)+1) end end if (self.case_insensitive) then local tcword = {} local prev_idx = 1 for i = 1, #word do local curr_idx = prev_idx+unicode.utf8len(word[i]) table.insert(tcword, unicode.utf8substr(l, prev_idx, curr_idx - 1)) prev_idx = curr_idx end word = tcword end return word end function BPE:segment(tokens, separator) local bpeSegment = {} for i=1, #tokens do local token = tokens[i] local left_sep = false local right_sep = false if self.joiner_annotate and not self.joiner_new then if token:sub(1, #separator) == separator then token = token:sub(#separator + 1) left_sep = true end if token:sub(-#separator, -1) == separator then token = token:sub(1, -#separator-1) right_sep = true end end local bpeTokens = self:encode(token) if self.joiner_annotate and not self.joiner_new then if left_sep then bpeTokens[1] = separator .. bpeTokens[1] end if right_sep then bpeTokens[#bpeTokens] = bpeTokens[#bpeTokens] .. separator end end for j=1, #bpeTokens-1 do if self.joiner_annotate then if not self.joiner_new then table.insert(bpeSegment, bpeTokens[j] .. separator) else table.insert(bpeSegment, bpeTokens[j]) table.insert(bpeSegment, separator) end else table.insert(bpeSegment, bpeTokens[j]) end end table.insert(bpeSegment, bpeTokens[#bpeTokens]) end return bpeSegment end return BPE
local unicode = require 'tools.utils.unicode' local BPE = torch.class('BPE') function BPE:__init(opt) self.split = string.split -- to be able to run the code without torch if not self.split then self.split = function(t, sep) local fields = {} local pattern = string.format("([^%s]+)", sep) t:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end end self.codes = {} local f = assert(io.open(opt.bpe_model, "r")) self.EOT_marker = opt.EOT_marker self.BOT_marker = opt.BOT_marker self.joiner_new = opt.joiner_new self.joiner_annotate = opt.joiner_annotate local t = f:read("*line") local options = self.split(t, ";") if (#options == 3 or #options == 4 ) then self.prefix = options[1] == "true" self.suffix = options[2] == "true" self.case_insensitive = options[3] == "true" t = f:read("*line") if #options == 4 then print ("Warning: The 'mode' parameter for tokenization compatibility between train and test has been depreciated, please make sure that the same tokenization parameters are applied while training BPE models and applying them on raw text inputs") end else self.prefix = opt.bpe_mode == "prefix" or opt.bpe_mode == "both" self.suffix = opt.bpe_mode == "suffix" or opt.bpe_mode == "both" self.case_insensitive = opt.bpe_case_insensitive end local i = 1 while not(t == nil) do local l = self.split(t, " ") if #l == 2 then self.codes[t] = i i = i + 1 end t=f:read("*line") end end local function getPairs(word) local pairs = {} for i = 1, #word-1, 1 do table.insert(pairs, word[i] .. ' ' .. word[i+1]) end return pairs end local function str2word(l, case_insensitive) local word = {} for v, c in unicode.utf8_iter(l) do if (case_insensitive) then local lu, lc = unicode.getLower(v) if lu then c = lc end end table.insert(word, c) end return word end function BPE:minPair(pairsTable) local mintmp = 100000 local minpair = '' for i = 1, #pairsTable, 1 do local pair_cur = pairsTable[i] if self.codes[pair_cur] then local scoretmp = self.codes[pair_cur] if (scoretmp < mintmp) then mintmp = scoretmp minpair = pair_cur end end end return minpair end function BPE:encode(l) local word = str2word(l, self.case_insensitive) if #word == 1 then word[1] = l return word end if self.prefix then table.insert(word, 1, self.BOT_marker) end if self.suffix then table.insert(word, self.EOT_marker) end local pairs = getPairs(word) while true do local bigram = self:minPair(pairs) if bigram == '' then break end bigram = self.split(bigram, ' ') local new_word = {} local merge = false for _, xx in ipairs(word) do if (merge) then if xx == bigram[2] then table.insert(new_word, bigram[1] .. bigram[2]) merge = false elseif xx == bigram[1] then table.insert(new_word, bigram[1]) else table.insert(new_word, bigram[1]) table.insert(new_word, xx) merge = false end else if bigram[1] == xx then merge = true else table.insert(new_word, xx) end end end if merge then table.insert(new_word, bigram[1]) end word = new_word if #word == 1 then break else pairs = getPairs(word) end end if self.suffix then if word[#word] == self.EOT_marker then table.remove(word, #word) elseif string.sub(word[#word],-string.len(self.EOT_marker)) == self.EOT_marker then word[#word] = string.sub(word[#word], 1, -string.len(self.EOT_marker)-1) end end if self.prefix then if word[1] == self.BOT_marker then table.remove(word, 1) elseif string.sub(word[1], 1, string.len(self.BOT_marker)) == self.BOT_marker then word[1] = string.sub(word[1], string.len(self.BOT_marker)+1) end end if (self.case_insensitive) then local tcword = {} local prev_idx = 1 for i = 1, #word do local curr_idx = prev_idx+unicode.utf8len(word[i]) table.insert(tcword, unicode.utf8substr(l, prev_idx, curr_idx - 1)) prev_idx = curr_idx end word = tcword end return word end function BPE:segment(tokens, separator) local bpeSegment = {} for i=1, #tokens do local token = tokens[i] local left_sep = false local right_sep = false if self.joiner_annotate and not self.joiner_new then if token:sub(1, #separator) == separator then token = token:sub(#separator + 1) left_sep = true end if token:sub(-#separator, -1) == separator then token = token:sub(1, -#separator-1) right_sep = true end end local bpeTokens = self:encode(token) if self.joiner_annotate and not self.joiner_new then if left_sep then bpeTokens[1] = separator .. bpeTokens[1] end if right_sep then bpeTokens[#bpeTokens] = bpeTokens[#bpeTokens] .. separator end end for j=1, #bpeTokens-1 do if self.joiner_annotate then if not self.joiner_new then table.insert(bpeSegment, bpeTokens[j] .. separator) else table.insert(bpeSegment, bpeTokens[j]) table.insert(bpeSegment, separator) end else table.insert(bpeSegment, bpeTokens[j]) end end table.insert(bpeSegment, bpeTokens[#bpeTokens]) end return bpeSegment end return BPE
Fix back compatibility for previous BPE models' option handling
Fix back compatibility for previous BPE models' option handling
Lua
mit
jsenellart-systran/OpenNMT,jsenellart/OpenNMT,OpenNMT/OpenNMT,da03/OpenNMT,jsenellart/OpenNMT,jungikim/OpenNMT,jungikim/OpenNMT,jungikim/OpenNMT,jsenellart/OpenNMT,jsenellart-systran/OpenNMT,OpenNMT/OpenNMT,da03/OpenNMT,da03/OpenNMT,jsenellart-systran/OpenNMT,OpenNMT/OpenNMT
1f53eddfa76a21ceea23483c01fe4c036e96f4ee
home/config/nvim/lua/plugins/vim-grepper.lua
home/config/nvim/lua/plugins/vim-grepper.lua
local wk = require('which-key') vim.g.grepper = { tools = {'rg', 'git'}, rg = { grepprg = 'rg -H --no-heading --vimgrep --hidden' }, } wk.register( { g = { '<Cmd>Grepper<Cr>', 'Grepper' }, G = { '<Cmd>Grepper -buffers<Cr>', 'Grepper Buffers' }, gs = { '<Plug>(GrepperOperator)', 'Grepper Operator' }, ['*'] = { '<Cmd>Grepper -cword -noprompt<Cr>', 'Grepper Word Under Cursor' }, }, { prefix = '<Leader>', } ) wk.register( { gs = { '<Plug>(GrepperOperator)', 'Grepper Operator' }, }, { mode = 'x', } )
local wk = require('which-key') vim.g.grepper = { tools = {'rg', 'git'}, rg = { grepprg = 'rg -H --no-heading --vimgrep --hidden' }, } wk.register( { g = { '<Cmd>Grepper<Cr>', 'Grepper' }, G = { '<Cmd>Grepper -buffers<Cr>', 'Grepper Buffers' }, ['*'] = { '<Cmd>Grepper -cword -noprompt<Cr>', 'Grepper Word Under Cursor' }, }, { prefix = '<Leader>', } ) wk.register( { gs = { '<Plug>(GrepperOperator)', 'Grepper Operator' }, }, { mode = 'n', } ) wk.register( { gs = { '<Plug>(GrepperOperator)', 'Grepper Operator' }, }, { mode = 'x', } )
nvim(grepper): move GrepperOperator outside of <Leader> prefix
nvim(grepper): move GrepperOperator outside of <Leader> prefix
Lua
unlicense
knpwrs/dotfiles,KenPowers/dotfiles
fb3bd3e06a903c1868b39e1abebc8a666a8f2f4a
lib/luvit/dgram.lua
lib/luvit/dgram.lua
--[[ Copyright 2012 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] -- Ported from node's dgram.js. local dns = require('dns') local net = require('net') local Udp = require('uv').Udp local Emitter = require('core').Emitter local dgram = {} local function lookup(address, family, callback) local matchedFamily = net.isIP(address) if matchedFamily then return callback(nil, address, matchedFamily) end return dns.lookup(address, family, callback) end local function lookup4(address, callback) return lookup(address or '0.0.0.0', 4, callback) end local function lookup6(address, callback) return lookup(address or '::0', 6, callback) end local function newHandle(family) if family == 'udp4' then local handle = Udp:new() handle.lookup = lookup4 handle.bind = handle.bind handle.send = handle.send return handle end if family == 'udp6' then local handle = Udp:new() handle.lookup = lookup6 handle.bind = handle.bind6 handle.send = handle.send6 return handle end error('Bad socket type specified. Valid types are: udp4, udp6') end --[[ Socket ]]-- local Socket = Emitter:extend() dgram.Socket = Socket function Socket:initialize(family, listener) self._handle = newHandle(family) self._receiving = false self._bound = false self._family = family self:_initEmitters() if type(listener) == 'function' then self:on('message', listener) end end function Socket:_initEmitters() self._handle:on('close', function(msg, rinfo) self._handle = nil self:emit('close') end) self._handle:on('message', function(msg, rinfo) self:emit('message', msg, rinfo) end) self._handle:on('error', function(err) self:emit('error', err) end) end function dgram.createSocket(family, listener) return Socket:new(family, listener) end function Socket:bind(port, address) self:_healthCheck() self._handle.lookup(address, function(err, ip) if err then process.nextTick(function() self:emit('error', err) end) return end self._handle:bind(ip, port or 0) self._bound = true self:_startReceiving() self:emit('listening') end) end function Socket:send(msg, port, address, callback) self:_healthCheck() self:_startReceiving() self._handle.lookup(address, function(err, ip) if err then if callback then callback(err) end self:emit('error', err) return end self._handle:send(msg, port, address, callback) end) end function Socket:close() self:_healthCheck() self:_stopReceiving() self._handle:close() end function Socket:address() self:_healthCheck() return self._handle:getsockname() end function Socket:setBroadcast(opt) self._handle:setBroadcast(opt and 1 or 0) end function Socket:setTTL(opt) self._handle:setTTL(opt) end function Socket:setMulticastTTL(opt) self._handle:setMulticastTTL(opt) end function Socket:setMulticastLoopback(opt) self._handle:setMulticastLoopback(opt and 1 or 0) end function Socket:setMembership(multicastAddress, multicastInterface, op) self:_healthCheck() if not multicastAddress then error("multicast address must be specified") end if not multicastInterface then if self._family == 'udp4' then multicastInterface = '0.0.0.0' elseif self._family == 'udp6' then multicastInterface = '::0' end end self._handle:setMembership(multicastAddress, multicastInterface, op) end function Socket:addMembership(multicastAddress, interfaceAddress) self:setMembership(multicastAddress, interfaceAddress, 'join') end function Socket:dropMembership(multicastAddress, interfaceAddress) self:setMembership(multicastAddress, interfaceAddress, 'leave') end function Socket:_healthCheck() if not self._handle then error('self._handle uninitialized') end end function Socket:_startReceiving() if self._receiving then return end if not self._bound then self:bind() if not self._bound then error('implicit bind failed') end end self._handle:recvStart() self._receiving = true end function Socket:_stopReceiving() if not self._receiving then return end self._handle:recvStop() self._receiving = false end return dgram
--[[ Copyright 2012 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] -- Ported from node's dgram.js. local dns = require('dns') local net = require('net') local Udp = require('uv').Udp local Emitter = require('core').Emitter local dgram = {} local function lookup(address, family, callback) local matchedFamily = net.isIP(address) if matchedFamily == 4 or matchedFamily == 6 then return callback(nil, address, matchedFamily) end return dns.lookup(address, family, function(...) callback(...) end) end local function lookup4(address, callback) return lookup(address or '0.0.0.0', 4, callback) end local function lookup6(address, callback) return lookup(address or '::0', 6, callback) end local function newHandle(family) if family == 'udp4' then local handle = Udp:new() handle.lookup = lookup4 handle.bind = handle.bind handle.send = handle.send return handle end if family == 'udp6' then local handle = Udp:new() handle.lookup = lookup6 handle.bind = handle.bind6 handle.send = handle.send6 return handle end error('Bad socket type specified. Valid types are: udp4, udp6') end --[[ Socket ]]-- local Socket = Emitter:extend() dgram.Socket = Socket function Socket:initialize(family, listener) self._handle = newHandle(family) self._receiving = false self._bound = false self._family = family self:_initEmitters() if type(listener) == 'function' then self:on('message', listener) end end function Socket:_initEmitters() self._handle:on('close', function(msg, rinfo) self._handle = nil self:emit('close') end) self._handle:on('message', function(msg, rinfo) self:emit('message', msg, rinfo) end) self._handle:on('error', function(err) self:emit('error', err) end) end function dgram.createSocket(family, listener) return Socket:new(family, listener) end function Socket:bind(port, address) self:_healthCheck() self._handle.lookup(address, function(err, ip) if err then process.nextTick(function() self:emit('error', err) end) return end self._handle:bind(ip, port or 0) self._bound = true self:_startReceiving() self:emit('listening') end) end function Socket:send(msg, port, address, callback) self:_healthCheck() self:_startReceiving() self._handle.lookup(address, function(err, ip) if err then if callback then callback(err) end self:emit('error', err) return end self._handle:send(msg, port, ip, callback) end) end function Socket:close() self:_healthCheck() self:_stopReceiving() self._handle:close() end function Socket:address() self:_healthCheck() return self._handle:getsockname() end function Socket:setBroadcast(opt) self._handle:setBroadcast(opt and 1 or 0) end function Socket:setTTL(opt) self._handle:setTTL(opt) end function Socket:setMulticastTTL(opt) self._handle:setMulticastTTL(opt) end function Socket:setMulticastLoopback(opt) self._handle:setMulticastLoopback(opt and 1 or 0) end function Socket:setMembership(multicastAddress, multicastInterface, op) self:_healthCheck() if not multicastAddress then error("multicast address must be specified") end if not multicastInterface then if self._family == 'udp4' then multicastInterface = '0.0.0.0' elseif self._family == 'udp6' then multicastInterface = '::0' end end self._handle:setMembership(multicastAddress, multicastInterface, op) end function Socket:addMembership(multicastAddress, interfaceAddress) self:setMembership(multicastAddress, interfaceAddress, 'join') end function Socket:dropMembership(multicastAddress, interfaceAddress) self:setMembership(multicastAddress, interfaceAddress, 'leave') end function Socket:_healthCheck() if not self._handle then error('self._handle uninitialized') end end function Socket:_startReceiving() if self._receiving then return end if not self._bound then self:bind() if not self._bound then error('implicit bind failed') end end self._handle:recvStart() self._receiving = true end function Socket:_stopReceiving() if not self._receiving then return end self._handle:recvStop() self._receiving = false end return dgram
fixes for dns lookup for udp
fixes for dns lookup for udp
Lua
apache-2.0
sousoux/luvit,sousoux/luvit,sousoux/luvit,sousoux/luvit,sousoux/luvit,sousoux/luvit
ad01e62c65eb15b2b4e3c63133ecbaaf5e0dbc10
mod_mam/rsm.lib.lua
mod_mam/rsm.lib.lua
local stanza = require"util.stanza".stanza; local tostring, tonumber = tostring, tonumber; local type = type; local pairs = pairs; local xmlns_rsm = 'http://jabber.org/protocol/rsm'; local element_parsers; do local function xs_int(st) return tonumber((st:get_text())); end local function xs_string(st) return st:get_text(); end element_parsers = { after = xs_string; before = function(st) return st:get_text() or true; end; max = xs_int; index = xs_int; first = function(st) return { index = tonumber(st.attr.index); st:get_text() }; end; last = xs_string; count = xs_int; } end local element_generators = setmetatable({ first = function(st, data) if type(data) == "table" then st:tag("first", { index = data.index }):text(data[1]):up(); else st:tag("first"):text(tostring(data)):up(); end end; before = function(st, data) if data == true then st:tag("before"):up(); else st:tag("before"):text(tostring(data)):up(); end end }, { __index = function(_, name) return function(st, data) st:tag(name):text(tostring(data)):up(); end end; }); local function parse(stanza) local rs = {}; for tag in stanza:childtags() do local name = tag.name; local parser = name and element_parsers[name]; if parser then rs[name] = parser(tag); end end return rs; end local function generate(t) local st = stanza("set", { xmlns = xmlns_rsm }); for k,v in pairs(t) do if element_parsers[k] then element_generators[k](st, v); end end return st; end local function get(st) local set = st:get_child("set", xmlns_rsm); if set and #set.tags > 0 then return parse(set); end end return { parse = parse, generate = generate, get = get };
local stanza = require"util.stanza".stanza; local tostring, tonumber = tostring, tonumber; local type = type; local pairs = pairs; local xmlns_rsm = 'http://jabber.org/protocol/rsm'; local element_parsers; do local function xs_int(st) return tonumber((st:get_text())); end local function xs_string(st) return st:get_text(); end element_parsers = { after = xs_string; before = function(st) local text = st:get_text(); return text == "" or text; end; max = xs_int; index = xs_int; first = function(st) return { index = tonumber(st.attr.index); st:get_text() }; end; last = xs_string; count = xs_int; } end local element_generators = setmetatable({ first = function(st, data) if type(data) == "table" then st:tag("first", { index = data.index }):text(data[1]):up(); else st:tag("first"):text(tostring(data)):up(); end end; before = function(st, data) if data == true then st:tag("before"):up(); else st:tag("before"):text(tostring(data)):up(); end end }, { __index = function(_, name) return function(st, data) st:tag(name):text(tostring(data)):up(); end end; }); local function parse(stanza) local rs = {}; for tag in stanza:childtags() do local name = tag.name; local parser = name and element_parsers[name]; if parser then rs[name] = parser(tag); end end return rs; end local function generate(t) local st = stanza("set", { xmlns = xmlns_rsm }); for k,v in pairs(t) do if element_parsers[k] then element_generators[k](st, v); end end return st; end local function get(st) local set = st:get_child("set", xmlns_rsm); if set and #set.tags > 0 then return parse(set); end end return { parse = parse, generate = generate, get = get };
mod_mam/rsm.lib: Fix parsing of empty before tag
mod_mam/rsm.lib: Fix parsing of empty before tag
Lua
mit
apung/prosody-modules,brahmi2/prosody-modules,prosody-modules/import,mardraze/prosody-modules,syntafin/prosody-modules,guilhem/prosody-modules,softer/prosody-modules,Craige/prosody-modules,syntafin/prosody-modules,dhotson/prosody-modules,jkprg/prosody-modules,mardraze/prosody-modules,iamliqiang/prosody-modules,guilhem/prosody-modules,heysion/prosody-modules,dhotson/prosody-modules,drdownload/prosody-modules,dhotson/prosody-modules,guilhem/prosody-modules,NSAKEY/prosody-modules,asdofindia/prosody-modules,vfedoroff/prosody-modules,amenophis1er/prosody-modules,1st8/prosody-modules,softer/prosody-modules,LanceJenkinZA/prosody-modules,crunchuser/prosody-modules,cryptotoad/prosody-modules,1st8/prosody-modules,stephen322/prosody-modules,mmusial/prosody-modules,apung/prosody-modules,prosody-modules/import,mardraze/prosody-modules,syntafin/prosody-modules,jkprg/prosody-modules,NSAKEY/prosody-modules,mmusial/prosody-modules,obelisk21/prosody-modules,brahmi2/prosody-modules,heysion/prosody-modules,either1/prosody-modules,joewalker/prosody-modules,dhotson/prosody-modules,vfedoroff/prosody-modules,olax/prosody-modules,heysion/prosody-modules,BurmistrovJ/prosody-modules,stephen322/prosody-modules,obelisk21/prosody-modules,1st8/prosody-modules,joewalker/prosody-modules,olax/prosody-modules,drdownload/prosody-modules,cryptotoad/prosody-modules,cryptotoad/prosody-modules,softer/prosody-modules,mmusial/prosody-modules,LanceJenkinZA/prosody-modules,olax/prosody-modules,softer/prosody-modules,joewalker/prosody-modules,vince06fr/prosody-modules,vince06fr/prosody-modules,dhotson/prosody-modules,stephen322/prosody-modules,stephen322/prosody-modules,stephen322/prosody-modules,mmusial/prosody-modules,prosody-modules/import,brahmi2/prosody-modules,amenophis1er/prosody-modules,olax/prosody-modules,mardraze/prosody-modules,asdofindia/prosody-modules,mmusial/prosody-modules,BurmistrovJ/prosody-modules,asdofindia/prosody-modules,iamliqiang/prosody-modules,LanceJenkinZA/prosody-modules,either1/prosody-modules,brahmi2/prosody-modules,iamliqiang/prosody-modules,amenophis1er/prosody-modules,drdownload/prosody-modules,softer/prosody-modules,BurmistrovJ/prosody-modules,drdownload/prosody-modules,asdofindia/prosody-modules,prosody-modules/import,obelisk21/prosody-modules,NSAKEY/prosody-modules,obelisk21/prosody-modules,either1/prosody-modules,either1/prosody-modules,guilhem/prosody-modules,jkprg/prosody-modules,NSAKEY/prosody-modules,heysion/prosody-modules,iamliqiang/prosody-modules,LanceJenkinZA/prosody-modules,prosody-modules/import,crunchuser/prosody-modules,Craige/prosody-modules,crunchuser/prosody-modules,jkprg/prosody-modules,vfedoroff/prosody-modules,brahmi2/prosody-modules,amenophis1er/prosody-modules,apung/prosody-modules,LanceJenkinZA/prosody-modules,olax/prosody-modules,joewalker/prosody-modules,BurmistrovJ/prosody-modules,joewalker/prosody-modules,obelisk21/prosody-modules,syntafin/prosody-modules,syntafin/prosody-modules,amenophis1er/prosody-modules,heysion/prosody-modules,1st8/prosody-modules,cryptotoad/prosody-modules,BurmistrovJ/prosody-modules,Craige/prosody-modules,vince06fr/prosody-modules,vince06fr/prosody-modules,jkprg/prosody-modules,vfedoroff/prosody-modules,either1/prosody-modules,guilhem/prosody-modules,mardraze/prosody-modules,crunchuser/prosody-modules,Craige/prosody-modules,asdofindia/prosody-modules,1st8/prosody-modules,vince06fr/prosody-modules,apung/prosody-modules,drdownload/prosody-modules,crunchuser/prosody-modules,apung/prosody-modules,Craige/prosody-modules,iamliqiang/prosody-modules,NSAKEY/prosody-modules,cryptotoad/prosody-modules,vfedoroff/prosody-modules
f985780b6dfa90639a6cdb0daaf29aef4401bde8
Identity.lua
Identity.lua
local Identity, parent = torch.class('nn.Identity', 'nn.Module') function Identity:__init() parent.__init(self) self.tensorOutput = torch.Tensor{} self.output = self.tensorOutput self.tensorGradInput = torch.Tensor{} self.gradInput = self.tensorGradInput end function Identity:updateOutput(input) if torch.isTensor(input) then self.tensorOutput:set(input) self.output = self.tensorOutput else self.output = input end return self.output end function Identity:updateGradInput(input, gradOutput) if torch.isTensor(gradOutput) then self.tensorGradInput:set(gradOutput) self.gradInput = self.tensorGradInput else self.gradInput = gradOutput end return self.gradInput end
local Identity, parent = torch.class('nn.Identity', 'nn.Module') function Identity:__init() parent.__init(self) self.tensorOutput = torch.Tensor{} self.output = self.tensorOutput self.tensorGradInput = torch.Tensor{} self.gradInput = self.tensorGradInput end local function backCompatibility(self, input) if self.tensorOutput == nil then self.tensorOutput = input.new{} self.output = self.tensorOutput self.tensorGradInput = torch.Tensor{} self.gradInput = self.tensorGradInput end end function Identity:updateOutput(input) backCompatibility(self, input) if torch.isTensor(input) then self.tensorOutput:set(input) self.output = self.tensorOutput else self.output = input end return self.output end function Identity:updateGradInput(input, gradOutput) if torch.isTensor(gradOutput) then self.tensorGradInput:set(gradOutput) self.gradInput = self.tensorGradInput else self.gradInput = gradOutput end return self.gradInput end
fix backcompat for nn.Identity
fix backcompat for nn.Identity
Lua
bsd-3-clause
eriche2016/nn,PraveerSINGH/nn,jonathantompson/nn,joeyhng/nn,jhjin/nn,nicholas-leonard/nn,Moodstocks/nn,caldweln/nn,diz-vara/nn,kmul00/nn,lukasc-ch/nn,colesbury/nn,apaszke/nn,sagarwaghmare69/nn,xianjiec/nn,elbamos/nn,andreaskoepf/nn,witgo/nn
d87b8433b7828ff0155fc34f5722028f48c904fe
examples/stream/libs/file.lua
examples/stream/libs/file.lua
-- This is a partial port of the built-in fs module as continuable format local native = require('uv') local iStream = require('stream').iStream local fs = {} fs.umask = "0644" local function noop() end function fs.open(path, flag, mode) if type(path) ~= "string" then error("open(path, flag, [mode]): path must be a string") end if type(flag) ~= "string" then error("open(path, flag, [mode]): flag must be a string") end if not mode then mode = fs.umask end if type(mode) ~= "string" then error("open(path, flag, [mode]): mode must be a string") end return function (callback) return native.fs_open(path, flag, mode, callback or noop) end end function fs.read(fd, offset, length) if type(fd) ~= "number" then error("read(fd, offset, length): fd must be a number") end if type(offset) ~= "number" then error("read(fd, offset, length): offset must be a number") end if type(length) ~= "number" then error("read(fd, offset, length): length must be a number") end return function (callback) return native.fs_read(fd, offset, length, callback or noop) end end function fs.write(fd, offset, chunk) if type(fd) ~= "number" then error("write(fd, offset, chunk): fd must be a number") end if type(offset) ~= "number" then error("write(fd, offset, chunk): offset must be a number") end if type(chunk) ~= "string" then error("write(fd, offset, chunk): chunk must be a string") end return function (callback) return native.fs_write(fd, offset, chunk, callback or noop) end end function fs.close(fd) if type(fd) ~= "number" then error("close(fd): fd must be a number") end return function (callback) return native.fs_close(fd, callback or noop) end end local ReadStream = iStream:extend() fs.ReadStream = ReadStream function ReadStream:initialize(fd) self.fd = fd self.offset = 0 self.chunkSize = 10 end function ReadStream:read() return function (callback) fs.read(self.fd, self.offset, self.chunkSize)(function (err, chunk) if err then return callback(err) end local bytesRead = #chunk if bytesRead == 0 then return callback() end self.offset = self.offset + bytesRead callback(nil, chunk) end) end end local WriteStream = iStream:extend() fs.WriteStream = WriteStream function WriteStream:initialize(fd) self.fd = fd self.offset = 0 end function WriteStream:write(chunk) return function (callback) if not chunk then return callback() end fs.write(self.fd, self.offset, chunk)(function (err, bytesWritten) if err then return callback(err) end self.offset = self.offset + bytesWritten callback() end) end end return fs
-- This is a partial port of the built-in fs module as continuable format local native = require('uv') local Emitter = require('core').Emitter local iStream = Emitter:extend() local fs = {} fs.umask = "0644" local function noop() end function fs.open(path, flag, mode) if type(path) ~= "string" then error("open(path, flag, [mode]): path must be a string") end if type(flag) ~= "string" then error("open(path, flag, [mode]): flag must be a string") end if not mode then mode = fs.umask end if type(mode) ~= "string" then error("open(path, flag, [mode]): mode must be a string") end return function (callback) return native.fs_open(path, flag, mode, callback or noop) end end function fs.read(fd, offset, length) if type(fd) ~= "number" then error("read(fd, offset, length): fd must be a number") end if type(offset) ~= "number" then error("read(fd, offset, length): offset must be a number") end if type(length) ~= "number" then error("read(fd, offset, length): length must be a number") end return function (callback) return native.fs_read(fd, offset, length, callback or noop) end end function fs.write(fd, offset, chunk) if type(fd) ~= "number" then error("write(fd, offset, chunk): fd must be a number") end if type(offset) ~= "number" then error("write(fd, offset, chunk): offset must be a number") end if type(chunk) ~= "string" then error("write(fd, offset, chunk): chunk must be a string") end return function (callback) return native.fs_write(fd, offset, chunk, callback or noop) end end function fs.close(fd) if type(fd) ~= "number" then error("close(fd): fd must be a number") end return function (callback) return native.fs_close(fd, callback or noop) end end local ReadStream = iStream:extend() fs.ReadStream = ReadStream function ReadStream:initialize(fd) self.fd = fd self.offset = 0 self.chunkSize = 10 end function ReadStream:read() return function (callback) fs.read(self.fd, self.offset, self.chunkSize)(function (err, chunk) if err then return callback(err) end local bytesRead = #chunk if bytesRead == 0 then return callback() end self.offset = self.offset + bytesRead callback(nil, chunk) end) end end local WriteStream = iStream:extend() fs.WriteStream = WriteStream function WriteStream:initialize(fd) self.fd = fd self.offset = 0 end function WriteStream:write(chunk) return function (callback) if not chunk then return callback() end fs.write(self.fd, self.offset, chunk)(function (err, bytesWritten) if err then return callback(err) end self.offset = self.offset + bytesWritten callback() end) end end return fs
Unbreak stream example
Unbreak stream example Fixes: ``` luvit test.lua Uncaught exception: /root/stream/libs/file.lua:67: attempt to index local 'iStream' (a nil value) ```
Lua
apache-2.0
zhaozg/luvit,luvit/luvit,zhaozg/luvit,luvit/luvit
ac77729254c01f0840f04188bf0c31816d5aafcd
interface/configenv/dynvars.lua
interface/configenv/dynvars.lua
local dynvar = {} local _mt_dynvar = { __index = dynvar } local function _new_dynvar(pkt, var, func) local self = { pkt = pkt, var = var, func = func } self.value = func() -- NOTE arp will execute in master return setmetatable(self, _mt_dynvar) end function dynvar:update() local v = self.func() self.value = v return v end -- TODO improve apply function dynvar:apply(pkt) local var = pkt[self.pkt][self.var] if type(var) == "cdata" then var:set(self.value) else pkt[self.pkt][self.var] = self.value end end function dynvar:updateApply(pkt) dynvar.update(self) local var = pkt[self.pkt][self.var] if type(var) == "cdata" then var:set(self.value) else pkt[self.pkt][self.var] = self.value end end local dynvars, dv_final = {}, {} local _mt_dynvars = { __index = dynvars } local _mt_dv_final = { __index = dv_final } function dynvars.new() local self = { index = {}, count = 0 } return setmetatable(self, _mt_dynvars) end local function _add_dv(self, index, dv) table.insert(self, dv) self.index[index] = dv self.count = self.count + 1 end function dynvars:add(pkt, var, func) local dv = _new_dynvar(pkt, var, func) _add_dv(self, pkt .. "_" .. var, dv) return dv end function dynvars:inherit(other) for i,v in pairs(other.index) do if not self.index[i] then _add_dv(self, i, v) end end end function dynvars:finalize() setmetatable(self, _mt_dv_final) end function dv_final:updateAll() for i = 1, self.count do dynvar.update(self[i]) end end function dv_final:applyAll(pkt) for i = 1, self.count do dynvar.apply(self[i], pkt) end end function dv_final:updateApplyAll(pkt) for i = 1, self.count do dynvar.updateApply(self[i], pkt) end end return dynvars
local proto = require "proto.proto" local dynvar = {} local _mt_dynvar = { __index = dynvar } local _aliases = { udp_src = "setSrcPort", udp_dst = "setDstPort", tcp_src = "setSrcPort", tcp_dst = "setDstPort", } local function _find_setter(pkt, var) local alias = _aliases[pkt .. "_" .. var] if alias then return proto[pkt].metatype[alias] end return proto[pkt].metatype["set" .. string.upper(string.sub(var, 1, 1)) .. string.sub(var, 2)] end local function _new_dynvar(pkt, var, func) local self = { pkt = pkt, var = var, func = func } self.applyfn = _find_setter(pkt, var) assert(self.applyfn, pkt .. "_" .. var) self.value = func() -- NOTE arp will execute in master return setmetatable(self, _mt_dynvar) end function dynvar:update() local v = self.func() self.value = v return v end function dynvar:apply(pkt) self.applyfn(pkt[self.pkt], self.value) end function dynvar:updateApply(pkt) dynvar.update(self) self.applyfn(pkt[self.pkt], self.value) end local dynvars, dv_final = {}, {} local _mt_dynvars = { __index = dynvars } local _mt_dv_final = { __index = dv_final } function dynvars.new() local self = { index = {}, count = 0 } return setmetatable(self, _mt_dynvars) end local function _add_dv(self, index, dv) table.insert(self, dv) self.index[index] = dv self.count = self.count + 1 end function dynvars:add(pkt, var, func) local dv = _new_dynvar(pkt, var, func) _add_dv(self, pkt .. "_" .. var, dv) return dv end function dynvars:inherit(other) for i,v in pairs(other.index) do if not self.index[i] then _add_dv(self, i, v) end end end function dynvars:finalize() setmetatable(self, _mt_dv_final) end function dv_final:updateAll() for i = 1, self.count do dynvar.update(self[i]) end end function dv_final:applyAll(pkt) for i = 1, self.count do dynvar.apply(self[i], pkt) end end function dv_final:updateApplyAll(pkt) for i = 1, self.count do dynvar.updateApply(self[i], pkt) end end return dynvars
Fix apply function.
Fix apply function.
Lua
mit
emmericp/MoonGen,dschoeffm/MoonGen,gallenmu/MoonGen,emmericp/MoonGen,gallenmu/MoonGen,scholzd/MoonGen,scholzd/MoonGen,gallenmu/MoonGen,dschoeffm/MoonGen,gallenmu/MoonGen,dschoeffm/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,emmericp/MoonGen,scholzd/MoonGen
1b7b815e585c4d4f7fda9ea34ad85a16532f2b2f
nyagos.d/suffix.lua
nyagos.d/suffix.lua
if not nyagos then print("This is a script for nyagos not lua.exe") os.exit() end share._suffixes={} share._setsuffix = function(suffix,cmdline) suffix=string.gsub(string.lower(suffix),"^%.","") share._suffixes[suffix]=cmdline end suffix = setmetatable({},{ __call = function(t,k,v) share._setsuffix(k,v) return end, __newindex = function(t,k,v) share._setsuffix(k,v) return end, __index = function(t,k) return share._suffixes[k] end }) share._org_suffix_argsfilter=nyagos.argsfilter nyagos.argsfilter = function(args) if share._org_suffix_argsfilter then local args_ = share._org_suffix_argsfilter(args) if args_ then args = args_ end end local m = string.match(args[0],"%.(%w+)$") if not m then return end local cmdline = share._suffixes[ string.lower(m) ] if not cmdline then return end local path=nyagos.which(args[0]) if not path then return end local newargs={} if type(cmdline) == 'table' then for i=1,#cmdline do newargs[i-1]=cmdline[i] end elseif type(cmdline) == 'string' then newargs[0] = cmdline end newargs[#newargs+1] = path for i=1,#args do newargs[#newargs+1] = args[i] end return newargs end nyagos.alias.suffix = function(args) if #args < 1 then for key,val in pairs(share._suffixes) do local right=val if type(val) == "table" then right = table.concat(val," ") end print(key .. "=" .. right) end return end for i=1,#args do local left,right=string.match(args[i],"^%.?([^=]+)%=(.+)$") if right then local args={} for m in string.gmatch(right,"%S+") do args[#args+1] = m end share._setsuffix(left,args) else local val = share._suffixes[args[i]] if not val then val = "" elseif type(val) == "table" then val = table.concat(val," ") end print(args[i].."="..val) end end end for key,val in pairs{ awk={"gawk","-f"}, js={"cscript","//nologo"}, lua={"nyagos.exe","--norc","--lua-file"}, pl={"perl"}, ps1={"powershell","-ExecutionPolicy","RemoteSigned","-file"}, rb={"ruby"}, vbs={"cscript","//nologo"}, wsf={"cscript","//nologo"}, py={"python"}, } do share._setsuffix( key , val ) end
if not nyagos then print("This is a script for nyagos not lua.exe") os.exit() end share._suffixes={} local function member(list,m) if not list then return false end return string.find(";"..list..";",";"..m..";",1,true) end share._setsuffix = function(suffix,cmdline) suffix=string.gsub(string.lower(suffix),"^%.","") if not share._suffixes[suffix] then local newext="."..suffix if not member(nyagos.env.PATHEXT,newext) then local orgpathext = nyagos.env.NYAGOSPATHEXT if orgpathext then if not member(orgpathext,newext) then nyagos.env.NYAGOSPATHEXT = orgpathext..";"..newext end else nyagos.env.NYAGOSPATHEXT = newext end end end share._suffixes[suffix]=cmdline end suffix = setmetatable({},{ __call = function(t,k,v) share._setsuffix(k,v) return end, __newindex = function(t,k,v) share._setsuffix(k,v) return end, __index = function(t,k) return share._suffixes[k] end }) share._org_suffix_argsfilter=nyagos.argsfilter nyagos.argsfilter = function(args) if share._org_suffix_argsfilter then local args_ = share._org_suffix_argsfilter(args) if args_ then args = args_ end end local m = string.match(args[0],"%.(%w+)$") if not m then return end local cmdline = share._suffixes[ string.lower(m) ] if not cmdline then return end local path=nyagos.which(args[0]) if not path then return end local newargs={} if type(cmdline) == 'table' then for i=1,#cmdline do newargs[i-1]=cmdline[i] end elseif type(cmdline) == 'string' then newargs[0] = cmdline end newargs[#newargs+1] = path for i=1,#args do newargs[#newargs+1] = args[i] end return newargs end nyagos.alias.suffix = function(args) if #args < 1 then for key,val in pairs(share._suffixes) do local right=val if type(val) == "table" then right = table.concat(val," ") end print(key .. "=" .. right) end return end for i=1,#args do local left,right=string.match(args[i],"^%.?([^=]+)%=(.+)$") if right then local args={} for m in string.gmatch(right,"%S+") do args[#args+1] = m end share._setsuffix(left,args) else local val = share._suffixes[args[i]] if not val then val = "" elseif type(val) == "table" then val = table.concat(val," ") end print(args[i].."="..val) end end end for key,val in pairs{ awk={"gawk","-f"}, js={"cscript","//nologo"}, lua={"nyagos.exe","--norc","--lua-file"}, pl={"perl"}, ps1={"powershell","-ExecutionPolicy","RemoteSigned","-file"}, rb={"ruby"}, vbs={"cscript","//nologo"}, wsf={"cscript","//nologo"}, py={"python"}, } do share._setsuffix( key , val ) end
(#425) suffix.lua appends suffixes to %NYAGOSPATHEXT%
(#425) suffix.lua appends suffixes to %NYAGOSPATHEXT%
Lua
bsd-3-clause
tsuyoshicho/nyagos
9b9a205977c5ca70574a6df397be80229fd127b6
agents/monitoring/tests/fixtures/protocol/server.lua
agents/monitoring/tests/fixtures/protocol/server.lua
local net = require('net') local JSON = require('json') local fixtures = require('./') local LineEmitter = require('line-emitter').LineEmitter local tls = require('tls') local timer = require('timer') local lineEmitter = LineEmitter:new() local port = 50041 local send_schedule_changed_initial = 2000 local send_schedule_changed_interval = 60000 local keyPem = [[ -----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQDx3wdzpq2rvwm3Ucun1qAD/ClB+wW+RhR1nVix286QvaNqePAd CAwwLL82NqXcVQRbQ4s95splQnwvjgkFdKVXFTjPKKJI5aV3wSRN61EBVPdYpCre 535yfG/uDysZFCnVQdnCZ1tnXAR8BirxCNjHqbVyIyBGjsNoNCEPb2R35QIDAQAB AoGBAJNem9C4ftrFNGtQ2DB0Udz7uDuucepkErUy4MbFsc947GfENjDKJXr42Kx0 kYx09ImS1vUpeKpH3xiuhwqe7tm4FsCBg4TYqQle14oxxm7TNeBwwGC3OB7hiokb aAjbPZ1hAuNs6ms3Ybvvj6Lmxzx42m8O5DXCG2/f+KMvaNUhAkEA/ekrOsWkNoW9 2n3m+msdVuxeek4B87EoTOtzCXb1dybIZUVv4J48VAiM43hhZHWZck2boD/hhwjC M5NWd4oY6QJBAPPcgBVNdNZSZ8hR4ogI4nzwWrQhl9MRbqqtfOn2TK/tjMv10ALg lPmn3SaPSNRPKD2hoLbFuHFERlcS79pbCZ0CQQChX3PuIna/gDitiJ8oQLOg7xEM wk9TRiDK4kl2lnhjhe6PDpaQN4E4F0cTuwqLAoLHtrNWIcOAQvzKMrYdu1MhAkBm Et3qDMnjDAs05lGT72QeN90/mPAcASf5eTTYGahv21cb6IBxM+AnwAPpqAAsHhYR 9h13Y7uYbaOjvuF23LRhAkBoI9eaSMn+l81WXOVUHnzh3ZwB4GuTyxMXXNOhuiFd 0z4LKAMh99Z4xQmqSoEkXsfM4KPpfhYjF/bwIcP5gOei -----END RSA PRIVATE KEY----- ]] local certPem = [[ -----BEGIN CERTIFICATE----- MIIDXDCCAsWgAwIBAgIJAKL0UG+mRkSPMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNV BAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEGA1UEBxMKUmh5cyBKb25l czEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVzdCBUTFMgQ2VydGlmaWNh dGUxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0wOTExMTEwOTUyMjJaFw0yOTExMDYw OTUyMjJaMH0xCzAJBgNVBAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEG A1UEBxMKUmh5cyBKb25lczEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVz dCBUTFMgQ2VydGlmaWNhdGUxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG 9w0BAQEFAAOBjQAwgYkCgYEA8d8Hc6atq78Jt1HLp9agA/wpQfsFvkYUdZ1YsdvO kL2janjwHQgMMCy/Njal3FUEW0OLPebKZUJ8L44JBXSlVxU4zyiiSOWld8EkTetR AVT3WKQq3ud+cnxv7g8rGRQp1UHZwmdbZ1wEfAYq8QjYx6m1ciMgRo7DaDQhD29k d+UCAwEAAaOB4zCB4DAdBgNVHQ4EFgQUL9miTJn+HKNuTmx/oMWlZP9cd4QwgbAG A1UdIwSBqDCBpYAUL9miTJn+HKNuTmx/oMWlZP9cd4ShgYGkfzB9MQswCQYDVQQG EwJVSzEUMBIGA1UECBMLQWNrbmFjayBMdGQxEzARBgNVBAcTClJoeXMgSm9uZXMx EDAOBgNVBAoTB25vZGUuanMxHTAbBgNVBAsTFFRlc3QgVExTIENlcnRpZmljYXRl MRIwEAYDVQQDEwlsb2NhbGhvc3SCCQCi9FBvpkZEjzAMBgNVHRMEBTADAQH/MA0G CSqGSIb3DQEBBQUAA4GBADRXXA2xSUK5W1i3oLYWW6NEDVWkTQ9RveplyeS9MOkP e7yPcpz0+O0ZDDrxR9chAiZ7fmdBBX1Tr+pIuCrG/Ud49SBqeS5aMJGVwiSd7o1n dhU2Sz3Q60DwJEL1VenQHiVYlWWtqXBThe9ggqRPnCfsCRTP8qifKkjk45zWPcpN -----END CERTIFICATE----- ]] local options = { cert = certPem, key = keyPem } local respond = function(client, payload) -- skip responses to requests if payload.method == nil then return end local response_method = payload.method .. '.response' local response = JSON.parse(fixtures[response_method]) local response_out = nil response.target = payload.source response.source = payload.target response.id = payload.id print("Sending response:") p(response) response_out = JSON.stringify(response) response_out:gsub("\n", " ") client:write(response_out .. '\n') end local send_schedule_changed = function(client) local request = fixtures['check_schedule.changed.request'] print("Sending request:") p(JSON.parse(request)) client:write(request .. '\n') end tls.createServer(options, function (client) client:pipe(lineEmitter) lineEmitter:on('data', function(line) local payload = JSON.parse(line) print("Got payload:") p(payload) respond(client, payload) end) timer.setTimeout(send_schedule_changed_initial, function() send_schedule_changed(client) end) timer.setInterval(send_schedule_changed_interval, function() send_schedule_changed(client) end) end):listen(port) print("TCP echo server listening on port " .. port)
local net = require('net') local JSON = require('json') local fixtures = require('./') local LineEmitter = require('line-emitter').LineEmitter local tls = require('tls') local timer = require('timer') local string = require('string') local math = require('math') local lineEmitter = LineEmitter:new() local ports = {50041, 50051, 50061} local opts = {} local function set_option(options, name, default) options[name] = process.env[string.upper(name)] or default end set_option(opts, "send_schedule_changed_initial", 2000) set_option(opts, "send_schedule_changed_interval", 60000) set_option(opts, "destroy_connection_jitter", 60000) set_option(opts, "destroy_connection_base", 60000) local keyPem = [[ -----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQDx3wdzpq2rvwm3Ucun1qAD/ClB+wW+RhR1nVix286QvaNqePAd CAwwLL82NqXcVQRbQ4s95splQnwvjgkFdKVXFTjPKKJI5aV3wSRN61EBVPdYpCre 535yfG/uDysZFCnVQdnCZ1tnXAR8BirxCNjHqbVyIyBGjsNoNCEPb2R35QIDAQAB AoGBAJNem9C4ftrFNGtQ2DB0Udz7uDuucepkErUy4MbFsc947GfENjDKJXr42Kx0 kYx09ImS1vUpeKpH3xiuhwqe7tm4FsCBg4TYqQle14oxxm7TNeBwwGC3OB7hiokb aAjbPZ1hAuNs6ms3Ybvvj6Lmxzx42m8O5DXCG2/f+KMvaNUhAkEA/ekrOsWkNoW9 2n3m+msdVuxeek4B87EoTOtzCXb1dybIZUVv4J48VAiM43hhZHWZck2boD/hhwjC M5NWd4oY6QJBAPPcgBVNdNZSZ8hR4ogI4nzwWrQhl9MRbqqtfOn2TK/tjMv10ALg lPmn3SaPSNRPKD2hoLbFuHFERlcS79pbCZ0CQQChX3PuIna/gDitiJ8oQLOg7xEM wk9TRiDK4kl2lnhjhe6PDpaQN4E4F0cTuwqLAoLHtrNWIcOAQvzKMrYdu1MhAkBm Et3qDMnjDAs05lGT72QeN90/mPAcASf5eTTYGahv21cb6IBxM+AnwAPpqAAsHhYR 9h13Y7uYbaOjvuF23LRhAkBoI9eaSMn+l81WXOVUHnzh3ZwB4GuTyxMXXNOhuiFd 0z4LKAMh99Z4xQmqSoEkXsfM4KPpfhYjF/bwIcP5gOei -----END RSA PRIVATE KEY----- ]] local certPem = [[ -----BEGIN CERTIFICATE----- MIIDXDCCAsWgAwIBAgIJAKL0UG+mRkSPMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNV BAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEGA1UEBxMKUmh5cyBKb25l czEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVzdCBUTFMgQ2VydGlmaWNh dGUxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0wOTExMTEwOTUyMjJaFw0yOTExMDYw OTUyMjJaMH0xCzAJBgNVBAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEG A1UEBxMKUmh5cyBKb25lczEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVz dCBUTFMgQ2VydGlmaWNhdGUxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG 9w0BAQEFAAOBjQAwgYkCgYEA8d8Hc6atq78Jt1HLp9agA/wpQfsFvkYUdZ1YsdvO kL2janjwHQgMMCy/Njal3FUEW0OLPebKZUJ8L44JBXSlVxU4zyiiSOWld8EkTetR AVT3WKQq3ud+cnxv7g8rGRQp1UHZwmdbZ1wEfAYq8QjYx6m1ciMgRo7DaDQhD29k d+UCAwEAAaOB4zCB4DAdBgNVHQ4EFgQUL9miTJn+HKNuTmx/oMWlZP9cd4QwgbAG A1UdIwSBqDCBpYAUL9miTJn+HKNuTmx/oMWlZP9cd4ShgYGkfzB9MQswCQYDVQQG EwJVSzEUMBIGA1UECBMLQWNrbmFjayBMdGQxEzARBgNVBAcTClJoeXMgSm9uZXMx EDAOBgNVBAoTB25vZGUuanMxHTAbBgNVBAsTFFRlc3QgVExTIENlcnRpZmljYXRl MRIwEAYDVQQDEwlsb2NhbGhvc3SCCQCi9FBvpkZEjzAMBgNVHRMEBTADAQH/MA0G CSqGSIb3DQEBBQUAA4GBADRXXA2xSUK5W1i3oLYWW6NEDVWkTQ9RveplyeS9MOkP e7yPcpz0+O0ZDDrxR9chAiZ7fmdBBX1Tr+pIuCrG/Ud49SBqeS5aMJGVwiSd7o1n dhU2Sz3Q60DwJEL1VenQHiVYlWWtqXBThe9ggqRPnCfsCRTP8qifKkjk45zWPcpN -----END CERTIFICATE----- ]] local options = { cert = certPem, key = keyPem } local respond = function(log, client, payload) -- skip responses to requests if payload.method == nil then return end local response_method = payload.method .. '.response' local response = JSON.parse(fixtures[response_method]) local response_out = nil response.target = payload.source response.source = payload.target response.id = payload.id log("Sending response:") p(response) response_out = JSON.stringify(response) response_out:gsub("\n", " ") client:write(response_out .. '\n') end local send_schedule_changed = function(log, client) local request = fixtures['check_schedule.changed.request'] log("Sending request:") p(JSON.parse(request)) client:write(request .. '\n') end local function start_fixture_server(options, port) local log = function(...) print(port .. ": " .. ...) end tls.createServer(options, function (client) client:pipe(lineEmitter) lineEmitter:on('data', function(line) local payload = JSON.parse(line) log("Got payload:") p(payload) respond(log, client, payload) end) timer.setTimeout(opts.send_schedule_changed_initial, function() send_schedule_changed(log, client) end) timer.setInterval(opts.send_schedule_changed_interval, function() send_schedule_changed(log, client) end) -- Disconnect the agent after some random number of seconds -- to exercise reconnect logic local disconnect_time = opts.destroy_connection_base + math.floor(math.random() * opts.destroy_connection_jitter) timer.setTimeout(disconnect_time, function() log("Destroying connection after " .. disconnect_time .. "ms connected") client:destroy() end) end):listen(port) end -- There is no cleanup code for the server here as the process for exiting is -- to just ctrl+c the runner or kill the process. for k, v in pairs(ports) do start_fixture_server(options, v) print("TCP echo server listening on port " .. v) end
monitoring: tests: server: listen on multiple ports
monitoring: tests: server: listen on multiple ports listen on all of the expected ports of the fixtures config file. Then randomly disconnect the agent at random intervals to test the retry logic.
Lua
apache-2.0
kans/zirgo,kans/zirgo,kans/zirgo
f04a7a122a01dc26c153fba410a013fe0d634008
lua/entities/gmod_wire_numpad.lua
lua/entities/gmod_wire_numpad.lua
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Numpad" ENT.WireDebugName = "Numpad" if CLIENT then return end -- No more client local keynames = {"0","1","2","3","4","5","6","7","8","9",".","enter","+","-","*","/"} -- Names as we will display them and for inputs/outputs local keyenums = {37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 52, 51, 50, 49, 48, 47} -- Same indexes as keynames, values are the corresponding KEY_* enums local nametoenum = {} for k,v in ipairs(keynames) do nametoenum[v] = keyenums[k] end -- Indexes are string input/output names, values are the corresponding KEY_* enums function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self.Inputs = Wire_CreateInputs(self, keynames) self.Outputs = Wire_CreateOutputs(self, keynames) self.Buffer = {} for i = 1, #keynames do self.Buffer[i] = 0 end end -- These two high speed functions want to access a zero indexed array of what keys are pressed (0-15), our buffer is 1-16 function ENT:ReadCell( Address ) if (Address >= 0) && (Address < #keynames) then return self.Buffer[Address+1] else return nil end end function ENT:WriteCell( Address, value ) if (Address >= 0) && (Address < #keynames) then self:TriggerInput(keynames[Address+1], value) return true else return false end end function ENT:TriggerInput(key, value) if value ~= 0 then numpad.Activate( self:GetPlayer(), nametoenum[key], true ) else numpad.Deactivate( self:GetPlayer(), nametoenum[key], true ) end end function ENT:Setup( toggle, value_off, value_on) self.toggle = toggle self.value_off = value_off self.value_on = value_on self.impulses = {} for k,keyenum in ipairs(keyenums) do table.insert(self.impulses, numpad.OnDown( pl, keyenum, "WireNumpad_On", self, k )) table.insert(self.impulses, numpad.OnUp( pl, keyenum, "WireNumpad_Off", self, k )) end self:ShowOutput() end function ENT:NumpadActivate( key ) if ( self.toggle ) then return self:Switch( self.Buffer[ key ] == 0, key ) end return self:Switch( true, key ) end function ENT:NumpadDeactivate( key ) if ( self.toggle ) then return true end return self:Switch( false, key ) end function ENT:Switch( on, key ) if (!self:IsValid()) then return false end self.Buffer[key] = on and 1 or 0 self:ShowOutput() self.Value = on and self.value_on or self.value_off Wire_TriggerOutput(self, keynames[key], self.Value) return true end function ENT:ShowOutput() local txt = "" for k,keyname in ipairs(keynames) do if (self.Buffer[k] ~= 0) then txt = txt..", "..keyname end end self:SetOverlayText( string.sub(txt,2) ) end function ENT:OnRemove() for _,impulse in ipairs(self.impulses) do numpad.Remove(impulse) end end local function On( pl, ent, key ) return ent:NumpadActivate( key ) end numpad.Register( "WireNumpad_On", On ) local function Off( pl, ent, key ) return ent:NumpadDeactivate( key ) end numpad.Register( "WireNumpad_Off", Off ) duplicator.RegisterEntityClass("gmod_wire_numpad", WireLib.MakeWireEnt, "Data", "toggle", "value_off", "value_on")
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Numpad" ENT.WireDebugName = "Numpad" if CLIENT then return end -- No more client local keynames = {"0","1","2","3","4","5","6","7","8","9",".","enter","+","-","*","/"} -- Names as we will display them and for inputs/outputs local keyenums = {37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 52, 51, 50, 49, 48, 47} -- Same indexes as keynames, values are the corresponding KEY_* enums local nametoenum = {} for k,v in ipairs(keynames) do nametoenum[v] = keyenums[k] end -- Indexes are string input/output names, values are the corresponding KEY_* enums function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self.Inputs = Wire_CreateInputs(self, keynames) self.Outputs = Wire_CreateOutputs(self, keynames) self.Buffer = {} for i = 1, #keynames do self.Buffer[i] = 0 end end -- These two high speed functions want to access a zero indexed array of what keys are pressed (0-15), our buffer is 1-16 function ENT:ReadCell( Address ) if (Address >= 0) && (Address < #keynames) then return self.Buffer[Address+1] else return nil end end function ENT:WriteCell( Address, value ) if (Address >= 0) && (Address < #keynames) then self:TriggerInput(keynames[Address+1], value) return true else return false end end function ENT:TriggerInput(key, value) if value ~= 0 then numpad.Activate( self:GetPlayer(), nametoenum[key], true ) else numpad.Deactivate( self:GetPlayer(), nametoenum[key], true ) end end function ENT:Setup( toggle, value_off, value_on) self.toggle = toggle self.value_off = value_off self.value_on = value_on self.impulses = {} for k,keyenum in ipairs(keyenums) do table.insert(self.impulses, numpad.OnDown( self:GetPlayer(), keyenum, "WireNumpad_On", self, k )) table.insert(self.impulses, numpad.OnUp( self:GetPlayer(), keyenum, "WireNumpad_Off", self, k )) end self:ShowOutput() end function ENT:NumpadActivate( key ) if ( self.toggle ) then return self:Switch( self.Buffer[ key ] == 0, key ) end return self:Switch( true, key ) end function ENT:NumpadDeactivate( key ) if ( self.toggle ) then return true end return self:Switch( false, key ) end function ENT:Switch( on, key ) if (!self:IsValid()) then return false end self.Buffer[key] = on and 1 or 0 self:ShowOutput() self.Value = on and self.value_on or self.value_off Wire_TriggerOutput(self, keynames[key], self.Value) return true end function ENT:ShowOutput() local txt = "" for k,keyname in ipairs(keynames) do if (self.Buffer[k] ~= 0) then txt = txt..", "..keyname end end self:SetOverlayText( string.sub(txt,2) ) end function ENT:OnRemove() for _,impulse in ipairs(self.impulses) do numpad.Remove(impulse) end end local function On( pl, ent, key ) return ent:NumpadActivate( key ) end numpad.Register( "WireNumpad_On", On ) local function Off( pl, ent, key ) return ent:NumpadDeactivate( key ) end numpad.Register( "WireNumpad_Off", Off ) duplicator.RegisterEntityClass("gmod_wire_numpad", WireLib.MakeWireEnt, "Data", "toggle", "value_off", "value_on")
Fix #599. Correctly register numpad callbacks.
Fix #599. Correctly register numpad callbacks.
Lua
apache-2.0
bigdogmat/wire,thegrb93/wire,dvdvideo1234/wire,CaptainPRICE/wire,mms92/wire,wiremod/wire,notcake/wire,sammyt291/wire,garrysmodlua/wire,Grocel/wire,rafradek/wire,NezzKryptic/Wire,immibis/wiremod,plinkopenguin/wiremod,mitterdoo/wire,Python1320/wire
f888eb12e75207da8189aa5c6f5907572a5e88ad
lua/entities/gmod_wire_turret.lua
lua/entities/gmod_wire_turret.lua
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Turret" ENT.WireDebugName = "Turret" if ( CLIENT ) then return end -- No more client function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self:DrawShadow( false ) self:SetCollisionGroup( COLLISION_GROUP_WEAPON ) local phys = self:GetPhysicsObject() if ( phys:IsValid() ) then phys:Wake() end -- Allocating internal values on initialize self.NextShot = 0 self.Firing = false self.spreadvector = Vector() self.effectdata = EffectData() self.attachmentPos = phys:WorldToLocal(self:GetAttachment(1).Pos) self.Inputs = WireLib.CreateSpecialInputs(self, { "Fire", "Force", "Damage", "NumBullets", "Spread", "Delay", "Sound", "Tracer" }, { "NORMAL", "NORMAL", "NORMAL", "NORMAL", "NORMAL", "NORMAL", "STRING", "STRING" }) self.Outputs = WireLib.CreateSpecialOutputs(self, { "HitEntity" }, { "ENTITY" }) end function ENT:FireShot() if ( self.NextShot > CurTime() ) then return end self.NextShot = CurTime() + self.delay -- Make a sound if you want to. if ( self.sound ) then self:EmitSound( self.sound ) end local phys = self:GetPhysicsObject() local shootOrigin = phys:LocalToWorld(self.attachmentPos) local shootAngles = phys:GetAngles() -- Shoot a bullet local bullet = {} bullet.Num = self.numbullets bullet.Src = shootOrigin bullet.Dir = shootAngles:Forward() bullet.Spread = self.spreadvector bullet.Tracer = self.tracernum bullet.TracerName = self.tracer bullet.Force = self.force bullet.Damage = self.damage bullet.Attacker = self:GetPlayer() bullet.Callback = function(attacker, traceres, cdamageinfo) WireLib.TriggerOutput(self, "HitEntity", traceres.Entity) end self:FireBullets( bullet ) -- Make a muzzle flash self.effectdata:SetOrigin( shootOrigin ) self.effectdata:SetAngles( shootAngles ) self.effectdata:SetScale( 1 ) util.Effect( "MuzzleEffect", self.effectdata ) end function ENT:OnTakeDamage( dmginfo ) self:TakePhysicsDamage( dmginfo ) end function ENT:Think() BaseClass.Think( self ) if ( self.Firing ) then self:FireShot() end self:NextThink( CurTime() ) return true end local ValidTracers = { ["Tracer"] = true, ["AR2Tracer"] = true, ["ToolTracer"] = true, ["GaussTracer"] = true, ["LaserTracer"] = true, ["StriderTracer"] = true, ["GunshipTracer"] = true, ["HelicopterTracer"] = true, ["AirboatGunTracer"] = true, ["AirboatGunHeavyTracer"] = true, [""] = true } function ENT:SetSound( sound ) sound = string.Trim( tostring( sound or "" ) ) -- Remove whitespace ( manual ) local check = string.find( sound, "[\"?]" ) -- Preventing client crashes self.sound = check == nil and sound ~= "" and sound or nil -- Apply the pattern check end function ENT:SetDelay( delay ) local check = game.SinglePlayer() -- clamp delay if it's not single player local limit = check and 0.01 or 0.05 self.delay = math.Clamp( delay, limit, 1 ) end function ENT:SetNumBullets( numbullets ) local check = game.SinglePlayer() -- clamp num bullets if it's not single player local limit = math.floor( math.max( 1, numbullets ) ) self.numbullets = check and limit or math.Clamp( limit, 1, 10 ) end function ENT:SetTracer( tracer ) local tracer = string.Trim(tracer) self.tracer = ValidTracers[tracer] and tracer or "" end function ENT:SetSpread( spread ) self.spread = math.Clamp( spread, 0, 1 ) self.spreadvector.x = self.spread self.spreadvector.y = self.spread end function ENT:SetDamage( damage ) self.damage = math.Clamp( damage, 0, 100 ) end function ENT:SetForce( force ) self.force = math.Clamp( force, 0, 500 ) end function ENT:SetTraceNum( tracernum ) self.tracernum = math.floor( math.max( tracernum or 1 ) ) end function ENT:TriggerInput( iname, value ) if (iname == "Fire") then self.Firing = value > 0 elseif (iname == "Force") then self:SetForce( value ) elseif (iname == "Damage") then self:SetDamage( value ) elseif (iname == "NumBullets") then self:SetNumBullets( value ) elseif (iname == "Spread") then self:SetSpread( value ) elseif (iname == "Delay") then self:SetDelay( value ) elseif (iname == "Sound") then self:SetSound( value ) elseif (iname == "Tracer") then self:SetTracer( value ) end end function ENT:Setup(delay, damage, force, sound, numbullets, spread, tracer, tracernum) self:SetForce(force) self:SetDelay(delay) self:SetSound(sound) self:SetDamage(damage) self:SetSpread(spread) self:SetTracer(tracer) self:SetTraceNum(tracernum) self:SetNumBullets(numbullets) end duplicator.RegisterEntityClass( "gmod_wire_turret", WireLib.MakeWireEnt, "Data", "delay", "damage", "force", "sound", "numbullets", "spread", "tracer", "tracernum" )
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Turret" ENT.WireDebugName = "Turret" if ( CLIENT ) then return end -- No more client function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self:DrawShadow( false ) self:SetCollisionGroup( COLLISION_GROUP_WEAPON ) local phys = self:GetPhysicsObject() if ( phys:IsValid() ) then phys:Wake() end -- Allocating internal values on initialize self.NextShot = 0 self.Firing = false self.spreadvector = Vector() self.effectdata = EffectData() self.attachmentPos = phys:WorldToLocal(self:GetAttachment(1).Pos) self.Inputs = WireLib.CreateSpecialInputs(self, { "Fire", "Force", "Damage", "NumBullets", "Spread", "Delay", "Sound", "Tracer" }, { "NORMAL", "NORMAL", "NORMAL", "NORMAL", "NORMAL", "NORMAL", "STRING", "STRING" }) self.Outputs = WireLib.CreateSpecialOutputs(self, { "HitEntity" }, { "ENTITY" }) end function ENT:FireShot() if ( self.NextShot > CurTime() ) then return end self.NextShot = CurTime() + self.delay -- Make a sound if you want to. if ( self.sound ) then self:EmitSound( self.sound ) end local shootOrigin, shootAngles local parent = self:GetParent() if parent:IsValid() then shootOrigin = self:LocalToWorld(self.attachmentPos) shootAngles = self:GetAngles() else local phys = self:GetPhysicsObject() shootOrigin = phys:LocalToWorld(self.attachmentPos) shootAngles = phys:GetAngles() end -- Shoot a bullet local bullet = {} bullet.Num = self.numbullets bullet.Src = shootOrigin bullet.Dir = shootAngles:Forward() bullet.Spread = self.spreadvector bullet.Tracer = self.tracernum bullet.TracerName = self.tracer bullet.Force = self.force bullet.Damage = self.damage bullet.Attacker = self:GetPlayer() bullet.Callback = function(attacker, traceres, cdamageinfo) WireLib.TriggerOutput(self, "HitEntity", traceres.Entity) end self:FireBullets( bullet ) -- Make a muzzle flash self.effectdata:SetOrigin( shootOrigin ) self.effectdata:SetAngles( shootAngles ) self.effectdata:SetScale( 1 ) util.Effect( "MuzzleEffect", self.effectdata ) end function ENT:OnTakeDamage( dmginfo ) self:TakePhysicsDamage( dmginfo ) end function ENT:Think() BaseClass.Think( self ) if ( self.Firing ) then self:FireShot() end self:NextThink( CurTime() ) return true end local ValidTracers = { ["Tracer"] = true, ["AR2Tracer"] = true, ["ToolTracer"] = true, ["GaussTracer"] = true, ["LaserTracer"] = true, ["StriderTracer"] = true, ["GunshipTracer"] = true, ["HelicopterTracer"] = true, ["AirboatGunTracer"] = true, ["AirboatGunHeavyTracer"] = true, [""] = true } function ENT:SetSound( sound ) sound = string.Trim( tostring( sound or "" ) ) -- Remove whitespace ( manual ) local check = string.find( sound, "[\"?]" ) -- Preventing client crashes self.sound = check == nil and sound ~= "" and sound or nil -- Apply the pattern check end function ENT:SetDelay( delay ) local check = game.SinglePlayer() -- clamp delay if it's not single player local limit = check and 0.01 or 0.05 self.delay = math.Clamp( delay, limit, 1 ) end function ENT:SetNumBullets( numbullets ) local check = game.SinglePlayer() -- clamp num bullets if it's not single player local limit = math.floor( math.max( 1, numbullets ) ) self.numbullets = check and limit or math.Clamp( limit, 1, 10 ) end function ENT:SetTracer( tracer ) local tracer = string.Trim(tracer) self.tracer = ValidTracers[tracer] and tracer or "" end function ENT:SetSpread( spread ) self.spread = math.Clamp( spread, 0, 1 ) self.spreadvector.x = self.spread self.spreadvector.y = self.spread end function ENT:SetDamage( damage ) self.damage = math.Clamp( damage, 0, 100 ) end function ENT:SetForce( force ) self.force = math.Clamp( force, 0, 500 ) end function ENT:SetTraceNum( tracernum ) self.tracernum = math.floor( math.max( tracernum or 1 ) ) end function ENT:TriggerInput( iname, value ) if (iname == "Fire") then self.Firing = value > 0 elseif (iname == "Force") then self:SetForce( value ) elseif (iname == "Damage") then self:SetDamage( value ) elseif (iname == "NumBullets") then self:SetNumBullets( value ) elseif (iname == "Spread") then self:SetSpread( value ) elseif (iname == "Delay") then self:SetDelay( value ) elseif (iname == "Sound") then self:SetSound( value ) elseif (iname == "Tracer") then self:SetTracer( value ) end end function ENT:Setup(delay, damage, force, sound, numbullets, spread, tracer, tracernum) self:SetForce(force) self:SetDelay(delay) self:SetSound(sound) self:SetDamage(damage) self:SetSpread(spread) self:SetTracer(tracer) self:SetTraceNum(tracernum) self:SetNumBullets(numbullets) end duplicator.RegisterEntityClass( "gmod_wire_turret", WireLib.MakeWireEnt, "Data", "delay", "damage", "force", "sound", "numbullets", "spread", "tracer", "tracernum" )
Fix turret behavior if parented (#2184)
Fix turret behavior if parented (#2184)
Lua
apache-2.0
Grocel/wire,wiremod/wire,dvdvideo1234/wire
74c8b1fb90271c586e315bb83683ba9154bca863
spec/security/crypto/ticket_spec.lua
spec/security/crypto/ticket_spec.lua
local encoding = require 'core.encoding' local cipher = require 'security.crypto.cipher' local digest = require 'security.crypto.digest' local ticket = require 'security.crypto.ticket' describe('ticket', function() local t = ticket.new { --digest = digest.new('md5'), digest = digest.hmac('ripemd160', 'key1'), cipher = cipher.new('aes128', 'key2'), encoder = encoding.new('base64') } assert.equals(900, t.max_age) it('decrypt encrypted', function() local r = t:encode('test') local value = t:decode(r) assert.equals('test', value) end) describe('new', function() it('supports string for digest', function() assert(ticket.new { digest = 'md5', cipher = cipher.new('aes128', 'key2'), encoder = encoding.new('base64') }) end) it('supports function for digest', function() local digest = require 'security.crypto.digest' local md5 = digest.new 'md5' assert(ticket.new { digest = md5, cipher = cipher.new('aes128', 'key2'), encoder = encoding.new('base64') }) end) it('raises an error if digest is not a string or function', function() local f = function() ticket.new {} end assert.error(f, 'digest: string or function expected') end) it('supports max_age', function() assert.equals(60, ticket.new { digest = 'md5', max_age = 60, cipher = cipher.new('aes128', 'key2'), encoder = encoding.new('base64') }.max_age) end) end) describe('decode', function() it('unable to decode', function() local value, err = t:decode('$') assert.is_nil(value) assert.equals('unable to decode', err) end) it('signature mismatch', function() local value, err = t:decode('invalid') assert.is_nil(value) assert.equals('signature missmatch', err) end) it('unable to decrypt', function() local t2 = ticket.new { digest = digest.hmac('ripemd160', 'key1'), cipher = cipher.new('aes128', 'invalid'), encoder = encoding.new('base64') } local r = t:encode('test') local value, err = t2:decode(r) assert.is_nil(value) assert.equals('unable to decrypt', err) end) it('expired', function() local value, err = t:decode( 'blRmix9ICePifLqLPHaVNkNV66IUdpn9Vy' .. 'mIotdkoYFjb/UEqOl2ZGJTsPZ5P/kuWZ8NUw==') assert.is_nil(value) assert.equals('expired', err) end) end) end)
local encoding = require 'core.encoding' local cipher = require 'security.crypto.cipher' local digest = require 'security.crypto.digest' local ticket = require 'security.crypto.ticket' describe('ticket', function() local t = ticket.new { --digest = digest.new('md5'), digest = digest.hmac('ripemd160', 'key1'), cipher = cipher.new('aes128', 'key2'), encoder = encoding.new('base64') } assert.equals(900, t.max_age) it('decrypt encrypted', function() local r = t:encode('test') local value = t:decode(r) assert.equals('test', value) end) describe('new', function() it('supports string for digest', function() assert(ticket.new { digest = 'md5', cipher = cipher.new('aes128', 'key2'), encoder = encoding.new('base64') }) end) it('supports function for digest', function() local md5 = digest.new 'md5' assert(ticket.new { digest = md5, cipher = cipher.new('aes128', 'key2'), encoder = encoding.new('base64') }) end) it('raises an error if digest is not a string or function', function() local f = function() ticket.new {} end assert.error(f, 'digest: string or function expected') end) it('supports max_age', function() assert.equals(60, ticket.new { digest = 'md5', max_age = 60, cipher = cipher.new('aes128', 'key2'), encoder = encoding.new('base64') }.max_age) end) end) describe('decode', function() it('unable to decode', function() local value, err = t:decode('$') assert.is_nil(value) assert.equals('unable to decode', err) end) it('signature mismatch', function() local value, err = t:decode('invalid') assert.is_nil(value) assert.equals('signature missmatch', err) end) it('unable to decrypt', function() local t2 = ticket.new { digest = digest.hmac('ripemd160', 'key1'), cipher = cipher.new('aes128', 'invalid'), encoder = encoding.new('base64') } local r = t:encode('test') local value, err = t2:decode(r) assert.is_nil(value) assert.equals('unable to decrypt', err) end) it('expired', function() local value, err = t:decode( 'blRmix9ICePifLqLPHaVNkNV66IUdpn9Vy' .. 'mIotdkoYFjb/UEqOl2ZGJTsPZ5P/kuWZ8NUw==') assert.is_nil(value) assert.equals('expired', err) end) end) end)
Fixed issue with shadowing upvalue digest in test case.
Fixed issue with shadowing upvalue digest in test case.
Lua
mit
akornatskyy/lucid
7dc11b360e849779d4f112c2fadd6aa5bc3f489d
lua/plugins/oscyank.lua
lua/plugins/oscyank.lua
-- luacheck: max line length 143 local executable = require('utils.files').executable local set_command = require('neovim.commands').set_command local set_autocmd = require('neovim.autocmds').set_autocmd if vim.g.OSCTERM then vim.g.oscyank_term = vim.g.OSCTERM elseif executable 'kitty' then vim.g.oscyank_term = 'kitty' elseif vim.env.TMUX then vim.g.oscyank_term = 'tmux' else vim.g.oscyank_term = 'default' end set_command { lhs = 'OSCTerm', rhs = 'let g:oscyank_term = <q-args>', args = { force = true, nargs = 1, complete = 'customlist,neovim#vim_oscyank' }, } set_autocmd { event = 'TextYankPost', pattern = '*', cmd = [[if v:event.operator is 'y' && (v:event.regname is '+' || v:event.regname is '*' || v:event.regname is '') | OSCYankReg + | endif]], group = 'OSCYank', }
-- luacheck: max line length 143 local executable = require('utils.files').executable local set_command = require('neovim.commands').set_command local set_autocmd = require('neovim.autocmds').set_autocmd if vim.g.OSCTERM then vim.g.oscyank_term = vim.g.OSCTERM elseif vim.env.OSCTERM then vim.g.oscyank_term = vim.env.OSCTERM elseif executable 'kitty' then vim.g.oscyank_term = 'kitty' elseif vim.env.TMUX then vim.g.oscyank_term = 'tmux' else vim.g.oscyank_term = 'default' end set_command { lhs = 'OSCTerm', rhs = 'let g:oscyank_term = <q-args>', args = { force = true, nargs = 1, complete = 'customlist,neovim#vim_oscyank' }, } set_autocmd { event = 'TextYankPost', pattern = '*', cmd = [[if v:event.operator is 'y' && (v:event.regname is '+' || v:event.regname is '*' || v:event.regname is '') | OSCYankReg + | endif]], group = 'OSCYank', }
fix: Respect environment OSCTERM var
fix: Respect environment OSCTERM var
Lua
mit
Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim
c199f33b7b506655ef5acbc6ae1960e36a08ea89
mock/gfx/asset/Font.lua
mock/gfx/asset/Font.lua
module 'mock' -------------------------------------------------------------------- local charCodes = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,:.?!{}()<>+_=" -------------------------------------------------------------------- -------font local function loadFont( node ) local font = MOAIFont.new() local atype = node.type --TODO: support serialized font local attributes = node.attributes or {} if attributes[ 'serialized' ] then local sdataPath = node.objectFiles['data'] local texturePath = node.objectFiles['texture'] font = dofile( sdataPath ) -- load the font image back in local image = MOAIImage.new () image:load ( texturePath, 0 ) -- set the font image font:setCache() font:setReader() font:setImage( image ) end if atype == 'font_bmfont' then local texPaths = {} for k, v in pairs( node.dependency ) do if k:sub(1,3) == 'tex' then local id = tonumber( k:sub(5,-1) ) texPaths[ id ] = v end end local textures = {} for i, path in ipairs( texPaths ) do local tex, node = loadAsset( path ) table.insert( textures, tex:getMoaiTexture() ) end if #textures > 0 then font:loadFromBMFont( node.objectFiles['font'], textures ) else _warn('bmfont texture not load', node:getNodePath() ) end elseif atype == 'font_ttf' then local filename = node.objectFiles['font'] font:getReader():enableAntiAliasing( true ) font:getCache():setColorFormat( MOAIImage.COLOR_FMT_RGBA_8888 ) font:load( filename, 0 ) elseif atype == 'font_bdf' then font:load( node.objectFiles['font'] ) else _error( 'failed to load font:', node.path ) return getFontPlaceHolder() end local dpi = 72 local size = attributes['size'] or 20 local preloadGlyphs = attributes['preloadGlyphs'] if preloadGlyphs then font:preloadGlyphs( preloadGlyphs, size ) end font.size = size return font end -------------------------------------------------------------------- registerAssetLoader( 'font_ttf', loadFont ) registerAssetLoader( 'font_bdf', loadFont ) registerAssetLoader( 'font_bmfont', loadFont ) --preload font placeholder getFontPlaceHolder()
module 'mock' -------------------------------------------------------------------- local charCodes = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,:.?!{}()<>+_=" -------------------------------------------------------------------- -------font local function loadFont( node ) local font = MOAIFont.new() local atype = node.type --TODO: support serialized font local attributes = node.attributes or {} if attributes[ 'serialized' ] then local sdataPath = node.objectFiles['data'] local texturePath = node.objectFiles['texture'] font = dofile( sdataPath ) -- load the font image back in local image = MOAIImage.new () image:load ( texturePath, 0 ) -- set the font image font:setCache() font:setReader() font:setImage( image ) end if atype == 'font_bmfont' then local texPaths = {} for k, v in pairs( node.dependency ) do if k:sub(1,3) == 'tex' then local id = tonumber( k:sub(5,-1) ) texPaths[ id ] = v end end local textures = {} for i, path in ipairs( texPaths ) do local tex, node = loadAsset( path ) if not tex then _error( 'failed load font texture' ) return getFontPlaceHolder() end table.insert( textures, tex:getMoaiTexture() ) end if #textures > 0 then font:loadFromBMFont( node.objectFiles['font'], textures ) else _warn('bmfont texture not load', node:getNodePath() ) end elseif atype == 'font_ttf' then local filename = node.objectFiles['font'] font:getReader():enableAntiAliasing( true ) font:getCache():setColorFormat( MOAIImage.COLOR_FMT_RGBA_8888 ) font:load( filename, 0 ) elseif atype == 'font_bdf' then font:load( node.objectFiles['font'] ) else _error( 'failed to load font:', node.path ) return getFontPlaceHolder() end local dpi = 72 local size = attributes['size'] or 20 local preloadGlyphs = attributes['preloadGlyphs'] if preloadGlyphs then font:preloadGlyphs( preloadGlyphs, size ) end font.size = size return font end -------------------------------------------------------------------- registerAssetLoader( 'font_ttf', loadFont ) registerAssetLoader( 'font_bdf', loadFont ) registerAssetLoader( 'font_bmfont', loadFont ) --preload font placeholder getFontPlaceHolder()
fix font bug
fix font bug
Lua
mit
tommo/mock
d0e920fab0f8e10d0068208781fada88f35da84c
test_scripts/Polices/Validation_of_PolicyTables/286_ATF_Validate_default_priority_preDataConsent.lua
test_scripts/Polices/Validation_of_PolicyTables/286_ATF_Validate_default_priority_preDataConsent.lua
--------------------------------------------------------------------------------------------- -- Requirement summary: -- [Policies] "pre_DataConsent" policies assigned to the application and "priority" value -- -- Description: -- Providing to HMI app`s default priority value of "pre_DataConsent" if "pre_DataConsent" policies assigned to the application -- 1. Used preconditions: -- SDL and HMI are running -- Close default connection -- Connect device -- -- 2. Performed steps -- Register app-> "pre_DataConsent" policies are assigned to the application -- Activate app -- -- Expected result: -- PoliciesManager must provide to HMI the app`s priority value(NONE) taken from "priority" field in "pre_DataConsent" section of PolicyTable --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonFunctions = require ('user_modules/shared_testcases/commonFunctions') local commonSteps = require('user_modules/shared_testcases/commonSteps') local commonTestCases = require('user_modules/shared_testcases/commonTestCases') 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_connect_device.lua") --TODO(istoimenova): 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_connect_device') require('cardinalities') require('user_modules/AppTypes') local mobile_session = require('mobile_session') --[[ Preconditions ]] commonSteps:DeleteLogsFileAndPolicyTable() function Test:Precondition_Close_default_connection() self.mobileConnection:Close() commonTestCases:DelayedExp(3000) end function Test:Precondition_Connect_device() commonTestCases:DelayedExp(2000) self:connectMobile() EXPECT_HMICALL("BasicCommunication.UpdateDeviceList", { deviceList = { { id = config.deviceMAC, name = "127.0.0.1", transportType = "WIFI" } } } ):Do(function(_,data) self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {}) end) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep1_Priority_NONE_OnAppRegistered() commonTestCases:DelayedExp(3000) self.mobileSession = mobile_session.MobileSession(self, self.mobileConnection) self.mobileSession:StartService(7) :Do(function() local correlationId = self.mobileSession:SendRPC("RegisterAppInterface", config.application1.registerAppInterfaceParams) EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered", {priority ="NONE"}) :Do(function(_,data) self.HMIAppID = data.params.application.appID end) self.mobileSession:ExpectResponse(correlationId, { success = true, resultCode = "SUCCESS" }) self.mobileSession:ExpectNotification("OnHMIStatus", {hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE", systemContext = "MAIN"}) end) end function Test:TestStep2_Priority_NONE_ActivateApp() local RequestId = self.hmiConnection:SendRequest("SDL.ActivateApp", { appID = self.applications[config.application1.registerAppInterfaceParams.appName]}) EXPECT_HMIRESPONSE(RequestId, {result = { code = 0, method ="SDL.ActivateApp", priority ="NONE"}}) :Do(function(_,data) if data.result.priority ~= "NONE" then commonFunctions:userPrint(31, "Error: wrong behavior of SDL - priority should be NONE") end end) EXPECT_HMICALL("BasicCommunication.ActivateApp"):Times(0) EXPECT_NOTIFICATION("OnHMIStatus", {}):Times(0) EXPECT_HMICALL("BasicCommunication.UpdateAppList",{applications = { {appName = config.application1.registerAppInterfaceParams.appName}}}) end function Test:Precondition_Check_priority_pre_DataConsent() local app_group_table = commonFunctions:get_data_policy_sql(config.pathToSDL.."/storage/policy.sqlite", "select functional_group_id from app_group where application_id = '"..config.application1.registerAppInterfaceParams.appID.."'") local app_group for _,value in pairs(app_group_table) do app_group = value end -- 129372391 - BaseBeforeDataConsent if(app_group ~= "129372391") then self:FailTestCase("Application is not assigned to pre_DataConsent. Real: "..app_group) end local priority_id_table = commonFunctions:get_data_policy_sql(config.pathToSDL.."/storage/policy.sqlite", "select priority_value from application where id = '"..config.application1.registerAppInterfaceParams.appID.."'") local priority_id for _, value in pairs(priority_id_table) do priority_id = value end if(priority_id ~= "NONE") then self:FailTestCase("Priority for pre_DataConsent is not NONE. Real: "..priority_id) end local is_predata_table = commonFunctions:get_data_policy_sql(config.pathToSDL.."/storage/policy.sqlite", "select is_predata from application where id = '"..config.application1.registerAppInterfaceParams.appID.."'") local is_predata for _,value in pairs(is_predata_table) do is_predata = value end if(is_predata ~= "1") then self:FailTestCase("Application is not assigned to pre_DataConsent, is_predata = "..priority_id) end end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_SDLStop() StopSDL() end return Test
--------------------------------------------------------------------------------------------- -- Requirement summary: -- [Policies] "pre_DataConsent" policies assigned to the application and "priority" value -- -- Description: -- Providing to HMI app`s default priority value of "pre_DataConsent" if "pre_DataConsent" policies assigned to the application -- 1. Used preconditions: -- SDL and HMI are running -- Close default connection -- Connect device -- -- 2. Performed steps -- Register app-> "pre_DataConsent" policies are assigned to the application -- Activate app -- -- Expected result: -- PoliciesManager must provide to HMI the app`s priority value(NONE) taken from "priority" field in "pre_DataConsent" section of PolicyTable --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonFunctions = require ('user_modules/shared_testcases/commonFunctions') local commonSteps = require('user_modules/shared_testcases/commonSteps') local commonTestCases = require('user_modules/shared_testcases/commonTestCases') 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_connect_device.lua") --TODO(istoimenova): 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_connect_device') require('cardinalities') require('user_modules/AppTypes') local mobile_session = require('mobile_session') --[[ Preconditions ]] commonSteps:DeleteLogsFileAndPolicyTable() function Test:Precondition_Close_default_connection() self.mobileConnection:Close() commonTestCases:DelayedExp(3000) end function Test:Precondition_Connect_device() commonTestCases:DelayedExp(2000) self:connectMobile() EXPECT_HMICALL("BasicCommunication.UpdateDeviceList", { deviceList = { { id = config.deviceMAC, name = "127.0.0.1", transportType = "WIFI" } } } ):Do(function(_,data) self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {}) end) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep1_Priority_NONE_OnAppRegistered() commonTestCases:DelayedExp(3000) self.mobileSession = mobile_session.MobileSession(self, self.mobileConnection) self.mobileSession:StartService(7) :Do(function() local correlationId = self.mobileSession:SendRPC("RegisterAppInterface", config.application1.registerAppInterfaceParams) EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered", {priority = nil }) :Do(function(_,data) self.HMIAppID = data.params.application.appID end) self.mobileSession:ExpectResponse(correlationId, { success = true, resultCode = "SUCCESS" }) self.mobileSession:ExpectNotification("OnHMIStatus", {hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE", systemContext = "MAIN"}) end) end function Test:TestStep2_Priority_NONE_ActivateApp() local RequestId = self.hmiConnection:SendRequest("SDL.ActivateApp", { appID = self.applications[config.application1.registerAppInterfaceParams.appName]}) EXPECT_HMIRESPONSE(RequestId, {result = { code = 0, method ="SDL.ActivateApp", priority = nil }}) :Do(function(_,data) if data.result.priority ~= nil then commonFunctions:userPrint(31, "Error: wrong behavior of SDL - priority should be omitted") end end) EXPECT_HMICALL("BasicCommunication.ActivateApp"):Times(0) EXPECT_NOTIFICATION("OnHMIStatus", {}):Times(0) -- EXPECT_HMICALL("BasicCommunication.UpdateAppList",{applications = { {appName = config.application1.registerAppInterfaceParams.appName}}}) end function Test:Precondition_Check_priority_pre_DataConsent() local app_group_table = commonFunctions:get_data_policy_sql(config.pathToSDL.."/storage/policy.sqlite", "select functional_group_id from app_group where application_id = '"..config.application1.registerAppInterfaceParams.appID.."'") local app_group for _,value in pairs(app_group_table) do app_group = value end -- 129372391 - BaseBeforeDataConsent if(app_group ~= "129372391") then self:FailTestCase("Application is not assigned to pre_DataConsent. Real: "..app_group) end local priority_id_table = commonFunctions:get_data_policy_sql(config.pathToSDL.."/storage/policy.sqlite", "select priority_value from application where id = '"..config.application1.registerAppInterfaceParams.appID.."'") local priority_id for _, value in pairs(priority_id_table) do priority_id = value end if(priority_id ~= "NONE") then self:FailTestCase("Priority for pre_DataConsent is not NONE. Real: "..priority_id) end local is_predata_table = commonFunctions:get_data_policy_sql(config.pathToSDL.."/storage/policy.sqlite", "select is_predata from application where id = '"..config.application1.registerAppInterfaceParams.appID.."'") local is_predata for _,value in pairs(is_predata_table) do is_predata = value end if(is_predata ~= "1") then self:FailTestCase("Application is not assigned to pre_DataConsent, is_predata = "..priority_id) end end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_SDLStop() StopSDL() end return Test
Fix issues
Fix issues
Lua
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
06891393a841859573d6e21fabedca1eeec3f4d7
kong/tools/wrpc/init.lua
kong/tools/wrpc/init.lua
local pb = require "pb" local queue = require "kong.tools.wrpc.queue" local threads = require "kong.tools.wrpc.threads" local future = require "kong.tools.wrpc.future" local pb_encode = pb.encode local queue_new = queue.new local future_new = future.new local ngx_log = ngx.log local NOTICE = ngx.NOTICE local ngx_now = ngx.now local DEFAULT_EXPIRATION_DELAY = 90 pb.option("no_default_values") local _M = {} local _MT = {} _MT.__index = _M _M.spawn_threads = threads.spawn _M.wait_threads = threads.wait local function is_wsclient(conn) return conn and not conn.close or nil end --- a `peer` object holds a (websocket) connection and a service. --- @param conn table WebSocket connection to use. --- @param service table Proto object that holds Serivces the connection supports. function _M.new_peer(conn, service, timeout) return setmetatable({ conn = conn, service = service, seq = 1, request_queue = is_wsclient(conn) and queue_new(), responses = {}, closing = false, _receiving_thread = nil, timeout = timeout or DEFAULT_EXPIRATION_DELAY, }, _MT) end -- functions for managing connection -- NOTICE: the caller is responsible to call this function before you can -- not reach the peer. -- -- A peer spwan threads refering itself, even if you cannot reach the object. -- -- Therefore it's impossible for __gc to kill the threads -- and close the WebSocket connection. function _M:close() self.closing = true self.conn:send_close() if self.conn.close then self.conn:close() end end function _M:send(d) if self.request_queue then return self.request_queue:push(d) end return self.conn:send_binary(d) end function _M:receive() while true do local data, typ, err = self.conn:recv_frame() if not data then return nil, err end if typ == "binary" then return data end if typ == "close" then ngx_log(NOTICE, "Received WebSocket \"close\" frame from peer: ", err, ": ", data) return self:close() end end end -- functions to send call --- Part of wrpc_peer:call() --- This performs the per-call parts. The arguments --- are the return values from wrpc_peer:encode_args(), --- either directly or cached (to repeat the same call --- several times). --- @param rpc(table) name of RPC to call or response --- @param payloads(string) payloads to send --- @return kong.tools.wrpc.future|nil future, string|nil err function _M:send_encoded_call(rpc, payloads) local response_future = future_new(self, self.timeout) local ok, err = self:send_payload({ mtype = "MESSAGE_TYPE_RPC", svc_id = rpc.svc_id, rpc_id = rpc.rpc_id, payload_encoding = "ENCODING_PROTO3", payloads = payloads, }) if not ok then return nil, err end return response_future end local send_encoded_call = _M.send_encoded_call -- Make an RPC call. -- -- Returns immediately. -- Caller is responsible to call wait() for the returned future. --- @param name(string) name of RPC to call, like "ConfigService.Sync" --- @param arg(table) arguments of the call, like {config = config} --- @return kong.tools.wrpc.future|nil future, string|nil err function _M:call(name, arg) local rpc, payloads = assert(self.service:encode_args(name, arg)) return send_encoded_call(self, rpc, payloads) end -- Make an RPC call. -- -- Block until the call is responded or an error occurs. --- @async --- @param name(string) name of RPC to call, like "ConfigService.Sync" --- @param arg(table) arguments of the call, like {config = config} --- @return any data, string|nil err result of the call function _M:call_async(name, arg) local future_to_wait, err = self:call(name, arg) return future_to_wait and future_to_wait:wait(), err end -- Make an RPC call. -- -- Returns immediately and ignore response of the call. --- @param name(string) name of RPC to call, like "ConfigService.Sync" --- @param arg(table) arguments of the call, like {config = config} --- @return boolean|nil ok, string|nil err result of the call function _M:call_no_return(name, arg) local future_to_wait, err = self:call(name, arg) if not future_to_wait then return nil, err end return future_to_wait:drop() end --- encodes and sends a wRPC message. --- Assumes protocol fields are already filled (except `.seq` and `.deadline`) --- and payload data (if any) is already encoded with the right type. --- Keeps track of the sequence number and assigns deadline. function _M:send_payload(payload) local seq = self.seq payload.seq = seq self.seq = seq + 1 -- protobuf may confuse with 0 value and nil(undefined) under some set up -- so we will just handle 0 as nil if not payload.ack or payload.ack == 0 then payload.deadline = ngx_now() + self.timeout end return self:send(pb_encode("wrpc.WebsocketPayload", { version = "PAYLOAD_VERSION_V1", payload = payload, })) end return _M
local pb = require "pb" local queue = require "kong.tools.wrpc.queue" local threads = require "kong.tools.wrpc.threads" local future = require "kong.tools.wrpc.future" local pb_encode = pb.encode local queue_new = queue.new local future_new = future.new local ngx_log = ngx.log local NOTICE = ngx.NOTICE local ngx_now = ngx.now local DEFAULT_EXPIRATION_DELAY = 90 pb.option("no_default_values") local _M = {} local _MT = {} _MT.__index = _M _M.spawn_threads = threads.spawn _M.wait_threads = threads.wait local function is_wsclient(conn) return conn and not conn.close or nil end --- a `peer` object holds a (websocket) connection and a service. --- @param conn table WebSocket connection to use. --- @param service table Proto object that holds Serivces the connection supports. function _M.new_peer(conn, service, timeout) timeout = timeout or DEFAULT_EXPIRATION_DELAY conn:set_timeout(timeout * 1000) return setmetatable({ conn = conn, service = service, seq = 1, request_queue = is_wsclient(conn) and queue_new(), responses = {}, closing = false, _receiving_thread = nil, timeout = timeout, }, _MT) end -- functions for managing connection -- NOTICE: the caller is responsible to call this function before you can -- not reach the peer. -- -- A peer spwan threads refering itself, even if you cannot reach the object. -- -- Therefore it's impossible for __gc to kill the threads -- and close the WebSocket connection. function _M:close() self.closing = true self.conn:send_close() if self.conn.close then self.conn:close() end end function _M:send(d) if self.request_queue then return self.request_queue:push(d) end return self.conn:send_binary(d) end function _M:receive() while true do local data, typ, err = self.conn:recv_frame() if not data then return nil, err end if typ == "binary" then return data end if typ == "close" then ngx_log(NOTICE, "Received WebSocket \"close\" frame from peer: ", err, ": ", data) return self:close() end end end -- functions to send call --- Part of wrpc_peer:call() --- This performs the per-call parts. The arguments --- are the return values from wrpc_peer:encode_args(), --- either directly or cached (to repeat the same call --- several times). --- @param rpc(table) name of RPC to call or response --- @param payloads(string) payloads to send --- @return kong.tools.wrpc.future|nil future, string|nil err function _M:send_encoded_call(rpc, payloads) local response_future = future_new(self, self.timeout) local ok, err = self:send_payload({ mtype = "MESSAGE_TYPE_RPC", svc_id = rpc.svc_id, rpc_id = rpc.rpc_id, payload_encoding = "ENCODING_PROTO3", payloads = payloads, }) if not ok then return nil, err end return response_future end local send_encoded_call = _M.send_encoded_call -- Make an RPC call. -- -- Returns immediately. -- Caller is responsible to call wait() for the returned future. --- @param name(string) name of RPC to call, like "ConfigService.Sync" --- @param arg(table) arguments of the call, like {config = config} --- @return kong.tools.wrpc.future|nil future, string|nil err function _M:call(name, arg) local rpc, payloads = assert(self.service:encode_args(name, arg)) return send_encoded_call(self, rpc, payloads) end -- Make an RPC call. -- -- Block until the call is responded or an error occurs. --- @async --- @param name(string) name of RPC to call, like "ConfigService.Sync" --- @param arg(table) arguments of the call, like {config = config} --- @return any data, string|nil err result of the call function _M:call_async(name, arg) local future_to_wait, err = self:call(name, arg) return future_to_wait and future_to_wait:wait(), err end -- Make an RPC call. -- -- Returns immediately and ignore response of the call. --- @param name(string) name of RPC to call, like "ConfigService.Sync" --- @param arg(table) arguments of the call, like {config = config} --- @return boolean|nil ok, string|nil err result of the call function _M:call_no_return(name, arg) local future_to_wait, err = self:call(name, arg) if not future_to_wait then return nil, err end return future_to_wait:drop() end --- encodes and sends a wRPC message. --- Assumes protocol fields are already filled (except `.seq` and `.deadline`) --- and payload data (if any) is already encoded with the right type. --- Keeps track of the sequence number and assigns deadline. function _M:send_payload(payload) local seq = self.seq payload.seq = seq self.seq = seq + 1 -- protobuf may confuse with 0 value and nil(undefined) under some set up -- so we will just handle 0 as nil if not payload.ack or payload.ack == 0 then payload.deadline = ngx_now() + self.timeout end return self:send(pb_encode("wrpc.WebsocketPayload", { version = "PAYLOAD_VERSION_V1", payload = payload, })) end return _M
fix(clustering): wRPC should set connect timeout for WebSocket connections
fix(clustering): wRPC should set connect timeout for WebSocket connections
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
76f0c83fec8c378a43c2dea2ba727e3c19be1b11
net/connlisteners.lua
net/connlisteners.lua
-- Prosody IM v0.2 -- Copyright (C) 2008 Matthew Wild -- Copyright (C) 2008 Waqas Hussain -- -- This program is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -- local listeners_dir = (CFG_SOURCEDIR or ".").."/net/"; local server = require "net.server"; local log = require "util.logger".init("connlisteners"); local dofile, pcall, error = dofile, pcall, error module "connlisteners" local listeners = {}; function register(name, listener) if listeners[name] and listeners[name] ~= listener then log("warn", "Listener %s is already registered, not registering any more", name); return false; end listeners[name] = listener; log("info", "Registered connection listener %s", name); return true; end function deregister(name) listeners[name] = nil; end function get(name) local h = listeners[name]; if not h then local ok, ret = pcall(dofile, listeners_dir..name:gsub("[^%w%-]", "_").."_listener.lua"); if not ok then return nil, ret; end h = listeners[name]; end return h; end local wrapper_functions = { tcp = server.wraptcpclient, ssl = server.wrapsslclient, tls = server.wraptlsclient } function start(name, udata) local h = get(name); if not h then error("No such connection module: "..name, 0); end local wrapper_function = wrapper_functions[(udata and udata.type)] or wrapper_functions.tcp; return server.add(h, (udata and udata.port) or h.default_port or error("Can't start listener "..name.." because no port was specified, and it has no default port", 0), (udata and udata.interface) or "*", (udata and udata.mode) or h.default_mode or 1, (udata and udata.ssl) or nil, wrapper_function); end return _M;
-- Prosody IM v0.2 -- Copyright (C) 2008 Matthew Wild -- Copyright (C) 2008 Waqas Hussain -- -- This program is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -- local listeners_dir = (CFG_SOURCEDIR or ".").."/net/"; local server = require "net.server"; local log = require "util.logger".init("connlisteners"); local dofile, pcall, error = dofile, pcall, error module "connlisteners" local listeners = {}; function register(name, listener) if listeners[name] and listeners[name] ~= listener then log("warn", "Listener %s is already registered, not registering any more", name); return false; end listeners[name] = listener; log("info", "Registered connection listener %s", name); return true; end function deregister(name) listeners[name] = nil; end function get(name) local h = listeners[name]; if not h then local ok, ret = pcall(dofile, listeners_dir..name:gsub("[^%w%-]", "_").."_listener.lua"); if not ok then return nil, ret; end h = listeners[name]; end return h; end local wrapper_functions = { tcp = server.wraptcpclient, ssl = server.wrapsslclient, tls = server.wraptlsclient } function start(name, udata) local h, err = get(name); if not h then error("No such connection module: "..name.. (err and (" ("..err..")") or ""), 0); end local wrapper_function = wrapper_functions[(udata and udata.type)] or wrapper_functions.tcp; return server.add(h, (udata and udata.port) or h.default_port or error("Can't start listener "..name.." because no port was specified, and it has no default port", 0), (udata and udata.interface) or "*", (udata and udata.mode) or h.default_mode or 1, (udata and udata.ssl) or nil, wrapper_function); end return _M;
net.connlisteners: Fix to report errors loading connlisteners
net.connlisteners: Fix to report errors loading connlisteners
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
7be32a933262a3190cb105f1b038fab81be8a748
modules/admin-mini/luasrc/model/cbi/mini/network.lua
modules/admin-mini/luasrc/model/cbi/mini/network.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> 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$ ]]-- require("luci.tools.webadmin") require("luci.sys") m0 = Map("network", translate("network")) m0.stateful = true local netstat = luci.sys.net.deviceinfo() m0.parse = function() end s = m0:section(TypedSection, "interface", translate("status")) s.template = "cbi/tblsection" s.rowcolors = true function s.filter(self, section) return section ~= "loopback" and section end hwaddr = s:option(DummyValue, "_hwaddr") function hwaddr.cfgvalue(self, section) local ix = self.map:get(section, "ifname") or "" return luci.fs.readfile("/sys/class/net/" .. ix .. "/address") or "n/a" end s:option(DummyValue, "ipaddr", translate("ipaddress")) s:option(DummyValue, "netmask", translate("netmask")) txrx = s:option(DummyValue, "_txrx") function txrx.cfgvalue(self, section) local ix = self.map:get(section, "ifname") local rx = netstat and netstat[ix] and netstat[ix][1] rx = rx and luci.tools.webadmin.byte_format(tonumber(rx)) or "-" local tx = netstat and netstat[ix] and netstat[ix][9] tx = tx and luci.tools.webadmin.byte_format(tonumber(tx)) or "-" return string.format("%s / %s", tx, rx) end errors = s:option(DummyValue, "_err") function errors.cfgvalue(self, section) local ix = self.map:get(section, "ifname") local rx = netstat and netstat[ix] and netstat[ix][3] local tx = netstat and netstat[ix] and netstat[ix][11] rx = rx and tostring(rx) or "-" tx = tx and tostring(tx) or "-" return string.format("%s / %s", tx, rx) end m = Map("network", "") s = m:section(NamedSection, "lan", "interface", translate("m_n_local")) s:option(Value, "ipaddr", translate("ipaddress")) nm = s:option(Value, "netmask", translate("netmask")) nm:value("255.255.255.0") nm:value("255.255.0.0") nm:value("255.0.0.0") gw = s:option(Value, "gateway", translate("gateway") .. translate("cbi_optional")) gw.rmempty = true dns = s:option(Value, "dns", translate("dnsserver") .. translate("cbi_optional")) dns.rmempty = true s = m:section(NamedSection, "wan", "interface", translate("m_n_inet")) p = s:option(ListValue, "proto", translate("protocol")) p:value("none", "disabled") p:value("static", translate("manual", "manual")) p:value("dhcp", translate("automatic", "automatic")) p:value("pppoe", "PPPoE") p:value("pptp", "PPTP") ip = s:option(Value, "ipaddr", translate("ipaddress")) ip:depends("proto", "static") nm = s:option(Value, "netmask", translate("netmask")) nm:depends("proto", "static") gw = s:option(Value, "gateway", translate("gateway")) gw:depends("proto", "static") gw.rmempty = true dns = s:option(Value, "dns", translate("dnsserver")) dns:depends("proto", "static") dns.rmempty = true usr = s:option(Value, "username", translate("username")) usr:depends("proto", "pppoe") usr:depends("proto", "pptp") pwd = s:option(Value, "password", translate("password")) pwd:depends("proto", "pppoe") pwd:depends("proto", "pptp") kea = s:option(Flag, "keepalive", translate("m_n_keepalive")) kea:depends("proto", "pppoe") kea:depends("proto", "pptp") kea.rmempty = true kea.enabled = "10" cod = s:option(Value, "demand", translate("m_n_dialondemand"), "s") cod:depends("proto", "pppoe") cod:depends("proto", "pptp") cod.rmempty = true srv = s:option(Value, "server", translate("m_n_pptp_server")) srv:depends("proto", "pptp") srv.rmempty = true return m0, m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> 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$ ]]-- require("luci.tools.webadmin") require("luci.sys") luci.model.uci.load_state("network") local wireless = luci.model.uci.get_all("network") luci.model.uci.unload("network") local netstat = luci.sys.net.deviceinfo() local ifaces = {} for k, v in pairs(wireless) do if v[".type"] == "interface" and k ~= "loopback" then table.insert(ifaces, v) end end m = Map("network", translate("network")) s = m:section(Table, ifaces, translate("status")) s.parse = function() end s:option(DummyValue, ".name", translate("network")) hwaddr = s:option(DummyValue, "_hwaddr", translate("network_interface_hwaddr"), translate("network_interface_hwaddr_desc")) function hwaddr.cfgvalue(self, section) local ix = self.map:get(section, "ifname") or "" return luci.fs.readfile("/sys/class/net/" .. ix .. "/address") or "n/a" end s:option(DummyValue, "ipaddr", translate("ipaddress")) s:option(DummyValue, "netmask", translate("netmask")) txrx = s:option(DummyValue, "_txrx", translate("network_interface_txrx"), translate("network_interface_txrx_desc")) function txrx.cfgvalue(self, section) local ix = self.map:get(section, "ifname") local rx = netstat and netstat[ix] and netstat[ix][1] rx = rx and luci.tools.webadmin.byte_format(tonumber(rx)) or "-" local tx = netstat and netstat[ix] and netstat[ix][9] tx = tx and luci.tools.webadmin.byte_format(tonumber(tx)) or "-" return string.format("%s / %s", tx, rx) end errors = s:option(DummyValue, "_err", translate("network_interface_err"), translate("network_interface_err_desc")) function errors.cfgvalue(self, section) local ix = self.map:get(section, "ifname") local rx = netstat and netstat[ix] and netstat[ix][3] local tx = netstat and netstat[ix] and netstat[ix][11] rx = rx and tostring(rx) or "-" tx = tx and tostring(tx) or "-" return string.format("%s / %s", tx, rx) end s = m:section(NamedSection, "lan", "interface", translate("m_n_local")) s:option(Value, "ipaddr", translate("ipaddress")) nm = s:option(Value, "netmask", translate("netmask")) nm:value("255.255.255.0") nm:value("255.255.0.0") nm:value("255.0.0.0") gw = s:option(Value, "gateway", translate("gateway") .. translate("cbi_optional")) gw.rmempty = true dns = s:option(Value, "dns", translate("dnsserver") .. translate("cbi_optional")) dns.rmempty = true s = m:section(NamedSection, "wan", "interface", translate("m_n_inet")) p = s:option(ListValue, "proto", translate("protocol")) p:value("none", "disabled") p:value("static", translate("manual", "manual")) p:value("dhcp", translate("automatic", "automatic")) p:value("pppoe", "PPPoE") p:value("pptp", "PPTP") ip = s:option(Value, "ipaddr", translate("ipaddress")) ip:depends("proto", "static") nm = s:option(Value, "netmask", translate("netmask")) nm:depends("proto", "static") gw = s:option(Value, "gateway", translate("gateway")) gw:depends("proto", "static") gw.rmempty = true dns = s:option(Value, "dns", translate("dnsserver")) dns:depends("proto", "static") dns.rmempty = true usr = s:option(Value, "username", translate("username")) usr:depends("proto", "pppoe") usr:depends("proto", "pptp") pwd = s:option(Value, "password", translate("password")) pwd:depends("proto", "pppoe") pwd:depends("proto", "pptp") kea = s:option(Flag, "keepalive", translate("m_n_keepalive")) kea:depends("proto", "pppoe") kea:depends("proto", "pptp") kea.rmempty = true kea.enabled = "10" cod = s:option(Value, "demand", translate("m_n_dialondemand"), "s") cod:depends("proto", "pppoe") cod:depends("proto", "pptp") cod.rmempty = true srv = s:option(Value, "server", translate("m_n_pptp_server")) srv:depends("proto", "pptp") srv.rmempty = true return m
Fixed duplicate tables
Fixed duplicate tables
Lua
apache-2.0
dwmw2/luci,cshore/luci,NeoRaider/luci,Sakura-Winkey/LuCI,palmettos/test,hnyman/luci,mumuqz/luci,shangjiyu/luci-with-extra,harveyhu2012/luci,male-puppies/luci,ff94315/luci-1,male-puppies/luci,urueedi/luci,NeoRaider/luci,Wedmer/luci,openwrt/luci,oyido/luci,kuoruan/luci,ff94315/luci-1,tobiaswaldvogel/luci,dwmw2/luci,remakeelectric/luci,kuoruan/luci,oneru/luci,NeoRaider/luci,thesabbir/luci,aa65535/luci,jchuang1977/luci-1,LuttyYang/luci,MinFu/luci,oyido/luci,shangjiyu/luci-with-extra,nwf/openwrt-luci,fkooman/luci,jorgifumi/luci,chris5560/openwrt-luci,joaofvieira/luci,wongsyrone/luci-1,david-xiao/luci,jorgifumi/luci,db260179/openwrt-bpi-r1-luci,cappiewu/luci,hnyman/luci,zhaoxx063/luci,lbthomsen/openwrt-luci,cshore-firmware/openwrt-luci,taiha/luci,kuoruan/lede-luci,dwmw2/luci,sujeet14108/luci,mumuqz/luci,ollie27/openwrt_luci,david-xiao/luci,bittorf/luci,deepak78/new-luci,marcel-sch/luci,palmettos/test,palmettos/cnLuCI,bittorf/luci,florian-shellfire/luci,opentechinstitute/luci,male-puppies/luci,981213/luci-1,taiha/luci,remakeelectric/luci,bright-things/ionic-luci,oyido/luci,dismantl/luci-0.12,joaofvieira/luci,lcf258/openwrtcn,joaofvieira/luci,tobiaswaldvogel/luci,taiha/luci,zhaoxx063/luci,deepak78/new-luci,rogerpueyo/luci,chris5560/openwrt-luci,hnyman/luci,artynet/luci,chris5560/openwrt-luci,db260179/openwrt-bpi-r1-luci,florian-shellfire/luci,urueedi/luci,cshore-firmware/openwrt-luci,taiha/luci,forward619/luci,oneru/luci,Kyklas/luci-proto-hso,tobiaswaldvogel/luci,RuiChen1113/luci,nmav/luci,bright-things/ionic-luci,jlopenwrtluci/luci,cshore/luci,lcf258/openwrtcn,lbthomsen/openwrt-luci,keyidadi/luci,palmettos/cnLuCI,oneru/luci,chris5560/openwrt-luci,Noltari/luci,palmettos/test,fkooman/luci,hnyman/luci,RedSnake64/openwrt-luci-packages,zhaoxx063/luci,david-xiao/luci,dwmw2/luci,obsy/luci,thess/OpenWrt-luci,ollie27/openwrt_luci,wongsyrone/luci-1,MinFu/luci,cshore/luci,RuiChen1113/luci,981213/luci-1,ff94315/luci-1,cshore-firmware/openwrt-luci,florian-shellfire/luci,marcel-sch/luci,openwrt-es/openwrt-luci,harveyhu2012/luci,sujeet14108/luci,chris5560/openwrt-luci,forward619/luci,981213/luci-1,bittorf/luci,teslamint/luci,schidler/ionic-luci,RuiChen1113/luci,openwrt/luci,jlopenwrtluci/luci,openwrt/luci,forward619/luci,slayerrensky/luci,Kyklas/luci-proto-hso,sujeet14108/luci,shangjiyu/luci-with-extra,RedSnake64/openwrt-luci-packages,jchuang1977/luci-1,oyido/luci,rogerpueyo/luci,fkooman/luci,remakeelectric/luci,urueedi/luci,sujeet14108/luci,LuttyYang/luci,dismantl/luci-0.12,schidler/ionic-luci,tobiaswaldvogel/luci,maxrio/luci981213,obsy/luci,nmav/luci,oneru/luci,harveyhu2012/luci,ReclaimYourPrivacy/cloak-luci,nwf/openwrt-luci,taiha/luci,zhaoxx063/luci,Hostle/openwrt-luci-multi-user,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,981213/luci-1,cshore-firmware/openwrt-luci,artynet/luci,dwmw2/luci,RuiChen1113/luci,marcel-sch/luci,ReclaimYourPrivacy/cloak-luci,oyido/luci,nmav/luci,jorgifumi/luci,mumuqz/luci,bright-things/ionic-luci,NeoRaider/luci,nmav/luci,kuoruan/luci,kuoruan/lede-luci,Hostle/luci,jchuang1977/luci-1,ReclaimYourPrivacy/cloak-luci,aircross/OpenWrt-Firefly-LuCI,oneru/luci,remakeelectric/luci,981213/luci-1,opentechinstitute/luci,dismantl/luci-0.12,LazyZhu/openwrt-luci-trunk-mod,deepak78/new-luci,jorgifumi/luci,jorgifumi/luci,MinFu/luci,Noltari/luci,opentechinstitute/luci,obsy/luci,lbthomsen/openwrt-luci,RedSnake64/openwrt-luci-packages,opentechinstitute/luci,RedSnake64/openwrt-luci-packages,tcatm/luci,ollie27/openwrt_luci,RuiChen1113/luci,chris5560/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,oyido/luci,tobiaswaldvogel/luci,oyido/luci,dismantl/luci-0.12,ReclaimYourPrivacy/cloak-luci,MinFu/luci,urueedi/luci,jlopenwrtluci/luci,fkooman/luci,ff94315/luci-1,cappiewu/luci,forward619/luci,thesabbir/luci,bittorf/luci,florian-shellfire/luci,chris5560/openwrt-luci,forward619/luci,daofeng2015/luci,wongsyrone/luci-1,Sakura-Winkey/LuCI,LazyZhu/openwrt-luci-trunk-mod,Sakura-Winkey/LuCI,oyido/luci,palmettos/test,tcatm/luci,Wedmer/luci,artynet/luci,Hostle/luci,RuiChen1113/luci,zhaoxx063/luci,NeoRaider/luci,taiha/luci,bright-things/ionic-luci,daofeng2015/luci,NeoRaider/luci,tcatm/luci,ollie27/openwrt_luci,maxrio/luci981213,forward619/luci,bright-things/ionic-luci,Kyklas/luci-proto-hso,nwf/openwrt-luci,wongsyrone/luci-1,Noltari/luci,palmettos/cnLuCI,cshore/luci,bittorf/luci,nmav/luci,oneru/luci,cappiewu/luci,oneru/luci,openwrt-es/openwrt-luci,MinFu/luci,Hostle/openwrt-luci-multi-user,cshore/luci,obsy/luci,rogerpueyo/luci,dwmw2/luci,sujeet14108/luci,slayerrensky/luci,david-xiao/luci,artynet/luci,opentechinstitute/luci,aa65535/luci,tcatm/luci,bittorf/luci,cappiewu/luci,marcel-sch/luci,LuttyYang/luci,Kyklas/luci-proto-hso,keyidadi/luci,joaofvieira/luci,LuttyYang/luci,bright-things/ionic-luci,male-puppies/luci,palmettos/test,lcf258/openwrtcn,db260179/openwrt-bpi-r1-luci,jorgifumi/luci,cshore-firmware/openwrt-luci,dismantl/luci-0.12,fkooman/luci,cshore/luci,aircross/OpenWrt-Firefly-LuCI,Hostle/luci,bittorf/luci,taiha/luci,nwf/openwrt-luci,Hostle/luci,ff94315/luci-1,thess/OpenWrt-luci,rogerpueyo/luci,opentechinstitute/luci,palmettos/cnLuCI,Wedmer/luci,florian-shellfire/luci,marcel-sch/luci,RedSnake64/openwrt-luci-packages,joaofvieira/luci,harveyhu2012/luci,Noltari/luci,kuoruan/lede-luci,Hostle/openwrt-luci-multi-user,ff94315/luci-1,bright-things/ionic-luci,mumuqz/luci,mumuqz/luci,chris5560/openwrt-luci,urueedi/luci,palmettos/cnLuCI,mumuqz/luci,thess/OpenWrt-luci,artynet/luci,maxrio/luci981213,lcf258/openwrtcn,daofeng2015/luci,MinFu/luci,opentechinstitute/luci,bright-things/ionic-luci,florian-shellfire/luci,tcatm/luci,LuttyYang/luci,RuiChen1113/luci,keyidadi/luci,NeoRaider/luci,harveyhu2012/luci,openwrt/luci,deepak78/new-luci,schidler/ionic-luci,kuoruan/luci,kuoruan/luci,cappiewu/luci,thess/OpenWrt-luci,dismantl/luci-0.12,openwrt/luci,harveyhu2012/luci,palmettos/cnLuCI,teslamint/luci,Hostle/luci,lcf258/openwrtcn,lcf258/openwrtcn,sujeet14108/luci,wongsyrone/luci-1,aa65535/luci,MinFu/luci,kuoruan/lede-luci,mumuqz/luci,kuoruan/lede-luci,LazyZhu/openwrt-luci-trunk-mod,jlopenwrtluci/luci,Hostle/openwrt-luci-multi-user,keyidadi/luci,keyidadi/luci,daofeng2015/luci,thesabbir/luci,cshore/luci,artynet/luci,oneru/luci,deepak78/new-luci,lbthomsen/openwrt-luci,taiha/luci,maxrio/luci981213,Hostle/openwrt-luci-multi-user,nwf/openwrt-luci,shangjiyu/luci-with-extra,aircross/OpenWrt-Firefly-LuCI,cshore-firmware/openwrt-luci,joaofvieira/luci,Sakura-Winkey/LuCI,thess/OpenWrt-luci,Wedmer/luci,tcatm/luci,sujeet14108/luci,openwrt-es/openwrt-luci,aa65535/luci,981213/luci-1,wongsyrone/luci-1,lbthomsen/openwrt-luci,urueedi/luci,jchuang1977/luci-1,aircross/OpenWrt-Firefly-LuCI,Wedmer/luci,harveyhu2012/luci,LazyZhu/openwrt-luci-trunk-mod,teslamint/luci,LazyZhu/openwrt-luci-trunk-mod,bittorf/luci,LazyZhu/openwrt-luci-trunk-mod,male-puppies/luci,teslamint/luci,ReclaimYourPrivacy/cloak-luci,palmettos/test,Sakura-Winkey/LuCI,jchuang1977/luci-1,palmettos/cnLuCI,zhaoxx063/luci,urueedi/luci,maxrio/luci981213,artynet/luci,Kyklas/luci-proto-hso,zhaoxx063/luci,kuoruan/luci,teslamint/luci,kuoruan/lede-luci,marcel-sch/luci,lcf258/openwrtcn,hnyman/luci,MinFu/luci,obsy/luci,nmav/luci,dismantl/luci-0.12,palmettos/test,slayerrensky/luci,ReclaimYourPrivacy/cloak-luci,aa65535/luci,keyidadi/luci,kuoruan/luci,fkooman/luci,nwf/openwrt-luci,Wedmer/luci,thesabbir/luci,mumuqz/luci,ff94315/luci-1,openwrt-es/openwrt-luci,ollie27/openwrt_luci,remakeelectric/luci,tobiaswaldvogel/luci,deepak78/new-luci,cshore-firmware/openwrt-luci,urueedi/luci,artynet/luci,rogerpueyo/luci,david-xiao/luci,thesabbir/luci,nwf/openwrt-luci,marcel-sch/luci,db260179/openwrt-bpi-r1-luci,thesabbir/luci,cshore-firmware/openwrt-luci,Kyklas/luci-proto-hso,artynet/luci,Hostle/openwrt-luci-multi-user,cappiewu/luci,jorgifumi/luci,florian-shellfire/luci,deepak78/new-luci,fkooman/luci,maxrio/luci981213,schidler/ionic-luci,RuiChen1113/luci,remakeelectric/luci,rogerpueyo/luci,marcel-sch/luci,openwrt-es/openwrt-luci,ollie27/openwrt_luci,lcf258/openwrtcn,Wedmer/luci,thesabbir/luci,tobiaswaldvogel/luci,daofeng2015/luci,aircross/OpenWrt-Firefly-LuCI,cappiewu/luci,hnyman/luci,db260179/openwrt-bpi-r1-luci,openwrt-es/openwrt-luci,slayerrensky/luci,openwrt/luci,lcf258/openwrtcn,maxrio/luci981213,ReclaimYourPrivacy/cloak-luci,lcf258/openwrtcn,openwrt/luci,deepak78/new-luci,Sakura-Winkey/LuCI,openwrt-es/openwrt-luci,981213/luci-1,Hostle/luci,opentechinstitute/luci,joaofvieira/luci,slayerrensky/luci,NeoRaider/luci,slayerrensky/luci,forward619/luci,sujeet14108/luci,nmav/luci,slayerrensky/luci,cappiewu/luci,keyidadi/luci,Hostle/luci,daofeng2015/luci,tcatm/luci,Noltari/luci,rogerpueyo/luci,LuttyYang/luci,ollie27/openwrt_luci,florian-shellfire/luci,db260179/openwrt-bpi-r1-luci,RedSnake64/openwrt-luci-packages,teslamint/luci,Noltari/luci,shangjiyu/luci-with-extra,jchuang1977/luci-1,schidler/ionic-luci,jlopenwrtluci/luci,schidler/ionic-luci,obsy/luci,wongsyrone/luci-1,joaofvieira/luci,maxrio/luci981213,Hostle/openwrt-luci-multi-user,teslamint/luci,david-xiao/luci,daofeng2015/luci,hnyman/luci,lbthomsen/openwrt-luci,shangjiyu/luci-with-extra,keyidadi/luci,thess/OpenWrt-luci,RedSnake64/openwrt-luci-packages,ollie27/openwrt_luci,jchuang1977/luci-1,thesabbir/luci,kuoruan/luci,Noltari/luci,hnyman/luci,jlopenwrtluci/luci,shangjiyu/luci-with-extra,aircross/OpenWrt-Firefly-LuCI,jorgifumi/luci,thess/OpenWrt-luci,jchuang1977/luci-1,wongsyrone/luci-1,aa65535/luci,db260179/openwrt-bpi-r1-luci,Sakura-Winkey/LuCI,Noltari/luci,remakeelectric/luci,nmav/luci,male-puppies/luci,obsy/luci,Wedmer/luci,ReclaimYourPrivacy/cloak-luci,slayerrensky/luci,nmav/luci,ff94315/luci-1,jlopenwrtluci/luci,Hostle/openwrt-luci-multi-user,obsy/luci,schidler/ionic-luci,remakeelectric/luci,teslamint/luci,male-puppies/luci,tcatm/luci,LazyZhu/openwrt-luci-trunk-mod,openwrt-es/openwrt-luci,schidler/ionic-luci,cshore/luci,aa65535/luci,palmettos/cnLuCI,lbthomsen/openwrt-luci,aa65535/luci,david-xiao/luci,Kyklas/luci-proto-hso,fkooman/luci,rogerpueyo/luci,Sakura-Winkey/LuCI,dwmw2/luci,LuttyYang/luci,LuttyYang/luci,palmettos/test,forward619/luci,david-xiao/luci,male-puppies/luci,nwf/openwrt-luci,thess/OpenWrt-luci,zhaoxx063/luci,kuoruan/lede-luci,daofeng2015/luci,Noltari/luci,Hostle/luci,kuoruan/lede-luci,openwrt/luci,dwmw2/luci,jlopenwrtluci/luci,shangjiyu/luci-with-extra,db260179/openwrt-bpi-r1-luci,aircross/OpenWrt-Firefly-LuCI
e536e4b39c4198408ed946ea85273079acaa84ff
PokémonInfo-Regionaldex.lua
PokémonInfo-Regionaldex.lua
-- Modulo da usare nel template PokémonInfo per determinare -- i dex regionali local rdex = {} local txt = require('Wikilib-strings') -- luacheck: no unused local tab = require('Wikilib-tables') -- luacheck: no unused local dex = require("Dex-data") local c = require("Colore-data") local sup = require("Sup-data") local links = require('Links') -- Ritorna il dex regionale di un Pokémon nel vecchio -- dex regionale specificato: nel caso in cui non sia -- presente, ritorna nil local getOldDex = function(newDex, oldDexTable, changedDexTable) if changedDexTable and changedDexTable[newDex] then return txt.tf(changedDexTable[newDex]) end for subtract, ndex in ipairs(oldDexTable) do if ndex == newDex then return nil; elseif ndex > newDex then return txt.tf(newDex - subtract + 1) end end return txt.tf(newDex - table.getn(oldDexTable)) end -- Aggiunge un title al primo argomento costituito -- dal secondo e dal terzo separati da uno spazio local addtt = function(newDex, oldDex, title) return string.interp(links.tt(newDex, oldDex .. title)) end -- Inserisce le informazioni relative al vecchio dex -- regionale: per Sinnoh un sup di platino, per le -- altre un title local insOld = {} insOld.johto = function(newDex, oldDex) return addtt(newDex, oldDex, ' nella seconda generazione') end insOld.hoenn = function(newDex, oldDex) return addtt(newDex, oldDex, ' nella terza generazione') end insOld.sinnoh = function(newDex, oldDex) return newDex .. sup.Pt end insOld.unima = function(newDex, oldDex) return addtt(newDex, oldDex, ' in Nero e Bianco') end insOld.alola = function(newDex, oldDex) return addtt(newDex, oldDex, ' in Sole e Luna') end -- Ordina la tabella store: la table è esterna alla -- funzione così da non essere ricreata ogni volta local regiongens = { Kanto = 1, Johto = 2, Hoenn = 3, Sinnoh = 4, Unima = 5, Kalos = 6, Alola = 7, Galar = 8, Armatura = 9, Corona = 10 } local region_sort = function(c, d) local a, b = c:match('>(%a+)</span>'), d:match('>(%a+)</span>') return regiongens[a] < regiongens[b] end -- La funzione che genera le celle per i dex regionali: -- nello scorrere la tabella fornita dalla search, -- controlla che il dex non sia tra quelli aggiornati in seguito -- ed effettua l'inserimento; se ciò non accade, concatena all'ultimo -- elemento l'asterisco giusto chiamando la funzione olddex. local dexlist = function(dexes) if table.getn(dexes) == 0 then return nil end local store = {} local str = [=[<span><div class="small-font">'''[[Elenco Pokémon secondo il Pokédex di ${reg}|<span style="color:#000">${reg}</span>]]'''</div>#${rdex}</span>]=] local kalos = [=[<span><div class="small-font">'''[[Elenco Pokémon secondo i Pokédex di Kalos#Pokédex di Kalos ${reg}|<span style="color:#${c}">Kalos</span>]]'''</div>#${ttdex}</span>]=] local incl = '<includeonly>[[Categoria:Pokémon originari della regione di ${reg}|${rdex}]]</includeonly>' for region, rdex in pairs(dexes) do if region:find('kalos') then local zone = region:match('kalos(%a+)$') table.insert(store, string.interp(kalos, {c = c['kalos' .. zone].normale, ttdex = links.tt(rdex, zone), reg = zone})) else local oldDexTable = dex[region .. 'Added'] if oldDexTable then local oldDex = getOldDex(tonumber(rdex), oldDexTable, dex[region .. 'Changed']) if oldDex ~= rdex then rdex = insOld[region](rdex, oldDex or 'Non disponibile') end end table.insert(store, string.interp(str, {reg = string.fu(region), rdex = rdex})) end end table.sort(store, region_sort) for k, v in ipairs(store) do store[k] = v end if #store > 5 then table.insert(store, 1 + math.floor(#store / 2), '<div class="width-xl-100"></div>') end return table.concat(store) end -- Semplicemente cerca tra tutti i dex se si trova il numero di dex -- nazionale fornito: in caso positivo, lo inserisce come elemento -- di una table con indice il nome della regione. Se una certa regione -- ha più dex regionali (es: alola) inserisce come valore una table -- contenente il numero di dex nazionale local search = function(ndex) local dexes = {} for region, regionalDex in pairs(dex) do local rdex = table.search(regionalDex, ndex) if rdex then dexes[region] = txt.three_figures(rdex) end end return dexes end --Interfaccia. Riceve un ndex su tre cifre e un tipo, e interpola il colore standard -- del tipo e la lista dei dex regionali, creata con la funzione dexlist, al box in wikicode rdex.regionaldex = function(frame) local ndex = string.trim(frame.args[1]) or '000' return string.interp([=[| colspan="2" | <div>[[Pokédex Regionale|<span style="color:#000;">'''Pokédex Regionali'''</span>]]</div> <div class="roundy flex-row-center-around flex-wrap" style="background: #fff; padding-top: 0.5ex; padding-bottom: 0.5ex;">${dexlist}</div> ]=], { dexlist = dexlist(search(ndex)) or 'In nessun Pokédex Regionale' }) end rdex.Regionaldex, rdex.RegionalDex = rdex.regionaldex, rdex.regionaldex return rdex
-- Modulo da usare nel template PokémonInfo per determinare -- i dex regionali local rdex = {} local txt = require('Wikilib-strings') -- luacheck: no unused local tab = require('Wikilib-tables') -- luacheck: no unused local dex = require("Dex-data") local c = require("Colore-data") local sup = require("Sup-data") local links = require('Links') -- Ritorna il dex regionale di un Pokémon nel vecchio -- dex regionale specificato: nel caso in cui non sia -- presente, ritorna nil local getOldDex = function(newDex, oldDexTable, changedDexTable) if changedDexTable and changedDexTable[newDex] then return txt.tf(changedDexTable[newDex]) end for subtract, ndex in ipairs(oldDexTable) do if ndex == newDex then return nil; elseif ndex > newDex then return txt.tf(newDex - subtract + 1) end end return txt.tf(newDex - table.getn(oldDexTable)) end -- Aggiunge un title al primo argomento costituito -- dal secondo e dal terzo separati da uno spazio local addtt = function(newDex, oldDex, title) return string.interp(links.tt(newDex, oldDex .. title)) end -- Inserisce le informazioni relative al vecchio dex -- regionale: per Sinnoh un sup di platino, per le -- altre un title local insOld = {} insOld.johto = function(newDex, oldDex) return addtt(newDex, oldDex, ' nella seconda generazione') end insOld.hoenn = function(newDex, oldDex) return addtt(newDex, oldDex, ' nella terza generazione') end insOld.sinnoh = function(newDex, oldDex) return newDex .. sup.Pt end insOld.unima = function(newDex, oldDex) return addtt(newDex, oldDex, ' in Nero e Bianco') end insOld.alola = function(newDex, oldDex) return addtt(newDex, oldDex, ' in Sole e Luna') end -- Ordina la tabella store: la table è esterna alla -- funzione così da non essere ricreata ogni volta local regiongens = { Kanto = { ord = 1 }, Johto = { ord = 2 }, Hoenn = { ord = 3 }, Sinnoh = { ord = 4 }, Unima = { ord = 5 }, Kalos = { ord = 6 }, Alola = { ord = 7 }, Galar = { ord = 8 }, Armatura = { ord = 9, pref = "" }, Corona = { ord = 10, pref = "" }, } local region_sort = function(c, d) local a, b = c:match('>(%a+)</span>'), d:match('>(%a+)</span>') return regiongens[a].ord < regiongens[b].ord end --[[ La funzione che genera le celle per i dex regionali: nello scorrere la tabella fornita dalla search, controlla che il dex non sia tra quelli aggiornati in seguito ed effettua l'inserimento; se ciò non accade, concatena all'ultimo elemento l'asterisco giusto chiamando la funzione olddex. --]] local dexlist = function(dexes) if table.getn(dexes) == 0 then return nil end local store = {} local str = [=[<span><div class="small-font">'''[[Elenco Pokémon secondo il Pokédex ${pref}${reg}|<span style="color:#000">${reg}</span>]]'''</div>#${rdex}</span>]=] local kalos = [=[<span><div class="small-font">'''[[Elenco Pokémon secondo i Pokédex di Kalos#Pokédex di Kalos ${reg}|<span style="color:#${c}">Kalos</span>]]'''</div>#${ttdex}</span>]=] for region, rdex in pairs(dexes) do if region:find('kalos') then local zone = region:match('kalos(%a+)$') table.insert(store, string.interp(kalos, {c = c['kalos' .. zone].normale, ttdex = links.tt(rdex, zone), reg = zone})) else local oldDexTable = dex[region .. 'Added'] if oldDexTable then local oldDex = getOldDex(tonumber(rdex), oldDexTable, dex[region .. 'Changed']) if oldDex ~= rdex then rdex = insOld[region](rdex, oldDex or 'Non disponibile') end end local regionName = string.fu(region) table.insert(store, string.interp(str, {reg = regionName, pref = regiongens[regionName].pref or "di ", rdex = rdex})) end end table.sort(store, region_sort) for k, v in ipairs(store) do store[k] = v end if #store > 5 then table.insert(store, 1 + math.floor(#store / 2), '<div class="width-xl-100"></div>') end return table.concat(store) end -- Semplicemente cerca tra tutti i dex se si trova il numero di dex -- nazionale fornito: in caso positivo, lo inserisce come elemento -- di una table con indice il nome della regione. Se una certa regione -- ha più dex regionali (es: alola) inserisce come valore una table -- contenente il numero di dex nazionale local search = function(ndex) local dexes = {} for region, regionalDex in pairs(dex) do local rdex = table.search(regionalDex, ndex) if rdex then dexes[region] = txt.three_figures(rdex) end end return dexes end --Interfaccia. Riceve un ndex su tre cifre e un tipo, e interpola il colore standard -- del tipo e la lista dei dex regionali, creata con la funzione dexlist, al box in wikicode rdex.regionaldex = function(frame) local ndex = string.trim(frame.args[1]) or '000' return string.interp([=[| colspan="2" | <div>[[Pokédex Regionale|<span style="color:#000;">'''Pokédex Regionali'''</span>]]</div> <div class="roundy flex-row-center-around flex-wrap" style="background: #fff; padding-top: 0.5ex; padding-bottom: 0.5ex;">${dexlist}</div> ]=], { dexlist = dexlist(search(ndex)) or 'In nessun Pokédex Regionale' }) end rdex.Regionaldex, rdex.RegionalDex = rdex.regionaldex, rdex.regionaldex return rdex
Fixed link to dex page in PokémonInfo-Regionaldex
Fixed link to dex page in PokémonInfo-Regionaldex
Lua
cc0-1.0
pokemoncentral/wiki-lua-modules
440370fc26475fd530d28cab4fba7cfd0fa6f37c
src/premake4.lua
src/premake4.lua
newoption { trigger = "gdal-csharp", value = "DIR", description = "Directory with GDAL C# bindings (REQUIRED)", } -- If an action other than clean is specified, verify that the -- --gdal-csharp option was used to provide the location of the -- GDAL C# bindings. function gdal_csharp_error(message) print("Error with --gdal-csharp: " .. message) error("command line error") end if _ACTION and _ACTION ~= "clean" then if not _OPTIONS["gdal-csharp"] then gdal_csharp_error("it is missing (use --help for details)") end gdal_csharp_dir = _OPTIONS["gdal-csharp"] if string.match(gdal_csharp_dir, "^%s*$") then gdal_csharp_error("no directory specified") end if os.isfile(gdal_csharp_dir) then gdal_csharp_error('"'..gdal_csharp_dir..'" is not a directory') end if not os.isdir(gdal_csharp_dir) then gdal_csharp_error('"'..gdal_csharp_dir..'" does not exist') end else -- set the directory variable so Premake don't report an error -- about attempting to concatentate to a nil value in the "links" -- function below gdal_csharp_dir="" end build_dir="../build" solution "landis-spatial" language "C#" -- by default, premake uses "Any CPU" for platform configurations { "Debug", "Release" } configuration "Debug" defines { "DEBUG" } flags { "Symbols" } targetdir ( build_dir .. "/Debug" ) configuration "Release" flags { "OptimizeSize" } targetdir ( build_dir .. "/Release" ) -- The library's API project "Landis_SpatialModeling" location "api" kind "SharedLib" targetname "Landis.SpatialModeling" files { "api/*.cs", "SharedAssemblyInfo.cs" } links { "System" } -- Implementation of the Landscape module project "Landis_Landscapes" location "Landscapes" kind "SharedLib" targetname "Landis.Landscapes" files { "Landscapes/**.cs", "SharedAssemblyInfo.cs" } links { "System", "Landis_SpatialModeling" } -- Data types shared by Raster I/O implementations project "Landis_RasterIO" location "RasterIO" kind "SharedLib" targetname "Landis.RasterIO" files { "RasterIO/**.cs", "SharedAssemblyInfo.cs" } links { "System", "Landis_SpatialModeling", } -- Implementation of the Raster I/O module using GDAL project "Landis_RasterIO_Gdal" location "RasterIO.Gdal" kind "SharedLib" targetname "Landis.RasterIO.Gdal" files { "RasterIO.Gdal/**.cs", "SharedAssemblyInfo.cs" } links { "System", "Landis_SpatialModeling", "Landis_RasterIO", gdal_csharp_dir.."/gdal_csharp.dll" }
build_dir="../build" solution "landis-spatial" language "C#" -- by default, premake uses "Any CPU" for platform configurations { "Debug", "Release" } configuration "Debug" defines { "DEBUG" } flags { "Symbols" } targetdir ( build_dir .. "/Debug" ) configuration "Release" flags { "OptimizeSize" } targetdir ( build_dir .. "/Release" ) -- The library's API project "Landis_SpatialModeling" location "api" kind "SharedLib" targetname "Landis.SpatialModeling" files { "api/*.cs", "SharedAssemblyInfo.cs" } links { "System" } -- Implementation of the Landscape module project "Landis_Landscapes" location "Landscapes" kind "SharedLib" targetname "Landis.Landscapes" files { "Landscapes/**.cs", "SharedAssemblyInfo.cs" } links { "System", "Landis_SpatialModeling" } -- Data types shared by Raster I/O implementations project "Landis_RasterIO" location "RasterIO" kind "SharedLib" targetname "Landis.RasterIO" files { "RasterIO/**.cs", "SharedAssemblyInfo.cs" } links { "System", "Landis_SpatialModeling", } -- Implementation of the Raster I/O module using GDAL project "Landis_RasterIO_Gdal" location "RasterIO.Gdal" kind "SharedLib" targetname "Landis.RasterIO.Gdal" files { "RasterIO.Gdal/**.cs", "SharedAssemblyInfo.cs" } links { "System", "Landis_SpatialModeling", "Landis_RasterIO", "../external/gdal/libs/managed/gdal_csharp.dll" }
Removed the --gdal-dir option from Premake script because the location of the GDAL C# bindings is now a fixed relative path within the project.
Removed the --gdal-dir option from Premake script because the location of the GDAL C# bindings is now a fixed relative path within the project.
Lua
apache-2.0
LANDIS-II-Foundation/Landis-Spatial-Modeling-Library
a8e8b7decbcebc42092f585c89da606841ad8dc9
src/websocket/sync.lua
src/websocket/sync.lua
local frame = require'websocket.frame' local handshake = require'websocket.handshake' local tools = require'websocket.tools' local tinsert = table.insert local tconcat = table.concat local receive = function(self) if self.state ~= 'OPEN' and not self.is_closing then return nil,nil,false,1006,'wrong state' end local first_opcode local frames local bytes = 3 local encoded = '' local clean = function(was_clean,code,reason) self.state = 'CLOSED' self:sock_close() if self.on_close then self:on_close() end return nil,nil,was_clean,code,reason or 'closed' end while true do local chunk,err = self:sock_receive(bytes) if err then return clean(false,1006,err) end encoded = encoded..chunk local decoded,fin,opcode,_,masked = frame.decode(encoded) if not self.is_server and masked then return clean(false,1006,'Websocket receive failed: frame was not masked') end if decoded then if opcode == frame.CLOSE then if not self.is_closing then local code,reason = frame.decode_close(decoded) -- echo code local msg = frame.encode_close(code) local encoded = frame.encode(msg,frame.CLOSE,not self.is_server) local n,err = self:sock_send(encoded) if n == #encoded then return clean(true,code,reason) else return clean(false,code,err) end else return decoded,opcode end end if not first_opcode then first_opcode = opcode end if not fin then if not frames then frames = {} elseif opcode ~= frame.CONTINUATION then return clean(false,1002,'protocol error') end bytes = 3 encoded = '' tinsert(frames,decoded) elseif not frames then return decoded,first_opcode else tinsert(frames,decoded) return tconcat(frames),first_opcode end else assert(type(fin) == 'number' and fin > 0) bytes = fin end end assert(false,'never reach here') end local send = function(self,data,opcode) if self.state ~= 'OPEN' then return nil,false,1006,'wrong state' end local encoded = frame.encode(data,opcode or frame.TEXT,not self.is_server) local n,err = self:sock_send(encoded) if n ~= #encoded then return nil,self:close(1006,err) end return true end local close = function(self,code,reason) if self.state ~= 'OPEN' then return false,1006,'wrong state' end if self.state == 'CLOSED' then return false,1006,'wrong state' end local msg = frame.encode_close(code or 1000,reason) local encoded = frame.encode(msg,frame.CLOSE,not self.is_server) local n,err = self:sock_send(encoded) local was_clean = false local code = 1005 local reason = '' if n == #encoded then self.is_closing = true local rmsg,opcode = self:receive() if rmsg and opcode == frame.CLOSE then code,reason = frame.decode_close(rmsg) was_clean = true end else reason = err end self:sock_close() if self.on_close then self:on_close() end self.state = 'CLOSED' return was_clean,code,reason or '' end local connect = function(self,ws_url,ws_protocol) if self.state ~= 'CLOSED' then return nil,'wrong state' end local protocol,host,port,uri = tools.parse_url(ws_url) if protocol ~= 'ws' then return nil,'bad protocol' end local _,err = self:sock_connect(host,port) if err then return nil,err end local key = tools.generate_key() local req = handshake.upgrade_request { key = key, host = host, port = port, protocols = {ws_protocol or ''}, uri = uri } local n,err = self:sock_send(req) if n ~= #req then return nil,err end local resp = {} repeat local line,err = self:sock_receive('*l') resp[#resp+1] = line if err then return nil,err end until line == '' local response = table.concat(resp,'\r\n') local headers = handshake.http_headers(response) local expected_accept = handshake.sec_websocket_accept(key) if headers['sec-websocket-accept'] ~= expected_accept then local msg = 'Websocket Handshake failed: Invalid Sec-Websocket-Accept (expected %s got %s)' return nil,msg:format(expected_accept,headers['sec-websocket-accept'] or 'nil') end self.state = 'OPEN' return true end local extend = function(obj) assert(obj.sock_connect) assert(obj.sock_send) assert(obj.sock_receive) assert(obj.sock_close) assert(not obj.is_server) assert(not obj.is_closing) assert(not obj.state) obj.state = 'CLOSED' obj.receive = receive obj.send = send obj.close = close obj.connect = connect return obj end return { extend = extend }
local frame = require'websocket.frame' local handshake = require'websocket.handshake' local tools = require'websocket.tools' local tinsert = table.insert local tconcat = table.concat local receive = function(self) if self.state ~= 'OPEN' and not self.is_closing then return nil,nil,false,1006,'wrong state' end local first_opcode local frames local bytes = 3 local encoded = '' local clean = function(was_clean,code,reason) self.state = 'CLOSED' self:sock_close() if self.on_close then self:on_close() end return nil,nil,was_clean,code,reason or 'closed' end while true do local chunk,err = self:sock_receive(bytes) if err then return clean(false,1006,err) end encoded = encoded..chunk local decoded,fin,opcode,_,masked = frame.decode(encoded) if not self.is_server and masked then return clean(false,1006,'Websocket receive failed: frame was not masked') end if decoded then if opcode == frame.CLOSE then if not self.is_closing then local code,reason = frame.decode_close(decoded) -- echo code local msg = frame.encode_close(code) local encoded = frame.encode(msg,frame.CLOSE,not self.is_server) local n,err = self:sock_send(encoded) if n == #encoded then return clean(true,code,reason) else return clean(false,code,err) end else return decoded,opcode end end if not first_opcode then first_opcode = opcode end if not fin then if not frames then frames = {} elseif opcode ~= frame.CONTINUATION then return clean(false,1002,'protocol error') end bytes = 3 encoded = '' tinsert(frames,decoded) elseif not frames then return decoded,first_opcode else tinsert(frames,decoded) return tconcat(frames),first_opcode end else assert(type(fin) == 'number' and fin > 0) bytes = fin end end assert(false,'never reach here') end local send = function(self,data,opcode) if self.state ~= 'OPEN' then return nil,false,1006,'wrong state' end local encoded = frame.encode(data,opcode or frame.TEXT,not self.is_server) local n,err = self:sock_send(encoded) if n ~= #encoded then return nil,self:close(1006,err) end return true end local close = function(self,code,reason) if self.state ~= 'OPEN' then return false,1006,'wrong state' end if self.state == 'CLOSED' then return false,1006,'wrong state' end local msg = frame.encode_close(code or 1000,reason) local encoded = frame.encode(msg,frame.CLOSE,not self.is_server) local n,err = self:sock_send(encoded) local was_clean = false local code = 1005 local reason = '' if n == #encoded then self.is_closing = true local rmsg,opcode = self:receive() if rmsg and opcode == frame.CLOSE then code,reason = frame.decode_close(rmsg) was_clean = true end else reason = err end self:sock_close() if self.on_close then self:on_close() end self.state = 'CLOSED' return was_clean,code,reason or '' end local connect = function(self,ws_url,ws_protocol) if self.state ~= 'CLOSED' then return nil,'wrong state' end local protocol,host,port,uri = tools.parse_url(ws_url) if protocol ~= 'ws' then return nil,'bad protocol' end local _,err = self:sock_connect(host,port) if err then return nil,err end local key = tools.generate_key() local req = handshake.upgrade_request { key = key, host = host, port = port, protocols = {ws_protocol or ''}, uri = uri } local n,err = self:sock_send(req) if n ~= #req then return nil,err end local resp = {} repeat local line,err = self:sock_receive('*l') resp[#resp+1] = line if err then return nil,err end until line == '' local response = table.concat(resp,'\r\n') local headers = handshake.http_headers(response) local expected_accept = handshake.sec_websocket_accept(key) if headers['sec-websocket-accept'] ~= expected_accept then local msg = 'Websocket Handshake failed: Invalid Sec-Websocket-Accept (expected %s got %s)' return nil,msg:format(expected_accept,headers['sec-websocket-accept'] or 'nil') end self.state = 'OPEN' return true end local extend = function(obj) assert(obj.sock_send) assert(obj.sock_receive) assert(obj.sock_close) assert(obj.is_closing == nil) assert(obj.receive == nil) assert(obj.send == nil) assert(obj.close == nil) assert(obj.connect == nil) if not obj.is_server then assert(obj.sock_connect) end if not obj.state then obj.state = 'CLOSED' end obj.receive = receive obj.send = send obj.close = close obj.connect = connect return obj end return { extend = extend }
Fix. sync works with copas server.
Fix. sync works with copas server.
Lua
mit
KSDaemon/lua-websockets,lipp/lua-websockets,OptimusLime/lua-websockets,lipp/lua-websockets,OptimusLime/lua-websockets,lipp/lua-websockets,enginix/lua-websockets,OptimusLime/lua-websockets,enginix/lua-websockets,KSDaemon/lua-websockets,enginix/lua-websockets,KSDaemon/lua-websockets
a1cffc6b109d5aeea0dbb70bfc216a7e891e45f0
src/sailor/db.lua
src/sailor/db.lua
-------------------------------------------------------------------------------- -- db.lua, v0.2: DB module for connecting and querying through LuaSQL -- This file is a part of Sailor project -- Copyright (c) 2014 Etiene Dalcol <dalcol@etiene.net> -- License: MIT -- http://sailorproject.org -------------------------------------------------------------------------------- local db = {env,con} local conf = require("conf.conf").db local luasql = require("luasql."..conf.driver) -- Creates the connection of the instance function db.connect() db.env = assert (luasql[conf.driver]()) db.con = assert (db.env:connect(conf.dbname,conf.user,conf.pass,conf.host)) end -- Closes the connection of the instance function db.close() db.con:close() db.env:close() end -- Runs a query -- @param query string: the query to be executed -- @return table: a cursor function db.query(query) local cur = assert(db.con:execute(query)) return cur end -- Escapes a string or a table (its values). Should be used before concatenating strings on a query. -- @param q string or table: the string or table to be escaped -- @return string or nil: if q is a string, returns the new escaped string. If q is a table -- it simply returns, since it already escaped the table's values function db.escape(q) if type(q) == "string" then q = db.con:escape(q) return q elseif type(q) == "table" then for k,v in pairs(q) do q[k] = db.con:escape(v) end return end return q end --- Runs two queries and returns the result of the second query. -- It is no longer in use. It was used by sailor.model to insert and obtain the last id. -- It is now replaced by query_insert but it's still a valid method that could be used again. -- @param q1 string: first query to be executed -- @param q2 string: second query to be executed -- return table: the result of the second execution --[[function db.query_query(q1,q2) local res local rows = assert(db.con:execute(q1)) if rows == 0 then res = 0 else res = assert(db.con:execute(q2)) end return res end]] --- Runs a query and returns the id of the last inserted row. Used for saving -- a model and obtaining the model id. -- @param query string: the query to be executed -- return number or string: the id of the last inserted row. function db.query_insert(query) assert(db.con:execute(query)) local id = db.con:getlastautoid() return id end return db
-------------------------------------------------------------------------------- -- db.lua, v0.2.1: DB module for connecting and querying through LuaSQL -- This file is a part of Sailor project -- Copyright (c) 2014 Etiene Dalcol <dalcol@etiene.net> -- License: MIT -- http://sailorproject.org -------------------------------------------------------------------------------- local db = {env,con} local conf = require("conf.conf").db local luasql = require("luasql."..conf.driver) -- Creates the connection of the instance function db.connect() db.env = assert (luasql[conf.driver]()) db.con = assert (db.env:connect(conf.dbname,conf.user,conf.pass,conf.host)) end -- Closes the connection of the instance function db.close() db.con:close() db.env:close() end -- Runs a query -- @param query string: the query to be executed -- @return table: a cursor function db.query(query) local cur = assert(db.con:execute(query)) return cur end -- Escapes a string or a table (its values). Should be used before concatenating strings on a query. -- @param q string or table: the string or table to be escaped -- @return string or nil: if q is a string, returns the new escaped string. If q is a table -- it simply returns, since it already escaped the table's values function db.escape(q) if type(q) == "string" then q = db.con:escape(q) return q elseif type(q) == "table" then for k,v in pairs(q) do q[k] = db.con:escape(v) end return end return q end --- Runs two queries and returns the result of the second query. -- It is no longer in use. It was used by sailor.model to insert and obtain the last id. -- It is now replaced by query_insert but it's still a valid method that could be used again. -- @param q1 string: first query to be executed -- @param q2 string: second query to be executed -- return table: the result of the second execution --[[function db.query_query(q1,q2) local res local rows = assert(db.con:execute(q1)) if rows == 0 then res = 0 else res = assert(db.con:execute(q2)) end return res end]] --- Runs a query and returns the id of the last inserted row. Used for saving -- a model and obtaining the model id. -- @param query string: the query to be executed -- return number or string: the id of the last inserted row. function db.query_insert(query) local id if conf.driver == "postgresql" then query = query .. "RETURNING uid; " id = assert(db.con:execute(query)) else query = query .. "; " assert(db.con:execute(query)) id = db.con:getlastautoid() end return id end return db
Fixing insert for postgresql
Fixing insert for postgresql
Lua
mit
ignacio/sailor,Etiene/sailor,felipedaragon/sailor,jeary/sailor,mpeterv/sailor,mpeterv/sailor,sailorproject/sailor,Etiene/sailor,noname007/sailor,hallison/sailor,felipedaragon/sailor,ignacio/sailor
98e75cc744855850214a4a52d5ef3d679a47a946
util/iterators.lua
util/iterators.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. -- --[[ Iterators ]]-- local it = {}; -- Reverse an iterator function it.reverse(f, s, var) local results = {}; -- First call the normal iterator while true do local ret = { f(s, var) }; var = ret[1]; if var == nil then break; end table.insert(results, 1, ret); end -- Then return our reverse one local i,max = 0, #results; return function (results) if i<max then i = i + 1; return unpack(results[i]); end end, results; end -- Iterate only over keys in a table local function _keys_it(t, key) return (next(t, key)); end function it.keys(t) return _keys_it, t; end -- Iterate only over values in a table function it.values(t) local key, val; return function (t) key, val = next(t, key); return val; end, t; end -- Given an iterator, iterate only over unique items function it.unique(f, s, var) local set = {}; return function () while true do local ret = { f(s, var) }; var = ret[1]; if var == nil then break; end if not set[var] then set[var] = true; return var; end end end; end --[[ Return the number of items an iterator returns ]]-- function it.count(f, s, var) local x = 0; while true do local ret = { f(s, var) }; var = ret[1]; if var == nil then break; end x = x + 1; end return x; end -- Return the first n items an iterator returns function it.head(n, f, s, var) local c = 0; return function (s, var) if c >= n then return nil; end c = c + 1; return f(s, var); end, s; end -- Skip the first n items an iterator returns function it.skip(n, f, s, var) for i=1,n do var = f(s, var); end return f, s, var; end -- Return the last n items an iterator returns function it.tail(n, f, s, var) local results, count = {}, 0; while true do local ret = { f(s, var) }; var = ret[1]; if var == nil then break; end results[(count%n)+1] = ret; count = count + 1; end if n > count then n = count; end local pos = 0; return function () pos = pos + 1; if pos > n then return nil; end return unpack(results[((count-1+pos)%n)+1]); end --return reverse(head(n, reverse(f, s, var))); end local function _ripairs_iter(t, key) if key > 1 then return key-1, t[key-1]; end end function it.ripairs(t) return _ripairs_iter, t, #t+1; end local function _range_iter(max, curr) if curr < max then return curr + 1; end end function it.range(x, y) if not y then x, y = 1, x; end -- Default to 1..x if y not given return _range_iter, y, x-1; end -- Convert the values returned by an iterator to an array function it.to_array(f, s, var) local t, var = {}; while true do var = f(s, var); if var == nil then break; end table.insert(t, var); end return t; end -- Treat the return of an iterator as key,value pairs, -- and build a table function it.to_table(f, s, var) local t, var2 = {}; while true do var, var2 = f(s, var); if var == nil then break; end t[var] = var2; end return t; end return it;
-- 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. -- --[[ Iterators ]]-- local it = {}; local t_insert = table.insert; local select, unpack, next = select, unpack, next; local function pack(...) return { n = select("#", ...), ... }; end -- Reverse an iterator function it.reverse(f, s, var) local results = {}; -- First call the normal iterator while true do local ret = { f(s, var) }; var = ret[1]; if var == nil then break; end t_insert(results, 1, ret); end -- Then return our reverse one local i,max = 0, #results; return function (results) if i<max then i = i + 1; return unpack(results[i]); end end, results; end -- Iterate only over keys in a table local function _keys_it(t, key) return (next(t, key)); end function it.keys(t) return _keys_it, t; end -- Iterate only over values in a table function it.values(t) local key, val; return function (t) key, val = next(t, key); return val; end, t; end -- Given an iterator, iterate only over unique items function it.unique(f, s, var) local set = {}; return function () while true do local ret = pack(f(s, var)); var = ret[1]; if var == nil then break; end if not set[var] then set[var] = true; return unpack(ret, 1, ret.n); end end end; end --[[ Return the number of items an iterator returns ]]-- function it.count(f, s, var) local x = 0; while true do local var = f(s, var); if var == nil then break; end x = x + 1; end return x; end -- Return the first n items an iterator returns function it.head(n, f, s, var) local c = 0; return function (s, var) if c >= n then return nil; end c = c + 1; return f(s, var); end, s; end -- Skip the first n items an iterator returns function it.skip(n, f, s, var) for i=1,n do var = f(s, var); end return f, s, var; end -- Return the last n items an iterator returns function it.tail(n, f, s, var) local results, count = {}, 0; while true do local ret = pack(f(s, var)); var = ret[1]; if var == nil then break; end results[(count%n)+1] = ret; count = count + 1; end if n > count then n = count; end local pos = 0; return function () pos = pos + 1; if pos > n then return nil; end local ret = results[((count-1+pos)%n)+1]; return unpack(ret, 1, ret.n); end --return reverse(head(n, reverse(f, s, var))); end local function _ripairs_iter(t, key) if key > 1 then return key-1, t[key-1]; end end function it.ripairs(t) return _ripairs_iter, t, #t+1; end local function _range_iter(max, curr) if curr < max then return curr + 1; end end function it.range(x, y) if not y then x, y = 1, x; end -- Default to 1..x if y not given return _range_iter, y, x-1; end -- Convert the values returned by an iterator to an array function it.to_array(f, s, var) local t, var = {}; while true do var = f(s, var); if var == nil then break; end t_insert(t, var); end return t; end -- Treat the return of an iterator as key,value pairs, -- and build a table function it.to_table(f, s, var) local t, var2 = {}; while true do var, var2 = f(s, var); if var == nil then break; end t[var] = var2; end return t; end return it;
util.iterators: Various fixes and improvements, primarily use pack() where it should be used.
util.iterators: Various fixes and improvements, primarily use pack() where it should be used.
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
dfc74d598b825de786531daf7d39bc5359b3432e
home/config/nvim/lua/plugins/lightspeed.lua
home/config/nvim/lua/plugins/lightspeed.lua
local cmd = vim.cmd local nvim_set_keymap = vim.api.nvim_set_keymap local opts = { silent = true } nvim_set_keymap('n', 'z', '<Plug>Lightspeed_s', opts) nvim_set_keymap('n', 'Z', '<Plug>Lightspeed_S', opts) nvim_set_keymap('v', 'z', '<Plug>Lightspeed_s', opts) nvim_set_keymap('v', 'Z', '<Plug>Lightspeed_S', opts) nvim_set_keymap('x', 'z', '<Plug>Lightspeed_x', opts) nvim_set_keymap('x', 'Z', '<Plug>Lightspeed_X', opts) vim.api.nvim_set_keymap('n', ';', '<Plug>Lightspeed_;_ft', opts) vim.api.nvim_set_keymap('x', ';', '<Plug>Lightspeed_;_ft', opts) vim.api.nvim_set_keymap('n', ',', '<Plug>Lightspeed_,_ft', opts) vim.api.nvim_set_keymap('x', ',', '<Plug>Lightspeed_,_ft', opts) cmd('unmap s') cmd('unmap S')
local cmd = vim.cmd local nvim_set_keymap = vim.api.nvim_set_keymap local opts = { silent = true } nvim_set_keymap('n', 'z', '<Plug>Lightspeed_s', opts) nvim_set_keymap('n', 'Z', '<Plug>Lightspeed_S', opts) nvim_set_keymap('v', 'z', '<Plug>Lightspeed_s', opts) nvim_set_keymap('v', 'Z', '<Plug>Lightspeed_S', opts) nvim_set_keymap('x', 'z', '<Plug>Lightspeed_x', opts) nvim_set_keymap('x', 'Z', '<Plug>Lightspeed_X', opts) vim.api.nvim_set_keymap('n', ';', '<Plug>Lightspeed_;_ft', opts) vim.api.nvim_set_keymap('x', ';', '<Plug>Lightspeed_;_ft', opts) vim.api.nvim_set_keymap('n', ',', '<Plug>Lightspeed_,_ft', opts) vim.api.nvim_set_keymap('x', ',', '<Plug>Lightspeed_,_ft', opts) -- Lightseed is changing a lot. Sometimes these are needed, sometimes not. --cmd('unmap s') --cmd('unmap S')
nvim: fix lightspeed
nvim: fix lightspeed
Lua
unlicense
knpwrs/dotfiles,KenPowers/dotfiles
0290af9ae22499bfba02671475c581bf7f9ea206
UCDinteriors/server.lua
UCDinteriors/server.lua
function foo(markerNumber, type_, entryOrExit) if (client and markerNumber and type_) then local goto = interiors[type_][markerNumber] if (entryOrExit == "exit") then client.position = Vector3(goto.entryX, goto.entryY, goto.entryZ) client.dimension = 0 client.interior = 0 elseif (entryOrExit == "entry") then client.position = Vector3(goto.exitX, goto.exitY, goto.exitZ) client.dimension = goto.dimension client.interior = goto.interior end end end addEvent("UCDinteriors.warp", true) addEventHandler("UCDinteriors.warp", root, foo)
function foo(markerNumber, type_, entryOrExit) if (client and markerNumber and type_) then local goto = interiors[type_][markerNumber] if (entryOrExit == "exit") then client.dimension = 0 client.interior = 0 client.position = Vector3(goto.entryX, goto.entryY, goto.entryZ) elseif (entryOrExit == "entry") then client.position = Vector3(goto.exitX, goto.exitY, goto.exitZ) client.dimension = goto.dimension client.interior = goto.interior end end end addEvent("UCDinteriors.warp", true) addEventHandler("UCDinteriors.warp", root, foo)
UCDinteriors
UCDinteriors - Fixed not recognising you entered LV when leaving an interior into LV.
Lua
mit
nokizorque/ucd,nokizorque/ucd
26c00558e534808ccbd5f06f63239dcf2ff8f1d2
Interface/AddOns/RayUI/modules/infobar/infobar.lua
Interface/AddOns/RayUI/modules/infobar/infobar.lua
local R, L, P = unpack(select(2, ...)) --Import: Engine, Locales, ProfileDB, local local IF = R:NewModule("InfoBar", "AceEvent-3.0", "AceHook-3.0", "AceConsole-3.0", "AceTimer-3.0") local bars = {} IF.InfoBarStatusColor = {{1, 0, 0}, {1, 1, 0}, {0, 0.4, 1}} local height = 15 local speed = 135 function IF:CreateInfoPanel(name, width) local panel = CreateFrame("Frame", name, RayUI_BottomInfoBar) panel:SetSize(width, height - 1) panel.Text = panel:CreateFontString(nil, "OVERLAY") panel.Text:SetJustifyH("LEFT") panel.Text:SetJustifyV("CENTER") panel.Text:SetFont(R["media"].font, R["media"].fontsize - 1, R["media"].fontflag) panel.Text:Point("LEFT", panel, "LEFT", 13, 0) panel.Text:SetShadowColor(0, 0, 0, 0.4) panel.Text:SetShadowOffset(R.mult, -R.mult) local r, g, b = unpack(RayUF.colors.class[R.myclass]) panel.Indicator = panel:CreateTexture(nil, "OVERLAY") panel.Indicator:SetAllPoints() panel.Indicator:SetTexture("Interface\\AddOns\\RayUI\\media\\threat") panel.Indicator:SetBlendMode("ADD") panel.Indicator:SetVertexColor(r, g, b, .6) panel.Indicator:Hide() panel.Square = panel:CreateTexture(nil, "OVERLAY") panel.Square:SetTexture(R.media.blank) panel.Square:SetVertexColor(unpack(IF.InfoBarStatusColor[3])) panel.Square:Point("LEFT", 5, 0) panel.Square:Size(5, 5) panel.Square.Bg = panel:CreateTexture(nil, "BORDER") panel.Square.Bg:SetTexture(0, 0, 0) panel.Square.Bg:Point("LEFT", 4, 0) panel.Square.Bg:Size(7, 7) panel:SetScript("OnEnter", function(self) if not IF.db.autoHide then return end IF:CancelTimer(IF.Anim) self.Indicator:Show() end) panel:SetScript("OnLeave", function(self) if not IF.db.autoHide then return end self.Indicator:Hide() IF:ReadyToSlideDown() end) return panel end function IF:ReadyToSlideDown() if not self.db.autoHide then return end self:CancelTimer(self.Anim) self.Anim = self:ScheduleTimer("SlideDown", 3) end function IF:SlideDown() local bottom = tonumber(R:Round(RayUI_BottomInfoBar:GetBottom())) if bottom <= -height then return end RayUI_BottomInfoBar:SetPoint("BOTTOM", UIParent, "BOTTOM", 0, 0) R:Slide(RayUI_BottomInfoBar, "DOWN", height, speed) end function IF:SlideUp() local bottom = tonumber(R:Round(RayUI_BottomInfoBar:GetBottom())) if bottom >= 0 then return end RayUI_BottomInfoBar:SetPoint("BOTTOM", UIParent, "BOTTOM", 0, -height) R:Slide(RayUI_BottomInfoBar, "UP", height, speed) end function IF:CheckAutoHide() if not self.db.autoHide then return end local x, y = GetCursorPosition() if y > height and self:TimeLeft(self.Anim) <= 0 then self:ReadyToSlideDown() end end function IF:Initialize() local menuFrame = CreateFrame("Frame", "RayUI_InfobarRightClickMenu", UIParent, "UIDropDownMenuTemplate") local menuList = { { text = L["自动隐藏信息条"], checked = function() return self.db.autoHide end, func = function() self.db.autoHide = not self.db.autoHide if not self.db.autoHide then self:CancelTimer(self.Anim) self:SlideUp() else self:SlideDown() end end, }, } local bottombar = CreateFrame("Frame", "RayUI_BottomInfoBar", UIParent) bottombar:SetWidth(UIParent:GetWidth()) bottombar:SetHeight(height) bottombar:SetPoint("BOTTOM", UIParent, "BOTTOM", 0, 0) bottombar:CreateShadow("Background") local trigger = CreateFrame("Frame", nil, UIParent) trigger:SetPoint("BOTTOMLEFT", UIParent, "BOTTOMLEFT", 0, 0) trigger:SetPoint("TOPRIGHT", UIParent, "BOTTOMRIGHT", 0, 5) trigger:SetScript("OnEnter", function() self:SlideUp() self:CancelTimer(self.Anim) end) bottombar:SetScript("OnEnter", function() self:CancelTimer(self.Anim) end) bottombar:SetScript("OnLeave", function() self:ReadyToSlideDown() end) local function PopupMenu(_, btn) if btn=="RightButton" then EasyMenu(menuList, menuFrame, "cursor", 0, 50, "MENU", 1) end end bottombar:SetScript("OnMouseUp", PopupMenu) trigger:SetScript("OnMouseUp", PopupMenu) UIParent:HookScript("OnSizeChanged", function(self) bottombar:SetWidth(UIParent:GetWidth()) end) self.Anim = self:ScheduleTimer("SlideDown", 10) self:ScheduleRepeatingTimer("CheckAutoHide", 1) -- local RayUI_ExpBar = CreateFrame("Frame", "RayUI_ExpBar", UIParent) -- RayUI_ExpBar:CreateShadow("Background") -- RayUI_ExpBar:SetFrameStrata("BACKGROUND") -- RayUI_ExpBar:SetPoint("TOPLEFT", Minimap, "BOTTOMLEFT", 0, -5) -- RayUI_ExpBar:SetPoint("BOTTOMRIGHT", Minimap, "BOTTOMRIGHT", 0, -11) self:LoadInfoText() end R:RegisterModule(IF:GetName())
local R, L, P = unpack(select(2, ...)) --Import: Engine, Locales, ProfileDB, local local IF = R:NewModule("InfoBar", "AceEvent-3.0", "AceHook-3.0", "AceConsole-3.0", "AceTimer-3.0") local bars = {} IF.InfoBarStatusColor = {{1, 0, 0}, {1, 1, 0}, {0, 0.4, 1}} local height = 15 local speed = 135 function IF:CreateInfoPanel(name, width) local panel = CreateFrame("Frame", name, RayUI_BottomInfoBar) panel:SetSize(width, height - 1) panel.Text = panel:CreateFontString(nil, "OVERLAY") panel.Text:SetJustifyH("LEFT") panel.Text:SetJustifyV("CENTER") panel.Text:SetFont(R["media"].font, R["media"].fontsize - 1, R["media"].fontflag) panel.Text:Point("LEFT", panel, "LEFT", 13, 0) panel.Text:SetShadowColor(0, 0, 0, 0.4) panel.Text:SetShadowOffset(R.mult, -R.mult) local r, g, b = unpack(RayUF.colors.class[R.myclass]) panel.Indicator = panel:CreateTexture(nil, "OVERLAY") panel.Indicator:SetAllPoints() panel.Indicator:SetTexture("Interface\\AddOns\\RayUI\\media\\threat") panel.Indicator:SetBlendMode("ADD") panel.Indicator:SetVertexColor(r, g, b, .6) panel.Indicator:Hide() panel.Square = panel:CreateTexture(nil, "OVERLAY") panel.Square:SetTexture(R.media.blank) panel.Square:SetVertexColor(unpack(IF.InfoBarStatusColor[3])) panel.Square:Point("LEFT", 5, 0) panel.Square:Size(5, 5) panel.Square.Bg = panel:CreateTexture(nil, "BORDER") panel.Square.Bg:SetTexture(0, 0, 0) panel.Square.Bg:Point("LEFT", 4, 0) panel.Square.Bg:Size(7, 7) panel:SetScript("OnEnter", function(self) if not IF.db.autoHide then return end IF:CancelTimer(IF.Anim) self.Indicator:Show() end) panel:SetScript("OnLeave", function(self) if not IF.db.autoHide then return end self.Indicator:Hide() IF:ReadyToSlideDown() end) return panel end function IF:ReadyToSlideDown() if not self.db.autoHide then return end self:CancelTimer(self.Anim) self.Anim = self:ScheduleTimer("SlideDown", 3) end function IF:SlideDown() local bottom = tonumber(R:Round(RayUI_BottomInfoBar:GetBottom())) if bottom <= -height then return end RayUI_BottomInfoBar:SetPoint("BOTTOM", UIParent, "BOTTOM", 0, 0) R:Slide(RayUI_BottomInfoBar, "DOWN", height, speed) end function IF:SlideUp() local bottom = tonumber(R:Round(RayUI_BottomInfoBar:GetBottom())) if bottom >= 0 then return end RayUI_BottomInfoBar:SetPoint("BOTTOM", UIParent, "BOTTOM", 0, -height) R:Slide(RayUI_BottomInfoBar, "UP", height, speed) end function IF:CheckAutoHide() if not self.db.autoHide then return end local x, y = GetCursorPosition() if y > height and self:TimeLeft(self.Anim) <= 0 then self:ReadyToSlideDown() end end function IF:Initialize() local menuFrame = CreateFrame("Frame", "RayUI_InfobarRightClickMenu", UIParent, "UIDropDownMenuTemplate") local menuList = { { text = L["自动隐藏信息条"], checked = function() return self.db.autoHide end, func = function() self.db.autoHide = not self.db.autoHide if not self.db.autoHide then self:CancelTimer(self.Anim) self:SlideUp() else self:SlideDown() end end, }, } local bottombar = CreateFrame("Frame", "RayUI_BottomInfoBar", UIParent) bottombar:SetWidth(UIParent:GetWidth()) bottombar:SetHeight(height) bottombar:SetPoint("BOTTOM", UIParent, "BOTTOM", 0, 0) bottombar:CreateShadow("Background") local trigger = CreateFrame("Frame", nil, UIParent) trigger:SetPoint("BOTTOMLEFT", UIParent, "BOTTOMLEFT", 0, 0) trigger:SetPoint("TOPRIGHT", UIParent, "BOTTOMRIGHT", 0, 5) trigger:SetScript("OnEnter", function() self:SlideUp() self:CancelTimer(self.Anim) end) bottombar:SetScript("OnEnter", function() self:CancelTimer(self.Anim) end) bottombar:SetScript("OnLeave", function() self:ReadyToSlideDown() end) local function PopupMenu(_, btn) if btn=="RightButton" then EasyMenu(menuList, menuFrame, "cursor", 0, 50, "MENU", 1) end end bottombar:SetScript("OnMouseUp", PopupMenu) trigger:SetScript("OnMouseUp", PopupMenu) UIParent:HookScript("OnSizeChanged", function(self) bottombar:SetWidth(UIParent:GetWidth()) end) if self.db.autoHide then self.Anim = self:ScheduleTimer("SlideDown", 10) end self:ScheduleRepeatingTimer("CheckAutoHide", 1) self:LoadInfoText() end R:RegisterModule(IF:GetName())
一处自动隐藏bug
一处自动隐藏bug
Lua
mit
fgprodigal/RayUI
43145fdaede79cac437e95a0b2201f5b4f780c88
lua_scripts/pathmaps/simple/00_default.lua
lua_scripts/pathmaps/simple/00_default.lua
-- Copyright (C) 2007 Lauri Leukkunen <lle@rahina.org> -- Licensed under MIT license. -- -- "simple" mode, to be used for software development & building -- (as the name says, this is the simple solution; See/use the "devel" -- mode when a more full-featured environment is needed) -- Rule file interface version, mandatory. -- rule_file_interface_version = "24" ---------------------------------- tools = tools_root if (not tools) then tools = "/" end simple_chain = { next_chain = nil, binary = nil, rules = { -- ----------------------------------------------- -- 1. The session directory {dir = session_dir, use_orig_path = true}, -- ----------------------------------------------- -- 2. Development environment special destinations: {prefix = "/sb2/wrappers", replace_by = sbox_dir.."/share/scratchbox2/wrappers", readonly = true}, {prefix = "/sb2/scripts", replace_by = sbox_dir.."/share/scratchbox2/scripts", readonly = true}, {prefix = sbox_user_home_dir, use_orig_path = true}, {prefix = sbox_dir .. "/share/scratchbox2", use_orig_path = true}, {path = "/usr/bin/sb2-show", use_orig_path = true, readonly = true}, -- ----------------------------------------------- -- 99. Other rules. {prefix = "/usr/lib/perl", map_to = tools}, {prefix = "/usr/lib/gcc", map_to = tools}, {prefix = "/usr/lib/git-core", use_orig_path = true, readonly = true}, {prefix = "/usr/lib", map_to = target_root}, {prefix = "/usr/include", map_to = target_root}, {prefix = "/home/user", map_to = target_root}, {prefix = "/home", use_orig_path = true}, {prefix = "/host_usr", map_to = target_root}, {prefix = "/tmp", use_orig_path = true}, {prefix = "/dev", use_orig_path = true}, {prefix = "/proc", custom_map_funct = sb2_procfs_mapper, virtual_path = true}, {prefix = "/sys", use_orig_path = true}, -- -- Following 3 rules are needed because package -- "resolvconf" makes resolv.conf to be symlink that -- points to /etc/resolvconf/run/resolv.conf and -- we want them all to come from host. -- {prefix = "/var/run/resolvconf", force_orig_path = true, readonly = true}, {prefix = "/etc/resolvconf", force_orig_path = true, readonly = true}, {prefix = "/etc/resolv.conf", force_orig_path = true, readonly = true}, {prefix = "/lib", map_to = target_root}, -- {prefix = tools, use_orig_path = true}, {path = "/", use_orig_path = true}, {prefix = "/", map_to = tools} } } qemu_chain = { next_chain = nil, binary = basename(sbox_cputransparency_method), rules = { {prefix = "/usr/lib", map_to = target_root}, {prefix = "/usr/local/lib", map_to = target_root}, {prefix = "/tmp", use_orig_path = true}, {prefix = "/dev", use_orig_path = true}, {dir = "/proc", custom_map_funct = sb2_procfs_mapper, virtual_path = true}, {prefix = "/sys", use_orig_path = true}, -- -- Following 3 rules are needed because package -- "resolvconf" makes resolv.conf to be symlink that -- points to /etc/resolvconf/run/resolv.conf and -- we want them all to come from host. -- {prefix = "/var/run/resolvconf", force_orig_path = true, readonly = true}, {prefix = "/etc/resolvconf", force_orig_path = true, readonly = true}, {prefix = "/etc/resolv.conf", force_orig_path = true, readonly = true}, {prefix = "/lib", map_to = target_root}, -- {prefix = tools, use_orig_path = true}, {path = "/", use_orig_path = true}, {prefix = "/", map_to = tools} } } export_chains = { qemu_chain, simple_chain } -- Exec policy rules. -- If the permission token exists and contains "root", -- use fakeroot local fakeroot_ld_preload = "" if sb.get_session_perm() == "root" then fakeroot_ld_preload = ":"..host_ld_preload_fakeroot end default_exec_policy = { name = "Default", native_app_ld_preload_prefix = host_ld_preload..fakeroot_ld_preload, native_app_ld_library_path_prefix = host_ld_library_path_libfakeroot .. host_ld_library_path_prefix .. host_ld_library_path_libsb2, native_app_ld_library_path_suffix = host_ld_library_path_suffix, } -- Note that the real path (mapped path) is used when looking up rules! all_exec_policies_chain = { next_chain = nil, binary = nil, rules = { -- DEFAULT RULE (must exist): {prefix = "/", exec_policy = default_exec_policy} } } exec_policy_chains = { all_exec_policies_chain } -- This table lists all exec policies - this is used when the current -- process wants to locate the currently active policy all_exec_policies = { default_exec_policy, }
-- Copyright (C) 2007 Lauri Leukkunen <lle@rahina.org> -- Licensed under MIT license. -- -- "simple" mode, to be used for software development & building -- (as the name says, this is the simple solution; See/use the "devel" -- mode when a more full-featured environment is needed) -- Rule file interface version, mandatory. -- rule_file_interface_version = "24" ---------------------------------- tools = tools_root if (not tools) then tools = "/" end simple_chain = { next_chain = nil, binary = nil, rules = { -- ----------------------------------------------- -- 1. The session directory {dir = session_dir, use_orig_path = true}, -- ----------------------------------------------- -- 2. Development environment special destinations: {prefix = "/sb2/wrappers", replace_by = sbox_dir.."/share/scratchbox2/wrappers", readonly = true}, {prefix = "/sb2/scripts", replace_by = sbox_dir.."/share/scratchbox2/scripts", readonly = true}, {prefix = sbox_user_home_dir, use_orig_path = true}, {prefix = sbox_dir .. "/share/scratchbox2", use_orig_path = true}, {path = "/usr/bin/sb2-show", use_orig_path = true, readonly = true}, -- ----------------------------------------------- -- 99. Other rules. {prefix = "/usr/share/python", use_orig_path = true, readonly = true}, {prefix = "/usr/share/pyshared", use_orig_path = true, readonly = true}, {prefix = "/usr/lib/pymodules", use_orig_path = true, readonly = true}, {prefix = "/usr/lib/pyshared", use_orig_path = true, readonly = true}, {prefix = "/usr/lib/python", use_orig_path = true, readonly = true}, {prefix = "/usr/lib/perl", map_to = tools}, {prefix = "/usr/lib/gcc", map_to = tools}, {prefix = "/usr/lib/git-core", use_orig_path = true, readonly = true}, {prefix = "/usr/lib", map_to = target_root}, {prefix = "/usr/include", map_to = target_root}, {prefix = "/home/user", map_to = target_root}, {prefix = "/home", use_orig_path = true}, {prefix = "/host_usr", map_to = target_root}, {prefix = "/tmp", use_orig_path = true}, {prefix = "/dev", use_orig_path = true}, {prefix = "/proc", custom_map_funct = sb2_procfs_mapper, virtual_path = true}, {prefix = "/sys", use_orig_path = true}, -- -- Following 3 rules are needed because package -- "resolvconf" makes resolv.conf to be symlink that -- points to /etc/resolvconf/run/resolv.conf and -- we want them all to come from host. -- {prefix = "/var/run/resolvconf", force_orig_path = true, readonly = true}, {prefix = "/etc/resolvconf", force_orig_path = true, readonly = true}, {prefix = "/etc/resolv.conf", force_orig_path = true, readonly = true}, {prefix = "/lib", map_to = target_root}, -- {prefix = tools, use_orig_path = true}, {path = "/", use_orig_path = true}, {prefix = "/", map_to = tools} } } qemu_chain = { next_chain = nil, binary = basename(sbox_cputransparency_method), rules = { {prefix = "/usr/lib", map_to = target_root}, {prefix = "/usr/local/lib", map_to = target_root}, {prefix = "/tmp", use_orig_path = true}, {prefix = "/dev", use_orig_path = true}, {dir = "/proc", custom_map_funct = sb2_procfs_mapper, virtual_path = true}, {prefix = "/sys", use_orig_path = true}, -- -- Following 3 rules are needed because package -- "resolvconf" makes resolv.conf to be symlink that -- points to /etc/resolvconf/run/resolv.conf and -- we want them all to come from host. -- {prefix = "/var/run/resolvconf", force_orig_path = true, readonly = true}, {prefix = "/etc/resolvconf", force_orig_path = true, readonly = true}, {prefix = "/etc/resolv.conf", force_orig_path = true, readonly = true}, {prefix = "/lib", map_to = target_root}, -- {prefix = tools, use_orig_path = true}, {path = "/", use_orig_path = true}, {prefix = "/", map_to = tools} } } export_chains = { qemu_chain, simple_chain } -- Exec policy rules. -- If the permission token exists and contains "root", -- use fakeroot local fakeroot_ld_preload = "" if sb.get_session_perm() == "root" then fakeroot_ld_preload = ":"..host_ld_preload_fakeroot end default_exec_policy = { name = "Default", native_app_ld_preload_prefix = host_ld_preload..fakeroot_ld_preload, native_app_ld_library_path_prefix = host_ld_library_path_libfakeroot .. host_ld_library_path_prefix .. host_ld_library_path_libsb2, native_app_ld_library_path_suffix = host_ld_library_path_suffix, } -- Note that the real path (mapped path) is used when looking up rules! all_exec_policies_chain = { next_chain = nil, binary = nil, rules = { -- DEFAULT RULE (must exist): {prefix = "/", exec_policy = default_exec_policy} } } exec_policy_chains = { all_exec_policies_chain } -- This table lists all exec policies - this is used when the current -- process wants to locate the currently active policy all_exec_policies = { default_exec_policy, }
fix to make python work
fix to make python work otherwise I get: 'import site' failed; use -v for traceback Signed-off-by: Lauri Aarnio <18c97056964064acc79deb3ed7547e2c4d053843@iki.fi>
Lua
lgpl-2.1
lbt/scratchbox2,OlegGirko/ldbox,madscientist42/scratchbox2,OlegGirko/ldbox,h113331pp/scratchbox2,h113331pp/scratchbox2,ldbox/ldbox,lbt/scratchbox2,OlegGirko/ldbox,loganchien/scratchbox2,lbt/scratchbox2,loganchien/scratchbox2,OlegGirko/ldbox,BinChengfei/scratchbox2,OlegGirko/ldbox,BinChengfei/scratchbox2,madscientist42/scratchbox2,madscientist42/scratchbox2,BinChengfei/scratchbox2,h113331pp/scratchbox2,madscientist42/scratchbox2,BinChengfei/scratchbox2,BinChengfei/scratchbox2,h113331pp/scratchbox2,loganchien/scratchbox2,loganchien/scratchbox2,ldbox/ldbox,lbt/scratchbox2,loganchien/scratchbox2,loganchien/scratchbox2,ldbox/ldbox,BinChengfei/scratchbox2,ldbox/ldbox,madscientist42/scratchbox2,h113331pp/scratchbox2,lbt/scratchbox2,madscientist42/scratchbox2,ldbox/ldbox,OlegGirko/ldbox,h113331pp/scratchbox2,ldbox/ldbox
0bb5bfc6355ad9db87e7d51e7b02da404afc55b6
src/blackjackgame.lua
src/blackjackgame.lua
local Gamestate = require 'vendor/gamestate' local anim8 = require 'vendor/anim8' local window = require 'window' local Prompt = require 'prompt' local camera = require 'camera' local state = Gamestate.new() function state:init() self.table = love.graphics.newImage( 'images/card_table.png' ) self.cardSprite = love.graphics.newImage('images/cards.png' ) self.chipSprite = love.graphics.newImage('images/chips.png' ) self.card = { ace = 1, two = 2, three = 3, four = 4, five = 5, six = 6, seven = 7, eight = 8, nine = 9, ten = 10, jack = 11, queen = 12, king = 13 } self.suit = { spade = 1, club = 2, heart = 3, diamond = 4 } self.center = {} self.center.x = ( window.width / 2 ) self.center.y = ( window.height / 2 ) self.frame = -100 end function state:update(dt) if self.prompt then self.prompt:update(dt) end self.frame = self.frame + 2 if self.frame >= 200 then self.frame = -50 end end function state:enter(previous, screenshot) self.music = love.audio.play("audio/daybreak.ogg", "stream", true) self.previous = previous self.screenshot = screenshot camera:setPosition( 100, 100 ) end function state:draw() if self.screenshot then love.graphics.draw( self.screenshot, 0, 0, 0, 0.5, 0.5 ) else love.graphics.setColor( 0, 0, 0, 255 ) love.graphics.rectangle( 'fill', 0, 0, love.graphics:getWidth(), love.graphics:getHeight() ) love.graphics.setColor( 255, 255, 255, 255 ) end love.graphics.draw( self.table, self.center.x - ( self.table:getWidth() / 2 ), self.center.y - ( self.table:getHeight() / 2 ) ) -- dealers stack local frame = self.frame if frame < 0 then frame = 0 end if frame > 100 then frame = 100 end self:drawCard( self.card.ace, self.suit.diamond, frame, map( frame, 0, 100, 300, 300 ), 40 ) self:drawCard( self.card.ace, self.suit.diamond, frame, map( frame, 0, 100, 60, 120 ), 40 ) self:drawCard( self.card.jack, self.suit.club, frame, map( frame, 0, 100, 300, 120 ), 100 ) self:drawCard( self.card.five, self.suit.heart, frame, map( frame, 0, 100, 60, 300 ), 160 ) if self.prompt then self.prompt:draw( self.center.x, self.center.y ) end end function state:keypressed(key, player) if key == 'escape' then self.prompt = Prompt.new( 120, 55, "Are you sure you want to exit?", function(result) if result then Gamestate.switch(self.previous) end end ) end if self.prompt then self.prompt:keypressed(key) end end function state:drawCard( card, suit, flip, x, y ) -- flip is a number from 0 to 100, where 0 is completely face down, and 100 is completely face up local w = 38 -- card width local h = 55 -- card height local st = 0.2 -- stretched top local sh = h * ( 1 + st ) -- stretched height if flip > 50 then limit = 100 _card = love.graphics.newQuad( ( card - 1 ) * w, ( suit - 1 ) * h, w, h, self.cardSprite:getWidth(), self.cardSprite:getHeight() ) else limit = 0 _card = love.graphics.newQuad( 0, h * 4, w, h, self.cardSprite:getWidth(), self.cardSprite:getHeight() ) end darkness = map( flip, 50, limit, 0, 250 ) love.graphics.setColor( darkness, darkness, darkness ) love.graphics.drawq( self.cardSprite, _card, -- image, quad x + map( flip, 50, limit, w / 2, 0 ), -- offset for flip map( flip, 50, limit, y - ( ( sh - h ) / 2 ), y ), -- height offset 0, -- no rotation map( flip, 50, limit, 0, 1 ), -- scale width for flip map( flip, 50, limit , 1 + st, 1 ) -- scale height for flip ) love.graphics.setColor( 255, 255, 255, 255 ) end function map( x, in_min, in_max, out_min, out_max) return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; end return state
local Gamestate = require 'vendor/gamestate' local anim8 = require 'vendor/anim8' local window = require 'window' local Prompt = require 'prompt' local camera = require 'camera' local state = Gamestate.new() function state:init() self.table = love.graphics.newImage( 'images/card_table.png' ) self.cardSprite = love.graphics.newImage('images/cards.png' ) self.chipSprite = love.graphics.newImage('images/chips.png' ) self.card = { ace = 1, two = 2, three = 3, four = 4, five = 5, six = 6, seven = 7, eight = 8, nine = 9, ten = 10, jack = 11, queen = 12, king = 13 } self.suit = { spade = 1, club = 2, heart = 3, diamond = 4 } self.center = {} self.center.x = ( window.width / 2 ) self.center.y = ( window.height / 2 ) self.frame = -100 end function state:update(dt) if self.prompt then self.prompt:update(dt) end self.frame = self.frame + 2 if self.frame >= 200 then self.frame = -50 end end function state:enter(previous, screenshot) self.music = love.audio.play("audio/daybreak.ogg", "stream", true) self.previous = previous self.screenshot = screenshot self.camera_x = camera.x camera.max.x = 0 camera:setPosition( 0, 0 ) end function state:leave() camera.x = self.camera_x end function state:draw() if self.screenshot then love.graphics.draw( self.screenshot, 0, 0, 0, 0.5, 0.5 ) else love.graphics.setColor( 0, 0, 0, 255 ) love.graphics.rectangle( 'fill', 0, 0, love.graphics:getWidth(), love.graphics:getHeight() ) love.graphics.setColor( 255, 255, 255, 255 ) end love.graphics.draw( self.table, self.center.x - ( self.table:getWidth() / 2 ), self.center.y - ( self.table:getHeight() / 2 ) ) -- dealers stack local frame = self.frame if frame < 0 then frame = 0 end if frame > 100 then frame = 100 end self:drawCard( self.card.ace, self.suit.diamond, frame, map( frame, 0, 100, 300, 300 ), 40 ) self:drawCard( self.card.ace, self.suit.diamond, frame, map( frame, 0, 100, 60, 120 ), 40 ) self:drawCard( self.card.jack, self.suit.club, frame, map( frame, 0, 100, 300, 120 ), 100 ) self:drawCard( self.card.five, self.suit.heart, frame, map( frame, 0, 100, 60, 300 ), 160 ) if self.prompt then self.prompt:draw( self.center.x, self.center.y ) end end function state:keypressed(key, player) if key == 'escape' then self.prompt = Prompt.new( 120, 55, "Are you sure you want to exit?", function(result) if result then Gamestate.switch(self.previous) end end ) end if self.prompt then self.prompt:keypressed(key) end end function state:drawCard( card, suit, flip, x, y ) -- flip is a number from 0 to 100, where 0 is completely face down, and 100 is completely face up local w = 38 -- card width local h = 55 -- card height local st = 0.2 -- stretched top local sh = h * ( 1 + st ) -- stretched height if flip > 50 then limit = 100 _card = love.graphics.newQuad( ( card - 1 ) * w, ( suit - 1 ) * h, w, h, self.cardSprite:getWidth(), self.cardSprite:getHeight() ) else limit = 0 _card = love.graphics.newQuad( 0, h * 4, w, h, self.cardSprite:getWidth(), self.cardSprite:getHeight() ) end darkness = map( flip, 50, limit, 0, 250 ) love.graphics.setColor( darkness, darkness, darkness ) love.graphics.drawq( self.cardSprite, _card, -- image, quad x + map( flip, 50, limit, w / 2, 0 ), -- offset for flip map( flip, 50, limit, y - ( ( sh - h ) / 2 ), y ), -- height offset 0, -- no rotation map( flip, 50, limit, 0, 1 ), -- scale width for flip map( flip, 50, limit , 1 + st, 1 ) -- scale height for flip ) love.graphics.setColor( 255, 255, 255, 255 ) end function map( x, in_min, in_max, out_min, out_max) return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; end return state
Fixed the pixel shift
Fixed the pixel shift
Lua
mit
hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua
f00316a42943a9a75303658f8d646d35f9e8d1b9
core/src/demo/xmake.lua
core/src/demo/xmake.lua
-- add target target("demo") -- add deps add_deps("xmake") -- make as a binary set_kind("binary") -- add defines add_defines("__tb_prefix__=\"xmake\"") -- set the object files directory set_objectdir("$(buildir)/.objs") -- add includes directory add_includedirs("$(projectdir)", "$(projectdir)/src") -- add the common source files add_files("**.c") -- add the resource files (it will be enabled after publishing new version) if is_plat("windows") then add_files("*.rc") end -- add links if is_plat("windows") then add_links("ws2_32", "advapi32", "shell32") add_ldflags("/export:malloc", "/export:free") elseif is_plat("android") then add_links("m", "c") elseif is_plat("macosx") then add_ldflags("-all_load", "-pagezero_size 10000", "-image_base 100000000") else add_links("pthread", "dl", "m", "c") end -- enable xp compatibility mode if is_plat("windows") then if is_arch("x86") then add_ldflags("/subsystem:console,5.01") else add_ldflags("/subsystem:console,5.02") end end -- copy target to the build directory after_build(function (target) os.cp(target:targetfile(), path.join(get_config("buildir"), path.filename(target:targetfile()))) end)
-- add target target("demo") -- add deps add_deps("xmake") -- make as a binary set_kind("binary") -- add defines add_defines("__tb_prefix__=\"xmake\"") -- set the object files directory set_objectdir("$(buildir)/.objs") -- add includes directory add_includedirs("$(projectdir)", "$(projectdir)/src") -- add the common source files add_files("**.c") -- add the resource files (it will be enabled after publishing new version) if is_plat("windows") then add_files("*.rc") end -- add links if is_plat("windows") then add_links("ws2_32", "advapi32", "shell32") add_ldflags("/export:malloc", "/export:free") elseif is_plat("android") then add_links("m", "c") elseif is_plat("macosx") then add_ldflags("-all_load", "-pagezero_size 10000", "-image_base 100000000") else add_links("pthread", "dl", "m", "c") end -- enable xp compatibility mode if is_plat("windows") then if is_arch("x86") then add_ldflags("/subsystem:console,5.01") else add_ldflags("/subsystem:console,5.02") end end -- copy target to the build directory after_build(function (target) os.cp(target:targetfile(), "$(buildir)/xmake" .. (is_plat("windows") and ".exe" or "")) end)
fix core xmake.lua again
fix core xmake.lua again
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
93419eee5fe987b5af0c2d6149ef0bcc45b47413
games/saloon/player.lua
games/saloon/player.lua
-- This is a simple class to represent the Player object in the game. You can extend it by adding utility functions here in this file. local class = require("joueur.utilities.class") local GameObject = require("games.saloon.gameObject") -- <<-- Creer-Merge: requires -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- you can add addtional require(s) here -- <<-- /Creer-Merge: requires -->> --- A player in this game. Every AI controls one player. -- @classmod Player local Player = class(GameObject) -- initializes a Player with basic logic as provided by the Creer code generator function Player:init(...) GameObject.init(self, ...) -- The following values should get overridden when delta states are merged, but we set them here as a reference for you to see what variables this class has. --- What type of client this is, e.g. 'Python', 'JavaScript', or some other language. For potential data mining purposes. self.clientType = "" --- Every Cowboy owned by this Player. self.cowboys = Table() --- How many enemy Cowboys this player's team has killed. self.kills = 0 --- If the player lost the game or not. self.lost = false --- The name of the player. self.name = "Anonymous" --- This player's opponent in the game. self.opponent = nil --- The reason why the player lost the game. self.reasonLost = "" --- The reason why the player won the game. self.reasonWon = "" --- How rowdy their team is. When it gets too high their team takes a collective siesta. self.rowdyness = 0 --- How many times their team has played a piano. self.score = 0 --- The amount of time (in ns) remaining for this AI to send commands. self.timeRemaining = 0 --- If the player won the game or not. self.won = false --- (inherited) String representing the top level Class that this game object is an instance of. Used for reflection to create new instances on clients, but exposed for convenience should AIs want this data. -- @field[string] self.gameObjectName -- @see GameObject.gameObjectName --- (inherited) A unique id for each instance of a GameObject or a sub class. Used for client and server communication. Should never change value after being set. -- @field[string] self.id -- @see GameObject.id --- (inherited) Any strings logged will be stored here. Intended for debugging. -- @field[{string, ...}] self.logs -- @see GameObject.logs end --- The Cowboy that was previously a 'Young Gun', and has now been promoted to a different job if successful, null otherwise. function Player:returns() return (self:_runOnServer("returns", { })) end --- Sends in the Young Gun to the nearest Tile into the Saloon, and promotes them to a new job. -- @tparam string job The job you want the Young Gun being brought in to be called in to do, changing their job to it. function Player:sendIn(job) return (self:_runOnServer("sendIn", { job = job, })) end --- (inherited) Adds a message to this GameObject's logs. Intended for your own debugging purposes, as strings stored here are saved in the gamelog. -- @function Player:log -- @see GameObject:log -- @tparam string message A string to add to this GameObject's log. Intended for debugging. -- <<-- Creer-Merge: functions -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- if you want to add any client side logic (such as state checking functions) this is where you can add them -- <<-- /Creer-Merge: functions -->> return Player
-- This is a simple class to represent the Player object in the game. You can extend it by adding utility functions here in this file. local class = require("joueur.utilities.class") local GameObject = require("games.saloon.gameObject") -- <<-- Creer-Merge: requires -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- you can add addtional require(s) here -- <<-- /Creer-Merge: requires -->> --- A player in this game. Every AI controls one player. -- @classmod Player local Player = class(GameObject) -- initializes a Player with basic logic as provided by the Creer code generator function Player:init(...) GameObject.init(self, ...) -- The following values should get overridden when delta states are merged, but we set them here as a reference for you to see what variables this class has. --- What type of client this is, e.g. 'Python', 'JavaScript', or some other language. For potential data mining purposes. self.clientType = "" --- Every Cowboy owned by this Player. self.cowboys = Table() --- How many enemy Cowboys this player's team has killed. self.kills = 0 --- If the player lost the game or not. self.lost = false --- The name of the player. self.name = "Anonymous" --- This player's opponent in the game. self.opponent = nil --- The reason why the player lost the game. self.reasonLost = "" --- The reason why the player won the game. self.reasonWon = "" --- How rowdy their team is. When it gets too high their team takes a collective siesta. self.rowdyness = 0 --- How many times their team has played a piano. self.score = 0 --- The amount of time (in ns) remaining for this AI to send commands. self.timeRemaining = 0 --- If the player won the game or not. self.won = false --- (inherited) String representing the top level Class that this game object is an instance of. Used for reflection to create new instances on clients, but exposed for convenience should AIs want this data. -- @field[string] self.gameObjectName -- @see GameObject.gameObjectName --- (inherited) A unique id for each instance of a GameObject or a sub class. Used for client and server communication. Should never change value after being set. -- @field[string] self.id -- @see GameObject.id --- (inherited) Any strings logged will be stored here. Intended for debugging. -- @field[{string, ...}] self.logs -- @see GameObject.logs end --- Sends in the Young Gun to the nearest Tile into the Saloon, and promotes them to a new job. -- @tparam string job The job you want the Young Gun being brought in to be called in to do, changing their job to it. -- @treturn Cowboy The Cowboy that was previously a 'Young Gun', and has now been promoted to a different job if successful, null otherwise. function Player:sendIn(job) return (self:_runOnServer("sendIn", { job = job, })) end --- (inherited) Adds a message to this GameObject's logs. Intended for your own debugging purposes, as strings stored here are saved in the gamelog. -- @function Player:log -- @see GameObject:log -- @tparam string message A string to add to this GameObject's log. Intended for debugging. -- <<-- Creer-Merge: functions -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- if you want to add any client side logic (such as state checking functions) this is where you can add them -- <<-- /Creer-Merge: functions -->> return Player
Re-ran creer with fixed Player.callIn()
Re-ran creer with fixed Player.callIn()
Lua
mit
siggame/Joueur.lua,JacobFischer/Joueur.lua,siggame/Joueur.lua
9033c5cdd96ad64c345191fd653a75248b6dc2e7
service/multicastd.lua
service/multicastd.lua
local skynet = require "skynet" local mc = require "multicast.c" local datacenter = require "datacenter" local harbor_id = skynet.harbor(skynet.self()) local command = {} local channel = {} local channel_n = {} local channel_remote = {} local channel_id = harbor_id local NORET = {} local function get_address(t, id) local v = assert(datacenter.get("multicast", id)) t[id] = v return v end local node_address = setmetatable({}, { __index = get_address }) -- new LOCAL channel , The low 8bit is the same with harbor_id function command.NEW() while channel[channel_id] do channel_id = mc.nextid(channel_id) end channel[channel_id] = {} channel_n[channel_id] = 0 local ret = channel_id channel_id = mc.nextid(channel_id) return ret end -- MUST call by the owner node of channel, delete a remote channel function command.DELR(source, c) channel[c] = nil channel_n[c] = nil return NORET end -- delete a channel, if the channel is remote, forward the command to the owner node -- otherwise, delete the channel, and call all the remote node, DELR function command.DEL(source, c) local node = c % 256 if node ~= harbor_id then skynet.send(node_address[node], "lua", "DEL", c) return NORET end local remote = channel_remote[c] channel[c] = nil channel_n[c] = nil channel_remote[c] = nil for node in pairs(remote) do skynet.send(node_address[node], "lua", "DELR", c) end return NORET end -- forward multicast message to a node (channel id use the session field) local function remote_publish(node, channel, source, ...) skynet.redirect(node_address[node], source, "multicast", channel, ...) end -- publish a message, for local node, use the message pointer (call mc.bind to add the reference) -- for remote node, call remote_publish. (call mc.unpack and skynet.tostring to convert message pointer to string) local function publish(c , source, pack, size) local group = channel[c] if group == nil then -- dead channel, delete the pack mc.bind(pack, 1) mc.close(pack) return end mc.bind(pack, channel_n[c]) local msg = skynet.tostring(pack, size) for k in pairs(group) do skynet.redirect(k, source, "multicast", c , msg) end local remote = channel_remote[c] if remote then local _, msg, sz = mc.unpack(pack, size) local msg = skynet.tostring(msg,sz) for node in pairs(remote) do remote_publish(node, c, source, msg) end end end skynet.register_protocol { name = "multicast", id = skynet.PTYPE_MULTICAST, unpack = function(msg, sz) return mc.packremote(msg, sz) end, dispatch = publish, } -- publish a message, if the caller is remote, forward the message to the owner node (by remote_publish) -- If the caller is local, call publish function command.PUB(source, c, pack, size) assert(skynet.harbor(source) == harbor_id) local node = c % 256 if node ~= harbor_id then -- remote publish remote_publish(node, c, source, mc.remote(pack)) else publish(c, source, pack,size) end end -- the node (source) subscribe a channel -- MUST call by channel owner node (assert source is not local and channel is create by self) -- If channel is not exist, return true -- Else set channel_remote[channel] true function command.SUBR(source, c) local node = skynet.harbor(source) if not channel[c] then -- channel none exist return true end assert(node ~= harbor_id and c % 256 == harbor_id) local group = channel_remote[c] if group == nil then group = {} channel_remote[c] = group end group[node] = true end -- the service (source) subscribe a channel -- If the channel is remote, node subscribe it by send a SUBR to the owner . function command.SUB(source, c) local node = c % 256 if node ~= harbor_id then -- remote group if channel[c] == nil then if skynet.call(node_address[node], "lua", "SUBR", c) then return end channel[c] = {} channel_n[c] = 0 end end local group = channel[c] if group and not group[source] then channel_n[c] = channel_n[c] + 1 group[source] = true end end -- MUST call by a node, unsubscribe a channel function command.USUBR(source, c) local node = skynet.harbor(source) assert(node ~= harbor_id) local group = assert(channel_remote[c]) group[node] = nil return NORET end -- Unsubscribe a channel, if the subscriber is empty and the channel is remote, send USUBR to the channel owner function command.USUB(source, c) local group = assert(channel[c]) if group[source] then group[source] = nil channel_n[c] = channel_n[c] - 1 if channel_n[c] == 0 then local node = c % 256 if node ~= harbor_id then -- remote group channel[c] = nil channel_n[c] = nil skynet.send(node_address[node], "lua", "USUBR", c) end end end return NORET end skynet.start(function() skynet.dispatch("lua", function(_,source, cmd, ...) local f = assert(command[cmd]) local result = f(source, ...) if result ~= NORET then skynet.ret(skynet.pack(result)) end end) local self = skynet.self() local id = skynet.harbor(self) assert(datacenter.set("multicast", id, self) == nil) end)
local skynet = require "skynet" local mc = require "multicast.c" local datacenter = require "datacenter" local harbor_id = skynet.harbor(skynet.self()) local command = {} local channel = {} local channel_n = {} local channel_remote = {} local channel_id = harbor_id local NORET = {} local function get_address(t, id) local v = assert(datacenter.get("multicast", id)) t[id] = v return v end local node_address = setmetatable({}, { __index = get_address }) -- new LOCAL channel , The low 8bit is the same with harbor_id function command.NEW() while channel[channel_id] do channel_id = mc.nextid(channel_id) end channel[channel_id] = {} channel_n[channel_id] = 0 local ret = channel_id channel_id = mc.nextid(channel_id) return ret end -- MUST call by the owner node of channel, delete a remote channel function command.DELR(source, c) channel[c] = nil channel_n[c] = nil return NORET end -- delete a channel, if the channel is remote, forward the command to the owner node -- otherwise, delete the channel, and call all the remote node, DELR function command.DEL(source, c) local node = c % 256 if node ~= harbor_id then skynet.send(node_address[node], "lua", "DEL", c) return NORET end local remote = channel_remote[c] channel[c] = nil channel_n[c] = nil channel_remote[c] = nil for node in pairs(remote) do skynet.send(node_address[node], "lua", "DELR", c) end return NORET end -- forward multicast message to a node (channel id use the session field) local function remote_publish(node, channel, source, ...) skynet.redirect(node_address[node], source, "multicast", channel, ...) end -- publish a message, for local node, use the message pointer (call mc.bind to add the reference) -- for remote node, call remote_publish. (call mc.unpack and skynet.tostring to convert message pointer to string) local function publish(c , source, pack, size) local group = channel[c] if group == nil then -- dead channel, delete the pack mc.bind(pack, 1) mc.close(pack) return end mc.bind(pack, channel_n[c]) local msg = skynet.tostring(pack, size) for k in pairs(group) do skynet.redirect(k, source, "multicast", c , msg) end local remote = channel_remote[c] if remote then local _, msg, sz = mc.unpack(pack, size) local msg = skynet.tostring(msg,sz) for node in pairs(remote) do remote_publish(node, c, source, msg) end end end skynet.register_protocol { name = "multicast", id = skynet.PTYPE_MULTICAST, unpack = function(msg, sz) return mc.packremote(msg, sz) end, dispatch = publish, } -- publish a message, if the caller is remote, forward the message to the owner node (by remote_publish) -- If the caller is local, call publish function command.PUB(source, c, pack, size) assert(skynet.harbor(source) == harbor_id) local node = c % 256 if node ~= harbor_id then -- remote publish remote_publish(node, c, source, mc.remote(pack)) else publish(c, source, pack,size) end end -- the node (source) subscribe a channel -- MUST call by channel owner node (assert source is not local and channel is create by self) -- If channel is not exist, return true -- Else set channel_remote[channel] true function command.SUBR(source, c) local node = skynet.harbor(source) if not channel[c] then -- channel none exist return true end assert(node ~= harbor_id and c % 256 == harbor_id) local group = channel_remote[c] if group == nil then group = {} channel_remote[c] = group end group[node] = true end -- the service (source) subscribe a channel -- If the channel is remote, node subscribe it by send a SUBR to the owner . function command.SUB(source, c) local node = c % 256 if node ~= harbor_id then -- remote group if channel[c] == nil then if skynet.call(node_address[node], "lua", "SUBR", c) then return end if channel[c] == nil then -- double check, because skynet.call whould yield, other SUB may occur. channel[c] = {} channel_n[c] = 0 end end end local group = channel[c] if group and not group[source] then channel_n[c] = channel_n[c] + 1 group[source] = true end end -- MUST call by a node, unsubscribe a channel function command.USUBR(source, c) local node = skynet.harbor(source) assert(node ~= harbor_id) local group = assert(channel_remote[c]) group[node] = nil return NORET end -- Unsubscribe a channel, if the subscriber is empty and the channel is remote, send USUBR to the channel owner function command.USUB(source, c) local group = assert(channel[c]) if group[source] then group[source] = nil channel_n[c] = channel_n[c] - 1 if channel_n[c] == 0 then local node = c % 256 if node ~= harbor_id then -- remote group channel[c] = nil channel_n[c] = nil skynet.send(node_address[node], "lua", "USUBR", c) end end end return NORET end skynet.start(function() skynet.dispatch("lua", function(_,source, cmd, ...) local f = assert(command[cmd]) local result = f(source, ...) if result ~= NORET then skynet.ret(skynet.pack(result)) end end) local self = skynet.self() local id = skynet.harbor(self) assert(datacenter.set("multicast", id, self) == nil) end)
bugfix: double check in SUB
bugfix: double check in SUB
Lua
mit
sundream/skynet,ilylia/skynet,fztcjjl/skynet,firedtoad/skynet,MoZhonghua/skynet,LiangMa/skynet,Markal128/skynet,asanosoyokaze/skynet,KAndQ/skynet,letmefly/skynet,MoZhonghua/skynet,korialuo/skynet,kyle-wang/skynet,QuiQiJingFeng/skynet,liuxuezhan/skynet,MRunFoss/skynet,zzh442856860/skynet-Note,bigrpg/skynet,JiessieDawn/skynet,codingabc/skynet,catinred2/skynet,winglsh/skynet,great90/skynet,zhouxiaoxiaoxujian/skynet,puXiaoyi/skynet,lawnight/skynet,chfg007/skynet,bigrpg/skynet,zhouxiaoxiaoxujian/skynet,ludi1991/skynet,zhaijialong/skynet,wangyi0226/skynet,pigparadise/skynet,zhangshiqian1214/skynet,gitfancode/skynet,your-gatsby/skynet,sanikoyes/skynet,cloudwu/skynet,microcai/skynet,boyuegame/skynet,vizewang/skynet,samael65535/skynet,wangyi0226/skynet,cloudwu/skynet,pichina/skynet,fhaoquan/skynet,bigrpg/skynet,Ding8222/skynet,sanikoyes/skynet,cpascal/skynet,kebo/skynet,LuffyPan/skynet,microcai/skynet,helling34/skynet,lc412/skynet,zhangshiqian1214/skynet,zhaijialong/skynet,zhangshiqian1214/skynet,MetSystem/skynet,letmefly/skynet,chuenlungwang/skynet,samael65535/skynet,rainfiel/skynet,xinjuncoding/skynet,leezhongshan/skynet,nightcj/mmo,xubigshu/skynet,gitfancode/skynet,QuiQiJingFeng/skynet,lawnight/skynet,QuiQiJingFeng/skynet,asanosoyokaze/skynet,sdgdsffdsfff/skynet,jxlczjp77/skynet,zhoukk/skynet,leezhongshan/skynet,fhaoquan/skynet,ludi1991/skynet,yinjun322/skynet,bingo235/skynet,ludi1991/skynet,zzh442856860/skynet,yunGit/skynet,catinred2/skynet,matinJ/skynet,xcjmine/skynet,wangjunwei01/skynet,MRunFoss/skynet,Zirpon/skynet,wangyi0226/skynet,KAndQ/skynet,zhangshiqian1214/skynet,qyli/test,chuenlungwang/skynet,pigparadise/skynet,lynx-seu/skynet,kyle-wang/skynet,bingo235/skynet,zhaijialong/skynet,ag6ag/skynet,jiuaiwo1314/skynet,dymx101/skynet,longmian/skynet,hongling0/skynet,matinJ/skynet,xcjmine/skynet,zzh442856860/skynet,iskygame/skynet,KittyCookie/skynet,ruleless/skynet,korialuo/skynet,wangjunwei01/skynet,zzh442856860/skynet-Note,microcai/skynet,chfg007/skynet,kyle-wang/skynet,jiuaiwo1314/skynet,togolwb/skynet,iskygame/skynet,liuxuezhan/skynet,firedtoad/skynet,chenjiansnail/skynet,icetoggle/skynet,helling34/skynet,yinjun322/skynet,KittyCookie/skynet,lawnight/skynet,dymx101/skynet,lynx-seu/skynet,u20024804/skynet,yunGit/skynet,felixdae/skynet,javachengwc/skynet,cpascal/skynet,Markal128/skynet,bttscut/skynet,javachengwc/skynet,jxlczjp77/skynet,codingabc/skynet,xjdrew/skynet,zhangshiqian1214/skynet,puXiaoyi/skynet,MetSystem/skynet,JiessieDawn/skynet,sanikoyes/skynet,lawnight/skynet,sdgdsffdsfff/skynet,xinmingyao/skynet,zzh442856860/skynet-Note,plsytj/skynet,yunGit/skynet,pigparadise/skynet,cuit-zhaxin/skynet,Ding8222/skynet,ag6ag/skynet,your-gatsby/skynet,letmefly/skynet,sundream/skynet,enulex/skynet,cmingjian/skynet,xinmingyao/skynet,kebo/skynet,javachengwc/skynet,xinjuncoding/skynet,czlc/skynet,togolwb/skynet,bttscut/skynet,yinjun322/skynet,togolwb/skynet,LiangMa/skynet,felixdae/skynet,ruleless/skynet,chuenlungwang/skynet,korialuo/skynet,bttscut/skynet,qyli/test,Markal128/skynet,xinjuncoding/skynet,catinred2/skynet,lc412/skynet,cuit-zhaxin/skynet,ypengju/skynet_comment,sdgdsffdsfff/skynet,MetSystem/skynet,u20024804/skynet,lynx-seu/skynet,xubigshu/skynet,pichina/skynet,plsytj/skynet,harryzeng/skynet,rainfiel/skynet,harryzeng/skynet,zhoukk/skynet,enulex/skynet,cdd990/skynet,zhouxiaoxiaoxujian/skynet,sundream/skynet,hongling0/skynet,ypengju/skynet_comment,qyli/test,plsytj/skynet,jiuaiwo1314/skynet,jxlczjp77/skynet,icetoggle/skynet,great90/skynet,cmingjian/skynet,rainfiel/skynet,chfg007/skynet,pichina/skynet,kebo/skynet,Ding8222/skynet,KAndQ/skynet,nightcj/mmo,zhoukk/skynet,cloudwu/skynet,liuxuezhan/skynet,bingo235/skynet,letmefly/skynet,liuxuezhan/skynet,great90/skynet,LuffyPan/skynet,MoZhonghua/skynet,helling34/skynet,fhaoquan/skynet,ludi1991/skynet,LuffyPan/skynet,vizewang/skynet,firedtoad/skynet,ypengju/skynet_comment,iskygame/skynet,KittyCookie/skynet,ruleless/skynet,winglsh/skynet,samael65535/skynet,zzh442856860/skynet-Note,zhangshiqian1214/skynet,your-gatsby/skynet,hongling0/skynet,felixdae/skynet,MRunFoss/skynet,gitfancode/skynet,xjdrew/skynet,boyuegame/skynet,chenjiansnail/skynet,winglsh/skynet,LiangMa/skynet,zzh442856860/skynet,fztcjjl/skynet,ilylia/skynet,lc412/skynet,boyuegame/skynet,cdd990/skynet,puXiaoyi/skynet,chenjiansnail/skynet,fztcjjl/skynet,cmingjian/skynet,nightcj/mmo,qyli/test,enulex/skynet,czlc/skynet,cpascal/skynet,Zirpon/skynet,longmian/skynet,harryzeng/skynet,xcjmine/skynet,asanosoyokaze/skynet,longmian/skynet,matinJ/skynet,cdd990/skynet,u20024804/skynet,icetoggle/skynet,codingabc/skynet,xjdrew/skynet,ag6ag/skynet,cuit-zhaxin/skynet,vizewang/skynet,wangjunwei01/skynet,leezhongshan/skynet,Zirpon/skynet,dymx101/skynet,czlc/skynet,ilylia/skynet,JiessieDawn/skynet
3f78f1f7213afded0029efcf439556c628971b17
conf/lua/rspamd.lua
conf/lua/rspamd.lua
-- This is main lua config file for rspamd config['regexp'] = {} dofile('regexp/headers.lua') dofile('regexp/lotto.lua') dofile('regexp/fraud.lua') dofile('regexp/drugs.lua') local reconf = config['regexp'] -- Uncategorized rules local html_length_1024_1536 = 'has_content_part_len(\'text\', \'html\', 1024, 1536)' local html_link_image = '/<img /iPr' reconf['HTML_SHORT_LINK_IMG_2'] = string.format('(%s) & (%s)', html_length_1024_1536, html_link_image) -- Local rules local r_bgcolor = '/BGCOLOR=/iP' local r_font_color = '/font color=[\\"\']?\\#FFFFFF[\\"\']?/iP' reconf['R_WHITE_ON_WHITE'] = string.format('(!(%s) & (%s))', r_bgcolor, r_font_color) reconf['R_FLASH_REDIR_IMGSHACK'] = '/^(?:http:\\/\\/)?img\\d{1,5}\\.imageshack\\.us\\/\\S+\\.swf/U' -- Different text parts reconf['R_PARTS_DIFFER'] = 'compare_parts_distance(50)'; rspamd_config.R_EMPTY_IMAGE = function (task) parts = task:get_text_parts() if parts then for _,part in ipairs(parts) do if part:is_empty() then images = task:get_images() if images then return true end return false end end end return false end -- Date issues rspamd_config.DATE_IN_FUTURE = function(task) if rspamd_config:get_api_version() >= 5 then local m = task:get_message() local dm = m:get_date() local dt = task:get_date() -- An hour if dm - dt > 3600 then return true end end return false end rspamd_config.DATE_IN_PAST = function(task) if rspamd_config:get_api_version() >= 5 then local m = task:get_message() local dm = m:get_date() local dt = task:get_date() -- A day if dt - dm > 86400 then return true end end return false end local function file_exists(filename) local file = io.open(filename) if file then io.close(file) return true else return false end end if file_exists('hfilter.lua') then dofile('hfilter.lua') end if file_exists('rspamd.local.lua') then dofile('rspamd.local.lua') end if file_exists('rspamd.classifiers.lua') then dofile('rspamd.classifiers.lua') end
-- This is main lua config file for rspamd config['regexp'] = {} dofile('regexp/headers.lua') dofile('regexp/lotto.lua') dofile('regexp/fraud.lua') dofile('regexp/drugs.lua') local reconf = config['regexp'] -- Uncategorized rules local html_length_1024_1536 = 'has_content_part_len(\'text\', \'html\', 1024, 1536)' local html_link_image = '/<img /iPr' reconf['HTML_SHORT_LINK_IMG_2'] = string.format('(%s) & (%s)', html_length_1024_1536, html_link_image) -- Local rules local r_bgcolor = '/BGCOLOR=/iP' local r_font_color = '/font color=[\\"\']?\\#FFFFFF[\\"\']?/iP' reconf['R_WHITE_ON_WHITE'] = string.format('(!(%s) & (%s))', r_bgcolor, r_font_color) reconf['R_FLASH_REDIR_IMGSHACK'] = '/^(?:http:\\/\\/)?img\\d{1,5}\\.imageshack\\.us\\/\\S+\\.swf/U' -- Different text parts reconf['R_PARTS_DIFFER'] = 'compare_parts_distance(50)'; rspamd_config.R_EMPTY_IMAGE = function (task) parts = task:get_text_parts() if parts then for _,part in ipairs(parts) do if part:is_empty() then images = task:get_images() if images then return true end return false end end end return false end -- Date issues rspamd_config.DATE_IN_FUTURE = function(task) if rspamd_config:get_api_version() >= 5 then local dm = task:get_date{format = 'message'} local dt = task:get_date{format = 'connect'} -- An hour if dm - dt > 3600 then return true end end return false end rspamd_config.DATE_IN_PAST = function(task) if rspamd_config:get_api_version() >= 5 then local dm = task:get_date{format = 'message', gmt = true} local dt = task:get_date{format = 'connect', gmt = true} -- A day if dt - dm > 86400 then return true end end return false end local function file_exists(filename) local file = io.open(filename) if file then io.close(file) return true else return false end end if file_exists('hfilter.lua') then dofile('hfilter.lua') end if file_exists('rspamd.local.lua') then dofile('rspamd.local.lua') end if file_exists('rspamd.classifiers.lua') then dofile('rspamd.classifiers.lua') end
Fix DATE_IN_PAST and DATE_IN_FUTURE
Fix DATE_IN_PAST and DATE_IN_FUTURE
Lua
apache-2.0
dark-al/rspamd,amohanta/rspamd,minaevmike/rspamd,dark-al/rspamd,minaevmike/rspamd,amohanta/rspamd,andrejzverev/rspamd,minaevmike/rspamd,minaevmike/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,dark-al/rspamd,minaevmike/rspamd,AlexeySa/rspamd,amohanta/rspamd,andrejzverev/rspamd,dark-al/rspamd,minaevmike/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,awhitesong/rspamd,minaevmike/rspamd,andrejzverev/rspamd,minaevmike/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,dark-al/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,awhitesong/rspamd,minaevmike/rspamd,amohanta/rspamd,AlexeySa/rspamd,awhitesong/rspamd,awhitesong/rspamd,AlexeySa/rspamd,amohanta/rspamd,AlexeySa/rspamd,AlexeySa/rspamd
1f3aca959c7ba53a3c830611d061fbc15a9a9ad1
torch/audio/benchmark.lua
torch/audio/benchmark.lua
require 'sys' require 'cunn' require 'cudnn' require 'nnx' require 'BatchBRNNReLU' require 'Dataset' local pl = require('pl.import_into')() local optnet = require 'optnet' cudnn.fastest = true cudnn.benchmark = false -- set this false due to the varying input shape cudnn.verbose = false local function printMemory() local freeMemory, totalMemory = cutorch.getMemoryUsage() print("total Memory", totalMemory, "free Memory", freeMemory, "used", totalMemory-freeMemory) end local opt = pl.lapp[[ --dryrun (default 10) number of iterations of a dry run not counted towards final timing --nGPU (default 1) number of GPUs to run on --batchSize (default 64) batch size --steps (default 1) number of steps to average performance --useOptnet (default true) whether to use optnet package for memory optimization ]] local nGPU = opt.nGPU deepSpeech = require 'cudnn_deepspeech2' print('Running on device: ' .. cutorch.getDeviceProperties(cutorch.getDevice()).name) local steps = opt.steps -- nb of steps in loop to average perf local nDryRuns = opt.dryrun local batchSize = opt.batchSize spectrogramSize = 161 criterion = nn.CTCCriterion():cuda() local dataset = nn.DeepSpeechDataset(batchSize) collectgarbage() local model, model_name, calculateInputSizes = deepSpeech(batchSize, dataset.freqBins, nGPU) local inputs = torch.CudaTensor() -- buffer for inputs local sizes, input, targets = dataset:nextTorchSet() input=input:view(opt.batchSize,1,spectrogramSize, -1) model = model:cuda() inputs:resize(input:size()):copy(input) print('ModelType: ' .. model_name, 'Kernels: ' .. 'cuDNN') if opt.useOptnet then local seqLength = inputs:size(4) local tmpinp = torch.randn(2,1, spectrogramSize, seqLength) local optinp = torch.CudaTensor() optinp:resize(tmpinp:size()):copy(tmpinp) local output=model:updateOutput(optinp) model:backward(optinp,output) cutorch.synchronize() mem1=optnet.countUsedMemory(model) optnet.optimizeMemory(model, optinp, {inplace=false, mode = 'training'}) model:backward(optinp,output) collectgarbage() mem2 = optnet.countUsedMemory(model) print('Before optimization : ', mem1) print('After optimization : ', mem2) end -- dry-run for i = 1, nDryRuns do model:zeroGradParameters() local output = model:updateOutput(inputs) local gradInput = model:updateGradInput(inputs, output) model:accGradParameters(inputs, output) cutorch.synchronize() collectgarbage() end local tmfAvg, tmbiAvg, tRoundTripAvg = 0,0,0,0 local ok = 1 for t = 1, steps do local tmf, tmbi, tRoundTrip = 0, 0, 0, 0 local roundTripTimer = torch.Timer() dataset = nn.DeepSpeechDataset(batchSize) local numberOfIterations = 0 local sizes, input, targets = dataset:nextTorchSet() while (sizes ~= nil) do input=input:view(opt.batchSize,1,spectrogramSize, -1) inputs:resize(input:size()):copy(input) sys.tic() -- Forward through model and then criterion. local output = model:updateOutput(inputs) loss = criterion:updateOutput(output, targets, calculateInputSizes(sizes)) tmf = tmf + sys.toc() cutorch.synchronize() -- Backwards (updateGradInput, accGradParameters) including the criterion. sys.tic() grads = criterion:updateGradInput(output, targets) model:backward(inputs,output) cutorch.synchronize() tmbi = tmbi + sys.toc() collectgarbage() numberOfIterations = numberOfIterations + 1 -- printMemory() xlua.progress(numberOfIterations * batchSize, dataset.size) end -- Divide the times to work out average time for updateOutput/updateGrad/accGrad tmfAvg = tmfAvg + tmf / numberOfIterations tmbiAvg = tmbiAvg + tmbi / numberOfIterations -- Add time taken for round trip of 1 epoch tRoundTripAvg = tRoundTripAvg + roundTripTimer:time().real end local tmf = tmfAvg / steps local tmbi = tmbiAvg / steps local tRoundTrip = tRoundTripAvg / steps print(string.format("%-30s %25s %10.2f", 'cuDNN', ':forward (ms):', tmf * 1000)) print(string.format("%-30s %25s %10.2f", 'cuDNN', ':backward (ms):', tmbi * 1000)) print(string.format("%-30s %25s %10.2f", 'cuDNN', ':TOTAL (ms):', (tmf + tmbi + tmbg) * 1000)) print(string.format("%-30s %25s %10.2f", 'cuDNN', ':Samples processed:', dataset.size)) print(string.format("%-30s %25s %10.2f", 'cuDNN', ':Samples per second:', dataset.size / tRoundTrip)) print(string.format("%-30s %25s %10.2f", 'cuDNN', ':Seconds of audio processed per second:', dataset.duration / tRoundTrip)) print(string.format("%-30s %25s %10.2f", 'cuDNN', ':EPOCH TIME (s):', tRoundTrip)) print() print('')
require 'sys' require 'cunn' require 'cudnn' require 'nnx' require 'BatchBRNNReLU' require 'Dataset' local pl = require('pl.import_into')() local optnet = require 'optnet' cudnn.fastest = true cudnn.benchmark = false -- set this false due to the varying input shape cudnn.verbose = false local function printMemory() local freeMemory, totalMemory = cutorch.getMemoryUsage() print("total Memory", totalMemory, "free Memory", freeMemory, "used", totalMemory-freeMemory) end local opt = pl.lapp[[ --dryrun (default 10) number of iterations of a dry run not counted towards final timing --nGPU (default 1) number of GPUs to run on --batchSize (default 64) batch size --steps (default 1) number of steps to average performance --useOptnet (default true) whether to use optnet package for memory optimization ]] local nGPU = opt.nGPU deepSpeech = require 'cudnn_deepspeech2' print('Running on device: ' .. cutorch.getDeviceProperties(cutorch.getDevice()).name) local steps = opt.steps -- nb of steps in loop to average perf local nDryRuns = opt.dryrun local batchSize = opt.batchSize spectrogramSize = 161 criterion = nn.CTCCriterion():cuda() local dataset = nn.DeepSpeechDataset(batchSize) collectgarbage() local model, model_name, calculateInputSizes = deepSpeech(batchSize, dataset.freqBins, nGPU) local inputs = torch.CudaTensor() -- buffer for inputs local sizes, input, targets = dataset:nextTorchSet() input=input:view(opt.batchSize,1,spectrogramSize, -1) model = model:cuda() inputs:resize(input:size()):copy(input) print('ModelType: ' .. model_name, 'Kernels: ' .. 'cuDNN') if opt.useOptnet then local seqLength = inputs:size(4) local tmpinp = torch.randn(2,1, spectrogramSize, seqLength) local optinp = torch.CudaTensor() optinp:resize(tmpinp:size()):copy(tmpinp) local output=model:updateOutput(optinp) model:backward(optinp,output) cutorch.synchronize() mem1=optnet.countUsedMemory(model) optnet.optimizeMemory(model, optinp, {inplace=false, mode = 'training'}) model:backward(optinp,output) collectgarbage() mem2 = optnet.countUsedMemory(model) print('Before optimization : ', mem1) print('After optimization : ', mem2) end -- dry-run for i = 1, nDryRuns do model:zeroGradParameters() local output = model:updateOutput(inputs) local gradInput = model:updateGradInput(inputs, output) model:accGradParameters(inputs, output) cutorch.synchronize() collectgarbage() end local tmfAvg, tmbiAvg, tRoundTripAvg = 0,0,0,0 local ok = 1 for t = 1, steps do local tmf, tmbi, tRoundTrip = 0, 0, 0, 0 local roundTripTimer = torch.Timer() dataset = nn.DeepSpeechDataset(batchSize) local numberOfIterations = 0 local sizes, input, targets = dataset:nextTorchSet() while (sizes ~= nil ) do input=input:view(opt.batchSize,1,spectrogramSize, -1) inputs:resize(input:size()):copy(input) sys.tic() -- Forward through model and then criterion. local output = model:updateOutput(inputs) loss = criterion:updateOutput(output, targets, calculateInputSizes(sizes)) cutorch.synchronize() tmf = tmf + sys.toc() -- Backwards (updateGradInput, accGradParameters) including the criterion. sys.tic() grads = criterion:updateGradInput(output, targets) model:backward(inputs,output) cutorch.synchronize() tmbi = tmbi + sys.toc() collectgarbage() numberOfIterations = numberOfIterations + 1 -- printMemory() xlua.progress(numberOfIterations * batchSize, dataset.size) end -- Divide the times to work out average time for updateOutput/updateGrad/accGrad tmfAvg = tmfAvg + tmf / numberOfIterations tmbiAvg = tmbiAvg + tmbi / numberOfIterations -- Add time taken for round trip of 1 epoch tRoundTripAvg = tRoundTripAvg + roundTripTimer:time().real end local tmf = tmfAvg / steps local tmbi = tmbiAvg / steps local tRoundTrip = tRoundTripAvg / steps print(string.format("%-30s %25s %10.2f", 'cuDNN', ':forward (ms):', tmf * 1000)) print(string.format("%-30s %25s %10.2f", 'cuDNN', ':backward (ms):', tmbi * 1000)) print(string.format("%-30s %25s %10.2f", 'cuDNN', ':TOTAL (ms):', (tmf + tmbi) * 1000)) print(string.format("%-30s %25s %10.2f", 'cuDNN', ':Samples processed:', dataset.size)) print(string.format("%-30s %25s %10.2f", 'cuDNN', ':Samples per second:', dataset.size / tRoundTrip)) print(string.format("%-30s %25s %10.2f", 'cuDNN', ':Seconds of audio processed per second:', dataset.duration / tRoundTrip)) print(string.format("%-30s %25s %10.2f", 'cuDNN', ':EPOCH TIME (s):', tRoundTrip)) print() print('')
fixed typos
fixed typos
Lua
apache-2.0
DeepMark/deepmark
29149b93a5c14f48af2face666e422e0be9ffbae
lua/weapons/gmod_tool/stools/sbep_docking_clamp.lua
lua/weapons/gmod_tool/stools/sbep_docking_clamp.lua
TOOL.Category = "SBEP" TOOL.Name = "#Docking Clamp" TOOL.Command = nil TOOL.ConfigName = "" local DockingClampModels = list.Get( "SBEP_DockingClampModels" ) local DockClampToolModels = list.Get( "SBEP_DockClampToolModels" ) if CLIENT then language.Add( "Tool.sbep_docking_clamp.name" , "SBEP Docking Clamp Tool" ) language.Add( "Tool.sbep_docking_clamp.desc" , "Create an SBEP docking clamp." ) language.Add( "Tool.sbep_docking_clamp.0" , "Left-click to spawn a docking clamp, or right-click an existing clamp to spawn a counterpart." ) language.Add( "undone_SBEP Docking Clamp" , "Undone SBEP Docking Clamp" ) end local CategoryTable = {} CategoryTable[1] = { { name = "Doors" , cat = "Door" } , { name = "MedBridge" , cat = "MedBridge" } , { name = "ElevatorSmall" , cat = "ElevatorSmall" } , { name = "PHX" , cat = "PHX" } , } TOOL.ClientConVar[ "model" ] = "models/smallbridge/panels/sbpaneldockin.mdl" TOOL.ClientConVar[ "allowuse" ] = 1 function TOOL:LeftClick( tr ) if CLIENT then return end local ply = self:GetOwner() local model = ply:GetInfo( "sbep_docking_clamp_model" ) local Data = DockingClampModels[ string.lower( model ) ] local pos = tr.HitPos local DockEnt = ents.Create( "sbep_base_docking_clamp" ) DockEnt.SPL = self:GetOwner() DockEnt:SetModel( model ) DockEnt:SetDockType( Data.ALType ) DockEnt:Spawn() DockEnt:Initialize() DockEnt:Activate() for n,P in pairs( Data.EfPoints ) do DockEnt:SetNetworkedVector("EfVec"..n, P.vec) DockEnt:SetNetworkedInt("EfSp"..n, P.sp) end DockEnt:SetPos( pos - Vector(0,0,DockEnt:OBBMins().z) ) DockEnt.Usable = ply:GetInfoNum( "sbep_docking_clamp_allowuse", 1 ) == 1 DockEnt:AddDockDoor() undo.Create("SBEP Docking Clamp") undo.AddEntity( DockEnt ) undo.SetPlayer( ply ) undo.Finish() return true end function TOOL:RightClick( tr ) if CLIENT then return end if !tr.Hit or !tr.Entity or !tr.Entity:IsValid() then return end local dock = tr.Entity local class = dock:GetClass() if class == "sbep_base_docking_clamp" then local type = dock.ALType for model,data in pairs( DockingClampModels ) do local check = false for i,T in ipairs( data.Compatible ) do if type == T.Type then check = i break end end if check then local pos = dock:GetPos() local ang = dock:GetAngles() local DockEnt = ents.Create( "sbep_base_docking_clamp" ) DockEnt.SPL = self:GetOwner() DockEnt:SetModel( model ) DockEnt:SetDockType( data.ALType ) DockEnt.Usable = dock.Usable DockEnt:Spawn() DockEnt:Initialize() DockEnt:Activate() for n,P in pairs( data.EfPoints ) do DockEnt:SetNetworkedVector("EfVec"..n, P.vec) DockEnt:SetNetworkedInt("EfSp"..n, P.sp) end DockEnt:SetPos( Vector(0,-50,100) + pos - Vector(0,0,DockEnt:OBBMins().z) ) DockEnt:SetAngles( ang + Angle( 0, data.Compatible[ check ].AYaw , 0 ) ) DockEnt:AddDockDoor() dock.DMode = 2 DockEnt.DMode = 2 undo.Create("SBEP Docking Clamp") undo.AddEntity( DockEnt ) undo.SetPlayer( self:GetOwner() ) undo.Finish() return true end end else return end end function TOOL:Reload( trace ) end function TOOL.BuildCPanel( panel ) panel:SetSpacing( 10 ) panel:SetName( "SBEP Docking Clamp" ) local UseCheckBox = vgui.Create( "DCheckBoxLabel", panel ) UseCheckBox:Dock(TOP) UseCheckBox:SetText( "Enable Use Key:" ) UseCheckBox:SetConVar( "sbep_docking_clamp_allowuse" ) UseCheckBox:SetValue( GetConVar( "sbep_docking_clamp_allowuse" ):GetBool() ) for Tab,v in pairs( DockClampToolModels ) do for Category, models in pairs( v ) do local catPanel = vgui.Create( "DCollapsibleCategory", panel ) catPanel:Dock( TOP ) catPanel:DockMargin(2,2,2,2) catPanel:SetText(Category) catPanel:SetLabel(Category) local grid = vgui.Create( "DGrid", catPanel ) grid:Dock( TOP ) local width,_ = catPanel:GetSize() grid:SetColWide( 64 ) grid:SetRowHeight( 64 ) for key, modelpath in pairs( models ) do local icon = vgui.Create( "SpawnIcon", panel ) --icon:Dock( TOP ) icon:SetModel( modelpath ) icon:SetToolTip( modelpath ) icon.DoClick = function( panel ) RunConsoleCommand( "sbep_docking_clamp_model", modelpath ) end --icon:SetIconSize( width ) grid:AddItem( icon ) end catPanel:SetExpanded( 0 ) end end --[[local MCPS = vgui.Create( "MCPropSelect" ) MCPS:SetConVar( "sbep_docking_clamp_model" ) for Cat,mt in pairs( MTT ) do MCPS:AddMCategory( Cat , mt ) end MCPS:SetCategory( 3 ) panel:AddItem( MCPS ) ]] end
TOOL.Category = "SBEP" TOOL.Name = "#Docking Clamp" TOOL.Command = nil TOOL.ConfigName = "" local DockingClampModels = list.Get( "SBEP_DockingClampModels" ) local DockClampToolModels = list.Get( "SBEP_DockClampToolModels" ) if CLIENT then language.Add( "Tool.sbep_docking_clamp.name" , "SBEP Docking Clamp Tool" ) language.Add( "Tool.sbep_docking_clamp.desc" , "Create an SBEP docking clamp." ) language.Add( "Tool.sbep_docking_clamp.0" , "Left-click to spawn a docking clamp, or right-click an existing clamp to spawn a counterpart." ) language.Add( "undone_SBEP Docking Clamp" , "Undone SBEP Docking Clamp" ) end local CategoryTable = {} CategoryTable[1] = { { name = "Doors" , cat = "Door" } , { name = "MedBridge" , cat = "MedBridge" } , { name = "ElevatorSmall" , cat = "ElevatorSmall" } , { name = "PHX" , cat = "PHX" } , } TOOL.ClientConVar[ "model" ] = "models/smallbridge/panels/sbpaneldockin.mdl" TOOL.ClientConVar[ "allowuse" ] = 1 function TOOL:LeftClick( tr ) if CLIENT then return end local ply = self:GetOwner() local model = ply:GetInfo( "sbep_docking_clamp_model" ) local Data = DockingClampModels[ string.lower( model ) ] local pos = tr.HitPos local DockEnt = ents.Create( "sbep_base_docking_clamp" ) DockEnt.SPL = self:GetOwner() DockEnt:SetModel( model ) DockEnt:SetDockType( Data.ALType ) DockEnt:Spawn() DockEnt:Initialize() DockEnt:Activate() for n,P in pairs( Data.EfPoints ) do DockEnt:SetNetworkedVector("EfVec"..n, P.vec) DockEnt:SetNetworkedInt("EfSp"..n, P.sp) end DockEnt:SetPos( pos - Vector(0,0,DockEnt:OBBMins().z) ) DockEnt.Usable = ply:GetInfoNum( "sbep_docking_clamp_allowuse", 1 ) == 1 DockEnt:AddDockDoor() undo.Create("SBEP Docking Clamp") undo.AddEntity( DockEnt ) undo.SetPlayer( ply ) undo.Finish() return true end function TOOL:RightClick( tr ) if CLIENT then return end if !tr.Hit or !tr.Entity or !tr.Entity:IsValid() then return end local dock = tr.Entity local class = dock:GetClass() if class == "sbep_base_docking_clamp" then local type = dock.ALType for model,data in pairs( DockingClampModels ) do local check = false for i,T in ipairs( data.Compatible ) do if type == T.Type then check = i break end end if check then local pos = dock:GetPos() local ang = dock:GetAngles() local DockEnt = ents.Create( "sbep_base_docking_clamp" ) DockEnt.SPL = self:GetOwner() DockEnt:SetModel( model ) DockEnt:SetDockType( data.ALType ) DockEnt.Usable = dock.Usable DockEnt:Spawn() DockEnt:Initialize() DockEnt:Activate() for n,P in pairs( data.EfPoints ) do DockEnt:SetNetworkedVector("EfVec"..n, P.vec) DockEnt:SetNetworkedInt("EfSp"..n, P.sp) end DockEnt:SetPos( Vector(0,-50,100) + pos - Vector(0,0,DockEnt:OBBMins().z) ) DockEnt:SetAngles( ang + Angle( 0, data.Compatible[ check ].AYaw or 0, 0 ) ) DockEnt:AddDockDoor() dock.DMode = 2 DockEnt.DMode = 2 undo.Create("SBEP Docking Clamp") undo.AddEntity( DockEnt ) undo.SetPlayer( self:GetOwner() ) undo.Finish() return true end end else return end end function TOOL:Reload( trace ) end function TOOL.BuildCPanel( panel ) panel:SetSpacing( 10 ) panel:SetName( "SBEP Docking Clamp" ) local UseCheckBox = vgui.Create( "DCheckBoxLabel", panel ) UseCheckBox:Dock(TOP) UseCheckBox:SetText( "Enable Use Key:" ) UseCheckBox:SetTextColor(Color(0,0,0,255)) UseCheckBox:SetConVar( "sbep_docking_clamp_allowuse" ) UseCheckBox:SetValue( GetConVar( "sbep_docking_clamp_allowuse" ):GetBool() ) for Tab,v in pairs( DockClampToolModels ) do for Category, models in pairs( v ) do local catPanel = vgui.Create( "DCollapsibleCategory", panel ) catPanel:Dock( TOP ) catPanel:DockMargin(2,2,2,2) catPanel:SetText(Category) catPanel:SetLabel(Category) local grid = vgui.Create( "DGrid", catPanel ) grid:Dock( TOP ) local width,_ = catPanel:GetSize() grid:SetColWide( 64 ) grid:SetRowHeight( 64 ) for key, modelpath in pairs( models ) do local icon = vgui.Create( "SpawnIcon", panel ) --icon:Dock( TOP ) icon:SetModel( modelpath ) icon:SetToolTip( modelpath ) icon.DoClick = function( panel ) RunConsoleCommand( "sbep_docking_clamp_model", modelpath ) end --icon:SetIconSize( width ) grid:AddItem( icon ) end catPanel:SetExpanded( 0 ) end end --[[local MCPS = vgui.Create( "MCPropSelect" ) MCPS:SetConVar( "sbep_docking_clamp_model" ) for Cat,mt in pairs( MTT ) do MCPS:AddMCategory( Cat , mt ) end MCPS:SetCategory( 3 ) panel:AddItem( MCPS ) ]] end
Fixes invalid angle error for docking clamp when using right click
Fixes invalid angle error for docking clamp when using right click minor change for label color
Lua
apache-2.0
SnakeSVx/sbep
6d45d34504eb3be5e51e7fe368f71ec1902336a5
enemy.lua
enemy.lua
require "ai/ai" function getAllNodes(map) local w = map.width local h = map.height local nodes = {} local k = 1 for i = 0, w do for j = 0, h do nodes[k]= {x=i,y=j,id=k} k = k + 1 end end return nodes end function findNode(nodes, x, y) for i = 1, #nodes do if nodes[i].x == x and nodes[i].y == y then return nodes[i] end end end function love.turris.newEnemy(img, map, x,y,baseX, baseY) local o = {} o.generateWaypoints = function(map, startX, startY, goalX, goalY) local all_nodes = getAllNodes(map) local start = findNode(all_nodes, startX, startY) local goal = findNode(all_nodes, goalX, goalY) local path = aStar(start,goal,all_nodes) local wp = {{startX,startY},{goalX,goalY}} if path then for i = 1, #path do wp[i] ={path[i].x,path[i].y} end end return wp end o.img = img o.x = x o.y = y o.waypoints = o.generateWaypoints(map,x,y,baseX,baseY) o.currentWaypoint = 2 o.health = 100.0 -- TODO this depends on the type and not on the particular enemy o.maxHealth = 100.0 o.speed = 1.0 -- type end --o.shadow = {} --o.shadow = lightWorld.newImage(o.img) --o.shadow.setShadowType("image",32,32, 1.0) o.updateVelocity = function(dirX,dirY) o.xVel = dirX*o.speed o.yVel = dirY*o.speed end o.getDirection = function() return math.atan2(o.xVel, o.yVel) end o.updateVelocity(1,0) --TODO this should be determined from the current position to the next waypoint o.getOrientation = function() local x,y = love.turris.normalize(o.xVel, o.yVel) return x,y end return o end function distance(x1,y1,x2,y2) --TODO let's not leave this global -- manhattan is sufficient for now return math.abs(x1-x2)+math.abs(y1-y2) end function love.turris.normalize(x,y) local m = math.max(math.abs(x),math.abs(y)) --print ("normalize: ", x, y, m) local xRet = x/m local yRet = y/m if (xRet ~= xRet) then print ("xRet NaN: ",xRet) end if (yRet ~= yRet) then print ("yRet NaN: ",yRet) end return xRet, yRet end function love.turris.updateEnemies(o,dt) for i = 1, o.enemyCount do local e = o.enemies[i] e.x = e.x+e.xVel*dt e.y = e.y+e.yVel*dt local x = e.x local y = e.y -- check if waypoint reached local wp = e.waypoints[e.currentWaypoint] if math.abs(wp[1]-x)<0.1 and math.abs(wp[2] -y)<0.1 then -- waypoint reached local nextWpIndex = e.currentWaypoint +1 e.currentWaypoint = nextWpIndex local wpNext = e.waypoints[nextWpIndex] local dirX,dirY = love.turris.normalize( wpNext[1]-wp[1], wpNext[2]-wp[2]) e.updateVelocity(dirX,dirY) end -- write back the changes o.enemies[i]= e -- check for and handle game over if math.abs(o.baseX - x) <1 and math.abs(y - o.baseY) < 1 then -- Game Over!!! (for now) -- TODO: destroy ship (explosion) -- TODO: destroy base (explosion!) -- TODO: after explosions have finished -> transition to game over state love.sounds.playSound("sounds/einschlag.mp3") love.setgamestate(4) gameOverEffect = 0 end end end
require "ai/ai" function getAllNodes(map) local w = map.width local h = map.height local nodes = {} local k = 1 for i = 0, w do for j = 0, h do nodes[k]= {x=i,y=j,id=k} k = k + 1 end end return nodes end function findNode(nodes, x, y) for i = 1, #nodes do if nodes[i].x == x and nodes[i].y == y then return nodes[i] end end end function love.turris.newEnemy(img, map, x,y,baseX, baseY) local o = {} o.generateWaypoints = function(map, startX, startY, goalX, goalY) local all_nodes = getAllNodes(map) local start = findNode(all_nodes, startX, startY) local goal = findNode(all_nodes, goalX, goalY) local path = aStar(start,goal,all_nodes) local wp = {{startX,startY},{goalX,goalY}} if path then for i = 1, #path do wp[i] ={path[i].x,path[i].y} end end return wp end o.img = img o.x = x o.y = y o.waypoints = o.generateWaypoints(map,x,y,baseX,baseY) o.currentWaypoint = 2 o.health = 100.0 -- TODO this depends on the type and not on the particular enemy o.maxHealth = 100.0 o.speed = 1.0 -- type end --o.shadow = {} --o.shadow = lightWorld.newImage(o.img) --o.shadow.setShadowType("image",32,32, 1.0) o.updateVelocity = function(dirX,dirY) o.xVel = dirX*o.speed o.yVel = dirY*o.speed end o.getDirection = function() return math.atan2(o.xVel, o.yVel) end o.updateVelocity(1,0) --TODO this should be determined from the current position to the next waypoint o.getOrientation = function() local x,y = love.turris.normalize(o.xVel, o.yVel) return x,y end return o end function distance(x1,y1,x2,y2) --TODO let's not leave this global -- manhattan is sufficient for now return math.abs(x1-x2)+math.abs(y1-y2) end function love.turris.normalize(x,y) local m = math.max(math.abs(x),math.abs(y)) --print ("normalize: ", x, y, m) local xRet = x/m local yRet = y/m if (xRet ~= xRet) then print ("xRet NaN: ",xRet) end if (yRet ~= yRet) then print ("yRet NaN: ",yRet) end return xRet, yRet end function love.turris.updateEnemies(o,dt) for i = 1, o.enemyCount do local e = o.enemies[i] e.x = e.x+e.xVel*dt e.y = e.y+e.yVel*dt local x = e.x local y = e.y -- check if waypoint reached local wp = e.waypoints[e.currentWaypoint] if math.abs(wp[1]-x)<0.1 and math.abs(wp[2] -y)<0.1 then -- waypoint reached local nextWpIndex = e.currentWaypoint +1 e.currentWaypoint = nextWpIndex local wpNext = e.waypoints[nextWpIndex] local dirX,dirY = love.turris.normalize( wpNext[1]-wp[1], wpNext[2]-wp[2]) e.updateVelocity(dirX,dirY) end -- write back the changes o.enemies[i]= e -- check for and handle game over if distance(o.baseX, o.baseY,x,y) < 1 then -- Game Over!!! (for now) -- TODO: destroy ship (explosion) -- TODO: destroy base (explosion!) -- TODO: after explosions have finished -> transition to game over state love.sounds.playSound("sounds/einschlag.mp3") love.setgamestate(4) gameOverEffect = 0 end end end
creep-base collision handled correctly now.
creep-base collision handled correctly now. This fixes issue #17
Lua
mit
sam1i/Turres-Monacorum,sam1i/Turres-Monacorum
18d09ea8d0d3af1871d19ca5ed219c8720f349ba
penguingui/TextField.lua
penguingui/TextField.lua
-- Editable text field TextField = class(Component) TextField.vPadding = 3 TextField.hPadding = 4 TextField.borderColor = "#545454" TextField.backgroundColor = "black" TextField.textColor = "white" TextField.textHoverColor = "#777777" TextField.defaultTextColor = "#333333" TextField.defaultTextHoverColor = "#777777" TextField.cursorColor = "white" TextField.cursorRate = 1 -- Constructs a new TextField. -- -- @param x The x coordinate of the new component, relative to its parent. -- @param y The y coordinate of the new component, relative to its parent. -- @param width The width of the new component. -- @param height The height of the new component. -- @param defaultText The text to display when nothing has been entered. function TextField:_init(x, y, width, height, defaultText) Component._init(self) self.x = x self.y = y self.width = width self.height = height self.fontSize = height - self.vPadding * 2 self.cursorPosition = 0 self.cursorX = 0 self.cursorTimer = self.cursorRate self.text = "" self.defaultText = defaultText self.textOffset = 0 self.textClip = nil self.mouseOver = false end function TextField:draw(dt) local startX = self.x local startY = self.y local w = self.width local h = self.height -- Draw border and background local borderRect = { startX, startY, startX + w, startY + h } local backgroundRect = { startX + 1, startY + 1, startX + w - 1, startY + h - 1 } console.canvasDrawRect(borderRect, self.borderColor) console.canvasDrawRect(backgroundRect, self.backgroundColor) local text = self.text -- Decide if the default text should be displayed local default = (text == "") and (self.defaultText ~= nil) local textColor -- Choose the color to draw the text with if self.mouseOver then textColor = default and self.defaultTextHoverColor or self.textHoverColor else textColor = default and self.defaultTextColor or self.textColor end local cursorPosition = self.cursorPosition text = default and self.defaultText or text:sub(self.textOffset, self.textOffset + (self.textClip or #text)) -- Draw the text console.canvasDrawText(text, { position = { startX + self.hPadding, startY + self.vPadding }, verticalAnchor = "bottom" }, self.fontSize, textColor) -- Text cursor if self.hasFocus then local timer = self.cursorTimer local rate = self.cursorRate timer = timer - dt if timer < 0 then timer = rate end if timer > rate / 2 then -- Draw cursor local cursorX = startX + self.cursorX + self.hPadding local cursorY = startY + self.vPadding console.canvasDrawLine({cursorX, cursorY}, {cursorX, cursorY + h - self.vPadding * 2}, self.cursorColor, 1) end self.cursorTimer = timer end Component.draw(self) end -- Set the character position of the text cursor. -- -- @param pos The new position for the cursor, where 0 is the beginning of the -- field. function TextField:setCursorPosition(pos) self.cursorPosition = pos if pos < self.textOffset then self.textOffset = pos end self:calculateTextClip() local textClip = self.textClip while (textClip) and (pos > self.textOffset + textClip) do self.textOffset = self.textOffset + 1 self:calculateTextClip() textClip = self.textClip end local text = self.text local cursorX = 0 for i=self.textOffset + 1,pos,1 do local charWidth = PtUtil.getStringWidth(text:sub(i, i), self.fontSize) cursorX = cursorX + charWidth end self.cursorX = cursorX self.cursorTimer = self.cursorRate end -- Calculates the text clip, i.e. how many characters to display. function TextField:calculateTextClip() local maxX = self.width - self.hPadding * 2 local text = self.text local totalWidth = 0 local startI = self.textOffset + 1 for i=startI,#text,1 do totalWidth = totalWidth + PtUtil.getStringWidth(text:sub(i, i), self.fontSize) if totalWidth > maxX then self.textClip = i - startI return end end self.textClip = nil end function TextField:clickEvent(position, button, pressed) local xPos = position[1] - self.offset[1] - self.hPadding local text = self.text local totalWidth = 0 for i=self.textOffset + 1,#text,1 do local charWidth = PtUtil.getStringWidth(text:sub(i, i), self.fontSize) if xPos < (totalWidth + charWidth * 0.8) then self:setCursorPosition(i - 1) return end totalWidth = totalWidth + charWidth end self:setCursorPosition(#text) end function TextField:keyEvent(keyCode, pressed) if not pressed then return end local keyState = GUI.keyState local shift = keyState[303] or keyState[304] local caps = keyState[301] local key = PtUtil.getKey(keyCode, shift, caps) local text = self.text local cursorPos = self.cursorPosition if #key == 1 then -- Type a character self.text = text:sub(1, cursorPos) .. key .. text:sub(cursorPos + 1) self:setCursorPosition(cursorPos + 1) else -- Special character if key == "backspace" then if cursorPos > 0 then self.text = text:sub(1, cursorPos - 1) .. text:sub(cursorPos + 1) self:setCursorPosition(cursorPos - 1) end elseif key == "enter" then if self.onEnter then self:onEnter() end elseif key == "delete" then if cursorPos < #text then self.text = text:sub(1, cursorPos) .. text:sub(cursorPos + 2) end elseif key == "right" then self:setCursorPosition(math.min(cursorPos + 1, #text)) elseif key == "left" then self:setCursorPosition(math.max(0, cursorPos - 1)) elseif key == "home" then self:setCursorPosition(0) elseif key == "end" then self:setCursorPosition(#text) end end end
-- Editable text field TextField = class(Component) TextField.vPadding = 3 TextField.hPadding = 4 TextField.borderColor = "#545454" TextField.backgroundColor = "black" TextField.textColor = "white" TextField.textHoverColor = "#999999" TextField.defaultTextColor = "#333333" TextField.defaultTextHoverColor = "#777777" TextField.cursorColor = "white" TextField.cursorRate = 1 -- Constructs a new TextField. -- -- @param x The x coordinate of the new component, relative to its parent. -- @param y The y coordinate of the new component, relative to its parent. -- @param width The width of the new component. -- @param height The height of the new component. -- @param defaultText The text to display when nothing has been entered. function TextField:_init(x, y, width, height, defaultText) Component._init(self) self.x = x self.y = y self.width = width self.height = height self.fontSize = height - self.vPadding * 2 self.cursorPosition = 0 self.cursorX = 0 self.cursorTimer = self.cursorRate self.text = "" self.defaultText = defaultText self.textOffset = 0 self.textClip = nil self.mouseOver = false end function TextField:draw(dt) local startX = self.x local startY = self.y local w = self.width local h = self.height -- Draw border and background local borderRect = { startX, startY, startX + w, startY + h } local backgroundRect = { startX + 1, startY + 1, startX + w - 1, startY + h - 1 } console.canvasDrawRect(borderRect, self.borderColor) console.canvasDrawRect(backgroundRect, self.backgroundColor) local text = self.text -- Decide if the default text should be displayed local default = (text == "") and (self.defaultText ~= nil) local textColor -- Choose the color to draw the text with if self.mouseOver then textColor = default and self.defaultTextHoverColor or self.textHoverColor else textColor = default and self.defaultTextColor or self.textColor end local cursorPosition = self.cursorPosition text = default and self.defaultText or text:sub(self.textOffset + 1, self.textOffset + (self.textClip or #text)) -- Draw the text console.canvasDrawText(text, { position = { startX + self.hPadding, startY + self.vPadding }, verticalAnchor = "bottom" }, self.fontSize, textColor) -- Text cursor if self.hasFocus then local timer = self.cursorTimer local rate = self.cursorRate timer = timer - dt if timer < 0 then timer = rate end if timer > rate / 2 then -- Draw cursor local cursorX = startX + self.cursorX + self.hPadding local cursorY = startY + self.vPadding console.canvasDrawLine({cursorX, cursorY}, {cursorX, cursorY + h - self.vPadding * 2}, self.cursorColor, 1) end self.cursorTimer = timer end Component.draw(self) end -- Set the character position of the text cursor. -- -- @param pos The new position for the cursor, where 0 is the beginning of the -- field. function TextField:setCursorPosition(pos) self.cursorPosition = pos if pos < self.textOffset then self.textOffset = pos end self:calculateTextClip() local textClip = self.textClip while (textClip) and (pos > self.textOffset + textClip) do self.textOffset = self.textOffset + 1 self:calculateTextClip() textClip = self.textClip end while self.textOffset > 0 and not textClip do self.textOffset = self.textOffset - 1 self:calculateTextClip() textClip = self.textClip if textClip then self.textOffset = self.textOffset + 1 self:calculateTextClip() end end -- world.logInfo("cursor: %s, textOffset: %s, textClip: %s", pos, self.textOffset, self.textClip) local text = self.text local cursorX = 0 for i=self.textOffset + 1,pos,1 do local charWidth = PtUtil.getStringWidth(text:sub(i, i), self.fontSize) cursorX = cursorX + charWidth end self.cursorX = cursorX self.cursorTimer = self.cursorRate end -- Calculates the text clip, i.e. how many characters to display. function TextField:calculateTextClip() local maxX = self.width - self.hPadding * 2 local text = self.text local totalWidth = 0 local startI = self.textOffset + 1 for i=startI,#text,1 do totalWidth = totalWidth + PtUtil.getStringWidth(text:sub(i, i), self.fontSize) if totalWidth > maxX then self.textClip = i - startI return end end self.textClip = nil end function TextField:clickEvent(position, button, pressed) local xPos = position[1] - self.x - self.offset[1] - self.hPadding local text = self.text local totalWidth = 0 for i=self.textOffset + 1,#text,1 do local charWidth = PtUtil.getStringWidth(text:sub(i, i), self.fontSize) if xPos < (totalWidth + charWidth * 0.6) then self:setCursorPosition(i - 1) return end totalWidth = totalWidth + charWidth end self:setCursorPosition(#text) end function TextField:keyEvent(keyCode, pressed) -- Ignore key releases and any keys pressed while ctrl or alt is held local keyState = GUI.keyState if not pressed or keyState[305] or keyState[306] or keyState[307] or keyState[308] then return end local shift = keyState[303] or keyState[304] local caps = keyState[301] local key = PtUtil.getKey(keyCode, shift, caps) local text = self.text local cursorPos = self.cursorPosition if #key == 1 then -- Type a character self.text = text:sub(1, cursorPos) .. key .. text:sub(cursorPos + 1) self:setCursorPosition(cursorPos + 1) else -- Special character if key == "backspace" then if cursorPos > 0 then self.text = text:sub(1, cursorPos - 1) .. text:sub(cursorPos + 1) self:setCursorPosition(cursorPos - 1) end elseif key == "enter" then if self.onEnter then self:onEnter() end elseif key == "delete" then if cursorPos < #text then self.text = text:sub(1, cursorPos) .. text:sub(cursorPos + 2) end elseif key == "right" then self:setCursorPosition(math.min(cursorPos + 1, #text)) elseif key == "left" then self:setCursorPosition(math.max(0, cursorPos - 1)) elseif key == "home" then self:setCursorPosition(0) elseif key == "end" then self:setCursorPosition(#text) end end end
Fixed mouse clicking and text clipping to actually work.
Fixed mouse clicking and text clipping to actually work. - There is a bug where drawing a string will trim the string of whitespace first.
Lua
apache-2.0
PenguinToast/PenguinGUI
3704f885ea1e982182faf421bb45d875764afe63
tools/migration/migrator/prosody_files.lua
tools/migration/migrator/prosody_files.lua
local print = print; local assert = assert; local setmetatable = setmetatable; local tonumber = tonumber; local char = string.char; local coroutine = coroutine; local lfs = require "lfs"; local loadfile = loadfile; local setfenv = setfenv; local pcall = pcall; local mtools = require "migrator.mtools"; local next = next; local pairs = pairs; local json = require "util.json"; prosody = {}; local dm = require "util.datamanager" module "prosody_files" local function is_dir(path) return lfs.attributes(path, "mode") == "directory"; end local function is_file(path) return lfs.attributes(path, "mode") == "file"; end local function clean_path(path) return path:gsub("\\", "/"):gsub("//+", "/"):gsub("^~", os.getenv("HOME") or "~"); end local encode, decode; do local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end }); decode = function (s) return s and (s:gsub("+", " "):gsub("%%([a-fA-F0-9][a-fA-F0-9])", urlcodes)); end encode = function (s) return s and (s:gsub("%W", function (c) return format("%%%02x", c:byte()); end)); end end local function decode_dir(x) if x:gsub("%%%x%x", ""):gsub("[a-zA-Z0-9]", "") == "" then return decode(x); end end local function decode_file(x) if x:match(".%.dat$") and x:gsub("%.dat$", ""):gsub("%%%x%x", ""):gsub("[a-zA-Z0-9]", "") == "" then return decode(x:gsub("%.dat$", "")); end end local function prosody_dir(path, ondir, onfile, ...) for x in lfs.dir(path) do local xpath = path.."/"..x; if decode_dir(x) and is_dir(xpath) then ondir(xpath, x, ...); elseif decode_file(x) and is_file(xpath) then onfile(xpath, x, ...); end end end local function handle_root_file(path, name) --print("root file: ", decode_file(name)) coroutine.yield { user = nil, host = nil, store = decode_file(name) }; end local function handle_host_file(path, name, host) --print("host file: ", decode_dir(host).."/"..decode_file(name)) coroutine.yield { user = nil, host = decode_dir(host), store = decode_file(name) }; end local function handle_store_file(path, name, store, host) --print("store file: ", decode_file(name).."@"..decode_dir(host).."/"..decode_dir(store)) coroutine.yield { user = decode_file(name), host = decode_dir(host), store = decode_dir(store) }; end local function handle_host_store(path, name, host) prosody_dir(path, function() end, handle_store_file, name, host); end local function handle_host_dir(path, name) prosody_dir(path, handle_host_store, handle_host_file, name); end local function handle_root_dir(path) prosody_dir(path, handle_host_dir, handle_root_file); end local function decode_user(item) local userdata = { user = item[1].user; host = item[1].host; stores = {}; }; for i=1,#item do -- loop over stores local result = {}; local store = item[i]; userdata.stores[store.store] = store.data; store.user = nil; store.host = nil; store.store = nil; end return userdata; end function reader(input) local path = clean_path(assert(input.path, "no input.path specified")); assert(is_dir(path), "input.path is not a directory"); local iter = coroutine.wrap(function()handle_root_dir(path);end); -- get per-user stores, sorted local iter = mtools.sorted { reader = function() local x = iter(); if x then dm.set_data_path(path); x.data = assert(dm.load(x.user, x.host, x.store)); return x; end end; sorter = function(a, b) local a_host, a_user, a_store = a.host or "", a.user or "", a.store or ""; local b_host, b_user, b_store = b.host or "", b.user or "", b.store or ""; return a_host > b_host or (a_host==b_host and a_user > b_user) or (a_host==b_host and a_user==b_user and a_store > b_store); end; }; -- merge stores to get users iter = mtools.merged(iter, function(a, b) return (a.host == b.host and a.user == b.user); end); return function() local x = iter(); return x and decode_user(x); end end function writer(output) local path = clean_path(assert(output.path, "no output.path specified")); assert(is_dir(path), "output.path is not a directory"); return function(item) if not item then return; end -- end of input dm.set_data_path(path); for store, data in pairs(item.stores) do assert(dm.store(item.user, item.host, store, data)); end end end return _M;
local print = print; local assert = assert; local setmetatable = setmetatable; local tonumber = tonumber; local char = string.char; local coroutine = coroutine; local lfs = require "lfs"; local loadfile = loadfile; local setfenv = setfenv; local pcall = pcall; local mtools = require "migrator.mtools"; local next = next; local pairs = pairs; local json = require "util.json"; local os_getenv = os.getenv; prosody = {}; local dm = require "util.datamanager" module "prosody_files" local function is_dir(path) return lfs.attributes(path, "mode") == "directory"; end local function is_file(path) return lfs.attributes(path, "mode") == "file"; end local function clean_path(path) return path:gsub("\\", "/"):gsub("//+", "/"):gsub("^~", os_getenv("HOME") or "~"); end local encode, decode; do local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end }); decode = function (s) return s and (s:gsub("+", " "):gsub("%%([a-fA-F0-9][a-fA-F0-9])", urlcodes)); end encode = function (s) return s and (s:gsub("%W", function (c) return format("%%%02x", c:byte()); end)); end end local function decode_dir(x) if x:gsub("%%%x%x", ""):gsub("[a-zA-Z0-9]", "") == "" then return decode(x); end end local function decode_file(x) if x:match(".%.dat$") and x:gsub("%.dat$", ""):gsub("%%%x%x", ""):gsub("[a-zA-Z0-9]", "") == "" then return decode(x:gsub("%.dat$", "")); end end local function prosody_dir(path, ondir, onfile, ...) for x in lfs.dir(path) do local xpath = path.."/"..x; if decode_dir(x) and is_dir(xpath) then ondir(xpath, x, ...); elseif decode_file(x) and is_file(xpath) then onfile(xpath, x, ...); end end end local function handle_root_file(path, name) --print("root file: ", decode_file(name)) coroutine.yield { user = nil, host = nil, store = decode_file(name) }; end local function handle_host_file(path, name, host) --print("host file: ", decode_dir(host).."/"..decode_file(name)) coroutine.yield { user = nil, host = decode_dir(host), store = decode_file(name) }; end local function handle_store_file(path, name, store, host) --print("store file: ", decode_file(name).."@"..decode_dir(host).."/"..decode_dir(store)) coroutine.yield { user = decode_file(name), host = decode_dir(host), store = decode_dir(store) }; end local function handle_host_store(path, name, host) prosody_dir(path, function() end, handle_store_file, name, host); end local function handle_host_dir(path, name) prosody_dir(path, handle_host_store, handle_host_file, name); end local function handle_root_dir(path) prosody_dir(path, handle_host_dir, handle_root_file); end local function decode_user(item) local userdata = { user = item[1].user; host = item[1].host; stores = {}; }; for i=1,#item do -- loop over stores local result = {}; local store = item[i]; userdata.stores[store.store] = store.data; store.user = nil; store.host = nil; store.store = nil; end return userdata; end function reader(input) local path = clean_path(assert(input.path, "no input.path specified")); assert(is_dir(path), "input.path is not a directory"); local iter = coroutine.wrap(function()handle_root_dir(path);end); -- get per-user stores, sorted local iter = mtools.sorted { reader = function() local x = iter(); if x then dm.set_data_path(path); x.data = assert(dm.load(x.user, x.host, x.store)); return x; end end; sorter = function(a, b) local a_host, a_user, a_store = a.host or "", a.user or "", a.store or ""; local b_host, b_user, b_store = b.host or "", b.user or "", b.store or ""; return a_host > b_host or (a_host==b_host and a_user > b_user) or (a_host==b_host and a_user==b_user and a_store > b_store); end; }; -- merge stores to get users iter = mtools.merged(iter, function(a, b) return (a.host == b.host and a.user == b.user); end); return function() local x = iter(); return x and decode_user(x); end end function writer(output) local path = clean_path(assert(output.path, "no output.path specified")); assert(is_dir(path), "output.path is not a directory"); return function(item) if not item then return; end -- end of input dm.set_data_path(path); for store, data in pairs(item.stores) do assert(dm.store(item.user, item.host, store, data)); end end end return _M;
tools/migration/migrator/prosody_files.lua: Fix for previous commit
tools/migration/migrator/prosody_files.lua: Fix for previous commit
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
c67607518dde152ebf2339f175136e6f0b98d02e
OfficerNoteWarning.lua
OfficerNoteWarning.lua
local mod = EPGP:NewModule("EPGP_OfficerNoteWarning", "AceHook-3.0") local L = LibStub:GetLibrary("AceLocale-3.0"):GetLocale("EPGP") function mod:OnInitialize() StaticPopupDialogs["EPGP_OFFICER_NOTE_WARNING"] = { text = L["EPGP is using Officer Notes for data storage. Do you really want to edit the Officer Note by hand?"], button1 = YES, button2 = NO, timeout = 0, OnAccept = function() self.hooks[GuildMemberOfficerNoteBackground]["OnMouseUp"]() end, whileDead = 1, hideOnEscape = 1, } end function mod:OnMouseUp() StaticPopup_Show("EPGP_OFFICER_NOTE_WARNING") end function mod:OnEnable() if GuildMemberOfficerNoteBackground and GuildMemberOfficerNoteBackground:HasScript("OnMouseUp") then self:HookScript(GuildMemberOfficerNoteBackground, "OnMouseUp") end end
local mod = EPGP:NewModule("EPGP_OfficerNoteWarning", "AceHook-3.0") local L = LibStub:GetLibrary("AceLocale-3.0"):GetLocale("EPGP") function mod:OnInitialize() StaticPopupDialogs["EPGP_OFFICER_NOTE_WARNING"] = { text = L["EPGP is using Officer Notes for data storage. Do you really want to edit the Officer Note by hand?"], button1 = YES, button2 = NO, timeout = 0, OnAccept = function(self) self:Hide() mod.hooks[GuildMemberOfficerNoteBackground]["OnMouseUp"]() end, whileDead = 1, hideOnEscape = 1, } end function mod:OnMouseUp() StaticPopup_Show("EPGP_OFFICER_NOTE_WARNING") end function mod:OnEnable() if GuildMemberOfficerNoteBackground and GuildMemberOfficerNoteBackground:HasScript("OnMouseUp") then self:RawHookScript(GuildMemberOfficerNoteBackground, "OnMouseUp") end end
Fix the officer note warning to not allow the edit of a note unless a user clicks accept.
Fix the officer note warning to not allow the edit of a note unless a user clicks accept.
Lua
bsd-3-clause
sheldon/epgp,ceason/epgp-tfatf,hayword/tfatf_epgp,sheldon/epgp,protomech/epgp-dkp-reloaded,ceason/epgp-tfatf,protomech/epgp-dkp-reloaded,hayword/tfatf_epgp
709a9003d276d74e28417b28464db6cd2a0f19d1
inputbox.lua
inputbox.lua
require "rendertext" require "keys" require "graphics" InputBox = { -- Class vars: h = 100, input_slot_w = nil, input_start_x = 145, input_start_y = nil, input_cur_x = nil, -- points to the start of next input pos input_bg = 0, input_string = "", shiftmode = false, altmode = false, cursor = nil, -- font for displaying input content -- we have to use mono here for better distance controlling face = freetype.newBuiltinFace("mono", 25), fhash = "m25", fheight = 25, fwidth = 15, } function InputBox:addString(str) for i = 1, #str do self:addChar(str:sub(i,i)) end end function InputBox:refreshText() -- clear previous painted text fb.bb:paintRect(140, self.input_start_y-19, self.input_slot_w, self.fheight, self.input_bg) -- paint new text renderUtf8Text(fb.bb, self.input_start_x, self.input_start_y, self.face, self.fhash, self.input_string, 0) end function InputBox:addChar(char) self.cursor:clear() -- draw new text local cur_index = (self.cursor.x_pos + 3 - self.input_start_x) / self.fwidth self.input_string = self.input_string:sub(0,cur_index)..char.. self.input_string:sub(cur_index+1) self:refreshText() self.input_cur_x = self.input_cur_x + self.fwidth -- draw new cursor self.cursor:moveHorizontal(self.fwidth) self.cursor:draw() fb:refresh(1, self.input_start_x-5, self.input_start_y-25, self.input_slot_w, self.h-25) end function InputBox:delChar() if self.input_start_x == self.input_cur_x then return end self.cursor:clear() -- draw new text local cur_index = (self.cursor.x_pos + 3 - self.input_start_x) / self.fwidth self.input_string = self.input_string:sub(0,cur_index-1).. self.input_string:sub(cur_index+1, -1) self:refreshText() self.input_cur_x = self.input_cur_x - self.fwidth -- draw new cursor self.cursor:moveHorizontal(-self.fwidth) self.cursor:draw() fb:refresh(1, self.input_start_x-5, self.input_start_y-25, self.input_slot_w, self.h-25) end function InputBox:clearText() self.cursor:clear() self.input_string = "" self:refreshText() self.cursor.x_pos = self.input_start_x - 3 self.cursor:draw() fb:refresh(1, self.input_start_x-5, self.input_start_y-25, self.input_slot_w, self.h-25) end function InputBox:drawBox(ypos, w, h, title) -- draw input border fb.bb:paintRect(20, ypos, w, h, 5) -- draw input slot fb.bb:paintRect(140, ypos + 10, w - 130, h - 20, self.input_bg) -- draw input title renderUtf8Text(fb.bb, 35, self.input_start_y, self.face, self.fhash, title, true) end ---------------------------------------------------------------------- -- InputBox:input() -- -- @title: input prompt for the box -- @d_text: default to nil (used to set default text in input slot) ---------------------------------------------------------------------- function InputBox:input(ypos, height, title, d_text) -- do some initilization self.h = height self.input_start_y = ypos + 35 self.input_cur_x = self.input_start_x self.input_slot_w = fb.bb:getWidth() - 170 self.cursor = Cursor:new { x_pos = self.input_start_x - 3, y_pos = ypos + 13, h = 30, } -- draw box and content w = fb.bb:getWidth() - 40 h = height - 45 self:drawBox(ypos, w, h, title) self.cursor:draw() if d_text then self.input_string = d_text self:addString(self.input_string) end fb:refresh(1, 20, ypos, w, h) while true do local ev = input.waitForEvent() ev.code = adjustKeyEvents(ev) if ev.type == EV_KEY and ev.value == EVENT_VALUE_KEY_PRESS then local secs, usecs = util.gettime() if ev.code == KEY_FW_UP then elseif ev.code == KEY_FW_DOWN then elseif ev.code == KEY_A then self:addChar("a") elseif ev.code == KEY_B then self:addChar("b") elseif ev.code == KEY_C then self:addChar("c") elseif ev.code == KEY_D then self:addChar("d") elseif ev.code == KEY_E then self:addChar("e") elseif ev.code == KEY_F then self:addChar("f") elseif ev.code == KEY_G then self:addChar("g") elseif ev.code == KEY_H then self:addChar("h") elseif ev.code == KEY_I then self:addChar("i") elseif ev.code == KEY_J then self:addChar("j") elseif ev.code == KEY_K then self:addChar("k") elseif ev.code == KEY_L then self:addChar("l") elseif ev.code == KEY_M then self:addChar("m") elseif ev.code == KEY_N then self:addChar("n") elseif ev.code == KEY_O then self:addChar("o") elseif ev.code == KEY_P then self:addChar("p") elseif ev.code == KEY_Q then self:addChar("q") elseif ev.code == KEY_R then self:addChar("r") elseif ev.code == KEY_S then self:addChar("s") elseif ev.code == KEY_T then self:addChar("t") elseif ev.code == KEY_U then self:addChar("u") elseif ev.code == KEY_V then self:addChar("v") elseif ev.code == KEY_W then self:addChar("w") elseif ev.code == KEY_X then self:addChar("x") elseif ev.code == KEY_Y then self:addChar("y") elseif ev.code == KEY_Z then self:addChar("z") elseif ev.code == KEY_1 then self:addChar("1") elseif ev.code == KEY_2 then self:addChar("2") elseif ev.code == KEY_3 then self:addChar("3") elseif ev.code == KEY_4 then self:addChar("4") elseif ev.code == KEY_5 then self:addChar("5") elseif ev.code == KEY_6 then self:addChar("6") elseif ev.code == KEY_7 then self:addChar("7") elseif ev.code == KEY_8 then self:addChar("8") elseif ev.code == KEY_9 then self:addChar("9") elseif ev.code == KEY_0 then self:addChar("0") elseif ev.code == KEY_SPACE then self:addChar(" ") elseif ev.code == KEY_PGFWD then elseif ev.code == KEY_PGBCK then elseif ev.code == KEY_FW_LEFT then if (self.cursor.x_pos + 3) > self.input_start_x then self.cursor:moveHorizontalAndDraw(-self.fwidth) fb:refresh(1, self.input_start_x-5, ypos, self.input_slot_w, h) end elseif ev.code == KEY_FW_RIGHT then if (self.cursor.x_pos + 3) < self.input_cur_x then self.cursor:moveHorizontalAndDraw(self.fwidth) fb:refresh(1,self.input_start_x-5, ypos, self.input_slot_w, h) end elseif ev.code == KEY_ENTER or ev.code == KEY_FW_PRESS then if self.input_string == "" then self.input_string = nil end break elseif ev.code == KEY_DEL then if Keys.shiftmode then self:clearText() else self:delChar() end elseif ev.code == KEY_BACK then self.input_string = nil break end local nsecs, nusecs = util.gettime() local dur = (nsecs - secs) * 1000000 + nusecs - usecs print("E: T="..ev.type.." V="..ev.value.." C="..ev.code.." DUR="..dur) end -- if end -- while return self.input_string end
require "rendertext" require "keys" require "graphics" InputBox = { -- Class vars: h = 100, input_slot_w = nil, input_start_x = 145, input_start_y = nil, input_cur_x = nil, -- points to the start of next input pos input_bg = 0, input_string = "", shiftmode = false, altmode = false, cursor = nil, -- font for displaying input content -- we have to use mono here for better distance controlling face = freetype.newBuiltinFace("mono", 25), fhash = "m25", fheight = 25, fwidth = 15, } function InputBox:refreshText() -- clear previous painted text fb.bb:paintRect(140, self.input_start_y-19, self.input_slot_w, self.fheight, self.input_bg) -- paint new text renderUtf8Text(fb.bb, self.input_start_x, self.input_start_y, self.face, self.fhash, self.input_string, 0) end function InputBox:addChar(char) self.cursor:clear() -- draw new text local cur_index = (self.cursor.x_pos + 3 - self.input_start_x) / self.fwidth self.input_string = self.input_string:sub(0,cur_index)..char.. self.input_string:sub(cur_index+1) self:refreshText() self.input_cur_x = self.input_cur_x + self.fwidth -- draw new cursor self.cursor:moveHorizontal(self.fwidth) self.cursor:draw() fb:refresh(1, self.input_start_x-5, self.input_start_y-25, self.input_slot_w, self.h-25) end function InputBox:delChar() if self.input_start_x == self.input_cur_x then return end self.cursor:clear() -- draw new text local cur_index = (self.cursor.x_pos + 3 - self.input_start_x) / self.fwidth self.input_string = self.input_string:sub(0,cur_index-1).. self.input_string:sub(cur_index+1, -1) self:refreshText() self.input_cur_x = self.input_cur_x - self.fwidth -- draw new cursor self.cursor:moveHorizontal(-self.fwidth) self.cursor:draw() fb:refresh(1, self.input_start_x-5, self.input_start_y-25, self.input_slot_w, self.h-25) end function InputBox:clearText() self.cursor:clear() self.input_string = "" self:refreshText() self.cursor.x_pos = self.input_start_x - 3 self.cursor:draw() fb:refresh(1, self.input_start_x-5, self.input_start_y-25, self.input_slot_w, self.h-25) end function InputBox:drawBox(ypos, w, h, title) -- draw input border fb.bb:paintRect(20, ypos, w, h, 5) -- draw input slot fb.bb:paintRect(140, ypos + 10, w - 130, h - 20, self.input_bg) -- draw input title renderUtf8Text(fb.bb, 35, self.input_start_y, self.face, self.fhash, title, true) end ---------------------------------------------------------------------- -- InputBox:input() -- -- @title: input prompt for the box -- @d_text: default to nil (used to set default text in input slot) ---------------------------------------------------------------------- function InputBox:input(ypos, height, title, d_text) -- do some initilization self.h = height self.input_start_y = ypos + 35 self.input_cur_x = self.input_start_x self.input_slot_w = fb.bb:getWidth() - 170 self.cursor = Cursor:new { x_pos = self.input_start_x - 3, y_pos = ypos + 13, h = 30, } -- draw box and content w = fb.bb:getWidth() - 40 h = height - 45 self:drawBox(ypos, w, h, title) if d_text then self.input_string = d_text self.input_cur_x = self.input_cur_x + (self.fwidth * d_text:len()) self.cursor.x_pos = self.cursor.x_pos + (self.fwidth * d_text:len()) self:refreshText() end self.cursor:draw() fb:refresh(1, 20, ypos, w, h) while true do local ev = input.waitForEvent() ev.code = adjustKeyEvents(ev) if ev.type == EV_KEY and ev.value == EVENT_VALUE_KEY_PRESS then local secs, usecs = util.gettime() if ev.code == KEY_FW_UP then elseif ev.code == KEY_FW_DOWN then elseif ev.code == KEY_A then self:addChar("a") elseif ev.code == KEY_B then self:addChar("b") elseif ev.code == KEY_C then self:addChar("c") elseif ev.code == KEY_D then self:addChar("d") elseif ev.code == KEY_E then self:addChar("e") elseif ev.code == KEY_F then self:addChar("f") elseif ev.code == KEY_G then self:addChar("g") elseif ev.code == KEY_H then self:addChar("h") elseif ev.code == KEY_I then self:addChar("i") elseif ev.code == KEY_J then self:addChar("j") elseif ev.code == KEY_K then self:addChar("k") elseif ev.code == KEY_L then self:addChar("l") elseif ev.code == KEY_M then self:addChar("m") elseif ev.code == KEY_N then self:addChar("n") elseif ev.code == KEY_O then self:addChar("o") elseif ev.code == KEY_P then self:addChar("p") elseif ev.code == KEY_Q then self:addChar("q") elseif ev.code == KEY_R then self:addChar("r") elseif ev.code == KEY_S then self:addChar("s") elseif ev.code == KEY_T then self:addChar("t") elseif ev.code == KEY_U then self:addChar("u") elseif ev.code == KEY_V then self:addChar("v") elseif ev.code == KEY_W then self:addChar("w") elseif ev.code == KEY_X then self:addChar("x") elseif ev.code == KEY_Y then self:addChar("y") elseif ev.code == KEY_Z then self:addChar("z") elseif ev.code == KEY_1 then self:addChar("1") elseif ev.code == KEY_2 then self:addChar("2") elseif ev.code == KEY_3 then self:addChar("3") elseif ev.code == KEY_4 then self:addChar("4") elseif ev.code == KEY_5 then self:addChar("5") elseif ev.code == KEY_6 then self:addChar("6") elseif ev.code == KEY_7 then self:addChar("7") elseif ev.code == KEY_8 then self:addChar("8") elseif ev.code == KEY_9 then self:addChar("9") elseif ev.code == KEY_0 then self:addChar("0") elseif ev.code == KEY_SPACE then self:addChar(" ") elseif ev.code == KEY_PGFWD then elseif ev.code == KEY_PGBCK then elseif ev.code == KEY_FW_LEFT then if (self.cursor.x_pos + 3) > self.input_start_x then self.cursor:moveHorizontalAndDraw(-self.fwidth) fb:refresh(1, self.input_start_x-5, ypos, self.input_slot_w, h) end elseif ev.code == KEY_FW_RIGHT then if (self.cursor.x_pos + 3) < self.input_cur_x then self.cursor:moveHorizontalAndDraw(self.fwidth) fb:refresh(1,self.input_start_x-5, ypos, self.input_slot_w, h) end elseif ev.code == KEY_ENTER or ev.code == KEY_FW_PRESS then if self.input_string == "" then self.input_string = nil end break elseif ev.code == KEY_DEL then if Keys.shiftmode then self:clearText() else self:delChar() end elseif ev.code == KEY_BACK or ev.code == KEY_HOME then self.input_string = nil break end local nsecs, nusecs = util.gettime() local dur = (nsecs - secs) * 1000000 + nusecs - usecs print("E: T="..ev.type.." V="..ev.value.." C="..ev.code.." DUR="..dur) end -- if end -- while return self.input_string end
fix: handle default text in inputbox
fix: handle default text in inputbox
Lua
agpl-3.0
apletnev/koreader-base,frankyifei/koreader-base,houqp/koreader-base,frankyifei/koreader-base,Hzj-jie/koreader-base,houqp/koreader,Frenzie/koreader-base,houqp/koreader-base,Hzj-jie/koreader-base,NiLuJe/koreader,Markismus/koreader,robert00s/koreader,poire-z/koreader,NiLuJe/koreader-base,Frenzie/koreader-base,koreader/koreader-base,apletnev/koreader-base,frankyifei/koreader-base,Hzj-jie/koreader,lgeek/koreader,koreader/koreader,noname007/koreader,NiLuJe/koreader-base,NiLuJe/koreader-base,Frenzie/koreader-base,apletnev/koreader-base,koreader/koreader,mihailim/koreader,chrox/koreader,koreader/koreader-base,frankyifei/koreader-base,Frenzie/koreader,mwoz123/koreader,Hzj-jie/koreader-base,pazos/koreader,ashhher3/koreader,apletnev/koreader-base,koreader/koreader-base,Frenzie/koreader-base,poire-z/koreader,frankyifei/koreader,NiLuJe/koreader-base,NickSavage/koreader,Frenzie/koreader,houqp/koreader-base,NiLuJe/koreader,Hzj-jie/koreader-base,koreader/koreader-base,houqp/koreader-base,apletnev/koreader,ashang/koreader,chihyang/koreader
8eeedf319f8fc65a06d4219df86c1feffaab6ff8
example.lua
example.lua
local tea = require "teateatea"; --[[ local tab = tea.pack(str, separator[, drop_empty, trim_value_whitespaces, multi_separators]); local tab = tea.kvpack(str, equals, separator[, drop_empty, trim_key_whitespaces, trim_value_whitespaces, multi_equals, multi_separators]); local trimed_str = tea.trim(str); where: str = "string" or metatable.__tostring result (target string) separator = "string" or metatable.__tostring result (separation token) equals = "string" or metatable.__tostring result (equals token) drop_empty = boolean (don't push empty values) trim_key_whitespaces = boolean (trim whitespaces from key before pushing) trim_value_whitespaces = boolean (trim whitespaces from value before pushing) multi_separators = boolean (use the separator value as a collection of 1 byte separation tokens) UTF-8 (2 bytes and more) is unsupported multi_equals = boolean (use the equals value as a collection of 1 byte equals tokens) UTF-8 (2 bytes and more) is unsupported ]] -- *** basic: local str = "abc;bcd;qwety;;;lol"; local tab = tea.pack(str, ";"); -- split str into the array bellow --[[ tab = { [1] = 'abc', [2] = 'bcd', [3] = 'qwerty', [4] = '', [5] = '', [6] = 'lol', } ]] --- *** key separator: local str = "abcCUTbcdCUTqwetyCUTCUTCUTlol"; local tab = tea.pack(str, "CUT"); --[[ tab = { [1] = 'abc', [2] = 'bcd', [3] = 'qwerty', [4] = '', [5] = '', [6] = 'lol', } ]] --- *** drop empty values: local str = "///abc/bcd/qwerty///////lastvalue//"; local tab = tea.pack(str, "/", true); -- using custom separator, setting 3rd arg to 'true' (drop empty values) --[[ tab = { [1] = 'abc', [2] = 'bcd', [3] = 'qwerty', [4] = 'lastvalue', } ]] --- *** trim whitespaces: local str = "one , two , three , , foh "; local tab = tea.pack(str, ",", nil, true); -- 4rd arg is true -> remove whitespaces before inserting --[[ tab = { [1] = 'one', [2] = 'two', [3] = 'three', [4] = '', -- to remove this, set 3rd to true [5] = 'foh', } ]] --- *** multi separators, with trim local str = "one; two! three foh"; local tab = tea.pack(str, ";! ", nil, true, true); -- 5th arg goes true (now using multi/single char separators) --[[ tab = { [1] = 'one', [2] = '', [3] = 'two', [4] = 'three', [5] = '', [6] = 'foh', } ]] --- *** key-value result: local str = "key1=value1;key2=value2;key3=value3"; local tab = tea.kvpack(str, "=", ";"); -- split str into the key-value table bellow --[[ tab = { ["key1"] = "value1", ["key2"] = "value2", ["key3"] = "value3", } ]] --- *** key-value big sep/eq: local str = "key1 is equal value1 and key2 is equal value2 and key3 is equal value3"; local tab = tea.kvpack(str, "is equal", "and", false, true, true); -- use multichar sep/eq, trim whitespaces --[[ tab = { ["key1"] = "value1", ["key2"] = "value2", ["key3"] = "value3", } ]] --- *** multi sep/eq: local str = "key1-value1:key2=value2;key3?value3!"; local tab = tea.kvpack(str, "=-?", ";:!", false, false, false, true, true); -- 7th (for eq) and 8th (for sep) args go true --[[ tab = { ["key1"] = "value1", ["key2"] = "value2", ["key3"] = "value3", } ]] local str = "key1=value1:key2=value2;key3=value3!"; local tab = tea.kvpack(str, "=", ";:!", false, false, false, false, true); -- only 8th goes true, if using multiple separators --[[ tab = { ["key1"] = "value1", ["key2"] = "value2", ["key3"] = "value3", } ]] --- *** empty keys are not supported! local str = "key1=value1;;;;;=broken; =broken_trimed_key; key2 = value2; key3=;key4"; local tab = tea.kvpack(str, "=", ";", false, true, true); -- trim whitespaces --[[ tab = { ["key1"] = "value1", ["key2"] = "value2", ["key3"] = "", ["key4"] = "", } ]] --- *** trim only keys local str = " key1 = value1 ; key2 = value2; key3 = ; key4 = ;"; local tab = tea.kvpack(str, "=", ";", false, true, false); -- trim whitespaces only from keys --[[ tab = { ["key1"] = " value1 ", ["key2"] = " value2", ["key3"] = " ", ["key4"] = " ", } ]] --- *** drop empty values local str = "key1=value1;=broken; =broken_trimed_key; key2 = value2; key3=;key4"; local tab = tea.kvpack(str, "=", ";", true, true, true); -- also ignore empty --[[ tab = { ["key1"] = "value1", ["key2"] = "value2", } ]] --- *** metatable.__tostring support (only for tables and userdata): local str = setmetatable({ [1] = "key1=value1"; [2] = "key2=value2"; [3] = "key3=value3"; }, { __tostring = function(self) return table.concat(self, ";"); end }); local tab = tea.kvpack(str, "=", ";"); --[[ tab = { ["key1"] = "value1", ["key2"] = "value2", ["key3"] = "value3", } ]] --- *** cookie pack example: local cookie = "cookie1=value1; cookie2=value2; cookie3=value3"; local packed_cookie = tea.kvpack(cookie, "=", ";", true, true, true); -- ignore empty values and trim whitespaces --[[ packed_cookie = { ["cookie1"] = "value1", ["cookie2"] = "value2", ["cookie3"] = "value3", } ]] --- *** string metatable.__index integration: local index = getmetatable("").__index; for k, v in next, (require"teateatea") do if (type(v) == "function") then index[k] = v; end end -- and now local tab = ("a|b|c|d"):pack("|"); --[[ tab = { [1] = "a", [2] = "b", [3] = "c", [4] = "d", } ]] -- or trim a string local str = (" TRIMED "):trim(); --[[ str = "TRIMED" ]]
local tea = require "teateatea"; --[[ local tab = tea.pack(str, separator[, drop_empty, trim_value_whitespaces, multi_separators]); local tab = tea.kvpack(str, equals, separator[, drop_empty, trim_key_whitespaces, trim_value_whitespaces, multi_equals, multi_separators]); local trimed_str = tea.trim(str); where: str = "string" or metatable.__tostring result (target string) separator = "string" or metatable.__tostring result (separation token) equals = "string" or metatable.__tostring result (equals token) drop_empty = boolean (don't push empty values) trim_key_whitespaces = boolean (trim whitespaces from key before pushing) trim_value_whitespaces = boolean (trim whitespaces from value before pushing) multi_separators = boolean (use the separator value as a collection of 1 byte separation tokens) UTF-8 (2 bytes and more) is unsupported multi_equals = boolean (use the equals value as a collection of 1 byte equals tokens) UTF-8 (2 bytes and more) is unsupported ]] -- *** basic: local str = "abc;bcd;qwety;;;lol"; local tab = tea.pack(str, ";"); -- split the str value into the array bellow --[[ tab = { [1] = 'abc', [2] = 'bcd', [3] = 'qwerty', [4] = '', [5] = '', [6] = 'lol', } ]] --- *** key separator: local str = "abcCUTbcdCUTqwetyCUTCUTCUTlol"; local tab = tea.pack(str, "CUT"); --[[ tab = { [1] = 'abc', [2] = 'bcd', [3] = 'qwerty', [4] = '', [5] = '', [6] = 'lol', } ]] --- *** drop empty values: local str = "///abc/bcd/qwerty///////lastvalue//"; local tab = tea.pack(str, "/", true); -- using the custom separator '/', setting the 3rd arg to 'true' (drop empty values) --[[ tab = { [1] = 'abc', [2] = 'bcd', [3] = 'qwerty', [4] = 'lastvalue', } ]] --- *** trim whitespaces: local str = "one , two , three , , foh "; local tab = tea.pack(str, ",", false, true); -- 4rd arg is true -> to remove any whitespaces before a value insertion --[[ tab = { [1] = 'one', [2] = 'two', [3] = 'three', [4] = '', -- to remove this, set 3rd to true [5] = 'foh', } ]] --- *** multi separators, with trim local str = "one; two! three foh"; local tab = tea.pack(str, ";! ", nil, true, true); -- 5th arg goes true (now using set of single char separators) --[[ tab = { [1] = 'one', [2] = '', [3] = 'two', [4] = 'three', [5] = '', [6] = 'foh', } ]] --- *** key-value result: local str = "key1=value1;key2=value2;key3=value3"; local tab = tea.kvpack(str, "=", ";"); -- split the str value into the key-value table bellow --[[ tab = { ["key1"] = "value1", ["key2"] = "value2", ["key3"] = "value3", } ]] --- *** key-value long sep/eq: local str = "key1 is equal value1 and key2 is equal value2 and key3 is equal value3"; local tab = tea.kvpack(str, "is equal", "and", false, true, true); -- use long sep/eq, trim whitespaces --[[ tab = { ["key1"] = "value1", ["key2"] = "value2", ["key3"] = "value3", } ]] --- *** multi sep/eq: local str = "key1-value1:key2=value2;key3?value3!"; local tab = tea.kvpack(str, "=-?", ";:!", false, false, false, true, true); -- 7th (for eq) and 8th (for sep) args go true --[[ tab = { ["key1"] = "value1", ["key2"] = "value2", ["key3"] = "value3", } ]] local str = "key1=value1:key2=value2;key3=value3!"; local tab = tea.kvpack(str, "=", ";:!", false, false, false, false, true); -- 8th goes true, if using a set of single char separators --[[ tab = { ["key1"] = "value1", ["key2"] = "value2", ["key3"] = "value3", } ]] --- *** empty keys are not supported! local str = "key1=value1;;;;;=broken; =broken_trimed_key; key2 = value2; key3=;key4"; local tab = tea.kvpack(str, "=", ";", false, true, true); -- trim whitespaces (but do not drop empty values) --[[ tab = { ["key1"] = "value1", ["key2"] = "value2", ["key3"] = "", ["key4"] = "", } ]] --- *** trim only keys local str = " key1 = value1 ; key2 = value2; key3 = ; key4 = ;"; local tab = tea.kvpack(str, "=", ";", false, true, false); -- trim whitespaces only from keys --[[ tab = { ["key1"] = " value1 ", ["key2"] = " value2", ["key3"] = " ", ["key4"] = " ", } ]] --- *** drop empty values local str = "key1=value1;=broken; =broken_trimed_key; key2 = value2; key3=;key4"; local tab = tea.kvpack(str, "=", ";", true, true, true); -- also ignore empty values and trim both (keys and values) --[[ tab = { ["key1"] = "value1", ["key2"] = "value2", } ]] --- *** metatable.__tostring support: local str = setmetatable({ [1] = "key1=value1"; [2] = "key2=value2"; [3] = "key3=value3"; }, { __tostring = function(self) return table.concat(self, ";"); end }); local tab = tea.kvpack(str, "=", ";"); --[[ tab = { ["key1"] = "value1", ["key2"] = "value2", ["key3"] = "value3", } ]] --- *** cookie pack example: local cookie = "cookie1=value1; cookie2=value2; cookie3=value3"; local packed_cookie = tea.kvpack(cookie, "=", ";", true, true, true); -- ignore empty values and trim whitespaces --[[ packed_cookie = { ["cookie1"] = "value1", ["cookie2"] = "value2", ["cookie3"] = "value3", } ]] --- *** string metatable.__index integration: local index = getmetatable("").__index; for k, v in next, (require"teateatea") do if (type(v) == "function") then index[k] = v; end end -- and now local tab = ("a|b|c|d"):pack("|"); --[[ tab = { [1] = "a", [2] = "b", [3] = "c", [4] = "d", } ]] -- or trim a string local str = (" TRIMED "):trim(); --[[ str = "TRIMED" ]]
fix som example misunderstanding
fix som example misunderstanding
Lua
mit
Darvame/teateatea
4fcb1e856f5d1456efd73ffaac379c06f615df18
tundra.lua
tundra.lua
require "tundra.syntax.glob" require "tundra.syntax.rust-cargo" ----------------------------------------------------------------------------------------------------------------------- local common = { Env = { M68KMAKE = "$(OBJECTDIR)$(SEP)m68kmake$(PROGSUFFIX)", M68KEMUPATH = "native/musashi", }, } ----------------------------------------------------------------------------------------------------------------------- local clang_opts = { { "-O0", "-g"; Config = "*-*-debug" }, { "-O3", "-g"; Config = "*-*-release" }, } ----------------------------------------------------------------------------------------------------------------------- local gcc_opts = { "-I.", "-Wno-array-bounds", "-Wno-attributes", "-Wno-unused-value", "-fPIC", { "-O0", "-g"; Config = "*-*-debug" }, { "-O3", "-g"; Config = "*-*-release" }, } ----------------------------------------------------------------------------------------------------------------------- local win64_opts = { "/EHsc", "/FS", "/MT", "/W3", "/I.", "/WX", "/DUNICODE", "/D_UNICODE", "/DWIN32", "/D_CRT_SECURE_NO_WARNINGS", "/wd4200", "/wd4152", "/wd4996", "/wd4389", "/wd4201", "/wd4152", "/wd4996", "/wd4389", { "/Od"; Config = "*-*-debug" }, { "/O2"; Config = "*-*-release" }, } ----------------------------------------------------------------------------------------------------------------------- local macosx = { Env = { CCOPTS = { clang_opts }, CXXOPTS = { clang_opts }, M68KMAKE = "$(OBJECTDIR)$(SEP)m68kmake$(PROGSUFFIX)", M68KEMUPATH = "native/musashi", }, } ----------------------------------------------------------------------------------------------------------------------- local win64 = { Env = { GENERATE_PDB = "1", CCOPTS = { win64_opts }, CXXOPTS = { win64_opts }, M68KMAKE = "$(OBJECTDIR)$(SEP)m68kmake$(PROGSUFFIX)", M68KEMUPATH = "native/musashi", }, } ----------------------------------------------------------------------------------------------------------------------- Build { Passes = { BuildTools = { Name="Build Tools", BuildOrder = 1 }, CodeGeneration = { Name="CodeGeneration", BuildOrder = 2 }, }, Units = { "units.lua", }, Configs = { Config { Name = "macosx-clang", DefaultOnHost = "macosx", Inherit = macosx, Tools = { "clang-osx", "rust" } }, Config { Name = "win64-msvc", DefaultOnHost = { "windows" }, Inherit = win64, Tools = { "msvc", "rust" } }, Config { Name = "linux-gcc", DefaultOnHost = { "linux" }, Inherit = gcc_opts, Tools = { "gcc", "rust" } }, }, }
require "tundra.syntax.glob" require "tundra.syntax.rust-cargo" ----------------------------------------------------------------------------------------------------------------------- local common = { Env = { M68KMAKE = "$(OBJECTDIR)$(SEP)m68kmake$(PROGSUFFIX)", M68KEMUPATH = "native/musashi", }, } ----------------------------------------------------------------------------------------------------------------------- local clang_opts = { { "-O0", "-g"; Config = "*-*-debug" }, { "-O3", "-g"; Config = "*-*-release" }, } ----------------------------------------------------------------------------------------------------------------------- local gcc_opts = { "-I.", "-Wno-array-bounds", "-Wno-attributes", "-Wno-unused-value", "-fPIC", { "-O0", "-g"; Config = "*-*-debug" }, { "-O3", "-g"; Config = "*-*-release" }, } ----------------------------------------------------------------------------------------------------------------------- local win64_opts = { "/EHsc", "/FS", "/MT", "/W3", "/I.", "/WX", "/DUNICODE", "/D_UNICODE", "/DWIN32", "/D_CRT_SECURE_NO_WARNINGS", "/wd4200", "/wd4152", "/wd4996", "/wd4389", "/wd4201", "/wd4152", "/wd4996", "/wd4389", { "/Od"; Config = "*-*-debug" }, { "/O2"; Config = "*-*-release" }, } ----------------------------------------------------------------------------------------------------------------------- local macosx = { Env = { CCOPTS = { clang_opts }, CXXOPTS = { clang_opts }, M68KMAKE = "$(OBJECTDIR)$(SEP)m68kmake$(PROGSUFFIX)", M68KEMUPATH = "native/musashi", }, } ----------------------------------------------------------------------------------------------------------------------- local nix = { Env = { CCOPTS = { gcc_opts }, CXXOPTS = { gcc_opts }, M68KMAKE = "$(OBJECTDIR)$(SEP)m68kmake$(PROGSUFFIX)", M68KEMUPATH = "native/musashi", }, } ----------------------------------------------------------------------------------------------------------------------- local win64 = { Env = { GENERATE_PDB = "1", CCOPTS = { win64_opts }, CXXOPTS = { win64_opts }, M68KMAKE = "$(OBJECTDIR)$(SEP)m68kmake$(PROGSUFFIX)", M68KEMUPATH = "native/musashi", }, } ----------------------------------------------------------------------------------------------------------------------- Build { Passes = { BuildTools = { Name="Build Tools", BuildOrder = 1 }, CodeGeneration = { Name="CodeGeneration", BuildOrder = 2 }, }, Units = { "units.lua", }, Configs = { Config { Name = "macosx-clang", DefaultOnHost = "macosx", Inherit = macosx, Tools = { "clang-osx", "rust" } }, Config { Name = "win64-msvc", DefaultOnHost = { "windows" }, Inherit = win64, Tools = { "msvc", "rust" } }, Config { Name = "nix-gcc", DefaultOnHost = { "linux" }, Inherit = nix, Tools = { "gcc", "rust" } }, }, }
Fixed linux build
Fixed linux build
Lua
apache-2.0
emoon/open_depacker,emoon/open_depacker,emoon/open_depacker,emoon/open_depacker
87a91f6f84576aa0f8c01f8bac32bafaf0309f55
vararg.lua
vararg.lua
local math = require "math" local table = require "table" local error, assert, select = error, assert, select local max, unpack = math.max, table.unpack or unpack local setmetatable = setmetatable local tinsert2 = function(t, n, i, v) -- lua 5.2 rise error if index out of range -- assert(type(t) =='table') -- assert(type(n) =='number') -- assert(type(i) =='number') if i > n then t[i] = v return i end for j = n, i, -1 do t[j + 1] = t[j] end t[i] = v return n+1 end local tremove2 = function(t, n, i) -- lua 5.2 rise error if index out of range -- assert(type(t) =='table') -- assert(type(n) =='number') -- assert(type(i) =='number') if i > n then for j = n+1, i do t[j] = nil end return n end for j = i, n do t[j] = t[j+1] end return n-1 end local function idx(i, n, d) if i == nil then return d elseif i < 0 then i = n+i+1 end return i end local function pack(...) local n = select("#", ...) local v = {...} return function(...) if (...) == "#" then return n else local argc = select("#", ...) if argc == 0 then return unpack(v, 1, n) else local i, j = ... if i == nil then if j == nil then j = 0 end i = j+1 if i > 0 and i <= n then return i, v[i] end else i = idx(i, n, 1) j = idx(j, n, i) return unpack(v, i, j) end end end end end local function range(i, j, ...) local n = select("#", ...) return unpack({...}, idx(i,n), idx(j,n)) end local function remove(i, ...) local n = select("#", ...) local t = {...} i = idx(i, n) assert(i>0, "index out of bounds") if i<=n then n = tremove2(t, n, i) end return unpack(t, 1, n) end local function insert(v, i, ...) local n = select("#", ...) local t = {...} i = idx(i, n) assert(i > 0, "index out of bounds") n = tinsert2(t, n, i, v) return unpack(t, 1, n) end local function replace(v, i, ...) local n = select("#", ...) local t = {...} i = idx(i, n) assert(i > 0, "index out of bounds") t[i] = v n = max(n, i) return unpack(t, 1, n) end local function append(...) local n = select("#",...) if n <= 1 then return ... end local t = {select(2, ...)} t[n] = (...) return unpack(t, 1, n) end local function map(...) local n = select("#", ...) assert(n > 0) local f = ... local t = {} for i = 2, n do t[i-1] = f((select(i, ...))) end return unpack(t, 1, n-1) end local function packinto(n, t, ...) local c = select("#", ...) for i = 1, c do t[n+i] = select(i, ...) end return n+c end local function concat(...) local n = 0 local t = {} for i = 1, select("#", ...) do local f = select(i, ...) n = packinto(n, t, f()) end return unpack(t, 1, n) end local function count(...) return select("#", ...) end local function at(i, ...) return range(i, i, ...) end return setmetatable({ pack = pack, range = range, insert = insert, remove = remove, replace = replace, append = append, map = map, concat = concat, },{ __call = function(_, ...) return pack(...) end })
local math = require "math" local table = require "table" local error, assert, select = error, assert, select local max, unpack = math.max, table.unpack or unpack local setmetatable = setmetatable local tinsert2 = function(t, n, i, v) -- lua 5.2 rise error if index out of range -- assert(type(t) =='table') -- assert(type(n) =='number') -- assert(type(i) =='number') if i > n then t[i] = v return i end for j = n, i, -1 do t[j + 1] = t[j] end t[i] = v return n+1 end local tremove2 = function(t, n, i) -- lua 5.2 rise error if index out of range -- assert(type(t) =='table') -- assert(type(n) =='number') -- assert(type(i) =='number') if i > n then for j = n+1, i do t[j] = nil end return n end for j = i, n do t[j] = t[j+1] end return n-1 end local function idx(i, n, d) if i == nil then return d elseif i < 0 then i = n+i+1 end return i end local function pack(...) local n = select("#", ...) local v = {...} return function(...) if (...) == "#" then return n else local argc = select("#", ...) if argc == 0 then return unpack(v, 1, n) else local i, j = ... if i == nil then if j == nil then j = 0 end i = j+1 if i > 0 and i <= n then return i, v[i] end else i = idx(i, n, 1) j = idx(j, n, i) return unpack(v, i, j) end end end end end local function range(i, j, ...) local n = select("#", ...) return unpack({...}, idx(i,n), idx(j,n)) end local function remove(i, ...) local n = select("#", ...) local t = {...} i = idx(i, n) assert(i>0, "index out of bounds") if i<=n then n = tremove2(t, n, i) end return unpack(t, 1, n) end local function insert(v, i, ...) local n = select("#", ...) local t = {...} i = idx(i, n) assert(i > 0, "index out of bounds") n = tinsert2(t, n, i, v) return unpack(t, 1, n) end local function replace(v, i, ...) local n = select("#", ...) local t = {...} i = idx(i, n) assert(i > 0, "index out of bounds") t[i] = v n = max(n, i) return unpack(t, 1, n) end local function append(...) local n = select("#",...) if n <= 1 then return ... end local t = {select(2, ...)} t[n] = (...) return unpack(t, 1, n) end local function map(...) local n = select("#", ...) assert(n > 0) local f = ... local t = {} for i = 2, n do t[i-1] = f((select(i, ...))) end return unpack(t, 1, n-1) end local function packinto(n, t, ...) local c = select("#", ...) for i = 1, c do t[n+i] = select(i, ...) end return n+c end local function concat(...) local n = 0 local t = {} for i = 1, select("#", ...) do local f = select(i, ...) n = packinto(n, t, f()) end return unpack(t, 1, n) end local function count(...) return select("#", ...) end local function at(i, ...) return range(i, i, ...) end return setmetatable({ pack = pack, range = range, insert = insert, remove = remove, replace = replace, append = append, map = map, concat = concat, count = count, at = at, },{ __call = function(_, ...) return pack(...) end })
Fix. Export `count` and `at` from `vararg-lua`
Fix. Export `count` and `at` from `vararg-lua`
Lua
mit
icetoggle/lua-vararg,moteus/lua-vararg,icetoggle/lua-vararg
cca8533640be60370cc409878426b446ed0c0342
lua/autorun/includes/modules/EventEmitter.lua
lua/autorun/includes/modules/EventEmitter.lua
--- -- EventEmitter -- -- Based off of Wolfy87's JavaScript EventEmitter -- local EventEmitter = {} local function indexOfListener(listeners, listener) local i = #listeners while i > 0 do if listeners[i].listener == listener then return i end i = i - 1 end return -1 end function EventEmitter:new(obj) if obj then table.Inherit(obj, self) else return setmetatable({}, self) end end function EventEmitter:getListeners(evt) local events = self:_getEvents() local response, key -- TODO: accept pattern matching if not events[evt] then events[evt] = {} end response = events[evt] return response end --[[function EventEmitter:flattenListeners(listeners) end]] function EventEmitter:getListenersAsObject(evt) local listeners = self:getListeners(evt) local response if type(listeners) == 'table' then response = {} response[evt] = listeners end return response or listeners end function EventEmitter:addListener(evt, listener) local listeners = self:getListenersAsObject(evt) local listenerIsWrapped = type(listener) == 'table' local key for key, _ in pairs(listeners) do if rawget(listeners, key) and indexOfListener(listeners[key], listener) == -1 then table.insert(listeners[key], listenerIsWrapped and listener or { listener = listener, once = false }) end end return self end EventEmitter.on = EventEmitter.addListener function EventEmitter:addOnceListener(evt, listener) return self:addListener(evt, { listener = listener, once = true }) end EventEmitter.once = EventEmitter.addOnceListener function EventEmitter:removeListener(evt, listener) local listeners = self:getListenersAsObject(evt) local index, key for key, _ in pairs(listeners) do if rawget(listeners, key) then index = indexOfListener(listeners[key], listener) if index ~= -1 then table.remove(listeners[key], index) end end end return self end EventEmitter.off = EventEmitter.removeListener --[[function EventEmitter:addListeners(evt, listeners) end]] function EventEmitter:removeEvent(evt) local typeStr = type(evt) local events = self:_getEvents() local key if typeStr == 'string' then events[evt] = nil else self._events = nil end return self end EventEmitter.removeAllListeners = EventEmitter.removeEvent function EventEmitter:emitEvent(evt, ...) local listeners = self:getListenersAsObject(evt) local listener, i, key, response for key, _ in pairs(listeners) do if rawget(listeners, key) then i = #listeners[key] while i > 0 do listener = listeners[key][i] if listener.once == true then self:removeListener(evt, listener.listener) end response = listener.listener(...) if response == self:_getOnceReturnValue() then self:removeListener(evt, listener.listener) end i = i - 1 end end end return self end EventEmitter.trigger = EventEmitter.emitEvent EventEmitter.emit = EventEmitter.emitEvent function EventEmitter:setOnceReturnValue(value) self._onceReturnValue = value return self end function EventEmitter:_getOnceReturnValue() if rawget(self, '_onceReturnValue') then return self._onceReturnValue else return true end end function EventEmitter:_getEvents() if not rawget(self, '_events') then self._events = {} end return self._events end _G.EventEmitter = EventEmitter
--- -- EventEmitter -- -- Based off of Wolfy87's JavaScript EventEmitter -- local EventEmitter = {} local function indexOfListener(listeners, listener) local value local i = #listeners while i > 0 do value = listeners[i] if type(value) == 'table' and value.listener == listener then return i end i = i - 1 end return -1 end function EventEmitter:new(obj) if obj then table.Inherit(obj, self) else return setmetatable({}, self) end end function EventEmitter:getListeners(evt) local events = self:_getEvents() local response -- TODO: accept pattern matching if not events[evt] then local tbl = {} tbl.__array = true events[evt] = tbl end response = events[evt] return response end --[[function EventEmitter:flattenListeners(listeners) end]] function EventEmitter:getListenersAsObject(evt) local listeners = self:getListeners(evt) local response if listeners.__array then response = {} response[evt] = listeners end return response or listeners, wrapped end function EventEmitter:addListener(evt, listener) local listeners = self:getListenersAsObject(evt) local listenerIsWrapped = type(listener) == 'table' for key, _ in pairs(listeners) do if rawget(listeners, key) and indexOfListener(listeners[key], listener) == -1 then local value if listenerIsWrapped then value = listener else value = { listener = listener, once = false } end table.insert(listeners[key], value) end end return self end EventEmitter.on = EventEmitter.addListener function EventEmitter:addOnceListener(evt, listener) return self:addListener(evt, { listener = listener, once = true }) end EventEmitter.once = EventEmitter.addOnceListener function EventEmitter:removeListener(evt, listener) local listeners = self:getListenersAsObject(evt) local index for key, _ in pairs(listeners) do if rawget(listeners, key) then index = indexOfListener(listeners[key], listener) if index ~= -1 then table.remove(listeners[key], index) end end end return self end EventEmitter.off = EventEmitter.removeListener --[[function EventEmitter:addListeners(evt, listeners) end]] function EventEmitter:removeEvent(evt) local typeStr = type(evt) local events = self:_getEvents() local key if typeStr == 'string' then events[evt] = nil else self._events = nil end return self end EventEmitter.removeAllListeners = EventEmitter.removeEvent function EventEmitter:emitEvent(evt, ...) local listeners = self:getListenersAsObject(evt) local listener, i, key, response for key, _ in pairs(listeners) do if rawget(listeners, key) then i = #listeners[key] while i > 0 do listener = listeners[key][i] if listener.once == true then self:removeListener(evt, listener.listener) end response = listener.listener(...) if response == self:_getOnceReturnValue() then self:removeListener(evt, listener.listener) end i = i - 1 end end end return self end EventEmitter.trigger = EventEmitter.emitEvent EventEmitter.emit = EventEmitter.emitEvent function EventEmitter:setOnceReturnValue(value) self._onceReturnValue = value return self end function EventEmitter:_getOnceReturnValue() if rawget(self, '_onceReturnValue') then return self._onceReturnValue else return true end end function EventEmitter:_getEvents() if not self._events then self._events = {} end return self._events end _G.EventEmitter = EventEmitter
Fixed issues with EventEmitter.
Fixed issues with EventEmitter.
Lua
mit
pixeltailgames/gm-mediaplayer,pixeltailgames/gm-mediaplayer
efc5f8af3e2683b299ab15d336c4248de6a60d49
Quadtastic/AppLogic.lua
Quadtastic/AppLogic.lua
local unpack = unpack or table.unpack local quit = love.event.quit or os.exit local AppLogic = {} local function run(self, f, ...) assert(type(f) == "function") local co = coroutine.create(f) local ret = {coroutine.resume(co, self._state.data, ...)} -- Print errors if there are any assert(ret[1], ret[2]) -- If the coroutine yielded then we will issue a state switch based -- on the returned values. if coroutine.status(co) == "suspended" then local new_state = ret[2] -- Save the coroutine so that it can be resumed later self._state.coroutine = co self:push_state(new_state) else assert(coroutine.status(co) == "dead") -- If values were returned, then they will be returned to the -- next state higher up in the state stack. -- If this is the only state, then the app will exit with the -- returned integer as exit code. if #ret > 0 then if #self._state_stack > 0 then self:pop_state(select(2, unpack(ret))) else quit(ret[1]) end end end end setmetatable(AppLogic, { __call = function(_, initial_state) local application = {} application._state = initial_state application._state_stack = {} application._event_queue = {} setmetatable(application, { __index = function(self, key) if rawget(AppLogic, key) then return rawget(AppLogic, key) -- If this is a call for the current state, return that state elseif key == self._state.name then -- return a function that executes the command in a subroutine, -- and captures the function's return values return function(event, ...) local f = self._state.transitions[event] run(self, f, ...) end -- Otherwise queue that call for later if we have a queue for it elseif self._event_queue[key] then return function(...) table.insert(self._event_queue[key], ...) end else error(string.format("There is no state %s in the current application.", key)) end end }) return application end }) function AppLogic.push_state(self, new_state) assert(string.sub(new_state.name, 1, 1) ~= "_", "State name cannot start with underscore") -- Push the current state onto the state stack table.insert(self._state_stack, self._state) -- Create a new event queue for the pushed state event_queue[self._state] = {} -- Switch states self._state = new_state end function AppLogic.pop_state(self, ...) -- Return to previous state self._state = table.remove(self._state_stack) -- Resume state's current coroutine with the passed event if self._state.coroutine and coroutine.status(self._state.coroutine) == "suspended" then coroutine.resume(self._state.coroutine, ...) end -- Catch up on events that happened for that state while we were in a -- different state for _,event_bundle in ipairs(event_queue[self.state]) do local event = event_bundle[1] self._state.process(event, select(2, unpack(event_bundle))) end end function AppLogic.get_states(self) local states = {} for i,state in ipairs(self._state_stack) do states[i] = state end -- Add the current state table.insert(states, self._state) return states end function AppLogic.get_current_state(self) return self._state.name end return AppLogic
local unpack = unpack or table.unpack local quit = love.event.quit or os.exit local AppLogic = {} local function run(self, f, ...) assert(type(f) == "function") local co = coroutine.create(f) local ret = {coroutine.resume(co, self._state.data, ...)} -- Print errors if there are any assert(ret[1], ret[2]) -- If the coroutine yielded then we will issue a state switch based -- on the returned values. if coroutine.status(co) == "suspended" then local new_state = ret[2] -- Save the coroutine so that it can be resumed later self._state.coroutine = co self:push_state(new_state) else assert(coroutine.status(co) == "dead") -- If values were returned, then they will be returned to the -- next state higher up in the state stack. -- If this is the only state, then the app will exit with the -- returned integer as exit code. if #ret > 0 then if #self._state_stack > 0 then self:pop_state(select(2, unpack(ret))) else quit(ret[1]) end end end end setmetatable(AppLogic, { __call = function(_, initial_state) local application = {} application._state = initial_state application._state_stack = {} application._event_queue = {} setmetatable(application, { __index = function(self, key) if rawget(AppLogic, key) then return rawget(AppLogic, key) -- If this is a call for the current state, return that state elseif key == self._state.name then -- return a function that executes the command in a subroutine, -- and captures the function's return values return setmetatable({}, {__index = function(_, event) local f = self._state.transitions[event] return function(...) run(self, f, ...) end end}) -- Otherwise queue that call for later if we have a queue for it elseif self._event_queue[key] then return function(...) table.insert(self._event_queue[key], ...) end else error(string.format("There is no state %s in the current application.", key)) end end }) return application end }) function AppLogic.push_state(self, new_state) assert(string.sub(new_state.name, 1, 1) ~= "_", "State name cannot start with underscore") -- Push the current state onto the state stack table.insert(self._state_stack, self._state) -- Create a new event queue for the pushed state event_queue[self._state] = {} -- Switch states self._state = new_state end function AppLogic.pop_state(self, ...) -- Return to previous state self._state = table.remove(self._state_stack) -- Resume state's current coroutine with the passed event if self._state.coroutine and coroutine.status(self._state.coroutine) == "suspended" then coroutine.resume(self._state.coroutine, ...) end -- Catch up on events that happened for that state while we were in a -- different state for _,event_bundle in ipairs(event_queue[self.state]) do local event = event_bundle[1] self._state.process(event, select(2, unpack(event_bundle))) end end function AppLogic.get_states(self) local states = {} for i,state in ipairs(self._state_stack) do states[i] = state end -- Add the current state table.insert(states, self._state) return states end function AppLogic.get_current_state(self) return self._state.name end return AppLogic
Fix indirection of state transitions
Fix indirection of state transitions
Lua
mit
25A0/Quadtastic,25A0/Quadtastic
06567a7e2c065f3bbfed7fc98b33425ae95ca13a
agents/monitoring/default/protocol/request.lua
agents/monitoring/default/protocol/request.lua
--[[ Copyright 2012 Rackspace Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local table = require('table') local https = require('https') local fs = require('fs') local logging = require('logging') local errors = require('../errors') local Error = require('core').Error local misc = require('../util/misc') local fmt = require('string').format local Object = require('core').Object local exports = {} local Request = Object:extend() --[[ Attempts to upload or download a file over https to options.host:options.port OR for endpoints in options.endpoints. Will try options.attempts number of times, or for each endpoint if not specified. options = { host/port OR endpoints [{Endpoint1, Endpoint2, ...}] path = "string", method = "METHOD" upload = nil or '/some/path' download = nil or '/some/path' attempts = int or #endpoints } ]]-- local function makeRequest(...) local req = Request:new(...) req:set_headers() req:request() return req end function Request:initialize(options, callback) self.callback = misc.fireOnce(callback) if not options.method then return self.callback(Error:new('I need a http method')) end if options.endpoints then self.endpoints = misc.merge({}, options.endpoints) else self.endpoints = {{host=options.host, port=options.port}} end self.attempts = options.attempts or #self.endpoints self.download = options.download self.upload = options.upload options.endpoints = nil options.attempts = nil options.download = nil options.upload = nil self.options = options if not self:_cycle_endpoint() then return self.callback(Error:new('call with options.port and options.host or options.endpoints')) end end function Request:request() logging.debugf('sending request to %s:%s', self.options.host, self.options.port) local options = misc.merge({}, self.options) local req = https.request(options, function(res) self:_handle_response(res) end) req:on('error', function(err) self:_ensure_retries(err) end) if not self.upload then return req:done() end local data = fs.createReadStream(self.upload) data:on('data', function(chunk) req:write(chunk) end) data:on('end', function(d) req:done(d) end) data:on('error', function(err) req:done() self._ensure_retries(err) end) end function Request:_cycle_endpoint() local position, endpoint while self.attempts > 0 do position = #self.endpoints % self.attempts endpoint = self.endpoints[position+1] self.attempts = self.attempts - 1 if endpoint and endpoint.host and endpoint.port then self.options.host = endpoint.host self.options.port = endpoint.port return true end end return false end function Request:set_headers(callback) local method = self.options.method:upper() local headers = {} -- set defaults headers['Content-Length'] = 0 headers["Content-Type"] = "application/text" self.options.headers = misc.merge(headers, self.options.headers) end function Request:_write_stream(res) logging.debugf('writing stream to disk: %s.', self.download) local stream = fs.createWriteStream(self.download) stream:on('end', function() self:_ensure_retries(nil, res) end) stream:on('error', function(err) self:_ensure_retries(err, res) end) res:on('end', function(d) stream:finish(d) end) res:pipe(stream) end function Request:_ensure_retries(err, res) if not err then self.callback(err, res) return end local status = res and res.status_code or "?" local msg = fmt('%s to %s:%s failed for %s with status: %s and error: %s.', (self.options.method or "?"), self.options.host, self.options.port, (self.download or self.upload or "?"), status, tostring(err)) logging.warn(msg) if not self:_cycle_endpoint() then return self.callback(err) end logging.debugf('retrying download %d more times.', self.attempts) self:request() end function Request:_handle_response(res) if self.download and res.status_code >= 200 and res.status_code < 300 then return self:_write_stream(res) end local buf = "" res:on('data', function(d) buf = buf .. d end) res:on('end', function() if res.status_code >= 400 then return self:_ensure_retries(Error:new(buf), res) end self:_ensure_retries(nil, res) end) end local exports = {makeRequest=makeRequest, Request=Request} return exports
--[[ Copyright 2012 Rackspace Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local table = require('table') local https = require('https') local fs = require('fs') local logging = require('logging') local errors = require('../errors') local Error = require('core').Error local misc = require('../util/misc') local fmt = require('string').format local Object = require('core').Object local exports = {} local Request = Object:extend() --[[ Attempts to upload or download a file over https to options.host:options.port OR for endpoints in options.endpoints. Will try options.attempts number of times, or for each endpoint if not specified. options = { host/port OR endpoints [{Endpoint1, Endpoint2, ...}] path = "string", method = "METHOD" upload = nil or '/some/path' download = nil or '/some/path' attempts = int or #endpoints } ]]-- local function makeRequest(...) local req = Request:new(...) req:set_headers() req:request() return req end function Request:initialize(options, callback) self.callback = misc.fireOnce(callback) if not options.method then return self.callback(Error:new('I need a http method')) end if options.endpoints then self.endpoints = misc.merge({}, options.endpoints) else self.endpoints = {{host=options.host, port=options.port}} end self.attempts = options.attempts or #self.endpoints self.download = options.download self.upload = options.upload options.endpoints = nil options.attempts = nil options.download = nil options.upload = nil self.options = options if not self:_cycle_endpoint() then return self.callback(Error:new('call with options.port and options.host or options.endpoints')) end end function Request:request() logging.debugf('sending request to %s:%s', self.options.host, self.options.port) local options = misc.merge({}, self.options) local req = https.request(options, function(res) self:_handle_response(res) end) req:on('error', function(err) self:_ensure_retries(err) end) if not self.upload then return req:done() end local data = fs.createReadStream(self.upload) data:on('data', function(chunk) req:write(chunk) end) data:on('end', function(d) req:done(d) end) data:on('error', function(err) req:done() self._ensure_retries(err) end) end function Request:_cycle_endpoint() local position, endpoint while self.attempts > 0 do position = #self.endpoints % self.attempts endpoint = self.endpoints[position+1] self.attempts = self.attempts - 1 if endpoint and endpoint.host and endpoint.port then self.options.host = endpoint.host self.options.port = endpoint.port return true end end return false end function Request:set_headers(callback) local method = self.options.method:upper() local headers = {} -- set defaults headers['Content-Length'] = 0 headers["Content-Type"] = "application/text" self.options.headers = misc.merge(headers, self.options.headers) end function Request:_write_stream(res) logging.debugf('writing stream to disk: %s.', self.download) local ok, stream = pcall(function() return fs.createWriteStream(self.download) end) if not ok then -- can't make the file because the dir doens't exist if stream.code and stream.code == "ENOENT" then return self.callback(stream) end return self:_ensure_retries(err, res) end stream:on('end', function() self:_ensure_retries(nil, res) end) stream:on('error', function(err) self:_ensure_retries(err, res) end) res:on('end', function(d) stream:finish(d) end) res:pipe(stream) end function Request:_ensure_retries(err, res) if not err then self.callback(err, res) return end local status = res and res.status_code or "?" local msg = fmt('%s to %s:%s failed for %s with status: %s and error: %s.', (self.options.method or "?"), self.options.host, self.options.port, (self.download or self.upload or "?"), status, tostring(err)) logging.warn(msg) if not self:_cycle_endpoint() then return self.callback(err) end logging.debugf('retrying download %d more times.', self.attempts) self:request() end function Request:_handle_response(res) if self.download and res.status_code >= 200 and res.status_code < 300 then return self:_write_stream(res) end local buf = "" res:on('data', function(d) buf = buf .. d end) res:on('end', function() if res.status_code >= 400 then return self:_ensure_retries(Error:new(buf), res) end self:_ensure_retries(nil, res) end) end local exports = {makeRequest=makeRequest, Request=Request} return exports
Fix request.lua to handle trying to open a stupid file
Fix request.lua to handle trying to open a stupid file
Lua
apache-2.0
cp16net/virgo-base,AlphaStaxLLC/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,cp16net/virgo-base,virgo-agent-toolkit/rackspace-monitoring-agent,cp16net/virgo-base,cp16net/virgo-base,cp16net/virgo-base
e84005bc8c34a0b8137e7ddb04e5b339dc16d02c
genie/toolchain.lua
genie/toolchain.lua
-- -- Copyright (c) 2015 Jonathan Howard, Daniele Bartolini -- MIT License -- function toolchain(build_dir, lib_dir) newoption { trigger = "compiler", value = "COMPILER", description = "Choose compiler", allowed = { { "osx", "Clang - OS X" }, { "linux-gcc", "Linux (GCC compiler)" }, { "linux-clang", "Linux (Clang compiler)" } } } if (_ACTION == nil) then return end location ( build_dir .. "projects/" .. _ACTION ) if _ACTION == "clean" then os.rmdir(BUILD_DIR) end if _ACTION == "gmake" then if nil == _OPTIONS["compiler"] then print("No compiler selected.") os.exit(1) end if "linux-gcc" == _OPTIONS["compiler"] or "linux-clang" == _OPTIONS["compiler"] then if not os.is("linux") then print("Action not valid in current OS.") end location(build_dir .. "projects/" .. "linux") end if "osx" == _OPTIONS["compiler"] then if not os.is("macosx") then print("Action not valid in current OS.") end location(build_dir .. "projects/" .. "osx") end if "osx" == _OPTIONS["compiler"] or "linux-clang" == _OPTIONS["compiler"] then premake.gcc.cc = "clang" premake.gcc.cxx = "clang++" premake.gcc.ar = "ar" end end if _ACTION == "vs2013" then if not os.is("windows") then print("Action not valid in current OS.") end location(build_dir .. "projects/" .. _ACTION) end flags { "StaticRuntime", "NoPCH", "NoRTTI", "NoExceptions", "NoEditAndContinue", "Symbols" } includedirs { BGFX_DIR .. "include/", BX_DIR .. "include/" } defines { "__STDC_FORMAT_MACROS", "__STDC_CONSTANT_MACROS", "__STDC_LIMIT_MACROS", } configuration { "gmake" } buildoptions { "-m64", "-std=c++11" } configuration { "development or release" } flags { "OptimizeSpeed" } configuration { "debug", "native" } targetsuffix "-debug" configuration { "development", "native" } targetsuffix "-development" configuration { "release", "native" } targetsuffix "-release" configuration { "vs*" } targetdir( build_dir .. "windows/bin" ) objdir( build_dir .. "windows/obj" ) includedirs { BX_DIR .. "include/compat/msvc" } defines { "WIN32", "_WIN32", "_HAS_EXCEPTIONS=0", "_HAS_ITERATOR_DEBUGGING=0", "_SCL_SECURE=0", "_SECURE_SCL=0", "_SCL_SECURE_NO_WARNINGS", "_CRT_SECURE_NO_WARNINGS", "_CRT_SECURE_NO_DEPRECATE", "NOMINMAX", } buildoptions { "/Oy-", -- Suppresses creation of frame pointers on the call stack. "/Ob2", -- The Inline Function Expansion } linkoptions { "/ignore:4199", -- LNK4199: /DELAYLOAD:*.dll ignored; no imports found from *.dll "/ignore:4221", -- LNK4221: This object file does not define any previously undefined public symbols, so it will not be used by any link operation that consumes this library "/ignore:4099", -- LNK4099: The linker was unable to find your .pdb file. } configuration { "osx" } targetdir( build_dir .. "osx/bin" ) objdir( build_dir .. "osx/obj" ) libdirs { build_dir .. "osx/bin" } links { "Cocoa.framework", "CoreVideo.framework", "IOKit.framework", "OpenGL.framework", "QuartzCore.framework", "Metal.framework" } includedirs { BX_DIR .. "include/compat/osx" } configuration {} --reset config end function strip() configuration { "android-arm", "release"} postbuildcommands { "$(SILENT) echo Stripping symbols", "$(SILENT) $(ANDROID_NDK_ARM)/bin/arm-linux-androideabi-strip -s \"$(TARGET)\"" } configuration { "linux-*", "release" } postbuildcommands { "$(SILENT) echo Stripping symbols", "$(SILENT) strip -s \"$(TARGET)\"" } configuration {} -- reset configuration end
-- -- Copyright (c) 2015 Jonathan Howard, Daniele Bartolini -- MIT License -- function toolchain(build_dir, lib_dir) newoption { trigger = "compiler", value = "COMPILER", description = "Choose compiler", allowed = { { "osx", "Clang - OS X" }, { "linux-gcc", "Linux (GCC compiler)" }, { "linux-clang", "Linux (Clang compiler)" } } } if (_ACTION == nil) then return end location ( build_dir .. "projects/" .. _ACTION ) if _ACTION == "clean" then os.rmdir(BUILD_DIR) end if _ACTION == "gmake" then if nil == _OPTIONS["compiler"] then print("No compiler selected.") os.exit(1) end if "linux-gcc" == _OPTIONS["compiler"] or "linux-clang" == _OPTIONS["compiler"] then if not os.is("linux") then print("Action not valid in current OS.") end location(build_dir .. "projects/" .. "linux") end if "osx" == _OPTIONS["compiler"] then if not os.is("macosx") then print("Action not valid in current OS.") end location(build_dir .. "projects/" .. "osx") end if "osx" == _OPTIONS["compiler"] or "linux-clang" == _OPTIONS["compiler"] then premake.gcc.cc = "clang" premake.gcc.cxx = "clang++" premake.gcc.ar = "ar" end end if _ACTION == "vs2013" then if not os.is("windows") then print("Action not valid in current OS.") end location(build_dir .. "projects/" .. _ACTION) end flags { "StaticRuntime", "NoPCH", "NoRTTI", "NoExceptions", "NoEditAndContinue", "Symbols" } includedirs { BGFX_DIR .. "include/", BX_DIR .. "include/" } defines { "__STDC_FORMAT_MACROS", "__STDC_CONSTANT_MACROS", "__STDC_LIMIT_MACROS", } configuration { "gmake" } buildoptions { "-m64" } buildoptions_cpp { "-std=c++11" } configuration { "development or release" } flags { "OptimizeSpeed" } configuration { "debug", "native" } targetsuffix "-debug" configuration { "development", "native" } targetsuffix "-development" configuration { "release", "native" } targetsuffix "-release" configuration { "vs*" } targetdir( build_dir .. "windows/bin" ) objdir( build_dir .. "windows/obj" ) includedirs { BX_DIR .. "include/compat/msvc" } defines { "WIN32", "_WIN32", "_HAS_EXCEPTIONS=0", "_HAS_ITERATOR_DEBUGGING=0", "_SCL_SECURE=0", "_SECURE_SCL=0", "_SCL_SECURE_NO_WARNINGS", "_CRT_SECURE_NO_WARNINGS", "_CRT_SECURE_NO_DEPRECATE", "NOMINMAX", } buildoptions { "/Oy-", -- Suppresses creation of frame pointers on the call stack. "/Ob2", -- The Inline Function Expansion } linkoptions { "/ignore:4199", -- LNK4199: /DELAYLOAD:*.dll ignored; no imports found from *.dll "/ignore:4221", -- LNK4221: This object file does not define any previously undefined public symbols, so it will not be used by any link operation that consumes this library "/ignore:4099", -- LNK4099: The linker was unable to find your .pdb file. } configuration { "osx" } targetdir( build_dir .. "osx/bin" ) objdir( build_dir .. "osx/obj" ) libdirs { build_dir .. "osx/bin" } links { "Cocoa.framework", "CoreVideo.framework", "IOKit.framework", "OpenGL.framework", "QuartzCore.framework", "Metal.framework" } includedirs { BX_DIR .. "include/compat/osx" } configuration {} --reset config end function strip() configuration { "android-arm", "release"} postbuildcommands { "$(SILENT) echo Stripping symbols", "$(SILENT) $(ANDROID_NDK_ARM)/bin/arm-linux-androideabi-strip -s \"$(TARGET)\"" } configuration { "linux-*", "release" } postbuildcommands { "$(SILENT) echo Stripping symbols", "$(SILENT) strip -s \"$(TARGET)\"" } configuration {} -- reset configuration end
fix -std=c++11 for tools
fix -std=c++11 for tools
Lua
mit
NathanaelThompson/altertum,v3n/altertum,NathanaelThompson/altertum,NathanaelThompson/altertum,v3n/altertum,v3n/altertum
1d3a97d6555287784e11679bbfd6875a7d2a03a1
item/id_222_amulett.lua
item/id_222_amulett.lua
-- UPDATE common SET com_script='item.id_222_amulett' WHERE com_itemid IN (222); require("item.priest.jewel") require("base.common") module("item.id_222_amulett", package.seeall, package.seeall(item.priest.jewel)) function MoveItemBeforeMove( who, sourceItem, targetItem ) fnd, eff = who.effects:find(9) if (fnd) then base.common.InformNLS(who, "Der Einfluss des Daemons hindert dich daran das Amulett ab zu nehmen","The power of the demon hinders you to remove the amulet"); return false; else if ( targetItem.data == 777 ) then if ( sourceItem.itempos == 2) then who:inform("Du kannst das Amulett nicht abnehmen.") return false; else return true; end elseif targetItem.data == 111 then if sourceItem:getType() == 3 then base.common.InformNLS(who, "Etwas hindert dich daran, das Amulett auch nur anzufassen.", "Something won't let you even touch the amulet."); --return false; end end end return true; end function LookAtItem(User, Item) if ( Item.data == 666 ) then if (User:getPlayerLanguage() == 0) then world:itemInform(User,Item,"Verfluchtes Amulett des Sukkubus"); else world:itemInform(User,Item,"Cursed amulet of the Succubus"); end elseif ( Item.data == 777 ) then if (User:getPlayerLanguage() == 0) then world:itemInform(User,Item,"Leevens Amulett"); else world:itemInform(User,Item,"Leeven's amulet"); end elseif ( Item.data == 778 ) then if (User:getPlayerLanguage() == 0) then world:itemInform(User,Item,"Sternfrmiges Amulett in dessen Mitte eine stilisierte Eisflamme eingelassen ist, die sich um eine ebenso stilisierte Feuerflamme windet"); else world:itemInform(User,Item,"star-shaped amulet with a stylized iceflame in the middle, which twines about an equally stylized fireflame"); end else world:itemInform(User,Item,GetItemDescription(User,Item,1,false,false )); end end function UseItem(User,SourceItem,TargetItem,counter,param,ltstate) local target = base.common.GetFrontItem(User); if target then TargetItem = target; end if (TargetItem.id == 914) and (TargetItem.data == 666) then User:talkLanguage(Character.say,Player.german ,"#me's Hand leuchtet, ebenso wie das Drachenamulett, hell auf und als das Licht verlischt liegt ein seltsam geformter Schlssel in der Hand und die Schrift auf dem Steinsockel glht auf."); User:talkLanguage(Character.say,Player.english,"#me's Hand, as well as the dragon amulet, starts to glow brightly and as the light is gone there is a strange formed key inside the hand and the letters on the stone socket starts to shine."); world:gfx(8,TargetItem.pos); world:gfx(11,TargetItem.pos); world:gfx(31,TargetItem.pos); world:swap(TargetItem,3105,333); world:makeSound(7,TargetItem.pos); world:makeSound(26,TargetItem.pos); Keydata=0; if (User.pos.z == -6) then Keydata=666; elseif (User.pos.z == 1) then Keydata=667; elseif (User.pos.z == 3) then Keydata=668; elseif (User.pos.z == 0) then Keydata=669; end User:createItem( 2144, 1, 333, Keydata ); elseif SourceItem.data == 111 and SourceItem.itempos == 2 then if counter == 1 then RingOfPower(User); elseif counter >= 2 and counter <= 5 then if not RoadToNode(User, counter-1) then end elseif counter == 6 then MuckyLuck(User); elseif counter == 7 then RemoveMuckyLuck(User, TargetItem); elseif counter == 8 and ((TargetItem ~= nil) and (TargetItem.id ~= 0)) then world:erase(TargetItem,255); end end end function RingOfPower(User) local pos = base.common.GetFrontPosition(User); world:gfx(2,pos); world:makeSound(4,pos); local flame = world:createItemFromId(359,1,pos,true,333,0); flame.wear = 1; world:changeItem(flame); world:makeSound(7,pos); end function RoadToNode(User, effectType) local charList = world:getPlayersInRangeOf(User.pos, 5); local validChars = {}; local retVal = false; for i,char in charList do if char.id ~= User.id and char.pos.z == User.pos.z then if not char.effects:find(29) then table.insert(validChars, char); retVal = true; end end end if retVal then local target = validChars[math.random(1,table.getn(validChars))]; local effect = LongTimeEffect(29,1); effect:addValue("effectType", effectType); target.effects:addEffect(effect); end return retVal; end function RemoveMuckyLuck(User, TargetItem) local radius = 2; local foodItems = {158,159,162}; if TargetItem.id ~= 0 then for i,id in foodItems do if id == TargetItem.id and TargetItem.wear == 255 then world:erase(TargetItem,1); end end else local item; local event; event = function(pos) item = world:getItemOnField(pos); for i,id in foodItems do if id == item.id and item.wear == 255 then world:erase(item,1); return; end end end for i=1,radius do base.common.CreateCircle(User.pos,i,event); end end end function MuckyLuck(User) local radius = 2; local foodItems = {158,159,162}; local pos = base.common.GetFrontPosition(User); if world:createDynamicNPC("Mucky Luck Sheep",18,pos,0,"npc_mucky_luck_sheep.lua") then world:makeSound(13,User.pos); local event; local item; local count = 1; event = function(posi) item = world:getItemOnField(posi); if item.id == 0 then count = (count > table.getn(foodItems)) and 1 or count; item = world:createItemFromId(foodItems[count],1,posi,false,333,0); item.wear = 255; world:changeItem(item); count = count + 1; end end for i=1,radius do base.common.CreateCircle(pos,i,event); end else base.common.InformNLS(User, "Irgendetwas verhindert die Ausfhrung des Rituals.", "Something inhibits performing the ritual."); end end
-- UPDATE common SET com_script='item.id_222_amulett' WHERE com_itemid IN (222); require("item.priest.jewel") require("base.common") module("item.id_222_amulett", package.seeall) function MoveItemBeforeMove( who, sourceItem, targetItem ) fnd, eff = who.effects:find(9) if (fnd) then base.common.InformNLS(who, "Der Einfluss des Daemons hindert dich daran das Amulett ab zu nehmen","The power of the demon hinders you to remove the amulet"); return false; else if ( targetItem.data == 777 ) then if ( sourceItem.itempos == 2) then who:inform("Du kannst das Amulett nicht abnehmen.") return false; else return true; end elseif targetItem.data == 111 then if sourceItem:getType() == 3 then base.common.InformNLS(who, "Etwas hindert dich daran, das Amulett auch nur anzufassen.", "Something won't let you even touch the amulet."); --return false; end end end return true; end function LookAtItem(User, Item) if ( Item.data == 666 ) then if (User:getPlayerLanguage() == 0) then world:itemInform(User,Item,"Verfluchtes Amulett des Sukkubus"); else world:itemInform(User,Item,"Cursed amulet of the Succubus"); end elseif ( Item.data == 777 ) then if (User:getPlayerLanguage() == 0) then world:itemInform(User,Item,"Leevens Amulett"); else world:itemInform(User,Item,"Leeven's amulet"); end elseif ( Item.data == 778 ) then if (User:getPlayerLanguage() == 0) then world:itemInform(User,Item,"Sternfrmiges Amulett in dessen Mitte eine stilisierte Eisflamme eingelassen ist, die sich um eine ebenso stilisierte Feuerflamme windet"); else world:itemInform(User,Item,"star-shaped amulet with a stylized iceflame in the middle, which twines about an equally stylized fireflame"); end else world:itemInform(User,Item,GetItemDescription(User,Item,1,false,false )); end end function UseItem(User,SourceItem,TargetItem,counter,param,ltstate) local target = base.common.GetFrontItem(User); if target then TargetItem = target; end if (TargetItem.id == 914) and (TargetItem.data == 666) then User:talkLanguage(Character.say,Player.german ,"#me's Hand leuchtet, ebenso wie das Drachenamulett, hell auf und als das Licht verlischt liegt ein seltsam geformter Schlssel in der Hand und die Schrift auf dem Steinsockel glht auf."); User:talkLanguage(Character.say,Player.english,"#me's Hand, as well as the dragon amulet, starts to glow brightly and as the light is gone there is a strange formed key inside the hand and the letters on the stone socket starts to shine."); world:gfx(8,TargetItem.pos); world:gfx(11,TargetItem.pos); world:gfx(31,TargetItem.pos); world:swap(TargetItem,3105,333); world:makeSound(7,TargetItem.pos); world:makeSound(26,TargetItem.pos); Keydata=0; if (User.pos.z == -6) then Keydata=666; elseif (User.pos.z == 1) then Keydata=667; elseif (User.pos.z == 3) then Keydata=668; elseif (User.pos.z == 0) then Keydata=669; end User:createItem( 2144, 1, 333, Keydata ); elseif SourceItem.data == 111 and SourceItem.itempos == 2 then if counter == 1 then RingOfPower(User); elseif counter >= 2 and counter <= 5 then if not RoadToNode(User, counter-1) then end elseif counter == 6 then MuckyLuck(User); elseif counter == 7 then RemoveMuckyLuck(User, TargetItem); elseif counter == 8 and ((TargetItem ~= nil) and (TargetItem.id ~= 0)) then world:erase(TargetItem,255); end end end function RingOfPower(User) local pos = base.common.GetFrontPosition(User); world:gfx(2,pos); world:makeSound(4,pos); local flame = world:createItemFromId(359,1,pos,true,333,0); flame.wear = 1; world:changeItem(flame); world:makeSound(7,pos); end function RoadToNode(User, effectType) local charList = world:getPlayersInRangeOf(User.pos, 5); local validChars = {}; local retVal = false; for i,char in charList do if char.id ~= User.id and char.pos.z == User.pos.z then if not char.effects:find(29) then table.insert(validChars, char); retVal = true; end end end if retVal then local target = validChars[math.random(1,table.getn(validChars))]; local effect = LongTimeEffect(29,1); effect:addValue("effectType", effectType); target.effects:addEffect(effect); end return retVal; end function RemoveMuckyLuck(User, TargetItem) local radius = 2; local foodItems = {158,159,162}; if TargetItem.id ~= 0 then for i,id in foodItems do if id == TargetItem.id and TargetItem.wear == 255 then world:erase(TargetItem,1); end end else local item; local event; event = function(pos) item = world:getItemOnField(pos); for i,id in foodItems do if id == item.id and item.wear == 255 then world:erase(item,1); return; end end end for i=1,radius do base.common.CreateCircle(User.pos,i,event); end end end function MuckyLuck(User) local radius = 2; local foodItems = {158,159,162}; local pos = base.common.GetFrontPosition(User); if world:createDynamicNPC("Mucky Luck Sheep",18,pos,0,"npc_mucky_luck_sheep.lua") then world:makeSound(13,User.pos); local event; local item; local count = 1; event = function(posi) item = world:getItemOnField(posi); if item.id == 0 then count = (count > table.getn(foodItems)) and 1 or count; item = world:createItemFromId(foodItems[count],1,posi,false,333,0); item.wear = 255; world:changeItem(item); count = count + 1; end end for i=1,radius do base.common.CreateCircle(pos,i,event); end else base.common.InformNLS(User, "Irgendetwas verhindert die Ausfhrung des Rituals.", "Something inhibits performing the ritual."); end end
fix module statement
fix module statement
Lua
agpl-3.0
Baylamon/Illarion-Content,vilarion/Illarion-Content,KayMD/Illarion-Content,LaFamiglia/Illarion-Content,Illarion-eV/Illarion-Content
f393e4ccf6da5d9ff0941b69f074cb2756c4869c
persona.lua
persona.lua
--- -- Persona Lua auth backend using ngx location capture -- also using postgresql capture for storing sessions to db -- -- Copyright Tor Hveem <thveem> 2013 -- -- Nginx conf example: -- location /persona/ { -- internal; -- proxy_set_header Content-type 'application/json'; -- proxy_pass 'https://verifier.login.persona.org:443/verify'; -- } -- local setmetatable = setmetatable local ngx = ngx local cjson = require"cjson" local sprintf = string.format local substr = string.sub local redis = require"resty.redis" module(...) local mt = { __index = _M } -- db global local red -- -- Initialise db -- local function init_db() -- Start redis connection red = redis:new() if ngx.shared.config.redis.unix_socket_path then local ok, err = red:connect("unix:" .. ngx.shared.config.redis.unix_socket_path) if not ok then ngx.log(ngx.ERR, "failed to connect: ", err) return 'Redis error', 403 end end end -- -- End db, park it in the pool instead -- local function end_db() -- put it into the connection pool of size 100, -- with 0 idle timeout local ok, err = red:set_keepalive(0, 100) if not ok then ngx.say("failed to set keepalive: ", err) return end end function verify(assertion, audience) local vars = { assertion=assertion, audience=audience, } local options = { method = ngx.HTTP_POST, body = cjson.encode(vars) } local res, err = ngx.location.capture('/persona/', options); if not res then return { err = res } end if res.status >= 200 and res.status < 300 then return cjson.decode(res.body) else return { status= res.status, body = res.body } end end function getsess(sessionid) --local res = db.dbreq("SELECT * FROM session WHERE sessionid = '"..sessionid.."'") init_db() local res = red:hgetall(sprintf('photongx:session:%s', sessionid)) if res == ngx.null then return nil end res = red:array_to_hash(res) end_db() return res end local function setsess(personadata) -- Set cookie for session local sessionid = ngx.md5(personadata.email .. ngx.md5(personadata.expires)) ngx.header['Set-Cookie'] = 'session='..sessionid..'; path=/; HttpOnly' init_db() local key = sprintf('photongx:session:%s', sessionid) local ok, err = red:hmset(key, { sessionid = sessionid, email = personadata.email, created = ngx.now(), expires = personadata.expires, }) -- persona timestamp is javascript timestamp, so only use 10 first digits -- FIXME why is persona ttl so low?? --local ok, err = red:expireat(key, substr(personadata.expires, 1, 10)) local ok, err = red:expire(key, 3600) end_db() end function get_current_email() local cookie = ngx.var['cookie_session'] if cookie then local sess = getsess(cookie) return sess['email'] end return false end function login() ngx.req.read_body() -- app is sending application/json local body = ngx.req.get_body_data() if body then local args = cjson.decode(body) local audience = 'pex.hveem.no' local personadata = verify(args.assertion, audience) if personadata.status == 'okay' then setsess(personadata) end -- Print the data back to client return cjson.encode(personadata) else return cjson.encode{ email = false } end end function status() local cookie = ngx.var['cookie_session'] if cookie then return ( cjson.encode(getsess(cookie)) ) else return '{"email":false}' end end function logout() local cookie = ngx.var['cookie_session'] if cookie then init_db() local ok, err = red:del(sprintf('photongx:session:%s', cookie)) end_db() return 'true' else return 'false' end end local class_mt = { -- to prevent use of casual module global variables __newindex = function (table, key, val) ngx.log(ngx.ERR, 'attempt to write to undeclared variable "' .. key .. '"') end } setmetatable(_M, class_mt)
--- -- Persona Lua auth backend using ngx location capture -- using redis storing sessions -- -- Copyright Tor Hveem <thveem> 2013 -- -- Nginx conf example: -- location /persona/ { -- internal; -- proxy_set_header Content-type 'application/json'; -- proxy_pass 'https://verifier.login.persona.org:443/verify'; -- } -- local setmetatable = setmetatable local ngx = ngx local cjson = require"cjson" local sprintf = string.format local substr = string.sub local redis = require"resty.redis" module(...) local mt = { __index = _M } -- db global local red -- -- Initialise db -- local function init_db() -- Start redis connection red = redis:new() if ngx.shared.config.redis.unix_socket_path then local ok, err = red:connect("unix:" .. ngx.shared.config.redis.unix_socket_path) if not ok then ngx.log(ngx.ERR, "failed to connect: ", err) return 'Redis error', 403 end end end -- -- End db, park it in the pool instead -- local function end_db() -- put it into the connection pool of size 100, -- with 0 idle timeout local ok, err = red:set_keepalive(0, 100) if not ok then ngx.say("failed to set keepalive: ", err) return end end function verify(assertion, audience) local vars = { assertion=assertion, audience=audience, } local options = { method = ngx.HTTP_POST, body = cjson.encode(vars) } local res, err = ngx.location.capture('/persona/', options); if not res then return { err = res } end if res.status >= 200 and res.status < 300 then return cjson.decode(res.body) else return { status= res.status, body = res.body } end end function getsess(sessionid) --local res = db.dbreq("SELECT * FROM session WHERE sessionid = '"..sessionid.."'") init_db() local res = red:hgetall(sprintf('photongx:session:%s', sessionid)) if res == ngx.null then return nil end res = red:array_to_hash(res) end_db() return res end local function setsess(personadata) -- Set cookie for session local sessionid = ngx.md5(personadata.email .. ngx.md5(personadata.expires)) ngx.header['Set-Cookie'] = 'session='..sessionid..'; path=/; HttpOnly' init_db() local key = sprintf('photongx:session:%s', sessionid) local ok, err = red:hmset(key, { sessionid = sessionid, email = personadata.email, created = ngx.now(), expires = personadata.expires, }) -- persona timestamp is javascript timestamp, so only use 10 first digits -- FIXME why is persona ttl so low?? --local ok, err = red:expireat(key, substr(personadata.expires, 1, 10)) local ok, err = red:expire(key, 3600) end_db() end function get_current_email() local cookie = ngx.var['cookie_session'] if cookie then local sess = getsess(cookie) return sess['email'] end return false end function login() ngx.req.read_body() -- app is sending application/json local body = ngx.req.get_body_data() if body then local args = cjson.decode(body) local audience = 'pex.hveem.no' local personadata = verify(args.assertion, audience) if personadata.status == 'okay' then setsess(personadata) end -- Print the data back to client return cjson.encode(personadata) else return cjson.encode{ email = false } end end function status() local cookie = ngx.var['cookie_session'] if cookie then return ( cjson.encode(getsess(cookie)) ) else return '{"email":false}' end end function logout() local cookie = ngx.var['cookie_session'] if cookie then init_db() local ok, err = red:del(sprintf('photongx:session:%s', cookie)) end_db() return 'true' else return 'false' end end local class_mt = { -- to prevent use of casual module global variables __newindex = function (table, key, val) ngx.log(ngx.ERR, 'attempt to write to undeclared variable "' .. key .. '"') end } setmetatable(_M, class_mt)
fix header
fix header
Lua
bsd-3-clause
torhve/pix,torhve/pix,torhve/pix,torhve/photongx,torhve/pix,torhve/photongx
2d853ef19626e5abcd09861d854469e15cffe631
lua/entities/gmod_wire_hologram/cl_init.lua
lua/entities/gmod_wire_hologram/cl_init.lua
include( "shared.lua" ) ENT.RenderGroup = RENDERGROUP_BOTH local blocked = {} local scale_buffer = {} local clip_buffer = {} local vis_buffer = {} function ENT:Initialize( ) self:DoScale() local ownerid = self:GetNetworkedInt("ownerid") self.blocked = blocked[ownerid] or false self.clips = {} end function ENT:SetupClipping() local eidx = self:EntIndex() if clip_buffer[eidx] != nil then table.Merge( self.clips, clip_buffer[eidx] ) clip_buffer[eidx] = nil end if next(self.clips) then render.EnableClipping( true ) for _,clip in pairs( self.clips ) do if clip.enabled and clip.normal and clip.origin then local norm = clip.normal local origin = clip.origin if !clip.isglobal then norm = self:LocalToWorld( norm ) - self:GetPos() origin = self:LocalToWorld( origin ) end render.PushCustomClipPlane( norm, norm:Dot( origin ) ) end end end end function ENT:FinishClipping() if next(self.clips) then for _, clip in pairs( self.clips ) do render.PopCustomClipPlane() end render.EnableClipping( false ) end end function ENT:Draw() if self.visible != vis_buffer[self:EntIndex()] then self.visible = vis_buffer[self:EntIndex()] end if self.blocked or self.visible == false then return end //self.visible and vis_buffer[] is nil by default, but nil != false self:SetupClipping() if self:GetNWBool( "disable_shading" ) then render.SuppressEngineLighting( true ) self:DrawModel() render.SuppressEngineLighting( false ) else self:DrawModel() end self:FinishClipping() end /******************************************************************************/ local function CheckClip(eidx, cidx) clip_buffer[eidx] = clip_buffer[eidx] or {} clip_buffer[eidx][cidx] = clip_buffer[eidx][cidx] or {} return clip_buffer[eidx][cidx] end local function SetClipEnabled(eidx, cidx, enabled) local clip = CheckClip(eidx, cidx) clip.enabled = enabled end local function SetClip(eidx, cidx, origin, norm, isglobal) local clip = CheckClip(eidx, cidx) clip.normal = norm clip.origin = origin clip.isglobal = isglobal end net.Receive("wire_holograms_clip", function( netlen ) local entid = net.ReadUInt(16) while entid ~= 0 do local clipid = net.ReadUInt(16) if net.ReadBit() ~= 0 then SetClipEnabled(entid, clipid, net.ReadBit()) else SetClip(entid, clipid, net.ReadVector(), net.ReadVector(), net.ReadBit() ~= 0) end entid = net.ReadUInt(16) end end) /******************************************************************************/ local function SetScale(entindex, scale) scale_buffer[entindex] = scale local ent = Entity(entindex) if ent and ent.DoScale then ent:DoScale() end end function ENT:DoScale() local eidx = self:EntIndex() local scale = scale_buffer[eidx] or Vector(1,1,1) local count = self:GetBoneCount() or -1 if count > 1 then for i=0, count do self:ManipulateBoneScale(i, scale) end elseif self.EnableMatrix then local mat = Matrix() mat:Scale(Vector(scale.y,scale.x,scale.z)) -- Note: We're swapping X and Y because RenderMultiply isn't consistant with the rest of source self:EnableMatrix("RenderMultiply", mat) else -- Some entities, like ragdolls, cannot be resized with EnableMatrix, so lets average the three components to get a float self:SetModelScale((scale.x+scale.y+scale.z)/3,0) end local propmax = self:OBBMaxs() local propmin = self:OBBMins() self:SetRenderBounds( Vector(scale.x*propmax.x, scale.y*propmax.y, scale.z*propmax.z), Vector(scale.x*propmin.x, scale.y*propmin.y, scale.z*propmin.z) ) scale_buffer[eidx] = nil end net.Receive("wire_holograms_set_scale", function( netlen ) local index = net.ReadUInt(16) while index ~= 0 do SetScale(index, Vector(net.ReadFloat(),net.ReadFloat(),net.ReadFloat())) index = net.ReadUInt(16) end end) /******************************************************************************/ net.Receive("wire_holograms_set_visible", function( netlen ) local index = net.ReadUInt(16) while index ~= 0 do vis_buffer[index] = net.ReadBit() ~= 0 index = net.ReadUInt(16) end end ) /******************************************************************************/ concommand.Add("wire_holograms_block_client", function(ply, command, args) local toblock for _,ply in ipairs(player.GetAll()) do if ply:Name() == args[1] then toblock = ply break end end if not toblock then error("Player not found") end local id = toblock:UserID() blocked[id] = true for _,ent in ipairs(ents.FindByClass("gmod_wire_hologram")) do if ent:GetNetworkedInt("ownerid") == id then ent.blocked = true end end end, function() local names = {} for _,ply in ipairs(player.GetAll()) do table.insert(names, "wire_holograms_block_client \""..ply:Name().."\"") end table.sort(names) return names end ) concommand.Add( "wire_holograms_unblock_client", function(ply, command, args) local toblock for _,ply in ipairs(player.GetAll()) do if ply:Name() == args[1] then toblock = ply break end end if not toblock then error("Player not found") end local id = toblock:UserID() blocked[id] = nil for _,ent in ipairs(ents.FindByClass("gmod_wire_hologram")) do if ent:GetNetworkedInt("ownerid") == id then ent.blocked = false end end end, function() local names = {} for _,ply in ipairs(player.GetAll()) do if blocked[ply:UserID()] then table.insert(names, "wire_holograms_unblock_client \""..ply:Name().."\"") end end table.sort(names) return names end )
include( "shared.lua" ) ENT.RenderGroup = RENDERGROUP_BOTH local blocked = {} local scale_buffer = {} local clip_buffer = {} local vis_buffer = {} function ENT:Initialize( ) self:DoScale() local ownerid = self:GetNetworkedInt("ownerid") self.blocked = blocked[ownerid] or false self.clips = {} end function ENT:SetupClipping() local eidx = self:EntIndex() if clip_buffer[eidx] != nil then table.Merge( self.clips, clip_buffer[eidx] ) clip_buffer[eidx] = nil end if next(self.clips) then render.EnableClipping( true ) for _,clip in pairs( self.clips ) do if clip.enabled and clip.normal and clip.origin then local norm = clip.normal local origin = clip.origin if !clip.isglobal then norm = self:LocalToWorld( norm ) - self:GetPos() origin = self:LocalToWorld( origin ) end render.PushCustomClipPlane( norm, norm:Dot( origin ) ) end end end end function ENT:FinishClipping() if next(self.clips) then for _, clip in pairs( self.clips ) do render.PopCustomClipPlane() end render.EnableClipping( false ) end end function ENT:Draw() local eidx = self:EntIndex() if vis_buffer[eidx] != nil then self.visible = vis_buffer[eidx] vis_buffer[eidx] = nil end if self.blocked or self.visible == false then return end //self.visible and vis_buffer[] is nil by default, but nil != false self:SetupClipping() if self:GetNWBool( "disable_shading" ) then render.SuppressEngineLighting( true ) self:DrawModel() render.SuppressEngineLighting( false ) else self:DrawModel() end self:FinishClipping() end /******************************************************************************/ local function CheckClip(eidx, cidx) clip_buffer[eidx] = clip_buffer[eidx] or {} clip_buffer[eidx][cidx] = clip_buffer[eidx][cidx] or {} return clip_buffer[eidx][cidx] end local function SetClipEnabled(eidx, cidx, enabled) local clip = CheckClip(eidx, cidx) clip.enabled = enabled end local function SetClip(eidx, cidx, origin, norm, isglobal) local clip = CheckClip(eidx, cidx) clip.normal = norm clip.origin = origin clip.isglobal = isglobal end net.Receive("wire_holograms_clip", function( netlen ) local entid = net.ReadUInt(16) while entid ~= 0 do local clipid = net.ReadUInt(16) if net.ReadBit() ~= 0 then SetClipEnabled(entid, clipid, net.ReadBit()) else SetClip(entid, clipid, net.ReadVector(), net.ReadVector(), net.ReadBit() ~= 0) end entid = net.ReadUInt(16) end end) /******************************************************************************/ local function SetScale(entindex, scale) scale_buffer[entindex] = scale local ent = Entity(entindex) if ent and ent.DoScale then ent:DoScale() end end function ENT:DoScale() local eidx = self:EntIndex() if(scale_buffer[eidx] != nil) then self.scale = scale_buffer[eidx] scale_buffer[eidx] = nil end local scale = self.scale or Vector(1,1,1) local count = self:GetBoneCount() or -1 if count > 1 then for i=0, count do self:ManipulateBoneScale(i, scale) end elseif self.EnableMatrix then local mat = Matrix() mat:Scale(Vector(scale.y,scale.x,scale.z)) -- Note: We're swapping X and Y because RenderMultiply isn't consistant with the rest of source self:EnableMatrix("RenderMultiply", mat) else -- Some entities, like ragdolls, cannot be resized with EnableMatrix, so lets average the three components to get a float self:SetModelScale((scale.x+scale.y+scale.z)/3,0) end local propmax = self:OBBMaxs() local propmin = self:OBBMins() self:SetRenderBounds( Vector(scale.x*propmax.x, scale.y*propmax.y, scale.z*propmax.z), Vector(scale.x*propmin.x, scale.y*propmin.y, scale.z*propmin.z) ) end net.Receive("wire_holograms_set_scale", function( netlen ) local index = net.ReadUInt(16) while index ~= 0 do SetScale(index, Vector(net.ReadFloat(),net.ReadFloat(),net.ReadFloat())) index = net.ReadUInt(16) end end) /******************************************************************************/ net.Receive("wire_holograms_set_visible", function( netlen ) local index = net.ReadUInt(16) while index ~= 0 do vis_buffer[index] = net.ReadBit() ~= 0 index = net.ReadUInt(16) end end ) /******************************************************************************/ concommand.Add("wire_holograms_block_client", function(ply, command, args) local toblock for _,ply in ipairs(player.GetAll()) do if ply:Name() == args[1] then toblock = ply break end end if not toblock then error("Player not found") end local id = toblock:UserID() blocked[id] = true for _,ent in ipairs(ents.FindByClass("gmod_wire_hologram")) do if ent:GetNetworkedInt("ownerid") == id then ent.blocked = true end end end, function() local names = {} for _,ply in ipairs(player.GetAll()) do table.insert(names, "wire_holograms_block_client \""..ply:Name().."\"") end table.sort(names) return names end ) concommand.Add( "wire_holograms_unblock_client", function(ply, command, args) local toblock for _,ply in ipairs(player.GetAll()) do if ply:Name() == args[1] then toblock = ply break end end if not toblock then error("Player not found") end local id = toblock:UserID() blocked[id] = nil for _,ent in ipairs(ents.FindByClass("gmod_wire_hologram")) do if ent:GetNetworkedInt("ownerid") == id then ent.blocked = false end end end, function() local names = {} for _,ply in ipairs(player.GetAll()) do if blocked[ply:UserID()] then table.insert(names, "wire_holograms_unblock_client \""..ply:Name().."\"") end end table.sort(names) return names end )
[E2] Holograms - save scale on entity should help with the weird scale reset bug on big lag
[E2] Holograms - save scale on entity should help with the weird scale reset bug on big lag + make vis_buffer more buffer like .)
Lua
apache-2.0
NezzKryptic/Wire,immibis/wiremod,wiremod/wire,Python1320/wire,garrysmodlua/wire,Grocel/wire,mms92/wire,CaptainPRICE/wire,notcake/wire,plinkopenguin/wiremod,bigdogmat/wire,mitterdoo/wire,thegrb93/wire,sammyt291/wire,rafradek/wire,dvdvideo1234/wire
21c1cc06abd8ec3b581bda5b8c4d62af3976178e
src/formatters/init.lua
src/formatters/init.lua
-- module will not return anything, only register formatters with the main assert engine local assert = require('luassert.assert') local function fmt_string(arg) if type(arg) == "string" then return string.format("(string) '%s'", arg) end end local function fmt_number(arg) if type(arg) == "number" then return string.format("(number) %s", tostring(arg)) end end local function fmt_boolean(arg) if type(arg) == "boolean" then return string.format("(boolean) %s", tostring(arg)) end end local function fmt_nil(arg) if type(arg) == "nil" then return "(nil)" end end local function fmt_table(arg) local tmax = tonumber(assert.fmttablelevels) or 3 -- max nesting-level displayed local ft ft = function(t, l) local result = "" for k, v in pairs(t) do if type(v) == "table" then if l < tmax or tmax < 0 then result = result .. string.format(string.rep(" ",l * 2) .. "[%s] = {\n%s }\n", tostring(k), tostring(ft(v, l + 1):sub(1,-2))) else result = result .. string.format(string.rep(" ",l * 2) .. "[%s] = { ... more }\n", tostring(k)) end else if type(v) == "string" then v = "'"..v.."'" end result = result .. string.format(string.rep(" ",l * 2) .. "[%s] = %s\n", tostring(k), tostring(v)) end end return result end if type(arg) == "table" then local result if tmax == 0 then if next(arg) then result = "(table): { ... more }" else result = "(table): { }" end else result = "(table): {\n" .. ft(arg, 1):sub(1,-2) .. " }\n" result = result:gsub("{\n }\n", "{ }\n") -- cleanup empty tables result = result:sub(1,-2) -- remove trailing newline end return result end end local function fmt_function(arg) if type(arg) == "function" then local debug_info = debug.getinfo(arg) return string.format("%s @ line %s in %s", tostring(arg), tostring(debug_info.linedefined), tostring(debug_info.source)) end end local function fmt_userdata(arg) if type(arg) == "userdata" then return string.format("(userdata) '%s'", tostring(arg)) end end assert:addformatter(fmt_string) assert:addformatter(fmt_number) assert:addformatter(fmt_boolean) assert:addformatter(fmt_nil) assert:addformatter(fmt_table) assert:addformatter(fmt_function) assert:addformatter(fmt_userdata)
-- module will not return anything, only register formatters with the main assert engine local assert = require('luassert.assert') local function fmt_string(arg) if type(arg) == "string" then return string.format("(string) '%s'", arg) end end local function fmt_number(arg) if type(arg) == "number" then return string.format("(number) %s", tostring(arg)) end end local function fmt_boolean(arg) if type(arg) == "boolean" then return string.format("(boolean) %s", tostring(arg)) end end local function fmt_nil(arg) if type(arg) == "nil" then return "(nil)" end end -- register member to prevent lookup as a modifier/assertion -- sets the default table display depth assert.fmttablelevels = 3 local function fmt_table(arg) local tmax = tonumber(assert.fmttablelevels) or 3 -- max nesting-level displayed local ft ft = function(t, l) local result = "" for k, v in pairs(t) do if type(v) == "table" then if l < tmax or tmax < 0 then result = result .. string.format(string.rep(" ",l * 2) .. "[%s] = {\n%s }\n", tostring(k), tostring(ft(v, l + 1):sub(1,-2))) else result = result .. string.format(string.rep(" ",l * 2) .. "[%s] = { ... more }\n", tostring(k)) end else if type(v) == "string" then v = "'"..v.."'" end result = result .. string.format(string.rep(" ",l * 2) .. "[%s] = %s\n", tostring(k), tostring(v)) end end return result end if type(arg) == "table" then local result if tmax == 0 then if next(arg) then result = "(table): { ... more }" else result = "(table): { }" end else result = "(table): {\n" .. ft(arg, 1):sub(1,-2) .. " }\n" result = result:gsub("{\n }\n", "{ }\n") -- cleanup empty tables result = result:sub(1,-2) -- remove trailing newline end return result end end local function fmt_function(arg) if type(arg) == "function" then local debug_info = debug.getinfo(arg) return string.format("%s @ line %s in %s", tostring(arg), tostring(debug_info.linedefined), tostring(debug_info.source)) end end local function fmt_userdata(arg) if type(arg) == "userdata" then return string.format("(userdata) '%s'", tostring(arg)) end end assert:addformatter(fmt_string) assert:addformatter(fmt_number) assert:addformatter(fmt_boolean) assert:addformatter(fmt_nil) assert:addformatter(fmt_table) assert:addformatter(fmt_function) assert:addformatter(fmt_userdata)
fixed the missing member of assert; 'fmttablelevels' causing an error for a missing modifier/assertion in the tests.
fixed the missing member of assert; 'fmttablelevels' causing an error for a missing modifier/assertion in the tests.
Lua
mit
o-lim/luassert,tst2005/lua-luassert,ZyX-I/luassert,mpeterv/luassert
34592d85a063dae1f23bf803c217cabed0f04255
nvim/lua/user/ui.lua
nvim/lua/user/ui.lua
local filereadable_key = 'filereadable' local function file_exists(name) local f = io.open(name, 'r') return f ~= nil and io.close(f) end local function buf_get_var(bufnr, name, default) local ok, value = pcall(vim.api.nvim_buf_get_var, bufnr, name) if ok then return value end return default end local function update_filereadable() local path = vim.api.nvim_buf_get_name(0) if path ~= '' then vim.api.nvim_buf_set_var(0, filereadable_key, file_exists(path)) end end local function tabline() local line = {} local current = vim.fn.tabpagenr() for tabnr = 1, vim.fn.tabpagenr('$') do local winnr = vim.fn.tabpagewinnr(tabnr) local buflist = vim.fn.tabpagebuflist(tabnr) local bufnr = buflist[winnr] local path = vim.api.nvim_buf_get_name(bufnr) local name = vim.fn.fnamemodify(path, ':t') name = name ~= '' and name or '[No Name]' local flags = {} if vim.bo[bufnr].mod then table.insert(flags, '+') end if not buf_get_var(bufnr, filereadable_key, true) then table.insert(flags, '?') end local tab = { '%', tabnr, 'T', (tabnr == current and '%#TabLineSel#' or '%#TabLine#'), ' ', name, (#flags > 0 and ' ' .. table.concat(flags, '') or ''), ' ', } table.insert(line, table.concat(tab, '')) end table.insert(line, '%#TabLineFill#') return table.concat(line, '') end local function render_statusline(winnr, active) local bufnr = vim.fn.winbufnr(winnr) local path = vim.api.nvim_buf_get_name(bufnr) local is_file = (path ~= '') local l0 = {} local l1 = {} local r1 = {} local r0 = {} if active then table.insert(l0, '%#StatusLineMode#▌%#StatusLineL0#') else table.insert(l0, '%#StatusLine#') end if active then local filetype = vim.bo[bufnr].filetype table.insert(l0, filetype == '' and 'plain' or filetype) else if is_file then local rel_path = vim.fn.fnamemodify(path, ':p:~:.') table.insert(l0, rel_path) else table.insert(l0, '[No Name]') end end local flags = {} if vim.bo[bufnr].readonly then table.insert(flags, '!') end if vim.bo[bufnr].modified then table.insert(flags, '+') end if not buf_get_var(bufnr, filereadable_key, true) then table.insert(flags, '?') end if #flags > 0 then table.insert(l0, table.concat(flags, '')) end if active and is_file then local last_saved_time = buf_get_var(bufnr, 'auto_save_last_saved_time', 0) if 0 < last_saved_time and last_saved_time >= os.time() - 60 then table.insert(l1, os.date('✓ %X', last_saved_time)) end end if active then local diagnostics = { E = 0, W = 0, I = 0, H = 0 } local status = buf_get_var(bufnr, 'coc_diagnostic_info', nil) if status then diagnostics.E = diagnostics.E + (status.error or 0) diagnostics.W = diagnostics.W + (status.warning or 0) diagnostics.I = diagnostics.I + (status.information or 0) diagnostics.H = diagnostics.H + (status.hint or 0) end if diagnostics.E > 0 then local text = string.format('%%#StatusLineDiagnosticsError#%s %d%%*', '✗', diagnostics.E) table.insert(l1, text) end if diagnostics.W > 0 then local text = string.format('%%#StatusLineDiagnosticsWarning#%s %d%%*', '∆', diagnostics.W) table.insert(l1, text) end if diagnostics.I > 0 then local text = string.format('%%#StatusLineDiagnosticsInfo#%s %d%%*', '▸', diagnostics.I) table.insert(l1, text) end if diagnostics.H > 0 then local text = string.format('%%#StatusLineDiagnosticsHint#%s %d%%*', '▪︎', diagnostics.H) table.insert(l1, text) end end local coc_status = vim.g.coc_status or '' if active and coc_status ~= '' then table.insert(r1, string.sub(coc_status, 0, 60)) end if active then local encoding = vim.bo[bufnr].fileencoding local format = vim.bo[bufnr].fileformat table.insert(r0, encoding ~= '' and encoding or vim.o.encoding) table.insert(r0, format) table.insert(r0, '∙') table.insert(r0, '%l:%c') table.insert(r0, '∙') table.insert(r0, '%p%%') end return table.concat({ table.concat(l0, ' '), '%*', table.concat(l1, ' '), '%=', table.concat(r1, ' '), '%*', table.concat(r0, ' '), '%*', }, ' ') end local function statusline() local winnr = vim.g.statusline_winid local active = winnr == vim.fn.win_getid() if active then require('candle').update_mode_highlight() end return render_statusline(winnr, active) end local function setup() vim.o.tabline = [[%!v:lua.require'user.ui'.tabline()]] vim.o.statusline = [[%!v:lua.require'user.ui'.statusline()]] vim.api.nvim_exec([[ augroup user_ui_statusline autocmd! autocmd FocusGained,BufEnter,BufReadPost,BufWritePost * lua require'user.ui'.update_filereadable() autocmd WinLeave,BufLeave * lua vim.wo.statusline=require'user.ui'.statusline() autocmd BufWinEnter,WinEnter,BufEnter * set statusline< autocmd VimResized * redrawstatus augroup END ]], false) end return { setup = setup, statusline = statusline, tabline = tabline, update_filereadable = update_filereadable, }
local filereadable_key = 'filereadable' local function file_exists(name) local f = io.open(name, 'r') return f ~= nil and io.close(f) end local function buf_get_var(bufnr, name, default) local ok, value = pcall(vim.api.nvim_buf_get_var, bufnr, name) if ok then return value end return default end local function update_filereadable() local path = vim.api.nvim_buf_get_name(0) if path ~= '' then vim.api.nvim_buf_set_var(0, filereadable_key, file_exists(path)) end end local function tabline() local line = {} local current = vim.fn.tabpagenr() for tabnr = 1, vim.fn.tabpagenr('$') do local winnr = vim.fn.tabpagewinnr(tabnr) local buflist = vim.fn.tabpagebuflist(tabnr) local bufnr = buflist[winnr] local path = vim.api.nvim_buf_get_name(bufnr) local name = vim.fn.fnamemodify(path, ':t') name = name ~= '' and name or '[No Name]' -- Work around flickering tab with https://github.com/Shougo/ddu-ui-ff if string.match(name, '^ddu-') then name = 'ddu' end local flags = {} if vim.bo[bufnr].mod then table.insert(flags, '+') end if not buf_get_var(bufnr, filereadable_key, true) then table.insert(flags, '?') end local tab = { '%', tabnr, 'T', (tabnr == current and '%#TabLineSel#' or '%#TabLine#'), ' ', name, (#flags > 0 and ' ' .. table.concat(flags, '') or ''), ' ', } table.insert(line, table.concat(tab, '')) end table.insert(line, '%#TabLineFill#') return table.concat(line, '') end local function render_statusline(winnr, active) local bufnr = vim.fn.winbufnr(winnr) local path = vim.api.nvim_buf_get_name(bufnr) local is_file = (path ~= '') local l0 = {} local l1 = {} local r1 = {} local r0 = {} if active then table.insert(l0, '%#StatusLineMode#▌%#StatusLineL0#') else table.insert(l0, '%#StatusLine#') end if active then local filetype = vim.bo[bufnr].filetype table.insert(l0, filetype == '' and 'plain' or filetype) else if is_file then local rel_path = vim.fn.fnamemodify(path, ':p:~:.') table.insert(l0, rel_path) else table.insert(l0, '[No Name]') end end local flags = {} if vim.bo[bufnr].readonly then table.insert(flags, '!') end if vim.bo[bufnr].modified then table.insert(flags, '+') end if not buf_get_var(bufnr, filereadable_key, true) then table.insert(flags, '?') end if #flags > 0 then table.insert(l0, table.concat(flags, '')) end if active and is_file then local last_saved_time = buf_get_var(bufnr, 'auto_save_last_saved_time', 0) if 0 < last_saved_time and last_saved_time >= os.time() - 60 then table.insert(l1, os.date('✓ %X', last_saved_time)) end end if active then local diagnostics = { E = 0, W = 0, I = 0, H = 0 } local status = buf_get_var(bufnr, 'coc_diagnostic_info', nil) if status then diagnostics.E = diagnostics.E + (status.error or 0) diagnostics.W = diagnostics.W + (status.warning or 0) diagnostics.I = diagnostics.I + (status.information or 0) diagnostics.H = diagnostics.H + (status.hint or 0) end if diagnostics.E > 0 then local text = string.format('%%#StatusLineDiagnosticsError#%s %d%%*', '✗', diagnostics.E) table.insert(l1, text) end if diagnostics.W > 0 then local text = string.format('%%#StatusLineDiagnosticsWarning#%s %d%%*', '∆', diagnostics.W) table.insert(l1, text) end if diagnostics.I > 0 then local text = string.format('%%#StatusLineDiagnosticsInfo#%s %d%%*', '▸', diagnostics.I) table.insert(l1, text) end if diagnostics.H > 0 then local text = string.format('%%#StatusLineDiagnosticsHint#%s %d%%*', '▪︎', diagnostics.H) table.insert(l1, text) end end local coc_status = vim.g.coc_status or '' if active and coc_status ~= '' then table.insert(r1, string.sub(coc_status, 0, 60)) end if active then local encoding = vim.bo[bufnr].fileencoding local format = vim.bo[bufnr].fileformat table.insert(r0, encoding ~= '' and encoding or vim.o.encoding) table.insert(r0, format) table.insert(r0, '∙') table.insert(r0, '%l:%c') table.insert(r0, '∙') table.insert(r0, '%p%%') end return table.concat({ table.concat(l0, ' '), '%*', table.concat(l1, ' '), '%=', table.concat(r1, ' '), '%*', table.concat(r0, ' '), '%*', }, ' ') end local function statusline() local winnr = vim.g.statusline_winid local active = winnr == vim.fn.win_getid() if active then require('candle').update_mode_highlight() end return render_statusline(winnr, active) end local function setup() vim.o.tabline = [[%!v:lua.require'user.ui'.tabline()]] vim.o.statusline = [[%!v:lua.require'user.ui'.statusline()]] vim.api.nvim_exec([[ augroup user_ui_statusline autocmd! autocmd FocusGained,BufEnter,BufReadPost,BufWritePost * lua require'user.ui'.update_filereadable() autocmd WinLeave,BufLeave * lua vim.wo.statusline=require'user.ui'.statusline() autocmd BufWinEnter,WinEnter,BufEnter * set statusline< autocmd VimResized * redrawstatus augroup END ]], false) end return { setup = setup, statusline = statusline, tabline = tabline, update_filereadable = update_filereadable, }
Fix flickering tab title
Fix flickering tab title
Lua
mit
creasty/dotfiles,creasty/dotfiles,creasty/dotfiles,creasty/dotfiles,creasty/dotfiles,creasty/dotfiles,creasty/dotfiles,creasty/dotfiles
04d40a5ce4d9175fa88f1706fef7cf4796642709
mods/default/player.lua
mods/default/player.lua
-- Minetest 0.4 mod: player -- See README.txt for licensing and other information. -- The API documentation in here was moved into doc/lua_api.txt -- Set mesh for all players function switch_player_visual() prop = { mesh = "player.x", textures = {"player.png", }, colors = {{255, 255, 255, 255}, }, visual = "mesh", visual_size = {x=1, y=1}, } for _, obj in pairs(minetest.get_connected_players()) do obj:set_properties(prop) obj:set_animation({x=1, y=50}, 35, 0) --obj:set_bone_position("", {x=0,y=0,z=0}, {x=0,y=0,z=0}) end minetest.after(1.0, switch_player_visual) end minetest.after(1.0, switch_player_visual) -- Test case for attachments: An object is spawned and attached to the player with the specified name (use your own playername there) 10 seconds after the server starts test2 = { collisionbox = { 0, 0, 0, 0, 0, 0 }, visual = "cube" } minetest.register_entity("default:test2", test2) function detachments(newobject) newobject:set_detach() print ("Detached test object") end function attachments() prop = { mesh = "player.x", textures = {"player.png", }, colors = {{255, 255, 255, 255}, }, visual = "mesh", visual_size = {x=1, y=1}, } local pos={x=0,y=0,z=0} local newobject=minetest.env:add_entity(pos, "test:test2") newobject:set_properties(prop) newobject:set_animation({x=1, y=50}, 35, 0) print ("Spawned test object") for _, obj in pairs(minetest.get_connected_players()) do if(obj:get_player_name() == "MirceaKitsune") then newobject:set_attach(obj, "Bone.001", {x=0,y=3,z=0}, {x=0,y=45,z=0}) print ("Attached test object to "..obj:get_player_name()) end end minetest.after(5.0, function() detachments(newobject) end) end minetest.after(15.0, attachments)]] -- Test case for player to player attachments function attachments_player() for _, obj in pairs(minetest.get_connected_players()) do if(obj:get_player_name() == "MirceaKitsune") then for _, obj2 in pairs(minetest.get_connected_players()) do if(obj2:get_player_name() == "MirceaKitsune1") then obj2:set_attach(obj, "Bone.001", {x=0,y=6,z=0}, {x=0,y=45,z=0}) print ("Attached player "..obj2:get_player_name().." to player "..obj:get_player_name()) end end end end end minetest.after(10.0, attachments_player) -- Definitions made by this mod that other mods can use too default = {} -- Load other files dofile(minetest.get_modpath("default").."/mapgen.lua") dofile(minetest.get_modpath("default").."/leafdecay.lua") -- END
-- Minetest 0.4 mod: player -- See README.txt for licensing and other information. -- The API documentation in here was moved into doc/lua_api.txt -- Set mesh for all players function switch_player_visual() prop = { mesh = "player.x", textures = {"player.png", }, colors = {{255, 255, 255, 255}, }, visual = "mesh", visual_size = {x=1, y=1}, } for _, obj in pairs(minetest.get_connected_players()) do obj:set_properties(prop) obj:set_animation({x=1, y=50}, 35, 0) --obj:set_bone_position("", {x=0,y=0,z=0}, {x=0,y=0,z=0}) end minetest.after(1.0, switch_player_visual) end minetest.after(1.0, switch_player_visual) -- Test case for attachments: An object is spawned and attached to the player with the specified name (use your own playername there) 10 seconds after the server starts test2 = { collisionbox = { 0, 0, 0, 0, 0, 0 }, visual = "cube" } minetest.register_entity("default:test2", test2) function attachments() prop = { mesh = "player.x", textures = {"player.png", }, colors = {{255, 255, 255, 255}, }, visual = "mesh", visual_size = {x=1, y=1}, } local pos={x=0,y=0,z=0} local newobject=minetest.env:add_entity(pos, "default:test2") newobject:set_properties(prop) newobject:set_animation({x=1, y=50}, 35, 0) print ("Spawned test object") for _, obj in pairs(minetest.get_connected_players()) do if(obj:get_player_name() == "some_nick") then newobject:set_attach(obj, "Bone.001", {x=0,y=3,z=0}, {x=0,y=45,z=0}) print ("Attached test object to "..obj:get_player_name()) end end minetest.after(5.0, function() detachments(newobject) end) end minetest.after(10.0, attachments) -- Definitions made by this mod that other mods can use too default = {} -- Load other files dofile(minetest.get_modpath("default").."/mapgen.lua") dofile(minetest.get_modpath("default").."/leafdecay.lua") -- END
Fix attachment test script and unregistered entities. Thanks jin_xi for this
Fix attachment test script and unregistered entities. Thanks jin_xi for this
Lua
lgpl-2.1
evrooije/beerarchy,evrooije/beerarchy,evrooije/beerarchy
7e8dbbeeddf462628b8595c37d0a06c49eab1b9d
otouto/plugins/imdb.lua
otouto/plugins/imdb.lua
local imdb = {} imdb.command = 'imdb <query>' function imdb:init(config) imdb.triggers = utilities.triggers(self.info.username, config.cmd_pat):t('imdb', true).table imdb.inline_triggers = { "^imdb (.+)" } imdb.doc = [[* ]]..config.cmd_pat..[[imdb* _<Film>_ Sucht _Film_ bei IMDb]] end local BASE_URL = 'https://www.omdbapi.com' function imdb:get_imdb_info(id) local url = BASE_URL..'/?i='..id local res, code = https.request(url) if code ~= 200 then return end local movie_info = json.decode(res) return movie_info end function imdb:inline_callback(inline_query, config, matches) local query = matches[1] local url = BASE_URL..'/?s='..URL.escape(query) local res, code = https.request(url) if code ~= 200 then utilities.answer_inline_query(self, inline_query) return end local data = json.decode(res) if data.Response ~= "True" then utilities.answer_inline_query(self, inline_query) return end local results = '[' for num in pairs(data.Search) do if num > 5 then break; end local imdb_id = data.Search[num].imdbID local movie_info = imdb:get_imdb_info(imdb_id) local title = movie_info.Title local year = movie_info.Year local description = movie_info.Plot local text = '<b>'..movie_info.Title.. ' ('..movie_info.Year..')</b> von '..movie_info.Director..'\\n'..string.gsub(movie_info.imdbRating, '%.', ',')..'/10 | '..movie_info.Runtime..' | '.. movie_info.Genre..'\\n<i>' .. movie_info.Plot .. '</i>' local text = text:gsub('"', '\\"') if movie_info.Poster == "N/A" then img_url = 'https://anditest.perseus.uberspace.de/inlineQuerys/imdb/logo.jpg' else img_url = movie_info.Poster end results = results..'{"type":"article","id":"'..math.random(100000000000000000)..'","title":"'..title..' ('..year..')","description":"'..description..'","url":"http://imdb.com/title/'..imdb_id..'","hide_url":true,"thumb_url":"'..img_url..'","reply_markup":{"inline_keyboard":[[{"text":"IMDb-Seite aufrufen","url":"http://imdb.com/title/'..imdb_id..'"}]]},"input_message_content":{"message_text":"'..text..'","parse_mode":"HTML"}},' end local results = results:sub(0, -2) local results = results..']' utilities.answer_inline_query(self, inline_query, results, 10000) end function imdb: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(self, msg.chat.id, imdb.doc, true, msg.message_id, true) return end end local url = BASE_URL..'/?t='..URL.escape(input) local jstr, res = https.request(url) if res ~= 200 then utilities.send_reply(self, msg, config.errors.connection) return end local jdat = json.decode(jstr) if jdat.Response ~= 'True' then utilities.send_reply(self, msg, config.errors.results) return end local output = '<b>'..jdat.Title.. ' ('..jdat.Year..')</b> von '..jdat.Director..'\n' output = output..string.gsub(jdat.imdbRating, '%.', ',')..'/10 | '..jdat.Runtime..' | '.. jdat.Genre..'\n' output = output..'<i>' .. jdat.Plot .. '</i>' utilities.send_reply(self, msg, output, 'HTML', '{"inline_keyboard":[[{"text":"IMDb-Seite aufrufen","url":"http://imdb.com/title/'.. jdat.imdbID..'"}]]}') if jdat.Poster ~= "N/A" then local file = download_to_file(jdat.Poster) utilities.send_photo(self, msg.chat.id, file) end end return imdb
local imdb = {} imdb.command = 'imdb <query>' function imdb:init(config) imdb.triggers = utilities.triggers(self.info.username, config.cmd_pat):t('imdb', true).table imdb.inline_triggers = { "^imdb (.+)" } imdb.doc = [[* ]]..config.cmd_pat..[[imdb* _<Film>_ Sucht _Film_ bei IMDb]] end local BASE_URL = 'https://www.omdbapi.com' function imdb:get_imdb_info(id) local url = BASE_URL..'/?i='..id local res, code = https.request(url) if code ~= 200 then return end local movie_info = json.decode(res) return movie_info end function imdb:inline_callback(inline_query, config, matches) local query = matches[1] local url = BASE_URL..'/?s='..URL.escape(query) local res, code = https.request(url) if code ~= 200 then utilities.answer_inline_query(self, inline_query) return end local data = json.decode(res) if data.Response ~= "True" then utilities.answer_inline_query(self, inline_query) return end local results = '[' for num in pairs(data.Search) do if num > 5 then break; end local imdb_id = data.Search[num].imdbID local movie_info = imdb:get_imdb_info(imdb_id) local title = movie_info.Title local year = movie_info.Year local text = '<b>'..movie_info.Title.. ' ('..movie_info.Year..')</b> von '..movie_info.Director..'\\n'..string.gsub(movie_info.imdbRating, '%.', ',')..'/10 | '..movie_info.Runtime..' | '.. movie_info.Genre if movie_info.Plot then text = text..'\\n<i>'..movie_info.Plot..'</i>' description = movie_info.Plot else description = 'Keine Beschreibung verfügbar' end local text = text:gsub('"', '\\"') local text = text:gsub("'", "\'") if movie_info.Poster == "N/A" then img_url = 'https://anditest.perseus.uberspace.de/inlineQuerys/imdb/logo.jpg' else img_url = movie_info.Poster end results = results..'{"type":"article","id":"'..math.random(100000000000000000)..'","title":"'..title..' ('..year..')","description":"'..description..'","url":"http://imdb.com/title/'..imdb_id..'","hide_url":true,"thumb_url":"'..img_url..'","reply_markup":{"inline_keyboard":[[{"text":"IMDb-Seite aufrufen","url":"http://imdb.com/title/'..imdb_id..'"}]]},"input_message_content":{"message_text":"'..text..'","parse_mode":"HTML"}},' end local results = results:sub(0, -2) local results = results..']' utilities.answer_inline_query(self, inline_query, results, 1) end function imdb: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(self, msg.chat.id, imdb.doc, true, msg.message_id, true) return end end local url = BASE_URL..'/?t='..URL.escape(input) local jstr, res = https.request(url) if res ~= 200 then utilities.send_reply(self, msg, config.errors.connection) return end local jdat = json.decode(jstr) if jdat.Response ~= 'True' then utilities.send_reply(self, msg, config.errors.results) return end local output = '<b>'..jdat.Title.. ' ('..jdat.Year..')</b> von '..jdat.Director..'\n' output = output..string.gsub(jdat.imdbRating, '%.', ',')..'/10 | '..jdat.Runtime..' | '.. jdat.Genre..'\n' output = output..'<i>' .. jdat.Plot .. '</i>' utilities.send_reply(self, msg, output, 'HTML', '{"inline_keyboard":[[{"text":"IMDb-Seite aufrufen","url":"http://imdb.com/title/'.. jdat.imdbID..'"}]]}') if jdat.Poster ~= "N/A" then local file = download_to_file(jdat.Poster) utilities.send_photo(self, msg.chat.id, file) end end return imdb
Paar Bugfixees für IMDB-Inline
Paar Bugfixees für IMDB-Inline
Lua
agpl-3.0
Brawl345/Brawlbot-v2
1e367dcbb79a6592e47cd36b99dff8d7e9d799e4
mods/sponge/init.lua
mods/sponge/init.lua
minetest.register_node("sponge:sponge", { description = "Sponge Dry", drawtype = "normal", tiles = {"sponge_sponge.png"}, paramtype = 'light', walkable = true, pointable = true, diggable = true, buildable_to = false, stack_max = 99, groups = {snappy=2,choppy=2,oddly_breakable_by_hand=3,flammable=3}, after_place_node = function(pos, placer, itemstack, pointed_thing) local pn = placer:get_player_name() if pointed_thing.type ~= "node" then return end if minetest.is_protected(pointed_thing.above, pn) then return end local change = false local on_water = false local pos = pointed_thing.above -- verifier si il est dans l'eau ou a cotée if string.find(minetest.get_node(pointed_thing.above).name, "water_source") or string.find(minetest.get_node(pointed_thing.above).name, "water_flowing") then on_water = true end for i=-1,1 do p = {x=pos.x+i, y=pos.y, z=pos.z} n = minetest.get_node(p) -- On verifie si il y a de l'eau if (n.name=="default:water_flowing") or (n.name == "default:water_source") then on_water = true end end for i=-1,1 do p = {x=pos.x, y=pos.y+i, z=pos.z} n = minetest.get_node(p) -- On verifie si il y a de l'eau if (n.name=="default:water_flowing") or (n.name == "default:water_source") then on_water = true end end for i=-1,1 do p = {x=pos.x, y=pos.y, z=pos.z+i} n = minetest.get_node(p) -- On verifie si il y a de l'eau if (n.name=="default:water_flowing") or (n.name == "default:water_source") then on_water = true end end if on_water == true then for i=-3,3 do for j=-3,3 do for k=-3,3 do p = {x=pos.x+i, y=pos.y+j, z=pos.z+k} n = minetest.get_node(p) -- On Supprime l'eau if (n.name=="default:water_flowing") or (n.name == "default:water_source")then minetest.add_node(p, {name="air"}) change = true end end end end end if change then minetest.add_node(pointed_thing.above, {name = "sponge:sponge_wet"}) end p = {x=pos.x, y=pos.y, z=pos.z} n = minetest.get_node(p) end }) minetest.register_node("sponge:sponge_wet", { description = "Wet Sponge", drawtype = "normal", tiles = {"sponge_sponge_wet.png"}, paramtype = 'light', walkable = true, pointable = true, diggable = true, buildable_to = false, stack_max = 99, groups = {snappy=2,choppy=2,oddly_breakable_by_hand=3}, }) -- Sponge wet back to Sponge Dry if coocked in a furnace minetest.register_craft({ type = "cooking", output = "sponge:sponge", recipe = "sponge:sponge_wet", }) minetest.register_craft({ output = "sponge:sponge", recipe = { {"", "dye:black", ""}, {"dye:yellow", "wool:white", "dye:yellow"}, {"", "farming:wheat", ""}, }, })
minetest.register_node("sponge:sponge", { description = "Sponge Dry", drawtype = "normal", tiles = {"sponge_sponge.png"}, paramtype = 'light', walkable = true, pointable = true, diggable = true, buildable_to = false, stack_max = 99, groups = {snappy=2,choppy=2,oddly_breakable_by_hand=3,flammable=3}, after_place_node = function(pos, placer, itemstack, pointed_thing) local pn = placer:get_player_name() if pointed_thing.type ~= "node" then return end if minetest.is_protected(pointed_thing.above, pn) then return end local change = false local on_water = false -- verifier si il est dans l'eau ou a cotée if string.find(minetest.get_node(pointed_thing.above).name, "water_source") or string.find(minetest.get_node(pointed_thing.above).name, "water_flowing") then on_water = true end for i=-1,1 do p = {x=pos.x+i, y=pos.y, z=pos.z} n = minetest.get_node(p) -- On verifie si il y a de l'eau if (n.name=="default:water_flowing") or (n.name == "default:water_source") then on_water = true end end for i=-1,1 do p = {x=pos.x, y=pos.y+i, z=pos.z} n = minetest.get_node(p) -- On verifie si il y a de l'eau if (n.name=="default:water_flowing") or (n.name == "default:water_source") then on_water = true end end for i=-1,1 do p = {x=pos.x, y=pos.y, z=pos.z+i} n = minetest.get_node(p) -- On verifie si il y a de l'eau if (n.name=="default:water_flowing") or (n.name == "default:water_source") then on_water = true end end if on_water == true then for i=-3,3 do for j=-3,3 do for k=-3,3 do p = {x=pos.x+i, y=pos.y+j, z=pos.z+k} n = minetest.get_node(p) -- On Supprime l'eau if (n.name=="default:water_flowing") or (n.name == "default:water_source")then minetest.add_node(p, {name="air"}) change = true end end end end end if change then minetest.add_node(pos, {name = "sponge:sponge_wet"}) end end }) minetest.register_node("sponge:sponge_wet", { description = "Wet Sponge", drawtype = "normal", tiles = {"sponge_sponge_wet.png"}, paramtype = 'light', walkable = true, pointable = true, diggable = true, buildable_to = false, stack_max = 99, groups = {snappy=2,choppy=2,oddly_breakable_by_hand=3}, }) -- Sponge wet back to Sponge Dry if coocked in a furnace minetest.register_craft({ type = "cooking", output = "sponge:sponge", recipe = "sponge:sponge_wet", }) minetest.register_craft({ output = "sponge:sponge", recipe = { {"", "dye:black", ""}, {"dye:yellow", "wool:white", "dye:yellow"}, {"", "farming:wheat", ""}, }, })
[sponge] Fix positions
[sponge] Fix positions
Lua
unlicense
Gael-de-Sailly/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Ombridride/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Coethium/server-minetestforfun,MinetestForFun/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,Coethium/server-minetestforfun,Coethium/server-minetestforfun,crabman77/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,MinetestForFun/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,sys4-fr/server-minetestforfun
f03fa57ede7249a241ddf4acdd440f893f33acd4
test/testExperience.lua
test/testExperience.lua
local Singleton = require 'structures/Singleton' local Experience = require 'Experience' local Test = torch.TestSuite() local standalone = tester == nil if standalone then tester = torch.Tester() end torch.manualSeed(1) local globals = Singleton({step = 1}) local isValidation = false local capacity = 1e4 local opt = { histLen = 1, nChannels = 1, height = 20, width = 20, batchSize = 10, gpu = false, memPriority = '', learnStart = 0, steps = 1e6, alpha = .65, betaZero = 0.45, Tensor = torch.Tensor, } local function randomPopulate(priorities, experience) local state = torch.Tensor(opt.nChannels, opt.width, opt.height) local terminal = false local action = 1 local reward = 1 local idx = torch.Tensor(1) local prio = torch.Tensor(1) local maxPrio = 1000 for i=1,capacity do experience:store(reward, state, terminal, action) idx[1] = i prio[1] = torch.random(maxPrio) - maxPrio / 2 priorities[i] = prio[1] experience:updatePriorities(idx, prio) end end local function samplePriorityMeans(times) local experience = Experience(capacity, opt, isValidation) local priorities = torch.Tensor(capacity) randomPopulate(priorities, experience) local samplePriorities = torch.Tensor(times, opt.batchSize) for i=1,times do local idxs = experience:sample() samplePriorities[i] = priorities:gather(1, idxs) end -- print(samplePriorities) local means = samplePriorities:abs():mean(1):squeeze() print(means) return means end function Test:TestExperience_TestUniform() torch.manualSeed(1) opt.memPriority = 'none' local means = samplePriorityMeans(1000) for i=1,means:size(1) do tester:assert(means[i]>235 and means[i]<265) end end function Test:TestExperience_TestRank() torch.manualSeed(1) opt.memPriority = 'rank' local means = samplePriorityMeans(10) for i=2,means:size(1) do tester:assertle(means[i], means[i-1]) end end if standalone then tester:add(Test) tester:run() end return Test
local Singleton = require 'structures/Singleton' local Experience = require 'Experience' local Test = torch.TestSuite() local standalone = tester == nil if standalone then tester = torch.Tester() end torch.manualSeed(1) local globals = Singleton({step = 1}) local isValidation = false local capacity = 1e4 local opt = { histLen = 1, stateSpec = { 'real', {1, 10, 10, 10}, {0, 1} }, discretiseMem = true, batchSize = 10, gpu = false, memPriority = '', learnStart = 0, steps = 1e6, alpha = .65, betaZero = 0.45, Tensor = torch.Tensor, } local function randomPopulate(priorities, experience) local state = torch.Tensor(table.unpack(opt.stateSpec[2])) local terminal = false local action = 1 local reward = 1 local idx = torch.Tensor(1) local prio = torch.Tensor(1) local maxPrio = 1000 for i=1,capacity do experience:store(reward, state, terminal, action) idx[1] = i prio[1] = torch.random(maxPrio) - maxPrio / 2 priorities[i] = prio[1] experience:updatePriorities(idx, prio) end end local function samplePriorityMeans(times) local experience = Experience(capacity, opt, isValidation) local priorities = torch.Tensor(capacity) randomPopulate(priorities, experience) local samplePriorities = torch.Tensor(times, opt.batchSize) for i=1,times do local idxs = experience:sample() samplePriorities[i] = priorities:gather(1, idxs) end -- print(samplePriorities) local means = samplePriorities:abs():mean(1):squeeze() print(means) return means end function Test:TestExperience_TestUniform() torch.manualSeed(1) opt.memPriority = 'none' local means = samplePriorityMeans(1000) for i=1,means:size(1) do tester:assert(means[i]>235 and means[i]<265) end end function Test:TestExperience_TestRank() torch.manualSeed(1) opt.memPriority = 'rank' local means = samplePriorityMeans(10) for i=2,means:size(1) do tester:assertle(means[i], means[i-1]) end end if standalone then tester:add(Test) tester:run() end return Test
Fix Travis test for experience replay
Fix Travis test for experience replay
Lua
mit
Kaixhin/Atari
dd1af57a203d76c99c3cdb6cb4a9c6df818a09d5
hammerspoon/luncher.lua
hammerspoon/luncher.lua
local logger = hs.logger.new('Luncher') local hyper = {"cmd", "shift"} local browsers = { { "Google Chrome", "Google Chrome Dev", "Safari", "com.google.Chrome.canary", "Firefox" } } local editorAndIDEs = { { "com.microsoft.VSCode", "Visual Studio Code", "com.github.atom", "org.vim.MacVim", "org.gnu.Emacs", "com.jetbrains.intellij.ce", "com.jetbrains.intellij", "Xcode" } } local emails = {{"Kiwi for Gmail", "Mailplane 3"}} local chats = {{"Slack", "WeChat", "Telegram", "Messages", "FaceTime"}} local tweets = {{"Tweetbot"}} local terminals = {{"iTerm2", "iTerm.app"}} local reminders = {{"Reminders", "Quip"}} local debuggers = {{"com.postmanlabs.mac"}} hs.hotkey.bind(hyper, "s", function() toggleApps(browsers) end) hs.hotkey.bind(hyper, "a", function() toggleApps(emails) end) hs.hotkey.bind(hyper, "x", function() toggleApps(editorAndIDEs) end) hs.hotkey.bind(hyper, "w", function() toggleApps(chats) end) -- hs.hotkey.bind(hyper, "o", function() toggleApps(tweets) end) hs.hotkey.bind(hyper, "j", function() toggleApps(terminals) end) -- hs.hotkey.bind(hyper, "k", function() toggleApps(debuggers) end) -- hs.hotkey.bind(hyper, "r", function() toggleApps(reminders) end) local canvas = nil local normalColor = {alpha = 0.8964, white = 1} local highlightColor = {alpha = 0.8964, red = 1} local function showIndicator(appNames, index) if canvas then canvas:hide(0) canvas:delete(0) canvas = nil end local frame = hs.screen.mainScreen():fullFrame() local width = 800 local height = 60 * #appNames local f = { x = frame.x + frame.w / 2 - width / 2, y = frame.y + frame.h / 2, w = width, h = height } canvas = hs.canvas.new(f) canvas:appendElements({ action = "fill", fillColor = {alpha = 0.8, black = 1}, type = "rectangle", trackMouseEnterExit = true }) for i, appName in pairs(appNames) do canvas:appendElements({ action = "fill", type = "text", absolutePosition = fasle, frame = { x = "0%", y = (100 / #appNames * (i - 1)) .. "%", h = "100%", w = "100%" }, textColor = (index == i and highlightColor or normalColor), textSize = 42, textAlignment = "center", text = appName }) end canvas:show() canvas:hide(1) return canvas end function getAppNames(appList) return appList[1] end function getLastUsedApp(appList) return appList["LAST_USED_APP"] end function setLastUsedApp(appList, app) appList["LAST_USED_APP"] = app end function toggleApps(appList) logger.e("toggleApps") local appNames = getAppNames(appList) local lastUsedApp = getLastUsedApp(appList) if lastUsedApp then logger.d("lastUsedApp: " .. lastUsedApp) end local appMap, nameArray, totalCount = filterOpenApps(appNames) if totalCount == 0 then return openFirstApp(appNames) end local foundLastUsed, index = false, 1 for _, appName in pairs(nameArray) do if lastUsedApp == appName then local appObj = appMap[appName] if appObj:isFrontmost() then logger.d(appName .. "is frontmost") foundLastUsed = true index = _ break else return toggleNextApp(index, totalCount, nameArray, appMap, appList) end end end if foundLastUsed then return toggleNextApp(index, totalCount, nameArray, appMap, appList) end index = 0 for _, appName in pairs(nameArray) do if appMap[appName]:isFrontmost() then index = _ break end end return toggleNextApp(index, totalCount, nameArray, appMap, appList) end function toggleNextApp(current, totalCount, nameArray, map, appList) local index = math.fmod(current, totalCount) + 1 local appName = nameArray[index] local appObj = map[appName] setLastUsedApp(appList, appName) logger.e("setLastUsedApp: " .. appName) if appObj:isFrontmost() then appObj:hide() else appObj:activate() showIndicator(nameArray, index) end end function filterOpenApps(apps) local map, names = {}, {} for _, app in pairs(apps) do appObj = hs.application.get(app) if appObj then map[app] = appObj names[#names + 1] = app end end return map, names, #names end function openFirstApp(apps) for _, app in pairs(apps) do local result = hs.application.launchOrFocus(app) if result then hs.alert.show("Open " .. app) return setLastUsedApp(appList, app) end end return hs.alert.show("No app found in:\n" .. table.concat(apps, "\n")) end
local logger = hs.logger.new('Luncher') local hyper = {"cmd", "shift"} local browsers = { { "Google Chrome", "Google Chrome Dev", "Safari", "com.google.Chrome.canary", "Firefox" } } local editorAndIDEs = { { "com.microsoft.VSCode", "Visual Studio Code", "com.github.atom", "org.vim.MacVim", "org.gnu.Emacs", "com.jetbrains.intellij.ce", "com.jetbrains.intellij", "Xcode" } } local emails = {{"Kiwi for Gmail", "Mailplane 3"}} local chats = {{"Slack", "WeChat", "Telegram", "Messages", "FaceTime"}} local tweets = {{"Tweetbot"}} local terminals = {{"iTerm2", "iTerm.app"}} local reminders = {{"Reminders", "Quip"}} local debuggers = {{"com.postmanlabs.mac"}} hs.hotkey.bind(hyper, "s", function() toggleApps(browsers) end) hs.hotkey.bind(hyper, "a", function() toggleApps(emails) end) hs.hotkey.bind(hyper, "x", function() toggleApps(editorAndIDEs) end) hs.hotkey.bind(hyper, "w", function() toggleApps(chats) end) -- hs.hotkey.bind(hyper, "o", function() toggleApps(tweets) end) hs.hotkey.bind(hyper, "j", function() toggleApps(terminals) end) -- hs.hotkey.bind(hyper, "k", function() toggleApps(debuggers) end) -- hs.hotkey.bind(hyper, "r", function() toggleApps(reminders) end) local canvas = nil local normalColor = {alpha = 0.8964, white = 1} local highlightColor = {alpha = 0.8964, red = 1} local function showIndicator(appNames, index) if canvas then canvas:hide(0) canvas:delete(0) canvas = nil end local frame = hs.screen.mainScreen():fullFrame() local width = 800 local height = 60 * #appNames local f = { x = frame.x + frame.w / 2 - width / 2, y = frame.y + frame.h / 2, w = width, h = height } canvas = hs.canvas.new(f) canvas:appendElements({ action = "fill", fillColor = {alpha = 0.8, black = 1}, type = "rectangle", trackMouseEnterExit = true }) for i, appName in pairs(appNames) do canvas:appendElements({ action = "fill", type = "text", absolutePosition = fasle, frame = { x = "0%", y = (100 / #appNames * (i - 1)) .. "%", h = "100%", w = "100%" }, textColor = (index == i and highlightColor or normalColor), textSize = 42, textAlignment = "center", text = appName }) end canvas:show() canvas:hide(1) return canvas end function getAppNames(appList) return appList[1] end function getLastUsedApp(appList) return appList["LAST_USED_APP"] end function setLastUsedApp(appList, app) appList["LAST_USED_APP"] = app end function table_to_string(tbl) local result = "{" for k, v in pairs(tbl) do -- Check the key type (ignore any numerical keys - assume its an array) if type(k) == "string" then result = result.."[\""..k.."\"]".."=" end -- Check the value type if type(v) == "table" then result = result..table_to_string(v) elseif type(v) == "boolean" then result = result..tostring(v) else result = result.."\""..v.."\"" end result = result.."," end -- Remove leading commas from the result if result ~= "" then result = result:sub(1, result:len()-1) end return result.."}" end function toggleApps(appList) logger.d("toggleApps, appList: " .. table_to_string(appList)) local appNames = getAppNames(appList) local lastUsedApp = getLastUsedApp(appList) if lastUsedApp then logger.d("lastUsedApp: " .. lastUsedApp) end local appMap, nameArray, totalCount = filterOpenApps(appNames) if totalCount == 0 then return openFirstApp(appNames) end local foundLastUsed, index = false, 1 for _, appName in pairs(nameArray) do if lastUsedApp == appName then local appObj = appMap[appName] if appObj:isFrontmost() then logger.d(appName .. "is frontmost") foundLastUsed = true index = _ break else logger.d(appName .. "is not frontmost, index: " .. _) return toggleNextApp(_ - 1, totalCount, nameArray, appMap, appList) end end end if foundLastUsed then return toggleNextApp(index, totalCount, nameArray, appMap, appList) end index = 0 for _, appName in pairs(nameArray) do if appMap[appName]:isFrontmost() then index = _ break end end return toggleNextApp(index, totalCount, nameArray, appMap, appList) end function toggleNextApp(current, totalCount, nameArray, map, appList) logger.d("toggleNextApp: " .. current .. " total: " .. totalCount) local index = math.fmod(current, totalCount) + 1 local appName = nameArray[index] local appObj = map[appName] setLastUsedApp(appList, appName) logger.d("setLastUsedApp: " .. appName) if appObj:isFrontmost() then appObj:hide() else appObj:activate() showIndicator(nameArray, index) end end function filterOpenApps(apps) local map, names = {}, {} for _, app in pairs(apps) do appObj = hs.application.get(app) if appObj then map[app] = appObj names[#names + 1] = app end end return map, names, #names end function openFirstApp(apps) for _, app in pairs(apps) do local result = hs.application.launchOrFocus(app) if result then hs.alert.show("Open " .. app) return setLastUsedApp(appList, app) end end return hs.alert.show("No app found in:\n" .. table.concat(apps, "\n")) end
Fix the launcher logic to resume the last active app
Fix the launcher logic to resume the last active app
Lua
mit
xcv58/Hammerspoon-xcv58
c21516f04d963d42cd197c2ac7784e7c2e95b4fc
waifu2x.lua
waifu2x.lua
require 'pl' local __FILE__ = (function() return string.gsub(debug.getinfo(2, 'S').source, "^@", "") end)() package.path = path.join(path.dirname(__FILE__), "lib", "?.lua;") .. package.path require 'sys' require 'w2nn' local iproc = require 'iproc' local reconstruct = require 'reconstruct' local image_loader = require 'image_loader' torch.setdefaulttensortype('torch.FloatTensor') local function convert_image(opt) local x, alpha = image_loader.load_float(opt.i) local new_x = nil local t = sys.clock() local scale_f, image_f if opt.tta == 1 then scale_f = reconstruct.scale_tta image_f = reconstruct.image_tta else scale_f = reconstruct.scale image_f = reconstruct.image end if opt.o == "(auto)" then local name = path.basename(opt.i) local e = path.extension(name) local base = name:sub(0, name:len() - e:len()) opt.o = path.join(path.dirname(opt.i), string.format("%s_%s.png", base, opt.m)) end if opt.m == "noise" then local model_path = path.join(opt.model_dir, ("noise%d_model.t7"):format(opt.noise_level)) local model = torch.load(model_path, "ascii") if not model then error("Load Error: " .. model_path) end new_x = image_f(model, x, opt.crop_size) elseif opt.m == "scale" then local model_path = path.join(opt.model_dir, ("scale%.1fx_model.t7"):format(opt.scale)) local model = torch.load(model_path, "ascii") if not model then error("Load Error: " .. model_path) end new_x = scale_f(model, opt.scale, x, opt.crop_size) elseif opt.m == "noise_scale" then local noise_model_path = path.join(opt.model_dir, ("noise%d_model.t7"):format(opt.noise_level)) local noise_model = torch.load(noise_model_path, "ascii") local scale_model_path = path.join(opt.model_dir, ("scale%.1fx_model.t7"):format(opt.scale)) local scale_model = torch.load(scale_model_path, "ascii") if not noise_model then error("Load Error: " .. noise_model_path) end if not scale_model then error("Load Error: " .. scale_model_path) end x = image_f(noise_model, x) new_x = scale_f(scale_model, opt.scale, x, opt.crop_size) else error("undefined method:" .. opt.method) end image_loader.save_png(opt.o, new_x, alpha, opt.depth) print(opt.o .. ": " .. (sys.clock() - t) .. " sec") end local function convert_frames(opt) local model_path, noise1_model, noise2_model, scale_model local scale_f, image_f if opt.tta == 1 then scale_f = reconstruct.scale_tta image_f = reconstruct.image_tta else scale_f = reconstruct.scale image_f = reconstruct.image end if opt.m == "scale" then model_path = path.join(opt.model_dir, ("scale%.1fx_model.t7"):format(opt.scale)) scale_model = torch.load(model_path, "ascii") if not scale_model then error("Load Error: " .. model_path) end elseif opt.m == "noise" and opt.noise_level == 1 then model_path = path.join(opt.model_dir, "noise1_model.t7") noise1_model = torch.load(model_path, "ascii") if not noise1_model then error("Load Error: " .. model_path) end elseif opt.m == "noise" and opt.noise_level == 2 then model_path = path.join(opt.model_dir, "noise2_model.t7") noise2_model = torch.load(model_path, "ascii") if not noise2_model then error("Load Error: " .. model_path) end elseif opt.m == "noise_scale" then model_path = path.join(opt.model_dir, ("scale%.1fx_model.t7"):format(opt.scale)) scale_model = torch.load(model_path, "ascii") if not scale_model then error("Load Error: " .. model_path) end if opt.noise_level == 1 then model_path = path.join(opt.model_dir, "noise1_model.t7") noise1_model = torch.load(model_path, "ascii") if not noise1_model then error("Load Error: " .. model_path) end elseif opt.noise_level == 2 then model_path = path.join(opt.model_dir, "noise2_model.t7") noise2_model = torch.load(model_path, "ascii") if not noise2_model then error("Load Error: " .. model_path) end end end local fp = io.open(opt.l) if not fp then error("Open Error: " .. opt.l) end local count = 0 local lines = {} for line in fp:lines() do table.insert(lines, line) end fp:close() for i = 1, #lines do if opt.resume == 0 or path.exists(string.format(opt.o, i)) == false then local x, alpha = image_loader.load_float(lines[i]) local new_x = nil if opt.m == "noise" and opt.noise_level == 1 then new_x = image_f(noise1_model, x, opt.crop_size) elseif opt.m == "noise" and opt.noise_level == 2 then new_x = image_func(noise2_model, x) elseif opt.m == "scale" then new_x = scale_f(scale_model, opt.scale, x, opt.crop_size) elseif opt.m == "noise_scale" and opt.noise_level == 1 then x = image_f(noise1_model, x) new_x = scale_f(scale_model, opt.scale, x, opt.crop_size) elseif opt.m == "noise_scale" and opt.noise_level == 2 then x = image_f(noise2_model, x, opt.crop_size) new_x = scale_f(scale_model, opt.scale, x, opt.crop_size) else error("undefined method:" .. opt.method) end local output = nil if opt.o == "(auto)" then local name = path.basename(lines[i]) local e = path.extension(name) local base = name:sub(0, name:len() - e:len()) output = path.join(path.dirname(opt.i), string.format("%s(%s).png", base, opt.m)) else output = string.format(opt.o, i) end image_loader.save_png(output, new_x, alpha, opt.depth) xlua.progress(i, #lines) if i % 10 == 0 then collectgarbage() end else xlua.progress(i, #lines) end end end local function waifu2x() local cmd = torch.CmdLine() cmd:text() cmd:text("waifu2x") cmd:text("Options:") cmd:option("-i", "images/miku_small.png", 'path to input image') cmd:option("-l", "", 'path to image-list.txt') cmd:option("-scale", 2, 'scale factor') cmd:option("-o", "(auto)", 'path to output file') cmd:option("-depth", 8, 'bit-depth of the output image (8|16)') cmd:option("-model_dir", "./models/anime_style_art_rgb", 'path to model directory') cmd:option("-m", "noise_scale", 'method (noise|scale|noise_scale)') cmd:option("-noise_level", 1, '(1|2)') cmd:option("-crop_size", 128, 'patch size per process') cmd:option("-resume", 0, "skip existing files (0|1)") cmd:option("-thread", -1, "number of CPU threads") cmd:option("-tta", 0, '8x slower and slightly high quality (0|1)') local opt = cmd:parse(arg) if opt.thread > 0 then torch.setnumthreads(opt.thread) end if cudnn then cudnn.fastest = true cudnn.benchmark = false end if string.len(opt.l) == 0 then convert_image(opt) else convert_frames(opt) end end waifu2x()
require 'pl' local __FILE__ = (function() return string.gsub(debug.getinfo(2, 'S').source, "^@", "") end)() package.path = path.join(path.dirname(__FILE__), "lib", "?.lua;") .. package.path require 'sys' require 'w2nn' local iproc = require 'iproc' local reconstruct = require 'reconstruct' local image_loader = require 'image_loader' torch.setdefaulttensortype('torch.FloatTensor') local function convert_image(opt) local x, alpha = image_loader.load_float(opt.i) local new_x = nil local t = sys.clock() local scale_f, image_f if opt.tta == 1 then scale_f = reconstruct.scale_tta image_f = reconstruct.image_tta else scale_f = reconstruct.scale image_f = reconstruct.image end if opt.o == "(auto)" then local name = path.basename(opt.i) local e = path.extension(name) local base = name:sub(0, name:len() - e:len()) opt.o = path.join(path.dirname(opt.i), string.format("%s_%s.png", base, opt.m)) end if opt.m == "noise" then local model_path = path.join(opt.model_dir, ("noise%d_model.t7"):format(opt.noise_level)) local model = torch.load(model_path, "ascii") if not model then error("Load Error: " .. model_path) end new_x = image_f(model, x, opt.crop_size) elseif opt.m == "scale" then local model_path = path.join(opt.model_dir, ("scale%.1fx_model.t7"):format(opt.scale)) local model = torch.load(model_path, "ascii") if not model then error("Load Error: " .. model_path) end new_x = scale_f(model, opt.scale, x, opt.crop_size) elseif opt.m == "noise_scale" then local noise_model_path = path.join(opt.model_dir, ("noise%d_model.t7"):format(opt.noise_level)) local noise_model = torch.load(noise_model_path, "ascii") local scale_model_path = path.join(opt.model_dir, ("scale%.1fx_model.t7"):format(opt.scale)) local scale_model = torch.load(scale_model_path, "ascii") if not noise_model then error("Load Error: " .. noise_model_path) end if not scale_model then error("Load Error: " .. scale_model_path) end x = image_f(noise_model, x, opt.crop_size) new_x = scale_f(scale_model, opt.scale, x, opt.crop_size) else error("undefined method:" .. opt.method) end image_loader.save_png(opt.o, new_x, alpha, opt.depth) print(opt.o .. ": " .. (sys.clock() - t) .. " sec") end local function convert_frames(opt) local model_path, noise1_model, noise2_model, scale_model local scale_f, image_f if opt.tta == 1 then scale_f = reconstruct.scale_tta image_f = reconstruct.image_tta else scale_f = reconstruct.scale image_f = reconstruct.image end if opt.m == "scale" then model_path = path.join(opt.model_dir, ("scale%.1fx_model.t7"):format(opt.scale)) scale_model = torch.load(model_path, "ascii") if not scale_model then error("Load Error: " .. model_path) end elseif opt.m == "noise" and opt.noise_level == 1 then model_path = path.join(opt.model_dir, "noise1_model.t7") noise1_model = torch.load(model_path, "ascii") if not noise1_model then error("Load Error: " .. model_path) end elseif opt.m == "noise" and opt.noise_level == 2 then model_path = path.join(opt.model_dir, "noise2_model.t7") noise2_model = torch.load(model_path, "ascii") if not noise2_model then error("Load Error: " .. model_path) end elseif opt.m == "noise_scale" then model_path = path.join(opt.model_dir, ("scale%.1fx_model.t7"):format(opt.scale)) scale_model = torch.load(model_path, "ascii") if not scale_model then error("Load Error: " .. model_path) end if opt.noise_level == 1 then model_path = path.join(opt.model_dir, "noise1_model.t7") noise1_model = torch.load(model_path, "ascii") if not noise1_model then error("Load Error: " .. model_path) end elseif opt.noise_level == 2 then model_path = path.join(opt.model_dir, "noise2_model.t7") noise2_model = torch.load(model_path, "ascii") if not noise2_model then error("Load Error: " .. model_path) end end end local fp = io.open(opt.l) if not fp then error("Open Error: " .. opt.l) end local count = 0 local lines = {} for line in fp:lines() do table.insert(lines, line) end fp:close() for i = 1, #lines do if opt.resume == 0 or path.exists(string.format(opt.o, i)) == false then local x, alpha = image_loader.load_float(lines[i]) local new_x = nil if opt.m == "noise" and opt.noise_level == 1 then new_x = image_f(noise1_model, x, opt.crop_size) elseif opt.m == "noise" and opt.noise_level == 2 then new_x = image_func(noise2_model, x, opt.crop_size) elseif opt.m == "scale" then new_x = scale_f(scale_model, opt.scale, x, opt.crop_size) elseif opt.m == "noise_scale" and opt.noise_level == 1 then x = image_f(noise1_model, x, opt.crop_size) new_x = scale_f(scale_model, opt.scale, x, opt.crop_size) elseif opt.m == "noise_scale" and opt.noise_level == 2 then x = image_f(noise2_model, x, opt.crop_size) new_x = scale_f(scale_model, opt.scale, x, opt.crop_size) else error("undefined method:" .. opt.method) end local output = nil if opt.o == "(auto)" then local name = path.basename(lines[i]) local e = path.extension(name) local base = name:sub(0, name:len() - e:len()) output = path.join(path.dirname(opt.i), string.format("%s(%s).png", base, opt.m)) else output = string.format(opt.o, i) end image_loader.save_png(output, new_x, alpha, opt.depth) xlua.progress(i, #lines) if i % 10 == 0 then collectgarbage() end else xlua.progress(i, #lines) end end end local function waifu2x() local cmd = torch.CmdLine() cmd:text() cmd:text("waifu2x") cmd:text("Options:") cmd:option("-i", "images/miku_small.png", 'path to input image') cmd:option("-l", "", 'path to image-list.txt') cmd:option("-scale", 2, 'scale factor') cmd:option("-o", "(auto)", 'path to output file') cmd:option("-depth", 8, 'bit-depth of the output image (8|16)') cmd:option("-model_dir", "./models/anime_style_art_rgb", 'path to model directory') cmd:option("-m", "noise_scale", 'method (noise|scale|noise_scale)') cmd:option("-noise_level", 1, '(1|2)') cmd:option("-crop_size", 128, 'patch size per process') cmd:option("-resume", 0, "skip existing files (0|1)") cmd:option("-thread", -1, "number of CPU threads") cmd:option("-tta", 0, '8x slower and slightly high quality (0|1)') local opt = cmd:parse(arg) if opt.thread > 0 then torch.setnumthreads(opt.thread) end if cudnn then cudnn.fastest = true cudnn.benchmark = false end if string.len(opt.l) == 0 then convert_image(opt) else convert_frames(opt) end end waifu2x()
Fix unused crop_size option
Fix unused crop_size option
Lua
mit
zyhkz/waifu2x,Spitfire1900/upscaler,zyhkz/waifu2x,nagadomi/waifu2x,zyhkz/waifu2x,nagadomi/waifu2x,nagadomi/waifu2x,vitaliylag/waifu2x,vitaliylag/waifu2x,nagadomi/waifu2x,higankanshi/waifu2x,zyhkz/waifu2x,higankanshi/waifu2x,Spitfire1900/upscaler,vitaliylag/waifu2x,higankanshi/waifu2x,nagadomi/waifu2x
9b99dc37f5cac5ce47db07670c82455491fa1ca3
terminal.lua
terminal.lua
local Terminal = {} --local EditorSheet = SpriteSheet(Image("/editorsheet.png"),24,12) local blinktime = 0.5 local blinktimer = 0 local blinkstate = false Terminal.textbuffer = {} Terminal.textcolors = {} Terminal.linesLimit = 14 Terminal.lengthLimit = 43 Terminal.currentLine = 1 function Terminal:tout(text,col,skipnl) self.textcolors[self.currentLine] = col or self.textcolors[self.currentLine] if skipnl then self.textbuffer[self.currentLine] = self.textbuffer[self.currentLine]..(text or "") if self.textbuffer[self.currentLine]:len() >= self.lengthLimit then self.textbuffer[self.currentLine] = self.textbuffer[self.currentLine]:sub(0,self.lengthLimit) end else self.textbuffer[self.currentLine] = self.textbuffer[self.currentLine]..(text or "") if self.textbuffer[self.currentLine]:len() >= self.lengthLimit then self.textbuffer[self.currentLine] = self.textbuffer[self.currentLine]:sub(0,self.lengthLimit) end if self.currentLine == self.linesLimit then for i=2,self.linesLimit do self.textbuffer[i-1] = self.textbuffer[i] end --Shiftup all the text for i=2,self.linesLimit do self.textcolors[i-1] = self.textcolors[i] end self.textbuffer[self.currentLine] = "" --Add a new line else self.currentLine = self.currentLine + 1 end end Terminal:_redraw() end function Terminal:setLine(l) self.currentLine = floor(l or 1) if self.currentLine > 20 then self.currentLine = 20 elseif self.currentLine < 1 then self.currentLine = 1 end end function Terminal:splitCommand(str) local t = {} for val in str:gmatch("%S+") do if not t[0] then t[0] = val else table.insert(t, val) end end return t end function Terminal:_startup() for i=1,self.linesLimit do table.insert(self.textbuffer,"") end --Clean the framebuffer for i=1,self.linesLimit do table.insert(self.textcolors,8) end keyrepeat(true) --tout("12345678901234567890123456789012345678901234567890123456789012345678901234567890",9) self:tout("-[[liko12]]-") self:tout("V0.0.1 DEV",9) self:tout() self:tout("A PICO-8 CLONE WITH EXTRA ABILITIES",7) --tout() self:tout("TYPE HELP FOR HELP",10) --tout() self:tout("> ",8,true) end function Terminal:_update(dt) blinktimer = blinktimer+dt if blinktimer > blinktime then blinktimer = blinktimer - blinktime blinkstate = not blinkstate end local curlen = self.textbuffer[self.currentLine]:len() color(blinkstate and 9 or 1) rect(curlen > 0 and ((curlen)*4+8+3) or 10,(self.currentLine)*8+2,4,5) end function Terminal:_redraw() clear(1) for line,text in ipairs(self.textbuffer) do color(self.textcolors[line]) if text == "-[[liko12]]-" then --THE SECRET PHASE SpriteGroup(67,9,line*8,6,1,1,1,EditorSheet) else print_grid(text,2,line+1) end end end function Terminal:_kpress(k,sc,ir) if k == "return" then self:tout() local splitted = self:splitCommand(self.textbuffer[self.currentLine-1]) local CMDFunc = require("terminal_commands")[string.lower(splitted[1] or "")] if CMDFunc then CMDFunc(unpack(splitted)) elseif splitted[1] then self:tout("UNKNOWN COMMAND '"..splitted[1].."' !",15) end self:tout("> ",8,true) end if k == "backspace" then self.textbuffer[self.currentLine] = self.textbuffer[self.currentLine]:sub(0,-2) self:_redraw() end end function Terminal:_tinput(t) if self.textbuffer[self.currentLine]:len() < self.lengthLimit then self:tout(t,8,true) end end function Terminal:_tpress() --This means the user is using a touch device self.linesLimit = 7 showkeyboard(true) end return Terminal
local Terminal = {} --local EditorSheet = SpriteSheet(Image("/editorsheet.png"),24,12) Terminal.blinktime = 0.5 Terminal.blinktimer = 0 Terminal.blinkstate = false Terminal.textbuffer = {} Terminal.textcolors = {} Terminal.linesLimit = 14 Terminal.lengthLimit = 43 Terminal.currentLine = 1 function Terminal:tout(text,col,skipnl) self.textcolors[self.currentLine] = col or self.textcolors[self.currentLine] if skipnl then self.textbuffer[self.currentLine] = self.textbuffer[self.currentLine]..(text or "") if self.textbuffer[self.currentLine]:len() >= self.lengthLimit then self.textbuffer[self.currentLine] = self.textbuffer[self.currentLine]:sub(0,self.lengthLimit) end else self.textbuffer[self.currentLine] = self.textbuffer[self.currentLine]..(text or "") if self.textbuffer[self.currentLine]:len() >= self.lengthLimit then self.textbuffer[self.currentLine] = self.textbuffer[self.currentLine]:sub(0,self.lengthLimit) end if self.currentLine == self.linesLimit then for i=2,self.linesLimit do self.textbuffer[i-1] = self.textbuffer[i] end --Shiftup all the text for i=2,self.linesLimit do self.textcolors[i-1] = self.textcolors[i] end self.textbuffer[self.currentLine] = "" --Add a new line else self.currentLine = self.currentLine + 1 end end self:_redraw() end function Terminal:setLine(l) self.currentLine = floor(l or 1) if self.currentLine > 20 then self.currentLine = 20 elseif self.currentLine < 1 then self.currentLine = 1 end end function Terminal:splitCommand(str) local t = {} for val in str:gmatch("%S+") do if not t[0] then t[0] = val else table.insert(t, val) end end return t end function Terminal:_startup() for i=1,self.linesLimit do table.insert(self.textbuffer,"") end --Clean the framebuffer for i=1,self.linesLimit do table.insert(self.textcolors,8) end keyrepeat(true) --tout("12345678901234567890123456789012345678901234567890123456789012345678901234567890",9) self:tout("-[[liko12]]-") self:tout("V0.0.1 DEV",9) self:tout() self:tout("A PICO-8 CLONE WITH EXTRA ABILITIES",7) --tout() self:tout("TYPE HELP FOR HELP",10) --tout() self:tout("> ",8,true) end function Terminal:_update(dt) self.blinktimer = self.blinktimer+dt if self.blinktimer > self.blinktime then self.blinktimer = self.blinktimer - self.blinktime self.blinkstate = not self.blinkstate end local curlen = self.textbuffer[self.currentLine]:len() color(self.blinkstate and 9 or 1) rect(curlen > 0 and ((curlen)*4+8+3) or 10,(self.currentLine)*8+2,4,5) end function Terminal:_redraw() clear(1) for line,text in ipairs(self.textbuffer) do color(self.textcolors[line]) if text == "-[[liko12]]-" then --THE SECRET PHASE SpriteGroup(67,9,line*8,6,1,1,1,EditorSheet) else print_grid(text,2,line+1) end end end function Terminal:_kpress(k,sc,ir) if k == "return" then self:tout() local splitted = self:splitCommand(self.textbuffer[self.currentLine-1]) local CMDFunc = require("terminal_commands")[string.lower(splitted[1] or "")] if CMDFunc then CMDFunc(unpack(splitted)) elseif splitted[1] then self:tout("UNKNOWN COMMAND '"..splitted[1].."' !",15) end self:tout("> ",8,true) end if k == "backspace" then self.textbuffer[self.currentLine] = self.textbuffer[self.currentLine]:sub(0,-2) self:_redraw() end end function Terminal:_tinput(t) if self.textbuffer[self.currentLine]:len() < self.lengthLimit then self:tout(t,8,true) end end function Terminal:_tpress() --This means the user is using a touch device self.linesLimit = 7 showkeyboard(true) end return Terminal
bug fixes
bug fixes
Lua
mit
RamiLego4Game/LIKO-12
945b8c1658aa7c6efb93376614e69c84dfdad07d
tests/Integration/queues.lua
tests/Integration/queues.lua
#!/usr/bin/tarantool box.cfg { listen = 3301, log_level = 6, wal_mode = 'none', snap_dir = '/tmp', slab_alloc_arena = .1, } box.schema.user.grant('guest', 'read,write,execute', 'universe') console = require('console') console.listen('127.0.0.1:33333') queue = require('queue') queue.start() function create_tube(tube_name, tube_type, opts) if queue.tube[tube_name] then queue.tube[tube_name]:drop() end return queue.create_tube(tube_name, tube_type, opts) end
#!/usr/bin/tarantool box.cfg { listen = 3301, log_level = 6, wal_mode = 'none', snap_dir = '/tmp', slab_alloc_arena = .1, } local function bootstrap() box.schema.user.grant('guest', 'read,write,execute', 'universe') end box.once('queues', bootstrap) console = require('console') console.listen('127.0.0.1:33333') queue = require('queue') queue.start() function create_tube(tube_name, tube_type, opts) if queue.tube[tube_name] then queue.tube[tube_name]:drop() end return queue.create_tube(tube_name, tube_type, opts) end
Fix queues.lua
Fix queues.lua
Lua
mit
tarantool-php/queue,tarantool-php/queue
9012468e8f9346fcbd8d1a59fab17b6ce6df990a
run-shell/run-shell.lua
run-shell/run-shell.lua
------------------------------------------------- -- Run Shell for Awesome Window Manager -- More details could be found here: -- https://github.com/streetturtle/awesome-wm-widgets/tree/master/run-shell -- @author Pavel Makhov -- @copyright 2018 Pavel Makhov ------------------------------------------------- local capi = { screen = screen, client = client, } local awful = require("awful") local gfs = require("gears.filesystem") local wibox = require("wibox") local gears = require("gears") local naughty = require("naughty") local completion = require("awful.completion") local run_shell = awful.widget.prompt() local function get_screen(s) return s and capi.screen[s] end local widget = {} function widget.new() local widget_instance = { _cached_wiboxes = {}, } function widget_instance:_create_wibox() local w = wibox { visible = false, ontop = true, height = 1060, width = 1920 } w:setup { { { { { text = 'a', font = 'awesomewm-font 13', widget = wibox.widget.textbox, }, id = 'icon', left = 10, layout = wibox.container.margin }, { run_shell, left = 10, layout = wibox.container.margin, }, id = 'left', layout = wibox.layout.fixed.horizontal }, widget = wibox.container.background, bg = '#333333', shape = function(cr, width, height) gears.shape.rounded_rect(cr, width, height, 3) end, shape_border_color = '#74aeab', shape_border_width = 1, forced_width = 200, forced_height = 50 }, layout = wibox.container.place } return w end function widget_instance:launch(s, c) c = c or capi.client.focus s = s or (c and c.screen or awful.screen.focused()) naughty.notify{text = 'screen ' .. s.index} if not self._cached_wiboxes[s] then self._cached_wiboxes[s] = {} naughty.notify{text = 'nope'} end if not self._cached_wiboxes[s][1] then self._cached_wiboxes[s][1] = self:_create_wibox() naughty.notify{text = 'nope'} end local w = self._cached_wiboxes[s][1] awful.spawn.with_line_callback(os.getenv("HOME") .. "/.config/awesome/awesome-wm-widgets/run-shell/scratch_6.sh " .. tostring(awful.screen.focused().geometry.x), { stdout = function(line) w.visible = true w.bgimage = '/tmp/i3lock-' .. line .. '.png' awful.placement.top(w, { margins = { top = 20 }, parent = awful.screen.focused() }) awful.prompt.run { prompt = "<b>Run</b>: ", bg_cursor = '#74aeab', textbox = run_shell.widget, completion_callback = completion.shell, exe_callback = function(...) run_shell:spawn_and_handle_error(...) end, history_path = gfs.get_cache_dir() .. "/history", done_callback = function() -- w.bgimage='' w.visible = false w.bgimage = '' awful.spawn([[bash -c 'rm -f /tmp/i3lock*']]) end } end, stderr = function(line) naughty.notify { text = "ERR:" .. line } end, }) end return widget_instance end local function get_default_widget() if not widget.default_widget then widget.default_widget = widget.new() end return widget.default_widget end function widget.launch(...) return get_default_widget():launch(...) end return widget
------------------------------------------------- -- Run Shell for Awesome Window Manager -- More details could be found here: -- https://github.com/streetturtle/awesome-wm-widgets/tree/master/run-shell -- @author Pavel Makhov -- @copyright 2018 Pavel Makhov ------------------------------------------------- local capi = { screen = screen, client = client, } local awful = require("awful") local gfs = require("gears.filesystem") local wibox = require("wibox") local gears = require("gears") local naughty = require("naughty") local completion = require("awful.completion") local run_shell = awful.widget.prompt() local widget = {} function widget.new() local widget_instance = { _cached_wiboxes = {}, } function widget_instance:_create_wibox() local w = wibox { visible = false, ontop = true, height = 1060, width = 1920 } w:setup { { { { { text = 'a', font = 'awesomewm-font 13', widget = wibox.widget.textbox, }, id = 'icon', left = 10, layout = wibox.container.margin }, { run_shell, left = 10, layout = wibox.container.margin, }, id = 'left', layout = wibox.layout.fixed.horizontal }, widget = wibox.container.background, bg = '#333333', shape = function(cr, width, height) gears.shape.rounded_rect(cr, width, height, 3) end, shape_border_color = '#74aeab', shape_border_width = 1, forced_width = 200, forced_height = 50 }, layout = wibox.container.place } return w end function widget_instance:launch(s, c) c = c or capi.client.focus s = s or (c and c.screen or awful.screen.focused()) naughty.notify{text = 'screen ' .. s.index} if not self._cached_wiboxes[s] then self._cached_wiboxes[s] = {} naughty.notify{text = 'nope'} end if not self._cached_wiboxes[s][1] then self._cached_wiboxes[s][1] = self:_create_wibox() naughty.notify{text = 'nope'} end local w = self._cached_wiboxes[s][1] awful.spawn.with_line_callback(os.getenv("HOME") .. "/.config/awesome/awesome-wm-widgets/run-shell/scratch_6.sh " .. tostring(awful.screen.focused().geometry.x), { stdout = function(line) w.visible = true w.bgimage = '/tmp/i3lock-' .. line .. '.png' awful.placement.top(w, { margins = { top = 20 }, parent = awful.screen.focused() }) awful.prompt.run { prompt = 'Run: ', bg_cursor = '#74aeab', textbox = run_shell.widget, completion_callback = completion.shell, exe_callback = function(...) run_shell:spawn_and_handle_error(...) end, history_path = gfs.get_cache_dir() .. "/history", done_callback = function() w.visible = false w.bgimage = '' awful.spawn([[bash -c 'rm -f /tmp/i3lock*']]) end } end, stderr = function(line) naughty.notify { text = "ERR:" .. line } end, }) end return widget_instance end local function get_default_widget() if not widget.default_widget then widget.default_widget = widget.new() end return widget.default_widget end function widget.launch(...) return get_default_widget():launch(...) end return widget
Small fix for run shell
Small fix for run shell
Lua
mit
streetturtle/awesome-wm-widgets,streetturtle/awesome-wm-widgets,streetturtle/AwesomeWM
91d045eb7bc66937e32171853a7563c6633f7bc2
nix/nvim/init.lua
nix/nvim/init.lua
require "paq" { "savq/paq-nvim"; "kylechui/nvim-surround"; "numToStr/Comment.nvim"; "kyazdani42/nvim-web-devicons"; "nvim-lualine/lualine.nvim"; "Mofiqul/dracula.nvim"; "neovim/nvim-lspconfig"; "hrsh7th/nvim-cmp"; "epwalsh/obsidian.nvim"; "junegunn/fzf"; {"nvim-treesitter/nvim-treesitter", run='TSUpdate'}; } --theme: vim.cmd[[colorscheme dracula]] require("dracula").setup({ show_end_of_buffer = true, transparent_bg = true, italic_comment = true }) --lualine require('lualine').setup { options = { theme = 'dracula-nvim' } ) require'lspconfig'.rnix.setup{} require'lspconfig'.pyright.setup{} require('nvim-surround').setup() require('Comment').setup { ---Add a space b/w comment and the line padding = true, ---Whether the cursor should stay at its position sticky = true, ---Lines to be ignored while (un)comment ignore = '^\s*$', ---LHS of toggle mappings in NORMAL mode toggler = { ---Line-comment toggle keymap line = 'gcc', ---Block-comment toggle keymap block = 'gbc', }, ---LHS of operator-pending mappings in NORMAL and VISUAL mode opleader = { ---Line-comment keymap line = 'gc', ---Block-comment keymap block = 'gb', }, ---LHS of extra mappings extra = { ---Add comment on the line above above = 'gcO', ---Add comment on the line below below = 'gco', ---Add comment at the end of line eol = 'gcA', }, ---Enable keybindings ---NOTE: If given `false` then the plugin won't create any mappings mappings = { ---Operator-pending mapping; `gcc` `gbc` `gc[count]{motion}` `gb[count]{motion}` basic = true, ---Extra mapping; `gco`, `gcO`, `gcA` extra = true, }, ---Function to call before (un)comment pre_hook = nil, ---Function to call after (un)comment post_hook = nil, } -- treesitter config require('nvim-treesitter.configs').setup { ensure_installed = { "python", "nix", "lua", "rust", "julia", "bash", "yaml", "markdown", "markdown_inline", "html", "css", "comment", "json", "json5", "sql", "toml"}, sync_install = false, auto_install = true, highlight = { enable = true, }, indent = { enable = true }, incremental_selection = { enable = true, keymaps = { init_selection = "gnn", node_incremental = "grn", scope_incremental = "grc", node_decremental = "grm", }, }, } set completeopt=menu,menuone,noselect require'cmp'.setup { mapping = cmp.mapping.preset.insert({ ['<C-b>'] = cmp.mapping.scroll_docs(-4), ['<C-f>'] = cmp.mapping.scroll_docs(4), ['<C-Space>'] = cmp.mapping.complete(), ['<C-e>'] = cmp.mapping.abort(), ['<CR>'] = cmp.mapping.confirm({ select = true }), -- Accept currently selected item. Set `select` to `false` to only confirm explicitly selected items. }), sources = cmp.config.sources({ { name = 'nvim_lsp' }, ), } -- fold using nvim treesitter vim.opt.foldmethod = "expr" vim.opt.foldexpr = nvim_treesitter#foldexpr() vim.opt.foldlevel = 99 --this makes the folds not show up initially vim.o.smartcase = true vim.o.hlsearch = true vim.o.incsearch = true vim.o.ignorecase = true vim.bo.expandtab = true vim.bo.tabstop = 2 vim.bo.shiftwidth = 2 vim.bo.softtabstop = 2 vim.opt.autoindent = true vim.g.mapleader = ','
require "paq" { "savq/paq-nvim"; "kylechui/nvim-surround"; "numToStr/Comment.nvim"; "kyazdani42/nvim-web-devicons"; "nvim-lualine/lualine.nvim"; "Mofiqul/dracula.nvim"; "neovim/nvim-lspconfig"; "hrsh7th/nvim-cmp"; "epwalsh/obsidian.nvim"; "junegunn/fzf"; {"nvim-treesitter/nvim-treesitter", run='TSUpdate'}; } --theme: vim.cmd[[colorscheme dracula]] require("dracula").setup({ show_end_of_buffer = true, transparent_bg = true, italic_comment = true }) --lualine require('lualine').setup { options = { theme = 'dracula-nvim' } } require'lspconfig'.rnix.setup{} require'lspconfig'.pyright.setup{} require('nvim-surround').setup() require('comment').setup { ---Add a space b/w comment and the line padding = true, ---Whether the cursor should stay at its position sticky = true, ---Lines to be ignored while (un)comment ignore = '^\\s*$', ---LHS of toggle mappings in NORMAL mode toggler = { ---Line-comment toggle keymap line = 'gcc', ---Block-comment toggle keymap block = 'gbc', }, ---LHS of operator-pending mappings in NORMAL and VISUAL mode opleader = { ---Line-comment keymap line = 'gc', ---Block-comment keymap block = 'gb', }, ---LHS of extra mappings extra = { ---Add comment on the line above above = 'gcO', ---Add comment on the line below below = 'gco', ---Add comment at the end of line eol = 'gcA', }, ---Enable keybindings ---NOTE: If given `false` then the plugin won't create any mappings mappings = { ---Operator-pending mapping; `gcc` `gbc` `gc[count]{motion}` `gb[count]{motion}` basic = true, ---Extra mapping; `gco`, `gcO`, `gcA` extra = true, }, ---Function to call before (un)comment pre_hook = nil, ---Function to call after (un)comment post_hook = nil, } -- treesitter config require('nvim-treesitter.configs').setup { ensure_installed = { "python", "nix", "lua", "rust", "julia", "bash", "yaml", "markdown", "markdown_inline", "html", "css", "comment", "json", "json5", "sql", "toml"}, sync_install = false, auto_install = true, highlight = { enable = true, }, indent = { enable = true }, incremental_selection = { enable = true, keymaps = { init_selection = "gnn", node_incremental = "grn", scope_incremental = "grc", node_decremental = "grm", }, }, } vim.o.completeopt="menuone,noinsert,noselect" local cmp = require'cmp' cmp.setup({ mapping = cmp.mapping.preset.insert({ ['<C-b>'] = cmp.mapping.scroll_docs(-4), ['<C-f>'] = cmp.mapping.scroll_docs(4), ['<C-Space>'] = cmp.mapping.complete(), ['<C-e>'] = cmp.mapping.abort(), ['<CR>'] = cmp.mapping.confirm({ select = true }), -- Accept currently selected item. Set `select` to `false` to only confirm explicitly selected items. }), sources = cmp.config.sources({ { name = 'nvim_lsp' }, }), }) -- fold using nvim treesitter vim.opt.foldmethod = "expr" vim.opt.foldexpr = "nvim_treesitter#foldexpr()" vim.opt.foldlevel = 99 --this makes the folds not show up initially vim.o.smartcase = true vim.o.hlsearch = true vim.o.incsearch = true vim.o.ignorecase = true vim.bo.expandtab = true vim.bo.tabstop = 2 vim.bo.shiftwidth = 2 vim.bo.softtabstop = 2 vim.opt.autoindent = true vim.g.mapleader = ','
fixing init.lua
fixing init.lua
Lua
unlicense
spott/dotfiles,spott/dotfiles
f706003b396de729f15800747a5b1005d8c24a23
homedecor/init.lua
homedecor/init.lua
-- Home Decor mod by VanessaE -- -- Mostly my own code, with bits and pieces lifted from Minetest's default -- lua files and from ironzorg's flowers mod. Many thanks to GloopMaster -- for helping me figure out the inventories used in the nightstands/dressers. -- -- The code for ovens, nightstands, refrigerators are basically modified -- copies of the code for chests and furnaces. homedecor = {} homedecor.debug = 0 -- detail level for roofing slopes and also cobwebs homedecor.detail_level = 16 homedecor.modpath = minetest.get_modpath("homedecor") homedecor.intllib_modpath = minetest.get_modpath("intllib") -- Boilerplate to support localized strings if intllib mod is installed. local S if homedecor.intllib_modpath then dofile(homedecor.intllib_modpath.."/intllib.lua") S = intllib.Getter(minetest.get_current_modname()) else S = function ( s ) return s end end homedecor.gettext = S -- debug local dbg = function(s) if homedecor.debug == 1 then print('[HomeDecor] ' .. s) end end -- infinite stacks if minetest.get_modpath("unified_inventory") or not minetest.setting_getbool("creative_mode") then homedecor.expect_infinite_stacks = false else homedecor.expect_infinite_stacks = true end --table copy function homedecor.table_copy(t) local nt = { }; for k, v in pairs(t) do if type(v) == "table" then nt[k] = homedecor.table_copy(v) else nt[k] = v end end return nt end -- function homedecor.get_nodedef_field(nodename, fieldname) if not minetest.registered_nodes[nodename] then return nil end return minetest.registered_nodes[nodename][fieldname] end -- Stack one node above another function homedecor.stack_vertically(itemstack, placer, pointed_thing, node1, node2) local pos = pointed_thing.under local pnode = minetest.get_node(pointed_thing.under) local rnodedef = minetest.registered_nodes[pnode.name] if not rnodedef["buildable_to"] then pos = pointed_thing.above end local fdir = minetest.dir_to_facedir(placer:get_look_dir()) local pos2 = { x = pos.x, y=pos.y + 1, z = pos.z } local tnode = minetest.get_node(pos) local tnode2 = minetest.get_node(pos2) if homedecor.get_nodedef_field(tnode.name, "buildable_to") and homedecor.get_nodedef_field(tnode2.name, "buildable_to") and not minetest.is_protected(pos, placer:get_player_name()) and not minetest.is_protected(pos2, placer:get_player_name()) then minetest.add_node(pos, { name = node1, param2 = fdir }) minetest.add_node(pos2, { name = node2, param2 = fdir }) if not homedecor.expect_infinite_stacks then itemstack:take_item() return itemstack end end end -- Place one node right of or behind another homedecor.fdir_to_right = { { 1, 0 }, { 0, -1 }, { -1, 0 }, { 0, 1 }, } homedecor.fdir_to_fwd = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 }, } function homedecor.stack_sideways(itemstack, placer, pointed_thing, node1, node2, dir) local pos = pointed_thing.under local pnode = minetest.get_node(pointed_thing.under) local rnodedef = minetest.registered_nodes[pnode.name] if not rnodedef["buildable_to"] then pos = pointed_thing.above end local fdir = minetest.dir_to_facedir(placer:get_look_dir()) local pos2 if dir then pos2 = { x = pos.x + homedecor.fdir_to_right[fdir+1][1], y=pos.y, z = pos.z + homedecor.fdir_to_right[fdir+1][2] } else pos2 = { x = pos.x + homedecor.fdir_to_fwd[fdir+1][1], y=pos.y, z = pos.z + homedecor.fdir_to_fwd[fdir+1][2] } end local tnode = minetest.get_node(pos) local tnode2 = minetest.get_node(pos2) if homedecor.get_nodedef_field(tnode.name, "buildable_to") and homedecor.get_nodedef_field(tnode2.name, "buildable_to") and not minetest.is_protected(pos, placer:get_player_name()) and not minetest.is_protected(pos2, placer:get_player_name()) then minetest.add_node(pos, { name = node1, param2 = fdir }) minetest.add_node(pos2, { name = node2, param2 = fdir }) if not homedecor.expect_infinite_stacks then itemstack:take_item() return itemstack end end end -- load various other components --dofile(homedecor.modpath.."/misc-nodes.lua") -- the catch-all for all misc nodes dofile(homedecor.modpath.."/tables.lua") --dofile(homedecor.modpath.."/electronics.lua") dofile(homedecor.modpath.."/shutters.lua") dofile(homedecor.modpath.."/shingles.lua") dofile(homedecor.modpath.."/slopes.lua") dofile(homedecor.modpath.."/door_models.lua") dofile(homedecor.modpath.."/doors_and_gates.lua") dofile(homedecor.modpath.."/fences.lua") dofile(homedecor.modpath.."/lighting.lua") dofile(homedecor.modpath.."/kitchen_cabinet.lua") dofile(homedecor.modpath.."/refrigerator.lua") --dofile(homedecor.modpath.."/misc-bathroom.lua") --dofile(homedecor.modpath.."/laundry.lua") --dofile(homedecor.modpath.."/furnaces.lua") --dofile(homedecor.modpath.."/nightstands.lua") --dofile(homedecor.modpath.."/clocks.lua") --dofile(homedecor.modpath.."/misc-electrical.lua") --dofile(homedecor.modpath.."/paintings.lua") --dofile(homedecor.modpath.."/window_treatments.lua") dofile(homedecor.modpath.."/crafts.lua") dofile(homedecor.modpath.."/furniture.lua") dofile(homedecor.modpath.."/furniture_medieval.lua") --dofile(homedecor.modpath.."/furniture_bathroom.lua") dofile(homedecor.modpath.."/furniture_recipes.lua") --dofile(homedecor.modpath.."/climate-control.lua") --dofile(homedecor.modpath.."/cobweb.lua") dofile(homedecor.modpath.."/locked.lua") print("[HomeDecor] "..S("Loaded!"))
-- Home Decor mod by VanessaE -- -- Mostly my own code, with bits and pieces lifted from Minetest's default -- lua files and from ironzorg's flowers mod. Many thanks to GloopMaster -- for helping me figure out the inventories used in the nightstands/dressers. -- -- The code for ovens, nightstands, refrigerators are basically modified -- copies of the code for chests and furnaces. homedecor = {} homedecor.debug = 0 -- detail level for roofing slopes and also cobwebs homedecor.detail_level = 16 homedecor.modpath = minetest.get_modpath("homedecor") homedecor.intllib_modpath = minetest.get_modpath("intllib") -- Boilerplate to support localized strings if intllib mod is installed. local S if homedecor.intllib_modpath then dofile(homedecor.intllib_modpath.."/intllib.lua") S = intllib.Getter(minetest.get_current_modname()) else S = function ( s ) return s end end homedecor.gettext = S -- debug local dbg = function(s) if homedecor.debug == 1 then print('[HomeDecor] ' .. s) end end -- infinite stacks if minetest.get_modpath("unified_inventory") or not minetest.setting_getbool("creative_mode") then homedecor.expect_infinite_stacks = false else homedecor.expect_infinite_stacks = true end --table copy function homedecor.table_copy(t) local nt = { }; for k, v in pairs(t) do if type(v) == "table" then nt[k] = homedecor.table_copy(v) else nt[k] = v end end return nt end -- function homedecor.get_nodedef_field(nodename, fieldname) if not minetest.registered_nodes[nodename] then return nil end return minetest.registered_nodes[nodename][fieldname] end -- Stack one node above another function homedecor.stack_vertically(itemstack, placer, pointed_thing, node1, node2) local pos = pointed_thing.under local pnode = minetest.get_node(pointed_thing.under) local rnodedef = minetest.registered_nodes[pnode.name] if not rnodedef["buildable_to"] then pos = pointed_thing.above end local fdir = minetest.dir_to_facedir(placer:get_look_dir()) local pos2 = { x = pos.x, y=pos.y + 1, z = pos.z } local tnode = minetest.get_node(pos) local tnode2 = minetest.get_node(pos2) if homedecor.get_nodedef_field(tnode.name, "buildable_to") and homedecor.get_nodedef_field(tnode2.name, "buildable_to") and not minetest.is_protected(pos, placer:get_player_name()) and not minetest.is_protected(pos2, placer:get_player_name()) then minetest.add_node(pos, { name = node1, param2 = fdir }) minetest.add_node(pos2, { name = node2, param2 = fdir }) if not homedecor.expect_infinite_stacks then itemstack:take_item() return itemstack end end end -- Place one node right of or behind another homedecor.fdir_to_right = { { 1, 0 }, { 0, -1 }, { -1, 0 }, { 0, 1 }, } homedecor.fdir_to_fwd = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 }, } function homedecor.stack_sideways(itemstack, placer, pointed_thing, node1, node2, dir) local pos = pointed_thing.under local pnode = minetest.get_node(pointed_thing.under) local rnodedef = minetest.registered_nodes[pnode.name] if not rnodedef["buildable_to"] then pos = pointed_thing.above end local fdir = minetest.dir_to_facedir(placer:get_look_dir()) local pos2 if dir then pos2 = { x = pos.x + homedecor.fdir_to_right[fdir+1][1], y=pos.y, z = pos.z + homedecor.fdir_to_right[fdir+1][2] } else pos2 = { x = pos.x + homedecor.fdir_to_fwd[fdir+1][1], y=pos.y, z = pos.z + homedecor.fdir_to_fwd[fdir+1][2] } end local tnode = minetest.get_node(pos) local tnode2 = minetest.get_node(pos2) if homedecor.get_nodedef_field(tnode.name, "buildable_to") and homedecor.get_nodedef_field(tnode2.name, "buildable_to") and not minetest.is_protected(pos, placer:get_player_name()) and not minetest.is_protected(pos2, placer:get_player_name()) then minetest.add_node(pos, { name = node1, param2 = fdir }) minetest.add_node(pos2, { name = node2, param2 = fdir }) if not homedecor.expect_infinite_stacks then itemstack:take_item() return itemstack end end end -- load various other components -- the catch-all for all misc nodes dofile(homedecor.modpath.."/tables.lua") dofile(homedecor.modpath.."/shutters.lua") dofile(homedecor.modpath.."/shingels.lua") dofile(homedecor.modpath.."/slopes.lua") dofile(homedecor.modpath.."/door_models.lua") dofile(homedecor.modpath.."/doors_and_gates.lua") dofile(homedecor.modpath.."/fences.lua") dofile(homedecor.modpath.."/lighting.lua") dofile(homedecor.modpath.."/kitchen_cabinet.lua") dofile(homedecor.modpath.."/refrigerator.lua") dofile(homedecor.modpath.."/crafts.lua") dofile(homedecor.modpath.."/furniture.lua") dofile(homedecor.modpath.."/furniture_medieval.lua") dofile(homedecor.modpath.."/furniture_recipes.lua") dofile(homedecor.modpath.."/locked.lua") print("[HomeDecor] "..S("Loaded!"))
Update init.lua
Update init.lua fixed it
Lua
unlicense
deezl/homedecor_lite
341d962de82218339540aed3e80503925346f941
src_trunk/resources/tag-system/c_tag_system.lua
src_trunk/resources/tag-system/c_tag_system.lua
cooldown = 0 count = 0 function clientTagWall(weapon, ammo, ammoInClip, hitX, hitY, hitZ, hitElement) if (weapon==41) then local team = getPlayerTeam(getLocalPlayer()) local ftype = getElementData(team, "type") local tag = getElementData(source, "tag") if (ftype~=2) then if not (hitElement) or (getElementType(hitElement)~="player") then -- Didn't attack someone if (cooldown==0) then if (ammoInClip>10) and (weapon==41) then -- Check the player is near a wall local localPlayer = getLocalPlayer() local x, y, z = getElementPosition(localPlayer) local rot = getPedRotation(localPlayer) local matrix = getElementMatrix (localPlayer) local oldX = 0 local oldY = 1 local oldZ = 0 local newX = oldX * matrix[1][1] + oldY * matrix [2][1] + oldZ * matrix [3][1] + matrix [4][1] local newY = oldX * matrix[1][2] + oldY * matrix [2][2] + oldZ * matrix [3][2] + matrix [4][2] local newZ = oldX * matrix[1][3] + oldY * matrix [2][3] + oldZ * matrix [3][3] + matrix [4][3] local facingWall, cx, cy, cz, element = processLineOfSight(x, y, z, newX, newY, newZ, true, false, false, true, false) if not (facingWall) then outputChatBox("You are not near a wall.", 255, 0, 0) count = 0 cooldown = 1 setTimer(resetCooldown, 5000, 1) else count = count + 1 if (count==20) then count = 0 cooldown = 1 setTimer(resetCooldown, 30000, 1) local interior = getElementInterior(localPlayer) local dimension = getElementDimension(localPlayer) --cx = cx - math.sin(math.rad(rot)) * 0.1 cy = cy - math.cos(math.rad(rot)) * 0.1 triggerServerEvent("createTag", localPlayer, cx, cy, cz, rot, interior, dimension) end end end end end end end end addEventHandler("onClientPlayerWeaponFire", getLocalPlayer(), clientTagWall) function resetCooldown() cooldown = 0 end function setTag(commandName, newTag) if not (newTag) then outputChatBox("SYNTAX: " .. commandName .. " [Tag # 1->8].", 255, 194, 14) else local newTag = tonumber(newTag) if (newTag>0) and (newTag<9) then setElementData(getLocalPlayer(), "tag", true, newTag) outputChatBox("Tag changed to #" .. newTag .. ".", 0, 255, 0) else outputChatBox("Invalid value, please enter a value between 1 and 8.", 255, 0, 0) end end end addCommandHandler("settag", setTag)
cooldown = 0 count = 0 function clientTagWall(weapon, ammo, ammoInClip, hitX, hitY, hitZ, hitElement) if (weapon==41) then local team = getPlayerTeam(getLocalPlayer()) local ftype = getElementData(team, "type") local tag = getElementData(source, "tag") if (ftype~=2) then if not (hitElement) or (getElementType(hitElement)~="player") then -- Didn't attack someone if (cooldown==0) then if (ammoInClip>10) and (weapon==41) then -- Check the player is near a wall local localPlayer = getLocalPlayer() local x, y, z = getElementPosition(localPlayer) local rot = getPedRotation(localPlayer) local matrix = getElementMatrix (localPlayer) -- DIRECTLY INFRONT OF PLAYER local oldX = 0 local oldY = 1 local oldZ = 0 local newX = oldX * matrix[1][1] + oldY * matrix [2][1] + oldZ * matrix [3][1] + matrix [4][1] local newY = oldX * matrix[1][2] + oldY * matrix [2][2] + oldZ * matrix [3][2] + matrix [4][2] local newZ = oldX * matrix[1][3] + oldY * matrix [2][3] + oldZ * matrix [3][3] + matrix [4][3] -- TO LEFT OF PLAYER local oldXleft = -1.5 local oldYleft = 1 local oldZleft = 0 local newXleft = oldXleft * matrix[1][1] + oldYleft * matrix [2][1] + oldZleft * matrix [3][1] + matrix [4][1] local newYleft = oldXleft * matrix[1][2] + oldYleft * matrix [2][2] + oldZleft * matrix [3][2] + matrix [4][2] local newZleft = oldXleft * matrix[1][3] + oldYleft * matrix [2][3] + oldZleft * matrix [3][3] + matrix [4][3] -- TO RIGHT OF PLAYER local oldXright = 1.5 local oldYright = 1 local oldZright = 0 local newXright = oldXright * matrix[1][1] + oldYright * matrix [2][1] + oldZright * matrix [3][1] + matrix [4][1] local newYright = oldXright * matrix[1][2] + oldYright * matrix [2][2] + oldZright * matrix [3][2] + matrix [4][2] local newZright = oldXright * matrix[1][3] + oldYright * matrix [2][3] + oldZright * matrix [3][3] + matrix [4][3] local facingWall, cx, cy, cz, element = processLineOfSight(x, y, z, newX, newY, newZ, true, false, false, true, false) local facingWallleft, lx, ly, lz, lelement = processLineOfSight(x, y, z, newXleft, newYleft, newZleft, true, false, false, true, false) local facingWallright, rx, ry, rz, relement = processLineOfSight(x, y, z, newXright, newYright, newZright, true, false, false, true, false) if not (facingWall) or not (facingWallleft) or not (facingWallright) then outputChatBox("You are not near a wall.", 255, 0, 0) count = 0 cooldown = 1 setTimer(resetCooldown, 5000, 1) else count = count + 1 if (count==20) then count = 0 cooldown = 1 setTimer(resetCooldown, 30000, 1) local interior = getElementInterior(localPlayer) local dimension = getElementDimension(localPlayer) --cx = cx - math.sin(math.rad(rot)) * 0.1 cy = cy - math.cos(math.rad(rot)) * 0.1 triggerServerEvent("createTag", localPlayer, cx, cy, cz, rot, interior, dimension) end end end end end end end end addEventHandler("onClientPlayerWeaponFire", getLocalPlayer(), clientTagWall) function resetCooldown() cooldown = 0 end function setTag(commandName, newTag) if not (newTag) then outputChatBox("SYNTAX: " .. commandName .. " [Tag # 1->8].", 255, 194, 14) else local newTag = tonumber(newTag) if (newTag>0) and (newTag<9) then setElementData(getLocalPlayer(), "tag", true, newTag) outputChatBox("Tag changed to #" .. newTag .. ".", 0, 255, 0) else outputChatBox("Invalid value, please enter a value between 1 and 8.", 255, 0, 0) end end end addCommandHandler("settag", setTag)
Fixed spraying tags on lampposts, also fixed spraying tags on walls which are too small to display the tag.
Fixed spraying tags on lampposts, also fixed spraying tags on walls which are too small to display the tag. git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@491 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
db111997392e93d1d9b16c6d9cad48d9a9ae2111
Interface/AddOns/RayUI/modules/skins/blizzard/quest.lua
Interface/AddOns/RayUI/modules/skins/blizzard/quest.lua
local R, L, P = unpack(select(2, ...)) --Import: Engine, Locales, ProfileDB, local local S = R:GetModule("Skins") local function LoadSkin() local r, g, b = S["media"].classcolours[R.myclass].r, S["media"].classcolours[R.myclass].g, S["media"].classcolours[R.myclass].b S:ReskinPortraitFrame(QuestFrame, true) QuestTitleFont:SetTextColor(1, 1, 1) QuestTitleFont:SetShadowColor(0, 0, 0) QuestTitleFont.SetTextColor = R.dummy QuestTitleFont.SetShadowColor = R.dummy QuestFont:SetTextColor(1, 1, 1) QuestFont.SetTextColor = R.dummy QuestFrameDetailPanel:DisableDrawLayer("BACKGROUND") QuestFrameProgressPanel:DisableDrawLayer("BACKGROUND") QuestFrameRewardPanel:DisableDrawLayer("BACKGROUND") QuestFrameGreetingPanel:DisableDrawLayer("BACKGROUND") QuestFrameDetailPanel:DisableDrawLayer("BORDER") QuestFrameRewardPanel:DisableDrawLayer("BORDER") QuestDetailScrollFrameTop:Hide() QuestDetailScrollFrameBottom:Hide() QuestDetailScrollFrameMiddle:Hide() QuestProgressScrollFrameTop:Hide() QuestProgressScrollFrameBottom:Hide() QuestProgressScrollFrameMiddle:Hide() QuestRewardScrollFrameTop:Hide() QuestRewardScrollFrameBottom:Hide() QuestRewardScrollFrameMiddle:Hide() QuestGreetingScrollFrameTop:Hide() QuestGreetingScrollFrameBottom:Hide() QuestGreetingScrollFrameMiddle:Hide() QuestFrameProgressPanelMaterialTopLeft:SetAlpha(0) QuestFrameProgressPanelMaterialTopRight:SetAlpha(0) QuestFrameProgressPanelMaterialBotLeft:SetAlpha(0) QuestFrameProgressPanelMaterialBotRight:SetAlpha(0) local line = QuestFrameGreetingPanel:CreateTexture() line:SetTexture(1, 1, 1, .2) line:SetSize(256, 1) line:SetPoint("CENTER", QuestGreetingFrameHorizontalBreak) QuestGreetingFrameHorizontalBreak:SetTexture("") QuestFrameGreetingPanel:HookScript("OnShow", function() line:SetShown(QuestGreetingFrameHorizontalBreak:IsShown()) end) for i = 1, MAX_REQUIRED_ITEMS do local bu = _G["QuestProgressItem"..i] local ic = _G["QuestProgressItem"..i.."IconTexture"] local na = _G["QuestProgressItem"..i.."NameFrame"] local co = _G["QuestProgressItem"..i.."Count"] ic:SetSize(40, 40) ic:SetTexCoord(.08, .92, .08, .92) ic:SetDrawLayer("OVERLAY") S:CreateBD(bu, .25) na:Hide() co:SetDrawLayer("OVERLAY") local line = CreateFrame("Frame", nil, bu) line:SetSize(1, 40) line:SetPoint("RIGHT", ic, 1, 0) S:CreateBD(line) end QuestDetailScrollFrame:SetWidth(302) -- else these buttons get cut off hooksecurefunc(QuestProgressRequiredMoneyText, "SetTextColor", function(self, r, g, b) if r == 0 then self:SetTextColor(.8, .8, .8) elseif r == .2 then self:SetTextColor(1, 1, 1) end end) for _, questButton in pairs({"QuestFrameAcceptButton", "QuestFrameDeclineButton", "QuestFrameCompleteQuestButton", "QuestFrameCompleteButton", "QuestFrameGoodbyeButton", "QuestFrameGreetingGoodbyeButton"}) do S:Reskin(_G[questButton]) end S:ReskinScroll(QuestProgressScrollFrameScrollBar) S:ReskinScroll(QuestRewardScrollFrameScrollBar) S:ReskinScroll(QuestDetailScrollFrameScrollBar) S:ReskinScroll(QuestGreetingScrollFrameScrollBar) -- Text colour stuff QuestProgressRequiredItemsText:SetTextColor(1, 1, 1) QuestProgressRequiredItemsText:SetShadowColor(0, 0, 0) QuestProgressText.SetTextColor = R.dummy GreetingText:SetTextColor(1, 1, 1) GreetingText.SetTextColor = R.dummy AvailableQuestsText:SetTextColor(1, 1, 1) AvailableQuestsText.SetTextColor = R.dummy AvailableQuestsText:SetShadowColor(0, 0, 0) CurrentQuestsText:SetTextColor(1, 1, 1) CurrentQuestsText.SetTextColor = R.dummy CurrentQuestsText:SetShadowColor(0, 0, 0) -- [[ Quest NPC model ]] QuestNPCModelShadowOverlay:Hide() QuestNPCModelBg:Hide() QuestNPCModel:DisableDrawLayer("OVERLAY") QuestNPCModelNameText:SetDrawLayer("ARTWORK") QuestNPCModelTextFrameBg:Hide() QuestNPCModelTextFrame:DisableDrawLayer("OVERLAY") local npcbd = CreateFrame("Frame", nil, QuestNPCModel) npcbd:SetPoint("TOPLEFT", -1, 1) npcbd:SetPoint("RIGHT", 2, 0) npcbd:SetPoint("BOTTOM", QuestNPCModelTextScrollFrame) npcbd:SetFrameLevel(0) S:CreateBD(npcbd) local npcLine = CreateFrame("Frame", nil, QuestNPCModel) npcLine:SetPoint("BOTTOMLEFT", 0, -1) npcLine:SetPoint("BOTTOMRIGHT", 1, -1) npcLine:SetHeight(1) npcLine:SetFrameLevel(0) S:CreateBD(npcLine, 0) hooksecurefunc("QuestFrame_ShowQuestPortrait", function(parentFrame, _, _, _, x, y) if parentFrame == QuestLogPopupDetailFrame or parentFrame == QuestFrame then x = x + 3 end QuestNPCModel:SetPoint("TOPLEFT", parentFrame, "TOPRIGHT", x, y) end) S:ReskinScroll(QuestNPCModelTextScrollFrameScrollBar) end S:RegisterSkin("RayUI", LoadSkin)
local R, L, P = unpack(select(2, ...)) --Import: Engine, Locales, ProfileDB, local local S = R:GetModule("Skins") local function LoadSkin() local r, g, b = S["media"].classcolours[R.myclass].r, S["media"].classcolours[R.myclass].g, S["media"].classcolours[R.myclass].b S:ReskinPortraitFrame(QuestFrame, true) QuestTitleFont:SetTextColor(1, 1, 1) QuestTitleFont:SetShadowColor(0, 0, 0) QuestFont:SetTextColor(1, 1, 1) hooksecurefunc("QuestFrameProgressItems_Update", function() QuestProgressTitleText:SetTextColor(1, 1, 1) QuestProgressTitleText:SetShadowColor(0, 0, 0) QuestProgressText:SetTextColor(1, 1, 1) end) QuestFrameDetailPanel:DisableDrawLayer("BACKGROUND") QuestFrameProgressPanel:DisableDrawLayer("BACKGROUND") QuestFrameRewardPanel:DisableDrawLayer("BACKGROUND") QuestFrameGreetingPanel:DisableDrawLayer("BACKGROUND") QuestFrameDetailPanel:DisableDrawLayer("BORDER") QuestFrameRewardPanel:DisableDrawLayer("BORDER") QuestDetailScrollFrameTop:Hide() QuestDetailScrollFrameBottom:Hide() QuestDetailScrollFrameMiddle:Hide() QuestProgressScrollFrameTop:Hide() QuestProgressScrollFrameBottom:Hide() QuestProgressScrollFrameMiddle:Hide() QuestRewardScrollFrameTop:Hide() QuestRewardScrollFrameBottom:Hide() QuestRewardScrollFrameMiddle:Hide() QuestGreetingScrollFrameTop:Hide() QuestGreetingScrollFrameBottom:Hide() QuestGreetingScrollFrameMiddle:Hide() QuestFrameProgressPanelMaterialTopLeft:SetAlpha(0) QuestFrameProgressPanelMaterialTopRight:SetAlpha(0) QuestFrameProgressPanelMaterialBotLeft:SetAlpha(0) QuestFrameProgressPanelMaterialBotRight:SetAlpha(0) local line = QuestFrameGreetingPanel:CreateTexture() line:SetTexture(1, 1, 1, .2) line:SetSize(256, 1) line:SetPoint("CENTER", QuestGreetingFrameHorizontalBreak) QuestGreetingFrameHorizontalBreak:SetTexture("") QuestFrameGreetingPanel:HookScript("OnShow", function() line:SetShown(QuestGreetingFrameHorizontalBreak:IsShown()) end) for i = 1, MAX_REQUIRED_ITEMS do local bu = _G["QuestProgressItem"..i] local ic = _G["QuestProgressItem"..i.."IconTexture"] local na = _G["QuestProgressItem"..i.."NameFrame"] local co = _G["QuestProgressItem"..i.."Count"] ic:SetSize(40, 40) ic:SetTexCoord(.08, .92, .08, .92) ic:SetDrawLayer("OVERLAY") S:CreateBD(bu, .25) na:Hide() co:SetDrawLayer("OVERLAY") local line = CreateFrame("Frame", nil, bu) line:SetSize(1, 40) line:SetPoint("RIGHT", ic, 1, 0) S:CreateBD(line) end QuestDetailScrollFrame:SetWidth(302) -- else these buttons get cut off hooksecurefunc(QuestProgressRequiredMoneyText, "SetTextColor", function(self, r, g, b) if r == 0 then self:SetTextColor(.8, .8, .8) elseif r == .2 then self:SetTextColor(1, 1, 1) end end) for _, questButton in pairs({"QuestFrameAcceptButton", "QuestFrameDeclineButton", "QuestFrameCompleteQuestButton", "QuestFrameCompleteButton", "QuestFrameGoodbyeButton", "QuestFrameGreetingGoodbyeButton"}) do S:Reskin(_G[questButton]) end S:ReskinScroll(QuestProgressScrollFrameScrollBar) S:ReskinScroll(QuestRewardScrollFrameScrollBar) S:ReskinScroll(QuestDetailScrollFrameScrollBar) S:ReskinScroll(QuestGreetingScrollFrameScrollBar) -- Text colour stuff QuestProgressRequiredItemsText:SetTextColor(1, 1, 1) QuestProgressRequiredItemsText:SetShadowColor(0, 0, 0) GreetingText:SetTextColor(1, 1, 1) GreetingText.SetTextColor = R.dummy AvailableQuestsText:SetTextColor(1, 1, 1) AvailableQuestsText.SetTextColor = R.dummy AvailableQuestsText:SetShadowColor(0, 0, 0) CurrentQuestsText:SetTextColor(1, 1, 1) CurrentQuestsText.SetTextColor = R.dummy CurrentQuestsText:SetShadowColor(0, 0, 0) -- [[ Quest NPC model ]] QuestNPCModelShadowOverlay:Hide() QuestNPCModelBg:Hide() QuestNPCModel:DisableDrawLayer("OVERLAY") QuestNPCModelNameText:SetDrawLayer("ARTWORK") QuestNPCModelTextFrameBg:Hide() QuestNPCModelTextFrame:DisableDrawLayer("OVERLAY") local npcbd = CreateFrame("Frame", nil, QuestNPCModel) npcbd:SetPoint("TOPLEFT", -1, 1) npcbd:SetPoint("RIGHT", 2, 0) npcbd:SetPoint("BOTTOM", QuestNPCModelTextScrollFrame) npcbd:SetFrameLevel(0) S:CreateBD(npcbd) local npcLine = CreateFrame("Frame", nil, QuestNPCModel) npcLine:SetPoint("BOTTOMLEFT", 0, -1) npcLine:SetPoint("BOTTOMRIGHT", 1, -1) npcLine:SetHeight(1) npcLine:SetFrameLevel(0) S:CreateBD(npcLine, 0) hooksecurefunc("QuestFrame_ShowQuestPortrait", function(parentFrame, _, _, _, x, y) if parentFrame == QuestLogPopupDetailFrame or parentFrame == QuestFrame then x = x + 3 end QuestNPCModel:SetPoint("TOPLEFT", parentFrame, "TOPRIGHT", x, y) end) S:ReskinScroll(QuestNPCModelTextScrollFrameScrollBar) end S:RegisterSkin("RayUI", LoadSkin)
fix QuestProgressText color again...
fix QuestProgressText color again...
Lua
mit
fgprodigal/RayUI
1c5aa436cb6a72d68c64555a485b221786a0c09f
net/http.lua
net/http.lua
-- Prosody IM -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local socket = require "socket" local mime = require "mime" local url = require "socket.url" local server = require "net.server" local connlisteners_get = require "net.connlisteners".get; local listener = connlisteners_get("httpclient") or error("No httpclient listener!"); local t_insert, t_concat = table.insert, table.concat; local tonumber, tostring, pairs, xpcall, select, debug_traceback, char, format = tonumber, tostring, pairs, xpcall, select, debug.traceback, string.char, string.format; local log = require "util.logger".init("http"); local print = function () end module "http" function urlencode(s) return s and (s:gsub("%W", function (c) return format("%%%02x", c:byte()); end)); end function urldecode(s) return s and (s:gsub("%%(%x%x)", function (c) return char(tonumber(c,16)); end)); end local function expectbody(reqt, code) if reqt.method == "HEAD" then return nil end if code == 204 or code == 304 or code == 301 then return nil end if code >= 100 and code < 200 then return nil end return 1 end local function request_reader(request, data, startpos) if not data then if request.body then log("debug", "Connection closed, but we have data, calling callback..."); request.callback(t_concat(request.body), request.code, request); elseif request.state ~= "completed" then -- Error.. connection was closed prematurely request.callback("connection-closed", 0, request); end destroy_request(request); request.body = nil; request.state = "completed"; return; end if request.state == "body" and request.state ~= "completed" then print("Reading body...") if not request.body then request.body = {}; request.havebodylength, request.bodylength = 0, tonumber(request.responseheaders["content-length"]); end if startpos then data = data:sub(startpos, -1) end t_insert(request.body, data); if request.bodylength then request.havebodylength = request.havebodylength + #data; if request.havebodylength >= request.bodylength then -- We have the body log("debug", "Have full body, calling callback"); if request.callback then request.callback(t_concat(request.body), request.code, request); end request.body = nil; request.state = "completed"; else print("", "Have "..request.havebodylength.." bytes out of "..request.bodylength); end end elseif request.state == "headers" then print("Reading headers...") local pos = startpos; local headers = request.responseheaders or {}; for line in data:sub(startpos, -1):gmatch("(.-)\r\n") do startpos = startpos + #line + 2; local k, v = line:match("(%S+): (.+)"); if k and v then headers[k:lower()] = v; print("Header: "..k:lower().." = "..v); elseif #line == 0 then request.responseheaders = headers; break; else print("Unhandled header line: "..line); end end -- Reached the end of the headers request.state = "body"; if #data > startpos then return request_reader(request, data, startpos); end elseif request.state == "status" then print("Reading status...") local http, code, text, linelen = data:match("^HTTP/(%S+) (%d+) (.-)\r\n()", startpos); code = tonumber(code); if not code then return request.callback("invalid-status-line", 0, request); end request.code, request.responseversion = code, http; if request.onlystatus or not expectbody(request, code) then if request.callback then request.callback(nil, code, request); end destroy_request(request); return; end request.state = "headers"; if #data > linelen then return request_reader(request, data, linelen); end end end local function handleerr(err) log("error", "Traceback[http]: %s: %s", tostring(err), debug_traceback()); end function request(u, ex, callback) local req = url.parse(u); if not (req and req.host) then callback(nil, 0, req); return nil, "invalid-url"; end if not req.path then req.path = "/"; end local custom_headers, body; local default_headers = { ["Host"] = req.host, ["User-Agent"] = "Prosody XMPP Server" } if req.userinfo then default_headers["Authorization"] = "Basic "..mime.b64(req.userinfo); end if ex then custom_headers = ex.headers; req.onlystatus = ex.onlystatus; body = ex.body; if body then req.method = "POST "; default_headers["Content-Length"] = tostring(#body); default_headers["Content-Type"] = "application/x-www-form-urlencoded"; end if ex.method then req.method = ex.method; end end req.handler, req.conn = server.wrapclient(socket.tcp(), req.host, req.port or 80, listener, "*a"); req.write = function (...) return req.handler:write(...); end req.conn:settimeout(0); local ok, err = req.conn:connect(req.host, req.port or 80); if not ok and err ~= "timeout" then callback(nil, 0, req); return nil, err; end local request_line = { req.method or "GET", " ", req.path, " HTTP/1.1\r\n" }; if req.query then t_insert(request_line, 4, "?"); t_insert(request_line, 5, req.query); end req.write(t_concat(request_line)); local t = { [2] = ": ", [4] = "\r\n" }; if custom_headers then for k, v in pairs(custom_headers) do t[1], t[3] = k, v; req.write(t_concat(t)); default_headers[k] = nil; end end for k, v in pairs(default_headers) do t[1], t[3] = k, v; req.write(t_concat(t)); default_headers[k] = nil; end req.write("\r\n"); if body then req.write(body); end req.callback = function (content, code, request) log("debug", "Calling callback, status %s", code or "---"); return select(2, xpcall(function () return callback(content, code, request) end, handleerr)); end req.reader = request_reader; req.state = "status"; listener.register_request(req.handler, req); return req; end function destroy_request(request) if request.conn then request.handler.close() listener.ondisconnect(request.conn, "closed"); end end _M.urlencode = urlencode; return _M;
-- Prosody IM -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local socket = require "socket" local mime = require "mime" local url = require "socket.url" local server = require "net.server" local connlisteners_get = require "net.connlisteners".get; local listener = connlisteners_get("httpclient") or error("No httpclient listener!"); local t_insert, t_concat = table.insert, table.concat; local tonumber, tostring, pairs, xpcall, select, debug_traceback, char, format = tonumber, tostring, pairs, xpcall, select, debug.traceback, string.char, string.format; local log = require "util.logger".init("http"); local print = function () end module "http" function urlencode(s) return s and (s:gsub("%W", function (c) return format("%%%02x", c:byte()); end)); end function urldecode(s) return s and (s:gsub("%%(%x%x)", function (c) return char(tonumber(c,16)); end)); end local function expectbody(reqt, code) if reqt.method == "HEAD" then return nil end if code == 204 or code == 304 or code == 301 then return nil end if code >= 100 and code < 200 then return nil end return 1 end local function request_reader(request, data, startpos) if not data then if request.body then log("debug", "Connection closed, but we have data, calling callback..."); request.callback(t_concat(request.body), request.code, request); elseif request.state ~= "completed" then -- Error.. connection was closed prematurely request.callback("connection-closed", 0, request); end destroy_request(request); request.body = nil; request.state = "completed"; return; end if request.state == "body" and request.state ~= "completed" then print("Reading body...") if not request.body then request.body = {}; request.havebodylength, request.bodylength = 0, tonumber(request.responseheaders["content-length"]); end if startpos then data = data:sub(startpos, -1) end t_insert(request.body, data); if request.bodylength then request.havebodylength = request.havebodylength + #data; if request.havebodylength >= request.bodylength then -- We have the body log("debug", "Have full body, calling callback"); if request.callback then request.callback(t_concat(request.body), request.code, request); end request.body = nil; request.state = "completed"; else print("", "Have "..request.havebodylength.." bytes out of "..request.bodylength); end end elseif request.state == "headers" then print("Reading headers...") local pos = startpos; local headers, headers_complete = request.responseheaders; if not headers then headers = {}; request.responseheaders = headers; end for line in data:sub(startpos, -1):gmatch("(.-)\r\n") do startpos = startpos + #line + 2; local k, v = line:match("(%S+): (.+)"); if k and v then headers[k:lower()] = v; --print("Header: "..k:lower().." = "..v); elseif #line == 0 then headers_complete = true; break; else print("Unhandled header line: "..line); end end if not headers_complete then return; end -- Reached the end of the headers if not expectbody(request, request.code) then request.callback(nil, request.code, request); return; end request.state = "body"; if #data > startpos then return request_reader(request, data, startpos); end elseif request.state == "status" then print("Reading status...") local http, code, text, linelen = data:match("^HTTP/(%S+) (%d+) (.-)\r\n()", startpos); code = tonumber(code); if not code then return request.callback("invalid-status-line", 0, request); end request.code, request.responseversion = code, http; if request.onlystatus then if request.callback then request.callback(nil, code, request); end destroy_request(request); return; end request.state = "headers"; if #data > linelen then return request_reader(request, data, linelen); end end end local function handleerr(err) log("error", "Traceback[http]: %s: %s", tostring(err), debug_traceback()); end function request(u, ex, callback) local req = url.parse(u); if not (req and req.host) then callback(nil, 0, req); return nil, "invalid-url"; end if not req.path then req.path = "/"; end local custom_headers, body; local default_headers = { ["Host"] = req.host, ["User-Agent"] = "Prosody XMPP Server" } if req.userinfo then default_headers["Authorization"] = "Basic "..mime.b64(req.userinfo); end if ex then custom_headers = ex.headers; req.onlystatus = ex.onlystatus; body = ex.body; if body then req.method = "POST "; default_headers["Content-Length"] = tostring(#body); default_headers["Content-Type"] = "application/x-www-form-urlencoded"; end if ex.method then req.method = ex.method; end end req.handler, req.conn = server.wrapclient(socket.tcp(), req.host, req.port or 80, listener, "*a"); req.write = function (...) return req.handler:write(...); end req.conn:settimeout(0); local ok, err = req.conn:connect(req.host, req.port or 80); if not ok and err ~= "timeout" then callback(nil, 0, req); return nil, err; end local request_line = { req.method or "GET", " ", req.path, " HTTP/1.1\r\n" }; if req.query then t_insert(request_line, 4, "?"); t_insert(request_line, 5, req.query); end req.write(t_concat(request_line)); local t = { [2] = ": ", [4] = "\r\n" }; if custom_headers then for k, v in pairs(custom_headers) do t[1], t[3] = k, v; req.write(t_concat(t)); default_headers[k] = nil; end end for k, v in pairs(default_headers) do t[1], t[3] = k, v; req.write(t_concat(t)); default_headers[k] = nil; end req.write("\r\n"); if body then req.write(body); end req.callback = function (content, code, request) log("debug", "Calling callback, status %s", code or "---"); return select(2, xpcall(function () return callback(content, code, request) end, handleerr)); end req.reader = request_reader; req.state = "status"; listener.register_request(req.handler, req); return req; end function destroy_request(request) if request.conn then request.handler.close() listener.ondisconnect(request.conn, "closed"); end end _M.urlencode = urlencode; return _M;
net.http: Port commit 2f235c57d713 to net.http to fix headers in responses (thanks dersd)
net.http: Port commit 2f235c57d713 to net.http to fix headers in responses (thanks dersd)
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
0ece12ef51bc78be974175d4e0ac1a23bdbfcb63
source-code/init.lua
source-code/init.lua
print("Heap: ", node.heap(), "Initializing device") require("start") print("Heap: ", node.heap(), "Loaded: ", "Startup (compiler & blinker)") print("Heap: ", node.heap(), "Connecting to Wifi..") local startCountDown = 0 if wifi.sta.getconfig() == "" then startCountDown = 5 enduser_setup.manual(false) enduser_setup.start() print("Heap: ", node.heap(), "End User Setup started") end local _ = tmr.create():alarm(900, tmr.ALARM_AUTO, function(t) require("led_flip").flip() if wifi.sta.getip() then t:unregister() t = nil print("Heap: ", node.heap(), "Wifi connected with IP: ", wifi.sta.getip()) if file.exists("update_init.lc")then require("update") else if startCountDown > 1 then startCountDown = startCountDown - 1 else startCountDown = nil gpio.write(4, gpio.HIGH) enduser_setup.stop() require("server") print("Heap: ", node.heap(), "Loaded: ", "server") require("application") print("Heap: ", node.heap(), "Loaded: ", "application") end end end end)
print("Heap: ", node.heap(), "Initializing device") require("start") print("Heap: ", node.heap(), "Loaded: ", "Startup (compiler & blinker)") print("Heap: ", node.heap(), "Connecting to Wifi..") local startCountDown = 0 wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, function(T) print("Heap: ", node.heap(), "Cannot connect to WiFi") enduser_setup.manual(false) enduser_setup.start() wifi.eventmon.unregister(wifi.eventmon.STA_DISCONNECTED) print("Heap: ", node.heap(), "WiFi Setup started") end) if wifi.sta.getconfig() == "" then print("Heap: ", node.heap(), "WiFi not configured") startCountDown = 5 enduser_setup.manual(false) enduser_setup.start() print("Heap: ", node.heap(), "WiFi Setup started") end local _ = tmr.create():alarm(900, tmr.ALARM_AUTO, function(t) require("led_flip").flip() if wifi.sta.getip() then t:unregister() t = nil print("Heap: ", node.heap(), "Wifi connected with IP: ", wifi.sta.getip()) if file.exists("update_init.lc")then require("update") else if startCountDown > 1 then startCountDown = startCountDown - 1 else startCountDown = nil gpio.write(4, gpio.HIGH) enduser_setup.stop() wifi.eventmon.unregister(wifi.eventmon.STA_DISCONNECTED) require("server") print("Heap: ", node.heap(), "Loaded: ", "server") require("application") print("Heap: ", node.heap(), "Loaded: ", "application") end end end end)
fix wrong password wifi lockout issue
fix wrong password wifi lockout issue
Lua
apache-2.0
konnected-io/konnected-security,konnected-io/konnected-security
5e836ece1febc0d5807a8b335fc0789b15ae0bc7
share/media/spiegel.lua
share/media/spiegel.lua
-- libquvi-scripts -- Copyright (C) 2010-2011,2013 Toni Gundogdu <legatvs@gmail.com> -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This program is free software: you can redistribute it and/or -- modify it under the terms of the GNU Affero General Public -- License as published by the Free Software Foundation, either -- version 3 of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU Affero General Public License for more details. -- -- You should have received a copy of the GNU Affero General -- Public License along with this program. If not, see -- <http://www.gnu.org/licenses/>. -- -- -- NOTE: Some streams (e.g. 3gp) do not appear to be available (404) even -- if they are listed in the config XML. -- local Spiegel = {} -- Utility functions unique to this script -- Identify the media script. function ident(qargs) return { can_parse_url = Spiegel.can_parse_url(qargs), domains = table.concat({'spiegel.de'}, ',') } end -- Parse the media properties. function parse(qargs) local C = require 'quvi/const' local o = { [C.qoo_fetch_from_charset] = 'iso-8859-1' } local p = quvi.http.fetch(qargs.input_url, o).data qargs.thumb_url = p:match('"og:image" content="(.-)"') or '' qargs.title = p:match('"spVideoTitle">(.-)<') or '' -- Make mandatory: needed to fetch the config XML qargs.id = qargs.input_url:match('/video/.-(%d+)%.html$') or error('no match: media ID') local t = {'http://video.spiegel.de/flash/', qargs.id, '.xml'} local c = quvi.http.fetch(table.concat(t,'')).data local P = require 'lxp.lom' local x = P.parse(c) qargs.streams = Spiegel.iter_streams(x) qargs.duration_ms = qargs.streams[1].nostd.duration_ms return qargs end -- -- Utility functions -- function Spiegel.can_parse_url(qargs) local U = require 'socket.url' local t = U.parse(qargs.input_url) if t and t.scheme and t.scheme:lower():match('^http$') and t.host and t.host:lower():match('spiegel%.de$') and t.path and t.path:lower():match('^/video/.-%d+%.html$') then return true else return false end end function Spiegel.iter_streams(x) local S = require 'quvi/stream' local L = require 'quvi/lxph' local r = {} for i=1, #x do if x[i].tag and x[i].tag:match('type%d+') then local n = L.find_first_tag(x[i], 'filename')[1] local u = 'http://video.spiegel.de/flash/'..n local t = S.stream_new(u) t.video = { bitrate_kbit_s = tonumber(L.find_first_tag(x[i], 'totalbitrate')[1]), height = tonumber(L.find_first_tag(x[i], 'height')[1]), encoding = L.find_first_tag(x[i], 'codec')[1]:lower(), width = tonumber(L.find_first_tag(x[i], 'width')[1]) } -- Used by this script only. libquvi will ignore the 'nostd' values. t.nostd = { duration_ms = (tonumber(L.find_first_tag(x[i], 'duration')[1])*1000) } t.container = (n:match('%.(%w+)$') or ''):lower() t.id = Spiegel.to_id(t) table.insert(r,t) end end if #r >1 then Spiegel.ch_best(S, r) end return r end function Spiegel.ch_best(S, t) local r = t[1] r.flags.best = true for _,v in pairs(t) do if v.video.height > r.video.height then r = S.swap_best(r, v) end end end function Spiegel.to_id(t) return string.format('%s_%s_%sk_%sp', t.container, t.video.encoding, t.video.bitrate_kbit_s, t.video.height) end -- vim: set ts=2 sw=2 tw=72 expandtab:
-- libquvi-scripts -- Copyright (C) 2010-2011,2013 Toni Gundogdu <legatvs@gmail.com> -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This program is free software: you can redistribute it and/or -- modify it under the terms of the GNU Affero General Public -- License as published by the Free Software Foundation, either -- version 3 of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU Affero General Public License for more details. -- -- You should have received a copy of the GNU Affero General -- Public License along with this program. If not, see -- <http://www.gnu.org/licenses/>. -- -- -- NOTE: Some streams (e.g. 3gp) do not appear to be available (404) even -- if they are listed in the config XML. -- local Spiegel = {} -- Utility functions unique to this script -- Identify the media script. function ident(qargs) return { can_parse_url = Spiegel.can_parse_url(qargs), domains = table.concat({'spiegel.de'}, ',') } end -- Parse the media properties. function parse(qargs) local C = require 'quvi/const' local o = { [C.qoo_fetch_from_charset] = 'iso-8859-1' } local p = quvi.http.fetch(qargs.input_url, o).data qargs.thumb_url = p:match('"og:image" content="(.-)"') or '' qargs.title = p:match('"module%-title">(.-)</') or p:match('"og:title".-content="(.-)%s+%-%s+SP') or '' -- Make mandatory: needed to fetch the config XML qargs.id = qargs.input_url:match('/video/.-(%d+)%.html$') or error('no match: media ID') local t = {'http://video.spiegel.de/flash/', qargs.id, '.xml'} local c = quvi.http.fetch(table.concat(t,'')).data local P = require 'lxp.lom' local x = P.parse(c) qargs.streams = Spiegel.iter_streams(x) qargs.duration_ms = qargs.streams[1].nostd.duration_ms return qargs end -- -- Utility functions -- function Spiegel.can_parse_url(qargs) local U = require 'socket.url' local t = U.parse(qargs.input_url) if t and t.scheme and t.scheme:lower():match('^http$') and t.host and t.host:lower():match('spiegel%.de$') and t.path and t.path:lower():match('^/video/.-%d+%.html$') then return true else return false end end function Spiegel.iter_streams(x) local S = require 'quvi/stream' local L = require 'quvi/lxph' local r = {} for i=1, #x do if x[i].tag and x[i].tag:match('type%d+') then local n = L.find_first_tag(x[i], 'filename')[1] local u = 'http://video.spiegel.de/flash/'..n local t = S.stream_new(u) t.video = { bitrate_kbit_s = tonumber(L.find_first_tag(x[i], 'totalbitrate')[1]), height = tonumber(L.find_first_tag(x[i], 'height')[1]), encoding = L.find_first_tag(x[i], 'codec')[1]:lower(), width = tonumber(L.find_first_tag(x[i], 'width')[1]) } -- Used by this script only. libquvi will ignore the 'nostd' values. t.nostd = { duration_ms = (tonumber(L.find_first_tag(x[i], 'duration')[1])*1000) } t.container = (n:match('%.(%w+)$') or ''):lower() t.id = Spiegel.to_id(t) table.insert(r,t) end end if #r >1 then Spiegel.ch_best(S, r) end return r end function Spiegel.ch_best(S, t) local r = t[1] r.flags.best = true for _,v in pairs(t) do if v.video.height > r.video.height then r = S.swap_best(r, v) end end end function Spiegel.to_id(t) return string.format('%s_%s_%sk_%sp', t.container, t.video.encoding, t.video.bitrate_kbit_s, t.video.height) end -- vim: set ts=2 sw=2 tw=72 expandtab:
FIX: media/spiegel.lua: title pattern (BACKPORTpt4)
FIX: media/spiegel.lua: title pattern (BACKPORTpt4) Other: * Add an additional title pattern to fall back to * Backported from maint-0.4 (20e95ca) Signed-off-by: Toni Gundogdu <eac2284b3c43676907b96f08de9d3d52d5df0361@gmail.com>
Lua
agpl-3.0
legatvs/libquvi-scripts,alech/libquvi-scripts,legatvs/libquvi-scripts,alech/libquvi-scripts
d0f553b7a50f2db9288685de0aa11c164e28de1f
aspects/nvim/files/.config/nvim/lua/wincent/vim/map.lua
aspects/nvim/files/.config/nvim/lua/wincent/vim/map.lua
wincent.g.map_callbacks = {} -- TODO: For completeness, should have unmap() too, and other variants -- as they arise (nunmap() etc); but for now just going with a "dispose" -- function as return value. local map = function (mode, lhs, rhs, opts) opts = opts or {} local rhs_type = type(rhs) if rhs_type == 'function' then local key = wincent.util.get_key_for_fn(rhs, wincent.g.map_callbacks) wincent.g.map_callbacks[key] = rhs rhs = 'v:lua.wincent.g.map_callbacks.' .. key .. '()' elseif rhs_type ~= 'string' then error('map(): unsupported rhs type: ' .. rhs_type) end local buffer = opts.buffer opts.buffer = nil if buffer == true then vim.api.nvim_buf_set_keymap(0, mode, lhs, rhs, opts) else vim.api.nvim_set_keymap(mode, lhs, rhs, opts) end return { dispose = function() if buffer == true then vim.api.nvim_buf_del_keymap(0, mode, lhs) else vim.api.nvim_del_keymap(mode, lhs) end wincent.g.map_callbacks[key] = nil end, } end return map
wincent.g.map_callbacks = {} -- TODO: For completeness, should have unmap() too, and other variants -- as they arise (nunmap() etc); but for now just going with a "dispose" -- function as return value. local map = function (mode, lhs, rhs, opts) opts = opts or {} local rhs_type = type(rhs) if rhs_type == 'function' then local key = wincent.util.get_key_for_fn(rhs, wincent.g.map_callbacks) wincent.g.map_callbacks[key] = rhs if opts.expr then rhs = 'v:lua.wincent.g.map_callbacks.' .. key .. '()' else rhs = ':lua wincent.g.map_callbacks.' .. key .. '()<CR>' end elseif rhs_type ~= 'string' then error('map(): unsupported rhs type: ' .. rhs_type) end local buffer = opts.buffer opts.buffer = nil if buffer == true then vim.api.nvim_buf_set_keymap(0, mode, lhs, rhs, opts) else vim.api.nvim_set_keymap(mode, lhs, rhs, opts) end return { dispose = function() if buffer == true then vim.api.nvim_buf_del_keymap(0, mode, lhs) else vim.api.nvim_del_keymap(mode, lhs) end wincent.g.map_callbacks[key] = nil end, } end return map
fix(nvim): unbreak <Leader>r mapping
fix(nvim): unbreak <Leader>r mapping I must have broken this months ago without noticing. The gotcha here is that we need to support both `<expr>` and non-`<expr>` mappings. Examples of the former category include some autocompletion-related ones. For those, we evaluate the (VimScript) expressions, which happen to be calls into Lua (eg. `v:lua.blah()`) and the return value ends up being the RHS of the mapping. The second category are ones like the `<Leader>r` mapping. For those we have to get into a command context and call a Lua function (ie. `:lua do_something()<CR>`).
Lua
unlicense
wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent
60aaa9c6991bc45d21d773dc881f972ea74938de
src/program/lwaftr/query/query.lua
src/program/lwaftr/query/query.lua
module(..., package.seeall) local S = require("syscall") local counter = require("core.counter") local ffi = require("ffi") local lib = require("core.lib") local lwaftr = require("apps.lwaftr.lwaftr") local lwtypes = require("apps.lwaftr.lwtypes") local lwutil = require("apps.lwaftr.lwutil") local shm = require("core.shm") local top = require("program.top.top") local select_snabb_instance = top.select_snabb_instance local keys = lwutil.keys -- Get the counter dir from the code. local counters_rel_dir = lwaftr.counters_dir function show_usage (code) print(require("program.lwaftr.query.README_inc")) main.exit(code) end local function sort (t) table.sort(t) return t end local function is_counter_name (name) return lwaftr.counter_names[name] ~= nil end local function pidof(maybe_pid) if tonumber(maybe_pid) then return maybe_pid end local name_id = maybe_pid for _, pid in ipairs(shm.children("/")) do if shm.exists(pid.."/nic/id") then local lwaftr_id = shm.open("/"..pid.."/nic/id", lwtypes.lwaftr_id_type) if ffi.string(lwaftr_id.value) == name_id then return pid end end end end function parse_args (raw_args) local handlers = {} function handlers.h() show_usage(0) end function handlers.l () for _, name in ipairs(sort(lwaftr.counter_names)) do print(name) end main.exit(0) end local args = lib.dogetopt(raw_args, handlers, "hl", { help="h", ["list-all"]="l" }) if #args > 2 then show_usage(1) end if #args == 2 then return args[1], args[2] end if #args == 1 then local arg = args[1] if is_counter_name(arg) then return nil, arg else local pid = pidof(arg) if not pid then error(("Couldn't find PID for argument '%s'"):format(arg)) end return pid, nil end end return nil, nil end local function read_counters (tree, filter) local ret = {} local cnt, cnt_path, value local max_width = 0 local counters_path = "/" .. tree .. "/" .. counters_rel_dir local counters = shm.children(counters_path) for _, name in ipairs(counters) do cnt_path = counters_path .. name cnt = counter.open(cnt_path, 'readonly') value = tonumber(counter.read(cnt)) if value ~= 0 then name = name:gsub(".counter$", "") if #name > max_width then max_width = #name end ret[name] = value end end return ret, max_width end local function skip_counter (name, filter) return filter and not name:match(filter) end local function print_counter (name, value, max_width) local nspaces = max_width - #name print(("%s: %s%s"):format(name, (" "):rep(nspaces), lib.comma_value(value))) end function print_counters (tree, filter) print("lwAFTR operational counters (non-zero)") -- Open, read and print whatever counters are in that directory. local counters, max_width = read_counters(tree, filter) for _, name in ipairs(sort(keys(counters))) do if not skip_counter(name, filter) then local value = counters[name] print_counter(name, value, max_width) end end end function run (raw_args) local target_pid, counter_name = parse_args(raw_args) local instance_tree = select_snabb_instance(target_pid) print_counters(instance_tree, counter_name) end
module(..., package.seeall) local S = require("syscall") local counter = require("core.counter") local ffi = require("ffi") local lib = require("core.lib") local lwcounter = require("apps.lwaftr.lwcounter") local lwtypes = require("apps.lwaftr.lwtypes") local lwutil = require("apps.lwaftr.lwutil") local shm = require("core.shm") local top = require("program.top.top") local select_snabb_instance = top.select_snabb_instance local keys = lwutil.keys -- Get the counter dir from the code. local counters_dir = lwcounter.counters_dir function show_usage (code) print(require("program.lwaftr.query.README_inc")) main.exit(code) end local function sort (t) table.sort(t) return t end local function is_counter_name (name) return lwcounter.counter_names[name] ~= nil end local function pidof(maybe_pid) if tonumber(maybe_pid) then return maybe_pid end local name_id = maybe_pid for _, pid in ipairs(shm.children("/")) do if shm.exists(pid.."/nic/id") then local lwaftr_id = shm.open("/"..pid.."/nic/id", lwtypes.lwaftr_id_type) if ffi.string(lwaftr_id.value) == name_id then return pid end end end end function parse_args (raw_args) local handlers = {} function handlers.h() show_usage(0) end function handlers.l () for _, name in ipairs(sort(lwcounter.counter_names)) do print(name) end main.exit(0) end local args = lib.dogetopt(raw_args, handlers, "hl", { help="h", ["list-all"]="l" }) if #args > 2 then show_usage(1) end if #args == 2 then return args[1], args[2] end if #args == 1 then local arg = args[1] if is_counter_name(arg) then return nil, arg else local pid = pidof(arg) if not pid then error(("Couldn't find PID for argument '%s'"):format(arg)) end return pid, nil end end return nil, nil end local function read_counters (tree, filter) local ret = {} local cnt, cnt_path, value local max_width = 0 local counters_path = "/" .. tree .. "/" .. counters_dir local counters = shm.children(counters_path) for _, name in ipairs(counters) do cnt_path = counters_path .. name cnt = counter.open(cnt_path, 'readonly') value = tonumber(counter.read(cnt)) if value ~= 0 then name = name:gsub(".counter$", "") if #name > max_width then max_width = #name end ret[name] = value end end return ret, max_width end local function skip_counter (name, filter) return filter and not name:match(filter) end local function print_counter (name, value, max_width) local nspaces = max_width - #name print(("%s: %s%s"):format(name, (" "):rep(nspaces), lib.comma_value(value))) end function print_counters (tree, filter) print("lwAFTR operational counters (non-zero)") -- Open, read and print whatever counters are in that directory. local counters, max_width = read_counters(tree, filter) for _, name in ipairs(sort(keys(counters))) do if not skip_counter(name, filter) then local value = counters[name] print_counter(name, value, max_width) end end end function run (raw_args) local target_pid, counter_name = parse_args(raw_args) local instance_tree = select_snabb_instance(target_pid) print_counters(instance_tree, counter_name) end
Fix counters path
Fix counters path
Lua
apache-2.0
Igalia/snabb,Igalia/snabb,mixflowtech/logsensor,eugeneia/snabbswitch,snabbco/snabb,eugeneia/snabb,dpino/snabb,snabbco/snabb,Igalia/snabb,dpino/snabbswitch,eugeneia/snabbswitch,dpino/snabb,eugeneia/snabbswitch,alexandergall/snabbswitch,Igalia/snabb,eugeneia/snabb,alexandergall/snabbswitch,SnabbCo/snabbswitch,eugeneia/snabb,eugeneia/snabb,snabbco/snabb,heryii/snabb,snabbco/snabb,snabbco/snabb,Igalia/snabb,eugeneia/snabbswitch,dpino/snabbswitch,heryii/snabb,dpino/snabb,kbara/snabb,heryii/snabb,Igalia/snabbswitch,SnabbCo/snabbswitch,snabbco/snabb,eugeneia/snabb,Igalia/snabbswitch,alexandergall/snabbswitch,mixflowtech/logsensor,Igalia/snabbswitch,kbara/snabb,dpino/snabb,kbara/snabb,snabbco/snabb,eugeneia/snabb,Igalia/snabb,Igalia/snabb,Igalia/snabbswitch,Igalia/snabbswitch,dpino/snabb,eugeneia/snabb,mixflowtech/logsensor,alexandergall/snabbswitch,dpino/snabbswitch,alexandergall/snabbswitch,kbara/snabb,dpino/snabb,heryii/snabb,snabbco/snabb,heryii/snabb,heryii/snabb,eugeneia/snabb,alexandergall/snabbswitch,kbara/snabb,SnabbCo/snabbswitch,SnabbCo/snabbswitch,alexandergall/snabbswitch,alexandergall/snabbswitch,Igalia/snabb,dpino/snabb,mixflowtech/logsensor,kbara/snabb,dpino/snabbswitch,mixflowtech/logsensor
4f4c9cee7dcb384a2b6f3b070580747f9198ddb7
alchemy/lte/id_329_transformation.lua
alchemy/lte/id_329_transformation.lua
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- LTE fr das Druidensystem -- by Falk -- Zeitverlauf und Rckwandlung bei Verwandlungen local common = require("base.common") local M = {} -- INSERT INTO longtimeeffects VALUES (329, 'alchemy_transformation', 'alchemy.lte.id_329_transformation'); function getAction(User,Effect,Runde) --Hier die eigentlichen Aktionen eintragen end function M.addEffect(Effect, User) -- Nur beim ersten Aufruf --User:inform("debug func addEffect") end function M.callEffect(Effect,User) --User:inform("debug func callEffect") local findCounter,counterBlack = Effect:findValue("counterBlack") if findCounter then if counterBlack >= 1 then -- info that the effect will be removed soon if counterBlack == 2 then common.InformNLS( User, "Du sphrst, wie ein Schauer ber deinen Krper luft. Deine Verwandlung wird nicht mehr lange andauern.", "Shortly, you feel a chill on your skin. Your transformation won't last a long time anymore." ) end counterBlack = counterBlack - 1; -- reduce of the effect counter Effect:addValue("counterBlack",counterBlack) local findCounter,counterBlack = Effect:findValue("counterBlack") if counterBlack == 0 then -- the effect counter is down to zero; we change the char back return false end end end Effect.nextCalled = 600 return true end function M.removeEffect(Effect,User) TransformBack(Effect,User) end function M.loadEffect(Effect,User) local findCounter,counterBlack = Effect:findValue("counterBlack") if findCounter then if counterBlack > 0 then -- check if the actual effect is still active local findNewSkincolor1, newSkincolor1 = Effect:findValue("newSkincolor1") local findNewSkincolor2, newSkincolor2 = Effect:findValue("newSkincolor2") local findNewSkincolor3, newSkincolor3 = Effect:findValue("newSkincolor3") local findNewHaircolor1, newHaircolor1 = Effect:findValue("newHaircolor1") local findNewHaircolor2, newHaircolor2 = Effect:findValue("newHaircolor2") local findNewHaircolor3, newHaircolor3 = Effect:findValue("newHaircolor3") local findNewBeard, newBeard = Effect:findValue("newBeard") local findNewHair, newHair = Effect:findValue("newHair") local findNewSex, newSex = Effect:findValue("newSex") if findNewSkincolor1 then User:setSkinColour(colour(newSkincolor1,newSkincolor2,newSkincolor3)) end if findNewHaircolor1 then User:setHairColour(colour(newHaircolor1,newHaircolor2,newHaircolor3)) end if findNewBeard then User:setBeard(newBeard) end if findNewHair then User:setHair(newHair) end if findNewSex then User:setAttrib("sex",newSex) end local findNewRace, newRace = Effect:findValue("newRace") local findNewHeight, newHeight = Effect:findValue("newHeight") User:setRace(newRace) User:setAttrib("body_height",newHeight) end end end function TransformBack(Effect,User) local findOldSkincolor1, oldSkincolor1 = Effect:findValue("oldSkincolor1") local findOldSkincolor2, oldSkincolor2 = Effect:findValue("oldSkincolor2") local findOldSkincolor3, oldSkincolor3 = Effect:findValue("oldSkincolor3") local findOldHaircolor1, oldHaircolor1 = Effect:findValue("oldHaircolor1") local findOldHaircolor2, oldHaircolor2 = Effect:findValue("oldHaircolor2") local findOldHaircolor3, oldHaircolor3 = Effect:findValue("oldHaircolor3") local findOldBeard, oldBeard = Effect:findValue("oldBeard") local findOldHair, oldHair = Effect:findValue("oldHair") local findOldSex, oldSex = Effect:findValue("oldSex") User:setSkinColour(colour(oldSkincolor1,oldSkincolor2,oldSkincolor3)) User:setHairColour(colour(oldHaircolor1,oldHaircolor2,oldHaircolor3)) User:setBeard(oldBeard) User:setHair(oldHair) User:setAttrib("sex",oldSex) local findOldRace, oldRace = Effect:findValue("oldRace") local findOldHeight, oldHeight = Effect:findValue("oldHeight") User:setRace(oldRace) User:setAttrib("body_height",oldHeight) end return M
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- LTE fr das Druidensystem -- by Falk -- Zeitverlauf und Rckwandlung bei Verwandlungen local common = require("base.common") local M = {} -- INSERT INTO longtimeeffects VALUES (329, 'alchemy_transformation', 'alchemy.lte.id_329_transformation'); function getAction(User,Effect,Runde) --Hier die eigentlichen Aktionen eintragen end function M.addEffect(Effect, User) -- Nur beim ersten Aufruf --User:inform("debug func addEffect") end function M.callEffect(Effect,User) --User:inform("debug func callEffect") local findCounter,counterBlack = Effect:findValue("counterBlack") if findCounter then if counterBlack >= 1 then -- info that the effect will be removed soon if counterBlack == 2 then common.InformNLS( User, "Du sphrst, wie ein Schauer ber deinen Krper luft. Deine Verwandlung wird nicht mehr lange andauern.", "Shortly, you feel a chill on your skin. Your transformation won't last a long time anymore." ) end counterBlack = counterBlack - 1; -- reduce of the effect counter Effect:addValue("counterBlack",counterBlack) local findCounter,counterBlack = Effect:findValue("counterBlack") if counterBlack == 0 then -- the effect counter is down to zero; we change the char back return false end end end Effect.nextCalled = 600 return true end local function TransformBack(Effect,User) local findOldSkincolor1, oldSkincolor1 = Effect:findValue("oldSkincolor1") local findOldSkincolor2, oldSkincolor2 = Effect:findValue("oldSkincolor2") local findOldSkincolor3, oldSkincolor3 = Effect:findValue("oldSkincolor3") local findOldHaircolor1, oldHaircolor1 = Effect:findValue("oldHaircolor1") local findOldHaircolor2, oldHaircolor2 = Effect:findValue("oldHaircolor2") local findOldHaircolor3, oldHaircolor3 = Effect:findValue("oldHaircolor3") local findOldBeard, oldBeard = Effect:findValue("oldBeard") local findOldHair, oldHair = Effect:findValue("oldHair") local findOldSex, oldSex = Effect:findValue("oldSex") local findOldRace, oldRace = Effect:findValue("oldRace") local findOldHeight, oldHeight = Effect:findValue("oldHeight") User:setRace(oldRace) User:setAttrib("body_height",oldHeight) User:setSkinColour(colour(oldSkincolor1,oldSkincolor2,oldSkincolor3)) User:setHairColour(colour(oldHaircolor1,oldHaircolor2,oldHaircolor3)) User:setBeard(oldBeard) User:setHair(oldHair) User:setAttrib("sex",oldSex) end function M.removeEffect(Effect,User) TransformBack(Effect,User) end function M.loadEffect(Effect,User) local findCounter,counterBlack = Effect:findValue("counterBlack") if findCounter then if counterBlack > 0 then -- check if the actual effect is still active local findNewSkincolor1, newSkincolor1 = Effect:findValue("newSkincolor1") local findNewSkincolor2, newSkincolor2 = Effect:findValue("newSkincolor2") local findNewSkincolor3, newSkincolor3 = Effect:findValue("newSkincolor3") local findNewHaircolor1, newHaircolor1 = Effect:findValue("newHaircolor1") local findNewHaircolor2, newHaircolor2 = Effect:findValue("newHaircolor2") local findNewHaircolor3, newHaircolor3 = Effect:findValue("newHaircolor3") local findNewBeard, newBeard = Effect:findValue("newBeard") local findNewHair, newHair = Effect:findValue("newHair") local findNewSex, newSex = Effect:findValue("newSex") if findNewSkincolor1 then User:setSkinColour(colour(newSkincolor1,newSkincolor2,newSkincolor3)) end if findNewHaircolor1 then User:setHairColour(colour(newHaircolor1,newHaircolor2,newHaircolor3)) end if findNewBeard then User:setBeard(newBeard) end if findNewHair then User:setHair(newHair) end if findNewSex then User:setAttrib("sex",newSex) end local findNewRace, newRace = Effect:findValue("newRace") local findNewHeight, newHeight = Effect:findValue("newHeight") User:setRace(newRace) User:setAttrib("body_height",newHeight) end end end return M
Remove baldness bug after using transformation potion
Remove baldness bug after using transformation potion
Lua
agpl-3.0
Baylamon/Illarion-Content,vilarion/Illarion-Content,Illarion-eV/Illarion-Content,KayMD/Illarion-Content
3aa48a6dc2dd6ec57ad03d9b63b12fc61327695d
SpatialConvolutionMM.lua
SpatialConvolutionMM.lua
require 'nn' nn.SpatialConvolutionMM.baseUpdateOutput = nn.SpatialConvolutionMM.updateOutput nn.SpatialConvolutionMM.baseUpdateGradInput = nn.SpatialConvolutionMM.updateGradInput nn.SpatialConvolutionMM.baseAccGradParameters = nn.SpatialConvolutionMM.accGradParameters function nn.SpatialConvolutionMM:updateOutput(input) if torch.type(input) ~= 'torch.ClTensor' then return self:baseUpdateOutput(input) end input.nn.SpatialConvolutionMM_updateOutput(self, input) return self.output end function nn.SpatialConvolutionMM:updateGradInput(input, gradOutput) if torch.type(input) ~= 'torch.ClTensor' then return self:baseUpdateGradInput(input, gradOutput) end input.nn.SpatialConvolutionMM_updateGradInput(self, input, gradOutput) return self.gradInput end function nn.SpatialConvolutionMM:accGradParameters(input, gradOutput, scale) if torch.type(input) ~= 'torch.ClTensor' then return self:baseAccGradParameters(input, gradOutput, scale) end input.nn.SpatialConvolutionMM_accGradParameters(self, input, gradOutput, scale) return self.gradInput end
require 'nn' nn.SpatialConvolutionMM.baseUpdateOutput = nn.SpatialConvolutionMM.updateOutput nn.SpatialConvolutionMM.baseUpdateGradInput = nn.SpatialConvolutionMM.updateGradInput nn.SpatialConvolutionMM.baseAccGradParameters = nn.SpatialConvolutionMM.accGradParameters function nn.SpatialConvolutionMM:updateOutput(input) if torch.type(input) ~= 'torch.ClTensor' then return self:baseUpdateOutput(input) end input.nn.SpatialConvolutionMM_updateOutput(self, input) return self.output end function nn.SpatialConvolutionMM:updateGradInput(input, gradOutput) if torch.type(input) ~= 'torch.ClTensor' then return self:baseUpdateGradInput(input, gradOutput) end return input.nn.SpatialConvolutionMM_updateGradInput(self, input, gradOutput) end function nn.SpatialConvolutionMM:accGradParameters(input, gradOutput, scale) if torch.type(input) ~= 'torch.ClTensor' then return self:baseAccGradParameters(input, gradOutput, scale) end return input.nn.SpatialConvolutionMM_accGradParameters(self, input, gradOutput, scale) end
fix return of accGradParameters in SpatialConvolutionMM
fix return of accGradParameters in SpatialConvolutionMM
Lua
bsd-2-clause
hughperkins/clnn,hughperkins/clnn,hughperkins/clnn,hughperkins/clnn
26be0656618a746e235b5fdef10a59abc4d02f01
src/plugins/finalcutpro/hacks/backupinterval.lua
src/plugins/finalcutpro/hacks/backupinterval.lua
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- B A C K U P I N T E R V A L P L U G I N -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- --- === plugins.finalcutpro.hacks.backupinterval === --- --- Change Final Cut Pro's Backup Interval. -------------------------------------------------------------------------------- -- -- EXTENSIONS: -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- CommandPost Extensions: -------------------------------------------------------------------------------- local dialog = require("cp.dialog") local fcp = require("cp.apple.finalcutpro") -------------------------------------------------------------------------------- -- -- CONSTANTS: -- -------------------------------------------------------------------------------- local PRIORITY = 30 local DEFAULT_VALUE = "15" local PREFERENCES_KEY = "FFPeriodicBackupInterval" -------------------------------------------------------------------------------- -- -- THE MODULE: -- -------------------------------------------------------------------------------- local mod = {} --- plugins.finalcutpro.hacks.backupinterval.get() -> number --- Function --- Gets the Periodic Backup Interval. --- --- Parameters: --- * None --- --- Returns: --- * The periodic backup interval as number function mod.get() local FFPeriodicBackupInterval = DEFAULT_VALUE local preferences = fcp:getPreferences() if preferences and preferences[PREFERENCES_KEY] then FFPeriodicBackupInterval = preferences[PREFERENCES_KEY] end return FFPeriodicBackupInterval end --- plugins.finalcutpro.hacks.backupinterval.set() -> number --- Function --- Sets the Periodic Backup Interval via a dialog box. --- --- Parameters: --- * None --- --- Returns: --- * The periodic backup interval as number function mod.set() -------------------------------------------------------------------------------- -- Get existing value: -------------------------------------------------------------------------------- local FFPeriodicBackupInterval = mod.get() -------------------------------------------------------------------------------- -- Ask user what to set the backup interval to: -------------------------------------------------------------------------------- local userSelectedBackupInterval = dialog.displaySmallNumberTextBoxMessage(i18n("setTextbox"), i18n("setError"), FFPeriodicBackupInterval) if not userSelectedBackupInterval then return "Cancel" end -------------------------------------------------------------------------------- -- Update plist: -------------------------------------------------------------------------------- local result = fcp:setPreference(PREFERENCES_KEY, tostring(userSelectedBackupInterval)) if result == nil then dialog.displayErrorMessage(i18n("backupIntervalFail")) return "Failed" end end -------------------------------------------------------------------------------- -- -- THE PLUGIN: -- -------------------------------------------------------------------------------- local plugin = { id = "finalcutpro.hacks.backupinterval", group = "finalcutpro", dependencies = { ["finalcutpro.menu.administrator.advancedfeatures"] = "menu", ["finalcutpro.commands"] = "fcpxCmds", } } -------------------------------------------------------------------------------- -- INITIALISE PLUGIN: -------------------------------------------------------------------------------- function plugin.init(deps) -------------------------------------------------------------------------------- -- Setup Menu Item: -------------------------------------------------------------------------------- deps.menu:addItem(PRIORITY, function() return { title = i18n("changeBackupInterval") .. " (" .. tostring(mod.get()) .. " " .. i18n("mins") .. ")", fn = mod.set } end) -------------------------------------------------------------------------------- -- Setup Command: -------------------------------------------------------------------------------- deps.fcpxCmds:add("cpChangeBackupInterval") :groupedBy("hacks") :activatedBy():ctrl():option():cmd("b") :whenActivated(mod.set) return mod end return plugin
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- B A C K U P I N T E R V A L P L U G I N -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- --- === plugins.finalcutpro.hacks.backupinterval === --- --- Change Final Cut Pro's Backup Interval. -------------------------------------------------------------------------------- -- -- EXTENSIONS: -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- CommandPost Extensions: -------------------------------------------------------------------------------- local dialog = require("cp.dialog") local fcp = require("cp.apple.finalcutpro") -------------------------------------------------------------------------------- -- -- CONSTANTS: -- -------------------------------------------------------------------------------- local PRIORITY = 30 local DEFAULT_VALUE = "15" local PREFERENCES_KEY = "FFPeriodicBackupInterval" -------------------------------------------------------------------------------- -- -- THE MODULE: -- -------------------------------------------------------------------------------- local mod = {} --- plugins.finalcutpro.hacks.backupinterval.get() -> number --- Function --- Gets the Periodic Backup Interval. --- --- Parameters: --- * None --- --- Returns: --- * The periodic backup interval as number function mod.get() local FFPeriodicBackupInterval = DEFAULT_VALUE local preferences = fcp:getPreferences() if preferences and preferences[PREFERENCES_KEY] then FFPeriodicBackupInterval = preferences[PREFERENCES_KEY] end return FFPeriodicBackupInterval end --- plugins.finalcutpro.hacks.backupinterval.set() -> number --- Function --- Sets the Periodic Backup Interval via a dialog box. --- --- Parameters: --- * None --- --- Returns: --- * The periodic backup interval as number function mod.set() -------------------------------------------------------------------------------- -- Get existing value: -------------------------------------------------------------------------------- local FFPeriodicBackupInterval = mod.get() -------------------------------------------------------------------------------- -- Ask user what to set the backup interval to: -------------------------------------------------------------------------------- local userSelectedBackupInterval = dialog.displaySmallNumberTextBoxMessage(i18n("changeBackupIntervalTextbox"), i18n("changeBackupIntervalError"), FFPeriodicBackupInterval) if not userSelectedBackupInterval then return "Cancel" end -------------------------------------------------------------------------------- -- Update plist: -------------------------------------------------------------------------------- local result = fcp:setPreference(PREFERENCES_KEY, tostring(userSelectedBackupInterval)) if result == nil then dialog.displayErrorMessage(i18n("backupIntervalFail")) return "Failed" end end -------------------------------------------------------------------------------- -- -- THE PLUGIN: -- -------------------------------------------------------------------------------- local plugin = { id = "finalcutpro.hacks.backupinterval", group = "finalcutpro", dependencies = { ["finalcutpro.menu.administrator.advancedfeatures"] = "menu", ["finalcutpro.commands"] = "fcpxCmds", } } -------------------------------------------------------------------------------- -- INITIALISE PLUGIN: -------------------------------------------------------------------------------- function plugin.init(deps) -------------------------------------------------------------------------------- -- Setup Menu Item: -------------------------------------------------------------------------------- deps.menu:addItem(PRIORITY, function() return { title = i18n("changeBackupInterval") .. " (" .. tostring(mod.get()) .. " " .. i18n("mins") .. ")", fn = mod.set } end) -------------------------------------------------------------------------------- -- Setup Command: -------------------------------------------------------------------------------- deps.fcpxCmds:add("cpChangeBackupInterval") :groupedBy("hacks") :activatedBy():ctrl():option():cmd("b") :whenActivated(mod.set) return mod end return plugin
#1176
#1176 - Fixed bug in Backup Interval - Closes #1176
Lua
mit
fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost,CommandPost/CommandPost,fcpxhacks/fcpxhacks