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
328e6748f78ea9f58884bd3429e2c4eb6012912a
lua/entities/gmod_wire_expression2/core/selfaware.lua
lua/entities/gmod_wire_expression2/core/selfaware.lua
/******************************************************************************\ Selfaware support \******************************************************************************/ __e2setcost(1) -- temporary e2function entity entity() return self.entity end e2function entity owner() return self.player end __e2setcost(nil) -- temporary e2function void selfDestruct() self.entity:Remove() end e2function void selfDestructAll() for k,v in pairs(constraint.GetAllConstrainedEntities(self.entity)) do if(getOwner(self,v)==self.player) then v:Remove() end end //constraint.RemoveAll(self.entity) self.entity:Remove() end /******************************************************************************/ -- i/o functions __e2setcost(10) -- Returns an array of all entities wired to the output e2function array ioOutputEntities( string output ) local ret = {} if (self.entity.Outputs[output]) then local tbl = self.entity.Outputs[output].Connected for i=1,#tbl do if (IsValid(tbl[i].Entity)) then ret[#ret+1] = tbl[i].Entity end end self.prf = self.prf + #ret end return ret end -- Returns the entity the input is wired to e2function entity ioInputEntity( string input ) if (self.entity.Inputs[input] and self.entity.Inputs[input].Src and IsValid(self.entity.Inputs[input].Src)) then return self.entity.Inputs[input].Src end end local function setOutput( self, args, Type ) local op1, op2 = args[2], args[3] local rv1, rv2 = op1[1](self,op1), op2[1](self,op2) if (self.entity.Outputs[rv1] and self.entity.Outputs[rv1].Type == Type) then self.GlobalScope[rv1] = rv2 self.GlobalScope.vclk[rv1] = true end end local function getInput( self, args, default, Type ) local op1 = args[2] local rv1 = op1[1](self,op1) if istable(default) then default = table.Copy(default) end if (self.entity.Inputs[rv1] and self.entity.Inputs[rv1].Type == Type) then return self.GlobalScope[rv1] or default end return default end local excluded_types = { xgt = true, } local function upperfirst( word ) return word:Left(1):upper() .. word:Right(-2):lower() end __e2setcost(5) registerCallback("postinit",function() for k,v in pairs( wire_expression_types ) do local short = v[1] if (!excluded_types[short]) then registerFunction("ioSetOutput","s"..short,""..short,function(self,args) return setOutput(self,args,k) end) registerFunction("ioGetInput"..upperfirst(k == "NORMAL" and "NUMBER" or k),"s",short,function(self,args) return getInput(self,args,v[2],k) end) end end end) /******************************************************************************/ -- Name functions -- Set the name of the E2 itself e2function void setName( string name ) local e = self.entity if( #name > 12000 ) then name = string.sub( name, 1, 12000 ) end if (e.name == name) then return end if (name == "generic" or name == "") then name = "generic" e.WireDebugName = "Expression 2" else e.WireDebugName = "E2 - " .. name end e.name = name e:SetNWString( "name", e.name ) e:SetOverlayText(name) end -- Set the name of a entity (component name if not E2) e2function void entity:setName( string name ) if not IsValid(this) or E2Lib.getOwner(self, this) ~= self.player then return end if( #name > 12000 ) then name = string.sub( name, 1, 12000 ) end if this:GetClass() == "gmod_wire_expression2" then if this.name == name then return end if name == "generic" or name == "" then name = "generic" this.WireDebugName = "Expression 2" else this.WireDebugName = "E2 - " .. name end this.name = name this:SetNWString( "name", this.name ) this:SetOverlayText(name) else if this.wireName == name or string.find(name, "[\n\r\"]") ~= nil then return end this.wireName = name this:SetNWString("WireName", name) duplicator.StoreEntityModifier(this, "WireName", { name = name }) end end -- Get the name of another E2 or compatible entity or component name of wiremod components e2function string entity:getName() if not IsValid(this) then return "" end if this.GetGateName then return this:GetGateName() or "" end return this:GetNWString("WireName", this.PrintName) or "" end /******************************************************************************/ registerCallback("construct", function(self) self.data.changed = {} end) __e2setcost(1) -- This is the prototype for everything that can be compared using the == operator e2function number changed(value) local chg = self.data.changed if value == chg[args] then return 0 end chg[args] = value return 1 end -- vectors can be of gmod type Vector, so we need to treat them separately e2function number changed(vector value) local chg = self.data.changed local this_chg = chg[args] if not this_chg then chg[args] = value return 1 end if this_chg and value[1] == this_chg[1] and value[2] == this_chg[2] and value[3] == this_chg[3] then return 0 end chg[args] = value return 1 end -- This is the prototype for all table types. e2function number changed(angle value) local chg = self.data.changed local this_chg = chg[args] if not this_chg then chg[args] = value return 1 end for i,v in pairs(value) do if v ~= this_chg[i] then chg[args] = value return 1 end end return 0 end local excluded_types = { n = true, v = true, a = true, [""] = true, r = true, t = true, } local comparable_types = { s = true, e = true, xwl = true, b = true, } registerCallback("postinit", function() -- generate this function for all types for typeid,_ in pairs(wire_expression_types2) do if not excluded_types[typeid] then if comparable_types[typeid] then registerFunction("changed", typeid, "n", e2_changed_n) else registerFunction("changed", typeid, "n", e2_changed_a) end end end end) /******************************************************************************/ __e2setcost( 5 ) local getHash = E2Lib.getHash e2function number hash() return getHash( self, self.entity.original ) end e2function number hashNoComments() return getHash( self, self.entity.buffer ) end e2function number hash( string str ) return getHash( self, str ) end
/******************************************************************************\ Selfaware support \******************************************************************************/ __e2setcost(1) -- temporary e2function entity entity() return self.entity end e2function entity owner() return self.player end __e2setcost(nil) -- temporary e2function void selfDestruct() self.entity:Remove() end e2function void selfDestructAll() for k,v in pairs(constraint.GetAllConstrainedEntities(self.entity)) do if(getOwner(self,v)==self.player) then v:Remove() end end //constraint.RemoveAll(self.entity) self.entity:Remove() end /******************************************************************************/ -- i/o functions __e2setcost(10) -- Returns an array of all entities wired to the output e2function array ioOutputEntities( string output ) local ret = {} if (self.entity.Outputs[output]) then local tbl = self.entity.Outputs[output].Connected for i=1,#tbl do if (IsValid(tbl[i].Entity)) then ret[#ret+1] = tbl[i].Entity end end self.prf = self.prf + #ret end return ret end -- Returns the entity the input is wired to e2function entity ioInputEntity( string input ) if (self.entity.Inputs[input] and self.entity.Inputs[input].Src and IsValid(self.entity.Inputs[input].Src)) then return self.entity.Inputs[input].Src end end local function setOutput( self, args, Type ) local op1, op2 = args[2], args[3] local rv1, rv2 = op1[1](self,op1), op2[1](self,op2) if (self.entity.Outputs[rv1] and self.entity.Outputs[rv1].Type == Type) then self.GlobalScope[rv1] = rv2 self.GlobalScope.vclk[rv1] = true end end local function getInput( self, args, default, Type ) local op1 = args[2] local rv1 = op1[1](self,op1) if istable(default) then default = table.Copy(default) end if (self.entity.Inputs[rv1] and self.entity.Inputs[rv1].Type == Type) then return self.GlobalScope[rv1] or default end return default end local excluded_types = { xgt = true, } local function upperfirst( word ) return word:Left(1):upper() .. word:Right(-2):lower() end __e2setcost(5) registerCallback("postinit",function() for k,v in pairs( wire_expression_types ) do local short = v[1] if (!excluded_types[short]) then registerFunction("ioSetOutput","s"..short,""..short,function(self,args) return setOutput(self,args,k) end) registerFunction("ioGetInput"..upperfirst(k == "NORMAL" and "NUMBER" or k),"s",short,function(self,args) return getInput(self,args,v[2],k) end) end end end) /******************************************************************************/ -- Name functions -- Set the name of the E2 itself e2function void setName( string name ) local e = self.entity if( #name > 12000 ) then name = string.sub( name, 1, 12000 ) end if (e.name == name) then return end if (name == "generic" or name == "") then name = "generic" e.WireDebugName = "Expression 2" else e.WireDebugName = "E2 - " .. name end e.name = name e:SetNWString( "name", e.name ) e:SetOverlayText(name) end -- Set the name of a entity (component name if not E2) e2function void entity:setName( string name ) if not IsValid(this) or E2Lib.getOwner(self, this) ~= self.player then return end if( #name > 12000 ) then name = string.sub( name, 1, 12000 ) end if this:GetClass() == "gmod_wire_expression2" then if this.name == name then return end if name == "generic" or name == "" then name = "generic" this.WireDebugName = "Expression 2" else this.WireDebugName = "E2 - " .. name end this.name = name this:SetNWString( "name", this.name ) this:SetOverlayText(name) else if this.wireName == name or string.find(name, "[\n\r\"]") ~= nil then return end this.wireName = name this:SetNWString("WireName", name) duplicator.StoreEntityModifier(this, "WireName", { name = name }) end end -- Get the name of another E2 or compatible entity or component name of wiremod components e2function string entity:getName() if not IsValid(this) then return "" end if this.GetGateName then return this:GetGateName() or "" end return this:GetNWString("WireName", this.PrintName) or "" end /******************************************************************************/ registerCallback("construct", function(self) self.data.changed = {} end) __e2setcost(1) -- This is the prototype for everything that can be compared using the == operator e2function number changed(value) local chg = self.data.changed if value == chg[args] then return 0 end chg[args] = value return 1 end -- vectors can be of gmod type Vector, so we need to treat them separately e2function number changed(vector value) local chg = self.data.changed local this_chg = chg[args] if not this_chg then chg[args] = value return 1 end if this_chg and value[1] == this_chg[1] and value[2] == this_chg[2] and value[3] == this_chg[3] then return 0 end chg[args] = value return 1 end -- This is the prototype for all table types. e2function number changed(angle value) local chg = self.data.changed local this_chg = chg[args] if not this_chg then chg[args] = value return 1 end for i,v in pairs(value) do if v ~= this_chg[i] then chg[args] = value return 1 end end return 0 end local excluded_types = { n = true, v = true, a = true, [""] = true, r = true, t = true, } local comparable_types = { s = true, e = true, xwl = true, b = true, } registerCallback("postinit", function() -- generate this function for all types for typeid,_ in pairs(wire_expression_types2) do if not excluded_types[typeid] then if comparable_types[typeid] then registerFunction("changed", typeid, "n", registeredfunctions.e2_changed_n) else registerFunction("changed", typeid, "n", registeredfunctions.e2_changed_a) end end end end) /******************************************************************************/ __e2setcost( 5 ) local getHash = E2Lib.getHash e2function number hash() return getHash( self, self.entity.original ) end e2function number hashNoComments() return getHash( self, self.entity.buffer ) end e2function number hash( string str ) return getHash( self, str ) end
fixed reference to missing locals
fixed reference to missing locals
Lua
apache-2.0
sammyt291/wire,NezzKryptic/Wire,wiremod/wire,Grocel/wire,dvdvideo1234/wire
685c381ec5309c80be0e2d35fbfbfdeb825f99b5
samples/testfiledlg.wlua
samples/testfiledlg.wlua
--[==[ luawinapi - winapi wrapper for Lua Copyright (C) 2011-2016 Klaus Oberhofer. See copyright notice in LICENSE file Test file dialog --]==] local winapi = require("luawinapi") local bit = require("bit32") local bor = bit.bor -- control IDs ID_EDIT = 1 ID_BUTTON = 2 -- commands CMD_OPENFILE = 100 CMD_SAVEFILE = 101 -- start print("-----------------GetModuleHandleW") hInstance = winapi.GetModuleHandleW(nil) clsname = toUCS2Z("GettingStarted") handlers = { [WM_CREATE] = function(hwnd, wParam, lParam) hEdit = winapi.CreateWindowExW( 0, toUCS2Z("EDIT"), -- window class name toUCS2Z("Getting Started"), -- window caption bor(WS_VISIBLE, WS_CHILD, ES_MULTILINE), -- window style CW_USEDEFAULT, -- initial x position CW_USEDEFAULT, -- initial y position CW_USEDEFAULT, -- initial x size CW_USEDEFAULT, -- initial y size hwnd, -- parent window handle 0, -- window menu handle hInstance, -- program instance handle 0) -- creation parameters winapi.Assert(hEdit); return 0 end, [WM_WINDOWPOSCHANGED] = function(hwnd, wParam, lParam) local rc = winapi.RECT:new() winapi.GetClientRect(hwnd, rc) local x, y, w, h = rc.left, rc.top, rc.right-rc.left, rc.bottom-rc.top winapi.MoveWindow(hEdit, x, y, w, h, FALSE) return 0 end, [WM_COMMAND] = function(hwnd, wParam, lParam) if (wParam == CMD_OPENFILE) then -- print("Open file", hwnd) local buffer = string.rep("\0\0", 270) local ofn = winapi.OPENFILENAMEW:new() ofn.lStructSize = #ofn ofn.hwndOwner = hwnd.handle -- ofn.hInstance; -- ofn.lpstrFilter = _T("*.txt"); -- ofn.lpstrCustomFilter -- ofn.nMaxCustFilter; -- ofn.nFilterIndex; ofn.lpstrFile = buffer ofn.nMaxFile = 260 -- ofn.lpstrFileTitle; -- ofn.nMaxFileTitle; -- ofn.lpstrInitialDir; -- ofn.lpstrTitle; -- ofn.Flags; -- ofn.nFileOffset; -- ofn.nFileExtension; -- ofn.lpstrDefExt; -- ofn.lCustData; local result = winapi.GetOpenFileNameW(ofn) winapi.Assert(result); if (result ~= 0) then -- set filaname as caption text winapi.SendMessageW(hwnd.handle, WM_SETTEXT, 0, buffer) -- load filename local file = io.open(toASCII(buffer), "r") local content = file:read("*a") winapi.SendMessageW(hEdit.handle, WM_SETTEXT, 0, _T(content)) end elseif (wParam == CMD_SAVEFILE) then -- print("Save file") local ofn = winapi.OPENFILENAMEW:new() ofn.lStructSize = #ofn ofn.hwndOwner = hwnd -- ofn.hInstance; ofn.lpstrFilter = _T("Text Files (*.txt)\0*.txt\0All Files (*.*)\0*.*\0"); -- ofn.lpstrCustomFilter -- ofn.nMaxCustFilter; -- ofn.nFilterIndex; -- ofn.lpstrFile; -- ofn.nMaxFile; -- ofn.lpstrFileTitle; -- ofn.nMaxFileTitle; -- ofn.lpstrInitialDir; -- ofn.lpstrTitle; -- ofn.Flags = bor(OFN_EXPLORER, OFN_HIDEREADONLY); -- ofn.nFileOffset; -- ofn.nFileExtension; ofn.lpstrDefExt = _T("txt"); -- ofn.lCustData; local result = winapi.GetSaveFileNameW(ofn) winapi.Assert(result); if (result ~= 0) then end end return 0 end, [WM_DESTROY] = function(hwnd, wParam, lParam) winapi.PostQuitMessage(0) return 0 end } function WndProc(hwnd, msg, wParam, lParam) -- print(hwnd, MSG_CONSTANTS[msg], wParam, lParam) local handler = handlers[msg] if (handler) then return handler(hwnd, wParam, lParam) else return winapi.DefWindowProcW(hwnd, msg, wParam, lParam) end end print("-----------------CreateWndProcThunk") WndProc_callback = winapi.WndProc.new(nil, WndProc) wndClass = winapi.WNDCLASSW:new() wndClass.style = CS_HREDRAW + CS_VREDRAW; wndClass.lpfnWndProc = WndProc_callback.entrypoint wndClass.cbClsExtra = 0 wndClass.cbWndExtra = 0 wndClass.hInstance = hInstance wndClass.hIcon = 0 -- winapi.LoadIcon(NULL, IDI_APPLICATION); wndClass.hCursor = winapi.LoadCursorW(NULL, IDC_ARROW); wndClass.hbrBackground = winapi.GetStockObject(WHITE_BRUSH); wndClass.lpszMenuName = 0 wndClass.lpszClassName = clsname print("-----------------RegisterClassW") atom = winapi.RegisterClassW(wndClass); print("-----------------atom", atom) if (not atom) then error(WinError()) end print("---------------CreateMenu-------------------------") local hmenu = winapi.CreateMenu(); local hSubMenu = winapi.CreateMenu(); winapi.AppendMenuW(hSubMenu, MF_STRING, CMD_OPENFILE, _T("OpenFile")); winapi.AppendMenuW(hSubMenu, MF_STRING, CMD_SAVEFILE, _T("SaveFile")); winapi.AppendMenuW(hmenu, MF_POPUP, hSubMenu, _T("File")); print("---------------CreateWindowExW -------------------") hMainWnd = winapi.CreateWindowExW( 0, clsname, -- window class name toUCS2Z("Getting Started"), -- window caption bor(WS_OVERLAPPEDWINDOW, WS_VISIBLE), -- window style CW_USEDEFAULT, -- initial x position CW_USEDEFAULT, -- initial y position CW_USEDEFAULT, -- initial x size CW_USEDEFAULT, -- initial y size 0, -- parent window handle hmenu, -- window menu handle hInstance, -- program instance handle 0) -- creation parameters print("----------- hMainWnd ", hMainWnd) if (0 == hMainWnd) then error(WinError()) end print("---------------ShowWindow -------------------") hMainWnd:ShowWindow(SW_SHOW) print("---------------UpdateWindow -------------------") hMainWnd:UpdateWindow() print("---------------ProcessMessages -------------------") return winapi.ProcessMessages() -- print("---------------end -------------------")
--[==[ luawinapi - winapi wrapper for Lua Copyright (C) 2011-2016 Klaus Oberhofer. See copyright notice in LICENSE file Test file dialog --]==] local winapi = require("luawinapi") local bit = require("bit32") local bor = bit.bor -- control IDs ID_EDIT = 1 ID_BUTTON = 2 -- commands CMD_OPENFILE = 100 CMD_SAVEFILE = 101 -- start print("-----------------GetModuleHandleW") hInstance = winapi.GetModuleHandleW(nil) clsname = toUCS2Z("GettingStarted") handlers = { [WM_CREATE] = function(hwnd, wParam, lParam) hEdit = winapi.CreateWindowExW( 0, toUCS2Z("EDIT"), -- window class name toUCS2Z("Getting Started"), -- window caption bor(WS_VISIBLE, WS_CHILD, ES_MULTILINE), -- window style CW_USEDEFAULT, -- initial x position CW_USEDEFAULT, -- initial y position CW_USEDEFAULT, -- initial x size CW_USEDEFAULT, -- initial y size hwnd, -- parent window handle 0, -- window menu handle hInstance, -- program instance handle 0) -- creation parameters winapi.Assert(hEdit); return 0 end, [WM_WINDOWPOSCHANGED] = function(hwnd, wParam, lParam) local rc = winapi.RECT:new() winapi.GetClientRect(hwnd, rc) local x, y, w, h = rc.left, rc.top, rc.right-rc.left, rc.bottom-rc.top winapi.MoveWindow(hEdit, x, y, w, h, FALSE) return 0 end, [WM_COMMAND] = function(hwnd, wParam, lParam) if (wParam == CMD_OPENFILE) then -- print("Open file", hwnd) local buffer = string.rep("\0\0", 270) local ofn = winapi.OPENFILENAMEW:new() ofn.lStructSize = #ofn ofn.hwndOwner = hwnd.handle -- ofn.hInstance; -- ofn.lpstrFilter = _T("*.txt"); -- ofn.lpstrCustomFilter -- ofn.nMaxCustFilter; -- ofn.nFilterIndex; ofn.lpstrFile = buffer ofn.nMaxFile = 260 -- ofn.lpstrFileTitle; -- ofn.nMaxFileTitle; -- ofn.lpstrInitialDir; -- ofn.lpstrTitle; -- ofn.Flags; -- ofn.nFileOffset; -- ofn.nFileExtension; -- ofn.lpstrDefExt; -- ofn.lCustData; local result = winapi.GetOpenFileNameW(ofn) winapi.Assert(result); if (result ~= 0) then -- set filaname as caption text winapi.SendMessageW(hwnd.handle, WM_SETTEXT, 0, buffer) -- load filename local file = io.open(toASCII(buffer), "r") local content = file:read("*a") winapi.SendMessageW(hEdit.handle, WM_SETTEXT, 0, _T(content)) end elseif (wParam == CMD_SAVEFILE) then local buffer = string.rep("\0\0", 270) -- print("Save file") local ofn = winapi.OPENFILENAMEW:new() ofn.lStructSize = #ofn ofn.hwndOwner = hwnd.handle -- ofn.hInstance; ofn.lpstrFilter = _T("Text Files (*.txt)\0*.txt\0All Files (*.*)\0*.*\0"); -- ofn.lpstrCustomFilter -- ofn.nMaxCustFilter; -- ofn.nFilterIndex; ofn.lpstrFile = buffer ofn.nMaxFile = 260 ofn.lpstrFileTitle = _T("FileTitle"); ofn.nMaxFileTitle = 9; -- ofn.lpstrInitialDir; ofn.lpstrTitle = _T("Title"); ofn.Flags = bor(OFN_SHOWHELP, OFN_OVERWRITEPROMPT); -- ofn.nFileOffset; -- ofn.nFileExtension; -- ofn.lpstrDefExt = _T("txt"); -- ofn.lCustData; local result = winapi.GetSaveFileNameW(ofn) winapi.Assert(result); if (result ~= 0) then end end return 0 end, [WM_DESTROY] = function(hwnd, wParam, lParam) winapi.PostQuitMessage(0) return 0 end } function WndProc(hwnd, msg, wParam, lParam) -- print(hwnd, MSG_CONSTANTS[msg], wParam, lParam) local handler = handlers[msg] if (handler) then return handler(hwnd, wParam, lParam) else return winapi.DefWindowProcW(hwnd, msg, wParam, lParam) end end print("-----------------CreateWndProcThunk") WndProc_callback = winapi.WndProc.new(nil, WndProc) wndClass = winapi.WNDCLASSW:new() wndClass.style = CS_HREDRAW + CS_VREDRAW; wndClass.lpfnWndProc = WndProc_callback.entrypoint wndClass.cbClsExtra = 0 wndClass.cbWndExtra = 0 wndClass.hInstance = hInstance wndClass.hIcon = 0 -- winapi.LoadIcon(NULL, IDI_APPLICATION); wndClass.hCursor = winapi.LoadCursorW(NULL, IDC_ARROW); wndClass.hbrBackground = winapi.GetStockObject(WHITE_BRUSH); wndClass.lpszMenuName = 0 wndClass.lpszClassName = clsname print("-----------------RegisterClassW") atom = winapi.RegisterClassW(wndClass); print("-----------------atom", atom) if (not atom) then error(WinError()) end print("---------------CreateMenu-------------------------") local hmenu = winapi.CreateMenu(); local hSubMenu = winapi.CreateMenu(); winapi.AppendMenuW(hSubMenu, MF_STRING, CMD_OPENFILE, _T("OpenFile")); winapi.AppendMenuW(hSubMenu, MF_STRING, CMD_SAVEFILE, _T("SaveFile")); winapi.AppendMenuW(hmenu, MF_POPUP, hSubMenu, _T("File")); print("---------------CreateWindowExW -------------------") hMainWnd = winapi.CreateWindowExW( 0, clsname, -- window class name toUCS2Z("Getting Started"), -- window caption bor(WS_OVERLAPPEDWINDOW, WS_VISIBLE), -- window style CW_USEDEFAULT, -- initial x position CW_USEDEFAULT, -- initial y position CW_USEDEFAULT, -- initial x size CW_USEDEFAULT, -- initial y size 0, -- parent window handle hmenu, -- window menu handle hInstance, -- program instance handle 0) -- creation parameters print("----------- hMainWnd ", hMainWnd) if (0 == hMainWnd) then error(WinError()) end print("---------------ShowWindow -------------------") hMainWnd:ShowWindow(SW_SHOW) print("---------------UpdateWindow -------------------") hMainWnd:UpdateWindow() print("---------------ProcessMessages -------------------") return winapi.ProcessMessages() -- print("---------------end -------------------")
fixed filedialog example
fixed filedialog example
Lua
mit
oberhofer/luawinapi,oberhofer/luawinapi
723e6eacdfd72c3453d18fa5678c604a45ce4419
examples/alexnet.lua
examples/alexnet.lua
require 'dp' --[[command line arguments]]-- cmd = torch.CmdLine() cmd:text() cmd:text('Training ImageNet (large-scale image classification) using an Alex Krizhevsky Convolution Neural Network') cmd:text('Ref.: A. http://www.cs.toronto.edu/~fritz/absps/imagenet.pdf') cmd:text('B. https://github.com/facebook/fbcunn/blob/master/examples/imagenet/models/alexnet_cunn.lua') cmd:text('Example:') cmd:text('$> th alexnet.lua --batchSize 128 --momentum 0.5') cmd:text('Options:') cmd:option('--dataPath', paths.concat(dp.DATA_DIR, 'ImageNet'), 'path to ImageNet') cmd:option('--trainPath', '', 'Path to train set. Defaults to --dataPath/ILSVRC2012_img_train') cmd:option('--validPath', '', 'Path to valid set. Defaults to --dataPath/ILSVRC2012_img_val') cmd:option('--metaPath', '', 'Path to metadata. Defaults to --dataPath/metadata') cmd:option('--learningRate', 0.01, 'learning rate at t=0') cmd:option('--maxOutNorm', -1, 'max norm each layers output neuron weights') cmd:option('-weightDecay', 5e-4, 'weight decay') cmd:option('--maxNormPeriod', 1, 'Applies MaxNorm Visitor every maxNormPeriod batches') cmd:option('--momentum', 0.9, 'momentum') cmd:option('--batchSize', 128, 'number of examples per batch') cmd:option('--cuda', false, 'use CUDA') cmd:option('--useDevice', 1, 'sets the device (GPU) to use') cmd:option('--trainEpochSize', -1, 'number of train examples seen between each epoch') cmd:option('--maxEpoch', 100, 'maximum number of epochs to run') cmd:option('--maxTries', 30, 'maximum number of epochs to try to find a better local minima for early-stopping') cmd:option('--accUpdate', false, 'accumulate gradients inplace') cmd:option('--verbose', false, 'print verbose messages') cmd:option('--progress', false, 'print progress bar') cmd:text() opt = cmd:parse(arg or {}) opt.trainPath = (opt.trainPath == '') and paths.concat(opt.dataPath, 'ILSVRC2012_img_train') or opt.trainPath opt.validPath = (opt.validPath == '') and paths.concat(opt.dataPath, 'ILSVRC2012_img_val') or opt.validPath opt.metaPath = (opt.metaPath == '') and paths.concat(opt.dataPath, 'metadata') or opt.metaPath table.print(opt) --[[data]]-- datasource = dp.ImageNet{ train_path=opt.trainPath, valid_path=opt.validPath, meta_path=opt.metaPath, verbose=opt.verbose } -- preprocessing function ppf = datasource:normalizePPF() --[[Model]]-- -- We create the model using pure nn function createModel() local features = nn.Concat(2) local fb1 = nn.Sequential() -- branch 1 fb1:add(nn.SpatialConvolutionMM(3,48,11,11,4,4,2,2)) -- 224 -> 55 fb1:add(nn.ReLU()) fb1:add(nn.SpatialMaxPooling(3,3,2,2)) -- 55 -> 27 fb1:add(nn.SpatialConvolutionMM(48,128,5,5,1,1,2,2)) -- 27 -> 27 fb1:add(nn.ReLU()) fb1:add(nn.SpatialMaxPooling(3,3,2,2)) -- 27 -> 13 fb1:add(nn.SpatialConvolutionMM(128,192,3,3,1,1,1,1)) -- 13 -> 13 fb1:add(nn.ReLU()) fb1:add(nn.SpatialConvolutionMM(192,192,3,3,1,1,1,1)) -- 13 -> 13 fb1:add(nn.ReLU()) fb1:add(nn.SpatialConvolutionMM(192,128,3,3,1,1,1,1)) -- 13 -> 13 fb1:add(nn.ReLU()) fb1:add(nn.SpatialMaxPooling(3,3,2,2)) -- 13 -> 6 local fb2 = fb1:clone() -- branch 2 for k,v in ipairs(fb2:findModules('nn.SpatialConvolutionMM')) do v:reset() -- reset branch 2's weights end features:add(fb1) features:add(fb2) -- 1.3. Create Classifier (fully connected layers) local classifier = nn.Sequential() classifier:add(nn.View(256*6*6)) classifier:add(nn.Dropout(0.5)) classifier:add(nn.Linear(256*6*6, 4096)) classifier:add(nn.Threshold(0, 1e-6)) classifier:add(nn.Dropout(0.5)) classifier:add(nn.Linear(4096, 4096)) classifier:add(nn.Threshold(0, 1e-6)) classifier:add(nn.Linear(4096, 1000)) classifier:add(nn.LogSoftMax()) -- 1.4. Combine 1.1 and 1.3 to produce final model local model = nn.Sequential():add(features):add(classifier) return model end -- wrap the nn.Module in a dp.Module model = dp.Module{ module = createModel(), input_view = 'bchw', output_view = 'bf', output = dp.ClassView() } --[[Visitor]]-- local visitor = {} -- the ordering here is important: if opt.momentum > 0 then if opt.accUpdate then print"Warning : momentum is ignored with acc_update = true" end table.insert(visitor, dp.Momentum{momentum_factor = opt.momentum} ) end if opt.weightDecay and opt.weightDecay > 0 then if opt.accUpdate then print"Warning : weightdecay is ignored with acc_update = true" end table.insert(visitor, dp.WeightDecay{wd_factor=opt.weightDecay}) end table.insert(visitor, dp.Learn{ learning_rate = opt.learningRate, observer = dp.LearningRateSchedule{ schedule={[1]=1e-2,[19]=5e-3,[30]=1e-3,[44]=5e-4,[53]=1e-4} } } ) if opt.maxOutNorm > 0 then table.insert(visitor, dp.MaxNorm{ max_out_norm = opt.maxOutNorm, period=opt.maxNormPeriod }) end --[[Propagators]]-- train = dp.Optimizer{ loss = dp.NLL(), visitor = visitor, feedback = dp.Confusion(), sampler = dp.RandomSampler{ batch_size=opt.batchSize, epoch_size=opt.trainEpochSize, ppf=ppf }, progress = opt.progress } valid = dp.Evaluator{ loss = dp.NLL(), feedback = dp.TopCrop{n_top={1,5,10},n_crop=10,center=2}, sampler = dp.Sampler{ batch_size=math.round(opt.batchSize/10), ppf=ppf } } --[[Experiment]]-- xp = dp.Experiment{ model = model, optimizer = train, validator = valid, observer = { dp.FileLogger(), dp.EarlyStopper{ error_report = {'validator','feedback','topcrop','all',5}, maximize = true, max_epochs = opt.maxTries } }, random_seed = os.time(), max_epoch = opt.maxEpoch } --[[GPU or CPU]]-- if opt.cuda then require 'cutorch' require 'cunn' cutorch.setDevice(opt.useDevice) xp:cuda() end print"nn.Modules :" print(model:toModule(datasource:trainSet():sub(1,32))) xp:run(datasource)
require 'dp' --[[command line arguments]]-- cmd = torch.CmdLine() cmd:text() cmd:text('Training ImageNet (large-scale image classification) using an Alex Krizhevsky Convolution Neural Network') cmd:text('Ref.: A. http://www.cs.toronto.edu/~fritz/absps/imagenet.pdf') cmd:text('B. https://github.com/facebook/fbcunn/blob/master/examples/imagenet/models/alexnet_cunn.lua') cmd:text('Example:') cmd:text('$> th alexnet.lua --batchSize 128 --momentum 0.5') cmd:text('Options:') cmd:option('--dataPath', paths.concat(dp.DATA_DIR, 'ImageNet'), 'path to ImageNet') cmd:option('--trainPath', '', 'Path to train set. Defaults to --dataPath/ILSVRC2012_img_train') cmd:option('--validPath', '', 'Path to valid set. Defaults to --dataPath/ILSVRC2012_img_val') cmd:option('--metaPath', '', 'Path to metadata. Defaults to --dataPath/metadata') cmd:option('--learningRate', 0.01, 'learning rate at t=0') cmd:option('--maxOutNorm', -1, 'max norm each layers output neuron weights') cmd:option('-weightDecay', 5e-4, 'weight decay') cmd:option('--maxNormPeriod', 1, 'Applies MaxNorm Visitor every maxNormPeriod batches') cmd:option('--momentum', 0.9, 'momentum') cmd:option('--batchSize', 128, 'number of examples per batch') cmd:option('--cuda', false, 'use CUDA') cmd:option('--useDevice', 1, 'sets the device (GPU) to use') cmd:option('--trainEpochSize', -1, 'number of train examples seen between each epoch') cmd:option('--maxEpoch', 100, 'maximum number of epochs to run') cmd:option('--maxTries', 30, 'maximum number of epochs to try to find a better local minima for early-stopping') cmd:option('--accUpdate', false, 'accumulate gradients inplace') cmd:option('--verbose', false, 'print verbose messages') cmd:option('--progress', false, 'print progress bar') cmd:text() opt = cmd:parse(arg or {}) opt.trainPath = (opt.trainPath == '') and paths.concat(opt.dataPath, 'ILSVRC2012_img_train') or opt.trainPath opt.validPath = (opt.validPath == '') and paths.concat(opt.dataPath, 'ILSVRC2012_img_val') or opt.validPath opt.metaPath = (opt.metaPath == '') and paths.concat(opt.dataPath, 'metadata') or opt.metaPath table.print(opt) --[[data]]-- datasource = dp.ImageNet{ train_path=opt.trainPath, valid_path=opt.validPath, meta_path=opt.metaPath, verbose=opt.verbose } -- preprocessing function ppf = datasource:normalizePPF() --[[Model]]-- -- We create the model using pure nn function createModel() local features = nn.Concat(2) local fb1 = nn.Sequential() -- branch 1 fb1:add(nn.SpatialConvolutionMM(3,48,11,11,4,4,2,2)) -- 224 -> 55 fb1:add(nn.ReLU()) fb1:add(nn.SpatialMaxPooling(3,3,2,2)) -- 55 -> 27 fb1:add(nn.SpatialConvolutionMM(48,128,5,5,1,1,2,2)) -- 27 -> 27 fb1:add(nn.ReLU()) fb1:add(nn.SpatialMaxPooling(3,3,2,2)) -- 27 -> 13 fb1:add(nn.SpatialConvolutionMM(128,192,3,3,1,1,1,1)) -- 13 -> 13 fb1:add(nn.ReLU()) fb1:add(nn.SpatialConvolutionMM(192,192,3,3,1,1,1,1)) -- 13 -> 13 fb1:add(nn.ReLU()) fb1:add(nn.SpatialConvolutionMM(192,128,3,3,1,1,1,1)) -- 13 -> 13 fb1:add(nn.ReLU()) fb1:add(nn.SpatialMaxPooling(3,3,2,2)) -- 13 -> 6 fb1:add(nn.Copy(nil, nil, true)) -- temp fix to SpatialMaxPooling bug local fb2 = fb1:clone() -- branch 2 for k,v in ipairs(fb2:findModules('nn.SpatialConvolutionMM')) do v:reset() -- reset branch 2's weights end features:add(fb1) features:add(fb2) -- 1.3. Create Classifier (fully connected layers) local classifier = nn.Sequential() classifier:add(nn.View(256*6*6)) classifier:add(nn.Dropout(0.5)) classifier:add(nn.Linear(256*6*6, 4096)) classifier:add(nn.Threshold(0, 1e-6)) classifier:add(nn.Dropout(0.5)) classifier:add(nn.Linear(4096, 4096)) classifier:add(nn.Threshold(0, 1e-6)) classifier:add(nn.Linear(4096, 1000)) classifier:add(nn.LogSoftMax()) -- 1.4. Combine 1.1 and 1.3 to produce final model local model = nn.Sequential():add(features):add(classifier) return model end -- wrap the nn.Module in a dp.Module model = dp.Module{ module = createModel(), input_view = 'bchw', output_view = 'bf', output = dp.ClassView() } --[[Visitor]]-- local visitor = {} -- the ordering here is important: if opt.momentum > 0 then if opt.accUpdate then print"Warning : momentum is ignored with acc_update = true" end table.insert(visitor, dp.Momentum{momentum_factor = opt.momentum} ) end if opt.weightDecay and opt.weightDecay > 0 then if opt.accUpdate then print"Warning : weightdecay is ignored with acc_update = true" end table.insert(visitor, dp.WeightDecay{wd_factor=opt.weightDecay}) end table.insert(visitor, dp.Learn{ learning_rate = opt.learningRate, observer = dp.LearningRateSchedule{ schedule={[1]=1e-2,[19]=5e-3,[30]=1e-3,[44]=5e-4,[53]=1e-4} } } ) if opt.maxOutNorm > 0 then table.insert(visitor, dp.MaxNorm{ max_out_norm = opt.maxOutNorm, period=opt.maxNormPeriod }) end --[[Propagators]]-- train = dp.Optimizer{ loss = dp.NLL(), visitor = visitor, feedback = dp.Confusion(), sampler = dp.RandomSampler{ batch_size=opt.batchSize, epoch_size=opt.trainEpochSize, ppf=ppf }, progress = opt.progress } valid = dp.Evaluator{ loss = dp.NLL(), feedback = dp.TopCrop{n_top={1,5,10},n_crop=10,center=2}, sampler = dp.Sampler{ batch_size=math.round(opt.batchSize/10), ppf=ppf } } --[[Experiment]]-- xp = dp.Experiment{ model = model, optimizer = train, validator = valid, observer = { dp.FileLogger(), dp.EarlyStopper{ error_report = {'validator','feedback','topcrop','all',5}, maximize = true, max_epochs = opt.maxTries } }, random_seed = os.time(), max_epoch = opt.maxEpoch } --[[GPU or CPU]]-- if opt.cuda then require 'cutorch' require 'cunn' cutorch.setDevice(opt.useDevice) xp:cuda() end print"nn.Modules :" print(model:toModule(datasource:trainSet():sub(1,32))) xp:run(datasource)
temporary SpatialMaxPooling fix
temporary SpatialMaxPooling fix
Lua
bsd-3-clause
rickyHong/dptorchLib,eulerreich/dp,jnhwkim/dp,sagarwaghmare69/dp,kracwarlock/dp,nicholas-leonard/dp,fiskio/dp
fb134b5114b42ae29731d01e739d9b916756fdbf
gamemode/cl_zm_options.lua
gamemode/cl_zm_options.lua
CreateClientConVar("zm_preference", "0", true, true, "What is your Zombie Master preference? (0 = Survivor, 1 = Zombie Master)") CreateClientConVar("zm_nopreferredmenu", "0", true, false, "Toggles the preference menu to appear or not.") GAMEMODE:MakePreferredMenu() local function ZM_Open_Preferred Menu(ply) if not IsValid(ply) then return end GAMEMODE:MakePreferredMenu() end concommand.Add("zm_open_preferred menu", ZM_Open_Preferred Menu, nil, "Opens the preference menu.") local function ZM_Power_PhysExplode(ply) if (not IsValid(ply)) or (IsValid(ply) and not ply:IsZM()) then return end ply:PrintTranslatedMessage(HUD_PRINTTALK, "enter_explosion_mode") GAMEMODE:SetPlacingShockwave(true) end concommand.Add("zm_power_physexplode", ZM_Power_PhysExplode, nil, "Creates a physics explosion at a chosen location") local function ZM_Power_SpotCreate(ply) if (not IsValid(ply)) or (IsValid(ply) and not ply:IsZM()) then return end ply:PrintTranslatedMessage(HUD_PRINTTALK, "enter_hidden_mode") GAMEMODE:SetPlacingSpotZombie(true) end concommand.Add("zm_power_spotcreate", ZM_Power_SpotCreate, nil, "Creates a Shambler at target location, if it is unseen to players") local function ZM_Power_NightVision(ply) if ply:IsZM() then GAMEMODE.nightVision = not GAMEMODE.nightVision ply:PrintTranslatedMessage(HUD_PRINTTALK, "toggled_nightvision") if not GAMEMODE.nightVision then GAMEMODE.nightVisionCur = 0.5 end end end concommand.Add("zm_power_nightvision", ZM_Power_NightVision, nil, "Enables night vision")
CreateClientConVar("zm_preference", "0", true, true, "What is your Zombie Master preference? (0 = Survivor, 1 = Zombie Master)") CreateClientConVar("zm_nopreferredmenu", "0", true, false, "Toggles the preference menu to appear or not.") local function ZM_Open_Preferred_Menu(ply) if not IsValid(ply) then return end GAMEMODE:MakePreferredMenu() end concommand.Add("zm_open_preferred menu", ZM_Open_Preferred_Menu, nil, "Opens the preference menu.") local function ZM_Power_PhysExplode(ply) if (not IsValid(ply)) or (IsValid(ply) and not ply:IsZM()) then return end ply:PrintTranslatedMessage(HUD_PRINTTALK, "enter_explosion_mode") GAMEMODE:SetPlacingShockwave(true) end concommand.Add("zm_power_physexplode", ZM_Power_PhysExplode, nil, "Creates a physics explosion at a chosen location") local function ZM_Power_SpotCreate(ply) if (not IsValid(ply)) or (IsValid(ply) and not ply:IsZM()) then return end ply:PrintTranslatedMessage(HUD_PRINTTALK, "enter_hidden_mode") GAMEMODE:SetPlacingSpotZombie(true) end concommand.Add("zm_power_spotcreate", ZM_Power_SpotCreate, nil, "Creates a Shambler at target location, if it is unseen to players") local function ZM_Power_NightVision(ply) if ply:IsZM() then GAMEMODE.nightVision = not GAMEMODE.nightVision ply:PrintTranslatedMessage(HUD_PRINTTALK, "toggled_nightvision") if not GAMEMODE.nightVision then GAMEMODE.nightVisionCur = 0.5 end end end concommand.Add("zm_power_nightvision", ZM_Power_NightVision, nil, "Enables night vision")
Fixed a error
Fixed a error
Lua
apache-2.0
ForrestMarkX/glua-ZombieMaster
87b860b3ecfad3d8d140e2eda8ed6247299283ee
spec/2.2.7_spec.lua
spec/2.2.7_spec.lua
local Helper = require('spec.spec_helper') local Promise = require('promise') local dummy = { dummy = 'dummy' } -- we fulfill or reject with this when we don't intend to test against it local sentinel = { sentinel = 'sentinel' } -- a sentinel fulfillment value to test for with strict equality local other = { other = 'other' } -- a value we don't want to be strict equal to local reasons = { ["`nil`"] = function() return nil end, ["`false`"] = function() return false end, ["`0`"] = function() return 0 end, ["an error"] = function() error() end, ["a table"] = function() return {} end, ["an always-pending nextable"] = function() return { next = function() end } end, ["a fulfilled promise"] = function() return Helper.resolved(dummy) end, ["a rejected promise"] = function() return Helper.rejected(dummy) end, } describe("2.2.7: `next` must return a promise: `promise2 = promise1:next(onFulfilled, onRejected)`", function() it("is a promise", function() local promise1 = Promise.new() local promise2 = promise1:next() assert.are.same(type(promise2), 'table') assert.are.same(type(promise2.next), "function") end) describe("2.2.7.1: If either `onFulfilled` or `onRejected` returns a value `x`, run the Promise Resolution Procedure `[[Resolve]](promise2, x)`", function() it("see separate 3.3 tests", function() end) end) describe("2.2.7.2: If either `onFulfilled` or `onRejected` throws an exception `e`, `promise2` must be rejected with `e` as the reason.", function() local function testReason(expectedReason, stringRepresentation) describe("The reason is " .. stringRepresentation, function() Helper.test_fulfilled(it, dummy, function(promise1, done) async() settimeout(0.1) local promise2 = promise1:next(function() error(expectedReason) end) promise2:next(nil, function(actualReason) assert.are.equals(actualReason, expectedReason) done() end) end) Helper.test_rejected(it, dummy, function (promise1, done) async() local promise2 = promise1:next(nil, function() error(expectedReason) end) promise2:next(nil, function(actualReason) assert.are.equals(actualReason, expectedReason) done() end):catch(print) end) end) end for stringRepresentation, callback in pairs(reasons) do testReason(callback, stringRepresentation) end end) end) describe("2.2.7.3: If `onFulfilled` is not a function and `promise1` is fulfilled, `promise2` must be fulfilled with the same value.", function() local function testNonFunction(nonFunction, stringRepresentation) describe("`onFulfilled` is " .. stringRepresentation, function() Helper.test_fulfilled(it, sentinel, function(promise1, done) async() settimeout(0.1) local promise2 = promise1:next(nonFunction) promise2:next(function(value) assert.are.equals(value, sentinel) done() end):catch(print) end) end) end testNonFunction(nil, "`nil`") testNonFunction(false, "`false`") testNonFunction(5, "`5`") testNonFunction({}, "a table") testNonFunction({function() return other end}, "an array containing a function") end) describe("2.2.7.4: If `onRejected` is not a function and `promise1` is rejected, `promise2` must be rejected with the same reason.", function() local function testNonFunction(nonFunction, stringRepresentation) describe("`onRejected` is " .. stringRepresentation, function() Helper.test_rejected(it, sentinel, function (promise1, done) local promise2 = promise1:next(nil, nonFunction) promise2:next(nil, function(reason) assert.are.equals(reason, sentinel) done() end) end) end) end testNonFunction(nil, "`nil`") testNonFunction(false, "`false`") testNonFunction(5, "`5`") testNonFunction({}, "a table") testNonFunction({ function()return other end}, "an array containing a function") end)
local Helper = require('spec.spec_helper') local Promise = require('promise') local dummy = { dummy = 'dummy' } -- we fulfill or reject with this when we don't intend to test against it local sentinel = { sentinel = 'sentinel' } -- a sentinel fulfillment value to test for with strict equality local other = { other = 'other' } -- a value we don't want to be strict equal to local reasons = { ["`nil`"] = function() return nil end, ["`false`"] = function() return false end, ["`0`"] = function() return 0 end, ["an error"] = function() error() end, ["a table"] = function() return {} end, ["an always-pending nextable"] = function() return { next = function() end } end, ["a fulfilled promise"] = function() return Helper.resolved(dummy) end, ["a rejected promise"] = function() return Helper.rejected(dummy) end, } describe("2.2.7: `next` must return a promise: `promise2 = promise1:next(onFulfilled, onRejected)`", function() it("is a promise", function() local promise1 = Promise.new() local promise2 = promise1:next() assert.are.same(type(promise2), 'table') assert.are.same(type(promise2.next), "function") end) describe("2.2.7.1: If either `onFulfilled` or `onRejected` returns a value `x`, run the Promise Resolution Procedure `[[Resolve]](promise2, x)`", function() it("see separate 3.3 tests", function() end) end) describe("2.2.7.2: If either `onFulfilled` or `onRejected` throws an exception `e`, `promise2` must be rejected with `e` as the reason.", function() local function testReason(expectedReason, stringRepresentation) describe("The reason is " .. stringRepresentation, function() Helper.test_fulfilled(it, dummy, function(promise1, done) async() local promise2 = promise1:next(function() error(expectedReason) end) promise2:next(nil, function(actualReason) assert.are.equals(actualReason, expectedReason) done() end) end) Helper.test_rejected(it, dummy, function (promise1, done) async() local promise2 = promise1:next(nil, function() error(expectedReason) end) promise2:next(nil, function(actualReason) assert.are.equals(actualReason, expectedReason) done() end):catch(print) end) end) end for stringRepresentation, callback in pairs(reasons) do testReason(callback, stringRepresentation) end end) end) describe("2.2.7.3: If `onFulfilled` is not a function and `promise1` is fulfilled, `promise2` must be fulfilled with the same value.", function() local function testNonFunction(nonFunction, stringRepresentation) describe("`onFulfilled` is " .. stringRepresentation, function() Helper.test_fulfilled(it, sentinel, function(promise1, done) async() settimeout(0.1) local promise2 = promise1:next(nonFunction) promise2:next(function(value) assert.are.equals(value, sentinel) done() end):catch(print) end) end) end testNonFunction(nil, "`nil`") testNonFunction(false, "`false`") testNonFunction(5, "`5`") testNonFunction({}, "a table") testNonFunction({function() return other end}, "an array containing a function") end) describe("2.2.7.4: If `onRejected` is not a function and `promise1` is rejected, `promise2` must be rejected with the same reason.", function() local function testNonFunction(nonFunction, stringRepresentation) describe("`onRejected` is " .. stringRepresentation, function() Helper.test_rejected(it, sentinel, function (promise1, done) async() local promise2 = promise1:next(nil, nonFunction) promise2:next(nil, function(reason) assert.are.equals(reason, sentinel) done() end) end) end) end testNonFunction(nil, "`nil`") testNonFunction(false, "`false`") testNonFunction(5, "`5`") testNonFunction({}, "a table") testNonFunction({ function()return other end}, "an array containing a function") end)
Fix missing async() causing sporadic test failure.
Fix missing async() causing sporadic test failure.
Lua
mit
takaaptech/promise.lua,Billiam/promise.lua
30f1fae25ce6086ec2e7dce26bb6d91cbb1f7e1d
libs/sys/luasrc/sys/mtdow.lua
libs/sys/luasrc/sys/mtdow.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Copyright 2008 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local io = require "io" local os = require "os" local fs = require "luci.fs" local util = require "luci.util" local ltn12 = require "luci.ltn12" local posix = require "posix" local type, assert, error = type, assert, error module "luci.sys.mtdow" WRITE_IMAGE = 0 WRITE_COMBINED = 1 WRITE_EMULATED = 2 ERROR_INTERNAL = 1 ERROR_NOTFOUND = 2 ERROR_RESOURCE = 3 ERROR_NODETECT = 4 ERROR_NOTAVAIL = 5 ERROR_NOSTREAM = 6 ERROR_INVMAGIC = 7 Writer = util.class() -- x86 EmulatedWriter = util.class(Writer) EmulatedWriter.blocks = { image = { magic = "eb48", device = "/dev/hda", write = WRITE_SEPARATELY } } function EmulatedWriter.write_block(self, name, imagestream, appendpattern) if appendpattern then os.execute("grep rootfs /proc/mtd >/dev/null || " .. "{ echo /dev/hda2,65536,rootfs > " .. "/sys/module/block2mtd/parameters/block2mtd }") end return Writer.write_block(self, name, imagestream, appendpattern) end -- Broadcom CFEWriter = util.class(Writer) CFEWriter.blocks = { image = { magic = {"4844", "5735"}, device = "linux", write = WRITE_COMBINED } } -- Magicbox CommonWriter = util.class(Writer) CommonWriter.blocks = { image = { device = "linux", write = WRITE_COMBINED } } -- Atheros RedWriter = util.class(Writer) RedWriter.blocks = { kernel = { device = "vmlinux.bin.l7", write = WRITE_IMAGE }, rootfs = { device = "rootfs", write = WRITE_COMBINED } } -- Auto Detect function native_writer() local w = Writer() -- Detect amd64 / x86 local x86 = {"x86_64", "i386", "i486", "i586", "i686"} if util.contains(x86, posix.uname("%m")) then return EmulatedWriter() end -- Detect CFE if w:_find_mtdblock("cfe") and w:_find_mtdblock("linux") then return CFEWriter() end -- Detect Redboot if w:_find_mtdblock("RedBoot") and w:_find_mtdblock("vmlinux.bin.l7") then return RedWriter() end -- Detect MagicBox if fs.readfile("/proc/cpuinfo"):find("MagicBox") then return CommonWriter() end end Writer.MTD = "/sbin/mtd" Writer.SAFEMTD = "/tmp/mtd" Writer.IMAGEFIFO = "/tmp/mtdimage.fifo" function Writer.write_block(self, name, imagestream, appendfile) assert(self.blocks[name], ERROR_NOTFOUND) local block = self.blocks[name] local device = block.device device = fs.stat(device) and device or self:_find_mtdblock(device) assert(device, ERROR_NODETECT) if block.magic then imagestream = self:_check_magic(imagestream, block.magic) end assert(imagestream, ERROR_INVMAGIC) if appendfile then if block.write == WRITE_COMBINED then return (self:_write_combined(device, imagestream, appendfile) == 0) elseif block.write == WRITE_EMULATED then return (self:_write_emulated(device, imagestream, appendfile) == 0) else error(ERROR_NOTAVAIL) end else return (self:_write_memory(device, imagestream) == 0) end end function Writer._check_magic(self, imagestream, magic) magic = type(magic) == "table" and magic or {magic} local block = imagestream() assert(block, ERROR_NOSTREAM) local cm = "%x%x" % {block:byte(1), block:byte(2)} if util.contains(magic, cm) then return ltn12.source.cat(ltn12.source.string(block), imagestream) end end function Writer._find_mtdblock(self, mtdname) local k local prefix = "/dev/mtd" prefix = prefix .. (fs.stat(prefix) and "/" or "") for l in io.lines("/proc/mtd") do local k = l:match('mtd([%%w-_]+):.*"%s"' % mtdname) if k then return prefix..k end end end function Writer._write_emulated(self, devicename, imagestream, appendfile) local stat = (self:_write_memory(device, imagestream) == 0) stat = stat and (self:_refresh_block("rootfs") == 0) local squash = self:_find_mtdblock("rootfs_data") if squash then stat = stat and (self:_append("rootfs_data", imagestream, true) == 0) else stat = stat and (self:_append("rootfs", imagestream) == 0) end return stat end function Writer._write_memory(self, devicename, imagestream) local devicestream = ltn12.sink.file(io.open(devicename, "w")) local stat, err = ltn12.pump.all(imagestream, devicestream) if stat then return os.execute("sync") end end function Writer._write_combined(self, devicename, imagestream, appendfile) local imageproc = posix.fork() assert(imageproc ~= -1, ERROR_RESOURCE) if imageproc == 0 then fs.unlink(self.IMAGEFIFO) assert(posix.mkfifo(self.IMAGEFIFO), ERROR_RESOURCE) local imagefifo = io.open(self.IMAGEFIFO, "w") assert(imagefifo, ERROR_RESOURCE) ltn12.pump.all(imagestream, ltn12.sink.file(imagefifo)) os.exit(0) end return os.execute( "%s -j '%s' write '%s' '%s'" % { self.MTD, appendfile, self.IMAGEFIFO, devicename } ) end function Writer._refresh_block(self, devicename) return os.execute("%s refresh '%s'" % {self.MTD, devicename}) end function Writer._append(self, devicename, appendfile, erase) erase = erase and ("-e '%s' " % devicename) or '' return os.execute( "%s %s jffs2write '%s' '%s'" % { self.MTD, erase, appendfile, devicename } ) end
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Copyright 2008 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local io = require "io" local os = require "os" local fs = require "luci.fs" local util = require "luci.util" local ltn12 = require "luci.ltn12" local posix = require "posix" local type, assert, error = type, assert, error module "luci.sys.mtdow" WRITE_IMAGE = 0 WRITE_COMBINED = 1 WRITE_EMULATED = 2 ERROR_INTERNAL = 1 ERROR_NOTFOUND = 2 ERROR_RESOURCE = 3 ERROR_NODETECT = 4 ERROR_NOTAVAIL = 5 ERROR_NOSTREAM = 6 ERROR_INVMAGIC = 7 Writer = util.class() -- x86 EmulatedWriter = util.class(Writer) EmulatedWriter.blocks = { image = { magic = "eb48", device = "/dev/hda", write = WRITE_SEPARATELY } } function EmulatedWriter.write_block(self, name, imagestream, appendpattern) if appendpattern then os.execute("grep rootfs /proc/mtd >/dev/null || " .. "{ echo /dev/hda2,65536,rootfs > " .. "/sys/module/block2mtd/parameters/block2mtd }") end return Writer.write_block(self, name, imagestream, appendpattern) end -- Broadcom CFEWriter = util.class(Writer) CFEWriter.blocks = { image = { magic = {"4844", "5735"}, device = "linux", write = WRITE_IMAGE } } -- Magicbox CommonWriter = util.class(Writer) CommonWriter.blocks = { image = { device = "linux", write = WRITE_COMBINED } } -- Atheros RedWriter = util.class(Writer) RedWriter.blocks = { kernel = { device = "vmlinux.bin.l7", write = WRITE_IMAGE }, rootfs = { device = "rootfs", write = WRITE_COMBINED } } -- Auto Detect function native_writer() local w = Writer() -- Detect amd64 / x86 local x86 = {"x86_64", "i386", "i486", "i586", "i686"} if util.contains(x86, posix.uname("%m")) then return EmulatedWriter() end -- Detect CFE if w:_find_mtdblock("cfe") and w:_find_mtdblock("linux") then return CFEWriter() end -- Detect Redboot if w:_find_mtdblock("RedBoot") and w:_find_mtdblock("vmlinux.bin.l7") then return RedWriter() end -- Detect MagicBox if fs.readfile("/proc/cpuinfo"):find("MagicBox") then return CommonWriter() end end Writer.MTD = "/sbin/mtd" Writer.SAFEMTD = "/tmp/mtd" Writer.IMAGEFIFO = "/tmp/mtdimage.fifo" function Writer.write_block(self, name, imagestream, appendfile) assert(self.blocks[name], ERROR_NOTFOUND) local block = self.blocks[name] local device = block.device device = fs.stat(device) and device or self:_find_mtdblock(device) assert(device, ERROR_NODETECT) if block.magic then imagestream = self:_check_magic(imagestream, block.magic) end assert(imagestream, ERROR_INVMAGIC) if appendfile then if block.write == WRITE_COMBINED then return (self:_write_combined(device, imagestream, appendfile) == 0) elseif block.write == WRITE_EMULATED then return (self:_write_emulated(device, imagestream, appendfile) == 0) else error(ERROR_NOTAVAIL) end else return (self:_write_memory(device, imagestream) == 0) end end function Writer._check_magic(self, imagestream, magic) magic = type(magic) == "table" and magic or {magic} local block = imagestream() assert(block, ERROR_NOSTREAM) local cm = "%x%x" % {block:byte(1), block:byte(2)} if util.contains(magic, cm) then return ltn12.source.cat(ltn12.source.string(block), imagestream) end end function Writer._find_mtdblock(self, mtdname) local k local prefix = "/dev/mtd" prefix = prefix .. (fs.stat(prefix) and "/" or "") for l in io.lines("/proc/mtd") do local k = l:match('mtd([%%w-_]+):.*"%s"' % mtdname) if k then return prefix..k end end end function Writer._write_emulated(self, devicename, imagestream, appendfile) local stat = (self:_write_memory(device, imagestream) == 0) stat = stat and (self:_refresh_block("rootfs") == 0) local squash = self:_find_mtdblock("rootfs_data") if squash then stat = stat and (self:_append("rootfs_data", imagestream, true) == 0) else stat = stat and (self:_append("rootfs", imagestream) == 0) end return stat end function Writer._write_memory(self, devicename, imagestream) local imageproc = posix.fork() assert(imageproc ~= -1, ERROR_RESOURCE) if imageproc == 0 then fs.unlink(self.IMAGEFIFO) assert(posix.mkfifo(self.IMAGEFIFO), ERROR_RESOURCE) local imagefifo = io.open(self.IMAGEFIFO, "w") assert(imagefifo, ERROR_RESOURCE) ltn12.pump.all(imagestream, ltn12.sink.file(imagefifo)) os.exit(0) end return os.execute( "%s write '%s' '%s'" % { self.MTD, self.IMAGEFIFO, devicename } ) end function Writer._write_combined(self, devicename, imagestream, appendfile) local imageproc = posix.fork() assert(imageproc ~= -1, ERROR_RESOURCE) if imageproc == 0 then fs.unlink(self.IMAGEFIFO) assert(posix.mkfifo(self.IMAGEFIFO), ERROR_RESOURCE) local imagefifo = io.open(self.IMAGEFIFO, "w") assert(imagefifo, ERROR_RESOURCE) ltn12.pump.all(imagestream, ltn12.sink.file(imagefifo)) os.exit(0) end return os.execute( "%s -j '%s' write '%s' '%s'" % { self.MTD, appendfile, self.IMAGEFIFO, devicename } ) end function Writer._refresh_block(self, devicename) return os.execute("%s refresh '%s'" % {self.MTD, devicename}) end function Writer._append(self, devicename, appendfile, erase) erase = erase and ("-e '%s' " % devicename) or '' return os.execute( "%s %s jffs2write '%s' '%s'" % { self.MTD, erase, appendfile, devicename } ) end
More mtdow fixes
More mtdow fixes git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@3360 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,8devices/carambola2-luci,ch3n2k/luci,Canaan-Creative/luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,Flexibity/luci,dtaht/cerowrt-luci-3.3,ReclaimYourPrivacy/cloak-luci,alxhh/piratenluci,vhpham80/luci,projectbismark/luci-bismark,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,8devices/carambola2-luci,projectbismark/luci-bismark,ch3n2k/luci,projectbismark/luci-bismark,zwhfly/openwrt-luci,vhpham80/luci,ch3n2k/luci,saraedum/luci-packages-old,ThingMesh/openwrt-luci,projectbismark/luci-bismark,freifunk-gluon/luci,phi-psi/luci,Canaan-Creative/luci,jschmidlapp/luci,gwlim/luci,8devices/carambola2-luci,stephank/luci,Flexibity/luci,ch3n2k/luci,8devices/carambola2-luci,ch3n2k/luci,Flexibity/luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,Flexibity/luci,zwhfly/openwrt-luci,projectbismark/luci-bismark,ThingMesh/openwrt-luci,Flexibity/luci,eugenesan/openwrt-luci,eugenesan/openwrt-luci,vhpham80/luci,dtaht/cerowrt-luci-3.3,alxhh/piratenluci,yeewang/openwrt-luci,gwlim/luci,zwhfly/openwrt-luci,dtaht/cerowrt-luci-3.3,eugenesan/openwrt-luci,vhpham80/luci,ch3n2k/luci,freifunk-gluon/luci,eugenesan/openwrt-luci,stephank/luci,ReclaimYourPrivacy/cloak-luci,gwlim/luci,jschmidlapp/luci,8devices/carambola2-luci,saraedum/luci-packages-old,ThingMesh/openwrt-luci,Flexibity/luci,freifunk-gluon/luci,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,alxhh/piratenluci,projectbismark/luci-bismark,phi-psi/luci,stephank/luci,Canaan-Creative/luci,saraedum/luci-packages-old,8devices/carambola2-luci,alxhh/piratenluci,projectbismark/luci-bismark,jschmidlapp/luci,phi-psi/luci,freifunk-gluon/luci,zwhfly/openwrt-luci,phi-psi/luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,ReclaimYourPrivacy/cloak-luci,saraedum/luci-packages-old,ThingMesh/openwrt-luci,vhpham80/luci,alxhh/piratenluci,Canaan-Creative/luci,jschmidlapp/luci,Flexibity/luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,yeewang/openwrt-luci,freifunk-gluon/luci,freifunk-gluon/luci,phi-psi/luci,gwlim/luci,zwhfly/openwrt-luci,projectbismark/luci-bismark,jschmidlapp/luci,Canaan-Creative/luci,zwhfly/openwrt-luci,vhpham80/luci,yeewang/openwrt-luci,8devices/carambola2-luci,yeewang/openwrt-luci,freifunk-gluon/luci,gwlim/luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,yeewang/openwrt-luci,dtaht/cerowrt-luci-3.3,phi-psi/luci,dtaht/cerowrt-luci-3.3,zwhfly/openwrt-luci,jschmidlapp/luci,alxhh/piratenluci,gwlim/luci,Flexibity/luci,Canaan-Creative/luci,freifunk-gluon/luci,gwlim/luci,zwhfly/openwrt-luci,alxhh/piratenluci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,stephank/luci,stephank/luci,stephank/luci,yeewang/openwrt-luci,dtaht/cerowrt-luci-3.3,jschmidlapp/luci
ca8fbd771a10ee3ef9f902ccfacd2d065778b951
test_scripts/Polices/build_options/020_ATF_P_TC_PTU_Validation_Failure_HTTP.lua
test_scripts/Polices/build_options/020_ATF_P_TC_PTU_Validation_Failure_HTTP.lua
--------------------------------------------------------------------------------------------- -- HTTP flow -- Requirements summary: -- [PolicyTableUpdate] PTU validation failure -- -- Description: -- In case PTU validation fails, SDL must log the error locally and discard the policy table update -- with No notification of Cloud about invalid data and -- notify HMI with OnPolicyUpdate(UPDATE_NEEDED) . -- 1. Used preconditions -- SDL is built with "-DEXTENDED_POLICY: HTTP" flag -- Application is registered. -- PTU is requested -- SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED) -- SDL->MOB: OnSystemRequest() -- SDL->HMI: SDL.OnStatusUpdate(UPDATING) -- 2. Performed steps -- MOB->SDL: SystemRequest(policy_file): policy_file with missing mandatory seconds_between_retries -- -- Expected result: -- SDL->HMI: OnStatusUpdate(UPDATE_NEEDED) -- SDL removes 'policyfile' from the directory --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonFunctions = require("user_modules/shared_testcases/commonFunctions") local commonSteps = require("user_modules/shared_testcases/commonSteps") local json = require("modules/json") --[[ Local Variables ]] local sequence = { } local app_id = config.application1.registerAppInterfaceParams.appID local f_name = os.tmpname() local ptu local policy_file_name = "PolicyTableUpdate" local policy_file_path = commonFunctions:read_parameter_from_smart_device_link_ini("SystemFilesPath") local actual_status = { } --[[ Local Functions ]] local function timestamp() local f = io.popen("date +%H:%M:%S.%3N") local o = f:read("*all") f:close() return (o:gsub("\n", "")) end local function log(event, ...) table.insert(sequence, { ts = timestamp(), e = event, p = {...} }) end local function show_log() print("--- Sequence -------------------------------------") for k, v in pairs(sequence) do local s = k .. ": " .. v.ts .. ": " .. v.e for _, val in pairs(v.p) do if val then s = s .. ": " .. val end end print(s) end print("--------------------------------------------------") end local function check_file_exists(name) local f = io.open(name, "r") if f ~= nil then io.close(f) return true else return false end end local function clean_table(t) for i = 0, #t do t[i]=nil end end --[[ General Precondition before ATF start ]] commonFunctions:SDLForceStop() commonSteps:DeleteLogsFileAndPolicyTable() --[[ General Settings for configuration ]] Test = require("connecttest") require("user_modules/AppTypes") config.defaultProtocolVersion = 2 function Test:RegisterNotification() self.mobileSession:ExpectNotification("OnSystemRequest") :Do(function(_, d) ptu = json.decode(d.binaryData) end) :Times(AtLeast(1)) :Pin() end --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test.DeletePTUFile() if check_file_exists(policy_file_path .. "/" .. policy_file_name) then os.remove(policy_file_path .. "/" .. policy_file_name) print("Policy file is removed") end end function Test:ValidatePTS() if ptu.policy_table.consumer_friendly_messages.messages then self:FailTestCase("Expected absence of 'consumer_friendly_messages.messages' section in PTS") end end function Test.UpdatePTS() ptu.policy_table.device_data = nil ptu.policy_table.usage_and_error_counts = nil ptu.policy_table.app_policies[app_id] = { keep_context = false, steal_focus = false, priority = "NONE", default_hmi = "NONE" } ptu.policy_table.app_policies[app_id]["groups"] = { "Base-4", "Base-6" } ptu.policy_table.functional_groupings["DataConsent-2"].rpcs = json.null -- remove mandatory field ptu.policy_table.module_config.seconds_between_retries = nil end function Test.StorePTSInFile() local f = io.open(f_name, "w") f:write(json.encode(ptu)) f:close() end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:Update_LPT() clean_table(actual_status) local corId = self.mobileSession:SendRPC("SystemRequest", { requestType = "HTTP", fileName = policy_file_name }, f_name) log("MOB->SDL: SystemRequest") EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate") :ValidIf(function(e, d) log("SDL->HMI: SDL.OnStatusUpdate", e.occurences, d.params.status) if e.occurences == 1 and d.params.status == "UPDATE_NEEDED" then return true elseif e.occurences == 2 and d.params.status == "UPDATING" then return true elseif e.occurences == 3 and d.params.status == "UPDATE_NEEDED" then return true end return false, table.concat({"Unexpected SDL.OnStatusUpdate with ocurrance '", e.occurences, "' and status '", d.params.status, "'"}) end) :Times(3) EXPECT_RESPONSE(corId, { success = true, resultCode = "SUCCESS" }) :Do(function(_, _) log("SUCCESS: SystemRequest()") end) end function Test.Test_ShowSequence() show_log() end function Test:Validate_PolicyFile() if check_file_exists(policy_file_path .. "/" .. policy_file_name) then self:FailTestCase("Expected absence of policy file, but it exists") end end function Test:Validate_LogFile() local log_file = "SmartDeviceLinkCore.log" local log_path = table.concat({ config.pathToSDL, "/", log_file }) local exp_msg = "Errors: policy_table.policy_table.module_config.seconds_between_retries: object is not initialized" if not commonFunctions:read_specific_message(log_path, exp_msg) then local msg = table.concat({ "Expected error message was not found in ", log_file }) self:FailTestCase(msg) end end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Clean() os.remove(f_name) end function Test.Postconditions_StopSDL() StopSDL() end return Test
--------------------------------------------------------------------------------------------- -- HTTP flow -- Requirements summary: -- [PolicyTableUpdate] PTU validation failure -- -- Description: -- In case PTU validation fails, SDL must log the error locally and discard the policy table update -- with No notification of Cloud about invalid data and -- notify HMI with OnPolicyUpdate(UPDATE_NEEDED) . -- 1. Used preconditions -- SDL is built with "-DEXTENDED_POLICY: HTTP" flag -- Application is registered. -- PTU is requested -- SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED) -- SDL->MOB: OnSystemRequest() -- SDL->HMI: SDL.OnStatusUpdate(UPDATING) -- 2. Performed steps -- MOB->SDL: SystemRequest(policy_file): policy_file with missing mandatory seconds_between_retries -- -- Expected result: -- SDL->HMI: OnStatusUpdate(UPDATE_NEEDED) --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonFunctions = require("user_modules/shared_testcases/commonFunctions") local commonSteps = require("user_modules/shared_testcases/commonSteps") local json = require("modules/json") --[[ Local Variables ]] local sequence = { } local app_id = config.application1.registerAppInterfaceParams.appID local f_name = os.tmpname() local ptu local policy_file_name = "PolicyTableUpdate" local policy_file_path = commonFunctions:read_parameter_from_smart_device_link_ini("SystemFilesPath") local r_expected = { "UPDATE_NEEDED", "UPDATING", "UPDATE_NEEDED", "UPDATING" } local r_actual = { } --[[ Local Functions ]] local function timestamp() local f = io.popen("date +%H:%M:%S.%3N") local o = f:read("*all") f:close() return (o:gsub("\n", "")) end local function log(event, ...) table.insert(sequence, { ts = timestamp(), e = event, p = {...} }) end local function show_log() print("--- Sequence -------------------------------------") for k, v in pairs(sequence) do local s = k .. ": " .. v.ts .. ": " .. v.e for _, val in pairs(v.p) do if val then s = s .. ": " .. val end end print(s) end print("--------------------------------------------------") end local function check_file_exists(name) local f = io.open(name, "r") if f ~= nil then io.close(f) return true else return false end end local function is_table_equal(t1, t2) local ty1 = type(t1) local ty2 = type(t2) if ty1 ~= ty2 then return false end if ty1 ~= 'table' and ty2 ~= 'table' then return t1 == t2 end for k1, v1 in pairs(t1) do local v2 = t2[k1] if v2 == nil or not is_table_equal(v1, v2) then return false end end for k2, v2 in pairs(t2) do local v1 = t1[k2] if v1 == nil or not is_table_equal(v1, v2) then return false end end return true end --[[ General Precondition before ATF start ]] commonFunctions:SDLForceStop() commonSteps:DeleteLogsFileAndPolicyTable() --[[ General Settings for configuration ]] Test = require("connecttest") require("user_modules/AppTypes") config.defaultProtocolVersion = 2 EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate") :Do(function(_, d) log("SDL->HMI: N: SDL.OnStatusUpdate", d.params.status) table.insert(r_actual, d.params.status) end) :Times(AnyNumber()) :Pin() function Test:RegisterNotification() self.mobileSession:ExpectNotification("OnSystemRequest") :Do(function(_, d) ptu = json.decode(d.binaryData) end) :Times(AtLeast(1)) :Pin() end --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test.DeletePTUFile() if check_file_exists(policy_file_path .. "/" .. policy_file_name) then os.remove(policy_file_path .. "/" .. policy_file_name) print("Policy file is removed") end end function Test:ValidatePTS() if ptu.policy_table.consumer_friendly_messages.messages then self:FailTestCase("Expected absence of 'consumer_friendly_messages.messages' section in PTS") end end function Test.UpdatePTS() ptu.policy_table.device_data = nil ptu.policy_table.usage_and_error_counts = nil ptu.policy_table.app_policies[app_id] = { keep_context = false, steal_focus = false, priority = "NONE", default_hmi = "NONE" } ptu.policy_table.app_policies[app_id]["groups"] = { "Base-4", "Base-6" } ptu.policy_table.functional_groupings["DataConsent-2"].rpcs = json.null -- remove mandatory field ptu.policy_table.module_config.seconds_between_retries = nil end function Test.StorePTSInFile() local f = io.open(f_name, "w") f:write(json.encode(ptu)) f:close() end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:Update_LPT() -- clean_table(r_actual) local corId = self.mobileSession:SendRPC("SystemRequest", { requestType = "HTTP", fileName = policy_file_name }, f_name) log("MOB->SDL: SystemRequest") EXPECT_RESPONSE(corId, { success = true, resultCode = "SUCCESS" }) :Do(function(_, _) log("SUCCESS: SystemRequest()") end) end function Test.Test_ShowSequence() show_log() end function Test:ValidateResult() if not is_table_equal(r_actual, r_expected) then local msg = table.concat({ "\nExpected sequence:\n", commonFunctions:convertTableToString(r_expected, 1), "\nActual:\n", commonFunctions:convertTableToString(r_actual, 1) }) self:FailTestCase(msg) end end function Test:Validate_LogFile() local log_file = "SmartDeviceLinkCore.log" local log_path = table.concat({ config.pathToSDL, "/", log_file }) local exp_msg = "Errors: policy_table.policy_table.module_config.seconds_between_retries: object is not initialized" if not commonFunctions:read_specific_message(log_path, exp_msg) then local msg = table.concat({ "Expected error message was not found in ", log_file }) self:FailTestCase(msg) end end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Clean() os.remove(f_name) end function Test.Postconditions_StopSDL() StopSDL() end return Test
Fix issues
Fix issues
Lua
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
b04ff7c985870e360fa267fc4fbc6de036c6d379
src/core/packet.lua
src/core/packet.lua
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(...,package.seeall) local debug = _G.developer_debug local ffi = require("ffi") local C = ffi.C local freelist = require("core.freelist") local lib = require("core.lib") local memory = require("core.memory") local counter = require("core.counter") local freelist_add, freelist_remove, freelist_nfree = freelist.add, freelist.remove, freelist.nfree require("core.packet_h") local packet_t = ffi.typeof("struct packet") local packet_ptr_t = ffi.typeof("struct packet *") local packet_size = ffi.sizeof(packet_t) local header_size = 8 local max_payload = tonumber(C.PACKET_PAYLOAD_SIZE) -- Freelist containing empty packets ready for use. local max_packets = 1e5 local packet_allocation_step = 1000 local packets_allocated = 0 local packets_fl = freelist.new("struct packet *", max_packets) -- Return an empty packet. function allocate () if freelist_nfree(packets_fl) == 0 then preallocate_step() end return freelist_remove(packets_fl) end -- Create a new empty packet. function new_packet () local p = ffi.cast(packet_ptr_t, memory.dma_alloc(packet_size)) p.length = 0 return p end -- Create an exact copy of a packet. function clone (p) local p2 = allocate() ffi.copy(p2, p, p.length) p2.length = p.length return p2 end -- Append data to the end of a packet. function append (p, ptr, len) assert(p.length + len <= max_payload, "packet payload overflow") ffi.copy(p.data + p.length, ptr, len) p.length = p.length + len return p end -- Prepend data to the start of a packet. function prepend (p, ptr, len) assert(p.length + len <= max_payload, "packet payload overflow") C.memmove(p.data + len, p.data, p.length) -- Move the existing payload ffi.copy(p.data, ptr, len) -- Fill the gap p.length = p.length + len return p end -- Move packet data to the left. This shortens the packet by dropping -- the header bytes at the front. function shiftleft (p, bytes) C.memmove(p.data, p.data+bytes, p.length-bytes) p.length = p.length - bytes end -- Move packet data to the right. This leaves length bytes of data -- at the beginning of the packet. function shiftright (p, bytes) C.memmove(p.data + bytes, p.data, p.length) p.length = p.length + bytes end -- Conveniently create a packet by copying some existing data. function from_pointer (ptr, len) return append(allocate(), ptr, len) end function from_string (d) return from_pointer(d, #d) end -- Free a packet that is no longer in use. local function free_internal (p) p.length = 0 freelist_add(packets_fl, p) end function free (p) counter.add(engine.frees) counter.add(engine.freebytes, p.length) -- Calculate bits of physical capacity required for packet on 10GbE -- Account for minimum data size and overhead of CRC and inter-packet gap counter.add(engine.freebits, (math.max(p.length, 46) + 4 + 5) * 8) free_internal(p) end -- Return pointer to packet data. function data (p) return p.data end -- Return packet data length. function length (p) return p.length end function preallocate_step() if _G.developer_debug then assert(packets_allocated + packet_allocation_step <= max_packets) end for i=1, packet_allocation_step do free_internal(new_packet(), true) end packets_allocated = packets_allocated + packet_allocation_step packet_allocation_step = 2 * packet_allocation_step end
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(...,package.seeall) local debug = _G.developer_debug local ffi = require("ffi") local C = ffi.C local freelist = require("core.freelist") local lib = require("core.lib") local memory = require("core.memory") local counter = require("core.counter") local freelist_add, freelist_remove, freelist_nfree = freelist.add, freelist.remove, freelist.nfree require("core.packet_h") local packet_t = ffi.typeof("struct packet") local packet_ptr_t = ffi.typeof("struct packet *") local packet_size = ffi.sizeof(packet_t) local header_size = 8 local max_payload = tonumber(C.PACKET_PAYLOAD_SIZE) -- Freelist containing empty packets ready for use. local max_packets = 1e6 local packet_allocation_step = 1000 local packets_allocated = 0 local packets_fl = freelist.new("struct packet *", max_packets) -- Return an empty packet. function allocate () if freelist_nfree(packets_fl) == 0 then preallocate_step() end return freelist_remove(packets_fl) end -- Create a new empty packet. function new_packet () local p = ffi.cast(packet_ptr_t, memory.dma_alloc(packet_size)) p.length = 0 return p end -- Create an exact copy of a packet. function clone (p) local p2 = allocate() ffi.copy(p2, p, p.length) p2.length = p.length return p2 end -- Append data to the end of a packet. function append (p, ptr, len) assert(p.length + len <= max_payload, "packet payload overflow") ffi.copy(p.data + p.length, ptr, len) p.length = p.length + len return p end -- Prepend data to the start of a packet. function prepend (p, ptr, len) assert(p.length + len <= max_payload, "packet payload overflow") C.memmove(p.data + len, p.data, p.length) -- Move the existing payload ffi.copy(p.data, ptr, len) -- Fill the gap p.length = p.length + len return p end -- Move packet data to the left. This shortens the packet by dropping -- the header bytes at the front. function shiftleft (p, bytes) C.memmove(p.data, p.data+bytes, p.length-bytes) p.length = p.length - bytes end -- Move packet data to the right. This leaves length bytes of data -- at the beginning of the packet. function shiftright (p, bytes) C.memmove(p.data + bytes, p.data, p.length) p.length = p.length + bytes end -- Conveniently create a packet by copying some existing data. function from_pointer (ptr, len) return append(allocate(), ptr, len) end function from_string (d) return from_pointer(d, #d) end -- Free a packet that is no longer in use. local function free_internal (p) p.length = 0 freelist_add(packets_fl, p) end function free (p) counter.add(engine.frees) counter.add(engine.freebytes, p.length) -- Calculate bits of physical capacity required for packet on 10GbE -- Account for minimum data size and overhead of CRC and inter-packet gap counter.add(engine.freebits, (math.max(p.length, 46) + 4 + 5) * 8) free_internal(p) end -- Return pointer to packet data. function data (p) return p.data end -- Return packet data length. function length (p) return p.length end function preallocate_step() if _G.developer_debug then assert(packets_allocated + packet_allocation_step <= max_packets, "packet allocation overflow") end for i=1, packet_allocation_step do free_internal(new_packet(), true) end packets_allocated = packets_allocated + packet_allocation_step packet_allocation_step = 2 * packet_allocation_step end
core.packet: Extend max packets from 100K to 1M
core.packet: Extend max packets from 100K to 1M Packets are allocated dynamically on demand and this is only an artifical limit of "more than anybody should ever need" for catching unbounded allocations (leaks). (The limit also serves to make the freelist simple i.e. a fixed-size array.) The previous value of 100,000 is too low to serve its purpose: it is reasonable to allocate more than 100,000 packet buffers when managing many network receive queues and wanting to avoid packet drops. See discussion at: https://github.com/snabbco/snabb/pull/882#issuecomment-213319205
Lua
apache-2.0
Igalia/snabbswitch,eugeneia/snabb,kbara/snabb,snabbco/snabb,dpino/snabbswitch,Igalia/snabb,SnabbCo/snabbswitch,eugeneia/snabb,eugeneia/snabb,alexandergall/snabbswitch,Igalia/snabbswitch,Igalia/snabbswitch,Igalia/snabb,eugeneia/snabb,wingo/snabbswitch,eugeneia/snabbswitch,snabbco/snabb,mixflowtech/logsensor,dpino/snabbswitch,alexandergall/snabbswitch,wingo/snabb,snabbco/snabb,heryii/snabb,kbara/snabb,dpino/snabb,SnabbCo/snabbswitch,snabbco/snabb,dpino/snabb,wingo/snabbswitch,snabbco/snabb,heryii/snabb,eugeneia/snabbswitch,wingo/snabbswitch,mixflowtech/logsensor,Igalia/snabbswitch,eugeneia/snabbswitch,SnabbCo/snabbswitch,kbara/snabb,Igalia/snabbswitch,heryii/snabb,heryii/snabb,alexandergall/snabbswitch,eugeneia/snabb,alexandergall/snabbswitch,snabbco/snabb,snabbco/snabb,Igalia/snabb,mixflowtech/logsensor,SnabbCo/snabbswitch,alexandergall/snabbswitch,heryii/snabb,eugeneia/snabb,kbara/snabb,alexandergall/snabbswitch,eugeneia/snabb,wingo/snabbswitch,dpino/snabb,eugeneia/snabb,dpino/snabb,Igalia/snabb,wingo/snabb,mixflowtech/logsensor,Igalia/snabb,snabbco/snabb,dpino/snabbswitch,alexandergall/snabbswitch,heryii/snabb,wingo/snabb,Igalia/snabb,wingo/snabb,kbara/snabb,kbara/snabb,dpino/snabb,dpino/snabb,wingo/snabb,wingo/snabb,Igalia/snabb,mixflowtech/logsensor,dpino/snabbswitch,eugeneia/snabbswitch,dpino/snabb,alexandergall/snabbswitch,Igalia/snabb
bf32e622fd361a205a5b1278c64f6ced5613114b
item/vase.lua
item/vase.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/>. ]] -- UPDATE items SET itm_script='item.vase' WHERE itm_id IN (75,292,315); local common = require("base.common") local lookat = require("base.lookat") local M = {} local lakeOfLifeVasePos = { position(660, 239, -9), position(744, 204, -9), position(777, 187, -9), position(705, 263, -9), position(725, 287, -9), position(763, 263, -9), position(777, 284, -9), position(759, 304, -9) } function M.UseItem(User, SourceItem, ltstate) for i = 1, #lakeOfLifeVasePos do if (SourceItem.pos == lakeOfLifeVasePos[i]) and User:getQuestProgress(508) == 1 then world:gfx(53, User.pos) -- nice GFX world:makeSound(13, User.pos) -- nice SFX common.InformNLS(User, "Das Pulver legt sich auf deine feuchte Haut und du beginnst zu glitzern.", "The powder settles on your damp body and you begin to sparkle.") User:setQuestProgress(508,0) User:setQuestProgress(509,0) elseif (SourceItem.pos == lakeOfLifeVasePos[i]) and User:getQuestProgress(508) == 0 then common.InformNLS(User, "Du musst dich fr diese Arbeit erst reinigen.", "You must cleanse first for this to work.") end 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/>. ]] -- UPDATE items SET itm_script='item.vase' WHERE itm_id IN (75,292,315); local common = require("base.common") local M = {} local lakeOfLifeVasePos = { position(660, 239, -9), position(744, 204, -9), position(777, 187, -9), position(705, 263, -9), position(725, 287, -9), position(763, 263, -9), position(777, 284, -9), position(759, 304, -9) } function M.UseItem(User, SourceItem) for i = 1, #lakeOfLifeVasePos do if (SourceItem.pos == lakeOfLifeVasePos[i]) and User:getQuestProgress(508) == 1 then world:gfx(53, User.pos) -- nice GFX world:makeSound(13, User.pos) -- nice SFX common.InformNLS(User, "Das Pulver legt sich auf deine feuchte Haut und du beginnst zu glitzern.", "The powder settles on your damp body and you begin to sparkle.") User:setQuestProgress(508, 0) User:setQuestProgress(509, 0) elseif (SourceItem.pos == lakeOfLifeVasePos[i]) and User:getQuestProgress(508) == 0 then common.InformNLS(User, "Du musst dich fr diese Arbeit erst reinigen.", "You must cleanse first for this to work.") end end end return M
fix indent
fix indent
Lua
agpl-3.0
Baylamon/Illarion-Content,KayMD/Illarion-Content,vilarion/Illarion-Content,Illarion-eV/Illarion-Content
1fc1a21e187453b1efbd430c6df793e3ac0566f0
Modules/Input/BindableAction.lua
Modules/Input/BindableAction.lua
local ReplicatedStorage = game:GetService("ReplicatedStorage") local ContextActionService = game:GetService("ContextActionService") local NevermoreEngine = require(ReplicatedStorage:WaitForChild("NevermoreEngine")) local LoadCustomLibrary = NevermoreEngine.LoadLibrary local Signal = LoadCustomLibrary("Signal") local MakeMaid = LoadCustomLibrary("Maid").MakeMaid --- Translates the ContextActionService binding into an OOP object with event-based properties. -- @author Quenty local BindableAction = {} BindableAction.ClassName = "BindableAction" BindableAction.__index = BindableAction function BindableAction.new(ActionName, InputTypes) local self = {} setmetatable(self, BindableAction) -- DATA self.ActionName = ActionName or error("[BindableAction] - Need ActionName") self.InputTypes = InputTypes or error("[BindableAction] - Need InputTypes") self.ButtonTitle = ActionName self.CreateTouchButton = false -- PRIVATE self.IsBoundState = false -- EVENTS self.BoundFunctionMaid = MakeMaid() self.ActionFired = Signal.new() -- Fires upon action fired. Suggested that you use :BindFunction(Name, Function) instead. self.Bound = Signal.new() -- Fires upon bind self.Unbound = Signal.new() -- Firse upon unbind return self end function BindableAction.FromData(Data) --- Construct from table --[[ Data = { ActionName = "Start_Flying"; FunctionToBind = function(ActionName, UserInputState, InputObject) -- Use UserInputState to determine whether the input is beginning or endnig end; CreateTouchButton = false; [ButtonTitle] = "Fly"; [ButtonImage] = "rbxassetid://137511721"; [InternalDescription] = "Start flying"; InputTypes = {Enum.UserInputType.Accelerometer, Enum.KeyCode.E, Enum.KeyCode.F}; } --]] local New = BindableAction.new(Data.ActionName or error("No ActionName"), Data.InputTypes or error("NO InputTypes")) if Data.CreateTouchButton ~= nil then New:SetCreateTouchButton(Data.CreateTouchButton) end -- BUTTON if Data.ButtonTitle then New:SetButtonTitle(Data.ButtonTitle) end if Data.ButtonImage then New:SetButtonImage(Data.ButtonImage) end -- DESCRIPTION if Data.InternalDescription then New:SetInternalDescription(Data.InternalDescription) end -- FUNCTION if type(Data.FunctionToBind) == "function" then New:BindFunction("Primary", Data.FunctionToBind) elseif type(Data.FunctionToBind) == "table" then for Name, Function in pairs(Data.FunctionToBind) do New:BindFunction(Name, Function) end end return New end function BindableAction:SetCreateTouchButton(DoCreateTouchButton) -- @param DoCreateTouchButton Boolean, should the action create a touch button -- Will not change until rebound. assert(type(DoCreateTouchButton) == "boolean", "DoCreateTouchButton must be a boolean") self.CreateTouchButton = DoCreateTouchButton end function BindableAction:GetInputTypes() return self.InputTypes end function BindableAction:IsBound() -- @return Boolean, true if the action is bound return self.IsBoundState end function BindableAction:GetName() -- @return The action's name return self.ActionName end function BindableAction:SetButtonTitle(ButtonTitle) assert(type(ButtonTitle) == "string", "ButtonTitle must be a string") self.ButtonTitle = ButtonTitle if self:IsBound() then ContextActionService:SetTitle(self.ActionName, self.ButtonTitle) end end function BindableAction:SetButtonImage(ButtonImage) assert(type(ButtonImage) == "string", "ButtonImage must be a string") self.ButtonImage = ButtonImage if self:IsBound() then ContextActionService:SetImage(self.ActionName, self.ButtonImage) end end function BindableAction:SetInternalDescription(Description) --- Sets the internal description self.InternalDescription = Description if self:IsBound() then ContextActionService:SetDescription(self.ActionName, self.InternalDescription) end end function BindableAction:BindFunction(Name, Function) ---Binds the to the BindableAction's FireBound event. :) -- Did some tests. When the BindableAction is GCed, this will also GC the signal and method. So Maid:DoCleaning() need not be called -- to finalize GC even with anonymous functions. self.BoundFunctionMaid[Name] = self.ActionFired:connect(Function) end function BindableAction:UnbindFunction(Name) --- Binds a function from the action assert(self.BoundFunctionMaid[Name], "Bound function does not exist") self.BoundFunctionMaid[Name] = nil end function BindableAction:FireBound(ActionName, UserInputState, InputObject) -- Used by the InputBind self.ActionFired:fire(ActionName, UserInputState, InputObject) end function BindableAction:Bind() assert(not self:IsBound(), "Already bound") self.IsBoundState = true ContextActionService:BindActionToInputTypes( self.ActionName or error("No action name"), function(...) self.ActionFired:fire(...) end, self.CreateTouchButton, unpack(self.InputTypes) ) if self.CreateTouchButton then if self.ButtonTitle then ContextActionService:SetTitle(self.ActionName, self.ButtonTitle) end if self.ButtonImage then ContextActionService:SetImage(self.ActionName, self.ButtonImage) end end if self.InternalDescription then ContextActionService:SetDescription(self.ActionName, self.InternalDescription) end self.Bound:fire() end function BindableAction:Unbind() --- Unbinds the action from ContextActionService. Should be done to ensure GC. assert(self:IsBound(), "Already unbound") self.IsBoundState = false ContextActionService:UnbindAction(self.ActionName) self.Unbound:fire() end return BindableAction
local ReplicatedStorage = game:GetService("ReplicatedStorage") local ContextActionService = game:GetService("ContextActionService") local NevermoreEngine = require(ReplicatedStorage:WaitForChild("NevermoreEngine")) local LoadCustomLibrary = NevermoreEngine.LoadLibrary local Signal = LoadCustomLibrary("Signal") local MakeMaid = LoadCustomLibrary("Maid").MakeMaid --- Translates the ContextActionService binding into an OOP object with event-based properties. -- @author Quenty local BindableAction = {} BindableAction.ClassName = "BindableAction" BindableAction.__index = BindableAction function BindableAction.new(ActionName, InputTypes) local self = {} setmetatable(self, BindableAction) -- DATA self.ActionName = ActionName or error("[BindableAction] - Need ActionName") self.InputTypes = InputTypes or error("[BindableAction] - Need InputTypes") self.ButtonTitle = ActionName self.CreateTouchButton = false -- PRIVATE self.IsBoundState = false -- EVENTS self.BoundFunctionMaid = MakeMaid() self.ActionFired = Signal.new() -- Fires upon action fired. Suggested that you use :BindFunction(Name, Function) instead. self.Bound = Signal.new() -- Fires upon bind self.Unbound = Signal.new() -- Firse upon unbind return self end function BindableAction.FromData(Data) --- Construct from table --[[ Data = { ActionName = "Start_Flying"; FunctionToBind = function(ActionName, UserInputState, InputObject) -- Use UserInputState to determine whether the input is beginning or endnig end; CreateTouchButton = false; [ButtonTitle] = "Fly"; [ButtonImage] = "rbxassetid://137511721"; [InternalDescription] = "Start flying"; InputTypes = {Enum.UserInputType.Accelerometer, Enum.KeyCode.E, Enum.KeyCode.F}; } --]] local New = BindableAction.new(Data.ActionName or error("No ActionName"), Data.InputTypes or error("NO InputTypes")) if Data.CreateTouchButton ~= nil then New:SetCreateTouchButton(Data.CreateTouchButton) end -- BUTTON if Data.ButtonTitle then New:SetButtonTitle(Data.ButtonTitle) end if Data.ButtonImage then New:SetButtonImage(Data.ButtonImage) end -- DESCRIPTION if Data.InternalDescription then New:SetInternalDescription(Data.InternalDescription) end -- FUNCTION if type(Data.FunctionToBind) == "function" then New:BindFunction("Primary", Data.FunctionToBind) elseif type(Data.FunctionToBind) == "table" then for Name, Function in pairs(Data.FunctionToBind) do New:BindFunction(Name, Function) end end return New end function BindableAction:SetCreateTouchButton(DoCreateTouchButton) -- @param DoCreateTouchButton Boolean, should the action create a touch button -- Will not change until rebound. assert(type(DoCreateTouchButton) == "boolean", "DoCreateTouchButton must be a boolean") self.CreateTouchButton = DoCreateTouchButton end function BindableAction:GetInputTypes() return self.InputTypes end function BindableAction:IsBound() -- @return Boolean, true if the action is bound return self.IsBoundState end function BindableAction:GetName() -- @return The action's name return self.ActionName end function BindableAction:SetButtonTitle(ButtonTitle) assert(type(ButtonTitle) == "string", "ButtonTitle must be a string") self.ButtonTitle = ButtonTitle if self:IsBound() then ContextActionService:SetTitle(self.ActionName, self.ButtonTitle) end end function BindableAction:SetButtonImage(ButtonImage) assert(type(ButtonImage) == "string", "ButtonImage must be a string") self.ButtonImage = ButtonImage if self:IsBound() then ContextActionService:SetImage(self.ActionName, self.ButtonImage) end end function BindableAction:SetInternalDescription(Description) --- Sets the internal description self.InternalDescription = Description if self:IsBound() then ContextActionService:SetDescription(self.ActionName, self.InternalDescription) end end function BindableAction:BindFunction(Name, Function) ---Binds the to the BindableAction's FireBound event. :) -- Did some tests. When the BindableAction is GCed, this will also GC the signal and method. So Maid:DoCleaning() need not be called -- to finalize GC even with anonymous functions. assert(type(Name) == "string", "Name must be a string") assert(type(Function) == "function", "Function must be a function") self.BoundFunctionMaid[Name] = self.ActionFired:connect(Function) end function BindableAction:UnbindFunction(Name) --- Binds a function from the action assert(self.BoundFunctionMaid[Name], "Bound function does not exist") self.BoundFunctionMaid[Name] = nil end function BindableAction:FireBound(ActionName, UserInputState, InputObject) -- Used by the InputBind self.ActionFired:fire(ActionName, UserInputState, InputObject) end function BindableAction:Bind() assert(not self:IsBound(), "Already bound") self.IsBoundState = true ContextActionService:BindActionToInputTypes( self.ActionName or error("No action name"), function(...) self.ActionFired:fire(...) end, self.CreateTouchButton, unpack(self.InputTypes) ) if self.CreateTouchButton then if self.ButtonTitle then ContextActionService:SetTitle(self.ActionName, self.ButtonTitle) end if self.ButtonImage then ContextActionService:SetImage(self.ActionName, self.ButtonImage) end end if self.InternalDescription then ContextActionService:SetDescription(self.ActionName, self.InternalDescription) end self.Bound:fire() end function BindableAction:Unbind() --- Unbinds the action from ContextActionService. Should be done to ensure GC. assert(self:IsBound(), "Already unbound") self.IsBoundState = false ContextActionService:UnbindAction(self.ActionName) self.Unbound:fire() end return BindableAction
Bug assertion
Bug assertion
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
8973cdb063ff644b475c75dc35cc63743f97b754
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) 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, handler) 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 --FIXME: All iq's must be replied to, here we should return service-unavailable I think 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]= 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;
Small fixes
Small fixes
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
92fe2d12d682a664856bbf9a1374f07db5a9c8d0
libs/web/luasrc/config.lua
libs/web/luasrc/config.lua
--[[ LuCI - Configuration Description: Some LuCI configuration values read from uci file "luci" FileId: $Id$ License: Copyright 2008 Steven Barth <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- local util = require "luci.util" local pcall = pcall local require = require module "luci.config" pcall(function() setmetatable(_M, {__index=require "luci.model.uci".cursor():get_all("luci")}) end)
--[[ LuCI - Configuration Description: Some LuCI configuration values read from uci file "luci" FileId: $Id$ License: Copyright 2008 Steven Barth <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- module("luci.config", function(m) if pcall(require, "luci.model.uci") then setmetatable(m, {__index = luci.model.uci.cursor():get_all("luci")}) end end)
Fixed luci.config
Fixed luci.config git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@3127 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
Canaan-Creative/luci,8devices/carambola2-luci,dtaht/cerowrt-luci-3.3,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,alxhh/piratenluci,Flexibity/luci,freifunk-gluon/luci,dtaht/cerowrt-luci-3.3,Flexibity/luci,8devices/carambola2-luci,8devices/carambola2-luci,stephank/luci,eugenesan/openwrt-luci,projectbismark/luci-bismark,ThingMesh/openwrt-luci,Canaan-Creative/luci,yeewang/openwrt-luci,ch3n2k/luci,zwhfly/openwrt-luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,phi-psi/luci,gwlim/luci,vhpham80/luci,ThingMesh/openwrt-luci,stephank/luci,vhpham80/luci,yeewang/openwrt-luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,8devices/carambola2-luci,ch3n2k/luci,dtaht/cerowrt-luci-3.3,Flexibity/luci,8devices/carambola2-luci,jschmidlapp/luci,stephank/luci,ch3n2k/luci,stephank/luci,Canaan-Creative/luci,jschmidlapp/luci,ThingMesh/openwrt-luci,projectbismark/luci-bismark,Flexibity/luci,Canaan-Creative/luci,alxhh/piratenluci,8devices/carambola2-luci,alxhh/piratenluci,eugenesan/openwrt-luci,eugenesan/openwrt-luci,jschmidlapp/luci,Canaan-Creative/luci,stephank/luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,Flexibity/luci,saraedum/luci-packages-old,gwlim/luci,zwhfly/openwrt-luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,gwlim/luci,alxhh/piratenluci,saraedum/luci-packages-old,zwhfly/openwrt-luci,vhpham80/luci,Canaan-Creative/luci,projectbismark/luci-bismark,ThingMesh/openwrt-luci,phi-psi/luci,ThingMesh/openwrt-luci,alxhh/piratenluci,yeewang/openwrt-luci,Flexibity/luci,zwhfly/openwrt-luci,Canaan-Creative/luci,gwlim/luci,yeewang/openwrt-luci,phi-psi/luci,Canaan-Creative/luci,ch3n2k/luci,ch3n2k/luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,jschmidlapp/luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,eugenesan/openwrt-luci,projectbismark/luci-bismark,freifunk-gluon/luci,alxhh/piratenluci,eugenesan/openwrt-luci,eugenesan/openwrt-luci,projectbismark/luci-bismark,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,vhpham80/luci,zwhfly/openwrt-luci,Flexibity/luci,projectbismark/luci-bismark,projectbismark/luci-bismark,freifunk-gluon/luci,zwhfly/openwrt-luci,Flexibity/luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,stephank/luci,zwhfly/openwrt-luci,alxhh/piratenluci,jschmidlapp/luci,saraedum/luci-packages-old,vhpham80/luci,gwlim/luci,zwhfly/openwrt-luci,gwlim/luci,saraedum/luci-packages-old,phi-psi/luci,dtaht/cerowrt-luci-3.3,gwlim/luci,phi-psi/luci,vhpham80/luci,phi-psi/luci,saraedum/luci-packages-old,zwhfly/openwrt-luci,yeewang/openwrt-luci,projectbismark/luci-bismark,phi-psi/luci,dtaht/cerowrt-luci-3.3,dtaht/cerowrt-luci-3.3,ch3n2k/luci,jschmidlapp/luci
f5ebb194dd950a045b7f2438c714a05601b7491b
mod/mpi/config/scripts/slideshow.lua
mod/mpi/config/scripts/slideshow.lua
local on = false local expected_playlist_pos = 0 local timer = nil local slideshow_sleep = mp.get_opt('slideshow-duration') if slideshow_sleep == nil then slideshow_sleep = 0.3 end function get_playlist_pos() return mp.get_property_number('playlist-pos') + 1 end function get_playlist_count() return mp.get_property_number('playlist-count') end function queue_next_slide() local next_slide = function() if (get_playlist_pos() == get_playlist_count()) or (get_playlist_pos() ~= expected_playlist_pos) then stop_slideshow() else mp.command('playlist_next') end end if timer then timer:kill() end timer = mp.add_timeout(slideshow_sleep, next_slide) end function start_slideshow() if get_playlist_pos() == get_playlist_count() then mp.osd_message('Can\'t start slideshow on last file') return end mp.osd_message('Slideshow started') on = true queue_next_slide() expected_playlist_pos = get_playlist_pos() end function stop_slideshow() if not on then return end mp.osd_message('Slideshow stopped') on = false timer:kill() end function toggle_slideshow() if on then stop_slideshow() else start_slideshow() end end function increase_slideshow_speed() slideshow_sleep = slideshow_sleep + 0.1 mp.osd_message('Slideshow speed: ' .. slideshow_sleep) end function decrease_slideshow_speed() slideshow_sleep = slideshow_sleep - 0.1 if slideshow_sleep < 0.1 then slideshow_sleep = 0.1 end mp.osd_message('Slideshow speed: ' .. slideshow_sleep) end function file_loaded() if on then expected_playlist_pos = expected_playlist_pos + 1 queue_next_slide() end end mp.register_event('file-loaded', file_loaded) mp.register_script_message('toggle-slideshow', toggle_slideshow) mp.register_script_message('decrease-speed', decrease_slideshow_speed) mp.register_script_message('increase-speed', increase_slideshow_speed)
local on = false local timer = nil local slideshow_sleep = mp.get_opt('slideshow-duration') local jump_from_slideshow = false if slideshow_sleep == nil then slideshow_sleep = 0.3 end function get_playlist_pos() return mp.get_property_number('playlist-pos') + 1 end function get_playlist_count() return mp.get_property_number('playlist-count') end function queue_next_slide() local next_slide = function() if (get_playlist_pos() == get_playlist_count()) then stop_slideshow() else jump_from_slideshow = true mp.command('playlist_next') end end if timer then timer:kill() end timer = mp.add_timeout(slideshow_sleep, next_slide) end function start_slideshow() if get_playlist_pos() == get_playlist_count() then mp.osd_message('Can\'t start slideshow on last file') return end mp.osd_message('Slideshow started') on = true jump_from_slideshow = true mp.command('playlist_next') end function stop_slideshow() if not on then return end mp.osd_message('Slideshow stopped') on = false jump_from_slideshow = false timer:kill() end function toggle_slideshow() if on then stop_slideshow() else start_slideshow() end end function increase_slideshow_speed() slideshow_sleep = slideshow_sleep + 0.1 mp.osd_message('Slideshow speed: ' .. slideshow_sleep) end function decrease_slideshow_speed() slideshow_sleep = slideshow_sleep - 0.1 if slideshow_sleep < 0.1 then slideshow_sleep = 0.1 end mp.osd_message('Slideshow speed: ' .. slideshow_sleep) end function file_loaded() if on then if jump_from_slideshow then jump_from_slideshow = false queue_next_slide() else stop_slideshow() end end end mp.register_event('file-loaded', file_loaded) mp.register_script_message('toggle-slideshow', toggle_slideshow) mp.register_script_message('decrease-speed', decrease_slideshow_speed) mp.register_script_message('increase-speed', increase_slideshow_speed)
mod/mpi: improve slideshow stopping
mod/mpi: improve slideshow stopping The prior approach to stopping the slideshow was unreliable (e.g. manually jumping to another file didn't always stop the slideshow.) While this commit doesn't fix the problem completely, it significantly reduces race chances. Additionally, it removes the delay between slideshow start and moving to the first next file.
Lua
mit
rr-/dotfiles,rr-/dotfiles,rr-/dotfiles
b00e080e976499171c0e7423efd0efb995e07526
editor/lib/lua/editor/edit/EditorCanvasScene.lua
editor/lib/lua/editor/edit/EditorCanvasScene.lua
local Scene = require("scenes.Scene") local InputDevice = require("input.InputDevice") local JUI = require("ui.JUI") local UIScreen = require("ui.UIScreen") local UICanvas = require("ui.UICanvas") local UIPanel = require("ui.UIPanel") --------------------------------------------------------------------------------- -- -- @type EditorCanvasScene -- --------------------------------------------------------------------------------- local EditorCanvasScene = Class( Scene, "EditorCanvasScene" ) function EditorCanvasScene:init( option ) self.EDITOR_TYPE = "scene" Scene.init(self, option) end function EditorCanvasScene:getRootGroup() if self.EDITOR_TYPE == "ui" then return self.jui._activeScreens[1] end return self.rootGroup end function EditorCanvasScene:setRootGroup( group ) if self.EDITOR_TYPE == "ui" then -- self.rootUI:removeChildren() -- self.rootUI:addChild( group ) -- self.rootUI.panel = group -- group.parent = nil return end Scene.setRootGroup( self, group ) end function EditorCanvasScene:setEnv( env ) self.env = env self.contextName = env.contextName end function EditorCanvasScene:getEnv() return self.env end function EditorCanvasScene:getContextName() return self.contextName end function EditorCanvasScene:getCanvasSize() local s = self.env.getCanvasSize() return s[0], s[1] end function EditorCanvasScene:hideCursor() return self.env.hideCursor() end function EditorCanvasScene:setCursor( id ) return self.env.setCursor( id ) end function EditorCanvasScene:showCursor() return self.env.showCursor() end function EditorCanvasScene:setCursorPos( x, y ) return self.env.setCursorPos( x, y ) end function EditorCanvasScene:startUpdateTimer( fps ) return self.env.startUpdateTimer( fps ) end function EditorCanvasScene:stopUpdateTimer() return self.env.stopUpdateTimer() end --------------------------------------------------------------------------------- -- -- @type create methods -- --------------------------------------------------------------------------------- function createEditorCanvasInputDevice( env ) local env = env or getfenv(2) local inputDevice = InputDevice( assert(env.contextName), env ) function env.onMouseDown( btn, x, y ) inputDevice:sendMouseEvent( 'down', x, y, btn ) end function env.onMouseUp( btn, x, y ) inputDevice:sendMouseEvent( 'up', x, y, btn ) end function env.onMouseMove( x, y ) inputDevice:sendMouseEvent( 'move', x, y, false ) end function env.onMouseScroll( dx, dy, x, y ) inputDevice:sendMouseEvent( 'scroll', dx, dy, false ) end function env.onMouseEnter() inputDevice:sendMouseEvent( 'enter' ) end function env.onMouseLeave() inputDevice:sendMouseEvent( 'leave' ) end function env.onKeyDown( key ) inputDevice:sendKeyEvent( key, true ) end function env.onKeyUp( key ) inputDevice:sendKeyEvent( key, false ) end env._delegate:updateHooks() return inputDevice end --------------------------------------------------------------------- function createEditorCanvasScene( stype ) stype = stype or "layout" local env = getfenv( 2 ) local viewport = MOAIViewport.new() local scene = EditorCanvasScene( { viewport = viewport } ) scene.EDITOR_TYPE = stype scene:setEnv( env ) if stype == "ui" then local jui = JUI() jui:setSize( 320, 480 ) scene.jui = jui table.insert( scene.renderTable, jui._renderables ) local screen = UIScreen( { viewport = viewport } ) jui:internalOpenScreen( screen ) -- scene.rootUI = UICanvas() -- scene:addLayer( "ui", scene.rootUI.layers ) -- scene.rootUI:setSize( 320, 480 ) -- local panel = scene.rootUI:addChild( UIPanel() ) -- scene.rootUI.panel = panel -- panel.parent = nil end -- FIXME -- function env.onResize( w, h ) -- scene:resize( w, h ) -- -- scene.cameraCom:setScreenSize( w, h ) -- end function env.onLoad() end local inputDevice = createEditorCanvasInputDevice( env ) scene.inputDevice = inputDevice -- function env.EditorInputScript() -- return mock.InputScript{ device = inputDevice } -- end return scene end
local Scene = require("scenes.Scene") local InputDevice = require("input.InputDevice") local JUI = require("ui.JUI") local UIScreen = require("ui.UIScreen") --------------------------------------------------------------------------------- -- -- @type EditorCanvasScene -- --------------------------------------------------------------------------------- local EditorCanvasScene = Class( Scene, "EditorCanvasScene" ) function EditorCanvasScene:init( option ) self.EDITOR_TYPE = "scene" Scene.init(self, option) end function EditorCanvasScene:getRootGroup() if self.EDITOR_TYPE == "ui" then return self.jui._activeScreens[1] end return self.rootGroup end function EditorCanvasScene:setRootGroup( group ) if self.EDITOR_TYPE == "ui" then -- FIXME -- self.rootUI:removeChildren() -- self.rootUI:addChild( group ) -- self.rootUI.panel = group -- group.parent = nil return end Scene.setRootGroup( self, group ) end function EditorCanvasScene:setEnv( env ) self.env = env self.contextName = env.contextName end function EditorCanvasScene:getEnv() return self.env end function EditorCanvasScene:getContextName() return self.contextName end function EditorCanvasScene:getCanvasSize() local s = self.env.getCanvasSize() return s[0], s[1] end function EditorCanvasScene:hideCursor() return self.env.hideCursor() end function EditorCanvasScene:setCursor( id ) return self.env.setCursor( id ) end function EditorCanvasScene:showCursor() return self.env.showCursor() end function EditorCanvasScene:setCursorPos( x, y ) return self.env.setCursorPos( x, y ) end function EditorCanvasScene:startUpdateTimer( fps ) return self.env.startUpdateTimer( fps ) end function EditorCanvasScene:stopUpdateTimer() return self.env.stopUpdateTimer() end --------------------------------------------------------------------------------- -- -- @type create methods -- --------------------------------------------------------------------------------- function createEditorCanvasInputDevice( env ) local env = env or getfenv(2) local inputDevice = InputDevice( assert(env.contextName), env ) function env.onMouseDown( btn, x, y ) inputDevice:sendMouseEvent( 'down', x, y, btn ) end function env.onMouseUp( btn, x, y ) inputDevice:sendMouseEvent( 'up', x, y, btn ) end function env.onMouseMove( x, y ) inputDevice:sendMouseEvent( 'move', x, y, false ) end function env.onMouseScroll( dx, dy, x, y ) inputDevice:sendMouseEvent( 'scroll', dx, dy, false ) end function env.onMouseEnter() inputDevice:sendMouseEvent( 'enter' ) end function env.onMouseLeave() inputDevice:sendMouseEvent( 'leave' ) end function env.onKeyDown( key ) inputDevice:sendKeyEvent( key, true ) end function env.onKeyUp( key ) inputDevice:sendKeyEvent( key, false ) end env._delegate:updateHooks() return inputDevice end --------------------------------------------------------------------- function createEditorCanvasScene( stype ) stype = stype or "layout" local env = getfenv( 2 ) local viewport = MOAIViewport.new() local scene = EditorCanvasScene( { viewport = viewport } ) scene.EDITOR_TYPE = stype scene:setEnv( env ) if stype == "ui" then local jui = JUI() jui:setSize( 320, 480 ) scene.jui = jui table.insert( scene.renderTable, jui._renderables ) local screen = UIScreen( { viewport = viewport } ) jui:internalOpenScreen( screen ) end -- FIXME -- function env.onResize( w, h ) -- scene:resize( w, h ) -- -- scene.cameraCom:setScreenSize( w, h ) -- end function env.onLoad() end local inputDevice = createEditorCanvasInputDevice( env ) scene.inputDevice = inputDevice -- function env.EditorInputScript() -- return mock.InputScript{ device = inputDevice } -- end return scene end
fix editor scene
fix editor scene
Lua
mit
RazielSun/juma-editor,RazielSun/juma-editor,cloudteampro/juma-editor,cloudteampro/juma-editor,RazielSun/juma-editor,cloudteampro/juma-editor,RazielSun/juma-editor,cloudteampro/juma-editor
c0294da8f398f606db2d03bd72e3bc619a86bd2c
scripts/lua/policies/backendRouting.lua
scripts/lua/policies/backendRouting.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. -- --- @module backendRouting -- Used to set the backend Url either statically or dynamically local url = require "url" local utils = require "lib/utils" local request = require "lib/request" local logger = require "lib/logger" local _M = {} --- Set upstream based on the backendUrl function _M.setRoute(backendUrl, gatewayPath) local u = url.parse(backendUrl) if u.scheme == nil then u = url.parse(utils.concatStrings({'http://', backendUrl})) end -- pass down gateway path to upstream path if $(request.path) is specified at the end of backendUrl if u.path:sub(-15) == '$(request.path)' then u.path = utils.concatStrings({u.path:sub(1, -16), u.path:sub(-16, -16) == '/' and '' or '/', gatewayPath}) ngx.req.set_uri(u.path) else ngx.req.set_uri(getUriPath(u.path)) end ngx.var.backendUrl = backendUrl setUpstream(u) end --- Set dynamic route based on the header that is passed in function _M.setDynamicRoute(obj) local whitelist = obj.whitelist for k in pairs(whitelist) do whitelist[k] = whitelist[k]:lower() end local header = obj.header ~= nil and obj.header or 'X-Cf-Forwarded-Url' local dynamicBackend = ngx.req.get_headers()[header] if dynamicBackend ~= nil and dynamicBackend ~= '' then local u = url.parse(dynamicBackend) if u.scheme == nil or u.scheme == '' then u = url.parse(utils.concatStrings({'http://', dynamicBackend})) end if utils.tableContains(whitelist, u.host) then ngx.req.set_uri(getUriPath(u.path)) local query = ngx.req.get_uri_args() for k, v in pairs(u.query) do query[k] = v end ngx.req.set_uri_args(query) setUpstream(u) else request.err(403, 'Dynamic backend host not part of whitelist.') end else logger.info('Header for dynamic routing not found. Defaulting to backendUrl.') end end function getUriPath(backendPath) local gatewayPath = ngx.unescape_uri(ngx.var.gatewayPath) gatewayPath = gatewayPath:gsub('-', '%%-') local uri = string.gsub(ngx.var.request_uri, '?.*', '') local _, j = uri:find(gatewayPath) local incomingPath = ((j and uri:sub(j + 1)) or nil) -- Check for backendUrl path if backendPath == nil or backendPath == '' or backendPath == '/' then incomingPath = (incomingPath and incomingPath ~= '') and incomingPath or '/' incomingPath = string.sub(incomingPath, 1, 1) == '/' and incomingPath or utils.concatStrings({'/', incomingPath}) return incomingPath else return utils.concatStrings({backendPath, incomingPath}) end end function setUpstream(u) local upstream = utils.concatStrings({u.scheme, '://', u.host}) if u.port ~= nil and u.port ~= '' then upstream = utils.concatStrings({upstream, ':', u.port}) end ngx.var.upstream = upstream end return _M
-- -- 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. -- --- @module backendRouting -- Used to set the backend Url either statically or dynamically local url = require "url" local utils = require "lib/utils" local request = require "lib/request" local logger = require "lib/logger" local _M = {} --- Set upstream based on the backendUrl function _M.setRoute(backendUrl, gatewayPath) local u = url.parse(backendUrl) if u.scheme == nil then u = url.parse(utils.concatStrings({'http://', backendUrl})) end -- pass down gateway path to upstream path if $(request.path) is specified at the end of backendUrl if u.path:sub(-15) == '$(request.path)' then u.path = utils.concatStrings({u.path:sub(1, -16), u.path:sub(-16, -16) == '/' and '' or '/', gatewayPath}) ngx.req.set_uri(u.path) else ngx.req.set_uri(getUriPath(u.path)) end ngx.var.backendUrl = backendUrl setUpstream(u) end --- Set dynamic route based on the header that is passed in function _M.setDynamicRoute(obj) local whitelist = obj.whitelist for k in pairs(whitelist) do whitelist[k] = whitelist[k]:lower() end local header = obj.header ~= nil and obj.header or 'X-Cf-Forwarded-Url' local dynamicBackend = ngx.req.get_headers()[header] if dynamicBackend ~= nil and dynamicBackend ~= '' then local u = url.parse(dynamicBackend) if u.scheme == nil or u.scheme == '' then u = url.parse(utils.concatStrings({'http://', dynamicBackend})) end if utils.tableContains(whitelist, u.host) then ngx.req.set_uri(getUriPath(u.path)) -- Split the dynamicBackend url to get the query parameters in the exact order that it was passed in. -- Don't use u.query here because it returns the parameters in an unordered lua table. local split = {string.match(dynamicBackend, '([^?]*)?(.*)')} local qs = split[2] if qs ~= nil then ngx.req.set_uri_args(qs) end setUpstream(u) else request.err(403, 'Dynamic backend host not part of whitelist.') end else logger.info('Header for dynamic routing not found. Defaulting to backendUrl.') end end function getUriPath(backendPath) local gatewayPath = ngx.unescape_uri(ngx.var.gatewayPath) gatewayPath = gatewayPath:gsub('-', '%%-') local uri = string.gsub(ngx.var.request_uri, '?.*', '') local _, j = uri:find(gatewayPath) local incomingPath = ((j and uri:sub(j + 1)) or nil) -- Check for backendUrl path if backendPath == nil or backendPath == '' or backendPath == '/' then incomingPath = (incomingPath and incomingPath ~= '') and incomingPath or '/' incomingPath = string.sub(incomingPath, 1, 1) == '/' and incomingPath or utils.concatStrings({'/', incomingPath}) return incomingPath else return utils.concatStrings({backendPath, incomingPath}) end end function setUpstream(u) local upstream = utils.concatStrings({u.scheme, '://', u.host}) if u.port ~= nil and u.port ~= '' then upstream = utils.concatStrings({upstream, ':', u.port}) end ngx.var.upstream = upstream end return _M
Fix multiple query parameter issue for dynamic backends (#270)
Fix multiple query parameter issue for dynamic backends (#270)
Lua
unknown
alexsong93/openwhisk-apigateway,openwhisk/openwhisk-apigateway,alexsong93/openwhisk-apigateway,openwhisk/apigateway,openwhisk/openwhisk-apigateway,openwhisk/apigateway,openwhisk/openwhisk-apigateway,alexsong93/openwhisk-apigateway,openwhisk/apigateway
364c271a84210a841762beeb2dd0715cd7c2e240
modules/luci-mod-rpc/luasrc/controller/rpc.lua
modules/luci-mod-rpc/luasrc/controller/rpc.lua
-- Copyright 2008 Steven Barth <[email protected]> -- Copyright 2008 Jo-Philipp Wich <[email protected]> -- Licensed to the public under the Apache License 2.0. module("luci.controller.rpc", package.seeall) function session_retrieve(sid, allowed_users) local util = require "luci.util" local sdat = util.ubus("session", "get", { ubus_rpc_session = sid }) if type(sdat) == "table" and type(sdat.values) == "table" and type(sdat.values.token) == "string" and type(sdat.values.secret) == "string" and type(sdat.values.username) == "string" and util.contains(allowed_users, sdat.values.username) then return sid, sdat.values end return nil end function authenticator(validator, accs) local http = require "luci.http" local ctrl = require "luci.controller.rpc" local auth = http.formvalue("auth", true) or http.getcookie("sysauth") if auth then -- if authentication token was given local sid, sdat = ctrl.session_retrieve(auth, accs) if sdat then -- if given token is valid return sdat.username, sid end http.status(403, "Forbidden") end end function index() local ctrl = require "luci.controller.rpc" local rpc = node("rpc") rpc.sysauth = "root" rpc.sysauth_authenticator = ctrl.authenticator rpc.notemplate = true entry({"rpc", "uci"}, call("rpc_uci")) entry({"rpc", "fs"}, call("rpc_fs")) entry({"rpc", "sys"}, call("rpc_sys")) entry({"rpc", "ipkg"}, call("rpc_ipkg")) entry({"rpc", "ip"}, call("rpc_ip")) entry({"rpc", "auth"}, call("rpc_auth")).sysauth = false end function rpc_auth() local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local sys = require "luci.sys" local ltn12 = require "luci.ltn12" local util = require "luci.util" local server = {} server.challenge = function(user, pass) local config = require "luci.config" local login = util.ubus("session", "login", { username = user, password = pass, timeout = tonumber(config.sauth.sessiontime) }) if type(login) == "table" and type(login.ubus_rpc_session) == "string" then util.ubus("session", "set", { ubus_rpc_session = login.ubus_rpc_session, values = { token = sys.uniqueid(16), secret = sys.uniqueid(16) } }) local sid, sdat = ctrl.session_retrieve(login.ubus_rpc_session, { user }) if sdat then return { sid = sid, token = sdat.token, secret = sdat.secret } end end return nil end server.login = function(...) local challenge = server.challenge(...) if challenge then http.header("Set-Cookie", 'sysauth=%s; path=%s' %{ challenge.sid, http.getenv("SCRIPT_NAME") }) return challenge.sid end end http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(server, http.source()), http.write) end function rpc_uci() if not pcall(require, "luci.model.uci") then luci.http.status(404, "Not Found") return nil end local uci = require "luci.jsonrpcbind.uci" local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(uci, http.source()), http.write) end function rpc_fs() local util = require "luci.util" local io = require "io" local fs2 = util.clone(require "nixio.fs") local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" function fs2.readfile(filename) local stat, mime = pcall(require, "mime") if not stat then error("Base64 support not available. Please install LuaSocket.") end local fp = io.open(filename) if not fp then return nil end local output = {} local sink = ltn12.sink.table(output) local source = ltn12.source.chain(ltn12.source.file(fp), mime.encode("base64")) return ltn12.pump.all(source, sink) and table.concat(output) end function fs2.writefile(filename, data) local stat, mime = pcall(require, "mime") if not stat then error("Base64 support not available. Please install LuaSocket.") end local file = io.open(filename, "w") local sink = file and ltn12.sink.chain(mime.decode("base64"), ltn12.sink.file(file)) return sink and ltn12.pump.all(ltn12.source.string(data), sink) or false end http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(fs2, http.source()), http.write) end function rpc_sys() local util = require "luci.util" local sys = require "luci.sys" local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" local sys2 = util.clone(sys) sys2.net = util.clone(sys.net) sys2.wifi = util.clone(sys.wifi) function sys2.wifi.getiwinfo(ifname, operation) local iw = sys.wifi.getiwinfo(ifname) if iw then if operation then assert(type(iwinfo[iw.type][operation]) == "function") return iw[operation] end local n, f local rv = { ifname = ifname } for n, f in pairs(iwinfo[iw.type]) do if type(f) == "function" and n ~= "scanlist" and n ~= "countrylist" then rv[n] = iw[n] end end return rv end return nil end http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(sys2, http.source()), http.write) end function rpc_ipkg() if not pcall(require, "luci.model.ipkg") then luci.http.status(404, "Not Found") return nil end local ipkg = require "luci.model.ipkg" local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(ipkg, http.source()), http.write) end function rpc_ip() if not pcall(require, "luci.ip") then luci.http.status(404, "Not Found") return nil end local util = require "luci.util" local ip = require "luci.ip" local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" local ip2 = util.clone(ip) local _, n for _, n in ipairs({ "new", "IPv4", "IPv6", "MAC" }) do ip2[n] = function(address, netmask, operation, argument) local cidr = ip[n](address, netmask) if cidr and operation then assert(type(cidr[operation]) == "function") local cidr2 = cidr[operation](cidr, argument) return (type(cidr2) == "userdata") and cidr2:string() or cidr2 end return (type(cidr) == "userdata") and cidr:string() or cidr end end http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(ip2, http.source()), http.write) end
-- Copyright 2008 Steven Barth <[email protected]> -- Copyright 2008 Jo-Philipp Wich <[email protected]> -- Licensed to the public under the Apache License 2.0. module("luci.controller.rpc", package.seeall) function session_retrieve(sid, allowed_users) local util = require "luci.util" local sdat = util.ubus("session", "get", { ubus_rpc_session = sid }) if type(sdat) == "table" and type(sdat.values) == "table" and type(sdat.values.token) == "string" and type(sdat.values.secret) == "string" and type(sdat.values.username) == "string" and util.contains(allowed_users, sdat.values.username) then return sid, sdat.values end return nil end function authenticator(validator, accs) local http = require "luci.http" local ctrl = require "luci.controller.rpc" local auth = http.formvalue("auth", true) or http.getcookie("sysauth") if auth then -- if authentication token was given local sid, sdat = ctrl.session_retrieve(auth, accs) if sdat then -- if given token is valid return sdat.username, sid end http.status(403, "Forbidden") end end function index() local ctrl = require "luci.controller.rpc" local rpc = node("rpc") rpc.sysauth = "root" rpc.sysauth_authenticator = ctrl.authenticator rpc.notemplate = true entry({"rpc", "uci"}, call("rpc_uci")) entry({"rpc", "fs"}, call("rpc_fs")) entry({"rpc", "sys"}, call("rpc_sys")) entry({"rpc", "ipkg"}, call("rpc_ipkg")) entry({"rpc", "ip"}, call("rpc_ip")) entry({"rpc", "auth"}, call("rpc_auth")).sysauth = false end function rpc_auth() local ctrl = require "luci.controller.rpc" local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local sys = require "luci.sys" local ltn12 = require "luci.ltn12" local util = require "luci.util" local server = {} server.challenge = function(user, pass) local config = require "luci.config" local login = util.ubus("session", "login", { username = user, password = pass, timeout = tonumber(config.sauth.sessiontime) }) if type(login) == "table" and type(login.ubus_rpc_session) == "string" then util.ubus("session", "set", { ubus_rpc_session = login.ubus_rpc_session, values = { token = sys.uniqueid(16), secret = sys.uniqueid(16) } }) local sid, sdat = ctrl.session_retrieve(login.ubus_rpc_session, { user }) if sdat then return { sid = sid, token = sdat.token, secret = sdat.secret } end end return nil end server.login = function(...) local challenge = server.challenge(...) if challenge then http.header("Set-Cookie", 'sysauth=%s; path=%s' %{ challenge.sid, http.getenv("SCRIPT_NAME") }) return challenge.sid end end http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(server, http.source()), http.write) end function rpc_uci() if not pcall(require, "luci.model.uci") then luci.http.status(404, "Not Found") return nil end local uci = require "luci.jsonrpcbind.uci" local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(uci, http.source()), http.write) end function rpc_fs() local util = require "luci.util" local io = require "io" local fs2 = util.clone(require "nixio.fs") local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" function fs2.readfile(filename) local stat, mime = pcall(require, "mime") if not stat then error("Base64 support not available. Please install LuaSocket.") end local fp = io.open(filename) if not fp then return nil end local output = {} local sink = ltn12.sink.table(output) local source = ltn12.source.chain(ltn12.source.file(fp), mime.encode("base64")) return ltn12.pump.all(source, sink) and table.concat(output) end function fs2.writefile(filename, data) local stat, mime = pcall(require, "mime") if not stat then error("Base64 support not available. Please install LuaSocket.") end local file = io.open(filename, "w") local sink = file and ltn12.sink.chain(mime.decode("base64"), ltn12.sink.file(file)) return sink and ltn12.pump.all(ltn12.source.string(data), sink) or false end http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(fs2, http.source()), http.write) end function rpc_sys() local util = require "luci.util" local sys = require "luci.sys" local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" local sys2 = util.clone(sys) sys2.net = util.clone(sys.net) sys2.wifi = util.clone(sys.wifi) function sys2.wifi.getiwinfo(ifname, operation) local iw = sys.wifi.getiwinfo(ifname) if iw then if operation then assert(type(iwinfo[iw.type][operation]) == "function") return iw[operation] end local n, f local rv = { ifname = ifname } for n, f in pairs(iwinfo[iw.type]) do if type(f) == "function" and n ~= "scanlist" and n ~= "countrylist" then rv[n] = iw[n] end end return rv end return nil end http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(sys2, http.source()), http.write) end function rpc_ipkg() if not pcall(require, "luci.model.ipkg") then luci.http.status(404, "Not Found") return nil end local ipkg = require "luci.model.ipkg" local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(ipkg, http.source()), http.write) end function rpc_ip() if not pcall(require, "luci.ip") then luci.http.status(404, "Not Found") return nil end local util = require "luci.util" local ip = require "luci.ip" local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" local ip2 = util.clone(ip) local _, n for _, n in ipairs({ "new", "IPv4", "IPv6", "MAC" }) do ip2[n] = function(address, netmask, operation, argument) local cidr = ip[n](address, netmask) if cidr and operation then assert(type(cidr[operation]) == "function") local cidr2 = cidr[operation](cidr, argument) return (type(cidr2) == "userdata") and cidr2:string() or cidr2 end return (type(cidr) == "userdata") and cidr:string() or cidr end end http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(ip2, http.source()), http.write) end
luci-mod-rpc: fix unresolved controller reference in rpc_auth()
luci-mod-rpc: fix unresolved controller reference in rpc_auth() Fixes the following error: .../rpc.lua:85: attempt to index global 'ctrl' (a nil value) Signed-off-by: Jo-Philipp Wich <[email protected]>
Lua
apache-2.0
kuoruan/luci,artynet/luci,chris5560/openwrt-luci,hnyman/luci,tobiaswaldvogel/luci,rogerpueyo/luci,openwrt/luci,wongsyrone/luci-1,artynet/luci,openwrt-es/openwrt-luci,artynet/luci,lbthomsen/openwrt-luci,kuoruan/luci,Noltari/luci,lbthomsen/openwrt-luci,rogerpueyo/luci,tobiaswaldvogel/luci,rogerpueyo/luci,kuoruan/lede-luci,Noltari/luci,wongsyrone/luci-1,tobiaswaldvogel/luci,openwrt-es/openwrt-luci,artynet/luci,kuoruan/luci,nmav/luci,lbthomsen/openwrt-luci,chris5560/openwrt-luci,nmav/luci,kuoruan/lede-luci,lbthomsen/openwrt-luci,chris5560/openwrt-luci,artynet/luci,kuoruan/lede-luci,openwrt-es/openwrt-luci,rogerpueyo/luci,openwrt/luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,rogerpueyo/luci,hnyman/luci,wongsyrone/luci-1,kuoruan/luci,chris5560/openwrt-luci,Noltari/luci,hnyman/luci,openwrt/luci,openwrt-es/openwrt-luci,Noltari/luci,openwrt-es/openwrt-luci,openwrt/luci,nmav/luci,artynet/luci,tobiaswaldvogel/luci,kuoruan/luci,chris5560/openwrt-luci,artynet/luci,lbthomsen/openwrt-luci,Noltari/luci,nmav/luci,openwrt/luci,openwrt/luci,openwrt-es/openwrt-luci,Noltari/luci,nmav/luci,kuoruan/lede-luci,nmav/luci,nmav/luci,Noltari/luci,wongsyrone/luci-1,kuoruan/lede-luci,hnyman/luci,kuoruan/luci,hnyman/luci,nmav/luci,rogerpueyo/luci,artynet/luci,kuoruan/lede-luci,lbthomsen/openwrt-luci,openwrt/luci,hnyman/luci,kuoruan/lede-luci,openwrt/luci,kuoruan/luci,openwrt-es/openwrt-luci,chris5560/openwrt-luci,wongsyrone/luci-1,artynet/luci,chris5560/openwrt-luci,hnyman/luci,Noltari/luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,tobiaswaldvogel/luci,wongsyrone/luci-1,wongsyrone/luci-1,kuoruan/lede-luci,openwrt-es/openwrt-luci,tobiaswaldvogel/luci,rogerpueyo/luci,rogerpueyo/luci,hnyman/luci,Noltari/luci,wongsyrone/luci-1,chris5560/openwrt-luci,kuoruan/luci,nmav/luci
a0b4f7e3b749e99ef3b3f8b86608f5e4fd131b4d
units.misc.lua
units.misc.lua
require "tundra.syntax.glob" require "tundra.path" require "tundra.util" ----------------------------------------------------------------------------------------------------------------------- -- Example 6502 emulator Program { Name = "fake6502", Env = { CPPPATH = { "api/include" }, CCOPTS = { { "-Wno-conversion", "-Wno-missing-variable-declarations", "-Werror", "-Wno-pedantic", "-Wno-conversion", "-Wno-missing-field-initializers", "-Wno-conversion", "-Wno-switch-enum", "-Wno-format-nonliteral"; Config = "macosx-*-*" }, }, }, Sources = { Glob { Dir = "examples/fake_6502", Extensions = { ".c", ".cpp", ".m" }, }, }, Libs = { { "wsock32.lib", "kernel32.lib" ; Config = { "win32-*-*", "win64-*-*" } } }, Depends = { "remote_api" }, } ----------------------------------------------------------------------------------------------------------------------- -- Crash Example Program { Name = "crashing_native", Sources = { Glob { Dir = "examples/crashing_native", Extensions = { ".c" }, }, }, } ----------------------------------------------------------------------------------------------------------------------- Program { Name = "core_tests", Env = { CPPPATH = { "api/include", "src/external/cmocka/include", "src/prodbg", }, }, Sources = { "src/prodbg/tests/core_tests.c", }, Depends = { "stb", "remote_api", "api", "core", "cmocka" }, } ----------------------------------------------------------------------------------------------------------------------- Default "fake6502" Default "crashing_native" Default "core_tests"
require "tundra.syntax.glob" require "tundra.path" require "tundra.util" ----------------------------------------------------------------------------------------------------------------------- -- Example 6502 emulator Program { Name = "fake6502", Env = { CPPPATH = { "api/include" }, CCOPTS = { { "-Wno-conversion", "-Wno-missing-variable-declarations", "-Werror", "-Wno-pedantic", "-Wno-conversion", "-Wno-missing-field-initializers", "-Wno-conversion", "-Wno-switch-enum", "-Wno-format-nonliteral"; Config = "macosx-*-*" }, }, }, Sources = { Glob { Dir = "examples/fake_6502", Extensions = { ".c", ".cpp", ".m" }, }, }, Libs = { { "wsock32.lib", "kernel32.lib" ; Config = { "win32-*-*", "win64-*-*" } } }, Depends = { "remote_api" }, } ----------------------------------------------------------------------------------------------------------------------- -- Crash Example Program { Name = "crashing_native", Sources = { Glob { Dir = "examples/crashing_native", Extensions = { ".c" }, }, }, } ----------------------------------------------------------------------------------------------------------------------- Program { Name = "core_tests", Env = { CPPPATH = { "api/include", "src/external/cmocka/include", "src/prodbg", }, }, Sources = { "src/prodbg/tests/core_tests.c", }, Depends = { "stb", "remote_api", "api", "core", "cmocka" }, Libs = { { "Ws2_32.lib", "psapi.lib", "iphlpapi.lib", "wsock32.lib", "kernel32.lib", "user32.lib", "gdi32.lib", "Comdlg32.lib", "Advapi32.lib" ; Config = { "win32-*-*", "win64-*-*" } } }, } ----------------------------------------------------------------------------------------------------------------------- Default "fake6502" Default "crashing_native" Default "core_tests"
link fixes on win64
link fixes on win64
Lua
mit
SlNPacifist/ProDBG,SlNPacifist/ProDBG,kondrak/ProDBG,ashemedai/ProDBG,kondrak/ProDBG,v3n/ProDBG,v3n/ProDBG,v3n/ProDBG,emoon/ProDBG,kondrak/ProDBG,emoon/ProDBG,ashemedai/ProDBG,v3n/ProDBG,kondrak/ProDBG,v3n/ProDBG,emoon/ProDBG,ashemedai/ProDBG,SlNPacifist/ProDBG,RobertoMalatesta/ProDBG,ashemedai/ProDBG,SlNPacifist/ProDBG,emoon/ProDBG,emoon/ProDBG,kondrak/ProDBG,RobertoMalatesta/ProDBG,kondrak/ProDBG,ashemedai/ProDBG,RobertoMalatesta/ProDBG,SlNPacifist/ProDBG,RobertoMalatesta/ProDBG,SlNPacifist/ProDBG,v3n/ProDBG,emoon/ProDBG,RobertoMalatesta/ProDBG,ashemedai/ProDBG
e636a0b23178e15959abb2477e6abc790d0efcd9
frontend/version.lua
frontend/version.lua
--[[-- This module helps with retrieving version information. ]] local Version = {} --- Returns current KOReader git-rev. -- @treturn string full KOReader git-rev such as `v2015.11-982-g704d4238` function Version:getCurrentRevision() if not self.rev then local rev_file = io.open("git-rev", "r") if rev_file then self.rev = rev_file:read() rev_file:close() end -- sanity check in case `git describe` failed if self.rev == "fatal: No names found, cannot describe anything." then self.rev = nil end end return self.rev end --- Returns normalized version of KOReader git-rev input string. -- @string rev full KOReader git-rev such as `v2015.11-982-g704d4238` -- @treturn int version in the form of a 10 digit number such as `2015110982` -- @treturn string short git commit version hash such as `704d4238` function Version:getNormalizedVersion(rev) if not rev then return end local year, month, revision = rev:match("v(%d%d%d%d)%.(%d%d)-?(%d*)") if type(year) ~= "number" then revision = 0 end if type(month) ~= "number" then revision = 0 end if type(revision) ~= "number" then revision = 0 end local commit = rev:match("-%d*-g(%x*)[%d_%-]*") -- NOTE: * 10000 to handle at most 9999 commits since last tag ;). return ((year or 0) * 100 + (month or 0)) * 10000 + (revision or 0), commit end --- Returns current version of KOReader. -- @treturn int version in the form of a 10 digit number such as `2015110982` -- @treturn string short git commit version hash such as `704d4238` -- @see normalized_version function Version:getNormalizedCurrentVersion() if not self.version or not self.commit then self.version, self.commit = self:getNormalizedVersion(self:getCurrentRevision()) end return self.version, self.commit end return Version
--[[-- This module helps with retrieving version information. ]] local Version = {} --- Returns current KOReader git-rev. -- @treturn string full KOReader git-rev such as `v2015.11-982-g704d4238` function Version:getCurrentRevision() if not self.rev then local rev_file = io.open("git-rev", "r") if rev_file then self.rev = rev_file:read() rev_file:close() end -- sanity check in case `git describe` failed if self.rev == "fatal: No names found, cannot describe anything." then self.rev = nil end end return self.rev end --- Returns normalized version of KOReader git-rev input string. -- @string rev full KOReader git-rev such as `v2015.11-982-g704d4238` -- @treturn int version in the form of a 10 digit number such as `2015110982` -- @treturn string short git commit version hash such as `704d4238` function Version:getNormalizedVersion(rev) if not rev then return end local year, month, revision = rev:match("v(%d%d%d%d)%.(%d%d)-?(%d*)") year = tonumber(year) month = tonumber(month) revision = tonumber(revision) local commit = rev:match("-%d*-g(%x*)[%d_%-]*") -- NOTE: * 10000 to handle at most 9999 commits since last tag ;). return ((year or 0) * 100 + (month or 0)) * 10000 + (revision or 0), commit end --- Returns current version of KOReader. -- @treturn int version in the form of a 10 digit number such as `2015110982` -- @treturn string short git commit version hash such as `704d4238` -- @see normalized_version function Version:getNormalizedCurrentVersion() if not self.version or not self.commit then self.version, self.commit = self:getNormalizedVersion(self:getCurrentRevision()) end return self.version, self.commit end return Version
[hotfix] tonumber makes an empty string nil
[hotfix] tonumber makes an empty string nil
Lua
agpl-3.0
koreader/koreader,Hzj-jie/koreader,NiLuJe/koreader,koreader/koreader,NiLuJe/koreader,poire-z/koreader,mwoz123/koreader,Frenzie/koreader,houqp/koreader,Frenzie/koreader,Markismus/koreader,mihailim/koreader,pazos/koreader,poire-z/koreader
1b72a3e9975948ebc26dfbee12c2d1a4ea9e97d4
nonsence/epoll_ffi.lua
nonsence/epoll_ffi.lua
--[[ Epoll bindings through the LuaJIT FFI Library Author: John Abrahamsen < [email protected] > This module "epoll_ffi" is a part of the Nonsence Web server. < https://github.com/JohnAbrahamsen/nonsence-ng/ > Nonsence is licensed under the MIT license < http://www.opensource.org/licenses/mit-license.php >: "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." ]] ------------------------------------------------------------------------- -- Load modules local ffi = require("ffi") local log = require("log") ------------------------------------------------------------------------- -- Module tabel to be returned local epoll = {} ------------------------------------------------------------------------- -- From epoll.h epoll.EPOLL_CTL_ADD = 1 -- Add a file decriptor to the interface epoll.EPOLL_CTL_DEL = 2 -- Remove a file decriptor from the interface epoll.EPOLL_CTL_MOD = 3 -- Change file decriptor epoll_event structure epoll.EPOLL_EVENTS = { ['EPOLLIN'] = 0x001, ['EPOLLPRI'] = 0x002, ['EPOLLOUT'] = 0x004, ['EPOLLERR'] = 0x008, ['EPOLLHUP'] = 0x0010, } ffi.cdef[[ typedef union epoll_data { void *ptr; int fd; uint32_t u32; uint64_t u64; } epoll_data_t; struct epoll_event { uint32_t events; /* Epoll events */ epoll_data_t data; /* User data variable */ } __attribute__ ((__packed__)); typedef struct epoll_event epoll_event; int epoll_create(int size); int epoll_ctl(int epfd, int op, int fd, struct epoll_event* event); int epoll_wait(int epfd, struct epoll_event *events, int maxevents, int timeout); ]] ------------------------------------------------------------------------- local MAX_EVENTS = 100 function epoll.epoll_create() --[[ Create a new epoll "instance". From man epoll: Note on int MAX_EVENTS: Since Linux 2.6.8, the size argument is unused, but must be greater than zero. (The kernel dynamically sizes the required data structures without needing this initial hint.) Returns the int of the created epoll and -1 on error with errno. --]] return ffi.C.epoll_create(MAX_EVENTS) end function epoll.epoll_ctl(epfd, op, fd, epoll_events) --[[ Control a epoll instance. From man epoll: EPOLL_CTL_ADD Register the target file descriptor fd on the epoll instance referred to by the file descriptor epfd and associate the event event with the internal file linked to fd. EPOLL_CTL_MOD Change the event event associated with the target file descriptor fd. EPOLL_CTL_DEL Remove (deregister) the target file descriptor fd from the epoll instance referred to by epfd. The event is ignored and can be NULL. Returns 0 on success and -1 on error together with errno. --]] local events = ffi.new("epoll_event", epoll_events) -- Add file_descriptor to data union. events.data.fd = fd return ffi.C.epoll_ctl(epfd, op, fd, events) end function epoll.epoll_wait(epfd, timeout) --[[ Wait for events on a epoll instance. From man epoll: The epoll_wait() system call waits for events on the epoll instance referred to by the file descriptor epfd. The memory area pointed to by events will contain the events that will be available for the caller. Up to maxevents are returned by epoll_wait(). The maxevents argument must be greater than zero. The call waits for a maximum time of timeout milliseconds. Specifying a timeout of -1 makes epoll_wait() wait indefinitely, while specifying a timeout equal to zero makes epoll_wait() to return immediately even if no events are available (return code equal to zero). Returns number of file descriptors ready for the requested I/O or -1 on error and errno is set. --]] local events = ffi.new("struct epoll_event[".. MAX_EVENTS.."]") local num_events, errno = ffi.C.epoll_wait(epfd, events, MAX_EVENTS, timeout) -- epoll_wait() returned error... if num_events == -1 then error(errno) end --[[ From CDATA to Lua table that will be easier to use. The table is structured as such: [fd, events, fd, events] The number preceeding after the fd is the events for the fd. --]] local events_t = {} for i=0, num_events do if events[i].data.fd > 0 then events_t[#events_t + 1 ] = events[i].data.fd events_t[#events_t + 1 ] = events[i].events end end return events_t end return epoll
--[[ Epoll bindings through the LuaJIT FFI Library Author: John Abrahamsen < [email protected] > This module "epoll_ffi" is a part of the Nonsence Web server. < https://github.com/JohnAbrahamsen/nonsence-ng/ > Nonsence is licensed under the MIT license < http://www.opensource.org/licenses/mit-license.php >: "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." ]] ------------------------------------------------------------------------- -- Load modules local ffi = require("ffi") local log = require("log") ------------------------------------------------------------------------- -- Module tabel to be returned local epoll = {} ------------------------------------------------------------------------- -- From epoll.h epoll.EPOLL_CTL_ADD = 1 -- Add a file decriptor to the interface epoll.EPOLL_CTL_DEL = 2 -- Remove a file decriptor from the interface epoll.EPOLL_CTL_MOD = 3 -- Change file decriptor epoll_event structure epoll.EPOLL_EVENTS = { ['EPOLLIN'] = 0x001, ['EPOLLPRI'] = 0x002, ['EPOLLOUT'] = 0x004, ['EPOLLERR'] = 0x008, ['EPOLLHUP'] = 0x0010, } ffi.cdef[[ typedef union epoll_data { void *ptr; int fd; uint32_t u32; uint64_t u64; } epoll_data_t; struct epoll_event { uint32_t events; /* Epoll events */ epoll_data_t data; /* User data variable */ } __attribute__ ((__packed__)); typedef struct epoll_event epoll_event; int epoll_create(int size); int epoll_ctl(int epfd, int op, int fd, struct epoll_event* event); int epoll_wait(int epfd, struct epoll_event *events, int maxevents, int timeout); ]] ------------------------------------------------------------------------- local MAX_EVENTS = 100 function epoll.epoll_create() --[[ Create a new epoll "instance". From man epoll: Note on int MAX_EVENTS: Since Linux 2.6.8, the size argument is unused, but must be greater than zero. (The kernel dynamically sizes the required data structures without needing this initial hint.) Returns the int of the created epoll and -1 on error with errno. --]] return ffi.C.epoll_create(MAX_EVENTS) end function epoll.epoll_ctl(epfd, op, fd, epoll_events) --[[ Control a epoll instance. From man epoll: EPOLL_CTL_ADD Register the target file descriptor fd on the epoll instance referred to by the file descriptor epfd and associate the event event with the internal file linked to fd. EPOLL_CTL_MOD Change the event event associated with the target file descriptor fd. EPOLL_CTL_DEL Remove (deregister) the target file descriptor fd from the epoll instance referred to by epfd. The event is ignored and can be NULL. Returns 0 on success and -1 on error together with errno. --]] local events = ffi.new("epoll_event", epoll_events) -- Add file_descriptor to data union. events.data.fd = fd return ffi.C.epoll_ctl(epfd, op, fd, events) end function epoll.epoll_wait(epfd, timeout) --[[ Wait for events on a epoll instance. From man epoll: The epoll_wait() system call waits for events on the epoll instance referred to by the file descriptor epfd. The memory area pointed to by events will contain the events that will be available for the caller. Up to maxevents are returned by epoll_wait(). The maxevents argument must be greater than zero. The call waits for a maximum time of timeout milliseconds. Specifying a timeout of -1 makes epoll_wait() wait indefinitely, while specifying a timeout equal to zero makes epoll_wait() to return immediately even if no events are available (return code equal to zero). Returns number of file descriptors ready for the requested I/O or -1 on error and errno is set. --]] local events = ffi.new("struct epoll_event[".. MAX_EVENTS.."]") local num_events = ffi.C.epoll_wait(epfd, events, MAX_EVENTS, timeout) -- epoll_wait() returned error... if num_events == -1 then return ffi.errno() end --[[ From CDATA to Lua table that will be easier to use. The table is structured as such: [fd, events, fd, events] The number preceeding after the fd is the events for the fd. --]] local events_t = {} if num_events == 0 then return events_t end if events[0].data.fd == 0 and events[0].data.events == 0 then return events_t end for i=0, num_events do local fd = events[i].data.fd if fd == 0 then -- Termination of array. break end if events[i].events then events_t[#events_t + 1 ] = {fd, events[i].events} end end return events_t end return epoll
Fixed some broken things, error handling amongst others
Fixed some broken things, error handling amongst others
Lua
apache-2.0
luastoned/turbo,luastoned/turbo,zcsteele/turbo,zcsteele/turbo,ddysher/turbo,ddysher/turbo,YuanPeir-Chen/turbo-support-mipsel,mniestroj/turbo,kernelsauce/turbo,YuanPeir-Chen/turbo-support-mipsel
f041da51e43dee21c89e7e08ef3d67217fb8d458
npl_mod/nwf/loader.lua
npl_mod/nwf/loader.lua
--[[ title: NPL web framework loader author: zenghui date: 2017/2/27 desc: this file will load NPL web framework basic module and init components. ]] print('npl web framework is loading...'); NPL.load("(gl)script/ide/Files.lua"); lfs = commonlib.Files.GetLuaFileSystem(); PROJECT_BASE_DIR = lfs.currentdir(); print("project base dir: '" .. PROJECT_BASE_DIR .. "'"); -- add search path NPL.load("(gl)script/ide/System/os/os.lua"); local os_util = commonlib.gettable("System.os"); if(os_util.GetPlatform() == "linux") then package.cpath = package.cpath .. ';./lib/so/?.so;' end if(os_util.GetPlatform() == "win32") then package.cpath = package.cpath .. ';./lib/dll/?.dll;' end -- init print("init framework..."); local nwf = commonlib.gettable("nwf"); nwf.controllers = {}; nwf.validators = {}; nwf.config = {}; nwf.initializedModules = {}; nwf.modules = {}; -- namespace for modules nwf.requestMappings = {}; nwf.template = require "nwf.resty.template"; nwf.validation = require "nwf.resty.validation"; nwf.mod_path = {"www/modules"} -- specified module search path -- init functions local filters = commonlib.gettable("nwf.filters"); --[[ nwf.registerFilter(function(ctx, doNext) local req = ctx.request; local res = ctx.response; doSomething(); doNext(); doSomething(); end); ]] function nwf.registerFilter(filter) table.insert(filters, filter); end; NPL.load("nwf.utils.configUtil") NPL.load("nwf.utils.string_util") NPL.load("nwf.dispatcher") NPL.load("nwf.utils.string_escape_util") NPL.load("nwf.nwf_load_file") -- builtin filters -- register request log filter nwf.registerFilter(function(ctx, doNext) local req = ctx.request; --local res = ctx.response; local requestPath = req:url(); local t1 = os.time(); local ms1 = ParaGlobal.timeGetTime(); print(); print(string.format([[[%s] method:[%s] url:[%s] id: [%d]. begin..]] , os.date("%c", t1), req:GetMethod(), requestPath, ms1)); doNext(); local ms2 = ParaGlobal.timeGetTime(); print(); print(string.format([[[%s] method:[%s] url:[%s] id: [%d]. total %d millisec.]] , os.date("%c", t1), req:GetMethod(), requestPath, ms1, ms2 - ms1)); end); -- load session component(filter) NPL.load("nwf.session"); -- error page controller nwf.registerRequestMapping("/404", function(ctx) return "404"; end); nwf.registerRequestMapping("/error", function(ctx) return "error"; end); -- load settings print("load framework settings..."); NPL.load("(gl)www/mvc_settings.lua"); -- load modules print("checking module search path setting...") for i,v in ipairs(nwf.mod_path) do assert(not string.match(v, "^/") , "module search path can not be absolute path, use relative path.") if (string.match(v, "/$")) then nwf.mod_path[i] = string.sub(v, 1, -2); end end nwf.loadModule = function (mod_base_dir, name) local path = mod_base_dir .. '/' .. name; if (nwf.initializedModules[name]) then print("module '" .. name .. "' already loaded, skipped."); return; else nwf.initializedModules[name] = true; end local dependenciesConfigPath = path .. '/dependencies.conf'; if (ParaIO.DoesFileExist(dependenciesConfigPath, false)) then local depConfig = io.open(dependenciesConfigPath); for line in depConfig:lines() do if (not nwf.initializedModules[line]) then print("load module '" .. line .."' as a dependency of module '" .. name .."'"); local moduleFounded = false; for i,v in ipairs(nwf.mod_path) do local dep_path = PROJECT_BASE_DIR .. "/" .. v .. "/" .. line; if (ParaIO.DoesFileExist(dep_path, false)) then moduleFounded = true; print("founded dependency on '" .. dep_path .. "'") print("load dependency on '" .. v .. "'"); nwf.loadModule(v, line); break; end end if (not moduleFounded) then error("dependency of module '" .. name .. "' can not found. load failed!"); end end end depConfig:close(); end print("loading module '" .. name .. "'"); local initScriptPath = PROJECT_BASE_DIR .. "/" .. path .. '/init.lua'; --[[local g = {}; setmetatable(g, {__index = _G}) local doInit = function() NPL.load(initScriptPath); end setfenv(doInit, g); doInit();--]] -- NPL.load(initScriptPath); nwf.load(initScriptPath); end function load_dir(mod_base_dir) for entry in lfs.dir(mod_base_dir) do if entry ~= '.' and entry ~= '..' then local path = mod_base_dir .. '/' .. entry; print("found module: '" .. path .. "'"); nwf.loadModule(mod_base_dir, entry); end end end print("load nwf modules..."); for i,v in ipairs(nwf.mod_path) do load_dir(v); end print('npl web framework loaded.');
--[[ title: NPL web framework loader author: zenghui date: 2017/2/27 desc: this file will load NPL web framework basic module and init components. ]] print('npl web framework is loading...'); NPL.load("(gl)script/ide/Files.lua"); lfs = commonlib.Files.GetLuaFileSystem(); PROJECT_BASE_DIR = lfs.currentdir(); print("project base dir: '" .. PROJECT_BASE_DIR .. "'"); -- add search path NPL.load("(gl)script/ide/System/os/os.lua"); local os_util = commonlib.gettable("System.os"); if(os_util.GetPlatform() == "linux") then package.cpath = package.cpath .. ';./lib/so/?.so;' end if(os_util.GetPlatform() == "win32") then package.cpath = package.cpath .. ';./lib/dll/?.dll;' end -- init print("init framework..."); local nwf = commonlib.gettable("nwf"); nwf.controllers = {}; nwf.validators = {}; nwf.config = {}; nwf.initializedModules = {}; nwf.modules = {}; -- namespace for modules nwf.requestMappings = {}; nwf.template = require "nwf.resty.template"; nwf.validation = require "nwf.resty.validation"; nwf.mod_path = {"www/modules"} -- specified module search path -- init functions local filters = commonlib.gettable("nwf.filters"); --[[ nwf.registerFilter(function(ctx, doNext) local req = ctx.request; local res = ctx.response; doSomething(); doNext(); doSomething(); end); ]] function nwf.registerFilter(filter) table.insert(filters, filter); end; NPL.load("nwf.utils.configUtil") NPL.load("nwf.utils.string_util") NPL.load("nwf.dispatcher") NPL.load("nwf.utils.string_escape_util") NPL.load("nwf.nwf_load_file") -- builtin filters -- register request log filter nwf.registerFilter(function(ctx, doNext) local req = ctx.request; --local res = ctx.response; local requestPath = req:url(); local t1 = os.time(); local ms1 = ParaGlobal.timeGetTime(); print(); print(string.format([[[%s] method:[%s] url:[%s] id: [%d]. begin..]] , os.date("%c", t1), req:GetMethod(), requestPath, ms1)); doNext(); local ms2 = ParaGlobal.timeGetTime(); print(); print(string.format([[[%s] method:[%s] url:[%s] id: [%d]. total %d millisec.]] , os.date("%c", t1), req:GetMethod(), requestPath, ms1, ms2 - ms1)); end); -- load session component(filter) NPL.load("nwf.session"); -- error page controller nwf.registerRequestMapping("/404", function(ctx) return "404"; end); nwf.registerRequestMapping("/error", function(ctx) return "error"; end); -- load settings print("load framework settings..."); NPL.load("(gl)www/mvc_settings.lua"); -- load modules print("checking module search path setting...") for i,v in ipairs(nwf.mod_path) do assert(not string.match(v, "^/") , "module search path can not be absolute path, use relative path.") if (string.match(v, "/$")) then nwf.mod_path[i] = string.sub(v, 1, -2); end end nwf.loadModule = function (mod_base_dir, name) local path = mod_base_dir .. '/' .. name; if (nwf.initializedModules[name]) then print("module '" .. name .. "' already loaded, skipped."); return; else nwf.initializedModules[name] = true; end local dependenciesConfigPath = path .. '/dependencies.conf'; if (ParaIO.DoesFileExist(dependenciesConfigPath, false)) then local depConfig = assert(io.open(dependenciesConfigPath)); for line in depConfig:lines() do if (not nwf.initializedModules[line]) then print("load module '" .. line .."' as a dependency of module '" .. name .."'"); local moduleFounded = false; for i,v in ipairs(nwf.mod_path) do local dep_path = PROJECT_BASE_DIR .. "/" .. v .. "/" .. line; if (ParaIO.DoesFileExist(dep_path, false)) then moduleFounded = true; print("founded dependency on '" .. dep_path .. "'") print("load dependency on '" .. v .. "'"); nwf.loadModule(v, line); break; end end if (not moduleFounded) then error("dependency of module '" .. name .. "' can not found. load failed!"); end end end depConfig:close(); end print("loading module '" .. name .. "'"); local initScriptPath = PROJECT_BASE_DIR .. "/" .. path .. '/init.lua'; --[[local g = {}; setmetatable(g, {__index = _G}) local doInit = function() NPL.load(initScriptPath); end setfenv(doInit, g); doInit();--]] -- NPL.load(initScriptPath); nwf.load(initScriptPath); end print("load nwf modules..."); local projectDependencies = PROJECT_BASE_DIR .. '/dependencies.conf'; if (ParaIO.DoesFileExist(projectDependencies, false)) then local projectDepConfig = assert(io.open(projectDependencies)); for line in projectDepConfig:lines() do if (not nwf.initializedModules[line]) then print("load module '" .. line .."' as a dependency of project"); local moduleFounded = false; for i,v in ipairs(nwf.mod_path) do local dep_path = PROJECT_BASE_DIR .. "/" .. v .. "/" .. line; if (ParaIO.DoesFileExist(dep_path, false)) then moduleFounded = true; print("founded project dependency on '" .. dep_path .. "'") print("load project dependency on '" .. v .. "'"); nwf.loadModule(v, line); break; end end if (not moduleFounded) then error("project dependency of module '" .. name .. "' can not found. load failed!"); end else print("project dependency '" .. line .. "' already loaded, skipped."); end end projectDepConfig:close(); end print('npl web framework loaded.');
fix bug about project module loading
fix bug about project module loading
Lua
mit
elvinzeng/nwf,Links7094/nwf,Links7094/nwf,elvinzeng/nwf
b71b63d5b5971706079bd04c50de36689e90ba6a
src/romdisk/framework/org/xboot/core/Asset.lua
src/romdisk/framework/org/xboot/core/Asset.lua
--- -- The 'Asset' class provides facilities to load and cache different -- type of resources. -- -- @module Asset local M = Class() --- -- Creates a new 'Asset' for cache different type of resources. -- -- @function [parent=#Asset] new -- @return New 'Asset' object. function M:init() self.textures = {} self.fonts = {} self.theme = {} end function M:loadTexture(filename) if not filename then return nil end if not self.textures[filename] then self.textures[filename] = Texture.new(filename) end return self.textures[filename] end function M:loadFont(family) if not family then return nil end if not self.fonts[family] then self.fonts[family] = Font.new(family) end return self.fonts[family] end function M:loadDisplay(image) if string.lower(string.sub(image, -6)) == ".9.png" then return DisplayNinePatch.new(self:loadTexture(image)) elseif string.lower(string.sub(image, -4)) == ".png" then return DisplayImage.new(self:loadTexture(image)) else return image end end function M:loadTheme(name) local name = name or "default" if not self.theme[name] then self.theme[name] = require("assets.themes." .. name) end return self.theme[name] end return M
--- -- The 'Asset' class provides facilities to load and cache different -- type of resources. -- -- @module Asset local M = Class() --- -- Creates a new 'Asset' for cache different type of resources. -- -- @function [parent=#Asset] new -- @return New 'Asset' object. function M:init() self.textures = {} self.fonts = {} self.theme = {} end function M:loadTexture(filename) if not filename then return nil end if not self.textures[filename] then self.textures[filename] = Texture.new(filename) end return self.textures[filename] end function M:loadFont(family) if not family then return nil end if not self.fonts[family] then self.fonts[family] = Font.new(family) end return self.fonts[family] end function M:loadDisplay(image) if type(image) == "string" then if string.lower(string.sub(image, -6)) == ".9.png" then return DisplayNinePatch.new(self:loadTexture(image)) elseif string.lower(string.sub(image, -4)) == ".png" then return DisplayImage.new(self:loadTexture(image)) end else return image end end function M:loadTheme(name) local name = name or "default" if not self.theme[name] then self.theme[name] = require("assets.themes." .. name) end return self.theme[name] end return M
fix Asset.lua
fix Asset.lua
Lua
mit
xboot/xboot,xboot/xboot
31b84c18dc38d9a23c001985127d404d2ac386d5
src/jet/daemon/radix.lua
src/jet/daemon/radix.lua
-- Implements a radix tree for the jet-daemon local pairs = pairs local next = next local tinsert = table.insert local tremove = table.remove local new = function() local j = {} -- the table that holds the radix_tree j.radix_tree = {} -- elments that can be filled by several functions -- and be returned as set of possible hits j.radix_elements = {} -- internal tree instance or table of tree instances -- used to hold parts of the tree that may be interesting afterwards j.return_tree = {} -- this FSM is used for string comparison -- can evaluate if the radix tree contains or ends with a specific string local lookup_fsm = function (wordpart,next_state,next_letter) if wordpart:sub(next_state,next_state) ~= next_letter then if wordpart:sub(1,1) ~= next_letter then return false,0 else return false,1 end end if #wordpart == next_state then return true,next_state else return false,next_state end end -- evaluate if the radix tree starts with a specific string -- returns pointer to subtree local root_lookup root_lookup = function(tree_instance,part) if #part == 0 then j.return_tree = tree_instance else local s = part:sub(1,1) if tree_instance and tree_instance[s] ~= true then root_lookup(tree_instance[s], part:sub(2)) end end end -- evaluate if the radix tree contains or ends with a specific string -- returns list of pointers to subtrees local leaf_lookup leaf_lookup = function(tree_instance,word,state) local next_state = state + 1 if tree_instance then for k,v in pairs(tree_instance) do if v ~= true then local hit,next_state = lookup_fsm(word,next_state,k) if hit == true then tinsert(j.return_tree,v) else leaf_lookup(v,word,next_state) end end end end end -- takes a single tree or a list of trees -- traverses the trees and adds all elements to j.radix_elements local radix_traverse radix_traverse = function(tree_instance) for k,v in pairs(tree_instance) do if v == true then j.radix_elements[k] = true elseif v ~= true then radix_traverse(v) end end end -- adds a new element to the tree local add_to_tree = function(word) local t = j.radix_tree for char in word:gfind('.') do if t[char] == true or t[char] == nil then t[char] = {} end t = t[char] end t[word] = true end -- removes an element from the tree local remove_from_tree = function(word) local t = j.radix_tree for char in word:gfind('.') do if t[char] == true then return end t = t[char] end t[word] = nil end -- performs the respective actions for the parts of a fetcher -- that can be handled by a radix tree -- fills j.radix_elements with all hits that were found local match_parts = function(tree_instance,parts) j.radix_elements = {} if parts['equals'] then j.return_tree = {} root_lookup(tree_instance,parts['equals']) if j.return_tree[parts['equals']] == true then j.radix_elements[parts['equals']] = true end else local temp_tree = tree_instance if parts['startsWith'] then j.return_tree = {} root_lookup(temp_tree,parts['startsWith']) temp_tree = j.return_tree end if parts['contains'] then j.return_tree = {} leaf_lookup(temp_tree,parts['contains'],0) temp_tree = j.return_tree end if parts['endsWith'] then j.return_tree = {} leaf_lookup(temp_tree,parts['endsWith'],0) for k,t in pairs(j.return_tree) do for _,v in pairs(t) do if v ~= true then j.return_tree[k] = nil break end end end temp_tree = j.return_tree end if temp_tree then radix_traverse(temp_tree) end end end -- evaluates if the fetch operation can be handled -- completely or partially by the radix tree -- returns elements from the j.radix_tree if it can be handled -- and nil otherwise local get_possible_matches = function(peer,params,fetch_id,is_case_insensitive) local involves_path_match = params.path local involves_value_match = params.value or params.valueField local level = 'impossible' local radix_expressions = {} if involves_path_match and not is_case_insensitive then for name,value in pairs(params.path) do if name == 'equals' or name == 'startsWith' or name == 'endsWith' or name == 'contains' then if radix_expressions[name] then level = 'impossible' break end radix_expressions[name] = value if level == 'partial_pending' or involves_value_match then level = 'partial' elseif level ~= 'partial' then level = 'all' end else if level == 'easy' or level == 'partial' then level = 'partial' else level = 'partial_pending' end end end if level == 'partial_pending' then level = 'impossible' end end if level ~= 'impossible' then match_parts(j.radix_tree,radix_expressions) return j.radix_elements else return nil end end j.add = function(word) add_to_tree(word) end j.remove = function(word) remove_from_tree(word) end j.get_possible_matches = get_possible_matches -- for unit testing j.match_parts = function(parts,xxx) match_parts(j.radix_tree,parts,xxx) end j.found_elements = function() return j.radix_elements end return j end return { new = new }
-- Implements a radix tree for the jet-daemon local pairs = pairs local next = next local tinsert = table.insert local tremove = table.remove local new = function() local j = {} -- the table that holds the radix_tree j.radix_tree = {} -- elments that can be filled by several functions -- and be returned as set of possible hits j.radix_elements = {} -- internal tree instance or table of tree instances -- used to hold parts of the tree that may be interesting afterwards j.return_tree = {} -- this FSM is used for string comparison -- can evaluate if the radix tree contains or ends with a specific string local lookup_fsm = function (wordpart,next_state,next_letter) if wordpart:sub(next_state,next_state) ~= next_letter then if wordpart:sub(1,1) ~= next_letter then return false,0 else return false,1 end end if #wordpart == next_state then return true,next_state else return false,next_state end end -- evaluate if the radix tree starts with a specific string -- returns pointer to subtree local root_lookup root_lookup = function(tree_instance,part) if #part == 0 then j.return_tree = tree_instance else local s = part:sub(1,1) if tree_instance and tree_instance[s] ~= true then root_lookup(tree_instance[s], part:sub(2)) end end end -- evaluate if the radix tree contains or ends with a specific string -- returns list of pointers to subtrees local leaf_lookup leaf_lookup = function(tree_instance,word,state) local next_state = state + 1 if tree_instance then for k,v in pairs(tree_instance) do if v ~= true then local hit,next_state = lookup_fsm(word,next_state,k) if hit == true then tinsert(j.return_tree,v) else leaf_lookup(v,word,next_state) end end end end end -- takes a single tree or a list of trees -- traverses the trees and adds all elements to j.radix_elements local radix_traverse radix_traverse = function(tree_instance) for k,v in pairs(tree_instance) do if v == true then j.radix_elements[k] = true elseif v ~= true then radix_traverse(v) end end end -- adds a new element to the tree local add_to_tree = function(word) local t = j.radix_tree for i=1,#word do local char = word:sub(i,i) local tmpt = t[char] if tmpt == nil then tmpt = {} t[char] = tmpt end t = tmpt end t[word] = true end -- removes an element from the tree local remove_from_tree = function(word) local t = j.radix_tree local tables = {} for i=1,#word do local char = word:sub(i,i) local tmpt = t[char] tables[i] = tmpt t = tmpt end t[word] = nil local i = #word while next(t) == nil and i > 1 do local char = word:sub(i, i) t = tables[i-1] t[char] = nil i = i - 1 end end -- performs the respective actions for the parts of a fetcher -- that can be handled by a radix tree -- fills j.radix_elements with all hits that were found local match_parts = function(tree_instance,parts) j.radix_elements = {} if parts['equals'] then j.return_tree = {} root_lookup(tree_instance,parts['equals']) if j.return_tree[parts['equals']] == true then j.radix_elements[parts['equals']] = true end else local temp_tree = tree_instance if parts['startsWith'] then j.return_tree = {} root_lookup(temp_tree,parts['startsWith']) temp_tree = j.return_tree end if parts['contains'] then j.return_tree = {} leaf_lookup(temp_tree,parts['contains'],0) temp_tree = j.return_tree end if parts['endsWith'] then j.return_tree = {} leaf_lookup(temp_tree,parts['endsWith'],0) for k,t in pairs(j.return_tree) do for _,v in pairs(t) do if v ~= true then j.return_tree[k] = nil break end end end temp_tree = j.return_tree end if temp_tree then radix_traverse(temp_tree) end end end -- evaluates if the fetch operation can be handled -- completely or partially by the radix tree -- returns elements from the j.radix_tree if it can be handled -- and nil otherwise local get_possible_matches = function(peer,params,fetch_id,is_case_insensitive) local involves_path_match = params.path local involves_value_match = params.value or params.valueField local level = 'impossible' local radix_expressions = {} if involves_path_match and not is_case_insensitive then for name,value in pairs(params.path) do if name == 'equals' or name == 'startsWith' or name == 'endsWith' or name == 'contains' then if radix_expressions[name] then level = 'impossible' break end radix_expressions[name] = value if level == 'partial_pending' or involves_value_match then level = 'partial' elseif level ~= 'partial' then level = 'all' end else if level == 'easy' or level == 'partial' then level = 'partial' else level = 'partial_pending' end end end if level == 'partial_pending' then level = 'impossible' end end if level ~= 'impossible' then match_parts(j.radix_tree,radix_expressions) return j.radix_elements else return nil end end j.add = function(word) add_to_tree(word) end j.remove = function(word) remove_from_tree(word) end j.get_possible_matches = get_possible_matches -- for unit testing j.match_parts = function(parts,xxx) match_parts(j.radix_tree,parts,xxx) end j.found_elements = function() return j.radix_elements end return j end return { new = new }
fixed memory leak
fixed memory leak
Lua
mit
lipp/lua-jet
a7d7f82043942ef25e12d92ec5be7e4b842bd1ea
src/bosh_registry_nginx/registry.lua
src/bosh_registry_nginx/registry.lua
-- -*- coding: utf-8 -*- local JSON = require "JSON" local registry_base_uri = "/metadata/" local request_base_uri = "/registry/" -- functions local function bad_request(msg) local logmsg = string.format("Sending BAD_REQUEST to client (status=%d): %s", ngx.HTTP_BAD_REQUEST, msg) ngx.log(ngx.NOTICE, logmsg) ngx.status = ngx.HTTP_BAD_REQUEST ngx.say(msg) ngx.exit(ngx.HTTP_OK) end local function do_not_found(id) ngx.log(ngx.NOTICE, "Sending NOT_FOUND to client (status=%d): %s", ngx.HTTP_NOT_FOUND, id) ngx.status = ngx.HTTP_NOT_FOUND msg = string.format("Id '%s' not found", id) ngx.say(msg) ngx.exit(ngx.HTTP_OK) end local function do_not_allowed(msg) local logmsg = string.format("Sending NOT_ALLOWED to client (status=%d): %s", ngx.HTTP_NOT_ALLOWED, msg) ngx.log(ngx.NOTICE, logmsg) ngx.status = ngx.HTTP_NOT_ALLOWED ngx.say(msg) ngx.exit(ngx.HTTP_OK) end local function do_conflict(id) local logmsg = string.format("Sending CONFLICT to client (status=%d): %s", ngx.HTTP_CONFLICT, msg) ngx.log(ngx.NOTICE, logmsg) ngx.status = ngx.HTTP_CONFLICT msg = string.format("Id '%s' already exists", id) ngx.say(msg) ngx.exit(ngx.HTTP_OK) end local function check(id) local logmsg = string.format("Checking if id=%s exists", id) ngx.log(ngx.NOTICE, logmsg) local res = ngx.location.capture(registry_base_uri .. id .. "/", { method = ngx.HTTP_HEAD }) if res.status == 200 then logmsg = string.format("Found id=%s in %s (status=%s).", id, registry_base_uri, res.status) ngx.log(ngx.NOTICE, logmsg) return true else logmsg = string.format("Not found id=%s in %s (status=%s).", id, registry_base_uri, res.status) ngx.log(ngx.NOTICE, logmsg) return false end end local function do_post(id) -- Creates ID (but no settings) local logmsg = string.format("Registry POST for id=%s", id) ngx.log(ngx.NOTICE, logmsg) if not check(id) then local res = ngx.location.capture(registry_base_uri .. id .. "/", { method = ngx.HTTP_MKCOL }) logmsg = string.format("Registry POST for id=%s. Done (status=%s)", id, res.status) ngx.log(ngx.NOTICE, logmsg) ngx.status = res.status ngx.say(res.body) ngx.exit(ngx.HTTP_OK) else -- 409 Conflict do_conflict(id) end end local function do_delete(id, param) -- Delete ID and/or settings local logmsg = string.format("Registry DELETE for id=%s, params='%s'", id, param) ngx.log(ngx.NOTICE, logmsg) if check(id) then local resource = '/' if param ~= '' then resource = resource .. param end local res = ngx.location.capture(registry_base_uri .. id .. resource, { method = ngx.HTTP_DELETE }) logmsg = string.format("Registry DELETE for id=%s '%s' (status=%s)", id, resource, res.status) ngx.log(ngx.NOTICE, logmsg) ngx.status = res.status ngx.say(res.body) ngx.exit(ngx.HTTP_OK) else -- 404 Id not found do_not_found(id) end end local function do_get(id, param) -- Get settings. No file, returns error json local logmsg = string.format("Registry GET for id=%s, params='%s'", id, param) ngx.log(ngx.NOTICE, logmsg) if check(id) and (param == "settings") then -- Get the settings from the metadata service local settings_value local status_value local res = ngx.location.capture(registry_base_uri .. id .. "/settings") if res.status == 200 then status_value = "ok" settings_value = JSON:decode(res.body) else status_value = "error" settings_value = {} end local output = { settings = settings_value, status = status_value } local result = JSON:encode_pretty(output) logmsg = string.format("Registry GET for id=%s. Done (status=%s)", id, res.status) ngx.log(ngx.NOTICE, logmsg) ngx.status = res.status ngx.say(result) ngx.exit(ngx.HTTP_OK) else -- 404 Id not found do_not_found(id) end end local function do_put(id, param) -- Put/Update settings local logmsg = string.format("Registry PUT for id=%s, params='%s'", id, param) ngx.log(ngx.NOTICE, logmsg) if check(id) and (param == "settings") then -- Internal Redirect with the content to metadata logmsg = string.format("Redirecting PUT: %s", registry_base_uri .. id .. "/settings") ngx.log(ngx.NOTICE, logmsg) ngx.exec(registry_base_uri .. id .. "/settings") else -- 404 Id not found do_not_found(id) end end -- Get the ID of the request local method_name = ngx.req.get_method() local regex = "^" .. request_base_uri .. "instances/([\\w-]+)/?(.*)?" local params, err = ngx.re.match(ngx.var.uri, regex) if params then -- Check request method type local id = params[1] local param = params[2] if method_name == "GET" then -- Get settings if param == '' then param = 'settings' end do_get(id, param) elseif method_name == "DELETE" then -- Delete ID and/or settings do_delete(id, param) elseif method_name == "PUT" then -- Update settings if param == '' then param = 'settings' end do_put(id, param) elseif method_name == "POST" then -- Create id do_post(id) else do_not_allowed("Method not allowed. Please, see bosh documentation") end else bad_request("Error parsing URI") end
-- -*- coding: utf-8 -*- local JSON = require "JSON" JSON.strictTypes = true JSON.decodeNumbersAsObjects = true JSON.noKeyConversion = true local registry_base_uri = "/metadata/" local request_base_uri = "/registry/" -- functions local function bad_request(msg) local logmsg = string.format("Sending BAD_REQUEST to client (status=%d): %s", ngx.HTTP_BAD_REQUEST, msg) ngx.log(ngx.NOTICE, logmsg) ngx.status = ngx.HTTP_BAD_REQUEST ngx.say(msg) ngx.exit(ngx.HTTP_OK) end local function do_not_found(id) ngx.log(ngx.NOTICE, "Sending NOT_FOUND to client (status=%d): %s", ngx.HTTP_NOT_FOUND, id) ngx.status = ngx.HTTP_NOT_FOUND msg = string.format("Id '%s' not found", id) ngx.say(msg) ngx.exit(ngx.HTTP_OK) end local function do_not_allowed(msg) local logmsg = string.format("Sending NOT_ALLOWED to client (status=%d): %s", ngx.HTTP_NOT_ALLOWED, msg) ngx.log(ngx.NOTICE, logmsg) ngx.status = ngx.HTTP_NOT_ALLOWED ngx.say(msg) ngx.exit(ngx.HTTP_OK) end local function do_conflict(id) local logmsg = string.format("Sending CONFLICT to client (status=%d): %s", ngx.HTTP_CONFLICT, msg) ngx.log(ngx.NOTICE, logmsg) ngx.status = ngx.HTTP_CONFLICT msg = string.format("Id '%s' already exists", id) ngx.say(msg) ngx.exit(ngx.HTTP_OK) end local function check(id) local logmsg = string.format("Checking if id=%s exists", id) ngx.log(ngx.NOTICE, logmsg) local res = ngx.location.capture(registry_base_uri .. id .. "/", { method = ngx.HTTP_HEAD }) if res.status == 200 then logmsg = string.format("Found id=%s in %s (status=%s).", id, registry_base_uri, res.status) ngx.log(ngx.NOTICE, logmsg) return true else logmsg = string.format("Not found id=%s in %s (status=%s).", id, registry_base_uri, res.status) ngx.log(ngx.NOTICE, logmsg) return false end end local function do_head(id) local logmsg = string.format("Registry HEAD for id=%s", id) ngx.log(ngx.NOTICE, logmsg) if check(id) then ngx.status = ngx.HTTP_OK else ngx.status = ngx.HTTP_NOT_FOUND end ngx.exit(ngx.HTTP_OK) end local function do_post(id) -- Creates ID (but no settings) local logmsg = string.format("Registry POST for id=%s", id) ngx.log(ngx.NOTICE, logmsg) if not check(id) then local res = ngx.location.capture(registry_base_uri .. id .. "/", { method = ngx.HTTP_MKCOL }) logmsg = string.format("Registry POST for id=%s. Done (status=%s)", id, res.status) ngx.log(ngx.NOTICE, logmsg) ngx.status = res.status ngx.say(res.body) ngx.exit(ngx.HTTP_OK) else -- 409 Conflict do_conflict(id) end end local function do_delete(id, param) -- Delete ID and/or settings local logmsg = string.format("Registry DELETE for id=%s, params='%s'", id, param) ngx.log(ngx.NOTICE, logmsg) if check(id) then local resource = '/' if param ~= '' then resource = resource .. param end local res = ngx.location.capture(registry_base_uri .. id .. resource, { method = ngx.HTTP_DELETE }) logmsg = string.format("Registry DELETE for id=%s '%s' (status=%s)", id, resource, res.status) ngx.log(ngx.NOTICE, logmsg) ngx.status = res.status ngx.say(res.body) ngx.exit(ngx.HTTP_OK) else -- 404 Id not found do_not_found(id) end end local function do_get(id, param) -- Get settings. No file, returns error json local logmsg = string.format("Registry GET for id=%s, params='%s'", id, param) ngx.log(ngx.NOTICE, logmsg) if check(id) and (param == "settings") then -- Get the settings from the metadata service local settings_value local status_value local res = ngx.location.capture(registry_base_uri .. id .. "/settings") if res.status == 200 then status_value = "ok" -- settings_value = res.body settings_value = JSON:decode(res.body) else status_value = "error" settings_value = {} end local output = { settings = settings_value, status = status_value } -- local result = JSON:encode_pretty(output) local result = JSON:encode(output, nil, { pretty = true, indent = " ", null = nil }) logmsg = string.format("Registry GET for id=%s. Done (status=%s)", id, res.status) ngx.log(ngx.NOTICE, logmsg) ngx.status = res.status ngx.say(result) ngx.exit(ngx.HTTP_OK) else -- 404 Id not found do_not_found(id) end end local function do_put(id, param) -- Put/Update settings local logmsg = string.format("Registry PUT for id=%s, params='%s'", id, param) ngx.log(ngx.NOTICE, logmsg) local exists = check(id) -- To make it compatible with -- https://github.com/cloudfoundry/bosh/blob/master/bosh_cpi/lib/bosh/cpi/registry_client.rb -- it has to accept put if ((not exists) and (param == "settings")) then local res = ngx.location.capture(registry_base_uri .. id .. "/", { method = ngx.HTTP_MKCOL }) logmsg = string.format("Registry POST for id=%s. Done (status=%s)", id, res.status) ngx.log(ngx.NOTICE, logmsg) end if (param == "settings") then -- Internal Redirect with the content to metadata logmsg = string.format("Redirecting PUT: %s", registry_base_uri .. id .. "/settings") ngx.log(ngx.NOTICE, logmsg) ngx.exec(registry_base_uri .. id .. "/settings") else -- 404 Id not found do_not_found(id) end end -- Get the ID of the request local method_name = ngx.req.get_method() local regex = "^" .. request_base_uri .. "instances/([\\w-]+)/?(.*)?" local params, err = ngx.re.match(ngx.var.uri, regex) if params then -- Check request method type local id = params[1] local param = params[2] if method_name == "GET" then -- Get settings if param == '' then param = 'settings' end do_get(id, param) elseif method_name == "DELETE" then -- Delete ID and/or settings do_delete(id, param) elseif method_name == "PUT" then -- Update settings if param == '' then param = 'settings' end do_put(id, param) elseif method_name == "HEAD" then -- Check if it exists do_head(id) elseif method_name == "POST" then -- Create id do_post(id) else do_not_allowed("Method not allowed. Please, see bosh documentation") end else bad_request("Error parsing URI") end
fix post/put, null and dict issues
fix post/put, null and dict issues
Lua
apache-2.0
jriguera/bosh-ironic-cpi-release,jriguera/bosh-ironic-cpi-release,jriguera/bosh-ironic-cpi-release
d655427c34c5b8fd7cbe414650ef57690a2a4a06
ssbase/gamemode/sv_profiles.lua
ssbase/gamemode/sv_profiles.lua
--------------------------- -- Bunny Hop -- -- Created by xAaron113x -- --------------------------- local selects = {"exp", "id", "steamId64", "lastLoginIp", "playtime", "lastLoginTimestamp", "steamId", "rank", "name", "money", "store", "equipped", "avatarUrl"} local update_filter = {"id", "steamId", "rank", "avatarUrl"} SS.Profiles = {} -- Check if the player has a valid avatar url stored in the database, if not fetch it. function PLAYER_META:CheckAvatar() if self.profile and (!self.profile.avatarUrl or string.Trim(self.profile.avatarUrl) == "" or string.sub(self.profile.avatarURL, string.len(self.profile.avatarURL)-9, string.len(self.profile.avatarURL)) == "_full.jpg") then http.Fetch("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=9D7A9B8269C1C1B1B7B21E659904DDEF&steamids="..self.profile.steamId64, function(body) if self and self:IsValid() then body = util.JSONToTable(body) DB_Query("UPDATE users SET avatarUrl='"..body.response.players[1].avatar.."' WHERE steamId='"..string.sub(self:SteamID(), 7).."'") end end, function(error) Error("[AVATAR FETCH FAILED] ".. error) end ) end end function PLAYER_META:CreateProfile() if(self:IsBot()) then return end local ip = string.Replace(game.IsDedicated() and self:IPAddress() or "127.0.0.1", ".", "") local query = "INSERT INTO users (steamid64, steamid, name, registerIp, lastLoginIP, registerTimestamp, lastLoginTimestamp) VALUES ('"..self:SteamID64().."','"..string.sub(self:SteamID(), 7).."','"..DB:escape(self:Name()).."','"..ip.."','"..ip.."','"..tostring(os.time()).."','"..tostring(os.time()).."')" DB_Query(query, function() if self and self:IsValid() then self:ProfileLoad() end end) end function PLAYER_META:ProfileLoad() if(self:IsBot()) then return end MsgN("[PROFILE] Loading ", self) local steamid = self:SteamID() SS.Profiles[steamid] = {} self:ChatPrint("Loading your profile") if DB_DEVS then self:ProfileLoaded() return end timer.Simple(30, function() if self and self:IsValid() and !self:IsProfileLoaded() then self:ChatPrint("Your profile seems to be having problems loading. Our appologies.") end end) DB_Query("SELECT "..table.concat(selects, ", ").." FROM users WHERE steamid='"..string.sub(steamid, 7).."'", function(data) if self and self:IsValid() then self:ProfileLoaded(data) end end, function() if self and self:IsValid() then self.ProfileFailed = true self:ChatPrint("We failed to load your profile, trying again in 60 seconds.") timer.Simple(60, function() if self and self:IsValid() then self:ProfileLoad() end end ) end end) end function PLAYER_META:ProfileLoaded(res) local steamid = self:SteamID() if res and res[1] then if res[2] then Error("Duplicate profile! Contact a developer! ("..steam..")") return end self.profile = res[1] MsgN("[PROFILE] Loaded ", self) self:SetRank(self.profile.rank) self:SetMoney(self.profile.money) self:SetExp(self.profile.exp) self:SetStoreItems(self.profile.store) self:SetEquipped(self.profile.equipped) self:NetworkOwnedItem() if !self:HasMoney(0) then self:SetMoney(0) self:ChatPrint("Oops! You have negative money, we set that to 0 for you. Please tell a developer how this happened!") end self:ChatPrint("Your profile has been loaded") elseif res and !res[1] then self:ChatPrint("No profile detected, creating one for you.") self:CreateProfile() return else self.profile = {} self.profile.lastLoginIp = self:IPAddress() self.profile.lastLoginTimestamp = os.time() self:SetRank(DB_DEVS and 100 or 0) self:SetMoney(100) self:SetExp(1) self:SetStoreItems("") self:SetEquipped("") self:ChatPrint("We had problems loading your profile and have created a temporary one for you.") end self.profile.playtime = self.profile.playtime or 0 -- Make sure it isn't nil self.playtimeStart = os.time() self.profile.lastLoginIp = self:IPAddress() self.profile.lastLoginTimestamp = os.time() SS.Profiles[self:SteamID()] = self.profile self:CheckAvatar() timer.Create(self:SteamID().."_ProfileUpdate", 120, 0, function() if self and self:IsValid() then self.profile.lastLoginTimestamp = os.time() self.profile.playtime = self.profile.playtime+(os.time()-self.playtimeStart) self.playtimeStart = os.time() self:ProfileSave() else timer.Destroy(steamid.."_ProfileUpdate") end end ) hook.Run("PlayerSetModel", self) self:SetNetworkedBool("ss_profileloaded", true) end /* Sync Profile with database */ function PLAYER_META:ProfileSave() if(self:IsBot()) then return end local profile = SS.Profiles[self:SteamID()] profile.money = self.money profile.exp = self.exp profile.playtime = profile.playtime+(os.time()-self.playtimeStart) profile.store = util.TableToJSON(self.storeItems) profile.equipped = util.TableToJSON(self.storeEquipped) self.playtimeStart = os.time() local Query = "UPDATE users SET " local first = true for k,v in pairs(profile) do if table.HasValue(update_filter, k) then continue end -- We don't want to automatically update these. if first then Query = Query..k.."='"..v.."'" first = false else Query = Query..", "..k.."='"..v.."'" end end Query = Query.." WHERE steamid='"..string.sub(self:SteamID(), 7).."'" DB_Query(Query) end function PLAYER_META:ProfileUpdate(col, val) -- Don't be an idiot with this if(self:IsBot()) then return end if !SERVER then return end DB_Query("UPDATE users SET "..tostring(col).."='"..tostring(val).."' WHERE steamid='"..string.sub(self:SteamID(), 7).."'" ) end -------------------------------------------------- -- -------------------------------------------------- function PLAYER_META:SetStoreItems(data) if (!data or data == "" or data == "[]") then self.storeItems = {} else self.storeItems = util.JSONToTable(data) end end -------------------------------------------------- -- -------------------------------------------------- function PLAYER_META:SetEquipped(data) if (!data or data == "" or data == "[]") then self.storeEquipped = {} for i = 1, SS.STORE.SLOT.MAXIMUM do self.storeEquipped[i] = {} end else self.storeEquipped = util.JSONToTable(data) end end
--------------------------- -- Bunny Hop -- -- Created by xAaron113x -- --------------------------- local selects = {"exp", "id", "steamId64", "lastLoginIp", "playtime", "lastLoginTimestamp", "steamId", "rank", "name", "money", "store", "equipped", "avatarUrl"} local update_filter = {"id", "steamId", "rank", "avatarUrl"} SS.Profiles = {} -- Check if the player has a valid avatar url stored in the database, if not fetch it. function PLAYER_META:CheckAvatar() if self.profile and (!self.profile.avatarUrl or string.Trim(self.profile.avatarUrl) == "" or string.match(self.profile.avatarUrl, "_full.jpg")) then http.Fetch("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=9D7A9B8269C1C1B1B7B21E659904DDEF&steamids="..self.profile.steamId64, function(body) if self and self:IsValid() then body = util.JSONToTable(body) DB_Query("UPDATE users SET avatarUrl='"..body.response.players[1].avatar.."' WHERE steamId='"..string.sub(self:SteamID(), 7).."'") end end, function(error) Error("[AVATAR FETCH FAILED] ".. error) end ) end end function PLAYER_META:CreateProfile() if(self:IsBot()) then return end local ip = string.Replace(game.IsDedicated() and self:IPAddress() or "127.0.0.1", ".", "") local query = "INSERT INTO users (steamid64, steamid, name, registerIp, lastLoginIP, registerTimestamp, lastLoginTimestamp) VALUES ('"..self:SteamID64().."','"..string.sub(self:SteamID(), 7).."','"..DB:escape(self:Name()).."','"..ip.."','"..ip.."','"..tostring(os.time()).."','"..tostring(os.time()).."')" DB_Query(query, function() if self and self:IsValid() then self:ProfileLoad() end end) end function PLAYER_META:ProfileLoad() if(self:IsBot()) then return end MsgN("[PROFILE] Loading ", self) local steamid = self:SteamID() SS.Profiles[steamid] = {} self:ChatPrint("Loading your profile") if DB_DEVS then self:ProfileLoaded() return end timer.Simple(30, function() if self and self:IsValid() and !self:IsProfileLoaded() then self:ChatPrint("Your profile seems to be having problems loading. Our appologies.") end end) DB_Query("SELECT "..table.concat(selects, ", ").." FROM users WHERE steamid='"..string.sub(steamid, 7).."'", function(data) if self and self:IsValid() then self:ProfileLoaded(data) end end, function() if self and self:IsValid() then self.ProfileFailed = true self:ChatPrint("We failed to load your profile, trying again in 60 seconds.") timer.Simple(60, function() if self and self:IsValid() then self:ProfileLoad() end end ) end end) end function PLAYER_META:ProfileLoaded(res) local steamid = self:SteamID() if res and res[1] then if res[2] then Error("Duplicate profile! Contact a developer! ("..steam..")") return end self.profile = res[1] MsgN("[PROFILE] Loaded ", self) self:SetRank(self.profile.rank) self:SetMoney(self.profile.money) self:SetExp(self.profile.exp) self:SetStoreItems(self.profile.store) self:SetEquipped(self.profile.equipped) self:NetworkOwnedItem() if !self:HasMoney(0) then self:SetMoney(0) self:ChatPrint("Oops! You have negative money, we set that to 0 for you. Please tell a developer how this happened!") end self:ChatPrint("Your profile has been loaded") elseif res and !res[1] then self:ChatPrint("No profile detected, creating one for you.") self:CreateProfile() return else self.profile = {} self.profile.lastLoginIp = self:IPAddress() self.profile.lastLoginTimestamp = os.time() self:SetRank(DB_DEVS and 100 or 0) self:SetMoney(100) self:SetExp(1) self:SetStoreItems("") self:SetEquipped("") self:ChatPrint("We had problems loading your profile and have created a temporary one for you.") end self.profile.playtime = self.profile.playtime or 0 -- Make sure it isn't nil self.playtimeStart = os.time() self.profile.lastLoginIp = self:IPAddress() self.profile.lastLoginTimestamp = os.time() SS.Profiles[self:SteamID()] = self.profile self:CheckAvatar() timer.Create(self:SteamID().."_ProfileUpdate", 120, 0, function() if self and self:IsValid() then self.profile.lastLoginTimestamp = os.time() self.profile.playtime = self.profile.playtime+(os.time()-self.playtimeStart) self.playtimeStart = os.time() self:ProfileSave() else timer.Destroy(steamid.."_ProfileUpdate") end end ) hook.Run("PlayerSetModel", self) self:SetNetworkedBool("ss_profileloaded", true) end /* Sync Profile with database */ function PLAYER_META:ProfileSave() if(self:IsBot()) then return end local profile = SS.Profiles[self:SteamID()] profile.money = self.money profile.exp = self.exp profile.playtime = profile.playtime+(os.time()-self.playtimeStart) profile.store = util.TableToJSON(self.storeItems) profile.equipped = util.TableToJSON(self.storeEquipped) self.playtimeStart = os.time() local Query = "UPDATE users SET " local first = true for k,v in pairs(profile) do if table.HasValue(update_filter, k) then continue end -- We don't want to automatically update these. if first then Query = Query..k.."='"..v.."'" first = false else Query = Query..", "..k.."='"..v.."'" end end Query = Query.." WHERE steamid='"..string.sub(self:SteamID(), 7).."'" DB_Query(Query) end function PLAYER_META:ProfileUpdate(col, val) -- Don't be an idiot with this if(self:IsBot()) then return end if !SERVER then return end DB_Query("UPDATE users SET "..tostring(col).."='"..tostring(val).."' WHERE steamid='"..string.sub(self:SteamID(), 7).."'" ) end -------------------------------------------------- -- -------------------------------------------------- function PLAYER_META:SetStoreItems(data) if (!data or data == "" or data == "[]") then self.storeItems = {} else self.storeItems = util.JSONToTable(data) end end -------------------------------------------------- -- -------------------------------------------------- function PLAYER_META:SetEquipped(data) if (!data or data == "" or data == "[]") then self.storeEquipped = {} for i = 1, SS.STORE.SLOT.MAXIMUM do self.storeEquipped[i] = {} end else self.storeEquipped = util.JSONToTable(data) end end
Profile fixed this time... I TESTED IT!
Profile fixed this time... I TESTED IT!
Lua
bsd-3-clause
T3hArco/skeyler-gamemodes
a774322bb4bf1d84fce1d6d86083ca8232d66d00
linux/.config/nvim/lua/nvimtree.lua
linux/.config/nvim/lua/nvimtree.lua
require'nvim-tree'.setup { disable_netrw = true, hijack_netrw = true, open_on_setup = false, ignore_ft_on_setup = {}, -- auto_close = false, open_on_tab = false, hijack_cursor = false, update_cwd = false, update_to_buf_dir = { enable = true, auto_open = true, }, diagnostics = { enable = false, icons = { hint = "", info = "", warning = "", error = "", } }, update_focused_file = { enable = false, update_cwd = false, ignore_list = {} }, system_open = { cmd = nil, args = {} }, filters = { dotfiles = false, custom = {} }, view = { width = 30, height = 30, hide_root_folder = false, side = 'left', auto_resize = false, mappings = { custom_only = false, list = {} } } }
require'nvim-tree'.setup { disable_netrw = true, hijack_netrw = true, open_on_setup = false, ignore_ft_on_setup = {}, -- auto_close = false, open_on_tab = false, hijack_cursor = false, update_cwd = false, hijack_directories = { enable = true, auto_open = true, }, diagnostics = { enable = false, icons = { hint = "", info = "", warning = "", error = "", } }, update_focused_file = { enable = false, update_cwd = false, ignore_list = {} }, system_open = { cmd = nil, args = {} }, filters = { dotfiles = false, custom = {} }, view = { width = 30, height = 30, hide_root_folder = false, side = 'left', mappings = { custom_only = false, list = {} } }, actions = { open_file = { resize_window = false } } }
Fix nvimtree deprecated config values
Fix nvimtree deprecated config values
Lua
mit
joserc87/config-files,joserc87/config-files,joserc87/config-files
d4defe253efb83cce09fd7cc7693cbf896e0fd6e
lua/weapons/disguiser/cl_fxfake.lua
lua/weapons/disguiser/cl_fxfake.lua
/** * Disguiser SWEP - Lets you disguise as any prop on a map. * * File: * cl_fxfake.lua * * Purpose: * Fake shoot effect on client-side via a trigger from server-side, as * for some reason on multiplayer servers the effect is not rendered on * client-side automatically. * * Copyright (C) 2013 Carl Kittelberger (Icedream) * * 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/>. */ usermessage.Hook("disguiserShootFX", function(um) local hitpos = um:ReadVector(), hitnormal = um:ReadVectorNormal(), entity = um:ReadEntity(), physbone = um:ReadLong(), bFirstTimePredicted = um:ReadBool() // Player and weapon valid? if !IsValid(LocalPlayer()) || !IsValid(LocalPlayer():GetWeapon("disguiser")) then return false end // Render shoot effect LocalPlayer():GetWeapon("disguiser").DoShootEffect( hitpos, hitnormal, entity, physbone, bFirstTimePredicted) end)
/** * Disguiser SWEP - Lets you disguise as any prop on a map. * * File: * cl_fxfake.lua * * Purpose: * Fake shoot effect on client-side via a trigger from server-side, as * for some reason on multiplayer servers the effect is not rendered on * client-side automatically. * * Copyright (C) 2013 Carl Kittelberger (Icedream) * * 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/>. */ usermessage.Hook("disguiserShootFX", function(um) local hitpos = um:ReadVector() local hitnormal = um:ReadVectorNormal() local entity = um:ReadEntity() local physbone = um:ReadLong() local bFirstTimePredicted = um:ReadBool() // Player and weapon valid? if !IsValid(LocalPlayer()) || !IsValid(LocalPlayer():GetWeapon("disguiser")) then return false end // Render shoot effect LocalPlayer():GetWeapon("disguiser").DoShootEffect( hitpos, hitnormal, entity, physbone, bFirstTimePredicted) end)
Sorry, I was too lazy. Fixed '=' syntax error.
Sorry, I was too lazy. Fixed '=' syntax error.
Lua
agpl-3.0
icedream/gmod-disguiser
ee586d82113a2018d36f6fd1ff75387b4ea6d11d
testserver/base/keys.lua
testserver/base/keys.lua
require("base.doors") module("base.keys", package.seeall) --[[ LockDoor Lock a door. This function checks if that item is a closed on that can be locked. It does not check if the player has a fitting key. @param ItemStruct - the item that is the closed door that shall be locked @return boolean - true in case the door got locked, false if anything went wrong ]] function LockDoor(Door) if base.doors.CheckClosedDoor(Door.id) then if (Door.quality == 233 and Door:getData("lockData") ~= "") then Door.quality = 333; world:changeItem(Door); world:makeSound(19, Door.pos); return true; else return false; end; else return false; end; return false; end; --[[ UnlockDoor Unlock a door. This function checks if the item is a closed locked door and unlocks it. It does not check if the player has a fitting key. @param ItemStruct - the item that is the closed door that shall be unlocked @return boolean - true in case the door got locked, false if anything went wrong ]] function UnlockDoor(Door) if base.doors.CheckClosedDoor(Door.id) then if (Door.quality ~= 233 and Door:getData("lockData") ~= "") then Door.quality = 233; world:changeItem(Door); world:makeSound(20, Door.pos); return true; else return false; end; else return false; end; return false; end; --[[ CheckKey Check if a key fits into a door. This function does not check if the item is really a key. It assumes that it is one and checks the lock that is encoded in the data value. How ever it checks if the door item is a opened or a closed door. @param ItemStruct - the item that is the key for a door @param ItemStruct - the item that is the door that shall be checked @return boolean - true in case the key item would fit to the door, false if it does not fit ]] function CheckKey(Key, Door) if base.doors.CheckClosedDoor(Door.id) or base.doors.CheckOpenDoor(Door.id) then if (Key:getData("lockData") == Door:getData("lockData") and Door:getData("lockData") ~= nil) then return true; else return false; end; else return false; end; end;
require("base.doors") module("base.keys", package.seeall) --[[ LockDoor Lock a door. This function checks if that item is a closed on that can be locked. It does not check if the player has a fitting key. @param ItemStruct - the item that is the closed door that shall be locked @return boolean - true in case the door got locked, false if anything went wrong ]] function LockDoor(Door) if base.doors.CheckClosedDoor(Door.id) then if (Door.quality == 233 and Door:getData("lockData") ~= "") then Door.quality = 333; world:changeItem(Door); world:makeSound(19, Door.pos); return true; else return false; end; else return false; end; end; --[[ UnlockDoor Unlock a door. This function checks if the item is a closed locked door and unlocks it. It does not check if the player has a fitting key. @param ItemStruct - the item that is the closed door that shall be unlocked @return boolean - true in case the door got locked, false if anything went wrong ]] function UnlockDoor(Door) if base.doors.CheckClosedDoor(Door.id) then if (Door.quality ~= 233 and Door:getData("lockData") ~= "") then Door.quality = 233; world:changeItem(Door); world:makeSound(20, Door.pos); return true; else return false; end; else return false; end; end; --[[ CheckKey Check if a key fits into a door. This function does not check if the item is really a key. It assumes that it is one and checks the lock that is encoded in the data value. How ever it checks if the door item is a opened or a closed door. @param ItemStruct - the item that is the key for a door @param ItemStruct - the item that is the door that shall be checked @return boolean - true in case the key item would fit to the door, false if it does not fit ]] function CheckKey(Key, Door) if base.doors.CheckClosedDoor(Door.id) or base.doors.CheckOpenDoor(Door.id) then if (Key:getData("lockData") == Door:getData("lockData") and Door:getData("lockData") ~= nil) then return true; else return false; end; else return false; end; end;
fixed unlocking of doors
fixed unlocking of doors
Lua
agpl-3.0
Baylamon/Illarion-Content,KayMD/Illarion-Content,LaFamiglia/Illarion-Content,Illarion-eV/Illarion-Content,vilarion/Illarion-Content
bbd0ff39ad2134907759daa1aee3a26d1d2a7f12
lib/image_loader.lua
lib/image_loader.lua
local gm = require 'graphicsmagick' local ffi = require 'ffi' require 'pl' local image_loader = {} function image_loader.decode_float(blob) local im, alpha = image_loader.decode_byte(blob) if im then im = im:float():div(255) end return im, alpha end function image_loader.encode_png(rgb, alpha) if rgb:type() == "torch.ByteTensor" then rgb = rgb:float():div(255) end if alpha then if not (alpha:size(2) == rgb:size(2) and alpha:size(3) == rgb:size(3)) then alpha = gm.Image(alpha, "I", "DHW"):size(rgb:size(3), rgb:size(2), "SincFast"):toTensor("float", "I", "DHW") end local rgba = torch.Tensor(4, rgb:size(2), rgb:size(3)) rgba[1]:copy(rgb[1]) rgba[2]:copy(rgb[2]) rgba[3]:copy(rgb[3]) rgba[4]:copy(alpha) local im = gm.Image():fromTensor(rgba, "RGBA", "DHW") im:format("png") return im:toBlob(9) else local im = gm.Image(rgb, "RGB", "DHW") im:format("png") return im:toBlob(9) end end function image_loader.save_png(filename, rgb, alpha) local blob, len = image_loader.encode_png(rgb, alpha) local fp = io.open(filename, "wb") fp:write(ffi.string(blob, len)) fp:close() return true end function image_loader.decode_byte(blob) local load_image = function() local im = gm.Image() local alpha = nil im:fromBlob(blob, #blob) -- FIXME: How to detect that a image has an alpha channel? if blob:sub(1, 4) == "\x89PNG" or blob:sub(1, 3) == "GIF" then -- split alpha channel im = im:toTensor('float', 'RGBA', 'DHW') local sum_alpha = (im[4] - 1.0):sum() if sum_alpha < 0 then alpha = im[4]:reshape(1, im:size(2), im:size(3)) end local new_im = torch.FloatTensor(3, im:size(2), im:size(3)) new_im[1]:copy(im[1]) new_im[2]:copy(im[2]) new_im[3]:copy(im[3]) im = new_im:mul(255):byte() else im = im:toTensor('byte', 'RGB', 'DHW') end return {im, alpha} end load_image() local state, ret = pcall(load_image) if state then return ret[1], ret[2] else return nil end end function image_loader.load_float(file) local fp = io.open(file, "rb") if not fp then error(file .. ": failed to load image") end local buff = fp:read("*a") fp:close() return image_loader.decode_float(buff) end function image_loader.load_byte(file) local fp = io.open(file, "rb") if not fp then error(file .. ": failed to load image") end local buff = fp:read("*a") fp:close() return image_loader.decode_byte(buff) end local function test() require 'image' local img img = image_loader.load_float("./a.jpg") if img then print(img:min()) print(img:max()) image.display(img) end img = image_loader.load_float("./b.png") if img then image.display(img) end end --test() return image_loader
local gm = require 'graphicsmagick' local ffi = require 'ffi' require 'pl' local image_loader = {} function image_loader.decode_float(blob) local im, alpha = image_loader.decode_byte(blob) if im then im = im:float():div(255) end return im, alpha end function image_loader.encode_png(rgb, alpha) if rgb:type() == "torch.ByteTensor" then rgb = rgb:float():div(255) end if alpha then if not (alpha:size(2) == rgb:size(2) and alpha:size(3) == rgb:size(3)) then alpha = gm.Image(alpha, "I", "DHW"):size(rgb:size(3), rgb:size(2), "SincFast"):toTensor("float", "I", "DHW") end local rgba = torch.Tensor(4, rgb:size(2), rgb:size(3)) rgba[1]:copy(rgb[1]) rgba[2]:copy(rgb[2]) rgba[3]:copy(rgb[3]) rgba[4]:copy(alpha) local im = gm.Image():fromTensor(rgba, "RGBA", "DHW") im:format("png") return im:toBlob(9) else local im = gm.Image(rgb, "RGB", "DHW") im:format("png") return im:toBlob(9) end end function image_loader.save_png(filename, rgb, alpha) local blob, len = image_loader.encode_png(rgb, alpha) local fp = io.open(filename, "wb") fp:write(ffi.string(blob, len)) fp:close() return true end function image_loader.decode_byte(blob) local load_image = function() local im = gm.Image() local alpha = nil im:fromBlob(blob, #blob) if im:colorspace() == "CMYK" then im:colorspace("RGB") end -- FIXME: How to detect that a image has an alpha channel? if blob:sub(1, 4) == "\x89PNG" or blob:sub(1, 3) == "GIF" then -- split alpha channel im = im:toTensor('float', 'RGBA', 'DHW') local sum_alpha = (im[4] - 1.0):sum() if sum_alpha < 0 then alpha = im[4]:reshape(1, im:size(2), im:size(3)) end local new_im = torch.FloatTensor(3, im:size(2), im:size(3)) new_im[1]:copy(im[1]) new_im[2]:copy(im[2]) new_im[3]:copy(im[3]) im = new_im:mul(255):byte() else im = im:toTensor('byte', 'RGB', 'DHW') end return {im, alpha} end load_image() local state, ret = pcall(load_image) if state then return ret[1], ret[2] else return nil end end function image_loader.load_float(file) local fp = io.open(file, "rb") if not fp then error(file .. ": failed to load image") end local buff = fp:read("*a") fp:close() return image_loader.decode_float(buff) end function image_loader.load_byte(file) local fp = io.open(file, "rb") if not fp then error(file .. ": failed to load image") end local buff = fp:read("*a") fp:close() return image_loader.decode_byte(buff) end local function test() require 'image' local img img = image_loader.load_float("./a.jpg") if img then print(img:min()) print(img:max()) image.display(img) end img = image_loader.load_float("./b.png") if img then image.display(img) end end --test() return image_loader
Fix handling for CMYK JPEG
Fix handling for CMYK JPEG
Lua
mit
zyhkz/waifu2x,vitaliylag/waifu2x,higankanshi/waifu2x,nagadomi/waifu2x,zyhkz/waifu2x,vitaliylag/waifu2x,higankanshi/waifu2x,Spitfire1900/upscaler,zyhkz/waifu2x,Spitfire1900/upscaler,nagadomi/waifu2x,higankanshi/waifu2x,nagadomi/waifu2x,nagadomi/waifu2x,nagadomi/waifu2x,zyhkz/waifu2x,vitaliylag/waifu2x
0297f26b657b4aec2fb1e8d3f987f98d1c4c9c07
lib/resty/auto-ssl/utils/shell_execute.lua
lib/resty/auto-ssl/utils/shell_execute.lua
local shell = require "resty.auto-ssl.vendor.shell" local start_sockproc = require "resty.auto-ssl.utils.start_sockproc" return function(command) -- Make sure the sockproc has started before trying to execute any commands -- (since it's started by only a single worker in init_worker, it's possible -- other workers have already finished their init_worker phases before the -- process is actually started). if not ngx.shared.auto_ssl:get("sockproc_started") then start_sockproc() local wait_time = 0 local sleep_time = 0.01 local max_time = 5 while not ngx.shared.auto_ssl:get("sockproc_started") do ngx.sleep(sleep_time) wait_time = wait_time + sleep_time if wait_time > max_time then break end end end local status, out, err = shell.execute(command) -- If the script fails due to a missing sockproc socket, try starting up -- the sockproc process again and then retry. if status ~= 0 and err == "no such file or directory" then ngx.log(ngx.ERR, "auto-ssl: sockproc unexpectedly not available, trying to restart") start_sockproc(true) status, out, err = shell.execute(command, { timeout = 60 }) end return status, out, err end
local shell = require "resty.auto-ssl.vendor.shell" local start_sockproc = require "resty.auto-ssl.utils.start_sockproc" return function(command) -- Make sure the sockproc has started before trying to execute any commands -- (since it's started by only a single worker in init_worker, it's possible -- other workers have already finished their init_worker phases before the -- process is actually started). if not ngx.shared.auto_ssl:get("sockproc_started") then start_sockproc() local wait_time = 0 local sleep_time = 0.01 local max_time = 5 while not ngx.shared.auto_ssl:get("sockproc_started") do ngx.sleep(sleep_time) wait_time = wait_time + sleep_time if wait_time > max_time then break end end end local options = { timeout = 60 } local status, out, err = shell.execute(command, options) -- If the script fails due to a missing sockproc socket, try starting up -- the sockproc process again and then retry. if status ~= 0 and err == "no such file or directory" then ngx.log(ngx.ERR, "auto-ssl: sockproc unexpectedly not available, trying to restart") start_sockproc(true) status, out, err = shell.execute(command, options) end return status, out, err end
Fix default shell timeout not actually being increased.
Fix default shell timeout not actually being increased. We had intended to increase the timeout we allow the dehydrated shell script to run beyond the default 15 seconds back in 1f395c66 (see https://github.com/GUI/lua-resty-auto-ssl/issues/11). However, that timeout increase wasn't actually being applied correctly. It was only being applied on the second `shell.execute` command, which only gets called under certain failure scenarios. This meant that the default 15 second timeout was still largely in place. Again, hopefully certificate registration won't generally take 15 seconds, but this should help account for random slowdowns. This should also hopefully fix intermittent test failures we've seen.
Lua
mit
GUI/lua-resty-auto-ssl,UseFedora/lua-resty-auto-ssl,UseFedora/lua-resty-auto-ssl
9615be6e0324bfb711e56b1bd7bebd5eed5f4ed3
popups.lua
popups.lua
local mod = EPGP:NewModule("EPGP_Popups") local L = LibStub("AceLocale-3.0"):GetLocale("EPGP") local GPTooltip = EPGP:GetModule("EPGP_GPTooltip") local function EPGP_CONFIRM_GP_CREDIT_UpdateButtons(self) local link = self.itemFrame.link local gp = tonumber(self.editBox:GetText()) if EPGP:CanIncGPBy(link, gp) then self.button1:Enable() self.button3:Enable() else self.button1:Disable() self.button3:Disable() end end local blizzardAnchors = {} local function savePoint(frame, i) local point, relativeTo, relativePoint, x, y = frame:GetPoint(i) if point then tinsert(blizzardAnchors, {frame, point, relativeTo, relativePoint, x, y}) end end local function makeAnchorTable(itemFrame, editBox, button1) for i=1,itemFrame:GetNumPoints() do savePoint(itemFrame, i) end for i=1,editBox:GetNumPoints() do savePoint(editBox, i) end for i=1,button1:GetNumPoints() do savePoint(button1, i) end end StaticPopupDialogs["EPGP_CONFIRM_GP_CREDIT"] = { text = L["Credit GP to %s"], button1 = ACCEPT, button2 = CANCEL, timeout = 0, whileDead = 1, maxLetters = 16, hideOnEscape = 1, hasEditBox = 1, hasItemFrame = 1, OnAccept = function(self) local link = self.itemFrame.link local gp = tonumber(self.editBox:GetText()) EPGP:IncGPBy(self.name, link, gp) end, OnCancel = function(self) self:Hide() ClearCursor() end, OnShow = function(self) local itemFrame = getglobal(self:GetName().."ItemFrame") local editBox = getglobal(self:GetName().."EditBox") local button1 = getglobal(self:GetName().."Button1") if #blizzardAnchors == 0 then makeAnchorTable(itemFrame, editBox, button1) end itemFrame:SetPoint("TOPLEFT", 35, -35) editBox:SetPoint("TOPLEFT", itemFrame, "TOPRIGHT", 150, -10) editBox:SetPoint("RIGHT", -35, 0) button1:SetPoint("TOPRIGHT", itemFrame, "BOTTOMRIGHT", 85, -6) local gp1, gp2 = GPTooltip:GetGPValue(itemFrame.link) if gp1 then if gp2 then editBox:SetText(L["%d or %d"]:format(gp1, gp2)) else editBox:SetText(gp1) end end editBox:HighlightText() EPGP_CONFIRM_GP_CREDIT_UpdateButtons(self) end, OnHide = function(self) local itemFrame = getglobal(self:GetName().."ItemFrame") local editBox = getglobal(self:GetName().."EditBox") local button1 = getglobal(self:GetName().."Button1") -- Clear anchor points of frames that we modified, and revert them. itemFrame:ClearAllPoints() editBox:ClearAllPoints() button1:ClearAllPoints() for p=1,#blizzardAnchors do local frame, point, relativeTo, relativePoint, x, y = unpack(blizzardAnchors[p]) frame:SetPoint(point, relativeTo, relativePoint, x, y) end if ChatFrameEditBox:IsShown() then ChatFrameEditBox:SetFocus() end end, EditBoxOnEnterPressed = function(self) local parent = self:GetParent() local link = parent.itemFrame.link local gp = tonumber(parent.editBox:GetText()) if EPGP:CanIncGPBy(link, gp) then EPGP:IncGPBy(parent.name, link, gp) parent:Hide() end end, EditBoxOnTextChanged = function(self) local parent = self:GetParent() EPGP_CONFIRM_GP_CREDIT_UpdateButtons(parent) end, EditBoxOnEscapePressed = function(self) self:GetParent():Hide() ClearCursor() end } StaticPopupDialogs["EPGP_DECAY_EPGP"] = { text = "", button1 = ACCEPT, button2 = CANCEL, timeout = 0, hideOnEscape = 1, whileDead = 1, OnShow = function() local text = getglobal(this:GetName().."Text") text:SetFormattedText(L["Decay EP and GP by %d%%?"], EPGP:GetDecayPercent()) end, OnAccept = function() EPGP:DecayEPGP() end } StaticPopupDialogs["EPGP_RESET_EPGP"] = { text = L["Reset all main toons' EP and GP to 0?"], button1 = ACCEPT, button2 = CANCEL, timeout = 0, hideOnEscape = 1, whileDead = 1, OnAccept = function() EPGP:ResetEPGP() end } local function Debug(fmt, ...) DEFAULT_CHAT_FRAME:AddMessage(string.format(fmt, ...)) end function mod:OnInitialize() -- local playername = UnitName("player") -- local itemName, itemLink, itemRarity, _, _, _, _, _, _, itemTexture = GetItemInfo(34541) -- local r, g, b = GetItemQualityColor(itemRarity); -- Debug("ItemName: %s ItemLink: %s ItemRarity: %d ItemTexture: %s", -- itemName, itemLink, itemRarity, itemTexture) -- local dialog = StaticPopup_Show("EPGP_CONFIRM_GP_CREDIT", playername, "", { -- texture = itemTexture, -- name = itemName, -- color = {r, g, b, 1}, -- link = itemLink -- }) -- if dialog then -- dialog.name = playername -- end end
local mod = EPGP:NewModule("EPGP_Popups") local L = LibStub("AceLocale-3.0"):GetLocale("EPGP") local GPTooltip = EPGP:GetModule("EPGP_GPTooltip") local function EPGP_CONFIRM_GP_CREDIT_UpdateButtons(self) local link = self.itemFrame.link local gp = tonumber(self.editBox:GetText()) if EPGP:CanIncGPBy(link, gp) then self.button1:Enable() self.button3:Enable() else self.button1:Disable() self.button3:Disable() end end local function SaveAnchors(t, ...) for n=1,select('#', ...) do local frame = select(n, ...) for i=1,frame:GetNumPoints() do local point, relativeTo, relativePoint, x, y = frame:GetPoint(i) if point then table.insert(t, {frame, point, relativeTo, relativePoint, x, y }) end end end end local function RestoreAnchors(t) for i=1,#t do local frame, point, relativeTo, relativePoint, x, y = unpack(t[i]) frame:SetPoint(point, relativeTo, relativePoint, x, y) end end local blizzardPopupAnchors = {} StaticPopupDialogs["EPGP_CONFIRM_GP_CREDIT"] = { text = L["Credit GP to %s"], button1 = ACCEPT, button2 = CANCEL, timeout = 0, whileDead = 1, maxLetters = 16, hideOnEscape = 1, hasEditBox = 1, hasItemFrame = 1, OnAccept = function(self) local link = self.itemFrame.link local gp = tonumber(self.editBox:GetText()) EPGP:IncGPBy(self.name, link, gp) end, OnCancel = function(self) self:Hide() ClearCursor() end, OnShow = function(self) local itemFrame = getglobal(self:GetName().."ItemFrame") local editBox = getglobal(self:GetName().."EditBox") local button1 = getglobal(self:GetName().."Button1") if not blizzardPopupAnchors[self] then blizzardPopupAnchors[self] = {} SaveAnchors(blizzardPopupAnchors[self], itemFrame, editBox, button1) end itemFrame:SetPoint("TOPLEFT", 35, -35) editBox:SetPoint("TOPLEFT", itemFrame, "TOPRIGHT", 150, -10) editBox:SetPoint("RIGHT", -35, 0) button1:SetPoint("TOPRIGHT", itemFrame, "BOTTOMRIGHT", 85, -6) local gp1, gp2 = GPTooltip:GetGPValue(itemFrame.link) if gp1 then if gp2 then editBox:SetText(L["%d or %d"]:format(gp1, gp2)) else editBox:SetText(gp1) end end editBox:HighlightText() EPGP_CONFIRM_GP_CREDIT_UpdateButtons(self) end, OnHide = function(self) local itemFrame = getglobal(self:GetName().."ItemFrame") local editBox = getglobal(self:GetName().."EditBox") local button1 = getglobal(self:GetName().."Button1") -- Clear anchor points of frames that we modified, and revert them. itemFrame:ClearAllPoints() editBox:ClearAllPoints() button1:ClearAllPoints() RestoreAnchors(blizzardPopupAnchors[self]) if ChatFrameEditBox:IsShown() then ChatFrameEditBox:SetFocus() end end, EditBoxOnEnterPressed = function(self) local parent = self:GetParent() local link = parent.itemFrame.link local gp = tonumber(parent.editBox:GetText()) if EPGP:CanIncGPBy(link, gp) then EPGP:IncGPBy(parent.name, link, gp) parent:Hide() end end, EditBoxOnTextChanged = function(self) local parent = self:GetParent() EPGP_CONFIRM_GP_CREDIT_UpdateButtons(parent) end, EditBoxOnEscapePressed = function(self) self:GetParent():Hide() ClearCursor() end } StaticPopupDialogs["EPGP_DECAY_EPGP"] = { text = "", button1 = ACCEPT, button2 = CANCEL, timeout = 0, hideOnEscape = 1, whileDead = 1, OnShow = function() local text = getglobal(this:GetName().."Text") text:SetFormattedText(L["Decay EP and GP by %d%%?"], EPGP:GetDecayPercent()) end, OnAccept = function() EPGP:DecayEPGP() end } StaticPopupDialogs["EPGP_RESET_EPGP"] = { text = L["Reset all main toons' EP and GP to 0?"], button1 = ACCEPT, button2 = CANCEL, timeout = 0, hideOnEscape = 1, whileDead = 1, OnAccept = function() EPGP:ResetEPGP() end }
Remove debug code. Refactor the code to be more readbale, more generic, and shorter. Also fix a bug: There are multiple popup frames. We save references to UIObjects so in the OnHide function when we restore the anchors we always restore the anchors of the first frame that popped up and got backed up, even if we are in another popup. This is fixed by doing a backup for each popup frame we see for the first time.
Remove debug code. Refactor the code to be more readbale, more generic, and shorter. Also fix a bug: There are multiple popup frames. We save references to UIObjects so in the OnHide function when we restore the anchors we always restore the anchors of the first frame that popped up and got backed up, even if we are in another popup. This is fixed by doing a backup for each popup frame we see for the first time.
Lua
bsd-3-clause
protomech/epgp-dkp-reloaded,ceason/epgp-tfatf,ceason/epgp-tfatf,protomech/epgp-dkp-reloaded,hayword/tfatf_epgp,hayword/tfatf_epgp,sheldon/epgp,sheldon/epgp
fe1bbe8ce7190d874069e3f9605bf4892e6b2bdf
modules/admin-mini/luasrc/model/cbi/mini/wifi.lua
modules/admin-mini/luasrc/model/cbi/mini/wifi.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Copyright 2008 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("wireless", translate("wifi"), translate("a_w_devices1")) s = m:section(TypedSection, "wifi-device", translate("devices")) en = s:option(Flag, "disabled", translate("enable")) en.enabled = "0" en.disabled = "1" mode = s:option(ListValue, "mode", translate("mode")) mode:value("", "standard") mode:value("11b", "802.11b") mode:value("11g", "802.11g") mode:value("11a", "802.11a") mode:value("11bg", "802.11b+g") mode.rmempty = true s:option(Value, "channel", translate("a_w_channel")) s = m:section(TypedSection, "wifi-iface", translate("m_n_local")) s.anonymous = true s:option(Value, "ssid", translate("a_w_netid")).maxlength = 32 local devs = {} luci.model.uci.foreach("wireless", "wifi-device", function (section) table.insert(devs, section[".name"]) end) if #devs > 1 then device = s:option(DummyValue, "device", translate("device")) else s.defaults.device = devs[1] end mode = s:option(ListValue, "mode", translate("mode")) mode:value("ap", translate("m_w_ap")) mode:value("adhoc", translate("m_w_adhoc")) mode:value("sta", translate("m_w_client")) function mode.write(self, section, value) if value == "sta" then -- ToDo: Move this away if not luci.model.uci.get("network", "wan") then luci.model.uci.set("network", "wan", "proto", "none") luci.model.uci.set("network", "wan", "ifname", " ") end luci.model.uci.set("network", "wan", "_ifname", luci.model.uci.get("network", "wan", "ifname") or " ") luci.model.uci.set("network", "wan", "ifname", " ") luci.model.uci.save("network") luci.model.uci.unload("network") self.map:set(section, "network", "wan") else if luci.model.uci.get("network", "wan", "_ifname") then luci.model.uci.set("network", "wan", "ifname", luci.model.uci.get("network", "wan", "_ifname")) end self.map:set(section, "network", "lan") end return ListValue.write(self, section, value) end encr = s:option(ListValue, "encryption", translate("encryption")) encr:value("none", "keine") encr:value("wep", "WEP") encr:value("psk", "WPA-PSK") encr:value("wpa", "WPA-Radius") encr:value("psk2", "WPA2-PSK") encr:value("wpa2", "WPA2-Radius") key = s:option(Value, "key", translate("key")) key:depends("encryption", "wep") key:depends("encryption", "psk") key:depends("encryption", "wpa") key:depends("encryption", "psk2") key:depends("encryption", "wpa2") key.rmempty = true server = s:option(Value, "server", translate("a_w_radiussrv")) server:depends("encryption", "wpa") server:depends("encryption", "wpa2") server.rmempty = true port = s:option(Value, "port", translate("a_w_radiusport")) port:depends("encryption", "wpa") port:depends("encryption", "wpa2") port.rmempty = true iso = s:option(Flag, "isolate", translate("a_w_apisolation"), translate("a_w_apisolation1")) iso.rmempty = true iso:depends("mode", "ap") hide = s:option(Flag, "hidden", translate("a_w_hideessid")) hide.rmempty = true hide:depends("mode", "ap") return m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Copyright 2008 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("wireless", translate("wifi"), translate("a_w_devices1")) s = m:section(TypedSection, "wifi-device", translate("devices")) en = s:option(Flag, "disabled", translate("enable")) en.enabled = "0" en.disabled = "1" mode = s:option(ListValue, "mode", translate("mode")) mode:value("", "standard") mode:value("11b", "802.11b") mode:value("11g", "802.11g") mode:value("11a", "802.11a") mode:value("11bg", "802.11b+g") mode.rmempty = true s:option(Value, "channel", translate("a_w_channel")) s = m:section(TypedSection, "wifi-iface", translate("m_n_local")) s.anonymous = true s:option(Value, "ssid", translate("a_w_netid")).maxlength = 32 local devs = {} luci.model.uci.foreach("wireless", "wifi-device", function (section) table.insert(devs, section[".name"]) end) if #devs > 1 then device = s:option(DummyValue, "device", translate("device")) else s.defaults.device = devs[1] end mode = s:option(ListValue, "mode", translate("mode")) mode:value("ap", translate("m_w_ap")) mode:value("adhoc", translate("m_w_adhoc")) mode:value("sta", translate("m_w_client")) function mode.write(self, section, value) if value == "sta" then -- ToDo: Move this away if not luci.model.uci.get("network", "wan") then luci.model.uci.set("network", "wan", "proto", "none") luci.model.uci.set("network", "wan", "ifname", " ") end local oldif = luci.model.uci.get("network", "wan", "ifname") if oldif and oldif ~= " " then luci.model.uci.set("network", "wan", "_ifname", oldif) end luci.model.uci.set("network", "wan", "ifname", " ") luci.model.uci.save("network") luci.model.uci.unload("network") self.map:set(section, "network", "wan") else if luci.model.uci.get("network", "wan", "_ifname") then luci.model.uci.set("network", "wan", "ifname", luci.model.uci.get("network", "wan", "_ifname")) end self.map:set(section, "network", "lan") end return ListValue.write(self, section, value) end encr = s:option(ListValue, "encryption", translate("encryption")) encr:value("none", "keine") encr:value("wep", "WEP") encr:value("psk", "WPA-PSK") encr:value("wpa", "WPA-Radius") encr:value("psk2", "WPA2-PSK") encr:value("wpa2", "WPA2-Radius") key = s:option(Value, "key", translate("key")) key:depends("encryption", "wep") key:depends("encryption", "psk") key:depends("encryption", "wpa") key:depends("encryption", "psk2") key:depends("encryption", "wpa2") key.rmempty = true server = s:option(Value, "server", translate("a_w_radiussrv")) server:depends("encryption", "wpa") server:depends("encryption", "wpa2") server.rmempty = true port = s:option(Value, "port", translate("a_w_radiusport")) port:depends("encryption", "wpa") port:depends("encryption", "wpa2") port.rmempty = true iso = s:option(Flag, "isolate", translate("a_w_apisolation"), translate("a_w_apisolation1")) iso.rmempty = true iso:depends("mode", "ap") hide = s:option(Flag, "hidden", translate("a_w_hideessid")) hide.rmempty = true hide:depends("mode", "ap") return m
modules/admin-mini: Fixed wifi client mode again
modules/admin-mini: Fixed wifi client mode again
Lua
apache-2.0
ff94315/luci-1,ff94315/luci-1,david-xiao/luci,palmettos/test,Wedmer/luci,Noltari/luci,ReclaimYourPrivacy/cloak-luci,kuoruan/luci,cshore/luci,opentechinstitute/luci,deepak78/new-luci,LazyZhu/openwrt-luci-trunk-mod,RedSnake64/openwrt-luci-packages,oyido/luci,dismantl/luci-0.12,palmettos/cnLuCI,florian-shellfire/luci,LuttyYang/luci,tobiaswaldvogel/luci,nmav/luci,rogerpueyo/luci,palmettos/cnLuCI,jlopenwrtluci/luci,Sakura-Winkey/LuCI,LuttyYang/luci,ollie27/openwrt_luci,cappiewu/luci,ollie27/openwrt_luci,obsy/luci,Hostle/openwrt-luci-multi-user,Hostle/openwrt-luci-multi-user,ReclaimYourPrivacy/cloak-luci,lcf258/openwrtcn,bittorf/luci,fkooman/luci,nwf/openwrt-luci,shangjiyu/luci-with-extra,jorgifumi/luci,openwrt/luci,LazyZhu/openwrt-luci-trunk-mod,openwrt-es/openwrt-luci,forward619/luci,fkooman/luci,981213/luci-1,bright-things/ionic-luci,thesabbir/luci,Noltari/luci,thesabbir/luci,mumuqz/luci,male-puppies/luci,dwmw2/luci,schidler/ionic-luci,remakeelectric/luci,ReclaimYourPrivacy/cloak-luci,zhaoxx063/luci,artynet/luci,male-puppies/luci,jlopenwrtluci/luci,harveyhu2012/luci,LazyZhu/openwrt-luci-trunk-mod,tcatm/luci,RuiChen1113/luci,marcel-sch/luci,daofeng2015/luci,deepak78/new-luci,harveyhu2012/luci,thesabbir/luci,kuoruan/luci,hnyman/luci,jlopenwrtluci/luci,Sakura-Winkey/LuCI,bittorf/luci,hnyman/luci,opentechinstitute/luci,dismantl/luci-0.12,cshore-firmware/openwrt-luci,joaofvieira/luci,maxrio/luci981213,Hostle/openwrt-luci-multi-user,MinFu/luci,hnyman/luci,ollie27/openwrt_luci,artynet/luci,palmettos/test,Hostle/openwrt-luci-multi-user,Hostle/luci,lcf258/openwrtcn,oyido/luci,forward619/luci,dwmw2/luci,obsy/luci,slayerrensky/luci,david-xiao/luci,Noltari/luci,chris5560/openwrt-luci,openwrt/luci,Wedmer/luci,nwf/openwrt-luci,MinFu/luci,sujeet14108/luci,florian-shellfire/luci,jorgifumi/luci,rogerpueyo/luci,teslamint/luci,urueedi/luci,Noltari/luci,cappiewu/luci,RuiChen1113/luci,florian-shellfire/luci,rogerpueyo/luci,db260179/openwrt-bpi-r1-luci,Sakura-Winkey/LuCI,wongsyrone/luci-1,tcatm/luci,maxrio/luci981213,kuoruan/lede-luci,wongsyrone/luci-1,RedSnake64/openwrt-luci-packages,jchuang1977/luci-1,jchuang1977/luci-1,jchuang1977/luci-1,lbthomsen/openwrt-luci,male-puppies/luci,remakeelectric/luci,Noltari/luci,florian-shellfire/luci,fkooman/luci,Kyklas/luci-proto-hso,teslamint/luci,harveyhu2012/luci,tobiaswaldvogel/luci,cshore-firmware/openwrt-luci,oyido/luci,jorgifumi/luci,urueedi/luci,Wedmer/luci,rogerpueyo/luci,bright-things/ionic-luci,sujeet14108/luci,palmettos/test,db260179/openwrt-bpi-r1-luci,981213/luci-1,db260179/openwrt-bpi-r1-luci,deepak78/new-luci,obsy/luci,palmettos/test,shangjiyu/luci-with-extra,ff94315/luci-1,teslamint/luci,oneru/luci,obsy/luci,LazyZhu/openwrt-luci-trunk-mod,tobiaswaldvogel/luci,hnyman/luci,fkooman/luci,jorgifumi/luci,harveyhu2012/luci,daofeng2015/luci,RedSnake64/openwrt-luci-packages,deepak78/new-luci,981213/luci-1,mumuqz/luci,shangjiyu/luci-with-extra,kuoruan/lede-luci,wongsyrone/luci-1,urueedi/luci,Hostle/openwrt-luci-multi-user,cshore/luci,oyido/luci,chris5560/openwrt-luci,taiha/luci,Hostle/luci,kuoruan/luci,obsy/luci,aircross/OpenWrt-Firefly-LuCI,palmettos/cnLuCI,RuiChen1113/luci,keyidadi/luci,lbthomsen/openwrt-luci,MinFu/luci,bittorf/luci,tobiaswaldvogel/luci,jorgifumi/luci,opentechinstitute/luci,thess/OpenWrt-luci,bittorf/luci,artynet/luci,mumuqz/luci,dwmw2/luci,tcatm/luci,dismantl/luci-0.12,deepak78/new-luci,981213/luci-1,cshore-firmware/openwrt-luci,Kyklas/luci-proto-hso,thesabbir/luci,teslamint/luci,cappiewu/luci,artynet/luci,aircross/OpenWrt-Firefly-LuCI,ollie27/openwrt_luci,taiha/luci,schidler/ionic-luci,jchuang1977/luci-1,nwf/openwrt-luci,nmav/luci,mumuqz/luci,artynet/luci,oneru/luci,opentechinstitute/luci,forward619/luci,Noltari/luci,981213/luci-1,Hostle/luci,LazyZhu/openwrt-luci-trunk-mod,zhaoxx063/luci,david-xiao/luci,deepak78/new-luci,lcf258/openwrtcn,cshore/luci,florian-shellfire/luci,artynet/luci,jlopenwrtluci/luci,lcf258/openwrtcn,NeoRaider/luci,openwrt-es/openwrt-luci,tcatm/luci,kuoruan/luci,teslamint/luci,nmav/luci,thess/OpenWrt-luci,slayerrensky/luci,openwrt-es/openwrt-luci,ollie27/openwrt_luci,thesabbir/luci,urueedi/luci,forward619/luci,openwrt/luci,fkooman/luci,lbthomsen/openwrt-luci,kuoruan/lede-luci,cappiewu/luci,db260179/openwrt-bpi-r1-luci,NeoRaider/luci,cshore/luci,joaofvieira/luci,lcf258/openwrtcn,ReclaimYourPrivacy/cloak-luci,bittorf/luci,cshore-firmware/openwrt-luci,cappiewu/luci,joaofvieira/luci,lcf258/openwrtcn,remakeelectric/luci,joaofvieira/luci,maxrio/luci981213,openwrt-es/openwrt-luci,sujeet14108/luci,oyido/luci,keyidadi/luci,schidler/ionic-luci,981213/luci-1,marcel-sch/luci,david-xiao/luci,aircross/OpenWrt-Firefly-LuCI,hnyman/luci,ollie27/openwrt_luci,kuoruan/luci,aircross/OpenWrt-Firefly-LuCI,lbthomsen/openwrt-luci,palmettos/test,NeoRaider/luci,nmav/luci,dwmw2/luci,openwrt/luci,remakeelectric/luci,openwrt-es/openwrt-luci,nwf/openwrt-luci,palmettos/cnLuCI,nmav/luci,aa65535/luci,bittorf/luci,teslamint/luci,bright-things/ionic-luci,jorgifumi/luci,aa65535/luci,lcf258/openwrtcn,david-xiao/luci,zhaoxx063/luci,jorgifumi/luci,shangjiyu/luci-with-extra,slayerrensky/luci,NeoRaider/luci,Noltari/luci,deepak78/new-luci,Kyklas/luci-proto-hso,sujeet14108/luci,thess/OpenWrt-luci,bittorf/luci,nmav/luci,daofeng2015/luci,kuoruan/lede-luci,marcel-sch/luci,maxrio/luci981213,wongsyrone/luci-1,cshore-firmware/openwrt-luci,chris5560/openwrt-luci,male-puppies/luci,david-xiao/luci,shangjiyu/luci-with-extra,hnyman/luci,marcel-sch/luci,harveyhu2012/luci,aircross/OpenWrt-Firefly-LuCI,teslamint/luci,oneru/luci,keyidadi/luci,Kyklas/luci-proto-hso,cshore-firmware/openwrt-luci,marcel-sch/luci,LazyZhu/openwrt-luci-trunk-mod,schidler/ionic-luci,jlopenwrtluci/luci,NeoRaider/luci,remakeelectric/luci,thesabbir/luci,rogerpueyo/luci,nmav/luci,rogerpueyo/luci,Hostle/luci,Wedmer/luci,kuoruan/luci,bright-things/ionic-luci,urueedi/luci,aircross/OpenWrt-Firefly-LuCI,ff94315/luci-1,artynet/luci,marcel-sch/luci,lcf258/openwrtcn,artynet/luci,urueedi/luci,slayerrensky/luci,981213/luci-1,NeoRaider/luci,oyido/luci,bright-things/ionic-luci,thess/OpenWrt-luci,oyido/luci,harveyhu2012/luci,wongsyrone/luci-1,db260179/openwrt-bpi-r1-luci,zhaoxx063/luci,dismantl/luci-0.12,daofeng2015/luci,mumuqz/luci,RedSnake64/openwrt-luci-packages,nwf/openwrt-luci,dwmw2/luci,wongsyrone/luci-1,cshore/luci,Sakura-Winkey/LuCI,tcatm/luci,wongsyrone/luci-1,jorgifumi/luci,cshore-firmware/openwrt-luci,Hostle/openwrt-luci-multi-user,opentechinstitute/luci,lcf258/openwrtcn,lbthomsen/openwrt-luci,thess/OpenWrt-luci,male-puppies/luci,shangjiyu/luci-with-extra,openwrt-es/openwrt-luci,artynet/luci,LuttyYang/luci,jchuang1977/luci-1,opentechinstitute/luci,sujeet14108/luci,NeoRaider/luci,fkooman/luci,Wedmer/luci,palmettos/cnLuCI,keyidadi/luci,Kyklas/luci-proto-hso,teslamint/luci,palmettos/test,kuoruan/luci,LuttyYang/luci,db260179/openwrt-bpi-r1-luci,Kyklas/luci-proto-hso,RedSnake64/openwrt-luci-packages,tobiaswaldvogel/luci,Sakura-Winkey/LuCI,Wedmer/luci,jlopenwrtluci/luci,male-puppies/luci,NeoRaider/luci,forward619/luci,male-puppies/luci,kuoruan/lede-luci,openwrt/luci,marcel-sch/luci,taiha/luci,cshore/luci,remakeelectric/luci,oneru/luci,sujeet14108/luci,zhaoxx063/luci,aa65535/luci,LazyZhu/openwrt-luci-trunk-mod,schidler/ionic-luci,chris5560/openwrt-luci,lcf258/openwrtcn,jlopenwrtluci/luci,mumuqz/luci,palmettos/test,db260179/openwrt-bpi-r1-luci,Wedmer/luci,sujeet14108/luci,sujeet14108/luci,taiha/luci,dwmw2/luci,bright-things/ionic-luci,ReclaimYourPrivacy/cloak-luci,forward619/luci,oyido/luci,forward619/luci,keyidadi/luci,nmav/luci,Hostle/luci,daofeng2015/luci,palmettos/cnLuCI,nwf/openwrt-luci,openwrt/luci,zhaoxx063/luci,obsy/luci,aircross/OpenWrt-Firefly-LuCI,jchuang1977/luci-1,LuttyYang/luci,florian-shellfire/luci,keyidadi/luci,MinFu/luci,obsy/luci,kuoruan/lede-luci,opentechinstitute/luci,slayerrensky/luci,mumuqz/luci,kuoruan/lede-luci,thesabbir/luci,oneru/luci,MinFu/luci,Sakura-Winkey/LuCI,tobiaswaldvogel/luci,jlopenwrtluci/luci,hnyman/luci,RuiChen1113/luci,opentechinstitute/luci,slayerrensky/luci,openwrt-es/openwrt-luci,taiha/luci,chris5560/openwrt-luci,RuiChen1113/luci,ollie27/openwrt_luci,keyidadi/luci,florian-shellfire/luci,Hostle/luci,shangjiyu/luci-with-extra,thess/OpenWrt-luci,RuiChen1113/luci,Kyklas/luci-proto-hso,daofeng2015/luci,jchuang1977/luci-1,zhaoxx063/luci,palmettos/cnLuCI,joaofvieira/luci,dwmw2/luci,aa65535/luci,obsy/luci,thesabbir/luci,maxrio/luci981213,Hostle/openwrt-luci-multi-user,fkooman/luci,palmettos/test,marcel-sch/luci,schidler/ionic-luci,kuoruan/luci,remakeelectric/luci,maxrio/luci981213,harveyhu2012/luci,aa65535/luci,slayerrensky/luci,Noltari/luci,dwmw2/luci,joaofvieira/luci,tobiaswaldvogel/luci,Sakura-Winkey/LuCI,cappiewu/luci,ff94315/luci-1,keyidadi/luci,chris5560/openwrt-luci,fkooman/luci,bright-things/ionic-luci,ff94315/luci-1,joaofvieira/luci,daofeng2015/luci,cshore-firmware/openwrt-luci,oneru/luci,kuoruan/lede-luci,LazyZhu/openwrt-luci-trunk-mod,wongsyrone/luci-1,tcatm/luci,forward619/luci,tcatm/luci,bright-things/ionic-luci,maxrio/luci981213,openwrt-es/openwrt-luci,cshore/luci,oneru/luci,shangjiyu/luci-with-extra,RuiChen1113/luci,oneru/luci,mumuqz/luci,taiha/luci,daofeng2015/luci,deepak78/new-luci,RuiChen1113/luci,cappiewu/luci,thess/OpenWrt-luci,lbthomsen/openwrt-luci,aa65535/luci,david-xiao/luci,tcatm/luci,Wedmer/luci,aa65535/luci,urueedi/luci,MinFu/luci,palmettos/cnLuCI,taiha/luci,urueedi/luci,aa65535/luci,chris5560/openwrt-luci,david-xiao/luci,male-puppies/luci,tobiaswaldvogel/luci,LuttyYang/luci,Hostle/luci,ff94315/luci-1,dismantl/luci-0.12,rogerpueyo/luci,rogerpueyo/luci,Noltari/luci,lbthomsen/openwrt-luci,cshore/luci,openwrt/luci,openwrt/luci,dismantl/luci-0.12,hnyman/luci,Hostle/openwrt-luci-multi-user,ReclaimYourPrivacy/cloak-luci,ollie27/openwrt_luci,RedSnake64/openwrt-luci-packages,slayerrensky/luci,remakeelectric/luci,florian-shellfire/luci,chris5560/openwrt-luci,db260179/openwrt-bpi-r1-luci,thess/OpenWrt-luci,taiha/luci,ff94315/luci-1,LuttyYang/luci,MinFu/luci,joaofvieira/luci,jchuang1977/luci-1,cappiewu/luci,LuttyYang/luci,Sakura-Winkey/LuCI,lbthomsen/openwrt-luci,maxrio/luci981213,ReclaimYourPrivacy/cloak-luci,nwf/openwrt-luci,Hostle/luci,bittorf/luci,MinFu/luci,ReclaimYourPrivacy/cloak-luci,schidler/ionic-luci,nmav/luci,dismantl/luci-0.12,schidler/ionic-luci,RedSnake64/openwrt-luci-packages,nwf/openwrt-luci,zhaoxx063/luci
4c4e6921f05719c63eba64500cfef4a030fe2411
tools/ejabberd2prosody.lua
tools/ejabberd2prosody.lua
#!/usr/bin/env lua -- Prosody IM -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- package.path = package.path ..";../?.lua"; if arg[0]:match("^./") then package.path = package.path .. ";"..arg[0]:gsub("/ejabberd2prosody.lua$", "/?.lua"); end require "erlparse"; local serialize = require "util.serialization".serialize; local st = require "util.stanza"; package.loaded["util.logger"] = {init = function() return function() end; end} local dm = require "util.datamanager" dm.set_data_path("data"); function build_stanza(tuple, stanza) if tuple[1] == "xmlelement" then local name = tuple[2]; local attr = {}; for _, a in ipairs(tuple[3]) do attr[a[1]] = a[2]; end local up; if stanza then stanza:tag(name, attr); up = true; else stanza = st.stanza(name, attr); end for _, a in ipairs(tuple[4]) do build_stanza(a, stanza); end if up then stanza:up(); else return stanza end elseif tuple[1] == "xmlcdata" then stanza:text(tuple[2]); else error("unknown element type: "..serialize(tuple)); end end function build_time(tuple) local Megaseconds,Seconds,Microseconds = unpack(tuple); return Megaseconds * 1000000 + Seconds; end function vcard(node, host, stanza) local ret, err = dm.store(node, host, "vcard", st.preserialize(stanza)); print("["..(err or "success").."] vCard: "..node.."@"..host); end function password(node, host, password) local ret, err = dm.store(node, host, "accounts", {password = password}); print("["..(err or "success").."] accounts: "..node.."@"..host.." = "..password); end function roster(node, host, jid, item) local roster = dm.load(node, host, "roster") or {}; roster[jid] = item; local ret, err = dm.store(node, host, "roster", roster); print("["..(err or "success").."] roster: " ..node.."@"..host.." - "..jid); end function roster_pending(node, host, jid) local roster = dm.load(node, host, "roster") or {}; roster.pending = roster.pending or {}; roster.pending[jid] = true; local ret, err = dm.store(node, host, "roster", roster); print("["..(err or "success").."] roster: " ..node.."@"..host.." - "..jid); end function private_storage(node, host, xmlns, stanza) local private = dm.load(node, host, "private") or {}; private[stanza.name..":"..xmlns] = st.preserialize(stanza); local ret, err = dm.store(node, host, "private", private); print("["..(err or "success").."] private: " ..node.."@"..host.." - "..xmlns); end function offline_msg(node, host, t, stanza) stanza.attr.stamp = os.date("!%Y-%m-%dT%H:%M:%SZ", t); stanza.attr.stamp_legacy = os.date("!%Y%m%dT%H:%M:%S", t); local ret, err = dm.list_append(node, host, "offline", st.preserialize(stanza)); print("["..(err or "success").."] offline: " ..node.."@"..host.." - "..os.date("!%Y-%m-%dT%H:%M:%SZ", t)); end local filters = { passwd = function(tuple) password(tuple[2][1], tuple[2][2], tuple[3]); end; vcard = function(tuple) vcard(tuple[2][1], tuple[2][2], build_stanza(tuple[3])); end; roster = function(tuple) local node = tuple[3][1]; local host = tuple[3][2]; local contact = (type(tuple[4][1]) == "table") and tuple[4][2] or tuple[4][1].."@"..tuple[4][2]; local name = tuple[5]; local subscription = tuple[6]; local ask = tuple[7]; local groups = tuple[8]; if type(name) ~= type("") then name = nil; end if ask == "none" then ask = nil; elseif ask == "out" then ask = "subscribe" elseif ask == "in" then roster_pending(node, host, contact); ask = nil; elseif ask == "both" then roster_pending(node, host, contact); ask = "subscribe"; else error("Unknown ask type: "..ask); end if subscription ~= "both" and subscription ~= "from" and subscription ~= "to" and subscription ~= "none" then error(subscription) end local item = {name = name, ask = ask, subscription = subscription, groups = {}}; for _, g in ipairs(groups) do item.groups[g] = true; end roster(node, host, contact, item); end; private_storage = function(tuple) private_storage(tuple[2][1], tuple[2][2], tuple[2][3], build_stanza(tuple[3])); end; offline_msg = function(tuple) offline_msg(tuple[2][1], tuple[2][2], build_time(tuple[3]), build_stanza(tuple[7])); end; config = function(tuple) if tuple[2] == "hosts" then local output = io.output(); io.output("prosody.cfg.lua"); io.write("-- Configuration imported from ejabberd --\n"); io.write([[Host "*" modules_enabled = { "saslauth"; -- Authentication for clients and servers. Recommended if you want to log in. "legacyauth"; -- Legacy authentication. Only used by some old clients and bots. "roster"; -- Allow users to have a roster. Recommended ;) "register"; -- Allow users to register on this server using a client "tls"; -- Add support for secure TLS on c2s/s2s connections "vcard"; -- Allow users to set vCards "private"; -- Private XML storage (for room bookmarks, etc.) "version"; -- Replies to server version requests "dialback"; -- s2s dialback support "uptime"; "disco"; "time"; "ping"; --"selftests"; }; ]]); for _, h in ipairs(tuple[3]) do io.write("Host \"" .. h .. "\"\n"); end io.output(output); print("prosody.cfg.lua created"); end end; }; local arg = ...; local help = "/? -? ? /h -h /help -help --help"; if not arg or help:find(arg, 1, true) then print([[ejabberd db dump importer for Prosody Usage: ejabberd2prosody.lua filename.txt The file can be generated from ejabberd using: sudo ./bin/ejabberdctl dump filename.txt Note: The path of ejabberdctl depends on your ejabberd installation, and ejabberd needs to be running for ejabberdctl to work.]]); os.exit(1); end local count = 0; local t = {}; for item in erlparse.parseFile(arg) do count = count + 1; local name = item[1]; t[name] = (t[name] or 0) + 1; --print(count, serialize(item)); if filters[name] then filters[name](item); end end --print(serialize(t));
#!/usr/bin/env lua -- Prosody IM -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- package.path = package.path ..";../?.lua"; if arg[0]:match("^./") then package.path = package.path .. ";"..arg[0]:gsub("/ejabberd2prosody.lua$", "/?.lua"); end require "erlparse"; local serialize = require "util.serialization".serialize; local st = require "util.stanza"; package.loaded["util.logger"] = {init = function() return function() end; end} local dm = require "util.datamanager" dm.set_data_path("data"); function build_stanza(tuple, stanza) if tuple[1] == "xmlelement" then local name = tuple[2]; local attr = {}; for _, a in ipairs(tuple[3]) do attr[a[1]] = a[2]; end local up; if stanza then stanza:tag(name, attr); up = true; else stanza = st.stanza(name, attr); end for _, a in ipairs(tuple[4]) do build_stanza(a, stanza); end if up then stanza:up(); else return stanza end elseif tuple[1] == "xmlcdata" then stanza:text(tuple[2]); else error("unknown element type: "..serialize(tuple)); end end function build_time(tuple) local Megaseconds,Seconds,Microseconds = unpack(tuple); return Megaseconds * 1000000 + Seconds; end function vcard(node, host, stanza) local ret, err = dm.store(node, host, "vcard", st.preserialize(stanza)); print("["..(err or "success").."] vCard: "..node.."@"..host); end function password(node, host, password) local ret, err = dm.store(node, host, "accounts", {password = password}); print("["..(err or "success").."] accounts: "..node.."@"..host.." = "..password); end function roster(node, host, jid, item) local roster = dm.load(node, host, "roster") or {}; roster[jid] = item; local ret, err = dm.store(node, host, "roster", roster); print("["..(err or "success").."] roster: " ..node.."@"..host.." - "..jid); end function roster_pending(node, host, jid) local roster = dm.load(node, host, "roster") or {}; roster.pending = roster.pending or {}; roster.pending[jid] = true; local ret, err = dm.store(node, host, "roster", roster); print("["..(err or "success").."] roster: " ..node.."@"..host.." - "..jid); end function private_storage(node, host, xmlns, stanza) local private = dm.load(node, host, "private") or {}; private[stanza.name..":"..xmlns] = st.preserialize(stanza); local ret, err = dm.store(node, host, "private", private); print("["..(err or "success").."] private: " ..node.."@"..host.." - "..xmlns); end function offline_msg(node, host, t, stanza) stanza.attr.stamp = os.date("!%Y-%m-%dT%H:%M:%SZ", t); stanza.attr.stamp_legacy = os.date("!%Y%m%dT%H:%M:%S", t); local ret, err = dm.list_append(node, host, "offline", st.preserialize(stanza)); print("["..(err or "success").."] offline: " ..node.."@"..host.." - "..os.date("!%Y-%m-%dT%H:%M:%SZ", t)); end local filters = { passwd = function(tuple) password(tuple[2][1], tuple[2][2], tuple[3]); end; vcard = function(tuple) vcard(tuple[2][1], tuple[2][2], build_stanza(tuple[3])); end; roster = function(tuple) local node = tuple[3][1]; local host = tuple[3][2]; local contact = (type(tuple[4][1]) == "table") and tuple[4][2] or tuple[4][1].."@"..tuple[4][2]; local name = tuple[5]; local subscription = tuple[6]; local ask = tuple[7]; local groups = tuple[8]; if type(name) ~= type("") then name = nil; end if ask == "none" then ask = nil; elseif ask == "out" then ask = "subscribe" elseif ask == "in" then roster_pending(node, host, contact); ask = nil; elseif ask == "both" then roster_pending(node, host, contact); ask = "subscribe"; else error("Unknown ask type: "..ask); end if subscription ~= "both" and subscription ~= "from" and subscription ~= "to" and subscription ~= "none" then error(subscription) end local item = {name = name, ask = ask, subscription = subscription, groups = {}}; for _, g in ipairs(groups) do if type(g) == "string" then item.groups[g] = true; end end roster(node, host, contact, item); end; private_storage = function(tuple) private_storage(tuple[2][1], tuple[2][2], tuple[2][3], build_stanza(tuple[3])); end; offline_msg = function(tuple) offline_msg(tuple[2][1], tuple[2][2], build_time(tuple[3]), build_stanza(tuple[7])); end; config = function(tuple) if tuple[2] == "hosts" then local output = io.output(); io.output("prosody.cfg.lua"); io.write("-- Configuration imported from ejabberd --\n"); io.write([[Host "*" modules_enabled = { "saslauth"; -- Authentication for clients and servers. Recommended if you want to log in. "legacyauth"; -- Legacy authentication. Only used by some old clients and bots. "roster"; -- Allow users to have a roster. Recommended ;) "register"; -- Allow users to register on this server using a client "tls"; -- Add support for secure TLS on c2s/s2s connections "vcard"; -- Allow users to set vCards "private"; -- Private XML storage (for room bookmarks, etc.) "version"; -- Replies to server version requests "dialback"; -- s2s dialback support "uptime"; "disco"; "time"; "ping"; --"selftests"; }; ]]); for _, h in ipairs(tuple[3]) do io.write("Host \"" .. h .. "\"\n"); end io.output(output); print("prosody.cfg.lua created"); end end; }; local arg = ...; local help = "/? -? ? /h -h /help -help --help"; if not arg or help:find(arg, 1, true) then print([[ejabberd db dump importer for Prosody Usage: ejabberd2prosody.lua filename.txt The file can be generated from ejabberd using: sudo ./bin/ejabberdctl dump filename.txt Note: The path of ejabberdctl depends on your ejabberd installation, and ejabberd needs to be running for ejabberdctl to work.]]); os.exit(1); end local count = 0; local t = {}; for item in erlparse.parseFile(arg) do count = count + 1; local name = item[1]; t[name] = (t[name] or 0) + 1; --print(count, serialize(item)); if filters[name] then filters[name](item); end end --print(serialize(t));
ejabberd2prosody: Fixed a problem with null roster groups.
ejabberd2prosody: Fixed a problem with null roster groups.
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
afbd5c31b117ca2e2e04824077cbd01666826d28
core/libtexpdf-output.lua
core/libtexpdf-output.lua
local pdf = require("justenoughlibtexpdf"); if (not SILE.outputters) then SILE.outputters = {} end local cursorX = 0 local cursorY = 0 local font = 0 SILE.outputters.libtexpdf = { init = function() pdf.init(SILE.outputFilename, SILE.documentState.paperSize[1],SILE.documentState.paperSize[2]) pdf.beginpage() end, newPage = function() pdf.endpage() pdf.beginpage() end, finish = function() pdf.endpage() pdf.finish() end, setColor = function(self, color) pdf.setcolor(color.r, color.g, color.b) end, pushColor = function (self, color) pdf.colorpush(color.r, color.g, color.b) end, popColor = function (self) pdf.colorpop() end, outputHbox = function (value,w) if not value.glyphString then return end if value.complex then for i=1,#(value.items) do local glyph = value.items[i].codepoint local buf = string.char(math.floor(glyph % 2^32 / 2^8)) .. string.char(glyph % 0x100) pdf.setstring(cursorX + (value.items[i].x_offset or 0), cursorY + (value.items[i].y_offset or 0), buf, string.len(buf), font, value.items[i].width) cursorX = cursorX + value.items[i].width end return end local buf = {} for i=1,#(value.glyphString) do glyph = value.glyphString[i] buf[#buf+1] = string.char(math.floor(glyph % 2^32 / 2^8)) buf[#buf+1] = string.char(glyph % 0x100) end buf = table.concat(buf, "") pdf.setstring(cursorX, cursorY, buf, string.len(buf), font, w) end, setFont = function (options) if SILE.font._key(options) == lastkey then return end lastkey = SILE.font._key(options) font = SILE.font.cache(options, SILE.shaper.getFace) if options.direction == "TTB" then font.layout_dir = 1 end f = pdf.loadfont(font) if f< 0 then SU.error("Font loading error for "..options) end font = f end, drawImage = function (src, x,y,w,h) pdf.drawimage(src, x, y, w, h) end, imageSize = function (src) local llx, lly, urx, ury = pdf.imagebbox(src) return (urx-llx), (ury-lly) end, moveTo = function (x,y) cursorX = x cursorY = SILE.documentState.paperSize[2] - y end, rule = function (x,y,w,d) pdf.setrule(x,SILE.documentState.paperSize[2] -y,w,d) end, debugFrame = function (self,f) pdf.colorpush(0.8,0,0) self.rule(f:left(), f:top(), f:width(), 0.5) self.rule(f:left(), f:top(), 0.5, - f:height()) self.rule(f:right(), f:top(), 0.5, - f:height()) self.rule(f:left(), f:bottom(), f:width(), 0.5) --self.rule(f:left() + f:width()/2 - 5, (f:top() + f:bottom())/2+5, 10, 10) local stuff = SILE.shaper:createNnodes(f.id, SILE.font.loadDefaults({})) stuff = stuff[1].nodes[1].value.glyphString -- Horrible hack local buf = {} for i=1,#stuff do glyph = stuff[i] buf[#buf+1] = string.char(math.floor(glyph % 2^32 / 2^8)) buf[#buf+1] = string.char(glyph % 0x100) end buf = table.concat(buf, "") if font == 0 then SILE.outputter.setFont({}) end pdf.setstring(f:left(), SILE.documentState.paperSize[2] -f:top(), buf, string.len(buf), font, 0) pdf.colorpop() end, debugHbox = function(typesetter, hbox, scaledWidth) end } SILE.outputter = SILE.outputters.libtexpdf
local pdf = require("justenoughlibtexpdf"); if (not SILE.outputters) then SILE.outputters = {} end local cursorX = 0 local cursorY = 0 local font = 0 local started = false SILE.outputters.libtexpdf = { init = function() pdf.init(SILE.outputFilename, SILE.documentState.paperSize[1],SILE.documentState.paperSize[2]) pdf.beginpage() started = true end, newPage = function() pdf.endpage() pdf.beginpage() end, finish = function() if not started then return end pdf.endpage() pdf.finish() end, setColor = function(self, color) pdf.setcolor(color.r, color.g, color.b) end, pushColor = function (self, color) pdf.colorpush(color.r, color.g, color.b) end, popColor = function (self) pdf.colorpop() end, outputHbox = function (value,w) if not value.glyphString then return end if value.complex then for i=1,#(value.items) do local glyph = value.items[i].codepoint local buf = string.char(math.floor(glyph % 2^32 / 2^8)) .. string.char(glyph % 0x100) pdf.setstring(cursorX + (value.items[i].x_offset or 0), cursorY + (value.items[i].y_offset or 0), buf, string.len(buf), font, value.items[i].width) cursorX = cursorX + value.items[i].width end return end local buf = {} for i=1,#(value.glyphString) do glyph = value.glyphString[i] buf[#buf+1] = string.char(math.floor(glyph % 2^32 / 2^8)) buf[#buf+1] = string.char(glyph % 0x100) end buf = table.concat(buf, "") pdf.setstring(cursorX, cursorY, buf, string.len(buf), font, w) end, setFont = function (options) if SILE.font._key(options) == lastkey then return end lastkey = SILE.font._key(options) font = SILE.font.cache(options, SILE.shaper.getFace) if options.direction == "TTB" then font.layout_dir = 1 end f = pdf.loadfont(font) if f< 0 then SU.error("Font loading error for "..options) end font = f end, drawImage = function (src, x,y,w,h) pdf.drawimage(src, x, y, w, h) end, imageSize = function (src) local llx, lly, urx, ury = pdf.imagebbox(src) return (urx-llx), (ury-lly) end, moveTo = function (x,y) cursorX = x cursorY = SILE.documentState.paperSize[2] - y end, rule = function (x,y,w,d) pdf.setrule(x,SILE.documentState.paperSize[2] -y,w,d) end, debugFrame = function (self,f) pdf.colorpush(0.8,0,0) self.rule(f:left(), f:top(), f:width(), 0.5) self.rule(f:left(), f:top(), 0.5, - f:height()) self.rule(f:right(), f:top(), 0.5, - f:height()) self.rule(f:left(), f:bottom(), f:width(), 0.5) --self.rule(f:left() + f:width()/2 - 5, (f:top() + f:bottom())/2+5, 10, 10) local stuff = SILE.shaper:createNnodes(f.id, SILE.font.loadDefaults({})) stuff = stuff[1].nodes[1].value.glyphString -- Horrible hack local buf = {} for i=1,#stuff do glyph = stuff[i] buf[#buf+1] = string.char(math.floor(glyph % 2^32 / 2^8)) buf[#buf+1] = string.char(glyph % 0x100) end buf = table.concat(buf, "") if font == 0 then SILE.outputter.setFont({}) end pdf.setstring(f:left(), SILE.documentState.paperSize[2] -f:top(), buf, string.len(buf), font, 0) pdf.colorpop() end, debugHbox = function(typesetter, hbox, scaledWidth) end } SILE.outputter = SILE.outputters.libtexpdf
Don’t try closing a PDF we didn’t actually open. Fixes #109
Don’t try closing a PDF we didn’t actually open. Fixes #109
Lua
mit
WAKAMAZU/sile_fe,anthrotype/sile,neofob/sile,simoncozens/sile,neofob/sile,anthrotype/sile,anthrotype/sile,alerque/sile,alerque/sile,WAKAMAZU/sile_fe,neofob/sile,neofob/sile,alerque/sile,anthrotype/sile,WAKAMAZU/sile_fe,alerque/sile,WAKAMAZU/sile_fe,simoncozens/sile,simoncozens/sile,simoncozens/sile
edc115fbb234a0ef6bb67eb1c1bf2b1b3e0eb2b9
core/sessionmanager.lua
core/sessionmanager.lua
-- Prosody IM v0.1 -- Copyright (C) 2008 Matthew Wild -- Copyright (C) 2008 Waqas Hussain -- -- This program is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -- local tonumber, tostring = tonumber, tostring; local ipairs, pairs, print, next= ipairs, pairs, print, next; local collectgarbage = collectgarbage; local m_random = import("math", "random"); local format = import("string", "format"); local hosts = hosts; local sessions = sessions; local modulemanager = require "core.modulemanager"; local log = require "util.logger".init("sessionmanager"); local error = error; local uuid_generate = require "util.uuid".generate; local rm_load_roster = require "core.rostermanager".load_roster; local config_get = require "core.configmanager".get; local st = require "util.stanza"; local newproxy = newproxy; local getmetatable = getmetatable; module "sessionmanager" local open_sessions = 0; function new_session(conn) local session = { conn = conn, priority = 0, type = "c2s_unauthed" }; if true then session.trace = newproxy(true); getmetatable(session.trace).__gc = function () open_sessions = open_sessions - 1; print("Session got collected, now "..open_sessions.." sessions are allocated") end; end open_sessions = open_sessions + 1; log("info", "open sessions now: ".. open_sessions); local w = conn.write; session.send = function (t) w(tostring(t)); end return session; end function destroy_session(session, err) (session.log or log)("info", "Destroying session"); -- Send unavailable presence if session.presence then local pres = st.presence{ type = "unavailable" }; if (not err) or err == "closed" then err = "connection closed"; end pres:tag("status"):text("Disconnected: "..err); session.stanza_dispatch(pres); end -- Remove session/resource from user's session list if session.host and session.username then if session.resource then hosts[session.host].sessions[session.username].sessions[session.resource] = nil; end if hosts[session.host] and hosts[session.host].sessions[session.username] then if not next(hosts[session.host].sessions[session.username].sessions) then log("debug", "All resources of %s are now offline", session.username); hosts[session.host].sessions[session.username] = nil; end end end for k in pairs(session) do if k ~= "trace" then session[k] = nil; end end end function make_authenticated(session, username) session.username = username; if session.type == "c2s_unauthed" then session.type = "c2s"; end return true; end -- returns true, nil on success -- returns nil, err_type, err, err_message on failure function bind_resource(session, resource) if not session.username then return nil, "auth", "not-authorized", "Cannot bind resource before authentication"; end if session.resource then return nil, "cancel", "already-bound", "Cannot bind multiple resources on a single connection"; end -- We don't support binding multiple resources resource = resource or uuid_generate(); --FIXME: Randomly-generated resources must be unique per-user, and never conflict with existing if not hosts[session.host].sessions[session.username] then hosts[session.host].sessions[session.username] = { sessions = {} }; else local sessions = hosts[session.host].sessions[session.username].sessions; local limit = config_get(session.host, "core", "max_resources") or 10; if #sessions >= limit then return nil, "cancel", "conflict", "Resource limit reached; only "..limit.." resources allowed"; end if sessions[resource] then -- Resource conflict local policy = config_get(session.host, "core", "conflict_resolve"); local increment; if policy == "random" then resource = uuid_generate(); increment = true; elseif policy == "increment" then increment = true; -- TODO ping old resource elseif policy == "kick_new" then return nil, "cancel", "conflict", "Resource already exists"; else -- if policy == "kick_old" then hosts[session.host].sessions[session.username].sessions[resource]:close { condition = "conflict"; text = "Replaced by new connection"; }; end if increment and sessions[resource] then local count = 1; while sessions[resource.."#"..count] do count = count + 1; end resource = resource.."#"..count; end end end session.resource = resource; session.full_jid = session.username .. '@' .. session.host .. '/' .. resource; hosts[session.host].sessions[session.username].sessions[resource] = session; session.roster = rm_load_roster(session.username, session.host); return true; end function streamopened(session, attr) local send = session.send; session.host = attr.to or error("Client failed to specify destination hostname"); session.version = tonumber(attr.version) or 0; session.streamid = m_random(1000000, 99999999); (session.log or session)("debug", "Client sent opening <stream:stream> to %s", session.host); send("<?xml version='1.0'?>"); send(format("<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' id='%s' from='%s' version='1.0'>", session.streamid, session.host)); if not hosts[session.host] then -- We don't serve this host... session:close{ condition = "host-unknown", text = "This server does not serve "..tostring(session.host)}; return; end local features = st.stanza("stream:features"); modulemanager.fire_event("stream-features", session, features); send(features); (session.log or log)("info", "Sent reply <stream:stream> to client"); session.notopen = nil; end function send_to_available_resources(user, host, stanza) local count = 0; local to = stanza.attr.to; stanza.attr.to = nil; local h = hosts[host]; if h and h.type == "local" then local u = h.sessions[user]; if u then for k, session in pairs(u.sessions) do if session.presence then session.send(stanza); count = count + 1; end end end end stanza.attr.to = to; return count; end return _M;
-- Prosody IM v0.1 -- Copyright (C) 2008 Matthew Wild -- Copyright (C) 2008 Waqas Hussain -- -- This program is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -- local tonumber, tostring = tonumber, tostring; local ipairs, pairs, print, next= ipairs, pairs, print, next; local collectgarbage = collectgarbage; local m_random = import("math", "random"); local format = import("string", "format"); local hosts = hosts; local sessions = sessions; local modulemanager = require "core.modulemanager"; local log = require "util.logger".init("sessionmanager"); local error = error; local uuid_generate = require "util.uuid".generate; local rm_load_roster = require "core.rostermanager".load_roster; local config_get = require "core.configmanager".get; local st = require "util.stanza"; local newproxy = newproxy; local getmetatable = getmetatable; module "sessionmanager" local open_sessions = 0; function new_session(conn) local session = { conn = conn, priority = 0, type = "c2s_unauthed" }; if true then session.trace = newproxy(true); getmetatable(session.trace).__gc = function () open_sessions = open_sessions - 1; print("Session got collected, now "..open_sessions.." sessions are allocated") end; end open_sessions = open_sessions + 1; log("info", "open sessions now: ".. open_sessions); local w = conn.write; session.send = function (t) w(tostring(t)); end return session; end function destroy_session(session, err) (session.log or log)("info", "Destroying session"); -- Send unavailable presence if session.presence then local pres = st.presence{ type = "unavailable" }; if (not err) or err == "closed" then err = "connection closed"; end pres:tag("status"):text("Disconnected: "..err); session.stanza_dispatch(pres); end -- Remove session/resource from user's session list if session.host and session.username then -- FIXME: How can the below ever be nil? (but they sometimes are...) if hosts[session.host] and hosts[session.host].sessions[session.username] then if session.resource then hosts[session.host].sessions[session.username].sessions[session.resource] = nil; end if not next(hosts[session.host].sessions[session.username].sessions) then log("debug", "All resources of %s are now offline", session.username); hosts[session.host].sessions[session.username] = nil; end end end for k in pairs(session) do if k ~= "trace" then session[k] = nil; end end end function make_authenticated(session, username) session.username = username; if session.type == "c2s_unauthed" then session.type = "c2s"; end return true; end -- returns true, nil on success -- returns nil, err_type, err, err_message on failure function bind_resource(session, resource) if not session.username then return nil, "auth", "not-authorized", "Cannot bind resource before authentication"; end if session.resource then return nil, "cancel", "already-bound", "Cannot bind multiple resources on a single connection"; end -- We don't support binding multiple resources resource = resource or uuid_generate(); --FIXME: Randomly-generated resources must be unique per-user, and never conflict with existing if not hosts[session.host].sessions[session.username] then hosts[session.host].sessions[session.username] = { sessions = {} }; else local sessions = hosts[session.host].sessions[session.username].sessions; local limit = config_get(session.host, "core", "max_resources") or 10; if #sessions >= limit then return nil, "cancel", "conflict", "Resource limit reached; only "..limit.." resources allowed"; end if sessions[resource] then -- Resource conflict local policy = config_get(session.host, "core", "conflict_resolve"); local increment; if policy == "random" then resource = uuid_generate(); increment = true; elseif policy == "increment" then increment = true; -- TODO ping old resource elseif policy == "kick_new" then return nil, "cancel", "conflict", "Resource already exists"; else -- if policy == "kick_old" then hosts[session.host].sessions[session.username].sessions[resource]:close { condition = "conflict"; text = "Replaced by new connection"; }; end if increment and sessions[resource] then local count = 1; while sessions[resource.."#"..count] do count = count + 1; end resource = resource.."#"..count; end end end session.resource = resource; session.full_jid = session.username .. '@' .. session.host .. '/' .. resource; hosts[session.host].sessions[session.username].sessions[resource] = session; session.roster = rm_load_roster(session.username, session.host); return true; end function streamopened(session, attr) local send = session.send; session.host = attr.to or error("Client failed to specify destination hostname"); session.version = tonumber(attr.version) or 0; session.streamid = m_random(1000000, 99999999); (session.log or session)("debug", "Client sent opening <stream:stream> to %s", session.host); send("<?xml version='1.0'?>"); send(format("<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' id='%s' from='%s' version='1.0'>", session.streamid, session.host)); if not hosts[session.host] then -- We don't serve this host... session:close{ condition = "host-unknown", text = "This server does not serve "..tostring(session.host)}; return; end local features = st.stanza("stream:features"); modulemanager.fire_event("stream-features", session, features); send(features); (session.log or log)("info", "Sent reply <stream:stream> to client"); session.notopen = nil; end function send_to_available_resources(user, host, stanza) local count = 0; local to = stanza.attr.to; stanza.attr.to = nil; local h = hosts[host]; if h and h.type == "local" then local u = h.sessions[user]; if u then for k, session in pairs(u.sessions) do if session.presence then session.send(stanza); count = count + 1; end end end end stanza.attr.to = to; return count; end return _M;
Quick fix for an issue that needs more looking into
Quick fix for an issue that needs more looking into
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
75da80e6392162414b424c651b39e9d7c6e6898a
levent/socket_util.lua
levent/socket_util.lua
local socket = require "levent.socket" local dns = require "levent.dns" local util = {} function util.create_connection(host, port, timeout) local ret, err = dns.resolve(host) if not ret then return nil, err end local ip = ret[1] local sock, err = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if not sock then return nil, err --maybe: Too many open files end if timeout then sock:set_timeout(timeout) end local ok, err = sock:connect(ip, port) if not ok then sock:close() return nil, err end return sock end function util.listen(ip, port) local sock, err= socket.socket(socket.AF_INET, socket.SOCK_STREAM) if not sock then return nil, err end local ok, err = sock:bind(ip, port) if not ok then return nil, err end local ok, err = sock:listen() if not ok then return nil, err end return sock end function util.read_full(sock, length) local reply = "" while #reply < length do local ret, err = sock:recv(length - #reply) if not ret then return nil, err end reply = reply .. ret end return reply end return util
local socket = require "levent.socket" local dns = require "levent.dns" local util = {} function util.create_connection(host, port, timeout) local ret, err = dns.resolve(host) if not ret then return nil, err end local ip = ret[1] local sock, err = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if not sock then return nil, err --maybe: Too many open files end if timeout then sock:set_timeout(timeout) end local ok, err = sock:connect(ip, port) if not ok then sock:close() return nil, err end return sock end function util.listen(ip, port) local sock, err= socket.socket(socket.AF_INET, socket.SOCK_STREAM) if not sock then return nil, err end local ok, err = sock:bind(ip, port) if not ok then return nil, err end local ok, err = sock:listen() if not ok then return nil, err end return sock end function util.read_full(sock, length) local reply = "" while #reply < length do local ret, err = sock:recv(length - #reply) if not ret then return nil, err end if #ret == 0 then return nil -- the peer may closed or shutdown write end reply = reply .. ret end return reply end return util
fix util.read_full dont return when cannot read data anymore
fix util.read_full dont return when cannot read data anymore
Lua
mit
xjdrew/levent
48283de92c16db2b544c77b6d84c2133acd9c17b
data/scripts/abe.lua
data/scripts/abe.lua
-- Composite helpers function InputSameAsDirection(s) return (s:InputLeft() and s:FacingLeft()) or (s:InputRight() and s:FacingRight()) end local function InputNotSameAsDirection(s) return (s:InputLeft() and s:FacingRight()) or (s:InputRight() and s:FacingLeft()) end function init(self) self.states = {} self.states.Stand = { animation = 'AbeStandIdle', condition = function(s) if (s:InputDown()) then -- ToHoistDown return 'ToCrouch' end if (s:InputUp()) then -- ToHoistUp return 'ToJump' end if (s:InputAction()) then -- PullLever return 'ToThrow' end if (InputSameAsDirection(s)) then if (s:InputRun()) then return 'ToRunning' elseif (s:InputSneak()) then return 'ToSneak' else return 'ToWalk' end end if (InputNotSameAsDirection(s)) then s:FlipXDirection() return 'StandingTurn' end if (s:InputChant()) then return 'ToChant' end if (s:InputHop()) then return 'ToHop' end -- StandSpeakXYZ -- ToKnockBackStanding -- ToFallingNoGround end } self.states.Crouch = { animation = 'AbeCrouchIdle', condition = function(s) if s:InputUp() then return 'CrouchToStand' end if (InputSameAsDirection(s)) then return 'ToRolling' end if (InputNotSameAsDirection(s)) then s:FlipXDirection() return 'CrouchingTurn' end end } self.states.ToRolling = { animation = 'AbeCrouchTurnAround', -- TODO: This changes instantly IsLastFrame bug? condition = function(s) if s:IsLastFrame() then return 'Crouch' end end } self.states.CrouchingTurn = { animation = 'AbeCrouchToRoll', condition = function(s) if s:IsLastFrame() then return 'Rolling' end end } self.states.Rolling = { animation = 'AbeRolling', condition = function(s) if(InputSameAsDirection(s) == false) then return 'Crouch' end end } self.states.Walking = { animation = 'AbeWalking', condition = function(s) if (InputSameAsDirection(s) == false) then return 'ToStand' end end } self.states.ToJump = { animation = 'AbeStandToJump', condition = function(s) if s:IsLastFrame() then return 'Jumping' end end } self.states.Jumping = { animation = 'AbeJumpUpFalling', condition = function(s) if s:IsLastFrame() then return 'ToHitGround' end end } self.states.ToHitGround = { animation = 'AbeHitGroundToStand', condition = function(s) if s:IsLastFrame() then return 'Stand' end end } self.states.StandingTurn = { animation = 'AbeStandTurnAround', condition = function(s) if s:IsLastFrame() then return 'Stand' end end } self.states.ToWalk = { animation = 'AbeStandToWalk', condition = function(s) if s:IsLastFrame() then return 'Walking' end end } self.states.ToStand = { animation = 'AbeWalkToStand', condition = function(s) if s:IsLastFrame() then return 'Stand' end end } self.states.ToCrouch = { animation = 'AbeStandToCrouch', condition = function(s) if s:IsLastFrame() then return 'Crouch' end end } self.states.CrouchToStand = { animation = 'AbeCrouchToStand', condition = function(s) if s:IsLastFrame() then return 'Stand' end end } print("Stand") self.states.Active = self.states.Stand self:SetAnimation(self.states.Active.animation) end function update(self) local nextState = self.states.Active.condition(self) if nextState ~= nil then local state = self.states[nextState] if state == nil then print("ERROR: State " .. nextState .. " not found!") else print(nextState) self.states.Active = state self:SetAnimation(self.states.Active.animation) end end end
-- Composite helpers function InputSameAsDirection(s) return (s:InputLeft() and s:FacingLeft()) or (s:InputRight() and s:FacingRight()) end local function InputNotSameAsDirection(s) return (s:InputLeft() and s:FacingRight()) or (s:InputRight() and s:FacingLeft()) end function init(self) self.states = {} self.states.Stand = { animation = 'AbeStandIdle', condition = function(s) if (s:InputDown()) then -- ToHoistDown return 'ToCrouch' end if (s:InputUp()) then -- ToHoistUp return 'ToJump' end if (s:InputAction()) then -- PullLever return 'ToThrow' end if (InputSameAsDirection(s)) then if (s:InputRun()) then return 'ToRunning' elseif (s:InputSneak()) then return 'ToSneak' else return 'ToWalk' end end if (InputNotSameAsDirection(s)) then s:FlipXDirection() return 'StandingTurn' end if (s:InputChant()) then return 'ToChant' end if (s:InputHop()) then return 'ToHop' end -- StandSpeakXYZ -- ToKnockBackStanding -- ToFallingNoGround end } self.states.Crouch = { animation = 'AbeCrouchIdle', condition = function(s) if s:InputUp() then return 'CrouchToStand' end if (InputSameAsDirection(s)) then return 'ToRolling' end if (InputNotSameAsDirection(s)) then s:FlipXDirection() return 'CrouchingTurn' end end } self.states.ToRolling = { animation = 'AbeCrouchToRoll', condition = function(s) if s:IsLastFrame() then return 'Rolling' end end } self.states.CrouchingTurn = { animation = 'AbeCrouchTurnAround', condition = function(s) if s:IsLastFrame() then return 'Crouch' end end } self.states.Rolling = { animation = 'AbeRolling', condition = function(s) if(InputSameAsDirection(s) == false) then return 'Crouch' end end } self.states.Walking = { animation = 'AbeWalking', condition = function(s) if (InputSameAsDirection(s) == false) then return 'ToStand' end end } self.states.ToJump = { animation = 'AbeStandToJump', condition = function(s) if s:IsLastFrame() then return 'Jumping' end end } self.states.Jumping = { animation = 'AbeJumpUpFalling', condition = function(s) if s:IsLastFrame() then return 'ToHitGround' end end } self.states.ToHitGround = { animation = 'AbeHitGroundToStand', condition = function(s) if s:IsLastFrame() then return 'Stand' end end } self.states.StandingTurn = { animation = 'AbeStandTurnAround', condition = function(s) if s:IsLastFrame() then return 'Stand' end end } self.states.ToWalk = { animation = 'AbeStandToWalk', condition = function(s) if s:IsLastFrame() then return 'Walking' end end } self.states.ToStand = { animation = 'AbeWalkToStand', condition = function(s) if s:IsLastFrame() then return 'Stand' end end } self.states.ToCrouch = { animation = 'AbeStandToCrouch', condition = function(s) if s:IsLastFrame() then return 'Crouch' end end } self.states.CrouchToStand = { animation = 'AbeCrouchToStand', condition = function(s) if s:IsLastFrame() then return 'Stand' end end } print("Stand") self.states.Active = self.states.Stand self:SetAnimation(self.states.Active.animation) end function update(self) local nextState = self.states.Active.condition(self) if nextState ~= nil then local state = self.states[nextState] if state == nil then print("ERROR: State " .. nextState .. " not found!") else print(nextState) self.states.Active = state self:SetAnimation(self.states.Active.animation) end end end
fix ToRolling/CrouchingTurn
fix ToRolling/CrouchingTurn
Lua
mit
mlgthatsme/alive,paulsapps/alive,paulsapps/alive,mlgthatsme/alive,paulsapps/alive,mlgthatsme/alive
419b4ea694cdabada1e19c70e152a1b6e6943a37
lua/include/packet.lua
lua/include/packet.lua
local ffi = require "ffi" require "utils" require "headers" require "dpdkc" local ntoh, hton = ntoh, hton local ntoh16, hton16 = ntoh16, hton16 local bswap = bswap local bswap16 = bwswap16 local bor, band, bnot, rshift, lshift= bit.bor, bit.band, bit.bnot, bit.rshift, bit.lshift local pkt = {} pkt.__index = pkt --- Retrieves the time stamp information -- @return the timestamp or nil if the packet was not time stamped function pkt:getTimestamp() if bit.bor(self.ol_flags, dpdk.PKT_RX_IEEE1588_TMST) ~= 0 then -- TODO: support timestamps that are stored in registers instead of the rx buffer local data = ffi.cast("uint32_t* ", self.pkt.data) -- TODO: this is only tested with the Intel 82580 NIC at the moment -- the datasheet claims that low and high are swapped, but this doesn't seem to be the case -- TODO: check other NICs local low = data[2] local high = data[3] return high * 2^32 + low end end ---ip packets local udpPacketType = ffi.typeof("struct udp_packet*") --- Retrieves an IPv4 UDP packet -- @return the packet in udp_packet format function pkt:getUDPPacket() return udpPacketType(self.pkt.data) end local ip4Header = {} ip4Header.__index = ip4Header --- Calculate and set the IPv4 header checksum function ip4Header:calculateChecksum() self.cs = 0 --just to be sure... self.cs = checksum(self, 20) end local ip4Addr = {} ip4Addr.__index = ip4Addr --- Retrieves the IPv4 address -- @return address in ipv4_address format function ip4Addr:get() return bswap(self.uint32) end --- Set the IPv4 address -- @param address in ipv4_address format function ip4Addr:set(ip) self.uint32 = bswap(ip) end --- Set the IPv4 address -- @param address in string format function ip4Addr:stringToIPAddress(ip) self:set(parseIPAddress(ip)) end -- Retrieves the string representation of an IPv4 address -- @return address in string format function ip4Addr:getString() return ("%d.%d.%d.%d"):format(self.uint8[0], self.uint8[1], self.uint8[2], self.uint8[3]) end --- ipv6 packets local udp6PacketType = ffi.typeof("struct udp_v6_packet*") --- Retrieves an IPv6 UDP packet -- @return the packet in udp_v6_packet format function pkt:getUDP6Packet() return udp6PacketType(self.pkt.data) end local ip6Addr = {} ip6Addr.__index = ip6Addr --- Retrieves the IPv6 address -- @return address in ipv6_address format function ip6Addr:get() local addr = ffi.new("union ipv6_address") addr.uint32[0] = bswap(self.uint32[3]) addr.uint32[1] = bswap(self.uint32[2]) addr.uint32[2] = bswap(self.uint32[1]) addr.uint32[3] = bswap(self.uint32[0]) return addr end --- Set the IPv6 address -- @param address in ipv6_address format function ip6Addr:set(addr) self.uint32[0] = bswap(addr.uint32[3]) self.uint32[1] = bswap(addr.uint32[2]) self.uint32[2] = bswap(addr.uint32[1]) self.uint32[3] = bswap(addr.uint32[0]) end --- Set the IPv6 address -- @param address in string format function ip6Addr:stringToIP6Address(ip) self:set(parseIPAddress(ip)) end --- Add a number to an IPv6 address -- max. 64bit -- @param number to add -- @return resulting address in ipv6_address format function ip6Addr:__add(val) local addr = ffi.new("union ipv6_address") local low, high = self.uint64[0], self.uint64[1] low = low + val -- handle overflow if low < val and val > 0 then high = high + 1 -- handle underflow elseif low > -val and val < 0 then high = high - 1 end addr.uint64[0] = low addr.uint64[1] = high return addr end --- Subtract a number from an IPv6 address -- max. 64 bit -- @param number to substract -- @return resulting address in ipv6_address format function ip6Addr:__sub(val) return self + -val end -- Retrieves the string representation of an IPv6 address -- @return address in string format function ip6Addr:getString() return ("%x%x:%x%x:%x%x:%x%x:%x%x:%x%x:%x%x:%x%x"):format(self.uint8[0], self.uint8[1], self.uint8[2], self.uint8[3], self.uint8[4], self.uint8[5], self.uint8[6], self.uint8[7], self.uint8[8], self.uint8[9], self.uint8[10], self.uint8[11], self.uint8[12], self.uint8[13], self.uint8[14], self.uint8[15]) end -- udp local udp6Header = {} udp6Header.__index = udp6Header --- Calculate and set the UDP header checksum for IPv6 packets function udp6Header:calculateChecksum() -- TODO as it is mandatory for IPv6 UDP packets self.cs = 0 end ffi.metatype("struct ipv4_header", ip4Header) ffi.metatype("union ipv4_address", ip4Addr) ffi.metatype("union ipv6_address", ip6Addr) ffi.metatype("struct udp_v6_header", udp6Header) ffi.metatype("struct rte_mbuf", pkt)
local ffi = require "ffi" require "utils" require "headers" require "dpdkc" local ntoh, hton = ntoh, hton local ntoh16, hton16 = ntoh16, hton16 local bswap = bswap local bswap16 = bwswap16 local bor, band, bnot, rshift, lshift= bit.bor, bit.band, bit.bnot, bit.rshift, bit.lshift local pkt = {} pkt.__index = pkt --- Retrieves the time stamp information -- @return the timestamp or nil if the packet was not time stamped function pkt:getTimestamp() if bit.bor(self.ol_flags, dpdk.PKT_RX_IEEE1588_TMST) ~= 0 then -- TODO: support timestamps that are stored in registers instead of the rx buffer local data = ffi.cast("uint32_t* ", self.pkt.data) -- TODO: this is only tested with the Intel 82580 NIC at the moment -- the datasheet claims that low and high are swapped, but this doesn't seem to be the case -- TODO: check other NICs local low = data[2] local high = data[3] return high * 2^32 + low end end ---ip packets local udpPacketType = ffi.typeof("struct udp_packet*") --- Retrieves an IPv4 UDP packet -- @return the packet in udp_packet format function pkt:getUDPPacket() return udpPacketType(self.pkt.data) end local ip4Header = {} ip4Header.__index = ip4Header --- Calculate and set the IPv4 header checksum function ip4Header:calculateChecksum() self.cs = 0 --just to be sure... self.cs = checksum(self, 20) end local ip4Addr = {} ip4Addr.__index = ip4Addr --- Retrieves the IPv4 address -- @return address in ipv4_address format function ip4Addr:get() return bswap(self.uint32) end --- Set the IPv4 address -- @param address in ipv4_address format function ip4Addr:set(ip) self.uint32 = bswap(ip) end --- Set the IPv4 address -- @param address in string format function ip4Addr:stringToIPAddress(ip) self:set(parseIPAddress(ip)) end -- Retrieves the string representation of an IPv4 address -- @return address in string format function ip4Addr:getString() return ("%d.%d.%d.%d"):format(self.uint8[0], self.uint8[1], self.uint8[2], self.uint8[3]) end local udpPacket = {} udpHeader.__index = udpPacket --- Calculate and set the UDP header checksum for IPv4 packets function udpPacket:calculateUDPChecksum() -- optional, so don't do it self.udp.cs = 0 end --- ipv6 packets local udp6PacketType = ffi.typeof("struct udp_v6_packet*") --- Retrieves an IPv6 UDP packet -- @return the packet in udp_v6_packet format function pkt:getUDP6Packet() return udp6PacketType(self.pkt.data) end local ip6Addr = {} ip6Addr.__index = ip6Addr --- Retrieves the IPv6 address -- @return address in ipv6_address format function ip6Addr:get() local addr = ffi.new("union ipv6_address") addr.uint32[0] = bswap(self.uint32[3]) addr.uint32[1] = bswap(self.uint32[2]) addr.uint32[2] = bswap(self.uint32[1]) addr.uint32[3] = bswap(self.uint32[0]) return addr end --- Set the IPv6 address -- @param address in ipv6_address format function ip6Addr:set(addr) self.uint32[0] = bswap(addr.uint32[3]) self.uint32[1] = bswap(addr.uint32[2]) self.uint32[2] = bswap(addr.uint32[1]) self.uint32[3] = bswap(addr.uint32[0]) end --- Set the IPv6 address -- @param address in string format function ip6Addr:stringToIP6Address(ip) self:set(parseIPAddress(ip)) end --- Add a number to an IPv6 address -- max. 64bit -- @param number to add -- @return resulting address in ipv6_address format function ip6Addr:__add(val) local addr = ffi.new("union ipv6_address") local low, high = self.uint64[0], self.uint64[1] low = low + val -- handle overflow if low < val and val > 0 then high = high + 1 -- handle underflow elseif low > -val and val < 0 then high = high - 1 end addr.uint64[0] = low addr.uint64[1] = high return addr end --- Subtract a number from an IPv6 address -- max. 64 bit -- @param number to substract -- @return resulting address in ipv6_address format function ip6Addr:__sub(val) return self + -val end -- Retrieves the string representation of an IPv6 address -- @return address in string format function ip6Addr:getString() return ("%x%x:%x%x:%x%x:%x%x:%x%x:%x%x:%x%x:%x%x"):format(self.uint8[0], self.uint8[1], self.uint8[2], self.uint8[3], self.uint8[4], self.uint8[5], self.uint8[6], self.uint8[7], self.uint8[8], self.uint8[9], self.uint8[10], self.uint8[11], self.uint8[12], self.uint8[13], self.uint8[14], self.uint8[15]) end -- udp local udp6Packet = {} udpHeader.__index = udp6Packet --- Calculate and set the UDP header checksum for IPv6 packets function udp6Packet:calculateUDPChecksum() -- TODO as it is mandatory for IPv6 UDP packets self.udp.cs = 0 end ffi.metatype("struct ipv4_header", ip4Header) ffi.metatype("union ipv4_address", ip4Addr) ffi.metatype("union ipv6_address", ip6Addr) ffi.metatype("struct udp_packet", udpPacket) ffi.metatype("struct udp_v6_packet", udp6Packet) ffi.metatype("struct rte_mbuf", pkt)
short fix
short fix
Lua
mit
kidaa/MoonGen,scholzd/MoonGen,slyon/MoonGen,gallenmu/MoonGen,wenhuizhang/MoonGen,werpat/MoonGen,slyon/MoonGen,atheurer/MoonGen,scholzd/MoonGen,NetronomeMoongen/MoonGen,slyon/MoonGen,schoenb/MoonGen,bmichalo/MoonGen,gallenmu/MoonGen,scholzd/MoonGen,dschoeffm/MoonGen,werpat/MoonGen,schoenb/MoonGen,werpat/MoonGen,emmericp/MoonGen,pavel-odintsov/MoonGen,kidaa/MoonGen,slyon/MoonGen,NetronomeMoongen/MoonGen,duk3luk3/MoonGen,bmichalo/MoonGen,NetronomeMoongen/MoonGen,dschoeffm/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,bmichalo/MoonGen,kidaa/MoonGen,gallenmu/MoonGen,emmericp/MoonGen,pavel-odintsov/MoonGen,emmericp/MoonGen,atheurer/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,bmichalo/MoonGen,atheurer/MoonGen,duk3luk3/MoonGen,pavel-odintsov/MoonGen,duk3luk3/MoonGen,dschoeffm/MoonGen,wenhuizhang/MoonGen,wenhuizhang/MoonGen,schoenb/MoonGen
baf5987b0bd9223f239faec5b1614fb792520aee
service/clusterd.lua
service/clusterd.lua
local skynet = require "skynet" require "skynet.manager" local cluster = require "skynet.cluster.core" local config_name = skynet.getenv "cluster" local node_address = {} local node_sender = {} local command = {} local config = {} local nodename = cluster.nodename() local connecting = {} local function open_channel(t, key) local ct = connecting[key] if ct then local co = coroutine.running() table.insert(ct, co) skynet.wait(co) return assert(ct.channel) end ct = {} connecting[key] = ct local address = node_address[key] if address == nil and not config.nowaiting then local co = coroutine.running() assert(ct.namequery == nil) ct.namequery = co skynet.error("Waiting for cluster node [".. key.."]") skynet.wait(co) address = node_address[key] end local succ, err, c if address then local host, port = string.match(address, "([^:]+):(.*)$") c = node_sender[key] if c == nil then c = skynet.newservice("clustersender", key, nodename) if node_sender[key] then -- double check skynet.kill(c) c = node_sender[key] else node_sender[key] = c end end succ = pcall(skynet.call, c, "lua", "changenode", host, port) if succ then t[key] = c ct.channel = c end else err = string.format("cluster node [%s] is %s.", key, address == false and "down" or "absent") end connecting[key] = nil for _, co in ipairs(ct) do skynet.wakeup(co) end assert(succ, err) return c end local node_channel = setmetatable({}, { __index = open_channel }) local function loadconfig(tmp) if tmp == nil then tmp = {} if config_name then local f = assert(io.open(config_name)) local source = f:read "*a" f:close() assert(load(source, "@"..config_name, "t", tmp))() end end for name,address in pairs(tmp) do if name:sub(1,2) == "__" then name = name:sub(3) config[name] = address skynet.error(string.format("Config %s = %s", name, address)) else assert(address == false or type(address) == "string") if node_address[name] ~= address then -- address changed if rawget(node_channel, name) then node_channel[name] = nil -- reset connection end node_address[name] = address end local ct = connecting[name] if ct and ct.namequery and not config.nowaiting then skynet.error(string.format("Cluster node [%s] resloved : %s", name, address)) skynet.wakeup(ct.namequery) end end end if config.nowaiting then -- wakeup all connecting request for name, ct in pairs(connecting) do if ct.namequery then skynet.wakeup(ct.namequery) end end end end function command.reload(source, config) loadconfig(config) skynet.ret(skynet.pack(nil)) end function command.listen(source, addr, port) local gate = skynet.newservice("gate") if port == nil then local address = assert(node_address[addr], addr .. " is down") addr, port = string.match(address, "([^:]+):(.*)$") end skynet.call(gate, "lua", "open", { address = addr, port = port }) skynet.ret(skynet.pack(nil)) end function command.sender(source, node) skynet.ret(skynet.pack(node_channel[node])) end local proxy = {} function command.proxy(source, node, name) if name == nil then node, name = node:match "^([^@.]+)([@.].+)" if name == nil then error ("Invalid name " .. tostring(node)) end end local fullname = node .. "." .. name local p = proxy[fullname] if p == nil then p = skynet.newservice("clusterproxy", node, name) -- double check if proxy[fullname] then skynet.kill(p) p = proxy[fullname] else proxy[fullname] = p end end skynet.ret(skynet.pack(p)) end local cluster_agent = {} -- fd:service local register_name = {} local function clearnamecache() for fd, service in pairs(cluster_agent) do if type(service) == "number" then skynet.send(service, "lua", "namechange") end end end function command.register(source, name, addr) assert(register_name[name] == nil) addr = addr or source local old_name = register_name[addr] if old_name then register_name[old_name] = nil clearnamecache() end register_name[addr] = name register_name[name] = addr skynet.ret(nil) skynet.error(string.format("Register [%s] :%08x", name, addr)) end function command.queryname(source, name) skynet.ret(skynet.pack(register_name[name])) end function command.socket(source, subcmd, fd, msg) if subcmd == "open" then skynet.error(string.format("socket accept from %s", msg)) -- new cluster agent cluster_agent[fd] = false local agent = skynet.newservice("clusteragent", skynet.self(), source, fd) local closed = cluster_agent[fd] cluster_agent[fd] = agent if closed then skynet.send(agent, "lua", "exit") cluster_agent[fd] = nil end else if subcmd == "close" or subcmd == "error" then -- close cluster agent local agent = cluster_agent[fd] if type(agent) == "boolean" then cluster_agent[fd] = true elseif agent then skynet.send(agent, "lua", "exit") cluster_agent[fd] = nil end else skynet.error(string.format("socket %s %d %s", subcmd, fd, msg or "")) end end end skynet.start(function() loadconfig() skynet.dispatch("lua", function(session , source, cmd, ...) local f = assert(command[cmd]) f(source, ...) end) end)
local skynet = require "skynet" require "skynet.manager" local cluster = require "skynet.cluster.core" local config_name = skynet.getenv "cluster" local node_address = {} local node_sender = {} local command = {} local config = {} local nodename = cluster.nodename() local connecting = {} local function open_channel(t, key) local ct = connecting[key] if ct then local co = coroutine.running() table.insert(ct, co) skynet.wait(co) return assert(ct.channel) end ct = {} connecting[key] = ct local address = node_address[key] if address == nil and not config.nowaiting then local co = coroutine.running() assert(ct.namequery == nil) ct.namequery = co skynet.error("Waiting for cluster node [".. key.."]") skynet.wait(co) address = node_address[key] end local succ, err, c if address then local host, port = string.match(address, "([^:]+):(.*)$") c = node_sender[key] if c == nil then c = skynet.newservice("clustersender", key, nodename) if node_sender[key] then -- double check skynet.kill(c) c = node_sender[key] else node_sender[key] = c end end succ = pcall(skynet.call, c, "lua", "changenode", host, port) if succ then t[key] = c ct.channel = c else err = string.format("changenode [%s] (%s:%s) failed", key, host, port) end else err = string.format("cluster node [%s] is %s.", key, address == false and "down" or "absent") end connecting[key] = nil for _, co in ipairs(ct) do skynet.wakeup(co) end assert(succ, err) return c end local node_channel = setmetatable({}, { __index = open_channel }) local function loadconfig(tmp) if tmp == nil then tmp = {} if config_name then local f = assert(io.open(config_name)) local source = f:read "*a" f:close() assert(load(source, "@"..config_name, "t", tmp))() end end for name,address in pairs(tmp) do if name:sub(1,2) == "__" then name = name:sub(3) config[name] = address skynet.error(string.format("Config %s = %s", name, address)) else assert(address == false or type(address) == "string") if node_address[name] ~= address then -- address changed if rawget(node_channel, name) then node_channel[name] = nil -- reset connection end node_address[name] = address end local ct = connecting[name] if ct and ct.namequery and not config.nowaiting then skynet.error(string.format("Cluster node [%s] resloved : %s", name, address)) skynet.wakeup(ct.namequery) end end end if config.nowaiting then -- wakeup all connecting request for name, ct in pairs(connecting) do if ct.namequery then skynet.wakeup(ct.namequery) end end end end function command.reload(source, config) loadconfig(config) skynet.ret(skynet.pack(nil)) end function command.listen(source, addr, port) local gate = skynet.newservice("gate") if port == nil then local address = assert(node_address[addr], addr .. " is down") addr, port = string.match(address, "([^:]+):(.*)$") end skynet.call(gate, "lua", "open", { address = addr, port = port }) skynet.ret(skynet.pack(nil)) end function command.sender(source, node) skynet.ret(skynet.pack(node_channel[node])) end local proxy = {} function command.proxy(source, node, name) if name == nil then node, name = node:match "^([^@.]+)([@.].+)" if name == nil then error ("Invalid name " .. tostring(node)) end end local fullname = node .. "." .. name local p = proxy[fullname] if p == nil then p = skynet.newservice("clusterproxy", node, name) -- double check if proxy[fullname] then skynet.kill(p) p = proxy[fullname] else proxy[fullname] = p end end skynet.ret(skynet.pack(p)) end local cluster_agent = {} -- fd:service local register_name = {} local function clearnamecache() for fd, service in pairs(cluster_agent) do if type(service) == "number" then skynet.send(service, "lua", "namechange") end end end function command.register(source, name, addr) assert(register_name[name] == nil) addr = addr or source local old_name = register_name[addr] if old_name then register_name[old_name] = nil clearnamecache() end register_name[addr] = name register_name[name] = addr skynet.ret(nil) skynet.error(string.format("Register [%s] :%08x", name, addr)) end function command.queryname(source, name) skynet.ret(skynet.pack(register_name[name])) end function command.socket(source, subcmd, fd, msg) if subcmd == "open" then skynet.error(string.format("socket accept from %s", msg)) -- new cluster agent cluster_agent[fd] = false local agent = skynet.newservice("clusteragent", skynet.self(), source, fd) local closed = cluster_agent[fd] cluster_agent[fd] = agent if closed then skynet.send(agent, "lua", "exit") cluster_agent[fd] = nil end else if subcmd == "close" or subcmd == "error" then -- close cluster agent local agent = cluster_agent[fd] if type(agent) == "boolean" then cluster_agent[fd] = true elseif agent then skynet.send(agent, "lua", "exit") cluster_agent[fd] = nil end else skynet.error(string.format("socket %s %d %s", subcmd, fd, msg or "")) end end end skynet.start(function() loadconfig() skynet.dispatch("lua", function(session , source, cmd, ...) local f = assert(command[cmd]) f(source, ...) end) end)
fix #1062
fix #1062
Lua
mit
bigrpg/skynet,sanikoyes/skynet,sanikoyes/skynet,cloudwu/skynet,pigparadise/skynet,hongling0/skynet,wangyi0226/skynet,hongling0/skynet,cloudwu/skynet,icetoggle/skynet,wangyi0226/skynet,wangyi0226/skynet,korialuo/skynet,korialuo/skynet,ag6ag/skynet,xjdrew/skynet,cloudwu/skynet,jxlczjp77/skynet,xjdrew/skynet,xjdrew/skynet,icetoggle/skynet,xcjmine/skynet,ag6ag/skynet,JiessieDawn/skynet,bigrpg/skynet,sanikoyes/skynet,pigparadise/skynet,korialuo/skynet,bigrpg/skynet,pigparadise/skynet,jxlczjp77/skynet,xcjmine/skynet,jxlczjp77/skynet,ag6ag/skynet,JiessieDawn/skynet,hongling0/skynet,icetoggle/skynet,xcjmine/skynet,JiessieDawn/skynet
0983fc30d532afcf59d7dcc9d9b1b289320721b8
telnet.lua
telnet.lua
-- -- setup a telnet server that hooks the sockets input -- local client local server local function sendout(str) if client then client:send(str) end end local function onReceive(sock, input) node.input(input) end local function onDisconnect(sock) node.output(nil) client = nil end local function listen(sock) if server then sock:send("Already in use.\n") sock:close() return end client = sock node.output(sendout, 0) sock:on("receive", onReceive) sock:on("disconnection", onDisconnect) sock:send("NodeMCU\n") end local function open() server = net.createServer(net.TCP, 180) server:listen(23, listen) end local function close() server:close() server = nil end return { open = open, close = close }
-- -- setup a telnet server that hooks the sockets input -- local client local server local function sendout(str) if client then client:send(str) end end local function onReceive(sock, input) node.input(input) end local function onDisconnect(sock) node.output(nil) client = nil end local function listen(sock) if client then sock:send("Already in use.\n") sock:close() return end client = sock node.output(sendout, 0) sock:on("receive", onReceive) sock:on("disconnection", onDisconnect) sock:send("NodeMCU\n") end local function open() server = net.createServer(net.TCP, 180) server:listen(23, listen) end local function close() if client then client:close() client = nil end if server then server:close() server = nil end end return { open = open, close = close }
screwed up telnet. fixed.
screwed up telnet. fixed.
Lua
mit
realraum/r3LoTHRPipeLEDs,realraum/r3LoTHRPipeLEDs
d2379fc6e6680fb316a1bdc937a10ccab4176b1c
frontend/device/remarkable/device.lua
frontend/device/remarkable/device.lua
local Generic = require("device/generic/device") -- <= look at this file! local TimeVal = require("ui/timeval") local logger = require("logger") local function yes() return true end local function no() return false end local EV_ABS = 3 local ABS_X = 00 local ABS_Y = 01 local ABS_MT_POSITION_X = 53 local ABS_MT_POSITION_Y = 54 -- Resolutions from libremarkable src/framebuffer/common.rs local screen_width = 1404 -- unscaled_size_check: ignore local screen_height = 1872 -- unscaled_size_check: ignore local wacom_width = 15725 -- unscaled_size_check: ignore local wacom_height = 20967 -- unscaled_size_check: ignore local wacom_scale_x = screen_width / wacom_width local wacom_scale_y = screen_height / wacom_height local Remarkable = Generic:new{ isRemarkable = yes, hasKeys = yes, needsScreenRefreshAfterResume = no, hasOTAUpdates = yes, canReboot = yes, canPowerOff = yes, isTouchDevice = yes, hasFrontlight = no, display_dpi = 226, -- Despite the SoC supporting it, it's finicky in practice (#6772) canHWInvert = no, home_dir = "/home/root", } local Remarkable1 = Remarkable:new{ model = "reMarkable", mt_width = 767, -- unscaled_size_check: ignore mt_height = 1023, -- unscaled_size_check: ignore input_wacom = "/dev/input/event0", input_ts = "/dev/input/event1", input_buttons = "/dev/input/event2", battery_path = "/sys/class/power_supply/bq27441-0/capacity", status_path = "/sys/class/power_supply/bq27441-0/status", } function Remarkable1:adjustTouchEvent(ev, by) if ev.type == EV_ABS then ev.time = TimeVal:now() -- Mirror X and Y and scale up both X & Y as touch input is different res from -- display if ev.code == ABS_MT_POSITION_X then ev.value = (Remarkable1.mt_width - ev.value) * by.mt_scale_x end if ev.code == ABS_MT_POSITION_Y then ev.value = (Remarkable1.mt_height - ev.value) * by.mt_scale_y end end end local Remarkable2 = Remarkable:new{ model = "reMarkable 2", mt_width = 1403, -- unscaled_size_check: ignore mt_height = 1871, -- unscaled_size_check: ignore input_wacom = "/dev/input/event1", input_ts = "/dev/input/event2", input_buttons = "/dev/input/event0", battery_path = "/sys/class/power_supply/max77818_battery/capacity", status_path = "/sys/class/power_supply/max77818-charger/status", } function Remarkable2:adjustTouchEvent(ev, by) if ev.type == EV_ABS then ev.time = TimeVal:now() -- Mirror Y and scale up both X & Y as touch input is different res from -- display if ev.code == ABS_MT_POSITION_X then ev.value = (ev.value) * by.mt_scale_x end if ev.code == ABS_MT_POSITION_Y then ev.value = (Remarkable2.mt_height - ev.value) * by.mt_scale_y end end end local adjustAbsEvt = function(self, ev) if ev.type == EV_ABS then if ev.code == ABS_X then ev.code = ABS_Y ev.value = (wacom_height - ev.value) * wacom_scale_y elseif ev.code == ABS_Y then ev.code = ABS_X ev.value = ev.value * wacom_scale_x end end end function Remarkable:init() self.screen = require("ffi/framebuffer_mxcfb"):new{device = self, debug = logger.dbg} self.powerd = require("device/remarkable/powerd"):new{ device = self, capacity_file = self.battery_path, status_file = self.status_path, } self.input = require("device/input"):new{ device = self, event_map = require("device/remarkable/event_map"), } self.input.open(self.input_wacom) -- Wacom self.input.open(self.input_ts) -- Touchscreen self.input.open(self.input_buttons) -- Buttons local scalex = screen_width / self.mt_width local scaley = screen_height / self.mt_height self.input:registerEventAdjustHook(adjustAbsEvt) self.input:registerEventAdjustHook(self.adjustTouchEvent, {mt_scale_x=scalex, mt_scale_y=scaley}) -- USB plug/unplug, battery charge/not charging are generated as fake events self.input.open("fake_events") local rotation_mode = self.screen.ORIENTATION_PORTRAIT self.screen.native_rotation_mode = rotation_mode self.screen.cur_rotation_mode = rotation_mode Generic.init(self) end function Remarkable:supportsScreensaver() return true end function Remarkable:setDateTime(year, month, day, hour, min, sec) if hour == nil or min == nil then return true end local command if year and month and day then command = string.format("timedatectl set-time '%d-%d-%d %d:%d:%d'", year, month, day, hour, min, sec) else command = string.format("timedatectl set-time '%d:%d'",hour, min) end return os.execute(command) == 0 end function Remarkable:suspend() os.execute("systemctl suspend") end function Remarkable:resume() end function Remarkable:powerOff() os.execute("systemctl poweroff") end function Remarkable:reboot() os.execute("systemctl reboot") end local f = io.open("/sys/devices/soc0/machine") if not f then error("missing sysfs entry for a remarkable") end local deviceType = f:read("*line") f:close() logger.info("deviceType: ", deviceType) if deviceType == "reMarkable 2.0" then if not os.getenv("RM2FB_SHIM") then error("reMarkable2 requires RM2FB to work (https://github.com/ddvk/remarkable2-framebuffer)") end return Remarkable2 else return Remarkable1 end
local Generic = require("device/generic/device") -- <= look at this file! local TimeVal = require("ui/timeval") local logger = require("logger") local function yes() return true end local function no() return false end local EV_ABS = 3 local ABS_X = 00 local ABS_Y = 01 local ABS_MT_POSITION_X = 53 local ABS_MT_POSITION_Y = 54 -- Resolutions from libremarkable src/framebuffer/common.rs local screen_width = 1404 -- unscaled_size_check: ignore local screen_height = 1872 -- unscaled_size_check: ignore local wacom_width = 15725 -- unscaled_size_check: ignore local wacom_height = 20967 -- unscaled_size_check: ignore local wacom_scale_x = screen_width / wacom_width local wacom_scale_y = screen_height / wacom_height local Remarkable = Generic:new{ isRemarkable = yes, hasKeys = yes, needsScreenRefreshAfterResume = no, hasOTAUpdates = yes, canReboot = yes, canPowerOff = yes, isTouchDevice = yes, hasFrontlight = no, display_dpi = 226, -- Despite the SoC supporting it, it's finicky in practice (#6772) canHWInvert = no, home_dir = "/home/root", } local Remarkable1 = Remarkable:new{ model = "reMarkable", mt_width = 767, -- unscaled_size_check: ignore mt_height = 1023, -- unscaled_size_check: ignore input_wacom = "/dev/input/event0", input_ts = "/dev/input/event1", input_buttons = "/dev/input/event2", battery_path = "/sys/class/power_supply/bq27441-0/capacity", status_path = "/sys/class/power_supply/bq27441-0/status", } function Remarkable1:adjustTouchEvent(ev, by) if ev.type == EV_ABS then ev.time = TimeVal:now() -- Mirror X and Y and scale up both X & Y as touch input is different res from -- display if ev.code == ABS_MT_POSITION_X then ev.value = (Remarkable1.mt_width - ev.value) * by.mt_scale_x end if ev.code == ABS_MT_POSITION_Y then ev.value = (Remarkable1.mt_height - ev.value) * by.mt_scale_y end end end local Remarkable2 = Remarkable:new{ model = "reMarkable 2", mt_width = 1403, -- unscaled_size_check: ignore mt_height = 1871, -- unscaled_size_check: ignore input_wacom = "/dev/input/event1", input_ts = "/dev/input/event2", input_buttons = "/dev/input/event0", battery_path = "/sys/class/power_supply/max77818_battery/capacity", status_path = "/sys/class/power_supply/max77818-charger/status", } function Remarkable2:adjustTouchEvent(ev, by) if ev.type == EV_ABS then ev.time = TimeVal:now() -- Mirror Y and scale up both X & Y as touch input is different res from -- display if ev.code == ABS_MT_POSITION_X then ev.value = (ev.value) * by.mt_scale_x end if ev.code == ABS_MT_POSITION_Y then ev.value = (Remarkable2.mt_height - ev.value) * by.mt_scale_y end end end local adjustAbsEvt = function(self, ev) if ev.type == EV_ABS then if ev.code == ABS_X then ev.code = ABS_Y ev.value = (wacom_height - ev.value) * wacom_scale_y elseif ev.code == ABS_Y then ev.code = ABS_X ev.value = ev.value * wacom_scale_x end end end function Remarkable:init() self.screen = require("ffi/framebuffer_mxcfb"):new{device = self, debug = logger.dbg} self.powerd = require("device/remarkable/powerd"):new{ device = self, capacity_file = self.battery_path, status_file = self.status_path, } self.input = require("device/input"):new{ device = self, event_map = require("device/remarkable/event_map"), } self.input.open(self.input_wacom) -- Wacom self.input.open(self.input_ts) -- Touchscreen self.input.open(self.input_buttons) -- Buttons local scalex = screen_width / self.mt_width local scaley = screen_height / self.mt_height self.input:registerEventAdjustHook(adjustAbsEvt) self.input:registerEventAdjustHook(self.adjustTouchEvent, {mt_scale_x=scalex, mt_scale_y=scaley}) -- USB plug/unplug, battery charge/not charging are generated as fake events self.input.open("fake_events") local rotation_mode = self.screen.ORIENTATION_PORTRAIT self.screen.native_rotation_mode = rotation_mode self.screen.cur_rotation_mode = rotation_mode Generic.init(self) end function Remarkable:supportsScreensaver() return true end function Remarkable:setDateTime(year, month, day, hour, min, sec) if hour == nil or min == nil then return true end local command if year and month and day then command = string.format("timedatectl set-time '%d-%d-%d %d:%d:%d'", year, month, day, hour, min, sec) else command = string.format("timedatectl set-time '%d:%d'",hour, min) end return os.execute(command) == 0 end function Remarkable:suspend() os.execute("systemctl suspend") end function Remarkable:resume() end function Remarkable:powerOff() self.screen:clear() self.screen:refreshFull() os.execute("systemctl poweroff") end function Remarkable:reboot() os.execute("systemctl reboot") end local f = io.open("/sys/devices/soc0/machine") if not f then error("missing sysfs entry for a remarkable") end local deviceType = f:read("*line") f:close() logger.info("deviceType: ", deviceType) if deviceType == "reMarkable 2.0" then if not os.getenv("RM2FB_SHIM") then error("reMarkable2 requires RM2FB to work (https://github.com/ddvk/remarkable2-framebuffer)") end return Remarkable2 else return Remarkable1 end
remarkable: poweroff.png ghosting fix (#7051)
remarkable: poweroff.png ghosting fix (#7051)
Lua
agpl-3.0
NiLuJe/koreader,Markismus/koreader,mwoz123/koreader,poire-z/koreader,poire-z/koreader,Frenzie/koreader,koreader/koreader,koreader/koreader,Hzj-jie/koreader,NiLuJe/koreader,Frenzie/koreader,pazos/koreader
023e96c95c9c4fdbe6e0e7ef6e52f8062279b01d
hostinfo/init.lua
hostinfo/init.lua
--[[ Copyright 2014 Rackspace Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local fs = require('fs') local json = require('json') local los = require('los') local async = require('async') local path = require('path') local HostInfo = require('./base').HostInfo local classes = require('./all') local function create_class_info() local map = {} local types = {} for x, klass in pairs(classes) do if klass.Info then klass = klass.Info end map[klass.getType()] = klass table.insert(types, klass.getType()) end return {map = map, types = types} end local CLASS_INFO = create_class_info() local HOST_INFO_MAP = CLASS_INFO.map local HOST_INFO_TYPES = CLASS_INFO.types --[[ NilInfo ]]-- local NilInfo = HostInfo:extend() function NilInfo:initialize() HostInfo.initialize(self) self._error = 'Agent does not support this Host Info type' end --[[ Factory ]]-- local function create(infoType) local klass = HOST_INFO_MAP[infoType] if klass then if klass.Info then return klass.Info:new() else return klass:new() end end return NilInfo:new() end -- [[ Types ]]-- local function getTypes() return HOST_INFO_TYPES end -- [[ Suite of debug util functions ]] -- local function debugInfo(infoType, callback) if not callback then callback = function() print('Running hostinfo of type: ' .. infoType) end end local klass = create(infoType) klass:run(function(err) local data = '{"Debug":{"InfoType":"' .. infoType .. '", "OS":"' .. los.type() .. '"}}\n\n' if err then data = data .. json.stringify({error = err}) else data = data .. json.stringify(klass:serialize(), {indent = 2}) end callback(data) end) end local function debugInfoAll(callback) local data = '' async.forEachLimit(HOST_INFO_TYPES, 5, function(infoType, cb) debugInfo(infoType, function(debugData) data = data .. debugData cb() end) end, function() callback(data) end) end local function debugInfoToFile(infoType, fileName, callback) debugInfo(infoType, function(debugData) fs.writeFile(fileName, debugData, callback) end) end local function debugInfoAllToFile(fileName, callback) debugInfoAll(function(data) fs.writeFile(fileName, data, callback) end) end local function debugInfoAllToFolder(folderName, callback) fs.mkdirSync(folderName) async.forEachLimit(HOST_INFO_TYPES, 5, function(infoType, cb) debugInfo(infoType, function(debugData) fs.writeFile(path.join(folderName, infoType .. '.json'), debugData, cb) end) end, function() callback() end) end local function debugInfoAllTime(callback) local data = {} async.forEachLimit(HOST_INFO_TYPES, 5, function(infoType, cb) local start = os.clock() debugInfo(infoType, function(_) local endTime = os.clock() - start data[infoType] = endTime cb() end) end, function() callback(json.stringify(data, {indent = 2})) end) end local function debugInfoAllSize(callback) local folderName = 'tempDebug' local data = {} data.hostinfos = {} local totalSize = 0 debugInfoAllToFolder(folderName, function() local files = fs.readdirSync(folderName) async.forEachLimit(files, 5, function(file, cb) local size = fs.statSync(path.join(folderName, file))['size'] totalSize = totalSize + size data.hostinfos[file:sub(0, -6)] = size cb() end, function() fs.unlinkSync(folderName) data.total_size = totalSize callback(json.stringify(data, {indent = 2})) end) end) end --[[ Exports ]]-- local exports = {} exports.create = create exports.classes = classes exports.getTypes = getTypes exports.debugInfo = debugInfo exports.debugInfoToFile = debugInfoToFile exports.debugInfoAll = debugInfoAll exports.debugInfoAllToFile = debugInfoAllToFile exports.debugInfoAllToFolder = debugInfoAllToFolder exports.debugInfoAllTime = debugInfoAllTime exports.debugInfoAllSize = debugInfoAllSize return exports
--[[ Copyright 2014 Rackspace Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local fs = require('fs') local json = require('json') local los = require('los') local async = require('async') local path = require('path') local HostInfo = require('./base').HostInfo local classes = require('./all') local uv = require('uv') local function create_class_info() local map = {} local types = {} for x, klass in pairs(classes) do if klass.Info then klass = klass.Info end map[klass.getType()] = klass table.insert(types, klass.getType()) end return {map = map, types = types} end local CLASS_INFO = create_class_info() local HOST_INFO_MAP = CLASS_INFO.map local HOST_INFO_TYPES = CLASS_INFO.types --[[ NilInfo ]]-- local NilInfo = HostInfo:extend() function NilInfo:initialize() HostInfo.initialize(self) self._error = 'Agent does not support this Host Info type' end --[[ Factory ]]-- local function create(infoType) local klass = HOST_INFO_MAP[infoType] if klass then if klass.Info then return klass.Info:new() else return klass:new() end end return NilInfo:new() end -- [[ Types ]]-- local function getTypes() return HOST_INFO_TYPES end -- [[ Suite of debug util functions ]] -- local function debugInfo(infoType, callback) if not callback then callback = function() print('Running hostinfo of type: ' .. infoType) end end local klass = create(infoType) klass:run(function(err) local data = '{"Debug":{"InfoType":"' .. infoType .. '", "OS":"' .. los.type() .. '"}}\n\n' if err then data = data .. json.stringify({error = err}) else data = data .. json.stringify(klass:serialize(), {indent = 2}) end callback(data) end) end local function debugInfoAll(callback) local data = '' async.forEachLimit(HOST_INFO_TYPES, 5, function(infoType, cb) debugInfo(infoType, function(debugData) data = data .. debugData cb() end) end, function() callback(data) end) end local function debugInfoToFile(infoType, fileName, callback) debugInfo(infoType, function(debugData) fs.writeFile(fileName, debugData, callback) end) end local function debugInfoAllToFile(fileName, callback) debugInfoAll(function(data) fs.writeFile(fileName, data, callback) end) end local function debugInfoAllToFolder(folderName, callback) fs.mkdirSync(folderName) async.forEachLimit(HOST_INFO_TYPES, 5, function(infoType, cb) debugInfo(infoType, function(debugData) fs.writeFile(path.join(folderName, infoType .. '.json'), debugData, cb) end) end, function() callback() end) end local function debugInfoAllTime(callback) local data = {} async.forEachLimit(HOST_INFO_TYPES, 5, function(infoType, cb) local start = uv.hrtime() debugInfo(infoType, function(_) local endTime = uv.hrtime() - start data[infoType] = endTime / 10000 cb() end) end, function() callback(json.stringify(data, {indent = 2})) end) end local function debugInfoAllSize(callback) local folderName = 'tempDebug' local data = {} data.hostinfos = {} local totalSize = 0 debugInfoAllToFolder(folderName, function() local files = fs.readdirSync(folderName) async.forEachLimit(files, 5, function(file, cb) local size = fs.statSync(path.join(folderName, file))['size'] totalSize = totalSize + size data.hostinfos[file:sub(0, -6)] = size cb() end, function() fs.unlinkSync(folderName) data.total_size = totalSize callback(json.stringify(data, {indent = 2})) end) end) end --[[ Exports ]]-- local exports = {} exports.create = create exports.classes = classes exports.getTypes = getTypes exports.debugInfo = debugInfo exports.debugInfoToFile = debugInfoToFile exports.debugInfoAll = debugInfoAll exports.debugInfoAllToFile = debugInfoAllToFile exports.debugInfoAllToFolder = debugInfoAllToFolder exports.debugInfoAllTime = debugInfoAllTime exports.debugInfoAllSize = debugInfoAllSize return exports
fix(debug timer): use uv.hrtime since os.clock doesnt work properly on centos, divide by 10k to make numbers easy to grok
fix(debug timer): use uv.hrtime since os.clock doesnt work properly on centos, divide by 10k to make numbers easy to grok
Lua
apache-2.0
AlphaStaxLLC/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent
5244090ac7e4a5126a8a20b1b41baa2cf3944a9c
MMOCoreORB/bin/scripts/screenplays/tasks/hero_of_tatooine/conversations/heroOfTatRanchersWifeConvoHandler.lua
MMOCoreORB/bin/scripts/screenplays/tasks/hero_of_tatooine/conversations/heroOfTatRanchersWifeConvoHandler.lua
local ObjectManager = require("managers.object.object_manager") heroOfTatRanchersWifeConvoHandler = { } function heroOfTatRanchersWifeConvoHandler:getNextConversationScreen(pConversationTemplate, pPlayer, selectedOption, pConversingNpc) return ObjectManager.withCreatureObject(pPlayer, function(player) local pConversationSession = player:getConversationSession() local pLastConversationScreen = nil if (pConversationSession ~= nil) then local conversationSession = LuaConversationSession(pConversationSession) pLastConversationScreen = conversationSession:getLastConversationScreen() end local conversationTemplate = LuaConversationTemplate(pConversationTemplate) if (pLastConversationScreen ~= nil) then local lastConversationScreen = LuaConversationScreen(pLastConversationScreen) local optionLink = lastConversationScreen:getOptionLink(selectedOption) return conversationTemplate:getScreen(optionLink) end return self:getInitialScreen(pPlayer, pConversingNpc, pConversationTemplate) end) end function heroOfTatRanchersWifeConvoHandler:getInitialScreen(pPlayer, pNpc, pConversationTemplate) return ObjectManager.withCreatureObject(pPlayer, function(player) local convoTemplate = LuaConversationTemplate(pConversationTemplate) local inProgressID = readData("hero_of_tat:ranch_player_id") if (inProgressID ~= 0 and inProgressID ~= player:getObjectID()) then return convoTemplate:getScreen("intro_otherinprogress") elseif (player:hasScreenPlayState(2, "hero_of_tatooine_honor")) then return convoTemplate:getScreen("intro_noquest") elseif (not player:hasScreenPlayState(2, "hero_of_tatooine_honor") and player:hasScreenPlayState(1, "hero_of_tatooine_honor") and readData(player:getObjectID() .. ":hero_of_tat_honor:accepted") == 1) then if (readData(player:getObjectID() .. ":hero_of_tat_honor:distracting_wife") == 1) then return convoTemplate:getScreen("intro_distract") else return convoTemplate:getScreen("intro_hasquest") end elseif (readData(player:getObjectID() .. ":hero_of_tat_honor:spoke_to_wife") == 1) then return convoTemplate:getScreen("intro_leftprior") else return convoTemplate:getScreen("intro") end end) end function heroOfTatRanchersWifeConvoHandler:runScreenHandlers(conversationTemplate, conversingPlayer, conversingNPC, selectedOption, conversationScreen) local screen = LuaConversationScreen(conversationScreen) local screenID = screen:getScreenID() local conversationScreen = screen:cloneScreen() local clonedConversation = LuaConversationScreen(conversationScreen) if (screenID == "leave_now") then writeData(CreatureObject(conversingPlayer):getObjectID() .. ":hero_of_tat_honor:spoke_to_wife", 1) elseif (screenID == "thanks_intercom") then HeroOfTatooineScreenPlay:doHonorStart(conversingPlayer) elseif (screenID == "so_nice_ahh") then HeroOfTatooineScreenPlay:doHonorFail(conversingPlayer) elseif (screenID == "cant_believe_this") then HeroOfTatooineScreenPlay:doHonorSuccess(conversingPlayer) HeroOfTatooineScreenPlay:doSuccessHonorPhase(conversingPlayer) end return conversationScreen end
local ObjectManager = require("managers.object.object_manager") heroOfTatRanchersWifeConvoHandler = { } function heroOfTatRanchersWifeConvoHandler:getNextConversationScreen(pConversationTemplate, pPlayer, selectedOption, pConversingNpc) return ObjectManager.withCreatureObject(pPlayer, function(player) local pConversationSession = player:getConversationSession() local pLastConversationScreen = nil if (pConversationSession ~= nil) then local conversationSession = LuaConversationSession(pConversationSession) pLastConversationScreen = conversationSession:getLastConversationScreen() end local conversationTemplate = LuaConversationTemplate(pConversationTemplate) if (pLastConversationScreen ~= nil) then local lastConversationScreen = LuaConversationScreen(pLastConversationScreen) local optionLink = lastConversationScreen:getOptionLink(selectedOption) return conversationTemplate:getScreen(optionLink) end return self:getInitialScreen(pPlayer, pConversingNpc, pConversationTemplate) end) end function heroOfTatRanchersWifeConvoHandler:getInitialScreen(pPlayer, pNpc, pConversationTemplate) return ObjectManager.withCreatureObject(pPlayer, function(player) local convoTemplate = LuaConversationTemplate(pConversationTemplate) local inProgressID = readData("hero_of_tat:ranch_player_id") if (inProgressID ~= 0 and inProgressID ~= player:getObjectID()) then return convoTemplate:getScreen("intro_otherinprogress") elseif (player:hasScreenPlayState(2, "hero_of_tatooine_honor")) then return convoTemplate:getScreen("intro_noquest") elseif (not player:hasScreenPlayState(2, "hero_of_tatooine_honor") and player:hasScreenPlayState(1, "hero_of_tatooine_honor") and readData(player:getObjectID() .. ":hero_of_tat_honor:accepted") == 1) then if (readData(player:getObjectID() .. ":hero_of_tat_honor:distracting_wife") == 1) then return convoTemplate:getScreen("intro_distract") else return convoTemplate:getScreen("intro_hasquest") end elseif (readData(player:getObjectID() .. ":hero_of_tat_honor:spoke_to_wife") == 1) then return convoTemplate:getScreen("intro_leftprior") else return convoTemplate:getScreen("intro") end end) end function heroOfTatRanchersWifeConvoHandler:runScreenHandlers(conversationTemplate, conversingPlayer, conversingNPC, selectedOption, conversationScreen) local screen = LuaConversationScreen(conversationScreen) local screenID = screen:getScreenID() local conversationScreen = screen:cloneScreen() local clonedConversation = LuaConversationScreen(conversationScreen) if (screenID == "leave_now") then writeData(CreatureObject(conversingPlayer):getObjectID() .. ":hero_of_tat_honor:spoke_to_wife", 1) elseif (screenID == "thanks_intercom") then local inProgressID = readData("hero_of_tat:ranch_player_id") if (inProgressID ~= 0 and inProgressID ~= SceneObject(conversingPlayer):getObjectID()) then clonedConversation:setDialogTextStringId("@conversation/quest_hero_of_tatooine_wife:s_c74cdffb") else HeroOfTatooineScreenPlay:doHonorStart(conversingPlayer) end elseif (screenID == "so_nice_ahh") then HeroOfTatooineScreenPlay:doHonorFail(conversingPlayer) elseif (screenID == "cant_believe_this") then HeroOfTatooineScreenPlay:doHonorSuccess(conversingPlayer) HeroOfTatooineScreenPlay:doSuccessHonorPhase(conversingPlayer) end return conversationScreen end
[fixed] Hero of Tat Rancher's Wife quest issue when multiple people converse at once - mantis 6407
[fixed] Hero of Tat Rancher's Wife quest issue when multiple people converse at once - mantis 6407 Change-Id: If03ccc456d539d50930d45a9a39bcfc771f0335e
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
0e26605f9d5f3534f8a7d4efcf553c1f92c8f82e
examples/class/another.lua
examples/class/another.lua
package.path = package.path .. ";./lib/?.lua" local example = require 'lux.oo.class' :package 'example' function example:Another(the_x, the_y) local x, y = the_x, the_y print "new" function self:move (dx, dy) x = self:getX(33)+dx y = y+dy print('moved!', x, y) end function self:getX(tmp) return tmp or x end function self.__meta:__call (...) print("call", x, y, ...) end function self:clone () return self.__class(x, y) end end print(example.Another) p = example.Another(2,2) p:move(1, -1) p:clone() 'test' function example:Master() example.Another:inherit(self, 42, 42) local z = self:getX() + 10 print("HAHA") function self:show () print "hey" self("child", z) end end q = example.Master() q:move(4, 4) q:show()
package.path = package.path .. ";./lib/?.lua" local example = require 'lux.oo.class' .package 'example' -- This is a class definition function example:Another(the_x, the_y) local x, y = the_x, the_y print "new" function self:move (dx, dy) x = self:getX(33)+dx y = y+dy print('moved!', x, y) end function self:getX(tmp) return tmp or x end function self.__meta:__call (...) print("call", x, y, ...) end function self:clone () return self.__class(x, y) end end print(example.Another) p = example.Another(2,2) p:move(1, -1) p:clone() 'test' -- This class inherits the previous one function example:Master() example.Another:inherit(self, 42, 42) local z = self:getX() + 10 print("HAHA") function self:show () print "hey" self("child", z) end end q = example.Master() q:move(4, 4) q:show()
Small fixes in the class example
Small fixes in the class example
Lua
mit
Kazuo256/luxproject
187d55ab8cffb1267677c620eeb216a53493e56a
release/lua/http-server.lua
release/lua/http-server.lua
--- Turbo.lua Hello world using HTTPServer -- -- Using the HTTPServer offers more control for the user, but less convenience. -- In almost all cases you want to use turbo.web.RequestHandler. -- -- Copyright 2013 John Abrahamsen -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. local arg = {...} -- *********************************************************************** package.path = package.path..";network/?.lua" package.path = package.path..";lua/?.lua" package.cpath = package.cpath..";bin/win64/?.dll" -- *********************************************************************** local ffi = require("ffi") local bit = require("bit") local floor = math.floor local turbo = require "turbo" local cmd = require "commands" -- *********************************************************************** -- RS232 Setup for interface rs232 = require("sys-comm") bauds = { 9600, 19200, 38400, 57600, 115200 } baud_rate = 1 serial_name = "COM5" serial_update = 2000 -- *********************************************************************** -- This will turn into pin configs. analog_output = { 0, 0, 0, 0, 0 } digital_output = { -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0 } -- Mapping for Arduino Nano AOP = { 0,1,2,3,4,5,6,7,8,9,10,11,12,13 } -- *********************************************************************** read_data = "" require("http-interface") -- *********************************************************************** -- Handler that takes a single argument 'username' local BasePageHandler = class("BasePageHandler", turbo.web.RequestHandler) function BasePageHandler:get(data, stuff) WritePage(self) if(data == "ttq") then turbo.ioloop.instance():close() end end -- *********************************************************************** -- Handler that takes a single argument 'username' local CodePageHandler = class("CodePageHandler", turbo.web.RequestHandler) function CodePageHandler:get(data, stuff) WriteCodePage(self) end -- *********************************************************************** -- Handler that takes a single argument 'username' local CommEnableHandler = class("CommEnableHandler", turbo.web.RequestHandler) function CommEnableHandler:get(data, stuff) rs232:InitComms() if rs232.fd == nil then read_data = read_data.."-------- Serial Error --------<br>" else read_data = read_data.."----- Serial Port Reset ------<br>" end -- Reset the server.. just to make sure the data is fresh. self:redirect("/index.html", false) end -- *********************************************************************** -- Handler that takes a single argument 'username' local ConfigHandler = class("ConfigHandler", turbo.web.RequestHandler) function ConfigHandler:get() serial_name = self:get_argument("name", "COM5", true) serial_update = tonumber(self:get_argument("rate", "2000", true)) --print("Check: ", serial_name, serial_update) self:redirect("/index.html?"..tostring(getVal()), false) end -- *********************************************************************** -- Handler that takes a single argument 'username' local AnalogHandler = class("AnalogHandler", turbo.web.RequestHandler) function AnalogHandler:get(data) local input = tonumber(self:get_argument("input", 1, true)) if input > 0 and input < 5 then self:write(tostring(analog_output[input])) else self:write("0") end end -- *********************************************************************** -- Handler that takes a single argument intput for the data id local DigitalHandler = class("DigitalHandler", turbo.web.RequestHandler) function DigitalHandler:get(data) local input = (self:get_argument("input", "", true)) if input ~= "" then local outdata = "" local k = tonumber(input) -- Check digital local v = digital_output[k] if v ~= -1 then if v > 0 then outdata = "img/button_green.png" else outdata = "img/button_red.png" end else outdata = "img/button_grey.png" end self:write(outdata) end end -- *********************************************************************** -- Handler that takes a single argument 'username' local CommHandler = class("CommHandler", turbo.web.RequestHandler) function CommHandler:get(data) local c = sys.msec() cmd:ReadAnalog() cmd:ReadDigital() local d = rs232:ReadComms() local data = cmd:CheckCommand(d) if data ~= "nil" then if string.len(data) > 1 then data = string.gsub(data, "\n", "<br>") read_data = read_data..data end end cmd:UpdateOutput(rs232, 6) self:write(read_data) --self:redirect("/index.html", false) end -- *********************************************************************** local AnalogInputHandler = class("AnalogInputHandler", turbo.web.RequestHandler) function AnalogInputHandler:post() local data = self:get_argument("aod", "0.0", true) local ival = self:get_argument("aot", "1", true) -- print("AnalogInput: ", ival, data) local output = cmd:BuildCommand("W", AOP[tonumber(ival)], math.floor(data * 1023.0)) if output then cmd:WriteCommand( output ) end end -- *********************************************************************** local app = turbo.web.Application:new({ -- Serve single index.html file on root requests. {"^/enablecomms.html", CommEnableHandler}, {"^/readcomms.html", CommHandler}, {"^/configcomms.html(.*)", ConfigHandler}, {"^/readanalog.html(.*)", AnalogHandler}, {"^/readdigital.html(.*)", DigitalHandler}, {"^/analoginput.html(.*)", AnalogInputHandler}, {"^/code_page.html(.*)", CodePageHandler}, {"^/index.html(.*)", BasePageHandler}, {"^/img/(.*)", turbo.web.StaticFileHandler, "www/img/"}, {"^/$", turbo.web.StaticFileHandler, "www/index.html"}, -- Serve contents of directory. {"^/(.*)$", turbo.web.StaticFileHandler, "www/"} }) -- *********************************************************************** app:set_server_name("WebDruino Server") local srv = turbo.httpserver.HTTPServer(app) srv:bind(8888) srv:start(1) -- Adjust amount of processes to fork - does nothing at moment. turbo.ioloop.instance():start() -- *********************************************************************** rs232:CloseComms() -- ***********************************************************************
--- Turbo.lua Hello world using HTTPServer -- -- Using the HTTPServer offers more control for the user, but less convenience. -- In almost all cases you want to use turbo.web.RequestHandler. -- -- Copyright 2013 John Abrahamsen -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. local arg = {...} -- *********************************************************************** package.path = package.path..";network/?.lua" package.path = package.path..";lua/?.lua" local ffi = require("ffi") if ffi.os == "Windows" then if ffi.abi("32bit") then package.cpath = package.cpath..";bin/win32/?.dll" else package.cpath = package.cpath..";bin/win64/?.dll" end end if ffi.os == "Linux" then package.cpath = package.cpath..";bin/linux/?.so" end -- *********************************************************************** local bit = require("bit") local floor = math.floor local turbo = require "turbo" local cmd = require "commands" -- *********************************************************************** -- RS232 Setup for interface rs232 = require("sys-comm") bauds = { 9600, 19200, 38400, 57600, 115200 } baud_rate = 1 serial_name = "COM5" serial_update = 2000 -- *********************************************************************** -- This will turn into pin configs. analog_output = { 0, 0, 0, 0, 0 } digital_output = { -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0 } -- Mapping for Arduino Nano AOP = { 0,1,2,3,4,5,6,7,8,9,10,11,12,13 } -- *********************************************************************** read_data = "" require("http-interface") -- *********************************************************************** -- Handler that takes a single argument 'username' local BasePageHandler = class("BasePageHandler", turbo.web.RequestHandler) function BasePageHandler:get(data, stuff) WritePage(self) if(data == "ttq") then turbo.ioloop.instance():close() end end -- *********************************************************************** -- Handler that takes a single argument 'username' local CodePageHandler = class("CodePageHandler", turbo.web.RequestHandler) function CodePageHandler:get(data, stuff) WriteCodePage(self) end -- *********************************************************************** -- Handler that takes a single argument 'username' local CommEnableHandler = class("CommEnableHandler", turbo.web.RequestHandler) function CommEnableHandler:get(data, stuff) rs232:InitComms() if rs232.fd == nil then read_data = read_data.."-------- Serial Error --------<br>" else read_data = read_data.."----- Serial Port Reset ------<br>" end -- Reset the server.. just to make sure the data is fresh. self:redirect("/index.html", false) end -- *********************************************************************** -- Handler that takes a single argument 'username' local ConfigHandler = class("ConfigHandler", turbo.web.RequestHandler) function ConfigHandler:get() serial_name = self:get_argument("name", "COM5", true) serial_update = tonumber(self:get_argument("rate", "2000", true)) --print("Check: ", serial_name, serial_update) self:redirect("/index.html?"..tostring(getVal()), false) end -- *********************************************************************** -- Handler that takes a single argument 'username' local AnalogHandler = class("AnalogHandler", turbo.web.RequestHandler) function AnalogHandler:get(data) local input = tonumber(self:get_argument("input", 1, true)) if input > 0 and input < 5 then self:write(tostring(analog_output[input])) else self:write("0") end end -- *********************************************************************** -- Handler that takes a single argument intput for the data id local DigitalHandler = class("DigitalHandler", turbo.web.RequestHandler) function DigitalHandler:get(data) local input = (self:get_argument("input", "", true)) if input ~= "" then local outdata = "" local k = tonumber(input) -- Check digital local v = digital_output[k] if v ~= -1 then if v > 0 then outdata = "img/button_green.png" else outdata = "img/button_red.png" end else outdata = "img/button_grey.png" end self:write(outdata) end end -- *********************************************************************** -- Handler that takes a single argument 'username' local CommHandler = class("CommHandler", turbo.web.RequestHandler) function CommHandler:get(data) local c = sys.msec() cmd:ReadAnalog() cmd:ReadDigital() local d = rs232:ReadComms() local data = cmd:CheckCommand(d) if data ~= "nil" then if string.len(data) > 1 then data = string.gsub(data, "\n", "<br>") read_data = read_data..data end end cmd:UpdateOutput(rs232, 6) self:write(read_data) --self:redirect("/index.html", false) end -- *********************************************************************** local AnalogInputHandler = class("AnalogInputHandler", turbo.web.RequestHandler) function AnalogInputHandler:post() local data = self:get_argument("aod", "0.0", true) local ival = self:get_argument("aot", "1", true) -- print("AnalogInput: ", ival, data) local output = cmd:BuildCommand("W", AOP[tonumber(ival)], math.floor(data * 1023.0)) if output then cmd:WriteCommand( output ) end end -- *********************************************************************** local app = turbo.web.Application:new({ -- Serve single index.html file on root requests. {"^/enablecomms.html", CommEnableHandler}, {"^/readcomms.html", CommHandler}, {"^/configcomms.html(.*)", ConfigHandler}, {"^/readanalog.html(.*)", AnalogHandler}, {"^/readdigital.html(.*)", DigitalHandler}, {"^/analoginput.html(.*)", AnalogInputHandler}, {"^/code_page.html(.*)", CodePageHandler}, {"^/index.html(.*)", BasePageHandler}, {"^/img/(.*)", turbo.web.StaticFileHandler, "www/img/"}, {"^/$", turbo.web.StaticFileHandler, "www/index.html"}, -- Serve contents of directory. {"^/(.*)$", turbo.web.StaticFileHandler, "www/"} }) -- *********************************************************************** app:set_server_name("WebDruino Server") local srv = turbo.httpserver.HTTPServer(app) srv:bind(8888) srv:start(1) -- Adjust amount of processes to fork - does nothing at moment. turbo.ioloop.instance():start() -- *********************************************************************** rs232:CloseComms() -- ***********************************************************************
Path fixes
Path fixes Fixed up path problems between Linux and Windows.
Lua
mit
dlannan/webdruino,dlannan/webdruino
2710ed977f3b6677273ddbee2567a17227325a3a
luasrc/search.lua
luasrc/search.lua
local path = require 'pl.path' local file = require 'pl.file' local http = require 'socket.http' function dokx._getVirtualEnvPath() return path.join(dokx._getDokxDir(), "dokx-search", "virtualenv") end local function inVirtualEnv(...) local virtualEnvPath = dokx._getVirtualEnvPath() if not path.isdir(virtualEnvPath) then dokx._installSearchDependencies() end local virtualenv = path.join(virtualEnvPath, "bin/activate") return stringx.join(" ", { 'source', virtualenv, '&&', ... }) end function dokx._installSearchDependencies() dokx.logger:info("Installing dependencies for dokx-search") if not dokx._which("virtualenv") then dokx.logger:error("Cannot find virtualenv command - unable to install dokx-search dependencies") return end if not dokx._which("pip") then dokx.logger:error("Cannot find pip command - unable to install dokx-search dependencies") return end local python = dokx._which("python2.7") if not python then dokx.logger:error("Cannot find python2.7 - unable to install dokx-search dependencies") return end local virtualEnvPath = dokx._getVirtualEnvPath() os.execute("virtualenv --python=" .. python .. " " .. virtualEnvPath) local requirements = path.join(dokx._getDokxDir(), "dokx-search", "requirements.txt") os.execute(inVirtualEnv("pip install -r " .. requirements)) local dokxDaemon = path.join(dokx._getDokxDir(), "dokx-search", "dokxDaemon.py") local virtualEnvLib = path.join(virtualEnvPath, "lib/python2.7") local dest = path.join(virtualEnvLib, "dokxDaemon.py") dokx.logger:info("Copying " .. dokxDaemon .. " -> " .. dest) file.copy(dokxDaemon, dest) end function dokx._runPythonScript(command, ...) local script = path.join(dokx._getDokxDir(), "dokx-search", command) dokx.logger:info("Executing: " .. command) os.execute(inVirtualEnv('python', script, ...)) end function dokx.buildSearchIndex(input, output) if not path.isdir(input) then dokx.logger:error("dokx.buildSearchIndex: input is not a directory - " .. tostring(input)) return end local python = dokx._which("python") if not python then dokx.logger:warn("Python not installed: dokx-search will not be available!") return end local script = path.join(dokx._getDokxDir(), "dokx-search", "dokx-build-search-index.py") if not path.isfile(script) then dokx.logger:warn("dokx-build-search-index.py not available: dokx-search will not be available!") return end dokx._runPythonScript(script, "--output", output, input) end function dokx._daemonIsRunning() local resultRest = http.request("http://localhost:8130/search/") local resultWeb = http.request("http://localhost:5000/") return resultRest ~= nil and resultWeb ~= nil end function dokx.runSearchServices() if dokx._daemonIsRunning() then return end dokx._runPythonScript("rest/dokx-service-rest.py", " --database ", dokx._luarocksSearchDB()) dokx._runPythonScript("web/dokx-service-web.py", "--docs", dokx._luarocksHtmlDir()) end function dokx._searchHTTP(query) return http.request("http://localhost:8130/search/" .. dokx._urlEncode(query) .. "/") end function dokx._searchGrep(query) local grep = dokx._chooseCommand {"ag", "ack", "ack-grep", "grep"} if not grep then dokx.logger:error("doxk.search: can't find grep either - giving up, sorry!") return end local searchDir = path.join(dokx._luarocksHtmlDir(), "_markdown") os.execute(grep .. " --color -r '" .. query .. "' " .. searchDir) end function dokx._browserSearch(query) dokx._openBrowser("http://localhost:5000/search?query=" .. dokx._urlEncode(query)) end function dokx.search(query, browse) local result = dokx._searchHTTP(query) if not result then -- If no response, try to run server first dokx.logger:info("dokx.search: no response; trying to launch search service") dokx.runSearchServices() -- Wait for process to start... (ick!) os.execute("sleep 1") result = dokx._searchHTTP(query) end -- If still no result, fall back to grep if not result then dokx.logger:warn("dokx.search: no result from search process - falling back to grep.") dokx._searchGrep(query) return end if browse then dokx._browserSearch(query) return end -- Decode JSON local json = require 'json' local decoded = json.decode(result) -- Format results local n = decoded.meta.results if n == 0 then print("No results for '" .. decoded.query .. "'.") return end print(n .. " results for '" .. decoded.query .. "':") for id, resultInfo in ipairs(decoded.results) do print(string.rep("-", 80)) print(" #" .. id .. " " .. resultInfo.tag) local snip = resultInfo.snippets[1] local yellow = '\27[1;33m' local clear = '\27[0m' snip = snip:gsub('<b>(.-)</b>', yellow .. '%1' .. clear) print(" ... " .. snip .. " ... \n") end end
local path = require 'pl.path' local file = require 'pl.file' local http = require 'socket.http' function dokx._getVirtualEnvPath() return path.join(dokx._getDokxDir(), "dokx-search", "virtualenv") end local function inVirtualEnv(...) local virtualEnvPath = dokx._getVirtualEnvPath() if not path.isdir(virtualEnvPath) then dokx._installSearchDependencies() end local virtualenv = path.join(virtualEnvPath, "bin/activate") return stringx.join(" ", { 'source', virtualenv, '&&', ... }) end function dokx._installSearchDependencies() dokx.logger:info("Installing dependencies for dokx-search") if not dokx._which("virtualenv") then dokx.logger:error("Cannot find virtualenv command - unable to install dokx-search dependencies") return end if not dokx._which("pip") then dokx.logger:error("Cannot find pip command - unable to install dokx-search dependencies") return end local python = dokx._which("python2.7") if not python then dokx.logger:error("Cannot find python2.7 - unable to install dokx-search dependencies") return end local virtualEnvPath = dokx._getVirtualEnvPath() os.execute("virtualenv --python=" .. python .. " " .. virtualEnvPath) local requirements = path.join(dokx._getDokxDir(), "dokx-search", "requirements.txt") os.execute(inVirtualEnv("pip install -r " .. requirements)) local dokxDaemon = path.join(dokx._getDokxDir(), "dokx-search", "dokxDaemon.py") local virtualEnvLib = path.join(virtualEnvPath, "lib/python2.7") local dest = path.join(virtualEnvLib, "dokxDaemon.py") dokx.logger:info("Copying " .. dokxDaemon .. " -> " .. dest) file.copy(dokxDaemon, dest) end function dokx._runPythonScript(script, ...) local scriptPath = path.join(dokx._getDokxDir(), "dokx-search", script) local command = inVirtualEnv('python', script, ...) dokx.logger:info("Executing: " .. command) os.execute(command) end function dokx.buildSearchIndex(input, output) if not path.isdir(input) then dokx.logger:error("dokx.buildSearchIndex: input is not a directory - " .. tostring(input)) return end local python = dokx._which("python") if not python then dokx.logger:warn("Python not installed: dokx-search will not be available!") return end local script = path.join(dokx._getDokxDir(), "dokx-search", "dokx-build-search-index.py") if not path.isfile(script) then dokx.logger:warn("dokx-build-search-index.py not available: dokx-search will not be available!") return end dokx._runPythonScript(script, "--output", output, input) end function dokx._daemonIsRunning() local resultRest = http.request("http://localhost:8130/search/") local resultWeb = http.request("http://localhost:5000/") return resultRest ~= nil and resultWeb ~= nil end function dokx.runSearchServices() if dokx._daemonIsRunning() then return end dokx._runPythonScript("rest/dokx-service-rest.py", " --database ", dokx._luarocksSearchDB()) dokx._runPythonScript("web/dokx-service-web.py", "--docs", dokx._luarocksHtmlDir()) end function dokx._searchHTTP(query) return http.request("http://localhost:8130/search/" .. dokx._urlEncode(query) .. "/") end function dokx._searchGrep(query) local grep = dokx._chooseCommand {"ag", "ack", "ack-grep", "grep"} if not grep then dokx.logger:error("doxk.search: can't find grep either - giving up, sorry!") return end local searchDir = path.join(dokx._luarocksHtmlDir(), "_markdown") os.execute(grep .. " --color -r '" .. query .. "' " .. searchDir) end function dokx._browserSearch(query) dokx._openBrowser("http://localhost:5000/search?query=" .. dokx._urlEncode(query)) end function dokx.search(query, browse) local result = dokx._searchHTTP(query) if not result then -- If no response, try to run server first dokx.logger:info("dokx.search: no response; trying to launch search service") dokx.runSearchServices() -- Wait for process to start... (ick!) os.execute("sleep 1") result = dokx._searchHTTP(query) end -- If still no result, fall back to grep if not result then dokx.logger:warn("dokx.search: no result from search process - falling back to grep.") dokx._searchGrep(query) return end if browse then dokx._browserSearch(query) return end -- Decode JSON local json = require 'json' local decoded = json.decode(result) -- Format results local n = decoded.meta.results if n == 0 then print("No results for '" .. decoded.query .. "'.") return end print(n .. " results for '" .. decoded.query .. "':") for id, resultInfo in ipairs(decoded.results) do print(string.rep("-", 80)) print(" #" .. id .. " " .. resultInfo.tag) local snip = resultInfo.snippets[1] local yellow = '\27[1;33m' local clear = '\27[0m' snip = snip:gsub('<b>(.-)</b>', yellow .. '%1' .. clear) print(" ... " .. snip .. " ... \n") end end
Fix log message when running search service
Fix log message when running search service
Lua
bsd-3-clause
deepmind/torch-dokx,Gueust/torch-dokx,yozw/torch-dokx,Gueust/torch-dokx,yozw/torch-dokx,deepmind/torch-dokx,Gueust/torch-dokx,yozw/torch-dokx,deepmind/torch-dokx
1b0a9c8d5bb2065f56250b9e83a5196ba50e5b67
app/modules/require.lua
app/modules/require.lua
local uv = require('uv') local luvi = require('luvi') local bundle = luvi.bundle local pathJoin = luvi.path.join local realRequire = require -- Requires are relative local function requireSystem(options) local loader, fixedLoader, finder, generator -- All options are optional options = options or {} -- The name of the function to inject local requireName = options.requireName or "require" -- The name of the folder to look for bundled dependencies local modulesName = options.modulesName or "modules" -- Map of format string to handler function -- Baked in is '#raw' to load a file as a raw string. -- Also is `#lua` (or no format) which loads the file as a module -- And allows it to require it's own dependencies. -- This supports circular dependencies usnig CJS style or -- return the exports at the end of the script. local formatters = {} -- Readers for different I/O prefixes -- Baked in is 'bundle:' for reading out of the luvi bundle -- and 'fs:' (or no prefix) for reading from the filesystem. local readers = { bundle = bundle.readfile } -- Internal table for caching resolved module paths (including prefix and format) to modules. local cachedModules = {} -- Given a callerPath and modulePath return a new modulePath and the raw body function finder(callerPath, modulePath) local prefix, format, base, path local match, newPath, module, err -- Extract format from modulePath format = string.match(modulePath, "#[^#]+$", -10) if format then path = string.sub(modulePath, 1, -#format - 1) format = string.sub(format, 2) else path = modulePath format = 'lua' end -- Extract prefix from callerPath match = string.match(callerPath, "^[^:]+:") if match then if string.match(match, "^[A-Z]:$") then prefix = "fs" base = callerPath else base = string.sub(callerPath, #match + 1) prefix = string.sub(match, 1, -2) end else base = callerPath end -- Extract prefix from path match = string.match(path, "^[^:]+:") if match then if string.match(match, "^[A-Z]:$") then prefix = "fs" else path = string.sub(path, #match + 1) if string.sub(path, 1, 1) == "." then return nil, "Don't use prefix with relative requires" end prefix = string.sub(match, 1, -2) end elseif string.sub(path, 1, 1) == '/' then prefix = 'fs' end -- Resolve relative directly if string.sub(path, 1, 1) == "." then newPath = pathJoin(base, "..", path) module, err = loader(prefix, newPath, format) -- Resolve absolute directly elseif string.sub(path, 1, 1) == "/" or string.sub(path, 1, 1) == "\\" then newPath = path module, err = loader(prefix, newPath, format) -- Search for others else repeat base = pathJoin(base, "..") newPath = pathJoin(base, modulesName, path) module, err = loader(prefix, newPath, format) until module or base == "" or base == "/" or string.match(base, "^[A-Z]:\\$") if not module and prefix ~= "bundle" then -- If it's not found outside the bundle, look there too. module, err = loader("bundle", pathJoin(modulesName, path), format) end end if module then return module.exports, module.path else return nil, err end end -- Common code for loading a module once it's path has been resolved function loader(prefix, path, format) local module, err if string.find(path, "%."..format.."$") then return fixedLoader(prefix, path, format) else module, err = fixedLoader(prefix, path .. '.' .. format, format) if module then return module, err end return fixedLoader(prefix, pathJoin(path, 'init.' .. format), format) end end function fixedLoader(prefix, path, format) local key = prefix .. ":" .. path .. "#" .. format local module = cachedModules[key] if module then return module end local readfile = readers[prefix] if not readfile then error("Unknown prefix: " .. prefix) end local formatter = formatters[format] if not formatter then error("Unknown format: " .. format) end local data, err = readfile(path) if not data then return nil, err end if prefix ~= "fs" then path = prefix .. ":" .. path end module = { format = format, path = path, dir = pathJoin(path, ".."), exports = {} } cachedModules[key] = module local _ _, err = formatter(data, module) if err then return _, err end return module end function formatters.raw (data, module) module.exports = data end function formatters.lua (data, module) local fn = assert(loadstring(data, module.path)) setfenv(fn, setmetatable({ [requireName] = generator(module.path), module = module, exports = module.exports, }, { __index = _G })) local ret = fn() -- Allow returning the exports as well if ret then module.exports = ret end end function readers.fs(path) local fd, stat, chunk, err fd, err = uv.fs_open(path, "r", tonumber("644", 8)) if not fd then return nil, err end stat, err = uv.fs_fstat(fd) if not stat then uv.fs_close(fd) return nil, err end chunk, err = uv.fs_read(fd, stat.size, 0) uv.fs_close(fd) if not chunk then return nil, err end return chunk end -- Mixin extra readers if options.readers then for key, value in pairs(options.readers) do readers[key] = value end end -- Mixin extra formatters if options.formatters then for key, value in pairs(options.formatters) do formatters[key] = value end end function generator(path) return function (name) return finder(path, name) or realRequire(name) end end return generator end return requireSystem
local uv = require('uv') local luvi = require('luvi') local bundle = luvi.bundle local pathJoin = luvi.path.join local realRequire = require -- Requires are relative local function requireSystem(options) local loader, fixedLoader, finder, generator -- All options are optional options = options or {} -- The name of the function to inject local requireName = options.requireName or "require" -- The name of the folder to look for bundled dependencies local modulesName = options.modulesName or "modules" -- Map of format string to handler function -- Baked in is '#raw' to load a file as a raw string. -- Also is `#lua` (or no format) which loads the file as a module -- And allows it to require it's own dependencies. -- This supports circular dependencies usnig CJS style or -- return the exports at the end of the script. local formatters = {} -- Readers for different I/O prefixes -- Baked in is 'bundle:' for reading out of the luvi bundle -- and 'fs:' (or no prefix) for reading from the filesystem. local readers = { bundle = bundle.readfile } -- Internal table for caching resolved module paths (including prefix and format) to modules. local cachedModules = {} -- Given a callerPath and modulePath return a new modulePath and the raw body function finder(callerPath, modulePath) local prefix, format, base, path local match, newPath, module, err -- Extract format from modulePath format = string.match(modulePath, "#[^#]+$", -10) if format then path = string.sub(modulePath, 1, -#format - 1) format = string.sub(format, 2) else path = modulePath format = 'lua' end -- Extract prefix from callerPath match = string.match(callerPath, "^[^:]+:") if match then if string.match(match, "^[A-Z]:$") then prefix = "fs" base = callerPath else base = string.sub(callerPath, #match + 1) prefix = string.sub(match, 1, -2) end else base = callerPath end -- Extract prefix from path match = string.match(path, "^[^:]+:") if match then if string.match(match, "^[A-Z]:$") then prefix = "fs" else path = string.sub(path, #match + 1) if string.sub(path, 1, 1) == "." then return nil, "Don't use prefix with relative requires" end prefix = string.sub(match, 1, -2) end elseif string.sub(path, 1, 1) == '/' then prefix = 'fs' end if not prefix then prefix = 'fs' end -- Resolve relative directly if string.sub(path, 1, 1) == "." then newPath = pathJoin(base, "..", path) module, err = loader(prefix, newPath, format) -- Resolve absolute directly elseif string.sub(path, 1, 1) == "/" or string.sub(path, 1, 1) == "\\" then newPath = path module, err = loader(prefix, newPath, format) -- Search for others else repeat base = pathJoin(base, "..") newPath = pathJoin(base, modulesName, path) module, err = loader(prefix, newPath, format) until module or base == "" or base == "/" or string.match(base, "^[A-Z]:\\$") if not module and prefix ~= "bundle" then -- If it's not found outside the bundle, look there too. module, err = loader("bundle", pathJoin(modulesName, path), format) end end if module then return module.exports, module.path else return nil, err end end -- Common code for loading a module once it's path has been resolved function loader(prefix, path, format) local module, err if string.find(path, "%."..format.."$") then return fixedLoader(prefix, path, format) else module, err = fixedLoader(prefix, path .. '.' .. format, format) if module then return module, err end return fixedLoader(prefix, pathJoin(path, 'init.' .. format), format) end end function fixedLoader(prefix, path, format) local key = prefix .. ":" .. path .. "#" .. format local module = cachedModules[key] if module then return module end local readfile = readers[prefix] if not readfile then error("Unknown prefix: " .. prefix) end local formatter = formatters[format] if not formatter then error("Unknown format: " .. format) end local data, err = readfile(path) if not data then return nil, err end if prefix ~= "fs" then path = prefix .. ":" .. path end module = { format = format, path = path, dir = pathJoin(path, ".."), exports = {} } cachedModules[key] = module local _ _, err = formatter(data, module) if err then return _, err end return module end function formatters.raw (data, module) module.exports = data end function formatters.lua (data, module) local fn = assert(loadstring(data, module.path)) setfenv(fn, setmetatable({ [requireName] = generator(module.path), module = module, exports = module.exports, }, { __index = _G })) local ret = fn() -- Allow returning the exports as well if ret then module.exports = ret end end function readers.fs(path) local fd, stat, chunk, err fd, err = uv.fs_open(path, "r", tonumber("644", 8)) if not fd then return nil, err end stat, err = uv.fs_fstat(fd) if not stat then uv.fs_close(fd) return nil, err end chunk, err = uv.fs_read(fd, stat.size, 0) uv.fs_close(fd) if not chunk then return nil, err end return chunk end -- Mixin extra readers if options.readers then for key, value in pairs(options.readers) do readers[key] = value end end -- Mixin extra formatters if options.formatters then for key, value in pairs(options.formatters) do formatters[key] = value end end function generator(path) return function (name) return finder(path, name) or realRequire(name) end end return generator end return requireSystem
Fix require on non-windows
Fix require on non-windows
Lua
apache-2.0
rjeli/luvit,DBarney/luvit,DBarney/luvit,DBarney/luvit,bsn069/luvit,GabrielNicolasAvellaneda/luvit-upstream,DBarney/luvit,zhaozg/luvit,rjeli/luvit,zhaozg/luvit,GabrielNicolasAvellaneda/luvit-upstream,rjeli/luvit,kaustavha/luvit,luvit/luvit,GabrielNicolasAvellaneda/luvit-upstream,kaustavha/luvit,bsn069/luvit,GabrielNicolasAvellaneda/luvit-upstream,rjeli/luvit,kaustavha/luvit,luvit/luvit,bsn069/luvit
9e11c4eacbc7faa31725355e9017c5fad33fc3cc
src/cosy/loader/js.lua
src/cosy/loader/js.lua
if #setmetatable ({}, { __len = function () return 1 end }) ~= 1 then error "Cosy requires Lua >= 5.2 to run." end return function (options) options = options or {} local loader = {} for k, v in pairs (options) do loader [k] = v end local global = _G or _ENV loader.home = "/" loader.prefix = "/" loader.js = global.js local modules = setmetatable ({}, { __mode = "kv" }) loader.request = function (url, allow_yield) local request = loader.js.new (loader.js.global.XMLHttpRequest) local co = loader.scheduler and loader.scheduler.running () if allow_yield and co then request:open ("GET", url, true) request.onreadystatechange = function () if request.readyState == 4 then loader.scheduler.wakeup (co) end end request:send (nil) loader.scheduler.sleep (-math.huge) else request:open ("GET", url, false) request:send (nil) end if request.status == 200 then return request.responseText, request.status else return nil, request.status end end table.insert (package.searchers, 2, function (name) local url = "/lua/" .. name local result, err = loader.request (url) if not result then error (err) end return load (result, url) end) loader.require = require loader.load = function (name) if modules [name] then return modules [name] end local module = loader.require (name) (loader) or true modules [name] = module return module end loader.coroutine = loader.require "coroutine.make" () loader.logto = true loader.scheduler = { _running = nil, waiting = {}, ready = {}, blocked = {}, coroutine = loader.coroutine, timeout = {}, } function loader.scheduler.running () return loader.scheduler._running end function loader.scheduler.addthread (f, ...) local co = loader.scheduler.coroutine.create (f) loader.scheduler.ready [co] = { parameters = { ... }, } if loader.scheduler.co and coroutine.status (loader.scheduler.co) == "suspended" then coroutine.resume (loader.scheduler.co) end end function loader.scheduler.block (co) loader.scheduler.blocked [co] = true end function loader.scheduler.release (co) loader.scheduler.blocked [co] = nil end function loader.scheduler.sleep (time) time = time or -math.huge local co = loader.scheduler.running () if time > 0 then loader.scheduler.timeout [co] = loader.js.global:setTimeout (function () loader.js.global:clearTimeout (loader.scheduler.timeout [co]) loader.scheduler.waiting [co] = nil loader.scheduler.ready [co] = true if coroutine.status (loader.scheduler.co) == "suspended" then coroutine.resume (loader.scheduler.co) end end, time * 1000) end if time ~= 0 then loader.scheduler.waiting [co] = true loader.scheduler.ready [co] = nil loader.scheduler.coroutine.yield () end end function loader.scheduler.wakeup (co) loader.js.global:clearTimeout (loader.scheduler.timeout [co]) loader.scheduler.waiting [co] = nil loader.scheduler.ready [co] = true coroutine.resume (loader.scheduler.co) end function loader.scheduler.loop () loader.scheduler.co = coroutine.running () while true do for to_run, t in pairs (loader.scheduler.ready) do if not loader.scheduler.blocked [to_run] then if loader.scheduler.coroutine.status (to_run) == "suspended" then loader.scheduler._running = to_run local ok, err = loader.scheduler.coroutine.resume (to_run, type (t) == "table" and table.unpack (t.parameters)) loader.scheduler._running = nil if not ok then loader.js.global.console:log (err) end end if loader.scheduler.coroutine.status (to_run) == "dead" then loader.scheduler.waiting [to_run] = nil loader.scheduler.ready [to_run] = nil end end end if not next (loader.scheduler.ready ) and not next (loader.scheduler.waiting) and not next (loader.scheduler.blocked) then loader.scheduler.co = nil return else local runnable = 0 for k in pairs (loader.scheduler.ready) do if not loader.scheduler.blocked [k] then runnable = runnable + 1 break end end if runnable == 0 then coroutine.yield () end end end end loader.load "cosy.string" return loader end
if #setmetatable ({}, { __len = function () return 1 end }) ~= 1 then error "Cosy requires Lua >= 5.2 to run." end return function (options) options = options or {} local loader = {} for k, v in pairs (options) do loader [k] = v end local global = _G or _ENV loader.home = "/" loader.prefix = "/" loader.js = global.js local modules = setmetatable ({}, { __mode = "kv" }) loader.request = function (url, allow_yield) local request = loader.js.new (loader.js.global.XMLHttpRequest) local co = loader.scheduler and loader.scheduler.running () if allow_yield and co then request:open ("GET", url, true) request.onreadystatechange = function () if request.readyState == 4 then loader.scheduler.wakeup (co) end end request:send (nil) loader.scheduler.sleep (-math.huge) else request:open ("GET", url, false) request:send (nil) end if request.status == 200 then return request.responseText, request.status else return nil, request.status end end table.insert (package.searchers, 2, function (name) local url = "/lua/" .. name local result, err = loader.request (url) if not result then error (err) end return load (result, url) end) loader.require = require loader.load = function (name) if modules [name] then return modules [name] end local module = loader.require (name) (loader) or true modules [name] = module return module end loader.coroutine = loader.require "coroutine.make" () loader.logto = true loader.scheduler = { _running = nil, waiting = {}, ready = {}, coroutine = loader.coroutine, timeout = {}, } function loader.scheduler.running () return loader.scheduler._running end function loader.scheduler.addthread (f, ...) local co = loader.scheduler.coroutine.create (f) loader.scheduler.ready [co] = { parameters = { ... }, } if loader.scheduler.co and coroutine.status (loader.scheduler.co) == "suspended" then coroutine.resume (loader.scheduler.co) end end function loader.scheduler.removethread (co) if loader.scheduler.timeout [co] then loader.js.global:clearTimeout (loader.scheduler.timeout [co]) end loader.scheduler.waiting [co] = nil loader.scheduler.ready [co] = nil loader.scheduler.timeout [co] = nil end function loader.scheduler.sleep (time) time = time or -math.huge local co = loader.scheduler.running () if time > 0 then loader.scheduler.timeout [co] = loader.js.global:setTimeout (function () loader.js.global:clearTimeout (loader.scheduler.timeout [co]) loader.scheduler.timeout [co] = nil loader.scheduler.waiting [co] = nil loader.scheduler.ready [co] = true if coroutine.status (loader.scheduler.co) == "suspended" then coroutine.resume (loader.scheduler.co) end end, time * 1000) end if time ~= 0 then loader.scheduler.waiting [co] = true loader.scheduler.ready [co] = nil loader.scheduler.coroutine.yield () end end function loader.scheduler.wakeup (co) loader.js.global:clearTimeout (loader.scheduler.timeout [co]) loader.scheduler.timeout [co] = nil loader.scheduler.waiting [co] = nil loader.scheduler.ready [co] = true coroutine.resume (loader.scheduler.co) end function loader.scheduler.loop () loader.scheduler.co = coroutine.running () while true do for to_run, t in pairs (loader.scheduler.ready) do if loader.scheduler.coroutine.status (to_run) == "suspended" then loader.scheduler._running = to_run local ok, err = loader.scheduler.coroutine.resume (to_run, type (t) == "table" and table.unpack (t.parameters)) loader.scheduler._running = nil if not ok then loader.js.global.console:log (err) end end end for co in pairs (loader.scheduler.ready) do if loader.scheduler.coroutine.status (co) == "dead" then loader.scheduler.waiting [co] = nil loader.scheduler.ready [co] = nil end end if not next (loader.scheduler.ready ) and not next (loader.scheduler.waiting) then loader.scheduler.co = nil return elseif not next (loader.scheduler.ready) then coroutine.yield () end end end loader.load "cosy.string" return loader end
Fix scheduler in js loader.
Fix scheduler in js loader.
Lua
mit
CosyVerif/library,CosyVerif/library,CosyVerif/library
ea42ac760e28e0b3ff3942562f0b5b36975d7cfa
lib/zip.lua
lib/zip.lua
local Fs = require('meta-fs') local Path = require('path') local Zlib = require('../zlib') local band = require('bit').band -- -- walk over entries of a zipball read from `stream` -- local function walk(stream, options, callback) -- defaults if not options then options = {} end -- data buffer and current position pointers local buffer = '' local pos = 1 local anchor = 1 -- preserved between calls to parse() -- get big-endian number of specified length local function get_number(bytes) local result = 0 local i = pos + bytes - 1 while i >= pos do result = result * 256 + buffer:byte(i) i = i - 1 end pos = pos + bytes return result end -- get string of specified length local function get_string(len) local result = buffer:sub(pos, pos + len - 1) pos = pos + len return result end -- parse collected buffer local function parse() pos = anchor -- wait until header is available if pos + 30 >= #buffer then return end -- ensure header signature is ok local signature = get_string(4) if signature ~= 'PK\003\004' then -- start of central directory? if signature == 'PK\001\002' then -- unzipping is done stream:emit('end') -- signature is not ok else -- report error stream:emit('error', 'File is not a Zip file') end return end -- read entry data local entry = {} local version = get_number(2) local flags = get_number(2) entry.comp_method = get_number(2) entry.mtime = get_number(4) entry.crc = get_number(4) entry.comp_size = get_number(4) entry.size = get_number(4) -- sanity check local err = nil if band(flags, 0x01) == 0x01 then err = 'File contains encrypted entry' elseif band(flags, 0x0800) == 0x0800 then err = 'File is using UTF8' elseif band(flags, 0x0008) == 0x0008 then err = 'File is using bit 3 trailing data descriptor' elseif entry.comp_size == 0xFFFFFFFF or entry.size == 0xFFFFFFFF then err = 'File is using Zip64 (4gb+ file size)' end if err then stream:emit('error', { code = 'ENOTSUPP', message = err, }) end -- wait until compressed data available local name_len = get_number(2) local extra_len = get_number(2) if pos + name_len + extra_len + entry.comp_size >= #buffer then return end -- read entry name and data local name = get_string(name_len) -- strip `options.strip` leading path chunks -- TODO: strip only `options.strip` components if options.strip then name = name:gsub('[^/]*/', '', options.strip) end -- prepend entry name with optional prefix if options.prefix then name = Path.join(options.prefix, name) end entry.name = name -- entry.extra = get_string(extra_len) -- TODO: stream compressed data too entry.data = get_string(entry.comp_size) -- shift the buffer, to save memory buffer = buffer:sub(pos) anchor = 1 -- fire 'entry' event stream:emit('entry', stream, entry) -- process next entry parse() end -- -- feed data to parser local function ondata(data) buffer = buffer .. data parse() end stream:on('data', ondata) -- end of stream means we're done ok stream:on('end', function () callback() end) -- read error means we're done in error stream:once('error', function (err) stream:remove_listener('data', ondata) callback(err) end) return stream end -- -- inflate and save to file specified zip entry -- local function unzip_entry(stream, entry) -- inflate local text local ok -- comp_method == 0 means data is stored as-is if entry.comp_method > 0 then -- TODO: how to stream data? ok, text = pcall(Zlib.inflate(-15), entry.data, 'finish') if not ok then text = '' end else text = entry.data end -- write inflated entry data --p(entry.name) Fs.mkdir_p(Path.dirname(entry.name), '0755', function (err) if err then stream:emit('error', err) ; return end Fs.write_file(entry.name, text, function (err) end) end) end -- -- unzip -- local function unzip(stream, options, callback) if not options then options = {} end if type(stream) == 'string' then stream = Fs.create_read_stream(stream) end stream:on('entry', unzip_entry) return walk(stream, { prefix = options.path, strip = options.strip, }, callback) end -- -- inflate -- local function inflate(data, callback) -- TODO: should return stream local ok, value = pcall(Zlib.inflate(), data, 'finish') if not ok then callback(value) else callback(nil, value) end end -- export return { unzip = unzip, inflate = inflate, }
local Fs = require('meta-fs') local Path = require('path') local Zlib = require('../zlib') local band = require('bit').band -- -- walk over entries of a zipball read from `stream` -- local function walk(stream, options, callback) -- defaults if not options then options = {} end -- data buffer and current position pointers local buffer = '' local pos = 1 local anchor = 1 -- preserved between calls to parse() -- get big-endian number of specified length local function get_number(bytes) local result = 0 local i = pos + bytes - 1 while i >= pos do result = result * 256 + buffer:byte(i) i = i - 1 end pos = pos + bytes return result end -- get string of specified length local function get_string(len) local result = buffer:sub(pos, pos + len - 1) pos = pos + len return result end -- parse collected buffer local function parse() pos = anchor -- wait until header is available if pos + 30 >= #buffer then return end -- ensure header signature is ok local signature = get_string(4) if signature ~= 'PK\003\004' then -- start of central directory? if signature == 'PK\001\002' then -- unzipping is done stream:emit('end') -- signature is not ok else -- report error stream:emit('error', 'File is not a Zip file') end return end -- read entry data local entry = {} local version = get_number(2) local flags = get_number(2) entry.comp_method = get_number(2) entry.mtime = get_number(4) entry.crc = get_number(4) entry.comp_size = get_number(4) entry.size = get_number(4) -- sanity check local err = nil if band(flags, 0x01) == 0x01 then err = 'File contains encrypted entry' elseif band(flags, 0x0800) == 0x0800 then err = 'File is using UTF8' elseif band(flags, 0x0008) == 0x0008 then err = 'File is using bit 3 trailing data descriptor' elseif entry.comp_size == 0xFFFFFFFF or entry.size == 0xFFFFFFFF then err = 'File is using Zip64 (4gb+ file size)' end if err then stream:emit('error', { code = 'ENOTSUPP', message = err, }) end -- wait until compressed data available local name_len = get_number(2) local extra_len = get_number(2) if pos + name_len + extra_len + entry.comp_size >= #buffer then return end -- read entry name and data local name = get_string(name_len) -- strip `options.strip` leading path chunks if options.strip then name = name:gsub('[^/]-/', '', tonumber(options.strip)) end -- prepend entry name with optional prefix if options.prefix then name = Path.join(options.prefix, name) end entry.name = name -- entry.extra = get_string(extra_len) -- TODO: stream compressed data too entry.data = get_string(entry.comp_size) -- shift the buffer, to save memory buffer = buffer:sub(pos) anchor = 1 -- fire 'entry' event stream:emit('entry', stream, entry) -- process next entry parse() end -- -- feed data to parser local function ondata(data) buffer = buffer .. data parse() end stream:on('data', ondata) -- end of stream means we're done ok stream:once('end', function () callback() end) -- read error means we're done in error stream:once('error', function (err) stream:remove_listener('data', ondata) callback(err) end) return stream end -- -- inflate and save to file specified zip entry -- local function unzip_entry(stream, entry) -- inflate local text local ok -- comp_method == 0 means data is stored as-is if entry.comp_method > 0 then -- TODO: how to stream data? ok, text = pcall(Zlib.inflate(-15), entry.data, 'finish') if not ok then text = '' end else text = entry.data end -- write inflated entry data --p(entry.name) Fs.mkdir_p(Path.dirname(entry.name), '0755', function (err) if err then stream:emit('error', err) ; return end Fs.write_file(entry.name, text, function (err) end) end) end -- -- unzip -- local function unzip(stream, options, callback) if not options then options = {} end if type(stream) == 'string' then stream = Fs.create_read_stream(stream) end stream:on('entry', unzip_entry) return walk(stream, { prefix = options.path, strip = options.strip, }, callback) end -- -- inflate -- local function inflate(data, callback) -- TODO: should return stream local ok, value = pcall(Zlib.inflate(), data, 'finish') if not ok then callback(value) else callback(nil, value) end end -- export return { unzip = unzip, inflate = inflate, }
fixed options.strip logic
fixed options.strip logic
Lua
mit
dvv/luvit-balls,dvv/luvit-balls
80538babd0e12435c3f4218542d299fea29ff015
codes/test.lua
codes/test.lua
function round(num, idp) local mult = 10^(idp or 3) return math.floor(num * mult + 0.5) / mult end function average(nums) local sum = 0 for i = 1, #nums do sum = sum + nums[i] end return sum / #nums end function runtest(func, times) local begin = os.clock() for i = 1, times do func() end local endtm = os.clock() return round(endtm - begin) end function is_luajit() for k, v in pairs(arg) do if k <= 0 and v:find("luajit") then return true end end return false end function dotest(cases, times) for i = 1, #cases do local case = cases[i] io.stdout:write(string.format("Case %d: %s", i, case.name)) for j = 1, 5 do io.stdout:write(".") collectgarbage() local runtime = runtest(case.code, times) case.t[#case.t + 1] = runtime end print() end print("Case ID", "Case name", "t1", "t2", "t3", "t4", "t5", "avg.", "%") local base = 0 for i = 1, #cases do local case = cases[i] local t, avg = case.t, average(case.t) if i == 1 then base = avg end local per = avg / base print(i, case.name, t[1], t[2], t[3], t[4], t[5], avg, round(100*per,2) .. "%") end print("----------------") end function dotimes(t, jt) local basetimes = 1000 local times = t or 1 if is_luajit() then times = times * (jt or 100) end return basetimes * times end function show_interpreter() if is_luajit() then print("In LuaJIT") else print("In Lua") end end show_interpreter()
function round(num, idp) local mult = 10^(idp or 3) return math.floor(num * mult + 0.5) / mult end function average(nums) local sum = 0 for i = 1, #nums do sum = sum + nums[i] end return sum / #nums end function runtest(func, times) local begin = os.clock() for i = 1, times do func() end local endtm = os.clock() return round(endtm - begin) end function is_luajit() for k, v in pairs(arg) do if k <= 0 and v:find("luajit") then return true end end return false end function dotest(cases, times) for i = 1, #cases do local case = cases[i] io.stdout:write(string.format("Case %d: %s ", i, case.name)) for j = 1, 5 do io.stdout:write(".") io.stdout:flush() collectgarbage() local runtime = runtest(case.code, times) case.t[#case.t + 1] = runtime end print() end print("Case ID", "Case name", "t1", "t2", "t3", "t4", "t5", "avg.", "%") local base = 0 for i = 1, #cases do local case = cases[i] local t, avg = case.t, average(case.t) if i == 1 then base = avg end local per = avg / base print(i, case.name, t[1], t[2], t[3], t[4], t[5], avg, round(100*per,2) .. "%") end print("----------------") end function dotimes(t, jt) local basetimes = 1000 local times = t or 1 if is_luajit() then times = times * (jt or 100) end return basetimes * times end function show_interpreter() if is_luajit() then print("In LuaJIT") else print("In Lua") end end show_interpreter()
Fix bug in linux show dots for every case.
Fix bug in linux show dots for every case.
Lua
bsd-2-clause
flily/lua-performance
fee4eb981c8ef4eb52f843391d740c4d34fbdd01
config/nvim/lua/opt/plugins/lsp/null-ls/ruby.lua
config/nvim/lua/opt/plugins/lsp/null-ls/ruby.lua
local lspnull = require("null-ls") local lspnull_h = require("null-ls.helpers") local fs = require("fs") local path = require("path") local M = {} local function use_rubocop() local current = vim.api.nvim_buf_get_name(0) if current == "" then current = path.cwd() end return fs.find_closest(current, { ".rubocop.yml" }) end function M.registration(register) if use_rubocop() then register({ method = lspnull.methods.DIAGNOSTICS, filetypes = { "ruby" }, generator = lspnull_h.generator_factory({ command = "bundle", args = ("exec rubocop --stdin $FILENAME --stderr --force-exclusion --format json"):split(" "), to_stdin = true, from_stderr = true, check_exit_code = { 0, 1 }, format = "json", on_output = function(params) local diagnostics = {} local severities = { convention = lspnull_h.diagnostics.severities["warning"], error = lspnull_h.diagnostics.severities["error"], fatal = lspnull_h.diagnostics.severities["error"], info = lspnull_h.diagnostics.severities["information"], refactor = lspnull_h.diagnostics.severities["hint"], warning = lspnull_h.diagnostics.severities["warning"], } local items = table.dig(params, { "output", "files", "[1]", "items" }) or {} for _, item in ipairs(items) do table.insert(diagnostics, { row = item.location.line, col = item.location.column, message = item.message, code = item.cop_name, severity = severities[item.severity], source = "rubocop", }) end return diagnostics end, }), }) register({ method = lspnull.methods.FORMATTING, filetypes = { "ruby" }, generator = lspnull_h.formatter_factory({ command = "bundle", args = ("exec rubocop --stdin $FILENAME --stderr --force-exclusion --auto-correct"):split(" "), to_stdin = true, }), }) end end function M.root_patterns() return { "Gemfile" } end return M
local lspnull = require("null-ls") local lspnull_h = require("null-ls.helpers") local fs = require("fs") local path = require("path") local M = {} local function use_rubocop() local current = vim.api.nvim_buf_get_name(0) if current == "" then current = path.cwd() end return fs.find_closest(current, { ".rubocop.yml" }) end function M.registration(register) if use_rubocop() then register({ method = lspnull.methods.DIAGNOSTICS, filetypes = { "ruby" }, generator = lspnull_h.generator_factory({ command = "bundle", args = ("exec rubocop --stdin $FILENAME --force-exclusion --format json"):split(" "), to_stdin = true, check_exit_code = { 0, 1 }, format = "json", on_output = function(params) local diagnostics = {} local severities = { convention = lspnull_h.diagnostics.severities["warning"], error = lspnull_h.diagnostics.severities["error"], fatal = lspnull_h.diagnostics.severities["error"], info = lspnull_h.diagnostics.severities["information"], refactor = lspnull_h.diagnostics.severities["hint"], warning = lspnull_h.diagnostics.severities["warning"], } local items = table.dig(params, { "output", "files", "[1]", "offenses" }) or {} for _, item in ipairs(items) do table.insert(diagnostics, { row = item.location.line, col = item.location.column, message = item.message, code = item.cop_name, severity = severities[item.severity], source = "rubocop", }) end return diagnostics end, }), }) register({ method = lspnull.methods.FORMATTING, filetypes = { "ruby" }, generator = lspnull_h.formatter_factory({ command = "bundle", args = ("exec rubocop --stdin $FILENAME --stderr --force-exclusion --format quiet --auto-correct"):split(" "), to_stdin = true, ignore_stderr = true, }), }) end end function M.root_patterns() return { "Gemfile" } end return M
Fix formatter
Fix formatter
Lua
mit
charlesbjohnson/dotfiles,charlesbjohnson/dotfiles
c1bff6211e9e1203cfeef1f726067147596b12f5
prototypes/entities.lua
prototypes/entities.lua
data:extend({ { type = "accumulator", name = "accelerator_charger", icon = "__base__/graphics/entity/basic-accumulator/basic-accumulator.png", flags = {"placeable-neutral", "player-creation"}, minable = {hardness = 0.1, mining_time = 0.1, result="accelerator_charger"}, indestructible = true, max_health = 150, corpse = "medium-remnants", collision_box = {{-0.9, -0.9}, {0.9, 0.9}}, selection_box = {{-1, -1}, {1, 1}}, energy_source = { type = "electric", buffer_capacity = "5MJ", usage_priority = "terciary", input_flow_limit = "300kW", output_flow_limit = "300kW" }, picture = { filename = "__base__/graphics/entity/basic-accumulator/basic-accumulator.png", priority = "extra-high", width = 124, height = 103, shift = {0.7, -0.2} }, charge_animation = { filename = "__base__/graphics/entity/basic-accumulator/basic-accumulator-charge-animation.png", width = 138, height = 135, line_length = 8, frame_count = 24, shift = {0.482, -0.638}, animation_speed = 0.5 }, charge_cooldown = 30, charge_light = {intensity = 0.3, size = 7}, discharge_animation = { filename = "__base__/graphics/entity/basic-accumulator/basic-accumulator-discharge-animation.png", width = 147, height = 128, line_length = 8, frame_count = 24, shift = {0.395, -0.525}, animation_speed = 0.5 }, discharge_cooldown = 60, discharge_light = {intensity = 0.7, size = 7}, vehicle_impact_sound = { filename = "__base__/sound/car-metal-impact.ogg", volume = 0.65 }, working_sound = { sound = { filename = "__base__/sound/accumulator-working.ogg", volume = 1 }, idle_sound = { filename = "__base__/sound/accumulator-idle.ogg", volume = 0.4 }, max_sounds_per_type = 5 }, } })
data:extend({ { type = "accumulator", name = "accelerator_charger", icon = "__base__/graphics/entity/accumulator/accumulator.png", flags = {"placeable-neutral", "player-creation"}, minable = {hardness = 0.1, mining_time = 0.1, result="accelerator_charger"}, indestructible = true, max_health = 150, order = "a-a-a", corpse = "medium-remnants", collision_box = {{-0.9, -0.9}, {0.9, 0.9}}, selection_box = {{-1, -1}, {1, 1}}, energy_source = { type = "electric", buffer_capacity = "5MJ", usage_priority = "terciary", input_flow_limit = "300kW", output_flow_limit = "300kW" }, picture = { filename = "__base__/graphics/entity/accumulator/accumulator.png", priority = "extra-high", width = 124, height = 103, shift = {0.7, -0.2} }, charge_animation = { filename = "__base__/graphics/entity/accumulator/accumulator-charge-animation.png", width = 138, height = 135, line_length = 8, frame_count = 24, shift = {0.482, -0.638}, animation_speed = 0.5 }, charge_cooldown = 30, charge_light = {intensity = 0.3, size = 7}, discharge_animation = { filename = "__base__/graphics/entity/accumulator/accumulator-discharge-animation.png", width = 147, height = 128, line_length = 8, frame_count = 24, shift = {0.395, -0.525}, animation_speed = 0.5 }, discharge_cooldown = 60, discharge_light = {intensity = 0.7, size = 7}, vehicle_impact_sound = { filename = "__base__/sound/car-metal-impact.ogg", volume = 0.65 }, working_sound = { sound = { filename = "__base__/sound/accumulator-working.ogg", volume = 1 }, idle_sound = { filename = "__base__/sound/accumulator-idle.ogg", volume = 0.4 }, max_sounds_per_type = 5 }, } })
fix filename paths
fix filename paths
Lua
mit
kiba/Factorio-MagneticFloor,kiba/Factorio-MagneticFloor
1264a68749fb9a17262d11c53c9ff7bd884b1160
xmake/actions/clean/main.lua
xmake/actions/clean/main.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 - 2019, TBOOX Open Source Group. -- -- @author ruki -- @file main.lua -- -- imports import("core.base.option") import("core.base.task") import("core.project.rule") import("core.project.config") import("core.base.global") import("core.project.project") import("core.platform.platform") -- remove the given files or directories function _remove(filedirs) -- done for _, filedir in ipairs(filedirs) do -- remove it first os.tryrm(filedir) -- remove it if the parent directory is empty local parentdir = path.directory(filedir) while parentdir and os.isdir(parentdir) and os.emptydir(parentdir) do os.tryrm(parentdir) parentdir = path.directory(parentdir) end end end -- do clean target function _do_clean_target(target) -- remove the target file _remove(target:targetfile()) -- remove the target dependent file if exists _remove(target:dependfile()) -- remove the symbol file _remove(target:symbolfile()) -- remove the c/c++ precompiled header file _remove(target:pcoutputfile("c")) _remove(target:pcoutputfile("cxx")) -- remove the object files _remove(target:objectfiles()) -- remove the depend files _remove(target:dependfiles()) -- TODO remove the header files (deprecated) local _, dstheaders = target:headers() _remove(dstheaders) -- remove all? if option.get("all") then -- remove the config.h file _remove(target:configheader()) end end -- on clean target function _on_clean_target(target) -- has been disabled? if target:get("enabled") == false then return end -- build target with rules local done = false for _, r in ipairs(target:orderules()) do local on_clean = r:script("clean") if on_clean then on_clean(target, {origin = _do_clean_target}) done = true end end if done then return end -- do clean _do_clean_target(target) end -- clean the given target files function _clean_target(target) -- the target scripts local scripts = { target:script("clean_before") , function (target) -- has been disabled? if target:get("enabled") == false then return end -- clean rules for _, r in ipairs(target:orderules()) do local before_clean = r:script("clean_before") if before_clean then before_clean(target) end end end , target:script("clean", _on_clean_target) , function (target) -- has been disabled? if target:get("enabled") == false then return end -- clean rules for _, r in ipairs(target:orderules()) do local after_clean = r:script("clean_after") if after_clean then after_clean(target) end end end , target:script("clean_after") } -- run the target scripts for i = 1, 5 do local script = scripts[i] if script ~= nil then script(target, {origin = (i == 3 and _do_clean_target or nil)}) end end end -- clean the given target and all dependent targets function _clean_target_and_deps(target) -- this target have been finished? if _g.finished[target:name()] then return end -- remove the target _clean_target(target) -- exists the dependent targets? for _, dep in ipairs(target:get("deps")) do _clean_target_and_deps(project.target(dep)) end -- finished _g.finished[target:name()] = true end -- clean target function _clean(targetname) -- clean the given target if targetname then _clean_target_and_deps(project.target(targetname)) else -- clean all targets for _, target in pairs(project.targets()) do _clean_target_and_deps(target) end end -- remove all if option.get("all") then -- remove the configure directory _remove(config.directory()) end end -- main function main() -- get the target name local targetname = option.get("target") -- config it first task.run("config", {target = targetname, require = false}) -- init finished states _g.finished = {} -- enter project directory local oldir = os.cd(project.directory()) -- clean the current target _clean(targetname) -- leave project directory os.cd(oldir) 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 - 2019, TBOOX Open Source Group. -- -- @author ruki -- @file main.lua -- -- imports import("core.base.option") import("core.base.task") import("core.project.rule") import("core.project.config") import("core.base.global") import("core.project.project") import("core.platform.platform") -- remove the given files or directories function _remove(filedirs) -- done for _, filedir in ipairs(filedirs) do -- remove it first os.tryrm(filedir) -- remove it if the parent directory is empty local parentdir = path.directory(filedir) while parentdir and os.isdir(parentdir) and os.emptydir(parentdir) do os.tryrm(parentdir) parentdir = path.directory(parentdir) end end end -- do clean target function _do_clean_target(target) -- is phony? if target:isphony() then return end -- remove the target file _remove(target:targetfile()) -- remove the target dependent file if exists _remove(target:dependfile()) -- remove the symbol file _remove(target:symbolfile()) -- remove the c/c++ precompiled header file _remove(target:pcoutputfile("c")) _remove(target:pcoutputfile("cxx")) -- remove the object files _remove(target:objectfiles()) -- remove the depend files _remove(target:dependfiles()) -- TODO remove the header files (deprecated) local _, dstheaders = target:headers() _remove(dstheaders) -- remove all? if option.get("all") then -- remove the config.h file _remove(target:configheader()) end end -- on clean target function _on_clean_target(target) -- has been disabled? if target:get("enabled") == false then return end -- build target with rules local done = false for _, r in ipairs(target:orderules()) do local on_clean = r:script("clean") if on_clean then on_clean(target, {origin = _do_clean_target}) done = true end end if done then return end -- do clean _do_clean_target(target) end -- clean the given target files function _clean_target(target) -- the target scripts local scripts = { target:script("clean_before") , function (target) -- has been disabled? if target:get("enabled") == false then return end -- clean rules for _, r in ipairs(target:orderules()) do local before_clean = r:script("clean_before") if before_clean then before_clean(target) end end end , target:script("clean", _on_clean_target) , function (target) -- has been disabled? if target:get("enabled") == false then return end -- clean rules for _, r in ipairs(target:orderules()) do local after_clean = r:script("clean_after") if after_clean then after_clean(target) end end end , target:script("clean_after") } -- run the target scripts for i = 1, 5 do local script = scripts[i] if script ~= nil then script(target, {origin = (i == 3 and _do_clean_target or nil)}) end end end -- clean the given target and all dependent targets function _clean_target_and_deps(target) -- this target have been finished? if _g.finished[target:name()] then return end -- remove the target _clean_target(target) -- exists the dependent targets? for _, dep in ipairs(target:get("deps")) do _clean_target_and_deps(project.target(dep)) end -- finished _g.finished[target:name()] = true end -- clean target function _clean(targetname) -- clean the given target if targetname then _clean_target_and_deps(project.target(targetname)) else -- clean all targets for _, target in pairs(project.targets()) do _clean_target_and_deps(target) end end -- remove all if option.get("all") then -- remove the configure directory _remove(config.directory()) end end -- main function main() -- get the target name local targetname = option.get("target") -- config it first task.run("config", {target = targetname, require = false}) -- init finished states _g.finished = {} -- enter project directory local oldir = os.cd(project.directory()) -- clean the current target _clean(targetname) -- leave project directory os.cd(oldir) end
fix clean for phony target
fix clean for phony target
Lua
apache-2.0
tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake
8892dfc7e99526d8b4b834475166eb4f4e346a32
lib/debug_session.lua
lib/debug_session.lua
require 're' -- copied from https://en.wikipedia.org/wiki/Escape_sequences_in_C local escaped_char_map = { a = 0x07, b = 0x08, f = 0x0C, n = 0x0A, r = 0x0D, t = 0x09, v = 0x0B, ["'"] = 0x27, ['"'] = 0x22 } local reverse_escaped_char_map = {} for key, value in pairs(escaped_char_map) do reverse_escaped_char_map[value] = key end local function readable_char(char, type) local str = string.char(char) if str == "'" and type == 'char' then return [[\']] elseif str == '"' and type == 'string' then return [[\"]] end if str:find("%g") then return ("%s"):format(str) else if reverse_escaped_char_map[char] then return ("\\%s"):format(reverse_escaped_char_map[char]) end return ("\\x%02X"):format(char) end end local literal_integer_mt = { __index = { tostring = function(self) return ("%d"):format(self.value) end, size = function() return 4 end } } local literal_float_mt = { __index = { tostring = function(self) return ("%g"):format(self.value) end, size = function() return 4 end } } local literal_character_mt = { __index = { tostring = function(self) return ("'%s'"):format(readable_char(self.value, 'char')) end, size = function() return 1 end } } local string_mt = { __index = { tostring = function(self) return ('"%s"'):format(self.value:gsub(".", function(char) if char == '"' then return '\\"' end if char:find "%g" then return char else local byte = string.byte(char) if reverse_escaped_char_map[byte] then return "\\" .. reverse_escaped_char_map[byte] else return ("\\x%02X"):format(byte) end end end)) end, size = function() return #self.value + 1 end } } local grammar = re.compile([[ definitions <- {| definition+ |} definition <- global_variable_definition global_variable_definition <- {| {type_specifier} %s* {IDENTIFIER} %s* {: static_initializer :}? %s* ';' %s* |} -> global_variable_definition type_specifier <- primitive_type (%s+ '*'+)? primitive_type <- 'int' / 'float' / 'char' static_initializer <- '=' %s* {: literal_value :} literal_value <- float / integer / character / string integer <- hexadecimal_integer / decimal_integer hexadecimal_integer <- ('0x' HEXCHAR+) -> literal_hexadecimal_integer decimal_integer <- (%d+) -> literal_decimal_integer float <- (%d+ '.' %d+) -> literal_float character <- "'" single_character "'" single_character <- ('\' { [abfnrtv'] } ) -> escaped_char / [^'] -> normal_char string <- '"' {| char_in_string* |} -> string '"' char_in_string <- ('\' {[abfnrtv"]} ) -> escaped_char_map / [^"] -> string_byte IDENTIFIER <- [_%w][_%w%d]* HEXCHAR <- [0-9a-fA-F] ]], { global_variable_definition = function(captures) return { definition = 'global', type = captures[1], name = captures[2], initializer = captures[3] } end, literal_hexadecimal_integer = function(str) return setmetatable( {type = 'literal_integer', value = tonumber(str, 16)}, literal_integer_mt ) end, literal_decimal_integer = function(str) return setmetatable( {type = 'literal_integer', value = tonumber(str)}, literal_integer_mt ) end, literal_float = function(str) return setmetatable( {type = 'literal_float', value = tonumber(str)}, literal_float_mt ) end, normal_char = function(char) return setmetatable( {type = 'character', value = string.byte(char) }, literal_character_mt ) end, escaped_char = function(char) return setmetatable( {type = 'character', value = escaped_char_map[char] }, literal_character_mt ) end, string = function(chars) return setmetatable( {type = 'string', value = string.char(unpack(chars))}, string_mt ) end, escaped_char_map = escaped_char_map, string_byte = string.byte }) local debug_session = {} debug_session.__index = debug_session function debug_session.new() local session = {} setmetatable(session, debug_session) return session end function debug_session:load(filename) local file = io.open(filename) local content = file:read '*a' file:close() self.definitions = grammar:match(content) return self.definitions end local function map(list, func) local mapped = {} for _, elem in ipairs(list) do table.insert(mapped, func(elem)) end return mapped end function debug_session:dump() if self.definitions then local lines = map(self.definitions, function(definition) if definition.definition == 'global' then local initializer = definition.initializer local space = ' ' if definition.type:find('[*]$') then space = '' end if initializer then return ("%s%s%s = %s;"):format(definition.type, space, definition.name, initializer:tostring()) else return ("%s%s%s;"):format(definition.type, space, definition.name) end end end) return table.concat(lines, "\n") end end return debug_session
require 're' -- copied from https://en.wikipedia.org/wiki/Escape_sequences_in_C local escaped_char_map = { a = 0x07, b = 0x08, f = 0x0C, n = 0x0A, r = 0x0D, t = 0x09, v = 0x0B, ["'"] = 0x27, ['"'] = 0x22 } local reverse_escaped_char_map = {} for key, value in pairs(escaped_char_map) do reverse_escaped_char_map[value] = key end local function readable_char(char, type) local str = string.char(char) if str == "'" and type == 'char' then return [[\']] elseif str == '"' and type == 'string' then return [[\"]] end if str:find("%g") then return ("%s"):format(str) else if reverse_escaped_char_map[char] then return ("\\%s"):format(reverse_escaped_char_map[char]) end return ("\\x%02X"):format(char) end end local integer_mt = { __index = { tostring = function(self) return ("%d"):format(self.value) end, size = function() return 4 end } } local float_mt = { __index = { tostring = function(self) return ("%g"):format(self.value) end, size = function() return 4 end } } local character_mt = { __index = { tostring = function(self) return ("'%s'"):format(readable_char(self.value, 'char')) end, size = function() return 1 end } } local string_mt = { __index = { tostring = function(self) return ('"%s"'):format(self.value:gsub(".", function(char) if char == '"' then return '\\"' end if char:find "%g" then return char else local byte = string.byte(char) if reverse_escaped_char_map[byte] then return "\\" .. reverse_escaped_char_map[byte] else return ("\\x%02X"):format(byte) end end end)) end, size = function() return #self.value + 1 end } } local grammar = re.compile([[ definitions <- {| definition+ |} definition <- global_variable_definition global_variable_definition <- {| {type_specifier} %s* {IDENTIFIER} %s* {: static_initializer :}? %s* ';' %s* |} -> global_variable_definition type_specifier <- primitive_type (%s+ '*'+)? primitive_type <- 'int' / 'float' / 'char' static_initializer <- '=' %s* {: literal_value :} literal_value <- float / integer / character / string integer <- hexadecimal_integer / decimal_integer hexadecimal_integer <- ('0x' HEXCHAR+) -> hexadecimal_integer decimal_integer <- (%d+) -> decimal_integer float <- (%d+ '.' %d+) -> float character <- "'" single_character "'" single_character <- ('\' { [abfnrtv'] } ) -> escaped_char / [^'] -> normal_char string <- '"' {| char_in_string* |} -> string '"' char_in_string <- ('\' {[abfnrtv"]} ) -> escaped_char_map / [^"] -> string_byte IDENTIFIER <- [_%w][_%w%d]* HEXCHAR <- [0-9a-fA-F] ]], { global_variable_definition = function(captures) return { definition = 'global', type = captures[1], name = captures[2], initializer = captures[3] } end, hexadecimal_integer = function(str) return setmetatable( {type = 'integer', value = tonumber(str, 16)}, integer_mt ) end, decimal_integer = function(str) return setmetatable( {type = 'integer', value = tonumber(str)}, integer_mt ) end, float = function(str) return setmetatable( {type = 'float', value = tonumber(str)}, float_mt ) end, normal_char = function(char) return setmetatable( {type = 'character', value = string.byte(char) }, character_mt ) end, escaped_char = function(char) return setmetatable( {type = 'character', value = escaped_char_map[char] }, character_mt ) end, string = function(chars) return setmetatable( {type = 'string', value = string.char(unpack(chars))}, string_mt ) end, escaped_char_map = escaped_char_map, string_byte = string.byte }) local debug_session = {} debug_session.__index = debug_session function debug_session.new() local session = {} setmetatable(session, debug_session) return session end function debug_session:load(filename) local file = io.open(filename) local content = file:read '*a' file:close() self.definitions = grammar:match(content) return self.definitions end local function map(list, func) local mapped = {} for _, elem in ipairs(list) do table.insert(mapped, func(elem)) end return mapped end function debug_session:dump() if self.definitions then local lines = map(self.definitions, function(definition) if definition.definition == 'global' then local initializer = definition.initializer local space = ' ' if definition.type:find('[*]$') then space = '' end if initializer then return ("%s%s%s = %s;"):format(definition.type, space, definition.name, initializer:tostring()) else return ("%s%s%s;"):format(definition.type, space, definition.name) end end end) return table.concat(lines, "\n") end end return debug_session
remove "literal" prefix
remove "literal" prefix
Lua
mit
Moligaloo/EmperorC
a631351f403697d3d38f5ed1a22e1ca852ab3aae
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", before_each_stack = {}, after_each_stack = {} }, options = {}, __call = function(self) local failures = 0 self.output = self.options.output --run test local function test(description, callback, no_output) 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 } failures = failures + 1 else test_status = { type = "success", description = description, info = info } end if not no_output and 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, decsription) if not context[stype] then return true else if type(context[stype]) == "function" then local result = test("Failed running test initializer '"..stype.."'", context[stype], true) return (result.type == "success"), result elseif type(context[stype]) == "table" then if #context[stype] > 0 then local result for i,v in pairs(context[stype]) do result = test("Failed running test initializer '"..decsription.."'", v, true) if result.type ~= "success" then return (result.type == "success"), result end end return (result.type == "success"), result else return true end end end 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 setup_ok, setup_error setup_ok, setup_error = run_setup(context, "setup") if setup_ok then for i,v in ipairs(context) do if v.type == "test" then setup_ok, setup_error = run_setup(context, "before_each_stack", "before_each") if not setup_ok then break end table.insert(status, test(v.description, v.callback)) setup_ok, setup_error = run_setup(context, "after_each_stack", "after_each") if not setup_ok then break end 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 end end if setup_ok then setup_ok, setup_error = run_setup(context, "teardown") end if not setup_ok then table.insert(status, setup_error) 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 old_TEST = _TEST _TEST = busted._VERSION 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 _TEST = old_TEST return status_string, failures 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", before_each_stack = {}, after_each_stack = {} }, options = {}, __call = function(self) local failures = 0 self.output = self.options.output --run test local function test(description, callback, no_output) 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 } failures = failures + 1 else test_status = { type = "success", description = description, info = info } end if not no_output and 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, decsription) if not context[stype] then return true else if type(context[stype]) == "function" then local result = test("Failed running test initializer '"..stype.."'", context[stype], true) return (result.type == "success"), result elseif type(context[stype]) == "table" then if #context[stype] > 0 then local result for i,v in pairs(context[stype]) do result = test("Failed running test initializer '"..decsription.."'", v, true) if result.type ~= "success" then return (result.type == "success"), result end end return (result.type == "success"), result else return true end end end 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 setup_ok, setup_error setup_ok, setup_error = run_setup(context, "setup") if setup_ok then for i,v in ipairs(context) do if v.type == "test" then setup_ok, setup_error = run_setup(context, "before_each_stack", "before_each") if not setup_ok then break end table.insert(status, test(v.description, v.callback)) setup_ok, setup_error = run_setup(context, "after_each_stack", "after_each") if not setup_ok then break end 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 end end if setup_ok then setup_ok, setup_error = run_setup(context, "teardown") end if not setup_ok then table.insert(status, setup_error) 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 old_TEST = _TEST _TEST = busted._VERSION 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 if not self.options.defer_print then print(self.output.footer(self.root_context)) end _TEST = old_TEST return status_string, failures end } return setmetatable(busted, busted)
Write to output footer - fixes issue #55
Write to output footer - fixes issue #55
Lua
mit
leafo/busted,o-lim/busted,sobrinho/busted,istr/busted,Olivine-Labs/busted,xyliuke/busted,nehz/busted,DorianGray/busted,azukiapp/busted,mpeterv/busted,ryanplusplus/busted
afbe771fc4aa3ebc6a062431149b915760bca504
tests/test-process.lua
tests/test-process.lua
local spawn = require('childprocess').spawn local los = require('los') local net = require('net') local uv = require('uv') require('tap')(function(test) test('process getpid', function() p('process pid', process.pid) assert(process.pid) end) test('process argv', function() p('process argv', process.argv) assert(process.argv) end) test('signal usr1,usr2,hup', function(expect) local onHUP, onUSR1, onUSR2 if los.type() == 'win32' then return end function onHUP() process:removeListener('sighup', onHUP) end function onUSR1() process:removeListener('sigusr1', onUSR1) end function onUSR2() process:removeListener('sigusr2', onUSR2) end process:on('sighup', expect(onHUP)) process:on('sigusr1', expect(onUSR1)) process:on('sigusr2', expect(onUSR2)) process.kill(process.pid, 'sighup') process.kill(process.pid, 'sigusr1') process.kill(process.pid, 'sigusr2') end) test('environment subprocess', function(expect) local child, options, onStdout, onExit, onEnd, data options = { env = { TEST1 = 1 } } data = '' if los.type() == 'win32' then child = spawn('cmd.exe', {'/C', 'set'}, options) else child = spawn('env', {}, options) end function onStdout(chunk) p('stdout', chunk) data = data .. chunk end function onExit(code, signal) p('exit') assert(code == 0) assert(signal == 0) end function onEnd() assert(data:find('TEST1=1')) p('found') child.stdin:destroy() end child:on('error', function(err) p(err) child:close() end) child.stdout:once('end', expect(onEnd)) child.stdout:on('data', onStdout) child:on('exit', expect(onExit)) child:on('close', expect(onExit)) end) test('invalid command', function(expect) local child, onError -- disable on windows, bug in libuv if los.type() == 'win32' then return end function onError(err) assert(err) end child = spawn('skfjsldkfjskdfjdsklfj') child:on('error', expect(onError)) child.stdout:on('error', expect(onError)) child.stderr:on('error', expect(onError)) end) test('invalid command verify exit callback', function(expect) local child, onExit, onClose -- disable on windows, bug in libuv if los.type() == 'win32' then return end function onExit() p('exit') end function onClose() p('close') end child = spawn('skfjsldkfjskdfjdsklfj') child:on('exit', expect(onExit)) child:on('close', expect(onClose)) end) test('process.env pairs', function() local key = "LUVIT_TEST_VARIABLE_1" local value = "TEST1" local iterate, found function iterate() for k, v in process.env.iterate() do p(k, v) if k == key and v == value then found = true break end end end process.env[key] = value found = false iterate() assert(found) process.env[key] = nil found = false iterate() assert(process.env[key] == nil) assert(found == false) end) test('child process no stdin', function(expect) local child, onData, options options = { stdio = { nil, net.Socket:new({ handle = uv.new_pipe(false) }), net.Socket:new({ handle = uv.new_pipe(false) }) } } function onData(data) end if los.type() == 'win32' then child = spawn('cmd.exe', {'/C', 'set'}, options) else child = spawn('env', {}, options) end child:on('data', onData) child:on('exit', expect(function(exitCode) options.stdio[2]:destroy() options.stdio[3]:destroy() assert(exitCode == 0) end)) child:on('close', expect(function() end)) child:on('error', function(err) p(err) child:close() end) end) test('child process (no stdin, no stderr, stdout) with close', function(expect) local child, onData, options options = { stdio = { nil, net.Socket:new({ handle = uv.new_pipe(false) }), nil } } function onData(data) p(data) end if los.type() == 'win32' then child = spawn('cmd.exe', {'/C', 'set'}, options) else child = spawn('env', {}, options) end child:on('data', onData) child:on('close', expect(function(exitCode) assert(exitCode == 0) end)) child:on('exit', expect(function(exitCode) options.stdio[2]:destroy() assert(exitCode == 0) end)) child:on('error', function(err) p(err) child:close() end) end) test('cpu usage', function(expect) local start = process:cpuUsage() local RUN_FOR_MS = 500 local SLOP_FACTOR = 2 local MICROSECONDS_PER_MILLISECOND = 1000 -- Run a busy loop local now = uv.now() while (uv.now() - now < RUN_FOR_MS) do uv.update_time() end local diff = process:cpuUsage(start) p(diff) assert(diff.user >= 0) assert(diff.user <= SLOP_FACTOR * RUN_FOR_MS * MICROSECONDS_PER_MILLISECOND) assert(diff.system >= 0) assert(diff.system <= SLOP_FACTOR * RUN_FOR_MS * MICROSECONDS_PER_MILLISECOND) end) test('cpu usage diff', function(expect) -- cpuUsage diffs should always be >= 0 for i=1,10 do local usage = process:cpuUsage() local diffUsage = process:cpuUsage(usage) assert(diffUsage.user >= 0) assert(diffUsage.system >= 0) end end) test('memory usage', function(expect) local memory = process:memoryUsage() assert(type(memory) == "table") assert(type(memory.rss) == "number") assert(memory.rss >= 0) assert(type(memory.heapUsed) == "number") assert(memory.heapUsed >= 0) p(memory) end) end)
local spawn = require('childprocess').spawn local los = require('los') local net = require('net') local uv = require('uv') require('tap')(function(test) test('process getpid', function() p('process pid', process.pid) assert(process.pid) end) test('process argv', function() p('process argv', process.argv) assert(process.argv) end) test('signal usr1,usr2,hup', function(expect) local onHUP, onUSR1, onUSR2, iCount if los.type() == 'win32' then return end iCount = 0 function onHUP() iCount=iCount+1 process:removeListener('sighup', onHUP) end function onUSR1() iCount=iCount+1 process:removeListener('sigusr1', onUSR1) end function onUSR2() iCount=iCount+1 process:removeListener('sigusr2', onUSR2) end process:on('sighup', expect(onHUP)) process:on('sigusr1', expect(onUSR1)) process:on('sigusr2', expect(onUSR2)) process.kill(process.pid, 'sighup') process.kill(process.pid, 'sigusr1') process.kill(process.pid, 'sigusr2') local function setTimeout(timeout, callback) local timer = uv.new_timer() timer:start(timeout, 0, function () timer:stop() timer:close() callback() end) return timer end setTimeout(10, function() assert(iCount==3) end) end) test('environment subprocess', function(expect) local child, options, onStdout, onExit, onEnd, data options = { env = { TEST1 = 1 } } data = '' if los.type() == 'win32' then child = spawn('cmd.exe', {'/C', 'set'}, options) else child = spawn('env', {}, options) end function onStdout(chunk) p('stdout', chunk) data = data .. chunk end function onExit(code, signal) p('exit') assert(code == 0) assert(signal == 0) end function onEnd() assert(data:find('TEST1=1')) p('found') child.stdin:destroy() end child:on('error', function(err) p(err) child:close() end) child.stdout:once('end', expect(onEnd)) child.stdout:on('data', onStdout) child:on('exit', expect(onExit)) child:on('close', expect(onExit)) end) test('invalid command', function(expect) local child, onError -- disable on windows, bug in libuv if los.type() == 'win32' then return end function onError(err) assert(err) end child = spawn('skfjsldkfjskdfjdsklfj') child:on('error', expect(onError)) child.stdout:on('error', expect(onError)) child.stderr:on('error', expect(onError)) end) test('invalid command verify exit callback', function(expect) local child, onExit, onClose -- disable on windows, bug in libuv if los.type() == 'win32' then return end function onExit() p('exit') end function onClose() p('close') end child = spawn('skfjsldkfjskdfjdsklfj') child:on('exit', expect(onExit)) child:on('close', expect(onClose)) end) test('process.env pairs', function() local key = "LUVIT_TEST_VARIABLE_1" local value = "TEST1" local iterate, found function iterate() for k, v in process.env.iterate() do p(k, v) if k == key and v == value then found = true break end end end process.env[key] = value found = false iterate() assert(found) process.env[key] = nil found = false iterate() assert(process.env[key] == nil) assert(found == false) end) test('child process no stdin', function(expect) local child, onData, options options = { stdio = { nil, net.Socket:new({ handle = uv.new_pipe(false) }), net.Socket:new({ handle = uv.new_pipe(false) }) } } function onData(data) end if los.type() == 'win32' then child = spawn('cmd.exe', {'/C', 'set'}, options) else child = spawn('env', {}, options) end child:on('data', onData) child:on('exit', expect(function(exitCode) options.stdio[2]:destroy() options.stdio[3]:destroy() assert(exitCode == 0) end)) child:on('close', expect(function() end)) child:on('error', function(err) p(err) child:close() end) end) test('child process (no stdin, no stderr, stdout) with close', function(expect) local child, onData, options options = { stdio = { nil, net.Socket:new({ handle = uv.new_pipe(false) }), nil } } function onData(data) p(data) end if los.type() == 'win32' then child = spawn('cmd.exe', {'/C', 'set'}, options) else child = spawn('env', {}, options) end child:on('data', onData) child:on('close', expect(function(exitCode) assert(exitCode == 0) end)) child:on('exit', expect(function(exitCode) options.stdio[2]:destroy() assert(exitCode == 0) end)) child:on('error', function(err) p(err) child:close() end) end) test('cpu usage', function(expect) local start = process:cpuUsage() local RUN_FOR_MS = 500 local SLOP_FACTOR = 2 local MICROSECONDS_PER_MILLISECOND = 1000 -- Run a busy loop local now = uv.now() while (uv.now() - now < RUN_FOR_MS) do uv.update_time() end local diff = process:cpuUsage(start) p(diff) assert(diff.user >= 0) assert(diff.user <= SLOP_FACTOR * RUN_FOR_MS * MICROSECONDS_PER_MILLISECOND) assert(diff.system >= 0) assert(diff.system <= SLOP_FACTOR * RUN_FOR_MS * MICROSECONDS_PER_MILLISECOND) end) test('cpu usage diff', function(expect) -- cpuUsage diffs should always be >= 0 for i=1,10 do local usage = process:cpuUsage() local diffUsage = process:cpuUsage(usage) assert(diffUsage.user >= 0) assert(diffUsage.system >= 0) end end) test('memory usage', function(expect) local memory = process:memoryUsage() assert(type(memory) == "table") assert(type(memory.rss) == "number") assert(memory.rss >= 0) assert(type(memory.heapUsed) == "number") assert(memory.heapUsed >= 0) p(memory) end) end)
fix test-process, make sure signal handled
fix test-process, make sure signal handled
Lua
apache-2.0
luvit/luvit,zhaozg/luvit,luvit/luvit,zhaozg/luvit
70f0b1baffc4f69a49523346a9df7463a1b768af
src/nn-robot-lua/dqn/GameEnvironment.lua
src/nn-robot-lua/dqn/GameEnvironment.lua
-- The GameEnvironment class. local gameEnv = torch.class('dqn.GameEnvironment') local py = require('fb.python') function readAll(file) local f = io.open(file, "rb") local content = f:read("*all") f:close() return content end function gameEnv:__init(_opt) print(_opt.game_path) local py_src = readAll(_opt.game_path) py.exec(py_src) -- TODO: make this configurable py.exec('game = GameEnvironment(\'nn-robot\', host=\'192.168.1.57\', port=9090') local _opt = _opt or {} -- defaults to emulator speed self.game_path = _opt.game_path or '.' self.verbose = _opt.verbose or 0 self._actrep = _opt.actrep or 1 self._random_starts = _opt.random_starts or 1 self:reset(_opt.env, _opt.env_params, _opt.gpu) return self end function gameEnv:_updateState(frame, reward, terminal, lives) self._state.frame = frame self._state.reward = reward self._state.terminal = terminal self._state.prev_lives = self._state.lives or lives self._state.lives = lives return self end function gameEnv:getState() return self._state.frame, self._state.reward, self._state.terminal end function gameEnv:reset(_env, _params, _gpu) self._actions = self:getActions() -- start the game if self.verbose > 0 then print('\nPlaying game') end self:_resetState() self:_updateState(self:_step(0)) self:getState() return self end function gameEnv:_resetState() self._state = self._state or {} return self end -- Function plays `action` in the game and return game state. function gameEnv:_step(action) local result = py.eval('game.step(' .. action .. ')') -- return x.data, x.reward, x.terminal, x.lives return result[1], result[2], result[3], result[4] end -- Function plays one random action in the game and return game state. function gameEnv:_randomStep() return self:_step(self._actions[torch.random(#self._actions)]) end function gameEnv:step(action, training) -- accumulate rewards over actrep action repeats local cumulated_reward = 0 local frame, reward, terminal, lives for i=1,self._actrep do -- Take selected action; ATARI games' actions start with action "0". frame, reward, terminal, lives = self:_step(action) -- accumulate instantaneous reward cumulated_reward = cumulated_reward + reward -- Loosing a life will trigger a terminal signal in training mode. -- We assume that a "life" IS an episode during training, but not during testing if training and lives and lives < self._state.lives then terminal = true end -- game over, no point to repeat current action if terminal then break end end self:_updateState(frame, cumulated_reward, terminal, lives) return self:getState() end --[[ Function advances the emulator state until a new game starts and returns this state. The new game may be a different one, in the sense that playing back the exact same sequence of actions will result in different outcomes. ]] function gameEnv:newGame() local obs, reward, terminal terminal = self._state.terminal while not terminal do obs, reward, terminal, lives = self:_randomStep() end -- take one null action in the new game return self:_updateState(self:_step(0)):getState() end --[[ Function advances the emulator state until a new (random) game starts and returns this state. ]] function gameEnv:nextRandomGame(k) local obs, reward, terminal = self:newGame() k = k or torch.random(self._random_starts) for i=1,k-1 do obs, reward, terminal, lives = self:_step(0) if terminal then print(string.format('WARNING: Terminal signal received after %d 0-steps', i)) end end return self:_updateState(self:_step(0)):getState() end --[[ Function returns the number total number of pixels in one frame/observation from the current game. ]] function gameEnv:nObsFeature() return 84 * 84 * 1 -- 84 x 84 pixels and one channel end -- Function returns a table with valid actions in the current game. function gameEnv:getActions() return py.eval('game.get_actions()') -- simply return a list of indexes that represent actions return {0, 1, 2, 3} end
-- The GameEnvironment class. local gameEnv = torch.class('dqn.GameEnvironment') local py = require('fb.python') function readAll(file) local f = io.open(file, "rb") local content = f:read("*all") f:close() return content end function gameEnv:__init(_opt) print(_opt.game_path) local py_src = readAll(_opt.game_path) py.exec(py_src) -- TODO: make this configurable py.exec('game = GameEnvironment(\'nn-robot\', host=\'192.168.1.57\', port=9090') local _opt = _opt or {} -- defaults to emulator speed self.game_path = _opt.game_path or '.' self.verbose = _opt.verbose or 0 self._actrep = _opt.actrep or 1 self._random_starts = _opt.random_starts or 1 self:reset(_opt.env, _opt.env_params, _opt.gpu) return self end function gameEnv:_updateState(frame, reward, terminal, lives) self._state.frame = frame self._state.reward = reward self._state.terminal = terminal self._state.prev_lives = self._state.lives or lives self._state.lives = lives return self end function gameEnv:getState() return self._state.frame, self._state.reward, self._state.terminal end function gameEnv:reset(_env, _params, _gpu) self._actions = self:getActions() -- start the game if self.verbose > 0 then print('\nPlaying game') end self:_resetState() self:_updateState(self:_step(0)) self:getState() return self end function gameEnv:_resetState() self._state = self._state or {} return self end -- Function plays `action` in the game and return game state. function gameEnv:_step(action) local result = py.eval('game.step(' .. action .. ')') -- return x.data, x.reward, x.terminal, x.lives return result[1], result[2], result[3], result[4] end -- Function plays one random action in the game and return game state. function gameEnv:_randomStep() return self:_step(self._actions[torch.random(#self._actions)]) end function gameEnv:step(action, training) -- accumulate rewards over actrep action repeats local cumulated_reward = 0 local frame, reward, terminal, lives for i=1,self._actrep do -- Take selected action; ATARI games' actions start with action "0". frame, reward, terminal, lives = self:_step(action) -- accumulate instantaneous reward cumulated_reward = cumulated_reward + reward -- Loosing a life will trigger a terminal signal in training mode. -- We assume that a "life" IS an episode during training, but not during testing if training and lives and lives < self._state.lives then terminal = true end -- game over, no point to repeat current action if terminal then break end end self:_updateState(frame, cumulated_reward, terminal, lives) return self:getState() end --[[ Function advances the emulator state until a new game starts and returns this state. The new game may be a different one, in the sense that playing back the exact same sequence of actions will result in different outcomes. ]] function gameEnv:newGame() local obs, reward, terminal terminal = self._state.terminal while not terminal do obs, reward, terminal, lives = self:_randomStep() end -- take one null action in the new game return self:_updateState(self:_step(0)):getState() end --[[ Function advances the emulator state until a new (random) game starts and returns this state. ]] function gameEnv:nextRandomGame(k) local obs, reward, terminal = self:newGame() k = k or torch.random(self._random_starts) for i=1,k-1 do obs, reward, terminal, lives = self:_step(0) if terminal then print(string.format('WARNING: Terminal signal received after %d 0-steps', i)) end end return self:_updateState(self:_step(0)):getState() end --[[ Function returns the number total number of pixels in one frame/observation from the current game. ]] function gameEnv:nObsFeature() return 84 * 84 * 1 -- 84 x 84 pixels and one channel end -- Function returns a table with valid actions in the current game. function gameEnv:getActions() return py.eval('game.get_actions()') end
Fix bug
Fix bug
Lua
mit
matthiasplappert/pibot
5f1c12a1cf241919ae2b157f91d5a730646745f4
tests/actions/make/cpp/test_make_pch.lua
tests/actions/make/cpp/test_make_pch.lua
-- -- tests/actions/make/cpp/test_make_pch.lua -- Validate the setup for precompiled headers in makefiles. -- Copyright (c) 2010-2013 Jason Perkins and the Premake project -- local suite = test.declare("make_pch") local make = premake.make local project = premake.project -- -- Setup and teardown -- local sln, prj function suite.setup() sln, prj = test.createsolution() end local function prepareVars() local cfg = test.getconfig(prj, "Debug") make.pch(cfg) end local function prepareRules() local cfg = test.getconfig(prj, "Debug") make.pchRules(cfg.project) end -- -- If no header has been set, nothing should be output. -- function suite.noConfig_onNoHeaderSet() prepareVars() test.isemptycapture() end -- -- If a header is set, but the NoPCH flag is also set, then -- nothing should be output. -- function suite.noConfig_onHeaderAndNoPCHFlag() pchheader "include/myproject.h" flags "NoPCH" prepareVars() test.isemptycapture() end -- -- If a header is specified and the NoPCH flag is not set, then -- the header can be used. -- function suite.config_onPchEnabled() pchheader "include/myproject.h" prepareVars() test.capture [[ PCH = include/myproject.h GCH = $(OBJDIR)/$(notdir $(PCH)).gch ]] end -- -- The PCH can be specified relative the an includes search path. -- function suite.pch_searchesIncludeDirs() pchheader "premake.h" includedirs { "../src/host" } prepareVars() test.capture [[ PCH = ../src/host/premake.h ]] end -- -- Verify the format of the PCH rules block for a C++ file. -- function suite.buildRules_onCpp() pchheader "include/myproject.h" prepareRules() test.capture [[ ifneq (,$(PCH)) $(GCH): $(PCH) @echo $(notdir $<) $(SILENT) $(CXX) -x c++-header $(ALL_CXXFLAGS) -MMD -MP $(DEFINES) $(INCLUDES) -o "$@" -MF "$(@:%.gch=%.d)" -c "$<" endif ]] end -- -- Verify the format of the PCH rules block for a C file. -- function suite.buildRules_onC() language "C" pchheader "include/myproject.h" prepareRules() test.capture [[ ifneq (,$(PCH)) $(GCH): $(PCH) @echo $(notdir $<) $(SILENT) $(CC) -x c-header $(ALL_CFLAGS) -MMD -MP $(DEFINES) $(INCLUDES) -o "$@" -MF "$(@:%.gch=%.d)" -c "$<" endif ]] end -- -- If the header is located on one of the include file -- search directories, it should get found automatically. -- function suite.findsPCH_onIncludeDirs() location "MyProject" pchheader "premake.h" includedirs { "../src/host" } prepareVars() test.capture [[ PCH = ../../src/host/premake.h ]] end
-- -- tests/actions/make/cpp/test_make_pch.lua -- Validate the setup for precompiled headers in makefiles. -- Copyright (c) 2010-2013 Jason Perkins and the Premake project -- local suite = test.declare("make_pch") local make = premake.make local project = premake.project -- -- Setup and teardown -- local sln, prj function suite.setup() sln, prj = test.createsolution() end local function prepareVars() local cfg = test.getconfig(prj, "Debug") make.pch(cfg) end local function prepareRules() local cfg = test.getconfig(prj, "Debug") make.pchRules(cfg.project) end -- -- If no header has been set, nothing should be output. -- function suite.noConfig_onNoHeaderSet() prepareVars() test.isemptycapture() end -- -- If a header is set, but the NoPCH flag is also set, then -- nothing should be output. -- function suite.noConfig_onHeaderAndNoPCHFlag() pchheader "include/myproject.h" flags "NoPCH" prepareVars() test.isemptycapture() end -- -- If a header is specified and the NoPCH flag is not set, then -- the header can be used. -- function suite.config_onPchEnabled() pchheader "include/myproject.h" prepareVars() test.capture [[ PCH = include/myproject.h GCH = $(OBJDIR)/$(notdir $(PCH)).gch ]] end -- -- The PCH can be specified relative the an includes search path. -- function suite.pch_searchesIncludeDirs() pchheader "premake.h" includedirs { "../src/host" } prepareVars() test.capture [[ PCH = ../src/host/premake.h ]] end -- -- Verify the format of the PCH rules block for a C++ file. -- function suite.buildRules_onCpp() pchheader "include/myproject.h" prepareRules() test.capture [[ ifneq (,$(PCH)) .NOTPARALLEL: $(GCH) $(PCH) $(GCH): $(PCH) @echo $(notdir $<) $(SILENT) $(CXX) -x c++-header $(ALL_CXXFLAGS) -MMD -MP $(DEFINES) $(INCLUDES) -o "$@" -MF "$(@:%.gch=%.d)" -c "$<" endif ]] end -- -- Verify the format of the PCH rules block for a C file. -- function suite.buildRules_onC() language "C" pchheader "include/myproject.h" prepareRules() test.capture [[ ifneq (,$(PCH)) .NOTPARALLEL: $(GCH) $(PCH) $(GCH): $(PCH) @echo $(notdir $<) $(SILENT) $(CC) -x c-header $(ALL_CFLAGS) -MMD -MP $(DEFINES) $(INCLUDES) -o "$@" -MF "$(@:%.gch=%.d)" -c "$<" endif ]] end -- -- If the header is located on one of the include file -- search directories, it should get found automatically. -- function suite.findsPCH_onIncludeDirs() location "MyProject" pchheader "premake.h" includedirs { "../src/host" } prepareVars() test.capture [[ PCH = ../../src/host/premake.h ]] end
Fix makefile unit tests broken by previous commits
Fix makefile unit tests broken by previous commits
Lua
bsd-3-clause
soundsrc/premake-core,saberhawk/premake-core,starkos/premake-core,prapin/premake-core,bravnsgaard/premake-core,aleksijuvani/premake-core,felipeprov/premake-core,dcourtois/premake-core,saberhawk/premake-core,Blizzard/premake-core,TurkeyMan/premake-core,Zefiros-Software/premake-core,jstewart-amd/premake-core,starkos/premake-core,mendsley/premake-core,mendsley/premake-core,starkos/premake-core,premake/premake-core,starkos/premake-core,soundsrc/premake-core,alarouche/premake-core,Yhgenomics/premake-core,akaStiX/premake-core,tvandijck/premake-core,grbd/premake-core,Tiger66639/premake-core,sleepingwit/premake-core,bravnsgaard/premake-core,noresources/premake-core,mendsley/premake-core,kankaristo/premake-core,felipeprov/premake-core,sleepingwit/premake-core,LORgames/premake-core,jsfdez/premake-core,LORgames/premake-core,resetnow/premake-core,dcourtois/premake-core,mandersan/premake-core,premake/premake-core,noresources/premake-core,PlexChat/premake-core,tvandijck/premake-core,xriss/premake-core,Meoo/premake-core,resetnow/premake-core,lizh06/premake-core,noresources/premake-core,tritao/premake-core,noresources/premake-core,Blizzard/premake-core,mendsley/premake-core,xriss/premake-core,Meoo/premake-core,Yhgenomics/premake-core,dcourtois/premake-core,LORgames/premake-core,Yhgenomics/premake-core,LORgames/premake-core,tvandijck/premake-core,prapin/premake-core,saberhawk/premake-core,Tiger66639/premake-core,mandersan/premake-core,jstewart-amd/premake-core,jstewart-amd/premake-core,premake/premake-core,starkos/premake-core,martin-traverse/premake-core,alarouche/premake-core,Zefiros-Software/premake-core,Meoo/premake-core,tritao/premake-core,tvandijck/premake-core,TurkeyMan/premake-core,TurkeyMan/premake-core,resetnow/premake-core,bravnsgaard/premake-core,alarouche/premake-core,Meoo/premake-core,tvandijck/premake-core,jstewart-amd/premake-core,CodeAnxiety/premake-core,prapin/premake-core,dcourtois/premake-core,Tiger66639/premake-core,resetnow/premake-core,martin-traverse/premake-core,soundsrc/premake-core,akaStiX/premake-core,Zefiros-Software/premake-core,grbd/premake-core,akaStiX/premake-core,soundsrc/premake-core,mendsley/premake-core,felipeprov/premake-core,mandersan/premake-core,jsfdez/premake-core,jstewart-amd/premake-core,lizh06/premake-core,Blizzard/premake-core,CodeAnxiety/premake-core,mandersan/premake-core,tritao/premake-core,akaStiX/premake-core,sleepingwit/premake-core,CodeAnxiety/premake-core,Zefiros-Software/premake-core,grbd/premake-core,aleksijuvani/premake-core,mandersan/premake-core,noresources/premake-core,CodeAnxiety/premake-core,premake/premake-core,xriss/premake-core,alarouche/premake-core,TurkeyMan/premake-core,tritao/premake-core,Blizzard/premake-core,soundsrc/premake-core,lizh06/premake-core,noresources/premake-core,xriss/premake-core,Zefiros-Software/premake-core,dcourtois/premake-core,bravnsgaard/premake-core,xriss/premake-core,aleksijuvani/premake-core,TurkeyMan/premake-core,jsfdez/premake-core,noresources/premake-core,premake/premake-core,Tiger66639/premake-core,PlexChat/premake-core,dcourtois/premake-core,Blizzard/premake-core,Blizzard/premake-core,kankaristo/premake-core,martin-traverse/premake-core,martin-traverse/premake-core,premake/premake-core,premake/premake-core,Yhgenomics/premake-core,sleepingwit/premake-core,PlexChat/premake-core,kankaristo/premake-core,sleepingwit/premake-core,prapin/premake-core,starkos/premake-core,saberhawk/premake-core,aleksijuvani/premake-core,aleksijuvani/premake-core,PlexChat/premake-core,LORgames/premake-core,grbd/premake-core,dcourtois/premake-core,felipeprov/premake-core,lizh06/premake-core,jsfdez/premake-core,starkos/premake-core,CodeAnxiety/premake-core,kankaristo/premake-core,bravnsgaard/premake-core,resetnow/premake-core
18d48c1802833ac653e8d5a4401fbf9891f4b825
etc/cavr/config/example.lua
etc/cavr/config/example.lua
sim_window = { view = { simulator_view = true; }; fullscreen = true; }; sim_window = { view = { simulator_view = true; }; fullscreen = true; }; perspective_window = { view = { eyes = { eye = cavr.sixdof("emulated"); --left_eye = cavr.sixdof("emulated3"); --right_eye = cavr.sixdof("emulated2"); --stereo ="mono"; }; lower_left = cavr.sixdof("emulated") * cavr.translate(-1, -1, -1); lower_right = cavr.sixdof("emulated") * cavr.translate(1, -1, -1); upper_left = cavr.sixdof("emulated") * cavr.translate(-1, 1, -1); }; fullscreen = true; }; x11_renderer = { type = "x11gl"; display = ":0.0"; windows = { --sim_window = sim_window; sim_window2 = sim_window; }; }; x11_renderer2 = { type = "x11gl"; display = ":0.1"; windows = { sim_window = sim_window; }; } x11_renderer3 = { type = "x11gl"; display = ":0.2"; windows = { perspective_window = perspective_window; --sim_window = sim_window; }; } vrpn = { type = "vrpn"; input_name = "vrpn"; buttons = { --"Button0@localhost"; }; analogs = { }; sixdofs = { --"[email protected]" }; }; self = { hostname = HOSTNAME; ssh = HOSTNAME;--"chase@" .. HOSTNAME; address = HOSTNAME; plugins = { x11_renderer3 = x11_renderer3; x11_renderer2 = x11_renderer2; x11_renderer = x11_renderer; vrpn = vrpn; }; }; others = { hostname = "hpcvis7"; ssh = "hpcvis7"; address = "hpcvis7";--"tcp://" .. "hpcvis7" .. ":8888"; plugins = { x11_renderer = x11_renderer; vrpn = vrpn; }; }; others2 = { hostname = "hpcvis2"; ssh = "hpcvis2"; address = "hpcvis2";--"tcp://" .. "hpcvis7" .. ":8888"; plugins = { x11_renderer = x11_renderer; vrpn = vrpn; }; }; machines = { self=self; --self2 = others; --self3 = others2; };
sim_window = { view = { simulator_view = true; }; fullscreen = true; }; sim_window = { view = { simulator_view = true; }; fullscreen = true; }; perspective_window = { view = { eyes = { eye = cavr.sixdof("emulated"); --left_eye = cavr.sixdof("emulated3"); --right_eye = cavr.sixdof("emulated2"); --stereo ="mono"; }; lower_left = cavr.sixdof("emulated") * cavr.translate(-1, -1, -1); lower_right = cavr.sixdof("emulated") * cavr.translate(1, -1, -1); upper_left = cavr.sixdof("emulated") * cavr.translate(-1, 1, -1); }; fullscreen = true; }; x11_renderer = { type = "x11gl"; display = ":0.0"; windows = { --sim_window = sim_window; sim_window2 = sim_window; }; }; vrpn = { type = "vrpn"; input_name = "vrpn"; buttons = { --"Button0@localhost"; }; analogs = { }; sixdofs = { --"[email protected]" }; }; self = { hostname = HOSTNAME; ssh = HOSTNAME;--"chase@" .. HOSTNAME; address = HOSTNAME; plugins = { x11_renderer = x11_renderer; vrpn = vrpn; }; }; others = { hostname = "hpcvis7"; ssh = "hpcvis7"; address = "hpcvis7";--"tcp://" .. "hpcvis7" .. ":8888"; plugins = { x11_renderer = x11_renderer; vrpn = vrpn; }; }; others2 = { hostname = "hpcvis2"; ssh = "hpcvis2"; address = "hpcvis2";--"tcp://" .. "hpcvis7" .. ":8888"; plugins = { x11_renderer = x11_renderer; vrpn = vrpn; }; }; machines = { self=self; --self2 = others; --self3 = others2; };
Fixing example.lua not to be based on local changes.
Fixing example.lua not to be based on local changes.
Lua
bsd-3-clause
BrainComputationLab/cavr,BrainComputationLab/cavr,BrainComputationLab/cavr,BrainComputationLab/cavr
ab7670b76491771c4de52b6b668dd1140b0cc92b
console/nwconsole.lua
console/nwconsole.lua
#!/usr/local/bin/luajit --[[ Nonsence Web console Copyright 2013 John Abrahamsen Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]] require "curses" require "os" local nonsence = require "nonsence" local SOCK_STREAM = nonsence.socket.SOCK.SOCK_STREAM local INADDRY_ANY = nonsence.socket.INADDR_ANY local AF_INET = nonsence.socket.AF.AF_INET if not arg[1] then print "Please provide a hostname as argument." os.exit(1) end local addr = arg[1]:split(":") if #addr ~= 2 then print "Bad syntax in hostname. Use <hostname:port>." os.exit(1) end local hostname = addr[1] local port = tonumber(addr[2]) local io_loop = nonsence.ioloop.instance() local stream = nonsence.iostream.IOStream:new(nonsence.socket.new_nonblock_socket(AF_INET, SOCK_STREAM, 0)) local rc, msg = stream:connect(hostname, port, AF_INET, function() -- On success curses.initscr() curses.cbreak() curses.echo(0) curses.nl(0) local stdscr = curses.stdscr() stdscr:clear() stdscr:mvaddstr(0,0, "Nonsence Web Debug Console") local reading = false io_loop:set_interval(200, function() -- 200 msec loop if reading then return end stream:write("s\n\n", function() reading = true stream:read_until("\n\n", function(data) reading = false local stats = nonsence.escape.json_decode(data) stdscr:mvaddstr(2,2, "TCP | Bytes recieved : ") stdscr:mvaddstr(2,60, stats.tcp_recv_bytes .. " B") stdscr:mvaddstr(3,2, "TCP | Bytes sent : ") stdscr:mvaddstr(3,60, stats.tcp_send_bytes .. " B") stdscr:mvaddstr(4,2, "TCP | Current open sockets : ") stdscr:mvaddstr(4,60, stats.tcp_open_sockets) stdscr:mvaddstr(5,2, "TCP | Total sockets opened : ") stdscr:mvaddstr(5,60, stats.tcp_total_connects ) stdscr:mvaddstr(6,2, "IO Loop | Callbacks run : ") stdscr:mvaddstr(6,60, stats.ioloop_callbacks_run) stdscr:mvaddstr(7,2, "IO Loop | Callbacks in queue : ") stdscr:mvaddstr(7,60, stats.ioloop_callbacks_queue) stdscr:mvaddstr(8,2, "IO Loop | Callback errors caught : ") stdscr:mvaddstr(8,60, stats.ioloop_callbacks_error_count) stdscr:mvaddstr(9,2, "IO Loop | Current FD count: ") stdscr:mvaddstr(9,60, stats.ioloop_fd_count ) stdscr:mvaddstr(10,2, "IO Loop | Active handler count : ") stdscr:mvaddstr(10,60, stats.ioloop_handlers_total) stdscr:mvaddstr(11,2, "IO Loop | Handlers added : ") stdscr:mvaddstr(11,60, stats.ioloop_add_handler_count) stdscr:mvaddstr(12,2, "IO Loop | Handlers updated: ") stdscr:mvaddstr(12,60, stats.ioloop_update_handler_count) stdscr:mvaddstr(13,2, "IO Loop | Handlers called : ") stdscr:mvaddstr(13,60, stats.ioloop_handlers_called) stdscr:mvaddstr(14,2, "IO Loop | Handler errors caught : ") stdscr:mvaddstr(14,60, stats.ioloop_handlers_errors_count) stdscr:mvaddstr(15,2, "IO Loop | Active timeout callback count : ") stdscr:mvaddstr(15,60, stats.ioloop_timeout_count) stdscr:mvaddstr(16,2, "IO Loop | Active interal callback count : ") stdscr:mvaddstr(16,60, stats.ioloop_interval_count) stdscr:mvaddstr(17,2, "IO Loop | Iteration count : ") stdscr:mvaddstr(17,60, stats.ioloop_iteration_count) stdscr:mvaddstr(18,2, "File cache | Objects count : ") stdscr:mvaddstr(18,60, stats.static_cache_objects) stdscr:mvaddstr(19,2, "File cache | Total bytes : ") stdscr:mvaddstr(19,60, stats.static_cache_bytes) stdscr:refresh() end) end) end) end, function(errno, strerror) -- On connect fail print(string.format("Could not connect to host %s: %s.", hostname, strerror)) os.exit(1) end) if rc == -1 then print("Could not connect to host. Invalid hostname given.") os.exit(1) elseif rc == -3 then print("Could not connect. Unknown error.") os.exit(1) end io_loop:start()
#!/usr/local/bin/luajit --[[ Nonsence Web console Copyright 2013 John Abrahamsen Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]] require "curses" require "os" local nonsence = require "nonsence" local SOCK_STREAM = nonsence.socket.SOCK_STREAM local INADDRY_ANY = nonsence.socket.INADDR_ANY local AF_INET = nonsence.socket.AF_INET if not arg[1] then print "Please provide a hostname as argument." os.exit(1) end local addr = arg[1]:split(":") if #addr ~= 2 then print "Bad syntax in hostname. Use <hostname:port>." os.exit(1) end local hostname = addr[1] local port = tonumber(addr[2]) local io_loop = nonsence.ioloop.instance() local stream = nonsence.iostream.IOStream:new(nonsence.socket.new_nonblock_socket(AF_INET, SOCK_STREAM, 0)) local rc, msg = stream:connect(hostname, port, AF_INET, function() -- On success curses.initscr() curses.cbreak() curses.echo(0) curses.nl(0) local stdscr = curses.stdscr() stdscr:clear() local reading = false io_loop:set_interval(200, function() -- 200 msec loop if reading then return end stream:write("s\n\n", function() reading = true stream:read_until("\n\n", function(data) if data:len() == 0 then os.exit(1) end reading = false stdscr:clear() local stats = nonsence.escape.json_decode(data) stdscr:mvaddstr(0,0, "Nonsence Web Debug Console") stdscr:mvaddstr(2,2, "TCP | Bytes recieved : ") stdscr:mvaddstr(2,60, stats.tcp_recv_bytes .. " B") stdscr:mvaddstr(3,2, "TCP | Bytes sent : ") stdscr:mvaddstr(3,60, stats.tcp_send_bytes .. " B") stdscr:mvaddstr(4,2, "TCP | Current open sockets : ") stdscr:mvaddstr(4,60, stats.tcp_open_sockets) stdscr:mvaddstr(5,2, "TCP | Total sockets opened : ") stdscr:mvaddstr(5,60, stats.tcp_total_connects ) stdscr:mvaddstr(6,2, "IO Loop | Callbacks run : ") stdscr:mvaddstr(6,60, stats.ioloop_callbacks_run) stdscr:mvaddstr(7,2, "IO Loop | Callbacks in queue : ") stdscr:mvaddstr(7,60, stats.ioloop_callbacks_queue) stdscr:mvaddstr(8,2, "IO Loop | Callback errors caught : ") stdscr:mvaddstr(8,60, stats.ioloop_callbacks_error_count) stdscr:mvaddstr(9,2, "IO Loop | Current FD count: ") stdscr:mvaddstr(9,60, stats.ioloop_fd_count ) stdscr:mvaddstr(10,2, "IO Loop | Active handler count : ") stdscr:mvaddstr(10,60, stats.ioloop_handlers_total) stdscr:mvaddstr(11,2, "IO Loop | Handlers added : ") stdscr:mvaddstr(11,60, stats.ioloop_add_handler_count) stdscr:mvaddstr(12,2, "IO Loop | Handlers updated: ") stdscr:mvaddstr(12,60, stats.ioloop_update_handler_count) stdscr:mvaddstr(13,2, "IO Loop | Handlers called : ") stdscr:mvaddstr(13,60, stats.ioloop_handlers_called) stdscr:mvaddstr(14,2, "IO Loop | Handler errors caught : ") stdscr:mvaddstr(14,60, stats.ioloop_handlers_errors_count) stdscr:mvaddstr(15,2, "IO Loop | Active timeout callback count : ") stdscr:mvaddstr(15,60, stats.ioloop_timeout_count) stdscr:mvaddstr(16,2, "IO Loop | Active interal callback count : ") stdscr:mvaddstr(16,60, stats.ioloop_interval_count) stdscr:mvaddstr(17,2, "IO Loop | Iteration count : ") stdscr:mvaddstr(17,60, stats.ioloop_iteration_count) stdscr:mvaddstr(18,2, "File cache | Objects count : ") stdscr:mvaddstr(18,60, stats.static_cache_objects) stdscr:mvaddstr(19,2, "File cache | Total bytes : ") stdscr:mvaddstr(19,60, stats.static_cache_bytes) stdscr:refresh() end) end) end) end, function(_, errno) -- On connect fail print(string.format("Could not connect to host %s: %s.", hostname, nonsence.socket.strerror(errno))) os.exit(1) end) if rc == -1 then print("Could not connect to host. Invalid hostname given.") os.exit(1) elseif rc == -3 then print("Could not connect. Unknown error.") os.exit(1) end io_loop:start()
Some fixes for debug console.
Some fixes for debug console.
Lua
apache-2.0
zcsteele/turbo,zcsteele/turbo,ddysher/turbo,mniestroj/turbo,kernelsauce/turbo,luastoned/turbo,YuanPeir-Chen/turbo-support-mipsel,ddysher/turbo,luastoned/turbo,YuanPeir-Chen/turbo-support-mipsel
475f4d1ab463b50432aaf774b75d94a682bb6e98
libs/term.lua
libs/term.lua
local prev, pl, luv, dir, T, stdin, exit_seq = ... local _colors = { [1] = "white"; [2] = "orange"; [4] = "magenta"; [8] = "lightBlue"; [16] = "yellow"; [32] = "lime"; [64] = "pink"; [128] = "gray"; [256] = "lightGray"; [512] = "cyan"; [1024] = "purple"; [2048] = "blue"; [4096] = "brown"; [8192] = "green"; [16384] = "red"; [32768] = "black"; } local color_escapes = { fg = { white = T.setaf(7); orange = T.setaf(3); magenta = T.setaf(5); lightBlue = T.setaf(4); yellow = T.setaf(3); lime = T.setaf(2); pink = T.setaf(5); gray = T.setaf(0); lightGray = T.setaf(0); cyan = T.setaf(6); purple = T.setaf(5); blue = T.setaf(4); brown = T.setaf(3); green = T.setaf(2); red = T.setaf(1); black = T.setaf(0); }; bg = { white = T.setab(7); orange = T.setab(3); magenta = T.setab(5); lightBlue = T.setab(4); yellow = T.setab(3); lime = T.setab(2); pink = T.setab(5); gray = T.setab(0); lightGray = T.setab(0); cyan = T.setab(6); purple = T.setab(5); blue = T.setab(4); brown = T.setab(3); green = T.setab(2); red = T.setab(1); black = T.setab(0); }; } do local fg_dir = pl.path.join(dir, '.termu', 'term-colors', 'fg') if pl.path.isdir(fg_dir) then for color in pl.path.dir(fg_dir) do local path = pl.path.join(fg_dir, color) if id ~= '.' and id ~= '..' and pl.path.isfile(path) then local h = prev.io.open(path) color_escapes.fg[color] = h:read '*a' h:close() end end end local bg_dir = pl.path.join(dir, '.termu', 'term-colors', 'bg') if pl.path.isdir(bg_dir) then for color in pl.path.dir(bg_dir) do local path = pl.path.join(bg_dir, color) if id ~= '.' and id ~= '..' and pl.path.isfile(path) then local h = prev.io.open(path) color_escapes.bg[color] = h:read '*a' h:close() end end end end local hex = { ['a'] = 10; ['b'] = 11; ['c'] = 12; ['d'] = 13; ['e'] = 14; ['f'] = 15; } for i = 0, 9 do hex[tostring(i)] = i end local cursorX, cursorY = 1, 1 local textColor, backColor = 0, 15 local log2 = math.log(2) local function ccColorFor(c) if type(c) ~= 'number' or c < 0 or c > 15 then error('that\'s not a valid color: ' .. tostring(c)) end return math.pow(2, c) end local function fromHexColor(h) return hex[h] or error('not a hex color: ' .. tostring(h)) end local processOutput if pl.path.exists(pl.path.join(dir, '.termu', 'term-munging')) then local utf8 = prev.utf8 or prev.require 'utf8' function processOutput(out) local res = '' for c in out:gmatch '.' do if c == '\0' or c == '\9' or c == '\10' or c == '\13' or c == '\32' or c == '\128' or c == '\160' then res = res .. c else res = res .. utf8.char(0xE000 + c:byte()) end end return res end else function processOutput(out) return out end end local termNat termNat = { clear = function() local w, h = termNat.getSize() for l = 0, h - 1 do prev.io.write(T.cup(l, 0)) prev.io.write((' '):rep(w)) end termNat.setCursorPos(cursorX, cursorY) end; clearLine = function() local w, h = termNat.getSize() prev.io.write(T.cup(cursorY - 1, 0)) prev.io.write((' '):rep(w)) termNat.setCursorPos(cursorX, cursorY) end; isColour = function() return true end; isColor = function() return true end; getSize = function() return luv.tty_get_winsize(stdin) -- return 52, 19 end; getCursorPos = function() return cursorX, cursorY end; setCursorPos = function(x, y) if type(x) ~= 'number' or type(y) ~= 'number' then error('term.setCursorPos expects number, number, got: ' .. type(x) .. ', ' .. type(y)) end local oldX, oldY = cursorX, cursorY cursorX, cursorY = math.floor(x), math.floor(y) local w, h = luv.tty_get_winsize(stdin) if cursorY < 1 or cursorY > h or cursorX < 1 or cursorX > w then prev.io.write(T.cursor_invisible()) else if oldY < 1 or oldY > h or oldX < 1 or oldX > w then prev.io.write(T.cursor_normal()) end prev.io.write(T.cup(cursorY - 1, cursorX - 1)) end end; setTextColour = function(...) return termNat.setTextColor(...) end; setTextColor = function(c) textColor = math.log(c) / log2 prev.io.write(color_escapes.fg[_colors[c] ]) end; getTextColour = function(...) return termNat.getTextColor(...) end; getTextColor = function() return ccColorFor(textColor) end; setBackgroundColour = function(...) return termNat.setBackgroundColor(...) end; setBackgroundColor = function(c) backColor = math.log(c) / log2 prev.io.write(color_escapes.bg[_colors[c] ]) end; getBackgroundColour = function(...) return termNat.getBackgroundColor(...) end; getBackgroundColor = function() return ccColorFor(backColor) end; write = function(text) text = tostring(text or '') text = text:gsub('[\n\r]', '?') prev.io.write(processOutput(text)) termNat.setCursorPos(cursorX + #text, cursorY) end; blit = function(text, textColors, backColors) text = text:gsub('[\n\r]', '?') if #text ~= #textColors or #text ~= #backColors then error('term.blit: text, textColors and backColors have to be the same length') end for i = 1, #text do termNat.setTextColor(ccColorFor(fromHexColor(textColors:sub(i, i)))) termNat.setBackgroundColor(ccColorFor(fromHexColor(backColors:sub(i, i)))) prev.io.write(processOutput(text:sub(i, i))) end cursorX = cursorX + #text end; setCursorBlink = function() end; scroll = function(n) n = n or 1 local w, h = luv.tty_get_winsize(stdin) prev.io.write(n < 0 and T.cup(0, 0) or T.cup(h, w)) local txt = T[n < 0 and 'ri' or 'ind']() prev.io.write(txt:rep(math.abs(n))) -- if n > 0 then -- prev.io.write(T.cup(h - n, 0)) -- prev.io.write(T.clr_eos()) -- elseif n < 0 then -- for i = 0, n do -- prev.io.write(T.cup(i, 0)) -- prev.io.write((' '):rep(w)) -- end -- end termNat.setCursorPos(cursorX, cursorY) end } prev.io.write(T.smcup()) termNat.setTextColor(1) termNat.setBackgroundColor(32768) termNat.clear() prev.io.flush() exit_seq[#exit_seq + 1] = function() prev.io.write(T.rmcup()) prev.io.flush() end return termNat
local prev, pl, luv, dir, T, stdin, exit_seq = ... local _colors = { [1] = "white"; [2] = "orange"; [4] = "magenta"; [8] = "lightBlue"; [16] = "yellow"; [32] = "lime"; [64] = "pink"; [128] = "gray"; [256] = "lightGray"; [512] = "cyan"; [1024] = "purple"; [2048] = "blue"; [4096] = "brown"; [8192] = "green"; [16384] = "red"; [32768] = "black"; } local color_escapes = { fg = { white = T.setaf(7); orange = T.setaf(3); magenta = T.setaf(5); lightBlue = T.setaf(4); yellow = T.setaf(3); lime = T.setaf(2); pink = T.setaf(5); gray = T.setaf(0); lightGray = T.setaf(0); cyan = T.setaf(6); purple = T.setaf(5); blue = T.setaf(4); brown = T.setaf(3); green = T.setaf(2); red = T.setaf(1); black = T.setaf(0); }; bg = { white = T.setab(7); orange = T.setab(3); magenta = T.setab(5); lightBlue = T.setab(4); yellow = T.setab(3); lime = T.setab(2); pink = T.setab(5); gray = T.setab(0); lightGray = T.setab(0); cyan = T.setab(6); purple = T.setab(5); blue = T.setab(4); brown = T.setab(3); green = T.setab(2); red = T.setab(1); black = T.setab(0); }; } do local fg_dir = pl.path.join(dir, '.termu', 'term-colors', 'fg') if pl.path.isdir(fg_dir) then for color in pl.path.dir(fg_dir) do local path = pl.path.join(fg_dir, color) if id ~= '.' and id ~= '..' and pl.path.isfile(path) then local h = prev.io.open(path) color_escapes.fg[color] = h:read '*a' h:close() end end end local bg_dir = pl.path.join(dir, '.termu', 'term-colors', 'bg') if pl.path.isdir(bg_dir) then for color in pl.path.dir(bg_dir) do local path = pl.path.join(bg_dir, color) if id ~= '.' and id ~= '..' and pl.path.isfile(path) then local h = prev.io.open(path) color_escapes.bg[color] = h:read '*a' h:close() end end end end local hex = { ['a'] = 10; ['b'] = 11; ['c'] = 12; ['d'] = 13; ['e'] = 14; ['f'] = 15; } for i = 0, 9 do hex[tostring(i)] = i end local cursorX, cursorY = 1, 1 local cursorBlink = true local textColor, backColor = 0, 15 local log2 = math.log(2) local function ccColorFor(c) if type(c) ~= 'number' or c < 0 or c > 15 then error('that\'s not a valid color: ' .. tostring(c)) end return math.pow(2, c) end local function fromHexColor(h) return hex[h] or error('not a hex color: ' .. tostring(h)) end local processOutput if pl.path.exists(pl.path.join(dir, '.termu', 'term-munging')) then local utf8 = prev.utf8 or prev.require 'utf8' function processOutput(out) local res = '' for c in out:gmatch '.' do if c == '\0' or c == '\9' or c == '\10' or c == '\13' or c == '\32' or c == '\128' or c == '\160' then res = res .. c else res = res .. utf8.char(0xE000 + c:byte()) end end return res end else function processOutput(out) return out end end local termNat termNat = { clear = function() local w, h = termNat.getSize() for l = 0, h - 1 do prev.io.write(T.cup(l, 0)) prev.io.write((' '):rep(w)) end termNat.setCursorPos(cursorX, cursorY) end; clearLine = function() local w, h = termNat.getSize() prev.io.write(T.cup(cursorY - 1, 0)) prev.io.write((' '):rep(w)) termNat.setCursorPos(cursorX, cursorY) end; isColour = function() return true end; isColor = function() return true end; getSize = function() return luv.tty_get_winsize(stdin) -- return 52, 19 end; getCursorPos = function() return cursorX, cursorY end; setCursorPos = function(x, y) if type(x) ~= 'number' or type(y) ~= 'number' then error('term.setCursorPos expects number, number, got: ' .. type(x) .. ', ' .. type(y)) end local oldX, oldY = cursorX, cursorY cursorX, cursorY = math.floor(x), math.floor(y) termNat.setCursorBlink(cursorBlink) local w, h = luv.tty_get_winsize(stdin) if cursorY >= 1 and cursorY <= h and cursorX >= 1 and cursorX <= w then prev.io.write(T.cup(cursorY - 1, cursorX - 1)) end end; setTextColour = function(...) return termNat.setTextColor(...) end; setTextColor = function(c) textColor = math.log(c) / log2 prev.io.write(color_escapes.fg[_colors[c] ]) end; getTextColour = function(...) return termNat.getTextColor(...) end; getTextColor = function() return ccColorFor(textColor) end; setBackgroundColour = function(...) return termNat.setBackgroundColor(...) end; setBackgroundColor = function(c) backColor = math.log(c) / log2 prev.io.write(color_escapes.bg[_colors[c] ]) end; getBackgroundColour = function(...) return termNat.getBackgroundColor(...) end; getBackgroundColor = function() return ccColorFor(backColor) end; write = function(text) text = tostring(text or '') text = text:gsub('[\n\r]', '?') local w, h = luv.tty_get_winsize(stdin) if cursorY >= 1 and cursorY <= h and cursorX > 1 - #text and cursorX <= w then prev.io.write(processOutput(text)) end termNat.setCursorPos(cursorX + #text, cursorY) end; blit = function(text, textColors, backColors) text = text:gsub('[\n\r]', '?') if #text ~= #textColors or #text ~= #backColors then error('term.blit: text, textColors and backColors have to be the same length') end local w, h = luv.tty_get_winsize(stdin) if cursorY >= 1 and cursorY <= h and cursorX > 1 - #text and cursorX <= w then local fg, bg = textColor, backColor for i = 1, #text do termNat.setTextColor(ccColorFor(fromHexColor(textColors:sub(i, i)))) termNat.setBackgroundColor(ccColorFor(fromHexColor(backColors:sub(i, i)))) prev.io.write(processOutput(text:sub(i, i))) end termNat.setTextColor(ccColorFor(fg)) termNat.setBackgroundColor(ccColorFor(bg)) end termNat.setCursorPos(cursorX + #text, cursorY) end; setCursorBlink = function(blink) cursorBlink = blink local w, h = luv.tty_get_winsize(stdin) if cursorBlink and cursorY >= 1 and cursorY <= h and cursorX >= 1 and cursorX <= w then prev.io.write(T.cursor_normal()) else prev.io.write(T.cursor_invisible()) end end; scroll = function(n) n = n or 1 local w, h = luv.tty_get_winsize(stdin) prev.io.write(n < 0 and T.cup(0, 0) or T.cup(h, w)) local txt = T[n < 0 and 'ri' or 'ind']() prev.io.write(txt:rep(math.abs(n))) -- if n > 0 then -- prev.io.write(T.cup(h - n, 0)) -- prev.io.write(T.clr_eos()) -- elseif n < 0 then -- for i = 0, n do -- prev.io.write(T.cup(i, 0)) -- prev.io.write((' '):rep(w)) -- end -- end termNat.setCursorPos(cursorX, cursorY) end } prev.io.write(T.smcup()) termNat.setTextColor(1) termNat.setBackgroundColor(32768) termNat.clear() prev.io.flush() exit_seq[#exit_seq + 1] = function() prev.io.write(T.rmcup()) prev.io.flush() end return termNat
Term stuff
Term stuff Fix rendering when the cursor is off screen Implement `setCursorBlink`
Lua
mit
CoderPuppy/cc-emu,CoderPuppy/cc-emu,CoderPuppy/cc-emu
b91f1c88627cc00bb561ae6f4656daf7de97dc52
src/cosy/server/cli.lua
src/cosy/server/cli.lua
local function printerr (...) local t = { ... } for i = 1, #t do t [i] = tostring (t [i]) end io.stderr:write (table.concat (t, "\t") .. "\n") end local arguments do local loader = require "cosy.loader.lua" { logto = false, } local Configuration = loader.load "cosy.configuration" local I18n = loader.load "cosy.i18n" local Arguments = loader.require "argparse" Configuration.load { "cosy.nginx", -- TODO: check "cosy.server", } local i18n = I18n.load { "cosy.client", "cosy.server", } i18n._locale = Configuration.server.locale local parser = Arguments () { name = "cosy-server", description = i18n ["server:command"] % {}, } local start = parser:command "start" { description = i18n ["server:start"] % {}, } start:option "-a" "--alias" { description = "configuration name", default = "default", } start:option "-p" "--port" { description = "network port", default = tostring (Configuration.http.port), defmode = "arg", } start:flag "-f" "--force" { description = i18n ["flag:force"] % {}, } start:flag "-c" "--clean" { description = i18n ["flag:clean"] % {}, } local stop = parser:command "stop" { description = i18n ["server:stop"] % {}, } stop:option "-a" "--alias" { description = "configuration name", default = "default", } stop:flag "-f" "--force" { description = i18n ["flag:force"] % {}, } local _ = parser:command "version" { description = i18n ["server:version"] % {}, } arguments = parser:parse () end local loader = require "cosy.loader.lua" { logto = false, alias = arguments.alias, } local Configuration = loader.load "cosy.configuration" local File = loader.load "cosy.file" local I18n = loader.load "cosy.i18n" local Library = loader.load "cosy.library" local Colors = loader.require "ansicolors" local Posix = loader.require "posix" Configuration.load { "cosy.nginx", -- TODO: check "cosy.server", } local i18n = I18n.load { "cosy.client", "cosy.server", } i18n._locale = Configuration.server.locale if arguments.start then local data = File.decode (Configuration.server.data) or {} local url = "http://{{{host}}}:{{{port}}}/" % { host = "localhost", port = data.port or Configuration.http.port, } local client = Library.connect (url) if client then if arguments.force and data then local result = client.server.stop { administration = data.token, } if not result then Posix.kill (data.pid, 9) -- kill end else printerr (Colors ("%{black redbg}" .. i18n ["failure"] % {}), Colors ("%{red blackbg}" .. i18n ["server:already-running"] % {})) os.exit (1) end end if arguments.clean then Configuration.load "cosy.redis" local Redis = loader.require "redis" local host = Configuration.redis.interface local port = Configuration.redis.port local database = Configuration.redis.database local redis = Redis.connect (host, port) redis:select (database) redis:flushdb () package.loaded ["redis"] = nil end os.remove (Configuration.server.log ) os.remove (Configuration.server.data) if Posix.fork () == 0 then local ev = require "ev" ev.Loop.default:fork () File.encode (Configuration.server.data, { alias = arguments.alias, http_port = tonumber (arguments.port) or data.port or Configuration.http.port, }) local Server = loader.load "cosy.server" Server.start () os.exit (0) end local tries = 0 local serverdata, nginxdata repeat Posix.sleep (1) serverdata = File.decode (Configuration.server.data) nginxdata = File.decode (Configuration.http .pid) tries = tries + 1 until (serverdata and nginxdata) or tries == 5 if serverdata and nginxdata then print (Colors ("%{black greenbg}" .. i18n ["success"] % {})) os.exit (0) else printerr (Colors ("%{black redbg}" .. i18n ["failure"] % {}), Colors ("%{red blackbg}" .. i18n ["server:unreachable"] % {})) os.exit (1) end elseif arguments.stop then local data = File.decode (Configuration.server.data) or {} local url = "http://{{{host}}}:{{{port}}}/" % { host = "localhost", port = data.port or Configuration.http.port, } local client = Library.connect (url) if client and data then local result = client.server.stop { administration = data.token, } if result then print (Colors ("%{black greenbg}" .. i18n ["success"] % {})) os.exit (0) end end if not client then if arguments.force and data.pid then Posix.kill (data.pid, 9) -- kill local nginx_file = io.open (Configuration.http.pid, "r") if nginx_file then local nginx_pid = nginx_file:read "*a" nginx_file:close () Posix.kill (nginx_pid:match "%S+", 15) -- term print (Colors ("%{black greenbg}" .. i18n ["success"] % {})) os.exit (0) else printerr (Colors ("%{black redbg}" .. i18n ["failure"] % {})) os.exit (1) end elseif arguments.force then printerr (Colors ("%{black redbg}" .. i18n ["failure"] % {})) os.exit (1) else printerr (Colors ("%{black redbg}" .. i18n ["failure"] % {}), Colors ("%{red blackbg}" .. i18n ["server:unreachable"] % {})) os.exit (1) end end elseif arguments.version then local path = package.searchpath ("cosy.server.cli", package.path) local parts = {} for part in path:gmatch "[^/]+" do parts [#parts+1] = part end parts [#parts] = nil parts [#parts] = nil path = (path:find "^/" and "/" or "") .. table.concat (parts, "/") local handler = assert (io.popen ([[ . "{{{prefix}}}/bin/realpath.sh" cd $(realpath "{{{path}}}") git describe ]] % { prefix = loader.prefix, path = path, }, "r")) local result, err = assert (handler:read "*a") handler:close () if result then print (result:match "%S+") print (Colors ("%{black greenbg}" .. i18n ["success"] % {})) os.exit (0) else printerr (Colors ("%{black redbg}" .. i18n ["failure"] % {}), Colors ("%{red blackbg}" .. err)) os.exit (1) end else assert (false) end
local function printerr (...) local t = { ... } for i = 1, #t do t [i] = tostring (t [i]) end io.stderr:write (table.concat (t, "\t") .. "\n") end local arguments do local loader = require "cosy.loader.lua" { logto = false, } local Configuration = loader.load "cosy.configuration" local I18n = loader.load "cosy.i18n" local Arguments = loader.require "argparse" Configuration.load { "cosy.nginx", -- TODO: check "cosy.server", } local i18n = I18n.load { "cosy.client", "cosy.server", } i18n._locale = Configuration.server.locale local parser = Arguments () { name = "cosy-server", description = i18n ["server:command"] % {}, } local start = parser:command "start" { description = i18n ["server:start"] % {}, } start:option "-a" "--alias" { description = "configuration name", default = "default", } start:option "-p" "--port" { description = "network port", default = tostring (Configuration.http.port), defmode = "arg", } start:flag "-f" "--force" { description = i18n ["flag:force"] % {}, } start:flag "-c" "--clean" { description = i18n ["flag:clean"] % {}, } local stop = parser:command "stop" { description = i18n ["server:stop"] % {}, } stop:option "-a" "--alias" { description = "configuration name", default = "default", } stop:flag "-f" "--force" { description = i18n ["flag:force"] % {}, } local _ = parser:command "version" { description = i18n ["server:version"] % {}, } arguments = parser:parse () end local Scheduler = require "copas.ev" local Hotswap = require "hotswap.ev".new { loop = Scheduler._loop, } local loader = require "cosy.loader.lua" { alias = arguments.aias, logto = false, hotswap = Hotswap, scheduler = Scheduler, } local Configuration = loader.load "cosy.configuration" local File = loader.load "cosy.file" local I18n = loader.load "cosy.i18n" local Library = loader.load "cosy.library" local Colors = loader.require "ansicolors" local Posix = loader.require "posix" Configuration.load { "cosy.nginx", -- TODO: check "cosy.server", } local i18n = I18n.load { "cosy.client", "cosy.server", } i18n._locale = Configuration.server.locale if arguments.start then local data = File.decode (Configuration.server.data) or {} local url = "http://{{{host}}}:{{{port}}}/" % { host = "localhost", port = data.port or Configuration.http.port, } local client = Library.connect (url) if client then if arguments.force and data then local result = client.server.stop { administration = data.token, } if not result then Posix.kill (data.pid, 9) -- kill end else printerr (Colors ("%{black redbg}" .. i18n ["failure"] % {}), Colors ("%{red blackbg}" .. i18n ["server:already-running"] % {})) os.exit (1) end end if arguments.clean then Configuration.load "cosy.redis" local Redis = loader.require "redis" local host = Configuration.redis.interface local port = Configuration.redis.port local database = Configuration.redis.database local redis = Redis.connect (host, port) redis:select (database) redis:flushdb () package.loaded ["redis"] = nil end os.remove (Configuration.server.log ) os.remove (Configuration.server.data) if Posix.fork () == 0 then local ev = require "ev" ev.Loop.default:fork () File.encode (Configuration.server.data, { alias = arguments.alias, http_port = tonumber (arguments.port) or data.port or Configuration.http.port, }) local Server = loader.load "cosy.server" Server.start () os.exit (0) end local tries = 0 local serverdata, nginxdata repeat Posix.sleep (1) serverdata = File.decode (Configuration.server.data) nginxdata = File.decode (Configuration.http .pid) tries = tries + 1 until (serverdata and nginxdata) or tries == 5 if serverdata and nginxdata then print (Colors ("%{black greenbg}" .. i18n ["success"] % {})) os.exit (0) else printerr (Colors ("%{black redbg}" .. i18n ["failure"] % {}), Colors ("%{red blackbg}" .. i18n ["server:unreachable"] % {})) os.exit (1) end elseif arguments.stop then local data = File.decode (Configuration.server.data) or {} local url = "http://{{{host}}}:{{{port}}}/" % { host = "localhost", port = data.port or Configuration.http.port, } local client = Library.connect (url) if client and data then local result = client.server.stop { administration = data.token, } if result then print (Colors ("%{black greenbg}" .. i18n ["success"] % {})) os.exit (0) end end if not client then if arguments.force and data.pid then Posix.kill (data.pid, 9) -- kill local nginx_file = io.open (Configuration.http.pid, "r") if nginx_file then local nginx_pid = nginx_file:read "*a" nginx_file:close () Posix.kill (nginx_pid:match "%S+", 15) -- term print (Colors ("%{black greenbg}" .. i18n ["success"] % {})) os.exit (0) else printerr (Colors ("%{black redbg}" .. i18n ["failure"] % {})) os.exit (1) end elseif arguments.force then printerr (Colors ("%{black redbg}" .. i18n ["failure"] % {})) os.exit (1) else printerr (Colors ("%{black redbg}" .. i18n ["failure"] % {}), Colors ("%{red blackbg}" .. i18n ["server:unreachable"] % {})) os.exit (1) end end elseif arguments.version then local path = package.searchpath ("cosy.server.cli", package.path) local parts = {} for part in path:gmatch "[^/]+" do parts [#parts+1] = part end parts [#parts] = nil parts [#parts] = nil path = (path:find "^/" and "/" or "") .. table.concat (parts, "/") local handler = assert (io.popen ([[ . "{{{prefix}}}/bin/realpath.sh" cd $(realpath "{{{path}}}") git describe ]] % { prefix = loader.prefix, path = path, }, "r")) local result, err = assert (handler:read "*a") handler:close () if result then print (result:match "%S+") print (Colors ("%{black greenbg}" .. i18n ["success"] % {})) os.exit (0) else printerr (Colors ("%{black redbg}" .. i18n ["failure"] % {}), Colors ("%{red blackbg}" .. err)) os.exit (1) end else assert (false) end
Fix #173
Fix #173
Lua
mit
CosyVerif/library,CosyVerif/library,CosyVerif/library
0ad468bef2b7e4514844cbfe3df7385dab52469b
Pooling.lua
Pooling.lua
local Pooling, parent = torch.class('cudnn._Pooling', 'nn.Module') local ffi = require 'ffi' local errcheck = cudnn.errcheck function Pooling:__init(kW, kH, dW, dH, padW, padH) parent.__init(self) self.kW = kW self.kH = kH self.dW = dW or kW self.dH = dH or kW self.padW = padW or 0 self.padH = padH or 0 self.iSize = torch.LongStorage(4):fill(0) self.ceil_mode = false end function Pooling:ceil() self.ceil_mode = true return self end function Pooling:floor() self.ceil_mode = false return self end function Pooling:resetPoolDescriptors() -- create pooling descriptor self.poolDesc = ffi.new('struct cudnnPoolingStruct*[1]') errcheck('cudnnCreatePoolingDescriptor', self.poolDesc) local ker = torch.IntTensor({self.kH, self.kW}) local str = torch.IntTensor({self.dH, self.dW}) local pad = torch.IntTensor({self.padH, self.padW}) errcheck('cudnnSetPoolingNdDescriptor', self.poolDesc[0], self.mode, 2, ker:data(), pad:data(), str:data()); local function destroyPoolDesc(d) errcheck('cudnnDestroyPoolingDescriptor', d[0]); end ffi.gc(self.poolDesc, destroyPoolDesc) end function Pooling:createIODescriptors(input) assert(self.mode, 'mode is not set. (trying to use base class?)'); local batch = true if input:dim() == 3 then input = input:view(1, input:size(1), input:size(2), input:size(3)) batch = false end assert(input:dim() == 4 and input:isContiguous()); if not self.iDesc or not self.oDesc or input:size(1) ~= self.iSize[1] or input:size(2) ~= self.iSize[2] or input:size(3) ~= self.iSize[3] or input:size(4) ~= self.iSize[4] then self.iSize = input:size() -- resize gradInput self.gradInput:resizeAs(input) -- resize output local oW, oH if self.ceil_mode then oW = math.ceil((input:size(4) - self.kW)/self.dW + 1) oH = math.ceil((input:size(3) - self.kH)/self.dH + 1) else oW = math.floor((input:size(4) - self.kW)/self.dW + 1) oH = math.floor((input:size(3) - self.kH)/self.dH + 1) end self.output:resize(input:size(1), input:size(2), oH, oW) -- create input/output descriptor self.iDesc = cudnn.toDescriptor(input) self.oDesc = cudnn.toDescriptor(self.output) if not batch then self.gradInput = self.gradInput:view(self.gradInput:size(2), self.gradInput:size(3), self.gradInput:size(4)) self.output = self.output:view(self.output:size(2), self.output:size(3), self.output:size(4)) end end end local one = torch.FloatTensor({1}); local zero = torch.FloatTensor({0}); function Pooling:updateOutput(input) if not self.poolDesc then self:resetPoolDescriptors() end self:createIODescriptors(input) errcheck('cudnnPoolingForward', cudnn.handle[cutorch.getDevice()-1], self.poolDesc[0], one:data(), self.iDesc[0], input:data(), zero:data(), self.oDesc[0], self.output:data()); return self.output end function Pooling:updateGradInput(input, gradOutput) assert(gradOutput:dim() == 3 or gradOutput:dim() == 4); if not gradOutput:isContiguous() then self._gradOutput = self._gradOutput or gradOutput.new():resizeAs(gradOutput) self._gradOutput:copy(gradOutput) gradOutput = self._gradOutput end if not self.poolDesc then self:resetPoolDescriptors() end self:createIODescriptors(input) errcheck('cudnnPoolingBackward', cudnn.handle[cutorch.getDevice()-1], self.poolDesc[0], one:data(), self.oDesc[0], self.output:data(), self.oDesc[0], gradOutput:data(), self.iDesc[0], input:data(), zero:data(), self.iDesc[0], self.gradInput:data()); return self.gradInput end
local Pooling, parent = torch.class('cudnn._Pooling', 'nn.Module') local ffi = require 'ffi' local errcheck = cudnn.errcheck function Pooling:__init(kW, kH, dW, dH, padW, padH) parent.__init(self) self.kW = kW self.kH = kH self.dW = dW or kW self.dH = dH or kW self.padW = padW or 0 self.padH = padH or 0 self.iSize = torch.LongStorage(4):fill(0) self.ceil_mode = false end function Pooling:ceil() self.ceil_mode = true return self end function Pooling:floor() self.ceil_mode = false return self end function Pooling:resetPoolDescriptors() -- create pooling descriptor self.padW = self.padW or 0 self.padH = self.padH or 0 self.poolDesc = ffi.new('struct cudnnPoolingStruct*[1]') errcheck('cudnnCreatePoolingDescriptor', self.poolDesc) local ker = torch.IntTensor({self.kH, self.kW}) local str = torch.IntTensor({self.dH, self.dW}) local pad = torch.IntTensor({self.padH, self.padW}) errcheck('cudnnSetPoolingNdDescriptor', self.poolDesc[0], self.mode, 2, ker:data(), pad:data(), str:data()); local function destroyPoolDesc(d) errcheck('cudnnDestroyPoolingDescriptor', d[0]); end ffi.gc(self.poolDesc, destroyPoolDesc) end function Pooling:createIODescriptors(input) assert(self.mode, 'mode is not set. (trying to use base class?)'); local batch = true if input:dim() == 3 then input = input:view(1, input:size(1), input:size(2), input:size(3)) batch = false end assert(input:dim() == 4 and input:isContiguous()); if not self.iDesc or not self.oDesc or input:size(1) ~= self.iSize[1] or input:size(2) ~= self.iSize[2] or input:size(3) ~= self.iSize[3] or input:size(4) ~= self.iSize[4] then self.iSize = input:size() -- resize gradInput self.gradInput:resizeAs(input) -- resize output local oW, oH if self.ceil_mode then oW = math.ceil((input:size(4) - self.kW)/self.dW + 1) oH = math.ceil((input:size(3) - self.kH)/self.dH + 1) else oW = math.floor((input:size(4) - self.kW)/self.dW + 1) oH = math.floor((input:size(3) - self.kH)/self.dH + 1) end self.output:resize(input:size(1), input:size(2), oH, oW) -- create input/output descriptor self.iDesc = cudnn.toDescriptor(input) self.oDesc = cudnn.toDescriptor(self.output) if not batch then self.gradInput = self.gradInput:view(self.gradInput:size(2), self.gradInput:size(3), self.gradInput:size(4)) self.output = self.output:view(self.output:size(2), self.output:size(3), self.output:size(4)) end end end local one = torch.FloatTensor({1}); local zero = torch.FloatTensor({0}); function Pooling:updateOutput(input) if not self.poolDesc then self:resetPoolDescriptors() end self:createIODescriptors(input) errcheck('cudnnPoolingForward', cudnn.handle[cutorch.getDevice()-1], self.poolDesc[0], one:data(), self.iDesc[0], input:data(), zero:data(), self.oDesc[0], self.output:data()); return self.output end function Pooling:updateGradInput(input, gradOutput) assert(gradOutput:dim() == 3 or gradOutput:dim() == 4); if not gradOutput:isContiguous() then self._gradOutput = self._gradOutput or gradOutput.new():resizeAs(gradOutput) self._gradOutput:copy(gradOutput) gradOutput = self._gradOutput end if not self.poolDesc then self:resetPoolDescriptors() end self:createIODescriptors(input) errcheck('cudnnPoolingBackward', cudnn.handle[cutorch.getDevice()-1], self.poolDesc[0], one:data(), self.oDesc[0], self.output:data(), self.oDesc[0], gradOutput:data(), self.iDesc[0], input:data(), zero:data(), self.iDesc[0], self.gradInput:data()); return self.gradInput end
fixes segfault in Pooling (no padW and padH in v1)
fixes segfault in Pooling (no padW and padH in v1)
Lua
bsd-3-clause
phunghx/phnn.torch,phunghx/phnn.torch,phunghx/phnn.torch
a0b8b710f6b502071d80b1626d344981b70f0ba2
xmake/modules/private/tools/cl/parse_deps_json.lua
xmake/modules/private/tools/cl/parse_deps_json.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 parse_deps_json.lua -- -- imports import("core.project.project") import("core.base.hashset") import("core.base.json") -- parse depsfiles from string function main(depsdata) -- decode json data first depsdata = json.decode(depsdata) -- get includes local includes if depsdata and depsdata.Data then includes = depsdata.Data.Includes end -- translate it local results = hashset.new() for _, includefile in ipairs(includes) do -- get the relative includefile = path.relative(includefile, project.directory()) includefile = path.absolute(includefile) -- save it if belong to the project if includefile:startswith(os.projectdir()) then -- insert it and filter repeat includefile = path.relative(includefile, project.directory()) results:insert(includefile) end end return results:to_array() 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 parse_deps_json.lua -- -- imports import("core.project.project") import("core.base.hashset") import("core.base.json") -- parse depsfiles from string function main(depsdata) -- decode json data first depsdata = json.decode(depsdata) -- get includes local includes if depsdata and depsdata.Data then includes = depsdata.Data.Includes end -- translate it local results = hashset.new() local projectdir = os.projectdir():lower() -- we need generate lower string, because json values are all lower for _, includefile in ipairs(includes) do -- get the absolute path if not path.is_absolute(includefile) then includefile = path.absolute(includefile, projectdir):lower() end -- save it if belong to the project if includefile:startswith(projectdir) then -- insert it and filter repeat includefile = path.relative(includefile, projectdir) results:insert(includefile) end end return results:to_array() end
fix parse_deps_json
fix parse_deps_json
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
fd822574f9bbf40e2cc38b9042299d5e595d8463
applications/luci-ddns/luasrc/model/cbi/ddns/ddns.lua
applications/luci-ddns/luasrc/model/cbi/ddns/ddns.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Copyright 2008 Jo-Philipp Wich <[email protected]> Copyright 2013 Manuel Munz <freifunk at somakoma dot de> 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 ]]-- require("luci.tools.webadmin") m = Map("ddns", translate("Dynamic DNS"), translate("Dynamic DNS allows that your router can be reached with " .. "a fixed hostname while having a dynamically changing " .. "IP address.")) s = m:section(TypedSection, "service", "") s.addremove = true s.anonymous = false s:option(Flag, "enabled", translate("Enable")) svc = s:option(ListValue, "service_name", translate("Service")) svc.rmempty = false svc.default = "dyndns.org" local services = { } local fd = io.open("/usr/lib/ddns/services", "r") if fd then local ln repeat ln = fd:read("*l") local s = ln and ln:match('^%s*"([^"]+)"') if s then services[#services+1] = s end until not ln fd:close() end local v for _, v in luci.util.vspairs(services) do svc:value(v) end function svc.cfgvalue(...) local v = Value.cfgvalue(...) if not v or #v == 0 then return "-" else return v end end function svc.write(self, section, value) if value == "-" then m.uci:delete("ddns", section, self.option) else Value.write(self, section, value) end end svc:value("-", "-- "..translate("custom").." --") local url = s:option(Value, "update_url", translate("Custom update-URL")) url:depends("service_name", "-") url.rmempty = true local hostname = s:option(Value, "domain", translate("Hostname")) hostname.rmempty = true hostname.default = "mypersonaldomain.dyndns.org" hostname.datatype = "host" local username = s:option(Value, "username", translate("Username")) username.rmempty = true local pw = s:option(Value, "password", translate("Password")) pw.rmempty = true pw.password = true require("luci.tools.webadmin") local src = s:option(ListValue, "ip_source", translate("Source of IP address")) src.default = "network" src:value("network", translate("network")) src:value("interface", translate("interface")) src:value("web", translate("URL")) local iface = s:option(ListValue, "ip_network", translate("Network")) iface:depends("ip_source", "network") iface.rmempty = true iface.default = "wan" luci.tools.webadmin.cbi_add_networks(iface) iface = s:option(ListValue, "ip_interface", translate("Interface")) iface:depends("ip_source", "interface") iface.rmempty = true for k, v in pairs(luci.sys.net.devices()) do iface:value(v) end local web = s:option(Value, "ip_url", translate("URL")) web:depends("ip_source", "web") web.default = "http://checkip.dyndns.com/" web.rmempty = true local ci = s:option(Value, "check_interval", translate("Check for changed IP every")) ci.datatype = "and(uinteger,min(1))" ci.default = 10 local unit = s:option(ListValue, "check_unit", translate("Check-time unit")) unit.default = "minutes" unit:value("minutes", translate("min")) unit:value("hours", translate("h")) fi = s:option(Value, "force_interval", translate("Force update every")) fi.datatype = "and(uinteger,min(1))" fi.default = 72 local unit = s:option(ListValue, "force_unit", translate("Force-time unit")) unit.default = "hours" unit:value("minutes", translate("min")) unit:value("hours", translate("h")) return m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Copyright 2008 Jo-Philipp Wich <[email protected]> Copyright 2013 Manuel Munz <freifunk at somakoma dot de> 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 ]]-- require("luci.tools.webadmin") m = Map("ddns", translate("Dynamic DNS"), translate("Dynamic DNS allows that your router can be reached with " .. "a fixed hostname while having a dynamically changing " .. "IP address.")) s = m:section(TypedSection, "service", "") s.addremove = true s.anonymous = false s:option(Flag, "enabled", translate("Enable")) interface = s:option(ListValue, "interface", translate("Event interface"), translate("Network on which the ddns-updater scripts will be started")) luci.tools.webadmin.cbi_add_networks(interface) interface.default = "wan" svc = s:option(ListValue, "service_name", translate("Service")) svc.rmempty = false svc.default = "dyndns.org" local services = { } local fd = io.open("/usr/lib/ddns/services", "r") if fd then local ln repeat ln = fd:read("*l") local s = ln and ln:match('^%s*"([^"]+)"') if s then services[#services+1] = s end until not ln fd:close() end local v for _, v in luci.util.vspairs(services) do svc:value(v) end function svc.cfgvalue(...) local v = Value.cfgvalue(...) if not v or #v == 0 then return "-" else return v end end function svc.write(self, section, value) if value == "-" then m.uci:delete("ddns", section, self.option) else Value.write(self, section, value) end end svc:value("-", "-- "..translate("custom").." --") local url = s:option(Value, "update_url", translate("Custom update-URL")) url:depends("service_name", "-") url.rmempty = true local hostname = s:option(Value, "domain", translate("Hostname")) hostname.rmempty = true hostname.default = "mypersonaldomain.dyndns.org" hostname.datatype = "host" local username = s:option(Value, "username", translate("Username")) username.rmempty = true local pw = s:option(Value, "password", translate("Password")) pw.rmempty = true pw.password = true require("luci.tools.webadmin") local src = s:option(ListValue, "ip_source", translate("Source of IP address")) src.default = "network" src:value("network", translate("network")) src:value("interface", translate("interface")) src:value("web", translate("URL")) local iface = s:option(ListValue, "ip_network", translate("Network")) iface:depends("ip_source", "network") iface.rmempty = true iface.default = "wan" luci.tools.webadmin.cbi_add_networks(iface) iface = s:option(ListValue, "ip_interface", translate("Interface")) iface:depends("ip_source", "interface") iface.rmempty = true for k, v in pairs(luci.sys.net.devices()) do iface:value(v) end local web = s:option(Value, "ip_url", translate("URL")) web:depends("ip_source", "web") web.default = "http://checkip.dyndns.com/" web.rmempty = true local ci = s:option(Value, "check_interval", translate("Check for changed IP every")) ci.datatype = "and(uinteger,min(1))" ci.default = 10 local unit = s:option(ListValue, "check_unit", translate("Check-time unit")) unit.default = "minutes" unit:value("minutes", translate("min")) unit:value("hours", translate("h")) fi = s:option(Value, "force_interval", translate("Force update every")) fi.datatype = "and(uinteger,min(1))" fi.default = 72 local unit = s:option(ListValue, "force_unit", translate("Force-time unit")) unit.default = "hours" unit:value("minutes", translate("min")) unit:value("hours", translate("h")) return m
[for-0.12] luci-app-ddns: fix OpenWrt Ticket #18018 in BB release
[for-0.12] luci-app-ddns: fix OpenWrt Ticket #18018 in BB release fix for OpenWrt Ticket #18018 in BB 14.07 release. Without fix the application writes a config without event interface which causes ddns-scripts to NEVER start. Signed-off-by: Christian Schoenebeck <[email protected]>
Lua
apache-2.0
keyidadi/luci,keyidadi/luci,opentechinstitute/luci,dismantl/luci-0.12,keyidadi/luci,opentechinstitute/luci,opentechinstitute/luci,dismantl/luci-0.12,opentechinstitute/luci,dismantl/luci-0.12,dismantl/luci-0.12,keyidadi/luci,keyidadi/luci,opentechinstitute/luci,opentechinstitute/luci,opentechinstitute/luci,keyidadi/luci,keyidadi/luci,dismantl/luci-0.12,opentechinstitute/luci,dismantl/luci-0.12,dismantl/luci-0.12,keyidadi/luci
23de2b6e05f53dc61ff7ad2101f0cf851f365369
nvim/init.lua
nvim/init.lua
local options = { number = true, relativenumber = true, hidden = true, inccommand = 'nosplit', hlsearch = false, ignorecase = true, mouse = 'a', breakindent = true, wrap = false, updatetime = 250, ttimeout = true, ttimeoutlen = 50 , signcolumn = 'yes', cursorline = true , colorcolumn = '81' , splitbelow = true , splitright = true , showtabline = 0, clipboard = "unnamedplus", completeopt = { "menuone", "noselect" }, shortmess = vim.opt.shortmess + 'c', undofile = true, -- Save undo history writebackup = false, -- if a file is being edited by another program (or was written to file while editing with another program), it is not allowed to be edited swapfile = false, -- creates a swapfile backup = false, -- creates a backup file scrolloff = 8, sidescrolloff = 8, expandtab = true, shiftwidth = 2, tabstop = 2, softtabstop = 2, smartcase = true, -- smartindent = true, termguicolors = true, grepprg = "rg --vimgrep --smart-case", } for k, v in pairs(options) do vim.opt[k] = v end -- `:Cfilter pattern` to filter entires in copen -- more ideas https://gosukiwi.github.io/vim/2022/04/19/vim-advanced-search-and-replace.html vim.cmd [[packadd! cfilter]] require("keybindings") require("plugins") vim.cmd('source $HOME/.config/nvim/funks.vim') require("statusline") require("funks") SetTheme() -- Highlight on yank (copy). It will do a nice highlight blink of the thing you just copied. require("utils").create_augroup({ {'TextYankPost', '*', 'silent! lua vim.highlight.on_yank()'} }, 'YankHighlight') vim.cmd [[ augroup Markdown autocmd! autocmd FileType markdown set wrap linebreak textwidth=80 augroup END ]]
local options = { number = true, relativenumber = true, hidden = true, inccommand = 'nosplit', hlsearch = false, ignorecase = true, mouse = 'a', breakindent = true, wrap = false, updatetime = 250, ttimeout = true, ttimeoutlen = 50 , signcolumn = 'yes', cursorline = true , colorcolumn = '81' , splitbelow = true , splitright = true , showtabline = 0, clipboard = "unnamedplus", completeopt = { "menuone", "noselect" }, shortmess = vim.opt.shortmess + 'c', undofile = true, -- Save undo history writebackup = false, -- if a file is being edited by another program (or was written to file while editing with another program), it is not allowed to be edited swapfile = false, -- creates a swapfile backup = false, -- creates a backup file scrolloff = 8, sidescrolloff = 8, expandtab = true, shiftwidth = 2, tabstop = 2, softtabstop = 2, smartcase = true, -- smartindent = true, termguicolors = true, grepprg = "rg --vimgrep --smart-case", } for k, v in pairs(options) do vim.opt[k] = v end -- `:Cfilter pattern` to filter entires in copen -- more ideas https://gosukiwi.github.io/vim/2022/04/19/vim-advanced-search-and-replace.html vim.cmd [[packadd! cfilter]] require("keybindings") require("plugins") vim.cmd('source $HOME/.config/nvim/funks.vim') require("statusline") require("funks") SetTheme() -- Highlight on yank (copy). It will do a nice highlight blink of the thing you just copied. require("utils").create_augroup({ {'TextYankPost', '*', 'silent! lua vim.highlight.on_yank()'} }, 'YankHighlight') vim.cmd [[ augroup Markdown autocmd! autocmd FileType markdown set wrap linebreak textwidth=80 augroup END ]] vim.cmd [[ " Terminal Function let g:term_buf = 0 let g:term_win = 0 function! TermToggle(height) if win_gotoid(g:term_win) hide else botright new exec "resize " . a:height try exec "buffer " . g:term_buf catch call termopen($SHELL, {"detach": 0}) let g:term_buf = bufnr("") set nonumber set norelativenumber set signcolumn=no endtry startinsert! let g:term_win = win_getid() endif endfunction " Toggle terminal on/off (neovim) nnoremap <C-t> :call TermToggle(12)<CR> inoremap <C-t> <Esc>:call TermToggle(12)<CR> tnoremap <C-t> <C-\><C-n>:call TermToggle(12)<CR> " Terminal go back to normal mode tnoremap <Esc> <C-\><C-n> tnoremap :qq <C-\><C-n>:q!<CR> ]]
Add terminal toggle function and maps
Add terminal toggle function and maps Thanks: https://www.reddit.com/r/vim/comments/8n5bzs/using_neovim_is_there_a_way_to_display_a_terminal/dzt3fix/?utm_source=reddit&utm_medium=web2x&context=3
Lua
mit
aasare/aaku
2bd9035b8bb1e37abc2875acd062cb822fe2da14
hid-discoveryd-enum.nse
hid-discoveryd-enum.nse
local comm = require "comm" local nmap = require "nmap" local shortport = require "shortport" local stdnse = require "stdnse" local string = require "string" local table = require "table" description = [[ Attempts to identify HID Door Controllers. ]] author = "Mike Kelly (@lixmk)" license = "Same as Nmap--See https://nmap.org/book/man-legal.html" categories = {"discovery", "safe"} --- -- @usage -- nmap -sU -p 4070 --script=hid-discoveryd-enum -- -- @output -- PORT STATE SERVICE -- 4070/udp open|filtered unknown -- | hid-discoveryd-enum: -- | Response: discovered -- | MAC Address: 00:06:8E:FF:FF:FF -- | Host Name: EdgeEH400-001 -- | Internal IP: 10.0.0.1 -- | Device Type: EH400 -- | Firmware Version: 3.5.1.1483 -- |_ Build Date: 07/02/2015 -- MAC Address: 00:06:8E:FF:FF:FF (HID) --- portrule = shortport.portnumber(4070, "udp") action = function(host, port) local socket = nmap.new_socket() local status, err = socket:connect(host, port) local status, err = socket:send('discover;013;') local status, data = socket:receive() local fld = stdnse.strsplit(";", data) local output = {} table.insert(output, stdnse.strjoin(" ", {"Response:", fld[1]})) table.insert(output, stdnse.strjoin(" ", {"MAC Address:", fld[3]})) table.insert(output, stdnse.strjoin(" ", {"Host Name:", fld[4]})) table.insert(output, stdnse.strjoin(" ", {"Internal IP:", fld[5]})) table.insert(output, stdnse.strjoin(" ", {"Device Type:", fld[7]})) table.insert(output, stdnse.strjoin(" ", {"Firmware Version:", fld[8]})) table.insert(output, stdnse.strjoin(" ", {"Build Date:", fld[9]})) return stdnse.format_output(true, output) end
local comm = require "comm" local nmap = require "nmap" local shortport = require "shortport" local stdnse = require "stdnse" local string = require "string" local table = require "table" description = [[ Used the discoveryd service on upd port 4070 to enumerate information from HID Door Controllers. ]] author = "Mike Kelly (@lixmk)" license = "Same as Nmap--See https://nmap.org/book/man-legal.html" categories = {"discovery", "safe"} --- -- @usage -- nmap -sU -p 4070 --script=hid-discoveryd-enum -- -- @output -- PORT STATE SERVICE -- 4070/udp open|filtered unknown -- | hid-discoveryd-enum: -- | Response: discovered -- | MAC Address: 00:06:8E:FF:FF:FF -- | Host Name: EdgeEH400-001 -- | Internal IP: 10.0.0.1 -- | Device Type: EH400 -- | Firmware Version: 3.5.1.1483 -- |_ Build Date: 07/02/2015 -- MAC Address: 00:06:8E:FF:FF:FF (HID) --- portrule = shortport.portnumber(4070, "udp") action = function(host, port) local socket = nmap.new_socket() local status, err = socket:connect(host, port) local status, err = socket:send('discover;013;') local status, data = socket:receive() local fld = stdnse.strsplit(";", data) local output = {} table.insert(output, stdnse.strjoin(" ", {"Response:", fld[1]})) table.insert(output, stdnse.strjoin(" ", {"MAC Address:", fld[3]})) table.insert(output, stdnse.strjoin(" ", {"Host Name:", fld[4]})) table.insert(output, stdnse.strjoin(" ", {"Internal IP:", fld[5]})) table.insert(output, stdnse.strjoin(" ", {"Device Type:", fld[7]})) table.insert(output, stdnse.strjoin(" ", {"Firmware Version:", fld[8]})) table.insert(output, stdnse.strjoin(" ", {"Build Date:", fld[9]})) if stdnse.contains(output, "Response: discovered") then return stdnse.format_output(true, output) end end
Fixed output error for non-HID systems
Fixed output error for non-HID systems
Lua
mit
lixmk/Concierge
0e1d31ad6f5663d4f56bd02ecb01b58fe6f162e1
mpris-widget/init.lua
mpris-widget/init.lua
------------------------------------------------- -- mpris based Arc Widget for Awesome Window Manager -- Modelled after Pavel Makhov's work -- @author Mohammed Gaber -- requires - playerctl -- @copyright 2020 ------------------------------------------------- local awful = require("awful") local beautiful = require("beautiful") local spawn = require("awful.spawn") local watch = require("awful.widget.watch") local wibox = require("wibox") local naughty = require("naughty") local GET_MPD_CMD = "playerctl -f '{{lc(status)}};{{xesam:artist}};{{xesam:title}}' metadata" local TOGGLE_MPD_CMD = "playerctl play-pause" local PAUSE_MPD_CMD = "playerctl pause" local STOP_MPD_CMD = "playerctl stop" local NEXT_MPD_CMD = "playerctl next" local PREV_MPD_CMD = "playerctl prev" local PATH_TO_ICONS = "/usr/share/icons/Arc" local PAUSE_ICON_NAME = PATH_TO_ICONS .. "/actions/24/player_pause.png" local PLAY_ICON_NAME = PATH_TO_ICONS .. "/actions/24/player_play.png" local STOP_ICON_NAME = PATH_TO_ICONS .. "/actions/24/player_stop.png" local LIBRARY_ICON_NAME = PATH_TO_ICONS .. "/actions/24/music-library.png" -- retriving song info current_song, artist = nil, nil local icon = wibox.widget { id = "icon", widget = wibox.widget.imagebox, image = PLAY_ICON_NAME } local mirrored_icon = wibox.container.mirror(icon, {horizontal = true}) local mpdarc = wibox.widget { mirrored_icon, -- max_value = 1, -- value = 0, thickness = 2, start_angle = 4.71238898, -- 2pi*3/4 forced_height = 24, forced_width = 24, rounded_edge = true, bg = "#ffffff11", paddings = 0, widget = wibox.container.arcchart } local mpdarc_icon_widget = wibox.container.mirror(mpdarc, {horizontal = true}) local mpdarc_current_song_widget = wibox.widget { id = 'current_song', widget = wibox.widget.textbox, font = 'Play 10' } local update_graphic = function(widget, stdout, _, _, _) mpdstatus, artist, current_song = stdout:match("(%w+)%;+(.-)%;(.*)") if current_song ~= nil then if current_song.len == 18 then current_song = string.sub(current_song, 0, 9) .. ".." end end if mpdstatus == "playing" then icon.image = PLAY_ICON_NAME widget.colors = {beautiful.widget_main_color} mpdarc_current_song_widget.markup = current_song elseif mpdstatus == "paused" then icon.image = PAUSE_ICON_NAME widget.colors = {beautiful.widget_main_color} mpdarc_current_song_widget.markup = current_song elseif mpdstatus == "stopped" then icon.image = STOP_ICON_NAME mpdarc_current_song_widget.markup = "" else -- no player is running icon.image = LIBRARY_ICON_NAME mpdarc_current_song_widget.markup = "" widget.colors = {beautiful.widget_red} end end mpdarc:connect_signal("button::press", function(_, _, _, button) if (button == 1) then awful.spawn(TOGGLE_MPD_CMD, false) -- left click elseif (button == 2) then awful.spawn(STOP_MPD_CMD, false) elseif (button == 3) then awful.spawn(PAUSE_MPD_CMD, false) elseif (button == 4) then awful.spawn(NEXT_MPD_CMD, false) -- scroll up elseif (button == 5) then awful.spawn(PREV_MPD_CMD, false) -- scroll down end spawn.easy_async(GET_MPD_CMD, function(stdout, stderr, exitreason, exitcode) update_graphic(mpdarc, stdout, stderr, exitreason, exitcode) end) end) local notification function show_MPD_status() spawn.easy_async(GET_MPD_CMD, function(stdout, _, _, _) notification = naughty.notify { text = current_song .. " by " .. artist, title = "Now Playing", timeout = 5, hover_timeout = 0.5, width = 600 } end) end mpdarc:connect_signal("mouse::enter", function() if current_song ~= nil and artist ~= nil then show_MPD_status() end end) mpdarc:connect_signal("mouse::leave", function() naughty.destroy(notification) end) watch(GET_MPD_CMD, 1, update_graphic, mpdarc) local mpdarc_widget = wibox.widget { mpdarc_icon_widget, mpdarc_current_song_widget, layout = wibox.layout.align.horizontal } return mpdarc_widget
------------------------------------------------- -- mpris based Arc Widget for Awesome Window Manager -- Modelled after Pavel Makhov's work -- @author Mohammed Gaber -- requires - playerctl -- @copyright 2020 ------------------------------------------------- local awful = require("awful") local beautiful = require("beautiful") local spawn = require("awful.spawn") local watch = require("awful.widget.watch") local wibox = require("wibox") local naughty = require("naughty") local GET_MPD_CMD = "playerctl -f '{{status}};{{xesam:artist}};{{xesam:title}}' metadata" local TOGGLE_MPD_CMD = "playerctl play-pause" local PAUSE_MPD_CMD = "playerctl pause" local STOP_MPD_CMD = "playerctl stop" local NEXT_MPD_CMD = "playerctl next" local PREV_MPD_CMD = "playerctl prev" local PATH_TO_ICONS = "/usr/share/icons/Arc" local PAUSE_ICON_NAME = PATH_TO_ICONS .. "/actions/24/player_pause.png" local PLAY_ICON_NAME = PATH_TO_ICONS .. "/actions/24/player_play.png" local STOP_ICON_NAME = PATH_TO_ICONS .. "/actions/24/player_stop.png" local LIBRARY_ICON_NAME = PATH_TO_ICONS .. "/actions/24/music-library.png" -- retriving song info current_song, artist = nil, nil local icon = wibox.widget { id = "icon", widget = wibox.widget.imagebox, image = PLAY_ICON_NAME } local mirrored_icon = wibox.container.mirror(icon, {horizontal = true}) local mpdarc = wibox.widget { mirrored_icon, -- max_value = 1, -- value = 0, thickness = 2, start_angle = 4.71238898, -- 2pi*3/4 forced_height = 24, forced_width = 24, rounded_edge = true, bg = "#ffffff11", paddings = 0, widget = wibox.container.arcchart } local mpdarc_icon_widget = wibox.container.mirror(mpdarc, {horizontal = true}) local mpdarc_current_song_widget = wibox.widget { id = 'current_song', widget = wibox.widget.textbox, font = 'Play 10' } local update_graphic = function(widget, stdout, _, _, _) mpdstatus, artist, current_song = stdout:match("(%w+)%;+(.-)%;(.*)") if current_song ~= nil then if current_song.len == 18 then current_song = string.sub(current_song, 0, 9) .. ".." end end if mpdstatus == "Playing" then mpdarc_icon_widget.visible = true icon.image = PLAY_ICON_NAME widget.colors = {beautiful.widget_main_color} mpdarc_current_song_widget.markup = current_song elseif mpdstatus == "Paused" then mpdarc_icon_widget.visible = true icon.image = PAUSE_ICON_NAME widget.colors = {beautiful.widget_main_color} mpdarc_current_song_widget.markup = current_song elseif mpdstatus == "Stopped" then mpdarc_icon_widget.visible = true icon.image = STOP_ICON_NAME mpdarc_current_song_widget.markup = "" else -- no player is running icon.image = LIBRARY_ICON_NAME mpdarc_icon_widget.visible = false mpdarc_current_song_widget.markup = "" widget.colors = {beautiful.widget_red} end end mpdarc:connect_signal("button::press", function(_, _, _, button) if (button == 1) then awful.spawn(TOGGLE_MPD_CMD, false) -- left click elseif (button == 2) then awful.spawn(STOP_MPD_CMD, false) elseif (button == 3) then awful.spawn(PAUSE_MPD_CMD, false) elseif (button == 4) then awful.spawn(NEXT_MPD_CMD, false) -- scroll up elseif (button == 5) then awful.spawn(PREV_MPD_CMD, false) -- scroll down end spawn.easy_async(GET_MPD_CMD, function(stdout, stderr, exitreason, exitcode) update_graphic(mpdarc, stdout, stderr, exitreason, exitcode) end) end) local notification function show_MPD_status() spawn.easy_async(GET_MPD_CMD, function(stdout, _, _, _) notification = naughty.notify { text = current_song .. " by " .. artist, title = mpdstatus, timeout = 5, hover_timeout = 0.5, width = 600 } end) end mpdarc:connect_signal("mouse::enter", function() if current_song ~= nil and artist ~= nil then show_MPD_status() end end) mpdarc:connect_signal("mouse::leave", function() naughty.destroy(notification) end) watch(GET_MPD_CMD, 1, update_graphic, mpdarc) local mpdarc_widget = wibox.widget { screen = 'primary', mpdarc_icon_widget, mpdarc_current_song_widget, layout = wibox.layout.align.horizontal } return mpdarc_widget
Fixed notify status - mpris widget
Fixed notify status - mpris widget
Lua
mit
streetturtle/awesome-wm-widgets,streetturtle/awesome-wm-widgets
02772caf01fd5c055edf64c7f26b2c06b379e9e3
src/loader/src/StaticLegacyLoader.lua
src/loader/src/StaticLegacyLoader.lua
--[=[ @private @class StaticLegacyLoader ]=] local loader = script.Parent local ScriptInfoUtils = require(script.Parent.ScriptInfoUtils) local LoaderUtils = require(script.Parent.LoaderUtils) local BounceTemplateUtils = require(script.Parent.BounceTemplateUtils) local StaticLegacyLoader = {} StaticLegacyLoader.ClassName = "StaticLegacyLoader" StaticLegacyLoader.__index = StaticLegacyLoader function StaticLegacyLoader.new() local self = setmetatable({ _packageLookups = {}; }, StaticLegacyLoader) return self end function StaticLegacyLoader:__call(value) return self:Require(value) end function StaticLegacyLoader:Lock() error("Cannot start loader while not running") end function StaticLegacyLoader:Require(root, value) if type(value) == "number" then return require(value) elseif type(value) == "string" then -- use very slow module recovery mechanism local module = self:_findModule(root, value) if module then self:_ensureFakeLoader(module) return require(module) else error("Error: Library '" .. tostring(value) .. "' does not exist.", 2) end elseif typeof(value) == "Instance" and value:IsA("ModuleScript") then return require(value) else error(("Error: module must be a string or ModuleScript, got '%s' for '%s'") :format(typeof(value), tostring(value))) end end function StaticLegacyLoader:_findModule(root, name) assert(typeof(root) == "Instance", "Bad root") assert(type(name) == "string", "Bad name") -- Implement the node_modules recursive find algorithm local packageRoot = self:_findPackageRoot(root) while packageRoot do -- Build lookup local highLevelLookup = self:_getOrCreateLookup(packageRoot) if highLevelLookup[name] then return highLevelLookup[name] end -- Ok, search our package dependencies local dependencies = packageRoot:FindFirstChild(ScriptInfoUtils.DEPENDENCY_FOLDER_NAME) if dependencies then for _, instance in pairs(dependencies:GetChildren()) do if instance:IsA("Folder") and instance.Name:sub(1, 1) == "@" then for _, child in pairs(instance:GetChildren()) do local lookup = self:_getPackageFolderLookup(child) if lookup[name] then return lookup[name] end end else local lookup = self:_getPackageFolderLookup(instance) if lookup[name] then return lookup[name] end end end end -- We failed to find anything... search up a level... packageRoot = self:_findPackageRoot(packageRoot) end return nil end function StaticLegacyLoader:GetLoader(moduleScript) assert(typeof(moduleScript) == "Instance", "Bad moduleScript") return setmetatable({}, { __call = function(_self, value) return self:Require(moduleScript, value) end; __index = function(_self, key) return self:Require(moduleScript, key) end; }) end function StaticLegacyLoader:_getPackageFolderLookup(instance) if instance:IsA("ObjectValue") then if instance.Value then return self:_getOrCreateLookup(instance.Value) else warn("[StaticLegacyLoader] - Bad link in packageFolder") return {} end elseif instance:IsA("Folder") or instance:IsA("Camera") then return self:_getOrCreateLookup(instance) elseif instance:IsA("ModuleScript") then return self:_getOrCreateLookup(instance) else warn(("Unknown instance %q (%s) in dependencyFolder - %q") :format(instance.Name, instance.ClassName, instance:GetFullName())) return {} end end function StaticLegacyLoader:_getOrCreateLookup(packageFolderOrModuleScript) assert(typeof(packageFolderOrModuleScript) == "Instance", "Bad packageFolderOrModuleScript") if self._packageLookups[packageFolderOrModuleScript] then return self._packageLookups[packageFolderOrModuleScript] end local lookup = {} self:_buildLookup(lookup, packageFolderOrModuleScript) self._packageLookups[packageFolderOrModuleScript] = lookup return lookup end function StaticLegacyLoader:_buildLookup(lookup, instance) if instance:IsA("Folder") or instance:IsA("Camera") then if instance.Name ~= ScriptInfoUtils.DEPENDENCY_FOLDER_NAME then for _, item in pairs(instance:GetChildren()) do self:_buildLookup(lookup, item) end end elseif instance:IsA("ModuleScript") then lookup[instance.Name] = instance end end function StaticLegacyLoader:_findPackageRoot(instance) assert(typeof(instance) == "Instance", "Bad instance") local current = instance.Parent while current and current ~= game do if LoaderUtils.isPackage(current) then return current else current = current.Parent end end return nil end function StaticLegacyLoader:_ensureFakeLoader(module) assert(typeof(module) == "Instance", "Bad module") local parent = module.Parent if not parent then warn("[StaticLegacyLoader] - No parent") return end -- NexusUnitTest -- luacheck: ignore -- selene: allow(undefined_variable) local shouldBeArchivable = Load and true or false -- Already have link local found = parent:FindFirstChild("loader") if found then if BounceTemplateUtils.isBounceTemplate(found) then found.Archivable = shouldBeArchivable end return end local link = BounceTemplateUtils.create(loader, "loader") link.Archivable = shouldBeArchivable link.Parent = parent end return StaticLegacyLoader
--[=[ @private @class StaticLegacyLoader ]=] local loader = script.Parent local ScriptInfoUtils = require(script.Parent.ScriptInfoUtils) local LoaderUtils = require(script.Parent.LoaderUtils) local BounceTemplateUtils = require(script.Parent.BounceTemplateUtils) local StaticLegacyLoader = {} StaticLegacyLoader.ClassName = "StaticLegacyLoader" StaticLegacyLoader.__index = StaticLegacyLoader function StaticLegacyLoader.new() local self = setmetatable({ _packageLookups = {}; }, StaticLegacyLoader) return self end function StaticLegacyLoader:__call(value) return self:Require(value) end function StaticLegacyLoader:Lock() error("Cannot start loader while not running") end function StaticLegacyLoader:Require(root, value) if type(value) == "number" then return require(value) elseif type(value) == "string" then -- use very slow module recovery mechanism local module = self:_findModule(root, value) if module then self:_ensureFakeLoader(module) return require(module) else error("Error: Library '" .. tostring(value) .. "' does not exist.", 2) end elseif typeof(value) == "Instance" and value:IsA("ModuleScript") then return require(value) else error(("Error: module must be a string or ModuleScript, got '%s' for '%s'") :format(typeof(value), tostring(value))) end end function StaticLegacyLoader:_findModule(root, name) assert(typeof(root) == "Instance", "Bad root") assert(type(name) == "string", "Bad name") -- Implement the node_modules recursive find algorithm local packageRoot = self:_findPackageRoot(root) while packageRoot do -- Build lookup local highLevelLookup = self:_getOrCreateLookup(packageRoot) if highLevelLookup[name] then return highLevelLookup[name] end -- Ok, search our package dependencies local dependencies = packageRoot:FindFirstChild(ScriptInfoUtils.DEPENDENCY_FOLDER_NAME) if dependencies then for _, instance in pairs(dependencies:GetChildren()) do if instance:IsA("Folder") and instance.Name:sub(1, 1) == "@" then for _, child in pairs(instance:GetChildren()) do local lookup = self:_getPackageFolderLookup(child) if lookup[name] then return lookup[name] end end else local lookup = self:_getPackageFolderLookup(instance) if lookup[name] then return lookup[name] end end end end -- We failed to find anything... search up a level... packageRoot = self:_findPackageRoot(packageRoot) end return nil end function StaticLegacyLoader:GetLoader(moduleScript) assert(typeof(moduleScript) == "Instance", "Bad moduleScript") return setmetatable({}, { __call = function(_self, value) return self:Require(moduleScript, value) end; __index = function(_self, key) return self:Require(moduleScript, key) end; }) end function StaticLegacyLoader:_getPackageFolderLookup(instance) if instance:IsA("ObjectValue") then if instance.Value then return self:_getOrCreateLookup(instance.Value) else warn("[StaticLegacyLoader] - Bad link in packageFolder") return {} end elseif instance:IsA("Folder") or instance:IsA("Camera") then return self:_getOrCreateLookup(instance) elseif instance:IsA("ModuleScript") then return self:_getOrCreateLookup(instance) else warn(("Unknown instance %q (%s) in dependencyFolder - %q") :format(instance.Name, instance.ClassName, instance:GetFullName())) return {} end end function StaticLegacyLoader:_getOrCreateLookup(packageFolderOrModuleScript) assert(typeof(packageFolderOrModuleScript) == "Instance", "Bad packageFolderOrModuleScript") if self._packageLookups[packageFolderOrModuleScript] then return self._packageLookups[packageFolderOrModuleScript] end local lookup = {} self:_buildLookup(lookup, packageFolderOrModuleScript) self._packageLookups[packageFolderOrModuleScript] = lookup return lookup end function StaticLegacyLoader:_buildLookup(lookup, instance) if instance:IsA("Folder") or instance:IsA("Camera") then if instance.Name ~= ScriptInfoUtils.DEPENDENCY_FOLDER_NAME then for _, item in pairs(instance:GetChildren()) do self:_buildLookup(lookup, item) end end elseif instance:IsA("ModuleScript") then lookup[instance.Name] = instance end end function StaticLegacyLoader:_findPackageRoot(instance) assert(typeof(instance) == "Instance", "Bad instance") local current = instance.Parent while current and current ~= game do if LoaderUtils.isPackage(current) then return current elseif self:_couldBePackageRootTopLevel(current) then return current else current = current.Parent end end return nil end function StaticLegacyLoader:_couldBePackageRootTopLevel(current) for _, instance in pairs(current:GetChildren()) do if instance:IsA("Folder") and instance.Name:sub(1, 1) == "@" then for _, item in pairs(instance:GetChildren()) do if LoaderUtils.isPackage(item) then return true end end end end return true end function StaticLegacyLoader:_ensureFakeLoader(module) assert(typeof(module) == "Instance", "Bad module") local parent = module.Parent if not parent then warn("[StaticLegacyLoader] - No parent") return end -- NexusUnitTest -- luacheck: ignore -- selene: allow(undefined_variable) local shouldBeArchivable = Load and true or false -- Already have link local found = parent:FindFirstChild("loader") if found then if BounceTemplateUtils.isBounceTemplate(found) then found.Archivable = shouldBeArchivable end return end local link = BounceTemplateUtils.create(loader, "loader") link.Archivable = shouldBeArchivable link.Parent = parent end return StaticLegacyLoader
fix: Fix hoarcekat stories not loading correctly when installed in a flat version of the repository (for example, via normal npm install @quenty/blend)
fix: Fix hoarcekat stories not loading correctly when installed in a flat version of the repository (for example, via normal npm install @quenty/blend)
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
c4702223a1ee3ccb59ef348fc4f7efeb8befa1c9
src/lua/sancus/template/generator.lua
src/lua/sancus/template/generator.lua
-- This file is part of sancus-lua-template -- <https://github.com/sancus-project/sancus-lua-template> -- -- Copyright (c) 2012, Alejandro Mery <[email protected]> -- local lpeg = assert(require"lpeg") local P,R,S,V = lpeg.P, lpeg.R, lpeg.S, lpeg.V local C,Cc,Cg,Ct,Cp = lpeg.C, lpeg.Cc, lpeg.Cg, lpeg.Ct, lpeg.Cp local assert, ipairs, pairs, type = assert, ipairs, pairs, type local setmetatable, loadstring = setmetatable, loadstring local tostring, tonumber, tconcat = tostring, tonumber, table.concat local _M = {} setfenv(1, _M) local function parser() local space, nl = S" \t", P"\n" + P"\r\n" local rest = (1 - nl)^0 local eol = (P(-1) + nl) local char = R"az" + R"AZ" local num = R"09" local dq = P'"' local be, ee = P"${", P"}" local bi, ei = P"<%", P"%>" local bc, ec = bi, P"/>" local attr = char * (char + num + P"_")^0 local value = (dq * C((1-dq)^0) * dq) + (num^1)/tonumber -- ${ ... } local expression = be * C((1 - nl - ee)^1) * ee expression = Ct(Cg(expression, "value") * Cg(Cc("expr"), "type")) -- <%command ... /> local command = space^1 * C(attr) * P"=" * value command = bc * Cg(attr, "value") * Cg(Cc("command"), "type") * (command^0) * space^0 * ec command = Ct(command) * (space^0 * eol)^-1 -- <% ... %> local inline = (1 - ei)^1 inline = bi * (C( (space * inline) + (nl * inline) )+(space + nl)^1) * ei inline = Ct(Cg(inline, "value") * Cg(Cc("inline"), "type")) -- [ \t]* %% comment local comment = space^0 * P"%%" * rest * eol -- [ \t]* % ... local code = space^0 * P"%" * C(rest) * eol code = Ct(Cg(code, "value") * Cg(Cc("code"), "type")) -- everything else local content = 1 - nl - be - bi content = content^1 * eol^-1 content = C(nl + content) local things = comment + code + content + expression + inline + command return Ct(things^1) * Cp() end parser = parser() local function find_line_col_by_pos(s, p) local nl = P"\n" + P"\r\n" local content = (1-nl)^1 local patt = (nl + (content * nl))*Cp() local t = Ct(patt^0):match(s) local line_no, from, to = 1, 0, nil for _, q in ipairs(t) do if q <= p then line_no = line_no + 1 from = q else to = q break end end local col = p - from local s1, s2 = s:sub(from, to), "" s1 = C(content):match(s1) if col > 0 then s2 = s1:sub(1,col):gsub("[^\t]", " ") .. "^" else s2 = "^" end return line_no, col+1, s1, s2 end local function parse(s) assert(type(s) == "string", "argument must be an string") if #s == 0 then return {} end local t, p = parser:match(s) if t and p == #s+1 then return t elseif p == nil then p = 1 end -- useful error message local line, col, s1, s2 = find_line_col_by_pos(s, p) local fmt = "sancus.template.parse: invalid element at (%s, %d):\n%s:%s\n%s%s" local prefix line = tostring(line) prefix = (" "):rep(#line+1) error(fmt:format(line, col, line, s1, prefix, s2)) end local function fold(t) local out, s = {}, {} local ptrim do -- trimming pattern local nl = P"\n" + P"\r\n" local space = S' \t' + nl local nospace = 1 - space ptrim = space^0 * C((space^0 * nospace^1)^0) end for _, x in ipairs(t) do if type(x) == "string" then s[#s+1] = x else if x.type == "command" then local args, key = {}, nil for _, v in ipairs(x) do if key then args[key] = v key = nil else key = v end end x = { type = "command", value = x.value, args = args } else x.value = ptrim:match(x.value) end if #x.value > 0 then if #s > 0 then out[#out+1] = tconcat(s) s = {} end out[#out+1] = x end end end if #s > 0 then out[#out+1] = tconcat(s) end return out end local function render(t) local out, v = {} out[#out+1] = "return function(_T,_C)" local function quote(s) -- TODO: replace with lpeg return s:gsub("\\","\\\\"):gsub("\"", '\\"'):gsub("\n", "\\n"):gsub("\t","\\t") end for _, x in ipairs(t) do if type(x) == "string" then -- %q is broken for \n and maybe others v = quote(x) v = ("_T:yield(\"%s\")"):format(v) elseif x.type == "expr" then v = ("_T:yield_expr(%s)"):format(x.value) elseif x.type == "command" then v = {} for k,val in pairs(x.args) do v[#v+1] = ("%s=%q"):format(k, val) end if #v > 0 then v = ("_T:%s(_C,{%s})"):format(x.value, tconcat(v, ',')) else v = ("_T:%s(_C)"):format(x.value) end else v = x.value end if v then out[#out+1] = v end end out[#out+1] = "end" return tconcat(out, '\n') end local function compile(s) return loadstring(s) end local function new(s) return compile(render(fold(parse(s)))) end setmetatable(_M, { __call = function(_, s) return new(s) end, }) return _M
-- This file is part of sancus-lua-template -- <https://github.com/sancus-project/sancus-lua-template> -- -- Copyright (c) 2012, Alejandro Mery <[email protected]> -- local lpeg = assert(require"lpeg") local P,R,S,V = lpeg.P, lpeg.R, lpeg.S, lpeg.V local C,Cc,Cg,Ct,Cp = lpeg.C, lpeg.Cc, lpeg.Cg, lpeg.Ct, lpeg.Cp local assert, error = assert, error local ipairs, pairs, type = ipairs, pairs, type local setmetatable, loadstring = setmetatable, loadstring local tostring, tonumber, tconcat = tostring, tonumber, table.concat local _M = {} setfenv(1, _M) local function parser() local space, nl = S" \t", P"\n" + P"\r\n" local rest = (1 - nl)^0 local eol = (P(-1) + nl) local char = R"az" + R"AZ" local num = R"09" local dq = P'"' local be, ee = P"${", P"}" local bi, ei = P"<%", P"%>" local bc, ec = bi, P"/>" local attr = char * (char + num + P"_")^0 local value = (dq * C((1-dq)^0) * dq) + (num^1)/tonumber -- ${ ... } local expression = be * C((1 - nl - ee)^1) * ee expression = Ct(Cg(expression, "value") * Cg(Cc("expr"), "type")) -- <%command ... /> local command = space^1 * C(attr) * P"=" * value command = bc * Cg(attr, "value") * Cg(Cc("command"), "type") * (command^0) * space^0 * ec command = Ct(command) * (space^0 * eol)^-1 -- <% ... %> local inline = (1 - ei)^1 inline = bi * (C( (space * inline) + (nl * inline) )+(space + nl)^1) * ei inline = Ct(Cg(inline, "value") * Cg(Cc("inline"), "type")) -- [ \t]* %% comment local comment = space^0 * P"%%" * rest * eol -- [ \t]* % ... local code = space^0 * P"%" * C(rest) * eol code = Ct(Cg(code, "value") * Cg(Cc("code"), "type")) -- everything else local content = 1 - nl - be - bi content = content^1 * eol^-1 content = C(nl + content) local things = comment + code + content + expression + inline + command return Ct(things^1) * Cp() end parser = parser() local function find_line_col_by_pos(s, p) local nl = P"\n" + P"\r\n" local content = (1-nl)^1 local patt = (nl + (content * nl))*Cp() local t = Ct(patt^0):match(s) local line_no, from, to = 1, 0, nil for _, q in ipairs(t) do if q <= p then line_no = line_no + 1 from = q else to = q break end end local col = p - from local s1, s2 = s:sub(from, to), "" s1 = C(content):match(s1) if col > 0 then s2 = s1:sub(1,col):gsub("[^\t]", " ") .. "^" else s2 = "^" end return line_no, col+1, s1, s2 end local function parse(s) assert(type(s) == "string", "argument must be an string") if #s == 0 then return {} end local t, p = parser:match(s) if t and p == #s+1 then return t elseif p == nil then p = 1 end -- useful error message local line, col, s1, s2 = find_line_col_by_pos(s, p) local fmt = "sancus.template.parse: invalid element at (%s, %d):\n%s:%s\n%s%s" local prefix line = tostring(line) prefix = (" "):rep(#line+1) error(fmt:format(line, col, line, s1, prefix, s2)) end local function fold(t) local out, s = {}, {} local ptrim do -- trimming pattern local nl = P"\n" + P"\r\n" local space = S' \t' + nl local nospace = 1 - space ptrim = space^0 * C((space^0 * nospace^1)^0) end for _, x in ipairs(t) do if type(x) == "string" then s[#s+1] = x else if x.type == "command" then local args, key = {}, nil for _, v in ipairs(x) do if key then args[key] = v key = nil else key = v end end x = { type = "command", value = x.value, args = args } else x.value = ptrim:match(x.value) end if #x.value > 0 then if #s > 0 then out[#out+1] = tconcat(s) s = {} end out[#out+1] = x end end end if #s > 0 then out[#out+1] = tconcat(s) end return out end local function render(t) local out, v = {} out[#out+1] = "return function(_T,_C)" local function quote(s) -- TODO: replace with lpeg return s:gsub("\\","\\\\"):gsub("\"", '\\"'):gsub("\n", "\\n"):gsub("\t","\\t") end for _, x in ipairs(t) do if type(x) == "string" then -- %q is broken for \n and maybe others v = quote(x) v = ("_T:yield(\"%s\")"):format(v) elseif x.type == "expr" then v = ("_T:yield_expr(%s)"):format(x.value) elseif x.type == "command" then v = {} for k,val in pairs(x.args) do v[#v+1] = ("%s=%q"):format(k, val) end if #v > 0 then v = ("_T:%s(_C,{%s})"):format(x.value, tconcat(v, ',')) else v = ("_T:%s(_C)"):format(x.value) end else v = x.value end if v then out[#out+1] = v end end out[#out+1] = "end" return tconcat(out, '\n') end local function compile(s) return loadstring(s) end local function new(s) return compile(render(fold(parse(s)))) end setmetatable(_M, { __call = function(_, s) return new(s) end, }) return _M
template.generator: fix missing `error`
template.generator: fix missing `error`
Lua
bsd-2-clause
sancus-project/sancus-lua-template
6bc83a14294e8a30881c1be1ee3588adbc221c6a
control.lua
control.lua
require 'util' require 'defines' function setup() global.hoverboard = global.hoverboard or {} global.charge = global.charge or 0 global.tick = 0 if global.hoverboard.status == nil then global.hoverboard.status = false end end script.on_init(setup) script.on_load(setup) function getTile() return game.player.surface.get_tile(game.player.position.x,game.player.position.y) end script.on_event(defines.events.on_tick, function(event) if global.tick == 0 then initializeGUI() global.tick = global.tick + 1 end hoverMode() end) script.on_event(defines.events.on_gui_click,function(event) if event.element.name == "mode" then if global.hoverboard.status == false then global.hoverboard.status = true updateGUI() elseif global.hoverboard.status == true then global.hoverboard.status = false updateGUI() end end end) function activeHoverMode() local orientation = game.player.walking_state.direction if global.charge > 0 then global.charge = global.charge - 1 game.player.walking_state = {walking = true, direction = orientation} end end function limitHoverboard() local tile = getTile() local count = 0 --http://www.factorioforums.com/forum/viewtopic.php?f=25&t=16571 local armor = game.player.get_inventory(defines.inventory.player_armor)[1] if armor.valid_for_read then if armor.has_grid then local equipment = armor.grid.equipment for i,e in pairs(equipment) do if e.name =="hoverboard" then if inboundTile(tile.name) == false then e.energy = 0 end if count > 0 then game.player.insert(armor.grid.take(e)) end count = count + 1 end end end end end function initializeGUI() if game.player.gui.top.hoverboard ~= nil then game.player.gui.top.hoverboard.destroy() end game.player.gui.top.add{type="frame", name="hoverboard"} game.player.gui.top.hoverboard.add{type="button",name="mode", caption = "Hoverboard Status: Inactive"} game.player.gui.top.hoverboard.add{type="label",name="charge"} global.hoverboard.status = false end function updateGUI() if global.hoverboard.status == true then game.player.gui.top.hoverboard.mode.caption = "Hoverboard Status: Active" elseif global.hoverboard.status == false then game.player.gui.top.hoverboard.mode.caption = "Hoverboard Status: Inactive" end end function updateStatusGUI() game.player.gui.top.hoverboard.charge.caption = "Charge: "..global.charge end function hoverMode() limitHoverboard() if global.hoverboard.status == true then activeHoverMode() tileCheck() updateStatusGUI() end end function inboundTile(name) local tiles = {"copper-floor", "copper-floor2", "copper-floor3","accelerator","down","left","up","right"} for _, tile in ipairs(tiles) do if tile == name then return true end end return false end function tileCheck() local tile = getTile() local walk = game.player.walking_state.walking if tile.name == "accelerator" then if global.charge <= 40 then global.charge = global.charge + 10 end elseif tile.name == "down" then game.player.walking_state = {walking = walk, direction = defines.direction.south} elseif tile.name == "up" then game.player.walking_state = {walking = walk, direction = defines.direction.north} elseif tile.name == "right" then game.player.walking_state = {walking = walk, direction = defines.direction.east} elseif tile.name == "left" then game.player.walking_state = {walking = walk, direction = defines.direction.west} elseif inboundTile(tile.name) == false then global.charge = 0 end end
require 'util' require 'defines' function setup() global.hoverboard = global.hoverboard or {} global.charge = global.charge or 0 global.tick = 0 if global.hoverboard.status == nil then global.hoverboard.status = false end global.dead = false end script.on_init(setup) script.on_load(setup) function getTile() return game.player.surface.get_tile(game.player.position.x,game.player.position.y) end script.on_event(defines.events.on_tick, function(event) if global.dead == false then if global.tick == 0 then initializeGUI() global.tick = global.tick + 1 end hoverMode() end end) script.on_event(defines.events.on_entity_died, function(event) if event.entity.name == "player" then global.dead = true end end) script.on_event(defines.events.on_gui_click,function(event) if event.element.name == "mode" then if global.hoverboard.status == false then global.hoverboard.status = true updateGUI() elseif global.hoverboard.status == true then global.hoverboard.status = false updateGUI() end end end) function activeHoverMode() local orientation = game.player.walking_state.direction if global.charge > 0 then global.charge = global.charge - 1 game.player.walking_state = {walking = true, direction = orientation} end end function limitHoverboard() local tile = getTile() local count = 0 --http://www.factorioforums.com/forum/viewtopic.php?f=25&t=16571 local armor = game.player.get_inventory(defines.inventory.player_armor)[1] if armor.valid_for_read then if armor.has_grid then local equipment = armor.grid.equipment for i,e in pairs(equipment) do if e.name =="hoverboard" then if inboundTile(tile.name) == false then e.energy = 0 end if count > 0 then game.player.insert(armor.grid.take(e)) end count = count + 1 end end end end end function initializeGUI() if game.player.gui.top.hoverboard ~= nil then game.player.gui.top.hoverboard.destroy() end game.player.gui.top.add{type="frame", name="hoverboard"} game.player.gui.top.hoverboard.add{type="button",name="mode", caption = "Hoverboard Status: Inactive"} game.player.gui.top.hoverboard.add{type="label",name="charge"} global.hoverboard.status = false end function updateGUI() if global.hoverboard.status == true then game.player.gui.top.hoverboard.mode.caption = "Hoverboard Status: Active" elseif global.hoverboard.status == false then game.player.gui.top.hoverboard.mode.caption = "Hoverboard Status: Inactive" end end function updateStatusGUI() game.player.gui.top.hoverboard.charge.caption = "Charge: "..global.charge end function hoverMode() limitHoverboard() if global.hoverboard.status == true then activeHoverMode() tileCheck() updateStatusGUI() end end function inboundTile(name) local tiles = {"copper-floor", "copper-floor2", "copper-floor3","accelerator","down","left","up","right"} for _, tile in ipairs(tiles) do if tile == name then return true end end return false end function tileCheck() local tile = getTile() local walk = game.player.walking_state.walking if tile.name == "accelerator" then if global.charge <= 40 then global.charge = global.charge + 10 end elseif tile.name == "down" then game.player.walking_state = {walking = walk, direction = defines.direction.south} elseif tile.name == "up" then game.player.walking_state = {walking = walk, direction = defines.direction.north} elseif tile.name == "right" then game.player.walking_state = {walking = walk, direction = defines.direction.east} elseif tile.name == "left" then game.player.walking_state = {walking = walk, direction = defines.direction.west} elseif inboundTile(tile.name) == false then global.charge = 0 end end
fix bug with dead players crashing the game
fix bug with dead players crashing the game
Lua
mit
kiba/Factorio-MagneticFloor,kiba/Factorio-MagneticFloor
5909a4ad12eca667131a762454d699b687a7c8e0
epgp_recurring.lua
epgp_recurring.lua
local L = LibStub("AceLocale-3.0"):GetLocale("EPGP") local GS = LibStub("LibGuildStorage-1.0") local Debug = LibStub("LibDebug-1.0") local callbacks = EPGP.callbacks local frame = CreateFrame("Frame", "EPGP_RecurringAwardFrame") local timeout = 0 local function RecurringTicker(self, elapsed) local vars = EPGP.db.profile local now = GetTime() if now > vars.next_award and GS:IsCurrentState() then EPGP:IncMassEPBy(vars.next_award_reason, vars.next_award_amount) vars.next_award = vars.next_award + vars.recurring_ep_period_mins * 60 end timeout = timeout + elapsed if timeout > 0.5 then callbacks:Fire("RecurringAwardUpdate", vars.next_award_reason, vars.next_award_amount, vars.next_award - now) timeout = 0 end end frame:SetScript("OnUpdate", RecurringTicker) frame:Hide() function EPGP:StartRecurringEP(reason, amount) local vars = EPGP.db.profile if vars.next_award then return false end vars.next_award_reason = reason vars.next_award_amount = amount vars.next_award = GetTime() + vars.recurring_ep_period_mins * 60 frame:Show() callbacks:Fire("StartRecurringAward", vars.next_award_reason, vars.next_award_amount, vars.recurring_ep_period_mins) return true end StaticPopupDialogs["EPGP_RECURRING_RESUME"] = { text = "%s", button1 = YES, button2 = NO, timeout = 0, hideOnEscape = 1, whileDead = 1, OnAccept = function() callbacks:Fire("ResumeRecurringAward", EPGP.db.profile.next_award_reason, EPGP.db.profile.next_award_amount, EPGP.db.profile.recurring_ep_period_mins) frame:Show() end, OnCancel = function(self, data, reason) if reason ~= "override" then EPGP:StopRecurringEP() end end, } function EPGP:ResumeRecurringEP() local vars = EPGP.db.profile local period_secs = vars.recurring_ep_period_mins * 60 local timeout = vars.next_award + period_secs - GetTime() StaticPopupDialogs["EPGP_RECURRING_RESUME"].timeout = timeout StaticPopup_Show( "EPGP_RECURRING_RESUME", -- We need to do the formatting here because static popups do -- not allow for 3 arguments to the formatting function. L["Do you want to resume recurring award (%s) %d EP/%s?"]:format( vars.next_award_reason, vars.next_award_amount, EPGP:RecurringEPPeriodString())) end function EPGP:CanResumeRecurringEP() local vars = EPGP.db.profile local now = GetTime() if not vars.next_award then return false end -- Now check if we only missed at most one award period. local period_secs = vars.recurring_ep_period_mins * 60 if vars.next_award + period_secs < now or vars.next_award > now then return false end return true end function EPGP:CancelRecurringEP() StaticPopup_Hide("EPGP_RECURRING_RESUME") local vars = EPGP.db.profile vars.next_award_reason = nil vars.next_award_amount = nil vars.next_award = nil frame:Hide() end function EPGP:StopRecurringEP() self:CancelRecurringEP() callbacks:Fire("StopRecurringAward") return true end function EPGP:RunningRecurringEP() local vars = EPGP.db.profile return not not vars.next_award end function EPGP:RecurringEPPeriodMinutes(val) local vars = EPGP.db.profile if val == nil then return vars.recurring_ep_period_mins end vars.recurring_ep_period_mins = val end function EPGP:RecurringEPPeriodString() local vars = EPGP.db.profile local fmt, val = SecondsToTimeAbbrev(vars.recurring_ep_period_mins * 60) return fmt:format(val) end
local L = LibStub("AceLocale-3.0"):GetLocale("EPGP") local GS = LibStub("LibGuildStorage-1.0") local Debug = LibStub("LibDebug-1.0") local callbacks = EPGP.callbacks local frame = CreateFrame("Frame", "EPGP_RecurringAwardFrame") local timeout = 0 local function RecurringTicker(self, elapsed) -- EPGP's db is available after GUILD_ROSTER_UPDATE. So we have a -- guard. if not EPGP.db then return end local vars = EPGP.db.profile local now = GetTime() if now > vars.next_award and GS:IsCurrentState() then EPGP:IncMassEPBy(vars.next_award_reason, vars.next_award_amount) vars.next_award = vars.next_award + vars.recurring_ep_period_mins * 60 end timeout = timeout + elapsed if timeout > 0.5 then callbacks:Fire("RecurringAwardUpdate", vars.next_award_reason, vars.next_award_amount, vars.next_award - now) timeout = 0 end end frame:SetScript("OnUpdate", RecurringTicker) frame:Hide() function EPGP:StartRecurringEP(reason, amount) local vars = EPGP.db.profile if vars.next_award then return false end vars.next_award_reason = reason vars.next_award_amount = amount vars.next_award = GetTime() + vars.recurring_ep_period_mins * 60 frame:Show() callbacks:Fire("StartRecurringAward", vars.next_award_reason, vars.next_award_amount, vars.recurring_ep_period_mins) return true end StaticPopupDialogs["EPGP_RECURRING_RESUME"] = { text = "%s", button1 = YES, button2 = NO, timeout = 0, hideOnEscape = 1, whileDead = 1, OnAccept = function() callbacks:Fire("ResumeRecurringAward", EPGP.db.profile.next_award_reason, EPGP.db.profile.next_award_amount, EPGP.db.profile.recurring_ep_period_mins) frame:Show() end, OnCancel = function(self, data, reason) if reason ~= "override" then EPGP:StopRecurringEP() end end, } function EPGP:ResumeRecurringEP() local vars = EPGP.db.profile local period_secs = vars.recurring_ep_period_mins * 60 local timeout = vars.next_award + period_secs - GetTime() StaticPopupDialogs["EPGP_RECURRING_RESUME"].timeout = timeout StaticPopup_Show( "EPGP_RECURRING_RESUME", -- We need to do the formatting here because static popups do -- not allow for 3 arguments to the formatting function. L["Do you want to resume recurring award (%s) %d EP/%s?"]:format( vars.next_award_reason, vars.next_award_amount, EPGP:RecurringEPPeriodString())) end function EPGP:CanResumeRecurringEP() local vars = EPGP.db.profile local now = GetTime() if not vars.next_award then return false end -- Now check if we only missed at most one award period. local period_secs = vars.recurring_ep_period_mins * 60 if vars.next_award + period_secs < now or vars.next_award > now then return false end return true end function EPGP:CancelRecurringEP() StaticPopup_Hide("EPGP_RECURRING_RESUME") local vars = EPGP.db.profile vars.next_award_reason = nil vars.next_award_amount = nil vars.next_award = nil frame:Hide() end function EPGP:StopRecurringEP() self:CancelRecurringEP() callbacks:Fire("StopRecurringAward") return true end function EPGP:RunningRecurringEP() local vars = EPGP.db.profile return not not vars.next_award end function EPGP:RecurringEPPeriodMinutes(val) local vars = EPGP.db.profile if val == nil then return vars.recurring_ep_period_mins end vars.recurring_ep_period_mins = val end function EPGP:RecurringEPPeriodString() local vars = EPGP.db.profile local fmt, val = SecondsToTimeAbbrev(vars.recurring_ep_period_mins * 60) return fmt:format(val) end
Fix error on zoning in while having recurring awards on. This fixes issue 389.
Fix error on zoning in while having recurring awards on. This fixes issue 389.
Lua
bsd-3-clause
hayword/tfatf_epgp,hayword/tfatf_epgp,ceason/epgp-tfatf,protomech/epgp-dkp-reloaded,ceason/epgp-tfatf,protomech/epgp-dkp-reloaded,sheldon/epgp,sheldon/epgp
4e25caae86d75428180b11e3ee99b5d9b1bd9dc6
epgp_recurring.lua
epgp_recurring.lua
local L = LibStub("AceLocale-3.0"):GetLocale("EPGP") local GS = LibStub("LibGuildStorage-1.0") local Debug = LibStub("LibDebug-1.0") local callbacks = EPGP.callbacks local frame = CreateFrame("Frame", "EPGP_RecurringAwardFrame") local timeout = 0 local function RecurringTicker(self, elapsed) -- EPGP's db is available after GUILD_ROSTER_UPDATE. So we have a -- guard. if not EPGP.db then return end local vars = EPGP.db.profile local now = GetTime() if now > vars.next_award and GS:IsCurrentState() then EPGP:IncMassEPBy(vars.next_award_reason, vars.next_award_amount) vars.next_award = vars.next_award + vars.recurring_ep_period_mins * 60 end timeout = timeout + elapsed if timeout > 0.5 then callbacks:Fire("RecurringAwardUpdate", vars.next_award_reason, vars.next_award_amount, vars.next_award - now) timeout = 0 end end frame:SetScript("OnUpdate", RecurringTicker) frame:Hide() function EPGP:StartRecurringEP(reason, amount) local vars = EPGP.db.profile if vars.next_award then return false end vars.next_award_reason = reason vars.next_award_amount = amount vars.next_award = GetTime() + vars.recurring_ep_period_mins * 60 frame:Show() callbacks:Fire("StartRecurringAward", vars.next_award_reason, vars.next_award_amount, vars.recurring_ep_period_mins) return true end StaticPopupDialogs["EPGP_RECURRING_RESUME"] = { text = "%s", button1 = YES, button2 = NO, timeout = 0, hideOnEscape = 1, whileDead = 1, OnAccept = function() callbacks:Fire("ResumeRecurringAward", EPGP.db.profile.next_award_reason, EPGP.db.profile.next_award_amount, EPGP.db.profile.recurring_ep_period_mins) frame:Show() end, OnCancel = function(self, data, reason) if reason ~= "override" then EPGP:StopRecurringEP() end end, } function EPGP:ResumeRecurringEP() local vars = EPGP.db.profile local period_secs = vars.recurring_ep_period_mins * 60 local timeout = vars.next_award + period_secs - GetTime() StaticPopupDialogs["EPGP_RECURRING_RESUME"].timeout = timeout StaticPopup_Show( "EPGP_RECURRING_RESUME", -- We need to do the formatting here because static popups do -- not allow for 3 arguments to the formatting function. L["Do you want to resume recurring award (%s) %d EP/%s?"]:format( vars.next_award_reason, vars.next_award_amount, EPGP:RecurringEPPeriodString())) end function EPGP:CanResumeRecurringEP() local vars = EPGP.db.profile local now = GetTime() if not vars.next_award then return false end -- Now check if we only missed at most one award period. local period_secs = vars.recurring_ep_period_mins * 60 if vars.next_award + period_secs < now or vars.next_award > now then return false end return true end function EPGP:CancelRecurringEP() StaticPopup_Hide("EPGP_RECURRING_RESUME") local vars = EPGP.db.profile vars.next_award_reason = nil vars.next_award_amount = nil vars.next_award = nil frame:Hide() end function EPGP:StopRecurringEP() self:CancelRecurringEP() callbacks:Fire("StopRecurringAward") return true end function EPGP:RunningRecurringEP() local vars = EPGP.db.profile return not not vars.next_award end function EPGP:RecurringEPPeriodMinutes(val) local vars = EPGP.db.profile if val == nil then return vars.recurring_ep_period_mins end vars.recurring_ep_period_mins = val end function EPGP:RecurringEPPeriodString() local vars = EPGP.db.profile local fmt, val = SecondsToTimeAbbrev(vars.recurring_ep_period_mins * 60) return fmt:format(val) end
local L = LibStub("AceLocale-3.0"):GetLocale("EPGP") local GS = LibStub("LibGuildStorage-1.0") local Debug = LibStub("LibDebug-1.0") local callbacks = EPGP.callbacks local frame = CreateFrame("Frame", "EPGP_RecurringAwardFrame") local timeout = 0 local function RecurringTicker(self, elapsed) -- EPGP's db is available after GUILD_ROSTER_UPDATE. So we have a -- guard. if not EPGP.db then return end local vars = EPGP.db.profile local now = GetTime() if now > vars.next_award and GS:IsCurrentState() then EPGP:IncMassEPBy(vars.next_award_reason, vars.next_award_amount) vars.next_award = vars.next_award + vars.recurring_ep_period_mins * 60 end timeout = timeout + elapsed if timeout > 0.5 then callbacks:Fire("RecurringAwardUpdate", vars.next_award_reason, vars.next_award_amount, vars.next_award - now) timeout = 0 end end frame:SetScript("OnUpdate", RecurringTicker) frame:Hide() function EPGP:StartRecurringEP(reason, amount) local vars = EPGP.db.profile if vars.next_award then return false end vars.next_award_reason = reason vars.next_award_amount = amount vars.next_award = GetTime() + vars.recurring_ep_period_mins * 60 frame:Show() callbacks:Fire("StartRecurringAward", vars.next_award_reason, vars.next_award_amount, vars.recurring_ep_period_mins) return true end StaticPopupDialogs["EPGP_RECURRING_RESUME"] = { text = "%s", button1 = YES, button2 = NO, timeout = 0, hideOnEscape = 1, whileDead = 1, OnAccept = function() callbacks:Fire("ResumeRecurringAward", EPGP.db.profile.next_award_reason, EPGP.db.profile.next_award_amount, EPGP.db.profile.recurring_ep_period_mins) frame:Show() end, OnCancel = function(self, data, reason) if reason ~= "override" then EPGP:StopRecurringEP() end end, } function EPGP:ResumeRecurringEP() local vars = EPGP.db.profile local period_secs = vars.recurring_ep_period_mins * 60 local timeout = vars.next_award + period_secs - GetTime() StaticPopupDialogs["EPGP_RECURRING_RESUME"].timeout = timeout StaticPopup_Show( "EPGP_RECURRING_RESUME", -- We need to do the formatting here because static popups do -- not allow for 3 arguments to the formatting function. L["Do you want to resume recurring award (%s) %d EP/%s?"]:format( vars.next_award_reason, vars.next_award_amount, EPGP:RecurringEPPeriodString())) end function EPGP:CanResumeRecurringEP() local vars = EPGP.db.profile local now = GetTime() if not vars.next_award then return false end local period_secs = vars.recurring_ep_period_mins * 60 local last_award = vars.next_award - period_secs local next_next_award = vars.next_award + period_secs if last_award < now and now < next_next_award then return true end return false end function EPGP:CancelRecurringEP() StaticPopup_Hide("EPGP_RECURRING_RESUME") local vars = EPGP.db.profile vars.next_award_reason = nil vars.next_award_amount = nil vars.next_award = nil frame:Hide() end function EPGP:StopRecurringEP() self:CancelRecurringEP() callbacks:Fire("StopRecurringAward") return true end function EPGP:RunningRecurringEP() local vars = EPGP.db.profile return not not vars.next_award end function EPGP:RecurringEPPeriodMinutes(val) local vars = EPGP.db.profile if val == nil then return vars.recurring_ep_period_mins end vars.recurring_ep_period_mins = val end function EPGP:RecurringEPPeriodString() local vars = EPGP.db.profile local fmt, val = SecondsToTimeAbbrev(vars.recurring_ep_period_mins * 60) return fmt:format(val) end
Fix recurring EP resume after a reloadUI. This fixes issue 289.
Fix recurring EP resume after a reloadUI. This fixes issue 289.
Lua
bsd-3-clause
hayword/tfatf_epgp,ceason/epgp-tfatf,hayword/tfatf_epgp,protomech/epgp-dkp-reloaded,sheldon/epgp,ceason/epgp-tfatf,protomech/epgp-dkp-reloaded,sheldon/epgp
53d5ed802ff3948dac15e099626ef16f65ed26f7
verizon.lua
verizon.lua
local url_count = 0 local tries = 0 local item_type = os.getenv('item_type') local item_value = os.getenv('item_value') read_file = function(file) if file then local f = assert(io.open(file)) local data = f:read("*all") f:close() return data else return "" end end wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason) local url = urlpos["url"]["url"] -- Skip redirect from mysite.verizon.net and members.bellatlantic.net if url == "http://entertainment.verizon.com/" then return false elseif string.match(url, "bellatlantic%.net/([^/]+)/") or string.match(url, "verizon%.net/([^/]+)/") then if item_type == "verizon" then local directory_name_verizon = string.match(url, "verizon%.net/([^/]+)/") directory_name_verizon = string.gsub(directory_name_verizon, '%%7E', '~') if directory_name_verizon ~= item_value then -- do not want someone else's homepage -- io.stdout:write("\n Reject " .. url .. " " .. directory_name_verizon .. "\n") -- io.stdout:flush() return false else return verdict end elseif item_type == "bellatlantic" then local directory_name_bellatlantic = string.match(url, "bellatlantic%.net/([^/]+)/") directory_name_bellatlantic = string.gsub(directory_name_bellatlantic, '%%7E', '~') if directory_name_bellatlantic ~= item_value then -- do not want someone else's homepage -- io.stdout:write("\n Reject " .. url .. " " .. directory_name_bellatlantic .. "\n") -- io.stdout:flush() return false else return verdict end elseif item_type == "bellatlantic36pack" then local directory_name_bellatlantic36pack = string.match(url, "bellatlantic%.net/([^/]+)/") directory_name_bellatlantic36pack = string.gsub(directory_name_bellatlantic36pack, '%%7E', '~') if directory_name_bellatlantic36pack ~= item_value then -- do not want someone else's homepage -- io.stdout:write("\n Reject " .. url .. " " .. directory_name_bellatlantic36pack .. "\n") -- io.stdout:flush() return false else return verdict end elseif item_type == "verizon36pack" then local verizon36pack = string.match(url, "verizon%.net/([^/]+)/") verizon36pack = string.gsub(verizon36pack, '%%7E', '~') if verizon36pack ~= item_value then -- do not want someone else's homepage -- io.stdout:write("\n Reject " .. url .. " " .. verizon36pack .. "\n") -- io.stdout:flush() return false else return verdict end else -- shouldn't reach here! assert(false) end elseif string.match(url, "//////////") then return false else return verdict end 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"] url_count = url_count + 1 io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \r") io.stdout:flush() if status_code >= 500 or (status_code >= 400 and status_code ~= 404 and status_code ~= 403) then if string.match(url["host"], "verizon%.net") or string.match(url["host"], "bellatlantic%.net") then if status_code == 423 then return wget.actions.ABORT end io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 5 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.ABORT else return wget.actions.CONTINUE end else io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 5 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.NOTHING else return wget.actions.CONTINUE end end elseif status_code == 0 then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 1") tries = tries + 1 if tries >= 5 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(1000, 2000) / 100.0) -- local sleep_time = 0 -- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then -- -- We should be able to go fast on images since that's what a web browser does -- sleep_time = 0 -- end if sleep_time > 0.001 then os.execute("sleep " .. sleep_time) end return wget.actions.NOTHING end
local url_count = 0 local tries = 0 local item_type = os.getenv('item_type') local item_value = os.getenv('item_value') read_file = function(file) if file then local f = assert(io.open(file)) local data = f:read("*all") f:close() return data else return "" end end wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason) local url = urlpos["url"]["url"] -- Skip redirect from mysite.verizon.net and members.bellatlantic.net if url == "http://entertainment.verizon.com/" then return false elseif string.match(url, "bellatlantic%.net/([^/]+)/") or string.match(url, "verizon%.net/([^/]+)/") then if item_type == "verizon" then local directory_name_verizon = string.match(url, "verizon%.net/([^/]+)/") directory_name_verizon = string.gsub(directory_name_verizon, '%%7E', '~') if directory_name_verizon ~= item_value then -- do not want someone else's homepage -- io.stdout:write("\n Reject " .. url .. " " .. directory_name_verizon .. "\n") -- io.stdout:flush() return false else return verdict end elseif item_type == "bellatlantic" then local directory_name_bellatlantic = string.match(url, "bellatlantic%.net/([^/]+)/") directory_name_bellatlantic = string.gsub(directory_name_bellatlantic, '%%7E', '~') if directory_name_bellatlantic ~= item_value then -- do not want someone else's homepage -- io.stdout:write("\n Reject " .. url .. " " .. directory_name_bellatlantic .. "\n") -- io.stdout:flush() return false else return verdict end elseif item_type == "bellatlantic36pack" then local directory_name_bellatlantic36pack = string.match(url, "bellatlantic%.net/([^/]+)/") directory_name_bellatlantic36pack = string.gsub(directory_name_bellatlantic36pack, '%%7E', '~') if directory_name_bellatlantic36pack ~= item_value then -- do not want someone else's homepage -- io.stdout:write("\n Reject " .. url .. " " .. directory_name_bellatlantic36pack .. "\n") -- io.stdout:flush() return false else return verdict end elseif item_type == "verizon36pack" then local directory_name_verizon36pack = string.match(url, "verizon%.net/([^/]+)/") directory_name_verizon36pack = string.gsub(directory_name_verizon36pack, '%%7E', '~') if directory_name_verizon36pack ~= item_value then -- do not want someone else's homepage -- io.stdout:write("\n Reject " .. url .. " " .. directory_name_verizon36pack .. "\n") -- io.stdout:flush() return false else return verdict end else -- shouldn't reach here! assert(false) end elseif string.match(url, "//////////") then return false else return verdict end 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"] url_count = url_count + 1 io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \r") io.stdout:flush() if status_code >= 500 or (status_code >= 400 and status_code ~= 404 and status_code ~= 403) then if string.match(url["host"], "verizon%.net") or string.match(url["host"], "bellatlantic%.net") then if status_code == 423 then return wget.actions.ABORT end io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 5 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.ABORT else return wget.actions.CONTINUE end else io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 5 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.NOTHING else return wget.actions.CONTINUE end end elseif status_code == 0 then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 1") tries = tries + 1 if tries >= 5 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(1000, 2000) / 100.0) -- local sleep_time = 0 -- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then -- -- We should be able to go fast on images since that's what a web browser does -- sleep_time = 0 -- end if sleep_time > 0.001 then os.execute("sleep " .. sleep_time) end return wget.actions.NOTHING end
verizon.lua: fix little mistake
verizon.lua: fix little mistake
Lua
unlicense
ArchiveTeam/verizon-grab,ArchiveTeam/verizon-grab,ArchiveTeam/verizon-grab
ee5088ef9ae92a0e4bcf1cfc77a6380d20ad1b79
lua/plugins/snippets/sh.lua
lua/plugins/snippets/sh.lua
local load_module = require('utils.helpers').load_module local ls = load_module 'luasnip' if not ls then return false end local s = ls.snippet local sn = ls.snippet_node local t = ls.text_node -- local isn = ls.indent_snippet_node local i = ls.insert_node -- local f = ls.function_node -- local c = ls.choice_node local d = ls.dynamic_node -- local l = require('luasnip.extras').lambda -- local r = require('luasnip.extras').rep -- local p = require('luasnip.extras').partial -- local m = require('luasnip.extras').match -- local n = require('luasnip.extras').nonempty -- local dl = require('luasnip.extras').dynamic_lambda -- local fmt = require('luasnip.extras.fmt').fmt -- local fmta = require('luasnip.extras.fmt').fmta -- local types = require 'luasnip.util.types' -- local events = require 'luasnip.util.events' -- local conds = require 'luasnip.extras.expand_conditions' local utils = RELOAD 'plugins.snippets.utils' local saved_text = utils.saved_text -- local get_comment = utils.get_comment -- local surround_with_func = utils.surround_with_func local function else_clause(args, snip, old_state, placeholder) local nodes = {} if snip.captures[1] == 'e' then table.insert(nodes, t { '', 'else', '\t' }) table.insert(nodes, i(1, ':')) else table.insert(nodes, t { '' }) end local snip_node = sn(nil, nodes) snip_node.old_state = old_state return snip_node end -- stylua: ignore ls.snippets.sh = { s( { trig = 'if(e?)', regTrig = true }, { t{'if [[ '}, i(1, 'condition'), t{' ]]; then', ''}, d(2, saved_text, {}, {text = ':', indent = true}), d(3, else_clause, {}, {}), t{'', 'fi'}, } ), s('fun', { t{'function '}, i(1, 'name'), t{'() {', ''}, d(2, saved_text, {}, {text = ':', indent = true}), t{'', '}'}, }), s('for', { t{'for '}, i(1, 'i'), t{' in '}, i(2, 'Iterator'), t{'; do', ''}, d(3, saved_text, {}, {text = ':', indent = true}), t{'', 'done'} }), s('wh', { t{'while '}, i(1, '[[ condition ]]'), t{'; do'}, d(2, saved_text, {}, {text = ':', indent = true}), t{'', 'done'} }), s("case", { t{'case "'}, i(1, '$VAR'), t{'" in', ""}, t{'\t'}, i(2, 'condition'), t{' )', ''}, t{'\t\t'}, i(3, ':'), t{'', '\t\t;;'}, t{'', 'esac'} }), s('l', { t{'local '}, i(1, 'varname'), t{'='}, i(2, '1'), }), s('ha', { t{'hash '}, i(1, 'cmd'), t{' 2>/dev/null'}, }), }
local load_module = require('utils.helpers').load_module local ls = load_module 'luasnip' if not ls then return false end local s = ls.snippet local sn = ls.snippet_node local t = ls.text_node -- local isn = ls.indent_snippet_node local i = ls.insert_node -- local f = ls.function_node -- local c = ls.choice_node local d = ls.dynamic_node -- local l = require('luasnip.extras').lambda local r = require('luasnip.extras').rep -- local p = require('luasnip.extras').partial -- local m = require('luasnip.extras').match -- local n = require('luasnip.extras').nonempty -- local dl = require('luasnip.extras').dynamic_lambda local fmt = require('luasnip.extras.fmt').fmt -- local fmta = require('luasnip.extras.fmt').fmta -- local types = require 'luasnip.util.types' -- local events = require 'luasnip.util.events' -- local conds = require 'luasnip.extras.expand_conditions' local utils = RELOAD 'plugins.snippets.utils' local saved_text = utils.saved_text -- local get_comment = utils.get_comment -- local surround_with_func = utils.surround_with_func local function else_clause(args, snip, old_state, placeholder) local nodes = {} if snip.captures[1] == 'e' then table.insert(nodes, t { 'else', '\t' }) table.insert(nodes, i(1, ':')) table.insert(nodes, t { '', '' }) else table.insert(nodes, t { '' }) end local snip_node = sn(nil, nodes) snip_node.old_state = old_state return snip_node end -- stylua: ignore ls.snippets.sh = { s( { trig = 'if(e?)', regTrig = true }, fmt([=[ if [[ {} ]]; then {} {}fi ]=], { i(1, 'condition'), d(2, saved_text, {}, {text = ':', indent = true}), d(3, else_clause, {}, {}), }) ), s('fun', fmt([[ function {}() {{ {} }} ]], { i(1, 'name'), d(2, saved_text, {}, {text = ':', indent = true}), })), s('for', fmt([[ for {} in {}; do {} done ]], { i(1, 'i'), i(2, 'Iterator'), d(3, saved_text, {}, {text = ':', indent = true}), })), s('fori', fmt([[ for (({} = {}; {} < {}; {}++)); do {} done ]], { i(1, 'i'), i(2, '0'), r(1), i(3, '10'), r(1), d(4, saved_text, {}, {text = ':', indent = true}), })), s('wh', fmt([=[ while [[ {} ]]; do {} done ]=], { i(1, 'condition'), d(2, saved_text, {}, {text = ':', indent = true}), })), s('l', fmt([[ local {}={} ]],{ i(1, 'varname'), i(2, '1'), })), s('ex', fmt([[ export {}={} ]],{ i(1, 'varname'), i(2, '1'), })), s('ha', fmt([[ hash {} 2>/dev/null ]],{ i(1, 'cmd'), })), s('case', fmt([[ case ${} in {}) {} ;; esac ]],{ i(1, 'VAR'), i(2, 'CONDITION'), i(3, ':'), })), }
fix: Start migrating snippets to fmt syntax
fix: Start migrating snippets to fmt syntax fmt string is more readable so start migrate snippets to use it
Lua
mit
Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim
46e055a6103e10213704154bd22cb7f12bc0b72a
control.lua
control.lua
require 'util' require 'gui' require "test" require "stdlib/log/logger" LOG = Logger.new("MagneticFloor") function print(stuff) game.players[1].print(stuff) end function printBool(stuff) game.players[1].print(tostring(stuff)) end function setup() global.hoverboard = global.hoverboard or {} end function activateEquipment(index) global.hoverboard[index].inserted = true global.hoverboard[index].active = false UI.initialize(index) end function deactivateEquipment(index) if global.hoverboard[index].inserted == true then global.hoverboard[index].inserted = false UI.destroy(index) end end function createPlayerMag(i) local entity = { charge = 0, active = false, inserted = false, } global.hoverboard[i] = entity end script.on_init(setup) function getTile(index) return game.players[index].surface.get_tile(game.players[index].position.x,game.players[index].position.y) end function getArmor(index) local armor = game.players[index].get_inventory(defines.inventory.player_armor)[1] return armor end function armorCheck(index) local armor = getArmor(index) if armor.valid_for_read and armor.has_grid then return true end return false end script.on_event(defines.events.on_player_joined_game, function(event) createPlayerMag(event.player_index) end) script.on_event(defines.events.on_tick, function(event) local n = 0 for k,v in pairs(game.players) do if global.hoverboard[k] == nil then createPlayerMag(v.index) end if global.hoverboard[k].inserted == true and global.hoverboard[k].active == true then locomotion(k) tileCheck(k) UI.updateStatus(k) end end end) script.on_event(defines.events.on_player_armor_inventory_changed, function(event) local index = event.player_index if armorCheck(index) then local armor = getArmor(index) local equipment = armor.grid.equipment for i, e in ipairs(equipment) do if e.name == "hoverboard" then activateEquipment(index) end end else deactivateEquipment(index) end end) script.on_event(defines.events.on_player_placed_equipment, function(event) local index = event.player_index if armorCheck(index) and event.equipment.name == "hoverboard" then activateEquipment(index) end end) script.on_event(defines.events.on_player_removed_equipment, function(event) local index = event.player_index if armorCheck(index) and event.equipment == "hoverboard" then deactivateEquipment(index) end end) script.on_event(defines.events.on_entity_died, function(event) if event.entity.name == "player" then global.dead = true end end) script.on_event(defines.events.on_gui_click,function(event) local index = event.player_index if event.element.name == "mode" then if global.hoverboard[index].active == false then global.hoverboard[index].active = true elseif global.hoverboard[index].active == true then global.hoverboard[index].active = false end UI.switchMode(global.hoverboard[index].active,index) end end) function entity_on_built_tile_action(event) for k,v in pairs(event.positions) do local tile = game.players[event.player_index].surface.get_tile(v.x,v.y) if tile.name == "accelerator" then local entity = game.players[event.player_index].surface.create_entity{ name = "accelerator_charger", position = tile.position, force = game.players[event.player_index].force } else local entity = game.players[event.player_index].surface.find_entity("accelerator_charger",tile.position) if entity ~= nil then entity.destroy() end end end end function entity_on_removed_tile_action(event) for k,v in pairs(event.positions) do local tile = game.players[event.player_index].surface.get_tile(v.x,v.y) local entity = game.players[event.player_index].surface.find_entity("accelerator_charger", tile.position) if entity ~= nil then entity.destroy() end end end script.on_event(defines.events.on_player_built_tile,entity_on_built_tile_action) script.on_event(defines.events.on_robot_built_tile,entity_on_built_tile_action) script.on_event(defines.events.on_player_mined_tile, entity_on_removed_tile_action) script.on_event(defines.events.on_robot_mined_tile, entity_on_removed_tile_action) function charge_hoverboard(index,tile) local entity = game.players[index].surface.find_entity("accelerator_charger", tile.position) if entity ~= nil then print("energy level: "..tostring(entity.energy)) local charge_needed = 5 - global.hoverboard[index].charge local energy_needed = (charge_needed) * "1000" if (entity.energy - energy_needed) > 0 then entity.energy = entity.energy - energy_needed global.hoverboard[index].charge = charge_needed end end end function locomotion(index) local orientation = game.players[index].walking_state.direction if global.hoverboard[index].charge > 0 then if game.tick % 60 == 0 then global.hoverboard[index].charge = global.hoverboard[index].charge - 1 end game.players[index].walking_state = {walking = true, direction = orientation} end end function inboundTile(name) local tiles = {"copper-floor", "copper-floor2", "copper-floor3","accelerator","down","left","up","right"} for _, tile in ipairs(tiles) do if tile == name then return true end end return false end function tileCheck(index) local tile = getTile(index) local walk = game.players[index].walking_state.walking if tile.name == "accelerator" then charge_hoverboard(index,tile) elseif tile.name == "down" and global.hoverboard[index].charge > 0 then game.players[index].walking_state = {walking = walk, direction = defines.direction.south} elseif tile.name == "up" and global.hoverboard[index].charge > 0 then game.players[index].walking_state = {walking = walk, direction = defines.direction.north} elseif tile.name == "right" and global.hoverboard[index].charge > 0 then game.players[index].walking_state = {walking = walk, direction = defines.direction.east} elseif tile.name == "left" and global.hoverboard[index].charge > 0 then game.players[index].walking_state = {walking = walk, direction = defines.direction.west} elseif inboundTile(tile.name) == false then global.hoverboard[index].charge = 0 end end
require 'util' require 'gui' require "test" require "stdlib/log/logger" LOG = Logger.new("MagneticFloor") function print(stuff) game.players[1].print(stuff) end function printBool(stuff) game.players[1].print(tostring(stuff)) end function setup() global.hoverboard = global.hoverboard or {} end function activateEquipment(index) global.hoverboard[index].inserted = true global.hoverboard[index].active = false UI.initialize(index) end function deactivateEquipment(index) if global.hoverboard[index].inserted == true then global.hoverboard[index].inserted = false UI.destroy(index) end end function createPlayerMag(i) local entity = { charge = 0, active = false, inserted = false, } global.hoverboard[i] = entity end script.on_init(setup) function getTile(index) return game.players[index].surface.get_tile(game.players[index].position.x,game.players[index].position.y) end function getArmor(index) local armor = game.players[index].get_inventory(defines.inventory.player_armor)[1] return armor end function armorCheck(index) local armor = getArmor(index) if armor.valid_for_read and armor.has_grid then return true end return false end script.on_event(defines.events.on_player_joined_game, function(event) createPlayerMag(event.player_index) end) script.on_event(defines.events.on_tick, function(event) local n = 0 for k,v in pairs(game.players) do if global.hoverboard[k] == nil then createPlayerMag(v.index) end if global.hoverboard[k].inserted == true and global.hoverboard[k].active == true then locomotion(k) tileCheck(k) UI.updateStatus(k) end end end) script.on_event(defines.events.on_player_armor_inventory_changed, function(event) local index = event.player_index if armorCheck(index) then local armor = getArmor(index) local equipment = armor.grid.equipment for i, e in ipairs(equipment) do if e.name == "hoverboard" then activateEquipment(index) end end else deactivateEquipment(index) end end) script.on_event(defines.events.on_player_placed_equipment, function(event) local index = event.player_index if armorCheck(index) and event.equipment.name == "hoverboard" then activateEquipment(index) end end) script.on_event(defines.events.on_player_removed_equipment, function(event) local index = event.player_index if armorCheck(index) and event.equipment == "hoverboard" then deactivateEquipment(index) end end) script.on_event(defines.events.on_entity_died, function(event) if event.entity.name == "player" then global.dead = true end end) script.on_event(defines.events.on_gui_click,function(event) local index = event.player_index if event.element.name == "mode" then if global.hoverboard[index].active == false then global.hoverboard[index].active = true elseif global.hoverboard[index].active == true then global.hoverboard[index].active = false end UI.switchMode(global.hoverboard[index].active,index) end end) function entity_on_built_tile_action(event) for k,v in pairs(event.positions) do local tile = game.players[event.player_index].surface.get_tile(v.x,v.y) if tile.name == "accelerator" then local entity = game.players[event.player_index].surface.create_entity{ name = "accelerator_charger", position = tile.position, force = game.players[event.player_index].force } else local entity = game.players[event.player_index].surface.find_entity("accelerator_charger",tile.position) if entity ~= nil then entity.destroy() end end end end function entity_on_removed_tile_action(event) for k,v in pairs(event.positions) do local tile = game.players[event.player_index].surface.get_tile(v.x,v.y) local entity = game.players[event.player_index].surface.find_entity("accelerator_charger", tile.position) if entity ~= nil then entity.destroy() end end end script.on_event(defines.events.on_player_built_tile,entity_on_built_tile_action) script.on_event(defines.events.on_robot_built_tile,entity_on_built_tile_action) script.on_event(defines.events.on_player_mined_tile, entity_on_removed_tile_action) script.on_event(defines.events.on_robot_mined_tile, entity_on_removed_tile_action) function charge_hoverboard(index,tile) local entity = game.players[index].surface.find_entity("accelerator_charger", tile.position) if entity ~= nil then print("energy level: "..tostring(entity.energy)) local charge_needed = 5 - global.hoverboard[index].charge local energy_needed = (charge_needed) * "1000" if (entity.energy - energy_needed) > 0 then entity.energy = entity.energy - energy_needed global.hoverboard[index].charge = global.hoverboard[index].charge + charge_needed end end end function locomotion(index) local orientation = game.players[index].walking_state.direction if global.hoverboard[index].charge > 0 then if game.tick % 60 == 0 then global.hoverboard[index].charge = global.hoverboard[index].charge - 1 end game.players[index].walking_state = {walking = true, direction = orientation} end end function inboundTile(name) local tiles = {"copper-floor", "copper-floor2", "copper-floor3","accelerator","down","left","up","right"} for _, tile in ipairs(tiles) do if tile == name then return true end end return false end function tileCheck(index) local tile = getTile(index) local walk = game.players[index].walking_state.walking if tile.name == "accelerator" then charge_hoverboard(index,tile) elseif tile.name == "down" and global.hoverboard[index].charge > 0 then game.players[index].walking_state = {walking = walk, direction = defines.direction.south} elseif tile.name == "up" and global.hoverboard[index].charge > 0 then game.players[index].walking_state = {walking = walk, direction = defines.direction.north} elseif tile.name == "right" and global.hoverboard[index].charge > 0 then game.players[index].walking_state = {walking = walk, direction = defines.direction.east} elseif tile.name == "left" and global.hoverboard[index].charge > 0 then game.players[index].walking_state = {walking = walk, direction = defines.direction.west} elseif inboundTile(tile.name) == false then global.hoverboard[index].charge = 0 end end
fix the charging formula
fix the charging formula
Lua
mit
kiba/Factorio-MagneticFloor,kiba/Factorio-MagneticFloor
e93778d4e0ec16e3358cff35ab79a497d52e8609
src/luarocks/fun.lua
src/luarocks/fun.lua
--- A set of basic functional utilities local fun = {} local unpack = table.unpack or unpack function fun.concat(xs, ys) local rs = {} local n = #xs for i = 1, n do rs[i] = xs[i] end for i = 1, #ys do rs[i + n] = ys[i] end return rs end function fun.contains(xs, v) for _, x in ipairs(xs) do if v == x then return true end end return false end function fun.map(xs, f) local rs = {} for i = 1, #xs do rs[i] = f(xs[i]) end return rs end function fun.filter(xs, f) local rs = {} for i = 1, #xs do local v = xs[i] if f(v) then rs[#rs+1] = v end end return rs end function fun.traverse(t, f) return fun.map(t, function(x) return type(x) == "table" and fun.traverse(x, f) or f(x) end) end function fun.reverse_in(t) for i = 1, math.floor(#t/2) do local m, n = i, #t - i + 1 local a, b = t[m], t[n] t[m] = b t[n] = a end return t end function fun.sort_in(t, f) table.sort(t, f) return t end function fun.flip(f) return function(a, b) return f(b, a) end end function fun.find(xs, f) if type(xs) == "function" then for v in xs do local x = f(v) if x then return x end end elseif type(xs) == "table" then for _, v in ipairs(xs) do local x = f(v) if x then return x end end end end function fun.partial(f, ...) local n = select("#", ...) if n == 1 then local a = ... return function(...) return f(a, ...) end elseif n == 2 then local a, b = ... return function(...) return f(a, b, ...) end else local pargs = { n = n, ... } return function(...) local m = select("#", ...) local fargs = { ... } local args = {} for i = 1, n do args[i] = pargs[i] end for i = 1, m do args[i+n] = fargs[i] end local unpack = unpack or table.unpack return f(unpack(args, 1, n+m)) end end end function fun.memoize(fn) local memory = setmetatable({}, { __mode = "k" }) local errors = setmetatable({}, { __mode = "k" }) local NIL = {} return function(arg) if memory[arg] then if memory[arg] == NIL then return nil, errors[arg] end return memory[arg] end local ret1, ret2 = fn(arg) if ret1 ~= nil then memory[arg] = ret1 else memory[arg] = NIL errors[arg] = ret2 end return ret1, ret2 end end return fun
--- A set of basic functional utilities local fun = {} local unpack = table.unpack or unpack function fun.concat(xs, ys) local rs = {} local n = #xs for i = 1, n do rs[i] = xs[i] end for i = 1, #ys do rs[i + n] = ys[i] end return rs end function fun.contains(xs, v) for _, x in ipairs(xs) do if v == x then return true end end return false end function fun.map(xs, f) local rs = {} for i = 1, #xs do rs[i] = f(xs[i]) end return rs end function fun.filter(xs, f) local rs = {} for i = 1, #xs do local v = xs[i] if f(v) then rs[#rs+1] = v end end return rs end function fun.traverse(t, f) return fun.map(t, function(x) return type(x) == "table" and fun.traverse(x, f) or f(x) end) end function fun.reverse_in(t) for i = 1, math.floor(#t/2) do local m, n = i, #t - i + 1 local a, b = t[m], t[n] t[m] = b t[n] = a end return t end function fun.sort_in(t, f) table.sort(t, f) return t end function fun.flip(f) return function(a, b) return f(b, a) end end function fun.find(xs, f) if type(xs) == "function" then for v in xs do local x = f(v) if x then return x end end elseif type(xs) == "table" then for _, v in ipairs(xs) do local x = f(v) if x then return x end end end end function fun.partial(f, ...) local n = select("#", ...) if n == 1 then local a = ... return function(...) return f(a, ...) end elseif n == 2 then local a, b = ... return function(...) return f(a, b, ...) end else local pargs = { n = n, ... } return function(...) local m = select("#", ...) local fargs = { ... } local args = {} for i = 1, n do args[i] = pargs[i] end for i = 1, m do args[i+n] = fargs[i] end return f(unpack(args, 1, n+m)) end end end function fun.memoize(fn) local memory = setmetatable({}, { __mode = "k" }) local errors = setmetatable({}, { __mode = "k" }) local NIL = {} return function(arg) if memory[arg] then if memory[arg] == NIL then return nil, errors[arg] end return memory[arg] end local ret1, ret2 = fn(arg) if ret1 ~= nil then memory[arg] = ret1 else memory[arg] = NIL errors[arg] = ret2 end return ret1, ret2 end end return fun
Fix duplicated unpack compat
Fix duplicated unpack compat
Lua
mit
luarocks/luarocks,keplerproject/luarocks,luarocks/luarocks,keplerproject/luarocks,keplerproject/luarocks,keplerproject/luarocks,luarocks/luarocks
a0ee948ffd7edb78b63e4cd7b4ea8efca4a06ae8
search-script.lua
search-script.lua
#!/usr/bin/env lua local config = require "config" local filePath = config.filePath function printArgs() for k,v in pairs(arg) do print(k,v) end end function countArgs() count = 0 for _ in pairs(arg) do count = count + 1 end return count - 2 end function helpMenu() print "#========================================================================#" print "# -h Display this help menu #" print "# -n The string to search #" print "# -b Search by file name, category or both #" print "# filename, category, all default all #" print "# Usage: ./search-script.lua -n foofile -b all -e png #" print "#========================================================================#" end -- see if the file exists function file_exists(file) local f = io.open(file, "rb") if f then f:close() end return f ~= nil end -- get all lines from a file, returns an empty -- list/table if the file does not exist function lines_from(file) if not file_exists(file) then print "El archivo no existe" os.exit() end lines = {} for line in io.lines(file) do lines[#lines + 1] = line end return lines end -- tests the functions above local file = filePath local lines = lines_from(file) -- print all line numbers and their contents function printAll(lines) for k,v in pairs(lines) do print('line[' .. k .. ']', v) end end function printResults(lines,script) for k,v in pairs(lines) do local i = string.find(v, script) if i ~= nil then print('[' .. k .. ']', v) end end end function defineArgs() local string for i=1,countArgs() do if arg[i] == "-h" then helpMenu() os.exit() end if arg[i] == "-n" then string = arg[i+1] print(script) end end --printResults(lines,script) end if countArgs() < 1 then printAll(lines) else defineArgs() end
#!/usr/bin/env lua local config = require "config" local filePath = config.filePath function printArgs() for k,v in pairs(arg) do print(k,v) end end function countArgs() count = 0 for _ in pairs(arg) do count = count + 1 end return count - 2 end function helpMenu() print "#========================================================================#" print "# -h Display this help menu #" print "# -n The string to search #" print "# -b Search by file name, category or both #" print "# filename, category, all default all #" print "# Usage: ./search-script.lua -n foofile -b all -e png #" print "#========================================================================#" end -- see if the file exists function file_exists(file) local f = io.open(file, "rb") if f then f:close() end return f ~= nil end -- get all lines from a file, returns an empty -- list/table if the file does not exist function lines_from(file) if not file_exists(file) then print "El archivo no existe" os.exit() end lines = {} for line in io.lines(file) do lines[#lines + 1] = line end return lines end -- tests the functions above local file = filePath local lines = lines_from(file) -- print all line numbers and their contents function printAll(lines) for k,v in pairs(lines) do print('line[' .. k .. ']', v) end end function printResults(lines,script) for k,v in pairs(lines) do local i = string.find(v, script) if i ~= nil then print('[' .. k .. ']', v) end end end function defineArgs() local string for i=1,countArgs() do if arg[i] == "-h" then helpMenu() os.exit() end if arg[i] == "-n" then string = arg[i+1] printResults(lines,string) end end --printResults(lines,script) end if countArgs() < 1 then printAll(lines) else defineArgs() end
Fixing search by name
Fixing search by name Signed-off-by: Jacobo Tibaquira <[email protected]>
Lua
apache-2.0
JKO/nsearch,JKO/nsearch
912f487e4b15c083e8c9e456f6ed0c940a47a6f2
profiles/stepless.lua
profiles/stepless.lua
-- Foot profile api_version = 1 local find_access_tag = require("lib/access").find_access_tag local Set = require('lib/set') local Sequence = require('lib/sequence') local Handlers = require("lib/handlers") local next = next -- bind to local for speed properties.max_speed_for_map_matching = 40/3.6 -- kmph -> m/s properties.use_turn_restrictions = false properties.continue_straight_at_waypoint = false properties.weight_name = 'duration' --properties.weight_name = 'routability' local walking_speed = 5 local profile = { default_mode = mode.walking, default_speed = walking_speed, oneway_handling = 'specific', -- respect 'oneway:foot' but not 'oneway' traffic_light_penalty = 2, u_turn_penalty = 2, barrier_whitelist = Set { 'cycle_barrier', 'bollard', 'entrance', 'cattle_grid', 'border_control', 'toll_booth', 'sally_port', 'gate', 'no', 'kerb', 'block' }, access_tag_whitelist = Set { 'yes', 'foot', 'permissive', 'designated' }, access_tag_blacklist = Set { 'no', 'agricultural', 'forestry', 'private', 'delivery', }, restricted_access_tag_list = Set { }, restricted_highway_whitelist = Set { }, access_tags_hierarchy = Sequence { 'foot', 'access' }, restrictions = Sequence { 'foot' }, -- list of suffixes to suppress in name change instructions suffix_list = Set { 'N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW', 'North', 'South', 'West', 'East' }, avoid = Set { 'impassable' }, speeds = Sequence { highway = { primary = walking_speed, primary_link = walking_speed, secondary = walking_speed, secondary_link = walking_speed, tertiary = walking_speed, tertiary_link = walking_speed, unclassified = walking_speed, residential = walking_speed, road = walking_speed, living_street = walking_speed, service = walking_speed, track = walking_speed, path = walking_speed, pedestrian = walking_speed, footway = walking_speed, pier = walking_speed, }, railway = { platform = walking_speed }, amenity = { parking = walking_speed, parking_entrance= walking_speed }, man_made = { pier = walking_speed }, leisure = { track = walking_speed } }, route_speeds = { ferry = 5 }, bridge_speeds = { }, surface_speeds = { fine_gravel = walking_speed*0.75, gravel = walking_speed*0.75, pebblestone = walking_speed*0.75, mud = walking_speed*0.5, sand = walking_speed*0.5 }, tracktype_speeds = { }, smoothness_speeds = { } } function node_function (node, result) -- parse access and barrier tags local access = find_access_tag(node, profile.access_tags_hierarchy) if access then if profile.access_tag_blacklist[access] then result.barrier = true end else local barrier = node:get_value_by_key("barrier") if barrier then -- make an exception for rising bollard barriers local bollard = node:get_value_by_key("bollard") local rising_bollard = bollard and "rising" == bollard if not profile.barrier_whitelist[barrier] and not rising_bollard then result.barrier = true end end end -- check if node is a traffic light local tag = node:get_value_by_key("highway") if "traffic_signals" == tag then result.traffic_lights = true end end -- main entry point for processsing a way function way_function(way, result) -- the intial filtering of ways based on presence of tags -- affects processing times significantly, because all ways -- have to be checked. -- to increase performance, prefetching and intial tag check -- is done in directly instead of via a handler. -- in general we should try to abort as soon as -- possible if the way is not routable, to avoid doing -- unnecessary work. this implies we should check things that -- commonly forbids access early, and handle edge cases later. -- data table for storing intermediate values during processing local data = { -- prefetch tags highway = way:get_value_by_key('highway'), bridge = way:get_value_by_key('bridge'), route = way:get_value_by_key('route'), leisure = way:get_value_by_key('leisure'), man_made = way:get_value_by_key('man_made'), railway = way:get_value_by_key('railway'), platform = way:get_value_by_key('platform'), amenity = way:get_value_by_key('amenity'), public_transport = way:get_value_by_key('public_transport') } -- perform an quick initial check and abort if the way is -- obviously not routable. here we require at least one -- of the prefetched tags to be present, ie. the data table -- cannot be empty if next(data) == nil then -- is the data table empty? return end local handlers = Sequence { -- set the default mode for this profile. if can be changed later -- in case it turns we're e.g. on a ferry 'handle_default_mode', -- check various tags that could indicate that the way is not -- routable. this includes things like status=impassable, -- toll=yes and oneway=reversible 'handle_blocked_ways', -- determine access status by checking our hierarchy of -- access tags, e.g: motorcar, motor_vehicle, vehicle 'handle_access', -- check whether forward/backward directons are routable 'handle_oneway', -- check whether forward/backward directons are routable 'handle_destinations', -- check whether we're using a special transport mode 'handle_ferries', 'handle_movables', -- compute speed taking into account way type, maxspeed tags, etc. 'handle_speed', 'handle_surface', -- handle turn lanes and road classification, used for guidance 'handle_classification', -- handle various other flags 'handle_roundabouts', 'handle_startpoint', -- set name, ref and pronunciation 'handle_names' } Handlers.run(handlers,way,result,data,profile) end function turn_function (turn) turn.duration = 0. if turn.direction_modifier == direction_modifier.u_turn then turn.duration = turn.duration + profile.u_turn_penalty end if turn.has_traffic_light then turn.duration = profile.traffic_light_penalty end if properties.weight_name == 'routability' then -- penalize turns from non-local access only segments onto local access only tags if not turn.source_restricted and turn.target_restricted then turn.weight = turn.weight + 3000 end end end
-- Foot profile api_version = 1 local find_access_tag = require("lib/access").find_access_tag local Set = require('lib/set') local Sequence = require('lib/sequence') local Handlers = require("lib/handlers") local next = next -- bind to local for speed properties.max_speed_for_map_matching = 40/3.6 -- kmph -> m/s properties.use_turn_restrictions = false properties.continue_straight_at_waypoint = false properties.weight_name = 'duration' --properties.weight_name = 'routability' -- Set to true if you need to call the node_function for every node. -- Generally can be left as false to avoid unnecessary Lua calls -- (which slow down pre-processing). properties.call_tagless_node_function = false local walking_speed = 5 local profile = { default_mode = mode.walking, default_speed = walking_speed, oneway_handling = 'specific', -- respect 'oneway:foot' but not 'oneway' traffic_light_penalty = 2, u_turn_penalty = 2, barrier_whitelist = Set { 'cycle_barrier', 'bollard', 'entrance', 'cattle_grid', 'border_control', 'toll_booth', 'sally_port', 'gate', 'no', 'kerb', 'block' }, access_tag_whitelist = Set { 'yes', 'foot', 'permissive', 'designated' }, access_tag_blacklist = Set { 'no', 'agricultural', 'forestry', 'private', 'delivery', }, restricted_access_tag_list = Set { }, restricted_highway_whitelist = Set { }, access_tags_hierarchy = Sequence { 'foot', 'access' }, restrictions = Sequence { 'foot' }, -- list of suffixes to suppress in name change instructions suffix_list = Set { 'N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW', 'North', 'South', 'West', 'East' }, avoid = Set { 'impassable', 'construction', 'proposed' }, speeds = Sequence { highway = { primary = walking_speed, primary_link = walking_speed, secondary = walking_speed, secondary_link = walking_speed, tertiary = walking_speed, tertiary_link = walking_speed, unclassified = walking_speed, residential = walking_speed, road = walking_speed, living_street = walking_speed, service = walking_speed, track = walking_speed, path = walking_speed, pedestrian = walking_speed, footway = walking_speed, pier = walking_speed, }, railway = { platform = walking_speed }, amenity = { parking = walking_speed, parking_entrance= walking_speed }, man_made = { pier = walking_speed }, leisure = { track = walking_speed } }, route_speeds = { ferry = 5 }, bridge_speeds = { }, surface_speeds = { fine_gravel = walking_speed*0.75, gravel = walking_speed*0.75, pebblestone = walking_speed*0.75, mud = walking_speed*0.5, sand = walking_speed*0.5 }, tracktype_speeds = { }, smoothness_speeds = { } } function node_function (node, result) -- parse access and barrier tags local access = find_access_tag(node, profile.access_tags_hierarchy) if access then if profile.access_tag_blacklist[access] then result.barrier = true end else local barrier = node:get_value_by_key("barrier") if barrier then -- make an exception for rising bollard barriers local bollard = node:get_value_by_key("bollard") local rising_bollard = bollard and "rising" == bollard if not profile.barrier_whitelist[barrier] and not rising_bollard then result.barrier = true end end end -- check if node is a traffic light local tag = node:get_value_by_key("highway") if "traffic_signals" == tag then result.traffic_lights = true end end -- main entry point for processsing a way function way_function(way, result) -- the intial filtering of ways based on presence of tags -- affects processing times significantly, because all ways -- have to be checked. -- to increase performance, prefetching and intial tag check -- is done in directly instead of via a handler. -- in general we should try to abort as soon as -- possible if the way is not routable, to avoid doing -- unnecessary work. this implies we should check things that -- commonly forbids access early, and handle edge cases later. -- data table for storing intermediate values during processing local data = { -- prefetch tags highway = way:get_value_by_key('highway'), bridge = way:get_value_by_key('bridge'), route = way:get_value_by_key('route'), leisure = way:get_value_by_key('leisure'), man_made = way:get_value_by_key('man_made'), railway = way:get_value_by_key('railway'), platform = way:get_value_by_key('platform'), amenity = way:get_value_by_key('amenity'), public_transport = way:get_value_by_key('public_transport') } -- perform an quick initial check and abort if the way is -- obviously not routable. here we require at least one -- of the prefetched tags to be present, ie. the data table -- cannot be empty if next(data) == nil then -- is the data table empty? return end local handlers = Sequence { -- set the default mode for this profile. if can be changed later -- in case it turns we're e.g. on a ferry 'handle_default_mode', -- check various tags that could indicate that the way is not -- routable. this includes things like status=impassable, -- toll=yes and oneway=reversible 'handle_blocked_ways', -- determine access status by checking our hierarchy of -- access tags, e.g: motorcar, motor_vehicle, vehicle 'handle_access', -- check whether forward/backward directons are routable 'handle_oneway', -- check whether forward/backward directons are routable 'handle_destinations', -- check whether we're using a special transport mode 'handle_ferries', 'handle_movables', -- compute speed taking into account way type, maxspeed tags, etc. 'handle_speed', 'handle_surface', -- handle turn lanes and road classification, used for guidance 'handle_classification', -- handle various other flags 'handle_roundabouts', 'handle_startpoint', -- set name, ref and pronunciation 'handle_names' } Handlers.run(handlers,way,result,data,profile) end function turn_function (turn) turn.duration = 0. if turn.direction_modifier == direction_modifier.u_turn then turn.duration = turn.duration + profile.u_turn_penalty end if turn.has_traffic_light then turn.duration = profile.traffic_light_penalty end if properties.weight_name == 'routability' then -- penalize turns from non-local access only segments onto local access only tags if not turn.source_restricted and turn.target_restricted then turn.weight = turn.weight + 3000 end end end
fix: update stepless profile
fix: update stepless profile
Lua
mit
urbica/galton,urbica/galton
475af843f1b08a305e5f1e1fca7946fa7a457560
lunamark/util.lua
lunamark/util.lua
-- (c) 2009-2011 John MacFarlane. Released under MIT license. -- See the file LICENSE in the source for details. --- Utility functions for lunamark. local M = {} local cosmo = require("cosmo") local rep = string.rep local insert = table.insert local lpeg = require("lpeg") local Cs, P, S, lpegmatch = lpeg.Cs, lpeg.P, lpeg.S, lpeg.match local any = lpeg.P(1) --- Find a template and return its contents (or `false` if -- not found). The template is sought first in the -- working directory, then in `templates`, then in -- `$HOME/.lunamark/templates`, then in the Windows -- `APPDATA` directory. function M.find_template(name) local base, ext = name:match("([^%.]*)(.*)") if (not ext or ext == "") and format then ext = "." .. format end local fname = base .. ext local file = io.open(fname, "read") if not file then file = io.open("templates/" .. fname, "read") end if not file then local home = os.getenv("HOME") if home then file = io.open(home .. "/.lunamark/templates/" .. fname, "read") end end if not file then local appdata = os.getenv("APPDATA") if appdata then file = io.open(appdata .. "/lunamark/templates/" .. fname, "read") end end if file then local data = file:read("*all") file:close() return data else return false, "Could not find template '" .. fname .. "'" end end --- Implements a `sepby` directive for cosmo templates. -- `$sepby{ myarray }[[$it]][[, ]]` will render the elements -- of `myarray` separated by commas. If `myarray` is a string, -- it will be treated as an array with one element. If it is -- `nil`, it will be treated as an empty array. function M.sepby(arg) local a = arg[1] if not a then a = {} elseif type(a) ~= "table" then a = {a} end for i,v in ipairs(a) do if i > 1 then cosmo.yield{_template=2} end cosmo.yield{it = a[i], _template=1} end end --[[ -- extend(t) returns a table that falls back to t for non-found values function M.extend(prototype) local newt = {} local metat = { __index = function(t,key) return prototype[key] end } setmetatable(newt, metat) return newt end --]] --- Print error message and exit. function M.err(msg, exit_code) io.stderr:write("lunamark: " .. msg .. "\n") os.exit(exit_code or 1) end --- Shallow table copy including metatables. function M.table_copy(t) local u = { } for k, v in pairs(t) do u[k] = v end return setmetatable(u, getmetatable(t)) end --- Expand tabs in a line of text. -- `s` is assumed to be a single line of text. -- From *Programming Lua*. function M.expand_tabs_in_line(s, tabstop) local tab = tabstop or 4 local corr = 0 return (s:gsub("()\t", function(p) local sp = tab - (p - 1 + corr)%tab corr = corr - 1 + sp return rep(" ",sp) end)) end --- Walk a rope `t`, applying a function `f` to each leaf element in order. -- A rope is an array whose elements may be ropes, strings, numbers, -- or functions. If a leaf element is a function, call it and get the return value -- before proceeding. local function walk(t, f) local typ = type(t) if typ == "string" then f(t) elseif typ == "table" then local i = 1 local n n = t[i] while n do walk(n, f) i = i + 1 n = t[i] end elseif typ == "function" then local ok, val = pcall(t) if ok then walk(val,f) end else f(tostring(t)) end end M.walk = walk --- Flatten an array `ary`. local function flatten(ary) local new = {} for i,v in ipairs(ary) do if type(v) == "table" then for j,w in ipairs(flatten(v)) do new[#new + 1] = w end else new[#new + 1] = v end end return new end M.flatten = flatten --- Convert a rope to a string. local function rope_to_string(rope) local buffer = {} walk(rope, function(x) buffer[#buffer + 1] = x end) return table.concat(buffer) end M.rope_to_string = rope_to_string -- assert(rope_to_string{"one","two"} == "onetwo") -- assert(rope_to_string{"one",{"1","2"},"three"} == "one12three") --- Return the last item in a rope. local function rope_last(rope) if #rope == 0 then return nil else local l = rope[#rope] if type(l) == "table" then return rope_last(l) else return l end end end -- assert(rope_last{"one","two"} == "two") -- assert(rope_last{} == nil) -- assert(rope_last{"one",{"2",{"3","4"}}} == "4") M.rope_last = rope_last --- Given an array `ary`, return a new array with `x` -- interspersed between elements of `ary`. function M.intersperse(ary, x) local new = {} local l = #ary for i,v in ipairs(ary) do local n = #new new[n + 1] = v if i ~= l then new[n + 2] = x end end return new end --- Given an array `ary`, return a new array with each -- element `x` of `ary` replaced by `f(x)`. function M.map(ary, f) local new = {} for i,v in ipairs(ary) do new[i] = f(v) end return new end --- Given a table `char_escapes` mapping escapable characters onto -- their escaped versions and optionally `string_escapes` mapping -- escapable strings (or multibyte UTF-8 characters) onto their -- escaped versions, returns a function that escapes a string. -- This function uses lpeg and is faster than gsub. function M.escaper(char_escapes, string_escapes) local char_escapes_list = "" for i,_ in pairs(char_escapes) do char_escapes_list = char_escapes_list .. i end local escapable = S(char_escapes_list) / char_escapes if string_escapes then for k,v in pairs(string_escapes) do escapable = P(k) / v + escapable end end local escape_string = Cs((escapable + any)^0) return function(s) return lpegmatch(escape_string, s) end end return M
-- (c) 2009-2011 John MacFarlane. Released under MIT license. -- See the file LICENSE in the source for details. --- Utility functions for lunamark. local M = {} local cosmo = require("cosmo") local rep = string.rep local lpeg = require("lpeg") local Cs, P, S, lpegmatch = lpeg.Cs, lpeg.P, lpeg.S, lpeg.match local any = lpeg.P(1) --- Find a template and return its contents (or `false` if -- not found). The template is sought first in the -- working directory, then in `templates`, then in -- `$HOME/.lunamark/templates`, then in the Windows -- `APPDATA` directory. function M.find_template(name) local base, ext = name:match("([^%.]*)(.*)") local fname = base .. ext local file = io.open(fname, "read") if not file then file = io.open("templates/" .. fname, "read") end if not file then local home = os.getenv("HOME") if home then file = io.open(home .. "/.lunamark/templates/" .. fname, "read") end end if not file then local appdata = os.getenv("APPDATA") if appdata then file = io.open(appdata .. "/lunamark/templates/" .. fname, "read") end end if file then local data = file:read("*all") file:close() return data else return false, "Could not find template '" .. fname .. "'" end end --- Implements a `sepby` directive for cosmo templates. -- `$sepby{ myarray }[[$it]][[, ]]` will render the elements -- of `myarray` separated by commas. If `myarray` is a string, -- it will be treated as an array with one element. If it is -- `nil`, it will be treated as an empty array. function M.sepby(arg) local a = arg[1] if not a then a = {} elseif type(a) ~= "table" then a = {a} end for i in ipairs(a) do if i > 1 then cosmo.yield{_template=2} end cosmo.yield{it = a[i], _template=1} end end --[[ -- extend(t) returns a table that falls back to t for non-found values function M.extend(prototype) local newt = {} local metat = { __index = function(t,key) return prototype[key] end } setmetatable(newt, metat) return newt end --]] --- Print error message and exit. function M.err(msg, exit_code) io.stderr:write("lunamark: " .. msg .. "\n") os.exit(exit_code or 1) end --- Shallow table copy including metatables. function M.table_copy(t) local u = { } for k, v in pairs(t) do u[k] = v end return setmetatable(u, getmetatable(t)) end --- Expand tabs in a line of text. -- `s` is assumed to be a single line of text. -- From *Programming Lua*. function M.expand_tabs_in_line(s, tabstop) local tab = tabstop or 4 local corr = 0 return (s:gsub("()\t", function(p) local sp = tab - (p - 1 + corr)%tab corr = corr - 1 + sp return rep(" ",sp) end)) end --- Walk a rope `t`, applying a function `f` to each leaf element in order. -- A rope is an array whose elements may be ropes, strings, numbers, -- or functions. If a leaf element is a function, call it and get the return value -- before proceeding. local function walk(t, f) local typ = type(t) if typ == "string" then f(t) elseif typ == "table" then local i = 1 local n n = t[i] while n do walk(n, f) i = i + 1 n = t[i] end elseif typ == "function" then local ok, val = pcall(t) if ok then walk(val,f) end else f(tostring(t)) end end M.walk = walk --- Flatten an array `ary`. local function flatten(ary) local new = {} for _,v in ipairs(ary) do if type(v) == "table" then for _,w in ipairs(flatten(v)) do new[#new + 1] = w end else new[#new + 1] = v end end return new end M.flatten = flatten --- Convert a rope to a string. local function rope_to_string(rope) local buffer = {} walk(rope, function(x) buffer[#buffer + 1] = x end) return table.concat(buffer) end M.rope_to_string = rope_to_string -- assert(rope_to_string{"one","two"} == "onetwo") -- assert(rope_to_string{"one",{"1","2"},"three"} == "one12three") --- Return the last item in a rope. local function rope_last(rope) if #rope == 0 then return nil else local l = rope[#rope] if type(l) == "table" then return rope_last(l) else return l end end end -- assert(rope_last{"one","two"} == "two") -- assert(rope_last{} == nil) -- assert(rope_last{"one",{"2",{"3","4"}}} == "4") M.rope_last = rope_last --- Given an array `ary`, return a new array with `x` -- interspersed between elements of `ary`. function M.intersperse(ary, x) local new = {} local l = #ary for i,v in ipairs(ary) do local n = #new new[n + 1] = v if i ~= l then new[n + 2] = x end end return new end --- Given an array `ary`, return a new array with each -- element `x` of `ary` replaced by `f(x)`. function M.map(ary, f) local new = {} for i,v in ipairs(ary) do new[i] = f(v) end return new end --- Given a table `char_escapes` mapping escapable characters onto -- their escaped versions and optionally `string_escapes` mapping -- escapable strings (or multibyte UTF-8 characters) onto their -- escaped versions, returns a function that escapes a string. -- This function uses lpeg and is faster than gsub. function M.escaper(char_escapes, string_escapes) local char_escapes_list = "" for i,_ in pairs(char_escapes) do char_escapes_list = char_escapes_list .. i end local escapable = S(char_escapes_list) / char_escapes if string_escapes then for k,v in pairs(string_escapes) do escapable = P(k) / v + escapable end end local escape_string = Cs((escapable + any)^0) return function(s) return lpegmatch(escape_string, s) end end return M
lunamark.util: fix luacheck warnings
lunamark.util: fix luacheck warnings
Lua
mit
jgm/lunamark,simoncozens/lunamark,jgm/lunamark,simoncozens/lunamark,jgm/lunamark,simoncozens/lunamark
f729aa71a7a73fbb7116bb5eb195f35412c98c78
plugins/mod_private.lua
plugins/mod_private.lua
local st = require "util.stanza" local send = require "core.sessionmanager".send_to_session local jid_split = require "util.jid".split; local datamanager = require "util.datamanager" add_iq_handler("c2s", "jabber:iq:private", function (session, stanza) local type = stanza.attr.type; local query = stanza.tags[1]; if (type == "get" or type == "set") and query.name == "query" then local node, host = jid_split(stanza.attr.to); if not(node or host) or (node == session.username and host == session.host) then node, host = session.username, session.host; if #query.tags == 1 then local tag = query.tags[1]; local key = tag.name..":"..tag.attr.xmlns; local data = datamanager.load(node, host, "private"); if stanza.attr.type == "get" then if data and data[key] then send(session, st.reply(stanza):tag("query", {xmlns = "jabber:iq:private"}):add_child(st.deserialize(data[key]))); else send(session, st.reply(stanza):add_child(stanza.tags[1])); end else -- set if not data then data = {}; end; if #tag == 0 then data[key] = nil; else data[key] = st.preserialize(tag); end -- TODO delete datastore if empty if datamanager.store(node, host, "private", data) then send(session, st.reply(stanza)); else send(session, st.error_reply(stanza, "wait", "internal-server-error")); end end else send(session, st.error_reply(stanza, "modify", "bad-format")); end else send(session, st.error_reply(stanza, "cancel", "forbidden")); end end end);
local st = require "util.stanza" local jid_split = require "util.jid".split; local datamanager = require "util.datamanager" add_iq_handler("c2s", "jabber:iq:private", function (session, stanza) local type = stanza.attr.type; local query = stanza.tags[1]; if (type == "get" or type == "set") and query.name == "query" then local node, host = jid_split(stanza.attr.to); if not(node or host) or (node == session.username and host == session.host) then node, host = session.username, session.host; if #query.tags == 1 then local tag = query.tags[1]; local key = tag.name..":"..tag.attr.xmlns; local data = datamanager.load(node, host, "private"); if stanza.attr.type == "get" then if data and data[key] then session.send(st.reply(stanza):tag("query", {xmlns = "jabber:iq:private"}):add_child(st.deserialize(data[key]))); else session.send(st.reply(stanza):add_child(stanza.tags[1])); end else -- set if not data then data = {}; end; if #tag == 0 then data[key] = nil; else data[key] = st.preserialize(tag); end -- TODO delete datastore if empty if datamanager.store(node, host, "private", data) then session.send(st.reply(stanza)); else session.send(st.error_reply(stanza, "wait", "internal-server-error")); end end else session.send(st.error_reply(stanza, "modify", "bad-format")); end else session.send(st.error_reply(stanza, "cancel", "forbidden")); end end end);
Fixed mod_private to use session.send for sending stanzas
Fixed mod_private to use session.send for sending stanzas
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
7c3cab36c18a9f35afa905a24f63ec84b7846c62
lib/lux/class.lua
lib/lux/class.lua
--[[ -- -- Copyright (c) 2013-2016 Wilson Kazuo Mizutani -- -- This software is provided 'as-is', without any express or implied -- warranty. In no event will the authors be held liable for any damages -- arising from the use of this software. -- -- Permission is granted to anyone to use this software for any purpose, -- including commercial applications, and to alter it and redistribute it -- freely, subject to the following restrictions: -- -- 1. The origin of this software must not be misrepresented; you must not -- claim that you wrote the original software. If you use this software -- in a product, an acknowledgment in the product documentation would be -- appreciated but is not required. -- -- 2. Altered source versions must be plainly marked as such, and must not be -- misrepresented as being the original software. -- -- 3. This notice may not be removed or altered from any source -- distribution. -- --]] --- A class-based implementation object oriented programming. -- Ironically, this is actually a prototype, which means it inherits from -- @{lux.prototype}, but otherwise provides its own mechanism for OOP. -- Be sure to check @{instance}, @{inherit} and @{super} usages. -- -- ***This module requires macro takeover in order to work properly*** -- -- @usage -- local MyClass = require 'lux.class' :new{} -- @prototype lux.class local class = require 'lux.prototype' :new {} --- Defines how an instance of the class should be constructed. -- This function is supposed to only be overriden, not called from the user's -- side. By populating the `_ENV` parameter provided in this factory-like -- strategy method is what creates class instances in this OOP feature. -- This is actually done automatically: every "global" variable or function -- you define inside this function is instead stored as a corresponding object -- field. -- -- @tparam object _ENV -- The to-be-constructed object. Its name must be exactly `_ENV` -- -- @param ... -- Arguments required by the construction of objects from the current class -- -- @see some.lua -- -- @usage -- local MyClass = require 'lux.class' :new{} -- local print = print -- must explicitly enclosure dependencies -- function MyClass:instance (obj, x) -- -- public field -- obj.y = 1337 -- -- private field -- local a_number = 42 -- -- public method -- function obj.show () -- print(a_number + x) -- end -- end -- -- myobj = MyClass(8001) -- -- call without colons! -- myobj.show() function class:instance (_ENV, ...) -- Does nothing end --- Makes this class inherit from another. -- This guarantess that instances from the former are also instances from the -- latter. The semantics differs from that of inheritance through prototyping! -- Also, it is necessary to call @{super} inside the current class' -- @{instance} definition method since there is no way of guessing how the -- parent class' constructor should be called. -- -- @tparam class another_class -- The class being inherited from -- -- @see class:super -- -- @usage -- local class = require 'lux.class' -- local ParentClass = class:new{} -- local ChildClass = class:new{} -- ChildClass:inherit(ParentClass) function class:inherit (another_class) assert(not self.__parent, "Multiple inheritance not allowed!") assert(another_class:__super() == class, "Must inherit a class!") self.__parent = another_class end local makeInstance function makeInstance (ofclass, obj, ...) ofclass:instance(obj, ...) end local operator_meta = {} function operator_meta:__newindex (key, value) rawset(self, "__"..key, value) end --- The class constructor. -- This is how someone actually instantiates objects from this class system. -- After having created a new class and defined its @{instance} method, calling -- the class itself behaves as expected by calling the constructor that will -- use the @{instance} method to create the object. -- -- @param ... -- The constructor parameters as specified in the @{instance} -- -- @treturn object -- A new instance from the current class. function class:__call (...) local obj = { __class = self, __extended = not self.__parent, __operator = setmetatable({}, operator_meta) } makeInstance(self, obj, ...) assert(obj.__extended, "Missing call to parent constructor!") return setmetatable(obj, obj.__operator) end class.__init = { __call = class.__call } --- Calls the parent class' constructor. -- Should only be called inside this class' @{instance} definition method when -- it inherits from another class. -- -- @tparam object obj -- The object being constructed by the child class, that is, the `_ENV` -- parameter passed to @{instance} -- -- @param ... -- The parent class' constructor parameters -- -- @see class:inherit -- -- @usage -- -- After ChildClass inherited ParentClass -- function ChildClass:instance (obj, x, y) -- self:super(obj, x + y) -- parent's constructor parameters -- -- Finish instancing -- end function class:super (obj, ...) assert(not obj.__extended, "Already called parent constructor!") makeInstance(self.__parent, obj, ...) obj.__extended = true end return class
--[[ -- -- Copyright (c) 2013-2016 Wilson Kazuo Mizutani -- -- This software is provided 'as-is', without any express or implied -- warranty. In no event will the authors be held liable for any damages -- arising from the use of this software. -- -- Permission is granted to anyone to use this software for any purpose, -- including commercial applications, and to alter it and redistribute it -- freely, subject to the following restrictions: -- -- 1. The origin of this software must not be misrepresented; you must not -- claim that you wrote the original software. If you use this software -- in a product, an acknowledgment in the product documentation would be -- appreciated but is not required. -- -- 2. Altered source versions must be plainly marked as such, and must not be -- misrepresented as being the original software. -- -- 3. This notice may not be removed or altered from any source -- distribution. -- --]] --- A class-based implementation object oriented programming. -- Ironically, this is actually a prototype, which means it inherits from -- @{lux.prototype}, but otherwise provides its own mechanism for OOP. -- Be sure to check @{instance}, @{inherit} and @{super} usages. -- -- ***This module requires macro takeover in order to work properly*** -- -- @usage -- local MyClass = require 'lux.class' :new{} -- @prototype lux.class local class = require 'lux.prototype' :new {} --- Defines how an instance of the class should be constructed. -- This function is supposed to only be overriden, not called from the user's -- side. By populating the `_ENV` parameter provided in this factory-like -- strategy method is what creates class instances in this OOP feature. -- This is actually done automatically: every "global" variable or function -- you define inside this function is instead stored as a corresponding object -- field. -- -- @tparam object obj -- The to-be-constructed object. On Lua5.2+, you may name it _ENV if you know -- what you are doing. -- -- @param ... -- Arguments required by the construction of objects from the current class -- -- @see some.lua -- -- @usage -- local MyClass = require 'lux.class' :new{} -- local print = print -- must explicitly enclosure dependencies -- function MyClass:instance (obj, x) -- -- public field -- obj.y = 1337 -- -- private field -- local a_number = 42 -- -- public method -- function obj.show () -- print(a_number + x) -- end -- end -- -- myobj = MyClass(8001) -- -- call without colons! -- myobj.show() function class:instance (_ENV, ...) -- Does nothing end --- Makes this class inherit from another. -- This guarantess that instances from the former are also instances from the -- latter. The semantics differs from that of inheritance through prototyping! -- Also, it is necessary to call @{super} inside the current class' -- @{instance} definition method since there is no way of guessing how the -- parent class' constructor should be called. -- -- @tparam class another_class -- The class being inherited from -- -- @see class:super -- -- @usage -- local class = require 'lux.class' -- local ParentClass = class:new{} -- local ChildClass = class:new{} -- ChildClass:inherit(ParentClass) function class:inherit (another_class) assert(not self.__parent, "Multiple inheritance not allowed!") assert(another_class:__super() == class, "Must inherit a class!") self.__parent = another_class end local makeInstance function makeInstance (ofclass, obj, ...) ofclass:instance(obj, ...) end local operator_meta = {} function operator_meta:__newindex (key, value) rawset(self, "__"..key, value) end --- The class constructor. -- This is how someone actually instantiates objects from this class system. -- After having created a new class and defined its @{instance} method, calling -- the class itself behaves as expected by calling the constructor that will -- use the @{instance} method to create the object. -- -- @param ... -- The constructor parameters as specified in the @{instance} -- -- @treturn object -- A new instance from the current class. function class:__call (...) local obj = { __class = self, __extended = not self.__parent, __operator = setmetatable({}, operator_meta) } makeInstance(self, obj, ...) assert(obj.__extended, "Missing call to parent constructor!") return setmetatable(obj, obj.__operator) end class.__init = { __call = class.__call } --- Calls the parent class' constructor. -- Should only be called inside this class' @{instance} definition method when -- it inherits from another class. -- -- @tparam object obj -- The object being constructed by the child class, that is, the `_ENV` -- parameter passed to @{instance} -- -- @param ... -- The parent class' constructor parameters -- -- @see class:inherit -- -- @usage -- -- After ChildClass inherited ParentClass -- function ChildClass:instance (obj, x, y) -- self:super(obj, x + y) -- parent's constructor parameters -- -- Finish instancing -- end function class:super (obj, ...) assert(not obj.__extended, "Already called parent constructor!") makeInstance(self.__parent, obj, ...) obj.__extended = true end return class
Fix documentation regarding class:instance
Fix documentation regarding class:instance Update to new parameter semantics
Lua
mit
Kazuo256/luxproject
0b821de90868cd2c421fd74fe58cf2d64cf4ee49
serializer.lua
serializer.lua
local function serialize(obj, indent, asArray) local s = "" indent = indent or '' for k,v in pairs(obj) do local t = type(v) if t == "table" then -- what kind of table, one like a list or a like a map? if v[1] == nil then -- map if asArray then s = s .. indent .. t .. "=" else s = s .. indent .. k .. ":" .. t .. "=" end s = s .. "{\n" .. serialize(v, indent .. ' ') .. indent .. "}\n" else -- list if asArray then s = s .. indent .. "list=" else s = s .. indent .. k .. ":list=" end s = s .. "[\n" .. serialize(v, indent .. ' ', true) .. indent .. "]\n" end elseif t == "boolean" then if asArray then s = s .. indent .. t .. "=" else s = s .. indent .. k .. ":" .. t .. "=" end if v then s = s .. "true\n" else s = s .. "false\n" end else if asArray then s = s .. indent .. t .. "=" else s = s .. indent .. k .. ":" .. t .. "=" end s = s .. v .. "\n" end end return s end local function deserializeFromLines(lines, asArray) local result = {} if #lines == 0 then return result end local i = 1 repeat local line = lines[i] local indent, k, t, v if asArray then k = i indent, t, v = string.match(line, '(%s*)([^=]+)=(.*)') else indent, k, t, v = string.match(line, '(%s*)([^:%s]+):(.+)=(.*)') end if t == "string" then result[k] = v elseif t == "number" then result[k] = tonumber(v) elseif t == "boolean" then result[k] = v == "true" elseif t == "table" then -- find all the lines containing this nested table local tableLines = {} repeat i = i + 1 line = lines[i] tableLines[#tableLines+1] = line until (line == (indent .. "}")) table.remove(tableLines, #tableLines) result[k] = deserializeFromLines(tableLines) elseif t == "list" then -- find all the lines containing this nested list local listLines = {} repeat i = i + 1 line = lines[i] listLines[#listLines+1] = line until (line == (indent .. "]")) table.remove(listLines, #listLines) result[k] = deserializeFromLines(listLines, true) end i = i + 1 until i > #lines return result end local function deserialize(str) local lines = {} for line in string.gmatch(str, "([^\n]+)") do lines[#lines + 1] = line end return deserializeFromLines(lines) end return { serialize = serialize, deserialize = deserialize, deserializeLines = deserializeFromLines, }
local function serialize(obj, indent, asArray) local s = "" indent = indent or '' if asArray then for _,v in ipairs(obj) do local t = type(v) if t == "table" then -- what kind of table, one like a list or a like a map? if v[1] == nil then -- map s = s .. indent .. t .. "=" s = s .. "{\n" .. serialize(v, indent .. ' ') .. indent .. "}\n" else -- list s = s .. indent .. "list=" s = s .. "[\n" .. serialize(v, indent .. ' ', true) .. indent .. "]\n" end elseif t == "boolean" then s = s .. indent .. t .. "=" if v then s = s .. "true\n" else s = s .. "false\n" end else s = s .. indent .. t .. "=" s = s .. v .. "\n" end end else for k,v in pairs(obj) do local t = type(v) if t == "table" then -- what kind of table, one like a list or a like a map? if v[1] == nil then -- map s = s .. indent .. k .. ":" .. t .. "=" s = s .. "{\n" .. serialize(v, indent .. ' ') .. indent .. "}\n" else -- list s = s .. indent .. k .. ":list=" s = s .. "[\n" .. serialize(v, indent .. ' ', true) .. indent .. "]\n" end elseif t == "boolean" then s = s .. indent .. k .. ":" .. t .. "=" if v then s = s .. "true\n" else s = s .. "false\n" end else s = s .. indent .. k .. ":" .. t .. "=" s = s .. v .. "\n" end end end return s end local function deserializeFromLines(lines, asArray) local result = {} if #lines == 0 then return result end local i = 1 repeat local line = lines[i] if string.len(line) > 0 then local indent, k, t, v if asArray then indent, t, v = string.match(line, '(%s*)([^=]+)=(.*)') else indent, k, t, v = string.match(line, '(%s*)([^:%s]+):(.+)=(.*)') end if t == "string" then v = v elseif t == "number" then v = tonumber(v) elseif t == "boolean" then v = v == "true" elseif t == "table" then -- find all the lines containing this nested table local tableLines = {} repeat i = i + 1 line = lines[i] tableLines[#tableLines+1] = line until (line == (indent .. "}")) table.remove(tableLines, #tableLines) v = deserializeFromLines(tableLines) elseif t == "list" then -- find all the lines containing this nested list local listLines = {} repeat i = i + 1 line = lines[i] listLines[#listLines+1] = line until (line == (indent .. "]")) table.remove(listLines, #listLines) v = deserializeFromLines(listLines, true) end if asArray then result[#result+1] = v else result[k] = v end end i = i + 1 until i > #lines return result end local function deserialize(str) local lines = {} for line in string.gmatch(str, "([^\n]+)") do lines[#lines + 1] = line end return deserializeFromLines(lines) end local function clone(o) return deserialize(serialize(o)) end local function deserializeFile(path) local l = io.lines(path) if not l then return nil, "could not open file" end local lines = {} for line in l do lines[#lines+1] = line end return deserializeFromLines(lines) end return { serialize = serialize, deserialize = deserialize, deserializeLines = deserializeFromLines, deserializeFile = deserializeFile, clone = clone }
fixes all kinds of problems deserializing lists, adds fromFile and clone
fixes all kinds of problems deserializing lists, adds fromFile and clone
Lua
apache-2.0
InfinitiesLoop/oclib
7e9a481871a1e332898f91e38387fc25016d076b
agents/monitoring/tests/fixtures/protocol/server.lua
agents/monitoring/tests/fixtures/protocol/server.lua
local net = require('net') local JSON = require('json') local fixtures = require('./') local LineEmitter = require('line-emitter').LineEmitter local table = require('table') local tls = require('tls') local timer = require('timer') local string = require('string') local math = require('math') local table = require('table') local http = require("http") local url = require('url') local lineEmitter = LineEmitter:new() local ports = {50041, 50051, 50061} local opts = {} local function set_option(options, name, default) options[name] = process.env[string.upper(name)] or default end set_option(opts, "send_schedule_changed_initial", 2000) set_option(opts, "send_schedule_changed_interval", 60000) set_option(opts, "destroy_connection_jitter", 60000) set_option(opts, "destroy_connection_base", 60000) set_option(opts, "listen_ip", '127.0.0.1') set_option(opts, "perform_client_disconnect", 'true') set_option(opts, "rate_limit", 3000) set_option(opts, "rate_limit_reset", 86400) -- Reset limit in 24 hours local keyPem = [[ -----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQDx3wdzpq2rvwm3Ucun1qAD/ClB+wW+RhR1nVix286QvaNqePAd CAwwLL82NqXcVQRbQ4s95splQnwvjgkFdKVXFTjPKKJI5aV3wSRN61EBVPdYpCre 535yfG/uDysZFCnVQdnCZ1tnXAR8BirxCNjHqbVyIyBGjsNoNCEPb2R35QIDAQAB AoGBAJNem9C4ftrFNGtQ2DB0Udz7uDuucepkErUy4MbFsc947GfENjDKJXr42Kx0 kYx09ImS1vUpeKpH3xiuhwqe7tm4FsCBg4TYqQle14oxxm7TNeBwwGC3OB7hiokb aAjbPZ1hAuNs6ms3Ybvvj6Lmxzx42m8O5DXCG2/f+KMvaNUhAkEA/ekrOsWkNoW9 2n3m+msdVuxeek4B87EoTOtzCXb1dybIZUVv4J48VAiM43hhZHWZck2boD/hhwjC M5NWd4oY6QJBAPPcgBVNdNZSZ8hR4ogI4nzwWrQhl9MRbqqtfOn2TK/tjMv10ALg lPmn3SaPSNRPKD2hoLbFuHFERlcS79pbCZ0CQQChX3PuIna/gDitiJ8oQLOg7xEM wk9TRiDK4kl2lnhjhe6PDpaQN4E4F0cTuwqLAoLHtrNWIcOAQvzKMrYdu1MhAkBm Et3qDMnjDAs05lGT72QeN90/mPAcASf5eTTYGahv21cb6IBxM+AnwAPpqAAsHhYR 9h13Y7uYbaOjvuF23LRhAkBoI9eaSMn+l81WXOVUHnzh3ZwB4GuTyxMXXNOhuiFd 0z4LKAMh99Z4xQmqSoEkXsfM4KPpfhYjF/bwIcP5gOei -----END RSA PRIVATE KEY----- ]] local certPem = [[ -----BEGIN CERTIFICATE----- MIIDXDCCAsWgAwIBAgIJAKL0UG+mRkSPMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNV BAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEGA1UEBxMKUmh5cyBKb25l czEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVzdCBUTFMgQ2VydGlmaWNh dGUxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0wOTExMTEwOTUyMjJaFw0yOTExMDYw OTUyMjJaMH0xCzAJBgNVBAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEG A1UEBxMKUmh5cyBKb25lczEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVz dCBUTFMgQ2VydGlmaWNhdGUxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG 9w0BAQEFAAOBjQAwgYkCgYEA8d8Hc6atq78Jt1HLp9agA/wpQfsFvkYUdZ1YsdvO kL2janjwHQgMMCy/Njal3FUEW0OLPebKZUJ8L44JBXSlVxU4zyiiSOWld8EkTetR AVT3WKQq3ud+cnxv7g8rGRQp1UHZwmdbZ1wEfAYq8QjYx6m1ciMgRo7DaDQhD29k d+UCAwEAAaOB4zCB4DAdBgNVHQ4EFgQUL9miTJn+HKNuTmx/oMWlZP9cd4QwgbAG A1UdIwSBqDCBpYAUL9miTJn+HKNuTmx/oMWlZP9cd4ShgYGkfzB9MQswCQYDVQQG EwJVSzEUMBIGA1UECBMLQWNrbmFjayBMdGQxEzARBgNVBAcTClJoeXMgSm9uZXMx EDAOBgNVBAoTB25vZGUuanMxHTAbBgNVBAsTFFRlc3QgVExTIENlcnRpZmljYXRl MRIwEAYDVQQDEwlsb2NhbGhvc3SCCQCi9FBvpkZEjzAMBgNVHRMEBTADAQH/MA0G CSqGSIb3DQEBBQUAA4GBADRXXA2xSUK5W1i3oLYWW6NEDVWkTQ9RveplyeS9MOkP e7yPcpz0+O0ZDDrxR9chAiZ7fmdBBX1Tr+pIuCrG/Ud49SBqeS5aMJGVwiSd7o1n dhU2Sz3Q60DwJEL1VenQHiVYlWWtqXBThe9ggqRPnCfsCRTP8qifKkjk45zWPcpN -----END CERTIFICATE----- ]] local options = { cert = certPem, key = keyPem } local respond = function(log, client, payload) local destroy = false -- skip responses to requests if payload.method == nil then return end local response_method = payload.method .. '.response' local response = JSON.parse(fixtures[response_method]) local response_out = nil -- Handle rate limit logic client.rate_limit = client.rate_limit - 1 if client.rate_limit <= 0 then response = JSON.parse(fixtures['rate-limiting']['rate-limit-error']) destroy = true end response.target = payload.source response.source = payload.target response.id = payload.id log("Sending response:") response_out = JSON.stringify(response) response_out:gsub("\n", " ") client:write(response_out .. '\n') if destroy == true then client:destroy() end return destroy end local send_schedule_changed = function(log, client) local request = fixtures['check_schedule.changed.request'] log("Sending request:") p(JSON.parse(request)) client:write(request .. '\n') end local function clear_timers(timer_ids) for k, v in pairs(timer_ids) do if v._closed ~= true then timer.clearTimer(v) end end end local function start_fixture_server(options, port) local log = function(...) print(port .. ": " .. ...) end local server = tls.createServer(options, function (client) local destroyed = false local timers = {} client.rate_limit = opts.rate_limit client:pipe(lineEmitter) lineEmitter:on('data', function(line) local payload = JSON.parse(line) log("Got payload:") p(payload) destroyed = respond(log, client, payload) if destroyed == true then clear_timers(timers) end end) -- Reset rate limit counter timer.setTimeout(opts.rate_limit_reset, function() client.rate_limit = opts.rate_limit end) timer.setTimeout(opts.send_schedule_changed_initial, function() send_schedule_changed(log, client) end) table.insert(timers, timer.setInterval(opts.send_schedule_changed_interval, function() send_schedule_changed(log, client) end) ) -- Disconnect the agent after some random number of seconds -- to exercise reconnect logic if opts.perform_client_disconnect == 'true' then local disconnect_time = opts.destroy_connection_base + math.floor(math.random() * opts.destroy_connection_jitter) timer.setTimeout(disconnect_time, function() log("Destroying connection after " .. disconnect_time .. "ms connected") client:destroy() end) end end):listen(port, opts.listen_ip) return server end -- There is no cleanup code for the server here as the process for exiting is -- to just ctrl+c the runner or kill the process. for k, v in pairs(ports) do start_fixture_server(options, v) print("TCP echo server listening on port " .. v) end
local net = require('net') local JSON = require('json') local fixtures = require('./') local LineEmitter = require('line-emitter').LineEmitter local table = require('table') local tls = require('tls') local timer = require('timer') local string = require('string') local math = require('math') local table = require('table') local http = require("http") local url = require('url') local ports = {50041, 50051, 50061} local opts = {} local function set_option(options, name, default) options[name] = process.env[string.upper(name)] or default end set_option(opts, "send_schedule_changed_initial", 2000) set_option(opts, "send_schedule_changed_interval", 60000) set_option(opts, "destroy_connection_jitter", 60000) set_option(opts, "destroy_connection_base", 60000) set_option(opts, "listen_ip", '127.0.0.1') set_option(opts, "perform_client_disconnect", 'true') set_option(opts, "rate_limit", 3000) set_option(opts, "rate_limit_reset", 86400) -- Reset limit in 24 hours local keyPem = [[ -----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQDx3wdzpq2rvwm3Ucun1qAD/ClB+wW+RhR1nVix286QvaNqePAd CAwwLL82NqXcVQRbQ4s95splQnwvjgkFdKVXFTjPKKJI5aV3wSRN61EBVPdYpCre 535yfG/uDysZFCnVQdnCZ1tnXAR8BirxCNjHqbVyIyBGjsNoNCEPb2R35QIDAQAB AoGBAJNem9C4ftrFNGtQ2DB0Udz7uDuucepkErUy4MbFsc947GfENjDKJXr42Kx0 kYx09ImS1vUpeKpH3xiuhwqe7tm4FsCBg4TYqQle14oxxm7TNeBwwGC3OB7hiokb aAjbPZ1hAuNs6ms3Ybvvj6Lmxzx42m8O5DXCG2/f+KMvaNUhAkEA/ekrOsWkNoW9 2n3m+msdVuxeek4B87EoTOtzCXb1dybIZUVv4J48VAiM43hhZHWZck2boD/hhwjC M5NWd4oY6QJBAPPcgBVNdNZSZ8hR4ogI4nzwWrQhl9MRbqqtfOn2TK/tjMv10ALg lPmn3SaPSNRPKD2hoLbFuHFERlcS79pbCZ0CQQChX3PuIna/gDitiJ8oQLOg7xEM wk9TRiDK4kl2lnhjhe6PDpaQN4E4F0cTuwqLAoLHtrNWIcOAQvzKMrYdu1MhAkBm Et3qDMnjDAs05lGT72QeN90/mPAcASf5eTTYGahv21cb6IBxM+AnwAPpqAAsHhYR 9h13Y7uYbaOjvuF23LRhAkBoI9eaSMn+l81WXOVUHnzh3ZwB4GuTyxMXXNOhuiFd 0z4LKAMh99Z4xQmqSoEkXsfM4KPpfhYjF/bwIcP5gOei -----END RSA PRIVATE KEY----- ]] local certPem = [[ -----BEGIN CERTIFICATE----- MIIDXDCCAsWgAwIBAgIJAKL0UG+mRkSPMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNV BAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEGA1UEBxMKUmh5cyBKb25l czEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVzdCBUTFMgQ2VydGlmaWNh dGUxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0wOTExMTEwOTUyMjJaFw0yOTExMDYw OTUyMjJaMH0xCzAJBgNVBAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEG A1UEBxMKUmh5cyBKb25lczEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVz dCBUTFMgQ2VydGlmaWNhdGUxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG 9w0BAQEFAAOBjQAwgYkCgYEA8d8Hc6atq78Jt1HLp9agA/wpQfsFvkYUdZ1YsdvO kL2janjwHQgMMCy/Njal3FUEW0OLPebKZUJ8L44JBXSlVxU4zyiiSOWld8EkTetR AVT3WKQq3ud+cnxv7g8rGRQp1UHZwmdbZ1wEfAYq8QjYx6m1ciMgRo7DaDQhD29k d+UCAwEAAaOB4zCB4DAdBgNVHQ4EFgQUL9miTJn+HKNuTmx/oMWlZP9cd4QwgbAG A1UdIwSBqDCBpYAUL9miTJn+HKNuTmx/oMWlZP9cd4ShgYGkfzB9MQswCQYDVQQG EwJVSzEUMBIGA1UECBMLQWNrbmFjayBMdGQxEzARBgNVBAcTClJoeXMgSm9uZXMx EDAOBgNVBAoTB25vZGUuanMxHTAbBgNVBAsTFFRlc3QgVExTIENlcnRpZmljYXRl MRIwEAYDVQQDEwlsb2NhbGhvc3SCCQCi9FBvpkZEjzAMBgNVHRMEBTADAQH/MA0G CSqGSIb3DQEBBQUAA4GBADRXXA2xSUK5W1i3oLYWW6NEDVWkTQ9RveplyeS9MOkP e7yPcpz0+O0ZDDrxR9chAiZ7fmdBBX1Tr+pIuCrG/Ud49SBqeS5aMJGVwiSd7o1n dhU2Sz3Q60DwJEL1VenQHiVYlWWtqXBThe9ggqRPnCfsCRTP8qifKkjk45zWPcpN -----END CERTIFICATE----- ]] local options = { cert = certPem, key = keyPem } local respond = function(log, client, payload) local destroy = false -- skip responses to requests if payload.method == nil then return end local response_method = payload.method .. '.response' local response = JSON.parse(fixtures[response_method]) local response_out = nil -- Handle rate limit logic client.rate_limit = client.rate_limit - 1 if client.rate_limit <= 0 then response = JSON.parse(fixtures['rate-limiting']['rate-limit-error']) destroy = true end response.target = payload.source response.source = payload.target response.id = payload.id log("Sending response:") response_out = JSON.stringify(response) response_out:gsub("\n", " ") client:write(response_out .. '\n') if destroy == true then client:destroy() end return destroy end local send_schedule_changed = function(log, client) local request = fixtures['check_schedule.changed.request'] log("Sending request:") p(JSON.parse(request)) client:write(request .. '\n') end local function clear_timers(timer_ids) for k, v in pairs(timer_ids) do if v._closed ~= true then timer.clearTimer(v) end end end local function start_fixture_server(options, port) local log = function(...) print(port .. ": " .. ...) end local server = tls.createServer(options, function (client) local lineEmitter = LineEmitter:new() local destroyed = false local timers = {} client.rate_limit = opts.rate_limit client:pipe(lineEmitter) lineEmitter:on('data', function(line) local payload = JSON.parse(line) log("Got payload:") p(payload) destroyed = respond(log, client, payload) if destroyed == true then clear_timers(timers) end end) -- Reset rate limit counter timer.setTimeout(opts.rate_limit_reset, function() client.rate_limit = opts.rate_limit end) timer.setTimeout(opts.send_schedule_changed_initial, function() send_schedule_changed(log, client) end) table.insert(timers, timer.setInterval(opts.send_schedule_changed_interval, function() send_schedule_changed(log, client) end) ) -- Disconnect the agent after some random number of seconds -- to exercise reconnect logic if opts.perform_client_disconnect == 'true' then local disconnect_time = opts.destroy_connection_base + math.floor(math.random() * opts.destroy_connection_jitter) timer.setTimeout(disconnect_time, function() log("Destroying connection after " .. disconnect_time .. "ms connected") client:destroy() end) end end):listen(port, opts.listen_ip) return server end -- There is no cleanup code for the server here as the process for exiting is -- to just ctrl+c the runner or kill the process. for k, v in pairs(ports) do start_fixture_server(options, v) print("TCP echo server listening on port " .. v) end
monitoring: fixtures: server: lineEmitter per connection
monitoring: fixtures: server: lineEmitter per connection make the lineEmitter per connection so that we don't end up sending responses to all three connections.
Lua
apache-2.0
virgo-agent-toolkit/rackspace-monitoring-agent,cp16net/virgo-base,AlphaStaxLLC/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,cp16net/virgo-base,cp16net/virgo-base,cp16net/virgo-base,kaustavha/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,cp16net/virgo-base
3bad08b4b23f12275d6d3ece798a76278f2824bc
CTCCriterion.lua
CTCCriterion.lua
-- Criterion based on the warp-ctc library -- by Baidu: https://github.com/baidu-research/warp-ctc -- Formatting of the input can be seen here: -- https://github.com/baidu-research/warp-ctc/blob/master/torch_binding/TUTORIAL.md require 'warp_ctc' local CTCCriterion, parent = torch.class('nn.CTCCriterion', 'nn.Criterion') function CTCCriterion:__init() parent.__init(self) -- GPU inputs (preallocate) self.acts = torch.Tensor() self.convertedGradients = torch.Tensor() end function CTCCriterion:updateOutput(output, labels) local tensorSizes = output:size() local acts = self:createCTCBatch(output, tensorSizes) local sizes = {} for x = 1, tensorSizes[1] do table.insert(sizes, tensorSizes[2]) end if (output:type() == 'torch.CudaTensor') then local grads = torch.CudaTensor() self.output = sumCosts(gpu_ctc(acts, grads, labels, sizes)) else local grads = torch.DoubleTensor() self.output = sumCosts(cpu_ctc(acts, grads, labels, sizes)) end return self.output end function CTCCriterion:updateGradInput(output, labels) local tensorSizes = output:size() local acts = self:createCTCBatch(output, tensorSizes) local sizes = {} for x = 1, tensorSizes[1] do table.insert(sizes, tensorSizes[2]) end local grads = acts:clone():zero() if (output:type() == 'torch.CudaTensor') then gpu_ctc(acts, grads, labels, sizes) else cpu_ctc(acts, grads, labels, sizes) end self.gradInput = self:revertBatching(grads, tensorSizes) return self.gradInput end --If batching occurs multiple costs are returned. We sum the costs and return. function sumCosts(list) local acc for k, v in ipairs(list) do if 1 == k then acc = v else acc = acc + v end end return acc end function CTCCriterion:createCTCBatch(output, sizes) self.acts:resize(sizes[1] * sizes[2], sizes[3]):zero() local counter = 1 for i = 1, sizes[2] do for j = 1, sizes[1] do self.acts[counter] = output[j][i] counter = counter + 1 end end return self.acts end function CTCCriterion:revertBatching(gradients, sizes) self.convertedGradients:resize(sizes[1], sizes[2], sizes[3]):zero() local counter = 1 for i = 1, sizes[2] do for j = 1, sizes[1] do self.convertedGradients[j][i] = gradients[counter] counter = counter + 1 end end return self.convertedGradients end
-- Criterion based on the warp-ctc library -- by Baidu: https://github.com/baidu-research/warp-ctc -- Formatting of the input can be seen here: -- https://github.com/baidu-research/warp-ctc/blob/master/torch_binding/TUTORIAL.md require 'warp_ctc' local CTCCriterion, parent = torch.class('nn.CTCCriterion', 'nn.Criterion') function CTCCriterion:__init() parent.__init(self) -- GPU inputs (preallocate) self.acts = torch.Tensor() self.convertedGradients = torch.Tensor() end function CTCCriterion:updateOutput(output, labels) local tensorSizes = output:size() local acts = self:createCTCBatch(output, tensorSizes) local sizes = {} for x = 1, tensorSizes[1] do table.insert(sizes, tensorSizes[2]) end if (output:type() == 'torch.CudaTensor') then local grads = torch.CudaTensor() self.output = sumCosts(gpu_ctc(acts, grads, labels, sizes)) else local grads = torch.Tensor() self.output = sumCosts(cpu_ctc(acts:float(), grads:float(), labels, sizes)) end return self.output end function CTCCriterion:updateGradInput(output, labels) local tensorSizes = output:size() local acts = self:createCTCBatch(output, tensorSizes) local sizes = {} for x = 1, tensorSizes[1] do table.insert(sizes, tensorSizes[2]) end local grads = acts:clone():zero() if (output:type() == 'torch.CudaTensor') then gpu_ctc(acts, grads, labels, sizes) else cpu_ctc(acts:float(), grads:float(), labels, sizes) end self.gradInput = self:revertBatching(grads, tensorSizes):typeAs(output) return self.gradInput end --If batching occurs multiple costs are returned. We sum the costs and return. function sumCosts(list) local acc for k, v in ipairs(list) do if 1 == k then acc = v else acc = acc + v end end return acc end function CTCCriterion:createCTCBatch(output, sizes) self.acts:resize(sizes[1] * sizes[2], sizes[3]):zero() local counter = 1 for i = 1, sizes[2] do for j = 1, sizes[1] do self.acts[counter] = output[j][i] counter = counter + 1 end end return self.acts end function CTCCriterion:revertBatching(gradients, sizes) self.convertedGradients:resize(sizes[1], sizes[2], sizes[3]):zero() local counter = 1 for i = 1, sizes[2] do for j = 1, sizes[1] do self.convertedGradients[j][i] = gradients[counter] counter = counter + 1 end end return self.convertedGradients end
fixed type issues
fixed type issues
Lua
mit
SeanNaren/CTCSpeechRecognition,zhirongw/Speech
986dd6a652a5da23b07f131160ed6b972a5c9341
mod_watchuntrusted/mod_watchuntrusted.lua
mod_watchuntrusted/mod_watchuntrusted.lua
local jid_prep = require "util.jid".prep; local secure_auth = module:get_option_boolean("s2s_secure_auth", false); local secure_domains, insecure_domains = module:get_option_set("s2s_secure_domains", {})._items, module:get_option_set("s2s_insecure_domains", {})._items; local untrusted_fail_watchers = module:get_option_set("untrusted_fail_watchers", module:get_option("admins", {})) / jid_prep; local untrusted_fail_notification = module:get_option("untrusted_fail_notification", "Establishing a secure connection from $from_host to $to_host failed. Certificate hash: $sha1. $errors"); local st = require "util.stanza"; local notified_about_already = { }; module:hook_global("s2s-check-certificate", function (event) local session, host = event.session, event.host; local conn = session.conn:socket(); local local_host = session.direction == "outgoing" and session.from_host or session.to_host; if not (local_host == module:get_host()) then return end module:log("debug", "Checking certificate..."); local must_secure = secure_auth; if not must_secure and secure_domains[host] then must_secure = true; elseif must_secure and insecure_domains[host] then must_secure = false; end if must_secure and (session.cert_chain_status ~= "valid" or session.cert_identity_status ~= "valid") and not notified_about_already[host] then notified_about_already[host] = os.time(); local _, errors = conn:getpeerverification(); local error_message = ""; for depth, t in pairs(errors or {}) do if #t > 0 then error_message = error_message .. "Error with certificate " .. (depth - 1) .. ": " .. table.concat(t, ", ") .. ". "; end end if session.cert_identity_status then error_message = error_message .. "This certificate is " .. session.cert_identity_status .. " for " .. host .. "."; end local replacements = { sha1 = event.cert and event.cert:digest("sha1"), errors = error_message }; local message = st.message{ type = "chat", from = local_host } :tag("body") :text(untrusted_fail_notification:gsub("%$([%w_]+)", function (v) return event[v] or session and session[v] or replacements and replacements[v] or nil; end)); for jid in untrusted_fail_watchers do module:log("debug", "Notifying %s", jid); message.attr.to = jid; module:send(message); end end end, -0.5); module:add_timer(14400, function (now) for host, time in pairs(notified_about_already) do if time + 86400 > now then notified_about_already[host] = nil; end end end)
local jid_prep = require "util.jid".prep; local secure_auth = module:get_option_boolean("s2s_secure_auth", false); local secure_domains, insecure_domains = module:get_option_set("s2s_secure_domains", {})._items, module:get_option_set("s2s_insecure_domains", {})._items; local untrusted_fail_watchers = module:get_option_set("untrusted_fail_watchers", module:get_option("admins", {})) / jid_prep; local untrusted_fail_notification = module:get_option("untrusted_fail_notification", "Establishing a secure connection from $from_host to $to_host failed. Certificate hash: $sha1. $errors"); local st = require "util.stanza"; local notified_about_already = { }; module:hook_global("s2s-check-certificate", function (event) local session, host = event.session, event.host; if not host then return end local conn = session.conn:socket(); local local_host = session.direction == "outgoing" and session.from_host or session.to_host; if not (local_host == module:get_host()) then return end module:log("debug", "Checking certificate..."); local must_secure = secure_auth; if not must_secure and secure_domains[host] then must_secure = true; elseif must_secure and insecure_domains[host] then must_secure = false; end if must_secure and (session.cert_chain_status ~= "valid" or session.cert_identity_status ~= "valid") and not notified_about_already[host] then notified_about_already[host] = os.time(); local _, errors = conn:getpeerverification(); local error_message = ""; for depth, t in pairs(errors or {}) do if #t > 0 then error_message = error_message .. "Error with certificate " .. (depth - 1) .. ": " .. table.concat(t, ", ") .. ". "; end end if session.cert_identity_status then error_message = error_message .. "This certificate is " .. session.cert_identity_status .. " for " .. host .. "."; end local replacements = { sha1 = event.cert and event.cert:digest("sha1"), errors = error_message }; local message = st.message{ type = "chat", from = local_host } :tag("body") :text(untrusted_fail_notification:gsub("%$([%w_]+)", function (v) return event[v] or session and session[v] or replacements and replacements[v] or nil; end)); for jid in untrusted_fail_watchers do module:log("debug", "Notifying %s", jid); message.attr.to = jid; module:send(message); end end end, -0.5); module:add_timer(14400, function (now) for host, time in pairs(notified_about_already) do if time + 86400 > now then notified_about_already[host] = nil; end end end)
mod_watchuntrusted: Skip connections to/from unknown hosts (fixes possible traceback)
mod_watchuntrusted: Skip connections to/from unknown hosts (fixes possible traceback)
Lua
mit
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
48b314ddbc2aabdaad292bb0323f9dcac4f879b3
scripts/tcp-connect.lua
scripts/tcp-connect.lua
local syn_table = {} print(string.format("\n Time IP:Port Retries Conenct Cost(s)")) print(string.format("-------------------------- ---------------------------------------------- -------------- ---------------------")) function process(packet) if packet.size ~= 0 then return -- // skip the packet with payload end if packet.request and packet.flags == 2 then -- syn packet local key = packet.sip..":"..packet.sport.." => "..packet.dip..":"..packet.dport if not syn_table[key] then syn_table[key] = { seq = packet.seq, count = 0, tv_sec = packet.tv_sec, tv_usec = packet.tv_usec } return end if syn_table[key].seq == packet.seq then -- duplicate syn syn_table[key].count = syn_table[key].count + 1 end return end if (not packet.request and packet.flags == 18) -- syn + ack or (bit32.band(packet.flags, 4) ~= 0) then -- rst local key = packet.dip..":"..packet.dport.." => "..packet.sip..":"..packet.sport local first_syn_packet = syn_table[key] -- only print the connection with retransmit syn packet if first_syn_packet and first_syn_packet.count > 0 then local time_str = os.date('%Y-%m-%d %H:%M:%S', packet.tv_sec).."."..packet.tv_usec if packet.tv_usec < first_syn_packet.tv_usec then packet.tv_sec = packet.tv_sec - 1 packet.tv_usec = packet.tv_usec + 1000000 end print(string.format("%26s %47s %6d %12d.%06d", time_str, key, syn_table[key].count, packet.tv_sec-first_syn_packet.tv_sec, packet.tv_usec-first_syn_packet.tv_usec )) end syn_table[key] = nil return end end
local syn_table = {} print(string.format("\n Time IP:Port Retries Conenct Cost(s)")) print(string.format("-------------------------- ---------------------------------------------- -------------- ---------------------")) function process(packet) if packet.size ~= 0 then return -- // skip the packet with payload end if packet.flags == 2 then -- syn packet local key = packet.sip..":"..packet.sport.." => "..packet.dip..":"..packet.dport if not syn_table[key] then syn_table[key] = { seq = packet.seq, count = 0, tv_sec = packet.tv_sec, tv_usec = packet.tv_usec } return end if syn_table[key].seq == packet.seq then -- duplicate syn syn_table[key].count = syn_table[key].count + 1 end return end if packet.flags == 18 or (bit32.band(packet.flags, 4) ~= 0) then local key = packet.dip..":"..packet.dport.." => "..packet.sip..":"..packet.sport local first_syn_packet = syn_table[key] if first_syn_packet and first_syn_packet.count >= 0 then local time_str = os.date('%Y-%m-%d %H:%M:%S', packet.tv_sec).."."..packet.tv_usec if packet.tv_usec < first_syn_packet.tv_usec then packet.tv_sec = packet.tv_sec - 1 packet.tv_usec = packet.tv_usec + 1000000 end print(string.format("%26s %47s %6d %12d.%06d", time_str, key, syn_table[key].count, packet.tv_sec-first_syn_packet.tv_sec, packet.tv_usec-first_syn_packet.tv_usec )) end syn_table[key] = nil end end
FIX: tcp connect script
FIX: tcp connect script
Lua
mit
git-hulk/tcpkit,git-hulk/tcpkit
122c8401ca88ebca3cc75340c51e2764f608bc1f
src/gtkpad.lua
src/gtkpad.lua
#! /usr/bin/env lua --[[-------------------------------------------------------------------------- Sample GTK Application program, simple notepad implementation. Copyright (c) 2010 Pavel Holejsovsky Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php --]]-------------------------------------------------------------------------- require 'lgi' local Gtk = require 'lgi.Gtk' local Gio = require 'lgi.Gio' local function new_window(app, file) local ok, contents = file and file:load_contents() local window = Gtk.Window { type = Gtk.WindowType.TOPLEVEL, application = app, title = file and file:get_parse_name() or '<Untitled>', child = Gtk.ScrolledWindow { child = Gtk.TextView { buffer = Gtk.TextBuffer { text = ok and contents or '' } } } } window:show_all() return window end if false then local app = Gtk.Application.new('org.lgi.GtkPad', Gio.ApplicationFlags.HANDLES_OPEN) app.on_activate = function(app) new_window(app) end app.on_open = function(app, files) for i = 1, #files do new_window(app, files[i]) end end return app:run(0, 'prd') else Gtk.init() local args, running = { ... }, 0 for i = 1, #args ~= 0 and #args or 1 do new_window(nil, args[i]).on_destroy = function() count = count - 1 if count == 0 then Gtk.main_quit() end end count = count + 1 end Gtk.main() end
#! /usr/bin/env lua --[[-------------------------------------------------------------------------- Sample GTK Application program, simple notepad implementation. Copyright (c) 2010 Pavel Holejsovsky Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php --]]-------------------------------------------------------------------------- require 'lgi' local Gtk = require 'lgi.Gtk' local Gio = require 'lgi.Gio' local function new_editor(app, file) local ok, contents if file then ok, contents = file:load_contents() end local window = Gtk.Window { type = Gtk.WindowType.TOPLEVEL, application = app, title = file and file:get_parse_name() or '<Untitled>', child = Gtk.ScrolledWindow { child = Gtk.TextView { buffer = Gtk.TextBuffer { text = ok and contents or '' } } } } window:show_all() return window end if false then local app = Gtk.Application.new('org.lgi.GtkPad', Gio.ApplicationFlags.HANDLES_OPEN) app.on_activate = function(app) new_editor(app) end app.on_open = function(app, files) for i = 1, #files do new_editor(app, files[i]) end end return app:run(...) else Gtk.init() local args, running = { ... }, 0 for i = 1, #args ~= 0 and #args or 1 do if args[i] then args[i] = Gio.file_new_for_path(args[i]) end local window = new_editor(nil, args[i]) running = running + 1 window.on_destroy = function() running = running - 1 if running == 0 then Gtk.main_quit() end end end Gtk.main() end
Fix gtkpad application.
Fix gtkpad application.
Lua
mit
psychon/lgi,zevv/lgi,pavouk/lgi
1551ce26fdc51165ecb80cadbb72d4b052116b3f
src/OAuth/helpers.lua
src/OAuth/helpers.lua
local pairs, table, tostring, select = pairs, table, tostring, select local type, assert, error = type, assert, error local string = require "string" local math = require "math" local Url, Qs local isLuaNode if process then Url = require "luanode.url" Qs = require "luanode.querystring" isLuaNode = true else Url = require "socket.url" end module((...)) -- -- Encodes the key-value pairs of a table according the application/x-www-form-urlencoded content type. url_encode_arguments = (isLuaNode and Qs.url_encode_arguments) or function(arguments) local body = {} for k,v in pairs(arguments) do body[#body + 1] = Url.escape(tostring(k)) .. "=" .. Url.escape(tostring(v)) end return table.concat(body, "&") end --- -- Multipart form-data helper. -- -- Taken from https://github.com/catwell/lua-multipart-post -- do -- Create a scope to avoid these local helpers to escape local function fmt(p, ...) if select('#',...) == 0 then return p else return string.format(p, ...) end end local function tprintf(t, p, ...) t[#t + 1] = fmt(p, ...) end local function append_data(r, k, data, extra) tprintf(r, "content-disposition: form-data; name=\"%s\"", k) if extra.filename then tprintf(r, "; filename=\"%s\"", extra.filename) end if extra.content_type then tprintf(r, "\r\ncontent-type: %s", extra.content_type) end if extra.content_transfer_encoding then tprintf(r, "\r\ncontent-transfer-encoding: %s", extra.content_transfer_encoding) end tprintf(r, "\r\n\r\n") tprintf(r, data) tprintf(r, "\r\n") end local function gen_boundary() local t = {"BOUNDARY-"} for i = 2, 17 do t[i] = string.char(math.random(65, 90)) end t[18] = "-BOUNDARY" return table.concat(t) end local function encode(t, boundary) local r = {} local _t -- generate a boundary if none was supplied boundary = boundary or gen_boundary() for k,v in pairs(t) do tprintf(r,"--%s\r\n",boundary) _t = type(v) if _t == "string" then append_data(r, k, v, {}) elseif _t == "table" then assert(v.data, "invalid input") local extra = { filename = v.filename or v.name, content_type = v.content_type or v.mimetype or "application/octet-stream", content_transfer_encoding = v.content_transfer_encoding or "binary", } append_data(r, k, v.data, extra) else append_data(r, k, tostring(v), {}) end end tprintf(r, "--%s--\r\n", boundary) return table.concat(r) end multipart = { --- -- t is a table with the data to be encoded as multipart/form-data -- TODO: improve docs Request = function(t) local boundary = gen_boundary() local body = encode(t, boundary) return { body = body, headers = { ["Content-Length"] = #body, ["Content-Type"] = ("multipart/form-data; boundary=%s"):format(boundary), }, } end } end -- end of multipart scope
local pairs, table, tostring, select = pairs, table, tostring, select local type, assert, error = type, assert, error local string = require "string" local math = require "math" local Url, Qs local isLuaNode if process then Url = require "luanode.url" Qs = require "luanode.querystring" isLuaNode = true else Url = require "socket.url" end module((...)) -- -- Encodes the key-value pairs of a table according the application/x-www-form-urlencoded content type. url_encode_arguments = (isLuaNode and Qs.url_encode_arguments) or function(arguments) local body = {} for k,v in pairs(arguments) do body[#body + 1] = Url.escape(tostring(k)) .. "=" .. Url.escape(tostring(v)) end return table.concat(body, "&") end --- -- Multipart form-data helper. -- -- Taken from https://github.com/catwell/lua-multipart-post -- do -- Create a scope to avoid these local helpers to escape local function fmt(p, ...) if select('#',...) == 0 then return p else return string.format(p, ...) end end local function tprintf(t, p, ...) t[#t + 1] = fmt(p, ...) end local function append_data(r, k, data, extra) tprintf(r, "content-disposition: form-data; name=\"%s\"", k) if extra.filename then tprintf(r, "; filename=\"%s\"", extra.filename) end if extra.content_type then tprintf(r, "\r\ncontent-type: %s", extra.content_type) end if extra.content_transfer_encoding then tprintf(r, "\r\ncontent-transfer-encoding: %s", extra.content_transfer_encoding) end tprintf(r, "\r\n\r\n") tprintf(r, data) tprintf(r, "\r\n") end local function gen_boundary() local t = {"BOUNDARY-"} for i = 2, 17 do t[i] = string.char(math.random(65, 90)) end t[18] = "-BOUNDARY" return table.concat(t) end local function encode(t, boundary) local r = {} local _t, _tkey, key -- generate a boundary if none was supplied boundary = boundary or gen_boundary() for k,v in pairs(t) do tprintf(r,"--%s\r\n",boundary) _tkey, _t = type(k), type(v) if _tkey ~= "string" and _tkey ~= "number" and _tkey ~= "boolean" then return nil, ("unexpected type %s for key %s"):format(_tkey, tostring(k)) end if _t == "string" then append_data(r, k, v, {}) elseif _t == "number" or _t == "boolean" then append_data(r, k, tostring(v), {}) elseif _t == "table" then assert(v.data, "invalid input") local extra = { filename = v.filename or v.name, content_type = v.content_type or v.mimetype or "application/octet-stream", content_transfer_encoding = v.content_transfer_encoding or "binary", } append_data(r, k, v.data, extra) else return nil, ("unexpected type %s for value at key %s"):format(_t, tostring(k)) end end tprintf(r, "--%s--\r\n", boundary) return table.concat(r) end multipart = { --- -- t is a table with the data to be encoded as multipart/form-data -- TODO: improve docs Request = function(t) local boundary = gen_boundary() local body, err = encode(t, boundary) if not body then return body, err end return { body = body, headers = { ["Content-Length"] = #body, ["Content-Type"] = ("multipart/form-data; boundary=%s"):format(boundary), }, } end } end -- end of multipart scope
Check types for multipart keys and values (#11)
Check types for multipart keys and values (#11) Tables to be encoded as multipart/form-data must comply with: - keys must be either strings, booleans or numbers - values must not be neither function nor userdata fixes #11
Lua
mit
ignacio/LuaOAuth
f3212c2cba762d7f52fff6e6c083cde9a2416cce
lua/path/findfile.lua
lua/path/findfile.lua
--- -- Implementation of afx.findfile local string = require "string" local table = require "table" local coroutine = require "coroutine" local PATH = require "path.module" local lfs = require "lfs" local function fs_foreach(path, match, cb, recursive) for name in lfs.dir(path) do if name ~= "." and name ~= ".." then local path_name = PATH.join(path, name) if match(path_name) then if cb(path_name) then return 'break' end end if recursive and PATH.isdir(path_name) then if 'break' == fs_foreach(path_name, match, cb, match) then return 'break' end end end end return true end local function filePat2rexPat(pat) local pat = pat:gsub("%.","%%."):gsub("%*",".*"):gsub("%?", ".") if PATH.IS_WINDOWS then pat = pat:upper() end return pat end local function match_pat(pat) pat = filePat2rexPat(pat) return PATH.IS_WINDOWS and function(s) return nil ~= string.find(string.upper(s), pat) end or function(s) return nil ~= string.find(s, pat) end end local attribs = { f = function(path) return PATH.fullpath(path) end; n = function(path) return PATH.basename(path) end; a = function(path) return PATH.fileattrib and PATH.fileattrib(path) or 0 end; z = function(path) return PATH.isdir(path) and 0 or PATH.size(path) end; t = function(path) return PATH.mtime(path) end; c = function(path) return PATH.ctime(path) end; l = function(path) return PATH.atime(path) end; } local function make_attrib(str) local t = {} for i = 1, #str do local ch = str:sub(i,i) local fn = attribs[ ch ] if not fn then return nil, 'unknown file attribute: ' .. ch end table.insert(t, fn) end return function(path) local res = {} for i, f in ipairs(t) do local ok, err = f(path) if ok == nil then return nil, err end table.insert(res, ok) end return res end end local function findfile_t(option) if not option.file then return nil, 'no file mask present' end local path, mask = PATH.splitpath( option.file ) if not PATH.isdir(path) then return end path = PATH.fullpath(path) local mask_match = match_pat(mask) local get_params, err = make_attrib(option.param or 'f') if not get_params then return nil, err end local unpack = unpack or table.unpack local filter = option.filter local match = function(path) return mask_match(path) and not (option.skipdirs and PATH.isdir(path)) and not (option.skipfiles and PATH.isfile(path)) end if option.callback then local callback = option.callback local function cb(path) local params = assert(get_params(path)) if filter and (not filter(unpack(params))) then return end callback(unpack(params)) end return fs_foreach(path, match, cb, option.recurse) else local function cb(path) local params = assert(get_params(path)) if filter and (not filter(unpack(params))) then return end coroutine.yield(params) end local co = coroutine.create(function() fs_foreach(path, match, cb, option.recurse) end) return function() local status, params = coroutine.resume(co) if status and params then return unpack(params) end end end end local function clone(t) local o = {} for k,v in pairs(t) do o[k] = v end return o end local function findfile_ssf(str_file, str_params, func_callback, tbl_option) tbl_option = tbl_option and clone(tbl_option) or {} tbl_option.file = assert(str_file) tbl_option.param = assert(str_params) tbl_option.callback = assert(func_callback) return findfile_t(tbl_option) end local function findfile_ss(str_file, str_params, tbl_option) tbl_option = tbl_option and clone(tbl_option) or {} tbl_option.file = assert(str_file) tbl_option.param = assert(str_params) return findfile_t(tbl_option) end local function findfile_sf(str_file, func_callback, tbl_option) tbl_option = tbl_option and clone(tbl_option) or {} tbl_option.file = assert(str_file) tbl_option.callback = assert(func_callback) return findfile_t(tbl_option) end local function findfile_s(str_file, tbl_option) tbl_option = tbl_option and clone(tbl_option) or {} tbl_option.file = assert(str_file) return findfile_t(tbl_option) end local function findfile_f(func_callback, tbl_option) tbl_option = clone(assert(tbl_option)) -- need file tbl_option.callback = assert(func_callback) return findfile_t(tbl_option) end local function findfile(p1,p2,p3,p4) if type(p1) == 'string' then if type(p2) == 'string' then if type(p3) == 'function' then return findfile_ssf(p1,p2,p3,p4) end return findfile_ss(p1,p2,p3) end if type(p2) == 'function' then return findfile_sf(p1,p2,p3) end return findfile_s(p1,p2) end if type(p1) == 'function' then return findfile_f(p1,p2) end return findfile_t(p1) end return findfile
--- -- Implementation of afx.findfile local string = require "string" local table = require "table" local coroutine = require "coroutine" local PATH = require "path.module" local lfs = require "lfs" local function fs_foreach(path, match, cb, recursive) for name in lfs.dir(path) do if name ~= "." and name ~= ".." then local path_name = PATH.join(path, name) if match(path_name) then if cb(path_name) then return 'break' end end if recursive and PATH.isdir(path_name) then if 'break' == fs_foreach(path_name, match, cb, match) then return 'break' end end end end return true end local function filePat2rexPat(pat) local pat = "^" .. pat:gsub("%.","%%."):gsub("%*",".*"):gsub("%?", ".") .. "$" if PATH.IS_WINDOWS then pat = pat:upper() end return pat end local function match_pat(pat) pat = filePat2rexPat(pat) return PATH.IS_WINDOWS and function(s) return nil ~= string.find(string.upper(s), pat) end or function(s) return nil ~= string.find(s, pat) end end local attribs = { f = function(path) return PATH.fullpath(path) end; n = function(path) return PATH.basename(path) end; a = function(path) return PATH.fileattrib and PATH.fileattrib(path) or 0 end; z = function(path) return PATH.isdir(path) and 0 or PATH.size(path) end; t = function(path) return PATH.mtime(path) end; c = function(path) return PATH.ctime(path) end; l = function(path) return PATH.atime(path) end; } local function make_attrib(str) local t = {} for i = 1, #str do local ch = str:sub(i,i) local fn = attribs[ ch ] if not fn then return nil, 'unknown file attribute: ' .. ch end table.insert(t, fn) end return function(path) local res = {} for i, f in ipairs(t) do local ok, err = f(path) if ok == nil then return nil, err end table.insert(res, ok) end return res end end local function findfile_t(option) if not option.file then return nil, 'no file mask present' end local path, mask = PATH.splitpath( option.file ) if not PATH.isdir(path) then return end path = PATH.fullpath(path) local mask_match = match_pat(mask) local get_params, err = make_attrib(option.param or 'f') if not get_params then return nil, err end local unpack = unpack or table.unpack local filter = option.filter local match = function(path) return mask_match(PATH.basename(path)) and not (option.skipdirs and PATH.isdir(path)) and not (option.skipfiles and PATH.isfile(path)) end if option.callback then local callback = option.callback local function cb(path) local params = assert(get_params(path)) if filter and (not filter(unpack(params))) then return end return callback(unpack(params)) end return fs_foreach(path, match, cb, option.recurse) else local function cb(path) local params = assert(get_params(path)) if filter and (not filter(unpack(params))) then return end coroutine.yield(params) end local co = coroutine.create(function() fs_foreach(path, match, cb, option.recurse) end) return function() local status, params = coroutine.resume(co) if status and params then return unpack(params) end end end end local function clone(t) local o = {} for k,v in pairs(t) do o[k] = v end return o end local function findfile_ssf(str_file, str_params, func_callback, tbl_option) tbl_option = tbl_option and clone(tbl_option) or {} tbl_option.file = assert(str_file) tbl_option.param = assert(str_params) tbl_option.callback = assert(func_callback) return findfile_t(tbl_option) end local function findfile_ss(str_file, str_params, tbl_option) tbl_option = tbl_option and clone(tbl_option) or {} tbl_option.file = assert(str_file) tbl_option.param = assert(str_params) return findfile_t(tbl_option) end local function findfile_sf(str_file, func_callback, tbl_option) tbl_option = tbl_option and clone(tbl_option) or {} tbl_option.file = assert(str_file) tbl_option.callback = assert(func_callback) return findfile_t(tbl_option) end local function findfile_s(str_file, tbl_option) tbl_option = tbl_option and clone(tbl_option) or {} tbl_option.file = assert(str_file) return findfile_t(tbl_option) end local function findfile_f(func_callback, tbl_option) tbl_option = clone(assert(tbl_option)) -- need file tbl_option.callback = assert(func_callback) return findfile_t(tbl_option) end local function findfile(p1,p2,p3,p4) if type(p1) == 'string' then if type(p2) == 'string' then if type(p3) == 'function' then return findfile_ssf(p1,p2,p3,p4) end return findfile_ss(p1,p2,p3) end if type(p2) == 'function' then return findfile_sf(p1,p2,p3) end return findfile_s(p1,p2) end if type(p1) == 'function' then return findfile_f(p1,p2) end return findfile_t(p1) end return findfile
Fix. In path.each the mask was used for the full path, instead of for a base name. Fix. break path.each.
Fix. In path.each the mask was used for the full path, instead of for a base name. Fix. break path.each.
Lua
mit
mpeterv/lua-path,kidaa/lua-path
427aab8e60059241d4892f50ec1b08eb798a0d28
lua/framework/graphics/transformation.lua
lua/framework/graphics/transformation.lua
--=========== Copyright © 2018, Planimeter, All rights reserved. =============-- -- -- Purpose: -- --============================================================================-- local kazmath = require( "kazmath" ) local ffi = require( "ffi" ) local GL = require( "opengl" ) local ipairs = ipairs local framework = framework local table = table module( "framework.graphics" ) local transformations = { "model", "view", "projection" } _matrixMode = _matrixMode or "model" _stack = _stack or {} for _, transformation in ipairs( transformations ) do local mat4 = ffi.new( "kmMat4" ) kazmath.kmMat4Identity( mat4 ) _stack[ transformation ] = _stack[ transformation ] or { mat4 } end local mat4 = ffi.new( "kmMat4" ) kazmath.kmMat4Identity( mat4 ) _normalMatrix = _normalMatrix or mat4 function getMatrixMode() return _matrixMode end function setMatrixMode( mode ) _matrixMode = mode end function getNormalMatrix() return _normalMatrix end function getTransformation() local mode = getMatrixMode() local stack = _stack[ mode ] return stack[ #stack ] end function push() local mode = getMatrixMode() local top = ffi.new( "kmMat4" ) kazmath.kmMat4Assign( top, getTransformation() ) table.insert( _stack[ mode ], top ) end function pop() local mode = getMatrixMode() local stack = _stack[ mode ] if ( #stack == 1 ) then return end table.remove( stack, #stack ) end function setPerspectiveProjection( fov, aspect, near, far ) local mode = getMatrixMode() setMatrixMode( "projection" ) local mat4 = getTransformation() kazmath.kmMat4PerspectiveProjection( mat4, fov, aspect, near, far ) setMatrixMode( mode ) updateTransformations() end function setReversedZPerspectiveProjection( fov, aspect, near ) local mode = getMatrixMode() setMatrixMode( "projection" ) local mat4 = getTransformation() kazmath.kmMat4ReversedZPerspectiveProjection( mat4, fov, aspect, near ) GL.glDepthFunc( GL.GL_GEQUAL ) setMatrixMode( mode ) updateTransformations() end function setOrthographicProjection( width, height ) if ( not width and not height ) then width, height = framework.graphics.getSize() end local mode = getMatrixMode() setMatrixMode( "projection" ) local mat4 = getTransformation() kazmath.kmMat4OrthographicProjection( mat4, 0, width, height, 0, -1.0, 1.0 ) setMatrixMode( mode ) updateTransformations() end function lookAt( eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ ) local mode = getMatrixMode() setMatrixMode( "view" ) local mat4 = getTransformation() local eye = ffi.new( "kmVec3", eyeX, eyeY, eyeZ ) local center = ffi.new( "kmVec3", centerX, centerY, centerZ ) local up = ffi.new( "kmVec3", upX, upY, upZ ) kazmath.kmMat4LookAt( mat4, eye, center, up ) setMatrixMode( mode ) updateTransformations() end function origin() kazmath.kmMat4Identity( getTransformation() ) end function rotate( angle ) local rotation = ffi.new( "kmMat4" ) kazmath.kmMat4RotationZ( rotation, angle ) local mat4 = getTransformation() kazmath.kmMat4Multiply( mat4, mat4, rotation ) end function rotateX( angle ) local rotation = ffi.new( "kmMat4" ) kazmath.kmMat4RotationX( rotation, angle ) local mat4 = getTransformation() kazmath.kmMat4Multiply( mat4, mat4, rotation ) end function rotateY( angle ) local rotation = ffi.new( "kmMat4" ) kazmath.kmMat4RotationY( rotation, angle ) local mat4 = getTransformation() kazmath.kmMat4Multiply( mat4, mat4, rotation ) end rotateZ = rotate function scale( x, y, z ) y = y or x z = z or 1 local scaling = ffi.new( "kmMat4" ) kazmath.kmMat4Scaling( scaling, x, y, z ) local mat4 = getTransformation() kazmath.kmMat4Multiply( mat4, mat4, scaling ) end function translate( x, y, z ) if ( z == nil ) then y = -y end z = z or 0 local translation = ffi.new( "kmMat4" ) kazmath.kmMat4Translation( translation, x, y, z ) local mat4 = getTransformation() kazmath.kmMat4Multiply( mat4, mat4, translation ) end local function updateNormalMatrix() local mode = getMatrixMode() -- local modelView = ffi.new( "kmMat4" ) setMatrixMode( "model" ) local model = getTransformation() -- setMatrixMode( "view" ) -- local view = getTransformation() setMatrixMode( mode ) -- kazmath.kmMat4Multiply( modelView, model, view ) -- local inverseModelView = ffi.new( "kmMat4" ) -- kazmath.kmMat4Inverse( inverseModelView, modelView ) -- kazmath.kmMat4Transpose( _normalMatrix, inverseModelView ) local inverseModel = ffi.new( "kmMat4" ) kazmath.kmMat4Inverse( inverseModel, model ) kazmath.kmMat4Transpose( _normalMatrix, inverseModel ) end function updateTransformations() local mode = getMatrixMode() local shader = framework.graphics.getShader() for _, transformation in ipairs( transformations ) do local uniform = GL.glGetUniformLocation( shader, transformation ) setMatrixMode( transformation ) local mat4 = getTransformation() GL.glUniformMatrix4fv( uniform, 1, GL.GL_FALSE, mat4.mat ) end updateNormalMatrix() local uniform = GL.glGetUniformLocation( shader, "normalMatrix" ) local normalMatrix = getNormalMatrix() GL.glUniformMatrix4fv( uniform, 1, GL.GL_FALSE, normalMatrix.mat ) setMatrixMode( mode ) end
--=========== Copyright © 2018, Planimeter, All rights reserved. =============-- -- -- Purpose: -- --============================================================================-- local kazmath = require( "kazmath" ) local ffi = require( "ffi" ) local GL = require( "opengl" ) local ipairs = ipairs local framework = framework local table = table module( "framework.graphics" ) local transformations = { "model", "view", "projection" } _matrixMode = _matrixMode or "model" _stack = _stack or {} for _, transformation in ipairs( transformations ) do local mat4 = ffi.new( "kmMat4" ) kazmath.kmMat4Identity( mat4 ) _stack[ transformation ] = _stack[ transformation ] or { mat4 } end local mat4 = ffi.new( "kmMat4" ) kazmath.kmMat4Identity( mat4 ) _normalMatrix = _normalMatrix or mat4 function getMatrixMode() return _matrixMode end function setMatrixMode( mode ) _matrixMode = mode end function getNormalMatrix() return _normalMatrix end function getTransformation() local mode = getMatrixMode() local stack = _stack[ mode ] return stack[ #stack ] end function push() local mode = getMatrixMode() local top = ffi.new( "kmMat4" ) kazmath.kmMat4Assign( top, getTransformation() ) table.insert( _stack[ mode ], top ) end function pop() local mode = getMatrixMode() local stack = _stack[ mode ] if ( #stack == 1 ) then return end table.remove( stack, #stack ) end function setPerspectiveProjection( fov, aspect, near, far ) local mode = getMatrixMode() setMatrixMode( "projection" ) local mat4 = getTransformation() kazmath.kmMat4PerspectiveProjection( mat4, fov, aspect, near, far ) setMatrixMode( mode ) updateTransformations() end function setReversedZPerspectiveProjection( fov, aspect, near ) local mode = getMatrixMode() setMatrixMode( "projection" ) local mat4 = getTransformation() kazmath.kmMat4ReversedZPerspectiveProjection( mat4, fov, aspect, near ) GL.glDepthFunc( GL.GL_GEQUAL ) setMatrixMode( mode ) updateTransformations() end function setOrthographicProjection( width, height ) if ( not width and not height ) then width, height = framework.graphics.getSize() end local mode = getMatrixMode() setMatrixMode( "projection" ) local mat4 = getTransformation() kazmath.kmMat4OrthographicProjection( mat4, 0, width, height, 0, -1.0, 1.0 ) setMatrixMode( mode ) updateTransformations() end function lookAt( eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ ) local mode = getMatrixMode() setMatrixMode( "view" ) local mat4 = getTransformation() local eye = ffi.new( "kmVec3", eyeX, eyeY, eyeZ ) local center = ffi.new( "kmVec3", centerX, centerY, centerZ ) local up = ffi.new( "kmVec3", upX, upY, upZ ) kazmath.kmMat4LookAt( mat4, eye, center, up ) setMatrixMode( mode ) updateTransformations() end function origin() kazmath.kmMat4Identity( getTransformation() ) end function rotate( angle ) local rotation = ffi.new( "kmMat4" ) kazmath.kmMat4RotationZ( rotation, angle ) local mat4 = getTransformation() kazmath.kmMat4Multiply( mat4, mat4, rotation ) end function rotateX( angle ) local rotation = ffi.new( "kmMat4" ) kazmath.kmMat4RotationX( rotation, angle ) local mat4 = getTransformation() kazmath.kmMat4Multiply( mat4, mat4, rotation ) end function rotateY( angle ) local rotation = ffi.new( "kmMat4" ) kazmath.kmMat4RotationY( rotation, angle ) local mat4 = getTransformation() kazmath.kmMat4Multiply( mat4, mat4, rotation ) end rotateZ = rotate function scale( x, y, z ) y = y or x z = z or 1 local scaling = ffi.new( "kmMat4" ) kazmath.kmMat4Scaling( scaling, x, y, z ) local mat4 = getTransformation() kazmath.kmMat4Multiply( mat4, mat4, scaling ) end function translate( x, y, z ) z = z or 0 local translation = ffi.new( "kmMat4" ) kazmath.kmMat4Translation( translation, x, y, z ) local mat4 = getTransformation() kazmath.kmMat4Multiply( mat4, mat4, translation ) end local function updateNormalMatrix() local mode = getMatrixMode() -- local modelView = ffi.new( "kmMat4" ) setMatrixMode( "model" ) local model = getTransformation() -- setMatrixMode( "view" ) -- local view = getTransformation() setMatrixMode( mode ) -- kazmath.kmMat4Multiply( modelView, model, view ) -- local inverseModelView = ffi.new( "kmMat4" ) -- kazmath.kmMat4Inverse( inverseModelView, modelView ) -- kazmath.kmMat4Transpose( _normalMatrix, inverseModelView ) local inverseModel = ffi.new( "kmMat4" ) kazmath.kmMat4Inverse( inverseModel, model ) kazmath.kmMat4Transpose( _normalMatrix, inverseModel ) end function updateTransformations() local mode = getMatrixMode() local shader = framework.graphics.getShader() for _, transformation in ipairs( transformations ) do local uniform = GL.glGetUniformLocation( shader, transformation ) setMatrixMode( transformation ) local mat4 = getTransformation() GL.glUniformMatrix4fv( uniform, 1, GL.GL_FALSE, mat4.mat ) end updateNormalMatrix() local uniform = GL.glGetUniformLocation( shader, "normalMatrix" ) local normalMatrix = getNormalMatrix() GL.glUniformMatrix4fv( uniform, 1, GL.GL_FALSE, normalMatrix.mat ) setMatrixMode( mode ) end
Remove erroneous `translate` fix
Remove erroneous `translate` fix
Lua
mit
Planimeter/lgameframework,Planimeter/lgameframework,Planimeter/lgameframework
53a0f9867af86c6732ff39b466fa2e653b29afe9
libs/core/luasrc/fs.lua
libs/core/luasrc/fs.lua
--[[ LuCI - Filesystem tools Description: A module offering often needed filesystem manipulation functions FileId: $Id$ License: Copyright 2008 Steven Barth <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- module("luci.fs", package.seeall) require("posix") -- Access access = posix.access -- Glob glob = posix.glob -- Checks whether a file exists function isfile(filename) local fp = io.open(filename, "r") if fp then fp:close() end return fp ~= nil end -- Returns the content of file function readfile(filename) local fp, err = io.open(filename) if fp == nil then return nil, err end local data = fp:read("*a") fp:close() return data end -- Writes given data to a file function writefile(filename, data) local fp, err = io.open(filename, "w") if fp == nil then return nil, err end fp:write(data) fp:close() return true end -- Returns the file modification date/time of "path" function mtime(path) return posix.stat(path, "mtime") end -- basename wrapper basename = posix.basename -- dirname wrapper dirname = posix.dirname -- dir wrapper dir = posix.dir -- wrapper for posix.mkdir function mkdir(path, recursive) if recursive then local base = "." if path:sub(1,1) == "/" then base = "" path = path:gsub("^/+","") end for elem in path:gmatch("([^/]+)/*") do base = base .. "/" .. elem local stat = posix.stat( base ) if not stat then local stat, errmsg, errno = posix.mkdir( base ) if type(stat) ~= "number" or stat ~= 0 then return stat, errmsg, errno end else if stat.type ~= "directory" then return nil, base .. ": File exists", 17 end end end return 0 else return posix.mkdir( path ) end end -- Alias for posix.rmdir rmdir = posix.rmdir -- Alias for posix.stat stat = posix.stat -- Alias for posix.chmod chmod = posix.chmod -- Alias for posix.link link = posix.link -- Alias for posix.unlink unlink = posix.unlink
--[[ LuCI - Filesystem tools Description: A module offering often needed filesystem manipulation functions FileId: $Id$ License: Copyright 2008 Steven Barth <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- module("luci.fs", package.seeall) require("posix") -- Access access = posix.access -- Glob glob = posix.glob -- Checks whether a file exists function isfile(filename) return posix.stat(filename, "type") == "regular" end -- Returns the content of file function readfile(filename) local fp, err = io.open(filename) if fp == nil then return nil, err end local data = fp:read("*a") fp:close() return data end -- Writes given data to a file function writefile(filename, data) local fp, err = io.open(filename, "w") if fp == nil then return nil, err end fp:write(data) fp:close() return true end -- Returns the file modification date/time of "path" function mtime(path) return posix.stat(path, "mtime") end -- basename wrapper basename = posix.basename -- dirname wrapper dirname = posix.dirname -- dir wrapper dir = posix.dir -- wrapper for posix.mkdir function mkdir(path, recursive) if recursive then local base = "." if path:sub(1,1) == "/" then base = "" path = path:gsub("^/+","") end for elem in path:gmatch("([^/]+)/*") do base = base .. "/" .. elem local stat = posix.stat( base ) if not stat then local stat, errmsg, errno = posix.mkdir( base ) if type(stat) ~= "number" or stat ~= 0 then return stat, errmsg, errno end else if stat.type ~= "directory" then return nil, base .. ": File exists", 17 end end end return 0 else return posix.mkdir( path ) end end -- Alias for posix.rmdir rmdir = posix.rmdir -- Alias for posix.stat stat = posix.stat -- Alias for posix.chmod chmod = posix.chmod -- Alias for posix.link link = posix.link -- Alias for posix.unlink unlink = posix.unlink
libs/core: Fixed luci.fs.isfile
libs/core: Fixed luci.fs.isfile
Lua
apache-2.0
rogerpueyo/luci,cshore/luci,Kyklas/luci-proto-hso,lbthomsen/openwrt-luci,cappiewu/luci,palmettos/cnLuCI,aircross/OpenWrt-Firefly-LuCI,cappiewu/luci,nwf/openwrt-luci,thess/OpenWrt-luci,bittorf/luci,opentechinstitute/luci,LazyZhu/openwrt-luci-trunk-mod,shangjiyu/luci-with-extra,Hostle/openwrt-luci-multi-user,jchuang1977/luci-1,thess/OpenWrt-luci,nwf/openwrt-luci,Hostle/openwrt-luci-multi-user,LuttyYang/luci,artynet/luci,Noltari/luci,sujeet14108/luci,RedSnake64/openwrt-luci-packages,deepak78/new-luci,RuiChen1113/luci,remakeelectric/luci,shangjiyu/luci-with-extra,palmettos/cnLuCI,sujeet14108/luci,mumuqz/luci,thess/OpenWrt-luci,jlopenwrtluci/luci,Sakura-Winkey/LuCI,bright-things/ionic-luci,Noltari/luci,dismantl/luci-0.12,forward619/luci,keyidadi/luci,chris5560/openwrt-luci,daofeng2015/luci,dismantl/luci-0.12,male-puppies/luci,Hostle/luci,tcatm/luci,Hostle/luci,Noltari/luci,florian-shellfire/luci,oyido/luci,ollie27/openwrt_luci,LuttyYang/luci,thesabbir/luci,Noltari/luci,marcel-sch/luci,NeoRaider/luci,cshore-firmware/openwrt-luci,teslamint/luci,lbthomsen/openwrt-luci,palmettos/cnLuCI,marcel-sch/luci,RuiChen1113/luci,taiha/luci,palmettos/test,kuoruan/lede-luci,nwf/openwrt-luci,opentechinstitute/luci,wongsyrone/luci-1,joaofvieira/luci,mumuqz/luci,slayerrensky/luci,db260179/openwrt-bpi-r1-luci,obsy/luci,openwrt/luci,harveyhu2012/luci,taiha/luci,ReclaimYourPrivacy/cloak-luci,daofeng2015/luci,sujeet14108/luci,fkooman/luci,oneru/luci,schidler/ionic-luci,marcel-sch/luci,aa65535/luci,openwrt-es/openwrt-luci,lbthomsen/openwrt-luci,remakeelectric/luci,forward619/luci,urueedi/luci,ReclaimYourPrivacy/cloak-luci,dwmw2/luci,fkooman/luci,jorgifumi/luci,joaofvieira/luci,cshore-firmware/openwrt-luci,opentechinstitute/luci,lcf258/openwrtcn,tobiaswaldvogel/luci,marcel-sch/luci,thesabbir/luci,zhaoxx063/luci,bright-things/ionic-luci,deepak78/new-luci,artynet/luci,ReclaimYourPrivacy/cloak-luci,kuoruan/lede-luci,oneru/luci,tobiaswaldvogel/luci,NeoRaider/luci,daofeng2015/luci,981213/luci-1,cshore-firmware/openwrt-luci,wongsyrone/luci-1,ReclaimYourPrivacy/cloak-luci,kuoruan/luci,sujeet14108/luci,slayerrensky/luci,Sakura-Winkey/LuCI,palmettos/cnLuCI,deepak78/new-luci,cshore/luci,taiha/luci,NeoRaider/luci,aa65535/luci,forward619/luci,sujeet14108/luci,openwrt/luci,teslamint/luci,ff94315/luci-1,artynet/luci,lcf258/openwrtcn,Wedmer/luci,openwrt-es/openwrt-luci,obsy/luci,hnyman/luci,aa65535/luci,aircross/OpenWrt-Firefly-LuCI,mumuqz/luci,palmettos/test,openwrt/luci,bright-things/ionic-luci,NeoRaider/luci,opentechinstitute/luci,MinFu/luci,jchuang1977/luci-1,david-xiao/luci,oyido/luci,ff94315/luci-1,teslamint/luci,opentechinstitute/luci,Noltari/luci,florian-shellfire/luci,daofeng2015/luci,ollie27/openwrt_luci,keyidadi/luci,david-xiao/luci,forward619/luci,marcel-sch/luci,harveyhu2012/luci,urueedi/luci,teslamint/luci,nmav/luci,Kyklas/luci-proto-hso,hnyman/luci,lbthomsen/openwrt-luci,kuoruan/lede-luci,openwrt-es/openwrt-luci,Wedmer/luci,Sakura-Winkey/LuCI,RuiChen1113/luci,deepak78/new-luci,cshore-firmware/openwrt-luci,bittorf/luci,florian-shellfire/luci,hnyman/luci,lcf258/openwrtcn,male-puppies/luci,thesabbir/luci,RuiChen1113/luci,dwmw2/luci,marcel-sch/luci,tcatm/luci,MinFu/luci,palmettos/test,openwrt-es/openwrt-luci,Hostle/openwrt-luci-multi-user,deepak78/new-luci,rogerpueyo/luci,tcatm/luci,aa65535/luci,aircross/OpenWrt-Firefly-LuCI,nwf/openwrt-luci,db260179/openwrt-bpi-r1-luci,rogerpueyo/luci,cappiewu/luci,NeoRaider/luci,schidler/ionic-luci,maxrio/luci981213,cshore/luci,daofeng2015/luci,bright-things/ionic-luci,oyido/luci,Hostle/luci,zhaoxx063/luci,Sakura-Winkey/LuCI,Sakura-Winkey/LuCI,openwrt/luci,kuoruan/lede-luci,florian-shellfire/luci,db260179/openwrt-bpi-r1-luci,dwmw2/luci,rogerpueyo/luci,RuiChen1113/luci,dwmw2/luci,marcel-sch/luci,ollie27/openwrt_luci,palmettos/test,palmettos/cnLuCI,wongsyrone/luci-1,florian-shellfire/luci,hnyman/luci,openwrt-es/openwrt-luci,shangjiyu/luci-with-extra,thess/OpenWrt-luci,NeoRaider/luci,lbthomsen/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,ff94315/luci-1,aircross/OpenWrt-Firefly-LuCI,LuttyYang/luci,hnyman/luci,taiha/luci,cappiewu/luci,teslamint/luci,jorgifumi/luci,db260179/openwrt-bpi-r1-luci,cshore-firmware/openwrt-luci,ollie27/openwrt_luci,kuoruan/lede-luci,taiha/luci,Hostle/openwrt-luci-multi-user,kuoruan/luci,MinFu/luci,dismantl/luci-0.12,kuoruan/luci,ReclaimYourPrivacy/cloak-luci,david-xiao/luci,florian-shellfire/luci,tcatm/luci,lcf258/openwrtcn,thesabbir/luci,tcatm/luci,nwf/openwrt-luci,joaofvieira/luci,nmav/luci,rogerpueyo/luci,cshore-firmware/openwrt-luci,lcf258/openwrtcn,keyidadi/luci,thesabbir/luci,slayerrensky/luci,harveyhu2012/luci,LazyZhu/openwrt-luci-trunk-mod,urueedi/luci,LazyZhu/openwrt-luci-trunk-mod,dismantl/luci-0.12,oneru/luci,joaofvieira/luci,bittorf/luci,bittorf/luci,RedSnake64/openwrt-luci-packages,kuoruan/lede-luci,rogerpueyo/luci,opentechinstitute/luci,keyidadi/luci,cshore-firmware/openwrt-luci,deepak78/new-luci,oyido/luci,tobiaswaldvogel/luci,urueedi/luci,bright-things/ionic-luci,david-xiao/luci,lcf258/openwrtcn,lbthomsen/openwrt-luci,cappiewu/luci,Hostle/luci,joaofvieira/luci,Wedmer/luci,jorgifumi/luci,openwrt/luci,wongsyrone/luci-1,mumuqz/luci,db260179/openwrt-bpi-r1-luci,Wedmer/luci,NeoRaider/luci,ff94315/luci-1,LuttyYang/luci,cshore/luci,aircross/OpenWrt-Firefly-LuCI,ollie27/openwrt_luci,chris5560/openwrt-luci,oyido/luci,Hostle/luci,MinFu/luci,openwrt-es/openwrt-luci,slayerrensky/luci,aircross/OpenWrt-Firefly-LuCI,urueedi/luci,shangjiyu/luci-with-extra,thesabbir/luci,daofeng2015/luci,joaofvieira/luci,forward619/luci,schidler/ionic-luci,thess/OpenWrt-luci,Wedmer/luci,nwf/openwrt-luci,wongsyrone/luci-1,palmettos/test,jchuang1977/luci-1,nwf/openwrt-luci,ff94315/luci-1,dismantl/luci-0.12,rogerpueyo/luci,fkooman/luci,Noltari/luci,bright-things/ionic-luci,Hostle/luci,MinFu/luci,NeoRaider/luci,slayerrensky/luci,RuiChen1113/luci,david-xiao/luci,Noltari/luci,Wedmer/luci,joaofvieira/luci,obsy/luci,LazyZhu/openwrt-luci-trunk-mod,forward619/luci,ollie27/openwrt_luci,schidler/ionic-luci,harveyhu2012/luci,artynet/luci,maxrio/luci981213,cappiewu/luci,ollie27/openwrt_luci,zhaoxx063/luci,deepak78/new-luci,shangjiyu/luci-with-extra,lcf258/openwrtcn,remakeelectric/luci,remakeelectric/luci,nmav/luci,male-puppies/luci,jlopenwrtluci/luci,jorgifumi/luci,db260179/openwrt-bpi-r1-luci,cshore/luci,tcatm/luci,harveyhu2012/luci,lbthomsen/openwrt-luci,palmettos/cnLuCI,bittorf/luci,rogerpueyo/luci,RedSnake64/openwrt-luci-packages,zhaoxx063/luci,Kyklas/luci-proto-hso,openwrt/luci,lcf258/openwrtcn,bright-things/ionic-luci,urueedi/luci,RedSnake64/openwrt-luci-packages,kuoruan/luci,obsy/luci,keyidadi/luci,LazyZhu/openwrt-luci-trunk-mod,shangjiyu/luci-with-extra,jlopenwrtluci/luci,cappiewu/luci,zhaoxx063/luci,cappiewu/luci,forward619/luci,kuoruan/luci,schidler/ionic-luci,florian-shellfire/luci,lcf258/openwrtcn,LazyZhu/openwrt-luci-trunk-mod,urueedi/luci,mumuqz/luci,bittorf/luci,male-puppies/luci,RuiChen1113/luci,Hostle/luci,oneru/luci,palmettos/test,nmav/luci,oneru/luci,fkooman/luci,MinFu/luci,ollie27/openwrt_luci,bittorf/luci,schidler/ionic-luci,obsy/luci,tobiaswaldvogel/luci,Wedmer/luci,male-puppies/luci,LuttyYang/luci,ff94315/luci-1,openwrt-es/openwrt-luci,981213/luci-1,wongsyrone/luci-1,dismantl/luci-0.12,aa65535/luci,jlopenwrtluci/luci,keyidadi/luci,zhaoxx063/luci,chris5560/openwrt-luci,chris5560/openwrt-luci,nmav/luci,schidler/ionic-luci,dismantl/luci-0.12,jchuang1977/luci-1,zhaoxx063/luci,obsy/luci,palmettos/test,palmettos/test,david-xiao/luci,male-puppies/luci,ff94315/luci-1,taiha/luci,remakeelectric/luci,LuttyYang/luci,taiha/luci,Kyklas/luci-proto-hso,db260179/openwrt-bpi-r1-luci,ff94315/luci-1,maxrio/luci981213,Hostle/openwrt-luci-multi-user,RedSnake64/openwrt-luci-packages,jorgifumi/luci,thesabbir/luci,deepak78/new-luci,jchuang1977/luci-1,hnyman/luci,nmav/luci,maxrio/luci981213,maxrio/luci981213,sujeet14108/luci,artynet/luci,nwf/openwrt-luci,Sakura-Winkey/LuCI,bittorf/luci,slayerrensky/luci,oyido/luci,taiha/luci,chris5560/openwrt-luci,oyido/luci,jchuang1977/luci-1,RedSnake64/openwrt-luci-packages,cshore/luci,Hostle/openwrt-luci-multi-user,sujeet14108/luci,keyidadi/luci,jlopenwrtluci/luci,teslamint/luci,maxrio/luci981213,Noltari/luci,tobiaswaldvogel/luci,artynet/luci,david-xiao/luci,Kyklas/luci-proto-hso,LazyZhu/openwrt-luci-trunk-mod,keyidadi/luci,teslamint/luci,Noltari/luci,opentechinstitute/luci,hnyman/luci,openwrt/luci,jorgifumi/luci,chris5560/openwrt-luci,cshore/luci,fkooman/luci,oyido/luci,MinFu/luci,nmav/luci,tobiaswaldvogel/luci,kuoruan/luci,palmettos/cnLuCI,remakeelectric/luci,male-puppies/luci,thess/OpenWrt-luci,artynet/luci,daofeng2015/luci,tobiaswaldvogel/luci,zhaoxx063/luci,male-puppies/luci,Sakura-Winkey/LuCI,forward619/luci,981213/luci-1,fkooman/luci,mumuqz/luci,cshore/luci,jorgifumi/luci,wongsyrone/luci-1,LuttyYang/luci,palmettos/cnLuCI,ReclaimYourPrivacy/cloak-luci,opentechinstitute/luci,dwmw2/luci,dwmw2/luci,981213/luci-1,981213/luci-1,aa65535/luci,MinFu/luci,nmav/luci,shangjiyu/luci-with-extra,aircross/OpenWrt-Firefly-LuCI,openwrt-es/openwrt-luci,ReclaimYourPrivacy/cloak-luci,obsy/luci,openwrt/luci,jorgifumi/luci,981213/luci-1,RedSnake64/openwrt-luci-packages,cshore-firmware/openwrt-luci,sujeet14108/luci,thess/OpenWrt-luci,schidler/ionic-luci,tcatm/luci,maxrio/luci981213,thess/OpenWrt-luci,dwmw2/luci,aa65535/luci,maxrio/luci981213,ReclaimYourPrivacy/cloak-luci,mumuqz/luci,RuiChen1113/luci,lbthomsen/openwrt-luci,teslamint/luci,Hostle/openwrt-luci-multi-user,slayerrensky/luci,chris5560/openwrt-luci,fkooman/luci,bright-things/ionic-luci,harveyhu2012/luci,joaofvieira/luci,fkooman/luci,urueedi/luci,db260179/openwrt-bpi-r1-luci,slayerrensky/luci,obsy/luci,kuoruan/lede-luci,artynet/luci,oneru/luci,kuoruan/luci,oneru/luci,marcel-sch/luci,remakeelectric/luci,remakeelectric/luci,Sakura-Winkey/LuCI,artynet/luci,lcf258/openwrtcn,harveyhu2012/luci,jlopenwrtluci/luci,tobiaswaldvogel/luci,LuttyYang/luci,Hostle/luci,florian-shellfire/luci,tcatm/luci,kuoruan/lede-luci,Hostle/openwrt-luci-multi-user,kuoruan/luci,daofeng2015/luci,981213/luci-1,Kyklas/luci-proto-hso,oneru/luci,jchuang1977/luci-1,chris5560/openwrt-luci,nmav/luci,shangjiyu/luci-with-extra,david-xiao/luci,aa65535/luci,Kyklas/luci-proto-hso,jchuang1977/luci-1,mumuqz/luci,wongsyrone/luci-1,thesabbir/luci,jlopenwrtluci/luci,Wedmer/luci,dwmw2/luci,jlopenwrtluci/luci,hnyman/luci
4d9ce9c196050cd54194819b5ccd1e39fe62ad16
src_trunk/resources/item-system/s_drug_system.lua
src_trunk/resources/item-system/s_drug_system.lua
function mixDrugs(drug1, drug2, drug1name, drug2name) exports.global:sendLocalMeAction(source, "mixes some chemicals together.") -- 30 = Cannabis Sativa -- 31 = Cocaine Alkaloid -- 32 = Lysergic Acid -- 33 = Unprocessed PCP -- 34 = Cocaine -- 35 = Drug 2 -- 36 = Drug 3 -- 37 = Drug 4 -- 38 = Marijuana -- 39 = Drug 6 -- 40 = Drug 7 -- 41 = LSD -- 42 = Drug 9 -- 43 = Angel Dust local drugName local drugID if (drug1 == 31 and drug2 == 31) then -- Cocaine drugName = "Cocaine" drugID = 34 elseif (drug1==30 and drug2==31) or (durg1==31 and drug2==30) then -- Drug 2 drugName = "Drug 2" drugID = 35 elseif (drug1==32 and drug2==31) or (drug2==31 and drug1==32) then -- Drug 3 drugName = "Drug 3" drugID = 36 elseif (drug1==33 and drug2==31) or (drug1==31 and drug2==33) then -- Drug 4 drugName = "Drug 4" drugID = 37 elseif (drug1==30 and drug2==30) then -- Marijuana drugName = "Marijuana" drugID = 38 elseif (drug1==30 and drug2==32) or (drug1==32 and drug2==30) then -- Drug 6 drugName = "Drug 6" drugID = 39 elseif (drug1==30 and drug2==33) or (drug1==33 and drug2==30) then -- Drug 7 drugName = "Drug 7" drugID = 40 elseif (drug1==32 and drug2==32) then -- LSD drugName = "LSD" drugID = 41 elseif (drug1==32 and drug2==33) or (drug1==33 and drug2==32) then -- Drug 9 drugName = "Drug 9" drugID = 42 elseif (drug1==33 and drug2==33) then -- Angel Dust drugName = "Angel Dust" drugID = 43 end if (drugName == nil or drugID == nil) then outputChatBox("Error #1000 - Report on http://bugs.valhallagaming.net", source, 255, 0, 0) return end outputChatBox("You mixed '" .. drug1name .. "' and '" .. drug2name .. "' to form '" .. drugName .. "'") exports.global:takePlayerItem(source, drug1, -1) exports.global:takePlayerItem(source, drug2, -1) exports.global:givePlayerItem(source, drugID, 1) end addEvent("mixDrugs", true) addEventHandler("mixDrugs", getRootElement(), mixDrugs)
function mixDrugs(drug1, drug2, drug1name, drug2name) -- 30 = Cannabis Sativa -- 31 = Cocaine Alkaloid -- 32 = Lysergic Acid -- 33 = Unprocessed PCP -- 34 = Cocaine -- 35 = Drug 2 -- 36 = Drug 3 -- 37 = Drug 4 -- 38 = Marijuana -- 39 = Drug 6 -- 40 = Drug 7 -- 41 = LSD -- 42 = Drug 9 -- 43 = Angel Dust local drugName local drugID if (drug1 == 31 and drug2 == 31) then -- Cocaine drugName = "Cocaine" drugID = 34 elseif (drug1==30 and drug2==31) or (drug1==31 and drug2==30) then -- Drug 2 drugName = "Drug 2" drugID = 35 elseif (drug1==32 and drug2==31) or (drug1==31 and drug2==32) then -- Drug 3 drugName = "Drug 3" drugID = 36 elseif (drug1==33 and drug2==31) or (drug1==31 and drug2==33) then -- Drug 4 drugName = "Drug 4" drugID = 37 elseif (drug1==30 and drug2==30) then -- Marijuana drugName = "Marijuana" drugID = 38 elseif (drug1==30 and drug2==32) or (drug1==32 and drug2==30) then -- Drug 6 drugName = "Drug 6" drugID = 39 elseif (drug1==30 and drug2==33) or (drug1==33 and drug2==30) then -- Drug 7 drugName = "Drug 7" drugID = 40 elseif (drug1==32 and drug2==32) then -- LSD drugName = "LSD" drugID = 41 elseif (drug1==32 and drug2==33) or (drug1==33 and drug2==32) then -- Drug 9 drugName = "Drug 9" drugID = 42 elseif (drug1==33 and drug2==33) then -- Angel Dust drugName = "Angel Dust" drugID = 43 end if (drugName == nil or drugID == nil) then outputChatBox("Error #1000 - Report on http://bugs.valhallagaming.net", source, 255, 0, 0) return end exports.global:takePlayerItem(source, drug1, -1) exports.global:takePlayerItem(source, drug2, -1) local given = exports.global:givePlayerItem(source, drugID, 1) if (given) then outputChatBox("You mixed '" .. drug1name .. "' and '" .. drug2name .. "' to form '" .. drugName .. "'", source) exports.global:sendLocalMeAction(source, "mixes some chemicals together.") else outputChatBox("You do not have enough space to mix these chemicals.", source, 255, 0, 0) exports.global:givePlayerItem(source, drug1, 1) exports.global:givePlayerItem(source, drug2, 1) end end addEvent("mixDrugs", true) addEventHandler("mixDrugs", getRootElement(), mixDrugs)
Bug fixes for drugs
Bug fixes for drugs git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@239 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
9bdb537e67bc0eb8f80b7649ed0cf283a52f50eb
fusion/Modules/Lua/test_cryptomatte_utilities.lua
fusion/Modules/Lua/test_cryptomatte_utilities.lua
--[[ Requires : Fusion 9.0.2+ Optional : cjson Created by : Cédric Duriau [[email protected]] Kristof Indeherberge [[email protected]] Andrew Hazelden [[email protected]] Version : 1.2.8 --]] local cryptoutils = require("cryptomatte_utilities") -- utils function collect_tests(module) --[[ Returns function names detected as test. Functions with names starting with "test_" will be picked up. :param module: Module to collect test function names of. :type module: table[string, function] :rtype: table[stri] ]] local tests = {} local substr = "test_" for name, _ in pairs(module) do if string.sub(name, 1, string.len(substr)) == substr then table.insert(tests, name) end end table.sort(tests) return tests end function run_tests(module) --[[ Detects and runs all test functions of a module. :param module: Module to run all tests for. :type module: table[string, function] ]] -- collect all tests from module print("collectings test(s) ...") local tests = collect_tests(module) local ntests = #tests print(string.format("detected %s test(s) ...", ntests)) local count = 0 for _, name in ipairs(tests) do count = count + 1 local percentage = (count / ntests) * 100 local percentage_str = string.format("%.0f%%", percentage) local padding = string.rep(" ", 4 - string.len(percentage_str)) percentage_str = string.format("%s%s", padding, percentage_str) local report = string.format("[%s] %s ... ", percentage_str, name) local status, err = pcall(module[name]) if status then report = string.format("%s [%s]", report, "OK") else report = string.format("%s [%s]\n%s", report, "FAILED", err) end print(report) end end function assert_equal(x, y) --[[ Tests the equality of two variables. :rtype: boolean ]] if x == y then return true else error(string.format("%s\nassertion failed: %s != %s", debug.traceback(), x, y)) end end -- mock funtions storage = {} function mock_print(msg) storage["print_return"] = msg end function mock_log_level_unset() return nil end function mock_log_level_none() return "0" end function mock_log_level_error() return "1" end function mock_log_level_info() return "2" end -- tests module = {} function module.test__log() old_print = print print = mock_print cryptoutils._log("LEVEL", "MESSAGE") print = old_print assert_equal(storage["print_return"], "[Cryptomatte][LEVEL] MESSAGE") end function module.test__get_log_level() old_get_env = os.getenv -- mock log level not set in environment os.getenv = mock_log_level_unset local r1 = cryptoutils._get_log_level() os.getenv = old_get_env assert_equal(r1, 1) -- mock log level set in environment (string -> number cast) os.getenv = mock_log_level_info local r2 = cryptoutils._get_log_level() os.getenv = old_get_env assert_equal(r2, 2) end function module.test__string_starts_with() assert_equal(cryptoutils._string_starts_with("foo_bar", "foo_"), true) assert_equal(cryptoutils._string_starts_with("foo_bar", "bar"), false) end function module.test__string_ends_with() assert_equal(cryptoutils._string_ends_with("foo_bar", "_bar"), true) assert_equal(cryptoutils._string_ends_with("foo_bar", "foo"), false) end function module.test__string_split() result = cryptoutils._string_split("foo, bar,bunny", "([^,]+),?%s*") assert_equal(#result, 3) expected = {"foo", "bar", "bunny"} for i, v in ipairs(result) do assert_equal(v, expected[i]) end end function module.test__solve_channel_name() -- r assert_equal(cryptoutils._solve_channel_name("r"), "r") assert_equal(cryptoutils._solve_channel_name("R"), "r") assert_equal(cryptoutils._solve_channel_name("red"), "r") assert_equal(cryptoutils._solve_channel_name("RED"), "r") -- g assert_equal(cryptoutils._solve_channel_name("g"), "g") assert_equal(cryptoutils._solve_channel_name("G"), "g") assert_equal(cryptoutils._solve_channel_name("green"), "g") assert_equal(cryptoutils._solve_channel_name("GREEN"), "g") -- b assert_equal(cryptoutils._solve_channel_name("b"), "b") assert_equal(cryptoutils._solve_channel_name("B"), "b") assert_equal(cryptoutils._solve_channel_name("blue"), "b") assert_equal(cryptoutils._solve_channel_name("BLUE"), "b") -- a assert_equal(cryptoutils._solve_channel_name("a"), "a") assert_equal(cryptoutils._solve_channel_name("A"), "a") assert_equal(cryptoutils._solve_channel_name("alpha"), "a") assert_equal(cryptoutils._solve_channel_name("ALPHA"), "a") end function module.test__get_channel_hierarchy() -- TODO end function module.test__get_absolute_position() local x, y = cryptoutils._get_absolute_position(10, 10, 0.5, 0.5) assert_equal(x, 5) assert_equal(y, 5) end function module.test__is_position_in_rect() -- NOTE: fusion rectangles follow mathematical convention, (origin=left,bottom) local rect = {left=0, top=10, right=10, bottom=0} assert_equal(cryptoutils._is_position_in_rect(rect, 5, 5), true) assert_equal(cryptoutils._is_position_in_rect(rect, 12, 5), false) assert_equal(cryptoutils._is_position_in_rect(rect, 5, 12), false) end function module.test__hex_to_float() assert_equal(cryptoutils._hex_to_float("3f800000"), 1.0) assert_equal(cryptoutils._hex_to_float("bf800000"), -1.0) end function module.test_log_error() -- TODO end function module.test_log_info() -- TODO end function module.test_get_cryptomatte_metadata() -- TODO end function module.test_read_manifest_file() -- TODO end function module.test_decode_manifest() -- TODO end function module.test_get_matte_names() -- TODO end function module.test_get_screen_matte_name() -- TODO end run_tests(module)
--[[ Requires : Fusion 9.0.2+ Optional : cjson Created by : Cédric Duriau [[email protected]] Kristof Indeherberge [[email protected]] Andrew Hazelden [[email protected]] Version : 1.2.8 --]] local cryptoutils = require("cryptomatte_utilities") -- utils function collect_tests(module) --[[ Returns function names detected as test. Functions with names starting with "test_" will be picked up. :param module: Module to collect test function names of. :type module: table[string, function] :rtype: table[stri] ]] local tests = {} local substr = "test_" for name, _ in pairs(module) do if string.sub(name, 1, string.len(substr)) == substr then table.insert(tests, name) end end table.sort(tests) return tests end function run_tests(module) --[[ Detects and runs all test functions of a module. :param module: Module to run all tests for. :type module: table[string, function] ]] -- collect all tests from module print("collectings test(s) ...") local tests = collect_tests(module) local ntests = #tests print(string.format("detected %s test(s) ...", ntests)) local count = 0 for _, name in ipairs(tests) do count = count + 1 local percentage = (count / ntests) * 100 local percentage_str = string.format("%.0f%%", percentage) local padding = string.rep(" ", 4 - string.len(percentage_str)) percentage_str = string.format("%s%s", padding, percentage_str) local report = string.format("[%s] %s ... ", percentage_str, name) local status, err = pcall(module[name]) if status then report = string.format("%s [%s]", report, "OK") else report = string.format("%s [%s]\n%s", report, "FAILED", err) end print(report) end end function assert_equal(x, y) --[[ Tests the equality of two variables. :rtype: boolean ]] if x == y then return true else error(string.format("%s\nassertion failed: %s != %s", debug.traceback(), x, y)) end end -- mock funtions storage = {} function mock_print(msg) storage["print_return"] = msg end function mock_log_level_unset() return nil end function mock_log_level_error() return "0" end function mock_log_level_warning() return "1" end function mock_log_level_info() return "2" end function mock_node() return {Name="NODE1"} end -- tests module = {} function module.test__format_log() old_self = self self = mock_node() local result = cryptoutils._format_log("LEVEL", "MESSAGE") self = old_self assert_equal(result, "[Cryptomatte][NODE1][LEVEL] MESSAGE") end function module.test__get_log_level() old_get_env = os.getenv -- mock log level not set in environment os.getenv = mock_log_level_unset local r1 = cryptoutils._get_log_level() os.getenv = old_get_env assert_equal(r1, 0) -- mock log level info set in environment (string -> number cast) os.getenv = mock_log_level_info local r2 = cryptoutils._get_log_level() os.getenv = old_get_env assert_equal(r2, 2) end function module.test__string_starts_with() assert_equal(cryptoutils._string_starts_with("foo_bar", "foo_"), true) assert_equal(cryptoutils._string_starts_with("foo_bar", "bar"), false) end function module.test__string_ends_with() assert_equal(cryptoutils._string_ends_with("foo_bar", "_bar"), true) assert_equal(cryptoutils._string_ends_with("foo_bar", "foo"), false) end function module.test__string_split() result = cryptoutils._string_split("foo, bar,bunny", "([^,]+),?%s*") assert_equal(#result, 3) expected = {"foo", "bar", "bunny"} for i, v in ipairs(result) do assert_equal(v, expected[i]) end end function module.test__solve_channel_name() -- r assert_equal(cryptoutils._solve_channel_name("r"), "r") assert_equal(cryptoutils._solve_channel_name("R"), "r") assert_equal(cryptoutils._solve_channel_name("red"), "r") assert_equal(cryptoutils._solve_channel_name("RED"), "r") -- g assert_equal(cryptoutils._solve_channel_name("g"), "g") assert_equal(cryptoutils._solve_channel_name("G"), "g") assert_equal(cryptoutils._solve_channel_name("green"), "g") assert_equal(cryptoutils._solve_channel_name("GREEN"), "g") -- b assert_equal(cryptoutils._solve_channel_name("b"), "b") assert_equal(cryptoutils._solve_channel_name("B"), "b") assert_equal(cryptoutils._solve_channel_name("blue"), "b") assert_equal(cryptoutils._solve_channel_name("BLUE"), "b") -- a assert_equal(cryptoutils._solve_channel_name("a"), "a") assert_equal(cryptoutils._solve_channel_name("A"), "a") assert_equal(cryptoutils._solve_channel_name("alpha"), "a") assert_equal(cryptoutils._solve_channel_name("ALPHA"), "a") end function module.test__get_channel_hierarchy() -- TODO end function module.test__get_absolute_position() local x, y = cryptoutils._get_absolute_position(10, 10, 0.5, 0.5) assert_equal(x, 5) assert_equal(y, 5) end function module.test__is_position_in_rect() -- NOTE: fusion rectangles follow mathematical convention, (origin=left,bottom) local rect = {left=0, top=10, right=10, bottom=0} assert_equal(cryptoutils._is_position_in_rect(rect, 5, 5), true) assert_equal(cryptoutils._is_position_in_rect(rect, 12, 5), false) assert_equal(cryptoutils._is_position_in_rect(rect, 5, 12), false) end function module.test__hex_to_float() assert_equal(cryptoutils._hex_to_float("3f800000"), 1.0) assert_equal(cryptoutils._hex_to_float("bf800000"), -1.0) end function module.test_log_error() -- TODO end function module.test_log_info() -- TODO end function module.test_get_cryptomatte_metadata() -- TODO end function module.test_read_manifest_file() -- TODO end function module.test_decode_manifest() -- TODO end function module.test_get_matte_names() -- TODO end run_tests(module)
fix log levels; remove _log; add _format_log test
fix log levels; remove _log; add _format_log test
Lua
bsd-3-clause
Psyop/Cryptomatte
40249240001c7c58bd19e205fe597fe9d5b523dc
configure.lua
configure.lua
require "package" require "debug" local deps = require "configure.dependency" local cxx = require "configure.lang.cxx" local c = require "configure.lang.c" local version = '0.0.1' function configure(build) build:status("Building on", build:host():os_string()) local with_coverage = build:bool_option( "coverage", "Enable coverage build", false ) local build_type = build:string_option( "build_type", "Set build type", 'debug' ):lower() if with_coverage then print("Coverage enabled:", with_coverage) end local fs = build:fs() for i, p in pairs(fs:rglob("src/lib/configure", "*.lua")) do fs:copy( p, "share/configure/lib/configure" / p:relative_path(build:project_directory() / "src/lib/configure") ) end local compiler = cxx.compiler.find{ build = build, standard = 'c++11', } lua_srcs = { "lua/src/lapi.c", "lua/src/lcode.c", "lua/src/lctype.c", "lua/src/ldebug.c", "lua/src/ldo.c", "lua/src/ldump.c", "lua/src/lfunc.c", "lua/src/lgc.c", "lua/src/llex.c", "lua/src/lmem.c", "lua/src/lobject.c", "lua/src/lopcodes.c", "lua/src/lparser.c", "lua/src/lstate.c", "lua/src/lstring.c", "lua/src/ltable.c", "lua/src/ltm.c", "lua/src/lundump.c", "lua/src/lvm.c", "lua/src/lzio.c", "lua/src/lauxlib.c", "lua/src/lbaselib.c", "lua/src/lbitlib.c", "lua/src/lcorolib.c", "lua/src/ldblib.c", "lua/src/liolib.c", "lua/src/lmathlib.c", "lua/src/loslib.c", "lua/src/lstrlib.c", "lua/src/ltablib.c", "lua/src/loadlib.c", "lua/src/linit.c", } local lua = compiler:link_static_library{ name = "lua", directory = "lib", sources = lua_srcs, include_directories = {"lua/src"}, object_directory = 'objects', } local libs = {lua,} local library_directories = {} local include_directories = {'src'} table.extend(libs, cxx.libraries.boost.find{ compiler = compiler, env_prefix = 'boost', components = { 'filesystem', 'serialization', 'iostreams', 'exception', 'system', } }) if build:host():os() == Platform.OS.windows then build:status("XXX Using boost auto link feature") table.extend(libs, { cxx.Library:new{name = 'Shlwapi', system = true, kind = 'static'}, }) end local libconfigure = compiler:link_static_library{ name = 'configure', sources = fs:rglob("src/configure", "*.cpp"), include_directories = include_directories, library_directories = library_directories, libraries = libs, coverage = with_coverage, defines = { {'CONFIGURE_VERSION_STRING', '\"' .. build_type .. '-' .. version .. '\"'} } } local configure_exe = compiler:link_executable{ name = "configure", sources = {'src/main.cpp'}, libraries = table.extend({libconfigure}, libs), include_directories = include_directories, library_directories = library_directories, coverage = with_coverage, runtime = 'static' } local test_libs = table.extend({libconfigure}, libs) table.extend(test_libs, cxx.libraries.boost.find{ compiler = compiler, env_prefix = 'boost2', components = {'unit_test_framework'}, kind = 'shared', }) local defines = {} local test_include_directories = table.append({}, 'test/unit') local unit_tests = Rule:new():add_target(build:virtual_node("check")) for i, src in pairs(fs:rglob("test/unit", "*.cpp")) do local test_name = src:path():stem() local defines = {{"BOOST_TEST_MODULE", test_name},} if tostring(test_name) == 'process' then table.append(defines, "BOOST_TEST_IGNORE_SIGCHLD") end local bin = compiler:link_executable{ name = test_name, directory = 'test/unit', sources = {src, }, libraries = test_libs, defines = defines, include_directories = test_include_directories, include_files = { ( build:host():os() == Platform.OS.osx and 'boost/test/unit_test.hpp' or 'boost/test/included/unit_test.hpp' ), }, coverage = with_coverage, library_directories = library_directories, } unit_tests:add_source(bin) unit_tests:add_shell_command(ShellCommand:new(bin)) end build:add_rule(unit_tests) end
require "package" require "debug" local deps = require "configure.dependency" local cxx = require "configure.lang.cxx" local c = require "configure.lang.c" local version = '0.0.1' function configure(build) build:status("Building on", build:host():os_string()) local with_coverage = build:bool_option( "coverage", "Enable coverage build", false ) local build_type = build:string_option( "build_type", "Set build type", 'debug' ):lower() if with_coverage then print("Coverage enabled:", with_coverage) end local fs = build:fs() for i, p in pairs(fs:rglob("src/lib/configure", "*.lua")) do fs:copy( p, "share/configure/lib/configure" / p:relative_path(build:project_directory() / "src/lib/configure") ) end local compiler = cxx.compiler.find{ build = build, standard = 'c++11', } lua_srcs = { "lua/src/lapi.c", "lua/src/lcode.c", "lua/src/lctype.c", "lua/src/ldebug.c", "lua/src/ldo.c", "lua/src/ldump.c", "lua/src/lfunc.c", "lua/src/lgc.c", "lua/src/llex.c", "lua/src/lmem.c", "lua/src/lobject.c", "lua/src/lopcodes.c", "lua/src/lparser.c", "lua/src/lstate.c", "lua/src/lstring.c", "lua/src/ltable.c", "lua/src/ltm.c", "lua/src/lundump.c", "lua/src/lvm.c", "lua/src/lzio.c", "lua/src/lauxlib.c", "lua/src/lbaselib.c", "lua/src/lbitlib.c", "lua/src/lcorolib.c", "lua/src/ldblib.c", "lua/src/liolib.c", "lua/src/lmathlib.c", "lua/src/loslib.c", "lua/src/lstrlib.c", "lua/src/ltablib.c", "lua/src/loadlib.c", "lua/src/linit.c", } local lua = compiler:link_static_library{ name = "lua", directory = "lib", sources = lua_srcs, include_directories = {"lua/src"}, object_directory = 'objects', } local libs = {lua,} local library_directories = {} local include_directories = {'src'} table.extend(libs, cxx.libraries.boost.find{ compiler = compiler, components = { 'filesystem', 'serialization', 'iostreams', 'exception', 'system', } }) if build:host():os() == Platform.OS.windows then build:status("XXX Using boost auto link feature") table.extend(libs, { cxx.Library:new{name = 'Shlwapi', system = true, kind = 'static'}, }) end local libconfigure = compiler:link_static_library{ name = 'configure', sources = fs:rglob("src/configure", "*.cpp"), include_directories = include_directories, library_directories = library_directories, libraries = libs, coverage = with_coverage, defines = { {'CONFIGURE_VERSION_STRING', '\"' .. build_type .. '-' .. version .. '\"'} } } local configure_exe = compiler:link_executable{ name = "configure", sources = {'src/main.cpp'}, libraries = table.extend({libconfigure}, libs), include_directories = include_directories, library_directories = library_directories, coverage = with_coverage, runtime = 'static' } local test_libs = table.extend({libconfigure}, libs) table.extend(test_libs, cxx.libraries.boost.find{ compiler = compiler, components = {'unit_test_framework'}, kind = 'shared', }) local defines = {} local test_include_directories = table.append({}, 'test/unit') local unit_tests = Rule:new():add_target(build:virtual_node("check")) for i, src in pairs(fs:rglob("test/unit", "*.cpp")) do local test_name = src:path():stem() local defines = {{"BOOST_TEST_MODULE", test_name},} if tostring(test_name) == 'process' then table.append(defines, "BOOST_TEST_IGNORE_SIGCHLD") end local bin = compiler:link_executable{ name = test_name, directory = 'test/unit', sources = {src, }, libraries = test_libs, defines = defines, include_directories = test_include_directories, include_files = { ( build:host():os() == Platform.OS.osx and 'boost/test/unit_test.hpp' or 'boost/test/included/unit_test.hpp' ), }, coverage = with_coverage, library_directories = library_directories, } unit_tests:add_source(bin) unit_tests:add_shell_command(ShellCommand:new(bin)) end build:add_rule(unit_tests) end
Remove custom env prefix from boost find invocations.
Remove custom env prefix from boost find invocations.
Lua
bsd-3-clause
hotgloupi/configure,hotgloupi/configure,hotgloupi/configure,hotgloupi/configure,hotgloupi/configure
b3828420c14bc13c96eb9257ac935f4dcf5dc488
tests/test-fs-readfile-zero-byte-liar.lua
tests/test-fs-readfile-zero-byte-liar.lua
--[[ Copyright 2012-2015 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License") you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] require('tap')(function(test) local FS = require('fs') local Path = require('path') local Buffer = require('buffer').Buffer local string = require('string') local __filename = module.path local dataExpected = FS.readFileSync(__filename) test('fs readfile zero byte liar', function() -- sometimes stat returns size=0, but it's a lie. FS._fstat = FS.fstat FS._fstatSync = FS.fstatSync FS.fstat = function(fd, cb) FS._fstat(fd, function(er, st) if er then return cb(er) end st.size = 0 return cb(er, st) end) end FS.fstatSync = function(fd) local st = FS._fstatSync st.size = 0 return st end local d = FS.readFileSync(__filename) assert(d == dataExpected) FS.readFile(__filename, function (er, d) assert(d == dataExpected) end) end) end)
--[[ Copyright 2012-2015 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License") you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] require('tap')(function(test) local FS = require('fs') local Path = require('path') local Buffer = require('buffer').Buffer local string = require('string') local __filename = module.path local dataExpected = FS.readFileSync(__filename) test('fs readfile zero byte liar', function() -- sometimes stat returns size=0, but it's a lie. local _fstat,_fstatSync = FS.fstat,FS.fstatSync FS._fstat = FS.fstat FS._fstatSync = FS.fstatSync FS.fstat = function(fd, cb) FS._fstat(fd, function(er, st) if er then return cb(er) end st.size = 0 return cb(er, st) end) end FS.fstatSync = function(fd) local st = FS._fstatSync st.size = 0 return st end local d = FS.readFileSync(__filename) assert(d == dataExpected) FS.readFile(__filename, function (er, d) assert(d == dataExpected) FS.fstat,FS.fstatSync = _fstat,_fstatSync end) end) end)
fix bug in test-fs-readfile-zero-byte-liar.lua
fix bug in test-fs-readfile-zero-byte-liar.lua
Lua
apache-2.0
kaustavha/luvit,zhaozg/luvit,bsn069/luvit,luvit/luvit,luvit/luvit,zhaozg/luvit,kaustavha/luvit,bsn069/luvit,bsn069/luvit,kaustavha/luvit
eab730cb61154ecd4e67276bcda005eca2325cfa
extensions/tabs/init.lua
extensions/tabs/init.lua
--- === hs.tabs === --- --- Place the windows of an application into tabs drawn on its titlebar local tabs = {} local drawing = require "hs.drawing" local uielement = require "hs.uielement" local watcher = uielement.watcher local fnutils = require "hs.fnutils" local timer = require "hs.timer" local application = require "hs.application" local appwatcher = application.watcher tabs.leftPad = 10 tabs.topPad = 2 tabs.tabPad = 2 tabs.tabWidth = 80 tabs.tabHeight = 17 tabs.tabRound = 4 tabs.textLeftPad = 2 tabs.textTopPad = 2 tabs.textSize = 10 tabs.fillColor = {red = 1.0, green = 1.0, blue = 1.0, alpha = 0.5} tabs.selectedColor = {red = .9, green = .9, blue = .9, alpha = 0.5} tabs.strokeColor = {red = 0.0, green = 0.0, blue = 0.0, alpha = 0.7} tabs.textColor = {red = 0.0, green = 0.0, blue = 0.0, alpha = 0.6} tabs.maxTitle = 11 local function realWindow(win) -- AXScrollArea is weird role of special finder desktop window return (win:isStandard() and win:role() ~= "AXScrollArea") end --- hs.tabs.tabWindows(app) --- Function --- Gets a list of the tabs of a window --- --- Parameters: --- * app - An `hs.application` object --- --- Returns: --- * An array of the tabbed windows of an app in the same order as they would be tabbed --- --- Notes: --- * This function can be used when writing tab switchers function tabs.tabWindows(app) local tabWins = fnutils.filter(app:allWindows(),realWindow) table.sort(tabWins, function(a,b) return a:title() < b:title() end) return tabWins end local drawTable = {} local function trashTabs(pid) local tab = drawTable[pid] if not tab then return end for i,obj in ipairs(tab) do obj:delete() end end local function drawTabs(app) local pid = app:pid() trashTabs(pid) drawTable[pid] = {} local proto = app:focusedWindow() if not proto or not app:isFrontmost() then return end local geom = app:focusedWindow():frame() local tabWins = tabs.tabWindows(app) local pt = {x = geom.x+geom.w-tabs.leftPad, y = geom.y+tabs.topPad} local objs = drawTable[pid] -- iterate in reverse order because we draw right to left local numTabs = #tabWins for i=0,(numTabs-1) do local win = tabWins[numTabs-i] pt.x = pt.x - tabs.tabWidth - tabs.tabPad local r = drawing.rectangle({x=pt.x,y=pt.y,w=tabs.tabWidth,h=tabs.tabHeight}) r:setClickCallback(nil, function() tabs.focusTab(app, #tabs.tabWindows(app) - i) end) r:setFill(true) if win == proto then r:setFillColor(tabs.selectedColor) else r:setFillColor(tabs.fillColor) end r:setStrokeColor(tabs.strokeColor) r:setRoundedRectRadii(tabs.tabRound,tabs.tabRound) r:bringToFront() r:show() table.insert(objs,r) local tabText = win:title():sub(1,tabs.maxTitle) local t = drawing.text({x=pt.x+tabs.textLeftPad,y=pt.y+tabs.textTopPad, w=tabs.tabWidth,h=tabs.tabHeight},tabText) t:setTextSize(tabs.textSize) t:setTextColor(tabs.textColor) t:show() table.insert(objs,t) end end local function reshuffle(app) local proto = app:focusedWindow() if not proto then return end local geom = app:focusedWindow():frame() for i,win in ipairs(app:allWindows()) do if win:isStandard() then win:setFrame(geom) end end drawTabs(app) end local function manageWindow(win, app) if not win:isStandard() then return end -- only trigger on focused window movements otherwise the reshuffling triggers itself local newWatch = win:newWatcher(function(el,ev,wat,ud) if el == app:focusedWindow() then reshuffle(app) end end) newWatch:start({watcher.windowMoved, watcher.windowResized, watcher.elementDestroyed}) local redrawWatch = win:newWatcher(function (el,ev,wat,ud) drawTabs(app) end) redrawWatch:start({watcher.elementDestroyed, watcher.titleChanged}) -- resize this window to match possible others local notThis = fnutils.filter(app:allWindows(), function(x) return (x ~= win and realWindow(x)) end) local protoWindow = notThis[1] if protoWindow then print("Prototyping to '" .. protoWindow:title() .. "'") win:setFrame(protoWindow:frame()) end end local function watchApp(app) -- print("Enabling tabs for " .. app:title()) for i,win in ipairs(app:allWindows()) do manageWindow(win,app) end local winWatch = app:newWatcher(function(el,ev,wat,appl) manageWindow(el,appl) end,app) winWatch:start({watcher.windowCreated}) local redrawWatch = app:newWatcher(function (el,ev,wat,ud) drawTabs(app) end) redrawWatch:start({watcher.applicationActivated, watcher.applicationDeactivated, watcher.applicationHidden, watcher.focusedWindowChanged}) reshuffle(app) end local appWatcherStarted = false local appWatches = {} --- hs.tabs.enableForApp(app) --- Function --- Places all the windows of an app into one place and tab them --- --- Parameters: --- * app - An `hs.application` object or the app title --- --- Returns: --- * None function tabs.enableForApp(app) if type(app) == "string" then appWatches[app] = true app = application.get(app) end -- might already be running if app then watchApp(app) end -- set up a watcher to catch any watched app launching or terminating if appWatcherStarted then return end appWatcherStarted = true local watch = appwatcher.new(function(name,event,app) -- print("Event from " .. name) if event == appwatcher.launched and appWatches[name] then watchApp(app) elseif event == appwatcher.terminated then trashTabs(app:pid()) end end) watch:start() end --- hs.tabs.focusTab(app, num) --- Function --- Focuses a specific tab of an app --- --- Parameters: --- * app - An `hs.application` object previously enabled for tabbing --- * num - A tab number to switch to --- --- Returns: --- * None --- --- Notes: --- * If num is higher than the number of tabs, the last tab will be focussed function tabs.focusTab(app,num) if not app or not appWatches[app:title()] then return end local tabs = tabs.tabWindows(app) local bounded = num --print(hs.inspect(tabs)) if num > #tabs then bounded = #tabs end tabs[bounded]:focus() end return tabs
--- === hs.tabs === --- --- Place the windows of an application into tabs drawn on its titlebar local tabs = {} local drawing = require "hs.drawing" local uielement = require "hs.uielement" local watcher = uielement.watcher local fnutils = require "hs.fnutils" local application = require "hs.application" local appwatcher = application.watcher tabs.leftPad = 10 tabs.topPad = 2 tabs.tabPad = 2 tabs.tabWidth = 80 tabs.tabHeight = 17 tabs.tabRound = 4 tabs.textLeftPad = 2 tabs.textTopPad = 2 tabs.textSize = 10 tabs.fillColor = {red = 1.0, green = 1.0, blue = 1.0, alpha = 0.5} tabs.selectedColor = {red = .9, green = .9, blue = .9, alpha = 0.5} tabs.strokeColor = {red = 0.0, green = 0.0, blue = 0.0, alpha = 0.7} tabs.textColor = {red = 0.0, green = 0.0, blue = 0.0, alpha = 0.6} tabs.maxTitle = 11 local function realWindow(win) -- AXScrollArea is weird role of special finder desktop window return (win:isStandard() and win:role() ~= "AXScrollArea") end --- hs.tabs.tabWindows(app) --- Function --- Gets a list of the tabs of a window --- --- Parameters: --- * app - An `hs.application` object --- --- Returns: --- * An array of the tabbed windows of an app in the same order as they would be tabbed --- --- Notes: --- * This function can be used when writing tab switchers function tabs.tabWindows(app) local tabWins = fnutils.filter(app:allWindows(),realWindow) table.sort(tabWins, function(a,b) return a:title() < b:title() end) return tabWins end local drawTable = {} local function trashTabs(pid) local tab = drawTable[pid] if not tab then return end for _,obj in ipairs(tab) do obj:delete() end end local function drawTabs(app) local pid = app:pid() trashTabs(pid) drawTable[pid] = {} local proto = app:focusedWindow() if not proto or not app:isFrontmost() then return end local geom = app:focusedWindow():frame() local tabWins = tabs.tabWindows(app) local pt = {x = geom.x+geom.w-tabs.leftPad, y = geom.y+tabs.topPad} local objs = drawTable[pid] -- iterate in reverse order because we draw right to left local numTabs = #tabWins for i=0,(numTabs-1) do local win = tabWins[numTabs-i] pt.x = pt.x - tabs.tabWidth - tabs.tabPad local r = drawing.rectangle({x=pt.x,y=pt.y,w=tabs.tabWidth,h=tabs.tabHeight}) r:setClickCallback(nil, function() tabs.focusTab(app, #tabs.tabWindows(app) - i) end) r:setFill(true) if win == proto then r:setFillColor(tabs.selectedColor) else r:setFillColor(tabs.fillColor) end r:setStrokeColor(tabs.strokeColor) r:setRoundedRectRadii(tabs.tabRound,tabs.tabRound) r:bringToFront() r:show() table.insert(objs,r) local tabText = win:title():sub(1,tabs.maxTitle) local t = drawing.text({x=pt.x+tabs.textLeftPad,y=pt.y+tabs.textTopPad, w=tabs.tabWidth,h=tabs.tabHeight},tabText) t:setTextSize(tabs.textSize) t:setTextColor(tabs.textColor) t:show() table.insert(objs,t) end end local function reshuffle(app) local proto = app:focusedWindow() if not proto then return end local geom = app:focusedWindow():frame() for _,win in ipairs(app:allWindows()) do if win:isStandard() then win:setFrame(geom) end end drawTabs(app) end local function manageWindow(win, app) if not win:isStandard() then return end -- only trigger on focused window movements otherwise the reshuffling triggers itself local newWatch = win:newWatcher(function(el) if el == app:focusedWindow() then reshuffle(app) end end) newWatch:start({watcher.windowMoved, watcher.windowResized, watcher.elementDestroyed}) local redrawWatch = win:newWatcher(function () drawTabs(app) end) redrawWatch:start({watcher.elementDestroyed, watcher.titleChanged}) -- resize this window to match possible others local notThis = fnutils.filter(app:allWindows(), function(x) return (x ~= win and realWindow(x)) end) local protoWindow = notThis[1] if protoWindow then print("Prototyping to '" .. protoWindow:title() .. "'") win:setFrame(protoWindow:frame()) end end local function watchApp(app) -- print("Enabling tabs for " .. app:title()) for _,win in ipairs(app:allWindows()) do manageWindow(win,app) end local winWatch = app:newWatcher(function(el,_,_,appl) manageWindow(el,appl) end,app) winWatch:start({watcher.windowCreated}) local redrawWatch = app:newWatcher(function () drawTabs(app) end) redrawWatch:start({watcher.applicationActivated, watcher.applicationDeactivated, watcher.applicationHidden, watcher.focusedWindowChanged}) reshuffle(app) end local appWatcherStarted = false local appWatches = {} --- hs.tabs.enableForApp(app) --- Function --- Places all the windows of an app into one place and tab them --- --- Parameters: --- * app - An `hs.application` object or the app title --- --- Returns: --- * None function tabs.enableForApp(app) if type(app) == "string" then appWatches[app] = true app = application.get(app) end -- might already be running if app then watchApp(app) end -- set up a watcher to catch any watched app launching or terminating if appWatcherStarted then return end appWatcherStarted = true local watch = appwatcher.new(function(name,event,theApp) -- print("Event from " .. name) if event == appwatcher.launched and appWatches[name] then watchApp(theApp) elseif event == appwatcher.terminated then trashTabs(theApp:pid()) end end) watch:start() end --- hs.tabs.focusTab(app, num) --- Function --- Focuses a specific tab of an app --- --- Parameters: --- * app - An `hs.application` object previously enabled for tabbing --- * num - A tab number to switch to --- --- Returns: --- * None --- --- Notes: --- * If num is higher than the number of tabs, the last tab will be focussed function tabs.focusTab(app,num) if not app or not appWatches[app:title()] then return end local theTabs = tabs.tabWindows(app) local bounded = num --print(hs.inspect(tabs)) if num > #theTabs then bounded = #theTabs end theTabs[bounded]:focus() end return tabs
Cleanup hs.tabs
Cleanup hs.tabs - Fixed @stickler-ci bugs
Lua
mit
Hammerspoon/hammerspoon,Hammerspoon/hammerspoon,Habbie/hammerspoon,asmagill/hammerspoon,Hammerspoon/hammerspoon,cmsj/hammerspoon,latenitefilms/hammerspoon,cmsj/hammerspoon,Hammerspoon/hammerspoon,cmsj/hammerspoon,latenitefilms/hammerspoon,Habbie/hammerspoon,CommandPost/CommandPost-App,Habbie/hammerspoon,latenitefilms/hammerspoon,latenitefilms/hammerspoon,Habbie/hammerspoon,cmsj/hammerspoon,latenitefilms/hammerspoon,latenitefilms/hammerspoon,Hammerspoon/hammerspoon,asmagill/hammerspoon,asmagill/hammerspoon,CommandPost/CommandPost-App,asmagill/hammerspoon,Habbie/hammerspoon,CommandPost/CommandPost-App,cmsj/hammerspoon,CommandPost/CommandPost-App,CommandPost/CommandPost-App,Habbie/hammerspoon,asmagill/hammerspoon,asmagill/hammerspoon,cmsj/hammerspoon,CommandPost/CommandPost-App,Hammerspoon/hammerspoon
9f9d5bc3dec0d08df7dbb27dabb809d355f17cb3
love2d/world.lua
love2d/world.lua
require "tileset" require "map" require "pawn" require "mapGenerator" function love.game.newWorld() local o = {} o.mapG = nil o.map = nil o.mapWidth = 32 o.mapHeight = 24 o.tileset = nil o.offsetX = 0 o.offsetY = 0 o.zoom = 1 o.offsetX = 0 o.offsetY = 0 o.goalX = 7 o.goalY =7 o.init = function() o.mapG = MapGenerator.newMap(o.mapWidth, o.mapHeight) o.tileset = love.game.newTileset("res/gfx/tileset.png", 32, 32, 1) o.map = love.game.newMap(o.mapWidth, o.mapHeight) o.map.setTileset(o.tileset) o.map.init() --test for i = 1, o.mapWidth do for k = 1, o.mapHeight do -- field if MapGenerator.getID(o.mapG, i, k) == 1 then o.map.setTileLayer(i, k, 1, 0) elseif MapGenerator.getID(o.mapG, i, k) == 2 then o.map.setTileLayer(i, k, 1, 2) end --objects if MapGenerator.getObject(o.mapG, i, k) == 1 then o.map.setTileLayer(i, k, 2, 3) elseif MapGenerator.getObject(o.mapG, i, k) == 2 then o.map.setTileLayer(i, k, 2, 22) elseif MapGenerator.getObject(o.mapG, i, k) == 4 then o.map.setTileLayer(i, k, 2, 18) else o.map.setTileLayer(i, k, 2, 63) end --objects 2 if MapGenerator.getObject(o.mapG, i, k) == 2 then o.map.setTileLayer(i, k - 1, 3, 14) else o.map.setTileLayer(i, k - 1, 3, 63) end end end o.pawns = {} local pawn = love.game.newPawn(o) table.insert(o.pawns, pawn) end o.update = function(dt) if love.keyboard.isDown("left") then o.offsetX = o.offsetX + dt * 100 elseif love.keyboard.isDown("right") then o.offsetX = o.offsetX - dt * 100 end if love.keyboard.isDown("up") then o.offsetY = o.offsetY + dt * 100 elseif love.keyboard.isDown("down") then o.offsetY = o.offsetY - dt * 100 end o.map.update(dt) for i = 1, #o.pawns do o.pawns[i].update(dt) end for i = 1, o.mapWidth do for k = 1, o.mapHeight do if MapGenerator.getObject(o.mapG, i, k) == 4 then o.map.setTileLayer(i, k, 2, 18 + math.floor((love.timer.getTime() * 10) % 4)) end end end end o.draw = function() o.map.draw(o.offsetX * o.zoom, o.offsetY * o.zoom, 1) for i = 1, #o.pawns do o.pawns[i].draw(o.offsetX, o.offsetY) end o.map.draw(o.offsetX * o.zoom, o.offsetY * o.zoom, 2) o.map.draw(o.offsetX * o.zoom, o.offsetY * o.zoom, 3) o.drawMapCursor() end o.zoomIn = function(z) z = z or 2 o.zoom = o.zoom * z o.map.setZoom(o.zoom) for i = 1, #o.pawns do o.pawns[i].setZoom(o.zoom) end end o.zoomOut = function(z) z = z or 2 o.zoom = o.zoom / z o.map.setZoom(o.zoom) for i = 1, #o.pawns do o.pawns[i].setZoom(o.zoom) end end o.drawMapCursor = function() local mx = love.mouse.getX() local my = love.mouse.getY() local tileX, tileY = getTileFromScreen(o.map,mx, my) tileX = tileX * o.map.tileScale tileY = tileY * o.map.tileScale if tileX >= 0 and tileY >= 0 and tileX < o.map.width and tileY < o.map.height then G.setColor(255, 63, 0) G.setLineWidth(2) local tw = o.map.tileset.tileWidth local th = o.map.tileset.tileHeight if tw and th then G.rectangle("line", tileX * tw*o.zoom - o.offsetX , tileY * th*o.zoom - o.offsetY, tw*o.zoom*o.map.tileScale, th*o.zoom*o.map.tileScale) end end end o.setGoal = function(map, x,y) o.goalX, o.goalY = getTileFromScreen(map,x,y) print (x, y, o.goalX, o.goalY) end return o end getTileFromScreen = function(map, mx, my) local ts = map.tileScale local tw = map.tileset.tileWidth local th = map.tileset.tileHeight local tileX =math.floor((mx) / (tw*ts)) local tileY =math.floor((my) / (tw*ts)) return tileX, tileY end
require "tileset" require "map" require "pawn" require "mapGenerator" function love.game.newWorld() local o = {} o.mapG = nil o.map = nil o.mapWidth = 32 o.mapHeight = 24 o.tileset = nil o.offsetX = 0 o.offsetY = 0 o.zoom = 1 o.offsetX = 0 o.offsetY = 0 o.goalX = 7 o.goalY =7 o.init = function() o.mapG = MapGenerator.newMap(o.mapWidth, o.mapHeight) o.tileset = love.game.newTileset("res/gfx/tileset.png", 32, 32, 1) o.map = love.game.newMap(o.mapWidth, o.mapHeight) o.map.setTileset(o.tileset) o.map.init() --test for i = 1, o.mapWidth do for k = 1, o.mapHeight do -- field if MapGenerator.getID(o.mapG, i, k) == 1 then o.map.setTileLayer(i, k, 1, 0) elseif MapGenerator.getID(o.mapG, i, k) == 2 then o.map.setTileLayer(i, k, 1, 2) end --objects if MapGenerator.getObject(o.mapG, i, k) == 1 then o.map.setTileLayer(i, k, 2, 3) elseif MapGenerator.getObject(o.mapG, i, k) == 2 then o.map.setTileLayer(i, k, 2, 22) elseif MapGenerator.getObject(o.mapG, i, k) == 4 then o.map.setTileLayer(i, k, 2, 18) else o.map.setTileLayer(i, k, 2, 63) end --objects 2 if MapGenerator.getObject(o.mapG, i, k) == 2 then o.map.setTileLayer(i, k - 1, 3, 14) else o.map.setTileLayer(i, k - 1, 3, 63) end end end o.pawns = {} local pawn = love.game.newPawn(o) table.insert(o.pawns, pawn) end o.update = function(dt) if love.keyboard.isDown("left") then o.offsetX = o.offsetX + dt * 100 elseif love.keyboard.isDown("right") then o.offsetX = o.offsetX - dt * 100 end if love.keyboard.isDown("up") then o.offsetY = o.offsetY + dt * 100 elseif love.keyboard.isDown("down") then o.offsetY = o.offsetY - dt * 100 end o.map.update(dt) for i = 1, #o.pawns do o.pawns[i].update(dt) end for i = 1, o.mapWidth do for k = 1, o.mapHeight do if MapGenerator.getObject(o.mapG, i, k) == 4 then o.map.setTileLayer(i, k, 2, 18 + math.floor((love.timer.getTime() * 10) % 4)) end end end end o.draw = function() o.map.draw(o.offsetX * o.zoom, o.offsetY * o.zoom, 1) for i = 1, #o.pawns do o.pawns[i].draw(o.offsetX, o.offsetY) end o.map.draw(o.offsetX * o.zoom, o.offsetY * o.zoom, 2) o.map.draw(o.offsetX * o.zoom, o.offsetY * o.zoom, 3) o.drawMapCursor() end o.zoomIn = function(z) z = z or 2 o.zoom = o.zoom * z o.map.setZoom(o.zoom) for i = 1, #o.pawns do o.pawns[i].setZoom(o.zoom) end end o.zoomOut = function(z) z = z or 2 o.zoom = o.zoom / z o.map.setZoom(o.zoom) for i = 1, #o.pawns do o.pawns[i].setZoom(o.zoom) end end o.drawMapCursor = function() local mx = love.mouse.getX() local my = love.mouse.getY() --[[ local tileX, tileY = getTileFromScreen(o.map, mx, my) tileX = tileX * o.map.tileScale tileY = tileY * o.map.tileScale if tileX >= 0 and tileY >= 0 and tileX < o.map.width and tileY < o.map.height then G.setColor(255, 63, 0) G.setLineWidth(2) local tw = o.map.tileset.tileWidth local th = o.map.tileset.tileHeight if tw and th then G.rectangle("line", tileX * tw*o.zoom - o.offsetX , tileY * th*o.zoom - o.offsetY, tw*o.zoom*o.map.tileScale, th*o.zoom*o.map.tileScale) end end ]]-- G.setColor(255, 63, 0) G.rectangle("line", math.floor(mx / (o.tileset.tileWidth * o.map.tileScale * o.zoom)) * (o.tileset.tileWidth * o.map.tileScale * o.zoom), math.floor(my / (o.tileset.tileHeight * o.map.tileScale * o.zoom)) * (o.tileset.tileHeight * o.map.tileScale * o.zoom), o.tileset.tileWidth * o.map.tileScale * o.zoom, o.tileset.tileHeight * o.map.tileScale * o.zoom) end o.setGoal = function(map, x,y) o.goalX, o.goalY = getTileFromScreen(map,x,y) print (x, y, o.goalX, o.goalY) end return o end getTileFromScreen = function(map, mx, my) local ts = map.tileScale local tw = map.tileset.tileWidth local th = map.tileset.tileHeight local tileX =math.floor((mx) / (tw*ts)) local tileY =math.floor((my) / (tw*ts)) return tileX, tileY end
fix cursor zoom.
fix cursor zoom.
Lua
mit
nczempin/lizard-journey
5c697556e7d23930544c071222a7dcc4da3a9fbe
plugins/2017.3081/android/metadata.lua
plugins/2017.3081/android/metadata.lua
local metadata = { plugin = { format = 'jar', manifest = { permissions = {}, usesPermissions = { "android.permission.WAKE_LOCK", "android.permission.ACCESS_NETWORK_STATE", "android.permission.RECEIVE_BOOT_COMPLETED" }, usesFeatures = {}, applicationChildElements = { [[<activity android:name="com.vungle.warren.ui.VungleActivity" android:configChanges="keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize" android:launchMode="singleTop" android:theme="@android:style/Theme.Translucent.NoTitleBar"/>]], [[<service android:name="com.evernote.android.job.v21.PlatformJobService" android:exported="false" android:permission="android.permission.BIND_JOB_SERVICE"/>]], [[<service android:name="com.evernote.android.job.v14.PlatformAlarmService" android:exported="false" android:permission="android.permission.BIND_JOB_SERVICE" />]], [[<service android:name="com.evernote.android.job.v14.PlatformAlarmServiceExact" android:exported="false"/>]], [[<receiver android:name="com.evernote.android.job.v14.PlatformAlarmReceiver" android:exported="false" > <intent-filter> <action android:name="com.evernote.android.job.v14.RUN_JOB" /> <action android:name="net.vrallev.android.job.v14.RUN_JOB" /> </intent-filter> </receiver>]], [[<receiver android:name="com.evernote.android.job.JobBootReceiver" android:exported="false" > <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> <action android:name="android.intent.action.QUICKBOOT_POWERON" /> <action android:name="com.htc.intent.action.QUICKBOOT_POWERON" /> <action android:name="android.intent.action.MY_PACKAGE_REPLACED" /> </intent-filter> </receiver>]], [[<service android:name="com.evernote.android.job.gcm.PlatformGcmService" android:enabled="false" android:exported="true" android:permission="com.google.android.gms.permission.BIND_NETWORK_TASK_SERVICE" > <intent-filter> <action android:name="com.google.android.gms.gcm.ACTION_TASK_READY" /> </intent-filter> </service>]], [[<service android:name="com.evernote.android.job.JobRescheduleService" android:exported="false" android:permission="android.permission.BIND_JOB_SERVICE" />]], }, }, }, coronaManifest = { dependencies = { ["shared.google.play.services.ads"] = "com.coronalabs", ["shared.android.support.v4"] = "com.coronalabs" } } } return metadata
local metadata = { plugin = { format = 'jar', manifest = { permissions = {}, usesPermissions = { "android.permission.WAKE_LOCK", "android.permission.ACCESS_NETWORK_STATE", "android.permission.RECEIVE_BOOT_COMPLETED" }, usesFeatures = {}, applicationChildElements = { [[<activity android:name="com.vungle.warren.ui.VungleActivity" android:configChanges="keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize" android:launchMode="singleTop" android:theme="@android:style/Theme.NoTitleBar.Fullscreen"/>]], [[<activity android:name="com.vungle.warren.ui.VungleFlexViewActivity" android:configChanges="keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize" android:launchMode="singleTop" android:theme="@android:style/Theme.Translucent.NoTitleBar"/>]], [[<service android:name="com.evernote.android.job.v21.PlatformJobService" android:exported="false" android:permission="android.permission.BIND_JOB_SERVICE"/>]], [[<service android:name="com.evernote.android.job.v14.PlatformAlarmService" android:exported="false" android:permission="android.permission.BIND_JOB_SERVICE" />]], [[<service android:name="com.evernote.android.job.v14.PlatformAlarmServiceExact" android:exported="false"/>]], [[<receiver android:name="com.evernote.android.job.v14.PlatformAlarmReceiver" android:exported="false" > <intent-filter> <action android:name="com.evernote.android.job.v14.RUN_JOB" /> <action android:name="net.vrallev.android.job.v14.RUN_JOB" /> </intent-filter> </receiver>]], [[<receiver android:name="com.evernote.android.job.JobBootReceiver" android:exported="false" > <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> <action android:name="android.intent.action.QUICKBOOT_POWERON" /> <action android:name="com.htc.intent.action.QUICKBOOT_POWERON" /> <action android:name="android.intent.action.MY_PACKAGE_REPLACED" /> </intent-filter> </receiver>]], [[<service android:name="com.evernote.android.job.gcm.PlatformGcmService" android:enabled="false" android:exported="true" android:permission="com.google.android.gms.permission.BIND_NETWORK_TASK_SERVICE" > <intent-filter> <action android:name="com.google.android.gms.gcm.ACTION_TASK_READY" /> </intent-filter> </service>]], [[<service android:name="com.evernote.android.job.JobRescheduleService" android:exported="false" android:permission="android.permission.BIND_JOB_SERVICE" />]], }, }, }, coronaManifest = { dependencies = { ["shared.google.play.services.ads"] = "com.coronalabs", ["shared.android.support.v4"] = "com.coronalabs" } } } return metadata
Fix manifest
Fix manifest
Lua
mit
Vungle/coronaplugin,Vungle/coronaplugin,Vungle/coronaplugin
e690dd9740835fd0173c7c26beae9cfdbabcd984
src/rspamadm/fuzzy_stat.lua
src/rspamadm/fuzzy_stat.lua
local util = require "rspamd_util" local opts = {} local function add_data(target, src) for k,v in pairs(src) do if k ~= 'ips' then if target[k] then target[k] = target[k] + v else target[k] = v end else if not target['ips'] then target['ips'] = {} end -- Iterate over IPs for ip,st in pairs(v) do if not target['ips'][ip] then target['ips'][ip] = {} end add_data(target['ips'][ip], st) end end end end local function print_num(num) if opts['n'] or opts['number'] then return tostring(num) else return util.humanize_number(num) end end local function print_stat(st, tabs) if st['checked'] then print(string.format('%sChecked: %s', tabs, print_num(st['checked']))) end if st['matched'] then print(string.format('%sMatched: %s', tabs, print_num(st['matched']))) end if st['errors'] then print(string.format('%sErrors: %s', tabs, print_num(st['errors']))) end if st['added'] then print(string.format('%sAdded: %s', tabs, print_num(st['added']))) end if st['deleted'] then print(string.format('%sDeleted: %s', tabs, print_num(st['deleted']))) end end -- Sort by checked local function sort_ips(tbl, opts) local res = {} for k,v in pairs(tbl) do table.insert(res, {ip = k, data = v}) end local function sort_order(elt) local key = 'checked' local res = 0 if opts['sort'] then if opts['sort'] == 'matched' then key = 'matched' elseif opts['sort'] == 'errors' then key = 'errors' elseif opts['sort'] == 'ip' then return elt['ip'] end end if elt['data'][key] then res = elt['data'][key] end return res end table.sort(res, function(a, b) return sort_order(a) > sort_order(b) end) return res end local function add_result(dst, src, k) if type(src) == 'table' then if type(dst) == 'number' then -- Convert dst to table dst = {dst} elseif type(dst) == 'nil' then dst = {} end for i,v in ipairs(src) do if dst[i] and k ~= 'fuzzy_stored' then dst[i] = dst[i] + v else dst[i] = v end end else if type(dst) == 'table' then if k ~= 'fuzzy_stored' then dst[1] = dst[1] + src else dst[1] = src end else if dst and k ~= 'fuzzy_stored' then dst = dst + src else dst = src end end end return dst end local function print_result(r) local function num_to_epoch(num) if num == 1 then return 'v0.6' elseif num == 2 then return 'v0.8' elseif num == 3 then return 'v0.9' elseif num == 4 then return 'v1.0+' end return '???' end if type(r) == 'table' then local res = {} for i,num in ipairs(r) do res[i] = string.format('(%s: %s)', num_to_epoch(i), print_num(num)) end return table.concat(res, ', ') end return print_num(r) end --.USE "getopt" return function(args, res) local res_ips = {} local res_databases = {} local wrk = res['workers'] opts = getopt(args, '') if wrk then for i,pr in pairs(wrk) do -- processes cycle if pr['data'] then local id = pr['id'] if id then local res_db = res_databases[id] if not res_db then res_db = { keys = {} } res_databases[id] = res_db end -- General stats for k,v in pairs(pr['data']) do if k ~= 'keys' and k ~= 'errors_ips' then res_db[k] = add_result(res_db[k], v, k) elseif k == 'errors_ips' then -- Errors ips if not res_db['errors_ips'] then res_db['errors_ips'] = {} end for ip,nerrors in pairs(v) do if not res_db['errors_ips'][ip] then res_db['errors_ips'][ip] = nerrors else res_db['errors_ips'][ip] = nerrors + res_db['errors_ips'][ip] end end end end if pr['data']['keys'] then local res_keys = res_db['keys'] if not res_keys then res_keys = {} res_db['keys'] = res_keys end -- Go through keys in input for k,elts in pairs(pr['data']['keys']) do -- keys cycle if not res_keys[k] then res_keys[k] = {} end add_data(res_keys[k], elts) if elts['ips'] then for ip,v in pairs(elts['ips']) do if not res_ips[ip] then res_ips[ip] = {} end add_data(res_ips[ip], v) end end end end end end end end -- General stats for db,st in pairs(res_databases) do print(string.format('Statistics for storage %s', db)) for k,v in pairs(st) do if k ~= 'keys' and k ~= 'errors_ips' then print(string.format('%s: %s', k, print_result(v))) end end print('') local res_keys = st['keys'] if res_keys and not opts['no-keys'] and not opts['short'] then print('Keys statistics:') for k,st in pairs(res_keys) do print(string.format('Key id: %s', k)) print_stat(st, '\t') if st['ips'] and not opts['no-ips'] then print('') print('\tIPs stat:') local sorted_ips = sort_ips(st['ips'], opts) for i,v in ipairs(sorted_ips) do print(string.format('\t%s', v['ip'])) print_stat(v['data'], '\t\t') print('') end end print('') end end if st['errors_ips'] and not opts['no-ips'] and not opts['short'] then print('') print('Errors IPs statistics:') local sorted_ips = sort_ips(st['errors_ips'], opts) for i, v in ipairs(sorted_ips) do print(string.format('%s: %s', v['ip'], print_result(v['data']))) end end end if not opts['no-ips'] and not opts['short'] then print('') print('IPs statistics:') local sorted_ips = sort_ips(res_ips, opts) for i, v in ipairs(sorted_ips) do print(string.format('%s', v['ip'])) print_stat(v['data'], '\t') print('') end end end
local util = require "rspamd_util" local opts = {} local function add_data(target, src) for k,v in pairs(src) do if k ~= 'ips' then if target[k] then target[k] = target[k] + v else target[k] = v end else if not target['ips'] then target['ips'] = {} end -- Iterate over IPs for ip,st in pairs(v) do if not target['ips'][ip] then target['ips'][ip] = {} end add_data(target['ips'][ip], st) end end end end local function print_num(num) if opts['n'] or opts['number'] then return tostring(num) else return util.humanize_number(num) end end local function print_stat(st, tabs) if st['checked'] then print(string.format('%sChecked: %s', tabs, print_num(st['checked']))) end if st['matched'] then print(string.format('%sMatched: %s', tabs, print_num(st['matched']))) end if st['errors'] then print(string.format('%sErrors: %s', tabs, print_num(st['errors']))) end if st['added'] then print(string.format('%sAdded: %s', tabs, print_num(st['added']))) end if st['deleted'] then print(string.format('%sDeleted: %s', tabs, print_num(st['deleted']))) end end -- Sort by checked local function sort_ips(tbl, opts) local res = {} for k,v in pairs(tbl) do table.insert(res, {ip = k, data = v}) end local function sort_order(elt) local key = 'checked' local res = 0 if opts['sort'] then if opts['sort'] == 'matched' then key = 'matched' elseif opts['sort'] == 'errors' then key = 'errors' elseif opts['sort'] == 'ip' then return elt['ip'] end end if elt['data'][key] then res = elt['data'][key] end return res end table.sort(res, function(a, b) return sort_order(a) > sort_order(b) end) return res end local function add_result(dst, src, k) if type(src) == 'table' then if type(dst) == 'number' then -- Convert dst to table dst = {dst} elseif type(dst) == 'nil' then dst = {} end for i,v in ipairs(src) do if dst[i] and k ~= 'fuzzy_stored' then dst[i] = dst[i] + v else dst[i] = v end end else if type(dst) == 'table' then if k ~= 'fuzzy_stored' then dst[1] = dst[1] + src else dst[1] = src end else if dst and k ~= 'fuzzy_stored' then dst = dst + src else dst = src end end end return dst end local function print_result(r) local function num_to_epoch(num) if num == 1 then return 'v0.6' elseif num == 2 then return 'v0.8' elseif num == 3 then return 'v0.9' elseif num == 4 then return 'v1.0+' end return '???' end if type(r) == 'table' then local res = {} for i,num in ipairs(r) do res[i] = string.format('(%s: %s)', num_to_epoch(i), print_num(num)) end return table.concat(res, ', ') end return print_num(r) end --.USE "getopt" return function(args, res) local res_ips = {} local res_databases = {} local wrk = res['workers'] opts = getopt(args, '') if wrk then for i,pr in pairs(wrk) do -- processes cycle if pr['data'] then local id = pr['id'] if id then local res_db = res_databases[id] if not res_db then res_db = { keys = {} } res_databases[id] = res_db end -- General stats for k,v in pairs(pr['data']) do if k ~= 'keys' and k ~= 'errors_ips' then res_db[k] = add_result(res_db[k], v, k) elseif k == 'errors_ips' then -- Errors ips if not res_db['errors_ips'] then res_db['errors_ips'] = {} end for ip,nerrors in pairs(v) do if not res_db['errors_ips'][ip] then res_db['errors_ips'][ip] = nerrors else res_db['errors_ips'][ip] = nerrors + res_db['errors_ips'][ip] end end end end if pr['data']['keys'] then local res_keys = res_db['keys'] if not res_keys then res_keys = {} res_db['keys'] = res_keys end -- Go through keys in input for k,elts in pairs(pr['data']['keys']) do -- keys cycle if not res_keys[k] then res_keys[k] = {} end add_data(res_keys[k], elts) if elts['ips'] then for ip,v in pairs(elts['ips']) do if not res_ips[ip] then res_ips[ip] = {} end add_data(res_ips[ip], v) end end end end end end end end -- General stats for db,st in pairs(res_databases) do print(string.format('Statistics for storage %s', db)) for k,v in pairs(st) do if k ~= 'keys' and k ~= 'errors_ips' then print(string.format('%s: %s', k, print_result(v))) end end print('') local res_keys = st['keys'] if res_keys and not opts['no-keys'] and not opts['short'] then print('Keys statistics:') for k,st in pairs(res_keys) do print(string.format('Key id: %s', k)) print_stat(st, '\t') if st['ips'] and not opts['no-ips'] then print('') print('\tIPs stat:') local sorted_ips = sort_ips(st['ips'], opts) for i,v in ipairs(sorted_ips) do print(string.format('\t%s', v['ip'])) print_stat(v['data'], '\t\t') print('') end end print('') end end if st['errors_ips'] and not opts['no-ips'] and not opts['short'] then print('') print('Errors IPs statistics:') table.sort(st['errors_ips'], function(a, b) return a > b end) for i, v in pairs(st['errors_ips']) do print(string.format('%s: %s', i, print_result(v))) end end end if not opts['no-ips'] and not opts['short'] then print('') print('IPs statistics:') local sorted_ips = sort_ips(res_ips, opts) for i, v in ipairs(sorted_ips) do print(string.format('%s', v['ip'])) print_stat(v['data'], '\t') print('') end end end
Fix sorting and output of errors_ips
Fix sorting and output of errors_ips
Lua
bsd-2-clause
AlexeySa/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,minaevmike/rspamd,minaevmike/rspamd,andrejzverev/rspamd,minaevmike/rspamd,minaevmike/rspamd,minaevmike/rspamd,minaevmike/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,minaevmike/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,minaevmike/rspamd,AlexeySa/rspamd,minaevmike/rspamd,AlexeySa/rspamd
edba7655494b83fe4c8428a751db5f26392e5bf9
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); 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: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 Hand", 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]) item:setData("uniqueID", tostring(math.random())); --tag the item with a unique ID item:setData("repairPos", tostring(i)); --tag the item its position in the inventory world:changeItem(item); 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 chosenItemUID=chosenItem:getData("uniqueID") chosenPos=chosenItem:getData("repairPos") repair(npcChar, speaker, chosenItem, chosenItemUID, chosenPos, 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, theItemUID, theItemPos, language) local theItemStats=world:getItemStats(theItem); local found=false; for i=17,0,-1 do local item = speaker:getItemAt(i); if (item.id > 0) and (item.number == 1) and (getRepairPrice(item,speaker) ~= 0) and (item:getData("uniqueID") == theItemUID) and (tonumber(theItemPos) == i) then --check for valid item 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("[FEHLER] Gegenstand nicht gefunden. Verndere nicht dein Inventar whrend der Reparatur.","[ERROR] Item not found. Do not change your equipment during repair.", Character.highPriority); end --item exists end; return M
#11095: Fix problem with repair dialog
#11095: Fix problem with repair dialog
Lua
agpl-3.0
Illarion-eV/Illarion-Content,Baylamon/Illarion-Content,vilarion/Illarion-Content,KayMD/Illarion-Content