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
91f51cf49222c3abd03069183b991aa207e016a0
fusion/core/lexer.lua
fusion/core/lexer.lua
local pretty = require("pl.pretty"); local re = require("re"); local defs = {} defs['true'] = function() return true end defs['false'] = function() return false end function defs:transform_binary_expression() table.insert(self, 1, 'expression') self.type = 'binary' return self end pattern = re.compile([[ statement_list <- {| (statement ws)* |} statement_block <- '{' ws statement_list ws '}' statement <- ( assignment / function_call ) ws ';' ws / ( statement_block ) function_call <- {| '' -> 'function_call' ( variable ({:has_self: ':' -> true :} value ws {:index_class: ws '<' ws {value} ws '>' :}? )? ws function_args ) |} function_args <- '(' expression_list? ')' assignment <- {| '' -> 'assignment' {| variable_list ws '=' ws expression_list |} |} expression_list <- {:expression_list: {| expression (ws ',' ws expression)* |} :} expression <- ex_or ex_or <- {| (ex_and ws {:operator: '||' :} ws ex_and) |} -> transform_binary_expression / ex_and ex_and <- {| ex_equality ws {:operator: '&&' :} ws ex_equality |} -> transform_binary_expression / ex_equality ex_equality <- {| ex_binary_or ws {:operator: ([<>!=] '=' / [<>]) :} ws ex_binary_or |} -> transform_binary_expression / ex_binary_or ex_binary_or <- {| ex_binary_xor ws {:operator: '|' :} ws ex_binary_xor |} -> transform_binary_expression / ex_binary_xor ex_binary_xor <- {| ex_binary_and ws {:operator: '~' :} ws ex_binary_and |} -> transform_binary_expression / ex_binary_and ex_binary_and <- {| ex_binary_shift ws {:operator: '&' :} ws ex_binary_shift |} -> transform_binary_expression / ex_binary_shift ex_binary_shift <- {| ex_concat ws {:operator: ('<<' / '>>') :} ws ex_concat |} -> transform_binary_expression / ex_concat ex_concat <- {| ex_term ws {:operator: '..' :} ws ex_term |} -> transform_binary_expression / ex_term ex_term <- {| ex_factor ws {:operator: [+-] :} ws expression |} -> transform_binary_expression / ex_factor ex_factor <- {| ex_unary ws {:operator: ([*/%] / '//') :} ws ex_unary |} -> transform_binary_expression / ex_unary ex_unary <- {| '' -> 'expression' {:type: '' -> 'unary' :} {:operator: [-!#~] :} ws ex_power |} / ex_power ex_power <- {| value ws {:operator: '^' :} ws value |} -> transform_binary_expression / value value <- literal / variable / '(' expression ')' variable_list <- {:variable_list: {| variable (ws ',' ws variable)* |} :} variable <- {| '' -> 'variable' name ws ('.' ws name / ws '[' ws value ws ']')* |} name <- {[A-Za-z_][A-Za-z0-9_]*} literal <- {| '' -> 'vararg' { '...' } |} / number / string / {| '' -> 'boolean' { 'true' / 'false' } |} / {| {'nil' -> 'nil'} |} number <- {| '' -> 'number' ( base16num / base10num ) |} base10num <- {:type: '' -> 'base10' :} { ((integer '.' integer) / (integer '.') / ('.' integer) / integer) int_exponent? } integer <- [0-9]+ int_exponent <- [eE] [+-]? integer base16num <- {:type: '' -> 'base16' :} { '0' [Xx] [0-9A-Fa-f]+ hex_exponent? } hex_exponent <- [pP] [+-]? integer string <- {| dqstring / sqstring / blstring |} dqstring <- '' -> 'dqstring' '"' { (('\\' .) / ([^\r\n"]))* } '"' sqstring <- '' -> 'sqstring' "'" { [^\r\n']* } "'" blstring <- '' -> 'blstring' '[' {:eq: '='* :} '[' blclose blclose <- ']' =eq ']' / . blclose ws <- %s* ]], defs); pretty.dump(pattern:match([[ a = b.c; ]]));
local pretty = require("pl.pretty"); local re = require("re"); local defs = {} defs['true'] = function() return true end defs['false'] = function() return false end function defs:transform_binary_expression() table.insert(self, 1, 'expression') self.type = 'binary' return self end local pattern = re.compile([[ statement_list <- {| (statement ws)* |} statement_block <- '{' ws statement_list ws '}' statement <- ( function_call / assignment ) ws ';' ws / ( statement_block ) function_call <- {| '' -> 'function_call' ( variable ({:has_self: ':' -> true :} variable ws {:index_class: ws '<' ws {value} ws '>' :}? )? ws function_args ) |} function_args <- '(' expression_list? ')' assignment <- {| '' -> 'assignment' {| variable_list ws '=' ws expression_list |} |} expression_list <- {:expression_list: {| expression (ws ',' ws expression)* |} :} expression <- ex_or ex_or <- {| (ex_and ws {:operator: '||' :} ws ex_and) |} -> transform_binary_expression / ex_and ex_and <- {| ex_equality ws {:operator: '&&' :} ws ex_equality |} -> transform_binary_expression / ex_equality ex_equality <- {| ex_binary_or ws {:operator: ([<>!=] '=' / [<>]) :} ws ex_binary_or |} -> transform_binary_expression / ex_binary_or ex_binary_or <- {| ex_binary_xor ws {:operator: '|' :} ws ex_binary_xor |} -> transform_binary_expression / ex_binary_xor ex_binary_xor <- {| ex_binary_and ws {:operator: '~' :} ws ex_binary_and |} -> transform_binary_expression / ex_binary_and ex_binary_and <- {| ex_binary_shift ws {:operator: '&' :} ws ex_binary_shift |} -> transform_binary_expression / ex_binary_shift ex_binary_shift <- {| ex_concat ws {:operator: ('<<' / '>>') :} ws ex_concat |} -> transform_binary_expression / ex_concat ex_concat <- {| ex_term ws {:operator: '..' :} ws ex_term |} -> transform_binary_expression / ex_term ex_term <- {| ex_factor ws {:operator: [+-] :} ws expression |} -> transform_binary_expression / ex_factor ex_factor <- {| ex_unary ws {:operator: ([*/%] / '//') :} ws ex_unary |} -> transform_binary_expression / ex_unary ex_unary <- {| '' -> 'expression' {:type: '' -> 'unary' :} {:operator: [-!#~] :} ws ex_power |} / ex_power ex_power <- {| value ws {:operator: '^' :} ws value |} -> transform_binary_expression / value value <- function_call / literal / variable / '(' expression ')' variable_list <- {:variable_list: {| variable (ws ',' ws variable)* |} :} variable <- {| '' -> 'variable' name ws ('.' ws name / ws '[' ws value ws ']')* |} name <- {[A-Za-z_][A-Za-z0-9_]*} literal <- {| '' -> 'vararg' { '...' } |} / number / string / {| '' -> 'boolean' { 'true' / 'false' } |} / {| {'nil' -> 'nil'} |} number <- {| '' -> 'number' ( base16num / base10num ) |} base10num <- {:type: '' -> 'base10' :} { ((integer '.' integer) / (integer '.') / ('.' integer) / integer) int_exponent? } integer <- [0-9]+ int_exponent <- [eE] [+-]? integer base16num <- {:type: '' -> 'base16' :} { '0' [Xx] [0-9A-Fa-f]+ hex_exponent? } hex_exponent <- [pP] [+-]? integer string <- {| dqstring / sqstring / blstring |} dqstring <- '' -> 'dqstring' '"' { (('\\' .) / ([^\r\n"]))* } '"' sqstring <- '' -> 'sqstring' "'" { [^\r\n']* } "'" blstring <- '' -> 'blstring' '[' {:eq: '='* :} '[' blclose blclose <- ']' =eq ']' / . blclose ws <- %s* ]], defs); return pattern
lexer.lua: fix functions (again)
lexer.lua: fix functions (again)
Lua
mit
RyanSquared/FusionScript
d30c0868b2f78345994a524827ca7252f6137847
pud/level/MapType.lua
pud/level/MapType.lua
-- table of valid map types local mt = { __index = function(t, k) k = k or 'nil' error('invalid map type ['..k..']') end, __newindex = function(t, k, v) error('attempt to add maptype '..k..' at runtime') end, } local MapType = { empty = ' ', wall = '#', floor = '.', doorC = '+', doorO = '-', stairU = '<', stairD = '>', } -- add glyph as index to itself -- for ease of use in conditions for k,v in pairs(MapType) do MapType[v] = v end return setmetatable(MapType, mt)
-- table of valid map types local mt = { __index = function(t, k) k = k or 'nil' error('invalid map type ['..k..']') end, __newindex = function(t, k, v) error('attempt to add maptype '..k..' at runtime') end, } local MapType = { empty = ' ', wall = '#', floor = '.', doorC = '+', doorO = '-', stairU = '<', stairD = '>', } -- add glyph as index to itself -- for ease of use in conditions local t = {} for k,v in pairs(MapType) do t[v] = v end for k,v in pairs(t) do MapType[k] = v end return setmetatable(MapType, mt)
fix MapType glyph self-indexing
fix MapType glyph self-indexing
Lua
mit
scottcs/wyx
c9e5d89cfab4a380e289db4a7a9aa45bfe46cda3
src/loader.lua
src/loader.lua
local Gamestate = require 'vendor/gamestate' local Level = require 'level' local window = require 'window' local fonts = require 'fonts' local state = Gamestate.new() local home = require 'menu' local nextState = 'home' local nextPlayer = 'nil' function state:init() state.finished = false state.current = 1 state.assets = {} fonts.set( 'courier' ) table.insert(state.assets, function() Gamestate.load('valley', Level.new('valley')) end) table.insert(state.assets, function() Gamestate.load('gay-island', Level.new('gay-island')) end) table.insert(state.assets, function() Gamestate.load('gay-island2', Level.new('gay-island2')) end) table.insert(state.assets, function() Gamestate.load('abedtown', Level.new('newtown')) end) table.insert(state.assets, function() Gamestate.load('lab', Level.new('lab')) end) table.insert(state.assets, function() Gamestate.load('house', Level.new('house')) end) table.insert(state.assets, function() Gamestate.load('studyroom', Level.new('studyroom')) end) table.insert(state.assets, function() Gamestate.load('hallway', Level.new('hallway')) end) table.insert(state.assets, function() Gamestate.load('forest', Level.new('forest')) end) table.insert(state.assets, function() Gamestate.load('forest2', Level.new('forest2')) end) table.insert(state.assets, function() Gamestate.load('village-forest', Level.new('village-forest')) end) table.insert(state.assets, function() Gamestate.load('town', Level.new('town')) end) table.insert(state.assets, function() Gamestate.load('tavern', Level.new('tavern')) end) table.insert(state.assets, function() Gamestate.load('blacksmith', Level.new('blacksmith')) end) table.insert(state.assets, function() Gamestate.load('greendale-exterior', Level.new('greendale-exterior')) end) table.insert(state.assets, function() Gamestate.load('deans-office-1', Level.new('deans-office-1')) end) table.insert(state.assets, function() Gamestate.load('deans-office-2', Level.new('deans-office-2')) end) table.insert(state.assets, function() Gamestate.load('deans-closet', Level.new('deans-closet')) end) table.insert(state.assets, function() Gamestate.load('baseball', Level.new('baseball')) end) table.insert(state.assets, function() Gamestate.load('dorm-lobby', Level.new('dorm-lobby')) end) table.insert(state.assets, function() Gamestate.load('borchert-hallway', Level.new('borchert-hallway')) end) table.insert(state.assets, function() Gamestate.load('admin-hallway', Level.new('admin-hallway')) end) table.insert(state.assets, function() Gamestate.load('class-hallway-1', Level.new('class-hallway-1')) end) table.insert(state.assets, function() Gamestate.load('class-hallway-2', Level.new('class-hallway-2')) end) table.insert(state.assets, function() Gamestate.load('rave-hallway', Level.new('rave-hallway')) end) table.insert(state.assets, function() Gamestate.load('class-basement', Level.new('class-basement')) end) table.insert(state.assets, function() Gamestate.load('gazette-office-1', Level.new('gazette-office-1')) end) table.insert(state.assets, function() Gamestate.load('gazette-office-2', Level.new('gazette-office-2')) end) table.insert(state.assets, function() Gamestate.load('overworld', require 'overworld') end) table.insert(state.assets, function() Gamestate.load('credits', require 'credits') end) table.insert(state.assets, function() Gamestate.load('select', require 'select') end) table.insert(state.assets, function() Gamestate.load('home', require 'menu') end) table.insert(state.assets, function() Gamestate.load('pause', require 'pause') end) table.insert(state.assets, function() Gamestate.load('cheatscreen', require 'cheatscreen') end) table.insert(state.assets, function() Gamestate.load('instructions', require 'instructions') end) table.insert(state.assets, function() Gamestate.load('options', require 'options') end) table.insert(state.assets, function() Gamestate.load('blackjackgame', require 'blackjackgame') end) state.step = 240 / # self.assets state.messages = { "terminal://", "operations://load program:(true)", "program: journey_to_the_center_of_hawkthorne", "loading simulation...", "5465415151", "5413572495", "7342195434", "8432159965", "3141592653", "5897932384", "1678942348", "1123581321", "9437832123", "1359756423" } end function state:update(dt) if self.finished then return end local asset = state.assets[self.current] if asset ~= nil then asset() self.current = self.current + 1 else self.finished = true self:switch() end end function state:switch() Gamestate.switch(nextState,nextPlayer) end function state:target(state,player) nextState = state nextPlayer = player end function state:draw() local progress = (self.current-1) / #self.assets local lineCount = math.floor(#self.messages * progress) -- Set the color to dark green for the loading font love.graphics.setColor(88, 246, 0) for i = 1,lineCount do -- Draw the first lines larger if i <= 4 then love.graphics.print(self.messages[i], 50, 15*(i+1), 0, 0.5, 0.5) else -- Draw the rest of the lines smaller and multiple times for j = 1,math.min(lineCount-i+1, 5) do love.graphics.print(self.messages[i], 60*j, 15*(i+1), 0, 0.4, 0.4) end end end love.graphics.setColor(255, 255, 255) end return state
local Gamestate = require 'vendor/gamestate' local Level = require 'level' local window = require 'window' local fonts = require 'fonts' local state = Gamestate.new() local home = require 'menu' local nextState = 'home' local nextPlayer = nil function state:init() state.finished = false state.current = 1 state.assets = {} table.insert(state.assets, function() Gamestate.load('valley', Level.new('valley')) end) table.insert(state.assets, function() Gamestate.load('gay-island', Level.new('gay-island')) end) table.insert(state.assets, function() Gamestate.load('gay-island2', Level.new('gay-island2')) end) table.insert(state.assets, function() Gamestate.load('abedtown', Level.new('newtown')) end) table.insert(state.assets, function() Gamestate.load('lab', Level.new('lab')) end) table.insert(state.assets, function() Gamestate.load('house', Level.new('house')) end) table.insert(state.assets, function() Gamestate.load('studyroom', Level.new('studyroom')) end) table.insert(state.assets, function() Gamestate.load('hallway', Level.new('hallway')) end) table.insert(state.assets, function() Gamestate.load('forest', Level.new('forest')) end) table.insert(state.assets, function() Gamestate.load('forest2', Level.new('forest2')) end) table.insert(state.assets, function() Gamestate.load('village-forest', Level.new('village-forest')) end) table.insert(state.assets, function() Gamestate.load('town', Level.new('town')) end) table.insert(state.assets, function() Gamestate.load('tavern', Level.new('tavern')) end) table.insert(state.assets, function() Gamestate.load('blacksmith', Level.new('blacksmith')) end) table.insert(state.assets, function() Gamestate.load('greendale-exterior', Level.new('greendale-exterior')) end) table.insert(state.assets, function() Gamestate.load('deans-office-1', Level.new('deans-office-1')) end) table.insert(state.assets, function() Gamestate.load('deans-office-2', Level.new('deans-office-2')) end) table.insert(state.assets, function() Gamestate.load('deans-closet', Level.new('deans-closet')) end) table.insert(state.assets, function() Gamestate.load('baseball', Level.new('baseball')) end) table.insert(state.assets, function() Gamestate.load('dorm-lobby', Level.new('dorm-lobby')) end) table.insert(state.assets, function() Gamestate.load('borchert-hallway', Level.new('borchert-hallway')) end) table.insert(state.assets, function() Gamestate.load('admin-hallway', Level.new('admin-hallway')) end) table.insert(state.assets, function() Gamestate.load('class-hallway-1', Level.new('class-hallway-1')) end) table.insert(state.assets, function() Gamestate.load('class-hallway-2', Level.new('class-hallway-2')) end) table.insert(state.assets, function() Gamestate.load('rave-hallway', Level.new('rave-hallway')) end) table.insert(state.assets, function() Gamestate.load('class-basement', Level.new('class-basement')) end) table.insert(state.assets, function() Gamestate.load('gazette-office-1', Level.new('gazette-office-1')) end) table.insert(state.assets, function() Gamestate.load('gazette-office-2', Level.new('gazette-office-2')) end) table.insert(state.assets, function() Gamestate.load('overworld', require 'overworld') end) table.insert(state.assets, function() Gamestate.load('credits', require 'credits') end) table.insert(state.assets, function() Gamestate.load('select', require 'select') end) table.insert(state.assets, function() Gamestate.load('home', require 'menu') end) table.insert(state.assets, function() Gamestate.load('pause', require 'pause') end) table.insert(state.assets, function() Gamestate.load('cheatscreen', require 'cheatscreen') end) table.insert(state.assets, function() Gamestate.load('instructions', require 'instructions') end) table.insert(state.assets, function() Gamestate.load('options', require 'options') end) table.insert(state.assets, function() Gamestate.load('blackjackgame', require 'blackjackgame') end) state.step = 240 / # self.assets end function state:update(dt) if self.finished then return end local asset = state.assets[self.current] if asset ~= nil then asset() self.current = self.current + 1 else self.finished = true self:switch() end end function state:switch() Gamestate.switch(nextState,nextPlayer) end function state:target(state,player) nextState = state nextPlayer = player end function state:draw() love.graphics.rectangle('line', window.width / 2 - 120, window.height / 2 - 10, 240, 20) love.graphics.rectangle('fill', window.width / 2 - 120, window.height / 2 - 10, (self.current - 1) * self.step, 20) end return state
Revert of loading screen for Windows 7 64-bit Fix #252
Revert of loading screen for Windows 7 64-bit Fix #252
Lua
mit
hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua
7e42557707463451979eb8711a470742a8535205
OS/DiskOS/Libraries/GUI/base.lua
OS/DiskOS/Libraries/GUI/base.lua
--Wrap a function, used to add functions alias names. local function wrap(f) return function(self,...) local args = {pcall(self[f],self,...)} if args[1] then local function a(ok,...) return ... end return a(unpack(args)) else return error(tostring(args[2])) end end end --Base object class local base = class("DiskOS.GUI.base") function base:initialize(gui,x,y,w,h) self.gui = gui or error("GUI State has to be passed",2) self.x, self.y = 0, 0 self.w, self.h = 0, 0 --self.touchid -> The object press touch id. --self.mousepress -> True when the object is pressed using the mouse. self:setSize(w,h) self:setPosition(x,y) self:setFGColor(self.gui:getFGColor()) self:setBGColor(self.gui:getBGColor()) self:setTColor(self.gui:getTColor()) end --Set object position. function base:setX(x) if x then if x < 0 then x = self.gui:getWidth()-self.w+x end end self.x = x or self.x return self end function base:setY(y) if y then if y < 0 then y = self.gui:getHeight()-self.h+y end end self.y = y or self.y return self end function base:setPos(x,y) self:setX(x) self:setY(y) return self end base.setPosition = wrap("setPos") --Get object position function base:getX() return self.x end function base:getY() return self.y end function base:getPos() return self:getX(), self:getY() end base.getPosition = wrap("getPos") --Set object size function base:setWidth(w) self.w = w or self.w; return self end function base:setHeight(h) self.h = h or self.h; return self end function base:setSize(w,h) self:setWidth(w) self:setHeight(h) return self end --Get object size function base:getWidth() return self.w end function base:getHeight() return self.h end function base:getSize() return self:getWidth(), self:getHeight() end function base:setRect(x,y,w,h) self:setPosition(x,y) self:setSize(x,y) return self end function base:getRect() local x,y = self:getPosition() local w,h = self:getSize() return x,y,w,h end --Set object colors function base:setFGColor(fgcol) self.fgcol = fgcol or self.fgcol; return self end function base:setBGColor(bgcol) self.bgcol = bgcol or self.bgcol; return self end function base:setTColor(tcol) self.tcol = tcol or self.tcol; return self end function base:setColors(fgcol,bgcol,tcol) self:setFGColor(fgcol) self:setBGColor(bgcol) self:setTColor(tcol) return self end --Get object colors function base:getFGColor() return self.fgcol end function base:getBGColor() return self.bgcol end function base:getTColor() return self.tcol end function base:getColors() return self:getFGColor(), self:getBGColor(), self:getTColor() end --Has to be overwritten function base:_draw(dt) end function base:_update(dt) end function base:pressed(x,y) return false end --Called when the mouse/touch is pressed. function base:released(x,y) end --Called when the mouse/touch is released after returning try from base:pressed. --Internal functions to handle multitouch function base:_mousepressed(button,x,y) if self.touchid or self.mousepress then return end self.mousepress = true self.mousepress = self:pressed(x,y) return self.mousepress end function base:_mousereleased(button,x,y) if self.touchid or (not self.mousepress) then return end self:released(x,y) self.mousepressed = false return true end function base:_touchpressed(id,x,y) if self.touchid or self.mousepress then return end self.touchid = id if not self:pressed(x,y) then self.touchid = nil end return self.touchid end function base:_touchreleased(id,x,y) if (not self.touchid) or self.mousepress then return end self:released(x,y) self.touchid = nil return true end return base
--Wrap a function, used to add functions alias names. local function wrap(f) return function(self,...) local args = {pcall(self[f],self,...)} if args[1] then local function a(ok,...) return ... end return a(unpack(args)) else return error(tostring(args[2])) end end end --Base object class local base = class("DiskOS.GUI.base") function base:initialize(gui,x,y,w,h) self.gui = gui or error("GUI State has to be passed",2) self.x, self.y = 0, 0 self.w, self.h = 0, 0 --self.touchid -> The object press touch id. --self.mousepress -> True when the object is pressed using the mouse. self:setSize(w,h) self:setPosition(x,y) self:setFGColor(self.gui:getFGColor()) self:setBGColor(self.gui:getBGColor()) self:setTColor(self.gui:getTColor()) end --Set object position. function base:setX(x) if x then if x < 0 then x = self.gui:getWidth()-self.w+x end end self.x = x or self.x return self end function base:setY(y) if y then if y < 0 then y = self.gui:getHeight()-self.h+y end end self.y = y or self.y return self end function base:setPos(x,y) self:setX(x) self:setY(y) return self end base.setPosition = wrap("setPos") --Get object position function base:getX() return self.x end function base:getY() return self.y end function base:getPos() return self:getX(), self:getY() end base.getPosition = wrap("getPos") --Set object size function base:setWidth(w) self.w = w or self.w; return self end function base:setHeight(h) self.h = h or self.h; return self end function base:setSize(w,h) self:setWidth(w) self:setHeight(h) return self end --Get object size function base:getWidth() return self.w end function base:getHeight() return self.h end function base:getSize() return self:getWidth(), self:getHeight() end function base:setRect(x,y,w,h) self:setPosition(x,y) self:setSize(x,y) return self end function base:getRect() local x,y = self:getPosition() local w,h = self:getSize() return x,y,w,h end --Set object colors function base:setFGColor(fgcol) self.fgcol = fgcol or self.fgcol; return self end function base:setBGColor(bgcol) self.bgcol = bgcol or self.bgcol; return self end function base:setTColor(tcol) self.tcol = tcol or self.tcol; return self end function base:setColors(fgcol,bgcol,tcol) self:setFGColor(fgcol) self:setBGColor(bgcol) self:setTColor(tcol) return self end --Get object colors function base:getFGColor() return self.fgcol end function base:getBGColor() return self.bgcol end function base:getTColor() return self.tcol end function base:getColors() return self:getFGColor(), self:getBGColor(), self:getTColor() end --Has to be overwritten function base:_draw(dt) end function base:_update(dt) end function base:pressed(x,y) return false end --Called when the mouse/touch is pressed. function base:released(x,y) end --Called when the mouse/touch is released after returning try from base:pressed. --Internal functions to handle multitouch function base:_mousepressed(button,x,y) if self.touchid or self.mousepress then return end self.mousepress = true self.mousepress = self:pressed(x,y) return self.mousepress end function base:_mousereleased(button,x,y) if self.touchid or (not self.mousepress) then return end self:released(x,y) self.mousepressed = false return true end function base:_touchpressed(id,x,y) if self.touchid or self.mousepress then return end self.touchid = id if not self:pressed(x,y) then self.touchid = nil end return self.touchid end function base:_touchreleased(id,x,y) if (not self.touchid) or self.mousepress then return end if self.touchid ~= id then return end self:released(x,y) self.touchid = nil return true end return base
Bugfix
Bugfix
Lua
mit
RamiLego4Game/LIKO-12
0dfa2b2f989ce0c71456c6122ead4130bccb9840
AceLocale-3.0/AceLocale-3.0.lua
AceLocale-3.0/AceLocale-3.0.lua
local MAJOR,MINOR = "AceLocale-3.0", "$Revision: 1" local lib = LibStub:RegisterLibrary(MAJOR, MINOR) if not lib then return end lib.apps = lib.apps or {} local meta = { __newindex = function(self, key, value) -- assigning values: replace 'true' with key string if value==true then rawset(self, key, key) else rawset(self, key, value) end end, __index = function(self, key) -- requesting unknown values: fire off a nonbreaking error and return key geterrorhandler()("AceLocale-3.0: Missing translation for '"..tostring(key).."'") return key end } -- AceLocale:RegisterLocale(application, locale) -- -- application (string) - unique name of addon -- locale (string) - name of locale to register -- -- Returns a table where localizations can be filled out, or nil if the locale is not needed -- The first call to :RegisterLocale always returns a table - the "default locale" function lib:RegisterLocale(application, locale) if locale=="enGB" then locale="enUS" -- treat enGB like enUS end local app = lib.apps[application] if not app then -- Always accept the first locale to be registered; it's the default one app = setmetatable({}, meta) lib.apps[application] = app return app end local GAME_LOCALE = GAME_LOCALE or GetLocale() if GAME_LOCALE=="enGB" then GAME_LOCALE="enUS" end if locale==GAME_LOCALE then return app -- okay, we're trying to register translations for the current game locale, go ahead end return -- nop, we don't need these translations end -- AceLocale:RegisterLocale(application, locale) -- -- application (string) - unique name of addon -- -- returns appropriate localizations for the current locale, errors if localizations are missing function lib:GetCurrentLocale(application) local app = lib.apps[application] if not app then error("GetCurrentLocale(): No locale registered for '"..tostring(application).."'", 2) end return app end
local MAJOR,MINOR = "AceLocale-3.0", "$Revision: 1$" local lib = LibStub:NewLibrary(MAJOR, MINOR) if not lib then return end lib.apps = lib.apps or {} -- This __newindex is used for most locale tables local function __newindex(self,key,value) -- assigning values: replace 'true' with key string if value==true then rawset(self, key, key) else rawset(self, key, value) end end, end -- __newindex_default is used for when the default locale is being registered. -- Reason 1: Allows loading locales in any order -- Reason 2: If 2 modules have the same string, but only the first one to be -- loaded has a translation for the current locale, the translation -- doesn't get overwritten. -- local function __newindex_default(self,key,value) if rawget(self,key) then return -- don't allow default locale to overwrite current locale stuff end __newindex(self,key,value) end -- The metatable used by all locales (yes, same one!) local meta = { __newindex = __newindex, __index = function(self, key) -- requesting unknown values: fire off a nonbreaking error and return key geterrorhandler()("AceLocale-3.0: Missing translation for '"..tostring(key).."'") return key end } -- AceLocale:NewLocale(application, locale, isDefault) -- -- application (string) - unique name of addon -- locale (string) - name of locale to register -- isDefault (string) - if this is the default locale being registered -- -- Returns a table where localizations can be filled out, or nil if the locale is not needed function lib:RegisterLocale(application, locale, isDefault) local app = lib.apps[application] if not app then app = setmetatable({}, meta) lib.apps[application] = app end if isDefault then getmetatable(app).__newindex = __newindex_default return app end local GAME_LOCALE = GAME_LOCALE or GetLocale() if GAME_LOCALE=="enGB" then GAME_LOCALE="enUS" end if locale~=GAME_LOCALE then return -- nop, we don't need these translations end getmetatable(app).__newindex = __newindex return app -- okay, we're trying to register translations for the current game locale, go ahead end -- AceLocale:RegisterLocale(application, locale) -- -- application (string) - unique name of addon -- -- returns appropriate localizations for the current locale, errors if localizations are missing function lib:GetCurrentLocale(application) local app = lib.apps[application] if not app then error("GetCurrentLocale(): No locale registered for '"..tostring(application).."'", 2) end return app end
Ace3 - ACE-24 (AceLocale) - Bugfixes - Rename :RegisterLocale to :NewLocale - Add a third "isDefault" argument -- allows default locales to be registered at any point, not just first (good for modules!) 100 lines in total now.
Ace3 - ACE-24 (AceLocale) - Bugfixes - Rename :RegisterLocale to :NewLocale - Add a third "isDefault" argument -- allows default locales to be registered at any point, not just first (good for modules!) 100 lines in total now. git-svn-id: 00c2b8bc9b083c53e126de03a83516ee6a3b87d9@129 5debad98-a965-4143-8383-f471b3509dcf
Lua
bsd-3-clause
sarahgerweck/Ace3
c26ab315b8fb838a2fa8337c4d3de0a274647709
rootfs/etc/nginx/lua/balancer/sticky.lua
rootfs/etc/nginx/lua/balancer/sticky.lua
local balancer_resty = require("balancer.resty") local ck = require("resty.cookie") local ngx_balancer = require("ngx.balancer") local split = require("util.split") local string_format = string.format local ngx_log = ngx.log local INFO = ngx.INFO local _M = balancer_resty:new() local DEFAULT_COOKIE_NAME = "route" function _M.cookie_name(self) return self.cookie_session_affinity.name or DEFAULT_COOKIE_NAME end function _M.new(self) local o = { alternative_backends = nil, cookie_session_affinity = nil, traffic_shaping_policy = nil } setmetatable(o, self) self.__index = self return o end function _M.get_cookie(self) local cookie, err = ck:new() if not cookie then ngx.log(ngx.ERR, err) end return cookie:get(self:cookie_name()) end function _M.set_cookie(self, value) local cookie, err = ck:new() if not cookie then ngx.log(ngx.ERR, err) end local cookie_path = self.cookie_session_affinity.path if not cookie_path then cookie_path = ngx.var.location_path end local cookie_data = { key = self:cookie_name(), value = value, path = cookie_path, httponly = true, secure = ngx.var.https == "on", } if self.cookie_session_affinity.expires and self.cookie_session_affinity.expires ~= "" then cookie_data.expires = ngx.cookie_time(ngx.time() + tonumber(self.cookie_session_affinity.expires)) end if self.cookie_session_affinity.maxage and self.cookie_session_affinity.maxage ~= "" then cookie_data.max_age = tonumber(self.cookie_session_affinity.maxage) end local ok ok, err = cookie:set(cookie_data) if not ok then ngx.log(ngx.ERR, err) end end function _M.get_last_failure() return ngx_balancer.get_last_failure() end local function get_failed_upstreams() local indexed_upstream_addrs = {} local upstream_addrs = split.split_upstream_var(ngx.var.upstream_addr) or {} for _, addr in ipairs(upstream_addrs) do indexed_upstream_addrs[addr] = true end return indexed_upstream_addrs end local function should_set_cookie(self) if self.cookie_session_affinity.locations and ngx.var.host then local locs = self.cookie_session_affinity.locations[ngx.var.host] if locs == nil then -- Based off of wildcard hostname in ../certificate.lua local wildcard_host, _, err = ngx.re.sub(ngx.var.host, "^[^\\.]+\\.", "*.", "jo") if err then ngx.log(ngx.ERR, "error: ", err); elseif wildcard_host then locs = self.cookie_session_affinity.locations[wildcard_host] end end if locs ~= nil then for _, path in pairs(locs) do if ngx.var.location_path == path then return true end end end end return false end function _M.balance(self) local upstream_from_cookie local key = self:get_cookie() if key then upstream_from_cookie = self.instance:find(key) end local last_failure = self.get_last_failure() local should_pick_new_upstream = last_failure ~= nil and self.cookie_session_affinity.change_on_failure or upstream_from_cookie == nil if not should_pick_new_upstream then return upstream_from_cookie end local new_upstream new_upstream, key = self:pick_new_upstream(get_failed_upstreams()) if not new_upstream then ngx.log(ngx.WARN, string.format("failed to get new upstream; using upstream %s", new_upstream)) elseif should_set_cookie(self) then self:set_cookie(key) end return new_upstream end function _M.sync(self, backend) -- reload balancer nodes balancer_resty.sync(self, backend) self.traffic_shaping_policy = backend.trafficShapingPolicy self.alternative_backends = backend.alternativeBackends self.cookie_session_affinity = backend.sessionAffinityConfig.cookieSessionAffinity end return _M
local balancer_resty = require("balancer.resty") local ck = require("resty.cookie") local ngx_balancer = require("ngx.balancer") local split = require("util.split") local _M = balancer_resty:new() local DEFAULT_COOKIE_NAME = "route" function _M.cookie_name(self) return self.cookie_session_affinity.name or DEFAULT_COOKIE_NAME end function _M.new(self) local o = { alternative_backends = nil, cookie_session_affinity = nil, traffic_shaping_policy = nil } setmetatable(o, self) self.__index = self return o end function _M.get_cookie(self) local cookie, err = ck:new() if not cookie then ngx.log(ngx.ERR, err) end return cookie:get(self:cookie_name()) end function _M.set_cookie(self, value) local cookie, err = ck:new() if not cookie then ngx.log(ngx.ERR, err) end local cookie_path = self.cookie_session_affinity.path if not cookie_path then cookie_path = ngx.var.location_path end local cookie_data = { key = self:cookie_name(), value = value, path = cookie_path, httponly = true, secure = ngx.var.https == "on", } if self.cookie_session_affinity.expires and self.cookie_session_affinity.expires ~= "" then cookie_data.expires = ngx.cookie_time(ngx.time() + tonumber(self.cookie_session_affinity.expires)) end if self.cookie_session_affinity.maxage and self.cookie_session_affinity.maxage ~= "" then cookie_data.max_age = tonumber(self.cookie_session_affinity.maxage) end local ok ok, err = cookie:set(cookie_data) if not ok then ngx.log(ngx.ERR, err) end end function _M.get_last_failure() return ngx_balancer.get_last_failure() end local function get_failed_upstreams() local indexed_upstream_addrs = {} local upstream_addrs = split.split_upstream_var(ngx.var.upstream_addr) or {} for _, addr in ipairs(upstream_addrs) do indexed_upstream_addrs[addr] = true end return indexed_upstream_addrs end local function should_set_cookie(self) if self.cookie_session_affinity.locations and ngx.var.host then local locs = self.cookie_session_affinity.locations[ngx.var.host] if locs == nil then -- Based off of wildcard hostname in ../certificate.lua local wildcard_host, _, err = ngx.re.sub(ngx.var.host, "^[^\\.]+\\.", "*.", "jo") if err then ngx.log(ngx.ERR, "error: ", err); elseif wildcard_host then locs = self.cookie_session_affinity.locations[wildcard_host] end end if locs ~= nil then for _, path in pairs(locs) do if ngx.var.location_path == path then return true end end end end return false end function _M.balance(self) local upstream_from_cookie local key = self:get_cookie() if key then upstream_from_cookie = self.instance:find(key) end local last_failure = self.get_last_failure() local should_pick_new_upstream = last_failure ~= nil and self.cookie_session_affinity.change_on_failure or upstream_from_cookie == nil if not should_pick_new_upstream then return upstream_from_cookie end local new_upstream new_upstream, key = self:pick_new_upstream(get_failed_upstreams()) if not new_upstream then ngx.log(ngx.WARN, string.format("failed to get new upstream; using upstream %s", new_upstream)) elseif should_set_cookie(self) then self:set_cookie(key) end return new_upstream end function _M.sync(self, backend) -- reload balancer nodes balancer_resty.sync(self, backend) self.traffic_shaping_policy = backend.trafficShapingPolicy self.alternative_backends = backend.alternativeBackends self.cookie_session_affinity = backend.sessionAffinityConfig.cookieSessionAffinity end return _M
Fixed LUA lint findings.
Fixed LUA lint findings.
Lua
apache-2.0
kubernetes/ingress-nginx,kubernetes/ingress-nginx,canhnt/ingress,kubernetes/ingress-nginx,canhnt/ingress,caicloud/ingress,aledbf/ingress-nginx,kubernetes/ingress-nginx,canhnt/ingress,caicloud/ingress,aledbf/ingress-nginx,canhnt/ingress,aledbf/ingress-nginx,kubernetes/ingress-nginx,caicloud/ingress,aledbf/ingress-nginx,caicloud/ingress
e738ebf8653deeb15a3914325acc9d7b86155df5
init.lua
init.lua
-- Copyright 2015 Boundary, Inc. -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. local framework = require('framework') local Plugin = framework.Plugin local DataSource = framework.DataSource local Accumulator = framework.Accumulator local mysql = require('mysql') local sum = framework.util.sum local merge = framework.table.merge local PollerCollection = framework.PollerCollection local DataSourcePoller = framework.DataSourcePoller local Cache = framework.Cache local ipack = framework.util.ipack local notEmpty = framework.string.notEmpty local ratio = framework.util.ratio local params = framework.params params.items = params.items or {} local cache = Cache(function () return Accumulator() end) local MySQLDataSource = DataSource:extend() function MySQLDataSource:initialize(opts) self.host = opts.host or 'localhost' self.port = opts.port or 3306 self.user = opts.username or 'root' self.password = opts.password self.logging = true self.source = opts.source end function MySQLDataSource:fetch(context, callback, params) if not self.client or not self.client.connected then self.client = mysql.createClient(self) self.client:propagate('error', self) end self.client:query('SHOW /*!50002 GLOBAL */ STATUS', function (err, status, fields) if err then err.source = self.source self:emit('error', err) else self.client:query('SHOW GLOBAL VARIABLES', function (err, variables, fields) if (err) then err.source = self.source self:emit('error', err) else local result = merge(status, variables) callback(result, { context = self }) end end) end end) end local function parse(data, context) local result = { curr = {}, diff = {}} local acc = cache:get(context.source) for _, row in ipairs(data) do local value = tonumber(row.Value) if value then result.diff[row.Variable_name] = acc(row.Variable_name, value) result.curr[row.Variable_name] = value end end return result end local function poller(item) item.pollInterval = notEmpty(item.pollInterval, 1000) local ds = MySQLDataSource:new(item) local p = DataSourcePoller(item.pollInterval, ds) return p end local function createPollers(items) local pollers = PollerCollection() for _, i in ipairs(items) do pollers:add(poller(i)) end return pollers end local pollers = createPollers(params.items) local plugin = Plugin({ pollInterval = 1000 }, pollers) function plugin:onParseValues(data, extra) local result = {} local metric = function (...) ipack(result, ...) end local parsed = parse(data, extra.context) local curr = parsed.curr local diff = parsed.diff local qcache_memory_usage = (curr.query_cache_size - curr.Qcache_free_memory) / curr.query_cache_size; local qcache_hits = ratio(diff.Qcache_hits, diff.Com_select + diff.Qcache_hits) local source = extra.context.source metric('MYSQL_CONNECTIONS', diff.Connections, nil, source) metric('MYSQL_ABORTED_CONNECTIONS', sum({ diff.Aborted_connects, diff.Aborted_clients }), nil, source) metric('MYSQL_BYTES_IN', diff.Bytes_received, nil, source) metric('MYSQL_BYTES_OUT', diff.Bytes_sent, nil, source) metric('MYSQL_SLOW_QUERIES', diff.Slow_queries, nil, source) metric('MYSQL_ROW_MODIFICATIONS', sum({ diff.Handler_write, diff.Handler_update, diff.Handler_delete }), nil, source) metric('MYSQL_ROW_READS', sum({ diff.Handler_read_first, diff.Handler_read_key, diff.Handler_read_next, diff.Handler_read_prev, diff.Handler_read_rnd, diff.Handler_read_rnd_next }), nil, source) metric('MYSQL_TABLE_LOCKS', diff.Table_locks_immediate, nil, source) metric('MYSQL_TABLE_LOCKS_WAIT', diff.Table_locks_waited, nil, source) metric('MYSQL_COMMITS', diff.Handler_commit, nil, source) metric('MYSQL_ROLLBACKS', diff.Handler_rollback, nil, source) metric('MYSQL_QCACHE_HITS', qcache_hits, nil, source) metric('MYSQL_QCACHE_PRUNES', diff.Qcache_lowmem_prunes, nil, source) metric('MYSQL_QCACHE_MEMORY', qcache_memory_usage, nil, source) return result end plugin:run()
-- Copyright 2015 Boundary, Inc. -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. local framework = require('framework') local Plugin = framework.Plugin local DataSource = framework.DataSource local Accumulator = framework.Accumulator local mysql = require('mysql') local sum = framework.util.sum local merge = framework.table.merge local PollerCollection = framework.PollerCollection local DataSourcePoller = framework.DataSourcePoller local Cache = framework.Cache local ipack = framework.util.ipack local notEmpty = framework.string.notEmpty local ratio = framework.util.ratio local params = framework.params params.items = params.items or {} local cache = Cache(function () return Accumulator() end) local MySQLDataSource = DataSource:extend() function MySQLDataSource:initialize(opts) self.host = opts.host or 'localhost' self.port = opts.port or 3306 self.user = opts.username or 'root' self.password = opts.password self.logging = true self.source = opts.source end function MySQLDataSource:fetch(context, callback, params) if not self.client or not self.client.connected then self.client = mysql.createClient(self) self.client:propagate('error', self) end self.client:query('SHOW /*!50002 GLOBAL */ STATUS', function (err, status, fields) if err then --err.source = self.source -- removed for luvit platform self:emit('error', err) else self.client:query('SHOW GLOBAL VARIABLES', function (err, variables, fields) if (err) then --err.source = self.source self:emit('error', err) else local result = merge(status, variables) callback(result, { context = self }) end end) end end) end local function parse(data, context) local result = { curr = {}, diff = {}} local acc = cache:get(context.source) for _, row in ipairs(data) do local value = tonumber(row.Value) if value then result.diff[row.Variable_name] = acc(row.Variable_name, value) result.curr[row.Variable_name] = value end end return result end local function poller(item) item.pollInterval = notEmpty(item.pollInterval, 1000) local ds = MySQLDataSource:new(item) local p = DataSourcePoller(item.pollInterval, ds) return p end local function createPollers(items) local pollers = PollerCollection() for _, i in ipairs(items) do pollers:add(poller(i)) end return pollers end local pollers = createPollers(params.items) local plugin = Plugin({ pollInterval = 1000 }, pollers) function plugin:onParseValues(data, extra) local result = {} local metric = function (...) ipack(result, ...) end local parsed = parse(data, extra.context) local curr = parsed.curr local diff = parsed.diff local qcache_memory_usage = (curr.query_cache_size - curr.Qcache_free_memory) / curr.query_cache_size; local qcache_hits = ratio(diff.Qcache_hits, diff.Com_select + diff.Qcache_hits) local source = extra.context.source metric('MYSQL_CONNECTIONS', diff.Connections, nil, source) metric('MYSQL_ABORTED_CONNECTIONS', sum({ diff.Aborted_connects, diff.Aborted_clients }), nil, source) metric('MYSQL_BYTES_IN', diff.Bytes_received, nil, source) metric('MYSQL_BYTES_OUT', diff.Bytes_sent, nil, source) metric('MYSQL_SLOW_QUERIES', diff.Slow_queries, nil, source) metric('MYSQL_ROW_MODIFICATIONS', sum({ diff.Handler_write, diff.Handler_update, diff.Handler_delete }), nil, source) metric('MYSQL_ROW_READS', sum({ diff.Handler_read_first, diff.Handler_read_key, diff.Handler_read_next, diff.Handler_read_prev, diff.Handler_read_rnd, diff.Handler_read_rnd_next }), nil, source) metric('MYSQL_TABLE_LOCKS', diff.Table_locks_immediate, nil, source) metric('MYSQL_TABLE_LOCKS_WAIT', diff.Table_locks_waited, nil, source) metric('MYSQL_COMMITS', diff.Handler_commit, nil, source) metric('MYSQL_ROLLBACKS', diff.Handler_rollback, nil, source) metric('MYSQL_QCACHE_HITS', qcache_hits, nil, source) metric('MYSQL_QCACHE_PRUNES', diff.Qcache_lowmem_prunes, nil, source) metric('MYSQL_QCACHE_MEMORY', qcache_memory_usage, nil, source) return result end plugin:run()
fix for error, its string in place of object for luvit
fix for error, its string in place of object for luvit
Lua
apache-2.0
boundary/boundary-plugin-mysql
bdf0fb917a3a364aba79ec8d892c43c597ef9b6c
src/ngx-oauth/either.lua
src/ngx-oauth/either.lua
--------- -- The Either monad. -- -- The Either type represents values with two possibilities: a value of type -- `Either a b` is either a Left, whose value is of type `a`, or a Right, whose -- value is of type `b`. The `Either` itself is not needed in this -- implementation, so you find only `Left` and `Right` here. -- -- This implementation (hopefully) satisfies [Monad](https://github.com/fantasyland/fantasy-land#monad) -- specification from the Fantasy Land Specification, except the `of` method. -- Instead of `Left.of(a)` and `Right.of(a)`, use `Left(a)` and `Right(a)`. local util = require 'ngx-oauth.util' local mtype = util.mtype local function Either (ttype, value) return setmetatable({ value = value }, { __eq = function(a, b) return mtype(a) == mtype(b) and a.value == b.value end, __tostring = function(a) return ttype..'('..a.value..')' end, __type = ttype }) end --- Returns a `Left` with the given `value`. -- @param value The value of any type to wrap. -- @treturn Left local function Left (value) local self = Either('Left', value) --- Returns self. -- @function Left.ap -- @treturn Left self self.ap = function() return self end --- Returns self. -- @function Left.map -- @treturn Left self self.map = function() return self end --- Returns self. -- @function Left.chain -- @treturn Left self self.chain = function() return self end return self end --- Returns a `Right` with the given `value`. -- @param value The value of any type to wrap. -- @treturn Right local function Right (value) local self = Either('Right', value) --- Returns a `Right` whose value is the result of applying self's value to -- the given Right's value, if it's `Right`; otherwise returns the given `Left`. -- -- @function Right.map -- @tparam Left|Right either -- @treturn any -- @raise Error if self's value is not a function or if _either_ is not -- `Left`, nor `Right`. self.ap = function(either) assert(mtype(value) == 'function', 'Could not apply this value to given Either; this value is not a function') assert(mtype(either) == 'Right' or mtype(either) == 'Left', 'Expected Left or Right') return either.map(value) end --- Returns a `Right` whose value is the result of applying the `func` to -- this Right's value. -- -- @function Right.map -- @tparam function func -- @treturn Right self.map = function(func) return Right(func(value)) end --- Returns the result of applying the given function to self's value. -- -- @function Right.chain -- @tparam function func -- @treturn any self.chain = function(func) return func(value) end return self end --- Returns the result of applying the `on_left` function to the Left's value, -- if the `teither` is a `Left`, or the result of applying the `on_right` -- function to the Right's value, if the `teither` is a `Right`. -- -- @tparam function on_left The Left's handler. -- @tparam function on_right The Right's handler. -- @tparam Left|Right teither -- @raise Error when `teither` is not `Left`, nor `Right`. local function either (on_left, on_right, teither) if mtype(teither) == 'Left' then return on_left(teither.value) elseif mtype(teither) == 'Right' then return on_right(teither.value) else return error 'Expected Left or Right as 3rd argument' end end --- Adapts the given function, that may throw an error, to return *either* -- `Left` with the error message, or `Right` with the result. -- -- @tparam function func The function to adapt. -- @treturn function An adapted `func` that accepts the same arguments as -- `func`, but returns `Left` on an error and `Right` on a success. local function encase (func) return function(...) local ok, val = pcall(func, ...) return ok and Right(val) or Left(val) end end --- Adapts the given function, that returns `nil,err` on failure and `res,nil` -- on success, to return *either* `Left` with `err`, or `Right` with `res`. -- -- @tparam function func The function to adapt. -- @treturn function An adapted `func` that accepts the same arguments as -- `func`, but returns `Left` on an error and `Right` on a success. local function encase2 (func) return function(...) local res, err = func(...) return err and Left(err) or Right(res) end end --- @export return { Left = Left, Right = Right, either = either, encase = encase, encase2 = encase2 }
--------- -- The Either monad. -- -- The Either type represents values with two possibilities: a value of type -- `Either a b` is either a Left, whose value is of type `a`, or a Right, whose -- value is of type `b`. The `Either` itself is not needed in this -- implementation, so you find only `Left` and `Right` here. -- -- This implementation (hopefully) satisfies [Monad](https://github.com/fantasyland/fantasy-land#monad) -- specification from the Fantasy Land Specification, except the `of` method. -- Instead of `Left.of(a)` and `Right.of(a)`, use `Left(a)` and `Right(a)`. local util = require 'ngx-oauth.util' local mtype = util.mtype local function either_eq (op1, op2) return mtype(op1) == mtype(op2) and op1.value == op2.value end local function Either (ttype, value) return setmetatable({ value = value }, { -- __eq must be a non-anonymous function, to have the same identity for each -- instance of Either, otherwise it doesn't work on Lua 5.1 and LuaJIT 2.0. __eq = either_eq, __tostring = function(a) return ttype..'('..a.value..')' end, __type = ttype }) end --- Returns a `Left` with the given `value`. -- @param value The value of any type to wrap. -- @treturn Left local function Left (value) local self = Either('Left', value) --- Returns self. -- @function Left.ap -- @treturn Left self self.ap = function() return self end --- Returns self. -- @function Left.map -- @treturn Left self self.map = function() return self end --- Returns self. -- @function Left.chain -- @treturn Left self self.chain = function() return self end return self end --- Returns a `Right` with the given `value`. -- @param value The value of any type to wrap. -- @treturn Right local function Right (value) local self = Either('Right', value) --- Returns a `Right` whose value is the result of applying self's value to -- the given Right's value, if it's `Right`; otherwise returns the given `Left`. -- -- @function Right.map -- @tparam Left|Right either -- @treturn any -- @raise Error if self's value is not a function or if _either_ is not -- `Left`, nor `Right`. self.ap = function(either) assert(mtype(value) == 'function', 'Could not apply this value to given Either; this value is not a function') assert(mtype(either) == 'Right' or mtype(either) == 'Left', 'Expected Left or Right') return either.map(value) end --- Returns a `Right` whose value is the result of applying the `func` to -- this Right's value. -- -- @function Right.map -- @tparam function func -- @treturn Right self.map = function(func) return Right(func(value)) end --- Returns the result of applying the given function to self's value. -- -- @function Right.chain -- @tparam function func -- @treturn any self.chain = function(func) return func(value) end return self end --- Returns the result of applying the `on_left` function to the Left's value, -- if the `teither` is a `Left`, or the result of applying the `on_right` -- function to the Right's value, if the `teither` is a `Right`. -- -- @tparam function on_left The Left's handler. -- @tparam function on_right The Right's handler. -- @tparam Left|Right teither -- @raise Error when `teither` is not `Left`, nor `Right`. local function either (on_left, on_right, teither) if mtype(teither) == 'Left' then return on_left(teither.value) elseif mtype(teither) == 'Right' then return on_right(teither.value) else return error 'Expected Left or Right as 3rd argument' end end --- Adapts the given function, that may throw an error, to return *either* -- `Left` with the error message, or `Right` with the result. -- -- @tparam function func The function to adapt. -- @treturn function An adapted `func` that accepts the same arguments as -- `func`, but returns `Left` on an error and `Right` on a success. local function encase (func) return function(...) local ok, val = pcall(func, ...) return ok and Right(val) or Left(val) end end --- Adapts the given function, that returns `nil,err` on failure and `res,nil` -- on success, to return *either* `Left` with `err`, or `Right` with `res`. -- -- @tparam function func The function to adapt. -- @treturn function An adapted `func` that accepts the same arguments as -- `func`, but returns `Left` on an error and `Right` on a success. local function encase2 (func) return function(...) local res, err = func(...) return err and Left(err) or Right(res) end end --- @export return { Left = Left, Right = Right, either = either, encase = encase, encase2 = encase2 }
Fix compatibility with Lua 5.1 and LuaJIT 2.0
Fix compatibility with Lua 5.1 and LuaJIT 2.0
Lua
mit
jirutka/ngx-oauth,jirutka/ngx-oauth
98af0c20af5aafe70f7777403f77200b1d7205a3
src/extensions/cp/ui/Button.lua
src/extensions/cp/ui/Button.lua
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- F I N A L C U T P R O A P I -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- --- === cp.ui.Button === --- --- Button Module. -------------------------------------------------------------------------------- -- -- EXTENSIONS: -- -------------------------------------------------------------------------------- -- local log = require("hs.logger").new("button") local axutils = require("cp.ui.axutils") local prop = require("cp.prop") -------------------------------------------------------------------------------- -- -- THE MODULE: -- -------------------------------------------------------------------------------- local Button = {} --- cp.ui.Button.matches(element) -> boolean --- Function --- Checks if the `element` is a `Button`, returning `true` if so. --- --- Parameters: --- * element - The `hs._asm.axuielement` to check. --- --- Returns: --- * `true` if the `element` is a `Button`, or `false` if not. function Button.matches(element) return element and element:attributeValue("AXRole") == "AXButton" end --- cp.ui.Button.new(parent, finderFn) -> cp.ui.Button --- Constructor --- Creates a new `Button` instance. --- --- Parameters: --- * parent - The parent object. Should have a `UI` and `isShowing` field. --- * finderFn - A function which will return the `hs._asm.axuielement` the button belongs to, or `nil` if not available. --- --- Returns: --- The new `Button` instance. function Button.new(parent, finderFn) local o = prop.extend({_parent = parent, _finder = finderFn}, Button) -- TODO: Add documentation local UI = prop(function(self) return axutils.cache(self, "_ui", finderFn, Button.matches) end) if prop.is(parent.UI) then UI:monitor(parent.UI) end local isShowing = UI:mutate(function(original, self) return original() ~= nil and self:parent():isShowing() end) if prop.is(parent.isShowing) then isShowing.monitor(parent.isShowing) end local frame = UI:mutate(function(original) local ui = original() return ui and ui:frame() or nil end) prop.bind(o) { --- cp.ui.Button.UI <cp.prop: hs._asm.axuielement; read-only> --- Field --- Retrieves the `axuielement` for the `Button`, or `nil` if not available.. UI = UI, --- cp.ui.Button.isShowing <cp.prop: boolean; read-only> --- Field --- If `true`, the `Button` is showing on screen. isShowing = isShowing, --- cp.ui.Button.frame <cp.prop: table; read-only> --- Field --- Returns the table containing the `x`, `y`, `w`, and `h` values for the button frame, or `nil` if not available. frame = frame, } return o end -- TODO: Add documentation function Button:parent() return self._parent end --- cp.ui.Button:isEnabled() -> boolean --- Method --- Returns `true` if the button is visible and enabled. --- --- Parameters: --- * None --- --- Returns: --- * `true` if the button is visible and enabled. function Button:isEnabled() local ui = self:UI() return ui ~= nil and ui:enabled() end --- cp.ui.Button:press() -> self --- Method --- Performs a button press action, if the button is available. --- --- Parameters: --- * None --- --- Returns: --- * The `Button` instance. function Button:press() local ui = self:UI() if ui then ui:doPress() end return self end --- cp.ui.Button:snapshot([path]) -> hs.image | nil --- Method --- Takes a snapshot of the button in its current state as a PNG and returns it. --- If the `path` is provided, the image will be saved at the specified location. --- --- Parameters: --- * path - (optional) The path to save the file. Should include the extension (should be `.png`). --- --- Return: --- * The `hs.image` that was created. function Button:snapshot(path) local ui = self:UI() if ui then return axutils.snapshot(ui, path) end return nil end --- cp.ui.Button:frame() -> table | nil --- Method --- Returns the `frame` of the `Button`, if available. --- --- Parameters: --- * None --- --- Returns: --- * The `Button` frame. function Button:frame() local ui = self:UI() return ui and ui:attributeValue("AXFrame") end return Button
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- F I N A L C U T P R O A P I -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- --- === cp.ui.Button === --- --- Button Module. -------------------------------------------------------------------------------- -- -- EXTENSIONS: -- -------------------------------------------------------------------------------- -- local log = require("hs.logger").new("button") local axutils = require("cp.ui.axutils") local prop = require("cp.prop") -------------------------------------------------------------------------------- -- -- THE MODULE: -- -------------------------------------------------------------------------------- local Button = {} --- cp.ui.Button.matches(element) -> boolean --- Function --- Checks if the `element` is a `Button`, returning `true` if so. --- --- Parameters: --- * element - The `hs._asm.axuielement` to check. --- --- Returns: --- * `true` if the `element` is a `Button`, or `false` if not. function Button.matches(element) return element and element:attributeValue("AXRole") == "AXButton" end --- cp.ui.Button.new(parent, finderFn) -> cp.ui.Button --- Constructor --- Creates a new `Button` instance. --- --- Parameters: --- * parent - The parent object. Should have a `UI` and `isShowing` field. --- * finderFn - A function which will return the `hs._asm.axuielement` the button belongs to, or `nil` if not available. --- --- Returns: --- The new `Button` instance. function Button.new(parent, finderFn) local o = prop.extend( { _parent = parent, _finder = finderFn, --- cp.ui.Button.UI <cp.prop: hs._asm.axuielement; read-only> --- Field --- Retrieves the `axuielement` for the `Button`, or `nil` if not available.. UI = prop(function(self) return axutils.cache(self, "_ui", finderFn, Button.matches) end), }, Button ) prop.bind(o) { --- cp.ui.Button.isShowing <cp.prop: boolean; read-only> --- Field --- If `true`, the `Button` is showing on screen. isShowing = o.UI:mutate(function(original, self) return original() ~= nil and self:parent():isShowing() end), --- cp.ui.Button.frame <cp.prop: table; read-only> --- Field --- Returns the table containing the `x`, `y`, `w`, and `h` values for the button frame, or `nil` if not available. frame = o.UI:mutate(function(original) local ui = original() return ui and ui:frame() or nil end), } if prop.is(parent.UI) then o.UI:monitor(parent.UI) end if prop.is(parent.isShowing) then o.isShowing:monitor(parent.isShowing) end return o end -- TODO: Add documentation function Button:parent() return self._parent end --- cp.ui.Button:isEnabled() -> boolean --- Method --- Returns `true` if the button is visible and enabled. --- --- Parameters: --- * None --- --- Returns: --- * `true` if the button is visible and enabled. function Button:isEnabled() local ui = self:UI() return ui ~= nil and ui:enabled() end --- cp.ui.Button:press() -> self --- Method --- Performs a button press action, if the button is available. --- --- Parameters: --- * None --- --- Returns: --- * The `Button` instance. function Button:press() local ui = self:UI() if ui then ui:doPress() end return self end --- cp.ui.Button:snapshot([path]) -> hs.image | nil --- Method --- Takes a snapshot of the button in its current state as a PNG and returns it. --- If the `path` is provided, the image will be saved at the specified location. --- --- Parameters: --- * path - (optional) The path to save the file. Should include the extension (should be `.png`). --- --- Return: --- * The `hs.image` that was created. function Button:snapshot(path) local ui = self:UI() if ui then return axutils.snapshot(ui, path) end return nil end return Button
#1065 * Fixed some issues in Button
#1065 * Fixed some issues in Button
Lua
mit
fcpxhacks/fcpxhacks,fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost,CommandPost/CommandPost
73094b66802aa81da1606078e80248b2973880a5
monster/race_10_mummy/id_107_madness.lua
monster/race_10_mummy/id_107_madness.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/>. ]] --ID 107, Mummy of Madness, Level: 2, Armourtype: -, Weapontype: slashing local mummies = require("monster.race_10_mummy.base") local M = mummies.generateCallbacks() local function isSpecialTime() if world:getTime("month") == 16 then return true -- It is Mas! end local hour = world:getTime("hour") -- "Special time" from 20:00 to 3:59 return hour >= 20 or hour <= 3 end local function spawnNewMummy(pos) local newMummy = world:createMonster(107, pos, 0) if newMummy ~= nil and isValidChar(newMummy) then world:gfx(5, newMummy.pos); end end -- The mummy of madness needs to spawn two new monsters of the same kind upon it's death. local orgOnDeath = M.onDeath function M.onDeath(monster) if isSpecialTime() then -- Special time! Respawn two new mummies to create more fun! for _ = 1, 2 do spawnNewMummy(monster.pos) end elseif orgOnDeath ~= nil then -- normal death, with drops and everything. Only in case the mummy is really killed. orgOnDeath(monster) end 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/>. ]] --ID 107, Mummy of Madness, Level: 2, Armourtype: -, Weapontype: slashing local base = require("monster.base.base") local mummies = require("monster.race_10_mummy.base") local M = mummies.generateCallbacks() local function isSpecialTime() if world:getTime("month") == 16 then return true -- It is Mas! end local hour = world:getTime("hour") -- "Special time" from 20:00 to 3:59 return hour >= 20 or hour <= 3 end local function spawnNewMummy(pos) local newMummy = world:createMonster(107, pos, 0) if newMummy ~= nil and isValidChar(newMummy) then world:gfx(5, newMummy.pos); end end -- The mummy of madness needs to spawn two new monsters of the same kind upon it's death. local orgOnDeath = M.onDeath function M.onDeath(monster) if isSpecialTime() then -- Special time! Respawn two new mummies to create more fun! for _ = 1, 2 do spawnNewMummy(monster.pos) end base.setNoDrop(monster) end if orgOnDeath ~= nil then orgOnDeath(monster) end end return M
Fixing clean up for mummy of madness
Fixing clean up for mummy of madness
Lua
agpl-3.0
KayMD/Illarion-Content,LaFamiglia/Illarion-Content,Illarion-eV/Illarion-Content,vilarion/Illarion-Content,Baylamon/Illarion-Content
01e2e66e28b949474b4f4ff7d0bdb19176d763fb
src/assert.lua
src/assert.lua
local s = require 'say' local __assertion_meta = { __call = function(self, ...) local state = self.state local val = self.callback(state, ...) local data_type = type(val) if data_type == "boolean" then if val ~= state.mod then if state.mod then error(s(self.positive_message, assert:format({...})) or "assertion failed!", 2) else error(s(self.negative_message, assert:format({...})) or "assertion failed!", 2) end else return state end end return val end } local __state_meta = { __call = function(self, payload, callback) self.payload = payload or rawget(self, "payload") if callback then callback(self) end return self end, __index = function(self, key) if rawget(self.parent, "modifier")[key] then rawget(self.parent, "modifier")[key].state = self return self(nil, rawget(self.parent, "modifier")[key] ) elseif rawget(self.parent, "assertion")[key] then rawget(self.parent, "assertion")[key].state = self return rawget(self.parent, "assertion")[key] else error("luassert: unknown modifier/assertion: '" .. tostring(key).."'", 2) end end } local obj = { -- list of registered assertions assertion = {}, state = function(obj) return setmetatable({mod=true, payload=nil, parent=obj}, __state_meta) end, -- list of registered modifiers modifier = {}, -- list of registered formatters formatter = {}, -- registers a function in namespace register = function(self, namespace, name, callback, positive_message, negative_message) -- register local lowername = name:lower() if not self[namespace] then self[namespace] = {} end self[namespace][lowername] = setmetatable({ callback = callback, name = lowername, positive_message=positive_message, negative_message=negative_message }, __assertion_meta) end, -- registers a formatter -- a formatter takes a single argument, and converts it to a string, or returns nil if it cannot format the argument addformatter = function(self, callback) table.insert(self.formatter, callback) end, -- unregisters a formatter removeformatter = function(self, formatter) for i, v in ipairs(self.formatter) do if v == formatter then table.remove(self.formatter, i) break end end end, format = function(self, args) for i = 1, #args do -- cannot use pairs because table might have nils local val = args[i] local valfmt = nil for n, fmt in ipairs(self.formatter) do valfmt = fmt(val) if valfmt ~= nil then break end end if valfmt == nil then valfmt = tostring(val) end -- no formatter found args[i] = valfmt end return args end } local __meta = { __call = function(self, bool, message) if not bool then error(message or "assertion failed!", 2) end return bool end, __index = function(self, key) return self.state(self)[key] end, } return setmetatable(obj, __meta)
local s = require 'say' local errorlevel = function() -- find the first level, not defined in the same file as this -- code file to properly report the error local level = 1 local info = debug.getinfo(level) local thisfile = (info or {}).source while thisfile and thisfile == (info or {}).source do level = level + 1 info = debug.getinfo(level) end if level > 1 then level = level - 1 end -- deduct call to errorlevel() itself return level end local __assertion_meta = { __call = function(self, ...) local state = self.state local val = self.callback(state, ...) local data_type = type(val) if data_type == "boolean" then if val ~= state.mod then if state.mod then error(s(self.positive_message, assert:format({...})) or "assertion failed!", errorlevel()) else error(s(self.negative_message, assert:format({...})) or "assertion failed!", errorlevel()) end else return state end end return val end } local __state_meta = { __call = function(self, payload, callback) self.payload = payload or rawget(self, "payload") if callback then callback(self) end return self end, __index = function(self, key) if rawget(self.parent, "modifier")[key] then rawget(self.parent, "modifier")[key].state = self return self(nil, rawget(self.parent, "modifier")[key] ) elseif rawget(self.parent, "assertion")[key] then rawget(self.parent, "assertion")[key].state = self return rawget(self.parent, "assertion")[key] else error("luassert: unknown modifier/assertion: '" .. tostring(key).."'", errorlevel()) end end } local obj = { -- list of registered assertions assertion = {}, state = function(obj) return setmetatable({mod=true, payload=nil, parent=obj}, __state_meta) end, -- list of registered modifiers modifier = {}, -- list of registered formatters formatter = {}, -- registers a function in namespace register = function(self, namespace, name, callback, positive_message, negative_message) -- register local lowername = name:lower() if not self[namespace] then self[namespace] = {} end self[namespace][lowername] = setmetatable({ callback = callback, name = lowername, positive_message=positive_message, negative_message=negative_message }, __assertion_meta) end, -- registers a formatter -- a formatter takes a single argument, and converts it to a string, or returns nil if it cannot format the argument addformatter = function(self, callback) table.insert(self.formatter, callback) end, -- unregisters a formatter removeformatter = function(self, formatter) for i, v in ipairs(self.formatter) do if v == formatter then table.remove(self.formatter, i) break end end end, format = function(self, args) for i = 1, #args do -- cannot use pairs because table might have nils local val = args[i] local valfmt = nil for n, fmt in ipairs(self.formatter) do valfmt = fmt(val) if valfmt ~= nil then break end end if valfmt == nil then valfmt = tostring(val) end -- no formatter found args[i] = valfmt end return args end } local __meta = { __call = function(self, bool, message) if not bool then error(message or "assertion failed!", 2) end return bool end, __index = function(self, key) return self.state(self)[key] end, } return setmetatable(obj, __meta)
report errors at correct level to properly point to the error in the test file, not luassert. Because the modifiers can be nested, the levels are also not fixed at 2. So added dynamic detection of the proper level.
report errors at correct level to properly point to the error in the test file, not luassert. Because the modifiers can be nested, the levels are also not fixed at 2. So added dynamic detection of the proper level.
Lua
mit
mpeterv/luassert,o-lim/luassert,ZyX-I/luassert,tst2005/lua-luassert
730a2903962c465b7a293597656d68c780b995ac
xmake/modules/devel/debugger/run.lua
xmake/modules/devel/debugger/run.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 run.lua -- -- imports import("core.base.option") import("core.project.config") import("detect.tools.find_cudagdb") import("detect.tools.find_cudamemcheck") import("detect.tools.find_gdb") import("detect.tools.find_lldb") import("detect.tools.find_windbg") import("detect.tools.find_x64dbg") import("detect.tools.find_ollydbg") import("detect.tools.find_devenv") import("detect.tools.find_vsjitdebugger") -- run gdb function _run_gdb(program, argv) -- find gdb local gdb = find_gdb({program = config.get("debugger")}) if not gdb then return false end -- patch arguments argv = argv or {} table.insert(argv, 1, program) table.insert(argv, 1, "--args") -- run it os.execv(gdb, argv) -- ok return true end -- run cuda-gdb function _run_cudagdb(program, argv) -- find cudagdb local gdb = find_cudagdb({program = config.get("debugger")}) if not gdb then return false end -- patch arguments argv = argv or {} table.insert(argv, 1, program) table.insert(argv, 1, "--args") -- run it os.execv(gdb, argv) -- ok return true end -- run lldb function _run_lldb(program, argv) -- find lldb local lldb = find_lldb({program = config.get("debugger")}) if not lldb then return false end -- attempt to split name, e.g. xcrun -sdk macosx lldb local names = lldb:split("%s") -- patch arguments argv = argv or {} table.insert(argv, 1, program) table.insert(argv, 1, "-f") for i = #names, 2, -1 do table.insert(argv, 1, names[i]) end -- run it os.execv(names[1], argv) -- ok return true end -- run windbg function _run_windbg(program, argv) -- find windbg local windbg = find_windbg({program = config.get("debugger")}) if not windbg then return false end -- patch arguments argv = argv or {} table.insert(argv, 1, program) -- run it os.execv(windbg, argv) -- ok return true end -- run cuda-memcheck function _run_cudamemcheck(program, argv) -- find cudamemcheck local cudamemcheck = find_cudamemcheck({program = config.get("debugger")}) if not cudamemcheck then return false end -- patch arguments argv = argv or {} table.insert(argv, 1, program) -- run it os.execv(cudamemcheck, argv) -- ok return true end -- run x64dbg function _run_x64dbg(program, argv) -- find x64dbg local x64dbg = find_x64dbg({program = config.get("debugger")}) if not x64dbg then return false end -- patch arguments argv = argv or {} table.insert(argv, 1, program) -- run it os.execv(x64dbg, argv) -- ok return true end -- run ollydbg function _run_ollydbg(program, argv) -- find ollydbg local ollydbg = find_ollydbg({program = config.get("debugger")}) if not ollydbg then return false end -- patch arguments argv = argv or {} table.insert(argv, 1, program) -- run it os.execv(ollydbg, argv) -- ok return true end -- run vsjitdebugger function _run_vsjitdebugger(program, argv) -- find vsjitdebugger local vsjitdebugger = find_vsjitdebugger({program = config.get("debugger")}) if not vsjitdebugger then return false end -- patch arguments argv = argv or {} table.insert(argv, 1, program) -- run it os.execv(vsjitdebugger, argv) -- ok return true end -- run devenv function _run_devenv(program, argv) -- find devenv local devenv = find_devenv({program = config.get("debugger")}) if not devenv then return false end -- patch arguments argv = argv or {} table.insert(argv, 1, "/DebugExe") table.insert(argv, 2, program) -- run it os.execv(devenv, argv) -- ok return true end -- run program with debugger -- -- @param program the program name -- @param argv the program rguments -- -- @code -- -- import("devel.debugger") -- -- debugger.run("test") -- debugger.run("echo", {"hello xmake!"}) -- -- @endcode -- function main(program, argv) -- init debuggers local debuggers = { {"lldb" , _run_lldb} , {"gdb" , _run_gdb} , {"cudagdb" , _run_cudagdb} , {"cudamemcheck", _run_cudamemcheck} } -- for windows target or on windows? if (config.plat() or os.host()) == "windows" then table.insert(debuggers, 1, {"windbg", _run_windbg}) table.insert(debuggers, 1, {"ollydbg", _run_ollydbg}) table.insert(debuggers, 1, {"x64dbg", _run_x64dbg}) table.insert(debuggers, 1, {"vsjitdebugger", _run_vsjitdebugger}) table.insert(debuggers, 1, {"devenv", _run_devenv}) end -- get debugger from the configure local debugger = config.get("debugger") if debugger then -- try exactmatch first debugger = debugger:lower() local debuggername = path.basename(debugger) for _, _debugger in ipairs(debuggers) do if debuggername:startswith(_debugger[1]) then if _debugger[2](program, argv) then return end end end for _, _debugger in ipairs(debuggers) do if debugger:find(_debugger[1]) then if _debugger[2](program, argv) then return end end end else -- run debugger for _, _debugger in ipairs(debuggers) do if _debugger[2](program, argv) then return end end end -- no debugger raise("debugger%s not found!", debugger and ("(" .. debugger .. ")") or "") 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 run.lua -- -- imports import("core.base.option") import("core.project.config") import("detect.tools.find_cudagdb") import("detect.tools.find_cudamemcheck") import("detect.tools.find_gdb") import("detect.tools.find_lldb") import("detect.tools.find_windbg") import("detect.tools.find_x64dbg") import("detect.tools.find_ollydbg") import("detect.tools.find_devenv") import("detect.tools.find_vsjitdebugger") -- run gdb function _run_gdb(program, argv) -- find gdb local gdb = find_gdb({program = config.get("debugger")}) if not gdb then return false end -- patch arguments argv = argv or {} table.insert(argv, 1, program) table.insert(argv, 1, "--args") -- run it os.execv(gdb, argv) -- ok return true end -- run cuda-gdb function _run_cudagdb(program, argv) -- find cudagdb local gdb = find_cudagdb({program = config.get("debugger")}) if not gdb then return false end -- patch arguments argv = argv or {} table.insert(argv, 1, program) table.insert(argv, 1, "--args") -- run it os.execv(gdb, argv) -- ok return true end -- run lldb function _run_lldb(program, argv) -- find lldb local lldb = find_lldb({program = config.get("debugger")}) if not lldb then return false end -- attempt to split name, e.g. xcrun -sdk macosx lldb local names = lldb:split("%s") -- patch arguments argv = argv or {} table.insert(argv, 1, "--") table.insert(argv, 1, program) table.insert(argv, 1, "-f") for i = #names, 2, -1 do table.insert(argv, 1, names[i]) end -- run it os.execv(names[1], argv) -- ok return true end -- run windbg function _run_windbg(program, argv) -- find windbg local windbg = find_windbg({program = config.get("debugger")}) if not windbg then return false end -- patch arguments argv = argv or {} table.insert(argv, 1, program) -- run it os.execv(windbg, argv) -- ok return true end -- run cuda-memcheck function _run_cudamemcheck(program, argv) -- find cudamemcheck local cudamemcheck = find_cudamemcheck({program = config.get("debugger")}) if not cudamemcheck then return false end -- patch arguments argv = argv or {} table.insert(argv, 1, program) -- run it os.execv(cudamemcheck, argv) -- ok return true end -- run x64dbg function _run_x64dbg(program, argv) -- find x64dbg local x64dbg = find_x64dbg({program = config.get("debugger")}) if not x64dbg then return false end -- patch arguments argv = argv or {} table.insert(argv, 1, program) -- run it os.execv(x64dbg, argv) -- ok return true end -- run ollydbg function _run_ollydbg(program, argv) -- find ollydbg local ollydbg = find_ollydbg({program = config.get("debugger")}) if not ollydbg then return false end -- patch arguments argv = argv or {} table.insert(argv, 1, program) -- run it os.execv(ollydbg, argv) -- ok return true end -- run vsjitdebugger function _run_vsjitdebugger(program, argv) -- find vsjitdebugger local vsjitdebugger = find_vsjitdebugger({program = config.get("debugger")}) if not vsjitdebugger then return false end -- patch arguments argv = argv or {} table.insert(argv, 1, program) -- run it os.execv(vsjitdebugger, argv) -- ok return true end -- run devenv function _run_devenv(program, argv) -- find devenv local devenv = find_devenv({program = config.get("debugger")}) if not devenv then return false end -- patch arguments argv = argv or {} table.insert(argv, 1, "/DebugExe") table.insert(argv, 2, program) -- run it os.execv(devenv, argv) -- ok return true end -- run program with debugger -- -- @param program the program name -- @param argv the program rguments -- -- @code -- -- import("devel.debugger") -- -- debugger.run("test") -- debugger.run("echo", {"hello xmake!"}) -- -- @endcode -- function main(program, argv) -- init debuggers local debuggers = { {"lldb" , _run_lldb} , {"gdb" , _run_gdb} , {"cudagdb" , _run_cudagdb} , {"cudamemcheck", _run_cudamemcheck} } -- for windows target or on windows? if (config.plat() or os.host()) == "windows" then table.insert(debuggers, 1, {"windbg", _run_windbg}) table.insert(debuggers, 1, {"ollydbg", _run_ollydbg}) table.insert(debuggers, 1, {"x64dbg", _run_x64dbg}) table.insert(debuggers, 1, {"vsjitdebugger", _run_vsjitdebugger}) table.insert(debuggers, 1, {"devenv", _run_devenv}) end -- get debugger from the configure local debugger = config.get("debugger") if debugger then -- try exactmatch first debugger = debugger:lower() local debuggername = path.basename(debugger) for _, _debugger in ipairs(debuggers) do if debuggername:startswith(_debugger[1]) then if _debugger[2](program, argv) then return end end end for _, _debugger in ipairs(debuggers) do if debugger:find(_debugger[1]) then if _debugger[2](program, argv) then return end end end else -- run debugger for _, _debugger in ipairs(debuggers) do if _debugger[2](program, argv) then return end end end -- no debugger raise("debugger%s not found!", debugger and ("(" .. debugger .. ")") or "") end
fix load program with args for lldb
fix load program with args for lldb
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
46ba257d0a8dc0886cb4eca280dd09009ec4f418
test/tests/regex_cap.lua
test/tests/regex_cap.lua
local assertEq = test.assertEq local function log(x) test.log(tostring(x) .. "\n") end local vi_regex = require('regex.regex') local compile = vi_regex.compile local pat pat = compile('a(.*)b') assertEq(pat:match("axyzb"), {_start=1,_end=5, groups={{2,4}},}) assertEq(pat:match("axyzbb"), {_start=1,_end=6, groups={{2,5}},}) pat = compile('a(foo|bar)*b') --log(test.tostring(vi_regex.parse('a(foo|bar)*b'), '')) --log(test.tostring(vi_regex.parse('a(foo|bar)*b'), '')) assertEq(pat:match("ab"), {_start=1,_end=2,}) assertEq(pat:match("afoob"), {_start=1,_end=5, groups={{2,4}},}) assertEq(pat:match("afoobarb"), {_start=1,_end=8, groups={{5,7}},}) pat = compile('a([a-z]*)z X([0-9]*)Y') assertEq(pat:match('az XY'), {_start=1, _end=5}) assertEq(pat:match('aasdfz X123Y'), {_start=1, _end=12, groups={{2,5},{9,11}}})
local assertEq = test.assertEq local function log(x) test.log(tostring(x) .. "\n") end local vi_regex = require('regex.regex') local compile = vi_regex.compile local pat pat = compile('a(.*)b') assertEq(pat:match("axyzb"), {_start=1,_end=5, groups={{2,4}},}) assertEq(pat:match("axyzbb"), {_start=1,_end=6, groups={{2,5}},}) pat = compile('a(foo|bar)*b') --log(test.tostring(vi_regex.parse('a(foo|bar)*b'), '')) assertEq(pat:match("ab"), {_start=1,_end=2,}) assertEq(pat:match("afoob"), {_start=1,_end=5, groups={{2,4}},}) assertEq(pat:match("afoobarb"), {_start=1,_end=8, groups={{5,7}},}) pat = compile('a([a-z]*)z X([0-9]*)Y') assertEq(pat:match('az XY'), {_start=1, _end=5, groups={{2,1}, {5,4}}}) assertEq(pat:match('aasdfz X123Y'), {_start=1, _end=12, groups={{2,5},{9,11}}})
Fix test, which is returning the correct results after all.
Fix test, which is returning the correct results after all.
Lua
mit
jugglerchris/textadept-vi,jugglerchris/textadept-vi,erig0/textadept-vi
07c26efcbfbd8ea1093410fd932a85aefe0651bf
tests/3drender/main3.lua
tests/3drender/main3.lua
local r = require "render" require "sprite" require "keys" require "loader" function keys:filter(press, key) return key == "left" or key == "right" or key == "w" or key == "a" or key == "s" or key == "d" or key == "up" or key == "down" or key == "r" or key == "b" end global { hangle = 0, x = 0, y = 0, z = 0 } declare { look = false } game.onkey = function(s, press, key) if not press then return false end local axis local vangle = 0 -- local hangle = 0 if key == "w" then print("L:", look:normalize():unpack()) x, y, z = (r.vec3(x, y, z) + look:normalize() * 10):unpack() elseif key == "a" then x = x - 2 elseif key == "s" then x, y, z = (r.vec3(x, y, z) - look:normalize() * 10):unpack() elseif key == "d" then x = x + 2 elseif key == "right" then hangle = hangle - (math.pi / 32) elseif key == "left" then hangle = hangle + (math.pi / 32) elseif key == "up" then vangle = (math.pi / 32) elseif key == "down" then vangle = - math.pi / 32 elseif key == "r" then local star = r.star({r = 160, temp = rnd(1000, 10000), seed = rnd(10000) }) local o = r.object():pixels(star, -160, 160, 1) scene.objects = {} scene:place(o, 0, 0, 200) elseif key == "b"then local star = r.star({r = 160, temp = 0, seed = rnd(10000) }) local o = r.object():pixels(star, -160, 160, 1) scene.objects = {} scene:place(o, 0, 0, 200) end scene:camera(x, y, z) -- if not look then look = r.vec3(0, 0, 1) end look = scene:climb(look, vangle, hangle) -- look = scene:roll(look, hangle) print("look: ", look:unpack()) scene:look(look, hangle) -- print("VIEW: ", hangle, vangle) screen:clear(0, 0, 0, 255) scene:render(screen) return true end game.pic = function() print "game.pic" if screen then return screen:sprite() end end declare { screen = false; scene = false; } room { nam = "main"; title = false; } function load(data) print "Rendering..." local screen = pixels.new(800, 568) screen:clear(0, 0, 0, 255) local scene = r.scene() local look local starv = r.vec3(-300, 0, 200) local planetv = r.vec3(30, 0, 30) local asteroidv = r.vec3(1, -3, 5) local star = r.star({r = 160, temp = 4500 }) local planet = r.planet({r = 160, light = planetv - starv }) local asteroid = r.asteroid({r = 160, light = asteroidv - starv, seed = rnd(110000) }) local o = r.object():pixels(star, -160, 160, 1) local p = r.object():pixels(planet, -160, 160, 0.1) local a = r.object():pixels(asteroid, -160, 160, 0.01) scene:place(o, starv) scene:place(p, planetv) scene:place(a, asteroidv) scene:setfov(160) scene:camera(0, 0, 1) look = r.vec3(0, 0, 1) scene:look(look) screen:clear(0, 0, 0, 255) scene:render(screen) data.screen = screen data.scene = scene data.look = look end function onload() print "Start..." local d = loader:data() screen = d.screen scene = d.scene look = d.look end
local r = require "render" require "sprite" require "keys" require "loader" function keys:filter(press, key) return key == "left" or key == "right" or key == "w" or key == "a" or key == "s" or key == "d" or key == "up" or key == "down" or key == "r" or key == "b" end global { hangle = 0, x = 0, y = 0, z = 0 } declare { look = false } game.onkey = function(s, press, key) if not press then return false end local axis local vangle = 0 -- local hangle = 0 if key == "w" then print("L:", look:normalize():unpack()) x, y, z = (r.vec3(x, y, z) + look:normalize() * 10):unpack() elseif key == "a" then x = x - 2 elseif key == "s" then x, y, z = (r.vec3(x, y, z) - look:normalize() * 10):unpack() elseif key == "d" then x = x + 2 elseif key == "right" then hangle = hangle - (math.pi / 32) elseif key == "left" then hangle = hangle + (math.pi / 32) elseif key == "up" then vangle = (math.pi / 32) elseif key == "down" then vangle = - math.pi / 32 elseif key == "r" then local star = r.star({r = 160, temp = rnd(1000, 10000), seed = rnd(10000) }) local o = r.object():pixels(star, -160, 160, 1) scene.objects = {} scene:place(o, 0, 0, 200) elseif key == "b"then local star = r.star({r = 160, temp = 0, seed = rnd(10000) }) local o = r.object():pixels(star, -160, 160, 1) scene.objects = {} scene:place(o, 0, 0, 200) end scene:camera(x, y, z) -- if not look then look = r.vec3(0, 0, 1) end look = scene:climb(look, vangle, hangle) -- look = scene:roll(look, hangle) print("look: ", look:unpack()) scene:look(look, hangle) -- print("VIEW: ", hangle, vangle) screen:clear(0, 0, 0, 255) scene:render(screen) return true end game.pic = function() print "game.pic" if screen then return screen:sprite() end end declare { screen = false; scene = false; } room { nam = "main"; title = false; } function load(data) print "Rendering..." local screen = pixels.new(800, 568) screen:clear(0, 0, 0, 255) local scene = r.scene() local look local starv = r.vec3(-300, 0, 200) local planetv = r.vec3(30, -5, 30) local asteroidv = r.vec3(1, -3, 5) local star = r.star({r = 160, temp = 4500 }) local planet = r.planet({r = 160, light = planetv - starv }) local asteroid = r.asteroid({r = 160, light = asteroidv - starv, seed = rnd(110000) }) local o = r.object():pixels(star, -160, 160, 1) local w, h = planet:size() local p = r.object():pixels(planet, -w/2, h/2, 0.1) local a = r.object():pixels(asteroid, -160, 160, 0.01) scene:place(o, starv) scene:place(p, planetv) scene:place(a, asteroidv) scene:setfov(160) scene:camera(0, 0, 1) look = r.vec3(0, 0, 1) scene:look(look) screen:clear(0, 0, 0, 255) scene:render(screen) data.screen = screen data.scene = scene data.look = look end function onload() print "Start..." local d = loader:data() screen = d.screen scene = d.scene look = d.look end
pos fix
pos fix
Lua
mit
gl00my/stead3
161ea16c21c45f5ca233ad70d615f7008cc650ef
2dmatch/train.lua
2dmatch/train.lua
require 'image' require 'cutorch' require 'cunn' require 'cudnn' require 'optim' -- Custom files require 'model' require 'sys' -- require 'qtwidget' -- for visualizing images dofile('util.lua') opt_string = [[ -h,--help print help -s,--save (default "logs") subdirectory to save logs -b,--batchSize (default 8) batch size -g,--gpu_index (default 0) GPU index (start from 0) --max_epoch (default 10) maximum number of epochs --basePath (default "/mnt/raid/datasets/Matterport/Matching1/") base path for train/test data --train_data (default "scenes_trainval.txt") txt file containing train --test_data (default "scenes_test.txt") txt file containing test --patchSize (default 64) patch size to extract (resized to 224) --matchFileSkip (default 10) only use every skip^th keypoint match in file ]] opt = lapp(opt_string) -- print help or chosen options if opt.help == true then print('Usage: th train.lua') print('Options:') print(opt_string) os.exit() else print(opt) end -- set gpu cutorch.setDevice(opt.gpu_index+1) -- Set RNG seed --math.randomseed(os.time()) math.randomseed(0) torch.manualSeed(0) -- Load model and criterion model,criterion = getModel() model = model:cuda() critrerion = criterion:cuda() model:zeroGradParameters() parameters, gradParameters = model:getParameters() --print(model) -- Construct window for visualizing training examples -- visWindow = qtwidget.newwindow(1792,672) -- load training and testing files train_files = getDataFiles(paths.concat(opt.basePath,opt.train_data), opt.basePath) --filter out non-existent scenes test_files = getDataFiles(paths.concat(opt.basePath,opt.test_data), opt.basePath) --filter out non-existent scenes print('#train files = ' .. #train_files) print('#test files = ' .. #test_files) -- config logging testLogger = optim.Logger(paths.concat(opt.save, 'test.log')) testLogger:setNames{'epoch', 'iteration', 'current train loss', 'avg train loss'} do local optfile = assert(io.open(paths.concat(opt.save, 'options.txt'), 'w')) local cur = io.output() io.output(optfile) serialize(opt) serialize(train_files) serialize(test_files) io.output(cur) optfile:close() end local patchSize = opt.patchSize local saveInterval = 1000 ------------------------------------ -- Training routine -- function train() model:training() epoch = epoch or 1 -- if epoch not defined, assign it as 1 print('epoch ' .. epoch) --if epoch % opt.epoch_step == 0 then optimState.learningRate = optimState.learningRate/2 end --load in the train data (positive and negative matches) local poss, negs = loadMatchFiles(opt.basePath, train_files, patchSize/2, opt.matchFileSkip) print(#poss) --print(poss) --print(negs) --local tic = torch.tic() local filesize = #poss local indices = torch.randperm(filesize):long():split(opt.batchSize) -- remove last mini-batch so that all the batches have equal size indices[#indices] = nil --print(indices) collectgarbage() --pre-allocate memory local inputs_anc = torch.zeros(opt.batchSize, 3, 224, 224):cuda() local inputs_pos = torch.zeros(opt.batchSize, 3, 224, 224):cuda() local inputs_neg = torch.zeros(opt.batchSize, 3, 224, 224):cuda() local totalloss = 0 local indices = torch.randperm(#poss) local numIters = math.floor(#poss/opt.batchSize) for trainIter = 1,numIters do -- print progress bar :D xlua.progress(trainIter, numIters) for k = 1,opt.batchSize do --create a mini batch local idx = indices[k] local sceneName = poss[idx][1] local imgPath = paths.concat(opt.basePath,sceneName,'images') local anc,pos,neg = getTrainingExampleTriplet(imgPath, poss[idx][2], poss[idx][3], negs[idx][3], patchSize) inputs_anc[{k,{},{},{}}]:copy(pos) --match inputs_pos[{k,{},{},{}}]:copy(anc) --anchor inputs_neg[{k,{},{},{}}]:copy(neg) --non-match end -- a function that takes single input and return f(x) and df/dx local curLoss = -1 local feval = function(x) if x ~= parameters then parameters:copy(x) end gradParameters:zero() -- Forward and backward pass local inputs = {inputs_pos, inputs_anc, inputs_neg} local output = model:forward(inputs) local loss = criterion:forward(output) --print('Training iteration '..trainIter..': '..loss) curLoss = loss totalloss = totalloss + loss local dLoss = criterion:backward(output) model:backward(inputs,dLoss) return loss,gradParameters end config = {learningRate = 0.001,momentum = 0.99} optim.sgd(feval, parameters, config) if testLogger then paths.mkdir(opt.save) testLogger:add{tostring(epoch), tostring(trainIter), curLoss, totalloss / trainIter} testLogger:style{'-','-','-','-'} end if trainIter > 0 and (trainIter % saveInterval == 0 or trainIter == #indices) then local filename = paths.concat(opt.save, 'model_' .. tostring(epoch) .. '-' .. tostring(trainIter) .. '.net') print('==> saving model to '..filename) torch.save(filename, model:clearState()) end end epoch = epoch + 1 end ------------------------------------- -- Test routine -- function test() --[[model:evaluate() for fn = 1, #test_files do local pos,anc,neg = loadDataFile(train_files[train_file_indices[fn]) local filesize = (#current_data)[1] local indices = torch.randperm(filesize):long():split(opt.batchSize) for t, v in ipairs(indices) do local inputs = { pos:index(1,v):cuda(), anc:index(1,v):cuda(), neg:index(1,v):cuda() } local outputs = model:forward(inputs) local loss = criterion:forward(output) end end --TODO PRINT TEST LOSS/ACCURACY if testLogger then paths.mkdir(opt.save) testLogger:add{train_acc, confusion.totalValid * 100} testLogger:style{'-','-'} end --]] -- save model every 10 epochs if epoch % 10 == 0 then local filename = paths.concat(opt.save, 'model_' ..tostring(epoch) .. '.net') print('==> saving model to '..filename) torch.save(filename, model:clearState()) end end ----------------------------------------- -- Start training -- for i = 1,opt.max_epoch do train() --test() end
require 'image' require 'cutorch' require 'cunn' require 'cudnn' require 'optim' -- Custom files require 'model' require 'sys' -- require 'qtwidget' -- for visualizing images dofile('util.lua') opt_string = [[ -h,--help print help -s,--save (default "logs") subdirectory to save logs -b,--batchSize (default 8) batch size -g,--gpu_index (default 0) GPU index (start from 0) --max_epoch (default 10) maximum number of epochs --basePath (default "/mnt/raid/datasets/Matterport/Matching1/") base path for train/test data --train_data (default "scenes_trainval.txt") txt file containing train --test_data (default "scenes_test.txt") txt file containing test --patchSize (default 64) patch size to extract (resized to 224) --matchFileSkip (default 10) only use every skip^th keypoint match in file ]] opt = lapp(opt_string) -- print help or chosen options if opt.help == true then print('Usage: th train.lua') print('Options:') print(opt_string) os.exit() else print(opt) end -- set gpu cutorch.setDevice(opt.gpu_index+1) -- Set RNG seed --math.randomseed(os.time()) math.randomseed(0) torch.manualSeed(0) -- Load model and criterion model,criterion = getModel() model = model:cuda() critrerion = criterion:cuda() model:zeroGradParameters() parameters, gradParameters = model:getParameters() --print(model) -- Construct window for visualizing training examples -- visWindow = qtwidget.newwindow(1792,672) -- load training and testing files train_files = getDataFiles(paths.concat(opt.basePath,opt.train_data), opt.basePath) --filter out non-existent scenes test_files = getDataFiles(paths.concat(opt.basePath,opt.test_data), opt.basePath) --filter out non-existent scenes print('#train files = ' .. #train_files) print('#test files = ' .. #test_files) -- config logging testLogger = optim.Logger(paths.concat(opt.save, 'test.log')) testLogger:setNames{'epoch', 'iteration', 'current train loss', 'avg train loss'} do local optfile = assert(io.open(paths.concat(opt.save, 'options.txt'), 'w')) local cur = io.output() io.output(optfile) serialize(opt) serialize(train_files) serialize(test_files) io.output(cur) optfile:close() end local patchSize = opt.patchSize local saveInterval = 1000 ------------------------------------ -- Training routine -- function train() model:training() epoch = epoch or 1 -- if epoch not defined, assign it as 1 print('epoch ' .. epoch) --if epoch % opt.epoch_step == 0 then optimState.learningRate = optimState.learningRate/2 end --load in the train data (positive and negative matches) local poss, negs = loadMatchFiles(opt.basePath, train_files, patchSize/2, opt.matchFileSkip) print(#poss) --print(poss) --print(negs) collectgarbage() --pre-allocate memory local inputs_anc = torch.zeros(opt.batchSize, 3, 224, 224):cuda() local inputs_pos = torch.zeros(opt.batchSize, 3, 224, 224):cuda() local inputs_neg = torch.zeros(opt.batchSize, 3, 224, 224):cuda() local totalloss = 0 local indices = torch.randperm(#poss) local numIters = math.floor(#poss/opt.batchSize) for iter = 1,#poss,opt.batchSize do -- print progress bar :D local trainIter = (iter-1)/opt.batchSize+1 xlua.progress(trainIter, numIters) for k = iter,iter+opt.batchSize-1 do --create a mini batch local idx = indices[k] local sceneName = poss[idx][1] local imgPath = paths.concat(opt.basePath,sceneName,'images') local anc,pos,neg = getTrainingExampleTriplet(imgPath, poss[idx][2], poss[idx][3], negs[idx][3], patchSize) --pos = torch.add(anc, torch.rand(3, 224, 224):float() * 0.1) inputs_anc[{k-iter+1,{},{},{}}]:copy(pos) --match inputs_pos[{k-iter+1,{},{},{}}]:copy(anc) --anchor inputs_neg[{k-iter+1,{},{},{}}]:copy(neg) --non-match end -- a function that takes single input and return f(x) and df/dx local curLoss = -1 local feval = function(x) if x ~= parameters then parameters:copy(x) end gradParameters:zero() -- Forward and backward pass local inputs = {inputs_pos, inputs_anc, inputs_neg} local output = model:forward(inputs) local loss = criterion:forward(output) --print('Training iteration '..trainIter..': '..loss) local dLoss = criterion:backward(output) model:backward(inputs,dLoss) curLoss = loss totalloss = totalloss + loss return loss,gradParameters end config = {learningRate = 0.001,momentum = 0.99} optim.sgd(feval, parameters, config) if testLogger then paths.mkdir(opt.save) testLogger:add{tostring(epoch), tostring(trainIter), curLoss, totalloss / trainIter} testLogger:style{'-','-','-','-'} end if trainIter > 0 and (trainIter % saveInterval == 0 or trainIter == #indices) then local filename = paths.concat(opt.save, 'model_' .. tostring(epoch) .. '-' .. tostring(trainIter) .. '.net') print('==> saving model to '..filename) torch.save(filename, model:clearState()) end end epoch = epoch + 1 end ------------------------------------- -- Test routine -- function test() --[[model:evaluate() for fn = 1, #test_files do local pos,anc,neg = loadDataFile(train_files[train_file_indices[fn]) local filesize = (#current_data)[1] local indices = torch.randperm(filesize):long():split(opt.batchSize) for t, v in ipairs(indices) do local inputs = { pos:index(1,v):cuda(), anc:index(1,v):cuda(), neg:index(1,v):cuda() } local outputs = model:forward(inputs) local loss = criterion:forward(output) end end --TODO PRINT TEST LOSS/ACCURACY if testLogger then paths.mkdir(opt.save) testLogger:add{train_acc, confusion.totalValid * 100} testLogger:style{'-','-'} end --]] -- save model every 10 epochs if epoch % 10 == 0 then local filename = paths.concat(opt.save, 'model_' ..tostring(epoch) .. '.net') print('==> saving model to '..filename) torch.save(filename, model:clearState()) end end ----------------------------------------- -- Start training -- for i = 1,opt.max_epoch do train() --test() end
actual indexing bug fix
actual indexing bug fix
Lua
mit
niessner/Matterport,niessner/Matterport,niessner/Matterport
30c823889015f03f490cdfdbd3022078b74d89d1
himan-scripts/nwcsaf-cumulus.lua
himan-scripts/nwcsaf-cumulus.lua
--[[ // Effective cloudinessin fiksausta // Leila&Anniina versio 09/06/22 // Korjaa NWCSAF effective cloudiness pilvisyyttä huomioiden erityisesti: // 2: pienet selkeät alueet ns. "kohinaa" tms. // --> tutkitaan onko ympäröivät hilapisteet pilvisiä ja lisätään pilveä jos näin on // 3: konvektion aiheuttamat pilvet on 100% vaikka pitäisi olla vähemmän // --> ECWMF mallin lyhytaaltosäteilyn voimakkuuden perusteella vähentää pilvisyyttä, jos konvektiota // --> Lasketaan SWR max ("clearsky") arvon avulla "SWR kerroin" ja korjaus huomioidaan vain päviällä ]] local effc = luatool:FetchWithType(current_time, current_level, param("NWCSAF_EFFCLD-0TO1"), current_forecast_type) local mnwc_prod = producer(7, "MNWC") mnwc_prod:SetCentre(251) mnwc_prod:SetProcess(7) local mnwc_origintime = raw_time(radon:GetLatestTime(mnwc_prod, "", 0)) local mnwc_time = forecast_time(mnwc_origintime, current_time:GetValidDateTime()) local o = {forecast_time = mnwc_time, level = current_level, param = param("NH-0TO1"), forecast_type = current_forecast_type, producer = mnwc_prod, geom_name = "", read_previous_forecast_if_not_found = true } local nh = luatool:FetchWithArgs(o) o["param"] = param("NM-0TO1") local nm = luatool:FetchWithArgs(o) o["param"] = param("NL-0TO1") local nl = luatool:FetchWithArgs(o) local ecg_prod = producer(240, "ECGMTA") ecg_prod:SetCentre(86) ecg_prod:SetProcess(240) local ecg_origintime = raw_time(radon:GetLatestTime(ecg_prod, "", 0)) local ecg_validtime = current_time:GetValidDateTime() local minutes = ecg_validtime:String("%M") ecg_validtime:Adjust(HPTimeResolution.kMinuteResolution,-minutes) local ecg_time = forecast_time(ecg_origintime, ecg_validtime) o = {forecast_time = ecg_time, level = current_level, param = param("RADGLO-WM2"), forecast_type = current_forecast_type, producer = ecg_prod, geom_name = "", read_previous_forecast_if_not_found = true } local swr = luatool:FetchWithArgs(o) o["param"] = param("RADGLOC-WM2") local swrc = luatool:FetchWithArgs(o) if not effc or not nh or not nm or not nl or not swr or not swrc then logger:Error("Some data not found") return end local filter = matrix(3, 3, 1, missing) filter:Fill(1/9.) local Nmat = matrix(result:GetGrid():GetNi(), result:GetGrid():GetNj(), 1, 0) Nmat:SetValues(effc) local effc_p1 = Filter2D(Nmat, filter, configuration:GetUseCuda()):GetValues() local filter = matrix(7, 7, 1, missing) filter:Fill(1/49.) local effc_p2 = Filter2D(Nmat, filter, configuration:GetUseCuda()):GetValues() local morning = 7 -- utc, cumulus process is starting local evening = 17 -- utc, cumulus process is ending local hour = tonumber(current_time:GetValidDateTime():String("%H")) local is_day = false if hour >= morning and hour < evening then is_day = true end local res = {} for i=1,#effc do local effc_ = effc[i] local nl_ = nl[i] local nm_ = nm[i] local nh_ = nh[i] local swr_ = swr[i] local swrc_ = swrc[i] local effc_p1_ = effc_p1[i] local effc_p2_ = effc_p2[i] -- Vähennetään pilveä jos pääosin yläpilveä if effc_ > 0.5 and nh_ > 0.5 and nl_ < 0.2 and nm_ < 0.2 then effc_ = 0.5 end -- Keskiarvoistetaan mahdolliset pienet väärät aukot pois if effc_ <= 0.8 and effc_p2_ > 0.6 then effc_ = 0.8 end if effc_ <= 0.7 and effc_p1_ > 0.5 then effc_ = 0.7 end -- N=100% kumpupilvitilanteiden pilvisyyden vähennys-testaus -- Lasketaan pilvettömän taivaan max lyhytaaltosäteilyn ja EC:n lyhytaaltosäteilynsuhde local swr_rela = swr_ / swrc_ if is_day then if swr_rela >= 0.65 and effc_ > 0.8 then effc_ = 0.8 end if swr_rela >= 0.75 and effc_ > 0.5 then effc_ = 0.5 end end res[i] = effc_ end result:SetParam(param("NWCSAF_EFFCLD-0TO1")) result:SetValues(res) luatool:WriteToFile(result)
--[[ // Effective cloudinessin fiksausta // Leila&Anniina versio 09/06/22 // Korjaa NWCSAF effective cloudiness pilvisyyttä huomioiden erityisesti: // 2: pienet selkeät alueet ns. "kohinaa" tms. // --> tutkitaan onko ympäröivät hilapisteet pilvisiä ja lisätään pilveä jos näin on // 3: konvektion aiheuttamat pilvet on 100% vaikka pitäisi olla vähemmän // --> ECWMF mallin lyhytaaltosäteilyn voimakkuuden perusteella vähentää pilvisyyttä, jos konvektiota // --> Lasketaan SWR max ("clearsky") arvon avulla "SWR kerroin" ja korjaus huomioidaan vain päviällä ]] function Write(res) result:SetParam(param("NWCSAF_EFFCLD-0TO1")) result:SetValues(res) luatool:WriteToFile(result) end function CumulusFix() local effc = luatool:FetchWithType(current_time, current_level, param("NWCSAF_EFFCLD-0TO1"), current_forecast_type) local mnwc_prod = producer(7, "MNWC") mnwc_prod:SetCentre(251) mnwc_prod:SetProcess(7) local mnwc_origintime = raw_time(radon:GetLatestTime(mnwc_prod, "", 0)) local mnwc_time = forecast_time(mnwc_origintime, current_time:GetValidDateTime()) local o = {forecast_time = mnwc_time, level = current_level, param = param("NH-0TO1"), forecast_type = current_forecast_type, producer = mnwc_prod, geom_name = "", read_previous_forecast_if_not_found = true } local nh = luatool:FetchWithArgs(o) o["param"] = param("NM-0TO1") local nm = luatool:FetchWithArgs(o) o["param"] = param("NL-0TO1") local nl = luatool:FetchWithArgs(o) local ecg_prod = producer(240, "ECGMTA") ecg_prod:SetCentre(86) ecg_prod:SetProcess(240) local ecg_origintime = raw_time(radon:GetLatestTime(ecg_prod, "", 0)) local ecg_validtime = current_time:GetValidDateTime() local minutes = ecg_validtime:String("%M") ecg_validtime:Adjust(HPTimeResolution.kMinuteResolution,-minutes) local ecg_time = forecast_time(ecg_origintime, ecg_validtime) o = {forecast_time = ecg_time, level = current_level, param = param("RADGLO-WM2"), forecast_type = current_forecast_type, producer = ecg_prod, geom_name = "", read_previous_forecast_if_not_found = true } local swr = luatool:FetchWithArgs(o) o["param"] = param("RADGLOC-WM2") local swrc = luatool:FetchWithArgs(o) if not effc or not nh or not nm or not nl or not swr or not swrc then logger:Error("Some data not found") return end local filter = matrix(3, 3, 1, missing) filter:Fill(1/9.) local Nmat = matrix(result:GetGrid():GetNi(), result:GetGrid():GetNj(), 1, 0) Nmat:SetValues(effc) local effc_p1 = Filter2D(Nmat, filter, configuration:GetUseCuda()):GetValues() local filter = matrix(7, 7, 1, missing) filter:Fill(1/49.) local effc_p2 = Filter2D(Nmat, filter, configuration:GetUseCuda()):GetValues() local morning = 7 -- utc, cumulus process is starting local evening = 17 -- utc, cumulus process is ending local hour = tonumber(current_time:GetValidDateTime():String("%H")) local is_day = false if hour >= morning and hour < evening then is_day = true end local res = {} for i=1,#effc do local effc_ = effc[i] local nl_ = nl[i] local nm_ = nm[i] local nh_ = nh[i] local swr_ = swr[i] local swrc_ = swrc[i] local effc_p1_ = effc_p1[i] local effc_p2_ = effc_p2[i] -- Vähennetään pilveä jos pääosin yläpilveä if effc_ > 0.5 and nh_ > 0.5 and nl_ < 0.2 and nm_ < 0.2 then effc_ = 0.5 end -- Keskiarvoistetaan mahdolliset pienet väärät aukot pois if effc_ <= 0.8 and effc_p2_ > 0.6 then effc_ = 0.8 end if effc_ <= 0.7 and effc_p1_ > 0.5 then effc_ = 0.7 end -- N=100% kumpupilvitilanteiden pilvisyyden vähennys-testaus -- Lasketaan pilvettömän taivaan max lyhytaaltosäteilyn ja EC:n lyhytaaltosäteilynsuhde local swr_rela = swr_ / swrc_ if is_day then if swr_rela >= 0.65 and effc_ > 0.8 then effc_ = 0.8 end if swr_rela >= 0.75 and effc_ > 0.5 then effc_ = 0.5 end end res[i] = effc_ end Write(res) end local mon = tonumber(current_time:GetValidDateTime():String("%m")) -- Fix is valid for summer months April .. August if mon >= 4 and mon <= 8 then CumulusFix() end
Effective cloudiness Cumulus fix is valid for summer months
Effective cloudiness Cumulus fix is valid for summer months
Lua
mit
fmidev/himan,fmidev/himan,fmidev/himan
0fdf2aefea2b0e337abe78bbd9c8a4e2efe44146
src/Author.lua
src/Author.lua
--================================================================================================== -- Copyright (C) 2014 - 2015 by Robert Machmer = -- = -- Permission is hereby granted, free of charge, to any person obtaining a copy = -- of this software and associated documentation files (the "Software"), to deal = -- in the Software without restriction, including without limitation the rights = -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell = -- copies of the Software, and to permit persons to whom the Software is = -- furnished to do so, subject to the following conditions: = -- = -- The above copyright notice and this permission notice shall be included in = -- all copies or substantial portions of the Software. = -- = -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR = -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, = -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE = -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER = -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, = -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN = -- THE SOFTWARE. = --================================================================================================== local Author = {}; -- ------------------------------------------------ -- Constants -- ------------------------------------------------ local AVATAR_SIZE = 48; local AUTHOR_INACTIVITY_TIMER = 2; local LINK_INACTIVITY_TIMER = 2; local FADE_FACTOR = 2; local DEFAULT_AVATAR_ALPHA = 255; local DEFAULT_LINK_ALPHA = 50; local DEFAULT_DAMPING_VALUE = 0.5; local MIN_DISTANCE = 400; local BEAM_WIDTH = 3; -- ------------------------------------------------ -- Constructor -- ------------------------------------------------ function Author.new(name, avatar, cx, cy) local self = {}; local posX, posY = cx + love.math.random(5, 40) * (love.math.random(0, 1) == 0 and -1 or 1), cy + love.math.random(5, 40) * (love.math.random(0, 1) == 0 and -1 or 1); local accX, accY = 0, 0; local velX, velY = 0, 0; local links = {}; local inactivity = 0; local avatarAlpha = DEFAULT_AVATAR_ALPHA; local linkAlpha = DEFAULT_LINK_ALPHA; -- Avatar's width and height. local aw, ah = avatar:getWidth(), avatar:getHeight(); local dampingFactor = DEFAULT_DAMPING_VALUE; -- ------------------------------------------------ -- Private Functions -- ------------------------------------------------ local function reactivate() inactivity = 0; dampingFactor = DEFAULT_DAMPING_VALUE; avatarAlpha = DEFAULT_AVATAR_ALPHA; linkAlpha = DEFAULT_LINK_ALPHA; end local function move(dt) local dx, dy; local distance for i = 1, #links do local file = links[i]; -- Attract dx, dy = posX - file:getX(), posY - file:getY(); distance = math.sqrt(dx * dx + dy * dy); -- Normalise vector. dx = dx / distance; dy = dy / distance; -- Attraction. if distance > MIN_DISTANCE then accX = dx * -distance * 5; accY = dy * -distance * 5; end -- Repulsion. accX = accX + (dx * distance); accY = accY + (dy * distance); end -- Repel from the graph's center. dx, dy = posX - cx, posY - cy; distance = math.sqrt(dx * dx + dy * dy); dx = dx / distance; dy = dy / distance; accX = accX + (dx * distance); accY = accY + (dy * distance); accX = math.max(-4, math.min(accX, 4)); accY = math.max(-4, math.min(accY, 4)); velX = velX + accX * dt * 16; velY = velY + accY * dt * 16; posX = posX + velX; posY = posY + velY; velX = velX * dampingFactor; velY = velY * dampingFactor; end -- ------------------------------------------------ -- Public Functions -- ------------------------------------------------ function self:draw(rotation) for i = 1, #links do love.graphics.setColor(255, 255, 255, linkAlpha); love.graphics.setLineWidth(BEAM_WIDTH); love.graphics.line(posX, posY, links[i]:getX(), links[i]:getY()); love.graphics.setLineWidth(1); love.graphics.setColor(255, 255, 255, 255); end love.graphics.setColor(255, 255, 255, avatarAlpha); love.graphics.draw(avatar, posX, posY, -rotation, AVATAR_SIZE / aw, AVATAR_SIZE / ah, aw * 0.5, ah * 0.5); love.graphics.setColor(255, 255, 255, 255); end function self:update(dt) move(dt); inactivity = inactivity + dt; if inactivity > AUTHOR_INACTIVITY_TIMER then avatarAlpha = avatarAlpha - avatarAlpha * dt * FADE_FACTOR; end if inactivity > LINK_INACTIVITY_TIMER then linkAlpha = linkAlpha - linkAlpha * dt * FADE_FACTOR; end dampingFactor = math.max(0.01, dampingFactor - dt); end function self:addLink(file) reactivate(); links[#links + 1] = file; end function self:resetLinks() links = {}; end return self; end -- ------------------------------------------------ -- Return Module -- ------------------------------------------------ return Author;
--================================================================================================== -- Copyright (C) 2014 - 2015 by Robert Machmer = -- = -- Permission is hereby granted, free of charge, to any person obtaining a copy = -- of this software and associated documentation files (the "Software"), to deal = -- in the Software without restriction, including without limitation the rights = -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell = -- copies of the Software, and to permit persons to whom the Software is = -- furnished to do so, subject to the following conditions: = -- = -- The above copyright notice and this permission notice shall be included in = -- all copies or substantial portions of the Software. = -- = -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR = -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, = -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE = -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER = -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, = -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN = -- THE SOFTWARE. = --================================================================================================== local Author = {}; -- ------------------------------------------------ -- Constants -- ------------------------------------------------ local AVATAR_SIZE = 48; local AUTHOR_INACTIVITY_TIMER = 2; local LINK_INACTIVITY_TIMER = 2; local FADE_FACTOR = 2; local DEFAULT_AVATAR_ALPHA = 255; local DEFAULT_LINK_ALPHA = 50; local DAMPING_FACTOR = 0.90; local FORCE_MAX = 2; local FORCE_SPRING = -0.5; local BEAM_WIDTH = 3; -- ------------------------------------------------ -- Constructor -- ------------------------------------------------ function Author.new(name, avatar, cx, cy) local self = {}; local posX, posY = cx + love.math.random(5, 200) * (love.math.random(0, 1) == 0 and -1 or 1), cy + love.math.random(5, 200) * (love.math.random(0, 1) == 0 and -1 or 1); local accX, accY = 0, 0; local velX, velY = 0, 0; local links = {}; local inactivity = 0; local avatarAlpha = DEFAULT_AVATAR_ALPHA; local linkAlpha = DEFAULT_LINK_ALPHA; -- Avatar's width and height. local aw, ah = avatar:getWidth(), avatar:getHeight(); -- ------------------------------------------------ -- Private Functions -- ------------------------------------------------ local function clamp(min, val, max) return math.max(min, math.min(val, max)); end local function reactivate() inactivity = 0; avatarAlpha = DEFAULT_AVATAR_ALPHA; linkAlpha = DEFAULT_LINK_ALPHA; end local function move(dt) velX = (velX + accX * dt * 32) * DAMPING_FACTOR; velY = (velY + accY * dt * 32) * DAMPING_FACTOR; posX = posX + velX; posY = posY + velY; end local function applyForce(fx, fy) accX = clamp(-FORCE_MAX, accX + fx, FORCE_MAX); accY = clamp(-FORCE_MAX, accY + fy, FORCE_MAX); end -- ------------------------------------------------ -- Public Functions -- ------------------------------------------------ function self:draw(rotation) for i = 1, #links do love.graphics.setColor(255, 255, 255, linkAlpha); love.graphics.setLineWidth(BEAM_WIDTH); love.graphics.line(posX, posY, links[i]:getX(), links[i]:getY()); love.graphics.setLineWidth(1); love.graphics.setColor(255, 255, 255, 255); end love.graphics.setColor(255, 255, 255, avatarAlpha); love.graphics.draw(avatar, posX, posY, -rotation, AVATAR_SIZE / aw, AVATAR_SIZE / ah, aw * 0.5, ah * 0.5); love.graphics.setColor(255, 255, 255, 255); end function self:update(dt) move(dt); inactivity = inactivity + dt; if inactivity > AUTHOR_INACTIVITY_TIMER then avatarAlpha = avatarAlpha - avatarAlpha * dt * FADE_FACTOR; end if inactivity > LINK_INACTIVITY_TIMER then linkAlpha = linkAlpha - linkAlpha * dt * FADE_FACTOR; end if inactivity > 0.5 then accX, accY = 0, 0; end end function self:addLink(file) reactivate(); links[#links + 1] = file; local dx, dy = posX - file:getX(), posY - file:getY(); local distance = math.sqrt(dx * dx + dy * dy); dx = dx / distance; dy = dy / distance; local strength = FORCE_SPRING * distance; applyForce(dx * strength, dy * strength); end function self:resetLinks() links = {}; end return self; end -- ------------------------------------------------ -- Return Module -- ------------------------------------------------ return Author;
Fix #5 - Improve author movement by applying just a spring force
Fix #5 - Improve author movement by applying just a spring force Rewrote most of the movement related code in the author class. Similar to the nodes in the graph it now uses a spring force to attract authors towards nodes. Authors aren't moving away too far from the graph anymore (except for in some rare cases). The movement is more fluent than before and authors move towards the parts of the graph they currently work on.
Lua
mit
rm-code/logivi
ee478bd93aba5299e1f9b0f52be06dc9626539c2
src/daemon.lua
src/daemon.lua
local c = require "systemd.daemon.core" -- Wrap notify functions with versions that take tables -- this lets you write `notifyt { READY=1, STATE="awesome!" }` local function pack_state(t) local state = { } for k, v in pairs(t) do state[#state+1] = k.."="..v end return table.concat(state, "\n") end local function wrap_notifier(func) return function(t) return func(false, pack_state(t)) end end c.notifyt = wrap_notifier(c.notify) c.pid_notifyt = wrap_notifier(c.pid_notify) -- Get our own pid in pure lua. local function get_pid() local fd, err, n = io.open "/proc/self/stat" if fd == nil then return nil, err, n end local pid = fd:read "*n" fd:close() return pid end -- sd_watchdog_enabled in pure lua. -- returns watchdog interval function c.watchdog_enabled(unset_environment) if unset_environment then error("unset not supported", 2) end local pid = os.getenv "WATCHDOG_PID" if not pid then return false end pid = tonumber(pid) if pid ~= get_pid() then return false end local usec = os.getenv "WATCHDOG_USEC" usec = tonumber(usec) if usec == nil then return nil, "invalid interval" end return usec/1e6 end function c.kick_dog() return c.notify(false, "WATCHDOG=1") end return c
local c = require "systemd.daemon.core" -- Wrap notify functions with versions that take tables -- this lets you write `notifyt { READY=1, STATE="awesome!" }` local function pack_state(t) local state = { } for k, v in pairs(t) do state[#state+1] = k.."="..v end return table.concat(state, "\n") end function c.notifyt(t) return c.notify(false, pack_state(t)) end function c.pid_notifyt(pid, t) return c.pid_notify(pid, false, pack_state(t)) end -- Get our own pid in pure lua. local function get_pid() local fd, err, n = io.open "/proc/self/stat" if fd == nil then return nil, err, n end local pid = fd:read "*n" fd:close() return pid end -- sd_watchdog_enabled in pure lua. -- returns watchdog interval function c.watchdog_enabled(unset_environment) if unset_environment then error("unset not supported", 2) end local pid = os.getenv "WATCHDOG_PID" if not pid then return false end pid = tonumber(pid) if pid ~= get_pid() then return false end local usec = os.getenv "WATCHDOG_USEC" usec = tonumber(usec) if usec == nil then return nil, "invalid interval" end return usec/1e6 end function c.kick_dog() return c.notify(false, "WATCHDOG=1") end return c
src/daemon.lua: Fix pid_notifyt to pass the pid
src/daemon.lua: Fix pid_notifyt to pass the pid
Lua
mit
daurnimator/lua-systemd
6b4978d0d3bf6df241ea71363ac0771f35133c71
kong/db/schema/plugin_loader.lua
kong/db/schema/plugin_loader.lua
local MetaSchema = require "kong.db.schema.metaschema" local socket_url = require "socket.url" local typedefs = require "kong.db.schema.typedefs" local Entity = require "kong.db.schema.entity" local utils = require "kong.tools.utils" local plugin_servers = require "kong.runloop.plugin_servers" local plugin_loader = {} local fmt = string.format local next = next local type = type local insert = table.insert local ipairs = ipairs --- Check if a string is a parseable URL. -- @param v input string string -- @return boolean indicating whether string is an URL. local function validate_url(v) if v and type(v) == "string" then local url = socket_url.parse(v) if url and not url.path then url.path = "/" end return not not (url and url.path and url.host and url.scheme) end end --- Read a plugin schema table in the old-DAO format and produce a -- best-effort translation of it into a plugin subschema in the new-DAO format. -- @param name a string with the schema name. -- @param old_schema the old-format schema table. -- @return a table with a new-format plugin subschema; or nil and a message. local function convert_legacy_schema(name, old_schema) local new_schema = { name = name, fields = { { config = { type = "record", required = true, fields = {} }} }, entity_checks = old_schema.entity_checks, } for old_fname, old_fdata in pairs(old_schema.fields) do local new_fdata = {} local new_field = { [old_fname] = new_fdata } local elements = {} for k, v in pairs(old_fdata) do if k == "type" then if v == "url" then new_fdata.type = "string" new_fdata.custom_validator = validate_url elseif v == "table" then if old_fdata.schema and old_fdata.schema.flexible then new_fdata.type = "map" else new_fdata.type = "record" new_fdata.required = true end elseif v == "array" then new_fdata.type = "array" elements.type = "string" -- FIXME stored as JSON in old db elseif v == "timestamp" then new_fdata = typedefs.timestamp elseif v == "string" then new_fdata.type = v new_fdata.len_min = 0 elseif v == "number" or v == "boolean" then new_fdata.type = v else return nil, "unkown legacy field type: " .. v end elseif k == "schema" then local rfields, err = convert_legacy_schema("fields", v) if err then return nil, err end rfields = rfields.fields[1].config.fields if v.flexible then new_fdata.keys = { type = "string" } new_fdata.values = { type = "record", required = true, fields = rfields, } else new_fdata.fields = rfields local rdefault = {} local has_default = false for _, field in ipairs(rfields) do local fname = next(field) local fdata = field[fname] if fdata.default then rdefault[fname] = fdata.default has_default = true end end if has_default then new_fdata.default = rdefault end end elseif k == "immutable" then -- FIXME really ignore? kong.log.debug("ignoring 'immutable' property") elseif k == "enum" then if old_fdata.type == "array" then elements.one_of = v else new_fdata.one_of = v end elseif k == "default" or k == "required" or k == "unique" then new_fdata[k] = v elseif k == "func" then -- FIXME some should become custom validators, some entity checks new_fdata.custom_validator = nil -- v elseif k == "new_type" then new_field[old_fname] = v break else return nil, "unknown legacy field attribute: " .. require"inspect"(k) end end if new_fdata.type == "array" then new_fdata.elements = elements end if (new_fdata.type == "map" and new_fdata.keys == nil) or (new_fdata.type == "record" and new_fdata.fields == nil) then new_fdata.type = "map" new_fdata.keys = { type = "string" } new_fdata.values = { type = "string" } end if new_fdata.type == nil then new_fdata.type = "string" end insert(new_schema.fields[1].config.fields, new_field) end if old_schema.no_route then insert(new_schema.fields, { route = typedefs.no_route }) end if old_schema.no_service then insert(new_schema.fields, { service = typedefs.no_service }) end if old_schema.no_consumer then insert(new_schema.fields, { consumer = typedefs.no_consumer }) end return new_schema end function plugin_loader.load_subschema(parent_schema, plugin, errors) local plugin_schema = "kong.plugins." .. plugin .. ".schema" local ok, schema = utils.load_module_if_exists(plugin_schema) if not ok then ok, schema = plugin_servers.load_schema(plugin) end if not ok then return nil, "no configuration schema found for plugin: " .. plugin end local err local is_legacy = false if not schema.name then is_legacy = true schema, err = convert_legacy_schema(plugin, schema) end if not err then local err_t ok, err_t = MetaSchema.MetaSubSchema:validate(schema) if not ok then err = tostring(errors:schema_violation(err_t)) end end if err then if is_legacy then err = "failed converting legacy schema for " .. plugin .. ": " .. err end return nil, err end ok, err = Entity.new_subschema(parent_schema, plugin, schema) if not ok then return nil, "error initializing schema for plugin: " .. err end return schema end function plugin_loader.load_entity_schema(plugin, schema_def, errors) local _, err_t = MetaSchema:validate(schema_def) if err_t then return nil, fmt("schema of custom plugin entity '%s.%s' is invalid: %s", plugin, schema_def.name, tostring(errors:schema_violation(err_t))) end local schema, err = Entity.new(schema_def) if err then return nil, fmt("schema of custom plugin entity '%s.%s' is invalid: %s", plugin, schema_def.name, err) end return schema end function plugin_loader.load_entities(plugin, errors, loader_fn) local has_daos, daos_schemas = utils.load_module_if_exists("kong.plugins." .. plugin .. ".daos") if not has_daos then return {} end local iterator = daos_schemas[1] and ipairs or pairs local res = {} for name, schema_def in iterator(daos_schemas) do if name ~= "tables" and schema_def.name then local ret, err = loader_fn(plugin, schema_def, errors) if err then return nil, err end res[schema_def.name] = ret end end return res end return plugin_loader
local MetaSchema = require "kong.db.schema.metaschema" local socket_url = require "socket.url" local typedefs = require "kong.db.schema.typedefs" local Entity = require "kong.db.schema.entity" local utils = require "kong.tools.utils" local plugin_servers = require "kong.runloop.plugin_servers" local plugin_loader = {} local fmt = string.format local next = next local type = type local insert = table.insert local ipairs = ipairs --- Check if a string is a parseable URL. -- @param v input string string -- @return boolean indicating whether string is an URL. local function validate_url(v) if v and type(v) == "string" then local url = socket_url.parse(v) if url and not url.path then url.path = "/" end return not not (url and url.path and url.host and url.scheme) end end --- Read a plugin schema table in the old-DAO format and produce a -- best-effort translation of it into a plugin subschema in the new-DAO format. -- @param name a string with the schema name. -- @param old_schema the old-format schema table. -- @return a table with a new-format plugin subschema; or nil and a message. local function convert_legacy_schema(name, old_schema) local new_schema = { name = name, fields = { { config = { type = "record", required = true, fields = {} }} }, entity_checks = old_schema.entity_checks, } for old_fname, old_fdata in pairs(old_schema.fields) do local new_fdata = {} local new_field = { [old_fname] = new_fdata } local elements = {} for k, v in pairs(old_fdata) do if k == "type" then if v == "url" then new_fdata.type = "string" new_fdata.custom_validator = validate_url elseif v == "table" then if old_fdata.schema and old_fdata.schema.flexible then new_fdata.type = "map" else new_fdata.type = "record" if new_fdata.required == nil then new_fdata.required = true end end elseif v == "array" then new_fdata.type = "array" elements.type = "string" -- FIXME stored as JSON in old db elseif v == "timestamp" then new_fdata = typedefs.timestamp elseif v == "string" then new_fdata.type = v new_fdata.len_min = 0 elseif v == "number" or v == "boolean" then new_fdata.type = v else return nil, "unkown legacy field type: " .. v end elseif k == "schema" then local rfields, err = convert_legacy_schema("fields", v) if err then return nil, err end rfields = rfields.fields[1].config.fields if v.flexible then new_fdata.keys = { type = "string" } new_fdata.values = { type = "record", required = true, fields = rfields, } else new_fdata.fields = rfields local rdefault = {} local has_default = false for _, field in ipairs(rfields) do local fname = next(field) local fdata = field[fname] if fdata.default then rdefault[fname] = fdata.default has_default = true end end if has_default then new_fdata.default = rdefault end end elseif k == "immutable" then -- FIXME really ignore? kong.log.debug("ignoring 'immutable' property") elseif k == "enum" then if old_fdata.type == "array" then elements.one_of = v else new_fdata.one_of = v end elseif k == "default" or k == "required" or k == "unique" then new_fdata[k] = v elseif k == "func" then -- FIXME some should become custom validators, some entity checks new_fdata.custom_validator = nil -- v elseif k == "new_type" then new_field[old_fname] = v break else return nil, "unknown legacy field attribute: " .. require"inspect"(k) end end if new_fdata.type == "array" then new_fdata.elements = elements end if (new_fdata.type == "map" and new_fdata.keys == nil) or (new_fdata.type == "record" and new_fdata.fields == nil) then new_fdata.type = "map" new_fdata.keys = { type = "string" } new_fdata.values = { type = "string" } end if new_fdata.type == nil then new_fdata.type = "string" end insert(new_schema.fields[1].config.fields, new_field) end if old_schema.no_route then insert(new_schema.fields, { route = typedefs.no_route }) end if old_schema.no_service then insert(new_schema.fields, { service = typedefs.no_service }) end if old_schema.no_consumer then insert(new_schema.fields, { consumer = typedefs.no_consumer }) end return new_schema end function plugin_loader.load_subschema(parent_schema, plugin, errors) local plugin_schema = "kong.plugins." .. plugin .. ".schema" local ok, schema = utils.load_module_if_exists(plugin_schema) if not ok then ok, schema = plugin_servers.load_schema(plugin) end if not ok then return nil, "no configuration schema found for plugin: " .. plugin end local err local is_legacy = false if not schema.name then is_legacy = true schema, err = convert_legacy_schema(plugin, schema) end if not err then local err_t ok, err_t = MetaSchema.MetaSubSchema:validate(schema) if not ok then err = tostring(errors:schema_violation(err_t)) end end if err then if is_legacy then err = "failed converting legacy schema for " .. plugin .. ": " .. err end return nil, err end ok, err = Entity.new_subschema(parent_schema, plugin, schema) if not ok then return nil, "error initializing schema for plugin: " .. err end return schema end function plugin_loader.load_entity_schema(plugin, schema_def, errors) local _, err_t = MetaSchema:validate(schema_def) if err_t then return nil, fmt("schema of custom plugin entity '%s.%s' is invalid: %s", plugin, schema_def.name, tostring(errors:schema_violation(err_t))) end local schema, err = Entity.new(schema_def) if err then return nil, fmt("schema of custom plugin entity '%s.%s' is invalid: %s", plugin, schema_def.name, err) end return schema end function plugin_loader.load_entities(plugin, errors, loader_fn) local has_daos, daos_schemas = utils.load_module_if_exists("kong.plugins." .. plugin .. ".daos") if not has_daos then return {} end local iterator = daos_schemas[1] and ipairs or pairs local res = {} for name, schema_def in iterator(daos_schemas) do if name ~= "tables" and schema_def.name then local ret, err = loader_fn(plugin, schema_def, errors) if err then return nil, err end res[schema_def.name] = ret end end return res end return plugin_loader
fix(db) old schema conversion with default value
fix(db) old schema conversion with default value ### Summary Depending on iteration order the `required` parameter may have been forcefully overwritten with a value of `true`, which may have turned the `required=false` to actually `true` with old schema conversion.
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
752deede2b3f6dfc79bf9f43df552adfeb8feee0
lua/String.lua
lua/String.lua
local squote = "'" local dquote = '"' local function chartopad(c) return string.format("\\%03d", string.byte(c)) end local pads = { z = "\\z", x = "\\x", ['0'] = '\\0', ['1'] = '\\1', ['2'] = '\\2', ['3'] = '\\3', ['4'] = '\\4', ['5'] = '\\5', ['6'] = '\\6', ['7'] = '\\7', ['8'] = '\\8', ['9'] = '\\9', -- remap escape sequences a = chartopad('\a'), b = chartopad('\b'), f = chartopad('\f'), r = chartopad('\r'), n = chartopad('\n'), t = chartopad('\t'), v = chartopad('\v'), ['"'] = chartopad('\"'), ["'"] = chartopad('\''), ['\\'] = chartopad('\\') } local numbers = { ['0'] = true, ['1'] = true, ['2'] = true, ['3'] = true, ['4'] = true, ['5'] = true, ['6'] = true, ['7'] = true, ['8'] = true, ['9'] = true } setmetatable(pads, { __index = function(t,k) error("invalid escape sequence near '\\" .. k .. "'", 3) end }) local findpairs do local function _findnext(flags, index) -- only branch if index = 0 if index > 0 then -- this should always give a match, -- as we're starting from the same index as the returned match -- TODO: test %f >.> local x,y = string.find(flags[1], flags[2], index, flags[3]) return string.find(flags[1], flags[2], y+1, flags[3]) else return string.find(flags[1], flags[2], index + 1, flags[3]) end end function findpairs(str, pat, raw) return _findnext, {str, pat, raw}, 0 end end -- Parse a string like it's a Lua 5.2 string. local function parseString52(s) -- "validate" string local startChar = string.sub(s,1,1) assert(startChar==squote or startChar==dquote, "not a string") assert(string.sub(s, -1, -1) == startChar, "unfinished string") -- remove quotes local str = string.sub(s, 2, -2) -- replace "normal" escapes with a padded escape str = string.gsub(str, "\\(.)", pads) -- check for non-escaped startChar assert(not string.find(str, startChar), "unfinished string") -- pad numerical escapes str = string.gsub(str, "\\([0-9])(.?)(.?)", function(a, b, c) local x = a -- swap b and c if #b == 0; this is to avoid UB: -- _in theory_ `c` could match but not `b`, this solves -- that problem. uncomment if you know what you're doing. if #b == 0 then b, c = c, b end if numbers[b] then x, b = x .. b, "" if numbers[c] then x, c = x .. c, "" end end local temp1 = ("0"):rep(3 - #x) return "\\" .. temp1 .. x .. b .. c end) local t = {} local i = 1 local last = 1 -- split on \z -- we can look for "\z" directly because we already escaped everything else for from, to in findpairs(str, "\\z", true) do t[i] = string.sub(str, last, from - 1) last = to+1 i = i + 1 end t[i] = string.sub(str, last) -- parse results local nt = {} for x,y in ipairs(t) do nt[x] = string.gsub(y, "\\(([x0-9])((.).))", function(a,b,c,d) if b ~= "x" then local n = tonumber(a) assert(n < 256, "decimal escape too large near '\\" .. a .. "'") return string.char(n) else local n = tonumber(c, 16) assert(n, "hexadecimal digit expected near '\\x" .. c .. "'") return string.char(n) end end) if x > 1 then -- handle \z nt[x] = string.gsub(nt[x], "^[%s]*", "") end end -- merge return table.concat(nt, "") end -- "tests" -- TODO add more -- also add automatic checks if _VERSION == "Lua 5.2" and not ... then local t = { [=["\""]=], [=["""]=], [=["v""]=], [=[""/"]=], [=["\v"/"]=], [=["\m"]=], [=["\32"]=], } for _, str in ipairs(t) do local s, m = pcall(parseString52, str) io.write(tostring(s and m or "nil")) io.write(tostring(s and "" or ("\t" .. m)) .. "\n") s, m = load("return " .. str, "@/home/soniex2/git/github/Stuff/lua/String.lua:") io.write(tostring(s and s())) io.write(tostring(m and "\t"..m or "") .. "\n") end elseif not ... then print("Tests require Lua 5.2") end return { parse52 = parseString52, findpairs = findpairs, }
-- workarounds for IDE bugs local squote = "'" local dquote = '"' local backslash = "\\" local function chartopad(c) return string.format("\\%03d", string.byte(c)) end local pads = { z = "\\z", x = "\\x", ['0'] = '\\0', ['1'] = '\\1', ['2'] = '\\2', ['3'] = '\\3', ['4'] = '\\4', ['5'] = '\\5', ['6'] = '\\6', ['7'] = '\\7', ['8'] = '\\8', ['9'] = '\\9', -- remap escape sequences a = chartopad('\a'), b = chartopad('\b'), f = chartopad('\f'), r = chartopad('\r'), n = chartopad('\n'), t = chartopad('\t'), v = chartopad('\v'), [ dquote ] = chartopad(dquote), [ squote ] = chartopad(squote), [ backslash ] = chartopad(backslash), ['\n'] = chartopad('\n') } local numbers = { ['0'] = true, ['1'] = true, ['2'] = true, ['3'] = true, ['4'] = true, ['5'] = true, ['6'] = true, ['7'] = true, ['8'] = true, ['9'] = true } local findpairs do local function _findnext(flags, index) -- only branch if index = 0 if index > 0 then -- this should always give a match, -- as we're starting from the same index as the returned match -- TODO: test %f >.> local x,y = string.find(flags[1], flags[2], index, flags[3]) return string.find(flags[1], flags[2], y+1, flags[3]) else return string.find(flags[1], flags[2], index + 1, flags[3]) end end function findpairs(str, pat, raw) return _findnext, {str, pat, raw}, 0 end end local function getline(str, pos) -- remove everything that's not a newline then count the newlines + 1 return #(string.gsub(string.sub(str, 1, pos - 1), "[^\n]", "")) + 1 end -- Parse a string like it's a Lua 5.2 string. local function parseString52(s) -- "validate" string local startChar = string.sub(s,1,1) if startChar~=squote and startChar~=dquote then error("not a string", 0) end if string.sub(s, -1, -1) ~= startChar then error(("[%s]:%d: unfinished string"):format(s, getline(s, -1)), 0) end -- remove quotes local str = string.sub(s, 2, -2) -- replace "normal" escapes with a padded escape str = string.gsub(str, "()\\(.)", function(idx,c) return pads[c] or error(("[%s]:%d: invalid escape sequence near '\\%s'"):format(s, getline(s, idx), c), 0) end) -- check for non-escaped startChar if string.find(str, startChar) then error(("[%s]:%d: unfinished string"):format(s, getline(s, -1)), 0) end -- pad numerical escapes str = string.gsub(str, "\\([0-9])(.?)(.?)", function(a, b, c) local x = a -- swap b and c if #b == 0; this is to avoid UB: -- _in theory_ `c` could match but not `b`, this solves -- that problem. uncomment if you know what you're doing. if #b == 0 then b, c = c, b end if numbers[b] then x, b = x .. b, "" if numbers[c] then x, c = x .. c, "" end end return backslash .. ("0"):rep(3 - #x) .. x .. b .. c end) local t = {} local i = 1 local last = 1 -- split on \z -- we can look for "\z" directly because we already escaped everything else for from, to in findpairs(str, "\\z", true) do t[i] = string.sub(str, last, from - 1) last = to+1 i = i + 1 end t[i] = string.sub(str, last) -- parse results local nt = {} for x,y in ipairs(t) do nt[x] = string.gsub(y, "()\\(([x0-9])((.).))", function(idx,a,b,c,d) if b ~= "x" then local n = tonumber(a) if n >= 256 then error(("[%s]:%d: decimal escape too large near '\\%s'"):format(s,getline(s,idx),a), 0) end return string.char(n) else local n = tonumber(c, 16) if n then return string.char(n) end local o = d:find("[0-9a-fA-F]") and c or d error(("[%s]:%d: hexadecimal digit expected near '\\x%s'"):format(s,getline(s,idx),o), 0) end end) if x > 1 then -- handle \z nt[x] = string.gsub(nt[x], "^[%s]*", "") end end -- merge return table.concat(nt, "") end -- "tests" -- TODO add more -- also add automatic checks if _VERSION == "Lua 5.2" and not ... then -- test string parsing local t = { [=["\""]=], [=["\32"]=], [=["\256"]=], [=["\xnn"]=], '"\\\n"', } for _, str in ipairs(t) do local s, m = pcall(parseString52, str) io.write(tostring(s and ("[" .. m .. "]") or "nil")) io.write(tostring(s and "" or ("\t" .. m)) .. "\n") s, m = load("return " .. str, "=[" .. str .. "]") io.write(tostring(s and ("[" .. s() .. "]"))) io.write(tostring(m and "\t"..m or "") .. "\n") end -- test line stuff local t2 = { {"test\nother", 5, 1}, {"test\nother", 6, 2}, {"\n", 1, 1}, {"\n", 2, 2}, -- there is no char 2 but that's not the point } for _, temp in ipairs(t2) do local got, expect = getline(temp[1], temp[2]), temp[3] assert(got == expect, ("got %d, expected %d"):format(got, expect)) end elseif not ... then print("Tests require Lua 5.2") end return { parse52 = parseString52, findpairs = findpairs, getline = getline, }
Fix more stuff and better errors
Fix more stuff and better errors
Lua
mit
SoniEx2/Stuff,SoniEx2/Stuff
59cbb75e0522d7f194c9feedd51dd98fece44592
lua/wire/client/rendertarget_fix.lua
lua/wire/client/rendertarget_fix.lua
WireLib.RTFix = {} local RTFix = WireLib.RTFix --------------------------------------------------------------------- -- RTFix Lib --------------------------------------------------------------------- RTFix.List = {} function RTFix:Add( ClassName, NiceName, Function ) RTFix.List[ClassName] = { NiceName, Function } end function RTFix:GetAll() return RTFix.List end function RTFix:Get( ClassName ) return RTFix.List[ClassName] end function RTFix:ReloadAll() for k,v in pairs( RTFix.List ) do local func = v[2] for k2,v2 in ipairs( ents.FindByClass( k ) ) do func( v2 ) end end end function RTFix:Reload( ClassName ) local func = RTFix.List[ClassName][2] for k, v in ipairs( ents.FindByClass( ClassName ) ) do func( v ) end end --------------------------------------------------------------------- -- Console Command --------------------------------------------------------------------- concommand.Add("wire_rt_fix",function() RTFix:ReloadAll() end) --------------------------------------------------------------------- -- Tool Menu --------------------------------------------------------------------- local function CreateCPanel( Panel ) Panel:ClearControls() Panel:Help( [[Here you can fix screens that use rendertargets if they break due to lag. If a screen is not on this list, it means that either its author has not added it to this list, the screen has its own fix, or that no fix is necessary. You can also use the console command "wire_rt_fix", which does the same thing as pressing the "All" button.]] ) local btn = vgui.Create("DButton") btn:SetText("All") function btn:DoClick() RTFix:ReloadAll() end btn:SetToolTip( "Fix all RTs on the map." ) Panel:AddItem( btn ) for k,v in pairs( RTFix.List ) do local btn = vgui.Create("DButton") btn:SetText( v[1] ) btn:SetToolTip( "Fix all " .. v[1] .. "s on the map\n("..k..")" ) function btn:DoClick() RTFix:Reload( k ) end Panel:AddItem( btn ) end end hook.Add("PopulateToolMenu","WireLib_RenderTarget_Fix",function() spawnmenu.AddToolMenuOption( "Wire", "Options", "RTFix", "Fix RenderTargets", "", "", CreateCPanel, nil ) end) --------------------------------------------------------------------- -- Add all default wire components -- credits to sk89q for making this: http://www.wiremod.com/forum/bug-reports/19921-cs-egp-gpu-etc-issue-when-rejoin-lag-out.html#post193242 --------------------------------------------------------------------- -- Helper function local function def( ent, redrawkey ) if (ent.GPU or ent.GPU.RT) then ent.GPU:FreeRT() end ent.GPU:Initialize() if (redrawkey) then ent[redrawkey] = true end end RTFix:Add("gmod_wire_consolescreen","Console Screen", function( ent ) def( ent, "NeedRefresh" ) end) RTFix:Add("gmod_wire_digitalscreen","Digital Screen", function( ent ) def( ent, "NeedRefresh" ) end) RTFix:Add("gmod_wire_gpu","GPU", def) --RTFix:Add("gmod_wire_graphics_tablet","Graphics Tablet", function( ent ) def( ent, nil, true ) end) No fix is needed for this RTFix:Add("gmod_wire_oscilloscope","Oscilloscope", def) --RTFix:Add("gmod_wire_panel","Control Panel", function( ent ) def( ent, nil, true ) end) No fix is needed for this --RTFix:Add("gmod_wire_screen","Screen", function( ent ) def( ent, nil, true ) end) No fix is needed for this RTFix:Add("gmod_wire_textscreen","Text Screen", function( ent ) def( ent, "NeedRefresh" ) end)
WireLib.RTFix = {} local RTFix = WireLib.RTFix --------------------------------------------------------------------- -- RTFix Lib --------------------------------------------------------------------- RTFix.List = {} function RTFix:Add( ClassName, NiceName, Function ) RTFix.List[ClassName] = { NiceName, Function } end function RTFix:GetAll() return RTFix.List end function RTFix:Get( ClassName ) return RTFix.List[ClassName] end function RTFix:ReloadAll() for k,v in pairs( RTFix.List ) do local func = v[2] for k2,v2 in ipairs( ents.FindByClass( k ) ) do func( v2 ) end end end function RTFix:Reload( ClassName ) local func = RTFix.List[ClassName][2] for k, v in ipairs( ents.FindByClass( ClassName ) ) do func( v ) end end --------------------------------------------------------------------- -- Console Command --------------------------------------------------------------------- concommand.Add("wire_rt_fix",function() RTFix:ReloadAll() end) --------------------------------------------------------------------- -- Tool Menu --------------------------------------------------------------------- local function CreateCPanel( Panel ) Panel:ClearControls() Panel:Help( [[Here you can fix screens that use rendertargets if they break due to lag. If a screen is not on this list, it means that either its author has not added it to this list, the screen has its own fix, or that no fix is necessary. You can also use the console command "wire_rt_fix", which does the same thing as pressing the "All" button.]] ) local btn = vgui.Create("DButton") btn:SetText("All") function btn:DoClick() RTFix:ReloadAll() end btn:SetToolTip( "Fix all RTs on the map." ) Panel:AddItem( btn ) for k,v in pairs( RTFix.List ) do local btn = vgui.Create("DButton") btn:SetText( v[1] ) btn:SetToolTip( "Fix all " .. v[1] .. "s on the map\n("..k..")" ) function btn:DoClick() RTFix:Reload( k ) end Panel:AddItem( btn ) end end hook.Add("PopulateToolMenu","WireLib_RenderTarget_Fix",function() spawnmenu.AddToolMenuOption( "Wire", "Options", "RTFix", "Fix RenderTargets", "", "", CreateCPanel, nil ) end) --------------------------------------------------------------------- -- Add all default wire components -- credits to sk89q for making this: http://www.wiremod.com/forum/bug-reports/19921-cs-egp-gpu-etc-issue-when-rejoin-lag-out.html#post193242 --------------------------------------------------------------------- -- Helper function local function def( ent, redrawkey ) if (ent.GPU or ent.GPU.RT) then ent.GPU:FreeRT() end ent.GPU:Initialize() if (redrawkey) then ent[redrawkey] = true end end RTFix:Add("gmod_wire_consolescreen","Console Screen", function( ent ) def( ent, "NeedRefresh" ) end) RTFix:Add("gmod_wire_digitalscreen","Digital Screen", function( ent ) def( ent, "NeedRefresh" ) end) RTFix:Add("gmod_wire_gpu","GPU", def) --RTFix:Add("gmod_wire_graphics_tablet","Graphics Tablet", function( ent ) def( ent, nil, true ) end) No fix is needed for this RTFix:Add("gmod_wire_oscilloscope","Oscilloscope", def) --RTFix:Add("gmod_wire_panel","Control Panel", function( ent ) def( ent, nil, true ) end) No fix is needed for this --RTFix:Add("gmod_wire_screen","Screen", function( ent ) def( ent, nil, true ) end) No fix is needed for this RTFix:Add("gmod_wire_textscreen","Text Screen", function( ent ) def( ent, "NeedRefresh" ) end) RTFix:Add("gmod_wire_egp","EGP",function( ent ) def( ent, "NeedsUpdate" ) end)
Added EGP to RT fix menu
Added EGP to RT fix menu
Lua
apache-2.0
notcake/wire,garrysmodlua/wire,mitterdoo/wire,sammyt291/wire,immibis/wiremod,CaptainPRICE/wire,NezzKryptic/Wire,dvdvideo1234/wire,mms92/wire,thegrb93/wire,bigdogmat/wire,plinkopenguin/wiremod,Python1320/wire,Grocel/wire,rafradek/wire,wiremod/wire
ead107000e83d0d0da706fb246f300c1ad9cfce7
base/repair.lua
base/repair.lua
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] local common = require("base.common") local money = require("base.money") itemPos = {{en="Head", de="Kopf"},{en="Neck", de="Hals"},{en="Breast", de="Brust"},{en="Both Hands", de="Beide Hnde"},{en="Left Hand", de="Linke Hand"}, {en="Right Tool", de="Rechte Hand"}, {en="Left Finger", de="Linker Finger"},{en="Right Finger", de="Rechter Finger"} ,{en="Legs", de="Beine"}, {en="Feet", de="Fe"}, {en="Coat", de="Umhang"},{en="Belt 1", de="Grtel 1"}, {en="Belt 2", de="Grtel 2"},{en="Belt 3", de="Grtel 3"},{en="Belt 4", de="Grtel 4"},{en="Belt 5", de="Grtel 5"},{en="Belt 6", de="Grtel 6"}} itemPos[0] = {en="Backpack", de="Rucksack"} local M = {} --opens a selection dialog for the player to choose an item to repair function M.repairDialog(npcChar, speaker) local dialogTitle, dialogInfoText, repairPriceText; local language = speaker:getPlayerLanguage(); --Set dialogmessages if language == 0 then --german dialogTitle = "Reparieren"; dialogInfoText = "Whle den Gegenstand aus, den du reparieren mchtest:"; repairPriceText = " Kosten: "; else --english dialogTitle = "Repair"; dialogInfoText = "Please choose an item you wish to repair:"; repairPriceText = " Cost: "; end --get all the items the char has on him, without the stuff in the backpack local itemsOnChar = {}; local itemPosOnChar = {}; for i=17,0,-1 do local item = speaker:getItemAt(i); if (item.id > 0) and (item.number == 1) and (getRepairPrice(item,speaker) ~= 0) then --only add items which are single items and repairable table.insert(itemsOnChar, item); table.insert(itemPosOnChar, itemPos[i]) end end local cbChooseItem = function (dialog) if (not dialog:getSuccess()) then return; end local index = dialog:getSelectedIndex()+1; local chosenItem = itemsOnChar[index] if chosenItem ~= nil then repair(npcChar, speaker, chosenItem, language); -- let's repair M.repairDialog(npcChar, speaker); -- call dialog recursively, to allow further repairs else speaker:inform("[ERROR] Something went wrong, please inform a developer."); end end local sdItems = SelectionDialog(dialogTitle, dialogInfoText, cbChooseItem); sdItems:setCloseOnMove(); local itemName, repairPrice, itemPosText; for i,item in ipairs(itemsOnChar) do itemName = world:getItemName(item.id,language) repairPrice = getRepairPrice(item,speaker) itemPosText = common.GetNLS(speaker, itemPosOnChar[i].de, itemPosOnChar[i].en) sdItems:addOption(item.id,itemName .. " (" .. itemPosText .. ")\n"..repairPriceText..repairPrice); end speaker:requestSelectionDialog(sdItems); end --returns the price as string to repair the item according to playerlanguage or 0 if the price is 0 function getRepairPrice(theItem, speaker) local theItemStats=world:getItemStats(theItem); if theItemStats.MaxStack == 1 then local durability=theItem.quality-100*math.floor(theItem.quality/100); --calculate the durability local toRepair=99-durability; --the amount of durability points that has to repaired local price=math.ceil(0.5*theItemStats.Worth*toRepair/1000)*10; --Price rounded up in 10 cp steps local gstring,estring; if price == 0 then return price; else gstring,estring=money.MoneyToString(price) end return common.GetNLS(speaker, gstring, estring) end return 0; end -- Repairs theItem. The NPC speaks if the repair was successful or the char has not enough money function repair(npcChar, speaker, theItem, language) local theItemStats=world:getItemStats(theItem); --Check all the items the char has on him, without the stuff in the backpack. Is the item still around? local itemsOnChar = {}; local itemPosOnChar = {}; for i=17,0,-1 do local item = speaker:getItemAt(i); if (item==theItem) then --if the item is around... found=true; end end if theItem and found then local durability=theItem.quality-100*math.floor(theItem.quality/100); --calculate the durability local toRepair=99-durability; --the amount of durability points that has to repaired local price=math.ceil(0.5*theItemStats.Worth*toRepair/1000)*10; local priceMessage = getRepairPrice(theItem, speaker); if theItemStats.Worth == 0 or theItemStats.isStackable or durability==99 then --Cannot repair perfect, priceless or stackable items local notRepairable={"Entschuldigt, aber das kann ich nicht reparieren.", "I cannot repair this, sorry."}; --Priceless, perfect or stackable item npcChar:talk(Character.say, notRepairable[language+1]); else -- I can repair it! if not money.CharHasMoney(speaker,price) then --player is broke local notEnoughMoney={"Ihr habt anscheinend nicht genug Geld. Die Reparatur wrde"..priceMessage.." kosten.","You don't have enough money I suppose. I demand"..priceMessage.." for repairing this item."}; --Player is broke npcChar:talk(Character.say, notEnoughMoney[language+1]); else --he has the money local successRepair={"Der Gegenstand wird fr"..priceMessage.." in Stand gesetzt.", "The item is repaired at a cost of"..priceMessage.."."}; speaker:inform(successRepair[language+1]); money.TakeMoneyFromChar(speaker,price); --pay! theItem.quality=theItem.quality+toRepair; --repair! world:changeItem(theItem); end --price/repair end --there is an item else speaker:inform("[ERROR] Item not found.","[FEHLER] Gegenstand nicht gefunden."); end --item exists end; return M
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] local common = require("base.common") local money = require("base.money") itemPos = {{en="Head", de="Kopf"},{en="Neck", de="Hals"},{en="Breast", de="Brust"},{en="Both Hands", de="Beide Hnde"},{en="Left Hand", de="Linke Hand"}, {en="Right Tool", de="Rechte Hand"}, {en="Left Finger", de="Linker Finger"},{en="Right Finger", de="Rechter Finger"} ,{en="Legs", de="Beine"}, {en="Feet", de="Fe"}, {en="Coat", de="Umhang"},{en="Belt 1", de="Grtel 1"}, {en="Belt 2", de="Grtel 2"},{en="Belt 3", de="Grtel 3"},{en="Belt 4", de="Grtel 4"},{en="Belt 5", de="Grtel 5"},{en="Belt 6", de="Grtel 6"}} itemPos[0] = {en="Backpack", de="Rucksack"} local M = {} --opens a selection dialog for the player to choose an item to repair function M.repairDialog(npcChar, speaker) local dialogTitle, dialogInfoText, repairPriceText; local language = speaker:getPlayerLanguage(); --Set dialogmessages if language == 0 then --german dialogTitle = "Reparieren"; dialogInfoText = "Whle den Gegenstand aus, den du reparieren mchtest:"; repairPriceText = " Kosten: "; else --english dialogTitle = "Repair"; dialogInfoText = "Please choose an item you wish to repair:"; repairPriceText = " Cost: "; end --get all the items the char has on him, without the stuff in the backpack local itemsOnChar = {}; local itemPosOnChar = {}; for i=17,0,-1 do local item = speaker:getItemAt(i); if (item.id > 0) and (item.number == 1) and (getRepairPrice(item,speaker) ~= 0) then --only add items which are single items and repairable table.insert(itemsOnChar, item); table.insert(itemPosOnChar, itemPos[i]) end end local cbChooseItem = function (dialog) if (not dialog:getSuccess()) then return; end local index = dialog:getSelectedIndex()+1; local chosenItem = itemsOnChar[index] if chosenItem ~= nil then repair(npcChar, speaker, chosenItem, language); -- let's repair M.repairDialog(npcChar, speaker); -- call dialog recursively, to allow further repairs else speaker:inform("[ERROR] Something went wrong, please inform a developer."); end end local sdItems = SelectionDialog(dialogTitle, dialogInfoText, cbChooseItem); sdItems:setCloseOnMove(); local itemName, repairPrice, itemPosText; for i,item in ipairs(itemsOnChar) do itemName = world:getItemName(item.id,language) repairPrice = getRepairPrice(item,speaker) itemPosText = common.GetNLS(speaker, itemPosOnChar[i].de, itemPosOnChar[i].en) sdItems:addOption(item.id,itemName .. " (" .. itemPosText .. ")\n"..repairPriceText..repairPrice); end speaker:requestSelectionDialog(sdItems); end --returns the price as string to repair the item according to playerlanguage or 0 if the price is 0 function getRepairPrice(theItem, speaker) local theItemStats=world:getItemStats(theItem); if theItemStats.MaxStack == 1 then local durability=theItem.quality-100*math.floor(theItem.quality/100); --calculate the durability local toRepair=99-durability; --the amount of durability points that has to repaired local price=math.ceil(0.5*theItemStats.Worth*toRepair/1000)*10; --Price rounded up in 10 cp steps local gstring,estring; if price == 0 then return price; else gstring,estring=money.MoneyToString(price) end return common.GetNLS(speaker, gstring, estring) end return 0; end -- Repairs theItem. The NPC speaks if the repair was successful or the char has not enough money function repair(npcChar, speaker, theItem, language) local theItemStats=world:getItemStats(theItem); if theItem then local durability=theItem.quality-100*math.floor(theItem.quality/100); --calculate the durability local toRepair=99-durability; --the amount of durability points that has to repaired local price=math.ceil(0.5*theItemStats.Worth*toRepair/1000)*10; local priceMessage = getRepairPrice(theItem, speaker); if theItemStats.Worth == 0 or theItemStats.isStackable or durability==99 then --Cannot repair perfect, priceless or stackable items local notRepairable={"Entschuldigt, aber das kann ich nicht reparieren.", "I cannot repair this, sorry."}; --Priceless, perfect or stackable item npcChar:talk(Character.say, notRepairable[language+1]); else -- I can repair it! if not money.CharHasMoney(speaker,price) then --player is broke local notEnoughMoney={"Ihr habt anscheinend nicht genug Geld. Die Reparatur wrde"..priceMessage.." kosten.","You don't have enough money I suppose. I demand"..priceMessage.." for repairing this item."}; --Player is broke npcChar:talk(Character.say, notEnoughMoney[language+1]); else --he has the money local successRepair={"Der Gegenstand wird fr"..priceMessage.." in Stand gesetzt.", "The item is repaired at a cost of"..priceMessage.."."}; speaker:inform(successRepair[language+1]); money.TakeMoneyFromChar(speaker,price); --pay! theItem.quality=theItem.quality+toRepair; --repair! world:swap(theItem,theItem.id,theItem.quality); end --price/repair end --there is an item else speaker:inform("[ERROR] Item not found.","[FEHLER] Gegenstand nicht gefunden."); end --item exists end; return M
Hotfix for #11095
Hotfix for #11095
Lua
agpl-3.0
Baylamon/Illarion-Content,Illarion-eV/Illarion-Content,vilarion/Illarion-Content,KayMD/Illarion-Content
4172b1b61c64a5038ed008056dfc282f1f325d6a
examples/list-boots.lua
examples/list-boots.lua
#!/usr/bin/env lua --[[ This program acts like journalctl --list-boots ]] local sj = require "systemd.journal" local j = assert(sj.open()) local t = {} local n = 0 for boot_id in j:each_unique("_BOOT_ID") do local boot_info = { id = boot_id; } n = n + 1 t[n] = boot_info -- We need to find the first and last entries for each boot assert(j:add_match("_BOOT_ID="..boot_id)) assert(j:seek_head()) assert(j:next()) boot_info.head = j:get_realtime_usec() assert(j:seek_tail()) assert(j:previous()) boot_info.tail = j:get_realtime_usec() j:flush_matches() end table.sort(t, function(a,b) return a.head < b.head end) for i=1, n do local boot_info = t[i] io.write(string.format("%2d %s %s—%s\n", i-n, boot_info.id, os.date("%a %Y-%m-%d %H:%M:%S %Z", boot_info.head/1e6), os.date("%a %Y-%m-%d %H:%M:%S %Z", boot_info.tail/1e6) )) end
#!/usr/bin/env lua --[[ This program acts like journalctl --list-boots ]] local sj = require "systemd.journal" local j = assert(sj.open()) local t = {} local n = 0 for boot_id in j:each_unique("_BOOT_ID") do local boot_info = { id = boot_id; } n = n + 1 t[n] = boot_info -- We need to find the first and last entries for each boot assert(j:add_match("_BOOT_ID="..boot_id)) assert(j:seek_head()) assert(j:next()) boot_info.head = j:get_realtime_usec() assert(j:seek_tail()) assert(j:previous()) boot_info.tail = j:get_realtime_usec() j:flush_matches() end table.sort(t, function(a,b) return a.head < b.head end) local d_width = math.floor(math.log(n, 10))+2 for i=1, n do local boot_info = t[i] io.write(string.format("%"..d_width.."d %s %s—%s\n", i-n, boot_info.id, os.date("%a %Y-%m-%d %H:%M:%S %Z", boot_info.head/1e6), os.date("%a %Y-%m-%d %H:%M:%S %Z", boot_info.tail/1e6) )) end
examples/list-boots: Fix print width when there are lots of boots
examples/list-boots: Fix print width when there are lots of boots
Lua
mit
daurnimator/lua-systemd
3060982e87f684b98546c8d90e436cc835d69778
rapidshare.lua
rapidshare.lua
dofile("urlcode.lua") dofile("table_show.lua") local url_count = 0 local tries = 0 local downloaded = {} local addedtolist = {} read_file = function(file) if file then local f = assert(io.open(file)) local data = f:read("*all") f:close() return data else return "" end end wget.callbacks.get_urls = function(file, url, is_css, iri) local urls = {} local html = nil local function check(newurl) if (downloaded[newurl] ~= true and addedtolist[newurl] ~= true) then table.insert(urls, { url=newurl }) addedtolist[newurl] = true end end if string.match(url, "https?://rapid%-search%-engine%.com/") then html = read_file(file) for newurl in string.gmatch(html, '"(https?://rapidshare%.com/[^"]+)"') do check(newurl) end for newurl in string.gmatch(html, '"(https?://www%.rapidshare%.com/[^"]+)"') do check(newurl) end end if string.match(url, "rapidshare%.com/files/[0-9]+/") then html = read_file(file) for newurl in string.gmatch(html, 'location="(https?://[^%.]+%.rapidshare%.com/cgi%-bin/[^"]+)"') do check(newurl) end end return urls end wget.callbacks.httploop_result = function(url, err, http_stat) -- NEW for 2014: Slightly more verbose messages because people keep -- complaining that it's not moving or not working local status_code = http_stat["statcode"] last_http_statcode = status_code url_count = url_count + 1 io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n") io.stdout:flush() if (status_code >= 200 and status_code <= 399) then downloaded[url["url"]] = true end if status_code >= 500 or (status_code >= 400 and status_code ~= 404) then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 5") tries = tries + 1 if tries >= 20 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.ABORT else return wget.actions.CONTINUE end elseif status_code == 0 then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 10 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.ABORT else return wget.actions.CONTINUE end end tries = 0 -- We're okay; sleep a bit (if we have to) and continue -- local sleep_time = 0.1 * (math.random(500, 5000) / 100.0) local sleep_time = math.random(100, 200) -- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then -- -- We should be able to go fast on images since that's what a web browser does -- sleep_time = 0 -- end if sleep_time > 0.001 then os.execute("sleep " .. sleep_time) end return wget.actions.NOTHING end
dofile("urlcode.lua") dofile("table_show.lua") local url_count = 0 local tries = 0 local downloaded = {} local addedtolist = {} read_file = function(file) if file then local f = assert(io.open(file)) local data = f:read("*all") f:close() return data else return "" end end wget.callbacks.get_urls = function(file, url, is_css, iri) local urls = {} local html = nil local function check(newurl) if (downloaded[newurl] ~= true and addedtolist[newurl] ~= true) then table.insert(urls, { url=newurl }) addedtolist[newurl] = true end end if string.match(url, "https?://rapid%-search%-engine%.com/") then html = read_file(file) for newurl in string.gmatch(html, '"(https?://rapidshare%.com/[^"]+)"') do check(newurl) local newurl1 = string.gsub(newurl, "/files/[0-9]", "/files/") check(newurl1) end for newurl in string.gmatch(html, '"(https?://www%.rapidshare%.com/[^"]+)"') do check(newurl) local newurl1 = string.gsub(newurl, "/files/[0-9]", "/files/") check(newurl1) end end if string.match(url, "rapidshare%.com/files/[0-9]+/") then html = read_file(file) for newurl in string.gmatch(html, 'location="(https?://[^%.]+%.rapidshare%.com/cgi%-bin/[^"]+)"') do check(newurl) end end return urls end wget.callbacks.httploop_result = function(url, err, http_stat) -- NEW for 2014: Slightly more verbose messages because people keep -- complaining that it's not moving or not working local status_code = http_stat["statcode"] last_http_statcode = status_code url_count = url_count + 1 io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n") io.stdout:flush() if (status_code >= 200 and status_code <= 399) then downloaded[url["url"]] = true end if status_code >= 500 or (status_code >= 400 and status_code ~= 404) then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 5") tries = tries + 1 if tries >= 20 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.ABORT else return wget.actions.CONTINUE end elseif status_code == 0 then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 10 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.ABORT else return wget.actions.CONTINUE end end tries = 0 -- We're okay; sleep a bit (if we have to) and continue -- local sleep_time = 0.1 * (math.random(500, 5000) / 100.0) local sleep_time = math.random(50, 100) -- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then -- -- We should be able to go fast on images since that's what a web browser does -- sleep_time = 0 -- end if sleep_time > 0.001 then os.execute("sleep " .. sleep_time) end return wget.actions.NOTHING end
rapidshare.lua: fix and shorter sleep_time
rapidshare.lua: fix and shorter sleep_time
Lua
unlicense
ArchiveTeam/rapidshare-grab,ArchiveTeam/rapidshare-grab
9384ce90fe890429e2612ad83395357e72ba9a14
AceModuleCore-3.0/AceModuleCore-3.0.lua
AceModuleCore-3.0/AceModuleCore-3.0.lua
local MAJOR, MINOR = "AceModuleCore-3.0", 0 local AceModuleCore, oldversion = LibStub:NewLibrary( MAJOR, MINOR ) local AceAddon = LibStub:GetLibrary("AceAddon-3.0") if not AceAddon then error(MAJOR.." requires AceAddon-3.0") end if not AceModuleCore then return elseif not oldversion then AceModuleCore.embeded = {} -- contains a list of namespaces this has been embeded into end local function safecall(func,...) if type(func) == "function" then local success, err = pcall(func,...) if not err:find("%.lua:%d+:") then err = (debugstack():match("\n(.-: )in.-\n") or "") .. err end geterrorhandler()(err) end end -- AceModuleCore:GetModule( name, [silent]) -- name (string) - unique module object name -- silent (boolean) - if true, module is optional, silently return nil if its not found -- -- throws an error if the addon object can not be found (except silent is set) -- returns the module object if found function GetModule(self, name, silent) if not silent and not self.modules[name] then error(("Cannot find a module named '%s'."):format(name), 2) end return self.modules[name] end -- AceModuleCore:NewModule( name, [prototype, [lib, lib, lib, ...] ) -- name (string) - unique module object name for this addon -- prototype (object) - object to derive this module from, methods and values from this table will be mixed into the module, if a string is passed a lib is assumed -- [lib] (string) - optional libs to embed in the addon object -- -- returns the addon object when succesful function NewModule(self, name, prototype, ... ) assert( type( name ) == "string", "Bad argument #2 to 'NewModule' (string expected)" ) assert( type( prototype ) == "string" or type( prototype ) == "string" or type( prototype ) == "nil" ), "Bad argument #3 to 'NewModule' (string, table or nil expected)" ) if self.modules[name] then error( ("Module '%s' already exists."):format(name), 2 ) end local module = AceAddon:NewAddon( ("%s_%s"):format( self.name or tostring(self), name) ) if type( prototype ) == "table" then module = AceAddon:EmbedLibraries( module, ... ) setmetatable(module, {__index=prototype}) -- More of a Base class type feel. elseif prototype then module = AceAddon:EmbedLibraries( module, prototype, ... ) end safecall(module.OnModuleCreated, self) -- Was in Ace2 and I think it could be a cool thing to have handy. self.modules[name] = module return module end local mixins = {NewModule = NewModule, GetModule = GetModule, modules = {}} -- AceModuleCore:Embed( target ) -- target (object) - target object to embed the modulecore in -- -- Embeds acemodule core into the target object function AceModuleCore:Embed( target ) for k, v in pairs( mixins ) do target[k] = v end table.insert(self.embeded, target) end function AceModuleCore:OnEmbedInitialize( target ) do for name, module in pairs( target.modules ) do AceAddon:InitializeAddon( module ) -- this whole deal needs serious testing end end function AceModuleCore:OnEmbedEnable( target ) for name, module in pairs( target.modules ) do AceAddon:EnableAddon( module ) -- this whole deal needs serious testing end end function AceModuleCore:OnEmbedDisable( target ) for name, module in pairs( target.modules ) do AceAddon:DisableAddon( module ) - this whole deal needs serious testing end end
local MAJOR, MINOR = "AceModuleCore-3.0", 0 local AceModuleCore, oldversion = LibStub:NewLibrary( MAJOR, MINOR ) local AceAddon = LibStub:GetLibrary("AceAddon-3.0") if not AceAddon then error(MAJOR.." requires AceAddon-3.0") end if not AceModuleCore then return elseif not oldversion then AceModuleCore.embeded = {} -- contains a list of namespaces this has been embeded into end local function safecall(func,...) if type(func) == "function" then local success, err = pcall(func,...) if not err:find("%.lua:%d+:") then err = (debugstack():match("\n(.-: )in.-\n") or "") .. err end geterrorhandler()(err) end end -- AceModuleCore:GetModule( name, [silent]) -- name (string) - unique module object name -- silent (boolean) - if true, module is optional, silently return nil if its not found -- -- throws an error if the addon object can not be found (except silent is set) -- returns the module object if found function GetModule(self, name, silent) if not silent and not self.modules[name] then error(("Cannot find a module named '%s'."):format(name), 2) end return self.modules[name] end -- AceModuleCore:NewModule( name, [prototype, [lib, lib, lib, ...] ) -- name (string) - unique module object name for this addon -- prototype (object) - object to derive this module from, methods and values from this table will be mixed into the module, if a string is passed a lib is assumed -- [lib] (string) - optional libs to embed in the addon object -- -- returns the addon object when succesful function NewModule(self, name, prototype, ... ) assert( type( name ) == "string", "Bad argument #2 to 'NewModule' (string expected)" ) assert( type( prototype ) == "string" or type( prototype ) == "string" or type( prototype ) == "nil" ), "Bad argument #3 to 'NewModule' (string, table or nil expected)" ) if self.modules[name] then error( ("Module '%s' already exists."):format(name), 2 ) end local module = AceAddon:NewAddon( ("%s_%s"):format( self.name or tostring(self), name) ) if type( prototype ) == "table" then module = AceAddon:EmbedLibraries( module, ... ) setmetatable(module, {__index=prototype}) -- More of a Base class type feel. elseif prototype then module = AceAddon:EmbedLibraries( module, prototype, ... ) end safecall(module.OnModuleCreated, self) -- Was in Ace2 and I think it could be a cool thing to have handy. self.modules[name] = module return module end local mixins = {NewModule = NewModule, GetModule = GetModule, modules = {}} -- AceModuleCore:Embed( target ) -- target (object) - target object to embed the modulecore in -- -- Embeds acemodule core into the target object function AceModuleCore:Embed( target ) for k, v in pairs( mixins ) do target[k] = v end self.embeded[target] = true end function AceModuleCore:OnEmbedInitialize( target ) do for name, module in pairs( target.modules ) do AceAddon:InitializeAddon( module ) -- this whole deal needs serious testing end end function AceModuleCore:OnEmbedEnable( target ) for name, module in pairs( target.modules ) do AceAddon:EnableAddon( module ) -- this whole deal needs serious testing end end function AceModuleCore:OnEmbedDisable( target ) for name, module in pairs( target.modules ) do AceAddon:DisableAddon( module ) - this whole deal needs serious testing end end --- Upgrade our old embeds for target, v in pairs( AceModuleCore.embeded ) do AceModuleCore:Embed( target ) end
Ace3: AceModuleCore-3.0 - Fix upgrading of old embeds
Ace3: AceModuleCore-3.0 - Fix upgrading of old embeds git-svn-id: 00c2b8bc9b083c53e126de03a83516ee6a3b87d9@14 5debad98-a965-4143-8383-f471b3509dcf
Lua
bsd-3-clause
sarahgerweck/Ace3
df9e47491f515d940d5cb2e5e035c210b81c2a3a
share/luaplaylist/youtube.lua
share/luaplaylist/youtube.lua
--[[ $Id$ Copyright © 2007 the VideoLAN team 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. --]] -- Helper function to get a parameter's value in a URL function get_url_param( url, name ) return string.gsub( url, "^.*[&?]"..name.."=([^&]*).*$", "%1" ) end function get_arturl( path, video_id ) if string.match( vlc.path, "iurl=" ) then return vlc.decode_uri( get_url_param( vlc.path, "iurl" ) ) end if not arturl then return "http://img.youtube.com/vi/"..video_id.."/default.jpg" end end -- Probe function. function probe() if vlc.access ~= "http" then return false end youtube_site = string.match( string.sub( vlc.path, 1, 8 ), "youtube" ) if not youtube_site then -- FIXME we should be using a builtin list of known youtube websites -- like "fr.youtube.com", "uk.youtube.com" etc.. youtube_site = string.find( vlc.path, ".youtube.com" ) if youtube_site == nil then return false end end return ( string.match( vlc.path, "watch%?v=" ) -- the html page or string.match( vlc.path, "watch_fullscreen%?video_id=" ) -- the fullscreen page or string.match( vlc.path, "p.swf" ) -- the (old?) player url or string.match( vlc.path, "jp.swf" ) -- the (new?) player url (as of 24/08/2007) or string.match( vlc.path, "player2.swf" ) ) -- another player url end -- Parse function. function parse() if string.match( vlc.path, "watch%?v=" ) then -- This is the HTML page's URL while true do -- Try to find the video's title line = vlc.readline() if not line then break end if string.match( line, "<meta name=\"title\"" ) then name = string.gsub( line, "^.*content=\"([^\"]*).*$", "%1" ) end if string.match( line, "<meta name=\"description\"" ) then description = string.gsub( line, "^.*content=\"([^\"]*).*$", "%1" ) end if string.match( line, "subscribe_to_user=" ) then artist = string.gsub( line, ".*subscribe_to_user=([^&]*).*", "%1" ) end -- OLD: var swfArgs = {hl:'en',BASE_YT_URL:'http://youtube.com/',video_id:'XPJ7d8dq0t8',l:'292',t:'OEgsToPDskLFdOYrrlDm3FQPoQBYaCP1',sk:'0gnr-AE6QZJEZmCMd3lq_AC'}; -- NEW: var swfArgs = {"video_id": "OHVvVmUNBFc", "l": 88, "sk": "WswKuJzDBsdD6oG3IakCXgC", "t": "OEgsToPDskK3zO44y0QN8Fr5ZSAZwCQp", "plid": "AARGnwWMrmGkbpOxAAAA4AT4IAA", "tk": "mEL4E7PqHeaZp5OG19NQThHt9mXJU4PbRTOw6lz9osHi4Hixp7RE1w=="}; if string.match( line, "swfArgs" ) and string.match( line, "video_id" ) then if string.match( line, "BASE_YT_URL" ) then base_yt_url = string.gsub( line, ".*BASE_YT_URL:'([^']*)'.*", "%1" ) end t = string.gsub( line, ".*\"t\": \"([^\"]*).*", "%1" ) -- vlc.msg_err( t ) -- video_id = string.gsub( line, ".*&video_id:'([^']*)'.*", "%1" ) end if name and description and artist --[[and video_id]] then break end end if not video_id then video_id = get_url_param( vlc.path, "v" ) end if not base_yt_url then base_yt_url = "http://youtube.com/" end arturl = get_arturl( vlc.path, video_id ) if t then return { { path = base_yt_url .. "get_video?video_id="..video_id.."&t="..t; name = name; description = description; artist = artist; arturl = arturl } } else -- This shouldn't happen ... but keep it as a backup. return { { path = "http://www.youtube.com/v/"..video_id; name = name; description = description; artist = artist; arturl = arturl } } end else -- This is the flash player's URL if string.match( vlc.path, "title=" ) then name = get_url_param( vlc.path, "title" ) end video_id = get_url_param( vlc.path, "video_id" ) arturl = get_arturl( vlc.path, video_id ) if not string.match( vlc.path, "t=" ) then -- This sucks, we're missing "t" which is now mandatory. Let's -- try using another url return { { path = "http://www.youtube.com/v/"..video_id; name = name; arturl = arturl } } end return { { path = "http://www.youtube.com/get_video.php?video_id="..video_id.."&t="..get_url_param( vlc.path, "t" ); name = name; arturl = arturl } } end end
--[[ $Id$ Copyright © 2007 the VideoLAN team 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. --]] -- Helper function to get a parameter's value in a URL function get_url_param( url, name ) return string.gsub( url, "^.*[&?]"..name.."=([^&]*).*$", "%1" ) end function get_arturl( path, video_id ) if string.match( vlc.path, "iurl=" ) then return vlc.decode_uri( get_url_param( vlc.path, "iurl" ) ) end if not arturl then return "http://img.youtube.com/vi/"..video_id.."/default.jpg" end end -- Probe function. function probe() if vlc.access ~= "http" then return false end youtube_site = string.match( string.sub( vlc.path, 1, 8 ), "youtube" ) if not youtube_site then -- FIXME we should be using a builtin list of known youtube websites -- like "fr.youtube.com", "uk.youtube.com" etc.. youtube_site = string.find( vlc.path, ".youtube.com" ) if youtube_site == nil then return false end end return ( string.match( vlc.path, "watch%?v=" ) -- the html page or string.match( vlc.path, "watch_fullscreen%?video_id=" ) -- the fullscreen page or string.match( vlc.path, "p.swf" ) -- the (old?) player url or string.match( vlc.path, "jp.swf" ) -- the (new?) player url (as of 24/08/2007) or string.match( vlc.path, "player2.swf" ) ) -- another player url end -- Parse function. function parse() if string.match( vlc.path, "watch%?v=" ) then -- This is the HTML page's URL while true do -- Try to find the video's title line = vlc.readline() if not line then break end if string.match( line, "<meta name=\"title\"" ) then name = string.gsub( line, "^.*content=\"([^\"]*).*$", "%1" ) end if string.match( line, "<meta name=\"description\"" ) then description = string.gsub( line, "^.*content=\"([^\"]*).*$", "%1" ) end if string.match( line, "subscribe_to_user=" ) then artist = string.gsub( line, ".*subscribe_to_user=([^&]*).*", "%1" ) end -- OLD: var swfArgs = {hl:'en',BASE_YT_URL:'http://youtube.com/',video_id:'XPJ7d8dq0t8',l:'292',t:'OEgsToPDskLFdOYrrlDm3FQPoQBYaCP1',sk:'0gnr-AE6QZJEZmCMd3lq_AC'}; -- NEW: var swfArgs = { "BASE_YT_URL": "http://youtube.com", "video_id": "OHVvVmUNBFc", "l": 88, "sk": "WswKuJzDBsdD6oG3IakCXgC", "t": "OEgsToPDskK3zO44y0QN8Fr5ZSAZwCQp", "plid": "AARGnwWMrmGkbpOxAAAA4AT4IAA", "tk": "mEL4E7PqHeaZp5OG19NQThHt9mXJU4PbRTOw6lz9osHi4Hixp7RE1w=="}; if string.match( line, "swfArgs" ) and string.match( line, "video_id" ) then if string.match( line, "BASE_YT_URL" ) then base_yt_url = string.gsub( line, ".*\"BASE_YT_URL\": \"([^\"]*).*", "%1" ) end t = string.gsub( line, ".*\"t\": \"([^\"]*).*", "%1" ) -- vlc.msg_err( t ) -- video_id = string.gsub( line, ".*&video_id:'([^']*)'.*", "%1" ) end if name and description and artist --[[and video_id]] then break end end if not video_id then video_id = get_url_param( vlc.path, "v" ) end if not base_yt_url then base_yt_url = "http://youtube.com/" end arturl = get_arturl( vlc.path, video_id ) if t then return { { path = base_yt_url .. "get_video?video_id="..video_id.."&t="..t; name = name; description = description; artist = artist; arturl = arturl } } else -- This shouldn't happen ... but keep it as a backup. return { { path = "http://www.youtube.com/v/"..video_id; name = name; description = description; artist = artist; arturl = arturl } } end else -- This is the flash player's URL if string.match( vlc.path, "title=" ) then name = get_url_param( vlc.path, "title" ) end video_id = get_url_param( vlc.path, "video_id" ) arturl = get_arturl( vlc.path, video_id ) if not string.match( vlc.path, "t=" ) then -- This sucks, we're missing "t" which is now mandatory. Let's -- try using another url return { { path = "http://www.youtube.com/v/"..video_id; name = name; arturl = arturl } } end return { { path = "http://www.youtube.com/get_video.php?video_id="..video_id.."&t="..get_url_param( vlc.path, "t" ); name = name; arturl = arturl } } end end
Fix youtube lua (BASE_YT_URL had not been converted to new format)
Fix youtube lua (BASE_YT_URL had not been converted to new format)
Lua
lgpl-2.1
xkfz007/vlc,krichter722/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,shyamalschandra/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc,vlc-mirror/vlc,krichter722/vlc,jomanmuk/vlc-2.1,xkfz007/vlc,xkfz007/vlc,vlc-mirror/vlc-2.1,shyamalschandra/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,krichter722/vlc,vlc-mirror/vlc-2.1,krichter722/vlc,krichter722/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc-2.1,shyamalschandra/vlc,vlc-mirror/vlc,krichter722/vlc,vlc-mirror/vlc,shyamalschandra/vlc,vlc-mirror/vlc-2.1,xkfz007/vlc,xkfz007/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,xkfz007/vlc,vlc-mirror/vlc-2.1,xkfz007/vlc,vlc-mirror/vlc,krichter722/vlc,jomanmuk/vlc-2.1
bb64c8f932de3c5d64332c3fc1a9ac484995088a
config/nvim/lua/gb/file-explorer.lua
config/nvim/lua/gb/file-explorer.lua
local keymap = require("gb.utils").map vim.g.nvim_tree_ignore = {".git", "node_modules", ".cache", ".DS_Store"} --empty by default vim.g.nvim_tree_group_empty = 1 vim.g.nvim_tree_root_folder_modifier = ":~" --This is the default. See :help filename-modifiers for more options keymap("n", "<leader>n", ":NvimTreeToggle<CR>", {silent = true}) local tree_cb = require "nvim-tree.config".nvim_tree_callback require "nvim-tree".setup { auto_close = false, diagnostics = { enable = false }, view = { width = 40, mappings = { list = { {key = "w", cb = tree_cb("vsplit")}, {key = "s", cb = tree_cb("split")} } } }, update_focused_file = { enable = true } }
local keymap = require("gb.utils").map vim.g.nvim_tree_group_empty = 1 vim.g.nvim_tree_root_folder_modifier = ":~" --This is the default. See :help filename-modifiers for more options keymap("n", "<leader>n", ":NvimTreeToggle<CR>", {silent = true}) local tree_cb = require "nvim-tree.config".nvim_tree_callback require "nvim-tree".setup { auto_close = false, diagnostics = { enable = false }, view = { width = 40, mappings = { list = { {key = "w", cb = tree_cb("vsplit")}, {key = "s", cb = tree_cb("split")} } } }, update_focused_file = { enable = true }, filters = { custom = {".git", "node_modules", ".cache", ".DS_Store"} } }
Fix nvim-tree
Fix nvim-tree
Lua
mit
gblock0/dotfiles
0068b627945ad6050ce70d898473ad3b17b7cb58
sslobby/gamemode/player_extended.lua
sslobby/gamemode/player_extended.lua
-------------------------------------------------- -- -------------------------------------------------- local slapSound = Sound("ambient/voices/citizen_punches2.wav") function PLAYER_META:Slap(target) local direction = (target:GetPos() -self:GetPos()):GetNormal() target:SetVelocity(direction *256) target:EmitSound(slapSound, 100, math.random(65, 90)) self.nextSlap = CurTime() +0.5 local minigameSlap = SS.Lobby.Minigame:CallWithPlayer("PlayerSlap", self, target, self.nextSlap) if (minigameSlap != nil) then self.nextSlap = minigameSlap end end -------------------------------------------------- -- -------------------------------------------------- function PLAYER_META:CanSlap(target) self.nextSlap = self.nextSlap or 0 local minigameSlap = SS.Lobby.Minigame:CallWithPlayer("CanPlayerSlap", self, target, self.nextSlap) if (minigameSlap != nil) then return minigameSlap end return self.nextSlap <= CurTime() end
-------------------------------------------------- -- -------------------------------------------------- local slapSound = Sound("ambient/voices/citizen_punches2.wav") function PLAYER_META:Slap(target) local direction = (target:GetPos() -self:GetPos()):GetNormal() target:SetVelocity(direction *256) target:EmitSound(slapSound, 100, math.random(65, 90)) self.nextSlap = CurTime() +0.5 local minigameSlap = SS.Lobby.Minigame:CallWithPlayer("PlayerSlap", self, target, self.nextSlap) if (minigameSlap != nil) then self.nextSlap = minigameSlap end end -------------------------------------------------- -- -------------------------------------------------- function PLAYER_META:CanSlap(target) if target.NoSlap then return false end self.nextSlap = self.nextSlap or 0 local minigameSlap = SS.Lobby.Minigame:CallWithPlayer("CanPlayerSlap", self, target, self.nextSlap) if (minigameSlap != nil) then return minigameSlap end return self.nextSlap <= CurTime() end
I think this should fix noslap
I think this should fix noslap
Lua
bsd-3-clause
T3hArco/skeyler-gamemodes
40969442e30e48a2dbe9cf0b5f87625f9c4a50c3
scripts/tundra/tools/msvc6.lua
scripts/tundra/tools/msvc6.lua
-- msvc6.lua - Visual Studio 6 module(..., package.seeall) local native = require "tundra.native" local os = require "os" function path_combine(path, path_to_append) if path == nil then return path_to_append end if path:find("\\$") then return path .. path_to_append end return path .. "\\" .. path_to_append end function path_it(maybe_list) if type(maybe_list) == "table" then return ipairs(maybe_list) end return ipairs({maybe_list}) end function apply(env, options) if native.host_platform ~= "windows" then error("the msvc6 toolset only works on windows hosts") end -- Load basic MSVC environment setup first. -- We're going to replace the paths to some tools. tundra.unitgen.load_toolset('msvc', env) options = options or {} -- We'll find any edition of VS (including Express) here local vs_root = native.reg_query("HKLM", "SOFTWARE\\Microsoft\\VisualStudio\\6.0\\Setup\\Microsoft Visual C++", "ProductDir") assert(vs_root, "The requested version of Visual Studio isn't installed") vs_root = string.gsub(vs_root, "\\+$", "\\") local common_root = native.reg_query("HKLM", "SOFTWARE\\Microsoft\\VisualStudio\\6.0\\Setup", "VsCommonDir") assert(common_root, "The requested version of Visual Studio isn't installed") common_root = string.gsub(common_root, "\\+$", "\\") local vc_lib local vc_bin vc_bin = vs_root .. "\\bin" vc_lib = vs_root .. "\\lib" -- Tools local cl_exe = '"' .. path_combine(vc_bin, "cl.exe") .. '"' local lib_exe = '"' .. path_combine(vc_bin, "lib.exe") .. '"' local link_exe = '"' .. path_combine(vc_bin, "link.exe") .. '"' local rc_exe = '"' .. path_combine(common_root, "MSDev98\\Bin\\rc.exe") .. '"' env:set('CC', cl_exe) env:set('CXX', cl_exe) env:set('LIB', lib_exe) env:set('LD', link_exe) env:set('RC', rc_exe) env:set("RCOPTS", "") -- clear the "/nologo" option (it was first added in VS2010) -- Wire-up the external environment env:set_external_env_var('VSINSTALLDIR', vs_root) env:set_external_env_var('VCINSTALLDIR', vs_root .. "\\vc") --env:set_external_env_var('DevEnvDir', vs_root .. "Common7\\IDE") do local include = { path_combine(vs_root, "ATL\\INCLUDE"), path_combine(vs_root, "INCLUDE"), path_combine(vs_root, "MFC\\INCLUDE"), } env:set_external_env_var("INCLUDE", table.concat(include, ';')) end do local lib = { path_combine(vs_root, "LIB"), path_combine(vs_root, "MFC\\LIB"), } local lib_str = table.concat(lib, ';') env:set_external_env_var("LIB", lib_str) env:set_external_env_var("LIBPATH", lib_str) end -- Modify %PATH% do local path = { path_combine(vs_root, "BIN"), path_combine(common_root, "MSDev98\\BIN"), env:get_external_env_var('PATH'), } env:set_external_env_var("PATH", table.concat(path, ';')) end end
-- msvc6.lua - Visual Studio 6 module(..., package.seeall) local native = require "tundra.native" local os = require "os" function path_combine(path, path_to_append) if path == nil then return path_to_append end if path:find("\\$") then return path .. path_to_append end return path .. "\\" .. path_to_append end function path_it(maybe_list) if type(maybe_list) == "table" then return ipairs(maybe_list) end return ipairs({maybe_list}) end function apply(env, options) if native.host_platform ~= "windows" then error("the msvc6 toolset only works on windows hosts") end -- Load basic MSVC environment setup first. -- We're going to replace the paths to some tools. tundra.unitgen.load_toolset('msvc', env) -- Override PCH handling for poor MSVC 6. While it supports writing PDB files -- from the compiler, it doesn't handling multiple invocations of the -- compiler wanting to write to the same PDB. So we switch to /Z7 format -- instead and have just the linker write a PDB. env:replace("_USE_PDB_CC_OPT", "/Z7") options = options or {} -- We'll find any edition of VS (including Express) here local vs_root = native.reg_query("HKLM", "SOFTWARE\\Microsoft\\VisualStudio\\6.0\\Setup\\Microsoft Visual C++", "ProductDir") assert(vs_root, "The requested version of Visual Studio isn't installed") vs_root = string.gsub(vs_root, "\\+$", "\\") local common_root = native.reg_query("HKLM", "SOFTWARE\\Microsoft\\VisualStudio\\6.0\\Setup", "VsCommonDir") assert(common_root, "The requested version of Visual Studio isn't installed") common_root = string.gsub(common_root, "\\+$", "\\") local vc_lib local vc_bin vc_bin = vs_root .. "\\bin" vc_lib = vs_root .. "\\lib" -- Tools local cl_exe = '"' .. path_combine(vc_bin, "cl.exe") .. '"' local lib_exe = '"' .. path_combine(vc_bin, "lib.exe") .. '"' local link_exe = '"' .. path_combine(vc_bin, "link.exe") .. '"' local rc_exe = '"' .. path_combine(common_root, "MSDev98\\Bin\\rc.exe") .. '"' env:set('CC', cl_exe) env:set('CXX', cl_exe) env:set('LIB', lib_exe) env:set('LD', link_exe) env:set('RC', rc_exe) env:set("RCOPTS", "") -- clear the "/nologo" option (it was first added in VS2010) -- Wire-up the external environment env:set_external_env_var('VSINSTALLDIR', vs_root) env:set_external_env_var('VCINSTALLDIR', vs_root .. "\\vc") --env:set_external_env_var('DevEnvDir', vs_root .. "Common7\\IDE") do local include = { path_combine(vs_root, "ATL\\INCLUDE"), path_combine(vs_root, "INCLUDE"), path_combine(vs_root, "MFC\\INCLUDE"), } env:set_external_env_var("INCLUDE", table.concat(include, ';')) end do local lib = { path_combine(vs_root, "LIB"), path_combine(vs_root, "MFC\\LIB"), } local lib_str = table.concat(lib, ';') env:set_external_env_var("LIB", lib_str) env:set_external_env_var("LIBPATH", lib_str) end -- Modify %PATH% do local path = { path_combine(vs_root, "BIN"), path_combine(common_root, "MSDev98\\BIN"), env:get_external_env_var('PATH'), } env:set_external_env_var("PATH", table.concat(path, ';')) end end
MSVC6: Fix PDB write errors.
MSVC6: Fix PDB write errors. Without extra care and temporary files each MSVC6 compiler process will attempt to open/write the same PDB, causing build errors when Tundra goes wide. So it seems better to just have it stuff the debug data in the object files and let the linker worry about producing a PDB. This change does that.
Lua
mit
bmharper/tundra,deplinenoise/tundra,deplinenoise/tundra,bmharper/tundra,bmharper/tundra,deplinenoise/tundra,bmharper/tundra
c6b90e8406da14b5c748b4caa7c17de9588c8b14
src/logging.lua
src/logging.lua
------------------------------------------------------------------------------- -- includes a new tostring function that handles tables recursively -- -- @author Danilo Tuler (tuler@ideais.com.br) -- @author Andre Carregal (info@keplerproject.org) -- @author Thiago Costa Ponte (thiago@ideais.com.br) -- -- @copyright 2004-2013 Kepler Project ------------------------------------------------------------------------------- local type, table, string, _tostring, tonumber = type, table, string, tostring, tonumber local select = select local error = error local format = string.format local pairs = pairs local ipairs = ipairs local logging = { -- Meta information _COPYRIGHT = "Copyright (C) 2004-2013 Kepler Project", _DESCRIPTION = "A simple API to use logging features in Lua", _VERSION = "LuaLogging 1.3.0", -- The DEBUG Level designates fine-grained instring.formational events that are most -- useful to debug an application DEBUG = "DEBUG", -- The INFO level designates instring.formational messages that highlight the -- progress of the application at coarse-grained level INFO = "INFO", -- The WARN level designates potentially harmful situations WARN = "WARN", -- The ERROR level designates error events that might still allow the -- application to continue running ERROR = "ERROR", -- The FATAL level designates very severe error events that will presumably -- lead the application to abort FATAL = "FATAL", } local LEVEL = {"DEBUG", "INFO", "WARN", "ERROR", "FATAL"} local MAX_LEVELS = #LEVEL -- make level names to order for i=1,MAX_LEVELS do LEVEL[LEVEL[i]] = i end -- private log function, with support for formating a complex log message. local function LOG_MSG(self, level, fmt, ...) local f_type = type(fmt) if f_type == 'string' then if select('#', ...) > 0 then local status, msg = pcall(format, fmt, ...) if status then return self:append(level, msg) else return self:append(level, "Error formatting log message: " .. msg) end else -- only a single string, no formating needed. return self:append(level, fmt) end elseif f_type == 'function' then -- fmt should be a callable function which returns the message to log return self:append(level, fmt(...)) end -- fmt is not a string and not a function, just call tostring() on it. return self:append(level, logging.tostring(fmt)) end -- create the proxy functions for each log level. local LEVEL_FUNCS = {} for i=1,MAX_LEVELS do local level = LEVEL[i] LEVEL_FUNCS[i] = function(self, ...) -- no level checking needed here, this function will only be called if it's level is active. return LOG_MSG(self, level, ...) end end -- do nothing function for disabled levels. local function disable_level() end -- improved assertion function. local function assert(exp, ...) -- if exp is true, we are finished so don't do any processing of the parameters if exp then return exp, ... end -- assertion failed, raise error error(format(...), 2) end ------------------------------------------------------------------------------- -- Creates a new logger object -- @param append Function used by the logger to append a message with a -- log-level to the log stream. -- @return Table representing the new logger object. ------------------------------------------------------------------------------- function logging.new(append) if type(append) ~= "function" then return nil, "Appender must be a function." end local logger = {} logger.append = append logger.setLevel = function (self, level) local order = LEVEL[level] assert(order, "undefined level `%s'", _tostring(level)) if self.level then self:log(logging.WARN, "Logger: changing loglevel from %s to %s", self.level, level) end self.level = level self.level_order = order -- enable/disable levels for i=1,MAX_LEVELS do local name = LEVEL[i]:lower() if i >= order then self[name] = LEVEL_FUNCS[i] else self[name] = disable_level end end end -- generic log function. logger.log = function (self, level, ...) local order = LEVEL[level] assert(order, "undefined level `%s'", _tostring(level)) if order < self.level_order then return end return LOG_MSG(self, level, ...) end -- initialize log level. logger:setLevel(logging.DEBUG) return logger end ------------------------------------------------------------------------------- -- Prepares the log message ------------------------------------------------------------------------------- function logging.prepareLogMsg(pattern, dt, level, message) local logMsg = pattern or "%date %level %message\n" message = string.gsub(message, "%%", "%%%%") logMsg = string.gsub(logMsg, "%%date", dt) logMsg = string.gsub(logMsg, "%%level", level) logMsg = string.gsub(logMsg, "%%message", message) return logMsg end ------------------------------------------------------------------------------- -- Converts a Lua value to a string -- -- Converts Table fields in alphabetical order ------------------------------------------------------------------------------- local function tostring(value) local str = '' if (type(value) ~= 'table') then if (type(value) == 'string') then str = string.format("%q", value) else str = _tostring(value) end else local auxTable = {} for key in pairs(value) do if (tonumber(key) ~= key) then table.insert(auxTable, key) else table.insert(auxTable, tostring(key)) end end table.sort(auxTable) str = str..'{' local separator = "" local entry = "" for _, fieldName in ipairs(auxTable) do if ((tonumber(fieldName)) and (tonumber(fieldName) > 0)) then entry = tostring(value[tonumber(fieldName)]) else entry = fieldName.." = "..tostring(value[fieldName]) end str = str..separator..entry separator = ", " end str = str..'}' end return str end logging.tostring = tostring local luamaj, luamin = _VERSION:match("Lua (%d+)%.(%d+)") if tonumber(luamaj) == 5 and tonumber(luamin) < 2 then -- still create 'logging' global for Lua versions < 5.2 _G.logging = logging end return logging
------------------------------------------------------------------------------- -- includes a new tostring function that handles tables recursively -- -- @author Danilo Tuler (tuler@ideais.com.br) -- @author Andre Carregal (info@keplerproject.org) -- @author Thiago Costa Ponte (thiago@ideais.com.br) -- -- @copyright 2004-2013 Kepler Project ------------------------------------------------------------------------------- local type, table, string, _tostring, tonumber = type, table, string, tostring, tonumber local select = select local error = error local format = string.format local pairs = pairs local ipairs = ipairs local logging = { -- Meta information _COPYRIGHT = "Copyright (C) 2004-2013 Kepler Project", _DESCRIPTION = "A simple API to use logging features in Lua", _VERSION = "LuaLogging 1.3.0", -- The DEBUG Level designates fine-grained instring.formational events that are most -- useful to debug an application DEBUG = "DEBUG", -- The INFO level designates instring.formational messages that highlight the -- progress of the application at coarse-grained level INFO = "INFO", -- The WARN level designates potentially harmful situations WARN = "WARN", -- The ERROR level designates error events that might still allow the -- application to continue running ERROR = "ERROR", -- The FATAL level designates very severe error events that will presumably -- lead the application to abort FATAL = "FATAL", } local LEVEL = {"DEBUG", "INFO", "WARN", "ERROR", "FATAL"} local MAX_LEVELS = #LEVEL -- make level names to order for i=1,MAX_LEVELS do LEVEL[LEVEL[i]] = i end -- private log function, with support for formating a complex log message. local function LOG_MSG(self, level, fmt, ...) local f_type = type(fmt) if f_type == 'string' then if select('#', ...) > 0 then local status, msg = pcall(format, fmt, ...) if status then return self:append(level, msg) else return self:append(level, "Error formatting log message: " .. msg) end else -- only a single string, no formating needed. return self:append(level, fmt) end elseif f_type == 'function' then -- fmt should be a callable function which returns the message to log return self:append(level, fmt(...)) end -- fmt is not a string and not a function, just call tostring() on it. return self:append(level, logging.tostring(fmt)) end -- create the proxy functions for each log level. local LEVEL_FUNCS = {} for i=1,MAX_LEVELS do local level = LEVEL[i] LEVEL_FUNCS[i] = function(self, ...) -- no level checking needed here, this function will only be called if it's level is active. return LOG_MSG(self, level, ...) end end -- do nothing function for disabled levels. local function disable_level() end -- improved assertion function. local function assert(exp, ...) -- if exp is true, we are finished so don't do any processing of the parameters if exp then return exp, ... end -- assertion failed, raise error error(format(...), 2) end ------------------------------------------------------------------------------- -- Creates a new logger object -- @param append Function used by the logger to append a message with a -- log-level to the log stream. -- @return Table representing the new logger object. ------------------------------------------------------------------------------- function logging.new(append) if type(append) ~= "function" then return nil, "Appender must be a function." end local logger = {} logger.append = append logger.setLevel = function (self, level) local order = LEVEL[level] assert(order, "undefined level `%s'", _tostring(level)) if self.level then self:log(logging.WARN, "Logger: changing loglevel from %s to %s", self.level, level) end self.level = level self.level_order = order -- enable/disable levels for i=1,MAX_LEVELS do local name = LEVEL[i]:lower() if i >= order then self[name] = LEVEL_FUNCS[i] else self[name] = disable_level end end end -- generic log function. logger.log = function (self, level, ...) local order = LEVEL[level] assert(order, "undefined level `%s'", _tostring(level)) if order < self.level_order then return end return LOG_MSG(self, level, ...) end -- initialize log level. logger:setLevel(logging.DEBUG) return logger end ------------------------------------------------------------------------------- -- Prepares the log message ------------------------------------------------------------------------------- function logging.prepareLogMsg(pattern, dt, level, message) local logMsg = pattern or "%date %level %message\n" message = string.gsub(message, "%%", "%%%%") logMsg = string.gsub(logMsg, "%%date", dt) logMsg = string.gsub(logMsg, "%%level", level) logMsg = string.gsub(logMsg, "%%message", message) return logMsg end ------------------------------------------------------------------------------- -- Converts a Lua value to a string -- -- Converts Table fields in alphabetical order ------------------------------------------------------------------------------- local function tostring(value) local str = '' if (type(value) ~= 'table') then if (type(value) == 'string') then str = string.format("%q", value) else str = _tostring(value) end else local strTable = {} local numTable = {} local mapping = {} for k, v in pairs(value) do if type(k) == 'number' then numTable[k] = tostring(v) else mapping[tostring(key)] = mapping[tostring(key)] or {} table.insert(strTable, tostring(key)) table.insert(mapping[tostring(key)], key) end end table.sort(strTable) str = str..'{' local separator = "" local entry = "" for _, v in ipairs(numTable) do str = str..separator..v separator = ", " for _, fieldName in ipairs(strTable) do for _, field in ipairs(mapping[fieldName]) do str = str..separator..fieldName.." = "..tostring(value[field]) separator = ", " end end str = str..'}' end return str end logging.tostring = tostring local luamaj, luamin = _VERSION:match("Lua (%d+)%.(%d+)") if tonumber(luamaj) == 5 and tonumber(luamin) < 2 then -- still create 'logging' global for Lua versions < 5.2 _G.logging = logging end return logging
Thorough rewrite of tostring. Hopefully all fix, no breakage.
Thorough rewrite of tostring. Hopefully all fix, no breakage.
Lua
mit
mwchase/log4l
3e2ab58032b1fdeb2ffc1060f46583f1162df928
scen_edit/state/default_state.lua
scen_edit/state/default_state.lua
DefaultState = AbstractState:extends{} function DefaultState:init() SB.SetMouseCursor() self.__clickedObjectID = nil self.__clickedObjectBridge = nil end function DefaultState:MousePress(mx, my, button) self.__clickedObjectID = nil self.__clickedObjectBridge = nil if Spring.GetGameRulesParam("sb_gameMode") ~= "dev" or button ~= 1 then return end local selection = SB.view.selectionManager:GetSelection() local selCount = SB.view.selectionManager:GetSelectionCount() local _, ctrl = Spring.GetModKeyState() if ctrl and selCount > 0 then -- TODO: There should be a cleaner way to disable some types of editing interactions during play if Spring.GetGameRulesParam("sb_gameMode") == "dev" then return true else return false end end local isDoubleClick = false local currentTime = os.clock() if self.__lastClick and currentTime - self.__lastClick < 0.2 then isDoubleClick = true end self.__lastClick = currentTime local result, objectID = SB.TraceScreenRay(mx, my) -- TODO: Instead of letting Spring handle it, maybe we should capture the -- event and draw the screen rectangle ourselves if result == "ground" or result == "sky" then SB.stateManager:SetState(RectangleSelectState(mx, my)) return end if not SB.lockTeam and result == "unit" then local unitTeamID = Spring.GetUnitTeam(objectID) if Spring.GetMyTeamID() ~= unitTeamID or Spring.GetSpectatingState() then if SB.FunctionExists(Spring.AssignPlayerToTeam, "Player change") then local cmd = ChangePlayerTeamCommand(Spring.GetMyPlayerID(), unitTeamID) SB.commandManager:execute(cmd) end end end local bridge = ObjectBridge.GetObjectBridge(result) local objects = selection[result] or {} local _, coords = SB.TraceScreenRay(mx, my, {onlyCoords = true}) local pos = bridge.s11n:Get(objectID, "pos") local x, y, z = pos.x, pos.y, pos.z -- it's possible that there is no ground behind (if object is near the map edge) if coords == nil then coords = { x, y, z } end self.dragDiffX, self.dragDiffZ = x - coords[1], z - coords[3] self.__clickedObjectID = objectID self.__clickedObjectBridge = bridge self.__wasSelected = false for _, oldObjectID in pairs(objects) do if oldObjectID == objectID then if isDoubleClick then if bridge.OnDoubleClick then local res = bridge.OnDoubleClick(objectID, coords[1], coords[2], coords[3]) if res ~= nil then return res end end elseif bridge.OnClick then local res = bridge.OnClick(objectID, coords[1], coords[2], coords[3]) if res ~= nil then return res end end self.__wasSelected = true end end return true end function DefaultState:MouseMove(x, y, dx, dy, button) local selection = SB.view.selectionManager:GetSelection() local selCount = SB.view.selectionManager:GetSelectionCount() if selCount == 0 then return end local _, ctrl, _, shift = Spring.GetModKeyState() if ctrl then if not shift then SB.stateManager:SetState(RotateObjectState()) return end local draggable = false for selType, selected in pairs(selection) do local bridge = ObjectBridge.GetObjectBridge(selType) if not bridge.NoHorizontalDrag and not bridge.NoDrag then if next(selected) ~= nil then draggable = true end end if draggable then break end end if draggable then SB.stateManager:SetState(DragHorizontalObjectState()) end return end if self.__clickedObjectID and self.__wasSelected then SB.stateManager:SetState(DragObjectState( self.__clickedObjectID, self.__clickedObjectBridge, self.dragDiffX, self.dragDiffZ) ) end end function DefaultState:MouseRelease(...) if self.__clickedObjectID then local objType = self.__clickedObjectBridge.name local _, _, _, shift = Spring.GetModKeyState() if shift then local selection = SB.view.selectionManager:GetSelection() if Table.Contains(selection[objType], self.__clickedObjectID) then local indx = Table.GetIndex(selection[objType], self.__clickedObjectID) table.remove(selection[objType], indx) else table.insert(selection[objType], self.__clickedObjectID) end SB.view.selectionManager:Select(selection) else SB.view.selectionManager:Select({ [objType] = {self.__clickedObjectID}}) end end end function DefaultState:KeyPress(key, mods, isRepeat, label, unicode) if self:super("KeyPress", key, mods, isRepeat, label, unicode) then return true end local action = Action.GetActionsForKeyPress( true, key, mods, isRepeat, label, unicode ) if action then action:execute() return true end if key == KEYSYMS.G then local selection = SB.view.selectionManager:GetSelection() local moveObjectID = nil local bridge = nil for selType, selected in pairs(selection) do _, moveObjectID = next(selected) if moveObjectID ~= nil then bridge = ObjectBridge.GetObjectBridge(selType) break end end if moveObjectID ~= nil then local mx, my = Spring.GetMouseState() local result, coords = Spring.TraceScreenRay(mx, my, true) local x, z = 0, 0 if result == "ground" then local objectPos = bridge.s11n:Get(moveObjectID, "pos") x = objectPos.x - coords[1] z = objectPos.z - coords[3] end SB.stateManager:SetState(DragObjectState( moveObjectID, bridge, x, z) ) end return true elseif key == KEYSYMS.R then -- TODO: Doesn't make sense to have rotation state possible with both R and ctrl-click -- Get rid of ctrl-click? local hasSelected = false local selection = SB.view.selectionManager:GetSelection() for selType, selected in pairs(selection) do _, moveObjectID = next(selected) if moveObjectID ~= nil then hasSelected = true break end end if hasSelected then SB.stateManager:SetState(RotateObjectState()) end end return false end
DefaultState = AbstractState:extends{} function DefaultState:init() SB.SetMouseCursor() self.__clickedObjectID = nil self.__clickedObjectBridge = nil end function DefaultState:MousePress(mx, my, button) self.__clickedObjectID = nil self.__clickedObjectBridge = nil if Spring.GetGameRulesParam("sb_gameMode") ~= "dev" or button ~= 1 then return end local selection = SB.view.selectionManager:GetSelection() local selCount = SB.view.selectionManager:GetSelectionCount() local _, ctrl = Spring.GetModKeyState() if ctrl and selCount > 0 then -- TODO: There should be a cleaner way to disable some types of editing interactions during play if Spring.GetGameRulesParam("sb_gameMode") == "dev" then return true else return false end end local isDoubleClick = false local currentTime = os.clock() if self.__lastClick and currentTime - self.__lastClick < 0.2 then isDoubleClick = true end self.__lastClick = currentTime local result, objectID = SB.TraceScreenRay(mx, my) -- TODO: Instead of letting Spring handle it, maybe we should capture the -- event and draw the screen rectangle ourselves if result == "ground" or result == "sky" then SB.stateManager:SetState(RectangleSelectState(mx, my)) return end if not SB.lockTeam and result == "unit" then local unitTeamID = Spring.GetUnitTeam(objectID) if Spring.GetMyTeamID() ~= unitTeamID or Spring.GetSpectatingState() then if SB.FunctionExists(Spring.AssignPlayerToTeam, "Player change") then local cmd = ChangePlayerTeamCommand(Spring.GetMyPlayerID(), unitTeamID) SB.commandManager:execute(cmd) end end end local bridge = ObjectBridge.GetObjectBridge(result) local objects = selection[result] or {} local _, coords = SB.TraceScreenRay(mx, my, {onlyCoords = true}) local pos = bridge.s11n:Get(objectID, "pos") local x, y, z = pos.x, pos.y, pos.z -- it's possible that there is no ground behind (if object is near the map edge) if coords == nil then coords = { x, y, z } end self.dragDiffX, self.dragDiffZ = x - coords[1], z - coords[3] self.__clickedObjectID = objectID self.__clickedObjectBridge = bridge self.__wasSelected = false for _, oldObjectID in pairs(objects) do if oldObjectID == objectID then if isDoubleClick then if bridge.OnDoubleClick then local res = bridge.OnDoubleClick(objectID, coords[1], coords[2], coords[3]) if res ~= nil then return res end end elseif bridge.OnClick then local res = bridge.OnClick(objectID, coords[1], coords[2], coords[3]) if res ~= nil then return res end end self.__wasSelected = true end end return true end function DefaultState:MouseMove(x, y, dx, dy, button) local selection = SB.view.selectionManager:GetSelection() local selCount = SB.view.selectionManager:GetSelectionCount() if selCount == 0 then return end local _, ctrl, _, shift = Spring.GetModKeyState() if ctrl then if not shift then SB.stateManager:SetState(RotateObjectState()) return end local draggable = false for selType, selected in pairs(selection) do local bridge = ObjectBridge.GetObjectBridge(selType) if not bridge.NoHorizontalDrag and not bridge.NoDrag then if next(selected) ~= nil then draggable = true end end if draggable then break end end if draggable then SB.stateManager:SetState(DragHorizontalObjectState()) end return end if self.__clickedObjectID and self.__wasSelected then SB.stateManager:SetState(DragObjectState( self.__clickedObjectID, self.__clickedObjectBridge, self.dragDiffX, self.dragDiffZ) ) end end function DefaultState:MouseRelease(...) if self.__clickedObjectID then local objType = self.__clickedObjectBridge.name local _, _, _, shift = Spring.GetModKeyState() if shift then local selection = SB.view.selectionManager:GetSelection() if Table.Contains(selection[objType], self.__clickedObjectID) then local indx = Table.GetIndex(selection[objType], self.__clickedObjectID) table.remove(selection[objType], indx) else table.insert(selection[objType], self.__clickedObjectID) end SB.view.selectionManager:Select(selection) else SB.view.selectionManager:Select({ [objType] = {self.__clickedObjectID}}) end end end function DefaultState:KeyPress(key, mods, isRepeat, label, unicode) if self:super("KeyPress", key, mods, isRepeat, label, unicode) then return true end local action = Action.GetActionsForKeyPress( true, key, mods, isRepeat, label, unicode ) if action then action:execute() return true end if key == KEYSYMS.G then local selection = SB.view.selectionManager:GetSelection() local moveObjectID local bridge for selType, selected in pairs(selection) do moveObjectID = select(2, next(selected)) if moveObjectID ~= nil then bridge = ObjectBridge.GetObjectBridge(selType) break end end if moveObjectID ~= nil then local mx, my = Spring.GetMouseState() local result, coords = Spring.TraceScreenRay(mx, my, true) local x, z = 0, 0 if result == "ground" then local objectPos = bridge.s11n:Get(moveObjectID, "pos") x = objectPos.x - coords[1] z = objectPos.z - coords[3] end SB.stateManager:SetState(DragObjectState( moveObjectID, bridge, x, z) ) end return true elseif key == KEYSYMS.R then -- TODO: Doesn't make sense to have rotation state possible with both R and ctrl-click -- Get rid of ctrl-click? local hasSelected = false local selection = SB.view.selectionManager:GetSelection() local moveObjectID for selType, selected in pairs(selection) do moveObjectID = select(2, next(selected)) if moveObjectID ~= nil then hasSelected = true break end end if hasSelected then SB.stateManager:SetState(RotateObjectState()) end end return false end
fix travis
fix travis
Lua
mit
Spring-SpringBoard/SpringBoard-Core,Spring-SpringBoard/SpringBoard-Core
98cbf9edb71807ab3261cf5cd8e746d830eb2ee2
Quadtastic/common.lua
Quadtastic/common.lua
local current_folder = ... and (...):match '(.-%.?)[^%.]+$' or '' local libquadtastic = require(current_folder.. ".libquadtastic") -- Utility functions that don't deserve their own module local common = {} function common.trim_whitespace(s) -- Trim leading whitespace s = string.gmatch(s, "%s*(%S[%s%S]*)")() -- Trim trailing whitespace s = string.gmatch(s, "([%s%S]*%S)%s*")() return s end function common.get_version() local version_info = love.filesystem.read("res/version.txt") if version_info then return common.trim_whitespace(version_info) else return "Unknown version" end end function common.get_edition() local edition_info = love.filesystem.read("res/edition.txt") if edition_info then return common.trim_whitespace(edition_info) end end -- Load imagedata from outside the game's source and save folder function common.load_imagedata(filepath) local filehandle, err = io.open(filepath, "rb") if err then error(err, 0) end local filecontent = filehandle:read("*a") filehandle:close() return love.image.newImageData( love.filesystem.newFileData(filecontent, 'img', 'file')) end -- Load an image from outside the game's source and save folder function common.load_image(filepath) local imagedata = common.load_imagedata(filepath) return love.graphics.newImage(imagedata) end -- Split a filepath into the path of the containing directory and a filename. -- Note that a trailing slash will result in an empty filename function common.split(filepath) local dirname, basename = string.gmatch(filepath, "(.*/)([^/]*)")() return dirname, basename end -- Returns the filename without extension as the first return value, and the -- extension as the second return value function common.split_extension(filename) return string.gmatch(filename, "(.*)%.([^%.]*)")() end local function export_quad(handle, quadtable) handle(string.format( "{x = %d, y = %d, w = %d, h = %d}", quadtable.x, quadtable.y, quadtable.w, quadtable.h)) end -- Checks if a given string qualifies as a Lua Name, see "Lexical Conventions" function common.is_lua_Name(str) -- Names (also called identifiers) in Lua can be any string of letters, -- digits, and underscores, not beginning with a digit. -- http://www.lua.org/manual/5.1/manual.html#2.1 return str and str == string.gmatch(str, "[A-Za-z_][A-Za-z0-9_]*")() end local function escape(str) str = string.gsub(str, "\\", "\\\\") str = string.gsub(str, "\"", "\\\"") return str end local function export_table_content(handle, tab, indentation) local numeric_keys = {} local string_keys = {} for k in pairs(tab) do if type(k) == "number" then table.insert(numeric_keys, k) elseif type(k) == "string" then table.insert(string_keys, k) end end table.sort(numeric_keys) table.sort(string_keys) local function export_pair(k, v) handle(string.rep(" ", indentation)) if type(k) == "string" then if common.is_lua_Name(k) then handle(string.format("%s = ", k)) else handle(string.format("[\"%s\"] = ", escape(k))) end elseif type(k) ~= "number" then error("Cannot handle table keys of type "..type(k)) end if type(v) == "table" then -- Check if it is a quad table, in which case we use a simpler function if libquadtastic.is_quad(v) then export_quad(handle, v) else handle("{\n") export_table_content(handle, v, indentation+1) handle(string.rep(" ", indentation)) handle("}") end elseif type(v) == "number" then handle(tostring(v)) elseif type(v) == "string" then handle("\"", v, "\"") else error("Cannot handle table values of type "..type(v)) end handle(",\n") end for _, k in ipairs(numeric_keys) do local v = tab[k] export_pair(k, v) end for _, k in ipairs(string_keys) do local v = tab[k] export_pair(k, v) end end function common.export_table_content(handle, tab) handle("return {\n") export_table_content(handle, tab, 1) handle("}\n") end function common.export_table_to_file(filehandle, tab) local writer = common.get_writer(filehandle) common.export_table_content(writer, tab) filehandle:close() end -- The name of the "exporter" that exports the quads as a quadfile. common.reserved_name_save = "Quadtastic quadfile" -- This is a table that exposes the default exporter in a way that is compatible -- with custom exporters. common.exporter_table = { name = common.reserved_name_save, ext = "lua", export = common.export_table_content, } function common.get_writer(filehandle) return function(...) filehandle:write(...) end end function common.serialize_table(tab) local strings = {} local function handle(...) for _,string in ipairs({...}) do table.insert(strings, string) end end common.export_table_content(handle, tab) return table.concat(strings) end return common
local current_folder = ... and (...):match '(.-%.?)[^%.]+$' or '' local libquadtastic = require(current_folder.. ".libquadtastic") -- Utility functions that don't deserve their own module local common = {} function common.trim_whitespace(s) -- Trim leading whitespace s = string.gmatch(s, "%s*(%S[%s%S]*)")() -- Trim trailing whitespace s = string.gmatch(s, "([%s%S]*%S)%s*")() return s end function common.get_version() local version_info = love.filesystem.read("res/version.txt") if version_info then return common.trim_whitespace(version_info) else return "Unknown version" end end function common.get_edition() local edition_info = love.filesystem.read("res/edition.txt") if edition_info then return common.trim_whitespace(edition_info) end end -- Load imagedata from outside the game's source and save folder function common.load_imagedata(filepath) local filehandle, err = io.open(filepath, "rb") if err then error(err, 0) end local filecontent = filehandle:read("*a") filehandle:close() return love.image.newImageData( love.filesystem.newFileData(filecontent, 'img', 'file')) end -- Load an image from outside the game's source and save folder function common.load_image(filepath) local imagedata = common.load_imagedata(filepath) return love.graphics.newImage(imagedata) end -- Split a filepath into the path of the containing directory and a filename. -- Note that a trailing slash will result in an empty filename function common.split(filepath) local dirname, basename = string.gmatch(filepath, "(.*/)([^/]*)")() return dirname, basename end -- Returns the filename without extension as the first return value, and the -- extension as the second return value function common.split_extension(filename) return string.gmatch(filename, "(.*)%.([^%.]*)")() end local function export_quad(handle, quadtable) handle(string.format( "{x = %d, y = %d, w = %d, h = %d}", quadtable.x, quadtable.y, quadtable.w, quadtable.h)) end -- Checks if a given string qualifies as a Lua Name, see "Lexical Conventions" function common.is_lua_Name(str) -- Names (also called identifiers) in Lua can be any string of letters, -- digits, and underscores, not beginning with a digit. -- http://www.lua.org/manual/5.1/manual.html#2.1 return str and str == string.gmatch(str, "[A-Za-z_][A-Za-z0-9_]*")() end local function escape(str) str = string.gsub(str, "\\", "\\\\") str = string.gsub(str, "\"", "\\\"") return str end local function export_table_content(handle, tab, indentation) local numeric_keys = {} local string_keys = {} for k in pairs(tab) do if type(k) == "number" then table.insert(numeric_keys, k) elseif type(k) == "string" then table.insert(string_keys, k) end end table.sort(numeric_keys) table.sort(string_keys) local function export_pair(k, v) handle(string.rep(" ", indentation)) if type(k) == "string" then if common.is_lua_Name(k) then handle(string.format("%s = ", k)) else handle(string.format("[\"%s\"] = ", escape(k))) end elseif type(k) ~= "number" then error("Cannot handle table keys of type "..type(k)) end if type(v) == "table" then -- Check if it is a quad table, in which case we use a simpler function if libquadtastic.is_quad(v) then export_quad(handle, v) else handle("{\n") export_table_content(handle, v, indentation+1) handle(string.rep(" ", indentation)) handle("}") end elseif type(v) == "number" then handle(tostring(v)) elseif type(v) == "string" then handle("\"", v, "\"") elseif type(v) == "boolean" then handle(tostring(v)) else error("Cannot handle table values of type "..type(v)) end handle(",\n") end for _, k in ipairs(numeric_keys) do local v = tab[k] export_pair(k, v) end for _, k in ipairs(string_keys) do local v = tab[k] export_pair(k, v) end end function common.export_table_content(handle, tab) handle("return {\n") export_table_content(handle, tab, 1) handle("}\n") end function common.export_table_to_file(filehandle, tab) local writer = common.get_writer(filehandle) common.export_table_content(writer, tab) filehandle:close() end -- The name of the "exporter" that exports the quads as a quadfile. common.reserved_name_save = "Quadtastic quadfile" -- This is a table that exposes the default exporter in a way that is compatible -- with custom exporters. common.exporter_table = { name = common.reserved_name_save, ext = "lua", export = common.export_table_content, } function common.get_writer(filehandle) return function(...) filehandle:write(...) end end function common.serialize_table(tab) local strings = {} local function handle(...) for _,string in ipairs({...}) do table.insert(strings, string) end end common.export_table_content(handle, tab) return table.concat(strings) end return common
Fix missing export for boolean types in common module
Fix missing export for boolean types in common module
Lua
mit
25A0/Quadtastic,25A0/Quadtastic
3532b216ce74a93c769cbba08a65199b738a32b6
mock/component/InputListener.lua
mock/component/InputListener.lua
module 'mock' --[[ each InputScript will hold a listener to responding input sensor filter [ mouse, keyboard, touch, joystick ] ]] function installInputListener( self, option ) option = option or {} local inputDevice = option['device'] or mock.getDefaultInputDevice() local refuseMockUpInput = option['no_mockup'] == true ----link callbacks local mouseCallback = false local keyboardCallback = false local touchCallback = false local joystickCallback = false local sensors = option['sensors'] or false if not sensors or table.index( sensors, 'mouse' ) then ----MouseEvent local onMouseEvent = self.onMouseEvent local onMouseDown = self.onMouseDown local onMouseUp = self.onMouseUp local onMouseMove = self.onMouseMove local onMouseEnter = self.onMouseEnter local onMouseLeave = self.onMouseLeave local onScroll = self.onScroll if onMouseDown or onMouseUp or onMouseMove or onScroll or onMouseLeave or onMouseEnter or onMouseEvent then mouseCallback = function( ev, x, y, btn, mock ) if mock and refuseMockUpInput then return end if ev == 'move' then if onMouseMove then onMouseMove( self, x, y, mock ) end elseif ev == 'down' then if onMouseDown then onMouseDown( self, btn, x, y, mock ) end elseif ev == 'up' then if onMouseUp then onMouseUp ( self, btn, x, y, mock ) end elseif ev == 'scroll' then if onScroll then onScroll ( self, x, y, mock ) end elseif ev == 'enter' then if onMouseEnter then onMouseEnter ( self, mock ) end elseif ev == 'leave' then if onMouseLeave then onMouseLeave ( self, mock ) end end if onMouseEvent then return onMouseEvent( self, ev, x, y, btn, mock ) end end inputDevice:addMouseListener( mouseCallback ) end end if not sensors or table.index( sensors, 'touch' ) then ----TouchEvent local onTouchEvent = self.onTouchEvent local onTouchDown = self.onTouchDown local onTouchUp = self.onTouchUp local onTouchMove = self.onTouchMove local onTouchCancel = self.onTouchCancel if onTouchDown or onTouchUp or onTouchMove or onTouchEvent then touchCallback = function( ev, id, x, y, mock ) if mock and refuseMockUpInput then return end if ev == 'move' then if onTouchMove then onTouchMove( self, id, x, y, mock ) end elseif ev == 'down' then if onTouchDown then onTouchDown( self, id, x, y, mock ) end elseif ev == 'up' then if onTouchUp then onTouchUp ( self, id, x, y, mock ) end elseif ev == 'cancel' then if onTouchCancel then onTouchCancel( self ) end end if onTouchEvent then return onTouchEvent( self, ev, id, x, y, mock ) end end inputDevice:addTouchListener( touchCallback ) end end ----KeyEvent if not sensors or table.index( sensors, 'keyboard' ) then local onKeyEvent = self.onKeyEvent local onKeyDown = self.onKeyDown local onKeyUp = self.onKeyUp if onKeyDown or onKeyUp or onKeyEvent then keyboardCallback = function( key, down, mock ) if mock and refuseMockUpInput then return end if down then if onKeyDown then onKeyDown( self, key, mock ) end else if onKeyUp then onKeyUp ( self, key, mock ) end end if onKeyEvent then return onKeyEvent( self, key, down, mock ) end end inputDevice:addKeyboardListener( keyboardCallback ) end end ---JOYSTICK EVNET if not sensors or table.index( sensors, 'joystick' ) then local onJoyButtonDown = self.onJoyButtonDown local onJoyButtonUp = self.onJoyButtonUp local onJoyAxisMove = self.onJoyAxisMove if onJoyButtonDown or onJoyButtonUp or onJoyAxisMove then joystickCallback = function( ev, joyId, btnId, axisId, value, mock ) -- print( ev, joyid, btnId, axisId, value ) if mock and refuseMockUpInput then return end if ev == 'down' then if onJoyButtonDown then onJoyButtonDown( self, joyId, btnId, mock ) end elseif ev == 'up' then if onJoyButtonUp then onJoyButtonUp( self, joyId, btnId, mock ) end elseif ev == 'axis' then if onJoyAxisMove then onJoyAxisMove( self, joyId, axisId, value ) end end end inputDevice:addJoystickListener( joystickCallback ) end end --MOTION Callbakcs self.__inputListenerData = { mouseCallback = mouseCallback, keyboardCallback = keyboardCallback, touchCallback = touchCallback, joystickCallback = joystickCallback, inputDevice = inputDevice } end function uninstallInputListener( self ) local data = self.__inputListenerData if not data then return end local inputDevice = data.inputDevice if data.mouseCallback then inputDevice:removeMouseListener( data.mouseCallback ) end if data.keyboardCallback then inputDevice:removeKeyboardListener( data.keyboardCallback ) end if data.touchCallback then inputDevice:removeTouchListener( data.touchCallback ) end if data.joystickCallback then inputDevice:removeJoystickListener( data.joystickCallback ) end end --[[ input event format: KeyDown ( keyname ) KeyUp ( keyname ) MouseMove ( x, y ) MouseDown ( btn, x, y ) MouseUp ( btn, x, y ) RawMouseMove ( id, x, y ) ---many mouse (??) RawMouseDown ( id, btn, x, y ) ---many mouse (??) RawMouseUp ( id, btn, x, y ) ---many mouse (??) TouchDown ( id, x, y ) TouchUp ( id, x, y ) TouchMove ( id, x, y ) TouchCancel ( ) JoystickMove( id, x, y ) JoystickDown( btn ) JoystickUp ( btn ) LEVEL: get from service COMPASS: get from service ]]
module 'mock' --[[ each InputScript will hold a listener to responding input sensor filter [ mouse, keyboard, touch, joystick ] ]] function installInputListener( self, option ) option = option or {} local inputDevice = option['device'] or mock.getDefaultInputDevice() local refuseMockUpInput = option['no_mockup'] == true ----link callbacks local mouseCallback = false local keyboardCallback = false local touchCallback = false local joystickCallback = false local sensors = option['sensors'] or false if not sensors or table.index( sensors, 'mouse' ) then ----MouseEvent local onMouseEvent = self.onMouseEvent local onMouseDown = self.onMouseDown local onMouseUp = self.onMouseUp local onMouseMove = self.onMouseMove local onMouseEnter = self.onMouseEnter local onMouseLeave = self.onMouseLeave local onScroll = self.onScroll if onMouseDown or onMouseUp or onMouseMove or onScroll or onMouseLeave or onMouseEnter or onMouseEvent then mouseCallback = function( ev, x, y, btn, mock ) if mock and refuseMockUpInput then return end if ev == 'move' then if onMouseMove then onMouseMove( self, x, y, mock ) end elseif ev == 'down' then if onMouseDown then onMouseDown( self, btn, x, y, mock ) end elseif ev == 'up' then if onMouseUp then onMouseUp ( self, btn, x, y, mock ) end elseif ev == 'scroll' then if onScroll then onScroll ( self, x, y, mock ) end elseif ev == 'enter' then if onMouseEnter then onMouseEnter ( self, mock ) end elseif ev == 'leave' then if onMouseLeave then onMouseLeave ( self, mock ) end end if onMouseEvent then return onMouseEvent( self, ev, x, y, btn, mock ) end end inputDevice:addMouseListener( mouseCallback ) end end if not sensors or table.index( sensors, 'touch' ) then ----TouchEvent local onTouchEvent = self.onTouchEvent local onTouchDown = self.onTouchDown local onTouchUp = self.onTouchUp local onTouchMove = self.onTouchMove local onTouchCancel = self.onTouchCancel if onTouchDown or onTouchUp or onTouchMove or onTouchEvent then touchCallback = function( ev, id, x, y, mock ) if mock and refuseMockUpInput then return end if ev == 'move' then if onTouchMove then onTouchMove( self, id, x, y, mock ) end elseif ev == 'down' then if onTouchDown then onTouchDown( self, id, x, y, mock ) end elseif ev == 'up' then if onTouchUp then onTouchUp ( self, id, x, y, mock ) end elseif ev == 'cancel' then if onTouchCancel then onTouchCancel( self ) end end if onTouchEvent then return onTouchEvent( self, ev, id, x, y, mock ) end end inputDevice:addTouchListener( touchCallback ) end end ----KeyEvent if not sensors or table.index( sensors, 'keyboard' ) then local onKeyEvent = self.onKeyEvent local onKeyDown = self.onKeyDown local onKeyUp = self.onKeyUp if onKeyDown or onKeyUp or onKeyEvent then keyboardCallback = function( key, down, mock ) if mock and refuseMockUpInput then return end if down then if onKeyDown then onKeyDown( self, key, mock ) end else if onKeyUp then onKeyUp ( self, key, mock ) end end if onKeyEvent then return onKeyEvent( self, key, down, mock ) end end inputDevice:addKeyboardListener( keyboardCallback ) end end ---JOYSTICK EVNET if not sensors or table.index( sensors, 'joystick' ) then local onJoyButtonDown = self.onJoyButtonDown local onJoyButtonUp = self.onJoyButtonUp local onJoyButtonEvent = self.onJoyButtonEvent local onJoyAxisMove = self.onJoyAxisMove if onJoyButtonDown or onJoyButtonUp or onJoyAxisMove or onJoyButtonEvent then joystickCallback = function( ev, joyId, btnId, axisId, value, mock ) -- print( ev, joyid, btnId, axisId, value ) if mock and refuseMockUpInput then return end if ev == 'down' then if onJoyButtonDown then onJoyButtonDown( self, joyId, btnId, mock ) end if onJoyButtonEvent then onJoyButtonEvent( self, joyId, btnId, true, mock ) end elseif ev == 'up' then if onJoyButtonUp then onJoyButtonUp( self, joyId, btnId, mock ) end if onJoyButtonEvent then onJoyButtonEvent( self, joyId, btnId, false, mock ) end elseif ev == 'axis' then if onJoyAxisMove then onJoyAxisMove( self, joyId, axisId, value ) end end end inputDevice:addJoystickListener( joystickCallback ) end end --MOTION Callbakcs self.__inputListenerData = { mouseCallback = mouseCallback, keyboardCallback = keyboardCallback, touchCallback = touchCallback, joystickCallback = joystickCallback, inputDevice = inputDevice } end function uninstallInputListener( self ) local data = self.__inputListenerData if not data then return end local inputDevice = data.inputDevice if data.mouseCallback then inputDevice:removeMouseListener( data.mouseCallback ) end if data.keyboardCallback then inputDevice:removeKeyboardListener( data.keyboardCallback ) end if data.touchCallback then inputDevice:removeTouchListener( data.touchCallback ) end if data.joystickCallback then inputDevice:removeJoystickListener( data.joystickCallback ) end end --[[ input event format: KeyDown ( keyname ) KeyUp ( keyname ) MouseMove ( x, y ) MouseDown ( btn, x, y ) MouseUp ( btn, x, y ) RawMouseMove ( id, x, y ) ---many mouse (??) RawMouseDown ( id, btn, x, y ) ---many mouse (??) RawMouseUp ( id, btn, x, y ) ---many mouse (??) TouchDown ( id, x, y ) TouchUp ( id, x, y ) TouchMove ( id, x, y ) TouchCancel ( ) JoystickMove( id, x, y ) JoystickDown( btn ) JoystickUp ( btn ) LEVEL: get from service COMPASS: get from service ]]
[fix]onJoyButtonEvent
[fix]onJoyButtonEvent
Lua
mit
tommo/mock
182a6bf469141c857a390e7661f77f038f2176f2
util/timer.lua
util/timer.lua
-- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local ns_addtimer = require "net.server".addtimer; local event = require "net.server".event; local event_base = require "net.server".event_base; local get_time = os.time; local t_insert = table.insert; local t_remove = table.remove; local ipairs, pairs = ipairs, pairs; local type = type; local data = {}; local new_data = {}; module "timer" local _add_task; if not event then function _add_task(delay, func) local current_time = get_time(); delay = delay + current_time; if delay >= current_time then t_insert(new_data, {delay, func}); else func(); end end ns_addtimer(function() local current_time = get_time(); if #new_data > 0 then for _, d in pairs(new_data) do t_insert(data, d); end new_data = {}; end for i, d in pairs(data) do local t, func = d[1], d[2]; if t <= current_time then data[i] = nil; local r = func(current_time); if type(r) == "number" then _add_task(r, func); end end end end); else local EVENT_LEAVE = (event.core and event.core.LEAVE) or -1; function _add_task(delay, func) event_base:addevent(nil, 0, function () local ret = func(); if ret then return 0, ret; else return EVENT_LEAVE; end end , delay); end end add_task = _add_task; return _M;
-- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local ns_addtimer = require "net.server".addtimer; local event = require "net.server".event; local event_base = require "net.server".event_base; local get_time = os.time; local t_insert = table.insert; local t_remove = table.remove; local ipairs, pairs = ipairs, pairs; local type = type; local data = {}; local new_data = {}; module "timer" local _add_task; if not event then function _add_task(delay, func) local current_time = get_time(); delay = delay + current_time; if delay >= current_time then t_insert(new_data, {delay, func}); else func(); end end ns_addtimer(function() local current_time = get_time(); if #new_data > 0 then for _, d in pairs(new_data) do t_insert(data, d); end new_data = {}; end for i, d in pairs(data) do local t, func = d[1], d[2]; if t <= current_time then data[i] = nil; local r = func(current_time); if type(r) == "number" then _add_task(r, func); end end end end); else local EVENT_LEAVE = (event.core and event.core.LEAVE) or -1; function _add_task(delay, func) local event_handle; event_handle = event_base:addevent(nil, 0, function () local ret = func(); if ret then return 0, ret; elseif event_handle then return EVENT_LEAVE; end end , delay); end end add_task = _add_task; return _M;
util.timer: When using libevent hold onto the event handle to stop it being collected (and the timer stopping). Fixes BOSH ghosts, thanks Flo, niekie, waqas.
util.timer: When using libevent hold onto the event handle to stop it being collected (and the timer stopping). Fixes BOSH ghosts, thanks Flo, niekie, waqas.
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
5248d443dcbb162f76c2b1de0d662d77a6ab1acc
service/launcher.lua
service/launcher.lua
local skynet = require "skynet" local core = require "skynet.core" require "skynet.manager" -- import manager apis local string = string local services = {} local command = {} local instance = {} -- for confirm (function command.LAUNCH / command.ERROR / command.LAUNCHOK) local launch_session = {} -- for command.QUERY, service_address -> session local function handle_to_address(handle) return tonumber("0x" .. string.sub(handle , 2)) end local NORET = {} function command.LIST() local list = {} for k,v in pairs(services) do list[skynet.address(k)] = v end return list end local function list_srv(ti, fmt_func, ...) local list = {} local sessions = {} local req = skynet.request() for addr in pairs(services) do local r = { addr, "debug", ... } req:add(r) sessions[r] = addr end for req, resp in req:select(ti) do local stat = resp[1] local addr = req[1] if resp then list[skynet.address(addr)] = fmt_func(stat, addr) else list[skynet.address(addr)] = fmt_func("ERROR", addr) end sessions[req] = nil end for session, addr in pairs(sessions) do list[skynet.address(addr)] = fmt_func("TIMEOUT", addr) end return list end function command.STAT(addr, ti) return list_srv(ti, function(v) return v end, "STAT") end function command.KILL(_, handle) skynet.kill(handle) local ret = { [skynet.address(handle)] = tostring(services[handle]) } services[handle] = nil return ret end function command.MEM(addr, ti) return list_srv(ti, function(kb, addr) local v = services[addr] if type(kb) == "string" then return string.format("%s (%s)", kb, v) else return string.format("%.2f Kb (%s)",kb,v) end end, "MEM") end function command.GC(addr, ti) for k,v in pairs(services) do skynet.send(k,"debug","GC") end return command.MEM(addr, ti) end function command.REMOVE(_, handle, kill) services[handle] = nil local response = instance[handle] if response then -- instance is dead response(not kill) -- return nil to caller of newservice, when kill == false instance[handle] = nil launch_session[handle] = nil end -- don't return (skynet.ret) because the handle may exit return NORET end local function launch_service(service, ...) local param = table.concat({...}, " ") local inst = skynet.launch(service, param) local session = skynet.context() local response = skynet.response() if inst then services[inst] = service .. " " .. param instance[inst] = response launch_session[inst] = session else response(false) return end return inst end function command.LAUNCH(_, service, ...) launch_service(service, ...) return NORET end function command.LOGLAUNCH(_, service, ...) local inst = launch_service(service, ...) if inst then core.command("LOGON", skynet.address(inst)) end return NORET end function command.ERROR(address) -- see serivce-src/service_lua.c -- init failed local response = instance[address] if response then response(false) launch_session[address] = nil instance[address] = nil end services[address] = nil return NORET end function command.LAUNCHOK(address) -- init notice local response = instance[address] if response then response(true, address) instance[address] = nil launch_session[address] = nil end return NORET end function command.QUERY(_, request_session) for address, session in pairs(launch_session) do if session == request_session then return address end end end -- for historical reasons, launcher support text command (for C service) skynet.register_protocol { name = "text", id = skynet.PTYPE_TEXT, unpack = skynet.tostring, dispatch = function(session, address , cmd) if cmd == "" then command.LAUNCHOK(address) elseif cmd == "ERROR" then command.ERROR(address) else error ("Invalid text command " .. cmd) end end, } skynet.dispatch("lua", function(session, address, cmd , ...) cmd = string.upper(cmd) local f = command[cmd] if f then local ret = f(address, ...) if ret ~= NORET then skynet.ret(skynet.pack(ret)) end else skynet.ret(skynet.pack {"Unknown command"} ) end end) skynet.start(function() end)
local skynet = require "skynet" local core = require "skynet.core" require "skynet.manager" -- import manager apis local string = string local services = {} local command = {} local instance = {} -- for confirm (function command.LAUNCH / command.ERROR / command.LAUNCHOK) local launch_session = {} -- for command.QUERY, service_address -> session local function handle_to_address(handle) return tonumber("0x" .. string.sub(handle , 2)) end local NORET = {} function command.LIST() local list = {} for k,v in pairs(services) do list[skynet.address(k)] = v end return list end local function list_srv(ti, fmt_func, ...) local list = {} local sessions = {} local req = skynet.request() for addr in pairs(services) do local r = { addr, "debug", ... } req:add(r) sessions[r] = addr end for req, resp in req:select(ti) do local addr = req[1] if resp then local stat = resp[1] list[skynet.address(addr)] = fmt_func(stat, addr) else list[skynet.address(addr)] = fmt_func("ERROR", addr) end sessions[req] = nil end for session, addr in pairs(sessions) do list[skynet.address(addr)] = fmt_func("TIMEOUT", addr) end return list end function command.STAT(addr, ti) return list_srv(ti, function(v) return v end, "STAT") end function command.KILL(_, handle) skynet.kill(handle) local ret = { [skynet.address(handle)] = tostring(services[handle]) } services[handle] = nil return ret end function command.MEM(addr, ti) return list_srv(ti, function(kb, addr) local v = services[addr] if type(kb) == "string" then return string.format("%s (%s)", kb, v) else return string.format("%.2f Kb (%s)",kb,v) end end, "MEM") end function command.GC(addr, ti) for k,v in pairs(services) do skynet.send(k,"debug","GC") end return command.MEM(addr, ti) end function command.REMOVE(_, handle, kill) services[handle] = nil local response = instance[handle] if response then -- instance is dead response(not kill) -- return nil to caller of newservice, when kill == false instance[handle] = nil launch_session[handle] = nil end -- don't return (skynet.ret) because the handle may exit return NORET end local function launch_service(service, ...) local param = table.concat({...}, " ") local inst = skynet.launch(service, param) local session = skynet.context() local response = skynet.response() if inst then services[inst] = service .. " " .. param instance[inst] = response launch_session[inst] = session else response(false) return end return inst end function command.LAUNCH(_, service, ...) launch_service(service, ...) return NORET end function command.LOGLAUNCH(_, service, ...) local inst = launch_service(service, ...) if inst then core.command("LOGON", skynet.address(inst)) end return NORET end function command.ERROR(address) -- see serivce-src/service_lua.c -- init failed local response = instance[address] if response then response(false) launch_session[address] = nil instance[address] = nil end services[address] = nil return NORET end function command.LAUNCHOK(address) -- init notice local response = instance[address] if response then response(true, address) instance[address] = nil launch_session[address] = nil end return NORET end function command.QUERY(_, request_session) for address, session in pairs(launch_session) do if session == request_session then return address end end end -- for historical reasons, launcher support text command (for C service) skynet.register_protocol { name = "text", id = skynet.PTYPE_TEXT, unpack = skynet.tostring, dispatch = function(session, address , cmd) if cmd == "" then command.LAUNCHOK(address) elseif cmd == "ERROR" then command.ERROR(address) else error ("Invalid text command " .. cmd) end end, } skynet.dispatch("lua", function(session, address, cmd , ...) cmd = string.upper(cmd) local f = command[cmd] if f then local ret = f(address, ...) if ret ~= NORET then skynet.ret(skynet.pack(ret)) end else skynet.ret(skynet.pack {"Unknown command"} ) end end) skynet.start(function() end)
Fix typo: Causes an error when `resp` is false (#1260)
Fix typo: Causes an error when `resp` is false (#1260) Co-authored-by: zhouyan <6bc36f5ddf5d3999e0b9d2cbb0ed704263aa3f35@onemt.com.cn>
Lua
mit
sanikoyes/skynet,cloudwu/skynet,korialuo/skynet,xcjmine/skynet,icetoggle/skynet,xcjmine/skynet,cloudwu/skynet,hongling0/skynet,korialuo/skynet,xjdrew/skynet,xjdrew/skynet,hongling0/skynet,korialuo/skynet,icetoggle/skynet,JiessieDawn/skynet,xcjmine/skynet,wangyi0226/skynet,hongling0/skynet,pigparadise/skynet,sanikoyes/skynet,cloudwu/skynet,xjdrew/skynet,pigparadise/skynet,wangyi0226/skynet,wangyi0226/skynet,JiessieDawn/skynet,pigparadise/skynet,JiessieDawn/skynet,sanikoyes/skynet,icetoggle/skynet
7906bd06f31f95dd4874d1e01bc3177ab178e1a3
gateway/src/apicast/executor.lua
gateway/src/apicast/executor.lua
--- Executor module -- The executor has a policy chain and will simply forward the calls it -- receives to that policy chain. It also manages the 'context' that is passed -- when calling the policy chain methods. This 'context' contains information -- shared among policies. require('apicast.loader') -- to load code from deprecated paths local PolicyChain = require('apicast.policy_chain') local Policy = require('apicast.policy') local linked_list = require('apicast.linked_list') local prometheus = require('apicast.prometheus') local uuid = require('resty.jit-uuid') local setmetatable = setmetatable local ipairs = ipairs local _M = { } local mt = { __index = _M } -- forward all policy methods to the policy chain for _,phase in Policy.phases() do _M[phase] = function(self) ngx.log(ngx.DEBUG, 'executor phase: ', phase) return self.policy_chain[phase](self.policy_chain, self:context(phase)) end end function _M.new(policy_chain) return setmetatable({ policy_chain = policy_chain:freeze() }, mt) end local function build_context(executor) local config = executor.policy_chain:export() return linked_list.readwrite({}, config) end local function shared_build_context(executor) local ok, ctx = pcall(function() return ngx.ctx end) if not ok then ctx = {} end local context = ctx.context if not context then context = build_context(executor) ctx.context = context end return context end --- Shared context among policies -- @tparam string phase Nginx phase -- @treturn linked_list The context. Note: The list returned is 'read-write'. function _M:context(phase) if phase == 'init' then return build_context(self) end return shared_build_context(self) end do local policy_loader = require('apicast.policy_loader') local policies local init = _M.init function _M:init() local executed = {} for _,policy in init(self) do executed[policy.init] = true end policies = policy_loader:get_all() for _, policy in ipairs(policies) do if not executed[policy.init] then policy.init() executed[policy.init] = true end end end local init_worker = _M.init_worker function _M:init_worker() -- Need to seed the UUID in init_worker. -- Ref: https://github.com/thibaultcha/lua-resty-jit-uuid/blob/c4c0004da0c4c4cdd23644a5472ea5c0d18decbb/README.md#usage uuid.seed() local executed = {} for _,policy in init_worker(self) do executed[policy.init_worker] = true end for _, policy in ipairs(policies or policy_loader:get_all()) do if not executed[policy.init_worker] then policy.init_worker() executed[policy.init_worker] = true end end end -- balancer() cannot be forwarded directly because we want to keep track of -- the number of times the balancer phase was executed for the current -- request. That's needed for retrying the upstream request a given number -- of times. -- Having this counter in the retry policy instead of here would impose -- restrictions on the place the retry policy needs to occupy in the chain. -- The counter is used in the balancer module, which can be called from -- several policies. The counter would only be updated if the retry policy -- was run because the others than run on balancer(). function _M:balancer() local context = self:context('balancer') context.balancer_retries = (context.balancer_retries and context.balancer_retries + 1) or 0 context.peer_set_in_current_balancer_try = false return self.policy_chain.balancer(self.policy_chain, context) end function _M.reset_available_policies() policies = policy_loader:get_all() end end local metrics = _M.metrics --- Render metrics from all policies. function _M:metrics(...) metrics(self, ...) return prometheus:collect() end return _M.new(PolicyChain.default())
--- Executor module -- The executor has a policy chain and will simply forward the calls it -- receives to that policy chain. It also manages the 'context' that is passed -- when calling the policy chain methods. This 'context' contains information -- shared among policies. require('apicast.loader') -- to load code from deprecated paths local PolicyChain = require('apicast.policy_chain') local Policy = require('apicast.policy') local linked_list = require('apicast.linked_list') local prometheus = require('apicast.prometheus') local uuid = require('resty.jit-uuid') local setmetatable = setmetatable local ipairs = ipairs local _M = { } local mt = { __index = _M } -- forward all policy methods to the policy chain for _,phase in Policy.phases() do _M[phase] = function(self) ngx.log(ngx.DEBUG, 'executor phase: ', phase) return self.policy_chain[phase](self.policy_chain, self:context(phase)) end end function _M.new(policy_chain) return setmetatable({ policy_chain = policy_chain:freeze() }, mt) end local function build_context(executor) local config = executor.policy_chain:export() return linked_list.readwrite({}, config) end local function store_original_request(context) -- There are a few phases[0] that req and var are not set and API is -- disabled. The reason to call this using a pcall function is to avoid to -- define the phases manually that are error prone. Also in openresty there -- is not a good method to check this. [1] -- [0] invalid phases: init_worker, init, timer and ssl_cer -- [1] https://github.com/openresty/lua-resty-core/blob/9937f5d83367e388da4fcc1d7de2141c9e38d7e2/lib/resty/core/request.lua#L96 if context.original_request then return end pcall(function() context.original_request = linked_list.readonly({ headers = ngx.req.get_headers(), host = ngx.var.host, path = ngx.var.request_uri, uri = ngx.var.uri, server_addr = ngx.var.server_addr, }) end) end local function shared_build_context(executor) local ok, ctx = pcall(function() return ngx.ctx end) if not ok then ctx = {} end local context = ctx.context if not context then context = build_context(executor) ctx.context = context store_original_request(ctx) end return context end --- Shared context among policies -- @tparam string phase Nginx phase -- @treturn linked_list The context. Note: The list returned is 'read-write'. function _M:context(phase) if phase == 'init' then return build_context(self) end return shared_build_context(self) end do local policy_loader = require('apicast.policy_loader') local policies local init = _M.init function _M:init() local executed = {} for _,policy in init(self) do executed[policy.init] = true end policies = policy_loader:get_all() for _, policy in ipairs(policies) do if not executed[policy.init] then policy.init() executed[policy.init] = true end end end local init_worker = _M.init_worker function _M:init_worker() -- Need to seed the UUID in init_worker. -- Ref: https://github.com/thibaultcha/lua-resty-jit-uuid/blob/c4c0004da0c4c4cdd23644a5472ea5c0d18decbb/README.md#usage uuid.seed() local executed = {} for _,policy in init_worker(self) do executed[policy.init_worker] = true end for _, policy in ipairs(policies or policy_loader:get_all()) do if not executed[policy.init_worker] then policy.init_worker() executed[policy.init_worker] = true end end end -- balancer() cannot be forwarded directly because we want to keep track of -- the number of times the balancer phase was executed for the current -- request. That's needed for retrying the upstream request a given number -- of times. -- Having this counter in the retry policy instead of here would impose -- restrictions on the place the retry policy needs to occupy in the chain. -- The counter is used in the balancer module, which can be called from -- several policies. The counter would only be updated if the retry policy -- was run because the others than run on balancer(). function _M:balancer() local context = self:context('balancer') context.balancer_retries = (context.balancer_retries and context.balancer_retries + 1) or 0 context.peer_set_in_current_balancer_try = false return self.policy_chain.balancer(self.policy_chain, context) end function _M.reset_available_policies() policies = policy_loader:get_all() end end local metrics = _M.metrics --- Render metrics from all policies. function _M:metrics(...) metrics(self, ...) return prometheus:collect() end return _M.new(PolicyChain.default())
Executor: Add original request information.
Executor: Add original request information. To be able to retrieve original request information on the policies without adding/deleting headers. This change allows users to handle routing policy with the original information, full disclosure on issue #1084 Fix #1084 Signed-off-by: Eloy Coto <2a8acc28452926ceac4d9db555411743254cf5f9@gmail.com>
Lua
mit
3scale/docker-gateway,3scale/docker-gateway
675c34e367c1279cc67f258b43f7dacaf59c38da
torch7/imagenet_winners/googlenet.lua
torch7/imagenet_winners/googlenet.lua
-- adapted from nagadomi's CIFAR attempt: https://github.com/nagadomi/kaggle-cifar10-torch7/blob/cuda-convnet2/inception_model.lua local function inception(depth_dim, input_size, config, lib) local SpatialConvolution = lib[1] local SpatialMaxPooling = lib[2] local ReLU = lib[3] local depth_concat = nn.Concat(depth_dim) local conv1 = nn.Sequential() conv1:add(SpatialConvolution(input_size, config[1][1], 1, 1)):add(ReLU(true)) depth_concat:add(conv1) local conv3 = nn.Sequential() conv3:add(SpatialConvolution(input_size, config[2][1], 1, 1)):add(ReLU(true)) conv3:add(SpatialConvolution(config[2][1], config[2][2], 3, 3, 1, 1, 1, 1)):add(ReLU(true)) depth_concat:add(conv3) local conv5 = nn.Sequential() conv5:add(SpatialConvolution(input_size, config[3][1], 1, 1)):add(ReLU(true)) conv5:add(SpatialConvolution(config[3][1], config[3][2], 5, 5, 1, 1, 2, 2)):add(ReLU(true)) depth_concat:add(conv5) local pool = nn.Sequential() pool:add(SpatialMaxPooling(config[4][1], config[4][1], 1, 1, 1, 1)) pool:add(SpatialConvolution(input_size, config[4][2], 1, 1)):add(ReLU(true)) depth_concat:add(pool) return depth_concat end local function googlenet(lib) local SpatialConvolution = lib[1] local SpatialMaxPooling = lib[2] local SpatialAveragePooling = torch.type(lib[2]) == 'nn.SpatialMaxPooling' and nn.SpatialAveragePooling or cudnn.SpatialAveragePooling local ReLU = lib[3] local model = nn.Sequential() model:add(SpatialConvolution(3,64,7,7,2,2)):add(ReLU(true)) model:add(SpatialMaxPooling(3,3,2,2)) -- LRN (not added for now) model:add(SpatialConvolution(64,64,1,1)):add(ReLU(true)) model:add(SpatialConvolution(64,192,3,3)):add(ReLU(true)) -- LRN (not added for now) model:add(SpatialMaxPooling(3,3,2,2)) model:add(inception(2, 192, {{64},{96,128},{16,32},{3,32}},lib)) -- 256 model:add(inception(2, 256, {{128},{128,192},{32,96},{3,64}},lib)) -- 480 model:add(SpatialMaxPooling(3,3,2,2)) model:add(inception(2, 480, {{192},{96,208},{16,48},{3,64}},lib)) -- 4(a) model:add(inception(2, 512, {{160},{112,224},{24,64},{3,64}},lib)) -- 4(b) model:add(inception(2, 512, {{128},{128,256},{24,64},{3,64}},lib)) -- 4(c) model:add(inception(2, 512, {{112},{144,288},{32,64},{3,64}},lib)) -- 4(d) model:add(inception(2, 528, {{256},{160,320},{32,128},{3,128}},lib)) -- 4(e) (14x14x832) model:add(SpatialMaxPooling(3,3,2,2)) model:add(inception(2, 832, {{256},{160,320},{32,128},{3,128}},lib)) -- 5(a) model:add(inception(2, 832, {{384},{192,384},{48,128},{3,128}},lib)) -- 5(b) model:add(SpatialAveragePooling(5,5,1,1)) model:add(nn.View(1024)) -- model:add(nn.Dropout(0.4)) model:add(nn.Linear(1024,1000)):add(nn.ReLU(true)) -- model:add(nn.LogSoftMax()) return model,'GoogleNet', {128,3,224,224} end return googlenet
-- adapted from nagadomi's CIFAR attempt: https://github.com/nagadomi/kaggle-cifar10-torch7/blob/cuda-convnet2/inception_model.lua local function inception(depth_dim, input_size, config, lib) local SpatialConvolution = lib[1] local SpatialMaxPooling = lib[2] local ReLU = lib[3] local depth_concat = nn.Concat(depth_dim) local conv1 = nn.Sequential() conv1:add(SpatialConvolution(input_size, config[1][1], 1, 1)):add(ReLU(true)) depth_concat:add(conv1) local conv3 = nn.Sequential() conv3:add(SpatialConvolution(input_size, config[2][1], 1, 1)):add(ReLU(true)) conv3:add(SpatialConvolution(config[2][1], config[2][2], 3, 3, 1, 1, 1, 1)):add(ReLU(true)) depth_concat:add(conv3) local conv5 = nn.Sequential() conv5:add(SpatialConvolution(input_size, config[3][1], 1, 1)):add(ReLU(true)) conv5:add(SpatialConvolution(config[3][1], config[3][2], 5, 5, 1, 1, 2, 2)):add(ReLU(true)) depth_concat:add(conv5) local pool = nn.Sequential() pool:add(SpatialMaxPooling(config[4][1], config[4][1], 1, 1, 1, 1)) pool:add(SpatialConvolution(input_size, config[4][2], 1, 1)):add(ReLU(true)) depth_concat:add(pool) return depth_concat end local function googlenet(lib) local SpatialConvolution = lib[1] local SpatialMaxPooling = lib[2] local SpatialAveragePooling = torch.type(lib[2]) == 'nn.SpatialMaxPooling' and nn.SpatialAveragePooling or cudnn.SpatialAveragePooling local ReLU = lib[3] local model = nn.Sequential() model:add(SpatialConvolution(3,64,7,7,2,2,3,3)):add(ReLU(true)) model:add(SpatialMaxPooling(3,3,2,2,1,1)) -- LRN (not added for now) model:add(SpatialConvolution(64,64,1,1,1,1,0,0)):add(ReLU(true)) model:add(SpatialConvolution(64,192,3,3,1,1,1,1)):add(ReLU(true)) -- LRN (not added for now) model:add(SpatialMaxPooling(3,3,2,2,1,1)) model:add(inception(2, 192, {{ 64}, { 96,128}, {16, 32}, {3, 32}},lib)) -- 256 model:add(inception(2, 256, {{128}, {128,192}, {32, 96}, {3, 64}},lib)) -- 480 model:add(SpatialMaxPooling(3,3,2,2)) model:add(inception(2, 480, {{192}, { 96,208}, {16, 48}, {3, 64}},lib)) -- 4(a) model:add(inception(2, 512, {{160}, {112,224}, {24, 64}, {3, 64}},lib)) -- 4(b) model:add(inception(2, 512, {{128}, {128,256}, {24, 64}, {3, 64}},lib)) -- 4(c) model:add(inception(2, 512, {{112}, {144,288}, {32, 64}, {3, 64}},lib)) -- 4(d) model:add(inception(2, 528, {{256}, {160,320}, {32,128}, {3,128}},lib)) -- 4(e) (14x14x832) model:add(SpatialMaxPooling(3,3,2,2,1,1)) model:add(inception(2, 832, {{256}, {160,320}, {32,128}, {3,128}},lib)) -- 5(a) model:add(inception(2, 832, {{384}, {192,384}, {48,128}, {3,128}},lib)) -- 5(b) model:add(SpatialAveragePooling(7,7,1,1)) model:add(nn.View(1024):setNumInputDims(3)) -- model:add(nn.Dropout(0.4)) model:add(nn.Linear(1024,1000)):add(nn.ReLU(true)) -- model:add(nn.LogSoftMax()) return model,'GoogleNet', {128,3,224,224} end return googlenet
some more fixes for torch googlenet
some more fixes for torch googlenet
Lua
mit
soumith/convnet-benchmarks,soumith/convnet-benchmarks,soumith/convnet-benchmarks,soumith/convnet-benchmarks,soumith/convnet-benchmarks
855fdfee0932d98ac6453d19c94b689139d1355b
packages/lime-proto-anygw/src/anygw.lua
packages/lime-proto-anygw/src/anygw.lua
#!/usr/bin/lua local fs = require("nixio.fs") local network = require("lime.network") local libuci = require "uci" anygw = {} anygw.configured = false function anygw.anygw_mac() local anygw_mac = config.get("network", "anygw_mac") or "aa:aa:aa:%N1:%N2:aa" return utils.applyNetTemplate16(anygw_mac) end function anygw.configure(args) if anygw.configured then return end anygw.configured = true local ipv4, ipv6 = network.primary_address() local anygw_mac = anygw.anygw_mac() local anygw_mac_mask = "ff:ff:ff:00:00:00" -- bytes 4 & 5 vary depending on %N1 and %N2 by default local anygw_ipv6 = ipv6:minhost() local anygw_ipv4 = ipv4:minhost() anygw_ipv6:prefix(64) -- SLAAC only works with a /64, per RFC anygw_ipv4:prefix(ipv4:prefix()) local baseIfname = "br-lan" local argsDev = { macaddr = anygw_mac } local argsIf = { proto = "static" } argsIf.ip6addr = anygw_ipv6:string() argsIf.ipaddr = anygw_ipv4:host():string() argsIf.netmask = anygw_ipv4:mask():string() local owrtInterfaceName, _, _ = network.createMacvlanIface( baseIfname, "anygw", argsDev, argsIf ) local uci = libuci:cursor() local pfr = network.limeIfNamePrefix.."anygw_" uci:set("network", pfr.."rule6", "rule6") uci:set("network", pfr.."rule6", "src", anygw_ipv6:host():string().."/128") uci:set("network", pfr.."rule6", "lookup", "170") -- 0xaa in decimal uci:set("network", pfr.."route6", "route6") uci:set("network", pfr.."route6", "interface", owrtInterfaceName) uci:set("network", pfr.."route6", "target", anygw_ipv6:network():string().."/"..anygw_ipv6:prefix()) uci:set("network", pfr.."route6", "table", "170") uci:set("network", pfr.."rule4", "rule") uci:set("network", pfr.."rule4", "src", anygw_ipv4:host():string().."/32") uci:set("network", pfr.."rule4", "lookup", "170") uci:set("network", pfr.."route4", "route") uci:set("network", pfr.."route4", "interface", owrtInterfaceName) uci:set("network", pfr.."route4", "target", anygw_ipv4:network():string()) uci:set("network", pfr.."route4", "netmask", anygw_ipv4:mask():string()) uci:set("network", pfr.."route4", "table", "170") uci:save("network") fs.mkdir("/etc/firewall.lime.d") fs.writefile( "/etc/firewall.lime.d/20-anygw-ebtables", "\n" .. "ebtables -D FORWARD -j DROP -d " .. anygw_mac .. "/" .. anygw_mac_mask .. "\n" .. "ebtables -A FORWARD -j DROP -d " .. anygw_mac .. "/" .. anygw_mac_mask .. "\n" .. "ebtables -t nat -D POSTROUTING -o bat0 -j DROP -s " .. anygw_mac .. "/" .. anygw_mac_mask .. "\n" .. "ebtables -t nat -A POSTROUTING -o bat0 -j DROP -s " .. anygw_mac .. "/" .. anygw_mac_mask .. "\n" ) uci:set("dhcp", "lan", "ignore", "1") uci:set("dhcp", owrtInterfaceName.."_dhcp", "dhcp") uci:set("dhcp", owrtInterfaceName.."_dhcp", "interface", owrtInterfaceName) uci:set("dhcp", owrtInterfaceName.."_dhcp", "start", "2") uci:set("dhcp", owrtInterfaceName.."_dhcp", "limit", (2 ^ (32 - anygw_ipv4:prefix()))) -- use whole network uci:set("dhcp", owrtInterfaceName.."_dhcp", "leasetime", "1h") uci:set("dhcp", owrtInterfaceName.."_dhcp", "force", "1") uci:set("dhcp", owrtInterfaceName, "tag") uci:set("dhcp", owrtInterfaceName, "dhcp_option", { "option:mtu,1350" } ) uci:set("dhcp", owrtInterfaceName, "force", "1") uci:foreach("dhcp", "dnsmasq", function(s) uci:set("dhcp", s[".name"], "address", { "/anygw/"..anygw_ipv4:host():string(), "/anygw/"..anygw_ipv6:host():string(), "/thisnode.info/"..anygw_ipv4:host():string(), "/thisnode.info/"..anygw_ipv6:host():string() }) end ) uci:save("dhcp") local cloudDomain = config.get("system", "domain") local content = { } table.insert(content, "enable-ra") table.insert(content, "dhcp-range=tag:anygw,"..ipv6:network():string()..",ra-names,24h") table.insert(content, "dhcp-option=tag:anygw,option6:domain-search,"..cloudDomain) fs.writefile("/etc/dnsmasq.d/lime-proto-anygw-20-ipv6.conf", table.concat(content, "\n").."\n") io.popen("/etc/init.d/dnsmasq enable || true"):close() end function anygw.setup_interface(ifname, args) end function anygw.bgp_conf(templateVarsIPv4, templateVarsIPv6) local base_conf = [[ protocol direct { interface "anygw"; } ]] return base_conf end return anygw
#!/usr/bin/lua local fs = require("nixio.fs") local network = require("lime.network") local libuci = require "uci" anygw = {} anygw.configured = false function anygw.configure(args) if anygw.configured then return end anygw.configured = true local ipv4, ipv6 = network.primary_address() local anygw_mac = config.get("network", "anygw_mac", "aa:aa:aa:%N1:%N2:aa") anygw_mac = utils.applyNetTemplate16(anygw_mac) --! bytes 4 & 5 vary depending on %N1 and %N2 by default local anygw_mac_mask = "ff:ff:ff:00:00:00" local anygw_ipv6 = ipv6:minhost() local anygw_ipv4 = ipv4:minhost() anygw_ipv6:prefix(64) -- SLAAC only works with a /64, per RFC anygw_ipv4:prefix(ipv4:prefix()) local baseIfname = "br-lan" local argsDev = { macaddr = anygw_mac } local argsIf = { proto = "static" } argsIf.ip6addr = anygw_ipv6:string() argsIf.ipaddr = anygw_ipv4:host():string() argsIf.netmask = anygw_ipv4:mask():string() local owrtInterfaceName, _, _ = network.createMacvlanIface( baseIfname, "anygw", argsDev, argsIf ) local uci = libuci:cursor() local pfr = network.limeIfNamePrefix.."anygw_" uci:set("network", pfr.."rule6", "rule6") uci:set("network", pfr.."rule6", "src", anygw_ipv6:host():string().."/128") uci:set("network", pfr.."rule6", "lookup", "170") -- 0xaa in decimal uci:set("network", pfr.."route6", "route6") uci:set("network", pfr.."route6", "interface", owrtInterfaceName) uci:set("network", pfr.."route6", "target", anygw_ipv6:network():string().."/"..anygw_ipv6:prefix()) uci:set("network", pfr.."route6", "table", "170") uci:set("network", pfr.."rule4", "rule") uci:set("network", pfr.."rule4", "src", anygw_ipv4:host():string().."/32") uci:set("network", pfr.."rule4", "lookup", "170") uci:set("network", pfr.."route4", "route") uci:set("network", pfr.."route4", "interface", owrtInterfaceName) uci:set("network", pfr.."route4", "target", anygw_ipv4:network():string()) uci:set("network", pfr.."route4", "netmask", anygw_ipv4:mask():string()) uci:set("network", pfr.."route4", "table", "170") uci:save("network") fs.mkdir("/etc/firewall.lime.d") fs.writefile( "/etc/firewall.lime.d/20-anygw-ebtables", "\n" .. "ebtables -D FORWARD -j DROP -d " .. anygw_mac .. "/" .. anygw_mac_mask .. "\n" .. "ebtables -A FORWARD -j DROP -d " .. anygw_mac .. "/" .. anygw_mac_mask .. "\n" .. "ebtables -t nat -D POSTROUTING -o bat0 -j DROP -s " .. anygw_mac .. "/" .. anygw_mac_mask .. "\n" .. "ebtables -t nat -A POSTROUTING -o bat0 -j DROP -s " .. anygw_mac .. "/" .. anygw_mac_mask .. "\n" ) uci:set("dhcp", "lan", "ignore", "1") uci:set("dhcp", owrtInterfaceName.."_dhcp", "dhcp") uci:set("dhcp", owrtInterfaceName.."_dhcp", "interface", owrtInterfaceName) uci:set("dhcp", owrtInterfaceName.."_dhcp", "start", "2") uci:set("dhcp", owrtInterfaceName.."_dhcp", "limit", (2 ^ (32 - anygw_ipv4:prefix()))) -- use whole network uci:set("dhcp", owrtInterfaceName.."_dhcp", "leasetime", "1h") uci:set("dhcp", owrtInterfaceName.."_dhcp", "force", "1") uci:set("dhcp", owrtInterfaceName, "tag") uci:set("dhcp", owrtInterfaceName, "dhcp_option", { "option:mtu,1350" } ) uci:set("dhcp", owrtInterfaceName, "force", "1") uci:foreach("dhcp", "dnsmasq", function(s) uci:set("dhcp", s[".name"], "address", { "/anygw/"..anygw_ipv4:host():string(), "/anygw/"..anygw_ipv6:host():string(), "/thisnode.info/"..anygw_ipv4:host():string(), "/thisnode.info/"..anygw_ipv6:host():string() }) end ) uci:save("dhcp") local cloudDomain = config.get("system", "domain") local content = { } table.insert(content, "enable-ra") table.insert(content, "dhcp-range=tag:anygw,"..ipv6:network():string()..",ra-names,24h") table.insert(content, "dhcp-option=tag:anygw,option6:domain-search,"..cloudDomain) fs.writefile("/etc/dnsmasq.d/lime-proto-anygw-20-ipv6.conf", table.concat(content, "\n").."\n") io.popen("/etc/init.d/dnsmasq enable || true"):close() end function anygw.setup_interface(ifname, args) end function anygw.bgp_conf(templateVarsIPv4, templateVarsIPv6) local base_conf = [[ protocol direct { interface "anygw"; } ]] return base_conf end return anygw
Fix undeclared default for: network.anygw_mac
Fix undeclared default for: network.anygw_mac
Lua
agpl-3.0
libremesh/lime-packages,p4u/lime-packages,p4u/lime-packages,p4u/lime-packages,libremesh/lime-packages,p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages,libremesh/lime-packages
51c5a9882e3bde47f54fda363661c3c04acd13de
base/doors.lua
base/doors.lua
require("base.common") module("base.doors", package.seeall) OpenDoors = {}; ClosedDoors = {}; --[[ AddToDoorList This is a helper function to fill the door list. It is removed after the initialisation. @param integer - the ID of the opened door of a opened closed door pair @param integer - the ID of the closed door of a opened closed door pair ]] function AddToDoorList(openedID, closedID) OpenDoors[openedID] = closedID; ClosedDoors[closedID] = openedID; end; AddToDoorList(86, 497); AddToDoorList(87, 922); AddToDoorList(927, 925); AddToDoorList(317, 926); AddToDoorList(476, 480); AddToDoorList(477, 481); AddToDoorList(478, 482); AddToDoorList(479, 483); AddToDoorList(499, 903); AddToDoorList(900, 904); AddToDoorList(901, 905); AddToDoorList(902, 906); AddToDoorList(484, 486); AddToDoorList(485, 487); AddToDoorList(924, 496); AddToDoorList(923, 920); AddToDoorList(668, 656); AddToDoorList(669, 657); AddToDoorList(660, 648); AddToDoorList(661, 649); AddToDoorList(684, 652); AddToDoorList(685, 653); AddToDoorList(664, 644); AddToDoorList(665, 645); AddToDoorList(666, 654); AddToDoorList(670, 658); AddToDoorList(671, 659); AddToDoorList(667, 655); AddToDoorList(662, 650); AddToDoorList(686, 646); AddToDoorList(663, 651); AddToDoorList(687, 647); AddToDoorList(715, 711); AddToDoorList(714, 710); AddToDoorList(712, 708); AddToDoorList(713, 709); AddToDoorList(865, 861); AddToDoorList(866, 862); AddToDoorList(867, 863); AddToDoorList(868, 864); AddToDoorList(944, 943); AddToDoorList(946, 945); AddToDoorList(948, 947); AddToDoorList(950, 949); AddToDoorList(1112, 1108); AddToDoorList(1113, 1109); AddToDoorList(1114, 1110); AddToDoorList(1115, 1111); AddToDoorList(3168, 3164); AddToDoorList(3169, 3165); AddToDoorList(3170, 3166); AddToDoorList(3171, 3167); AddToDoorList(3228, 3224); AddToDoorList(3229, 3225); AddToDoorList(3230, 3226); AddToDoorList(3231, 3227); AddToDoorList(3234, 3232); AddToDoorList(3235, 3233); AddToDoorList(3238, 3236); AddToDoorList(3239, 3237); AddToDoorList(3318, 3314); AddToDoorList(3319, 3315); AddToDoorList(3320, 3316); AddToDoorList(3321, 3317); AddToDoorList(3481, 3477); AddToDoorList(3482, 3478); AddToDoorList(3483, 3479); AddToDoorList(3484, 3480); AddToDoorList(3285, 3203); AddToDoorList(3202, 3282); -- n cl AddToDoorList(3203, 3283); -- e cl AddToDoorList(3284, 3200); -- s op AddToDoorList = nil; --[[ GetDoorItem Check if there is a item that is a door at a specified location and get the item struct of this item. @param PositionStruct - the position that shall be searched @return ItemStruct - the door item that was found or nil ]] function GetDoorItem(Posi) local items = base.common.GetItemsOnField(Posi); for _, item in pairs(items) do if (OpenDoors[item.id] or ClosedDoors[item.id]) then return item; end; end; return nil; end; --[[ CheckOpenDoor Check if this a item ID is a opened door. @param integer - the ID of the item that shall be checked @return boolean - true in case the item is a opened door, else false ]] function CheckOpenDoor(DoorID) return (OpenDoors[DoorID] ~= nil); end; --[[ CheckClosedDoor Check if this a item ID is a closed door. @param integer - the ID of the item that shall be checked @return boolean - true in case the item is a closed door, else false ]] function CheckClosedDoor(DoorID) return (ClosedDoors[DoorID] ~= nil); end; --[[ CloseDoor Close a opened door item by swapping the item. @param ItemStruct - the door item that shall be turned to a closed door @ewruen boolean - true in case the door got closed, false if something went wrong ]] function CloseDoor(Door) if OpenDoors[Door.id] then world:swap(Door, OpenDoors[Door.id], 233); world:makeSound(21, Door.pos); return true; end; return false; end; --[[ OpenDoor Open a closed door item by swapping the item. That function performs the check if the door is unlocked or has no lock and only opens the door in this case. @param ItemStruct - the door item that shall be turned to a opened door @return boolean, boolean - the first return value is true in case the door item was found and it wound be possible to open it, the second value is true in case the door really got opened and false if it was locked ]] function OpenDoor(Door) if ClosedDoors[Door.id] then if (Door.quality == 233 or Door.data == 0) then world:swap(Door, ClosedDoors[Door.id], 233); world:makeSound(21, Door.pos); return true, true; end return true, false; end return false, false; end
require("base.common") module("base.doors", package.seeall) OpenDoors = {}; ClosedDoors = {}; --[[ AddToDoorList This is a helper function to fill the door list. It is removed after the initialisation. @param integer - the ID of the opened door of a opened closed door pair @param integer - the ID of the closed door of a opened closed door pair ]] function AddToDoorList(openedID, closedID) OpenDoors[openedID] = closedID; ClosedDoors[closedID] = openedID; end; AddToDoorList(86, 497); AddToDoorList(87, 922); AddToDoorList(927, 925); AddToDoorList(317, 926); AddToDoorList(476, 480); AddToDoorList(477, 481); AddToDoorList(478, 482); AddToDoorList(479, 483); AddToDoorList(499, 903); AddToDoorList(900, 904); AddToDoorList(901, 905); AddToDoorList(902, 906); AddToDoorList(484, 486); AddToDoorList(485, 487); AddToDoorList(924, 496); AddToDoorList(923, 920); AddToDoorList(668, 656); AddToDoorList(669, 657); AddToDoorList(660, 648); AddToDoorList(661, 649); AddToDoorList(684, 652); AddToDoorList(685, 653); AddToDoorList(664, 644); AddToDoorList(665, 645); AddToDoorList(666, 654); AddToDoorList(670, 658); AddToDoorList(671, 659); AddToDoorList(667, 655); AddToDoorList(662, 650); AddToDoorList(686, 646); AddToDoorList(663, 651); AddToDoorList(687, 647); AddToDoorList(715, 711); AddToDoorList(714, 710); AddToDoorList(712, 708); AddToDoorList(713, 709); AddToDoorList(865, 861); AddToDoorList(866, 862); AddToDoorList(867, 863); AddToDoorList(868, 864); AddToDoorList(944, 943); AddToDoorList(946, 945); AddToDoorList(948, 947); AddToDoorList(950, 949); AddToDoorList(1112, 1108); AddToDoorList(1113, 1109); AddToDoorList(1114, 1110); AddToDoorList(1115, 1111); AddToDoorList(3168, 3164); AddToDoorList(3169, 3165); AddToDoorList(3170, 3166); AddToDoorList(3171, 3167); AddToDoorList(3228, 3224); AddToDoorList(3229, 3225); AddToDoorList(3230, 3226); AddToDoorList(3231, 3227); AddToDoorList(3234, 3232); AddToDoorList(3235, 3233); AddToDoorList(3238, 3236); AddToDoorList(3239, 3237); AddToDoorList(3318, 3314); AddToDoorList(3319, 3315); AddToDoorList(3320, 3316); AddToDoorList(3321, 3317); AddToDoorList(3481, 3477); AddToDoorList(3482, 3478); AddToDoorList(3483, 3479); AddToDoorList(3484, 3480); AddToDoorList(3489, 3485); AddToDoorList(3490, 3486); AddToDoorList(3491, 3487); AddToDoorList(3492, 3488); AddToDoorList(3285, 3203); AddToDoorList(3202, 3282); AddToDoorList(3203, 3283); AddToDoorList(3284, 3200); AddToDoorList = nil; --[[ GetDoorItem Check if there is a item that is a door at a specified location and get the item struct of this item. @param PositionStruct - the position that shall be searched @return ItemStruct - the door item that was found or nil ]] function GetDoorItem(Posi) local items = base.common.GetItemsOnField(Posi); for _, item in pairs(items) do if (OpenDoors[item.id] or ClosedDoors[item.id]) then return item; end; end; return nil; end; --[[ CheckOpenDoor Check if this a item ID is a opened door. @param integer - the ID of the item that shall be checked @return boolean - true in case the item is a opened door, else false ]] function CheckOpenDoor(DoorID) return (OpenDoors[DoorID] ~= nil); end; --[[ CheckClosedDoor Check if this a item ID is a closed door. @param integer - the ID of the item that shall be checked @return boolean - true in case the item is a closed door, else false ]] function CheckClosedDoor(DoorID) return (ClosedDoors[DoorID] ~= nil); end; --[[ CloseDoor Close a opened door item by swapping the item. @param ItemStruct - the door item that shall be turned to a closed door @ewruen boolean - true in case the door got closed, false if something went wrong ]] function CloseDoor(Door) if OpenDoors[Door.id] then world:swap(Door, OpenDoors[Door.id], 233); world:makeSound(21, Door.pos); return true; end; return false; end; --[[ OpenDoor Open a closed door item by swapping the item. That function performs the check if the door is unlocked or has no lock and only opens the door in this case. @param ItemStruct - the door item that shall be turned to a opened door @return boolean, boolean - the first return value is true in case the door item was found and it wound be possible to open it, the second value is true in case the door really got opened and false if it was locked ]] function OpenDoor(Door) if ClosedDoors[Door.id] then if (Door.quality == 233 or Door.data == 0) then world:swap(Door, ClosedDoors[Door.id], 233); world:makeSound(21, Door.pos); return true, true; end return true, false; end return false, false; end
Bug #6922
Bug #6922
Lua
agpl-3.0
Baylamon/Illarion-Content,LaFamiglia/Illarion-Content,KayMD/Illarion-Content,vilarion/Illarion-Content,Illarion-eV/Illarion-Content
56e004e096ce9fe1cca0ceb1f2808b47073f700c
xmake/modules/core/project/depend.lua
xmake/modules/core/project/depend.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 depend.lua -- -- load dependent info from the given file (.d) function load(dependfile) if os.isfile(dependfile) then -- may be the depend file has been incomplete when if the compilation process is abnormally interrupted return try { function() return io.load(dependfile) end } end end -- save dependent info to file function save(dependinfo, dependfile) io.save(dependfile, dependinfo) end -- the dependent info is changed? -- -- if not depend.is_changed(dependinfo, {filemtime = os.mtime(objectfile), values = {...}}) then -- return -- end -- function is_changed(dependinfo, opt) -- empty depend info? always be changed local files = dependinfo.files or {} local values = dependinfo.values or {} if #files == 0 and #values == 0 then return true end -- check the dependent files are changed? local lastmtime = nil _g.file_results = _g.file_results or {} for _, file in ipairs(files) do -- optimization: this file has been not checked? local status = _g.file_results[file] if status == nil then -- optimization: only uses the mtime of first object file lastmtime = lastmtime or opt.lastmtime or 0 -- source and header files have been changed? if not os.isfile(file) or os.mtime(file) > lastmtime then -- mark this file as changed _g.file_results[file] = true return true end -- mark this file as not changed _g.file_results[file] = false -- has been checked and changed? elseif status then return true end end -- check the dependent values are changed? local depvalues = values local optvalues = opt.values or {} if #depvalues ~= #optvalues then return true end for idx, depvalue in ipairs(depvalues) do local optvalue = optvalues[idx] local deptype = type(depvalue) local opttype = type(optvalue) if deptype ~= opttype then return true elseif deptype == "string" and depvalue ~= optvalue then return true elseif deptype == "table" then for subidx, subvalue in ipairs(depvalue) do if subvalue ~= optvalue[subidx] then return true end end end end -- check the dependent files list are changed? local optfiles = opt.files if optfiles then for idx, file in ipairs(files) do if file ~= optfiles[idx] then return true end end end 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 depend.lua -- -- load dependent info from the given file (.d) function load(dependfile) if os.isfile(dependfile) then -- may be the depend file has been incomplete when if the compilation process is abnormally interrupted return try { function() return io.load(dependfile) end } end end -- save dependent info to file function save(dependinfo, dependfile) io.save(dependfile, dependinfo) end -- the dependent info is changed? -- -- if not depend.is_changed(dependinfo, {filemtime = os.mtime(objectfile), values = {...}}) then -- return -- end -- function is_changed(dependinfo, opt) -- empty depend info? always be changed local files = dependinfo.files or {} local values = dependinfo.values or {} if #files == 0 and #values == 0 then return true end -- check the dependent files are changed? local lastmtime = opt.lastmtime or 0 _g.files_mtime = _g.files_mtime or {} local files_mtime = _g.files_mtime for _, file in ipairs(files) do -- get and cache the file mtime local mtime = files_mtime[file] or (os.isfile(file) and os.mtime(file) or nil) files_mtime[file] = mtime -- source and header files have been changed? if mtime == nil or mtime > lastmtime then return true end end -- check the dependent values are changed? local depvalues = values local optvalues = opt.values or {} if #depvalues ~= #optvalues then return true end for idx, depvalue in ipairs(depvalues) do local optvalue = optvalues[idx] local deptype = type(depvalue) local opttype = type(optvalue) if deptype ~= opttype then return true elseif deptype == "string" and depvalue ~= optvalue then return true elseif deptype == "table" then for subidx, subvalue in ipairs(depvalue) do if subvalue ~= optvalue[subidx] then return true end end end end -- check the dependent files list are changed? local optfiles = opt.files if optfiles then for idx, file in ipairs(files) do if file ~= optfiles[idx] then return true end end end end
fix check depend mtime
fix check depend mtime
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
eee1a66f287c2264ec96972406891ce883522b1d
Hammerspoon/setup.lua
Hammerspoon/setup.lua
local modpath, prettypath, fullpath, configdir, docstringspath, hasinitfile, autoload_extensions = ... os.exit = hs._exit local function runstring(s) local fn, err = load("return " .. s) if not fn then fn, err = load(s) end if not fn then return tostring(err) end local str = "" local results = table.pack(pcall(fn)) for i = 2,results.n do if i > 2 then str = str .. "\t" end str = str .. tostring(results[i]) end return str end --- hs.configdir = "~/.hammerspoon/" --- Constant --- The user's Hammerspoon config directory. Modules may use it, assuming --- they've worked out a contract with the user about how to use it. hs.configdir = configdir --- hs.docstrings_json_file --- Constant --- This is the full path to the docs.json file shipped with Hammerspoon. --- It contains the same documentation used to generate the full Hammerspoon --- API documentation, in JSON form. --- You can load, parse and access this information using the hs.doc extension hs.docstrings_json_file = docstringspath --- hs.showerror(err) --- Function --- --- Presents an error to the user via Hammerspoon's GUI. The default --- implementation prints the error, focuses Hammerspoon, and opens --- Hammerspoon's console. --- --- Users can override this with a new function that shows errors in a --- custom way. --- --- Modules can call this in the event of an error, e.g. in callbacks --- from the user: --- --- local ok, err = xpcall(callbackfn, debug.traceback) --- if not ok then hs.showerror(err) end function hs.showerror(err) hs._notify("Hammerspoon config error") -- undecided on this line print(err) hs.focus() hs.openconsole() end --- hs.rawprint = print --- Function --- The original print function, before hammerspoon overrides it. local rawprint = print hs.rawprint = rawprint function print(...) rawprint(...) local vals = table.pack(...) for k = 1, vals.n do vals[k] = tostring(vals[k]) end local str = table.concat(vals, "\t") .. "\n" hs._logmessage(str) end print("-- Augmenting require paths") package.path=package.path..";"..modpath.."/?.lua"..";"..modpath.."/?/init.lua" package.cpath=package.cpath..";"..modpath.."/?.so" -- place user path at head to allow for easy overrides package.path=configdir.."/?.lua"..";"..configdir.."/?/init.lua;"..package.path package.cpath=configdir.."/?.so"..";"..configdir.."/?/init.so;"..package.cpath if autoload_extensions then print("-- Lazily loading extensions") _extensions = {} -- Discover extensions in our .app bundle local iter, dir_obj = require("hs.fs").dir(modpath.."/hs") local extension = iter(dir_obj) while extension do if (extension ~= ".") and (extension ~= "..") then _extensions[extension] = true end extension = iter(dir_obj) end -- Inject a lazy extension loader into the main HS table setmetatable(hs, { __index = function(t, key) if _extensions[key] ~= nil then print("-- Loading extension: "..key) hs[key] = require("hs."..key) return hs[key] else return nil end end }) end function help(identifier) local doc = require "hs.doc" local tree = doc.from_json_file(hs.docstrings_json_file) local result = tree for word in string.gmatch(identifier, '([^.]+)') do result = result[word] end print(result) end if not hasinitfile then hs.notify.register("__noinitfile", function() os.execute("open http://www.hammerspoon.org/go/") end) hs.notify.show("Hammerspoon", "No config file found", "Click here for the Getting Started Guide", "__noinitfile") print(string.format("-- Can't find %s; create it and reload your config.", prettypath)) return runstring end print("-- Loading " .. prettypath) local fn, err = loadfile(fullpath) if not fn then hs.showerror(err) return runstring end local ok, err = xpcall(fn, debug.traceback) if not ok then hs.showerror(err) return runstring end print "-- Done." return runstring
local modpath, prettypath, fullpath, configdir, docstringspath, hasinitfile, autoload_extensions = ... os.exit = hs._exit local function runstring(s) local fn, err = load("return " .. s) if not fn then fn, err = load(s) end if not fn then return tostring(err) end local str = "" local results = table.pack(pcall(fn)) for i = 2,results.n do if i > 2 then str = str .. "\t" end str = str .. tostring(results[i]) end return str end --- hs.configdir = "~/.hammerspoon/" --- Constant --- The user's Hammerspoon config directory. Modules may use it, assuming --- they've worked out a contract with the user about how to use it. hs.configdir = configdir --- hs.docstrings_json_file --- Constant --- This is the full path to the docs.json file shipped with Hammerspoon. --- It contains the same documentation used to generate the full Hammerspoon --- API documentation, in JSON form. --- You can load, parse and access this information using the hs.doc extension hs.docstrings_json_file = docstringspath --- hs.showerror(err) --- Function --- --- Presents an error to the user via Hammerspoon's GUI. The default --- implementation prints the error, focuses Hammerspoon, and opens --- Hammerspoon's console. --- --- Users can override this with a new function that shows errors in a --- custom way. --- --- Modules can call this in the event of an error, e.g. in callbacks --- from the user: --- --- local ok, err = xpcall(callbackfn, debug.traceback) --- if not ok then hs.showerror(err) end function hs.showerror(err) hs._notify("Hammerspoon config error") -- undecided on this line print(err) hs.focus() hs.openconsole() end --- hs.rawprint = print --- Function --- The original print function, before hammerspoon overrides it. local rawprint = print hs.rawprint = rawprint function print(...) rawprint(...) local vals = table.pack(...) for k = 1, vals.n do vals[k] = tostring(vals[k]) end local str = table.concat(vals, "\t") .. "\n" hs._logmessage(str) end print("-- Augmenting require paths") package.path=configdir.."/?.lua"..";"..configdir.."/?/init.lua"..";"..package.path..";"..modpath.."/?.lua"..";"..modpath.."/?/init.lua" package.cpath=configdir.."/?.so"..";"..package.cpath..";"..modpath.."/?.so" print("-- package.path:") for part in string.gmatch(package.path, "([^;]+)") do print(" "..part) end print("-- package.cpath:") for part in string.gmatch(package.cpath, "([^;]+)") do print(" "..part) end if autoload_extensions then print("-- Lazy extension loading enabled") _extensions = {} -- Discover extensions in our .app bundle local iter, dir_obj = require("hs.fs").dir(modpath.."/hs") local extension = iter(dir_obj) while extension do if (extension ~= ".") and (extension ~= "..") then _extensions[extension] = true end extension = iter(dir_obj) end -- Inject a lazy extension loader into the main HS table setmetatable(hs, { __index = function(t, key) if _extensions[key] ~= nil then print("-- Loading extension: "..key) hs[key] = require("hs."..key) return hs[key] else return nil end end }) end function help(identifier) local doc = require "hs.doc" local tree = doc.from_json_file(hs.docstrings_json_file) local result = tree for word in string.gmatch(identifier, '([^.]+)') do result = result[word] end print(result) end if not hasinitfile then hs.notify.register("__noinitfile", function() os.execute("open http://www.hammerspoon.org/go/") end) hs.notify.show("Hammerspoon", "No config file found", "Click here for the Getting Started Guide", "__noinitfile") print(string.format("-- Can't find %s; create it and reload your config.", prettypath)) return runstring end print("-- Loading " .. prettypath) local fn, err = loadfile(fullpath) if not fn then hs.showerror(err) return runstring end local ok, err = xpcall(fn, debug.traceback) if not ok then hs.showerror(err) return runstring end print "-- Done." return runstring
Fix up require paths to be more consistent, and collapsed into a single step. Also print out the resulting paths. Also tidy up wording in another startup message
Fix up require paths to be more consistent, and collapsed into a single step. Also print out the resulting paths. Also tidy up wording in another startup message
Lua
mit
wvierber/hammerspoon,lowne/hammerspoon,chrisjbray/hammerspoon,kkamdooong/hammerspoon,trishume/hammerspoon,nkgm/hammerspoon,zzamboni/hammerspoon,asmagill/hammerspoon,Habbie/hammerspoon,ocurr/hammerspoon,trishume/hammerspoon,knl/hammerspoon,heptal/hammerspoon,Hammerspoon/hammerspoon,hypebeast/hammerspoon,peterhajas/hammerspoon,junkblocker/hammerspoon,CommandPost/CommandPost-App,cmsj/hammerspoon,Stimim/hammerspoon,Hammerspoon/hammerspoon,Stimim/hammerspoon,joehanchoi/hammerspoon,peterhajas/hammerspoon,wvierber/hammerspoon,wsmith323/hammerspoon,tmandry/hammerspoon,TimVonsee/hammerspoon,junkblocker/hammerspoon,CommandPost/CommandPost-App,wvierber/hammerspoon,junkblocker/hammerspoon,joehanchoi/hammerspoon,latenitefilms/hammerspoon,Hammerspoon/hammerspoon,joehanchoi/hammerspoon,dopcn/hammerspoon,CommandPost/CommandPost-App,Stimim/hammerspoon,kkamdooong/hammerspoon,heptal/hammerspoon,bradparks/hammerspoon,nkgm/hammerspoon,knu/hammerspoon,lowne/hammerspoon,bradparks/hammerspoon,joehanchoi/hammerspoon,emoses/hammerspoon,dopcn/hammerspoon,cmsj/hammerspoon,asmagill/hammerspoon,wsmith323/hammerspoon,zzamboni/hammerspoon,Stimim/hammerspoon,asmagill/hammerspoon,knl/hammerspoon,lowne/hammerspoon,zzamboni/hammerspoon,nkgm/hammerspoon,chrisjbray/hammerspoon,knl/hammerspoon,ocurr/hammerspoon,latenitefilms/hammerspoon,TimVonsee/hammerspoon,knu/hammerspoon,lowne/hammerspoon,tmandry/hammerspoon,chrisjbray/hammerspoon,peterhajas/hammerspoon,bradparks/hammerspoon,knu/hammerspoon,wsmith323/hammerspoon,wvierber/hammerspoon,dopcn/hammerspoon,wsmith323/hammerspoon,bradparks/hammerspoon,wvierber/hammerspoon,CommandPost/CommandPost-App,hypebeast/hammerspoon,joehanchoi/hammerspoon,nkgm/hammerspoon,hypebeast/hammerspoon,knl/hammerspoon,wsmith323/hammerspoon,Habbie/hammerspoon,bradparks/hammerspoon,junkblocker/hammerspoon,CommandPost/CommandPost-App,Stimim/hammerspoon,cmsj/hammerspoon,dopcn/hammerspoon,latenitefilms/hammerspoon,peterhajas/hammerspoon,heptal/hammerspoon,nkgm/hammerspoon,Habbie/hammerspoon,cmsj/hammerspoon,latenitefilms/hammerspoon,CommandPost/CommandPost-App,lowne/hammerspoon,chrisjbray/hammerspoon,ocurr/hammerspoon,zzamboni/hammerspoon,knu/hammerspoon,hypebeast/hammerspoon,ocurr/hammerspoon,emoses/hammerspoon,cmsj/hammerspoon,TimVonsee/hammerspoon,hypebeast/hammerspoon,Hammerspoon/hammerspoon,Habbie/hammerspoon,trishume/hammerspoon,chrisjbray/hammerspoon,zzamboni/hammerspoon,Hammerspoon/hammerspoon,emoses/hammerspoon,dopcn/hammerspoon,heptal/hammerspoon,knl/hammerspoon,emoses/hammerspoon,heptal/hammerspoon,peterhajas/hammerspoon,TimVonsee/hammerspoon,latenitefilms/hammerspoon,zzamboni/hammerspoon,chrisjbray/hammerspoon,ocurr/hammerspoon,Habbie/hammerspoon,emoses/hammerspoon,kkamdooong/hammerspoon,asmagill/hammerspoon,kkamdooong/hammerspoon,junkblocker/hammerspoon,kkamdooong/hammerspoon,asmagill/hammerspoon,tmandry/hammerspoon,Habbie/hammerspoon,latenitefilms/hammerspoon,asmagill/hammerspoon,cmsj/hammerspoon,knu/hammerspoon,Hammerspoon/hammerspoon,TimVonsee/hammerspoon,knu/hammerspoon
2e981bc10fd6f38a89e7e5f944817e3828738c18
class_optimization.lua
class_optimization.lua
require 'torch' require 'nn' require 'optim' require 'model' require 'image' require 'cutorch' require 'cunn' require('gnuplot') require('lfs') require('data') data = {} dtype = 'torch.CudaTensor' -- specify directories model_root = 'models' data_root = 'data/deepbind/' viz_dir = 'visualization_results/' -- ****************************************************************** -- -- ****************** CHANGE THESE FIELDS *************************** -- TFs = {'GATA1_K562_GATA-1_USC'} cnn_model = 'model=CNN,cnn_size=128,cnn_filters=9-5-3,dropout=0.5,learning_rate=0.01,batch_size=256' rnn_model = 'model=RNN,rnn_size=32,rnn_layers=1,dropout=0.5,learning_rate=0.01,batch_size=256' cnnrnn_model = 'model=CNN-RNN,cnn_size=128,cnn_filter=9,rnn_size=32,rnn_layers=1,dropout=0.5,learning_rate=0.01,batch_size=256' model_names = {rnn_model_name,cnn_model_name,cnnrnn_model_name} -- ****************************************************************** -- -- ****************************************************************** -- alphabet = 'ACGT' OneHot = OneHot(#alphabet):type(dtype) crit = nn.ClassNLLCriterion():type(dtype) --c start_pos = 1 end_pos = start_pos + 0 lambda = 0.009 config = {learningRate=.05,momentum=0.9} iterations = 1000 for _,TF in pairs(TFs) do print(TF) save_path = viz_dir..TF..'/' os.execute('mkdir '..save_path..' > /dev/null 2>&1') -- Load Models models = {} for _,model_name in pairs(model_names) do load_path = model_root..model_name..'/'..TF..'/' model = torch.load(load_path..'best_model.t7') model:evaluate() model.model:type(dtype) models[model_name] = model end --#######################################################################-- --######################### CLASS OPTIMIZATION ##########################-- --#######################################################################-- for model_name, model in pairs(models) do print('\n ****** Optimizing '..model_name..' *******\n') print(model.model) model:resetStates() motif = torch.rand(1,101,4):type(dtype) target = torch.Tensor({1}):type(dtype) -- motif weight update feval = function(X) local output = model:forward(X) local loss = crit:forward(output[1], target) local df_do = crit:backward(output[1], target) local inputGrads = model:backward(motif, df_do) return (loss + lambda*(X:norm())^2), (inputGrads + X*2*lambda) end -- SGD Loop for i = 1,iterations do motif,f = optim.rmsprop(feval,motif,config) print(f[1]) end -- resize motif = motif[1]:type(dtype) -- clamp to values in (0,1) motif:clamp(0,1) max = motif:max() for i = 1,101 do sum = motif[i]:sum() if sum == 0 then motif[i] = torch.zeros(4) else for j = 1,4 do motif[i][j] = motif[i][j]/max end end end for i = 1,101 do --add smoothing constant for j = 1,4 do motif[i][j] = motif[i][j]+0.01 end --normalize sum = motif[i]:sum() for j = 1,4 do motif[i][j] = motif[i][j]/sum end end s2l_filename = save_path..model_name..'_optimization.txt' optimization_file = io.open(s2l_filename, 'w') optimization_file:write('PO ') alphabet:gsub(".",function(c) optimization_file:write(tostring(c)..' ') end) optimization_file:write('\n') for i=1,motif:size(1) do optimization_file:write(tostring(i)..' ') for j=1,motif:size(2) do optimization_file:write(tostring(motif[i][j])..' ') end optimization_file:write('\n') end optimization_file:close() cmd = "weblogo -D transfac -F png -o "..save_path..model_name.."_optimization.png --errorbars NO --show-xaxis NO --show-yaxis NO -A dna --composition none -n 101 --color '#00CC00' 'A' 'A' --color '#0000CC' 'C' 'C' --color '#FFB300' 'G' 'G' --color '#CC0000' 'T' 'T' < "..s2l_filename os.execute(cmd) end print('') print(lfs.currentdir()..'/'..save_path) os.execute('rm '..save_path..'/*.csv > /dev/null 2>&1') os.execute('rm '..save_path..'/*.txt > /dev/null 2>&1') end
require 'torch' require 'nn' require 'optim' require 'model' require 'image' require 'cutorch' require 'cunn' require('gnuplot') require('lfs') require('data') data = {} dtype = 'torch.CudaTensor' -- specify directories model_root = 'models/' data_root = 'data/deepbind/' viz_dir = 'visualization_results/' -- ****************************************************************** -- -- ****************** CHANGE THESE FIELDS *************************** -- TFs = {'ATF1_K562_ATF1_-06-325-_Harvard'} cnn_model_name = 'model=CNN,cnn_size=128,cnn_filters=9-5-3,dropout=0.5,learning_rate=0.01,batch_size=256' rnn_model_name = 'model=RNN,rnn_size=32,rnn_layers=1,dropout=0.5,learning_rate=0.01,batch_size=256' cnnrnn_model_name = 'model=CNN-RNN,cnn_size=128,cnn_filter=9,rnn_size=32,rnn_layers=1,dropout=0.5,learning_rate=0.01,batch_size=256' model_names = {rnn_model_name,cnn_model_name,cnnrnn_model_name} -- ****************************************************************** -- -- ****************************************************************** -- alphabet = 'ACGT' OneHot = OneHot(#alphabet):type(dtype) crit = nn.ClassNLLCriterion():type(dtype) --c start_pos = 1 end_pos = start_pos + 0 lambda = 0.009 config = {learningRate=.05,momentum=0.9} iterations = 1000 for _,TF in pairs(TFs) do print(TF) save_path = viz_dir..TF..'/' os.execute('mkdir '..save_path..' > /dev/null 2>&1') -- Load Models models = {} for _,model_name in pairs(model_names) do load_path = model_root..model_name..'/'..TF..'/' model = torch.load(load_path..'best_model.t7') model:evaluate() model.model:type(dtype) models[model_name] = model end --#######################################################################-- --######################### CLASS OPTIMIZATION ##########################-- --#######################################################################-- for model_name, model in pairs(models) do print('\n ****** Optimizing '..model_name..' *******\n') print(model.model) model.model:remove(1) model:resetStates() motif = torch.rand(1,101,4):type(dtype) target = torch.Tensor({1}):type(dtype) -- motif weight update feval = function(X) local output = model:forward(X) local loss = crit:forward(output[1], target) local df_do = crit:backward(output[1], target) local inputGrads = model:backward(motif, df_do) return (loss + lambda*(X:norm())^2), (inputGrads + X*2*lambda) end -- SGD Loop for i = 1,iterations do motif,f = optim.rmsprop(feval,motif,config) print(f[1]) end -- resize motif = motif[1]:type(dtype) -- clamp to values in (0,1) motif:clamp(0,1) max = motif:max() for i = 1,101 do sum = motif[i]:sum() if sum == 0 then motif[i] = torch.zeros(4) else for j = 1,4 do motif[i][j] = motif[i][j]/max end end end for i = 1,101 do --add smoothing constant for j = 1,4 do motif[i][j] = motif[i][j]+0.01 end --normalize sum = motif[i]:sum() for j = 1,4 do motif[i][j] = motif[i][j]/sum end end s2l_filename = save_path..model_name..'_optimization.txt' optimization_file = io.open(s2l_filename, 'w') optimization_file:write('PO ') alphabet:gsub(".",function(c) optimization_file:write(tostring(c)..' ') end) optimization_file:write('\n') for i=1,motif:size(1) do optimization_file:write(tostring(i)..' ') for j=1,motif:size(2) do optimization_file:write(tostring(motif[i][j])..' ') end optimization_file:write('\n') end optimization_file:close() cmd = "weblogo -D transfac -F png -o "..save_path..model_name.."_optimization.png --errorbars NO --show-xaxis NO --show-yaxis NO -A dna --composition none -n 101 --color '#00CC00' 'A' 'A' --color '#0000CC' 'C' 'C' --color '#FFB300' 'G' 'G' --color '#CC0000' 'T' 'T' < "..s2l_filename os.execute(cmd) end print('') print(lfs.currentdir()..'/'..save_path) os.execute('rm '..save_path..'/*.csv > /dev/null 2>&1') os.execute('rm '..save_path..'/*.txt > /dev/null 2>&1') end
fix class_optimization bug
fix class_optimization bug
Lua
mit
QData/DeepMotif
fa3f03a296c8bcf927140579ff1d083cabe64af3
lib/sh.lua
lib/sh.lua
--[=============================================================================[ The MIT License (MIT) Copyright (c) 2014 RepeatPan excluding parts that were written by Radiant Entertainment Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]=============================================================================] --! realm jelly local sh = {} --! desc Requires a file from within Stonehearth. For the lazy. --! param string path Path to the file inside stonehearth/. No file extension. --! returns Whatever the loaded file returns - usually a class or an object. function sh.require(path) return radiant.mods.require('stonehearth.' .. path) end -- Define a list of classes we might want to use, including name. local classes = { TerrainInfo = "services.server.world_generation.terrain_info", Array2D = "services.server.world_generation.array_2D", MathFns = "services.server.world_generation.math.math_fns", FilterFns = "services.server.world_generation.filter.filter_fns", PerturbationGrid = "services.server.world_generation.perturbation_grid", BoulderGenerator = "services.server.world_generation.boulder_generator" } for k, v in pairs(classes) do sh[k] = sh.require(v) end return sh
--[=============================================================================[ The MIT License (MIT) Copyright (c) 2014 RepeatPan excluding parts that were written by Radiant Entertainment Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]=============================================================================] --! realm jelly local sh = {} --! desc Requires a file from within Stonehearth. For the lazy. --! param string path Path to the file inside stonehearth/. No file extension. --! returns Whatever the loaded file returns - usually a class or an object. function sh.require(path) return radiant.mods.require('stonehearth.' .. path) end -- Define a list of classes we might want to use, including name. local classes = { TerrainInfo = "services.server.world_generation.terrain_info", Array2D = "services.server.world_generation.array_2D", FilterFns = "services.server.world_generation.filter.filter_fns", PerturbationGrid = "services.server.world_generation.perturbation_grid", BoulderGenerator = "services.server.world_generation.boulder_generator" } for k, v in pairs(classes) do sh[k] = sh.require(v) end return sh
Fixed removed dependency
Fixed removed dependency
Lua
mit
Quit/jelly
176fd8cd6884deaa98b6b989402dfc17e0fee8c9
assert.lua
assert.lua
-- See LICENSE file for copyright and license details local Misc = require('misc') local M = Misc.newModule() local printStacktrace = function() -- print("ASSERT: 1") local stacktarce = Misc.split(debug.traceback(), '\n') -- table.remove(stacktarce, 1) -- remove 'traceback:..' -- table.remove(stacktarce) -- remove 'in C[?]' for i = 1, #stacktarce do if not string.find(stacktarce[i], 'runTests.lua') and not string.find(stacktarce[i], 'assert.lua') then print(stacktarce[i]) end end end M.isEqual = function(real, expected) assert(real, 'real is nil!') assert(expected) if false then assert(Misc.compare(real, expected), 'Expected <<< ' .. Misc.dump(expected) .. ' >>>, ' .. 'but got <<< ' .. Misc.dump(real) .. ' >>>') else if not Misc.compare(real, expected) then printStacktrace() -- print("ASSERT: 2") print(Misc.diffTables(expected, real)) os.exit() -- TODO: optional? end end end M.isTrue = function(real) assert(real) end M.isFalse = function(real) assert(not real) end M.isNil = function(real) assert(real == nil, 'Expected nil but got ' .. (real or 'nil')) end return M
-- See LICENSE file for copyright and license details local Misc = require('misc') local M = Misc.newModule() local printStacktrace = function() -- print("ASSERT: 1") local stacktarce = Misc.split(debug.traceback(), '\n') -- table.remove(stacktarce, 1) -- remove 'traceback:..' -- table.remove(stacktarce) -- remove 'in C[?]' for i = 1, #stacktarce do if not string.find(stacktarce[i], 'runTests.lua') and not string.find(stacktarce[i], 'assert.lua') then print(stacktarce[i]) end end end M.isEqual = function(real, expected) assert(real, 'real is nil!') assert(expected) if false then assert(Misc.compare(real, expected), 'Expected <<< ' .. Misc.dump(expected) .. ' >>>, ' .. 'but got <<< ' .. Misc.dump(real) .. ' >>>') else if not Misc.compare(real, expected) then printStacktrace() -- print("ASSERT: 2") if type(expected) == 'table' then print(Misc.diffTables(expected, real)) else print( 'Expected <<< ' .. Misc.dump(expected) .. ' >>> but got <<< ' .. Misc.dump(real) .. ' >>>') end os.exit() -- TODO: optional? end end end M.isTrue = function(real) assert(real) end M.isFalse = function(real) assert(not real) end M.isNil = function(real) assert(real == nil, 'Expected nil but got ' .. (real or 'nil')) end return M
assert.lua: Stupid fix
assert.lua: Stupid fix
Lua
mit
ozkriff/misery-lua
75ea7e3160321fd60c80907accb427650391bb0e
mods/bones/init.lua
mods/bones/init.lua
-- Minetest 0.4 mod: bones -- See README.txt for licensing and other information. bones = {} local function is_owner(pos, name) local owner = minetest.get_meta(pos):get_string("owner") if owner == "" or owner == name then return true end return false end bones.bones_formspec = "size[8,9]".. default.gui_bg.. default.gui_bg_img.. default.gui_slots.. "list[current_name;main;0,0.3;8,4;]".. "list[current_player;main;0,4.85;8,1;]".. "list[current_player;main;0,6.08;8,3;8]".. default.get_hotbar_bg(0,4.85) minetest.register_node("bones:bones", { description = "Bones", tiles = { "bones_top.png", "bones_bottom.png", "bones_side.png", "bones_side.png", "bones_rear.png", "bones_front.png" }, paramtype2 = "facedir", groups = {dig_immediate=2}, sounds = default.node_sound_dirt_defaults({ footstep = {name="default_gravel_footstep", gain=0.5}, dug = {name="default_gravel_footstep", gain=1.0}, }), can_dig = function(pos, player) local inv = minetest.get_meta(pos):get_inventory() return is_owner(pos, player:get_player_name()) and inv:is_empty("main") end, allow_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player) if is_owner(pos, player:get_player_name()) then return count end return 0 end, allow_metadata_inventory_put = function(pos, listname, index, stack, player) return 0 end, allow_metadata_inventory_take = function(pos, listname, index, stack, player) if is_owner(pos, player:get_player_name()) then return stack:get_count() end return 0 end, on_metadata_inventory_take = function(pos, listname, index, stack, player) local meta = minetest.get_meta(pos) if meta:get_inventory():is_empty("main") then minetest.remove_node(pos) end end, on_punch = function(pos, node, player) if(not is_owner(pos, player:get_player_name())) then return end local inv = minetest.get_meta(pos):get_inventory() local player_inv = player:get_inventory() local has_space = true for i=1,inv:get_size("main") do local stk = inv:get_stack("main", i) if player_inv:room_for_item("main", stk) then inv:set_stack("main", i, nil) player_inv:add_item("main", stk) else has_space = false break end end -- remove bones if player emptied them if has_space then minetest.remove_node(pos) end end, on_timer = function(pos, elapsed) local meta = minetest.get_meta(pos) local time = meta:get_int("time")+elapsed local publish = 1200 if tonumber(minetest.setting_get("share_bones_time")) then publish = tonumber(minetest.setting_get("share_bones_time")) end if publish == 0 then return end if time >= publish then meta:set_string("infotext", meta:get_string("owner").."'s old bones") meta:set_string("owner", "") else return true end end, }) minetest.register_on_dieplayer(function(player) if minetest.setting_getbool("creative_mode") then return end local player_inv = player:get_inventory() if player_inv:is_empty("main") and player_inv:is_empty("craft") then return end local pos = player:getpos() pos.x = math.floor(pos.x+0.5) pos.y = math.floor(pos.y+0.5) pos.z = math.floor(pos.z+0.5) local param2 = minetest.dir_to_facedir(player:get_look_dir()) local player_name = player:get_player_name() local player_inv = player:get_inventory() local nn = minetest.get_node(pos).name if minetest.registered_nodes[nn].can_dig and not minetest.registered_nodes[nn].can_dig(pos, player) then -- drop items instead of delete for i=1,player_inv:get_size("main") do minetest.add_item(pos, player_inv:get_stack("main", i)) end for i=1,player_inv:get_size("craft") do minetest.add_item(pos, player_inv:get_stack("craft", i)) end -- empty lists main and craft player_inv:set_list("main", {}) player_inv:set_list("craft", {}) return end minetest.dig_node(pos) minetest.add_node(pos, {name="bones:bones", param2=param2}) local meta = minetest.get_meta(pos) local inv = meta:get_inventory() inv:set_size("main", 8*4) inv:set_list("main", player_inv:get_list("main")) for i=1,player_inv:get_size("craft") do local stack = player_inv:get_stack("craft", i) if inv:room_for_item("main", stack) then inv:add_item("main", stack) else --drop if no space left minetest.add_item(pos, stack) end end player_inv:set_list("main", {}) player_inv:set_list("craft", {}) meta:set_string("formspec", bones.bones_formspec) meta:set_string("infotext", player_name.."'s fresh bones") meta:set_string("owner", player_name) meta:set_int("time", 0) local timer = minetest.get_node_timer(pos) timer:start(10) end)
-- Minetest 0.4 mod: bones -- See README.txt for licensing and other information. bones = {} local function is_owner(pos, name) local owner = minetest.get_meta(pos):get_string("owner") if owner == "" or owner == name then return true end return false end bones.bones_formspec = "size[8,9]".. default.gui_bg.. default.gui_bg_img.. default.gui_slots.. "list[current_name;main;0,0.3;8,4;]".. "list[current_player;main;0,4.85;8,1;]".. "list[current_player;main;0,6.08;8,3;8]".. default.get_hotbar_bg(0,4.85) local share_bones_time = tonumber(minetest.setting_get("share_bones_time") or 1200) local share_bones_time_early = tonumber(minetest.setting_get("share_bones_time_early") or (share_bones_time/4)) minetest.register_node("bones:bones", { description = "Bones", tiles = { "bones_top.png", "bones_bottom.png", "bones_side.png", "bones_side.png", "bones_rear.png", "bones_front.png" }, paramtype2 = "facedir", groups = {dig_immediate=2}, sounds = default.node_sound_dirt_defaults({ footstep = {name="default_gravel_footstep", gain=0.5}, dug = {name="default_gravel_footstep", gain=1.0}, }), can_dig = function(pos, player) local inv = minetest.get_meta(pos):get_inventory() return is_owner(pos, player:get_player_name()) and inv:is_empty("main") end, allow_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player) if is_owner(pos, player:get_player_name()) then return count end return 0 end, allow_metadata_inventory_put = function(pos, listname, index, stack, player) return 0 end, allow_metadata_inventory_take = function(pos, listname, index, stack, player) if is_owner(pos, player:get_player_name()) then return stack:get_count() end return 0 end, on_metadata_inventory_take = function(pos, listname, index, stack, player) local meta = minetest.get_meta(pos) if meta:get_inventory():is_empty("main") then minetest.remove_node(pos) end end, on_punch = function(pos, node, player) if(not is_owner(pos, player:get_player_name())) then return end local inv = minetest.get_meta(pos):get_inventory() local player_inv = player:get_inventory() local has_space = true for i=1,inv:get_size("main") do local stk = inv:get_stack("main", i) if player_inv:room_for_item("main", stk) then inv:set_stack("main", i, nil) player_inv:add_item("main", stk) else has_space = false break end end -- remove bones if player emptied them if has_space then minetest.remove_node(pos) end end, on_timer = function(pos, elapsed) local meta = minetest.get_meta(pos) local time = meta:get_int("time") + elapsed if time >= share_bones_time then meta:set_string("infotext", meta:get_string("owner").."'s old bones") meta:set_string("owner", "") else meta:set_int("time", time) return true end end, }) local function may_replace(pos, player) local node_name = minetest.get_node(pos).name local node_definition = minetest.registered_nodes[node_name] -- if the node is unknown, we let the protection mod decide -- this is consistent with when a player could dig or not dig it -- unknown decoration would often be removed -- while unknown building materials in use would usually be left if not node_definition then -- only replace nodes that are not protected return not minetest.is_protected(pos, player:get_player_name()) end -- allow replacing air and liquids if node_name == "air" or node_definition.liquidtype ~= "none" then return true end -- don't replace filled chests and other nodes that don't allow it local can_dig_func = node_definition.can_dig if can_dig_func and not can_dig_func(pos, player) then return false end -- default to each nodes buildable_to; if a placed block would replace it, why shouldn't bones? -- flowers being squished by bones are more realistical than a squished stone, too -- exception are of course any protected buildable_to return node_definition.buildable_to and not minetest.is_protected(pos, player:get_player_name()) end minetest.register_on_dieplayer(function(player) if minetest.setting_getbool("creative_mode") then return end local player_inv = player:get_inventory() if player_inv:is_empty("main") and player_inv:is_empty("craft") then return end local pos = player:getpos() pos.x = math.floor(pos.x+0.5) pos.y = math.floor(pos.y+0.5) pos.z = math.floor(pos.z+0.5) local param2 = minetest.dir_to_facedir(player:get_look_dir()) local player_name = player:get_player_name() local player_inv = player:get_inventory() if (not may_replace(pos, player)) then if (may_replace({x=pos.x, y=pos.y+1, z=pos.z}, player)) then -- drop one node above if there's space -- this should solve most cases of protection related deaths in which players dig straight down -- yet keeps the bones reachable pos.y = pos.y+1 else -- drop items instead of delete for i=1,player_inv:get_size("main") do minetest.add_item(pos, player_inv:get_stack("main", i)) end for i=1,player_inv:get_size("craft") do minetest.add_item(pos, player_inv:get_stack("craft", i)) end -- empty lists main and craft player_inv:set_list("main", {}) player_inv:set_list("craft", {}) return end end minetest.set_node(pos, {name="bones:bones", param2=param2}) local meta = minetest.get_meta(pos) local inv = meta:get_inventory() inv:set_size("main", 8*4) inv:set_list("main", player_inv:get_list("main")) for i=1,player_inv:get_size("craft") do local stack = player_inv:get_stack("craft", i) if inv:room_for_item("main", stack) then inv:add_item("main", stack) else --drop if no space left minetest.add_item(pos, stack) end end player_inv:set_list("main", {}) player_inv:set_list("craft", {}) meta:set_string("formspec", bones.bones_formspec) meta:set_string("owner", player_name) if share_bones_time ~= 0 then meta:set_string("infotext", player_name.."'s fresh bones") if share_bones_time_early == 0 or not minetest.is_protected(pos, player_name) then meta:set_int("time", 0) else meta:set_int("time", (share_bones_time - share_bones_time_early)) end minetest.get_node_timer(pos):start(10) else meta:set_string("infotext", player_name.."'s bones") end end)
Bones mod fixes
Bones mod fixes 1. don't delete protected nodes, 2. time out in loaded chunks, 3. don't crash when dying in certain nodes (like default doors or sign_lib signs)
Lua
lgpl-2.1
evrooije/beerarchy,evrooije/beerarchy,evrooije/beerarchy
6c3d9af3742a23cde87db1b4c4649bcbf4267057
lua/include/histogram.lua
lua/include/histogram.lua
local histogram = {} histogram.__index = histogram local serpent = require "Serpent" function histogram:create() local histo = setmetatable({}, histogram) histo.histo = {} histo.dirty = true return histo end histogram.new = histogram.create setmetatable(histogram, { __call = histogram.create }) function histogram:update(k) if not k then return end self.histo[k] = (self.histo[k] or 0) +1 self.dirty = true end function histogram:calc() self.sortedHisto = {} self.sum = 0 self.numSamples = 0 for k, v in pairs(self.histo) do table.insert(self.sortedHisto, { k = k, v = v }) self.numSamples = self.numSamples + v self.sum = self.sum + k * v end self.avg = self.sum / self.numSamples local stdDevSum = 0 for k, v in pairs(self.histo) do stdDevSum = stdDevSum + v * (k - self.avg)^2 end self.stdDev = (stdDevSum / (self.numSamples - 1)) ^ 0.5 table.sort(self.sortedHisto, function(e1, e2) return e1.k < e2.k end) -- TODO: this is obviously not entirely correct for numbers not divisible by 4 -- however, it doesn't really matter for the number of samples we usually use local quartSamples = self.numSamples / 4 self.quarts = {} local idx = 0 for _, p in ipairs(self.sortedHisto) do -- TODO: inefficient for _ = 1, p.v do if not self.quarts[1] and idx >= quartSamples then self.quarts[1] = p.k elseif not self.quarts[2] and idx >= quartSamples * 2 then self.quarts[2] = p.k elseif not self.quarts[3] and idx >= quartSamples * 3 then self.quarts[3] = p.k break end idx = idx + 1 end end for i = 1, 3 do if not self.quarts[i] then self.quarts[i] = 0/0 end end self.dirty = false end function histogram:totals() if self.dirty then self:calc() end return self.numSamples, self.sum, self.avg end function histogram:avg() if self.dirty then self:calc() end return self.avg end function histogram:standardDeviation() if self.dirty then self:calc() end return self.stdDev end function histogram:quartiles() if self.dirty then self:calc() end return unpack(self.quarts) end function histogram:median() if self.dirty then self:calc() end return self.quarts[2] end function histogram:samples() local i = 0 if self.dirty then self:calc() end local n = #self.sortedHisto return function() if not self.dirty then i = i + 1 if i <= n then return self.sortedHisto[i] end end end end -- FIXME: add support for different formats function histogram:print() if self.dirty then self:calc() end printf("Samples: %d, Average: %.1f, StdDev: %.1f, Quartiles: %.1f/%.1f/%.1f", self.numSamples, self.avg, self.stdDev, unpack(self.quarts)) end function histogram:save(file) if self.dirty then self:calc() end local close = false if type(file) ~= "userdata" then printf("Saving histogram to '%s'", file) file = io.open(file, "w+") close = true end for i, v in ipairs(self.sortedHisto) do file:write(("%s,%s\n"):format(v.k, v.v)) end if close then file:close() end end function histogram:__serialize() return "require 'histogram'; return " .. serpent.addMt(serpent.dumpRaw(self), "require('histogram')"), true end return histogram
local histogram = {} histogram.__index = histogram local serpent = require "Serpent" function histogram:create() local histo = setmetatable({}, histogram) histo.histo = {} histo.dirty = true return histo end histogram.new = histogram.create setmetatable(histogram, { __call = histogram.create }) function histogram:update(k) if not k then return end self.histo[k] = (self.histo[k] or 0) +1 self.dirty = true end function histogram:calc() self.sortedHisto = {} self.sum = 0 self.numSamples = 0 for k, v in pairs(self.histo) do table.insert(self.sortedHisto, { k = k, v = v }) self.numSamples = self.numSamples + v self.sum = self.sum + k * v end self.avg = self.sum / self.numSamples local stdDevSum = 0 for k, v in pairs(self.histo) do stdDevSum = stdDevSum + v * (k - self.avg)^2 end self.stdDev = (stdDevSum / (self.numSamples - 1)) ^ 0.5 table.sort(self.sortedHisto, function(e1, e2) return e1.k < e2.k end) -- TODO: this is obviously not entirely correct for numbers not divisible by 4 -- however, it doesn't really matter for the number of samples we usually use local quartSamples = self.numSamples / 4 self.quarts = {} local idx = 0 for _, p in ipairs(self.sortedHisto) do -- TODO: inefficient for _ = 1, p.v do if not self.quarts[1] and idx >= quartSamples then self.quarts[1] = p.k elseif not self.quarts[2] and idx >= quartSamples * 2 then self.quarts[2] = p.k elseif not self.quarts[3] and idx >= quartSamples * 3 then self.quarts[3] = p.k break end idx = idx + 1 end end for i = 1, 3 do if not self.quarts[i] then self.quarts[i] = 0/0 end end self.dirty = false end function histogram:totals() if self.dirty then self:calc() end return self.numSamples, self.sum, self.avg end function histogram:avg() if self.dirty then self:calc() end return self.avg end function histogram:standardDeviation() if self.dirty then self:calc() end return self.stdDev end function histogram:quartiles() if self.dirty then self:calc() end return unpack(self.quarts) end function histogram:median() if self.dirty then self:calc() end return self.quarts[2] end function histogram:samples() local i = 0 if self.dirty then self:calc() end local n = #self.sortedHisto return function() if not self.dirty then i = i + 1 if i <= n then return self.sortedHisto[i] end end end end -- FIXME: add support for different formats function histogram:print(prefix) if self.dirty then self:calc() end printf("%sSamples: %d, Average: %.1f ns, StdDev: %.1f ns, Quartiles: %.1f/%.1f/%.1f ns", prefix and ("[" .. prefix .. "] ") or "", self.numSamples, self.avg, self.stdDev, unpack(self.quarts)) end function histogram:save(file) if self.dirty then self:calc() end local close = false if type(file) ~= "userdata" then printf("Saving histogram to '%s'", file) file = io.open(file, "w+") close = true end for i, v in ipairs(self.sortedHisto) do file:write(("%s,%s\n"):format(v.k, v.v)) end if close then file:close() end end function histogram:__serialize() return "require 'histogram'; return " .. serpent.addMt(serpent.dumpRaw(self), "require('histogram')"), true end return histogram
hist: add prefix to print() method, show units
hist: add prefix to print() method, show units
Lua
mit
duk3luk3/MoonGen,atheurer/MoonGen,gallenmu/MoonGen,emmericp/MoonGen,NetronomeMoongen/MoonGen,dschoeffm/MoonGen,wenhuizhang/MoonGen,scholzd/MoonGen,werpat/MoonGen,wenhuizhang/MoonGen,atheurer/MoonGen,kidaa/MoonGen,bmichalo/MoonGen,gallenmu/MoonGen,atheurer/MoonGen,wenhuizhang/MoonGen,gallenmu/MoonGen,NetronomeMoongen/MoonGen,scholzd/MoonGen,bmichalo/MoonGen,kidaa/MoonGen,slyon/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,werpat/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,kidaa/MoonGen,bmichalo/MoonGen,gallenmu/MoonGen,slyon/MoonGen,duk3luk3/MoonGen,emmericp/MoonGen,schoenb/MoonGen,schoenb/MoonGen,schoenb/MoonGen,slyon/MoonGen,NetronomeMoongen/MoonGen,slyon/MoonGen,dschoeffm/MoonGen,bmichalo/MoonGen,duk3luk3/MoonGen,scholzd/MoonGen,werpat/MoonGen,emmericp/MoonGen,dschoeffm/MoonGen
d6bd90d780e34896a7b45cc33367eafd074dacee
game/scripts/vscripts/libraries/keyvalues.lua
game/scripts/vscripts/libraries/keyvalues.lua
KEYVALUES_VERSION = "1.00" --[[ Simple Lua KeyValues library, modified version Author: Martin Noya // github.com/MNoya Installation: - require this file inside your code Usage: - Your npc custom files will be validated on require, error will occur if one is missing or has faulty syntax. - This allows to safely grab key-value definitions in npc custom abilities/items/units/heroes "some_custom_entry" { "CustomName" "Barbarian" "CustomKey" "1" "CustomStat" "100 200" } With a handle: handle:GetKeyValue() -- returns the whole table based on the handles baseclass handle:GetKeyValue("CustomName") -- returns "Barbarian" handle:GetKeyValue("CustomKey") -- returns 1 (number) handle:GetKeyValue("CustomStat") -- returns "100 200" (string) handle:GetKeyValue("CustomStat", 2) -- returns 200 (number) Same results with strings: GetKeyValue("some_custom_entry") GetKeyValue("some_custom_entry", "CustomName") GetKeyValue("some_custom_entry", "CustomStat") GetKeyValue("some_custom_entry", "CustomStat", 2) - Ability Special value grabbing: "some_custom_ability" { "AbilitySpecial" { "01" { "var_type" "FIELD_INTEGER" "some_key" "-3 -4 -5" } } } With a handle: ability:GetAbilitySpecial("some_key") -- returns based on the level of the ability/item With string: GetAbilitySpecial("some_custom_ability", "some_key") -- returns "-3 -4 -5" (string) GetAbilitySpecial("some_custom_ability", "some_key", 2) -- returns -4 (number) Notes: - In case a key can't be matched, the returned value will be nil - Don't identify your custom units/heroes with the same name or it will only grab one of them. ]] if not KeyValues then KeyValues = {} end -- Load all the necessary key value files function LoadGameKeyValues() local scriptPath = "scripts/npc/" local override = LoadKeyValues(scriptPath.."npc_abilities_override.txt") local files = { AbilityKV = {base = "npc_abilities",custom = "npc_abilities_custom"}, ItemKV = {base = "items", custom = "npc_items_custom"}, UnitKV = {base = "npc_units", custom = "npc_units_custom"}, HeroKV = {base = "npc_heroes", custom = "npc_heroes_custom", new = "heroes/new"} } if not override then print("[KeyValues] Critical Error on "..override..".txt") return end -- Load and validate the files for KVType,KVFilePaths in pairs(files) do local file = LoadKeyValues(scriptPath .. KVFilePaths.base .. ".txt") -- Replace main game keys by any match on the override file for k,v in pairs(override) do if file[k] then if type(v) == "table" then table.merge(file[k], v) else file[k] = v end end end local custom_file = LoadKeyValues(scriptPath .. KVFilePaths.custom .. ".txt") if custom_file then if KVType == "HeroKV" then for k,v in pairs(custom_file) do if not file[k] then file[k] = {} local override_hero = v.override_hero if override_hero then if file[override_hero] then table.deepmerge(file[k], file[override_hero]) end if custom_file[override_hero] then table.deepmerge(file[k], custom_file[override_hero]) end end table.deepmerge(file[k], v) else table.deepmerge(file[k], v) end end else table.deepmerge(file, custom_file) end else print("[KeyValues] Critical Error on " .. KVFilePaths.custom .. ".txt") return end if KVFilePaths.new then table.deepmerge(file, LoadKeyValues(scriptPath .. KVFilePaths.new .. ".txt")) end KeyValues[KVType] = file end -- Merge All KVs KeyValues.All = {} for name,path in pairs(files) do for key,value in pairs(KeyValues[name]) do KeyValues.All[key] = value end end -- Merge units and heroes (due to them sharing the same class CDOTA_BaseNPC) for key,value in pairs(KeyValues.HeroKV) do if not KeyValues.UnitKV[key] then KeyValues.UnitKV[key] = value elseif type(KeyValues.All[key]) == "table" then table.deepmerge(KeyValues.UnitKV[key], value) end end end -- Works for heroes and units on the same table due to merging both tables on game init function CDOTA_BaseNPC:GetKeyValue(key, level, bOriginalHero) return GetUnitKV(bOriginalHero and self:GetUnitName() or self:GetFullName(), key, level) end -- Dynamic version of CDOTABaseAbility:GetAbilityKeyValues() function CDOTABaseAbility:GetKeyValue(key, level) if level then return GetAbilityKV(self:GetAbilityName(), key, level) else return GetAbilityKV(self:GetAbilityName(), key) end end -- Item version function CDOTA_Item:GetKeyValue(key, level) if level then return GetItemKV(self:GetAbilityName(), key, level) else return GetItemKV(self:GetAbilityName(), key) end end function CDOTABaseAbility:GetAbilitySpecial(key) return GetAbilitySpecial(self:GetAbilityName(), key, self:GetLevel()) end -- Global functions -- Key is optional, returns the whole table by omission -- Level is optional, returns the whole value by omission function GetKeyValue(name, key, level, tbl) local t = tbl or KeyValues.All[name] if key and t then if t[key] and level then local s = string.split(t[key]) if s[level] then return tonumber(s[level]) or s[level] -- Try to cast to number else return tonumber(s[#s]) or s[#s] end else return t[key] end else return t end end function GetUnitKV(unitName, key, level) return GetKeyValue(unitName, key, level, KeyValues.UnitKV[unitName]) end function GetAbilityKV(abilityName, key, level) return GetKeyValue(abilityName, key, level, KeyValues.AbilityKV[abilityName]) end function GetItemKV(itemName, key, level) return GetKeyValue(itemName, key, level, KeyValues.ItemKV[itemName]) end function GetAbilitySpecial(name, key, level, t) if not t then t = KeyValues.All[name] end if t then local AbilitySpecial = t.AbilitySpecial if AbilitySpecial then if key then -- Find the key we are looking for for _,values in pairs(AbilitySpecial) do if values[key] then return GetValueInStringForLevel(values[key], level) end end else local o = {} for _,values in pairs(AbilitySpecial) do for k,v in pairs(values) do if k ~= 'var_type' and k ~= 'CalculateSpellDamageTooltip' and k ~= 'levelkey' then o[k] = v end end end return o end end end end function GetValueInStringForLevel(str, level) if not level then return str else local s = string.split(str) if s[level] then -- If we match the level, return that one return tonumber(s[level]) else -- Otherwise, return the max return tonumber(s[#s]) end end end function GetItemNameById(itemid) for name,kv in pairs(KeyValues.ItemKV) do if kv and type(kv) == "table" and kv.ID and kv.ID == itemid then return name end end end function GetItemIdByName(itemName) return KeyValues.ItemKV[itemName].ID end --if not KeyValues.All then LoadGameKeyValues() end LoadGameKeyValues()
KEYVALUES_VERSION = "1.00" --[[ Simple Lua KeyValues library, modified version Author: Martin Noya // github.com/MNoya Installation: - require this file inside your code Usage: - Your npc custom files will be validated on require, error will occur if one is missing or has faulty syntax. - This allows to safely grab key-value definitions in npc custom abilities/items/units/heroes "some_custom_entry" { "CustomName" "Barbarian" "CustomKey" "1" "CustomStat" "100 200" } With a handle: handle:GetKeyValue() -- returns the whole table based on the handles baseclass handle:GetKeyValue("CustomName") -- returns "Barbarian" handle:GetKeyValue("CustomKey") -- returns 1 (number) handle:GetKeyValue("CustomStat") -- returns "100 200" (string) handle:GetKeyValue("CustomStat", 2) -- returns 200 (number) Same results with strings: GetKeyValue("some_custom_entry") GetKeyValue("some_custom_entry", "CustomName") GetKeyValue("some_custom_entry", "CustomStat") GetKeyValue("some_custom_entry", "CustomStat", 2) - Ability Special value grabbing: "some_custom_ability" { "AbilitySpecial" { "01" { "var_type" "FIELD_INTEGER" "some_key" "-3 -4 -5" } } } With a handle: ability:GetAbilitySpecial("some_key") -- returns based on the level of the ability/item With string: GetAbilitySpecial("some_custom_ability", "some_key") -- returns "-3 -4 -5" (string) GetAbilitySpecial("some_custom_ability", "some_key", 2) -- returns -4 (number) Notes: - In case a key can't be matched, the returned value will be nil - Don't identify your custom units/heroes with the same name or it will only grab one of them. ]] if not KeyValues then KeyValues = {} end -- Load all the necessary key value files function LoadGameKeyValues() local scriptPath = "scripts/npc/" local override = LoadKeyValues(scriptPath.."npc_abilities_override.txt") local files = { AbilityKV = {base = "npc_abilities",custom = "npc_abilities_custom"}, ItemKV = {base = "items", custom = "npc_items_custom"}, UnitKV = {base = "npc_units", custom = "npc_units_custom"}, HeroKV = {base = "npc_heroes", custom = "npc_heroes_custom", new = "heroes/new"} } if not override then print("[KeyValues] Critical Error on "..override..".txt") return end -- Load and validate the files for KVType,KVFilePaths in pairs(files) do local file = LoadKeyValues(scriptPath .. KVFilePaths.base .. ".txt") -- Replace main game keys by any match on the override file for k,v in pairs(override) do if file[k] then if type(v) == "table" then table.merge(file[k], v) else file[k] = v end end end local custom_file = LoadKeyValues(scriptPath .. KVFilePaths.custom .. ".txt") if custom_file then if KVType == "HeroKV" then for k,v in pairs(custom_file) do if not file[k] then file[k] = {} table.deepmerge(file[k], v) else table.deepmerge(file[k], v) end end else table.deepmerge(file, custom_file) end else print("[KeyValues] Critical Error on " .. KVFilePaths.custom .. ".txt") return end if KVFilePaths.new then table.deepmerge(file, LoadKeyValues(scriptPath .. KVFilePaths.new .. ".txt")) end file.Version = nil KeyValues[KVType] = file end -- Merge All KVs KeyValues.All = {} for name,path in pairs(files) do for key,value in pairs(KeyValues[name]) do KeyValues.All[key] = value end end -- Merge units and heroes (due to them sharing the same class CDOTA_BaseNPC) for key,value in pairs(KeyValues.HeroKV) do if not KeyValues.UnitKV[key] then KeyValues.UnitKV[key] = value elseif type(KeyValues.All[key]) == "table" then table.deepmerge(KeyValues.UnitKV[key], value) end end KeyValues.HeroKV = nil for k,v in pairs(KeyValues.UnitKV) do local override_hero = v.override_hero or v.base_hero if override_hero and KeyValues.UnitKV[override_hero] then table.deepmerge(v, KeyValues.UnitKV[override_hero]) end end end -- Works for heroes and units on the same table due to merging both tables on game init function CDOTA_BaseNPC:GetKeyValue(key, level, bOriginalHero) return GetUnitKV(bOriginalHero and self:GetUnitName() or self:GetFullName(), key, level) end -- Dynamic version of CDOTABaseAbility:GetAbilityKeyValues() function CDOTABaseAbility:GetKeyValue(key, level) if level then return GetAbilityKV(self:GetAbilityName(), key, level) else return GetAbilityKV(self:GetAbilityName(), key) end end -- Item version function CDOTA_Item:GetKeyValue(key, level) if level then return GetItemKV(self:GetAbilityName(), key, level) else return GetItemKV(self:GetAbilityName(), key) end end function CDOTABaseAbility:GetAbilitySpecial(key) return GetAbilitySpecial(self:GetAbilityName(), key, self:GetLevel()) end -- Global functions -- Key is optional, returns the whole table by omission -- Level is optional, returns the whole value by omission function GetKeyValue(name, key, level, tbl) local t = tbl or KeyValues.All[name] if key and t then if t[key] and level then local s = string.split(t[key]) if s[level] then return tonumber(s[level]) or s[level] -- Try to cast to number else return tonumber(s[#s]) or s[#s] end else return t[key] end else return t end end function GetUnitKV(unitName, key, level) return GetKeyValue(unitName, key, level, KeyValues.UnitKV[unitName]) end function GetAbilityKV(abilityName, key, level) return GetKeyValue(abilityName, key, level, KeyValues.AbilityKV[abilityName]) end function GetItemKV(itemName, key, level) return GetKeyValue(itemName, key, level, KeyValues.ItemKV[itemName]) end function GetAbilitySpecial(name, key, level, t) if not t then t = KeyValues.All[name] end if t then local AbilitySpecial = t.AbilitySpecial if AbilitySpecial then if key then -- Find the key we are looking for for _,values in pairs(AbilitySpecial) do if values[key] then return GetValueInStringForLevel(values[key], level) end end else local o = {} for _,values in pairs(AbilitySpecial) do for k,v in pairs(values) do if k ~= 'var_type' and k ~= 'CalculateSpellDamageTooltip' and k ~= 'levelkey' then o[k] = v end end end return o end end end end function GetValueInStringForLevel(str, level) if not level then return str else local s = string.split(str) if s[level] then -- If we match the level, return that one return tonumber(s[level]) else -- Otherwise, return the max return tonumber(s[#s]) end end end function GetItemNameById(itemid) for name,kv in pairs(KeyValues.ItemKV) do if kv and type(kv) == "table" and kv.ID and kv.ID == itemid then return name end end end function GetItemIdByName(itemName) return KeyValues.ItemKV[itemName].ID end --if not KeyValues.All then LoadGameKeyValues() end LoadGameKeyValues()
fix(keyvalues): now merges base_hero into hero's KV Also fixes ArmorPhysical was nil on some heroes while armor attribute adjusting
fix(keyvalues): now merges base_hero into hero's KV Also fixes ArmorPhysical was nil on some heroes while armor attribute adjusting
Lua
mit
ark120202/aabs
079c8476950b137a8090b2cae595f7c51904fcd2
plugins/mod_disco.lua
plugins/mod_disco.lua
-- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local get_children = require "core.hostmanager".get_children; local is_contact_subscribed = require "core.rostermanager".is_contact_subscribed; local jid_split = require "util.jid".split; local jid_bare = require "util.jid".bare; local st = require "util.stanza" local calculate_hash = require "util.caps".calculate_hash; local disco_items = module:get_option("disco_items") or {}; do -- validate disco_items for _, item in ipairs(disco_items) do local err; if type(item) ~= "table" then err = "item is not a table"; elseif type(item[1]) ~= "string" then err = "item jid is not a string"; elseif item[2] and type(item[2]) ~= "string" then err = "item name is not a string"; end if err then module:log("error", "option disco_items is malformed: %s", err); disco_items = {}; -- TODO clean up data instead of removing it? break; end end end module:add_identity("server", "im", "Prosody"); -- FIXME should be in the non-existing mod_router module:add_feature("http://jabber.org/protocol/disco#info"); module:add_feature("http://jabber.org/protocol/disco#items"); -- Generate and cache disco result and caps hash local _cached_server_disco_info, _cached_server_caps_feature, _cached_server_caps_hash; local function build_server_disco_info() local query = st.stanza("query", { xmlns = "http://jabber.org/protocol/disco#info" }); local done = {}; for _,identity in ipairs(module:get_host_items("identity")) do local identity_s = identity.category.."\0"..identity.type; if not done[identity_s] then query:tag("identity", identity):up(); done[identity_s] = true; end end for _,feature in ipairs(module:get_host_items("feature")) do if not done[feature] then query:tag("feature", {var=feature}):up(); done[feature] = true; end end _cached_server_disco_info = query; _cached_server_caps_hash = calculate_hash(query); _cached_server_caps_feature = st.stanza("c", { xmlns = "http://jabber.org/protocol/caps"; hash = "sha-1"; node = "http://prosody.im"; ver = _cached_server_caps_hash; }); end local function clear_disco_cache() _cached_server_disco_info, _cached_server_caps_feature, _cached_server_caps_hash = nil, nil, nil; end local function get_server_disco_info() if not _cached_server_disco_info then build_server_disco_info(); end return _cached_server_disco_info; end local function get_server_caps_feature() if not _cached_server_caps_feature then build_server_disco_info(); end return _cached_server_caps_feature; end local function get_server_caps_hash() if not _cached_server_caps_hash then build_server_disco_info(); end return _cached_server_caps_hash; end module:hook("item-added/identity", clear_disco_cache); module:hook("item-added/feature", clear_disco_cache); -- Handle disco requests to the server module:hook("iq/host/http://jabber.org/protocol/disco#info:query", function(event) local origin, stanza = event.origin, event.stanza; if stanza.attr.type ~= "get" then return; end local node = stanza.tags[1].attr.node; if node and node ~= "" and node ~= "http://prosody.im#"..get_server_caps_hash() then return; end -- TODO fire event? local reply_query = get_server_disco_info(); reply_query.node = node; local reply = st.reply(stanza):add_child(reply_query); origin.send(reply); return true; end); module:hook("iq/host/http://jabber.org/protocol/disco#items:query", function(event) local origin, stanza = event.origin, event.stanza; if stanza.attr.type ~= "get" then return; end local node = stanza.tags[1].attr.node; if node and node ~= "" then return; end -- TODO fire event? local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items"); for jid in pairs(get_children(module.host)) do reply:tag("item", {jid = jid}):up(); end for _, item in ipairs(disco_items) do reply:tag("item", {jid=item[1], name=item[2]}):up(); end origin.send(reply); return true; end); -- Handle caps stream feature module:hook("stream-features", function (event) event.features:add_child(get_server_caps_feature()); end); -- Handle disco requests to user accounts module:hook("iq/bare/http://jabber.org/protocol/disco#info:query", function(event) local origin, stanza = event.origin, event.stanza; if stanza.attr.type ~= "get" then return; end local node = stanza.tags[1].attr.node; if node and node ~= "" then return; end -- TODO fire event? local username = jid_split(stanza.attr.to) or origin.username; if not stanza.attr.to or is_contact_subscribed(username, module.host, jid_bare(stanza.attr.from)) then local reply = st.reply(stanza):tag('query', {xmlns='http://jabber.org/protocol/disco#info'}); if not reply.attr.from then reply.attr.from = origin.username.."@"..origin.host; end -- COMPAT To satisfy Psi when querying own account module:fire_event("account-disco-info", { origin = origin, stanza = reply }); origin.send(reply); return true; end end); module:hook("iq/bare/http://jabber.org/protocol/disco#items:query", function(event) local origin, stanza = event.origin, event.stanza; if stanza.attr.type ~= "get" then return; end local node = stanza.tags[1].attr.node; if node and node ~= "" then return; end -- TODO fire event? local username = jid_split(stanza.attr.to) or origin.username; if not stanza.attr.to or is_contact_subscribed(username, module.host, jid_bare(stanza.attr.from)) then local reply = st.reply(stanza):tag('query', {xmlns='http://jabber.org/protocol/disco#items'}); if not reply.attr.from then reply.attr.from = origin.username.."@"..origin.host; end -- COMPAT To satisfy Psi when querying own account module:fire_event("account-disco-items", { origin = origin, stanza = reply }); origin.send(reply); return true; end end);
-- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local get_children = require "core.hostmanager".get_children; local is_contact_subscribed = require "core.rostermanager".is_contact_subscribed; local jid_split = require "util.jid".split; local jid_bare = require "util.jid".bare; local st = require "util.stanza" local calculate_hash = require "util.caps".calculate_hash; local disco_items = module:get_option("disco_items") or {}; do -- validate disco_items for _, item in ipairs(disco_items) do local err; if type(item) ~= "table" then err = "item is not a table"; elseif type(item[1]) ~= "string" then err = "item jid is not a string"; elseif item[2] and type(item[2]) ~= "string" then err = "item name is not a string"; end if err then module:log("error", "option disco_items is malformed: %s", err); disco_items = {}; -- TODO clean up data instead of removing it? break; end end end module:add_identity("server", "im", "Prosody"); -- FIXME should be in the non-existing mod_router module:add_feature("http://jabber.org/protocol/disco#info"); module:add_feature("http://jabber.org/protocol/disco#items"); -- Generate and cache disco result and caps hash local _cached_server_disco_info, _cached_server_caps_feature, _cached_server_caps_hash; local function build_server_disco_info() local query = st.stanza("query", { xmlns = "http://jabber.org/protocol/disco#info" }); local done = {}; for _,identity in ipairs(module:get_host_items("identity")) do local identity_s = identity.category.."\0"..identity.type; if not done[identity_s] then query:tag("identity", identity):up(); done[identity_s] = true; end end for _,feature in ipairs(module:get_host_items("feature")) do if not done[feature] then query:tag("feature", {var=feature}):up(); done[feature] = true; end end _cached_server_disco_info = query; _cached_server_caps_hash = calculate_hash(query); _cached_server_caps_feature = st.stanza("c", { xmlns = "http://jabber.org/protocol/caps"; hash = "sha-1"; node = "http://prosody.im"; ver = _cached_server_caps_hash; }); end local function clear_disco_cache() _cached_server_disco_info, _cached_server_caps_feature, _cached_server_caps_hash = nil, nil, nil; end local function get_server_disco_info() if not _cached_server_disco_info then build_server_disco_info(); end return _cached_server_disco_info; end local function get_server_caps_feature() if not _cached_server_caps_feature then build_server_disco_info(); end return _cached_server_caps_feature; end local function get_server_caps_hash() if not _cached_server_caps_hash then build_server_disco_info(); end return _cached_server_caps_hash; end module:hook("item-added/identity", clear_disco_cache); module:hook("item-added/feature", clear_disco_cache); module:hook("item-removed/identity", clear_disco_cache); module:hook("item-removed/feature", clear_disco_cache); -- Handle disco requests to the server module:hook("iq/host/http://jabber.org/protocol/disco#info:query", function(event) local origin, stanza = event.origin, event.stanza; if stanza.attr.type ~= "get" then return; end local node = stanza.tags[1].attr.node; if node and node ~= "" and node ~= "http://prosody.im#"..get_server_caps_hash() then return; end -- TODO fire event? local reply_query = get_server_disco_info(); reply_query.node = node; local reply = st.reply(stanza):add_child(reply_query); origin.send(reply); return true; end); module:hook("iq/host/http://jabber.org/protocol/disco#items:query", function(event) local origin, stanza = event.origin, event.stanza; if stanza.attr.type ~= "get" then return; end local node = stanza.tags[1].attr.node; if node and node ~= "" then return; end -- TODO fire event? local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items"); for jid in pairs(get_children(module.host)) do reply:tag("item", {jid = jid}):up(); end for _, item in ipairs(disco_items) do reply:tag("item", {jid=item[1], name=item[2]}):up(); end origin.send(reply); return true; end); -- Handle caps stream feature module:hook("stream-features", function (event) event.features:add_child(get_server_caps_feature()); end); -- Handle disco requests to user accounts module:hook("iq/bare/http://jabber.org/protocol/disco#info:query", function(event) local origin, stanza = event.origin, event.stanza; if stanza.attr.type ~= "get" then return; end local node = stanza.tags[1].attr.node; if node and node ~= "" then return; end -- TODO fire event? local username = jid_split(stanza.attr.to) or origin.username; if not stanza.attr.to or is_contact_subscribed(username, module.host, jid_bare(stanza.attr.from)) then local reply = st.reply(stanza):tag('query', {xmlns='http://jabber.org/protocol/disco#info'}); if not reply.attr.from then reply.attr.from = origin.username.."@"..origin.host; end -- COMPAT To satisfy Psi when querying own account module:fire_event("account-disco-info", { origin = origin, stanza = reply }); origin.send(reply); return true; end end); module:hook("iq/bare/http://jabber.org/protocol/disco#items:query", function(event) local origin, stanza = event.origin, event.stanza; if stanza.attr.type ~= "get" then return; end local node = stanza.tags[1].attr.node; if node and node ~= "" then return; end -- TODO fire event? local username = jid_split(stanza.attr.to) or origin.username; if not stanza.attr.to or is_contact_subscribed(username, module.host, jid_bare(stanza.attr.from)) then local reply = st.reply(stanza):tag('query', {xmlns='http://jabber.org/protocol/disco#items'}); if not reply.attr.from then reply.attr.from = origin.username.."@"..origin.host; end -- COMPAT To satisfy Psi when querying own account module:fire_event("account-disco-items", { origin = origin, stanza = reply }); origin.send(reply); return true; end end);
mod_disco: Fixed: Service discovery features were not being removed on module unload (issue #205).
mod_disco: Fixed: Service discovery features were not being removed on module unload (issue #205).
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
b0e09b785290a8ae614ebc298742a077616abde2
core/usermanager.lua
core/usermanager.lua
-- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local datamanager = require "util.datamanager"; local modulemanager = require "core.modulemanager"; local log = require "util.logger".init("usermanager"); local type = type; local error = error; local ipairs = ipairs; local hashes = require "util.hashes"; local jid_bare = require "util.jid".bare; local config = require "core.configmanager"; local hosts = hosts; local require_provisioning = config.get("*", "core", "cyrus_require_provisioning") or false; local prosody = _G.prosody; local setmetatable = setmetatable; local default_provider = "internal_plain"; module "usermanager" function new_null_provider() local function dummy() end; return setmetatable({name = "null"}, { __index = function() return dummy; end }); end function initialize_host(host) local host_session = hosts[host]; host_session.events.add_handler("item-added/auth-provider", function (event) local provider = event.item; local auth_provider = config.get(host, "core", "authentication") or default_provider; if provider.name == auth_provider then host_session.users = provider; end if host_session.users ~= nil and host_session.users.name ~= nil then log("debug", "host '%s' now set to use user provider '%s'", host, host_session.users.name); end end); host_session.events.add_handler("item-removed/auth-provider", function (event) local provider = event.item; if host_session.users == provider then host_session.users = new_null_provider(); end end); host_session.users = new_null_provider(); -- Start with the default usermanager provider local auth_provider = config.get(host, "core", "authentication") or default_provider; if auth_provider ~= "null" then modulemanager.load(host, "auth_"..auth_provider); end end; prosody.events.add_handler("host-activated", initialize_host, 100); prosody.events.add_handler("component-activated", initialize_host, 100); function is_cyrus(host) return config.get(host, "core", "sasl_backend") == "cyrus"; end function test_password(username, password, host) return hosts[host].users.test_password(username, password); end function get_password(username, host) return hosts[host].users.get_password(username); end function set_password(username, password, host) return hosts[host].users.set_password(username, password); end function user_exists(username, host) return hosts[host].users.user_exists(username); end function create_user(username, password, host) return hosts[host].users.create_user(username, password); end function get_sasl_handler(host) return hosts[host].users.get_sasl_handler(); end function get_provider(host) return hosts[host].users; end function is_admin(jid, host) local is_admin; jid = jid_bare(jid); host = host or "*"; local host_admins = config.get(host, "core", "admins"); local global_admins = config.get("*", "core", "admins"); if host_admins and host_admins ~= global_admins then if type(host_admins) == "table" then for _,admin in ipairs(host_admins) do if admin == jid then is_admin = true; break; end end elseif admins then log("error", "Option 'admins' for host '%s' is not a list", host); end end if not is_admin and global_admins then if type(global_admins) == "table" then for _,admin in ipairs(global_admins) do if admin == jid then is_admin = true; break; end end elseif admins then log("error", "Global option 'admins' is not a list"); end end -- Still not an admin, check with auth provider if not is_admin and host ~= "*" and hosts[host].users.is_admin then is_admin = hosts[host].users.is_admin(jid); end return is_admin or false; end return _M;
-- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local datamanager = require "util.datamanager"; local modulemanager = require "core.modulemanager"; local log = require "util.logger".init("usermanager"); local type = type; local error = error; local ipairs = ipairs; local hashes = require "util.hashes"; local jid_bare = require "util.jid".bare; local config = require "core.configmanager"; local hosts = hosts; local sasl_new = require "util.sasl".new; local require_provisioning = config.get("*", "core", "cyrus_require_provisioning") or false; local prosody = _G.prosody; local setmetatable = setmetatable; local default_provider = "internal_plain"; module "usermanager" function new_null_provider() local function dummy() end; local function dummy_get_sasl_handler() return sasl_new(nil, {}); end return setmetatable({name = "null", get_sasl_handler = dummy_get_sasl_handler}, { __index = function() return dummy; end }); end function initialize_host(host) local host_session = hosts[host]; host_session.events.add_handler("item-added/auth-provider", function (event) local provider = event.item; local auth_provider = config.get(host, "core", "authentication") or default_provider; if provider.name == auth_provider then host_session.users = provider; end if host_session.users ~= nil and host_session.users.name ~= nil then log("debug", "host '%s' now set to use user provider '%s'", host, host_session.users.name); end end); host_session.events.add_handler("item-removed/auth-provider", function (event) local provider = event.item; if host_session.users == provider then host_session.users = new_null_provider(); end end); host_session.users = new_null_provider(); -- Start with the default usermanager provider local auth_provider = config.get(host, "core", "authentication") or default_provider; if auth_provider ~= "null" then modulemanager.load(host, "auth_"..auth_provider); end end; prosody.events.add_handler("host-activated", initialize_host, 100); prosody.events.add_handler("component-activated", initialize_host, 100); function is_cyrus(host) return config.get(host, "core", "sasl_backend") == "cyrus"; end function test_password(username, password, host) return hosts[host].users.test_password(username, password); end function get_password(username, host) return hosts[host].users.get_password(username); end function set_password(username, password, host) return hosts[host].users.set_password(username, password); end function user_exists(username, host) return hosts[host].users.user_exists(username); end function create_user(username, password, host) return hosts[host].users.create_user(username, password); end function get_sasl_handler(host) return hosts[host].users.get_sasl_handler(); end function get_provider(host) return hosts[host].users; end function is_admin(jid, host) local is_admin; jid = jid_bare(jid); host = host or "*"; local host_admins = config.get(host, "core", "admins"); local global_admins = config.get("*", "core", "admins"); if host_admins and host_admins ~= global_admins then if type(host_admins) == "table" then for _,admin in ipairs(host_admins) do if admin == jid then is_admin = true; break; end end elseif admins then log("error", "Option 'admins' for host '%s' is not a list", host); end end if not is_admin and global_admins then if type(global_admins) == "table" then for _,admin in ipairs(global_admins) do if admin == jid then is_admin = true; break; end end elseif admins then log("error", "Global option 'admins' is not a list"); end end -- Still not an admin, check with auth provider if not is_admin and host ~= "*" and hosts[host].users.is_admin then is_admin = hosts[host].users.is_admin(jid); end return is_admin or false; end return _M;
usermanager: Return a non-nil SASL handler from the null auth provider (fixes a traceback).
usermanager: Return a non-nil SASL handler from the null auth provider (fixes a traceback).
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
480df1b39315b1cd9c4a2705082289cb8dfbda7e
vi_quickfix.lua
vi_quickfix.lua
-- Implement quickfix-like functionality. local M = {} local lpeg = require('lpeg') local P = lpeg.P local S = lpeg.S local C = lpeg.C local R = lpeg.R local Ct = lpeg.Ct local Cg = lpeg.Cg local Cc = lpeg.Cc local ws = S" \t" local to_nl = (P(1) - P"\n") ^ 0 local errpat_newdir = Ct(P"make: Entering directory " * S("'`") * Cg((P(1) - P"'")^0, 'newdir')* P"'") local errpat_leavedir = Ct(P"make: Leaving directory " * S("'`") * Cg((P(1) - P"'")^0, 'leavedir')* P"'") local errpat_error = Ct((P"In file included from " ^-1) * Cg((P(1) - S":\n") ^ 0, 'path') * P":" * Cg(R"09" ^ 0, 'lineno') * P":" * (S(" \t") ^ 0) * Cg(to_nl, "message")) local errpat_error_nofile = Ct((P"error" + P"Error" + P"ERROR") * P":" * ws * Cg(to_nl, "message")) + Ct(Cg(P"make: ***" * to_nl, "message")) local errpat_ignore = (P(1) - "\n") ^ 0 local errpat_line = (errpat_newdir + errpat_error + errpat_error_nofile)-- + errpat_ignore) local function pretty(x) if type(x) == 'table' then local bits = {'{\n'} for k,v in pairs(x) do bits[#bits+1] = " " bits[#bits+1] = pretty(k) bits[#bits+1] = " = " bits[#bits+1] = pretty(v) bits[#bits+1] = "\n" end bits[#bits+1] = '}\n' return table.concat(bits) elseif type(x) == 'string' then return "'" .. x .. "'" else return tostring(x) end end local function ts(...) local args = {...} local bits = {} for i,v in ipairs(args) do bits[#bits + 1] = pretty(v) bits[#bits + 1] = "," end return table.concat(bits) end function M.quickfix_from_buffer(buffer) local dirs = {} local results = {} for i=0,buffer.line_count-1 do local line = buffer:get_line(i) line = line:match("([^\n]*)") local match = errpat_line:match(line) if match then if match.newdir then dirs[#dirs+1] = match.newdir elseif match.leavedir then if dirs[#dirs] ~= match.leavedir then error("Non-matching leave directory") else dirs[#dirs] = nil end elseif match.path or match.message then local path = match.path local lineno = match.lineno and tonumber(match.lineno) or nil local message = match.message if path and #dirs > 0 then path = dirs[#dirs] .. "/" .. path end local idx = #results + 1 results[idx] = { line, path=path, lineno=lineno, idx=idx, message=message } end end --cme_log("<"..buffer:get_line(i)..">") --cme_log("{"..ts(errpat_newdir:match((buffer:get_line(i)))).."}") --cme_log(ts(errpat_line:match((buffer:get_line(i))))) end return results end return M
-- Implement quickfix-like functionality. local M = {} local lpeg = require('lpeg') local P = lpeg.P local S = lpeg.S local C = lpeg.C local R = lpeg.R local Ct = lpeg.Ct local Cg = lpeg.Cg local Cc = lpeg.Cc local ws = S" \t" local to_nl = (P(1) - P"\n") ^ 0 local errpat_newdir = Ct(P"make: Entering directory " * S("'`") * Cg((P(1) - P"'")^0, 'newdir')* P"'") local errpat_leavedir = Ct(P"make: Leaving directory " * S("'`") * Cg((P(1) - P"'")^0, 'leavedir')* P"'") local errpat_error = Ct((P"In file included from " ^-1) * Cg((P(1) - S":\n") ^ 0, 'path') * P":" * Cg(R"09" ^ 0, 'lineno') * P":" * ((Cg(R"09" ^ 0, 'colno') * P":")^-1) * (S(" \t") ^ 0) * Cg(to_nl, "message")) local errpat_error_nofile = Ct((P"error" + P"Error" + P"ERROR") * P":" * ws * Cg(to_nl, "message")) + Ct(Cg(P"make: ***" * to_nl, "message")) local errpat_ignore = (P(1) - "\n") ^ 0 local errpat_line = (errpat_newdir + errpat_error + errpat_error_nofile)-- + errpat_ignore) local function pretty(x) if type(x) == 'table' then local bits = {'{\n'} for k,v in pairs(x) do bits[#bits+1] = " " bits[#bits+1] = pretty(k) bits[#bits+1] = " = " bits[#bits+1] = pretty(v) bits[#bits+1] = "\n" end bits[#bits+1] = '}\n' return table.concat(bits) elseif type(x) == 'string' then return "'" .. x .. "'" else return tostring(x) end end local function ts(...) local args = {...} local bits = {} for i,v in ipairs(args) do bits[#bits + 1] = pretty(v) bits[#bits + 1] = "," end return table.concat(bits) end function M.quickfix_from_buffer(buffer) local dirs = {} local results = {} for i=1,buffer.line_count do local line = buffer:get_line(i) line = line:match("([^\n]*)") local match = errpat_line:match(line) if match then if match.newdir then dirs[#dirs+1] = match.newdir elseif match.leavedir then if dirs[#dirs] ~= match.leavedir then error("Non-matching leave directory") else dirs[#dirs] = nil end elseif match.path or match.message then local path = match.path local lineno = match.lineno and tonumber(match.lineno) or nil local colno = match.colno and tonumber(match.colno) or nil local message = match.message -- Get any extra lines of a multi-line message local errline = i + 1 while errline <= buffer.line_count do local contline = buffer:get_line(errline) local matchlen = contline:match("^[ %d]* | ()") if matchlen then message = message .. "\n" .. contline:sub(matchlen) contline = contline:match("([^\n]*)") line = line .. "\n" .. contline i = i + 1 else break end errline = errline + 1 end if path and #dirs > 0 then path = dirs[#dirs] .. "/" .. path end local idx = #results + 1 results[idx] = { line, path=path, lineno=lineno, colno=colno, idx=idx, message=message } end end --cme_log("<"..buffer:get_line(i)..">") --cme_log("{"..ts(errpat_newdir:match((buffer:get_line(i)))).."}") --cme_log(ts(errpat_line:match((buffer:get_line(i))))) end return results end return M
Fix :clist - includes the extra continuation lines.
Fix :clist - includes the extra continuation lines.
Lua
mit
jugglerchris/textadept-vi,jugglerchris/textadept-vi
07ab947817d217fe2e20be3460b2a352245c7405
lua_scripts/create_argvmods_usr_bin_rules.lua
lua_scripts/create_argvmods_usr_bin_rules.lua
-- Copyright (c) 2009 Nokia Corporation. -- Author: Lauri T. Aarnio -- -- Licensed under MIT license -- This script is executed after a new SB2 session has been created, -- to create mapping rules for toolchain components: -- For example, /usr/bin/gcc will be mapped to the toolchain. These rules -- are used for other filesystem operations than exec* -- (for example, when the shell is looking for a program, it must be -- possible to stat() the destination) -- gcc_rule_file_path = session_dir .. "/gcc-conf.lua" default_rule = os.getenv("SBOX_ARGVMODS_USR_BIN_DEFAULT_RULE") function argvmods_to_mapping_rules(prefix) local n for n in pairs(argvmods) do local rule = argvmods[n] -- print("-- rule ", n, " new_filename=", rule.new_filename) local process_now = true if prefix ~= nil then if not sb.isprefix(prefix, n) then process_now = false end end if process_now and not rule.argvmods_processed then rule.argvmods_processed = true local k for k=1,table.maxn(rule.path_prefixes) do if rule.path_prefixes[k] == "/usr/bin/" and rule.new_filename ~= nil then -- this rule maps "n" from /usr/bin to -- another file if sb.path_exists(rule.new_filename) then print(" {path=\"/usr/bin/"..n.."\",") print(" replace_by=\"" .. rule.new_filename.."\"},") else print(" -- WARNING: " .. rule.new_filename .. " does not exist") end end end end end end print("-- Argvmods-to-mapping-rules converter:") print("-- Automatically generated mapping rules. Do not edit:") -- Mode-specific fixed config settings to ruledb: -- -- "enable_cross_gcc_toolchain" (default=true): All special processing -- for the gcc-related tools (gcc,as,ld,..) will be disabled if set -- to false. -- ruletree.attach_ruletree() local modename_in_ruletree = sb.get_forced_mapmode() if modename_in_ruletree == nil then print("-- ERROR: modename_in_ruletree = nil") os.exit(14) end enable_cross_gcc_toolchain = true do_file(session_dir .. "/share/scratchbox2/modes/"..modename_in_ruletree.."/config.lua") ruletree.catalog_set("Conf."..modename_in_ruletree, "enable_cross_gcc_toolchain", ruletree.new_boolean(enable_cross_gcc_toolchain)) if exec_engine_loaded then print("-- Warning: exec engine was already loaded, will load again") end -- load the right argvmods_* file do_file(session_dir .. "/lua_scripts/argvmods_loader.lua") load_argvmods_file() -- Next, the argvmods stuff. print("argvmods_rules_for_usr_bin_"..sbox_cpu.." = {") argvmods_to_mapping_rules(sbox_cpu) if (default_rule ~= nil) then print(" -- default:") print(" ", default_rule) end print("}") local prefixrule1 = " {prefix=\"/usr/bin/"..sbox_cpu.. "\",rules=argvmods_rules_for_usr_bin_"..sbox_cpu.."}," local prefixrule2 = "" if sbox_cpu ~= sbox_uname_machine then print("argvmods_rules_for_usr_bin_"..sbox_uname_machine.." = {") argvmods_to_mapping_rules(sbox_uname_machine) if (default_rule ~= nil) then print(" -- default:") print(" ", default_rule) end print("}") prefixrule2 = " {prefix=\"/usr/bin/"..sbox_uname_machine.. "\",rules=argvmods_rules_for_usr_bin_"..sbox_uname_machine.."}," end print("argvmods_rules_for_usr_bin = {") print(prefixrule1) print(prefixrule2) argvmods_to_mapping_rules(nil) if (default_rule ~= nil) then print(" -- default:") print(" ", default_rule) end print("}") print("-- End of rules created by argvmods-to-mapping-rules converter.")
-- Copyright (c) 2009 Nokia Corporation. -- Author: Lauri T. Aarnio -- -- Licensed under MIT license -- This script is executed after a new SB2 session has been created, -- to create mapping rules for toolchain components: -- For example, /usr/bin/gcc will be mapped to the toolchain. These rules -- are used for other filesystem operations than exec* -- (for example, when the shell is looking for a program, it must be -- possible to stat() the destination) -- gcc_rule_file_path = session_dir .. "/gcc-conf.lua" default_rule = os.getenv("SBOX_ARGVMODS_USR_BIN_DEFAULT_RULE") function argvmods_to_mapping_rules(prefix) local n for n in pairs(argvmods) do local rule = argvmods[n] -- print("-- rule ", n, " new_filename=", rule.new_filename) local process_now = true if prefix ~= nil then if not sb.isprefix(prefix, n) then process_now = false end end if process_now and not rule.argvmods_processed then rule.argvmods_processed = true local k for k=1,table.maxn(rule.path_prefixes) do if rule.path_prefixes[k] == "/usr/bin/" and rule.new_filename ~= nil then -- this rule maps "n" from /usr/bin to -- another file if sb.path_exists(rule.new_filename) then print(" {path=\"/usr/bin/"..n.."\",") print(" replace_by=\"" .. rule.new_filename.."\"},") else print(" -- WARNING: " .. rule.new_filename .. " does not exist") end end end end end end print("-- Argvmods-to-mapping-rules converter:") print("-- Automatically generated mapping rules. Do not edit:") -- Mode-specific fixed config settings to ruledb: -- -- "enable_cross_gcc_toolchain" (default=true): All special processing -- for the gcc-related tools (gcc,as,ld,..) will be disabled if set -- to false. -- ruletree.attach_ruletree() local modename_in_ruletree = sb.get_forced_mapmode() if modename_in_ruletree == nil then print("-- ERROR: modename_in_ruletree = nil") os.exit(14) end enable_cross_gcc_toolchain = true tools = tools_root if (not tools) then tools = "/" end if (tools == "/") then tools_prefix = "" else tools_prefix = tools end do_file(session_dir .. "/share/scratchbox2/modes/"..modename_in_ruletree.."/config.lua") ruletree.catalog_set("Conf."..modename_in_ruletree, "enable_cross_gcc_toolchain", ruletree.new_boolean(enable_cross_gcc_toolchain)) if exec_engine_loaded then print("-- Warning: exec engine was already loaded, will load again") end -- load the right argvmods_* file do_file(session_dir .. "/lua_scripts/argvmods_loader.lua") load_argvmods_file() -- Next, the argvmods stuff. print("argvmods_rules_for_usr_bin_"..sbox_cpu.." = {") argvmods_to_mapping_rules(sbox_cpu) if (default_rule ~= nil) then print(" -- default:") print(" ", default_rule) end print("}") local prefixrule1 = " {prefix=\"/usr/bin/"..sbox_cpu.. "\",rules=argvmods_rules_for_usr_bin_"..sbox_cpu.."}," local prefixrule2 = "" if sbox_cpu ~= sbox_uname_machine then print("argvmods_rules_for_usr_bin_"..sbox_uname_machine.." = {") argvmods_to_mapping_rules(sbox_uname_machine) if (default_rule ~= nil) then print(" -- default:") print(" ", default_rule) end print("}") prefixrule2 = " {prefix=\"/usr/bin/"..sbox_uname_machine.. "\",rules=argvmods_rules_for_usr_bin_"..sbox_uname_machine.."}," end print("argvmods_rules_for_usr_bin = {") print(prefixrule1) print(prefixrule2) argvmods_to_mapping_rules(nil) if (default_rule ~= nil) then print(" -- default:") print(" ", default_rule) end print("}") print("-- End of rules created by argvmods-to-mapping-rules converter.")
Set "tools" and "tools_prefix" in create_argvmods_usr_bin_rules.lua, too
Set "tools" and "tools_prefix" in create_argvmods_usr_bin_rules.lua, too
Lua
lgpl-2.1
ldbox/ldbox,OlegGirko/ldbox,ldbox/ldbox,h113331pp/scratchbox2,h113331pp/scratchbox2,OlegGirko/ldbox,OlegGirko/ldbox,h113331pp/scratchbox2,ldbox/ldbox,h113331pp/scratchbox2,ldbox/ldbox,OlegGirko/ldbox,OlegGirko/ldbox,ldbox/ldbox,ldbox/ldbox,h113331pp/scratchbox2,h113331pp/scratchbox2,OlegGirko/ldbox
a4d6298e4fdf4d4a74a3614713da4c7726a3a9ae
vrp/modules/item_transformer.lua
vrp/modules/item_transformer.lua
-- this module define a generic system to transform (generate, process, convert) items and money to other items or money in a specific area -- each transformer can take things to generate other things, using a unit of work -- units are generated periodically at a specific rate -- reagents => products (reagents can be nothing, as for an harvest transformer) local cfg = require("resources/vrp/cfg/item_transformers") -- api local transformers = {} local function tr_remove_player(tr,player) -- remove player from transforming tr.players[player] = nil -- dereference player vRPclient.removeProgressBar(player,{"vRP:tr:"..tr.name}) vRP.closeMenu(player) end local function tr_add_player(tr,player) -- add player to transforming tr.players[player] = true -- reference player as using transformer vRP.closeMenu(player) vRPclient.setProgressBar(player,{"vRP:tr:"..tr.name,"center",tr.itemtr.action.."...",tr.itemtr.r,tr.itemtr.g,tr.itemtr.b,0}) end local function tr_tick(tr) -- do transformer tick for k,v in pairs(tr.players) do local user_id = vRP.getUserId(k) if user_id ~= nil then -- for each player transforming if tr.units > 0 then -- check units -- check reagents local reagents_ok = true for l,w in pairs(tr.itemtr.reagents) do reagents_ok = reagents_ok and (vRP.getInventoryItemAmount(user_id,l) >= w) end -- check money local money_ok = (vRP.getMoney(user_id) >= tr.itemtr.in_money) -- todo: check if inventory can carry products local inventory_ok = true if money_ok and reagents_ok and inventory_ok then -- do transformation tr.units = tr.units-1 -- sub work unit -- consume reagents if tr.in_money > 0 then vRP.tryPayment(user_id,tr.itemtr.in_money) end for l,w in pairs(tr.itemtr.reagents) do vRP.tryGetInventoryItem(user_id,l,w) end -- produce products if tr.out_money > 0 then vRP.giveMoney(user_id,tr.itemtr.out_money) end for l,w in pairs(tr.itemtr.products) do vRP.giveInventoryItem(user_id,l,w) end end end end end -- display transformation state to all transforming players for k,v in pairs(tr.players) do vRPclient.setProgressBarValue(k,{"vRP:tr:"..tr.name,math.floor(tr.units/tr.itemtr.max_units*100.0)}) if tr.units > 0 then -- display units left vRPclient.setProgressBarText(k,{"vRP:tr:"..tr.name,tr.itemtr.action.."... "..tr.units.."/"..tr.itemtr.max_units}) else vRPclient.setProgressBarText(k,{"vRP:tr:"..tr.name,"empty"}) end end end local function bind_tr_area(player,tr) -- add tr area to client vRP.setArea(player,"vRP:tr:"..tr.name,tr.itemtr.x,tr.itemtr.y,tr.itemtr.z,tr.itemtr.radius,tr.itemtr.height,tr.enter,tr.leave) end local function unbind_tr_area(player,tr) -- remove tr area from client vRP.removeArea(player,"vRP:tr:"..tr.name) end -- add an item transformer -- name: transformer id name -- itemtr: item transformer definition table --- name --- max_units --- units_per_minute --- x,y,z,radius,height (area properties) --- r,g,b (color) --- action --- description --- in_money --- out_money --- reagents: items as idname => amount --- products: items as idname => amount function vRP.setItemTransformer(name,itemtr) vRP.removeItemTransformer(name) -- remove pre-existing transformer local tr = {itemtr=itemtr} tr.name = name transformers[name] = tr -- init transformer tr.units = 0 tr.players = {} -- build menu tr.menu = {name=itemtr.name,css={top="75px",header_color="rgba("..itemtr.r..","..itemtr.g..","..itemtr.b..",0.75)"}} tr.menu[itemtr.action] = {function(player,choice) tr_add_player(tr,player) end, itemtr.description} -- build area tr.enter = function(player,area) vRP.openMenu(player, tr.menu) -- open menu end tr.leave = function(player,area) tr_remove_player(tr, player) end -- bind tr area to all already spawned players for k,v in pairs(vRP.rusers) do local source = vRP.getUserSource(k) if source ~= nil then bind_tr_area(source,tr) end end end -- remove an item transformer function vRP.removeItemTransformer(name) local tr = transformers[name] if tr then for k,v in pairs(tr.players) do -- remove players from transforming tr_remove_player(tr,k) end -- remove tr area from all already spawned players for k,v in pairs(vRP.rusers) do local source = vRP.getUserSource(k) if source ~= nil then unbind_tr_area(source,tr) end end transformers[name] = nil end end -- task: transformers ticks (every 3 seconds) local function transformers_tick() for k,tr in pairs(transformers) do tr_tick(tr) end SetTimeout(3000,transformers_tick) end transformers_tick() -- task: transformers unit regeneration local function transformers_regen() for k,tr in pairs(transformers) do tr.units = tr.units+tr.itemtr.units_per_minute end SetTimeout(60000,transformers_regen) end transformers_regen() -- add transformers areas on player first spawn AddEventHandler("vRP:playerSpawned",function() local user_id = vRP.getUserId(source) if vRP.isFirstSpawn(user_id) then for k,tr in pairs(transformers) do bind_tr_area(source,tr) end end end) -- load item transformers from config file for k,v in pairs(cfg.item_transformers) do vRP.setItemTransformer("cfg:"..k,v) end
-- this module define a generic system to transform (generate, process, convert) items and money to other items or money in a specific area -- each transformer can take things to generate other things, using a unit of work -- units are generated periodically at a specific rate -- reagents => products (reagents can be nothing, as for an harvest transformer) local cfg = require("resources/vrp/cfg/item_transformers") -- api local transformers = {} local function tr_remove_player(tr,player) -- remove player from transforming tr.players[player] = nil -- dereference player vRPclient.removeProgressBar(player,{"vRP:tr:"..tr.name}) vRP.closeMenu(player) end local function tr_add_player(tr,player) -- add player to transforming tr.players[player] = true -- reference player as using transformer vRP.closeMenu(player) vRPclient.setProgressBar(player,{"vRP:tr:"..tr.name,"center",tr.itemtr.action.."...",tr.itemtr.r,tr.itemtr.g,tr.itemtr.b,0}) end local function tr_tick(tr) -- do transformer tick for k,v in pairs(tr.players) do local user_id = vRP.getUserId(k) if user_id ~= nil then -- for each player transforming if tr.units > 0 then -- check units -- check reagents local reagents_ok = true for l,w in pairs(tr.itemtr.reagents) do reagents_ok = reagents_ok and (vRP.getInventoryItemAmount(user_id,l) >= w) end -- check money local money_ok = (vRP.getMoney(user_id) >= tr.itemtr.in_money) -- todo: check if inventory can carry products local inventory_ok = true if money_ok and reagents_ok and inventory_ok then -- do transformation tr.units = tr.units-1 -- sub work unit -- consume reagents if tr.in_money > 0 then vRP.tryPayment(user_id,tr.itemtr.in_money) end for l,w in pairs(tr.itemtr.reagents) do vRP.tryGetInventoryItem(user_id,l,w) end -- produce products if tr.out_money > 0 then vRP.giveMoney(user_id,tr.itemtr.out_money) end for l,w in pairs(tr.itemtr.products) do vRP.giveInventoryItem(user_id,l,w) end end end end end -- display transformation state to all transforming players for k,v in pairs(tr.players) do vRPclient.setProgressBarValue(k,{"vRP:tr:"..tr.name,math.floor(tr.units/tr.itemtr.max_units*100.0)}) if tr.units > 0 then -- display units left vRPclient.setProgressBarText(k,{"vRP:tr:"..tr.name,tr.itemtr.action.."... "..tr.units.."/"..tr.itemtr.max_units}) else vRPclient.setProgressBarText(k,{"vRP:tr:"..tr.name,"empty"}) end end end local function bind_tr_area(player,tr) -- add tr area to client vRP.setArea(player,"vRP:tr:"..tr.name,tr.itemtr.x,tr.itemtr.y,tr.itemtr.z,tr.itemtr.radius,tr.itemtr.height,tr.enter,tr.leave) end local function unbind_tr_area(player,tr) -- remove tr area from client vRP.removeArea(player,"vRP:tr:"..tr.name) end -- add an item transformer -- name: transformer id name -- itemtr: item transformer definition table --- name --- max_units --- units_per_minute --- x,y,z,radius,height (area properties) --- r,g,b (color) --- action --- description --- in_money --- out_money --- reagents: items as idname => amount --- products: items as idname => amount function vRP.setItemTransformer(name,itemtr) vRP.removeItemTransformer(name) -- remove pre-existing transformer local tr = {itemtr=itemtr} tr.name = name transformers[name] = tr -- init transformer tr.units = 0 tr.players = {} -- build menu tr.menu = {name=itemtr.name,css={top="75px",header_color="rgba("..itemtr.r..","..itemtr.g..","..itemtr.b..",0.75)"}} tr.menu[itemtr.action] = {function(player,choice) tr_add_player(tr,player) end, itemtr.description} -- build area tr.enter = function(player,area) vRP.openMenu(player, tr.menu) -- open menu end tr.leave = function(player,area) tr_remove_player(tr, player) end -- bind tr area to all already spawned players for k,v in pairs(vRP.rusers) do local source = vRP.getUserSource(k) if source ~= nil then bind_tr_area(source,tr) end end end -- remove an item transformer function vRP.removeItemTransformer(name) local tr = transformers[name] if tr then for k,v in pairs(tr.players) do -- remove players from transforming tr_remove_player(tr,k) end -- remove tr area from all already spawned players for k,v in pairs(vRP.rusers) do local source = vRP.getUserSource(k) if source ~= nil then unbind_tr_area(source,tr) end end transformers[name] = nil end end -- task: transformers ticks (every 3 seconds) local function transformers_tick() for k,tr in pairs(transformers) do tr_tick(tr) end SetTimeout(3000,transformers_tick) end transformers_tick() -- task: transformers unit regeneration local function transformers_regen() for k,tr in pairs(transformers) do tr.units = tr.units+tr.itemtr.units_per_minute if tr.units >= tr.itemtr.max_units then tr.units = tr.itemtr.max_units end end SetTimeout(60000,transformers_regen) end transformers_regen() -- add transformers areas on player first spawn AddEventHandler("vRP:playerSpawned",function() local user_id = vRP.getUserId(source) if vRP.isFirstSpawn(user_id) then for k,tr in pairs(transformers) do bind_tr_area(source,tr) end end end) -- load item transformers from config file for k,v in pairs(cfg.item_transformers) do vRP.setItemTransformer("cfg:"..k,v) end
Fix item transformer progress bar issue
Fix item transformer progress bar issue
Lua
mit
ENDrain/vRP-plusplus,ENDrain/vRP-plusplus,ImagicTheCat/vRP,ImagicTheCat/vRP,ENDrain/vRP-plusplus
991aea195e8d8daefb74616cf4fb2bce961f4ed1
src/plugins/finalcutpro/timeline/zoomtoselection.lua
src/plugins/finalcutpro/timeline/zoomtoselection.lua
--- === plugins.finalcutpro.timeline.zoomtoselection === --- --- Zoom the Timeline to fit the currently-selected clips. local require = require local fcp = require("cp.apple.finalcutpro") local mod = {} --- plugins.finalcutpro.timeline.zoomtoselection.SELECTION_BUFFER -> number --- Constant --- The number of pixels of buffer space to allow the selection zoom to fit. mod.SELECTION_BUFFER = 70 --- plugins.finalcutpro.timeline.zoomtoselection.DEFAULT_SHIFT -> number --- Constant --- Default Shift. mod.DEFAULT_SHIFT = 1.0 --- plugins.finalcutpro.timeline.zoomtoselection.MIN_SHIFT -> number --- Constant --- Minimum Shift. mod.MIN_SHIFT = 0.025 -- plugins.finalcutpro.timeline.zoomtoselection._selectedWidth(minClip, maxClip) -> number -- Function -- Selected Width -- -- Parameters: -- * minClip - Minimum Clip Width as number -- * maxClip - Maximum Clip Width as number -- -- Returns: -- * Selected Width as number function mod._selectedWidth(minClip, maxClip) return maxClip:position().x + maxClip:size().w - minClip:frame().x + mod.SELECTION_BUFFER*2 end -- plugins.finalcutpro.timeline.zoomtoselection._zoomToFit(minClip, maxClip, shift) -> number -- Function -- Zoom to fit. -- -- Parameters: -- * minClip - Minimum Clip Width as number -- * maxClip - Maximum Clip Width as number -- * shift - Shift as number -- -- Returns: -- * Selected Width as number function mod._zoomToFit(minClip, maxClip, shift) local zoomAmount = mod.zoomAmount local selectedWidth = mod._selectedWidth(minClip, maxClip) local viewFrame = mod.contents:viewFrame() local dir = selectedWidth < viewFrame.w and 1 or -1 if shift < mod.MIN_SHIFT then if dir == -1 then -------------------------------------------------------------------------------- -- We need to zoom back out: -------------------------------------------------------------------------------- shift = mod.MIN_SHIFT else -------------------------------------------------------------------------------- -- Too small - bail. -- Move to the first clip position: -------------------------------------------------------------------------------- mod.contents:shiftHorizontalToX(minClip:position().x - mod.SELECTION_BUFFER) mod.appearance:hide() return end end -------------------------------------------------------------------------------- -- Show the appearance popup: -------------------------------------------------------------------------------- mod.appearance:show() -------------------------------------------------------------------------------- -- Zoom in until it fits: -------------------------------------------------------------------------------- while dir == 1 and selectedWidth < viewFrame.w or dir == -1 and selectedWidth > viewFrame.w do zoomAmount:value(zoomAmount:value() + shift * dir) selectedWidth = mod._selectedWidth(minClip, maxClip) viewFrame = mod.contents:viewFrame() end -------------------------------------------------------------------------------- -- Keep zooming, with better precision: -------------------------------------------------------------------------------- mod._zoomToFit(minClip, maxClip, shift/2) end --- plugins.finalcutpro.timeline.zoomtoselection.zoomToSelection() -> boolean --- Method --- Zooms the view to fit the currently-selected clips. --- --- Parameters: --- * None --- --- Returns: --- * `true` if there is selected content in the timeline and zooming was successful. function mod.zoomToSelection() local selectedClips = mod.contents:selectedClipsUI() if not selectedClips or #selectedClips == 0 then return false end local minClip, maxClip local rangeSelection = mod.contents:rangeSelectionUI() if rangeSelection then minClip = rangeSelection maxClip = rangeSelection else -------------------------------------------------------------------------------- -- Find the min/max clip and 'x' value for selected clips: -------------------------------------------------------------------------------- local minX, maxX for _,clip in ipairs(selectedClips) do local frame = clip:frame() if minX == nil or minX > frame.x then minX = frame.x minClip = clip end if maxX == nil or maxX < (frame.x + frame.w) then maxX = frame.x + frame.w maxClip = clip end end end -------------------------------------------------------------------------------- -- Zoom in until it fits, getting more precise as we go: -------------------------------------------------------------------------------- mod._zoomToFit(minClip, maxClip, mod.DEFAULT_SHIFT) return true end local plugin = { id = "finalcutpro.timeline.zoomtoselection", group = "finalcutpro", dependencies = { ["finalcutpro.commands"] = "fcpxCmds", } } function plugin.init(deps) -------------------------------------------------------------------------------- -- Only load plugin if Final Cut Pro is supported: -------------------------------------------------------------------------------- if not fcp:isSupported() then return end -------------------------------------------------------------------------------- -- Initialise the module: -------------------------------------------------------------------------------- mod.appearance = fcp.timeline.toolbar.appearance mod.zoomAmount = mod.appearance.zoomAmount mod.contents = fcp.timeline.contents -------------------------------------------------------------------------------- -- Setup Commands: -------------------------------------------------------------------------------- deps.fcpxCmds :add("cpZoomToSelection") :activatedBy():option():shift("z") :whenActivated(mod.zoomToSelection) return mod end return plugin
--- === plugins.finalcutpro.timeline.zoomtoselection === --- --- Zoom the Timeline to fit the currently-selected clips. local require = require local fcp = require "cp.apple.finalcutpro" local mod = {} -- SELECTION_BUFFER -> number -- Constant -- The number of pixels of buffer space to allow the selection zoom to fit. local SELECTION_BUFFER = 70 -- DEFAULT_SHIFT -> number -- Constant -- Default Shift. local DEFAULT_SHIFT = 1.0 -- MIN_SHIFT -> number -- Constant -- Minimum Shift. local MIN_SHIFT = 0.025 -- getSelectedWidth(minClip, maxClip) -> number -- Function -- Gets the Selected Width. -- -- Parameters: -- * minClip - Minimum Clip Width as number -- * maxClip - Maximum Clip Width as number -- -- Returns: -- * Selected Width as number local function getSelectedWidth(minClip, maxClip) return maxClip:attributeValue("AXPosition").x + maxClip:attributeValue("AXSize").w - minClip:attributeValue("AXFrame").x + SELECTION_BUFFER*2 end -- zoomToFit(minClip, maxClip, shift) -> number -- Function -- Zoom to fit. -- -- Parameters: -- * minClip - Minimum Clip Width as number -- * maxClip - Maximum Clip Width as number -- * shift - Shift as number -- -- Returns: -- * Selected Width as number local function zoomToFit(minClip, maxClip, shift) local contents = fcp.timeline.contents local appearance = fcp.timeline.toolbar.appearance local zoomAmount = appearance.zoomAmount local selectedWidth = getSelectedWidth(minClip, maxClip) local viewFrame = contents:viewFrame() local dir = selectedWidth < viewFrame.w and 1 or -1 if shift < MIN_SHIFT then if dir == -1 then -------------------------------------------------------------------------------- -- We need to zoom back out: -------------------------------------------------------------------------------- shift = MIN_SHIFT else -------------------------------------------------------------------------------- -- Too small - bail. -- Move to the first clip position: -------------------------------------------------------------------------------- contents:shiftHorizontalToX(minClip:attributeValue("AXPosition").x - SELECTION_BUFFER) appearance:hide() return end end -------------------------------------------------------------------------------- -- Show the appearance popup: -------------------------------------------------------------------------------- appearance:show() -------------------------------------------------------------------------------- -- Zoom in until it fits: -------------------------------------------------------------------------------- while dir == 1 and selectedWidth < viewFrame.w or dir == -1 and selectedWidth > viewFrame.w do zoomAmount:value(zoomAmount:value() + shift * dir) selectedWidth = getSelectedWidth(minClip, maxClip) viewFrame = contents:viewFrame() end -------------------------------------------------------------------------------- -- Keep zooming, with better precision: -------------------------------------------------------------------------------- zoomToFit(minClip, maxClip, shift/2) end --- plugins.finalcutpro.timeline.zoomtoselection.zoomToSelection() -> boolean --- Method --- Zooms the view to fit the currently-selected clips. --- --- Parameters: --- * None --- --- Returns: --- * `true` if there is selected content in the timeline and zooming was successful. function mod.zoomToSelection() local contents = fcp.timeline.contents local selectedClips = contents:selectedClipsUI() if not selectedClips or #selectedClips == 0 then return false end local minClip, maxClip local rangeSelection = contents:rangeSelectionUI() if rangeSelection then minClip = rangeSelection maxClip = rangeSelection else -------------------------------------------------------------------------------- -- Find the min/max clip and 'x' value for selected clips: -------------------------------------------------------------------------------- local minX, maxX for _,clip in ipairs(selectedClips) do local frame = clip:attributeValue("AXFrame") if minX == nil or minX > frame.x then minX = frame.x minClip = clip end if maxX == nil or maxX < (frame.x + frame.w) then maxX = frame.x + frame.w maxClip = clip end end end -------------------------------------------------------------------------------- -- Zoom in until it fits, getting more precise as we go: -------------------------------------------------------------------------------- zoomToFit(minClip, maxClip, DEFAULT_SHIFT) return true end local plugin = { id = "finalcutpro.timeline.zoomtoselection", group = "finalcutpro", dependencies = { ["finalcutpro.commands"] = "fcpxCmds", } } function plugin.init(deps) -------------------------------------------------------------------------------- -- Only load plugin if Final Cut Pro is supported: -------------------------------------------------------------------------------- if not fcp:isSupported() then return end -------------------------------------------------------------------------------- -- Setup Commands: -------------------------------------------------------------------------------- deps.fcpxCmds :add("cpZoomToSelection") :activatedBy():option():shift("z") :whenActivated(mod.zoomToSelection) return mod end return plugin
Fixed AX bugs in "Zoom to Selection" action
Fixed AX bugs in "Zoom to Selection" action - Closes #2606
Lua
mit
CommandPost/CommandPost,CommandPost/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost,fcpxhacks/fcpxhacks
9eea9234404eff39061e56e75c9a62a3a2b57fcb
states/game.lua
states/game.lua
local Scene = require 'entities.scene' local Dynamo = require 'entities.scenes.dynamo' local Sprite = require 'entities.sprite' local game = {} function game:init() self.dynamo = Dynamo:new() self.scene = Scene:new() self.catalogs = { art = require 'catalogs.art', } self.isoSprite = love.graphics.newImage(self.catalogs.art.iso_tile) self.grid = require 'data.ship' self.gridX = 300 self.gridY = 300 self.gridWidth = #self.grid[1] -- tiles self.gridHeight = #self.grid -- tiles self.tileWidth = self.isoSprite:getWidth() -- pixels self.tileHeight = self.isoSprite:getHeight() -- pixels self.tileDepth = self.tileHeight / 2 -- Convert row-major to column-major local columnMajorGrid = {} for x = 1, self.gridWidth do columnMajorGrid[x] = {} for y = 1, self.gridHeight do columnMajorGrid[x][y] = self.grid[y][x] end end self.grid = columnMajorGrid local function screenToGrid(sx, sy) local gx = ((sx / self.tileWidth / 2) + (sy / self.tileDepth / 2)) / 2 + 1 local gy = ((sy / self.tileDepth / 2) - (sx / self.tileWidth / 2)) / 2 + 1 return Lume.round(gx), Lume.round(gy) -- local a = 0.5 -- local b = self.tileDepth -- local x = math.floor((x-y*a)/b) -- local y = math.floor((x+y*a)/b) -- return x, y end local function gridToScreen(gx, gy) -- local tx = game.gridX + ((x-y) * (game.tileWidth / 2)) -- local ty = game.gridY + ((x+y) * (game.tileDepth / 2)) - (game.tileDepth * (game.tileHeight / 2)) local x = (gx - gy) * game.tileWidth / 2 local y = (gx + gy) * game.tileDepth / 2 return x, y end self.gridScreenWidth = self.gridWidth * self.tileWidth self.gridScreenHeight = self.gridHeight * self.tileDepth self.scene:add{ hoverX = nil, hoverY = nil, update = function(self, dt) local mx, my = love.mouse.getPosition() mx = game.gridX - mx my = game.gridY - my self.hoverX, self.hoverY = screenToGrid(-mx, -my) end, draw = function(self) love.graphics.print(self.hoverX .. ', ' .. self.hoverY, 10, 10) love.graphics.push() love.graphics.translate(game.gridX, game.gridY) for x = 1, game.gridWidth do for y = 1, game.gridHeight do if x == self.hoverX and y == self.hoverY then love.graphics.setColor(255, 0, 0) else love.graphics.setColor(255, 255, 255) end -- Calculate isometric tile positions -- @TODO gridX and gridY are actually nowhere near the center of the grid tx, ty = gridToScreen(x, y) local cellValue = game.grid[x][y] if cellValue == 1 then love.graphics.setFont(Fonts.monospace[12]) love.graphics.print(x .. ',' .. y, tx, ty - 15) love.graphics.draw(game.isoSprite, tx, ty) end -- @Debug love.graphics.rectangle('line', 0, 0, game.gridScreenWidth, game.gridScreenHeight) end end love.graphics.pop() end, } end function game:enter() end function game:update(dt) self.scene:update(dt) self.dynamo:update(dt) end function game:keypressed(key, code) self.scene:keypressed(key, code) self.dynamo:keypressed(key, code) end function game:keyreleased(key, code) self.scene:keyreleased(key, code) self.dynamo:keyreleased(key, code) end function game:mousepressed(x, y, mbutton) self.scene:mousepressed(x, y, mbutton) self.dynamo:mousepressed(x, y, mbutton) end function game:mousereleased(x, y, mbutton) self.scene:mousereleased(x, y, mbutton) self.dynamo:mousereleased(x, y, mbutton) end function game:mousemoved(x, y, dx, dy, istouch) self.scene:mousemoved(x, y, dx, dy, istouch) self.dynamo:mousemoved(x, y, dx, dy, istouch) end function game:draw() self.scene:draw() self.dynamo:draw() end return game
local Scene = require 'entities.scene' local Dynamo = require 'entities.scenes.dynamo' local Sprite = require 'entities.sprite' local game = {} function game:init() self.dynamo = Dynamo:new() self.scene = Scene:new() self.catalogs = { art = require 'catalogs.art', } self.isoSprite = love.graphics.newImage(self.catalogs.art.iso_tile) self.grid = require 'data.ship' self.gridX = 300 self.gridY = 300 self.gridWidth = #self.grid[1] -- tiles self.gridHeight = #self.grid -- tiles self.tileWidth = self.isoSprite:getWidth() -- pixels self.tileHeight = self.isoSprite:getHeight() -- pixels self.tileDepth = self.tileHeight / 2 -- Convert row-major to column-major local columnMajorGrid = {} for x = 1, self.gridWidth do columnMajorGrid[x] = {} for y = 1, self.gridHeight do columnMajorGrid[x][y] = self.grid[y][x] end end self.grid = columnMajorGrid local function screenToGrid(sx, sy) local gx = ((sx / (self.tileWidth / 2)) + (sy / (self.tileDepth / 2))) / 2 + 1 local gy = ((sy / (self.tileDepth / 2)) - (sx / (self.tileWidth / 2))) / 2 + 1 return Lume.round(gx), Lume.round(gy) end local function gridToScreen(gx, gy) local x = (gx - gy) * game.tileWidth / 2 local y = (gx + gy) * game.tileDepth / 2 return x, y end self.gridScreenWidth = self.gridWidth * self.tileWidth self.gridScreenHeight = self.gridHeight * self.tileDepth self.scene:add{ hoverX = nil, hoverY = nil, update = function(self, dt) local mx, my = love.mouse.getPosition() mx = game.gridX - mx my = game.gridY - my mx = mx + game.tileWidth / 2 my = my + game.tileHeight self.hoverX, self.hoverY = screenToGrid(-mx, -my) end, draw = function(self) love.graphics.print(self.hoverX .. ', ' .. self.hoverY, 10, 10) love.graphics.push() love.graphics.translate(game.gridX, game.gridY) for x = 1, game.gridWidth do for y = 1, game.gridHeight do if x == self.hoverX and y == self.hoverY then love.graphics.setColor(255, 0, 0) else love.graphics.setColor(255, 255, 255) end -- Calculate isometric tile positions -- @TODO gridX and gridY are actually nowhere near the center of the grid tx, ty = gridToScreen(x, y) local cellValue = game.grid[x][y] if cellValue == 1 then love.graphics.setFont(Fonts.monospace[12]) love.graphics.print(x .. ',' .. y, tx, ty - 15) love.graphics.draw(game.isoSprite, tx, ty) end -- @Debug love.graphics.rectangle('line', 0, 0, game.gridScreenWidth, game.gridScreenHeight) end end love.graphics.pop() end, } end function game:enter() end function game:update(dt) self.scene:update(dt) self.dynamo:update(dt) end function game:keypressed(key, code) self.scene:keypressed(key, code) self.dynamo:keypressed(key, code) end function game:keyreleased(key, code) self.scene:keyreleased(key, code) self.dynamo:keyreleased(key, code) end function game:mousepressed(x, y, mbutton) self.scene:mousepressed(x, y, mbutton) self.dynamo:mousepressed(x, y, mbutton) end function game:mousereleased(x, y, mbutton) self.scene:mousereleased(x, y, mbutton) self.dynamo:mousereleased(x, y, mbutton) end function game:mousemoved(x, y, dx, dy, istouch) self.scene:mousemoved(x, y, dx, dy, istouch) self.dynamo:mousemoved(x, y, dx, dy, istouch) end function game:draw() self.scene:draw() self.dynamo:draw() end return game
Fix bad hovering math
Fix bad hovering math
Lua
mit
Nuthen/ludum-dare-39
5fc937a0504b82d0781a60614a51d2a9315f4d27
xmake/modules/lib/detect/find_tool.lua
xmake/modules/lib/detect/find_tool.lua
--!A cross-platform build utility based on Lua -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2017, TBOOX Open Source Group. -- -- @author ruki -- @file find_tool.lua -- -- imports import("lib.detect.find_program") import("lib.detect.find_programver") import("lib.detect.find_toolname") -- find tool from modules function _find_from_modules(name, opt) -- attempt to import "detect.tools.find_xxx" local find_tool = import("detect.tools.find_" .. name, {try = true}) if find_tool then local program, version, toolname = find_tool(opt) return {name = toolname or name, program = program, version = version} end end -- find tool -- -- @param name the tool name -- @param opt the options, .e.g {program = "xcrun -sdk macosx clang", pathes = {"/usr/bin"}, check = function (tool) os.run("%s -h", tool) end, version = true} -- -- @return {name = "", program = "", version = ""} or nil -- -- @code -- -- local tool = find_tool("clang") -- local tool = find_tool("clang", {program = "xcrun -sdk macosx clang"}) -- local tool = find_tool("clang", {pathes = {"/usr/bin", "/usr/local/bin"}}) -- local tool = find_tool("clang", {check = "--help"}) -- simple check command: ccache --help -- local tool = find_tool("clang", {check = function (tool) os.run("%s -h", tool) end}) -- local tool = find_tool("clang", {pathes = {"$(env PATH)", "$(reg HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug;Debugger)"}}) -- local tool = find_tool("clang", {pathes = {"$(env PATH)", function () return "/usr/bin"end}}) -- local tool = find_tool("ccache", {version = true}) -- -- @endcode -- function main(name, opt) -- init options opt = opt or {} -- find tool name local toolname = find_toolname(name or opt.program) if not toolname then return end -- init program opt.program = opt.program or name -- attempt to find tool from modules first local tool = _find_from_modules(toolname, opt) if tool then return tool end -- find tool local program = find_program(opt.program, opt.pathes, opt.check) if not program then return end -- find tool version local version = nil if program and opt.version then version = find_programver(program) end -- ok? return {name = toolname, program = program, version = version} end
--!A cross-platform build utility based on Lua -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2017, TBOOX Open Source Group. -- -- @author ruki -- @file find_tool.lua -- -- imports import("lib.detect.find_program") import("lib.detect.find_programver") import("lib.detect.find_toolname") -- find tool from modules function _find_from_modules(name, opt) -- attempt to import "detect.tools.find_xxx" local find_tool = import("detect.tools.find_" .. name, {try = true}) if find_tool then local program, version, toolname = find_tool(opt) if program then return {name = toolname or name, program = program, version = version} end end end -- find tool -- -- @param name the tool name -- @param opt the options, .e.g {program = "xcrun -sdk macosx clang", pathes = {"/usr/bin"}, check = function (tool) os.run("%s -h", tool) end, version = true} -- -- @return {name = "", program = "", version = ""} or nil -- -- @code -- -- local tool = find_tool("clang") -- local tool = find_tool("clang", {program = "xcrun -sdk macosx clang"}) -- local tool = find_tool("clang", {pathes = {"/usr/bin", "/usr/local/bin"}}) -- local tool = find_tool("clang", {check = "--help"}) -- simple check command: ccache --help -- local tool = find_tool("clang", {check = function (tool) os.run("%s -h", tool) end}) -- local tool = find_tool("clang", {pathes = {"$(env PATH)", "$(reg HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug;Debugger)"}}) -- local tool = find_tool("clang", {pathes = {"$(env PATH)", function () return "/usr/bin"end}}) -- local tool = find_tool("ccache", {version = true}) -- -- @endcode -- function main(name, opt) -- init options opt = opt or {} -- find tool name local toolname = find_toolname(name or opt.program) if not toolname then return end -- init program opt.program = opt.program or name -- attempt to find tool from modules first local tool = _find_from_modules(toolname, opt) if tool then return tool end -- find tool local program = find_program(opt.program, opt.pathes, opt.check) if not program then return end -- find tool version local version = nil if program and opt.version then version = find_programver(program) end -- ok? return {name = toolname, program = program, version = version} end
continue to fix find_tool bug
continue to fix find_tool bug
Lua
apache-2.0
tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,tboox/xmake
3c4ba2190506e46788c16f3e65f78307551dc780
src/core.lua
src/core.lua
-- return truthy if we're in a coroutine local function in_coroutine() local current_routine, main = coroutine.running() -- need check to the main variable for 5.2, it's nil for 5.1 return current_routine and (main == nil or main == false) end local busted = { root_context = { type = "describe", description = "global" }, options = {}, __call = function(self) self.output = self.options.output --run test local function test(description, callback) local debug_info = debug.getinfo(callback) local info = { source = debug_info.source, short_src = debug_info.short_src, linedefined = debug_info.linedefined, } local stack_trace = "" local function err_handler(err) stack_trace = debug.traceback("", 4) return err end local status, err = xpcall(callback, err_handler) local test_status = {} if not status then test_status = { type = "failure", description = description, info = info, trace = stack_trace, err = err } else test_status = { type = "success", description = description, info = info } end if not self.options.defer_print then self.output.currently_executing(test_status, self.options) end return test_status end --run test case local function run_context(context) local match = false if self.options.tags and #self.options.tags > 0 then for i,t in ipairs(self.options.tags) do if context.description:find("#"..t) then match = true end end else match = true end local status = { description = context.description, type = "description", run = match } if context.setup then context.setup() end for i,v in ipairs(context) do if context.before_each then context.before_each() end if v.type == "test" then table.insert(status, test(v.description, v.callback)) elseif v.type == "describe" then table.insert(status, coroutine.create(function() run_context(v) end)) elseif v.type == "pending" then local pending_test_status = { type = "pending", description = v.description, info = v.info } v.callback(pending_test_status) table.insert(status, pending_test_status) end if context.after_each then context.after_each() end end if context.teardown then context.teardown() end if in_coroutine() then coroutine.yield(status) else return true, status end end local play_sound = function(failures) math.randomseed(os.time()) if self.options.failure_messages and #self.options.failure_messages > 0 and self.options.success_messages and #self.options.success_messages > 0 then if failures and failures > 0 then io.popen("say \""..failure_messages[math.random(1, #failure_messages)]:format(failures).."\"") else io.popen("say \""..success_messages[math.random(1, #success_messages)].."\"") end end end local ms = os.clock() if not self.options.defer_print then print(self.output.header(self.root_context)) end --fire off tests, return status list local function get_statuses(done, list) local ret = {} for i,v in pairs(list) do local vtype = type(v) if vtype == "thread" then local res = get_statuses(coroutine.resume(v)) for key,value in pairs(res) do table.insert(ret, value) end elseif vtype == "table" then table.insert(ret, v) end end return ret end local statuses = get_statuses(run_context(self.root_context)) --final run time ms = os.clock() - ms if self.options.defer_print then print(self.output.header(self.root_context)) end local status_string = self.output.formatted_status(statuses, self.options, ms) if self.options.sound then play_sound(failures) end return status_string end } return setmetatable(busted, busted)
-- return truthy if we're in a coroutine local function in_coroutine() local current_routine, main = coroutine.running() -- need check to the main variable for 5.2, it's nil for 5.1 return current_routine and (main == nil or main == false) end local busted = { root_context = { type = "describe", description = "global" }, options = {}, __call = function(self) self.output = self.options.output --run test local function test(description, callback) local debug_info = debug.getinfo(callback) local info = { source = debug_info.source, short_src = debug_info.short_src, linedefined = debug_info.linedefined, } local stack_trace = "" local function err_handler(err) stack_trace = debug.traceback("", 4) return err end local status, err = xpcall(callback, err_handler) local test_status = {} if not status then test_status = { type = "failure", description = description, info = info, trace = stack_trace, err = err } else test_status = { type = "success", description = description, info = info } end if not self.options.defer_print then self.output.currently_executing(test_status, self.options) end return test_status end -- run setup/teardown local function run_setup(context, stype) local errResult = nil if context[stype] then errResult = test("Failed running test initializer '"..stype.."'", context[stype]) if errResult.type == "success" then errResult = nil end end return errResult end --run test case local function run_context(context) local match = false if self.options.tags and #self.options.tags > 0 then for i,t in ipairs(self.options.tags) do if context.description:find("#"..t) then match = true end end else match = true end local status = { description = context.description, type = "description", run = match } local setupstatus = nil setupstatus = run_setup(context, "setup") if not setupstatus then for i,v in ipairs(context) do setupstatus = run_setup(context, "before_each") if setupstatus then break end if v.type == "test" then table.insert(status, test(v.description, v.callback)) elseif v.type == "describe" then table.insert(status, coroutine.create(function() run_context(v) end)) elseif v.type == "pending" then local pending_test_status = { type = "pending", description = v.description, info = v.info } v.callback(pending_test_status) table.insert(status, pending_test_status) end setupstatus = run_setup(context, "after_each") if setupstatus then break end end end if not setupstatus then setupstatus = run_setup(context, "teardown") end if setupstatus then table.insert(status, setupstatus) end if in_coroutine() then coroutine.yield(status) else return true, status end end local play_sound = function(failures) math.randomseed(os.time()) if self.options.failure_messages and #self.options.failure_messages > 0 and self.options.success_messages and #self.options.success_messages > 0 then if failures and failures > 0 then io.popen("say \""..failure_messages[math.random(1, #failure_messages)]:format(failures).."\"") else io.popen("say \""..success_messages[math.random(1, #success_messages)].."\"") end end end local ms = os.clock() if not self.options.defer_print then print(self.output.header(self.root_context)) end --fire off tests, return status list local function get_statuses(done, list) local ret = {} for i,v in pairs(list) do local vtype = type(v) if vtype == "thread" then local res = get_statuses(coroutine.resume(v)) for key,value in pairs(res) do table.insert(ret, value) end elseif vtype == "table" then table.insert(ret, v) end end return ret end local statuses = get_statuses(run_context(self.root_context)) --final run time ms = os.clock() - ms if self.options.defer_print then print(self.output.header(self.root_context)) end local status_string = self.output.formatted_status(statuses, self.options, ms) if self.options.sound then play_sound(failures) end return status_string end } return setmetatable(busted, busted)
fix for the setup/teardown errors to be reported nicely
fix for the setup/teardown errors to be reported nicely
Lua
mit
nehz/busted,istr/busted,sobrinho/busted,ryanplusplus/busted,mpeterv/busted,o-lim/busted,leafo/busted,azukiapp/busted,xyliuke/busted,DorianGray/busted,Olivine-Labs/busted
0a4fb89239864dbf9e76ba4f5f28967706cd01aa
frontend/apps/reader/modules/readerconfig.lua
frontend/apps/reader/modules/readerconfig.lua
local ConfigDialog = require("ui/widget/configdialog") local Device = require("device") local Event = require("ui/event") local Geom = require("ui/geometry") local InputContainer = require("ui/widget/container/inputcontainer") local UIManager = require("ui/uimanager") local _ = require("gettext") local ReaderConfig = InputContainer:new{ last_panel_index = 1, } function ReaderConfig:init() if not self.dimen then self.dimen = Geom:new{} end if Device:hasKeyboard() then self.key_events = { ShowConfigMenu = { { "AA" }, doc = "show config dialog" }, } end if Device:isTouchDevice() then self:initGesListener() end self.activation_menu = G_reader_settings:readSetting("activate_menu") if self.activation_menu == nil then self.activation_menu = "swipe_tap" end end function ReaderConfig:initGesListener() self.ui:registerTouchZones({ { id = "readerconfigmenu_tap", ges = "tap", screen_zone = { ratio_x = DTAP_ZONE_CONFIG.x, ratio_y = DTAP_ZONE_CONFIG.y, ratio_w = DTAP_ZONE_CONFIG.w, ratio_h = DTAP_ZONE_CONFIG.h, }, overrides = { 'tap_forward', 'tap_backward', }, handler = function() return self:onTapShowConfigMenu() end, }, { id = "readerconfigmenu_swipe", ges = "swipe", screen_zone = { ratio_x = DTAP_ZONE_CONFIG.x, ratio_y = DTAP_ZONE_CONFIG.y, ratio_w = DTAP_ZONE_CONFIG.w, ratio_h = DTAP_ZONE_CONFIG.h, }, overrides = { "rolling_swipe", "paging_swipe", }, handler = function(ges) return self:onSwipeShowConfigMenu(ges) end, }, { id = "readerconfigmenu_pan", ges = "pan", screen_zone = { ratio_x = DTAP_ZONE_CONFIG.x, ratio_y = DTAP_ZONE_CONFIG.y, ratio_w = DTAP_ZONE_CONFIG.w, ratio_h = DTAP_ZONE_CONFIG.h, }, overrides = { "rolling_pan", "paging_pan", }, handler = function(ges) return self:onSwipeShowConfigMenu(ges) end, }, }) end function ReaderConfig:onShowConfigMenu() self.config_dialog = ConfigDialog:new{ dimen = self.dimen:copy(), ui = self.ui, configurable = self.configurable, config_options = self.options, is_always_active = true, close_callback = function() self:onCloseCallback() end, } self.ui:handleEvent(Event:new("DisableHinting")) -- show last used panel when opening config dialog self.config_dialog:onShowConfigPanel(self.last_panel_index) UIManager:show(self.config_dialog) return true end function ReaderConfig:onTapShowConfigMenu() if self.activation_menu ~= "swipe" then self:onShowConfigMenu() return true end end function ReaderConfig:onSwipeShowConfigMenu(ges) if self.activation_menu ~= "tap" and ges.direction == "north" then self:onShowConfigMenu() return true end end function ReaderConfig:onSetDimensions(dimen) if Device:isTouchDevice() then self:initGesListener() end -- since we cannot redraw config_dialog with new size, we close -- the old one on screen size change if self.config_dialog then self.config_dialog:closeDialog() end end function ReaderConfig:onCloseCallback() self.last_panel_index = self.config_dialog.panel_index self.config_dialog = nil self.ui:handleEvent(Event:new("RestoreHinting")) end -- event handler for readercropping function ReaderConfig:onCloseConfigMenu() if self.config_dialog then self.config_dialog:closeDialog() end end function ReaderConfig:onReadSettings(config) self.configurable:loadSettings(config, self.options.prefix.."_") self.last_panel_index = config:readSetting("config_panel_index") or 1 end function ReaderConfig:onSaveSettings() self.configurable:saveSettings(self.ui.doc_settings, self.options.prefix.."_") self.ui.doc_settings:saveSetting("config_panel_index", self.last_panel_index) end return ReaderConfig
local ConfigDialog = require("ui/widget/configdialog") local Device = require("device") local Event = require("ui/event") local Geom = require("ui/geometry") local InputContainer = require("ui/widget/container/inputcontainer") local UIManager = require("ui/uimanager") local _ = require("gettext") local ReaderConfig = InputContainer:new{ last_panel_index = 1, } function ReaderConfig:init() if not self.dimen then self.dimen = Geom:new{} end if Device:hasKeyboard() then self.key_events = { ShowConfigMenu = { { "AA" }, doc = "show config dialog" }, } end if Device:isTouchDevice() then self:initGesListener() end self.activation_menu = G_reader_settings:readSetting("activate_menu") if self.activation_menu == nil then self.activation_menu = "swipe_tap" end end function ReaderConfig:initGesListener() self.ui:registerTouchZones({ { id = "readerconfigmenu_tap", ges = "tap", screen_zone = { ratio_x = DTAP_ZONE_CONFIG.x, ratio_y = DTAP_ZONE_CONFIG.y, ratio_w = DTAP_ZONE_CONFIG.w, ratio_h = DTAP_ZONE_CONFIG.h, }, overrides = { 'tap_forward', 'tap_backward', }, handler = function() return self:onTapShowConfigMenu() end, }, { id = "readerconfigmenu_swipe", ges = "swipe", screen_zone = { ratio_x = DTAP_ZONE_CONFIG.x, ratio_y = DTAP_ZONE_CONFIG.y, ratio_w = DTAP_ZONE_CONFIG.w, ratio_h = DTAP_ZONE_CONFIG.h, }, overrides = { "rolling_swipe", "paging_swipe", }, handler = function(ges) return self:onSwipeShowConfigMenu(ges) end, }, { id = "readerconfigmenu_pan", ges = "pan", screen_zone = { ratio_x = DTAP_ZONE_CONFIG.x, ratio_y = DTAP_ZONE_CONFIG.y, ratio_w = DTAP_ZONE_CONFIG.w, ratio_h = DTAP_ZONE_CONFIG.h, }, overrides = { "rolling_pan", "paging_pan", }, handler = function(ges) return self:onSwipeShowConfigMenu(ges) end, }, }) end function ReaderConfig:onShowConfigMenu() self.config_dialog = ConfigDialog:new{ dimen = self.dimen:copy(), ui = self.ui, configurable = self.configurable, config_options = self.options, is_always_active = true, close_callback = function() self:onCloseCallback() end, } self.ui:handleEvent(Event:new("DisableHinting")) -- show last used panel when opening config dialog self.config_dialog:onShowConfigPanel(self.last_panel_index) UIManager:show(self.config_dialog) return true end function ReaderConfig:onTapShowConfigMenu() if self.activation_menu ~= "swipe" then self:onShowConfigMenu() return true end end function ReaderConfig:onSwipeShowConfigMenu(ges) if self.activation_menu ~= "tap" and ges.direction == "north" then self:onShowConfigMenu() return true end end function ReaderConfig:onSetDimensions(dimen) if Device:isTouchDevice() then self:initGesListener() end -- since we cannot redraw config_dialog with new size, we close -- the old one on screen size change if self.config_dialog then self.config_dialog:closeDialog() end end function ReaderConfig:onCloseCallback() self.last_panel_index = self.config_dialog.panel_index self.config_dialog = nil self.ui:handleEvent(Event:new("RestoreHinting")) end -- event handler for readercropping function ReaderConfig:onCloseConfigMenu() if self.config_dialog then self.config_dialog:closeDialog() end end function ReaderConfig:onReadSettings(config) self.configurable:loadSettings(config, self.options.prefix.."_") local config_panel_index = config:readSetting("config_panel_index") if config_panel_index then config_panel_index = math.min(config_panel_index, #self.options) end self.last_panel_index = config_panel_index or 1 end function ReaderConfig:onSaveSettings() self.configurable:saveSettings(self.ui.doc_settings, self.options.prefix.."_") self.ui.doc_settings:saveSetting("config_panel_index", self.last_panel_index) end return ReaderConfig
Fix possible crash with config panel when engine switched (#3761)
Fix possible crash with config panel when engine switched (#3761) Reading an epub file with Mupdf would show 6 items in bottom config panel. Reading it with crengine would show only 5. A crash would happen if we were on the 6th when leaving MuPDF, and later opening config panel with crengine.
Lua
agpl-3.0
poire-z/koreader,mwoz123/koreader,NiLuJe/koreader,pazos/koreader,Markismus/koreader,poire-z/koreader,Frenzie/koreader,houqp/koreader,Hzj-jie/koreader,lgeek/koreader,koreader/koreader,NiLuJe/koreader,mihailim/koreader,koreader/koreader,Frenzie/koreader
5a88699be3a068e721e23f786a9fdeb6b82b0771
etc/replay.lua
etc/replay.lua
pcall(require, 'luarocks.require') require 'lua-nucleo.module' require 'lua-nucleo.strict' require = import 'lua-nucleo/require_and_declare.lua' { 'require_and_declare' } math.randomseed(12345) local luatexts = require 'luatexts' local luatexts_lua = require 'luatexts.lua' local ensure, ensure_equals, ensure_tequals, ensure_tdeepequals, ensure_strequals, ensure_error, ensure_error_with_substring, ensure_fails_with_substring, ensure_returns = import 'lua-nucleo/ensure.lua' { 'ensure', 'ensure_equals', 'ensure_tequals', 'ensure_tdeepequals', 'ensure_strequals', 'ensure_error', 'ensure_error_with_substring', 'ensure_fails_with_substring', 'ensure_returns' } local split_by_char = import 'lua-nucleo/string.lua' { 'split_by_char' } local tset = import 'lua-nucleo/table-utils.lua' { 'tset' } local tpretty = import 'lua-nucleo/tpretty.lua' { 'tpretty' } local tstr = import 'lua-nucleo/tstr.lua' { 'tstr' } local tserialize = import 'lua-nucleo/tserialize.lua' { 'tserialize' } local tdeepequals = import 'lua-nucleo/tdeepequals.lua' { 'tdeepequals' } local find_all_files, read_file = import 'lua-aplicado/filesystem.lua' { 'find_all_files', 'read_file' } -------------------------------------------------------------------------------- -- TODO: ?! UGH! #3836 declare 'inf' inf = 1/0 -------------------------------------------------------------------------------- local PREFIX = select(1, ...) or "tmp" local OFFSET = tonumber(select(2, ...) or 1) or 1 -------------------------------------------------------------------------------- local filenames = find_all_files("tmp", ".*%.luatexts$") table.sort(filenames) local n_str for i = 1, #filenames do local filename = filenames[i] n_str = assert(filename:match("^tmp/(%d+).luatexts$")) local n = assert(tonumber(n_str, 10)) if n >= OFFSET then local tuple, tuple_size = assert(dofile("tmp/"..n_str..".lua")) local data = assert(read_file(filename)) ensure_returns( "load " .. n_str, tuple_size + 1, { true, unpack(tuple, 1, tuple_size) }, luatexts.load(data) ) end end io.stdout:flush() print("OK")
pcall(require, 'luarocks.require') require 'lua-nucleo.module' require 'lua-nucleo.strict' require = import 'lua-nucleo/require_and_declare.lua' { 'require_and_declare' } math.randomseed(12345) local luatexts = require 'luatexts' local ensure, ensure_equals, ensure_tequals, ensure_tdeepequals, ensure_strequals, ensure_error, ensure_error_with_substring, ensure_fails_with_substring, ensure_returns = import 'lua-nucleo/ensure.lua' { 'ensure', 'ensure_equals', 'ensure_tequals', 'ensure_tdeepequals', 'ensure_strequals', 'ensure_error', 'ensure_error_with_substring', 'ensure_fails_with_substring', 'ensure_returns' } local split_by_char = import 'lua-nucleo/string.lua' { 'split_by_char' } local tset = import 'lua-nucleo/table-utils.lua' { 'tset' } local tpretty = import 'lua-nucleo/tpretty.lua' { 'tpretty' } local tstr = import 'lua-nucleo/tstr.lua' { 'tstr' } local tserialize = import 'lua-nucleo/tserialize.lua' { 'tserialize' } local tdeepequals = import 'lua-nucleo/tdeepequals.lua' { 'tdeepequals' } local find_all_files, read_file = import 'lua-aplicado/filesystem.lua' { 'find_all_files', 'read_file' } -------------------------------------------------------------------------------- -- TODO: ?! UGH! #3836 declare 'inf' inf = 1/0 -------------------------------------------------------------------------------- local PREFIX = select(1, ...) or "tmp" local OFFSET = tonumber(select(2, ...) or 1) or 1 -------------------------------------------------------------------------------- local filenames = find_all_files(PREFIX, ".*%d+%.luatexts$") table.sort(filenames) local n_str for i = 1, #filenames do local filename = filenames[i] n_str = assert(filename:match("^"..PREFIX.."/(%d+).luatexts$")) local n = assert(tonumber(n_str, 10)) if n >= OFFSET then local tuple, tuple_size = assert(dofile(PREFIX.."/"..n_str..".lua")) local data = assert(read_file(filename)) ensure_returns( "load " .. n_str, tuple_size + 1, { true, unpack(tuple, 1, tuple_size) }, luatexts.load(data) ) end end io.stdout:flush() print("OK")
etc/replay: honoring PREFIX
etc/replay: honoring PREFIX
Lua
mit
agladysh/luatexts,agladysh/luatexts,agladysh/luatexts,agladysh/luatexts,agladysh/luatexts
fc0477dfb7102d1d1d9b95b5295bddc053d7c863
core/modulemanager.lua
core/modulemanager.lua
local log = require "util.logger".init("modulemanager") local loadfile, pcall = loadfile, pcall; local setmetatable, setfenv, getfenv = setmetatable, setfenv, getfenv; local pairs, ipairs = pairs, ipairs; local t_insert = table.insert; local type = type; local tostring, print = tostring, print; local _G = _G; module "modulemanager" local handler_info = {}; local handlers = {}; local modulehelpers = setmetatable({}, { __index = _G }); function modulehelpers.add_iq_handler(origin_type, xmlns, handler) if not (origin_type and handler and xmlns) then return false; end handlers[origin_type] = handlers[origin_type] or {}; handlers[origin_type].iq = handlers[origin_type].iq or {}; if not handlers[origin_type].iq[xmlns] then handlers[origin_type].iq[xmlns]= handler; handler_info[handler] = getfenv(2).module; log("debug", "mod_%s now handles tag 'iq' with query namespace '%s'", getfenv(2).module.name, xmlns); else log("warning", "mod_%s wants to handle tag 'iq' with query namespace '%s' but mod_%s already handles that", getfenv(2).module.name, xmlns, handler_info[handlers[origin_type].iq[xmlns]].module.name); end end function modulehelpers.add_handler(origin_type, tag, xmlns, handler) if not (origin_type and tag and xmlns and handler) then return false; end handlers[origin_type] = handlers[origin_type] or {}; if not handlers[origin_type][tag] then handlers[origin_type][tag]= handler; handler_info[handler] = getfenv(2).module; log("debug", "mod_%s now handles tag '%s'", getfenv(2).module.name, tag); elseif handler_info[handlers[origin_type][tag]] then log("warning", "mod_%s wants to handle tag '%s' but mod_%s already handles that", getfenv(2).module.name, tag, handler_info[handlers[origin_type][tag]].module.name); end end function loadall() load("saslauth"); load("legacyauth"); load("roster"); end function load(name) local mod, err = loadfile("plugins/mod_"..name..".lua"); if not mod then log("error", "Unable to load module '%s': %s", name or "nil", err or "nil"); return; end local pluginenv = setmetatable({ module = { name = name } }, { __index = modulehelpers }); setfenv(mod, pluginenv); local success, ret = pcall(mod); if not success then log("error", "Error initialising module '%s': %s", name or "nil", ret or "nil"); return; end end function handle_stanza(origin, stanza) local name, xmlns, origin_type = stanza.name, stanza.attr.xmlns, origin.type; if name == "iq" and xmlns == "jabber:client" and handlers[origin_type] then log("debug", "Stanza is an <iq/>"); local child = stanza.tags[1]; if child then local xmlns = child.attr.xmlns; log("debug", "Stanza has xmlns: %s", xmlns); local handler = handlers[origin_type][name][xmlns]; if handler then log("debug", "Passing stanza to mod_%s", handler_info[handler].name); return handler(origin, stanza) or true; end end elseif handlers[origin_type] then local handler = handlers[origin_type][name]; if handler then log("debug", "Passing stanza to mod_%s", handler_info[handler].name); return handler(origin, stanza) or true; end end log("debug", "Stanza unhandled by any modules"); return false; -- we didn't handle it end do local event_handlers = {}; function modulehelpers.add_event_hook(name, handler) if not event_handlers[name] then event_handlers[name] = {}; end t_insert(event_handlers[name] , handler); end function fire_event(name, ...) local event_handlers = event_handlers[name]; if event_handlers then for name, handler in ipairs(event_handlers) do handler(...); end end end end return _M;
local log = require "util.logger".init("modulemanager") local loadfile, pcall = loadfile, pcall; local setmetatable, setfenv, getfenv = setmetatable, setfenv, getfenv; local pairs, ipairs = pairs, ipairs; local t_insert = table.insert; local type = type; local tostring, print = tostring, print; local _G = _G; module "modulemanager" local handler_info = {}; local handlers = {}; local modulehelpers = setmetatable({}, { __index = _G }); function modulehelpers.add_iq_handler(origin_type, xmlns, handler) if not (origin_type and handler and xmlns) then return false; end handlers[origin_type] = handlers[origin_type] or {}; handlers[origin_type].iq = handlers[origin_type].iq or {}; if not handlers[origin_type].iq[xmlns] then handlers[origin_type].iq[xmlns]= handler; handler_info[handler] = getfenv(2).module; log("debug", "mod_%s now handles tag 'iq' with query namespace '%s'", getfenv(2).module.name, xmlns); else log("warning", "mod_%s wants to handle tag 'iq' with query namespace '%s' but mod_%s already handles that", getfenv(2).module.name, xmlns, handler_info[handlers[origin_type].iq[xmlns]].module.name); end end function modulehelpers.add_handler(origin_type, tag, xmlns, handler) if not (origin_type and tag and xmlns and handler) then return false; end handlers[origin_type] = handlers[origin_type] or {}; if not handlers[origin_type][tag] then handlers[origin_type][tag] = handlers[origin_type][tag] or {}; handlers[origin_type][tag][xmlns]= handler; handler_info[handler] = getfenv(2).module; log("debug", "mod_%s now handles tag '%s'", getfenv(2).module.name, tag); elseif handler_info[handlers[origin_type][tag]] then log("warning", "mod_%s wants to handle tag '%s' but mod_%s already handles that", getfenv(2).module.name, tag, handler_info[handlers[origin_type][tag]].module.name); end end function loadall() load("saslauth"); load("legacyauth"); load("roster"); end function load(name) local mod, err = loadfile("plugins/mod_"..name..".lua"); if not mod then log("error", "Unable to load module '%s': %s", name or "nil", err or "nil"); return; end local pluginenv = setmetatable({ module = { name = name } }, { __index = modulehelpers }); setfenv(mod, pluginenv); local success, ret = pcall(mod); if not success then log("error", "Error initialising module '%s': %s", name or "nil", ret or "nil"); return; end end function handle_stanza(origin, stanza) local name, xmlns, origin_type = stanza.name, stanza.attr.xmlns, origin.type; if name == "iq" and xmlns == "jabber:client" and handlers[origin_type] then log("debug", "Stanza is an <iq/>"); local child = stanza.tags[1]; if child then local xmlns = child.attr.xmlns; log("debug", "Stanza has xmlns: %s", xmlns); local handler = handlers[origin_type][name][xmlns]; if handler then log("debug", "Passing stanza to mod_%s", handler_info[handler].name); return handler(origin, stanza) or true; end end elseif handlers[origin_type] then local handler = handlers[origin_type][name]; if handler then handler = handler[xmlns]; if handler then log("debug", "Passing stanza to mod_%s", handler_info[handler].name); return handler(origin, stanza) or true; end end end log("debug", "Stanza unhandled by any modules, xmlns: %s", stanza.attr.xmlns); return false; -- we didn't handle it end do local event_handlers = {}; function modulehelpers.add_event_hook(name, handler) if not event_handlers[name] then event_handlers[name] = {}; end t_insert(event_handlers[name] , handler); end function fire_event(name, ...) local event_handlers = event_handlers[name]; if event_handlers then for name, handler in ipairs(event_handlers) do handler(...); end end end end return _M;
Fix stanza handlers to use xmlns also for matching
Fix stanza handlers to use xmlns also for matching
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
5e849af9c539370158b4beebf201023656998c7a
lua_modules/http/httpserver.lua
lua_modules/http/httpserver.lua
------------------------------------------------------------------------------ -- HTTP server module -- -- LICENCE: http://opensource.org/licenses/MIT -- Vladimir Dronnikov <dronnikov@gmail.com> ------------------------------------------------------------------------------ local collectgarbage, tonumber, tostring = collectgarbage, tonumber, tostring local http do ------------------------------------------------------------------------------ -- request methods ------------------------------------------------------------------------------ local make_req = function(conn, method, url) return { conn = conn, method = method, url = url, } end ------------------------------------------------------------------------------ -- response methods ------------------------------------------------------------------------------ local make_res = function(csend, cfini) local send = function(self, data, status) -- TODO: req.send should take care of response headers! if self.send_header then csend("HTTP/1.1 ") csend(tostring(status or 200)) -- TODO: real HTTP status code/name table csend(" OK\r\n") -- we use chunked transfer encoding, to not deal with Content-Length: -- response header self:send_header("Transfer-Encoding", "chunked") -- TODO: send standard response headers, such as Server:, Date: end if data then -- NB: no headers allowed after response body started if self.send_header then self.send_header = nil -- end response headers csend("\r\n") end -- chunked transfer encoding csend(("%X\r\n"):format(#data)) csend(data) csend("\r\n") end end local send_header = function(self, name, value) -- luacheck: ignore -- NB: quite a naive implementation csend(name) csend(": ") csend(value) csend("\r\n") end -- finalize request, optionally sending data local finish = function(self, data, status) -- NB: res.send takes care of response headers if data then self:send(data, status) end -- finalize chunked transfer encoding csend("0\r\n\r\n") -- close connection cfini() end -- local res = { } res.send_header = send_header res.send = send res.finish = finish return res end ------------------------------------------------------------------------------ -- HTTP parser ------------------------------------------------------------------------------ local http_handler = function(handler) return function(conn) local csend = (require "fifosock").wrap(conn) local cfini = function() conn:on("receive", nil) conn:on("disconnection", nil) csend(function() conn:on("sent", nil) conn:close() end) end local req, res local buf = "" local method, url local ondisconnect = function(connection) connection:on("sent", nil) collectgarbage("collect") end -- header parser local cnt_len = 0 local onheader = function(connection, k, v) -- luacheck: ignore -- TODO: look for Content-Type: header -- to help parse body -- parse content length to know body length if k == "content-length" then cnt_len = tonumber(v) end if k == "expect" and v == "100-continue" then csend("HTTP/1.1 100 Continue\r\n") end -- delegate to request object if req and req.onheader then req:onheader(k, v) end end -- body data handler local body_len = 0 local ondata = function(connection, chunk) -- luacheck: ignore -- feed request data to request handler if not req or not req.ondata then return end req:ondata(chunk) -- NB: once length of seen chunks equals Content-Length: -- ondata(conn) is called body_len = body_len + #chunk -- print("-B", #chunk, body_len, cnt_len, node.heap()) if body_len >= cnt_len then req:ondata() end end local onreceive = function(connection, chunk) -- merge chunks in buffer if buf then buf = buf .. chunk else buf = chunk end -- consume buffer line by line while #buf > 0 do -- extract line local e = buf:find("\r\n", 1, true) if not e then break end local line = buf:sub(1, e - 1) buf = buf:sub(e + 2) -- method, url? if not method then local i, _ -- luacheck: ignore -- NB: just version 1.1 assumed _, i, method, url = line:find("^([A-Z]+) (.-) HTTP/1.1$") if method then -- make request and response objects req = make_req(connection, method, url) res = make_res(csend, cfini) end -- spawn request handler handler(req, res) -- header line? elseif #line > 0 then -- parse header local _, _, k, v = line:find("^([%w-]+):%s*(.+)") -- header seems ok? if k then k = k:lower() onheader(connection, k, v) end -- headers end else -- NB: we feed the rest of the buffer as starting chunk of body ondata(connection, buf) -- buffer no longer needed buf = nil -- NB: we explicitly reassign receive handler so that -- next received chunks go directly to body handler connection:on("receive", ondata) -- parser done break end end end conn:on("receive", onreceive) conn:on("disconnection", ondisconnect) end end ------------------------------------------------------------------------------ -- HTTP server ------------------------------------------------------------------------------ local srv local createServer = function(port, handler) -- NB: only one server at a time if srv then srv:close() end srv = net.createServer(net.TCP, 15) -- listen srv:listen(port, http_handler(handler)) return srv end ------------------------------------------------------------------------------ -- HTTP server methods ------------------------------------------------------------------------------ http = { createServer = createServer, } end return http
------------------------------------------------------------------------------ -- HTTP server module -- -- LICENCE: http://opensource.org/licenses/MIT -- Vladimir Dronnikov <dronnikov@gmail.com> ------------------------------------------------------------------------------ local collectgarbage, tonumber, tostring = collectgarbage, tonumber, tostring local http do ------------------------------------------------------------------------------ -- request methods ------------------------------------------------------------------------------ local make_req = function(conn, method, url) return { conn = conn, method = method, url = url, } end ------------------------------------------------------------------------------ -- response methods ------------------------------------------------------------------------------ local make_res = function(csend, cfini) local send = function(self, data, status) -- TODO: req.send should take care of response headers! if self.send_header then csend("HTTP/1.1 ") csend(tostring(status or 200)) -- TODO: real HTTP status code/name table csend(" OK\r\n") -- we use chunked transfer encoding, to not deal with Content-Length: -- response header self:send_header("Transfer-Encoding", "chunked") -- TODO: send standard response headers, such as Server:, Date: end if data then -- NB: no headers allowed after response body started if self.send_header then self.send_header = nil -- end response headers csend("\r\n") end -- chunked transfer encoding csend(("%X\r\n"):format(#data)) csend(data) csend("\r\n") end end local send_header = function(_, name, value) -- NB: quite a naive implementation csend(name) csend(": ") csend(value) csend("\r\n") end -- finalize request, optionally sending data local finish = function(self, data, status) -- NB: res.send takes care of response headers if data then self:send(data, status) end -- finalize chunked transfer encoding csend("0\r\n\r\n") -- close connection cfini() end -- local res = { } res.send_header = send_header res.send = send res.finish = finish return res end ------------------------------------------------------------------------------ -- HTTP parser ------------------------------------------------------------------------------ local http_handler = function(handler) return function(conn) local csend = (require "fifosock").wrap(conn) local req, res local buf = "" local method, url local cfini = function() conn:on("receive", nil) conn:on("disconnection", nil) csend(function() conn:on("sent", nil) conn:close() end) end local ondisconnect = function(connection) connection:on("sent", nil) collectgarbage("collect") end -- header parser local cnt_len = 0 local onheader = function(_, k, v) -- TODO: look for Content-Type: header -- to help parse body -- parse content length to know body length if k == "content-length" then cnt_len = tonumber(v) end if k == "expect" and v == "100-continue" then csend("HTTP/1.1 100 Continue\r\n") end -- delegate to request object if req and req.onheader then req:onheader(k, v) end end -- body data handler local body_len = 0 local ondata = function(_, chunk) -- feed request data to request handler if not req or not req.ondata then return end req:ondata(chunk) -- NB: once length of seen chunks equals Content-Length: -- ondata(conn) is called body_len = body_len + #chunk -- print("-B", #chunk, body_len, cnt_len, node.heap()) if body_len >= cnt_len then req:ondata() end end local onreceive = function(connection, chunk) -- merge chunks in buffer if buf then buf = buf .. chunk else buf = chunk end -- consume buffer line by line while #buf > 0 do -- extract line local e = buf:find("\r\n", 1, true) if not e then break end local line = buf:sub(1, e - 1) buf = buf:sub(e + 2) -- method, url? if not method then do local _ -- NB: just version 1.1 assumed _, _, method, url = line:find("^([A-Z]+) (.-) HTTP/1.1$") end if method then -- make request and response objects req = make_req(connection, method, url) res = make_res(csend, cfini) end -- spawn request handler handler(req, res) -- header line? elseif #line > 0 then -- parse header local _, _, k, v = line:find("^([%w-]+):%s*(.+)") -- header seems ok? if k then k = k:lower() onheader(connection, k, v) end -- headers end else -- NB: we explicitly reassign receive handler so that -- next received chunks go directly to body handler connection:on("receive", ondata) -- NB: we feed the rest of the buffer as starting chunk of body ondata(connection, buf) -- buffer no longer needed buf = nil -- parser done break end end end conn:on("receive", onreceive) conn:on("disconnection", ondisconnect) end end ------------------------------------------------------------------------------ -- HTTP server ------------------------------------------------------------------------------ local srv local createServer = function(port, handler) -- NB: only one server at a time if srv then srv:close() end srv = net.createServer(net.TCP, 15) -- listen srv:listen(port, http_handler(handler)) return srv end ------------------------------------------------------------------------------ -- HTTP server methods ------------------------------------------------------------------------------ http = { createServer = createServer, } end return http
fix: fixed the memory leak
fix: fixed the memory leak
Lua
mit
FelixPe/nodemcu-firmware,HEYAHONG/nodemcu-firmware,eku/nodemcu-firmware,vsky279/nodemcu-firmware,vsky279/nodemcu-firmware,vsky279/nodemcu-firmware,FelixPe/nodemcu-firmware,eku/nodemcu-firmware,nodemcu/nodemcu-firmware,HEYAHONG/nodemcu-firmware,nodemcu/nodemcu-firmware,nodemcu/nodemcu-firmware,nodemcu/nodemcu-firmware,nodemcu/nodemcu-firmware,eku/nodemcu-firmware,FelixPe/nodemcu-firmware,HEYAHONG/nodemcu-firmware,vsky279/nodemcu-firmware,vsky279/nodemcu-firmware,HEYAHONG/nodemcu-firmware,FelixPe/nodemcu-firmware,eku/nodemcu-firmware,HEYAHONG/nodemcu-firmware,FelixPe/nodemcu-firmware
ffdc3aec032bf2490020287ff7afc32fd6df9729
xmake/modules/private/action/build/object.lua
xmake/modules/private/action/build/object.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 object.lua -- -- imports import("core.base.option") import("core.theme.theme") import("core.tool.compiler") import("core.project.depend") import("private.tools.ccache") import("private.async.runjobs") -- do build file function _do_build_file(target, sourcefile, opt) -- get build info local objectfile = opt.objectfile local dependfile = opt.dependfile local sourcekind = opt.sourcekind local progress = opt.progress -- load compiler local compinst = compiler.load(sourcekind, {target = target}) -- get compile flags local compflags = compinst:compflags({target = target, sourcefile = sourcefile, configs = opt.configs}) -- load dependent info local dependinfo = option.get("rebuild") and {} or (depend.load(dependfile) or {}) -- need build this object? local depvalues = {compinst:program(), compflags} if not depend.is_changed(dependinfo, {lastmtime = os.mtime(objectfile), values = depvalues}) then return end -- is verbose? local verbose = option.get("verbose") -- exists ccache? local exists_ccache = ccache.exists() -- trace progress info if not opt.quiet then local progress_prefix = "${color.build.progress}" .. theme.get("text.build.progress_format") .. ":${clear} " if verbose then cprint(progress_prefix .. "${dim color.build.object}%scompiling.$(mode) %s", progress, exists_ccache and "ccache " or "", sourcefile) else cprint(progress_prefix .. "${color.build.object}%scompiling.$(mode) %s", progress, exists_ccache and "ccache " or "", sourcefile) end end -- trace verbose info if verbose then print(compinst:compcmd(sourcefile, objectfile, {compflags = compflags})) end -- compile it dependinfo.files = {} if not option.get("dry-run") then assert(compinst:compile(sourcefile, objectfile, {dependinfo = dependinfo, compflags = compflags})) end -- update files and values to the dependent file dependinfo.values = depvalues table.join2(dependinfo.files, sourcefile, target:pcoutputfile("cxx") or {}, target:pcoutputfile("c")) depend.save(dependinfo, dependfile) end -- build object function _build_object(target, sourcebatch, index, opt) -- get the object and source with the given index local sourcefile = sourcebatch.sourcefiles[index] local objectfile = sourcebatch.objectfiles[index] local dependfile = sourcebatch.dependfiles[index] local sourcekind = assert(sourcebatch.sourcekind, "%s: sourcekind not found!", sourcefile) -- init build option opt.objectfile = objectfile opt.dependfile = dependfile opt.sourcekind = sourcekind -- do before build local before_build_file = target:script("build_file_before") if before_build_file then before_build_file(target, sourcefile, opt) end -- do build local on_build_file = target:script("build_file") if on_build_file then on_build_file(target, sourcefile, opt) else _do_build_file(target, sourcefile, opt) end -- do after build local after_build_file = target:script("build_file_after") if after_build_file then after_build_file(target, sourcefile, opt) end end -- add batch jobs to build the source files function main(target, batchjobs, sourcebatch, opt) local rootjob = opt.rootjob for i = 1, #sourcebatch.sourcefiles do batchjobs:addjob(tostring(i), function (index, total) _build_object(target, sourcebatch, i, {progress = (index * 100) / total}) end, rootjob) end 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 object.lua -- -- imports import("core.base.option") import("core.theme.theme") import("core.tool.compiler") import("core.project.depend") import("private.tools.ccache") import("private.async.runjobs") -- do build file function _do_build_file(target, sourcefile, opt) -- get build info local objectfile = opt.objectfile local dependfile = opt.dependfile local sourcekind = opt.sourcekind local progress = opt.progress -- load compiler local compinst = compiler.load(sourcekind, {target = target}) -- get compile flags local compflags = compinst:compflags({target = target, sourcefile = sourcefile, configs = opt.configs}) -- load dependent info local dependinfo = option.get("rebuild") and {} or (depend.load(dependfile) or {}) -- need build this object? local depvalues = {compinst:program(), compflags} if not depend.is_changed(dependinfo, {lastmtime = os.mtime(objectfile), values = depvalues}) then return end -- is verbose? local verbose = option.get("verbose") -- exists ccache? local exists_ccache = ccache.exists() -- trace progress info if not opt.quiet then local progress_prefix = "${color.build.progress}" .. theme.get("text.build.progress_format") .. ":${clear} " if verbose then cprint(progress_prefix .. "${dim color.build.object}%scompiling.$(mode) %s", progress, exists_ccache and "ccache " or "", sourcefile) else cprint(progress_prefix .. "${color.build.object}%scompiling.$(mode) %s", progress, exists_ccache and "ccache " or "", sourcefile) end end -- trace verbose info if verbose then print(compinst:compcmd(sourcefile, objectfile, {compflags = compflags})) end -- compile it dependinfo.files = {} if not option.get("dry-run") then assert(compinst:compile(sourcefile, objectfile, {dependinfo = dependinfo, compflags = compflags})) end -- update files and values to the dependent file dependinfo.values = depvalues table.join2(dependinfo.files, sourcefile, target:pcoutputfile("cxx") or {}, target:pcoutputfile("c")) depend.save(dependinfo, dependfile) end -- build object function _build_object(target, sourcebatch, opt) -- do before build local before_build_file = target:script("build_file_before") if before_build_file then before_build_file(target, sourcefile, opt) end -- do build local on_build_file = target:script("build_file") if on_build_file then on_build_file(target, sourcefile, opt) else _do_build_file(target, sourcefile, opt) end -- do after build local after_build_file = target:script("build_file_after") if after_build_file then after_build_file(target, sourcefile, opt) end end -- add batch jobs to build the source files function main(target, batchjobs, sourcebatch, opt) local rootjob = opt.rootjob for i = 1, #sourcebatch.sourcefiles do local sourcefile = sourcebatch.sourcefiles[i] local objectfile = sourcebatch.objectfiles[i] local dependfile = sourcebatch.dependfiles[i] local sourcekind = assert(sourcebatch.sourcekind, "%s: sourcekind not found!", sourcefile) batchjobs:addjob(sourcefile, function (index, total) _build_object(target, sourcebatch, {objectfile = objectfile, dependfile = dependfile, sourcekind = sourcekind, progress = (index * 100) / total}) end, rootjob) end end
fix build object
fix build object
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
700949c10d42f9572ddc4bc97a90f6ca657db078
orange/plugins/dynamic_upstream/handler.lua
orange/plugins/dynamic_upstream/handler.lua
local pairs = pairs local ipairs = ipairs local ngx_re_sub = ngx.re.sub local ngx_re_find = ngx.re.find local string_sub = string.sub local orange_db = require("orange.store.orange_db") local judge_util = require("orange.utils.judge") local extractor_util = require("orange.utils.extractor") local handle_util = require("orange.utils.handle") local BasePlugin = require("orange.plugins.base_handler") local ngx_set_uri_args = ngx.req.set_uri_args local ngx_decode_args = ngx.decode_args local function ngx_set_uri(uri,rule_handle) ngx.var.upstream_host = rule_handle.host and rule_handle.host or ngx.var.host ngx.var.upstream_url = rule_handle.upstream_name ngx.var.upstream_request_uri = uri .. '?' .. ngx.encode_args(ngx.req.get_uri_args()) ngx.log(ngx.INFO,'[DynamicUpstream][upstream uri][http://',ngx.var.upstream_url,ngx.var.upstream_request_uri,']') end local function filter_rules(sid, plugin, ngx_var_uri) local rules = orange_db.get_json(plugin .. ".selector." .. sid .. ".rules") if not rules or type(rules) ~= "table" or #rules <= 0 then return false end for i, rule in ipairs(rules) do if rule.enable == true then -- judge阶段 local pass = judge_util.judge_rule(rule, "dynamic_upstream") -- extract阶段 local variables = extractor_util.extract_variables(rule.extractor) -- handle阶段 if pass then local handle = rule.handle if handle and handle.uri_tmpl and handle.upstream_name then local to_rewrite = handle_util.build_uri(rule.extractor.type, handle.uri_tmpl, variables) if to_rewrite and to_rewrite ~= ngx_var_uri then if handle.log == true then ngx.log(ngx.INFO, "[DynamicUpstream] ", ngx_var_uri, " to:", to_rewrite) end local from, to, err = ngx_re_find(to_rewrite, "[%?]{1}", "jo") if not err and from and from >= 1 then --local qs = ngx_re_sub(to_rewrite, "[A-Z0-9a-z-_/]*[%?]{1}", "", "jo") local qs = string_sub(to_rewrite, from+1) if qs then local args = ngx_decode_args(qs, 0) if args then ngx_set_uri_args(args) end end end ngx_set_uri(to_rewrite, handle) return true end end return true end end end return false end local DynamicUpstreamHandler = BasePlugin:extend() DynamicUpstreamHandler.PRIORITY = 2000 function DynamicUpstreamHandler:new(store) DynamicUpstreamHandler.super.new(self, "dynamic-upstream-plugin") self.store = store end function DynamicUpstreamHandler:rewrite(conf) DynamicUpstreamHandler.super.rewrite(self) local enable = orange_db.get("dynamic_upstream.enable") local meta = orange_db.get_json("dynamic_upstream.meta") local selectors = orange_db.get_json("dynamic_upstream.selectors") local ordered_selectors = meta and meta.selectors if not enable or enable ~= true or not meta or not ordered_selectors or not selectors then return end local ngx_var_uri = ngx.var.uri for i, sid in ipairs(ordered_selectors) do local selector = selectors[sid] ngx.log(ngx.INFO, "==[DynamicUpstream][START SELECTOR:", sid, "][NAME:",selector.name,']') if selector and selector.enable == true then local selector_pass if selector.type == 0 then -- 全流量选择器 selector_pass = true else selector_pass = judge_util.judge_selector(selector, "dynamic_upstream")-- selector judge end if selector_pass then if selector.handle and selector.handle.log == true then ngx.log(ngx.INFO, "[DynamicUpstream][PASS-SELECTOR:", sid, "] ", ngx_var_uri) end local stop = filter_rules(sid, "dynamic_upstream", ngx_var_uri) if stop then -- 不再执行此插件其他逻辑 return end else if selector.handle and selector.handle.log == true then ngx.log(ngx.INFO, "[DynamicUpstream][NOT-PASS-SELECTOR:", sid, "] ", ngx_var_uri) end end -- if continue or break the loop if selector.handle and selector.handle.continue == true then -- continue next selector else break end end end end return DynamicUpstreamHandler
local pairs = pairs local ipairs = ipairs local ngx_re_sub = ngx.re.sub local ngx_re_find = ngx.re.find local string_sub = string.sub local orange_db = require("orange.store.orange_db") local judge_util = require("orange.utils.judge") local extractor_util = require("orange.utils.extractor") local handle_util = require("orange.utils.handle") local BasePlugin = require("orange.plugins.base_handler") local ngx_set_uri_args = ngx.req.set_uri_args local ngx_decode_args = ngx.decode_args local function ngx_set_uri(uri,rule_handle) ngx.var.upstream_host = rule_handle.host and rule_handle.host or ngx.var.host ngx.var.upstream_url = rule_handle.upstream_name ngx.var.upstream_request_uri = uri .. '?' .. ngx.encode_args(ngx.req.get_uri_args()) ngx.log(ngx.INFO, '[DynamicUpstream][upstream request][http://', ngx.var.upstream_url, ngx.var.upstream_request_uri, ']') end local function filter_rules(sid, plugin, ngx_var_uri) local rules = orange_db.get_json(plugin .. ".selector." .. sid .. ".rules") if not rules or type(rules) ~= "table" or #rules <= 0 then return false end for i, rule in ipairs(rules) do if rule.enable == true then ngx.log(ngx.INFO, "==[DynamicUpstream][rule name:", rule.name, "][rule id:", rule.id, ']') -- judge阶段 local pass = judge_util.judge_rule(rule, "dynamic_upstream") -- extract阶段 local variables = extractor_util.extract_variables(rule.extractor) -- handle阶段 if pass then local handle = rule.handle if handle and handle.uri_tmpl and handle.upstream_name then local to_rewrite = handle_util.build_uri(rule.extractor.type, handle.uri_tmpl, variables) if to_rewrite then if handle.log == true then ngx.log(ngx.INFO, "[DynamicUpstream] ", ngx_var_uri, " to:", to_rewrite) end local from, to, err = ngx_re_find(to_rewrite, "[?]{1}", "jo") if not err and from and from >= 1 then --local qs = ngx_re_sub(to_rewrite, "[A-Z0-9a-z-_/]*[%?]{1}", "", "jo") local qs = string_sub(to_rewrite, from + 1) if qs then -- save original query params -- ngx_set_uri_args(ngx.req.get_uri_args()) -- not use above just to keep the same behavior with nginx `rewrite` instruct local args = ngx_decode_args(qs, 0) if args then ngx_set_uri_args(args) end end to_rewrite = string_sub(to_rewrite, 1, from - 1) end ngx_set_uri(to_rewrite, handle) return true end end return true end end end return false end local DynamicUpstreamHandler = BasePlugin:extend() DynamicUpstreamHandler.PRIORITY = 2000 function DynamicUpstreamHandler:new(store) DynamicUpstreamHandler.super.new(self, "dynamic-upstream-plugin") self.store = store end function DynamicUpstreamHandler:rewrite(conf) DynamicUpstreamHandler.super.rewrite(self) local enable = orange_db.get("dynamic_upstream.enable") local meta = orange_db.get_json("dynamic_upstream.meta") local selectors = orange_db.get_json("dynamic_upstream.selectors") local ordered_selectors = meta and meta.selectors if not enable or enable ~= true or not meta or not ordered_selectors or not selectors then return end local ngx_var_uri = ngx.var.uri for i, sid in ipairs(ordered_selectors) do local selector = selectors[sid] ngx.log(ngx.INFO, "==[DynamicUpstream][START SELECTOR:", sid, ",NAME:",selector.name,']') if selector and selector.enable == true then local selector_pass if selector.type == 0 then -- 全流量选择器 selector_pass = true else selector_pass = judge_util.judge_selector(selector, "dynamic_upstream")-- selector judge end if selector_pass then if selector.handle and selector.handle.log == true then ngx.log(ngx.INFO, "[DynamicUpstream][PASS-SELECTOR:", sid, "] ", ngx_var_uri) end local stop = filter_rules(sid, "dynamic_upstream", ngx_var_uri) if stop then -- 不再执行此插件其他逻辑 return end else if selector.handle and selector.handle.log == true then ngx.log(ngx.INFO, "[DynamicUpstream][NOT-PASS-SELECTOR:", sid, "] ", ngx_var_uri) end end -- if continue or break the loop if selector.handle and selector.handle.continue == true then -- continue next selector else break end end end end return DynamicUpstreamHandler
fix & modify dynamic_upstream
fix & modify dynamic_upstream 1. keep the behavior with rewrite ins 2. fix copy bug: not to rewrite whtn to_rewrite equals to uri 3. test case : 添加两个规则,规则中配置处理一栏: 1. /notso/${1}/2ad%20fa/hha dd/?name=11 2223&ab=1c, ${1} 表示变量提取式,可以随意配置一个。 2. /gooda/ requrest: http://192.168.110.137/hhhe?aafad=1 http://192.168.110.137/good?normal=1
Lua
mit
sumory/orange,sumory/orange,sumory/orange
2c5f6ad39e37f4029a263419a28f3c05c0019f9a
etc/Far3/Profile/Macros/scripts/Plugin.Editor.FarColorer.lua
etc/Far3/Profile/Macros/scripts/Plugin.Editor.FarColorer.lua
local guid = 'D2F36B62-A470-418D-83A3-ED7A3710E5B5'; Macro { area = "Editor"; key = "AltL"; flags = ""; description = "Editor: List of types"; action = function() Plugin.Call(guid, 1); -- Keys("F11 c 1") end } Macro { area = "Editor"; key = "Alt["; flags = ""; description = "Editor: Find pair brackets"; action = function() Plugin.Call(guid, 2); -- Keys("F11 c 2") end } Macro { area = "Editor"; key = "Alt]"; flags = ""; description = "Editor: Select a block with brackets"; action = function() Plugin.Call(guid, 3); -- Keys("F11 c 3") end } Macro { area = "Editor"; key = "AltP"; flags = ""; description = "Editor: Select a block within brackets"; action = function() Plugin.Call(guid, 4); -- Keys("F11 c 4") end } Macro { area = "Editor"; key = "Alt;"; flags = ""; description = "Editor: List of functions"; action = function() Plugin.Call(guid, 5); -- Keys("F11 c 5") end } Macro { area = "Editor"; key = "Alt'"; flags = ""; description = "Editor: List of errors"; action = function() Plugin.Call(guid, 6); -- Keys("F11 c 6") end }
local guid = 'D2F36B62-A470-418D-83A3-ED7A3710E5B5'; Macro { area = "Editor"; key = "AltL"; flags = ""; description = "Editor: List of types"; action = function() Plugin.Call(guid, 1); -- Keys("F11 c 1"); if export.GetGlobalInfo().MinFarVersion[4] > 4242 then Keys("Enter"); end; -- workaround for Far3 build 4400 end } Macro { area = "Editor"; key = "Alt["; flags = ""; description = "Editor: Find pair brackets"; action = function() Plugin.Call(guid, 2); -- Keys("F11 c 2") end } Macro { area = "Editor"; key = "Alt]"; flags = ""; description = "Editor: Select a block with brackets"; action = function() Plugin.Call(guid, 3); -- Keys("F11 c 3") end } Macro { area = "Editor"; key = "AltP"; flags = ""; description = "Editor: Select a block within brackets"; action = function() Plugin.Call(guid, 4); -- Keys("F11 c 4") end } Macro { area = "Editor"; key = "Alt;"; flags = ""; description = "Editor: List of functions"; action = function() Plugin.Call(guid, 5); -- Keys("F11 c 5") end } Macro { area = "Editor"; key = "Alt'"; flags = ""; description = "Editor: List of errors"; action = function() Plugin.Call(guid, 6); -- Keys("F11 c 6") end }
Plugin.Editor.FarColorer.lua updated to fix issie with ALT-L in Far3.0.4400
Plugin.Editor.FarColorer.lua updated to fix issie with ALT-L in Far3.0.4400
Lua
mit
ildar-shaimordanov/tea-set
56a0e894324f42e8f3cad3e15a84ebe0f3f18063
modules/urbandict.lua
modules/urbandict.lua
local simplehttp = require'simplehttp' local json = require'json' local trim = function(s) return (string.gsub(s, "^%s*(.-)%s*$", "%1")) end local urlEncode = function(str) return str:gsub( '([^%w ])', function (c) return string.format ("%%%02X", string.byte(c)) end ):gsub(' ', '+') end local parseJSON = function(data) data = json.decode(data) if(#data.list > 0) then return data.list[1].definition:gsub('\r\n', ' ') end end local handler = function(self, source, destination, input) input = trim(input) simplehttp( APIBase:format(urlEncode(input)), function(data) local result = parseJSON(data) if(result) then local msgLimit = (512 - 16 - 65 - 10) - #self.config.nick - #destination if(#result > msgLimit) then result = result:sub(1, msgLimit - 3) .. '...' end self:Msg('privmsg', destination, source, string.format('%s: %s', source.nick, result)) else self:Msg('privmsg', destination, source, string.format("%s: %s is bad and you should feel bad.", source.nick, input)) end end ) end local APIBase = 'http://api.urbandictionary.com/v0/define?term=%s' return { PRIVMSG = { ['^!ud (.+)$'] = handler, ['^!urb (.+)$'] = handler, }, }
local simplehttp = require'simplehttp' local json = require'json' local trim = function(s) return (string.gsub(s, "^%s*(.-)%s*$", "%1")) end local urlEncode = function(str) return str:gsub( '([^%w ])', function (c) return string.format ("%%%02X", string.byte(c)) end ):gsub(' ', '+') end local parseJSON = function(data) data = json.decode(data) if(#data.list > 0) then return data.list[1].definition:gsub('\r\n', ' ') end end local APIBase = 'http://api.urbandictionary.com/v0/define?term=%s' local handler = function(self, source, destination, input) input = trim(input) simplehttp( APIBase:format(urlEncode(input)), function(data) local result = parseJSON(data) if(result) then local msgLimit = (512 - 16 - 65 - 10) - #self.config.nick - #destination if(#result > msgLimit) then result = result:sub(1, msgLimit - 3) .. '...' end self:Msg('privmsg', destination, source, string.format('%s: %s', source.nick, result)) else self:Msg('privmsg', destination, source, string.format("%s: %s is bad and you should feel bad.", source.nick, input)) end end ) end return { PRIVMSG = { ['^!ud (.+)$'] = handler, ['^!urb (.+)$'] = handler, }, }
urbandict: Fix fail. :-(
urbandict: Fix fail. :-( Former-commit-id: c4cfe85be09f92255da904949de5b2357de869c5 [formerly 318017e4c676dc2586af50a403a6b9cb9d84db31] Former-commit-id: 1134f37fd149d1a588dad923d18f6e10835fa59d
Lua
mit
haste/ivar2,torhve/ivar2,torhve/ivar2,torhve/ivar2
da8dbb98262c6543b0846335ac693e61e7008163
src/luacheck/globbing.lua
src/luacheck/globbing.lua
local fs = require "luacheck.fs" local utils = require "luacheck.utils" -- Only ?, *, ** and simple character classes (with ranges and negation) are supported. -- Hidden files are not treated specially. Special characters can't be escaped. local globbing = {} local cur_dir = fs.current_dir() local function is_regular_path(glob) return not glob:find("[*?%[]") end local function get_parts(path) local parts = {} for part in path:gmatch("[^"..utils.dir_sep.."]+") do table.insert(parts, part) end return parts end local function glob_pattern_escaper(c) return ((c == "*" or c == "?") and "." or "%")..c end local function glob_range_escaper(c) return c == "-" and c or ("%"..c) end local function glob_part_to_pattern(glob_part) local buffer = {"^"} local i = 1 while i <= #glob_part do local bracketless bracketless, i = glob_part:match("([^%[]*)()", i) table.insert(buffer, (bracketless:gsub("%p", glob_pattern_escaper))) if glob_part:sub(i, i) == "[" then table.insert(buffer, "[") i = i + 1 local first_char = glob_part:sub(i, i) if first_char == "!" then table.insert(buffer, "^") else table.insert(buffer, "%"..first_char) end bracketless, i = glob_part:match("([^%]]*)()", i + 1) if bracketless:sub(1, 1) == "-" then table.insert(buffer, "%-") bracketless = bracketless:sub(2) end local last_dash = "" if bracketless:sub(-1) == "-" then last_dash = "-" bracketless = bracketless:sub(1, -2) end table.insert(buffer, (bracketless:gsub("%p", glob_range_escaper))) table.insert(buffer, last_dash.."]") i = i + 1 end end table.insert(buffer, "$") return table.concat(buffer) end local function part_match(glob_part, path_part) return utils.pmatch(path_part, glob_part_to_pattern(glob_part)) end local function parts_match(glob_parts, glob_i, path_parts, path_i) local glob_part = glob_parts[glob_i] if not glob_part then -- Reached glob end, path matches the glob or its subdirectory. -- E.g. path "foo/bar/baz/src.lua" matches glob "foo/*/baz". return true end if glob_part == "**" then -- "**" can consume any number of path parts. for i = path_i, #path_parts + 1 do if parts_match(glob_parts, glob_i + 1, path_parts, i) then return true end end return false end local path_part = path_parts[path_i] return path_part and part_match(glob_part, path_part) and parts_match(glob_parts, glob_i + 1, path_parts, path_i + 1) end -- Checks if a path matches a globbing pattern. function globbing.match(glob, path) glob = fs.normalize(fs.join(cur_dir, glob)) path = fs.normalize(fs.join(cur_dir, path)) if is_regular_path(glob) then return fs.is_subpath(glob, path) end local glob_base, path_base glob_base, glob = fs.split_base(glob) path_base, path = fs.split_base(path) if glob_base ~= path_base then return false end local glob_parts = get_parts(glob) local path_parts = get_parts(path) return parts_match(glob_parts, 1, path_parts, 1) end return globbing
local fs = require "luacheck.fs" local utils = require "luacheck.utils" -- Only ?, *, ** and simple character classes (with ranges and negation) are supported. -- Hidden files are not treated specially. Special characters can't be escaped. local globbing = {} local cur_dir = fs.current_dir() local function is_regular_path(glob) return not glob:find("[*?%[]") end local function get_parts(path) local parts = {} for part in path:gmatch("[^"..utils.dir_sep.."]+") do table.insert(parts, part) end return parts end local function glob_pattern_escaper(c) return ((c == "*" or c == "?") and "." or "%")..c end local function glob_range_escaper(c) return c == "-" and c or ("%"..c) end local function glob_part_to_pattern(glob_part) local buffer = {"^"} local i = 1 while i <= #glob_part do local bracketless bracketless, i = glob_part:match("([^%[]*)()", i) table.insert(buffer, (bracketless:gsub("%p", glob_pattern_escaper))) if glob_part:sub(i, i) == "[" then table.insert(buffer, "[") i = i + 1 local first_char = glob_part:sub(i, i) if first_char == "!" then table.insert(buffer, "^") i = i + 1 elseif first_char == "]" then table.insert(buffer, "%]") i = i + 1 end bracketless, i = glob_part:match("([^%]]*)()", i) if bracketless:sub(1, 1) == "-" then table.insert(buffer, "%-") bracketless = bracketless:sub(2) end local last_dash = "" if bracketless:sub(-1) == "-" then last_dash = "-" bracketless = bracketless:sub(1, -2) end table.insert(buffer, (bracketless:gsub("%p", glob_range_escaper))) table.insert(buffer, last_dash.."]") i = i + 1 end end table.insert(buffer, "$") return table.concat(buffer) end local function part_match(glob_part, path_part) return utils.pmatch(path_part, glob_part_to_pattern(glob_part)) end local function parts_match(glob_parts, glob_i, path_parts, path_i) local glob_part = glob_parts[glob_i] if not glob_part then -- Reached glob end, path matches the glob or its subdirectory. -- E.g. path "foo/bar/baz/src.lua" matches glob "foo/*/baz". return true end if glob_part == "**" then -- "**" can consume any number of path parts. for i = path_i, #path_parts + 1 do if parts_match(glob_parts, glob_i + 1, path_parts, i) then return true end end return false end local path_part = path_parts[path_i] return path_part and part_match(glob_part, path_part) and parts_match(glob_parts, glob_i + 1, path_parts, path_i + 1) end -- Checks if a path matches a globbing pattern. function globbing.match(glob, path) glob = fs.normalize(fs.join(cur_dir, glob)) path = fs.normalize(fs.join(cur_dir, path)) if is_regular_path(glob) then return fs.is_subpath(glob, path) end local glob_base, path_base glob_base, glob = fs.split_base(glob) path_base, path = fs.split_base(path) if glob_base ~= path_base then return false end local glob_parts = get_parts(glob) local path_parts = get_parts(path) return parts_match(glob_parts, 1, path_parts, 1) end return globbing
Fix ranges in globbing
Fix ranges in globbing Always escaping and discarding first character in a class is not correct when it's part of a range, e.g. '[a-z]'.
Lua
mit
adan830/luacheck,mpeterv/luacheck,xpol/luacheck,xpol/luacheck,mpeterv/luacheck,kidaa/luacheck,adan830/luacheck,tst2005/luacheck,linuxmaniac/luacheck,xpol/luacheck,linuxmaniac/luacheck,tst2005/luacheck,kidaa/luacheck,mpeterv/luacheck
e7df75c4471e9db913e95326f4a2f9fd6aa59708
Sassilization/gamemode/modules/unit/units/ballista/init.lua
Sassilization/gamemode/modules/unit/units/ballista/init.lua
---------------------------------------- -- Sassilization -- http://sassilization.com -- By Sassafrass / Spacetech / LuaPineapple ---------------------------------------- local arrowspeed = 200 function UNIT:DoAttack( enemy, dmginfo ) dmginfo.dmgtype = DMG_BULLET local arrowTime = enemy:LocalToWorld(dmginfo.dmgpos):Distance( self:GetPos() ) / arrowspeed local ed = EffectData() ed:SetOrigin( self:GetPos() + VECTOR_UP * 1.8 ) ed:SetScale( CurTime() + arrowTime ) ed:SetEntity( enemy.NWEnt and enemy.NWEnt or enemy ) ed:SetStart( dmginfo.dmgpos ) util.Effect( "ballista_arrow", ed, true, true ) box = ents.FindInBox( self:GetPos() + VECTOR_UP * 1.8 - (self.NWEnt:GetRight() * 1.5), enemy:GetPos() + ((enemy:GetPos() - self:GetPos()):GetNormal() * 4) + (self.NWEnt:GetRight() * 1.5) ) timer.Simple( arrowTime, function() for k,v in pairs(box) do if IsValid(v) and v.Unit then if v.Unit:GetEmpire() != self:GetEmpire() then v.Unit:Damage( dmginfo ) end elseif IsValid(v) and v.Building then if v:GetEmpire() != self:GetEmpire() then dmginfo.damage = 5 v:Damage( dmginfo ) end end end end ) end function UNIT:Think() self.BaseClass.Think( self ) end
---------------------------------------- -- Sassilization -- http://sassilization.com -- By Sassafrass / Spacetech / LuaPineapple ---------------------------------------- local arrowspeed = 200 function UNIT:DoAttack( enemy, dmginfo ) dmginfo.dmgtype = DMG_BULLET local arrowTime = enemy:LocalToWorld(dmginfo.dmgpos):Distance( self:GetPos() ) / arrowspeed local ed = EffectData() ed:SetOrigin( self:GetPos() + VECTOR_UP * 1.8 ) ed:SetScale( CurTime() + arrowTime ) ed:SetEntity( enemy.NWEnt and enemy.NWEnt or enemy ) ed:SetStart( dmginfo.dmgpos ) util.Effect( "ballista_arrow", ed, true, true ) box = ents.FindInBox( self:GetPos() + VECTOR_UP * 1.8 - (self.NWEnt:GetRight() * 1.5), enemy:GetPos() + ((enemy:GetPos() - self:GetPos()):GetNormal() * 4) + (self.NWEnt:GetRight() * 1.5) ) timer.Simple( arrowTime, function() for k,v in pairs(box) do if IsValid(v) and v.Unit then if v.Unit:GetEmpire() != self:GetEmpire() && !Allied(self:GetEmpire(), v.Unit:GetEmpire()) then v.Unit:Damage( dmginfo ) end elseif IsValid(v) and v.Building then if v:GetEmpire() != self:GetEmpire() then dmginfo.damage = 3 v:Damage( dmginfo ) end end end end ) end function UNIT:Think() self.BaseClass.Think( self ) end
Fixed ballistas damaging allies. Lowered ballista damage to buildings to 3 (From 5).
Fixed ballistas damaging allies. Lowered ballista damage to buildings to 3 (From 5).
Lua
bsd-3-clause
T3hArco/skeyler-gamemodes
0081d72c1e1f1f0efaa74a34de4578dc8d5b0845
vrp/client/player_state.lua
vrp/client/player_state.lua
-- periodic player state update local state_ready = false AddEventHandler("playerSpawned",function() -- delay state recording state_ready = false Citizen.CreateThread(function() Citizen.Wait(30000) state_ready = true end) end) Citizen.CreateThread(function() while true do Citizen.Wait(30000) if IsPlayerPlaying(PlayerId()) and state_ready then local x,y,z = table.unpack(GetEntityCoords(GetPlayerPed(-1),true)) vRPserver.updatePos({x,y,z}) vRPserver.updateHealth({tvRP.getHealth()}) vRPserver.updateWeapons({tvRP.getWeapons()}) vRPserver.updateCustomization({tvRP.getCustomization()}) end end end) -- WEAPONS -- def local weapon_types = { "WEAPON_KNIFE", "WEAPON_STUNGUN", "WEAPON_FLASHLIGHT", "WEAPON_NIGHTSTICK", "WEAPON_HAMMER", "WEAPON_BAT ", "WEAPON_GOLFCLUB", "WEAPON_CROWBAR", "WEAPON_PISTOL", "WEAPON_COMBATPISTOL", "WEAPON_APPISTOL", "WEAPON_PISTOL50", "WEAPON_MICROSMG", "WEAPON_SMG ", "WEAPON_ASSAULTSMG", "WEAPON_ASSAULTRIFLE", "WEAPON_CARBINERIFLE", "WEAPON_ADVANCEDRIFLE", "WEAPON_MG", "WEAPON_COMBATMG", "WEAPON_PUMPSHOTGUN ", "WEAPON_SAWNOFFSHOTGUN", "WEAPON_ASSAULTSHOTGUN", "WEAPON_BULLPUPSHOTGUN", "WEAPON_STUNGUN ", "WEAPON_SNIPERRIFLE ", "WEAPON_HEAVYSNIPER ", "WEAPON_REMOTESNIPER", "WEAPON_GRENADELAUNCHER", "WEAPON_GRENADELAUNCHER_SMOKE", "WEAPON_RPG", "WEAPON_PASSENGER_ROCKET", "WEAPON_AIRSTRIKE_ROCKET", "WEAPON_STINGER", "WEAPON_MINIGUN", "WEAPON_GRENADE", "WEAPON_STICKYBOMB", "WEAPON_SMOKEGRENADE", "WEAPON_BZGAS", "WEAPON_MOLOTOV ", "WEAPON_FIREEXTINGUISHER", "WEAPON_PETROLCAN ", "WEAPON_DIGISCANNER", "WEAPON_BRIEFCASE", "WEAPON_BRIEFCASE_02", "WEAPON_BALL", "WEAPON_FLARE" } function tvRP.getWeaponTypes() return weapon_types end function tvRP.getWeapons() local player = GetPlayerPed(-1) local weapons = {} for k,v in pairs(weapon_types) do local hash = GetHashKey(v) if HasPedGotWeapon(player,hash) then local weapon = {} weapons[v] = weapon weapon.ammo = GetAmmoInPedWeapon(player,hash) end end return weapons end function tvRP.giveWeapons(weapons,clear_before) local player = GetPlayerPed(-1) -- give weapons to player if clear_before then RemoveAllPedWeapons(player,true) end for k,weapon in pairs(weapons) do local hash = GetHashKey(k) local ammo = weapon.ammo or 0 GiveWeaponToPed(player, hash, ammo, false) end -- send weapons update vRPserver.updateWeapons({tvRP.getWeapons()}) end --[[ function tvRP.dropWeapon() SetPedDropsWeapon(GetPlayerPed(-1)) end --]] -- PLAYER CUSTOMIZATION -- parse part key (a ped part or a prop part) -- return is_proppart, index local function parse_part(key) if type(key) == "string" and string.sub(key,1,1) == "p" then return true,tonumber(string.sub(key,2)) else return false,tonumber(key) end end function tvRP.getDrawables(part) local isprop, index = parse_part(part) if isprop then return GetNumberOfPedPropDrawableVariations(GetPlayerPed(-1),index) else return GetNumberOfPedDrawableVariations(GetPlayerPed(-1),index) end end function tvRP.getDrawableTextures(part,drawable) local isprop, index = parse_part(part) if isprop then return GetNumberOfPedPropTextureVariations(GetPlayerPed(-1),index,drawable) else return GetNumberOfPedTextureVariations(GetPlayerPed(-1),index,drawable) end end function tvRP.getCustomization() local ped = GetPlayerPed(-1) local custom = {} custom.modelhash = GetEntityModel(ped) -- ped parts for i=0,20 do -- index limit to 20 custom[i] = {GetPedDrawableVariation(ped,i), GetPedTextureVariation(ped,i), GetPedPaletteVariation(ped,i)} end -- props for i=0,10 do -- index limit to 10 custom["p"..i] = {GetPedPropIndex(ped,i), math.max(GetPedPropTextureIndex(ped,i),0)} end return custom end -- partial customization (only what is set is changed) function tvRP.setCustomization(custom) -- indexed [drawable,texture,palette] components or props (p0...) plus .modelhash or .model local exit = TUNNEL_DELAYED() -- delay the return values Citizen.CreateThread(function() -- new thread if custom then local ped = GetPlayerPed(-1) local mhash = nil -- model if custom.modelhash ~= nil then mhash = custom.modelhash elseif custom.model ~= nil then mhash = GetHashKey(custom.model) end if mhash ~= nil then local i = 0 while not HasModelLoaded(mhash) and i < 10000 do RequestModel(mhash) Citizen.Wait(10) end if HasModelLoaded(mhash) then SetPlayerModel(PlayerId(), mhash) SetModelAsNoLongerNeeded(mhash) end end ped = GetPlayerPed(-1) -- parts for k,v in pairs(custom) do if k ~= "model" and k ~= "modelhash" then local isprop, index = parse_part(k) if isprop then if v[1] < 0 then ClearPedProp(ped,index) else SetPedPropIndex(ped,index,v[1],v[2],v[3] or 2) end else SetPedComponentVariation(ped,index,v[1],v[2],v[3] or 2) end end end end exit({}) end) end -- fix invisible players by resetting customization every minutes --[[ Citizen.CreateThread(function() while true do Citizen.Wait(60000) if state_ready then local custom = tvRP.getCustomization() custom.model = nil custom.modelhash = nil tvRP.setCustomization(custom) end end end) --]]
-- periodic player state update local state_ready = false AddEventHandler("playerSpawned",function() -- delay state recording state_ready = false Citizen.CreateThread(function() Citizen.Wait(30000) state_ready = true end) end) Citizen.CreateThread(function() while true do Citizen.Wait(30000) if IsPlayerPlaying(PlayerId()) and state_ready then local x,y,z = table.unpack(GetEntityCoords(GetPlayerPed(-1),true)) vRPserver.updatePos({x,y,z}) vRPserver.updateHealth({tvRP.getHealth()}) vRPserver.updateWeapons({tvRP.getWeapons()}) vRPserver.updateCustomization({tvRP.getCustomization()}) end end end) -- WEAPONS -- def local weapon_types = { "WEAPON_KNIFE", "WEAPON_STUNGUN", "WEAPON_FLASHLIGHT", "WEAPON_NIGHTSTICK", "WEAPON_HAMMER", "WEAPON_BAT ", "WEAPON_GOLFCLUB", "WEAPON_CROWBAR", "WEAPON_PISTOL", "WEAPON_COMBATPISTOL", "WEAPON_APPISTOL", "WEAPON_PISTOL50", "WEAPON_MICROSMG", "WEAPON_SMG ", "WEAPON_ASSAULTSMG", "WEAPON_ASSAULTRIFLE", "WEAPON_CARBINERIFLE", "WEAPON_ADVANCEDRIFLE", "WEAPON_MG", "WEAPON_COMBATMG", "WEAPON_PUMPSHOTGUN ", "WEAPON_SAWNOFFSHOTGUN", "WEAPON_ASSAULTSHOTGUN", "WEAPON_BULLPUPSHOTGUN", "WEAPON_STUNGUN ", "WEAPON_SNIPERRIFLE ", "WEAPON_HEAVYSNIPER ", "WEAPON_REMOTESNIPER", "WEAPON_GRENADELAUNCHER", "WEAPON_GRENADELAUNCHER_SMOKE", "WEAPON_RPG", "WEAPON_PASSENGER_ROCKET", "WEAPON_AIRSTRIKE_ROCKET", "WEAPON_STINGER", "WEAPON_MINIGUN", "WEAPON_GRENADE", "WEAPON_STICKYBOMB", "WEAPON_SMOKEGRENADE", "WEAPON_BZGAS", "WEAPON_MOLOTOV ", "WEAPON_FIREEXTINGUISHER", "WEAPON_PETROLCAN ", "WEAPON_DIGISCANNER", "WEAPON_BRIEFCASE", "WEAPON_BRIEFCASE_02", "WEAPON_BALL", "WEAPON_FLARE" } function tvRP.getWeaponTypes() return weapon_types end function tvRP.getWeapons() local player = GetPlayerPed(-1) local weapons = {} for k,v in pairs(weapon_types) do local hash = GetHashKey(v) if HasPedGotWeapon(player,hash) then local weapon = {} weapons[v] = weapon weapon.ammo = GetAmmoInPedWeapon(player,hash) end end return weapons end function tvRP.giveWeapons(weapons,clear_before) local player = GetPlayerPed(-1) -- give weapons to player if clear_before then RemoveAllPedWeapons(player,true) end for k,weapon in pairs(weapons) do local hash = GetHashKey(k) local ammo = weapon.ammo or 0 GiveWeaponToPed(player, hash, ammo, false) end -- send weapons update vRPserver.updateWeapons({tvRP.getWeapons()}) end --[[ function tvRP.dropWeapon() SetPedDropsWeapon(GetPlayerPed(-1)) end --]] -- PLAYER CUSTOMIZATION -- parse part key (a ped part or a prop part) -- return is_proppart, index local function parse_part(key) if type(key) == "string" and string.sub(key,1,1) == "p" then return true,tonumber(string.sub(key,2)) else return false,tonumber(key) end end function tvRP.getDrawables(part) local isprop, index = parse_part(part) if isprop then return GetNumberOfPedPropDrawableVariations(GetPlayerPed(-1),index) else return GetNumberOfPedDrawableVariations(GetPlayerPed(-1),index) end end function tvRP.getDrawableTextures(part,drawable) local isprop, index = parse_part(part) if isprop then return GetNumberOfPedPropTextureVariations(GetPlayerPed(-1),index,drawable) else return GetNumberOfPedTextureVariations(GetPlayerPed(-1),index,drawable) end end function tvRP.getCustomization() local ped = GetPlayerPed(-1) local custom = {} custom.modelhash = GetEntityModel(ped) -- ped parts for i=0,20 do -- index limit to 20 custom[i] = {GetPedDrawableVariation(ped,i), GetPedTextureVariation(ped,i), GetPedPaletteVariation(ped,i)} end -- props for i=0,10 do -- index limit to 10 custom["p"..i] = {GetPedPropIndex(ped,i), math.max(GetPedPropTextureIndex(ped,i),0)} end return custom end -- partial customization (only what is set is changed) function tvRP.setCustomization(custom) -- indexed [drawable,texture,palette] components or props (p0...) plus .modelhash or .model local exit = TUNNEL_DELAYED() -- delay the return values Citizen.CreateThread(function() -- new thread if custom then local ped = GetPlayerPed(-1) local mhash = nil -- model if custom.modelhash ~= nil then mhash = custom.modelhash elseif custom.model ~= nil then mhash = GetHashKey(custom.model) end if mhash ~= nil then local i = 0 while not HasModelLoaded(mhash) and i < 10000 do RequestModel(mhash) Citizen.Wait(10) end if HasModelLoaded(mhash) then -- changing player model remove weapons, so save it local weapons = tvRP.getWeapons() SetPlayerModel(PlayerId(), mhash) tvRP.giveWeapons(weapons,true) SetModelAsNoLongerNeeded(mhash) end end ped = GetPlayerPed(-1) -- parts for k,v in pairs(custom) do if k ~= "model" and k ~= "modelhash" then local isprop, index = parse_part(k) if isprop then if v[1] < 0 then ClearPedProp(ped,index) else SetPedPropIndex(ped,index,v[1],v[2],v[3] or 2) end else SetPedComponentVariation(ped,index,v[1],v[2],v[3] or 2) end end end end exit({}) end) end -- fix invisible players by resetting customization every minutes --[[ Citizen.CreateThread(function() while true do Citizen.Wait(60000) if state_ready then local custom = tvRP.getCustomization() custom.model = nil custom.modelhash = nil tvRP.setCustomization(custom) end end end) --]]
Try to fix setCustomization clear weapons issue
Try to fix setCustomization clear weapons issue
Lua
mit
ImagicTheCat/vRP,ImagicTheCat/vRP,ENDrain/vRP-plusplus,ENDrain/vRP-plusplus,ENDrain/vRP-plusplus
528757522a86c6a22d987a33b7614c93555f2e79
app/post/profile.lua
app/post/profile.lua
--[[ file: app/post/profile desc: update profile ]] --modules local user, header, request, template, countries, session = luawa.user, luawa.header, luawa.request, oxy.template, require( oxy.config.root .. 'app/countries' ).iso, luawa.session --login? or invalid request (update type MUST be set) if not user:checkLogin() or not request.post.update then return header:redirect( '/' ) end --token? if not request.post.token or not session:checkToken( request.post.token ) then return template:error( 'Invalid token' ) end --update address? if request.post.update == 'address' then --make sure we have stuff if not request.post.address or not request.post.country or not countries[request.post.country] then return template:error( 'Please fill out all details' ) end --update local status, err = user:setData({ address = request.post.address, country = request.post.country }) if not status then return header:redirect( '/profile', 'error', err ) else return header:redirect( '/profile', 'success', 'Address updated' ) end --update details? else --make sure we have stuff if not request.post.name or not request.post.email then return template:error( 'Please provide an email and a name' ) elseif not request.post.email:find( '^[^@]+@' ) then return header:redirect( '/profile', 'error', 'Please use a valid email address' ) else --update local status, err = user:setData({ real_name = request.post.real_name, name = request.post.name, email = request.post.email, password = request.post.password, company = request.post.company }) if not status then return header:redirect( '/profile', 'error', err ) else return header:redirect( '/profile', 'success', 'Profile updated' ) end end end
--[[ file: app/post/profile desc: update profile ]] --modules local user, header, request, template, countries, session = luawa.user, luawa.header, luawa.request, oxy.template, require( oxy.config.root .. 'app/countries' ).iso, luawa.session --login? or invalid request (update type MUST be set) if not user:checkLogin() or not request.post.update then return header:redirect( '/' ) end --token? if not request.post.token or not session:checkToken( request.post.token ) then return template:error( 'Invalid token' ) end --update address? if request.post.update == 'address' then --make sure we have stuff if not request.post.address or not request.post.country or not countries[request.post.country] then return template:error( 'Please fill out all details' ) end --update local status, err = user:setData({ real_name = request.post.real_name, address = request.post.address, country = request.post.country }) if not status then return header:redirect( '/profile', 'error', err ) else return header:redirect( '/profile', 'success', 'Address updated' ) end --update details? else --make sure we have stuff if not request.post.name or not request.post.email then return template:error( 'Please provide an email and a name' ) elseif not request.post.email:find( '^[^@]+@' ) then return header:redirect( '/profile', 'error', 'Please use a valid email address' ) elseif request.post.phone and not tonumber( request.post.phone ) then return header:redirect( '/profile', 'error', 'Please enter a valid phone number' ) else --update local status, err = user:setData({ name = request.post.name, email = request.post.email, phone = tonumber( request.post.phone ), password = request.post.password, two_factor = request.post.two_factor == 'on' and 1 or 0 }) if not status then return header:redirect( '/profile', 'error', err ) else return header:redirect( '/profile', 'success', 'Profile updated' ) end end end
Fix bug with name saving
Fix bug with name saving
Lua
mit
Oxygem/Oxycore,Oxygem/Oxycore,Oxygem/Oxycore
15443d2f63cf88d1186f4d92f4d7ac7552b86814
src/lua-factory/sources/grl-euronews.lua
src/lua-factory/sources/grl-euronews.lua
--[[ * Copyright (C) 2014 Bastien Nocera * * Contact: Bastien Nocera <hadess@hadess.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * --]] EURONEWS_URL = 'http://euronews.hexaglobe.com/json/' --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-euronews-lua", name = "Euronews", description = "A source for watching Euronews online", supported_keys = { "id", "title", "url" }, supported_media = 'video', tags = { 'news', 'tv' } } ------------------ -- Source utils -- ------------------ function grl_source_browse(media_id) if grl.get_options("skip") > 0 then grl.callback() else grl.fetch(EURONEWS_URL, "euronews_fetch_cb") end end ------------------------ -- Callback functions -- ------------------------ -- return all the media found function euronews_fetch_cb(results) local json = {} json = grl.lua.json.string_to_table(results) if not json or json.stat == "fail" or not json.primary then grl.callback() return end for index, item in pairs(json.primary) do local media = create_media(index, item) grl.callback(media, -1) end grl.callback() end ------------- -- Helpers -- ------------- function get_lang(id) local langs = {} langs.ru = "Russian" langs.hu = "Hungarian" langs.de = "German" langs.fa = "Persian" langs.ua = "Ukrainian" langs.ar = "Arabic" langs.es = "Spanish; Castilian" langs.gr = "Greek, Modern (1453-)" langs.tr = "Turkish" langs.pe = "Persian" -- Duplicate? langs.en = "English" langs.it = "Italian" langs.fr = "French" langs.pt = "Portuguese" if not langs[id] then grl.warning('Could not find language ' .. id) return id end return grl.dgettext('iso_639', langs[id]) end function create_media(lang, item) local media = {} media.type = "video" media.id = lang media.title = "Euronews " .. get_lang(lang) media.url = item.rtmp_flash["750"].server .. item.rtmp_flash["750"].name .. " playpath=" .. item.rtmp_flash["750"].name .. " swfVfy=1 " .. "swfUrl=http://euronews.com/media/player_live_1_14.swf ".. "live=1" return media end
--[[ * Copyright (C) 2014 Bastien Nocera * * Contact: Bastien Nocera <hadess@hadess.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * --]] EURONEWS_URL = 'http://euronews.hexaglobe.com/json/' --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-euronews-lua", name = "Euronews", description = "A source for watching Euronews online", supported_keys = { "id", "title", "url" }, supported_media = 'video', tags = { 'news', 'tv' } } ------------------ -- Source utils -- ------------------ function grl_source_browse(media_id) if grl.get_options("skip") > 0 then grl.callback() else grl.fetch(EURONEWS_URL, "euronews_fetch_cb") end end ------------------------ -- Callback functions -- ------------------------ -- return all the media found function euronews_fetch_cb(results) local json = {} json = grl.lua.json.string_to_table(results) if not json or json.stat == "fail" or not json.primary then grl.callback() return end for index, item in pairs(json.primary) do local media = create_media(index, item) if media ~= nil then grl.callback(media, -1) end end grl.callback() end ------------- -- Helpers -- ------------- function get_lang(id) local langs = {} langs.ru = "Russian" langs.hu = "Hungarian" langs.de = "German" langs.fa = "Persian" langs.ua = "Ukrainian" langs.ar = "Arabic" langs.es = "Spanish; Castilian" langs.gr = "Greek, Modern (1453-)" langs.tr = "Turkish" langs.pe = "Persian" -- Duplicate? langs.en = "English" langs.it = "Italian" langs.fr = "French" langs.pt = "Portuguese" if not langs[id] then grl.warning('Could not find language ' .. id) return id end return grl.dgettext('iso_639', langs[id]) end function create_media(lang, item) local media = {} if item.rtmp_flash["750"].name == 'UNAVAILABLE' then return nil end media.type = "video" media.id = lang media.title = "Euronews " .. get_lang(lang) media.url = item.rtmp_flash["750"].server .. item.rtmp_flash["750"].name .. " playpath=" .. item.rtmp_flash["750"].name .. " swfVfy=1 " .. "swfUrl=http://euronews.com/media/player_live_1_14.swf ".. "live=1" return media end
lua-factory: Fix broken URLs for Euronews outside Europe
lua-factory: Fix broken URLs for Euronews outside Europe From some locations, Euronews will not make all of its streams available. This ensures that we filter out the streams that aren't available. https://bugzilla.gnome.org/show_bug.cgi?id=731224
Lua
lgpl-2.1
jasuarez/grilo-plugins,MathieuDuponchelle/grilo-plugins,MathieuDuponchelle/grilo-plugins,grilofw/grilo-plugins,grilofw/grilo-plugins,vrutkovs/grilo-plugins,MathieuDuponchelle/grilo-plugins,MikePetullo/grilo-plugins,vrutkovs/grilo-plugins,GNOME/grilo-plugins,vrutkovs/grilo-plugins,MathieuDuponchelle/grilo-plugins,vrutkovs/grilo-plugins,jasuarez/grilo-plugins,MikePetullo/grilo-plugins,GNOME/grilo-plugins,MikePetullo/grilo-plugins
9413f919821000f7c072247db8d1defc3ae78717
test-loop.lua
test-loop.lua
local p = require('lib/utils').prettyPrint local uv = require('luv') -- local function collectgarbage() end -- Helper to log all handles in a loop local function logHandles(loop, verbose) local handles = uv.walk(loop) if not verbose then p(loop, uv.walk(loop)) return end local data = {} for i, handle in ipairs(uv.walk(loop)) do local props = {} for key, value in pairs(handle) do props[key] = value end data[handle] = props end p(loop, data) end -- Close all handles for a given loop local function closeLoop(loop) print(loop, "Closing all handles in loop") for i, handle in ipairs(uv.walk(loop)) do print(handle, "closing...") uv.close(handle) print(handle, "closed.") end end -- Sanity check for uv_prepare_t local function testPrepare(loop, callback) local prepare = uv.new_prepare(loop) function prepare:onprepare() print("onprepare") assert(self == prepare) uv.prepare_stop(prepare) if callback then callback() end end uv.prepare_start(prepare); end -- Sanity check for uv_check_t local function testCheck(loop, callback) local check = uv.new_check(loop) function check:oncheck() print("oncheck") assert(self == check) uv.check_stop(check) if callback then callback() end end uv.check_start(check) end -- Sanity check for uv_idle_t local function testIdle(loop, callback) local idle = uv.new_idle(loop) function idle:onidle() print("onidle") assert(self == idle) uv.idle_stop(idle) if callback then callback() end end uv.idle_start(idle) end local function testAsync(loop) local async = uv.new_async(loop) function async:onasync() print("onasync") assert(self == async) end uv.async_send(async) end local function testPoll(loop) local poll = uv.new_poll(loop, 0) function poll:onpoll(err, evt) p("onpoll", err, evt) assert(self == poll) uv.poll_stop(poll) end uv.poll_start(poll, "r") p("Press Enter to test poll handler") end -- Sanity check for uv_timer_t local function testTimer(loop) local timer = uv.new_timer(loop) function timer:ontimeout() print("ontimeout 1") assert(self == timer) uv.timer_stop(timer) assert(uv.timer_get_repeat(timer) == 100) uv.timer_set_repeat(timer, 200) uv.timer_again(timer) function timer:ontimeout() print("ontimeout 2") assert(self == timer) assert(uv.timer_get_repeat(timer) == 200) uv.timer_stop(self) end end uv.timer_start(timer, 200, 100) end local function testSignal(loop, callback) local signal = uv.new_signal(loop) function signal:onsignal(name) p("onsignal", name) assert(self == signal) uv.signal_stop(signal) if callback then callback() end end uv.signal_start(signal, "SIGINT") p("Press Control+C to test signal handler") end local function testProcess(loop, callback) -- local process = assert(uv.spawn(loop, "sleep", { -- args = {1}, -- })) -- local process = assert(uv.spawn(loop, "id", { -- uid = 1000, -- gid = 1000, -- stdio = {nil,2,2} -- })) -- local process = assert(uv.spawn(loop, "pwd", { -- -- cwd = "/home/tim", -- stdio = {nil,2,2} -- })) local process = assert(uv.spawn(loop, "env", { args = {"env", "MERGED=true"}, env = {"NAME=tim", "AGE=32"}, stdio = {nil,2,2} })) function process:onexit(exit_status, term_signal) p("onexit", exit_status, term_signal) assert(self == process) if callback then callback() end end uv.disable_stdio_inheritance() end local function testTcp(loop) local server = uv.new_tcp(loop) uv.tcp_nodelay(server, true) uv.tcp_keepalive(server, true, 100); uv.tcp_simultaneous_accepts(server, false) -- uv.tcp_bind(server, "::1", 7000) uv.tcp_bind(server, "127.0.0.1", 7000) -- uv.tcp_bind(server, "::", 0) -- uv.tcp_bind(server, "0.0.0.0", 7000) uv.listen(server, 128) local address = uv.tcp_getsockname(server); p(server, { listening=address }) function server:onconnection() local client = uv.new_tcp(loop) uv.accept(server, client) p(client, { peername=uv.tcp_getpeername(client), sockname=uv.tcp_getsockname(client), }) uv.write(uv.write_req(), client, "Welcome\r\n") function client:onread(err, data) p("onread", {err=err,data=data}) if data then uv.write(uv.write_req(), client, data) uv.read_stop(client) uv.shutdown(uv.shutdown_req(), client) uv.close(client) end collectgarbage() logHandles(loop, true) end uv.read_start(client) collectgarbage() logHandles(loop, true) end local socket = uv.new_tcp(loop) uv.tcp_connect(uv.connect_req(), socket, address.ip, address.port) p(socket, { peername=uv.tcp_getpeername(socket), sockname=uv.tcp_getsockname(socket), }) collectgarbage() logHandles(loop, true) end local tests = { -- testPrepare, -- testCheck, -- testIdle, -- testAsync, -- testPoll, -- testTimer, -- testProcess, testTcp, testSignal, } coroutine.wrap(function () local loop = uv.new_loop() collectgarbage() logHandles(loop) local function onDone() closeLoop(loop) collectgarbage() logHandles(loop, true) end for i=1,#tests-1 do tests[i](loop) collectgarbage() logHandles(loop) end tests[#tests](loop, onDone) collectgarbage() logHandles(loop, true) print("blocking") uv.run(loop) print("done blocking") collectgarbage() logHandles(loop, true) uv.loop_close(loop) end)()
local p = require('lib/utils').prettyPrint local uv = require('luv') -- local function collectgarbage() end -- Helper to log all handles in a loop local function logHandles(loop, verbose) local handles = uv.walk(loop) if not verbose then p(loop, uv.walk(loop)) return end local data = {} for i, handle in ipairs(uv.walk(loop)) do local props = {} for key, value in pairs(handle) do props[key] = value end data[handle] = props end p(loop, data) end -- Close all handles for a given loop local function closeLoop(loop) print(loop, "Closing all handles in loop") for i, handle in ipairs(uv.walk(loop)) do print(handle, "closing...") uv.close(handle) print(handle, "closed.") end end -- Sanity check for uv_prepare_t local function testPrepare(loop, callback) local prepare = uv.new_prepare(loop) function prepare:onprepare() print("onprepare") assert(self == prepare) uv.prepare_stop(prepare) if callback then callback() end end uv.prepare_start(prepare); end -- Sanity check for uv_check_t local function testCheck(loop, callback) local check = uv.new_check(loop) function check:oncheck() print("oncheck") assert(self == check) uv.check_stop(check) if callback then callback() end end uv.check_start(check) end -- Sanity check for uv_idle_t local function testIdle(loop, callback) local idle = uv.new_idle(loop) function idle:onidle() print("onidle") assert(self == idle) uv.idle_stop(idle) if callback then callback() end end uv.idle_start(idle) end local function testAsync(loop) local async = uv.new_async(loop) function async:onasync() print("onasync") assert(self == async) end uv.async_send(async) end local function testPoll(loop) local poll = uv.new_poll(loop, 0) function poll:onpoll(err, evt) p("onpoll", err, evt) assert(self == poll) uv.poll_stop(poll) end uv.poll_start(poll, "r") p("Press Enter to test poll handler") end -- Sanity check for uv_timer_t local function testTimer(loop) local timer = uv.new_timer(loop) function timer:ontimeout() print("ontimeout 1") assert(self == timer) uv.timer_stop(timer) assert(uv.timer_get_repeat(timer) == 100) uv.timer_set_repeat(timer, 200) uv.timer_again(timer) function timer:ontimeout() print("ontimeout 2") assert(self == timer) assert(uv.timer_get_repeat(timer) == 200) uv.timer_stop(self) end end uv.timer_start(timer, 200, 100) end local function testSignal(loop, callback) local signal = uv.new_signal(loop) function signal:onsignal(name) p("onsignal", name) assert(self == signal) uv.signal_stop(signal) if callback then callback() end end uv.signal_start(signal, "SIGINT") p("Press Control+C to test signal handler") end local function testProcess(loop, callback) -- local process = assert(uv.spawn(loop, "sleep", { -- args = {1}, -- })) -- local process = assert(uv.spawn(loop, "id", { -- uid = 1000, -- gid = 1000, -- stdio = {nil,2,2} -- })) -- local process = assert(uv.spawn(loop, "pwd", { -- -- cwd = "/home/tim", -- stdio = {nil,2,2} -- })) local process = assert(uv.spawn(loop, "env", { args = {"env", "MERGED=true"}, env = {"NAME=tim", "AGE=32"}, stdio = {nil,2,2} })) function process:onexit(exit_status, term_signal) p("onexit", exit_status, term_signal) assert(self == process) if callback then callback() end end uv.disable_stdio_inheritance() end local function testTcp(loop) local server = uv.new_tcp(loop) uv.tcp_nodelay(server, true) uv.tcp_keepalive(server, true, 100); uv.tcp_simultaneous_accepts(server, false) -- uv.tcp_bind(server, "::1", 7000) -- uv.tcp_bind(server, "127.0.0.1", 7000) uv.tcp_bind(server, "::", 0) -- uv.tcp_bind(server, "0.0.0.0", 7000) uv.listen(server, 128) local address = uv.tcp_getsockname(server); p(server, { listening=address }) function server:onconnection() local client = uv.new_tcp(loop) uv.accept(server, client) p(client, { peername=uv.tcp_getpeername(client), sockname=uv.tcp_getsockname(client), }) uv.write(uv.write_req(), client, "Welcome\r\n") function client:onread(err, data) p("onread", {err=err,data=data}) if data then uv.write(uv.write_req(), client, data) uv.read_stop(client) uv.shutdown(uv.shutdown_req(), client) uv.close(client) end collectgarbage() logHandles(loop, true) end uv.read_start(client) collectgarbage() logHandles(loop, true) end collectgarbage() local socket = uv.new_tcp(loop) function socket:onread(err, data) p("socket onread", {err=err,data=data}) if not err and not data then uv.close(socket) end collectgarbage() end uv.read_start(socket) uv.tcp_connect(uv.connect_req(), socket, address.ip, address.port) p(socket, { peername=uv.tcp_getpeername(socket), sockname=uv.tcp_getsockname(socket), }) uv.write(uv.write_req(), socket, "Greetings\r\n") uv.shutdown(uv.shutdown_req(), socket) collectgarbage() logHandles(loop, true) end local tests = { -- testPrepare, -- testCheck, -- testIdle, -- testAsync, -- testPoll, -- testTimer, -- testProcess, testTcp, testSignal, } local loop = uv.new_loop() coroutine.wrap(function () collectgarbage() logHandles(loop) local function onDone() closeLoop(loop) collectgarbage() logHandles(loop, true) end for i=1,#tests-1 do tests[i](loop) collectgarbage() logHandles(loop) end tests[#tests](loop, onDone) collectgarbage() logHandles(loop, true) end)() collectgarbage() coroutine.wrap(function () print("blocking") uv.run(loop) print("done blocking") collectgarbage() logHandles(loop, true) uv.loop_close(loop) end)()
Fix tcp test
Fix tcp test
Lua
apache-2.0
luvit/luv,NanXiao/luv,leecrest/luv,joerg-krause/luv,xpol/luv,luvit/luv,brimworks/luv,daurnimator/luv,zhaozg/luv,mkschreder/luv,joerg-krause/luv,daurnimator/luv,zhaozg/luv,daurnimator/luv,DBarney/luv,leecrest/luv,xpol/luv,RomeroMalaquias/luv,mkschreder/luv,DBarney/luv,RomeroMalaquias/luv,kidaa/luv,NanXiao/luv,RomeroMalaquias/luv,kidaa/luv,brimworks/luv
050e1c1d4d00d1f638414b51e8183aa992b2892a
map/11record.lua
map/11record.lua
local suc, content = pcall(storm.load, '11record.txt') if suc then local names = {} --注册专属信使 messenger = {} local funcs = { ['特殊称号'] = function(line) local name, title = line:match('([%C%S]+)=([%C%S]+)') if name then names[name] = title end end, ['特殊信使'] = function(line) local name, value = line:match('([%C%S]+)=([%C%S]+)') local key if name == '名字' then messenger.who = value:split(';') for _, name in ipairs(messenger.who) do messenger[name] = {name = name} end elseif name == '信使' then key = {'uid', __id(value)} elseif name == '图标' then key = {'image', value} elseif name == '技能' then key = {'type', value == '被动' and 'skill1' or value == '主动' and 'skill2' or nil} elseif name == '标题' then key = {'title', value} elseif name == '内容' then key = {'text', value} end if key then for _, name in ipairs(messenger.who) do messenger[name][key[1]] = key[2] end end end, } local now_type for line in content:gmatch('([^\n\r]+)') do now_type = line:match('==(%C+)==') or now_type if now_type then funcs[now_type](line) end end function cmd.fresh_name(p) local base_name = p:getBaseName() if names[base_name] then local name = p:getName() name = names[base_name] .. name p:setName(name) end end --信使被动专属技能 messenger.skill1 = { |A0RK|, |A0RL|, |A0RM|, |A0RN|, |A0RO|, |A0RP|, |A0RQ|, |A0RR|, |A0RS|, |A0RT|, } --信使主动专属技能 messenger.skill2 = { |A0RI|, |A0RU|, |A0RV|, |A0RW|, |A0RX|, |A0RY|, |A0RZ|, |A0S0|, |A0S1|, |A0S2|, } function cmd.get_messenger_type(p) jass.udg_Lua_integer = |n008| local name = p:getBaseName() if messenger[name] then jass.udg_Lua_integer = messenger[name].uid end end function cmd.set_messenger_text(p, u) local name = p:getBaseName() if messenger[name] then local t = messenger[name] if t.type then local sid = messenger[t.type][p:get()] local function sub(s, t) return s:gsub('(%%%C-%%)', function(s) s = s:sub(2, -2) return t[s] end ) end u = tonumber(u) jass.UnitAddAbility(u, sid) jass.UnitMakeAbilityPermanent(u, true, sid) local ab = japi.EXGetUnitAbility(u, sid) japi.EXSetAbilityDataString(ab, 1, 204, t.image) japi.EXSetAbilityDataString(ab, 1, 215, sub(t.title, t)) japi.EXSetAbilityDataString(ab, 1, 218, sub(t.text, t)) end end end end
local suc, content = pcall(storm.load, '11record.txt') if suc then local names = {} --注册专属信使 messenger = {} local funcs = { ['特殊称号'] = function(line) local name, title = line:match('(.+)=(.+)') if name then names[name] = title end end, ['特殊信使'] = function(line) local name, value = line:match('(.+)=(.+)') local key if name == '名字' then messenger.who = value:split(';') for _, name in ipairs(messenger.who) do messenger[name] = {name = name} end elseif name == '信使' then key = {'uid', __id(value)} elseif name == '图标' then key = {'image', value} elseif name == '技能' then key = {'type', value == '被动' and 'skill1' or value == '主动' and 'skill2' or nil} elseif name == '标题' then key = {'title', value} elseif name == '内容' then key = {'text', value} end if key then for _, name in ipairs(messenger.who) do messenger[name][key[1]] = key[2] end end end, } local now_type for line in content:gmatch('([^\n\r\t]+)') do for i = 1, #line do if line:sub(i, i) ~= ' ' then line = line:sub(i) break end end for i = #line, 1, -1 do if line:sub(i, i) ~= ' ' then line = line:sub(1, i) break end end now_type = line:match('==(%C+)==') or now_type if now_type then funcs[now_type](line) end end function cmd.fresh_name(p) local base_name = p:getBaseName() if names[base_name] then local name = p:getName() name = names[base_name] .. name p:setName(name) end end --信使被动专属技能 messenger.skill1 = { |A0RK|, |A0RL|, |A0RM|, |A0RN|, |A0RO|, |A0RP|, |A0RQ|, |A0RR|, |A0RS|, |A0RT|, } --信使主动专属技能 messenger.skill2 = { |A0RI|, |A0RU|, |A0RV|, |A0RW|, |A0RX|, |A0RY|, |A0RZ|, |A0S0|, |A0S1|, |A0S2|, } function cmd.get_messenger_type(p) jass.udg_Lua_integer = |n008| local name = p:getBaseName() if messenger[name] then jass.udg_Lua_integer = messenger[name].uid end end function cmd.set_messenger_text(p, u) local name = p:getBaseName() if messenger[name] then local t = messenger[name] if t.type then local sid = messenger[t.type][p:get()] local function sub(s, t) return s:gsub('(%%%C-%%)', function(s) s = s:sub(2, -2) return t[s] end ) end u = tonumber(u) jass.UnitAddAbility(u, sid) jass.UnitMakeAbilityPermanent(u, true, sid) local ab = japi.EXGetUnitAbility(u, sid) japi.EXSetAbilityDataString(ab, 1, 204, t.image) japi.EXSetAbilityDataString(ab, 1, 215, sub(t.title, t)) japi.EXSetAbilityDataString(ab, 1, 218, sub(t.text, t)) end end end end
修正名单行首有空格会导致名字识别错误的BUG
修正名单行首有空格会导致名字识别错误的BUG
Lua
apache-2.0
syj2010syj/All-star-Battle
83c073d8275997ec48705e9e5466553835f9b895
wyx/ui/TooltipFactory.lua
wyx/ui/TooltipFactory.lua
local Class = require 'lib.hump.class' local Tooltip = getClass 'wyx.ui.Tooltip' local Text = getClass 'wyx.ui.Text' local Bar = getClass 'wyx.ui.Bar' local Frame = getClass 'wyx.ui.Frame' local Style = getClass 'wyx.ui.Style' local property = require 'wyx.component.property' local math_ceil = math.ceil local colors = colors -- some constants local MARGIN = 16 local MINWIDTH = 300 -- Common styles for tooltips local tooltipStyle = Style({ bgcolor = colors.BLACK_A85, bordersize = 4, borderinset = 4, bordercolor = colors.GREY30, }) local header1Style = Style({ font = GameFont.small, fontcolor = colors.WHITE, }) local textStyle = Style({ font = GameFont.verysmall, fontcolor = colors.GREY70, }) local iconStyle = Style({ bordersize = 4, bordercolor = colors.GREY70, bgcolor = colors.GREY10, fgcolor = colors.WHITE, }) local healthBarStyle = Style({ fgcolor = colors.RED, bgcolor = colors.DARKRED, }) -- TooltipFactory -- local TooltipFactory = Class{name='TooltipFactory', function(self) end } -- destructor function TooltipFactory:destroy() end -- make a tooltip for an entity function TooltipFactory:makeEntityTooltip(id) local entity = type(id) == 'string' and EntityRegistry:get(id) or id verifyClass('wyx.entity.Entity', entity) local name = entity:getName() local family = entity:getFamily() local kind = entity:getKind() local description = entity:getDescription() local headerW = 0 -- make the icon local icon local tileset = entity:query(property('TileSet')) if tileset then local image = Image[tileset] local allcoords = entity:query(property('TileCoords')) local coords local coords = allcoords.item or allcoords.front or allcoords.right or allcoords.left if not coords then for k in pairs(allcoords) do coords = allcoords[k]; break end end if coords then local size = entity:query(property('TileSize')) if size then local x, y = (coords[1]-1) * size, (coords[2]-1) * size icon = self:_makeIcon(image, x, y, size, size) else warning('makeEntityTooltip: bad TileSize property in entity %q', name) end else warning('makeEntityTooltip: bad TileCoords property in entity %q', name) end else warning('makeEntityTooltip: bad TileSet property in entity %q', name) end -- make the first header local header1 if name then header1 = self:_makeHeader1(name) headerW = header1:getWidth() else warning('makeEntityTooltip: bad Name for entity %q', tostring(entity)) end headerW = icon and headerW + icon:getWidth() + MARGIN or headerW local width = headerW > MINWIDTH and headerW or MINWIDTH -- make the health bar local health = entity:query(property('Health')) local maxHealth = entity:query(property('MaxHealth')) local healthBar if health and maxHealth then healthBar = Bar(0, 0, width, margin) healthBar:setNormalStyle(healthBarStyle) healthBar:setLimits(0, maxHealth) healthBar:setValue(health) end -- make the family and kind line local famLine if family and kind then local string = family..' ('..kind..')' famLine = self:_makeText(string) local width = famLine:getWidth() else warning('makeEntityTooltip: missing family or kind for entity %q', name) end -- make the stats frames -- TODO -- make the description local body if description then body = self:_makeText(description, width) else warning('makeEntityTooltip: missing description for entity %q', name) end -- make the tooltip local tooltip = Tooltip() tooltip:setNormalStyle(tooltipStyle) tooltip:setMargin(MARGIN) if icon then tooltip:setIcon(icon) end if header1 then tooltip:setHeader1(header1) end if healthBar then tooltip:addBar(healthBar) end if famLine then tooltip:addText(famLine) end if stats then for i=1,numStats do local stat = stats[i] tooltip:addText(stat) end end if body then if stats then tooltip:addSpace() end tooltip:addText(body) end return tooltip end -- make a simple generic tooltip with text function TooltipFactory:makeVerySimpleTooltip(text) verifyAny(text, 'string', 'function') local body = self:_makeText(text) local tooltip = Tooltip() tooltip:setNormalStyle(tooltipStyle) tooltip:setMargin(MARGIN) if body then tooltip:addText(body) end return tooltip end -- make a simple generic tooltip with a header and text function TooltipFactory:makeSimpleTooltip(header, text) verify('string', header) verifyAny(text, 'string', 'function') local header1 = self:_makeHeader1(header) local headerW = header1:getWidth() local width = headerW > MINWIDTH and headerW or MINWIDTH local body = self:_makeText(text, width) local tooltip = Tooltip() tooltip:setNormalStyle(tooltipStyle) tooltip:setMargin(MARGIN) if header1 then tooltip:setHeader1(header1) end if body then tooltip:addText(body) end return tooltip end -- make an icon frame function TooltipFactory:_makeIcon(image, x, y, w, h) local style = iconStyle:clone({fgimage = image}) style:setFGQuad(x, y, w, h) local icon = Frame(0, 0, w, h) icon:setNormalStyle(style, true) return icon end -- make a header1 Text frame function TooltipFactory:_makeHeader1(text) local font = header1Style:getFont() local fontH = font:getHeight() local width = font:getWidth(text) local header1 = Text(0, 0, width, fontH) header1:setNormalStyle(header1Style) header1:setText(text) return header1 end -- make a header2 Text frame function TooltipFactory:_makeHeader2(text) local font = header2Style:getFont() local fontH = font:getHeight() local width = font:getWidth(text) local header2 = Text(0, 0, width, fontH) header2:setNormalStyle(header2Style) header2:setText(text) return header2 end -- make a generic Text frame function TooltipFactory:_makeText(text, width) local isString = type(text) == 'string' local font = textStyle:getFont() local fontH = font:getHeight() local fontW = isString and font:getWidth(text) or font:getWidth(text()) width = width or fontW local numLines = math_ceil(fontW / width) local line = Text(0, 0, width, numLines * fontH) line:setMaxLines(numLines) line:setNormalStyle(textStyle) if isString then line:setText(text) else line:watch(text) end return line end -- the class return TooltipFactory
local Class = require 'lib.hump.class' local Tooltip = getClass 'wyx.ui.Tooltip' local Text = getClass 'wyx.ui.Text' local Bar = getClass 'wyx.ui.Bar' local Frame = getClass 'wyx.ui.Frame' local Style = getClass 'wyx.ui.Style' local property = require 'wyx.component.property' local math_ceil = math.ceil local colors = colors -- some constants local MARGIN = 16 local MINWIDTH = 300 -- Common styles for tooltips local tooltipStyle = Style({ bgcolor = colors.BLACK_A85, bordersize = 4, borderinset = 4, bordercolor = colors.GREY30, }) local header1Style = Style({ font = GameFont.small, fontcolor = colors.WHITE, }) local textStyle = Style({ font = GameFont.verysmall, fontcolor = colors.GREY70, }) local iconStyle = Style({ bordersize = 4, bordercolor = colors.GREY70, bgcolor = colors.GREY10, fgcolor = colors.WHITE, }) local healthBarStyle = Style({ fgcolor = colors.RED, bgcolor = colors.DARKRED, }) -- TooltipFactory -- local TooltipFactory = Class{name='TooltipFactory', function(self) end } -- destructor function TooltipFactory:destroy() end -- make a tooltip for an entity function TooltipFactory:makeEntityTooltip(id) local entity = type(id) == 'string' and EntityRegistry:get(id) or id verifyClass('wyx.entity.Entity', entity) local name = entity:getName() local family = entity:getFamily() local kind = entity:getKind() local description = entity:getDescription() local headerW = 0 -- make the icon local icon local tileset = entity:query(property('TileSet')) if tileset then local image = Image[tileset] local allcoords = entity:query(property('TileCoords')) local coords local coords = allcoords.item or allcoords.front or allcoords.right or allcoords.left if not coords then for k in pairs(allcoords) do coords = allcoords[k]; break end end if coords then local size = entity:query(property('TileSize')) if size then local x, y = (coords[1]-1) * size, (coords[2]-1) * size icon = self:_makeIcon(image, x, y, size, size) else warning('makeEntityTooltip: bad TileSize property in entity %q', name) end else warning('makeEntityTooltip: bad TileCoords property in entity %q', name) end else warning('makeEntityTooltip: bad TileSet property in entity %q', name) end -- make the first header local header1 if name then header1 = self:_makeHeader1(name) headerW = header1:getWidth() else warning('makeEntityTooltip: bad Name for entity %q', tostring(entity)) end headerW = icon and headerW + icon:getWidth() + MARGIN or headerW local width = headerW > MINWIDTH and headerW or MINWIDTH -- make the health bar local pHealth = property('Health') local pHealthB = property('HealthBonus') local pMaxHealth = property('MaxHealth') local pMaxHealthB = property('MaxHealthBonus') local health = entity:query(pHealth) local maxHealth = entity:query(pMaxHealth) local healthBar if health and maxHealth then healthBar = Bar(0, 0, width, 9) healthBar:setNormalStyle(healthBarStyle) local func = function() local h = entity:query(pHealth) + entity:query(pHealthB) local max = entity:query(pMaxHealth) + entity:query(pMaxHealthB) return h, 0, max end healthBar:watch(func) end -- make the family and kind line local famLine if family and kind then local string = family..' ('..kind..')' famLine = self:_makeText(string) local width = famLine:getWidth() else warning('makeEntityTooltip: missing family or kind for entity %q', name) end -- make the stats frames -- TODO -- make the description local body if description then body = self:_makeText(description, width) else warning('makeEntityTooltip: missing description for entity %q', name) end -- make the tooltip local tooltip = Tooltip() tooltip:setNormalStyle(tooltipStyle) tooltip:setMargin(MARGIN) if icon then tooltip:setIcon(icon) end if header1 then tooltip:setHeader1(header1) end if healthBar then tooltip:addBar(healthBar) tooltip:addSpace() end if famLine then tooltip:addText(famLine) end if stats then for i=1,numStats do local stat = stats[i] tooltip:addText(stat) end end if body then if stats then tooltip:addSpace() end tooltip:addText(body) end return tooltip end -- make a simple generic tooltip with text function TooltipFactory:makeVerySimpleTooltip(text) verifyAny(text, 'string', 'function') local body = self:_makeText(text) local tooltip = Tooltip() tooltip:setNormalStyle(tooltipStyle) tooltip:setMargin(MARGIN) if body then tooltip:addText(body) end return tooltip end -- make a simple generic tooltip with a header and text function TooltipFactory:makeSimpleTooltip(header, text) verify('string', header) verifyAny(text, 'string', 'function') local header1 = self:_makeHeader1(header) local headerW = header1:getWidth() local width = headerW > MINWIDTH and headerW or MINWIDTH local body = self:_makeText(text, width) local tooltip = Tooltip() tooltip:setNormalStyle(tooltipStyle) tooltip:setMargin(MARGIN) if header1 then tooltip:setHeader1(header1) end if body then tooltip:addText(body) end return tooltip end -- make an icon frame function TooltipFactory:_makeIcon(image, x, y, w, h) local style = iconStyle:clone({fgimage = image}) style:setFGQuad(x, y, w, h) local icon = Frame(0, 0, w, h) icon:setNormalStyle(style, true) return icon end -- make a header1 Text frame function TooltipFactory:_makeHeader1(text) local font = header1Style:getFont() local fontH = font:getHeight() local width = font:getWidth(text) local header1 = Text(0, 0, width, fontH) header1:setNormalStyle(header1Style) header1:setText(text) return header1 end -- make a header2 Text frame function TooltipFactory:_makeHeader2(text) local font = header2Style:getFont() local fontH = font:getHeight() local width = font:getWidth(text) local header2 = Text(0, 0, width, fontH) header2:setNormalStyle(header2Style) header2:setText(text) return header2 end -- make a generic Text frame function TooltipFactory:_makeText(text, width) local isString = type(text) == 'string' local font = textStyle:getFont() local fontH = font:getHeight() local fontW = isString and font:getWidth(text) or font:getWidth(text()) width = width or fontW local numLines = math_ceil(fontW / width) local line = Text(0, 0, width, numLines * fontH) line:setMaxLines(numLines) line:setNormalStyle(textStyle) if isString then line:setText(text) else line:watch(text) end return line end -- the class return TooltipFactory
fix healthbar
fix healthbar
Lua
mit
scottcs/wyx
278807162bdf58a1c56db60581a0ed224d3dd475
src/lib/yang/util.lua
src/lib/yang/util.lua
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(..., package.seeall) local lib = require("core.lib") local ffi = require("ffi") local ipv4 = require("lib.protocol.ipv4") ffi.cdef([[ unsigned long long strtoull (const char *nptr, const char **endptr, int base); ]]) function tointeger(str, what, min, max) if not what then what = 'integer' end local str = assert(str, 'missing value for '..what) local start = 1 local is_negative local base = 10 if str:match('^-') then start, is_negative = 2, true elseif str:match('^+') then start = 2 end if str:match('^0x', start) then base, start = 16, start + 2 elseif str:match('^0', start) then base = 8 end str = str:lower() local function check(test) return assert(test, 'invalid numeric value for '..what..': '..str) end check(start <= str:len()) -- FIXME: check that res did not overflow the 64-bit number local res = ffi.C.strtoull(str:sub(start), nil, base) if is_negative then res = ffi.new('int64_t[1]', -1*res)[0] check(res <= 0) if min then check(min <= 0 and min <= res) end else -- Only compare min and res if both are positive, otherwise if min -- is a negative int64_t then the comparison will treat it as a -- large uint64_t. if min then check(min <= 0 or min <= res) end end if max then check(res <= max) end -- Only return Lua numbers for values within int32 + uint32 range. if -0x8000000 <= res and res <= 0xffffffff then return tonumber(res) end return res end function ffi_array(ptr, elt_t, count) local mt = {} local size = count or ffi.sizeof(ptr)/ffi.sizeof(elt_t) function mt:__len() return size end function mt:__index(idx) assert(1 <= idx and idx <= size) return ptr[idx-1] end function mt:__newindex(idx, val) assert(1 <= idx and idx <= size) ptr[idx-1] = val end function mt:__ipairs() local idx = -1 return function() idx = idx + 1 if idx >= size then return end return idx+1, ptr[idx] end end return ffi.metatype(ffi.typeof('struct { $* ptr; }', elt_t), mt)(ptr) end -- The yang modules represent IPv4 addresses as host-endian uint32 -- values in Lua. See https://github.com/snabbco/snabb/issues/1063. function ipv4_pton(str) return lib.ntohl(ffi.cast('uint32_t*', assert(ipv4:pton(str)))[0]) end function ipv4_ntop(addr) return ipv4:ntop(ffi.new('uint32_t[1]', lib.htonl(addr))) end function selftest() print('selftest: lib.yang.util') assert(tointeger('0') == 0) assert(tointeger('-0') == 0) assert(tointeger('10') == 10) assert(tointeger('-10') == -10) assert(tointeger('010') == 8) assert(tointeger('-010') == -8) assert(tointeger('0xffffffff') == 0xffffffff) assert(tointeger('0xffffffffffffffff') == 0xffffffffffffffffULL) assert(tointeger('0x7fffffffffffffff') == 0x7fffffffffffffffULL) assert(tointeger('0xffffffffffffffff') == 0xffffffffffffffffULL) assert(tointeger('-0x7fffffffffffffff') == -0x7fffffffffffffffLL) assert(tointeger('-0x8000000000000000') == -0x8000000000000000LL) assert(ipv4_pton('255.0.0.1') == 255 * 2^24 + 1) assert(ipv4_ntop(ipv4_pton('255.0.0.1')) == '255.0.0.1') print('selftest: ok') end
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(..., package.seeall) local lib = require("core.lib") local ffi = require("ffi") local ipv4 = require("lib.protocol.ipv4") ffi.cdef([[ unsigned long long strtoull (const char *nptr, const char **endptr, int base); ]]) function tointeger(str, what, min, max) if not what then what = 'integer' end local str = assert(str, 'missing value for '..what) local start = 1 local is_negative local base = 10 if str:match('^-') then start, is_negative = 2, true elseif str:match('^+') then start = 2 end if str:match('^0x', start) then base, start = 16, start + 2 elseif str:match('^0', start) then base = 8 end str = str:lower() local function check(test) return assert(test, 'invalid numeric value for '..what..': '..str) end check(start <= str:len()) -- FIXME: check that res did not overflow the 64-bit number local res = ffi.C.strtoull(str:sub(start), nil, base) if is_negative then res = ffi.new('int64_t[1]', -1*res)[0] check(res <= 0) if min then check(min <= 0 and min <= res) end else -- Only compare min and res if both are positive, otherwise if min -- is a negative int64_t then the comparison will treat it as a -- large uint64_t. if min then check(min <= 0 or min <= res) end end if max then check(res <= max) end -- Only return Lua numbers for values within int32 + uint32 range. -- The 0 <= res check is needed because res might be a uint64, in -- which case comparing to a negative Lua number will cast that Lua -- number to a uint64 :-(( if (0 <= res or -0x8000000 <= res) and res <= 0xffffffff then return tonumber(res) end return res end function ffi_array(ptr, elt_t, count) local mt = {} local size = count or ffi.sizeof(ptr)/ffi.sizeof(elt_t) function mt:__len() return size end function mt:__index(idx) assert(1 <= idx and idx <= size) return ptr[idx-1] end function mt:__newindex(idx, val) assert(1 <= idx and idx <= size) ptr[idx-1] = val end function mt:__ipairs() local idx = -1 return function() idx = idx + 1 if idx >= size then return end return idx+1, ptr[idx] end end return ffi.metatype(ffi.typeof('struct { $* ptr; }', elt_t), mt)(ptr) end -- The yang modules represent IPv4 addresses as host-endian uint32 -- values in Lua. See https://github.com/snabbco/snabb/issues/1063. function ipv4_pton(str) return lib.ntohl(ffi.cast('uint32_t*', assert(ipv4:pton(str)))[0]) end function ipv4_ntop(addr) return ipv4:ntop(ffi.new('uint32_t[1]', lib.htonl(addr))) end function selftest() print('selftest: lib.yang.util') assert(tointeger('0') == 0) assert(tointeger('-0') == 0) assert(tointeger('10') == 10) assert(tostring(tointeger('10')) == '10') assert(tointeger('-10') == -10) assert(tointeger('010') == 8) assert(tointeger('-010') == -8) assert(tointeger('0xffffffff') == 0xffffffff) assert(tointeger('0xffffffffffffffff') == 0xffffffffffffffffULL) assert(tointeger('0x7fffffffffffffff') == 0x7fffffffffffffffULL) assert(tointeger('0xffffffffffffffff') == 0xffffffffffffffffULL) assert(tointeger('-0x7fffffffffffffff') == -0x7fffffffffffffffLL) assert(tointeger('-0x8000000000000000') == -0x8000000000000000LL) assert(ipv4_pton('255.0.0.1') == 255 * 2^24 + 1) assert(ipv4_ntop(ipv4_pton('255.0.0.1')) == '255.0.0.1') print('selftest: ok') end
Fix integer parsing bug in yang
Fix integer parsing bug in yang
Lua
apache-2.0
eugeneia/snabbswitch,Igalia/snabb,snabbco/snabb,Igalia/snabb,dpino/snabb,dpino/snabb,dpino/snabbswitch,eugeneia/snabb,Igalia/snabb,eugeneia/snabb,alexandergall/snabbswitch,snabbco/snabb,eugeneia/snabbswitch,eugeneia/snabb,heryii/snabb,dpino/snabb,eugeneia/snabb,SnabbCo/snabbswitch,heryii/snabb,Igalia/snabb,Igalia/snabbswitch,alexandergall/snabbswitch,eugeneia/snabbswitch,SnabbCo/snabbswitch,Igalia/snabbswitch,dpino/snabb,eugeneia/snabbswitch,snabbco/snabb,Igalia/snabbswitch,heryii/snabb,snabbco/snabb,SnabbCo/snabbswitch,Igalia/snabbswitch,alexandergall/snabbswitch,alexandergall/snabbswitch,eugeneia/snabb,dpino/snabb,snabbco/snabb,Igalia/snabbswitch,snabbco/snabb,dpino/snabbswitch,eugeneia/snabb,alexandergall/snabbswitch,heryii/snabb,heryii/snabb,Igalia/snabb,dpino/snabbswitch,alexandergall/snabbswitch,Igalia/snabb,dpino/snabb,heryii/snabb,Igalia/snabb,snabbco/snabb,dpino/snabb,SnabbCo/snabbswitch,eugeneia/snabb,snabbco/snabb,eugeneia/snabb,dpino/snabbswitch,Igalia/snabb,alexandergall/snabbswitch,alexandergall/snabbswitch
340da5d552067b8a1738091f6a24b42ff07323b7
src/lua-factory/sources/grl-euronews.lua
src/lua-factory/sources/grl-euronews.lua
--[[ * Copyright (C) 2014 Bastien Nocera * * Contact: Bastien Nocera <hadess@hadess.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * --]] LANG_EN = "en" EURONEWS_URL = 'https://%s.euronews.com/api/watchlive.json' local langs = { arabic = "Arabic", de = "German", en = "English", es = "Spanish; Castilian", fa = "Persian", fr = "French", gr = "Greek, Modern (1453-)", hu = "Hungarian", it = "Italian", pt = "Portuguese", ru = "Russian", tr = "Turkish", } local num_callbacks = 0 --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-euronews-lua", name = "Euronews", description = "A source for watching Euronews online", supported_keys = { "id", "title", "url" }, supported_media = 'video', icon = 'resource:///org/gnome/grilo/plugins/euronews/euronews.svg', tags = { 'news', 'tv', 'net:internet', 'net:plaintext' } } ------------------ -- Source utils -- ------------------ function grl_source_browse(media_id) if grl.get_options("skip") > 0 then grl.callback() return end for lang in pairs(langs) do num_callbacks = num_callbacks + 1 end for lang in pairs(langs) do local api_url = get_api_url(lang) grl.fetch(api_url, euronews_initial_fetch_cb, lang) end end ------------------------ -- Callback functions -- ------------------------ function euronews_initial_fetch_cb(results, lang) local json = {} json = grl.lua.json.string_to_table(results) if not json or not json.url then local api_url = get_api_url(lang) grl.warning ("Initial fetch failed for: " .. api_url) callback_done() return end local streaming_lang = json.url:match("://euronews%-(..)%-p%-api") if lang ~= LANG_EN and streaming_lang == LANG_EN then grl.debug("Skipping " .. langs[lang] .. " as it redirects to " .. langs[LANG_EN] .. " stream.") callback_done() return end grl.fetch("https:" .. json.url, euronews_fetch_cb, lang) end -- return all the media found function euronews_fetch_cb(results, lang) local json = {} json = grl.lua.json.string_to_table(results) if not json or json.status ~= "ok" or not json.primary then local api_url = get_api_url(lang) grl.warning("Fetch failed for: " .. api_url) callback_done() return end local media = create_media(lang, json) if media ~= nil then grl.callback(media, -1) end callback_done() end ------------- -- Helpers -- ------------- function callback_done() num_callbacks = num_callbacks - 1 -- finalize operation if num_callbacks == 0 then grl.callback() end end function get_api_url(id) if not langs[id] then grl.warning('Could not find language ' .. id) return id end return string.format(EURONEWS_URL, id == LANG_EN and "www" or id) end function get_lang(id) if not langs[id] then grl.warning('Could not find language ' .. id) return id end return grl.dgettext('iso_639', langs[id]) end function create_media(lang, item) local media = {} media.type = "video" media.id = lang media.title = "Euronews " .. get_lang(lang) media.url = item.primary return media end
--[[ * Copyright (C) 2014 Bastien Nocera * * Contact: Bastien Nocera <hadess@hadess.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * --]] LANG_EN = "en" EURONEWS_URL = 'https://%s.euronews.com/api/watchlive.json' local langs = { arabic = "Arabic", de = "German", en = "English", es = "Spanish; Castilian", fa = "Persian", fr = "French", gr = "Greek, Modern (1453-)", hu = "Hungarian", it = "Italian", pt = "Portuguese", ru = "Russian", tr = "Turkish", } local num_callbacks = 0 --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-euronews-lua", name = "Euronews", description = "A source for watching Euronews online", supported_keys = { "id", "title", "url" }, supported_media = 'video', icon = 'resource:///org/gnome/grilo/plugins/euronews/euronews.svg', tags = { 'news', 'tv', 'net:internet', 'net:plaintext' } } ------------------ -- Source utils -- ------------------ function grl_source_browse(media_id) if grl.get_options("skip") > 0 then grl.callback() return end for lang in pairs(langs) do num_callbacks = num_callbacks + 1 end for lang in pairs(langs) do local api_url = get_api_url(lang) grl.fetch(api_url, euronews_initial_fetch_cb, lang) end end ------------------------ -- Callback functions -- ------------------------ function euronews_initial_fetch_cb(results, lang) local json = {} json = grl.lua.json.string_to_table(results) -- pfp: youtube, uses videoId for url -- jw: will provide an url to request video if not json or (json.player ~= "pfp" and json.player ~= "jw") or (json.player == "pfp" and not json.videoId) or (json.player == "jw" and not json.url) then local api_url = get_api_url(lang) grl.warning ("Initial fetch failed for: " .. api_url) callback_done() return end if json.player == "pfp" then item = {} item.primary = string.format("https://www.youtube.com/watch?v=%s", json.videoId) local media = create_media(lang, item) if media ~= nil then grl.callback(media, -1) end callback_done() return end local streaming_lang = json.url:match("://euronews%-(..)%-p%-api") if lang ~= LANG_EN and streaming_lang == LANG_EN then grl.debug("Skipping " .. langs[lang] .. " as it redirects to " .. langs[LANG_EN] .. " stream.") callback_done() return end grl.fetch("https:" .. json.url, euronews_fetch_cb, lang) end -- return all the media found function euronews_fetch_cb(results, lang) local json = {} json = grl.lua.json.string_to_table(results) if not json or json.status ~= "ok" or not json.primary then local api_url = get_api_url(lang) grl.warning("Fetch failed for: " .. api_url) callback_done() return end local media = create_media(lang, json) if media ~= nil then grl.callback(media, -1) end callback_done() end ------------- -- Helpers -- ------------- function callback_done() num_callbacks = num_callbacks - 1 -- finalize operation if num_callbacks == 0 then grl.callback() end end function get_api_url(id) if not langs[id] then grl.warning('Could not find language ' .. id) return id end return string.format(EURONEWS_URL, id == LANG_EN and "www" or id) end function get_lang(id) if not langs[id] then grl.warning('Could not find language ' .. id) return id end return grl.dgettext('iso_639', langs[id]) end function create_media(lang, item) local media = {} media.type = "video" media.id = lang media.title = "Euronews " .. get_lang(lang) media.url = item.primary return media end
euronews: adapt url to YouTube feeds
euronews: adapt url to YouTube feeds Euronews seemed to have migrated to YouTube for most of its content. At this moment, from the previous list of Feeds, only Persian is not exclusive YouTube. This patch uses the videoId provided by euronews to create an YouTube url. Fixes: https://gitlab.gnome.org/GNOME/grilo-plugins/-/issues/78
Lua
lgpl-2.1
GNOME/grilo-plugins,GNOME/grilo-plugins
5f4f1ddb6f07c0e4bcf207bcc4b9a0046e9c6241
bin/guard.lua
bin/guard.lua
#!/usr/bin/lua -- This is script that runs periodically to validate -- iptables (-t mangle) allowed_guests chain against -- sessions table stored in database. local dirname = string.gsub(arg[0], "(.*)/(.*)", "%1"); package.path = package.path .. ";" .. dirname .. "/../vendor/?.lua;" .. dirname .. "/../backend/?.lua"; -- bootstrap application (to have database), but not run require "application".bootstrap(dirname .. "/../backend"); local Session = require "models.session"; local Arp = require "models.arp"; io.stdout:write("Validating guest sessions.\n"); -- iterate through rules local currentRules = io.popen("iptables -t mangle -vL allowed_guests"); for rule in currentRules:lines() do -- grab some basic metrics local outgoingPkts, outgoingBytes, macAddress = rule:match("%s*(%d+)%s+(%d+).-MAC%s+(%S+)"); -- perform checks in pcall to catch errors local status, error = pcall(function(mac, pkts, bytes) if mac then local session = Session.new(mac); if session then -- check if session is still valid if session.expires <= os.time() then -- session expired, delete session:delete(); return 0; end -- if IP has been changed, then something is wrong and probably -- someone is spoofing MAC address to gain network access local currentIp = Arp.findIpByMac(mac); if (currentIp and currentIp ~= session.ip) then -- ip conflict, delete session io.stdout:write("IP address recorded in session does not match current. Deleting session.\n"); io.stdout:write("Current IP: " .. currentIp .. ", Recorder IP: " .. session.ip .. "\n"); io.stdout:write("Current MAC: " .. mac .. ", Recorder MAC: " .. session.mac .. "\n"); session:delete(); return 0; end -- if traffic was recorded for given session, extend it's validity -- for another day, if pkts > session.pkts then io.stdout:write("Extending session lifetime for " .. session.mac .. " (" .. session.ip .. ")\n"); session:updateCounters(pkts, bytes); session:extend(); end else -- session does not exist, immediately delete rule! io.stdout:write("Session for mac address <" .. mac .. "> does not exist, deleting...\n"); assert( os.execute("iptables -t mangle -D allowed_guests -m mac --mac-source " .. mac .. " -j MARK --set-mark 0x2") ); return 0; end end end, macAddress, tonumber(outgoingPkts), tonumber(outgoingBytes)); if not status then io.stderr:write(error .. "\n"); end -- delete all expired sessions left Session.clearExpired(); end return 0;
#!/usr/bin/lua -- This is script that runs periodically to validate -- iptables (-t mangle) allowed_guests chain against -- sessions table stored in database. local dirname = string.gsub(arg[0], "(.*)/(.*)", "%1"); package.path = package.path .. ";" .. dirname .. "/../vendor/?.lua;" .. dirname .. "/../backend/?.lua"; -- bootstrap application (to have database), but not run require "application".bootstrap(dirname .. "/../backend"); local Session = require "models.session"; local Arp = require "models.arp"; io.stdout:write("Validating guest sessions.\n"); -- iterate through rules local currentRules = io.popen("iptables -t mangle -xnvL allowed_guests"); for rule in currentRules:lines() do -- grab some basic metrics local outgoingPkts, outgoingBytes, macAddress = rule:match("%s*(%d+)%s+(%d+).-MAC%s+(%S+)"); -- perform checks in pcall to catch errors local status, error = pcall(function(mac, pkts, bytes) if mac then io.stdout:write("Validatig " .. assert(mac) .. "\n"); local session = Session.new(mac); if session then -- check if session is still valid if session.expires <= os.time() then -- session expired, delete session:delete(); return 0; end -- if IP has been changed, then something is wrong and probably -- someone is spoofing MAC address to gain network access local currentIp = Arp.findIpByMac(mac); if (currentIp and currentIp ~= session.ip) then -- ip conflict, delete session io.stdout:write("IP address recorded in session does not match current. Deleting session.\n"); io.stdout:write("Current IP: " .. currentIp .. ", Recorder IP: " .. session.ip .. "\n"); io.stdout:write("Current MAC: " .. mac .. ", Recorder MAC: " .. session.mac .. "\n"); session:delete(); return 0; end -- if traffic was recorded for given session, extend it's validity -- for another day, if pkts > session.pkts then io.stdout:write("Extending session lifetime for " .. session.mac .. " (" .. session.ip .. ")\n"); session:updateCounters(pkts, bytes); session:extend(); end else -- session does not exist, immediately delete rule! io.stdout:write("Session for mac address <" .. mac .. "> does not exist, deleting...\n"); assert( os.execute("iptables -t mangle -D allowed_guests -m mac --mac-source " .. mac .. " -j MARK --set-mark 0x2") ); return 0; end end end, macAddress, tonumber(outgoingPkts), tonumber(outgoingBytes)); if not status then io.stderr:write(error .. "\n"); end -- delete all expired sessions left Session.clearExpired(); end return 0;
Fixed issues with guard & big iptables counters.
Fixed issues with guard & big iptables counters.
Lua
mit
pamelus/lua-captive-portal,pamelus/lua-captive-portal,pamelus/lua-captive-portal,pamelus/lua-captive-portal
1745133e797a2f96431b61d156cbdc32fbd4a00a
lib/switchboard_modules/lua_script_debugger/premade_scripts/counter_examples/quadrature_input_large_integers.lua
lib/switchboard_modules/lua_script_debugger/premade_scripts/counter_examples/quadrature_input_large_integers.lua
--Title: quadrature_input_large_integers.lua --Purpose: Program for handling quadrature input counts that overflow 32 bit floats by -- tracking and reporting counts in two registers. --Note: Could modify with the DIO0_EF_READ_AF register for float mode --Note: Does not take into effect counter-clockwise revolutions or two''s complement conversion print("quadrature_input_large_integers.lua") devType = MB.R(60000, 3) efReadAReg = 0 efReadAAndResetReg = 0 if(devType == 7) then print("T7: Enabling quadrature input on DIO0 and DIO1") --Formatting for quadrature input MB.W(44000, 1, 0) --disable DIO0 MB.W(44002, 1, 0) --disable DIO1 MB.W(44100, 1, 10) --set DIO0 index MB.W(44102, 1, 10) --set DIO1 index MB.W(44000, 1, 1) --enable DIO0 for phase A MB.W(44002, 1, 1) --enable DIO1 for phase B efReadAReg = 3000 efReadAAndResetReg = 3100 else if(devType == 4) then print("T4: Enabling quadrature input on DIO4 and DIO5") --Formatting for quadrature input MB.W(44008, 1, 0) --disable DIO0 MB.W(44010, 1, 0) --disable DIO1 MB.W(44108, 1, 10) --set DIO0 index MB.W(44110, 1, 10) --set DIO1 index MB.W(44008, 1, 1) --enable DIO0 for phase A MB.W(44010, 1, 1) --enable DIO1 for phase B efReadAReg = 3008 efReadAAndResetReg = 3108 end LJ.IntervalConfig(0, 500) --Update data every half second newcount = 0 --Number used to store the new value polled from the LabJack register lownum = 0 --Number used to keep the higher precision lower 22 bits of the number residual = 0 --Number used to store the residual number of counts after conversion multiplier = 0 --Number used to store how many multiples of 2^22 have been reached while true do --Can take out CheckInterval or make very low for ~continuous data polling if LJ.CheckInterval(0) then lownum = MB.R(efReadAReg, 1) + residual --Read DIO0_EF_READ_A register & combine w/ any residual from last conversion --Once the register has a number of counts large enough that the precision could be comprimised, (greater than 22 bits) --convert by resetting the register and split it into separate values if (math.abs(lownum) >= 2^22) then lownum = MB.R(efReadAAndResetReg, 1) + residual --Read and reset DIO0_EF_READ_A register to zero if(math.abs(lownum) > 2^23) then print("Quadrature count precision loss detected") end multiplier = multiplier + math.floor(lownum/2^22) --save how many multiples of 2^22 of counts have occured residual = (lownum) % 2^22 --store number of residual counts lownum = residual --Prepare to store residual end --Save the number of counts to USER_RAM0_U32 and USER_RAM1_U32 MB.W(46100,1,lownum) MB.W(46102,1,multiplier) --Now, to get the full number of counts from an external application: -- counts = (2^22 * USER_RAM1_U32) + USER_RAM0_U32 --USER_RAM1_U32 can now also be used as a boolean register to see weather an overflow (>=2^22) has occurred end end
--[[ Name: quadrature_input_large_integers.lua Desc: Program for handling quadrature input counts that overflow 32 bit floats by tracking and reporting counts in two registers Note: Could modify with the DIO0_EF_READ_AF register for float mode Does not take into effect counter-clockwise revolutions or two's complement conversion --]] -- For sections of code that require precise timing assign global functions -- locally (local definitions of globals are marginally faster) local check_interval = LJ.CheckInterval local modbus_read = MB.R local modbus_write = MB.W print("quadrature_input_large_integers.lua") -- Get the device type by reading the PRODUCT_ID register devtype = modbus_read(60000, 3) efreadreg = 0 efreadresetreg = 0 if(devtype == 7) then print("T7: Enabling quadrature input on DIO0 and DIO1") -- Formatting for quadrature input if using a T7 -- Disable DIO0 modbus_write(44000, 1, 0) -- Disable DIO1 modbus_write(44002, 1, 0) -- Set DIO0_EF_INDEX to 10 (use the quadrature in feature) modbus_write(44100, 1, 10) -- Set DIO1_EF_INDEX to 10 (use the quadrature in feature) modbus_write(44102, 1, 10) -- Enable DIO0 for phase A modbus_write(44000, 1, 1) -- Enable DIO1 for phase B modbus_write(44002, 1, 1) -- Use DIO0_EF_READ_A to read the input count as a signed 2's complement value efreadreg = 3000 -- Use DIO0_EF_READ_A_AND_RESET (same as DIO0_EF_READ_A but it resets the -- count back to 0 after getting the input value) efreadresetreg = 3100 else if(devtype == 4) then print("T4: Enabling quadrature input on DIO4 and DIO5") -- Formatting for quadrature input if using a T4 -- Disable DIO4 modbus_write(44008, 1, 0) -- Disable DIO5 modbus_write(44010, 1, 0) -- Set DIO4_EF_INDEX to 10 (use the quadrature in feature) modbus_write(44108, 1, 10) -- Set DIO5_EF_INDEX to 10 (use the quadrature in feature) modbus_write(44110, 1, 10) -- Enable DIO4 for phase A modbus_write(44008, 1, 1) -- Enable DIO5 for phase B modbus_write(44010, 1, 1) -- Use DIO4_EF_READ_A to read the input count as a signed 2's complement value efreadreg = 3008 -- Use DIO4_EF_READ_A_AND_RESET (same as DIO4_EF_READ_A but it resets the -- count back to 0 after getting the input value) efreadresetreg = 3108 end -- Update data every 500ms LJ.IntervalConfig(0, 500) -- Number used to store the new value polled from the LabJack register newcount = 0 -- Number used to keep the higher precision lower 22 bits of the number lownum = 0 -- Number used to store the residual number of counts after conversion residual = 0 -- Number used to store how many multiples of 2^22 have been reached multiplier = 0 while true do -- It is possible to take out CheckInterval or make the interval very small -- for nearly continuous data polling if check_interval(0) then -- Read the DIO#_EF_READ_A register and combine it with any residual from -- the last conversion lownum = modbus_read(efreadreg, 1) + residual -- Once the register has a number of counts large enough that the -- precision could be compromised (greater than 22 bits), convert by -- resetting the register and split it into separate values if (math.abs(lownum) >= 2^22) then -- Read and reset the count to zero by reading the -- DIO#_EF_READ_A_AND_RESET register lownum = modbus_read(efreadresetreg, 1) + residual if(math.abs(lownum) > 2^23) then print("Quadrature count precision loss detected") end -- Save how many multiples of 2^22 of counts have occurred multiplier = multiplier + math.floor(lownum/2^22) -- Get the number of residual counts residual = (lownum) % 2^22 -- Prepare to store the residual lownum = residual end -- Save the number of counts to USER_RAM0_U32 and USER_RAM1_U32 modbus_write(46100,1,lownum) modbus_write(46102,1,multiplier) -- To get the full number of counts from an external application: -- counts = (2^22 * USER_RAM1_U32) + USER_RAM0_U32 -- USER_RAM1_U32 can now also be used as a boolean register to see whether -- an overflow (data>=2^22) has occurred end end
Fixed up the formatting quadrature with large integers example
Fixed up the formatting quadrature with large integers example
Lua
mit
chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager
6c940e63890c22d2e2c0eb19b130e8bfc8993157
core/lfs_ext.lua
core/lfs_ext.lua
-- Copyright 2007-2018 Mitchell mitchell.att.foicica.com. See LICENSE. --[[ This comment is for LuaDoc. --- -- Extends the `lfs` library to find files in directories and determine absolute -- file paths. module('lfs')]] --- -- The filter table containing common binary file extensions and version control -- directories to exclude when iterating over files and directories using -- `dir_foreach`. -- @see dir_foreach -- @class table -- @name default_filter lfs.default_filter = { -- File extensions to exclude. '!.a', '!.bmp', '!.bz2', '!.class', '!.dll', '!.exe', '!.gif', '!.gz', '!.jar', '!.jpeg', '!.jpg', '!.o', '!.pdf', '!.png', '!.so', '!.tar', '!.tgz', '!.tif', '!.tiff', '!.xz', '!.zip', -- Directories to exclude. '!/%.bzr$', '!/%.git$', '!/%.hg$', '!/%.svn$', '!/node_modules$', --[[Temporary backwards-compatibility]]extensions={'a','bmp','bz2','class','dll','exe','gif','gz','jar','jpeg','jpg','o','pdf','png','so','tar','tgz','tif','tiff','xz','zip'},folders={'%.bzr$','%.git$','%.hg$','%.svn$','node_modules'} } --- -- Iterates over all files and sub-directories (up to *n* levels deep) in -- directory *dir*, calling function *f* with each file found. -- String or list *filter* determines which files to pass through to *f*, with -- the default filter being `lfs.default_filter`. A filter consists of Lua -- patterns that match file and directory paths to include or exclude. Exclusive -- patterns begin with a '!'. If no inclusive patterns are given, any path is -- initially considered. As a convenience, file extensions can be specified -- literally instead of as a Lua pattern (e.g. '.lua' vs. '%.lua$'), and '/' -- also matches the Windows directory separator ('[/\\]' is not needed). -- @param dir The directory path to iterate over. -- @param f Function to call with each full file path found. If *f* returns -- `false` explicitly, iteration ceases. -- @param filter Optional filter for files and directories to include and -- exclude. The default value is `lfs.default_filter`. -- @param n Optional maximum number of directory levels to descend into. -- The default value is `nil`, which indicates no limit. -- @param include_dirs Optional flag indicating whether or not to call *f* with -- directory names too. Directory names are passed with a trailing '/' or '\', -- depending on the current platform. -- The default value is `false`. -- @param level Utility value indicating the directory level this function is -- at. This value is used and set internally, and should not be set otherwise. -- @see filter -- @name dir_foreach function lfs.dir_foreach(dir, f, filter, n, include_dirs, level) if not level then -- Convert filter to a table from nil or string arguments. if not filter then filter = lfs.default_filter end if type(filter) == 'string' then filter = {filter} end --[[Temporary backwards-compatibility.]]if filter.extensions and filter~=lfs.default_filter then;local compat_filter={};ui.dialogs.textbox{title='Compatibility Notice',informative_text='Warning: use of deprecated filter format; please update your scripts',text=debug.traceback()};for i=1,#filter do if filter[i]:find('^!')then compat_filter[i]=filter[i]:sub(2)else compat_filter[i]='!'..filter[i]end end;for i=1,#filter.extensions do compat_filter[#compat_filter+1]='!.'..filter.extensions[i]end;if filter.folders then for i=1,#filter.folders do; compat_filter[#compat_filter+1]='!'..filter.folders[i]:gsub('^%%.[^.]+%$$','[/\\]%0')end end;filter = compat_filter;end -- Process the given filter into something that can match files more easily -- and/or quickly. For example, convert '.ext' shorthand to '%.ext$', -- substitute '/' with '[/\\]', and enable hash lookup for file extensions -- to include or exclude. local processed_filter = {consider_any = true, exts = {}} for i = 1, #filter do local patt = filter[i] patt = patt:gsub('^(!?)%%?%.([^.]+)$', '%1%%.%2$') -- '.lua' to '%.lua$' patt = patt:gsub('/([^\\])', '[/\\]%1') -- '/' to '[/\\]' if not patt:find('^!') then processed_filter.consider_any = false end local ext = patt:match('^!?%%.([^.]+)%$$') if ext then processed_filter.exts[ext] = patt:find('^!') and 'exclude' or 'include' else processed_filter[#processed_filter + 1] = patt end end filter = processed_filter end local dir_sep, lfs_attributes = not WIN32 and '/' or '\\', lfs.attributes for basename in lfs.dir(dir) do if not basename:find('^%.%.?$') then -- ignore . and .. local filename = dir..(dir ~= '/' and dir_sep or '')..basename local mode = lfs_attributes(filename, 'mode') if mode ~= 'directory' and mode ~= 'file' then goto skip end local include if mode == 'file' then local ext = filename:match('[^.]+$') if ext and filter.exts[ext] == 'exclude' then goto skip end include = filter.consider_any or ext and filter.exts[ext] == 'include' elseif mode == 'directory' then include = filter.consider_any or #filter == 0 end for i = 1, #filter do local patt = filter[i] -- Treat exclusive patterns as logical AND. if patt:find('^!') and filename:find(patt:sub(2)) then goto skip end -- Treat inclusive patterns as logical OR. include = include or (not patt:find('^!') and filename:find(patt)) end if include and mode == 'directory' then if include_dirs and f(filename..dir_sep) == false then return end if not n or (level or 0) < n then local halt = lfs.dir_foreach(filename, f, filter, n, include_dirs, (level or 0) + 1) == false if halt then return false end end elseif include and mode == 'file' then if f(filename) == false then return false end end ::skip:: end end end --- -- Returns the absolute path to string *filename*. -- *prefix* or `lfs.currentdir()` is prepended to a relative filename. The -- returned path is not guaranteed to exist. -- @param filename The relative or absolute path to a file. -- @param prefix Optional prefix path prepended to a relative filename. -- @return string absolute path -- @name abspath function lfs.abspath(filename, prefix) if WIN32 then filename = filename:gsub('/', '\\') end if not filename:find(not WIN32 and '^/' or '^%a:[/\\]') and not (WIN32 and filename:find('^\\\\')) then prefix = prefix or lfs.currentdir() filename = prefix..(not WIN32 and '/' or '\\')..filename end filename = filename:gsub('%f[^/\\]%.[/\\]', '') -- clean up './' while filename:find('[^/\\]+[/\\]%.%.[/\\]') do filename = filename:gsub('[^/\\]+[/\\]%.%.[/\\]', '', 1) -- clean up '../' end return filename end
-- Copyright 2007-2018 Mitchell mitchell.att.foicica.com. See LICENSE. --[[ This comment is for LuaDoc. --- -- Extends the `lfs` library to find files in directories and determine absolute -- file paths. module('lfs')]] --- -- The filter table containing common binary file extensions and version control -- directories to exclude when iterating over files and directories using -- `dir_foreach`. -- @see dir_foreach -- @class table -- @name default_filter lfs.default_filter = { -- File extensions to exclude. '!.a', '!.bmp', '!.bz2', '!.class', '!.dll', '!.exe', '!.gif', '!.gz', '!.jar', '!.jpeg', '!.jpg', '!.o', '!.pdf', '!.png', '!.so', '!.tar', '!.tgz', '!.tif', '!.tiff', '!.xz', '!.zip', -- Directories to exclude. '!/%.bzr$', '!/%.git$', '!/%.hg$', '!/%.svn$', '!/node_modules$', --[[Temporary backwards-compatibility]]extensions={'a','bmp','bz2','class','dll','exe','gif','gz','jar','jpeg','jpg','o','pdf','png','so','tar','tgz','tif','tiff','xz','zip'},folders={'%.bzr$','%.git$','%.hg$','%.svn$','node_modules'} } --- -- Iterates over all files and sub-directories (up to *n* levels deep) in -- directory *dir*, calling function *f* with each file found. -- String or list *filter* determines which files to pass through to *f*, with -- the default filter being `lfs.default_filter`. A filter consists of Lua -- patterns that match file and directory paths to include or exclude. Exclusive -- patterns begin with a '!'. If no inclusive patterns are given, any path is -- initially considered. As a convenience, file extensions can be specified -- literally instead of as a Lua pattern (e.g. '.lua' vs. '%.lua$'), and '/' -- also matches the Windows directory separator ('[/\\]' is not needed). -- @param dir The directory path to iterate over. -- @param f Function to call with each full file path found. If *f* returns -- `false` explicitly, iteration ceases. -- @param filter Optional filter for files and directories to include and -- exclude. The default value is `lfs.default_filter`. -- @param n Optional maximum number of directory levels to descend into. -- The default value is `nil`, which indicates no limit. -- @param include_dirs Optional flag indicating whether or not to call *f* with -- directory names too. Directory names are passed with a trailing '/' or '\', -- depending on the current platform. -- The default value is `false`. -- @param level Utility value indicating the directory level this function is -- at. This value is used and set internally, and should not be set otherwise. -- @see filter -- @name dir_foreach function lfs.dir_foreach(dir, f, filter, n, include_dirs, level) if not level then -- Convert filter to a table from nil or string arguments. if not filter then filter = lfs.default_filter end if type(filter) == 'string' then filter = {filter} end --[[Temporary backwards-compatibility.]]if filter.extensions and filter~=lfs.default_filter then;local compat_filter={};ui.dialogs.textbox{title='Compatibility Notice',informative_text='Warning: use of deprecated filter format; please update your scripts',text=debug.traceback()};for i=1,#filter do if filter[i]:find('^!')then compat_filter[i]=filter[i]:sub(2)else compat_filter[i]='!'..filter[i]end end;for i=1,#filter.extensions do compat_filter[#compat_filter+1]='!.'..filter.extensions[i]end;if filter.folders then for i=1,#filter.folders do; compat_filter[#compat_filter+1]='!'..filter.folders[i]:gsub('^%%.[^.]+%$$','[/\\]%0')end end;filter = compat_filter;end -- Process the given filter into something that can match files more easily -- and/or quickly. For example, convert '.ext' shorthand to '%.ext$', -- substitute '/' with '[/\\]', and enable hash lookup for file extensions -- to include or exclude. local processed_filter = {consider_any = true, exts = {}} for i = 1, #filter do local patt = filter[i] patt = patt:gsub('^(!?)%%?%.([^.]+)$', '%1%%.%2$') -- '.lua' to '%.lua$' patt = patt:gsub('/([^\\])', '[/\\]%1') -- '/' to '[/\\]' local include = not patt:find('^!') if include then processed_filter.consider_any = false end local ext = patt:match('^!?%%.([^.]+)%$$') if ext then processed_filter.exts[ext] = include and 'include' or 'exclude' if include and not getmetatable(processed_filter.exts) then -- Exclude any extensions not manually specified. setmetatable(processed_filter.exts, {__index = function() return 'exclude' end}) end else processed_filter[#processed_filter + 1] = patt end end filter = processed_filter end local dir_sep, lfs_attributes = not WIN32 and '/' or '\\', lfs.attributes for basename in lfs.dir(dir) do if not basename:find('^%.%.?$') then -- ignore . and .. local filename = dir..(dir ~= '/' and dir_sep or '')..basename local mode = lfs_attributes(filename, 'mode') if mode ~= 'directory' and mode ~= 'file' then goto skip end local include if mode == 'file' then local ext = filename:match('[^.]+$') if ext and filter.exts[ext] == 'exclude' then goto skip end include = filter.consider_any or ext and filter.exts[ext] == 'include' elseif mode == 'directory' then include = filter.consider_any or #filter == 0 end for i = 1, #filter do local patt = filter[i] -- Treat exclusive patterns as logical AND. if patt:find('^!') and filename:find(patt:sub(2)) then goto skip end -- Treat inclusive patterns as logical OR. include = include or (not patt:find('^!') and filename:find(patt)) end if include and mode == 'directory' then if include_dirs and f(filename..dir_sep) == false then return end if not n or (level or 0) < n then local halt = lfs.dir_foreach(filename, f, filter, n, include_dirs, (level or 0) + 1) == false if halt then return false end end elseif include and mode == 'file' then if f(filename) == false then return false end end ::skip:: end end end --- -- Returns the absolute path to string *filename*. -- *prefix* or `lfs.currentdir()` is prepended to a relative filename. The -- returned path is not guaranteed to exist. -- @param filename The relative or absolute path to a file. -- @param prefix Optional prefix path prepended to a relative filename. -- @return string absolute path -- @name abspath function lfs.abspath(filename, prefix) if WIN32 then filename = filename:gsub('/', '\\') end if not filename:find(not WIN32 and '^/' or '^%a:[/\\]') and not (WIN32 and filename:find('^\\\\')) then prefix = prefix or lfs.currentdir() filename = prefix..(not WIN32 and '/' or '\\')..filename end filename = filename:gsub('%f[^/\\]%.[/\\]', '') -- clean up './' while filename:find('[^/\\]+[/\\]%.%.[/\\]') do filename = filename:gsub('[^/\\]+[/\\]%.%.[/\\]', '', 1) -- clean up '../' end return filename end
Fixed bug in new filter regarding extensions. If any extensions are specified as inclusive, exclude all others not specified.
Fixed bug in new filter regarding extensions. If any extensions are specified as inclusive, exclude all others not specified.
Lua
mit
rgieseke/textadept,rgieseke/textadept
940fc40f8e8045a59b6a3f33051a58b918cbf815
init.lua
init.lua
--[[ Copyright (c) 2011 Matthias Richter Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]]-- module(..., package.seeall) require(_PACKAGE .. 'shape') require(_PACKAGE .. 'polygon') require(_PACKAGE .. 'spatialhash') require(_PACKAGE .. 'vector') local vector = vector.new local is_initialized = false hash = nil local shapes = {} local shape_ids = {} local function __NOT_INIT() error("Not yet initialized") end local function __NULL() end local cb_start, cb_persist, cb_stop = __NOT_INIT, __NOT_INIT, __NOT_INIT function init(cell_size, callback_start, callback_persist, callback_stop) cb_start = callback_start or __NULL cb_persist = callback_persist or __NULL cb_stop = callback_stop or __NULL hash = Spatialhash(cell_size) is_initialized = true end function setCallbacks(start,persist,stop) local tbl = start if type(start) == "function" then tbl = {start = start, persist = persist, stop = stop} end if tbl.start then cb_start = tbl.start end if tbl.persist then cb_persist = tbl.persist end if tbl.stop then cb_stop = tbl.stop end end local function newShape(shape, ul,lr) shapes[#shapes+1] = shape shape_ids[shape] = #shapes hash:insert(shape, ul,lr) return shape end -- create polygon shape and add it to internal structures function newPolygonShape(...) assert(is_initialized, "Not properly initialized!") local poly = Polygon(...) local shape if not poly:isConvex() then shape = CompoundShape( poly, poly:splitConvex() ) else shape = PolygonShape( poly ) end -- replace shape member function with a function that also updates -- the hash local function hash_aware_member(oldfunc) return function(self, ...) local x1,y1, x2,y2 = self._polygon:getBBox() oldfunc(self, ...) local x3,y3, x4,y4 = self._polygon:getBBox() hash:update(self, vector(x1,y1), vector(x2,y2), vector(x3,y3), vector(x4,y4)) end end shape.move = hash_aware_member(shape.move) shape.rotate = hash_aware_member(shape.rotate) local x1,y1, x2,y2 = poly:getBBox() return newShape(shape, vector(x1,y1), vector(x2,y2)) end -- create new polygon approximation of a circle function newCircleShape(cx, cy, radius) assert(is_initialized, "Not properly initialized!") local shape = CircleShape(cx,cy, radius) local oldmove = shape.move function shape:move(x,y) local r = vector(self._radius, self._radius) local c1 = self._center oldmove(self,x,y) local c2 = self._center hash:update(self, c1-r, c1+r, c2-r, c2+r) end local c,r = shape._center, vector(radius,radius) return newShape(shape, c-r, c+r) end -- get unique indentifier for an unordered pair of shapes, i.e.: -- collision_id(s,t) = collision_id(t,s) local function collision_id(s,t) local i,k = shape_ids[s], shape_ids[t] if i < k then i,k = k,i end return string.format("%d,%d", i,k) end -- check for collisions local colliding_last_frame = {} function update(dt) -- collect colliding shapes local tested, colliding = {}, {} for _,s in pairs(shapes) do local neighbors if s._type == Shape.CIRCLE then local c,r = s._center, vector(s._radius, s._radius) neighbors = hash:getNeighbors(s, c-r, c+r) else local x1,y1, x2,y2 = s._polygon:getBBox() neighbors = hash:getNeighbors(s, vector(x1,y1), vector(x2,y2)) end for _,t in ipairs(neighbors) do -- check if shapes have already been tested for collision local id = collision_id(s,t) if not tested[id] then local collide, sep = s:collidesWith(t) if collide then colliding[id] = {s, t, sep.x, sep.y} end tested[id] = true end end end -- call colliding callbacks on colliding shapes for id,info in pairs(colliding) do if colliding_last_frame[id] then colliding_last_frame[id] = nil cb_persist( dt, unpack(info) ) else cb_start( dt, unpack(info) ) end end -- call stop callback on shapes that do not collide -- anymore for _,info in pairs(colliding_last_frame) do cb_stop( dt, unpack(info) ) end colliding_last_frame = colliding end -- remove shape from internal tables and the hash function removeShape(shape) local id = shape_ids[shape] shapes[id] = nil shape_ids[shape] = nil if shape.type == Shape.CIRCLE then local c,r = shape._center, vector(shape._radius, shape._radius) hash:remove(shape, c-r, c+r) else local x1,y1, x2,y2 = poly:getBBox() hash:remove(shape, vector(x1,y1), vector(x2,y2)) end for id,info in pairs(colliding_last_frame) do if info[1] == shape or info[2] == shape then colliding_last_frame[id] = nil end end end
--[[ Copyright (c) 2011 Matthias Richter Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]]-- local _PATH = (...):gsub("(%.?)init$", "%1") module(..., package.seeall) require(_PATH .. '.shape') require(_PATH .. '.polygon') require(_PATH .. '.spatialhash') require(_PATH .. '.vector') local vector = vector.new local is_initialized = false hash = nil local shapes = {} local shape_ids = {} local function __NOT_INIT() error("Not yet initialized") end local function __NULL() end local cb_start, cb_persist, cb_stop = __NOT_INIT, __NOT_INIT, __NOT_INIT function init(cell_size, callback_start, callback_persist, callback_stop) cb_start = callback_start or __NULL cb_persist = callback_persist or __NULL cb_stop = callback_stop or __NULL hash = Spatialhash(cell_size) is_initialized = true end function setCallbacks(start,persist,stop) local tbl = start if type(start) == "function" then tbl = {start = start, persist = persist, stop = stop} end if tbl.start then cb_start = tbl.start end if tbl.persist then cb_persist = tbl.persist end if tbl.stop then cb_stop = tbl.stop end end local function newShape(shape, ul,lr) shapes[#shapes+1] = shape shape_ids[shape] = #shapes hash:insert(shape, ul,lr) return shape end -- create polygon shape and add it to internal structures function newPolygonShape(...) assert(is_initialized, "Not properly initialized!") local poly = Polygon(...) local shape if not poly:isConvex() then shape = CompoundShape( poly, poly:splitConvex() ) else shape = PolygonShape( poly ) end -- replace shape member function with a function that also updates -- the hash local function hash_aware_member(oldfunc) return function(self, ...) local x1,y1, x2,y2 = self._polygon:getBBox() oldfunc(self, ...) local x3,y3, x4,y4 = self._polygon:getBBox() hash:update(self, vector(x1,y1), vector(x2,y2), vector(x3,y3), vector(x4,y4)) end end shape.move = hash_aware_member(shape.move) shape.rotate = hash_aware_member(shape.rotate) local x1,y1, x2,y2 = poly:getBBox() return newShape(shape, vector(x1,y1), vector(x2,y2)) end -- create new polygon approximation of a circle function newCircleShape(cx, cy, radius) assert(is_initialized, "Not properly initialized!") local shape = CircleShape(cx,cy, radius) local oldmove = shape.move function shape:move(x,y) local r = vector(self._radius, self._radius) local c1 = self._center oldmove(self,x,y) local c2 = self._center hash:update(self, c1-r, c1+r, c2-r, c2+r) end local c,r = shape._center, vector(radius,radius) return newShape(shape, c-r, c+r) end -- get unique indentifier for an unordered pair of shapes, i.e.: -- collision_id(s,t) = collision_id(t,s) local function collision_id(s,t) local i,k = shape_ids[s], shape_ids[t] if i < k then i,k = k,i end return string.format("%d,%d", i,k) end -- check for collisions local colliding_last_frame = {} function update(dt) -- collect colliding shapes local tested, colliding = {}, {} for _,s in pairs(shapes) do local neighbors if s._type == Shape.CIRCLE then local c,r = s._center, vector(s._radius, s._radius) neighbors = hash:getNeighbors(s, c-r, c+r) else local x1,y1, x2,y2 = s._polygon:getBBox() neighbors = hash:getNeighbors(s, vector(x1,y1), vector(x2,y2)) end for _,t in ipairs(neighbors) do -- check if shapes have already been tested for collision local id = collision_id(s,t) if not tested[id] then local collide, sep = s:collidesWith(t) if collide then colliding[id] = {s, t, sep.x, sep.y} end tested[id] = true end end end -- call colliding callbacks on colliding shapes for id,info in pairs(colliding) do if colliding_last_frame[id] then colliding_last_frame[id] = nil cb_persist( dt, unpack(info) ) else cb_start( dt, unpack(info) ) end end -- call stop callback on shapes that do not collide -- anymore for _,info in pairs(colliding_last_frame) do cb_stop( dt, unpack(info) ) end colliding_last_frame = colliding end -- remove shape from internal tables and the hash function removeShape(shape) local id = shape_ids[shape] shapes[id] = nil shape_ids[shape] = nil if shape.type == Shape.CIRCLE then local c,r = shape._center, vector(shape._radius, shape._radius) hash:remove(shape, c-r, c+r) else local x1,y1, x2,y2 = poly:getBBox() hash:remove(shape, vector(x1,y1), vector(x2,y2)) end for id,info in pairs(colliding_last_frame) do if info[1] == shape or info[2] == shape then colliding_last_frame[id] = nil end end end
Fix package path problem
Fix package path problem
Lua
mit
aswyk/botrot
b0f2da06f8151d0090d2a3bcb29156ead6e5df1b
advanced-combinator_0.16.0/control.lua
advanced-combinator_0.16.0/control.lua
-- Use item tags. When removing an item, save its tags, when placing item use tags if any exist. Use the config string as the tag -- /c local t = game.player.selected.get_control_behavior().parameters.parameters[1].signal; for i, v in pairs(t) do game.print(i .. " = " .. v) end local logic = require "logic" local gui = require "gui" local model = require "model" local perform = model.perform local advanced_combinators = {} local runtime_combinators = {} local function out(txt) local debug = false if debug then game.print(txt) end end local function txtpos(pos) return "{" .. pos["x"] .. ", " .. pos["y"] .."}" end local function worldAndPos(entity, key) return entity.surface.name .. txtpos(entity.position) end local function onInit() global.advanced_combinators = {} end local function onLoad() advanced_combinators = global.advanced_combinators for k, v in pairs(advanced_combinators) do runtime_combinators[k] = model.parse(v) end end local function updateConfiguration(entity) if entity.name ~= "advanced-combinator" then game.print("Can't update configuration of a non-advanced-combinator") return end runtime_combinators[worldAndPos(entity)] = model.parse(advanced_combinators[worldAndPos(entity)], entity) end local function onPlaceEntity(event) local entity = event.created_entity if entity.name == "advanced-combinator" then advanced_combinators[worldAndPos(entity)] = { entity = event.created_entity, updatePeriod = 1, config = "1:virtual/signal-A = mod(add(previous(1),const(1)),const(60))\n2:virtual/signal-B = current(1)\n3:virtual/signal-C = add(green(this,item/iron-plate),red(this,item/copper-plate))" -- config = "iron-plate = sum(const(20), green(this, copper-plate))" } updateConfiguration(entity) end end local function onRemoveEntity(event) local entity = event.entity advanced_combinators[worldAndPos(entity)] = nil end local function onTick() for k, v in pairs(advanced_combinators) do if game.tick % v.updatePeriod == 0 then model.perform(v, runtime_combinators[k]) end end end function onGuiOpened(event) local player = game.players[event.player_index] if event.gui_type ~= defines.gui_type.entity then return end local entity = event.entity if entity.name == "advanced-combinator" then local advanced_combinator = advanced_combinators[worldAndPos(entity)] if advanced_combinator.entity and advanced_combinator.entity.valid and advanced_combinator.entity == entity then gui.openGUI(player, entity) end end end script.on_init(onInit) script.on_load(onLoad) script.on_event(defines.events.on_built_entity, onPlaceEntity) script.on_event(defines.events.on_robot_built_entity, onPlaceEntity) script.on_event(defines.events.on_pre_player_mined_item, onRemoveEntity) script.on_event(defines.events.on_robot_pre_mined, onRemoveEntity) script.on_event(defines.events.on_entity_died, onRemoveEntity) script.on_event(defines.events.on_tick, onTick) script.on_event(defines.events.on_gui_opened, onGuiOpened) --script.on_event(defines.events.on_gui_click, onClick) --script.on_event(defines.events.on_gui_elem_changed, onChosenElementChanged) --script.on_event(defines.events.on_gui_checked_state_changed, onCheckboxClick) --script.on_event(defines.events.on_selected_entity_changed, onSelectedEntityChanged) --script.on_event(defines.events.on_entity_settings_pasted, onPasteSettings) --script.on_event(defines.events.on_gui_closed, onGuiClosed) --script.on_configuration_changed(onConfigurationChanged)
-- Use item tags. When removing an item, save its tags, when placing item use tags if any exist. Use the config string as the tag -- /c local t = game.player.selected.get_control_behavior().parameters.parameters[1].signal; for i, v in pairs(t) do game.print(i .. " = " .. v) end local gui = require "gui" local model = require "model" local advanced_combinators = {} local runtime_combinators = {} local function out(txt) local debug = false if debug then game.print(txt) end end local function txtpos(pos) return "{" .. pos["x"] .. ", " .. pos["y"] .."}" end local function worldAndPos(entity) return entity.surface.name .. txtpos(entity.position) end local function onInit() global.advanced_combinators = {} end local function onLoad() advanced_combinators = global.advanced_combinators for k, v in pairs(advanced_combinators) do runtime_combinators[k] = model.parse(v) end end local function updateConfiguration(entity) if entity.name ~= "advanced-combinator" then game.print("Can't update configuration of a non-advanced-combinator") return end runtime_combinators[worldAndPos(entity)] = model.parse(advanced_combinators[worldAndPos(entity)], entity) end local function onPlaceEntity(event) local entity = event.created_entity if entity.name == "advanced-combinator" then advanced_combinators[worldAndPos(entity)] = { entity = event.created_entity, updatePeriod = 1, config = "1:virtual/signal-A = mod(add(previous(1),const(1)),const(60))\n" .. "2:virtual/signal-B = current(1)\n" .. "3:virtual/signal-C = add(green(this,item/iron-plate),red(this,item/copper-plate))" } updateConfiguration(entity) end end local function onRemoveEntity(event) local entity = event.entity advanced_combinators[worldAndPos(entity)] = nil end local function onTick() for k, v in pairs(advanced_combinators) do if game.tick % v.updatePeriod == 0 then model.perform(v, runtime_combinators[k]) end end end local function onGuiOpened(event) local player = game.players[event.player_index] if event.gui_type ~= defines.gui_type.entity then return end local entity = event.entity if entity.name == "advanced-combinator" then local advanced_combinator = advanced_combinators[worldAndPos(entity)] if advanced_combinator.entity and advanced_combinator.entity.valid and advanced_combinator.entity == entity then gui.openGUI(player, entity) end end end script.on_init(onInit) script.on_load(onLoad) script.on_event(defines.events.on_built_entity, onPlaceEntity) script.on_event(defines.events.on_robot_built_entity, onPlaceEntity) script.on_event(defines.events.on_pre_player_mined_item, onRemoveEntity) script.on_event(defines.events.on_robot_pre_mined, onRemoveEntity) script.on_event(defines.events.on_entity_died, onRemoveEntity) script.on_event(defines.events.on_tick, onTick) script.on_event(defines.events.on_gui_opened, onGuiOpened) --script.on_event(defines.events.on_gui_click, onClick) --script.on_event(defines.events.on_gui_elem_changed, onChosenElementChanged) --script.on_event(defines.events.on_gui_checked_state_changed, onCheckboxClick) --script.on_event(defines.events.on_selected_entity_changed, onSelectedEntityChanged) --script.on_event(defines.events.on_entity_settings_pasted, onPasteSettings) --script.on_event(defines.events.on_gui_closed, onGuiClosed) --script.on_configuration_changed(onConfigurationChanged)
Advanced Combinator: Fix some Lua warnings
Advanced Combinator: Fix some Lua warnings
Lua
mit
Zomis/FactorioMods
9dd3994dd8dde2f4826ca4c96e82cd54e8313fec
selectmenu.lua
selectmenu.lua
require "rendertext" require "keys" require "graphics" require "font" SelectMenu = { -- font for displaying item names fsize = 22, -- font for page title tfsize = 25, -- font for paging display ffsize = 16, -- font for item shortcut sface = freetype.newBuiltinFace("mono", 22), sfhash = "mono22", -- title height title_H = 40, -- spacing between lines spacing = 36, -- foot height foot_H = 27, menu_title = "None Titled", no_item_msg = "No items found.", item_array = {}, items = 0, item_shortcuts = { "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "A", "S", "D", "F", "G", "H", "J", "K", "L", "Del", "Z", "X", "C", "V", "B", "N", "M", ".", "Sym", "Ent", }, last_shortcut = 0, -- state buffer page = 1, current = 1, oldcurrent = 0, } function SelectMenu:new(o) o = o or {} setmetatable(o, self) self.__index = self o.items = #o.item_array o.page = 1 o.current = 1 o.oldcurrent = 0 -- increase spacing for DXG so we don't have more than 30 shortcuts if fb.bb:getHeight() == 1200 then o.spacing = 37 end return o end function SelectMenu:getItemIndexByShortCut(c, perpage) if c == nil then return end -- unused key for _k,_v in ipairs(self.item_shortcuts) do if _v == c and _k <= self.last_shortcut then return (perpage * (self.page - 1) + _k) end end end --[ -- return the index of selected item --] function SelectMenu: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 self.last_shortcut = 0 while true do local cface, cfhash = Font:getFaceAndHash(22) local tface, tfhash = Font:getFaceAndHash(25, Font.tfont) local fface, ffhash = Font:getFaceAndHash(16, Font.ffont) if pagedirty then markerdirty = true -- draw menu title fb.bb:paintRect(0, ypos, fb.bb:getWidth(), self.title_H + 10, 0) fb.bb:paintRect(10, ypos + 10, fb.bb:getWidth() - 20, self.title_H, 5) local x = 20 local y = ypos + self.title_H renderUtf8Text(fb.bb, x, y, tface, tfhash, self.menu_title, true) -- draw items fb.bb:paintRect(0, ypos + self.title_H + 10, fb.bb:getWidth(), height - self.title_H, 0) if self.items == 0 then y = ypos + self.title_H + (self.spacing * 2) renderUtf8Text(fb.bb, 30, y, cface, cfhash, "Oops... Bad news for you:", true) y = y + self.spacing renderUtf8Text(fb.bb, 30, y, cface, cfhash, self.no_item_msg, true) markerdirty = false else 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) -- paint shortcut indications if c <= 10 or c > 20 then blitbuffer.paintBorder(fb.bb, 10, y-22, 29, 29, 2, 15) else fb.bb:paintRect(10, y-22, 29, 29, 3) end if self.item_shortcuts[c] ~= nil and string.len(self.item_shortcuts[c]) == 3 then -- print "Del", "Sym and "Ent" renderUtf8Text(fb.bb, 13, y, fface, ffhash, self.item_shortcuts[c], true) else renderUtf8Text(fb.bb, 18, y, self.sface, self.sfhash, self.item_shortcuts[c], true) end self.last_shortcut = c renderUtf8Text(fb.bb, 50, y, cface, cfhash, self.item_array[i], true) end end end -- draw footer y = ypos + self.title_H + (self.spacing * perpage) + self.foot_H + 5 x = (fb.bb:getWidth() / 2) - 50 renderUtf8Text(fb.bb, x, y, fface, ffhash, "Page "..self.page.." of "..(math.floor(self.items / perpage)+1), true) end if markerdirty then if not pagedirty then if self.oldcurrent > 0 then y = ypos + self.title_H + (self.spacing * self.oldcurrent) + 8 fb.bb:paintRect(45, y, fb.bb:getWidth() - 60, 3, 0) fb:refresh(1, 45, y, fb.bb:getWidth() - 60, 3) end end -- draw new marker line y = ypos + self.title_H + (self.spacing * self.current) + 8 fb.bb:paintRect(45, y, fb.bb:getWidth() - 60, 3, 15) if not pagedirty then fb:refresh(1, 45, 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() ev.code = adjustKeyEvents(ev) if ev.type == EV_KEY and ev.value == EVENT_VALUE_KEY_PRESS then local selected = nil 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_FW_PRESS or ev.code == KEY_ENTER and self.last_shortcut < 30 then if self.items == 0 then return nil else return (perpage*(self.page-1) + self.current) end elseif ev.code >= KEY_Q and ev.code <= KEY_P then selected = self:getItemIndexByShortCut(self.item_shortcuts[ ev.code - KEY_Q + 1 ], perpage) elseif ev.code >= KEY_A and ev.code <= KEY_L then selected = self:getItemIndexByShortCut(self.item_shortcuts[ ev.code - KEY_A + 11], perpage) elseif ev.code >= KEY_Z and ev.code <= KEY_M then selected = self:getItemIndexByShortCut(self.item_shortcuts[ ev.code - KEY_Z + 21], perpage) elseif ev.code == KEY_DEL then selected = self:getItemIndexByShortCut("Del", perpage) elseif ev.code == KEY_DOT then selected = self:getItemIndexByShortCut(".", perpage) elseif ev.code == KEY_SYM or ev.code == KEY_SLASH then -- DXG has slash after dot selected = self:getItemIndexByShortCut("Sym", perpage) elseif ev.code == KEY_ENTER then selected = self:getItemIndexByShortCut("Ent", perpage) elseif ev.code == KEY_BACK then return nil end if selected ~= nil then print("# selected "..selected) return selected end end end end
require "rendertext" require "keys" require "graphics" require "font" SelectMenu = { -- font for displaying item names fsize = 22, -- font for page title tfsize = 25, -- font for paging display ffsize = 16, -- font for item shortcut sface = freetype.newBuiltinFace("mono", 22), sfhash = "mono22", -- title height title_H = 40, -- spacing between lines spacing = 36, -- foot height foot_H = 27, menu_title = "None Titled", no_item_msg = "No items found.", item_array = {}, items = 0, item_shortcuts = { "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "A", "S", "D", "F", "G", "H", "J", "K", "L", "Del", "Z", "X", "C", "V", "B", "N", "M", ".", "Sym", "Ent", }, last_shortcut = 0, -- state buffer page = 1, current = 1, oldcurrent = 0, } function SelectMenu:new(o) o = o or {} setmetatable(o, self) self.__index = self o.items = #o.item_array o.page = 1 o.current = 1 o.oldcurrent = 0 -- increase spacing for DXG so we don't have more than 30 shortcuts if fb.bb:getHeight() == 1200 then o.spacing = 37 end return o end function SelectMenu:getItemIndexByShortCut(c, perpage) if c == nil then return end -- unused key for _k,_v in ipairs(self.item_shortcuts) do if _v == c and _k <= self.last_shortcut then return (perpage * (self.page - 1) + _k) end end end --[ -- return the index of selected item --] function SelectMenu: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 self.last_shortcut = 0 while true do local cface, cfhash = Font:getFaceAndHash(22) local tface, tfhash = Font:getFaceAndHash(25, Font.tfont) local fface, ffhash = Font:getFaceAndHash(16, Font.ffont) if pagedirty then markerdirty = true -- draw menu title fb.bb:paintRect(0, ypos, fb.bb:getWidth(), self.title_H + 10, 0) fb.bb:paintRect(10, ypos + 10, fb.bb:getWidth() - 20, self.title_H, 5) local x = 20 local y = ypos + self.title_H renderUtf8Text(fb.bb, x, y, tface, tfhash, self.menu_title, true) -- draw items fb.bb:paintRect(0, ypos + self.title_H + 10, fb.bb:getWidth(), height - self.title_H, 0) if self.items == 0 then y = ypos + self.title_H + (self.spacing * 2) renderUtf8Text(fb.bb, 30, y, cface, cfhash, "Oops... Bad news for you:", true) y = y + self.spacing renderUtf8Text(fb.bb, 30, y, cface, cfhash, self.no_item_msg, true) markerdirty = false else 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) -- paint shortcut indications if c <= 10 or c > 20 then blitbuffer.paintBorder(fb.bb, 10, y-22, 29, 29, 2, 15) else fb.bb:paintRect(10, y-22, 29, 29, 3) end if self.item_shortcuts[c] ~= nil and string.len(self.item_shortcuts[c]) == 3 then -- print "Del", "Sym and "Ent" renderUtf8Text(fb.bb, 13, y, fface, ffhash, self.item_shortcuts[c], true) else renderUtf8Text(fb.bb, 18, y, self.sface, self.sfhash, self.item_shortcuts[c], true) end self.last_shortcut = c renderUtf8Text(fb.bb, 50, y, cface, cfhash, self.item_array[i], true) end end end -- draw footer y = ypos + self.title_H + (self.spacing * perpage) + self.foot_H + 5 x = (fb.bb:getWidth() / 2) - 50 renderUtf8Text(fb.bb, x, y, fface, ffhash, "Page "..self.page.." of "..(math.floor(self.items / perpage)+1), true) end if markerdirty then if not pagedirty then if self.oldcurrent > 0 then y = ypos + self.title_H + (self.spacing * self.oldcurrent) + 8 fb.bb:paintRect(45, y, fb.bb:getWidth() - 60, 3, 0) fb:refresh(1, 45, y, fb.bb:getWidth() - 60, 3) end end -- draw new marker line y = ypos + self.title_H + (self.spacing * self.current) + 8 fb.bb:paintRect(45, y, fb.bb:getWidth() - 60, 3, 15) if not pagedirty then fb:refresh(1, 45, 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() ev.code = adjustKeyEvents(ev) if ev.type == EV_KEY and ev.value == EVENT_VALUE_KEY_PRESS then local selected = nil if ev.code == KEY_FW_UP then prevItem() elseif ev.code == KEY_FW_DOWN then nextItem() elseif ev.code == KEY_PGFWD or ev.code == KEY_LPGFWD 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 or ev.code == KEY_LPGBCK then if self.page > 1 then self.page = self.page - 1 pagedirty = true else self.current = 1 markerdirty = true end elseif ev.code == KEY_FW_PRESS or ev.code == KEY_ENTER and self.last_shortcut < 30 then if self.items == 0 then return nil else return (perpage*(self.page-1) + self.current) end elseif ev.code >= KEY_Q and ev.code <= KEY_P then selected = self:getItemIndexByShortCut(self.item_shortcuts[ ev.code - KEY_Q + 1 ], perpage) elseif ev.code >= KEY_A and ev.code <= KEY_L then selected = self:getItemIndexByShortCut(self.item_shortcuts[ ev.code - KEY_A + 11], perpage) elseif ev.code >= KEY_Z and ev.code <= KEY_M then selected = self:getItemIndexByShortCut(self.item_shortcuts[ ev.code - KEY_Z + 21], perpage) elseif ev.code == KEY_DEL then selected = self:getItemIndexByShortCut("Del", perpage) elseif ev.code == KEY_DOT then selected = self:getItemIndexByShortCut(".", perpage) elseif ev.code == KEY_SYM or ev.code == KEY_SLASH then -- DXG has slash after dot selected = self:getItemIndexByShortCut("Sym", perpage) elseif ev.code == KEY_ENTER then selected = self:getItemIndexByShortCut("Ent", perpage) elseif ev.code == KEY_BACK then return nil end if selected ~= nil then print("# selected "..selected) return selected end end end end
fix: handle LPGBCK and LPGFWD in selectmenu
fix: handle LPGBCK and LPGFWD in selectmenu
Lua
agpl-3.0
NiLuJe/koreader-base,NiLuJe/koreader,koreader/koreader-base,Frenzie/koreader-base,Frenzie/koreader,apletnev/koreader,pazos/koreader,frankyifei/koreader-base,ashang/koreader,Hzj-jie/koreader-base,houqp/koreader-base,koreader/koreader,NiLuJe/koreader-base,houqp/koreader-base,NickSavage/koreader,NiLuJe/koreader,mwoz123/koreader,poire-z/koreader,frankyifei/koreader,koreader/koreader-base,apletnev/koreader-base,koreader/koreader-base,chihyang/koreader,Frenzie/koreader-base,frankyifei/koreader-base,chrox/koreader,frankyifei/koreader-base,frankyifei/koreader-base,Hzj-jie/koreader-base,NiLuJe/koreader-base,Frenzie/koreader-base,koreader/koreader-base,robert00s/koreader,Frenzie/koreader,apletnev/koreader-base,poire-z/koreader,Hzj-jie/koreader-base,Frenzie/koreader-base,houqp/koreader-base,lgeek/koreader,Markismus/koreader,Hzj-jie/koreader-base,ashhher3/koreader,houqp/koreader,koreader/koreader,houqp/koreader-base,Hzj-jie/koreader,NiLuJe/koreader-base,noname007/koreader,mihailim/koreader,apletnev/koreader-base,apletnev/koreader-base
da8a7e8a4506e627cf9e4a0b9f4ee1cef9421520
lua/mediaplayer/players/entity/sh_meta.lua
lua/mediaplayer/players/entity/sh_meta.lua
--[[--------------------------------------------------------- Media Player Entity Meta -----------------------------------------------------------]] local EntityMeta = FindMetaTable("Entity") if not EntityMeta then return end function EntityMeta:GetMediaPlayer() return self._mp end -- -- Installs a media player reference to the entity. -- -- @param Table|String? mp Media player table or string type. -- @param String? mpId Media player unique ID. -- function EntityMeta:InstallMediaPlayer( mp, mpId ) if not istable(mp) then local mpType = isstring(mp) and mp or "entity" if not MediaPlayer.IsValidType(mpType) then ErrorNoHalt("ERROR: Attempted to install invalid mediaplayer type onto an entity!\n") ErrorNoHalt("ENTITY: " .. tostring(self) .. "\n") ErrorNoHalt("TYPE: " .. tostring(mpType) .. "\n") mpType = "entity" -- default end local mpId = mpId or "Entity" .. self:EntIndex() mp = MediaPlayer.Create( mpId, mpType ) end self._mp = mp self._mp:SetEntity(self) if isfunction(self.SetupMediaPlayer) then self:SetupMediaPlayer(mp) end return mp end local DefaultConfig = { offset = Vector(0,0,0), -- translation from entity origin angle = Angle(0,0,0), -- rotation -- attachment = "corner" -- attachment name width = 64, -- screen width height = 64 * 9/16 -- screen height } function EntityMeta:GetMediaPlayerPosition() local cfg = self.PlayerConfig or DefaultConfig local w = (cfg.width or DefaultConfig.width) local h = (cfg.height or DefaultConfig.height) local pos, ang if cfg.attachment then local idx = self:LookupAttachment(cfg.attachment) if not idx then local err = string.format("MediaPlayer:Entity.Draw: Invalid attachment '%s'\n", cfg.attachment) Error(err) end -- Get attachment orientation local attach = self:GetAttachment(idx) pos = attach.pos ang = attach.ang else pos = self:GetPos() -- TODO: use GetRenderOrigin? end -- Apply offset if cfg.offset then pos = pos + self:GetForward() * cfg.offset.x + self:GetRight() * cfg.offset.y + self:GetUp() * cfg.offset.z end -- Set angles ang = ang or self:GetAngles() -- TODO: use GetRenderAngles? ang:RotateAroundAxis( ang:Right(), cfg.angle.p ) ang:RotateAroundAxis( ang:Up(), cfg.angle.y ) ang:RotateAroundAxis( ang:Forward(), cfg.angle.r ) return w, h, pos, ang end
--[[--------------------------------------------------------- Media Player Entity Meta -----------------------------------------------------------]] local EntityMeta = FindMetaTable("Entity") if not EntityMeta then return end function EntityMeta:GetMediaPlayer() return self._mp end -- -- Installs a media player reference to the entity. -- -- @param Table|String? mp Media player table or string type. -- @param String? mpId Media player unique ID. -- function EntityMeta:InstallMediaPlayer( mp, mpId ) if not istable(mp) then local mpType = isstring(mp) and mp or "entity" if not MediaPlayer.IsValidType(mpType) then ErrorNoHalt("ERROR: Attempted to install invalid mediaplayer type onto an entity!\n") ErrorNoHalt("ENTITY: " .. tostring(self) .. "\n") ErrorNoHalt("TYPE: " .. tostring(mpType) .. "\n") mpType = "entity" -- default end local mpId = mpId or "Entity" .. self:EntIndex() mp = MediaPlayer.Create( mpId, mpType ) end self._mp = mp self._mp:SetEntity(self) if isfunction(self.SetupMediaPlayer) then self:SetupMediaPlayer(mp) end return mp end local DefaultConfig = { offset = Vector(0,0,0), -- translation from entity origin angle = Angle(0,0,0), -- rotation -- attachment = "corner" -- attachment name width = 64, -- screen width height = 64 * 9/16 -- screen height } function EntityMeta:GetMediaPlayerPosition() local cfg = self.PlayerConfig or DefaultConfig local w = (cfg.width or DefaultConfig.width) local h = (cfg.height or DefaultConfig.height) local pos, ang if cfg.attachment then local idx = self:LookupAttachment(cfg.attachment) if not idx then local err = string.format("MediaPlayer:Entity.Draw: Invalid attachment '%s'\n", cfg.attachment) Error(err) end -- Get attachment orientation local attach = self:GetAttachment(idx) pos = attach.pos ang = attach.ang else pos = self:GetPos() -- TODO: use GetRenderOrigin? end -- Apply offset if cfg.offset then pos = pos + self:GetForward() * cfg.offset.x + self:GetRight() * cfg.offset.y + self:GetUp() * cfg.offset.z end -- Set angles ang = ang or self:GetAngles() -- TODO: use GetRenderAngles? -- Rotate angle based on the config if cfg.angle then ang:RotateAroundAxis( ang:Right(), cfg.angle.p ) ang:RotateAroundAxis( ang:Up(), cfg.angle.y ) ang:RotateAroundAxis( ang:Forward(), cfg.angle.r ) end return w, h, pos, ang end
Fixed error in which the mediaplayer entity config doesn't specify an angle.
Fixed error in which the mediaplayer entity config doesn't specify an angle.
Lua
mit
pixeltailgames/gm-mediaplayer,pixeltailgames/gm-mediaplayer
7d6f80d4608039c147998056baa7f5435f7e1d30
nyagos.d/catalog/subcomplete.lua
nyagos.d/catalog/subcomplete.lua
if not nyagos then print("This is a script for nyagos not lua.exe") os.exit() end share.maincmds = {} -- git local githelp=io.popen("git help -a 2>nul","r") local hubhelp=io.popen("hub help -a 2>nul","r") if githelp then local gitcmds={} local hub=false if hubhelp then hub=true local startflag = false local found=false for line in hubhelp:lines() do if not found then if startflag then -- skip blank line if string.match(line,"%S") then -- found commands for word in string.gmatch(line, "%S+") do gitcmds[ #gitcmds+1 ] = word end found = true end end if string.match(line,"hub custom") then startflag = true end end end hubhelp:close() end for line in githelp:lines() do local word = string.match(line,"^ +(%S+)") if nil ~= word then gitcmds[ #gitcmds+1 ] = word end end githelp:close() if #gitcmds > 1 then local maincmds = share.maincmds maincmds["git"] = gitcmds maincmds["git.exe"] = gitcmds if hub then maincmds["hub"] = gitcmds maincmds["hub.exe"] = gitcmds end share.maincmds = maincmds end end -- Subversion local svnhelp=nyagos.eval("svn help 2>nul","r") if string.len(svnhelp) > 5 then local svncmds={} for line in string.gmatch(svnhelp,"[^\n]+") do local m=string.match(line,"^ +([a-z]+)") if m then svncmds[ #svncmds+1 ] = m end end if #svncmds > 1 then local maincmds = share.maincmds maincmds["svn"] = svncmds maincmds["svn.exe"] = svncmds share.maincmds = maincmds end end -- Mercurial local hghelp=nyagos.eval("hg debugcomplete 2>nul","r") if string.len(hghelp) > 5 then local hgcmds={} for line in string.gmatch(hghelp,"[^\n]+") do for word in string.gmatch(line,"[a-z]+") do hgcmds[#hgcmds+1] = word end end if #hgcmds > 1 then local maincmds=share.maincmds maincmds["hg"] = hgcmds maincmds["hg.exe"] = hgcmds share.maincmds = maincmds end end -- Rclone local rclonehelp=io.popen("rclone --help 2>nul","r") if rclonehelp then local rclonecmds={} local startflag = false local flagsfound=false for line in rclonehelp:lines() do if not flagsfound then if string.match(line,"Available Commands:") then startflag = true end if string.match(line,"Flags:") then flagsfound = true end if startflag then local m=string.match(line,"^%s+([a-z]+)") if m then rclonecmds[ #rclonecmds+1 ] = m end end end end rclonehelp:close() if #rclonecmds > 1 then local maincmds=share.maincmds maincmds["rclone"] = rclonecmds maincmds["rclone.exe"] = rclonecmds share.maincmds = maincmds end end if next(share.maincmds) then nyagos.completion_hook = function(c) if c.pos <= 1 then return nil end local cmdname = string.match(c.text,"^%S+") if not cmdname then return nil end --[[ 2nd command completion like :git bisect go[od] user define-able local subcommands={"good", "bad"} local maincmds=share.maincmds maincmds["git bisect"] = subcommands share.maincmds = maincmds --]] local cmd2nd = string.match(c.text,"^%S+%s+%S+") if share.maincmds[cmd2nd] then cmdname = cmd2nd end local subcmds = {} local subcmdData = share.maincmds[cmdname] if not subcmdData then return nil end local subcmdType = type(subcmdData) if "table" == subcmdType then subcmds = subcmdData elseif "function" == subcmdType then subcmds = subcmdData() end for i=1,#subcmds do table.insert(c.list,subcmds[i]) end return c.list end end
if not nyagos then print("This is a script for nyagos not lua.exe") os.exit() end share.maincmds = {} -- git local githelp=io.popen("git help -a 2>nul","r") local hubhelp=io.popen("hub help -a 2>nul","r") if githelp then local gitcmds={} local hub=false if hubhelp then hub=true local startflag = false local found=false for line in hubhelp:lines() do if not found then if startflag then -- skip blank line if string.match(line,"%S") then -- found commands for word in string.gmatch(line, "%S+") do gitcmds[ #gitcmds+1 ] = word end found = true end end if string.match(line,"hub custom") then startflag = true end end end hubhelp:close() end for line in githelp:lines() do local word = string.match(line,"^ +(%S+)") if nil ~= word then gitcmds[ #gitcmds+1 ] = word end end githelp:close() if #gitcmds > 1 then local maincmds = share.maincmds maincmds["git"] = gitcmds if hub then maincmds["hub"] = gitcmds end share.maincmds = maincmds end end -- Subversion local svnhelp=nyagos.eval("svn help 2>nul","r") if string.len(svnhelp) > 5 then local svncmds={} for line in string.gmatch(svnhelp,"[^\n]+") do local m=string.match(line,"^ +([a-z]+)") if m then svncmds[ #svncmds+1 ] = m end end if #svncmds > 1 then local maincmds = share.maincmds maincmds["svn"] = svncmds share.maincmds = maincmds end end -- Mercurial local hghelp=nyagos.eval("hg debugcomplete 2>nul","r") if string.len(hghelp) > 5 then local hgcmds={} for line in string.gmatch(hghelp,"[^\n]+") do for word in string.gmatch(line,"[a-z]+") do hgcmds[#hgcmds+1] = word end end if #hgcmds > 1 then local maincmds=share.maincmds maincmds["hg"] = hgcmds share.maincmds = maincmds end end -- Rclone local rclonehelp=io.popen("rclone --help 2>nul","r") if rclonehelp then local rclonecmds={} local startflag = false local flagsfound=false for line in rclonehelp:lines() do if not flagsfound then if string.match(line,"Available Commands:") then startflag = true end if string.match(line,"Flags:") then flagsfound = true end if startflag then local m=string.match(line,"^%s+([a-z]+)") if m then rclonecmds[ #rclonecmds+1 ] = m end end end end rclonehelp:close() if #rclonecmds > 1 then local maincmds=share.maincmds maincmds["rclone"] = rclonecmds share.maincmds = maincmds end end if next(share.maincmds) then nyagos.completion_hook = function(c) if c.pos <= 1 then return nil end local cmdname = string.match(c.text,"^%S+") if not cmdname then return nil end cmdname = string.lower(string.gsub(cmdname,"%.%w+$","")) --[[ 2nd command completion like :git bisect go[od] user define-able local subcommands={"good", "bad"} local maincmds=share.maincmds maincmds["git bisect"] = subcommands share.maincmds = maincmds --]] local cmd2nd = string.match(c.text,"^%S+%s+%S+") if share.maincmds[cmd2nd] then cmdname = cmd2nd end local subcmds = {} local subcmdData = share.maincmds[cmdname] if not subcmdData then return nil end local subcmdType = type(subcmdData) if "table" == subcmdType then subcmds = subcmdData elseif "function" == subcmdType then subcmds = subcmdData() end for i=1,#subcmds do table.insert(c.list,subcmds[i]) end return c.list end end
(#378) nyagos.d/catalog/subcomplete.lua: ignore command's case and suffixes
(#378) nyagos.d/catalog/subcomplete.lua: ignore command's case and suffixes
Lua
bsd-3-clause
zetamatta/nyagos,nocd5/nyagos,tsuyoshicho/nyagos
112567c97576c57e586539dfa1f3f5760be95059
premake4.lua
premake4.lua
local action = _ACTION or "" solution "nanovg" location ( "build" ) configurations { "Debug", "Release" } platforms {"native", "x64", "x32"} project "nanovg" language "C" kind "StaticLib" includedirs { "src" } files { "src/*.c" } targetdir("build") defines { "_CRT_SECURE_NO_WARNINGS" } --,"FONS_USE_FREETYPE" } Uncomment to compile with FreeType support configuration "Debug" defines { "DEBUG" } flags { "Symbols", "ExtraWarnings"} configuration "Release" defines { "NDEBUG" } flags { "Optimize", "ExtraWarnings"} project "example_gl2" kind "ConsoleApp" language "C" files { "example/example_gl2.c", "example/demo.c", "example/perf.c" } includedirs { "src", "example" } targetdir("build") links { "nanovg" } configuration { "linux" } linkoptions { "`pkg-config --libs glfw3`" } links { "GL", "GLU", "m", "GLEW" } defines { "NANOVG_GLEW" } configuration { "windows" } links { "glfw3", "gdi32", "winmm", "user32", "GLEW", "glu32","opengl32", "kernel32" } defines { "NANOVG_GLEW", "_CRT_SECURE_NO_WARNINGS" } configuration { "macosx" } links { "glfw3" } linkoptions { "-framework OpenGL", "-framework Cocoa", "-framework IOKit", "-framework CoreVideo" } configuration "Debug" defines { "DEBUG" } flags { "Symbols", "ExtraWarnings"} configuration "Release" defines { "NDEBUG" } flags { "Optimize", "ExtraWarnings"} project "example_gl3" kind "ConsoleApp" language "C" files { "example/example_gl3.c", "example/demo.c", "example/perf.c" } includedirs { "src", "example" } targetdir("build") links { "nanovg" } configuration { "linux" } linkoptions { "`pkg-config --libs glfw3`" } links { "GL", "GLU", "m", "GLEW" } defines { "NANOVG_GLEW" } configuration { "windows" } links { "glfw3", "gdi32", "winmm", "user32", "GLEW", "glu32","opengl32", "kernel32" } defines { "NANOVG_GLEW", "_CRT_SECURE_NO_WARNINGS" } configuration { "macosx" } links { "glfw3" } linkoptions { "-framework OpenGL", "-framework Cocoa", "-framework IOKit", "-framework CoreVideo" } configuration "Debug" defines { "DEBUG" } flags { "Symbols", "ExtraWarnings"} configuration "Release" defines { "NDEBUG" } flags { "Optimize", "ExtraWarnings"} project "example_gl2_msaa" kind "ConsoleApp" language "C" defines { "DEMO_MSAA" } files { "example/example_gl2.c", "example/demo.c", "example/perf.c" } includedirs { "src", "example" } targetdir("build") links { "nanovg" } configuration { "linux" } linkoptions { "`pkg-config --libs glfw3`" } links { "GL", "GLU", "m", "GLEW" } defines { "NANOVG_GLEW" } configuration { "windows" } links { "glfw3", "gdi32", "winmm", "user32", "GLEW", "glu32","opengl32", "kernel32" } defines { "NANOVG_GLEW", "_CRT_SECURE_NO_WARNINGS" } configuration { "macosx" } links { "glfw3" } linkoptions { "-framework OpenGL", "-framework Cocoa", "-framework IOKit", "-framework CoreVideo" } configuration "Debug" defines { "DEBUG" } flags { "Symbols", "ExtraWarnings"} configuration "Release" defines { "NDEBUG" } flags { "Optimize", "ExtraWarnings"} project "example_gl3_msaa" kind "ConsoleApp" language "C" defines { "DEMO_MSAA" } files { "example/example_gl3.c", "example/demo.c", "example/perf.c" } includedirs { "src", "example" } targetdir("build") links { "nanovg" } configuration { "linux" } linkoptions { "`pkg-config --libs glfw3`" } links { "GL", "GLU", "m", "GLEW" } defines { "NANOVG_GLEW" } configuration { "windows" } links { "glfw3", "gdi32", "winmm", "user32", "GLEW", "glu32","opengl32", "kernel32" } defines { "NANOVG_GLEW", "_CRT_SECURE_NO_WARNINGS" } configuration { "macosx" } links { "glfw3" } linkoptions { "-framework OpenGL", "-framework Cocoa", "-framework IOKit", "-framework CoreVideo" } configuration "Debug" defines { "DEBUG" } flags { "Symbols", "ExtraWarnings"} configuration "Release" defines { "NDEBUG" } flags { "Optimize", "ExtraWarnings"} project "example_fbo" kind "ConsoleApp" language "C" files { "example/example_fbo.c", "example/perf.c" } includedirs { "src", "example" } targetdir("build") links { "nanovg" } configuration { "linux" } linkoptions { "`pkg-config --libs glfw3`" } links { "GL", "GLU", "m", "GLEW" } configuration { "windows" } links { "glfw3", "gdi32", "winmm", "user32", "GLEW", "glu32","opengl32", "kernel32" } defines { "NANOVG_GLEW", "_CRT_SECURE_NO_WARNINGS" } configuration { "macosx" } links { "glfw3" } linkoptions { "-framework OpenGL", "-framework Cocoa", "-framework IOKit", "-framework CoreVideo" } configuration "Debug" defines { "DEBUG" } flags { "Symbols", "ExtraWarnings"} configuration "Release" defines { "NDEBUG" } flags { "Optimize", "ExtraWarnings"} project "example_gles2" kind "ConsoleApp" language "C" files { "example/example_gles2.c", "example/demo.c", "example/perf.c" } includedirs { "src", "example" } targetdir("build") links { "nanovg" } configuration { "linux" } linkoptions { "`pkg-config --libs glfw3`" } links { "GL", "GLU", "m", "GLEW" } configuration { "windows" } links { "glfw3", "gdi32", "winmm", "user32", "GLEW", "glu32","opengl32", "kernel32" } defines { "NANOVG_GLEW", "_CRT_SECURE_NO_WARNINGS" } configuration { "macosx" } links { "glfw3" } linkoptions { "-framework OpenGL", "-framework Cocoa", "-framework IOKit", "-framework CoreVideo" } configuration "Debug" defines { "DEBUG" } flags { "Symbols", "ExtraWarnings"} configuration "Release" defines { "NDEBUG" } flags { "Optimize", "ExtraWarnings"} project "example_gles3" kind "ConsoleApp" language "C" files { "example/example_gles3.c", "example/demo.c", "example/perf.c" } includedirs { "src", "example" } targetdir("build") links { "nanovg" } configuration { "linux" } linkoptions { "`pkg-config --libs glfw3`" } links { "GL", "GLU", "m", "GLEW" } configuration { "windows" } links { "glfw3", "gdi32", "winmm", "user32", "GLEW", "glu32","opengl32", "kernel32" } defines { "NANOVG_GLEW", "_CRT_SECURE_NO_WARNINGS" } configuration { "macosx" } links { "glfw3" } linkoptions { "-framework OpenGL", "-framework Cocoa", "-framework IOKit", "-framework CoreVideo" } configuration "Debug" defines { "DEBUG" } flags { "Symbols", "ExtraWarnings"} configuration "Release" defines { "NDEBUG" } flags { "Optimize", "ExtraWarnings"}
local action = _ACTION or "" solution "nanovg" location ( "build" ) configurations { "Debug", "Release" } platforms {"native", "x64", "x32"} project "nanovg" language "C" kind "StaticLib" includedirs { "src" } files { "src/*.c" } targetdir("build") defines { "_CRT_SECURE_NO_WARNINGS" } --,"FONS_USE_FREETYPE" } Uncomment to compile with FreeType support configuration "Debug" defines { "DEBUG" } flags { "Symbols", "ExtraWarnings"} configuration "Release" defines { "NDEBUG" } flags { "Optimize", "ExtraWarnings"} project "example_gl2" kind "ConsoleApp" language "C" files { "example/example_gl2.c", "example/demo.c", "example/perf.c" } includedirs { "src", "example" } targetdir("build") links { "nanovg" } configuration { "linux" } linkoptions { "`pkg-config --libs glfw3`" } links { "GL", "GLU", "m", "GLEW" } defines { "NANOVG_GLEW" } configuration { "windows" } links { "glfw3", "gdi32", "winmm", "user32", "GLEW", "glu32","opengl32", "kernel32" } defines { "NANOVG_GLEW", "_CRT_SECURE_NO_WARNINGS" } configuration { "macosx" } links { "glfw3" } linkoptions { "-framework OpenGL", "-framework Cocoa", "-framework IOKit", "-framework CoreVideo", "-framework Carbon" } configuration "Debug" defines { "DEBUG" } flags { "Symbols", "ExtraWarnings"} configuration "Release" defines { "NDEBUG" } flags { "Optimize", "ExtraWarnings"} project "example_gl3" kind "ConsoleApp" language "C" files { "example/example_gl3.c", "example/demo.c", "example/perf.c" } includedirs { "src", "example" } targetdir("build") links { "nanovg" } configuration { "linux" } linkoptions { "`pkg-config --libs glfw3`" } links { "GL", "GLU", "m", "GLEW" } defines { "NANOVG_GLEW" } configuration { "windows" } links { "glfw3", "gdi32", "winmm", "user32", "GLEW", "glu32","opengl32", "kernel32" } defines { "NANOVG_GLEW", "_CRT_SECURE_NO_WARNINGS" } configuration { "macosx" } links { "glfw3" } linkoptions { "-framework OpenGL", "-framework Cocoa", "-framework IOKit", "-framework CoreVideo", "-framework Carbon" } configuration "Debug" defines { "DEBUG" } flags { "Symbols", "ExtraWarnings"} configuration "Release" defines { "NDEBUG" } flags { "Optimize", "ExtraWarnings"} project "example_gl2_msaa" kind "ConsoleApp" language "C" defines { "DEMO_MSAA" } files { "example/example_gl2.c", "example/demo.c", "example/perf.c" } includedirs { "src", "example" } targetdir("build") links { "nanovg" } configuration { "linux" } linkoptions { "`pkg-config --libs glfw3`" } links { "GL", "GLU", "m", "GLEW" } defines { "NANOVG_GLEW" } configuration { "windows" } links { "glfw3", "gdi32", "winmm", "user32", "GLEW", "glu32","opengl32", "kernel32" } defines { "NANOVG_GLEW", "_CRT_SECURE_NO_WARNINGS" } configuration { "macosx" } links { "glfw3" } linkoptions { "-framework OpenGL", "-framework Cocoa", "-framework IOKit", "-framework CoreVideo", "-framework Carbon" } configuration "Debug" defines { "DEBUG" } flags { "Symbols", "ExtraWarnings"} configuration "Release" defines { "NDEBUG" } flags { "Optimize", "ExtraWarnings"} project "example_gl3_msaa" kind "ConsoleApp" language "C" defines { "DEMO_MSAA" } files { "example/example_gl3.c", "example/demo.c", "example/perf.c" } includedirs { "src", "example" } targetdir("build") links { "nanovg" } configuration { "linux" } linkoptions { "`pkg-config --libs glfw3`" } links { "GL", "GLU", "m", "GLEW" } defines { "NANOVG_GLEW" } configuration { "windows" } links { "glfw3", "gdi32", "winmm", "user32", "GLEW", "glu32","opengl32", "kernel32" } defines { "NANOVG_GLEW", "_CRT_SECURE_NO_WARNINGS" } configuration { "macosx" } links { "glfw3" } linkoptions { "-framework OpenGL", "-framework Cocoa", "-framework IOKit", "-framework CoreVideo", "-framework Carbon" } configuration "Debug" defines { "DEBUG" } flags { "Symbols", "ExtraWarnings"} configuration "Release" defines { "NDEBUG" } flags { "Optimize", "ExtraWarnings"} project "example_fbo" kind "ConsoleApp" language "C" files { "example/example_fbo.c", "example/perf.c" } includedirs { "src", "example" } targetdir("build") links { "nanovg" } configuration { "linux" } linkoptions { "`pkg-config --libs glfw3`" } links { "GL", "GLU", "m", "GLEW" } configuration { "windows" } links { "glfw3", "gdi32", "winmm", "user32", "GLEW", "glu32","opengl32", "kernel32" } defines { "NANOVG_GLEW", "_CRT_SECURE_NO_WARNINGS" } configuration { "macosx" } links { "glfw3" } linkoptions { "-framework OpenGL", "-framework Cocoa", "-framework IOKit", "-framework CoreVideo", "-framework Carbon" } configuration "Debug" defines { "DEBUG" } flags { "Symbols", "ExtraWarnings"} configuration "Release" defines { "NDEBUG" } flags { "Optimize", "ExtraWarnings"} project "example_gles2" kind "ConsoleApp" language "C" files { "example/example_gles2.c", "example/demo.c", "example/perf.c" } includedirs { "src", "example" } targetdir("build") links { "nanovg" } configuration { "linux" } linkoptions { "`pkg-config --libs glfw3`" } links { "GL", "GLU", "m", "GLEW" } configuration { "windows" } links { "glfw3", "gdi32", "winmm", "user32", "GLEW", "glu32","opengl32", "kernel32" } defines { "NANOVG_GLEW", "_CRT_SECURE_NO_WARNINGS" } configuration { "macosx" } links { "glfw3" } linkoptions { "-framework OpenGL", "-framework Cocoa", "-framework IOKit", "-framework CoreVideo", "-framework Carbon" } configuration "Debug" defines { "DEBUG" } flags { "Symbols", "ExtraWarnings"} configuration "Release" defines { "NDEBUG" } flags { "Optimize", "ExtraWarnings"} project "example_gles3" kind "ConsoleApp" language "C" files { "example/example_gles3.c", "example/demo.c", "example/perf.c" } includedirs { "src", "example" } targetdir("build") links { "nanovg" } configuration { "linux" } linkoptions { "`pkg-config --libs glfw3`" } links { "GL", "GLU", "m", "GLEW" } configuration { "windows" } links { "glfw3", "gdi32", "winmm", "user32", "GLEW", "glu32","opengl32", "kernel32" } defines { "NANOVG_GLEW", "_CRT_SECURE_NO_WARNINGS" } configuration { "macosx" } links { "glfw3" } linkoptions { "-framework OpenGL", "-framework Cocoa", "-framework IOKit", "-framework CoreVideo", "-framework Carbon" } configuration "Debug" defines { "DEBUG" } flags { "Symbols", "ExtraWarnings"} configuration "Release" defines { "NDEBUG" } flags { "Optimize", "ExtraWarnings"}
Added "-framework Carbon" as a link option to premake4.lua.
Added "-framework Carbon" as a link option to premake4.lua. To get nanovg to link correctly under OS X 12.3, it needs to be linked against the Carbon libraries. This was missing in the premake4.lua files. Now fixed.
Lua
bsd-3-clause
dleslie/nanovg-egg
456d1a5e5df2f834649574e52d735e1b001f8e3c
CIFAR10/cifar10_L2.lua
CIFAR10/cifar10_L2.lua
--[[ Multiple meta-iterations for DrMAD on CIFAR10 ]] require 'torch' require 'sys' require 'image' local root = '../' local grad = require 'autograd' local utils = require(root .. 'models/utils.lua') local optim = require 'optim' local dl = require 'dataload' local xlua = require 'xlua' local c = require 'trepl.colorize' --local debugger = require 'fb.debugger' opt = lapp[[ -s,--save (default "logs") subdirectory to save logs -b,--batchSize (default 64) batch size -r,--learningRate (default 0.0001) learning rate --learningRateDecay (default 1e-7) learning rate decay --weightDecay (default 0.0005) weightDecay -m,--momentum (default 0.9) momentum --epoch_step (default 25) epoch step --model (default vgg) model name --max_epoch (default 300) maximum number of iterations --backend (default nn) backend --mode (default L2) L2/L1/learningrate --type (default cuda) cuda/float/cl --numMeta (default 3) #episode --hLR (default 0.0001) learningrate of hyperparameter --initHyper (default 0.001) initial value for hyperparameter ]] print(c.blue "==> " .. "parameter:") print(opt) grad.optimize(true) -- Load in MNIST print(c.blue '==>' ..' loading data') local trainset, validset, testset = dl.loadCIFAR10() local classes = testset.classes local confusionMatrix = optim.ConfusionMatrix(classes) print(c.blue ' completed!') local predict, model, modelf, dfTrain, params, initParams, params_l2 local hyper_params = {} local function cast(t) if opt.type == 'cuda' then require 'cunn' return t:cuda() elseif opt.type == 'float' then return t:float() elseif opt.type == 'cl' then require 'clnn' return t:cl() else error('Unknown type '..opt.type) end end local function L2_norm_create(params, initHyper) local hyper_L2 = {} for i = 1, #params do -- dimension = 1 is bias, do not need L2_reg if (params[i]:nDimension() > 1) then hyper_L2[i] = params[i]:clone():fill(initHyper) end end return hyper_L2 end local function L2_norm(params, params_l2) -- print(params_l2, params[1]) local penalty = torch.sum(torch.cmul(params[1], params_l2[1])) -- local penalty = torch.sum(params[1]) -- local penalty = 0 -- for i = 1, #params do -- -- dimension = 1 is bias, do not need L2_reg -- if (params[i]:nDimension() > 1) then -- print(i) -- penalty = penalty + torch.sum(params[i]) * params_l2[i] -- end -- end return penalty end local function init(iter) ---- --- build VGG net. ---- if iter == 1 then -- load model print(c.blue '==>' ..' configuring model') model = cast(dofile(root .. 'models/'..opt.model..'.lua')) -- cast a model using functionalize modelf, params = grad.functionalize(model) params_l2 = L2_norm_create(params, opt.initHyper) local Lossf = grad.nn.MSECriterion() local function fTrain(params, x, y) print(params.p1) print(params.p2) local prediction = modelf(params.p2, x) local penalty = L2_norm(params.p2, params.p1) return Lossf(prediction, y) + penalty end dfTrain = grad(fTrain) -- a simple unit test local X = cast(torch.Tensor(64, 3, 32, 32):fill(0.5)) local Y = cast(torch.Tensor(64, 10):fill(0)) local p = { p1 = params_l2, p2 = params } local dparams, l = dfTrain(p, X, Y) if (l) then print(c.green ' Auto Diff works!') end print(c.blue ' completed!') end print(c.blue '==>' ..' initializing model') utils.MSRinit(model) print(c.blue ' completed!') -- copy initial weights for later computation initParams = utils.deepcopy(params) end local function train_meta(iter) --[[ One meta-iteration to get directives w.r.t. hyperparameters ]] ----------------------------------- -- [[Meta training]] ----------------------------------- -- Train a neural network to get final parameters for epoch = 1, opt.max_epoch do print(c.blue '==>' ..' Meta episode #' .. iter .. ', Training epoch #' .. epoch) for i, inputs, targets in trainset:subiter(opt.batchSize) do local function makesample(inputs, targets) local t_ = torch.FloatTensor(targets:size(1), 10):zero() for j = 1, targets:size(1) do t_[targets[j]] = 1 end return inputs:cuda(), t_:cuda() end local p = { p1 = params_l2, p2 = params } local grads, loss = dfTrain(p, makesample(inputs, targets)) for i = 1, #grads do params[i] = params[i] + opt.learningRate * grads[i] end print(c.red 'loss: ', loss) end end -- copy final parameters after convergence local finalParams = utils.deepcopy(params) finalParams = nn.utils.recursiveCopy(finalParams, params) ----------------------- -- [[Reverse mode hyper-parameter training: -- to get gradient w.r.t. hyper-parameters]] ----------------------- end ----------------------------- -- entry point ----------------------------- local time = sys.clock() for i = 1, opt.numMeta do init(i) -- print("wtf", model) train_meta(i) end time = sys.clock() - time print(time)
--[[ Multiple meta-iterations for DrMAD on CIFAR10 ]] require 'torch' require 'sys' require 'image' local root = '../' local grad = require 'autograd' local utils = require(root .. 'models/utils.lua') local optim = require 'optim' local dl = require 'dataload' local xlua = require 'xlua' local c = require 'trepl.colorize' --local debugger = require 'fb.debugger' opt = lapp[[ -s,--save (default "logs") subdirectory to save logs -b,--batchSize (default 64) batch size -r,--learningRate (default 0.0001) learning rate --learningRateDecay (default 1e-7) learning rate decay --weightDecay (default 0.0005) weightDecay -m,--momentum (default 0.9) momentum --epoch_step (default 25) epoch step --model (default vgg) model name --max_epoch (default 300) maximum number of iterations --backend (default nn) backend --mode (default L2) L2/L1/learningrate --type (default cuda) cuda/float/cl --numMeta (default 3) #episode --hLR (default 0.0001) learningrate of hyperparameter --initHyper (default 0.001) initial value for hyperparameter ]] print(c.blue "==> " .. "parameter:") print(opt) grad.optimize(true) -- Load in MNIST print(c.blue '==>' ..' loading data') local trainset, validset, testset = dl.loadCIFAR10() local classes = testset.classes local confusionMatrix = optim.ConfusionMatrix(classes) print(c.blue ' completed!') local predict, model, modelf, dfTrain, params, initParams, params_l2 local hyper_params = {} local function cast(t) if opt.type == 'cuda' then require 'cunn' return t:cuda() elseif opt.type == 'float' then return t:float() elseif opt.type == 'cl' then require 'clnn' return t:cl() else error('Unknown type '..opt.type) end end local function L2_norm_create(params, initHyper) local hyper_L2 = {} for i = 1, #params do -- dimension = 1 is bias, do not need L2_reg if (params[i]:nDimension() > 1) then hyper_L2[i] = params[i]:clone():fill(initHyper) end end return hyper_L2 end local function L2_norm(params, params_l2) -- print(params_l2, params[1]) -- local penalty = torch.sum(torch.cmul(params[1], params_l2[1])) -- local penalty = torch.sum(params[1]) local penalty = 0 for i = 1, #params do --dimension = 1 is bias, do not need L2_reg if (params[i]:nDimension() > 1) then -- print('it works!'..i) -- print(params[i]) -- print(params_l2[i]) penalty = penalty + torch.sum(torch.cmul(torch.cmul(params[i], params[i]), params_l2[i])) -- print("finish!") end end return penalty end local function init(iter) ---- --- build VGG net. ---- if iter == 1 then -- load model print(c.blue '==>' ..' configuring model') model = cast(dofile(root .. 'models/'..opt.model..'.lua')) -- cast a model using functionalize modelf, params = grad.functionalize(model) params_l2 = L2_norm_create(params, opt.initHyper) local Lossf = grad.nn.MSECriterion() local function fTrain(params, x, y) -- print(params.p1) -- print(params.p2) local prediction = modelf(params.p2, x) local penalty = L2_norm(params.p2, params.p1) return Lossf(prediction, y) + penalty end dfTrain = grad(fTrain) -- a simple unit test local X = cast(torch.Tensor(64, 3, 32, 32):fill(0.5)) local Y = cast(torch.Tensor(64, 10):fill(0)) local p = { p1 = params_l2, p2 = params } local dparams, l = dfTrain(p, X, Y) if (l) then print(c.green ' Auto Diff works!') end print(c.blue ' completed!') end print(c.blue '==>' ..' initializing model') utils.MSRinit(model) print(c.blue ' completed!') -- copy initial weights for later computation initParams = utils.deepcopy(params) end local function train_meta(iter) --[[ One meta-iteration to get directives w.r.t. hyperparameters ]] ----------------------------------- -- [[Meta training]] ----------------------------------- -- Train a neural network to get final parameters for epoch = 1, opt.max_epoch do print(c.blue '==>' ..' Meta episode #' .. iter .. ', Training epoch #' .. epoch) for i, inputs, targets in trainset:subiter(opt.batchSize) do local function makesample(inputs, targets) local t_ = torch.FloatTensor(targets:size(1), 10):zero() for j = 1, targets:size(1) do t_[targets[j]] = 1 end return inputs:cuda(), t_:cuda() end local p = { p1 = params_l2, p2 = params } local grads, loss = dfTrain(p, makesample(inputs, targets)) for i = 1, #grads do params[i] = params[i] + opt.learningRate * grads[i] end print(c.red 'loss: ', loss) end end -- copy final parameters after convergence local finalParams = utils.deepcopy(params) finalParams = nn.utils.recursiveCopy(finalParams, params) ----------------------- -- [[Reverse mode hyper-parameter training: -- to get gradient w.r.t. hyper-parameters]] ----------------------- end ----------------------------- -- entry point ----------------------------- local time = sys.clock() for i = 1, opt.numMeta do init(i) -- print("wtf", model) train_meta(i) end time = sys.clock() - time print(time)
fix bug: equation is wrong.
fix bug: equation is wrong.
Lua
mit
bigaidream-projects/drmad
b1786cdb8fcaa589f575f63d1a79cf0b6daa25d6
lua/entities/gmod_wire_clutch.lua
lua/entities/gmod_wire_clutch.lua
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Clutch" ENT.Purpose = "Allows rotational friction to be varied dynamically" ENT.WireDebugName = "Clutch" if CLIENT then return end -- No more client function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self.Inputs = Wire_CreateInputs( self, { "Friction" } ) //self.Outputs = Wire_CreateOutputs( self, { "Welded" } ) self.clutch_friction = 0 self.clutch_ballsockets = {} -- Table of constraints as keys self:UpdateOverlay() end function ENT:UpdateOverlay() local text = "Friction: " .. tostring( self.clutch_friction ) .. "\n" local num_constraints = table.Count( self.clutch_ballsockets ) if num_constraints > 0 then text = text .. "Links: " .. tostring( num_constraints ) else text = text .. "Unlinked" end self:SetOverlayText( text ) end /*--------------------------------------------------------- -- Constraint functions -- Functions for handling clutch constraints ---------------------------------------------------------*/ function ENT:ClutchExists( Ent1, Ent2 ) for k, v in pairs( self.clutch_ballsockets ) do if ( Ent1 == k.Ent1 and Ent2 == k.Ent2 ) or ( Ent1 == k.Ent2 and Ent2 == k.Ent1 ) then return true end end return false end // Returns an array with each entry as a table containing Ent1, Ent2 function ENT:GetConstrainedPairs() local ConstrainedPairs = {} for k, v in pairs( self.clutch_ballsockets ) do if IsValid( k ) then table.insert( ConstrainedPairs, {Ent1 = k.Ent1, Ent2 = k.Ent2} ) else self.clutch_ballsockets[k] = nil end end return ConstrainedPairs end local function NewBallSocket( Ent1, Ent2, friction ) if !IsValid( Ent1 ) then return false end local ballsocket = constraint.AdvBallsocket( Ent1, Ent2, 0, 0, Vector(0,0,0), Vector(0,0,0), 0, 0, -180, -180, -180, 180, 180, 180, friction, friction, friction, 1, 0 ) if ballsocket then // Prevent ball socket from being affected by dupe/remove functions ballsocket.Type = "" end return ballsocket end // Register a new clutch association with the controller function ENT:AddClutch( Ent1, Ent2, friction ) local ballsocket = NewBallSocket( Ent1, Ent2, friction or self.clutch_friction ) if ballsocket then self:DeleteOnRemove( ballsocket ) self.clutch_ballsockets[ballsocket] = true end self:UpdateOverlay() return ballsocket end // Remove a new clutch association from the controller function ENT:RemoveClutch( const ) self.clutch_ballsockets[const] = nil if IsValid( const ) then const:Remove() end self:UpdateOverlay() end function ENT:SetClutchFriction( const, friction ) // There seems to be no direct way to edit constraint friction, so we must create a new ball socket constraint self.clutch_ballsockets[const] = nil if IsValid( const ) then local Ent1 = const.Ent1 local Ent2 = const.Ent2 const:Remove() local newconst = NewBallSocket( Ent1, Ent2, friction ) self:DeleteOnRemove( newconst ) self.clutch_ballsockets[newconst] = true else print("Wire Clutch: Attempted to set friction on invalid constraint") end return true end /*--------------------------------------------------------- -- Main controller functions -- Handle controller tables, wire input ---------------------------------------------------------*/ // Used for setting/restoring entity mass when creating the clutch constraint local function SaveMass( MassTable, ent ) if IsValid( ent ) and !MassTable[ent] then local Phys = ent:GetPhysicsObject() if IsValid( Phys ) then MassTable[ent] = Phys:GetMass() Phys:SetMass(1) end end end local function RestoreMass( MassTable ) for k, v in pairs( MassTable ) do k:GetPhysicsObject():SetMass( v ) end end // Set friction on all constrained ents, called by input or timer (if delayed) function ENT:UpdateFriction() // Set masses to 1 - this will prevents friction from varying depending on mass local MassTable = {} // Create a table copy so when we start ammending self.clutch_ballsockets, it won't affect this loop local clutch_ballsockets = table.Copy( self.clutch_ballsockets ) // Update all registered ball socket constraints local numconstraints = 0 -- Used to calculate the delay between inputs for k, v in pairs( clutch_ballsockets ) do if !IsValid( k ) then self:RemoveClutch( k ) else SaveMass( MassTable, k.Ent1 ) SaveMass( MassTable, k.Ent2 ) self:SetClutchFriction( k, self.clutch_friction ) numconstraints = numconstraints + 1 end end RestoreMass( MassTable ) self:UpdateOverlay() return numconstraints end // Called when the clutch input delay timer finishes local function ClutchDelayEnd( ent ) ent.ClutchDelay = nil if ent.delayed_clutch_friction then ent:TriggerInput( "Friction", ent.delayed_clutch_friction ) ent.delayed_clutch_friction = nil end end function ENT:TriggerInput( iname, value ) if iname == "Friction" then if !self.ClutchDelay then self.clutch_friction = value // Create a delay to avoid server lag local numconstraints = self:UpdateFriction() local maxrate = math.max( GetConVarNumber( "wire_clutch_maxrate", 20 ), 1 ) local Delay = numconstraints / maxrate self.ClutchDelay = true timer.Create( "wire_clutch_delay_" .. tostring(self:EntIndex()), Delay, 0, function() ClutchDelayEnd(self) end ) else // This should only happen if an error prevents the ClutchDelayEnd function from being called if !timer.Exists( "wire_clutch_delay_" .. tostring(self:EntIndex())) then self.ClutchDelay = false end // Store new friction value so it can be updated after the delay self.delayed_clutch_friction = value end end end /*--------------------------------------------------------- -- Adv Duplicator Support -- Linked entities are stored and recalled by their EntIndexes ---------------------------------------------------------*/ function ENT:BuildDupeInfo() local info = self.BaseClass.BuildDupeInfo(self) or {} info.constrained_pairs = {} for k, v in pairs( self:GetConstrainedPairs() ) do info.constrained_pairs[k] = {} info.constrained_pairs[k].Ent1 = v.Ent1:EntIndex() or 0 info.constrained_pairs[k].Ent2 = v.Ent2:EntIndex() or 0 end return info end function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID) self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID) for k, v in pairs( info.constrained_pairs ) do Ent1 = GetEntByID(v.Ent1) Ent2 = GetEntByID(v.Ent2, game.GetWorld()) if IsValid(Ent1) and Ent1 ~= Ent2 and hook.Run( "CanTool", ply, WireLib.dummytrace(Ent1), "ballsocket_adv" ) and hook.Run( "CanTool", ply, WireLib.dummytrace(Ent2), "ballsocket_adv" ) then self:AddClutch( Ent1, Ent2 ) end end end duplicator.RegisterEntityClass("gmod_wire_clutch", WireLib.MakeWireEnt, "Data")
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Clutch" ENT.Purpose = "Allows rotational friction to be varied dynamically" ENT.WireDebugName = "Clutch" if CLIENT then return end -- No more client function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self.Inputs = Wire_CreateInputs( self, { "Friction" } ) --self.Outputs = Wire_CreateOutputs( self, { "Welded" } ) self.clutch_friction = 0 self.clutch_ballsockets = {} -- Table of constraints as keys self:UpdateOverlay() end function ENT:UpdateOverlay() local text = "Friction: " .. tostring( self.clutch_friction ) .. "\n" local num_constraints = table.Count( self.clutch_ballsockets ) if num_constraints > 0 then text = text .. "Links: " .. tostring( num_constraints ) else text = text .. "Unlinked" end self:SetOverlayText( text ) end --[[------------------------------------------------------- -- Constraint functions -- Functions for handling clutch constraints ---------------------------------------------------------]] function ENT:ClutchExists( Ent1, Ent2 ) for k, v in pairs( self.clutch_ballsockets ) do if ( Ent1 == k.Ent1 and Ent2 == k.Ent2 ) or ( Ent1 == k.Ent2 and Ent2 == k.Ent1 ) then return true end end return false end -- Returns an array with each entry as a table containing Ent1, Ent2 function ENT:GetConstrainedPairs() local ConstrainedPairs = {} for k, v in pairs( self.clutch_ballsockets ) do if IsValid( k ) then table.insert( ConstrainedPairs, {Ent1 = k.Ent1, Ent2 = k.Ent2} ) else self.clutch_ballsockets[k] = nil end end return ConstrainedPairs end local function NewBallSocket( Ent1, Ent2, friction ) if not IsValid( Ent1 ) or not IsValid( Ent2 ) then return false end local ballsocket = constraint.AdvBallsocket( Ent1, Ent2, 0, 0, Vector(0,0,0), Vector(0,0,0), 0, 0, -180, -180, -180, 180, 180, 180, friction, friction, friction, 1, 0 ) if ballsocket then -- Prevent ball socket from being affected by dupe/remove functions ballsocket.Type = "" end return ballsocket end -- Register a new clutch association with the controller function ENT:AddClutch( Ent1, Ent2, friction ) local ballsocket = NewBallSocket( Ent1, Ent2, friction or self.clutch_friction ) if ballsocket then self.clutch_ballsockets[ballsocket] = true end self:UpdateOverlay() return ballsocket end -- Remove a new clutch association from the controller function ENT:RemoveClutch( const ) self.clutch_ballsockets[const] = nil if IsValid( const ) then const:Remove() end self:UpdateOverlay() end function ENT:SetClutchFriction( const, friction ) -- There seems to be no direct way to edit constraint friction, so we must create a new ball socket constraint self.clutch_ballsockets[const] = nil if IsValid( const ) then local Ent1 = const.Ent1 local Ent2 = const.Ent2 const:Remove() local newconst = NewBallSocket( Ent1, Ent2, friction ) if newconst then self.clutch_ballsockets[newconst] = true end else print("Wire Clutch: Attempted to set friction on invalid constraint") end return true end function ENT:OnRemove() for k, v in pairs( self.clutch_ballsockets ) do self:RemoveClutch( k ) end end --[[------------------------------------------------------- -- Main controller functions -- Handle controller tables, wire input ---------------------------------------------------------]] -- Used for setting/restoring entity mass when creating the clutch constraint local function SaveMass( MassTable, ent ) if IsValid( ent ) and !MassTable[ent] then local Phys = ent:GetPhysicsObject() if IsValid( Phys ) then MassTable[ent] = Phys:GetMass() Phys:SetMass(1) end end end local function RestoreMass( MassTable ) for k, v in pairs( MassTable ) do k:GetPhysicsObject():SetMass( v ) end end -- Set friction on all constrained ents, called by input or timer (if delayed) function ENT:UpdateFriction() -- Set masses to 1 - this will prevents friction from varying depending on mass local MassTable = {} -- Create a table copy so when we start ammending self.clutch_ballsockets, it won't affect this loop local clutch_ballsockets = table.Copy( self.clutch_ballsockets ) -- Update all registered ball socket constraints local numconstraints = 0 -- Used to calculate the delay between inputs for k, v in pairs( clutch_ballsockets ) do if !IsValid( k ) then self:RemoveClutch( k ) else SaveMass( MassTable, k.Ent1 ) SaveMass( MassTable, k.Ent2 ) self:SetClutchFriction( k, self.clutch_friction ) numconstraints = numconstraints + 1 end end RestoreMass( MassTable ) self:UpdateOverlay() return numconstraints end -- Called when the clutch input delay timer finishes local function ClutchDelayEnd( ent ) ent.ClutchDelay = nil if ent.delayed_clutch_friction then ent:TriggerInput( "Friction", ent.delayed_clutch_friction ) ent.delayed_clutch_friction = nil end end function ENT:TriggerInput( iname, value ) if iname == "Friction" then if !self.ClutchDelay then self.clutch_friction = value -- Create a delay to avoid server lag local numconstraints = self:UpdateFriction() local maxrate = math.max( GetConVarNumber( "wire_clutch_maxrate", 20 ), 1 ) local Delay = numconstraints / maxrate self.ClutchDelay = true timer.Create( "wire_clutch_delay_" .. tostring(self:EntIndex()), Delay, 0, function() ClutchDelayEnd(self) end ) else -- This should only happen if an error prevents the ClutchDelayEnd function from being called if !timer.Exists( "wire_clutch_delay_" .. tostring(self:EntIndex())) then self.ClutchDelay = false end -- Store new friction value so it can be updated after the delay self.delayed_clutch_friction = value end end end --[[------------------------------------------------------- -- Adv Duplicator Support -- Linked entities are stored and recalled by their EntIndexes ---------------------------------------------------------]] function ENT:BuildDupeInfo() local info = self.BaseClass.BuildDupeInfo(self) or {} info.constrained_pairs = {} for k, v in pairs( self:GetConstrainedPairs() ) do info.constrained_pairs[k] = {} info.constrained_pairs[k].Ent1 = v.Ent1:EntIndex() or 0 info.constrained_pairs[k].Ent2 = v.Ent2:EntIndex() or 0 end return info end function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID) self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID) for k, v in pairs( info.constrained_pairs ) do Ent1 = GetEntByID(v.Ent1) Ent2 = GetEntByID(v.Ent2, game.GetWorld()) if IsValid(Ent1) and Ent1 ~= Ent2 and hook.Run( "CanTool", ply, WireLib.dummytrace(Ent1), "ballsocket_adv" ) and hook.Run( "CanTool", ply, WireLib.dummytrace(Ent2), "ballsocket_adv" ) then self:AddClutch( Ent1, Ent2 ) end end end duplicator.RegisterEntityClass("gmod_wire_clutch", WireLib.MakeWireEnt, "Data")
Fixed NULL error on removal. Moved constraint cleanup to OnRemoved.
Fixed NULL error on removal. Moved constraint cleanup to OnRemoved.
Lua
apache-2.0
bigdogmat/wire,wiremod/wire,sammyt291/wire,dvdvideo1234/wire,notcake/wire,thegrb93/wire,mitterdoo/wire,mms92/wire,CaptainPRICE/wire,Grocel/wire,rafradek/wire,garrysmodlua/wire,NezzKryptic/Wire
32147c5679eb904a3c7008de0e9ab17142e3276a
9p.lua
9p.lua
data = require "data" dio = require "data_io" io = require "io" -- Returns a 9P number in table format. Offset and size in bytes function num9p(offset, size) return {offset*8, size*8, 'number', 'le'} end function putstr(to, s) -- XXX if an empty string is passed down, we segfault in setting p.s if #s == 0 then return end if #s > #to - 2 then io.stderr:write("small\n") return 0 end local p = to:segment():layout{len = num9p(0, 2), s = {2, #s, 's'}} p.len = #s p.s = s return 1 end function getstr(from) local p = from:segment() local len = p:layout{len = num9p(0, 2)}.len return p:layout{str = {2, len, 's'}}.str end function version() local Xversion = data.layout{ size = num9p(0, 4), type = num9p(4, 1), tag = num9p(5, 2), msize = num9p(7, 4), } local txbuf = data.new(19) txbuf:layout(Xversion) txbuf.size = 19 txbuf.type = 100 txbuf.tag = 0 txbuf.msize = 8192 putstr(txbuf:segment(11), "9P2000") dio.write(txbuf, 0, txbuf.size) local rxbuf = data.new(8192) rxbuf:layout(Xversion) dio.read(rxbuf, 0, 4) dio.read(rxbuf, 4, rxbuf.size-4) return rxbuf.msize end function attach(uname, aname) local LTattach = data.layout{ size = num9p(0, 4), type = num9p(4, 1), tag = num9p(5, 2), fid = num9p(7, 4), afid = num9p(11, 4), } local LRattach = data.layout{ size = num9p(0, 4), type = num9p(4, 1), tag = num9p(5, 2), qtype = num9p(7, 1), qvers = num9p(8, 4), qpath = num9p(12, 8), } local tx = txbuf:segment() tx:layout(LTattach) tx.size = 22 tx.type = 104 tx.tag = 0 tx.fid = 0 tx.afid = -1 putstr(tx:segment(15), uname) putstr(tx:segment(21), aname) dio.write(tx, 0, tx.size) local rx = rxbuf:segment() rx:layout(LRattach) dio.read(rx, 0, 4) dio.read(rx, 0, rx.size-4) end msize = version() txbuf = data.new(msize) rxbuf = data.new(msize) attach("iru", "")
data = require "data" dio = require "data_io" io = require "io" function perr(s) io.stderr:write(s .. "\n") end -- Returns a 9P number in table format. Offset and size in bytes function num9p(offset, size) return {offset*8, size*8, 'number', 'le'} end function putstr(to, s) -- XXX if an empty string is passed down, we segfault in setting p.s if #s > #to - 2 then return end local p = to:segment():layout{len = num9p(0, 2), s = {2, #s, 's'}} p.len = #s p.s = s end function getstr(from) local p = from:segment() local len = p:layout{len = num9p(0, 2)}.len return p:layout{str = {2, len, 's'}}.str end function version() local Xversion = data.layout{ size = num9p(0, 4), type = num9p(4, 1), tag = num9p(5, 2), msize = num9p(7, 4), } local txbuf = data.new(19) txbuf:layout(Xversion) txbuf.size = 19 txbuf.type = 100 txbuf.tag = 0 txbuf.msize = 8192 putstr(txbuf:segment(11), "9P2000") dio.write(txbuf, 0, txbuf.size) local rxbuf = data.new(8192) rxbuf:layout(Xversion) dio.read(rxbuf, 0, 4) dio.read(rxbuf, 4, rxbuf.size-4) return rxbuf.msize end function attach(uname, aname) local LTattach = data.layout{ size = num9p(0, 4), type = num9p(4, 1), tag = num9p(5, 2), fid = num9p(7, 4), afid = num9p(11, 4), } local LRattach = data.layout{ size = num9p(0, 4), type = num9p(4, 1), tag = num9p(5, 2), qtype = num9p(7, 1), qvers = num9p(8, 4), qpath = num9p(12, 8), } local tx = txbuf:segment() tx:layout(LTattach) tx.size = 15 + 2 + #uname + 2 + #aname tx.type = 104 tx.tag = 0 tx.fid = 0 tx.afid = -1 putstr(tx:segment(15), uname) putstr(tx:segment(15 + 2 + #uname), aname) dio.write(tx, 0, tx.size) local rx = rxbuf:segment() rx:layout(LRattach) dio.read(rx, 0, 4) dio.read(rx, 4, rx.size-4) end function walk(fid, newfid, name) local LTwalk = data.layout{ size = num9p(0, 4), type = num9p(4, 1), tag = num9p(5, 2), fid = num9p(7, 4), nfid = num9p(11, 4), nwname = num9p(15, 2), } local LRwalk = data.layout{ size = num9p(0, 4), type = num9p(4, 1), tag = num9p(5, 2), nwqid = num9p(7, 2), } local tx = txbuf:segment() tx:layout(LTwalk) -- #name == 0 clones the fid tx.size = 17 + (#name ~= 0 and 2 or 0) + #name tx.type = 110 tx.tag = 0 tx.fid = fid tx.nfid = newfid tx.nwname = (#name ~= 0 and 1 or 0) putstr(tx:segment(17), name) dio.write(tx, 0, tx.size) local rx = rxbuf:segment() rx:layout(LRwalk) dio.read(rx, 0, 4) dio.read(rx, 4, rx.size-4) end function fidclone(fid, newfid) walk(fid, newfid, "") end function _test() msize = version() txbuf = data.new(msize) rxbuf = data.new(msize) attach("iru", "") walk(0, 1, "/tmp") fidclone(1, 2) end _test()
Implement walk. Fix attach.
Implement walk. Fix attach.
Lua
bsd-3-clause
iru-/lua9p,iru-/lua9p
8f84bff236b52df079ce6ad3a7cdd598c1525518
MMOCoreORB/bin/scripts/mobile/quest/tatooine/wizzel.lua
MMOCoreORB/bin/scripts/mobile/quest/tatooine/wizzel.lua
wizzel = Creature:new { objectName = "", socialGroup = "thug", faction = "thug", level = 13, chanceHit = 0.3, damageMin = 140, damageMax = 150, baseXp = 714, baseHAM = 1500, baseHAMmax = 1900, armor = 0, resists = {0,0,0,0,0,0,0,-1,-1}, meatType = "", meatAmount = 0, hideType = "", hideAmount = 0, boneType = "", boneAmount = 0, milk = 0, tamingChance = 0, ferocity = 0, pvpBitmask = AGGRESSIVE + ATTACKABLE + ENEMY, creatureBitmask = PACK + KILLER, optionsBitmask = 128, diet = HERBIVORE, templates = {"object/mobile/dressed_tatooine_rodian_clan_warchief.iff"}, lootGroups = { { groups = { {group = "task_loot_rakir_banai_contract", chance = 10000000} }, lootChance = 10000000 } }, weapons = {"rebel_weapons_heavy"}, conversationTemplate = "", attacks = merge(marksmanmid,brawlermid) } CreatureTemplates:addCreatureTemplate(wizzel, "wizzel")
wizzel = Creature:new { objectName = "", socialGroup = "mercenary", faction = "", level = 13, chanceHit = 0.3, damageMin = 140, damageMax = 150, baseXp = 714, baseHAM = 1500, baseHAMmax = 1900, armor = 0, resists = {0,0,0,0,0,0,0,-1,-1}, meatType = "", meatAmount = 0, hideType = "", hideAmount = 0, boneType = "", boneAmount = 0, milk = 0, tamingChance = 0, ferocity = 0, pvpBitmask = ATTACKABLE, creatureBitmask = PACK + KILLER, optionsBitmask = 128, diet = HERBIVORE, templates = {"object/mobile/dressed_tatooine_rodian_clan_warchief.iff"}, lootGroups = { { groups = { {group = "task_loot_rakir_banai_contract", chance = 10000000} }, lootChance = 10000000 } }, weapons = {"rebel_weapons_heavy"}, conversationTemplate = "", attacks = merge(marksmanmid,brawlermid) } CreatureTemplates:addCreatureTemplate(wizzel, "wizzel")
[Fixed] targets in rakir banai's 4th mission no longer attack each other - mantis 6667
[Fixed] targets in rakir banai's 4th mission no longer attack each other - mantis 6667 Change-Id: Ib2d87a634a1d4303bca294daa6aa3c3e08ca1dbd
Lua
agpl-3.0
Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo
15183a0e7bf9853ae1ff11f77a30aa591e125b91
src/premake4.lua
src/premake4.lua
-- Procedurally Generated Transitional Audio Build -- -- A solution contains projects, and defines the available configurations solution "pgta_engine" location "build" --startproject "pgta_engine" language "C++" -- build configurations -- configurations { "Debug", "Release" } configuration "Debug" targetdir "build/Debug" defines { "DEBUG", "_DEBUG" } configuration "Release" targetdir "build/Release" defines { "NDEBUG" } optimize "Full" flags{ "LinkTimeOptimization", "MultiProcessorCompile" } configuration {} -- A project defines one build target project "engine" kind "ConsoleApp" targetdir "../bin" language "C++" files { "pgta_engine/**.h", "pgta_engine/**.cpp" } configuration "linux" buildoptions { "-std=c++11" } configuration{}
-- Procedurally Generated Transitional Audio Build -- -- A solution contains projects, and defines the available configurations solution "pgta_engine" location "build" --startproject "pgta_engine" language "C++" platforms { "x32", "x64" } -- build configurations -- configurations { "Debug", "Release" } configuration "Debug" targetdir "build/Debug" defines { "DEBUG", "_DEBUG" } configuration "Release" targetdir "build/Release" defines { "NDEBUG" } optimize "Full" flags{ "LinkTimeOptimization", "MultiProcessorCompile" } configuration "x32" targetsuffix "_x32" configuration "x64" targetsuffix "_x64" configuration {} -- A project defines one build target project "engine" kind "ConsoleApp" targetdir "../bin" language "C++" files { "pgta_engine/**.h", "pgta_engine/**.cpp" } configuration "linux" buildoptions { "-std=c++11" } configuration{}
Updated premake script to append configuration suffix to the end of the target name.
Updated premake script to append configuration suffix to the end of the target name.
Lua
mit
PGTA/PGTA,PGTA/PGTA,PGTA/PGTA
e00978cfdbea9551676166dd1b1dc3748f11398d
src/npge/block/identity.lua
src/npge/block/identity.lua
local round = function(x) return math.floor(x + 0.5) end local mt = {} mt.__index = mt -- use C version if available local has_c, cidentity = pcall(require, 'npge.block.cidentity') if has_c then mt.__call = function(self, block) local rows = {} for fragment in block:iter_fragments() do table.insert(rows, block:text(fragment)) end return cidentity(rows, #rows, block:length()) end else mt.__call = function(self, block) local ident = 0 for bp = 0, block:length() - 1 do local gap, first, bad for fragment in block:iter_fragments() do local letter = block:at(fragment, bp) if letter == '-' then gap = true elseif first and letter ~= first then bad = true -- different nongap letters break else first = letter end end if not bad and not gap then ident = ident + 1 elseif not bad and gap then ident = ident + 0.5 end end return ident / block:length() end end -- round to 0.001 and compare local MULTIPLIER = 1000 mt.less = function(a, b) return round(a * MULTIPLIER) < round(b * MULTIPLIER) end mt.eq = function(a, b) return round(a * MULTIPLIER) == round(b * MULTIPLIER) end return setmetatable({}, mt)
local round = function(x) return math.floor(x + 0.5) end local mt = {} mt.__index = mt -- use C version if available local has_c, cidentity = pcall(require, 'npge.block.cidentity') if has_c then mt.__call = function(self, block) local rows = {} for fragment in block:iter_fragments() do table.insert(rows, block:text(fragment)) end return cidentity(rows, #rows, block:length()) end else mt.__call = function(self, block) local ident = 0 for bp = 0, block:length() - 1 do local gap, first, bad for fragment in block:iter_fragments() do local at = require 'npge.block.at' local letter = at(block, fragment, bp) if letter == '-' then gap = true elseif first and letter ~= first then bad = true -- different nongap letters break else first = letter end end if not bad and not gap then ident = ident + 1 elseif not bad and gap then ident = ident + 0.5 end end return ident / block:length() end end -- round to 0.001 and compare local MULTIPLIER = 1000 mt.less = function(a, b) return round(a * MULTIPLIER) < round(b * MULTIPLIER) end mt.eq = function(a, b) return round(a * MULTIPLIER) == round(b * MULTIPLIER) end return setmetatable({}, mt)
fix identity (pure Lua impl)
fix identity (pure Lua impl) Forget to update code using block:at (removed method)
Lua
mit
starius/lua-npge,npge/lua-npge,npge/lua-npge,starius/lua-npge,starius/lua-npge,npge/lua-npge
39535b06faa3c0c624ca576fa180dc716be78cdc
mod_register_json/mod_register_json.lua
mod_register_json/mod_register_json.lua
-- Expose a simple servlet to handle user registrations from web pages -- via JSON. -- -- A Good chunk of the code is from mod_data_access.lua by Kim Alvefur -- aka Zash. local jid_prep = require "util.jid".prep local jid_split = require "util.jid".split local usermanager = require "core.usermanager" local b64_decode = require "util.encodings".base64.decode local json_decode = require "util.json".decode local os_time = os.time local nodeprep = require "util.encodings".stringprep.nodeprep module:depends("http") module:set_global() -- Pick up configuration. local set_realm_name = module:get_option_string("reg_servlet_realm", "Restricted") local base_path = module:get_option_string("reg_servlet_base", "/register_account/") local throttle_time = module:get_option_number("reg_servlet_ttime", nil) local whitelist = module:get_option_set("reg_servlet_wl", {}) local blacklist = module:get_option_set("reg_servlet_bl", {}) local recent_ips = {} -- Begin local function http_response(event, code, message, headers) local response = event.response if headers then for header, data in pairs(headers) do response.headers[header] = data end end response.headers.content_type = "application/json" response.status_code = code response:send(message) end local function handle_req(event) local request = event.request local body = request.body if request.method ~= "POST" then return http_response(event, 405, "Bad method...", {["Allow"] = "POST"}) end if not request.headers["authorization"] then return http_response(event, 401, "No... No...", {["WWW-Authenticate"]='Basic realm="'.. set_realm_name ..'"'}) end local user, password = b64_decode(request.headers.authorization:match("[^ ]*$") or ""):match("([^:]*):(.*)") user = jid_prep(user) if not user or not password then return http_response(event, 400, "What's this..?") end local user_node, user_host = jid_split(user) if not hosts[user_host] then return http_response(event, 401, "Negative.") end module:log("warn", "%s is authing to submit a new user registration data", user) if not usermanager.test_password(user_node, user_host, password) then module:log("warn", "%s failed authentication", user) return http_response(event, 401, "Who the hell are you?! Guards!") end local req_body -- We check that what we have is valid JSON wise else we throw an error... if not pcall(function() req_body = json_decode(body) end) then module:log("debug", "JSON data submitted for user registration by %s failed to Decode.", user) return http_response(event, 400, "JSON Decoding failed.") else -- Decode JSON data and check that all bits are there else throw an error req_body = json_decode(body) if req_body["username"] == nil or req_body["password"] == nil or req_body["host"] == nil or req_body["ip"] == nil then module:log("debug", "%s supplied an insufficent number of elements or wrong elements for the JSON registration", user) return http_response(event, 400, "Invalid syntax.") end -- Check if user is an admin of said host if not usermanager.is_admin(user, req_body["host"]) then module:log("warn", "%s tried to submit registration data for %s but he's not an admin", user, req_body["host"]) return http_response(event, 401, "I obey only to my masters... Have a nice day.") else -- Checks for both Throttling/Whitelist and Blacklist (basically copycatted from prosody's register.lua code) if blacklist:contains(req_body["ip"]) then module:log("warn", "Attempt of reg. submission to the JSON servlet from blacklisted address: %s", req_body["ip"]) ; return http_response(403, "The specified address is blacklisted, sorry sorry.") end if throttle_time and not whitelist:contains(req_body["ip"]) then if not recent_ips[req_body["ip"]] then recent_ips[req_body["ip"]] = os_time() else if os_time() - recent_ips[req_body["ip"]] < throttle_time then recent_ips[req_body["ip"]] = os_time() module:log("warn", "JSON Registration request from %s has been throttled.", req_body["ip"]) return http_response(503, "Woah... How many users you want to register..? Request throttled, wait a bit and try again.") end recent_ips[req_body["ip"]] = os_time() end end -- We first check if the supplied username for registration is already there. -- And nodeprep the username local username = nodeprep(req_body["username"]) if not usermanager.user_exists(username, req_body["host"]) then if not username then module:log("debug", "%s supplied an username containing invalid characters: %s", user, username) return http_response(event, 406, "Supplied username contains invalid characters, see RFC 6122.") else local ok, error = usermanager.create_user(username, req_body["password"], req_body["host"]) if ok then hosts[req_body["host"]].events.fire_event("user-registered", { username = username, host = req_body["host"], source = "mod_register_json", session = { ip = req_body["ip"] } }) module:log("debug", "%s registration data submission for %s@%s is successful", user, username, req_body["host"]) return http_response(event, 200, "Done.") else module:log("error", "user creation failed: "..error) return http_response(event 500, "Encountered server error while creating the user: "..error) end end else module:log("debug", "%s registration data submission for %s failed (user already exists)", user, username) return http_response(event, 409, "User already exists.") end end end end -- Set it up! module:provides("http", { default_path = base_path, route = { ["GET /"] = handle_req, ["POST /"] = handle_req } })
-- Expose a simple servlet to handle user registrations from web pages -- via JSON. -- -- A Good chunk of the code is from mod_data_access.lua by Kim Alvefur -- aka Zash. local jid_prep = require "util.jid".prep local jid_split = require "util.jid".split local usermanager = require "core.usermanager" local b64_decode = require "util.encodings".base64.decode local json_decode = require "util.json".decode local os_time = os.time local nodeprep = require "util.encodings".stringprep.nodeprep module:depends("http") module:set_global() -- Pick up configuration. local secure = module:get_option_boolean("reg_servlet_secure", true) local set_realm_name = module:get_option_string("reg_servlet_realm", "Restricted") local base_path = module:get_option_string("reg_servlet_base", "/register_account/") local throttle_time = module:get_option_number("reg_servlet_ttime", nil) local whitelist = module:get_option_set("reg_servlet_wl", {}) local blacklist = module:get_option_set("reg_servlet_bl", {}) local recent_ips = {} -- Begin local function http_response(event, code, message, headers) local response = event.response if headers then for header, data in pairs(headers) do response.headers[header] = data end end response.headers.content_type = "application/json" response.status_code = code response:send(message) end local function handle_req(event) local request = event.request local body = request.body if request.method ~= "POST" then return http_response(event, 405, "Bad method...", {["Allow"] = "POST"}) end if not request.headers["authorization"] then return http_response(event, 401, "No... No...", {["WWW-Authenticate"]='Basic realm="'.. set_realm_name ..'"'}) end local user, password = b64_decode(request.headers.authorization:match("[^ ]*$") or ""):match("([^:]*):(.*)") user = jid_prep(user) if not user or not password then return http_response(event, 400, "What's this..?") end local user_node, user_host = jid_split(user) if not hosts[user_host] then return http_response(event, 401, "Negative.") end module:log("warn", "%s is authing to submit a new user registration data", user) if not usermanager.test_password(user_node, user_host, password) then module:log("warn", "%s failed authentication", user) return http_response(event, 401, "Who the hell are you?! Guards!") end local req_body -- We check that what we have is valid JSON wise else we throw an error... if not pcall(function() req_body = json_decode(body) end) then module:log("debug", "JSON data submitted for user registration by %s failed to Decode.", user) return http_response(event, 400, "JSON Decoding failed.") else -- Decode JSON data and check that all bits are there else throw an error req_body = json_decode(body) if req_body["username"] == nil or req_body["password"] == nil or req_body["host"] == nil or req_body["ip"] == nil then module:log("debug", "%s supplied an insufficent number of elements or wrong elements for the JSON registration", user) return http_response(event, 400, "Invalid syntax.") end -- Check if user is an admin of said host if not usermanager.is_admin(user, req_body["host"]) then module:log("warn", "%s tried to submit registration data for %s but he's not an admin", user, req_body["host"]) return http_response(event, 401, "I obey only to my masters... Have a nice day.") else -- Checks for both Throttling/Whitelist and Blacklist (basically copycatted from prosody's register.lua code) if blacklist:contains(req_body["ip"]) then module:log("warn", "Attempt of reg. submission to the JSON servlet from blacklisted address: %s", req_body["ip"]) ; return http_response(403, "The specified address is blacklisted, sorry sorry.") end if throttle_time and not whitelist:contains(req_body["ip"]) then if not recent_ips[req_body["ip"]] then recent_ips[req_body["ip"]] = os_time() else if os_time() - recent_ips[req_body["ip"]] < throttle_time then recent_ips[req_body["ip"]] = os_time() module:log("warn", "JSON Registration request from %s has been throttled.", req_body["ip"]) return http_response(503, "Woah... How many users you want to register..? Request throttled, wait a bit and try again.") end recent_ips[req_body["ip"]] = os_time() end end -- We first check if the supplied username for registration is already there. -- And nodeprep the username local username = nodeprep(req_body["username"]) if not usermanager.user_exists(username, req_body["host"]) then if not username then module:log("debug", "%s supplied an username containing invalid characters: %s", user, username) return http_response(event, 406, "Supplied username contains invalid characters, see RFC 6122.") else local ok, error = usermanager.create_user(username, req_body["password"], req_body["host"]) if ok then hosts[req_body["host"]].events.fire_event("user-registered", { username = username, host = req_body["host"], source = "mod_register_json", session = { ip = req_body["ip"] } }) module:log("debug", "%s registration data submission for %s@%s is successful", user, username, req_body["host"]) return http_response(event, 200, "Done.") else module:log("error", "user creation failed: "..error) return http_response(event, 500, "Encountered server error while creating the user: "..error) end end else module:log("debug", "%s registration data submission for %s failed (user already exists)", user, username) return http_response(event, 409, "User already exists.") end end end end -- Set it up! module:provides((secure and "https" or "http"), { default_path = base_path, route = { ["GET /"] = handle_req, ["POST /"] = handle_req } })
mod_register_json: fixed typo, added https/http switch and default value to it.
mod_register_json: fixed typo, added https/http switch and default value to it.
Lua
mit
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
86c626b9e8f2a359a3b810a70e86d38817d6d694
spec/plugins/keyauth/api_spec.lua
spec/plugins/keyauth/api_spec.lua
local json = require "cjson" local http_client = require "kong.tools.http_client" local spec_helper = require "spec.spec_helpers" describe("Key Auth Credentials API", function() local BASE_URL, credential, consumer setup(function() spec_helper.prepare_db() spec_helper.start_kong() end) teardown(function() spec_helper.stop_kong() end) describe("/consumers/:consumer/keyauth/", function() setup(function() local fixtures = spec_helper.insert_fixtures { consumer = {{ username = "bob" }} } consumer = fixtures.consumer[1] BASE_URL = spec_helper.API_URL.."/consumers/bob/keyauth/" end) describe("POST", function() it("[SUCCESS] should create a keyauth credential", function() local response, status = http_client.post(BASE_URL, { key = "1234" }) assert.equal(201, status) credential = json.decode(response) assert.equal(consumer.id, credential.consumer_id) end) it("[FAILURE] should return proper errors", function() local response, status = http_client.post(BASE_URL, {}) assert.equal(400, status) assert.equal('{"key":"key is required"}\n', response) end) end) describe("PUT", function() setup(function() spec_helper.get_env().dao_factory.keyauth_credentials:delete({id = credential.id}) end) it("[SUCCESS] should create and update", function() local response, status = http_client.put(BASE_URL, { key = "1234" }) assert.equal(201, status) credential = json.decode(response) assert.equal(consumer.id, credential.consumer_id) end) it("[FAILURE] should return proper errors", function() local response, status = http_client.put(BASE_URL, {}) assert.equal(400, status) assert.equal('{"key":"key is required"}\n', response) end) end) describe("GET", function() it("should retrieve all", function() local response, status = http_client.get(BASE_URL) assert.equal(200, status) local body = json.decode(response) assert.equal(1, #(body.data)) end) end) end) describe("/consumers/:consumer/keyauth/:id", function() describe("GET", function() it("should retrieve by id", function() local _, status = http_client.get(BASE_URL..credential.id) assert.equal(200, status) end) end) describe("PATCH", function() it("[SUCCESS] should update a credential", function() local response, status = http_client.patch(BASE_URL..credential.id, { key = "4321" }) assert.equal(200, status) credential = json.decode(response) assert.equal("4321", credential.key) end) it("[FAILURE] should return proper errors", function() local response, status = http_client.patch(BASE_URL..credential.id, { key = "" }) assert.equal(400, status) assert.equal('{"key":"key is not a string"}\n', response) end) end) describe("DELETE", function() it("[FAILURE] should return proper errors", function() local _, status = http_client.delete(BASE_URL.."blah") assert.equal(400, status) _, status = http_client.delete(BASE_URL.."00000000-0000-0000-0000-000000000000") assert.equal(404, status) end) it("[SUCCESS] should delete a credential", function() local _, status = http_client.delete(BASE_URL..credential.id) assert.equal(204, status) end) end) end) end)
local json = require "cjson" local http_client = require "kong.tools.http_client" local spec_helper = require "spec.spec_helpers" describe("Key Auth Credentials API", function() local BASE_URL, credential, consumer setup(function() spec_helper.prepare_db() spec_helper.start_kong() end) teardown(function() spec_helper.stop_kong() end) describe("/consumers/:consumer/keyauth/", function() setup(function() local fixtures = spec_helper.insert_fixtures { consumer = {{ username = "bob" }} } consumer = fixtures.consumer[1] BASE_URL = spec_helper.API_URL.."/consumers/bob/keyauth/" end) describe("POST", function() it("[SUCCESS] should create a keyauth credential", function() local response, status = http_client.post(BASE_URL, { key = "1234" }) assert.equal(201, status) credential = json.decode(response) assert.equal(consumer.id, credential.consumer_id) end) it("[SUCCESS] should create a keyauth credential auto-generating the key", function() local response, status = http_client.post(BASE_URL, {}) assert.equal(201, status) end) end) describe("PUT", function() setup(function() spec_helper.get_env().dao_factory.keyauth_credentials:delete({id = credential.id}) end) it("[SUCCESS] should create and update", function() local response, status = http_client.put(BASE_URL, { key = "1234" }) assert.equal(201, status) credential = json.decode(response) assert.equal(consumer.id, credential.consumer_id) end) it("[SUCCESS] should create a keyauth credential auto-generating the key", function() local response, status = http_client.put(BASE_URL, {}) assert.equal(201, status) end) end) describe("GET", function() it("should retrieve all", function() local response, status = http_client.get(BASE_URL) assert.equal(200, status) local body = json.decode(response) assert.equal(3, #(body.data)) end) end) end) describe("/consumers/:consumer/keyauth/:id", function() describe("GET", function() it("should retrieve by id", function() local _, status = http_client.get(BASE_URL..credential.id) assert.equal(200, status) end) end) describe("PATCH", function() it("[SUCCESS] should update a credential", function() local response, status = http_client.patch(BASE_URL..credential.id, { key = "4321" }) assert.equal(200, status) credential = json.decode(response) assert.equal("4321", credential.key) end) it("[FAILURE] should return proper errors", function() local response, status = http_client.patch(BASE_URL..credential.id, { key = "" }) assert.equal(400, status) assert.equal('{"key":"key is not a string"}\n', response) end) end) describe("DELETE", function() it("[FAILURE] should return proper errors", function() local _, status = http_client.delete(BASE_URL.."blah") assert.equal(400, status) _, status = http_client.delete(BASE_URL.."00000000-0000-0000-0000-000000000000") assert.equal(404, status) end) it("[SUCCESS] should delete a credential", function() local _, status = http_client.delete(BASE_URL..credential.id) assert.equal(204, status) end) end) end) end)
Fixing test
Fixing test Former-commit-id: 854e276ac7a90897abb5d91f92de411b3095caab
Lua
apache-2.0
streamdataio/kong,isdom/kong,Kong/kong,ind9/kong,akh00/kong,beauli/kong,kyroskoh/kong,Kong/kong,rafael/kong,jerizm/kong,vzaramel/kong,ajayk/kong,jebenexer/kong,Kong/kong,streamdataio/kong,ejoncas/kong,Mashape/kong,li-wl/kong,ind9/kong,Vermeille/kong,xvaara/kong,smanolache/kong,shiprabehera/kong,kyroskoh/kong,isdom/kong,rafael/kong,ccyphers/kong,ejoncas/kong,salazar/kong,icyxp/kong,vzaramel/kong
24ec07ff1f7d7c3b1e8da9e91e3932d9f4269608
nyagos.d/box.lua
nyagos.d/box.lua
if not nyagos then print("This is a script for nyagos not lua.exe") os.exit() end nyagos.key.C_o = function(this) local word,pos = this:lastword() word = string.gsub(word,'"','') local wildcard = word.."*" local list = nyagos.glob(wildcard) if #list == 1 and list[1] == wildcard then return end local dict = {} local array = {} for _,path in ipairs(list) do local index=string.find(path,"[^\\/]+$") local fname if index then fname=string.sub(path,index) else fname=path end local stat1 = nyagos.stat(path) if stat1 and stat1.isdir then path = path .. nyagos.pathseparator fname = fname .. nyagos.pathseparator end array[1+#array] = fname dict[fname] = path end nyagos.write("\n") local result={ nyagos.box(array) } if result and type(result)=='table' then local tmp={} for _,val in ipairs(result) do local one=dict[val] if one then if string.find(one," ",1,true) then if string.find(one,"^~[\\/]") then if string.sub(one,string.len(one)) == "\\" then -- dont put quotation after \ -- one = '~"'..string.sub(one,2) else one = '~"'..string.sub(one,2)..'"' end else if string.sub(one,string.len(one)) == "\\" then -- dont put quotation after \ -- one = '"'..one else one = '"'..one..'"' end end end tmp[#tmp+1] = one end end result = tmp else result = { word } end this:call("REPAINT_ON_NEWLINE") assert( this:replacefrom(pos,table.concat(result," ")) ) end share.__dump_history = function() local uniq={} local result={} for i=nyagos.gethistory()-1,1,-1 do local line = nyagos.gethistory(i) if line ~= "" and not uniq[line] then result[ #result+1 ] = line uniq[line] = true end end return result end nyagos.key.C_x = function(this) nyagos.write("\nC-x: [r]:command-history, [h]:cd-history, [g]:git-revision\n") local ch = nyagos.getkey() local c = string.lower(string.char(ch)) local result if c == 'r' or ch == nyagos.bitand(string.byte('r'),0x1F) then result = nyagos.box(share.__dump_history()) elseif c == 'h' or ch == nyagos.bitand(string.byte('h') , 0x1F) then result = nyagos.eval('cd --history | box') if string.find(result,' ') then result = '"'..result..'"' end elseif c == 'g' or ch == nyagos.bitand(string.byte('g'),0x1F) then result = nyagos.eval('git log --pretty="format:%h %s" | box') result = string.match(result,"^%S+") or "" end this:call("REPAINT_ON_NEWLINE") return result end nyagos.key.M_r = function(this) nyagos.write("\n") local result = nyagos.box(share.__dump_history()) this:call("REPAINT_ON_NEWLINE") if string.find(result,' ') then result = '"'..result..'"' end return result end nyagos.key.M_h = function(this) nyagos.write("\n") local result = nyagos.eval('cd --history | box') this:call("REPAINT_ON_NEWLINE") if string.find(result,' ') then result = '"'..result..'"' end return result end nyagos.key.M_g = function(this) nyagos.write("\n") local result = nyagos.eval('git log --pretty="format:%h %s" | box') this:call("REPAINT_ON_NEWLINE") return string.match(result,"^%S+") or "" end nyagos.key["M-o"] = function(this) local spacecut = false if string.match(this.text," $") then this:call("BACKWARD_DELETE_CHAR") spacecut = true end local path,pos = this:lastword() if not string.match(path,"%.[Ll][Nn][Kk]$") then if spacecut then return " " end return end path = string.gsub(path,'"','') path = string.gsub(path,"/","\\") path = string.gsub(path,"^~",os.getenv("USERPROFILE")) local wsh,err = nyagos.create_object("WScript.Shell") if wsh then local shortcut = wsh:CreateShortCut(path) if shortcut then local newpath = shortcut:_get("TargetPath") if newpath then local isDir = false local fso = nyagos.create_object("Scripting.FileSystemObject") if fso then if fso:FolderExists(newpath) then isDir = true end fso:_release() end if string.find(newpath," ") then if isDir then newpath = '"'..newpath..'\\' else newpath = '"'..newpath..'"' if spacecut then newpath = newpath .. ' ' end end elseif isDir then newpath = newpath .. '\\' elseif spacecut then newpath = newpath .. ' ' end if string.len(newpath) > 0 then this:replacefrom(pos,newpath) end end shortcut:_release() end wsh:_release() end end
if not nyagos then print("This is a script for nyagos not lua.exe") os.exit() end nyagos.key.C_o = function(this) local word,pos = this:lastword() word = string.gsub(word,'"','') local wildcard = word.."*" local list = nyagos.glob(wildcard) if #list == 1 and list[1] == wildcard then return end local dict = {} local array = {} for _,path in ipairs(list) do local index=string.find(path,"[^\\/]+$") local fname if index then fname=string.sub(path,index) else fname=path end local stat1 = nyagos.stat(path) if stat1 and stat1.isdir then path = path .. nyagos.pathseparator fname = fname .. nyagos.pathseparator end array[1+#array] = fname dict[fname] = path end nyagos.write("\n") local result={ nyagos.box(array) } if result and type(result)=='table' then local tmp={} for _,val in ipairs(result) do local one=dict[val] if one then if string.find(one," ",1,true) then if string.find(one,"^~[\\/]") then if string.sub(one,string.len(one)) == "\\" then -- dont put quotation after \ -- one = '~"'..string.sub(one,2) else one = '~"'..string.sub(one,2)..'"' end else if string.sub(one,string.len(one)) == "\\" then -- dont put quotation after \ -- one = '"'..one else one = '"'..one..'"' end end end tmp[#tmp+1] = one end end if tmp and #tmp >= 1 then result = tmp else result = { word } end else result = { word } end this:call("REPAINT_ON_NEWLINE") assert( this:replacefrom(pos,table.concat(result," ")) ) end share.__dump_history = function() local uniq={} local result={} for i=nyagos.gethistory()-1,1,-1 do local line = nyagos.gethistory(i) if line ~= "" and not uniq[line] then result[ #result+1 ] = line uniq[line] = true end end return result end nyagos.key.C_x = function(this) nyagos.write("\nC-x: [r]:command-history, [h]:cd-history, [g]:git-revision\n") local ch = nyagos.getkey() local c = string.lower(string.char(ch)) local result if c == 'r' or ch == nyagos.bitand(string.byte('r'),0x1F) then result = nyagos.box(share.__dump_history()) elseif c == 'h' or ch == nyagos.bitand(string.byte('h') , 0x1F) then result = nyagos.eval('cd --history | box') if string.find(result,' ') then result = '"'..result..'"' end elseif c == 'g' or ch == nyagos.bitand(string.byte('g'),0x1F) then result = nyagos.eval('git log --pretty="format:%h %s" | box') result = string.match(result,"^%S+") or "" end this:call("REPAINT_ON_NEWLINE") return result end nyagos.key.M_r = function(this) nyagos.write("\n") local result = nyagos.box(share.__dump_history()) this:call("REPAINT_ON_NEWLINE") if string.find(result,' ') then result = '"'..result..'"' end return result end nyagos.key.M_h = function(this) nyagos.write("\n") local result = nyagos.eval('cd --history | box') this:call("REPAINT_ON_NEWLINE") if string.find(result,' ') then result = '"'..result..'"' end return result end nyagos.key.M_g = function(this) nyagos.write("\n") local result = nyagos.eval('git log --pretty="format:%h %s" | box') this:call("REPAINT_ON_NEWLINE") return string.match(result,"^%S+") or "" end nyagos.key["M-o"] = function(this) local spacecut = false if string.match(this.text," $") then this:call("BACKWARD_DELETE_CHAR") spacecut = true end local path,pos = this:lastword() if not string.match(path,"%.[Ll][Nn][Kk]$") then if spacecut then return " " end return end path = string.gsub(path,'"','') path = string.gsub(path,"/","\\") path = string.gsub(path,"^~",os.getenv("USERPROFILE")) local wsh,err = nyagos.create_object("WScript.Shell") if wsh then local shortcut = wsh:CreateShortCut(path) if shortcut then local newpath = shortcut:_get("TargetPath") if newpath then local isDir = false local fso = nyagos.create_object("Scripting.FileSystemObject") if fso then if fso:FolderExists(newpath) then isDir = true end fso:_release() end if string.find(newpath," ") then if isDir then newpath = '"'..newpath..'\\' else newpath = '"'..newpath..'"' if spacecut then newpath = newpath .. ' ' end end elseif isDir then newpath = newpath .. '\\' elseif spacecut then newpath = newpath .. ' ' end if string.len(newpath) > 0 then this:replacefrom(pos,newpath) end end shortcut:_release() end wsh:_release() end end
Fix: C-o and ESCAPE erased the user-input-word.
Fix: C-o and ESCAPE erased the user-input-word.
Lua
bsd-3-clause
zetamatta/nyagos,tsuyoshicho/nyagos
3c2caae0c2cc683b8346084cae6e1ce530b12573
src/luarocks/cmd/new_version.lua
src/luarocks/cmd/new_version.lua
--- Module implementing the LuaRocks "new_version" command. -- Utility function that writes a new rockspec, updating data from a previous one. local new_version = {} local util = require("luarocks.util") local download = require("luarocks.download") local fetch = require("luarocks.fetch") local persist = require("luarocks.persist") local fs = require("luarocks.fs") local dir = require("luarocks.dir") local type_rockspec = require("luarocks.type.rockspec") function new_version.add_to_parser(parser) local cmd = parser:command("new_version", [[ This is a utility function that writes a new rockspec, updating data from a previous one. If a package name is given, it downloads the latest rockspec from the default server. If a rockspec is given, it uses it instead. If no argument is given, it looks for a rockspec same way 'luarocks make' does. If the version number is not given and tag is passed using --tag, it is used as the version, with 'v' removed from beginning. Otherwise, it only increments the revision number of the given (or downloaded) rockspec. If a URL is given, it replaces the one from the old rockspec with the given URL. If a URL is not given and a new version is given, it tries to guess the new URL by replacing occurrences of the version number in the URL or tag. It also tries to download the new URL to determine the new MD5 checksum. If a tag is given, it replaces the one from the old rockspec. If there is an old tag but no new one passed, it is guessed in the same way URL is. If a directory is not given, it defaults to the current directory. WARNING: it writes the new rockspec to the given directory, overwriting the file if it already exists.]], util.see_also()) :summary("Auto-write a rockspec for a new version of a rock.") cmd:argument("rock", "Package name or rockspec.") :args("?") cmd:argument("new_version", "New version of the rock.") :args("?") cmd:argument("new_url", "New URL of the rock.") :args("?") cmd:option("--dir", "Output directory for the new rockspec.") cmd:option("--tag", "New SCM tag.") end local function try_replace(tbl, field, old, new) if not tbl[field] then return false end local old_field = tbl[field] local new_field = tbl[field]:gsub(old, new) if new_field ~= old_field then util.printout("Guessing new '"..field.."' field as "..new_field) tbl[field] = new_field return true end return false end -- Try to download source file using URL from a rockspec. -- If it specified MD5, update it. -- @return (true, false) if MD5 was not specified or it stayed same, -- (true, true) if MD5 changed, (nil, string) on error. local function check_url_and_update_md5(out_rs) local file, temp_dir = fetch.fetch_url_at_temp_dir(out_rs.source.url, "luarocks-new-version-"..out_rs.package) if not file then util.warning("invalid URL - "..temp_dir) return true, false end local inferred_dir, found_dir = fetch.find_base_dir(file, temp_dir, out_rs.source.url, out_rs.source.dir) if not inferred_dir then return nil, found_dir end if found_dir and found_dir ~= inferred_dir then out_rs.source.dir = found_dir end if file then if out_rs.source.md5 then util.printout("File successfully downloaded. Updating MD5 checksum...") local new_md5, err = fs.get_md5(file) if not new_md5 then return nil, err end local old_md5 = out_rs.source.md5 out_rs.source.md5 = new_md5 return true, new_md5 ~= old_md5 else util.printout("File successfully downloaded.") return true, false end end end local function update_source_section(out_rs, url, tag, old_ver, new_ver) if tag then out_rs.source.tag = tag end if url then out_rs.source.url = url return check_url_and_update_md5(out_rs) end if new_ver == old_ver then return true end if out_rs.source.dir then try_replace(out_rs.source, "dir", old_ver, new_ver) end if out_rs.source.file then try_replace(out_rs.source, "file", old_ver, new_ver) end if try_replace(out_rs.source, "url", old_ver, new_ver) then return check_url_and_update_md5(out_rs) end if tag or try_replace(out_rs.source, "tag", old_ver, new_ver) then return true end -- Couldn't replace anything significant, use the old URL. local ok, md5_changed = check_url_and_update_md5(out_rs) if not ok then return nil, md5_changed end if md5_changed then util.warning("URL is the same, but MD5 has changed. Old rockspec is broken.") end return true end function new_version.command(args) if not args.rock then local err args.rock, err = util.get_default_rockspec() if not args.rock then return nil, err end end local filename, err if args.rock:match("rockspec$") then filename, err = fetch.fetch_url(args.rock) if not filename then return nil, err end else filename, err = download.download("rockspec", args.rock:lower()) if not filename then return nil, err end end local valid_rs, err = fetch.load_rockspec(filename) if not valid_rs then return nil, err end local old_ver, old_rev = valid_rs.version:match("(.*)%-(%d+)$") local new_ver, new_rev if args.tag and not args.new_version then args.new_version = args.tag:gsub("^v", "") end local out_dir if args.dir then out_dir = dir.normalize(args.dir) end if args.new_version then new_ver, new_rev = args.new_version:match("(.*)%-(%d+)$") new_rev = tonumber(new_rev) if not new_rev then new_ver = args.new_version new_rev = 1 end else new_ver = old_ver new_rev = tonumber(old_rev) + 1 end local new_rockver = new_ver:gsub("-", "") local out_rs, err = persist.load_into_table(filename) local out_name = out_rs.package:lower() out_rs.version = new_rockver.."-"..new_rev local ok, err = update_source_section(out_rs, args.new_url, args.tag, old_ver, new_ver) if not ok then return nil, err end if out_rs.build and out_rs.build.type == "module" then out_rs.build.type = "builtin" end local out_filename = out_name.."-"..new_rockver.."-"..new_rev..".rockspec" if out_dir then out_filename = dir.path(out_dir, out_filename) fs.make_dir(out_dir) end persist.save_from_table(out_filename, out_rs, type_rockspec.order) util.printout("Wrote "..out_filename) local valid_out_rs, err = fetch.load_local_rockspec(out_filename) if not valid_out_rs then return nil, "Failed loading generated rockspec: "..err end return true end return new_version
--- Module implementing the LuaRocks "new_version" command. -- Utility function that writes a new rockspec, updating data from a previous one. local new_version = {} local util = require("luarocks.util") local download = require("luarocks.download") local fetch = require("luarocks.fetch") local persist = require("luarocks.persist") local fs = require("luarocks.fs") local dir = require("luarocks.dir") local type_rockspec = require("luarocks.type.rockspec") function new_version.add_to_parser(parser) local cmd = parser:command("new_version", [[ This is a utility function that writes a new rockspec, updating data from a previous one. If a package name is given, it downloads the latest rockspec from the default server. If a rockspec is given, it uses it instead. If no argument is given, it looks for a rockspec same way 'luarocks make' does. If the version number is not given and tag is passed using --tag, it is used as the version, with 'v' removed from beginning. Otherwise, it only increments the revision number of the given (or downloaded) rockspec. If a URL is given, it replaces the one from the old rockspec with the given URL. If a URL is not given and a new version is given, it tries to guess the new URL by replacing occurrences of the version number in the URL or tag; if the guessed URL is invalid, the old URL is restored. It also tries to download the new URL to determine the new MD5 checksum. If a tag is given, it replaces the one from the old rockspec. If there is an old tag but no new one passed, it is guessed in the same way URL is. If a directory is not given, it defaults to the current directory. WARNING: it writes the new rockspec to the given directory, overwriting the file if it already exists.]], util.see_also()) :summary("Auto-write a rockspec for a new version of a rock.") cmd:argument("rock", "Package name or rockspec.") :args("?") cmd:argument("new_version", "New version of the rock.") :args("?") cmd:argument("new_url", "New URL of the rock.") :args("?") cmd:option("--dir", "Output directory for the new rockspec.") cmd:option("--tag", "New SCM tag.") end local function try_replace(tbl, field, old, new) if not tbl[field] then return false end local old_field = tbl[field] local new_field = tbl[field]:gsub(old, new) if new_field ~= old_field then util.printout("Guessing new '"..field.."' field as "..new_field) tbl[field] = new_field return true end return false end -- Try to download source file using URL from a rockspec. -- If it specified MD5, update it. -- @return (true, false) if MD5 was not specified or it stayed same, -- (true, true) if MD5 changed, (nil, string) on error. local function check_url_and_update_md5(out_rs, invalid_is_error) local file, temp_dir = fetch.fetch_url_at_temp_dir(out_rs.source.url, "luarocks-new-version-"..out_rs.package) if not file then if invalid_is_error then return nil, "invalid URL - "..temp_dir end util.warning("invalid URL - "..temp_dir) return true, false end local inferred_dir, found_dir = fetch.find_base_dir(file, temp_dir, out_rs.source.url, out_rs.source.dir) if not inferred_dir then return nil, found_dir end if found_dir and found_dir ~= inferred_dir then out_rs.source.dir = found_dir end if file then if out_rs.source.md5 then util.printout("File successfully downloaded. Updating MD5 checksum...") local new_md5, err = fs.get_md5(file) if not new_md5 then return nil, err end local old_md5 = out_rs.source.md5 out_rs.source.md5 = new_md5 return true, new_md5 ~= old_md5 else util.printout("File successfully downloaded.") return true, false end end end local function update_source_section(out_rs, url, tag, old_ver, new_ver) if tag then out_rs.source.tag = tag end if url then out_rs.source.url = url return check_url_and_update_md5(out_rs) end if new_ver == old_ver then return true end if out_rs.source.dir then try_replace(out_rs.source, "dir", old_ver, new_ver) end if out_rs.source.file then try_replace(out_rs.source, "file", old_ver, new_ver) end local old_url = out_rs.source.url if try_replace(out_rs.source, "url", old_ver, new_ver) then local ok, md5_changed = check_url_and_update_md5(out_rs, true) if ok then return ok, md5_changed end out_rs.source.url = old_url end if tag or try_replace(out_rs.source, "tag", old_ver, new_ver) then return true end -- Couldn't replace anything significant, use the old URL. local ok, md5_changed = check_url_and_update_md5(out_rs) if not ok then return nil, md5_changed end if md5_changed then util.warning("URL is the same, but MD5 has changed. Old rockspec is broken.") end return true end function new_version.command(args) if not args.rock then local err args.rock, err = util.get_default_rockspec() if not args.rock then return nil, err end end local filename, err if args.rock:match("rockspec$") then filename, err = fetch.fetch_url(args.rock) if not filename then return nil, err end else filename, err = download.download("rockspec", args.rock:lower()) if not filename then return nil, err end end local valid_rs, err = fetch.load_rockspec(filename) if not valid_rs then return nil, err end local old_ver, old_rev = valid_rs.version:match("(.*)%-(%d+)$") local new_ver, new_rev if args.tag and not args.new_version then args.new_version = args.tag:gsub("^v", "") end local out_dir if args.dir then out_dir = dir.normalize(args.dir) end if args.new_version then new_ver, new_rev = args.new_version:match("(.*)%-(%d+)$") new_rev = tonumber(new_rev) if not new_rev then new_ver = args.new_version new_rev = 1 end else new_ver = old_ver new_rev = tonumber(old_rev) + 1 end local new_rockver = new_ver:gsub("-", "") local out_rs, err = persist.load_into_table(filename) local out_name = out_rs.package:lower() out_rs.version = new_rockver.."-"..new_rev local ok, err = update_source_section(out_rs, args.new_url, args.tag, old_ver, new_ver) if not ok then return nil, err end if out_rs.build and out_rs.build.type == "module" then out_rs.build.type = "builtin" end local out_filename = out_name.."-"..new_rockver.."-"..new_rev..".rockspec" if out_dir then out_filename = dir.path(out_dir, out_filename) fs.make_dir(out_dir) end persist.save_from_table(out_filename, out_rs, type_rockspec.order) util.printout("Wrote "..out_filename) local valid_out_rs, err = fetch.load_local_rockspec(out_filename) if not valid_out_rs then return nil, "Failed loading generated rockspec: "..err end return true end return new_version
fix(new_version): keep the old url if the md5 doesn't change.
fix(new_version): keep the old url if the md5 doesn't change.
Lua
mit
keplerproject/luarocks,keplerproject/luarocks,luarocks/luarocks,luarocks/luarocks,luarocks/luarocks,keplerproject/luarocks,keplerproject/luarocks
3115c80120856a686816599880cf0aa9c7d136c8
kong/tools/dns.lua
kong/tools/dns.lua
local utils = require "kong.tools.utils" local dns_client --- Load and setup the DNS client according to the provided configuration. -- @param conf (table) Kong configuration -- @return the initialized `resty.dns.client` module, or an error local setup_client = function(conf) if not dns_client then dns_client = require "resty.dns.client" end conf = conf or {} local servers = {} -- servers must be reformatted as name/port sub-arrays if conf.dns_resolver then for i, server in ipairs(conf.dns_resolver) do local s = utils.normalize_ip(server) servers[i] = { s.host, s.port or 53 } -- inserting port if omitted end end local opts = { hosts = conf.dns_hostsfile, resolvConf = nil, -- defaults to system resolv.conf nameservers = servers, -- provided list or taken from resolv.conf enable_ipv6 = true, -- allow for ipv6 nameserver addresses retrans = nil, -- taken from system resolv.conf; attempts timeout = nil, -- taken from system resolv.conf; timeout validTtl = conf.dns_valid_ttl, -- ttl in seconds overriding ttl of valid records badTtl = conf.dns_not_found_ttl, -- ttl in seconds for dns error responses (except 3 - name error) emptyTtl = conf.dns_error_ttl, -- ttl in seconds for empty and "(3) name error" dns responses staleTtl = conf.dns_stale_ttl, -- ttl in seconds for records once they become stale order = conf.dns_order, -- order of trying record types noSynchronisation = conf.dns_no_sync, } assert(dns_client.init(opts)) return dns_client end return setup_client
local utils = require "kong.tools.utils" local dns_client --- Load and setup the DNS client according to the provided configuration. -- @param conf (table) Kong configuration -- @return the initialized `resty.dns.client` module, or an error local setup_client = function(conf) if not dns_client then dns_client = require "resty.dns.client" end conf = conf or {} local servers = {} -- servers must be reformatted as name/port sub-arrays if conf.dns_resolver then for i, server in ipairs(conf.dns_resolver) do local s = utils.normalize_ip(server) servers[i] = { s.host, s.port or 53 } -- inserting port if omitted end end local opts = { hosts = conf.dns_hostsfile, resolvConf = nil, -- defaults to system resolv.conf nameservers = servers, -- provided list or taken from resolv.conf enable_ipv6 = true, -- allow for ipv6 nameserver addresses retrans = nil, -- taken from system resolv.conf; attempts timeout = nil, -- taken from system resolv.conf; timeout validTtl = conf.dns_valid_ttl, -- ttl in seconds overriding ttl of valid records badTtl = conf.dns_error_ttl, -- ttl in seconds for dns error responses (except 3 - name error) emptyTtl = conf.dns_not_found_ttl, -- ttl in seconds for empty and "(3) name error" dns responses staleTtl = conf.dns_stale_ttl, -- ttl in seconds for records once they become stale order = conf.dns_order, -- order of trying record types noSynchronisation = conf.dns_no_sync, } assert(dns_client.init(opts)) return dns_client end return setup_client
fix(dns) config parameters swapped (#5684)
fix(dns) config parameters swapped (#5684)
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
209224902758b5cde52ce145ab0e89a8efd081fb
Threshold.lua
Threshold.lua
require 'nn' require 'cltorch' local function floatToString(val) local valstring = tostring(val) if valstring:find('%.') or valstring:find('e') then valstring = valstring .. 'f' end return valstring end function torch.ClTensor.nn.Threshold_updateOutput(self, input) -- print('torch.nn.ReLU -- self.output:map(input, "*out = *in1 > 0.0f ? *in1 : 0.0f") self.thresholdstring = floatToString(self.threshold) self.valstring = floatToString(self.val) if self.inplace then input:apply("*out = (*out > " .. self.thresholdstring .. ") ? *out : " .. self.valstring) self.output = input else self.output:resize(input:size()) self.output:map(input, "*out = ( *in1 > " .. self.thresholdstring .. ") ? *in1 : " .. self.valstring) end return self.output end function torch.ClTensor.nn.Threshold_updateGradInput(self, input, gradOutput) local nElement = self.gradInput:nElement() self.gradInput:resizeAs(input) if self.gradInput:nElement() ~= nElement then self.gradInput:zero() end if self.inplace then gradOutput:map2(input, gradOutput, "*out = (*in1 > " .. self.thresholdstring .. ") ? *in2 : 0.0f") self.gradInput = gradOutput else self.gradInput:map2(input, gradOutput, "*out = (*in1 > " .. self.thresholdstring .. ") ? *in2 : 0.0f") end -- self.gradInput:map2(gradOutput, self.output, "*out = *in2 > 0.0f ? *in1 : 0.0f") return self.gradInput end
require 'nn' require 'cltorch' nn.Threshold.baseUpdateOutput = nn.Threshold.updateOutput nn.Threshold.baseUpdateGradInput = nn.Threshold.updateGradInput local function floatToString(val) local valstring = tostring(val) if valstring:find('%.') or valstring:find('e') then valstring = valstring .. 'f' end return valstring end function nn.Threshold.updateOutput(self, input) if torch.type(input) ~= 'torch.ClTensor' then return self:baseUpdateOutput(input) end self.thresholdstring = floatToString(self.threshold) self.valstring = floatToString(self.val) if self.inplace then input:apply("*out = (*out > " .. self.thresholdstring .. ") ? *out : " .. self.valstring) self.output = input else self.output:resize(input:size()) self.output:map(input, "*out = ( *in1 > " .. self.thresholdstring .. ") ? *in1 : " .. self.valstring) end return self.output end function nn.Threshold.updateGradInput(self, input, gradOutput) if torch.type(input) ~= 'torch.ClTensor' then return self:baseUpdateGradInput(input, gradOutput) end local nElement = self.gradInput:nElement() self.gradInput:resizeAs(input) if self.gradInput:nElement() ~= nElement then self.gradInput:zero() end if self.inplace then gradOutput:map2(input, gradOutput, "*out = (*in1 > " .. self.thresholdstring .. ") ? *in2 : 0.0f") self.gradInput = gradOutput else self.gradInput:map2(input, gradOutput, "*out = (*in1 > " .. self.thresholdstring .. ") ? *in2 : 0.0f") end return self.gradInput end
fix Threshold for THNN
fix Threshold for THNN
Lua
bsd-2-clause
hughperkins/clnn,hughperkins/clnn,hughperkins/clnn,hughperkins/clnn
3b93896a2049ede2b1ef20a5020a2cfdcd1dc917
scripts/bgfx.lua
scripts/bgfx.lua
-- -- Copyright 2010-2018 Branimir Karadzic. All rights reserved. -- License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause -- function filesexist(_srcPath, _dstPath, _files) for _, file in ipairs(_files) do file = path.getrelative(_srcPath, file) local filePath = path.join(_dstPath, file) if not os.isfile(filePath) then return false end end return true end function overridefiles(_srcPath, _dstPath, _files) local remove = {} local add = {} for _, file in ipairs(_files) do file = path.getrelative(_srcPath, file) local filePath = path.join(_dstPath, file) if not os.isfile(filePath) then return end table.insert(remove, path.join(_srcPath, file)) table.insert(add, filePath) end removefiles { remove, } files { add, } end function bgfxProject(_name, _kind, _defines) project ("bgfx" .. _name) uuid (os.uuid("bgfx" .. _name)) bgfxProjectBase(_kind, _defines) copyLib() end function bgfxProjectBase(_kind, _defines) kind (_kind) if _kind == "SharedLib" then defines { "BGFX_SHARED_LIB_BUILD=1", } links { "bimg", "bx", } configuration { "vs20* or mingw*" } links { "gdi32", "psapi", } configuration { "mingw*" } linkoptions { "-shared", } configuration { "linux-*" } buildoptions { "-fPIC", } configuration {} end includedirs { path.join(BGFX_DIR, "3rdparty"), path.join(BX_DIR, "include"), path.join(BIMG_DIR, "include"), } defines { _defines, } links { "bx", } if _OPTIONS["with-glfw"] then defines { "BGFX_CONFIG_MULTITHREADED=0", } end if _OPTIONS["with-ovr"] then defines { -- "BGFX_CONFIG_MULTITHREADED=0", "BGFX_CONFIG_USE_OVR=1", } includedirs { "$(OVR_DIR)/LibOVR/Include", } configuration { "x32" } libdirs { path.join("$(OVR_DIR)/LibOVR/Lib/Windows/Win32/Release", _ACTION) } configuration { "x64" } libdirs { path.join("$(OVR_DIR)/LibOVR/Lib/Windows/x64/Release", _ACTION) } configuration { "x32 or x64" } links { "libovr" } configuration {} end configuration { "Debug" } defines { "BGFX_CONFIG_DEBUG=1", } configuration { "vs* or mingw*", "not durango" } includedirs { path.join(BGFX_DIR, "3rdparty/dxsdk/include"), } configuration { "android*" } links { "EGL", "GLESv2", } configuration { "winstore*" } linkoptions { "/ignore:4264" -- LNK4264: archiving object file compiled with /ZW into a static library; note that when authoring Windows Runtime types it is not recommended to link with a static library that contains Windows Runtime metadata } configuration { "*clang*" } buildoptions { "-Wno-microsoft-enum-value", -- enumerator value is not representable in the underlying type 'int' "-Wno-microsoft-const-init", -- default initialization of an object of const type '' without a user-provided default constructor is a Microsoft extension } configuration { "osx" } linkoptions { "-framework Cocoa", "-framework QuartzCore", "-framework OpenGL", "-weak_framework Metal", "-weak_framework MetalKit", } configuration { "not linux-steamlink", "not NX32", "not NX64" } includedirs { -- steamlink has EGL headers modified... -- NX has EGL headers modified... path.join(BGFX_DIR, "3rdparty/khronos"), } configuration { "linux-steamlink" } defines { "EGL_API_FB", } configuration {} includedirs { path.join(BGFX_DIR, "include"), } files { path.join(BGFX_DIR, "include/**.h"), path.join(BGFX_DIR, "src/**.cpp"), path.join(BGFX_DIR, "src/**.h"), } removefiles { path.join(BGFX_DIR, "src/**.bin.h"), } overridefiles(BGFX_DIR, path.join(BGFX_DIR, "../bgfx-ext"), { path.join(BGFX_DIR, "src/renderer_gnm.cpp"), path.join(BGFX_DIR, "src/renderer_gnm.h"), }) if _OPTIONS["with-amalgamated"] then excludes { path.join(BGFX_DIR, "src/bgfx.cpp"), path.join(BGFX_DIR, "src/debug_**.cpp"), path.join(BGFX_DIR, "src/glcontext_**.cpp"), path.join(BGFX_DIR, "src/image.cpp"), path.join(BGFX_DIR, "src/hmd**.cpp"), path.join(BGFX_DIR, "src/renderer_**.cpp"), path.join(BGFX_DIR, "src/shader**.cpp"), path.join(BGFX_DIR, "src/topology.cpp"), path.join(BGFX_DIR, "src/vertexdecl.cpp"), } configuration { "xcode* or osx or ios*" } files { path.join(BGFX_DIR, "src/amalgamated.mm"), } excludes { path.join(BGFX_DIR, "src/glcontext_**.mm"), path.join(BGFX_DIR, "src/renderer_**.mm"), path.join(BGFX_DIR, "src/amalgamated.cpp"), } configuration { "not (xcode* or osx or ios*)" } excludes { path.join(BGFX_DIR, "src/**.mm"), } configuration {} else configuration { "xcode* or osx or ios*" } files { path.join(BGFX_DIR, "src/glcontext_**.mm"), path.join(BGFX_DIR, "src/renderer_**.mm"), } configuration {} excludes { path.join(BGFX_DIR, "src/amalgamated.**"), } end configuration {} end
-- -- Copyright 2010-2018 Branimir Karadzic. All rights reserved. -- License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause -- function filesexist(_srcPath, _dstPath, _files) for _, file in ipairs(_files) do file = path.getrelative(_srcPath, file) local filePath = path.join(_dstPath, file) if not os.isfile(filePath) then return false end end return true end function overridefiles(_srcPath, _dstPath, _files) local remove = {} local add = {} for _, file in ipairs(_files) do file = path.getrelative(_srcPath, file) local filePath = path.join(_dstPath, file) if not os.isfile(filePath) then return end table.insert(remove, path.join(_srcPath, file)) table.insert(add, filePath) end removefiles { remove, } files { add, } end function bgfxProject(_name, _kind, _defines) project ("bgfx" .. _name) uuid (os.uuid("bgfx" .. _name)) bgfxProjectBase(_kind, _defines) copyLib() end function bgfxProjectBase(_kind, _defines) kind (_kind) if _kind == "SharedLib" then defines { "BGFX_SHARED_LIB_BUILD=1", } links { "bimg", "bx", } configuration { "vs20* or mingw*" } links { "gdi32", "psapi", } configuration { "mingw*" } linkoptions { "-shared", } configuration { "linux-*" } buildoptions { "-fPIC", } configuration {} end includedirs { path.join(BGFX_DIR, "3rdparty"), path.join(BX_DIR, "include"), path.join(BIMG_DIR, "include"), } defines { _defines, } links { "bx", } if _OPTIONS["with-glfw"] then defines { "BGFX_CONFIG_MULTITHREADED=0", } end if _OPTIONS["with-ovr"] then defines { -- "BGFX_CONFIG_MULTITHREADED=0", "BGFX_CONFIG_USE_OVR=1", } includedirs { "$(OVR_DIR)/LibOVR/Include", } configuration { "x32" } libdirs { path.join("$(OVR_DIR)/LibOVR/Lib/Windows/Win32/Release", _ACTION) } configuration { "x64" } libdirs { path.join("$(OVR_DIR)/LibOVR/Lib/Windows/x64/Release", _ACTION) } configuration { "x32 or x64" } links { "libovr" } configuration {} end configuration { "Debug" } defines { "BGFX_CONFIG_DEBUG=1", } configuration { "vs* or mingw*", "not durango" } includedirs { path.join(BGFX_DIR, "3rdparty/dxsdk/include"), } configuration { "android*" } links { "EGL", "GLESv2", } configuration { "winstore*" } linkoptions { "/ignore:4264" -- LNK4264: archiving object file compiled with /ZW into a static library; note that when authoring Windows Runtime types it is not recommended to link with a static library that contains Windows Runtime metadata } configuration { "*clang*" } buildoptions { "-Wno-microsoft-enum-value", -- enumerator value is not representable in the underlying type 'int' "-Wno-microsoft-const-init", -- default initialization of an object of const type '' without a user-provided default constructor is a Microsoft extension } configuration { "osx" } linkoptions { "-framework Cocoa", "-framework QuartzCore", "-framework OpenGL", "-weak_framework Metal", "-weak_framework MetalKit", } configuration { "not linux-steamlink", "not NX32", "not NX64" } includedirs { -- steamlink has EGL headers modified... -- NX has EGL headers modified... path.join(BGFX_DIR, "3rdparty/khronos"), } configuration { "linux-steamlink" } defines { "EGL_API_FB", } configuration {} includedirs { path.join(BGFX_DIR, "include"), } files { path.join(BGFX_DIR, "include/**.h"), path.join(BGFX_DIR, "src/**.cpp"), path.join(BGFX_DIR, "src/**.h"), } removefiles { path.join(BGFX_DIR, "src/**.bin.h"), } overridefiles(BGFX_DIR, path.join(BGFX_DIR, "../bgfx-ext"), { path.join(BGFX_DIR, "src/renderer_gnm.cpp"), path.join(BGFX_DIR, "src/renderer_gnm.h"), }) if _OPTIONS["with-amalgamated"] then excludes { path.join(BGFX_DIR, "src/bgfx.cpp"), path.join(BGFX_DIR, "src/debug_**.cpp"), path.join(BGFX_DIR, "src/dxgi.cpp"), path.join(BGFX_DIR, "src/glcontext_**.cpp"), path.join(BGFX_DIR, "src/hmd**.cpp"), path.join(BGFX_DIR, "src/image.cpp"), path.join(BGFX_DIR, "src/nvapi.cpp"), path.join(BGFX_DIR, "src/renderer_**.cpp"), path.join(BGFX_DIR, "src/shader**.cpp"), path.join(BGFX_DIR, "src/topology.cpp"), path.join(BGFX_DIR, "src/vertexdecl.cpp"), } configuration { "xcode* or osx or ios*" } files { path.join(BGFX_DIR, "src/amalgamated.mm"), } excludes { path.join(BGFX_DIR, "src/glcontext_**.mm"), path.join(BGFX_DIR, "src/renderer_**.mm"), path.join(BGFX_DIR, "src/amalgamated.cpp"), } configuration { "not (xcode* or osx or ios*)" } excludes { path.join(BGFX_DIR, "src/**.mm"), } configuration {} else configuration { "xcode* or osx or ios*" } files { path.join(BGFX_DIR, "src/glcontext_**.mm"), path.join(BGFX_DIR, "src/renderer_**.mm"), } configuration {} excludes { path.join(BGFX_DIR, "src/amalgamated.**"), } end configuration {} end
Fixed amalgamated build.
Fixed amalgamated build.
Lua
bsd-2-clause
emoon/bgfx,MikePopoloski/bgfx,jpcy/bgfx,attilaz/bgfx,mendsley/bgfx,attilaz/bgfx,fluffyfreak/bgfx,bkaradzic/bgfx,jpcy/bgfx,jdryg/bgfx,jdryg/bgfx,bkaradzic/bgfx,septag/bgfx,mendsley/bgfx,fluffyfreak/bgfx,LWJGL-CI/bgfx,septag/bgfx,jpcy/bgfx,jdryg/bgfx,LWJGL-CI/bgfx,fluffyfreak/bgfx,bkaradzic/bgfx,LWJGL-CI/bgfx,mendsley/bgfx,septag/bgfx,bkaradzic/bgfx,emoon/bgfx,attilaz/bgfx,LWJGL-CI/bgfx,jdryg/bgfx,jpcy/bgfx,MikePopoloski/bgfx,emoon/bgfx,fluffyfreak/bgfx,MikePopoloski/bgfx
8f0e1fc9aa58c6223530daecef5d8f2d43d136b0
onmt/modules/BiEncoder.lua
onmt/modules/BiEncoder.lua
local function reverseInput(batch) batch.sourceInput, batch.sourceInputRev = batch.sourceInputRev, batch.sourceInput batch.sourceInputFeatures, batch.sourceInputRevFeatures = batch.sourceInputRevFeatures, batch.sourceInputFeatures batch.sourceInputPadLeft, batch.sourceInputRevPadLeft = batch.sourceInputRevPadLeft, batch.sourceInputPadLeft end --[[ BiEncoder is a bidirectional Sequencer used for the source language. `netFwd` h_1 => h_2 => h_3 => ... => h_n | | | | . . . . | | | | h_1 => h_2 => h_3 => ... => h_n | | | | | | | | x_1 x_2 x_3 x_n `netBwd` h_1 <= h_2 <= h_3 <= ... <= h_n | | | | . . . . | | | | h_1 <= h_2 <= h_3 <= ... <= h_n | | | | | | | | x_1 x_2 x_3 x_n Inherits from [onmt.Sequencer](onmt+modules+Sequencer). --]] local BiEncoder, parent = torch.class('onmt.BiEncoder', 'nn.Container') --[[ Create a bi-encoder. Parameters: * `input` - input neural network. * `rnn` - recurrent template module. * `merge` - fwd/bwd merge operation {"concat", "sum"} ]] function BiEncoder:__init(input, rnn, merge) parent.__init(self) self.fwd = onmt.Encoder.new(input, rnn) self.bwd = onmt.Encoder.new(input:clone('weight', 'bias', 'gradWeight', 'gradBias'), rnn:clone()) self.args = {} self.args.merge = merge self.args.rnnSize = rnn.outputSize self.args.numEffectiveLayers = rnn.numEffectiveLayers if self.args.merge == 'concat' then self.args.hiddenSize = self.args.rnnSize * 2 else self.args.hiddenSize = self.args.rnnSize end self:add(self.fwd) self:add(self.bwd) self:resetPreallocation() end --[[ Return a new BiEncoder using the serialized data `pretrained`. ]] function BiEncoder.load(pretrained) local self = torch.factory('onmt.BiEncoder')() parent.__init(self) self.fwd = onmt.Encoder.load(pretrained.modules[1]) self.bwd = onmt.Encoder.load(pretrained.modules[2]) self.args = pretrained.args self:add(self.fwd) self:add(self.bwd) self:resetPreallocation() return self end --[[ Return data to serialize. ]] function BiEncoder:serialize() return { modules = self.modules, args = self.args } end function BiEncoder:resetPreallocation() -- Prototype for preallocated full context vector. self.contextProto = torch.Tensor() -- Prototype for preallocated full hidden states tensors. self.stateProto = torch.Tensor() -- Prototype for preallocated gradient of the backward context self.gradContextBwdProto = torch.Tensor() end function BiEncoder:maskPadding() self.fwd:maskPadding() self.bwd:maskPadding() end function BiEncoder:forward(batch) if self.statesProto == nil then self.statesProto = onmt.utils.Tensor.initTensorTable(self.args.numEffectiveLayers, self.stateProto, { batch.size, self.args.hiddenSize }) end local states = onmt.utils.Tensor.reuseTensorTable(self.statesProto, { batch.size, self.args.hiddenSize }) local context = onmt.utils.Tensor.reuseTensor(self.contextProto, { batch.size, batch.sourceLength, self.args.hiddenSize }) local fwdStates, fwdContext = self.fwd:forward(batch) reverseInput(batch) local bwdStates, bwdContext = self.bwd:forward(batch) reverseInput(batch) if self.args.merge == 'concat' then for i = 1, #fwdStates do states[i]:narrow(2, 1, self.args.rnnSize):copy(fwdStates[i]) states[i]:narrow(2, self.args.rnnSize + 1, self.args.rnnSize):copy(bwdStates[i]) end for t = 1, batch.sourceLength do context[{{}, t}]:narrow(2, 1, self.args.rnnSize) :copy(fwdContext[{{}, t}]) context[{{}, t}]:narrow(2, self.args.rnnSize + 1, self.args.rnnSize) :copy(bwdContext[{{}, batch.sourceLength - t + 1}]) end elseif self.args.merge == 'sum' then for i = 1, #states do states[i]:copy(fwdStates[i]) states[i]:add(bwdStates[i]) end for t = 1, batch.sourceLength do context[{{}, t}]:copy(fwdContext[{{}, t}]) context[{{}, t}]:add(bwdContext[{{}, batch.sourceLength - t + 1}]) end end return states, context end function BiEncoder:backward(batch, gradStatesOutput, gradContextOutput) gradStatesOutput = gradStatesOutput or onmt.utils.Tensor.initTensorTable(self.args.numEffectiveLayers, onmt.utils.Cuda.convert(torch.Tensor()), { batch.size, self.args.rnnSize*2 }) local gradContextOutputFwd local gradContextOutputBwd local gradStatesOutputFwd = {} local gradStatesOutputBwd = {} if self.args.merge == 'concat' then local gradContextOutputSplit = gradContextOutput:chunk(2, 3) gradContextOutputFwd = gradContextOutputSplit[1] gradContextOutputBwd = gradContextOutputSplit[2] for i = 1, #gradStatesOutput do local statesSplit = gradStatesOutput[i]:chunk(2, 2) table.insert(gradStatesOutputFwd, statesSplit[1]) table.insert(gradStatesOutputBwd, statesSplit[2]) end elseif self.args.merge == 'sum' then gradContextOutputFwd = gradContextOutput gradContextOutputBwd = gradContextOutput gradStatesOutputFwd = gradStatesOutput gradStatesOutputBwd = gradStatesOutput end local gradInputFwd = self.fwd:backward(batch, gradStatesOutputFwd, gradContextOutputFwd) -- reverse gradients of the backward context local gradContextBwd = onmt.utils.Tensor.reuseTensor(self.gradContextBwdProto, { batch.size, batch.sourceLength, self.args.rnnSize }) for t = 1, batch.sourceLength do gradContextBwd[{{}, t}]:copy(gradContextOutputBwd[{{}, batch.sourceLength - t + 1}]) end local gradInputBwd = self.bwd:backward(batch, gradStatesOutputBwd, gradContextBwd) for t = 1, batch.sourceLength do local revIndex = batch.sourceLength - t + 1 if torch.isTensor(gradInputFwd[t]) then gradInputFwd[t]:add(gradInputBwd[revIndex]) else for i = 1, #gradInputFwd[t] do gradInputFwd[t][i]:add(gradInputBwd[revIndex][i]) end end end return gradInputFwd end
local function reverseInput(batch) batch.sourceInput, batch.sourceInputRev = batch.sourceInputRev, batch.sourceInput batch.sourceInputFeatures, batch.sourceInputRevFeatures = batch.sourceInputRevFeatures, batch.sourceInputFeatures batch.sourceInputPadLeft, batch.sourceInputRevPadLeft = batch.sourceInputRevPadLeft, batch.sourceInputPadLeft end --[[ BiEncoder is a bidirectional Sequencer used for the source language. `netFwd` h_1 => h_2 => h_3 => ... => h_n | | | | . . . . | | | | h_1 => h_2 => h_3 => ... => h_n | | | | | | | | x_1 x_2 x_3 x_n `netBwd` h_1 <= h_2 <= h_3 <= ... <= h_n | | | | . . . . | | | | h_1 <= h_2 <= h_3 <= ... <= h_n | | | | | | | | x_1 x_2 x_3 x_n Inherits from [onmt.Sequencer](onmt+modules+Sequencer). --]] local BiEncoder, parent = torch.class('onmt.BiEncoder', 'nn.Container') --[[ Create a bi-encoder. Parameters: * `input` - input neural network. * `rnn` - recurrent template module. * `merge` - fwd/bwd merge operation {"concat", "sum"} ]] function BiEncoder:__init(input, rnn, merge) parent.__init(self) self.fwd = onmt.Encoder.new(input, rnn) self.bwd = onmt.Encoder.new(input:clone('weight', 'bias', 'gradWeight', 'gradBias'), rnn:clone()) self.args = {} self.args.merge = merge self.args.rnnSize = rnn.outputSize self.args.numEffectiveLayers = rnn.numEffectiveLayers if self.args.merge == 'concat' then self.args.hiddenSize = self.args.rnnSize * 2 else self.args.hiddenSize = self.args.rnnSize end self:add(self.fwd) self:add(self.bwd) self:resetPreallocation() end --[[ Return a new BiEncoder using the serialized data `pretrained`. ]] function BiEncoder.load(pretrained) local self = torch.factory('onmt.BiEncoder')() parent.__init(self) self.fwd = onmt.Encoder.load(pretrained.modules[1]) self.bwd = onmt.Encoder.load(pretrained.modules[2]) self.args = pretrained.args self:add(self.fwd) self:add(self.bwd) self:resetPreallocation() return self end --[[ Return data to serialize. ]] function BiEncoder:serialize() local modulesData = {} for i = 1, #self.modules do table.insert(modulesData, self.modules[i]:serialize()) end return { modules = modulesData, args = self.args } end function BiEncoder:resetPreallocation() -- Prototype for preallocated full context vector. self.contextProto = torch.Tensor() -- Prototype for preallocated full hidden states tensors. self.stateProto = torch.Tensor() -- Prototype for preallocated gradient of the backward context self.gradContextBwdProto = torch.Tensor() end function BiEncoder:maskPadding() self.fwd:maskPadding() self.bwd:maskPadding() end function BiEncoder:forward(batch) if self.statesProto == nil then self.statesProto = onmt.utils.Tensor.initTensorTable(self.args.numEffectiveLayers, self.stateProto, { batch.size, self.args.hiddenSize }) end local states = onmt.utils.Tensor.reuseTensorTable(self.statesProto, { batch.size, self.args.hiddenSize }) local context = onmt.utils.Tensor.reuseTensor(self.contextProto, { batch.size, batch.sourceLength, self.args.hiddenSize }) local fwdStates, fwdContext = self.fwd:forward(batch) reverseInput(batch) local bwdStates, bwdContext = self.bwd:forward(batch) reverseInput(batch) if self.args.merge == 'concat' then for i = 1, #fwdStates do states[i]:narrow(2, 1, self.args.rnnSize):copy(fwdStates[i]) states[i]:narrow(2, self.args.rnnSize + 1, self.args.rnnSize):copy(bwdStates[i]) end for t = 1, batch.sourceLength do context[{{}, t}]:narrow(2, 1, self.args.rnnSize) :copy(fwdContext[{{}, t}]) context[{{}, t}]:narrow(2, self.args.rnnSize + 1, self.args.rnnSize) :copy(bwdContext[{{}, batch.sourceLength - t + 1}]) end elseif self.args.merge == 'sum' then for i = 1, #states do states[i]:copy(fwdStates[i]) states[i]:add(bwdStates[i]) end for t = 1, batch.sourceLength do context[{{}, t}]:copy(fwdContext[{{}, t}]) context[{{}, t}]:add(bwdContext[{{}, batch.sourceLength - t + 1}]) end end return states, context end function BiEncoder:backward(batch, gradStatesOutput, gradContextOutput) gradStatesOutput = gradStatesOutput or onmt.utils.Tensor.initTensorTable(self.args.numEffectiveLayers, onmt.utils.Cuda.convert(torch.Tensor()), { batch.size, self.args.rnnSize*2 }) local gradContextOutputFwd local gradContextOutputBwd local gradStatesOutputFwd = {} local gradStatesOutputBwd = {} if self.args.merge == 'concat' then local gradContextOutputSplit = gradContextOutput:chunk(2, 3) gradContextOutputFwd = gradContextOutputSplit[1] gradContextOutputBwd = gradContextOutputSplit[2] for i = 1, #gradStatesOutput do local statesSplit = gradStatesOutput[i]:chunk(2, 2) table.insert(gradStatesOutputFwd, statesSplit[1]) table.insert(gradStatesOutputBwd, statesSplit[2]) end elseif self.args.merge == 'sum' then gradContextOutputFwd = gradContextOutput gradContextOutputBwd = gradContextOutput gradStatesOutputFwd = gradStatesOutput gradStatesOutputBwd = gradStatesOutput end local gradInputFwd = self.fwd:backward(batch, gradStatesOutputFwd, gradContextOutputFwd) -- reverse gradients of the backward context local gradContextBwd = onmt.utils.Tensor.reuseTensor(self.gradContextBwdProto, { batch.size, batch.sourceLength, self.args.rnnSize }) for t = 1, batch.sourceLength do gradContextBwd[{{}, t}]:copy(gradContextOutputBwd[{{}, batch.sourceLength - t + 1}]) end local gradInputBwd = self.bwd:backward(batch, gradStatesOutputBwd, gradContextBwd) for t = 1, batch.sourceLength do local revIndex = batch.sourceLength - t + 1 if torch.isTensor(gradInputFwd[t]) then gradInputFwd[t]:add(gradInputBwd[revIndex]) else for i = 1, #gradInputFwd[t] do gradInputFwd[t][i]:add(gradInputBwd[revIndex][i]) end end end return gradInputFwd end
fix brnn serialization (#33)
fix brnn serialization (#33) BiEncoder's submodules are plain Encoder objects that contain clones and preallocated Tensors. We have to save the serialized form of these submodules.
Lua
mit
OpenNMT/OpenNMT,jsenellart/OpenNMT,cservan/OpenNMT_scores_0.2.0,da03/OpenNMT,monsieurzhang/OpenNMT,jsenellart/OpenNMT,da03/OpenNMT,jsenellart-systran/OpenNMT,monsieurzhang/OpenNMT,srush/OpenNMT,OpenNMT/OpenNMT,jsenellart-systran/OpenNMT,jungikim/OpenNMT,da03/OpenNMT,monsieurzhang/OpenNMT,OpenNMT/OpenNMT,jungikim/OpenNMT,jsenellart-systran/OpenNMT,jsenellart/OpenNMT,jungikim/OpenNMT
a103f58697ac6663c0f3f62bebd6d66317fc0685
otouto/plugins/twitter.lua
otouto/plugins/twitter.lua
local twitter = {} local utilities = require('otouto.utilities') local HTTPS = require('ssl.https') local JSON = require('dkjson') local redis = (loadfile "./otouto/redis.lua")() local OAuth = (require "OAuth") local bindings = require('otouto.bindings') function twitter:init(config) if not cred_data.tw_consumer_key then print('Missing config value: tw_consumer_key.') print('twitter.lua will not be enabled.') return elseif not cred_data.tw_consumer_secret then print('Missing config value: tw_consumer_secret.') print('twitter.lua will not be enabled.') return elseif not cred_data.tw_access_token then print('Missing config value: tw_access_token.') print('twitter.lua will not be enabled.') return elseif not cred_data.tw_access_token_secret then print('Missing config value: tw_access_token_secret.') print('twitter.lua will not be enabled.') return end twitter.triggers = { 'twitter.com/[^/]+/statuse?s?/([0-9]+)' } twitter.doc = [[*Twitter-Link*: Postet Tweet]] end local consumer_key = cred_data.tw_consumer_key local consumer_secret = cred_data.tw_consumer_secret local access_token = cred_data.tw_access_token local access_token_secret = cred_data.tw_access_token_secret local client = OAuth.new(consumer_key, consumer_secret, { RequestToken = "https://api.twitter.com/oauth/request_token", AuthorizeUser = {"https://api.twitter.com/oauth/authorize", method = "GET"}, AccessToken = "https://api.twitter.com/oauth/access_token" }, { OAuthToken = access_token, OAuthTokenSecret = access_token_secret }) function twitter:action(msg) if not msg.text:match('twitter.com/[^/]+/statuse?s?/([0-9]+)') then return end local id = msg.text:match('twitter.com/[^/]+/statuse?s?/([0-9]+)') local twitter_url = "https://api.twitter.com/1.1/statuses/show/" .. id.. ".json" local response_code, response_headers, response_status_line, response_body = client:PerformRequest("GET", twitter_url) local response = JSON.decode(response_body) local full_name = response.user.name local user_name = response.user.screen_name if response.user.verified then verified = ' ✅' else verified = '' end -- MD: local header = 'Tweet von '..full_name..' ([@' ..user_name.. '](https://twitter.com/'..user_name..')'..verified..')\n' local header = 'Tweet von '..full_name..' (@' ..user_name..verified..')\n' local text = response.text -- favorites & retweets if response.retweet_count == 0 then retweets = "" else retweets = response.retweet_count..'x retweeted' end if response.favorite_count == 0 then favorites = "" else favorites = response.favorite_count..'x favorisiert' end if retweets == "" and favorites ~= "" then footer = favorites elseif retweets ~= "" and favorites == "" then footer = retweets elseif retweets ~= "" and favorites ~= "" then footer = retweets..' - '..favorites else footer = "" end -- replace short URLs if response.entities.urls then for k, v in pairs(response.entities.urls) do local short = v.url local long = v.expanded_url text = text:gsub(short, long) end end -- remove images local images = {} local videos = {} if response.entities.media and response.extended_entities.media then for k, v in pairs(response.extended_entities.media) do local url = v.url local pic = v.media_url_https if v.video_info then if not v.video_info.variants[3] then local vid = v.video_info.variants[1].url table.insert(videos, vid) else local vid = v.video_info.variants[3].url table.insert(videos, vid) end end text = text:gsub(url, "") table.insert(images, pic) end end -- quoted tweet if response.quoted_status then local quoted_text = response.quoted_status.text local quoted_name = response.quoted_status.user.name local quoted_screen_name = response.quoted_status.user.screen_name if response.quoted_status.user.verified then quoted_verified = ' ✅' else quoted_verified = '' end -- MD: quote = 'Als Antwort auf '..quoted_name..' ([@' ..quoted_screen_name.. '](https://twitter.com/'..quoted_screen_name..')'..quoted_verified..'):\n'..quoted_text quote = 'Als Antwort auf '..quoted_name..' (@' ..quoted_screen_name..quoted_verified..'):\n'..quoted_text text = text..'\n\n'..quote..'\n' end -- send the parts local text = unescape(text) utilities.send_reply(self, msg, header .. "\n" .. text.."\n"..footer) for k, v in pairs(images) do local file = download_to_file(v) utilities.send_photo(self, msg.chat.id, file, nil, msg.message_id) end for k, v in pairs(videos) do local file = download_to_file(v) utilities.send_video(self, msg.chat.id, file, nil, msg.message_id) end end return twitter
local twitter = {} local utilities = require('otouto.utilities') local HTTPS = require('ssl.https') local JSON = require('dkjson') local redis = (loadfile "./otouto/redis.lua")() local OAuth = (require "OAuth") local bindings = require('otouto.bindings') function twitter:init(config) if not cred_data.tw_consumer_key then print('Missing config value: tw_consumer_key.') print('twitter.lua will not be enabled.') return elseif not cred_data.tw_consumer_secret then print('Missing config value: tw_consumer_secret.') print('twitter.lua will not be enabled.') return elseif not cred_data.tw_access_token then print('Missing config value: tw_access_token.') print('twitter.lua will not be enabled.') return elseif not cred_data.tw_access_token_secret then print('Missing config value: tw_access_token_secret.') print('twitter.lua will not be enabled.') return end twitter.triggers = { 'twitter.com/[^/]+/statuse?s?/([0-9]+)', 'twitter.com/statuse?s?/([0-9]+)' } twitter.doc = [[*Twitter-Link*: Postet Tweet]] end local consumer_key = cred_data.tw_consumer_key local consumer_secret = cred_data.tw_consumer_secret local access_token = cred_data.tw_access_token local access_token_secret = cred_data.tw_access_token_secret local client = OAuth.new(consumer_key, consumer_secret, { RequestToken = "https://api.twitter.com/oauth/request_token", AuthorizeUser = {"https://api.twitter.com/oauth/authorize", method = "GET"}, AccessToken = "https://api.twitter.com/oauth/access_token" }, { OAuthToken = access_token, OAuthTokenSecret = access_token_secret }) function twitter:action(msg, config, matches) if not matches[2] then id = matches[1] else id = matches[2] end local twitter_url = "https://api.twitter.com/1.1/statuses/show/" .. id.. ".json" local response_code, response_headers, response_status_line, response_body = client:PerformRequest("GET", twitter_url) local response = JSON.decode(response_body) local full_name = response.user.name local user_name = response.user.screen_name if response.user.verified then verified = ' ✅' else verified = '' end -- MD: local header = 'Tweet von '..full_name..' ([@' ..user_name.. '](https://twitter.com/'..user_name..')'..verified..')\n' local header = 'Tweet von '..full_name..' (@' ..user_name..verified..')\n' local text = response.text -- favorites & retweets if response.retweet_count == 0 then retweets = "" else retweets = response.retweet_count..'x retweeted' end if response.favorite_count == 0 then favorites = "" else favorites = response.favorite_count..'x favorisiert' end if retweets == "" and favorites ~= "" then footer = favorites elseif retweets ~= "" and favorites == "" then footer = retweets elseif retweets ~= "" and favorites ~= "" then footer = retweets..' - '..favorites else footer = "" end -- replace short URLs if response.entities.urls then for k, v in pairs(response.entities.urls) do local short = v.url local long = v.expanded_url text = text:gsub(short, long) end end -- remove images local images = {} local videos = {} if response.entities.media and response.extended_entities.media then for k, v in pairs(response.extended_entities.media) do local url = v.url local pic = v.media_url_https if v.video_info then if not v.video_info.variants[3] then local vid = v.video_info.variants[1].url table.insert(videos, vid) else local vid = v.video_info.variants[3].url table.insert(videos, vid) end end text = text:gsub(url, "") table.insert(images, pic) end end -- quoted tweet if response.quoted_status then local quoted_text = response.quoted_status.text local quoted_name = response.quoted_status.user.name local quoted_screen_name = response.quoted_status.user.screen_name if response.quoted_status.user.verified then quoted_verified = ' ✅' else quoted_verified = '' end -- MD: quote = 'Als Antwort auf '..quoted_name..' ([@' ..quoted_screen_name.. '](https://twitter.com/'..quoted_screen_name..')'..quoted_verified..'):\n'..quoted_text quote = 'Als Antwort auf '..quoted_name..' (@' ..quoted_screen_name..quoted_verified..'):\n'..quoted_text text = text..'\n\n'..quote..'\n' end -- send the parts local text = unescape(text) utilities.send_reply(self, msg, header .. "\n" .. text.."\n"..footer) for k, v in pairs(images) do local file = download_to_file(v) utilities.send_photo(self, msg.chat.id, file, nil, msg.message_id) end for k, v in pairs(videos) do local file = download_to_file(v) utilities.send_video(self, msg.chat.id, file, nil, msg.message_id) end end return twitter
Twitter: Fix Pattern
Twitter: Fix Pattern
Lua
agpl-3.0
Brawl345/Brawlbot-v2
275bc29d30b8feea3bbf0ff71574badc3940fb25
nvim/lua/theme.lua
nvim/lua/theme.lua
vim.opt.background = 'dark' vim.cmd('syntax enable') -- vim.cmd('colorscheme gruvbox') require('nightfox').load('nordfox') --require('nightfox').load('dawnfox') -- lualine -- require('lualine').setup {options = { theme = 'gruvbox' }} -- require('lualine').setup {options = { theme = 'nightfox' }} require('nvim-web-devicons').setup {} require('lualine').setup { options = { theme = 'gruvbox', icons_enabled = false, component_separators = { left = '', right = ''}, section_separators = { left = '', right = ''}, disabled_filetypes = {}, always_divide_middle = true, }, sections = { lualine_a = {'mode'}, lualine_b = {'diagnostics'}, lualine_c = {'filename'}, lualine_x = {}, lualine_y = {'progress'}, lualine_z = {'location'} }, inactive_sections = { lualine_a = {}, lualine_b = {}, lualine_c = {'filename'}, lualine_x = {'location'}, lualine_y = {}, lualine_z = {} }, tabline = {}, extensions = {'quickfix'} }
vim.opt.background = 'dark' vim.cmd('syntax enable') -- vim.cmd('colorscheme gruvbox') vim.cmd('colorscheme nordfox') -- vim.cmd('colorscheme dawnfox') -- lualine -- require('lualine').setup {options = { theme = 'gruvbox' }} -- require('lualine').setup {options = { theme = 'nightfox' }} require('nvim-web-devicons').setup {} require('lualine').setup { options = { theme = 'gruvbox', icons_enabled = false, component_separators = { left = '', right = ''}, section_separators = { left = '', right = ''}, disabled_filetypes = {}, always_divide_middle = true, }, sections = { lualine_a = {'mode'}, lualine_b = {'diagnostics'}, lualine_c = {'filename'}, lualine_x = {}, lualine_y = {'progress'}, lualine_z = {'location'} }, inactive_sections = { lualine_a = {}, lualine_b = {}, lualine_c = {'filename'}, lualine_x = {'location'}, lualine_y = {}, lualine_z = {} }, tabline = {}, extensions = {'quickfix'} }
nvim: fix colorscheme after plugin update
nvim: fix colorscheme after plugin update
Lua
mit
iff/dotfiles,iff/dotfiles
66cb733bd98b55ecf31a63bf9415d6a36c8f6ae5
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 = {} self.visible = true 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 local nclips = 0 if self.clips then nclips = table.Count( self.clips ) end if nclips > 0 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() local nclips = 0 if self.clips then nclips = table.Count( self.clips ) end if nclips > 0 then for i = 1, nclips do render.PopCustomClipPlane() end render.EnableClipping( false ) end end function ENT:Draw() local eidx = self:EntIndex() if self.visible != vis_buffer[eidx] then self.visible = vis_buffer[eidx] end if self.blocked or self.visible == false then return end self:SetupClipping() self:DrawModel() 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 usermessage.Hook("wire_holograms_clip", function( um ) local eidx = um:ReadShort() while eidx != 0 do local cidx = um:ReadShort() if um:ReadBool() then SetClipEnabled(eidx, cidx, um:ReadBool()) else SetClip(eidx, cidx, um:ReadVector(), um:ReadVector(), um:ReadShort() ~= 0) end eidx = um:ReadShort() 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) self:SetModelScale( scale ) local propmax = self:OBBMaxs() local propmin = self:OBBMins() propmax.x = scale.x * propmax.x propmax.y = scale.y * propmax.y propmax.z = scale.z * propmax.z propmin.x = scale.x * propmin.x propmin.y = scale.y * propmin.y propmin.z = scale.z * propmin.z self:SetRenderBounds( propmax, propmin ) scale_buffer[eidx] = nil end usermessage.Hook("wire_holograms_set_scale", function( um ) local index = um:ReadShort() while index ~= 0 do local scale = um:ReadVector() SetScale(index, scale) index = um:ReadShort() end end) /******************************************************************************/ usermessage.Hook( "wire_holograms_set_visible", function( um ) local index = um:ReadShort() while index ~= 0 do vis_buffer[index] = um:ReadBool() index = um:ReadShort() end end ) /******************************************************************************/ /* hook.Add( "EntityRemoved", "gmod_wire_hologram", function(ent) scales[ent:EntIndex()] = nil clip_buffer[ent:EntIndex()] = nil vis_buffer[ent:EntIndex()] = nil 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 = {} self.visible = true 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 local nclips = 0 if self.clips then nclips = table.Count( self.clips ) end if nclips > 0 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() local nclips = 0 if self.clips then nclips = table.Count( self.clips ) end if nclips > 0 then for i = 1, nclips do render.PopCustomClipPlane() end render.EnableClipping( false ) end end function ENT:Draw() local eidx = self:EntIndex() if self.visible != vis_buffer[eidx] then self.visible = vis_buffer[eidx] end if self.blocked or self.visible == false then return end self:SetupClipping() render.SuppressEngineLighting( true ) self:DrawModel() render.SuppressEngineLighting( false ) 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 usermessage.Hook("wire_holograms_clip", function( um ) local eidx = um:ReadShort() while eidx != 0 do local cidx = um:ReadShort() if um:ReadBool() then SetClipEnabled(eidx, cidx, um:ReadBool()) else SetClip(eidx, cidx, um:ReadVector(), um:ReadVector(), um:ReadShort() ~= 0) end eidx = um:ReadShort() 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) self:SetModelScale( scale ) local propmax = self:OBBMaxs() local propmin = self:OBBMins() propmax.x = scale.x * propmax.x propmax.y = scale.y * propmax.y propmax.z = scale.z * propmax.z propmin.x = scale.x * propmin.x propmin.y = scale.y * propmin.y propmin.z = scale.z * propmin.z self:SetRenderBounds( propmax, propmin ) scale_buffer[eidx] = nil end usermessage.Hook("wire_holograms_set_scale", function( um ) local index = um:ReadShort() while index ~= 0 do local scale = um:ReadVector() SetScale(index, scale) index = um:ReadShort() end end) /******************************************************************************/ usermessage.Hook( "wire_holograms_set_visible", function( um ) local index = um:ReadShort() while index ~= 0 do vis_buffer[index] = um:ReadBool() index = um:ReadShort() end end ) /******************************************************************************/ /* hook.Add( "EntityRemoved", "gmod_wire_hologram", function(ent) scales[ent:EntIndex()] = nil clip_buffer[ent:EntIndex()] = nil vis_buffer[ent:EntIndex()] = nil 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 cl_init.lua: Disabled engine lighting on holograms. This has been suggested several times, being as how they are "holograms" it doesn't really make sense that they are dynamically lit. If the community is really against this, it is a quick easy fix.
[E2] holograms cl_init.lua: Disabled engine lighting on holograms. This has been suggested several times, being as how they are "holograms" it doesn't really make sense that they are dynamically lit. If the community is really against this, it is a quick easy fix.
Lua
apache-2.0
NezzKryptic/Wire,notcake/wire,rafradek/wire,garrysmodlua/wire,Python1320/wire,plinkopenguin/wiremod,wiremod/wire,dvdvideo1234/wire,Grocel/wire,immibis/wiremod,thegrb93/wire,mitterdoo/wire,sammyt291/wire,bigdogmat/wire,CaptainPRICE/wire,mms92/wire