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
fe45bb336033e3458030cb0e092dc35c227c5bd6
premake5.lua
premake5.lua
baseAbsPath = os.getcwd() srcAbsPath = baseAbsPath .. "/src" buildPath = "build/" .. _ACTION buildAbsPath = baseAbsPath .. "/" .. buildPath versionMajor = 0 versionMinor = 0 versionBuild = 0 function setSolutionDefaults() configurations {"debug", "release"} architecture "x86_64" location(buildPath) objdir(buildPath .. "/obj") libdirs { buildPath .. "/bin" } targetdir(buildPath .. "/bin") defines { "coVERSION_MAJOR="..versionMajor, "coVERSION_MINOR="..versionMinor, "coVERSION_BUILD="..versionBuild } rtti "Off" exceptionhandling "Off" vectorextensions "SSE2" warnings "Extra" floatingpoint "Fast" editandcontinue "Off" flags { "Symbols", "NoMinimalRebuild", "FatalWarnings", "C++14", "MultiProcessorCompile" } filter { "gmake" } buildoptions { "-Wno-reorder", "-Wno-deprecated" } includedirs { gmakeIncludeDir } filter { "configurations:debug" } targetsuffix "_d" filter { "configurations:release" } optimize "On" flags { "OptimizeSpeed", "NoFramePointer"} filter { "vs*" } defines { "_HAS_EXCEPTIONS=0" } --flags { "StaticRuntime" } linkoptions { "/ENTRY:mainCRTStartup" } filter {} end function setPCH(_dir, _projectName, _fileName) pchheader(_projectName .. "/".. _fileName .. '.h') pchsource(_dir .. "/" .. _fileName .. '.cpp') --[[ filter { "action:vs*" } pchheader(_fileName .. '.h') pchsource(_fileName .. '.cpp') filter { "action:not vs*" } pchheader(_dir .. '/' .. _fileName .. '.h') filter {} --]] end function setProjectDefaults(_projectDir, _projectName, _prefix, _postfix) __prefix = _prefix __postfix= _postfix kind "StaticLib" location (buildAbsPath.."/projects") includedirs { _projectDir } --files { _prefix.."PCH".._postfix..".cpp" } files { _projectDir .. "/" .. "**.cpp", _projectDir .. "/" .. "**.h"} setPCH(_projectDir, _projectName, "pch") --vpaths { ["*"] = _projectDir } defines { "coPROJECT_NAME=".._projectName } language "C++" filter {} end function addProject(_name, _params) project(_name) setProjectDefaults("src/".._name, _name , "", "") if _params then if _params.kind then kind(_params.kind) end if _params.links then links {_params.links} end end end workspace("core") setSolutionDefaults() includedirs { "src" } addProject("debug") addProject("lang") addProject("math") addProject("memory") addProject("container") addProject("pattern") addProject("test") addProject("event") addProject("io") addProject("prebuild", { kind = "ConsoleApp", links = {"lang"} }) addProject("test_math", { kind = "ConsoleApp", links = {"test", "container", "memory", "lang", "math"} }) addProject("test_container", { kind = "ConsoleApp", links = {"test", "container", "memory", "lang"} })
baseAbsPath = os.getcwd() srcAbsPath = baseAbsPath .. "/src" buildPath = "build/" .. _ACTION buildAbsPath = baseAbsPath .. "/" .. buildPath versionMajor = 0 versionMinor = 0 versionBuild = 0 function coSetSolutionDefaults() configurations {"debug", "release"} architecture "x86_64" location(buildPath) objdir(buildPath .. "/obj") libdirs { buildPath .. "/bin" } targetdir(buildPath .. "/bin") defines { "coVERSION_MAJOR="..versionMajor, "coVERSION_MINOR="..versionMinor, "coVERSION_BUILD="..versionBuild } rtti "Off" exceptionhandling "Off" vectorextensions "SSE2" warnings "Extra" floatingpoint "Fast" editandcontinue "Off" flags { "Symbols", "NoMinimalRebuild", "FatalWarnings", "C++14", "MultiProcessorCompile" } filter { "gmake" } buildoptions { "-Wno-reorder", "-Wno-deprecated" } includedirs { gmakeIncludeDir } filter { "configurations:debug" } targetsuffix "_d" filter { "configurations:release" } optimize "On" flags { "OptimizeSpeed", "NoFramePointer"} filter { "vs*" } defines { "_HAS_EXCEPTIONS=0" } --flags { "StaticRuntime" } linkoptions { "/ENTRY:mainCRTStartup" } filter {} end function coSetPCH(_dir, _projectName, _fileName) pchheader(_projectName .. "/".. _fileName .. '.h') pchsource(_dir .. "/" .. _fileName .. '.cpp') --[[ filter { "action:vs*" } pchheader(_fileName .. '.h') pchsource(_fileName .. '.cpp') filter { "action:not vs*" } pchheader(_dir .. '/' .. _fileName .. '.h') filter {} --]] end function coSetProjectDefaults(_projectDir, _projectName, _prefix, _postfix) __prefix = _prefix __postfix= _postfix kind "StaticLib" location (buildAbsPath.."/projects") includedirs { _projectDir } --files { _prefix.."PCH".._postfix..".cpp" } files { _projectDir .. "/" .. "**.cpp", _projectDir .. "/" .. "**.h"} coSetPCH(_projectDir, _projectName, "pch") --vpaths { ["*"] = _projectDir } defines { "coPROJECT_NAME=".._projectName } language "C++" filter {} end function coAddProject(_name, _params) project(_name) coSetProjectDefaults("src/".._name, _name , "", "") if _params then if _params.kind then kind(_params.kind) end if _params.links then links {_params.links} end end end workspace("core") coSetSolutionDefaults() includedirs { "src" } coAddProject("debug") coAddProject("lang") coAddProject("math") coAddProject("memory") coAddProject("container") coAddProject("pattern") coAddProject("test") coAddProject("event") coAddProject("io") coAddProject("prebuild", { kind = "ConsoleApp", links = {"lang"} }) coAddProject("test_math", { kind = "ConsoleApp", links = {"test", "container", "memory", "lang", "math"} }) coAddProject("test_container", { kind = "ConsoleApp", links = {"test", "container", "memory", "lang"} })
Added the "co" prefix to the functions in the premake lua.
Added the "co" prefix to the functions in the premake lua.
Lua
mit
smogpill/core,smogpill/core
6bded7aaf7577192417987f45253e0f347ea6060
frontend/apps/reader/modules/readerconfig.lua
frontend/apps/reader/modules/readerconfig.lua
local ConfigDialog = require("ui/widget/configdialog") local Device = require("device") local Event = require("ui/event") local Geom = require("ui/geometry") local InputContainer = require("ui/widget/container/inputcontainer") local UIManager = require("ui/uimanager") local _ = require("gettext") local ReaderConfig = InputContainer:new{ last_panel_index = 1, } function ReaderConfig:init() if not self.dimen then self.dimen = Geom:new{} end if Device:hasKeyboard() then self.key_events = { ShowConfigMenu = { { "AA" }, doc = "show config dialog" }, } end if Device:isTouchDevice() then self:initGesListener() end self.activation_menu = G_reader_settings:readSetting("activate_menu") if self.activation_menu == nil then self.activation_menu = "swipe_tap" end end function ReaderConfig:initGesListener() self.ui:registerTouchZones({ { id = "readerconfigmenu_tap", ges = "tap", screen_zone = { ratio_x = DTAP_ZONE_CONFIG.x, ratio_y = DTAP_ZONE_CONFIG.y, ratio_w = DTAP_ZONE_CONFIG.w, ratio_h = DTAP_ZONE_CONFIG.h, }, overrides = { 'tap_forward', 'tap_backward', }, handler = function() return self:onTapShowConfigMenu() end, }, { id = "readerconfigmenu_swipe", ges = "swipe", screen_zone = { ratio_x = DTAP_ZONE_CONFIG.x, ratio_y = DTAP_ZONE_CONFIG.y, ratio_w = DTAP_ZONE_CONFIG.w, ratio_h = DTAP_ZONE_CONFIG.h, }, overrides = { "rolling_swipe", "paging_swipe", }, handler = function(ges) return self:onSwipeShowConfigMenu(ges) end, }, }) end function ReaderConfig:onShowConfigMenu() self.config_dialog = ConfigDialog:new{ dimen = self.dimen:copy(), ui = self.ui, configurable = self.configurable, config_options = self.options, is_always_active = true, close_callback = function() self:onCloseCallback() end, } self.ui:handleEvent(Event:new("DisableHinting")) -- show last used panel when opening config dialog self.config_dialog:onShowConfigPanel(self.last_panel_index) UIManager:show(self.config_dialog) return true end function ReaderConfig:onTapShowConfigMenu() if self.activation_menu ~= "swipe" then self:onShowConfigMenu() return true end end function ReaderConfig:onSwipeShowConfigMenu(ges) if self.activation_menu ~= "tap" and ges.direction == "north" then self:onShowConfigMenu() return true end end function ReaderConfig:onSetDimensions(dimen) if Device:isTouchDevice() then self:initGesListener() end -- since we cannot redraw config_dialog with new size, we close -- the old one on screen size change if self.config_dialog then self.config_dialog:closeDialog() end end function ReaderConfig:onCloseCallback() self.last_panel_index = self.config_dialog.panel_index self.ui:handleEvent(Event:new("RestoreHinting")) end -- event handler for readercropping function ReaderConfig:onCloseConfigMenu() if self.config_dialog then self.config_dialog:closeDialog() end end function ReaderConfig:onReadSettings(config) self.configurable:loadSettings(config, self.options.prefix.."_") self.last_panel_index = config:readSetting("config_panel_index") or 1 end function ReaderConfig:onSaveSettings() self.configurable:saveSettings(self.ui.doc_settings, self.options.prefix.."_") self.ui.doc_settings:saveSetting("config_panel_index", self.last_panel_index) end return ReaderConfig
local ConfigDialog = require("ui/widget/configdialog") local Device = require("device") local Event = require("ui/event") local Geom = require("ui/geometry") local InputContainer = require("ui/widget/container/inputcontainer") local UIManager = require("ui/uimanager") local _ = require("gettext") local ReaderConfig = InputContainer:new{ last_panel_index = 1, } function ReaderConfig:init() if not self.dimen then self.dimen = Geom:new{} end if Device:hasKeyboard() then self.key_events = { ShowConfigMenu = { { "AA" }, doc = "show config dialog" }, } end if Device:isTouchDevice() then self:initGesListener() end self.activation_menu = G_reader_settings:readSetting("activate_menu") if self.activation_menu == nil then self.activation_menu = "swipe_tap" end end function ReaderConfig:initGesListener() self.ui:registerTouchZones({ { id = "readerconfigmenu_tap", ges = "tap", screen_zone = { ratio_x = DTAP_ZONE_CONFIG.x, ratio_y = DTAP_ZONE_CONFIG.y, ratio_w = DTAP_ZONE_CONFIG.w, ratio_h = DTAP_ZONE_CONFIG.h, }, overrides = { 'tap_forward', 'tap_backward', }, handler = function() return self:onTapShowConfigMenu() end, }, { id = "readerconfigmenu_swipe", ges = "swipe", screen_zone = { ratio_x = DTAP_ZONE_CONFIG.x, ratio_y = DTAP_ZONE_CONFIG.y, ratio_w = DTAP_ZONE_CONFIG.w, ratio_h = DTAP_ZONE_CONFIG.h, }, overrides = { "rolling_swipe", "paging_swipe", }, handler = function(ges) return self:onSwipeShowConfigMenu(ges) end, }, { id = "readerconfigmenu_pan", ges = "pan", screen_zone = { ratio_x = DTAP_ZONE_CONFIG.x, ratio_y = DTAP_ZONE_CONFIG.y, ratio_w = DTAP_ZONE_CONFIG.w, ratio_h = DTAP_ZONE_CONFIG.h, }, overrides = { "rolling_pan", "paging_pan", }, handler = function(ges) return self:onSwipeShowConfigMenu(ges) end, }, }) end function ReaderConfig:onShowConfigMenu() self.config_dialog = ConfigDialog:new{ dimen = self.dimen:copy(), ui = self.ui, configurable = self.configurable, config_options = self.options, is_always_active = true, close_callback = function() self:onCloseCallback() end, } self.ui:handleEvent(Event:new("DisableHinting")) -- show last used panel when opening config dialog self.config_dialog:onShowConfigPanel(self.last_panel_index) UIManager:show(self.config_dialog) return true end function ReaderConfig:onTapShowConfigMenu() if self.activation_menu ~= "swipe" then self:onShowConfigMenu() return true end end function ReaderConfig:onSwipeShowConfigMenu(ges) if self.activation_menu ~= "tap" and ges.direction == "north" then self:onShowConfigMenu() return true end end function ReaderConfig:onSetDimensions(dimen) if Device:isTouchDevice() then self:initGesListener() end -- since we cannot redraw config_dialog with new size, we close -- the old one on screen size change if self.config_dialog then self.config_dialog:closeDialog() end end function ReaderConfig:onCloseCallback() self.last_panel_index = self.config_dialog.panel_index self.ui:handleEvent(Event:new("RestoreHinting")) end -- event handler for readercropping function ReaderConfig:onCloseConfigMenu() if self.config_dialog then self.config_dialog:closeDialog() end end function ReaderConfig:onReadSettings(config) self.configurable:loadSettings(config, self.options.prefix.."_") self.last_panel_index = config:readSetting("config_panel_index") or 1 end function ReaderConfig:onSaveSettings() self.configurable:saveSettings(self.ui.doc_settings, self.options.prefix.."_") self.ui.doc_settings:saveSetting("config_panel_index", self.last_panel_index) end return ReaderConfig
readerconfigmenu(fix): override pan gesture from scrolling
readerconfigmenu(fix): override pan gesture from scrolling
Lua
agpl-3.0
Hzj-jie/koreader,pazos/koreader,Frenzie/koreader,koreader/koreader,koreader/koreader,NiLuJe/koreader,houqp/koreader,mihailim/koreader,lgeek/koreader,NiLuJe/koreader,apletnev/koreader,Markismus/koreader,mwoz123/koreader,poire-z/koreader,poire-z/koreader,Frenzie/koreader
ebc42da8cd5a60f633b79a54fabbe32cfd6dfcdd
share/lua/website/youjizz.lua
share/lua/website/youjizz.lua
-- libquvi-scripts -- Copyright (C) 2010-2012 quvi project -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -- 02110-1301 USA -- -- Identify the script. function ident(self) package.path = self.script_dir .. '/?.lua' local C = require 'quvi/const' local r = {} r.domain = "youjizz%.com" r.formats = "default" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/videos/.-%.html"}) return r end -- Query available formats. function query_formats(self) self.formats = 'default' return self end -- Parse media URL. function parse(self) self.host_id = "youjizz" local p = quvi.fetch(self.page_url) self.title = p:match("<title>(.-)</") or error ("no match: media title") self.id = p:match("%?id=(%d+)") or error ("no match: media ID") self.url = {p:match('addVariable%("file",encodeURIComponent%("(.-)"') or error ("no match: media URL")} return self end -- vim: set ts=4 sw=4 tw=72 expandtab:
-- libquvi-scripts -- Copyright (C) 2010-2012 quvi project -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -- 02110-1301 USA -- -- Identify the script. function ident(self) package.path = self.script_dir .. '/?.lua' local C = require 'quvi/const' local r = {} r.domain = "youjizz%.com" r.formats = "default" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/videos/.-%.html"}) return r end -- Query available formats. function query_formats(self) self.formats = 'default' return self end -- Parse media URL. function parse(self) self.host_id = "youjizz" self.id = self.page_url:match('%-(%d+)%.html') or error ("no match: media ID") local p = quvi.fetch(self.page_url) self.title = p:match("<title>(.-)</") or error ("no match: media title") self.thumbnail_url = p:match('data%-original="(.-)"') or '' local c = quvi.fetch('http://youjizz.com/videos/embed/' .. self.id, {fetch_type='config'}) self.url = {c:match('addVariable%("file",encodeURIComponent%("(.-)"') or error ("no match: media stream URL")} return self end -- vim: set ts=4 sw=4 tw=72 expandtab:
FIX: website/youjizz.lua
FIX: website/youjizz.lua Fix media {ID,media stream URL} parsing. Parse thumbnail URL. Signed-off-by: anon
Lua
agpl-3.0
alech/libquvi-scripts,DangerCove/libquvi-scripts,legatvs/libquvi-scripts,alech/libquvi-scripts,legatvs/libquvi-scripts,DangerCove/libquvi-scripts
106265e0a7761eb7e3633d9bc76d98acaed48a0f
CCLib/src/cc/native/Turtle.lua
CCLib/src/cc/native/Turtle.lua
natives["cc.turtle.Turtle"] = natives["cc.turtle.Turtle"] or {} function booleanToInt(b) if b then return 1 else return 0 end end natives["cc.turtle.Turtle"]["forward()Z"] = function(this) local success = turtle.forward() return booleanToInt(success) end natives["cc.turtle.Turtle"]["back()Z"] = function(this) local success = turtle.back() return booleanToInt(success) end natives["cc.turtle.Turtle"]["up()Z"] = function(this) local success = turtle.up() return booleanToInt(success) end natives["cc.turtle.Turtle"]["down()Z"] = function(this) local success = turtle.down() return booleanToInt(success) end natives["cc.turtle.Turtle"]["turnLeft()Z"] = function(this) local success = turtle.turnLeft() return booleanToInt(success) end natives["cc.turtle.Turtle"]["turnRight()Z"] = function(this) local success = turtle.turnRight() return booleanToInt(success) end natives["cc.turtle.Turtle"]["select(I)Z"] = function(this, slot) local success = turtle.select(slot) return booleanToInt(success) end natives["cc.turtle.Turtle"]["getSelectedSlot()I"] = function(this) local slot = turtle.getSelectedSlot() return slot; end natives["cc.turtle.Turtle"]["getItemCount(I)I"] = function(this, slot) local count = turtle.getItemCount(slot); return count; end natives["cc.turtle.Turtle"]["getItemSpace(I)I"] = function(this, slot) local space = turtle.getItemSpace(slot); return space; end natives["cc.turtle.Turtle"]["getItemDetail(I)Lcc/turtle/ItemStack;"] = function(this, slot) local data = turtle.getItemDetail(slot); if data == nil then return null end local class = classByName("cc.turtle.ItemStack") local itemstack = newInstance(class) findMethod(class, "<init>()V")[1](itemstack) setObjectField(itemstack, "name", toJString(data.name)) setObjectField(itemstack, "damage", data.damage) setObjectField(itemstack, "count", data.count) return itemstack; end natives["cc.turtle.Turtle"]["equipLeft()Z"] = function(this) local success = turtle.equipLeft() return success end natives["cc.turtle.Turtle"]["equipRight()Z"] = function(this) local success = turtle.equipRight() return success end natives["cc.turtle.Turtle"]["place(Ljava/lang/String;)Z"] = function(this, text) local success = turtle.place(toLString(text)) return booleanToInt(success) end natives["cc.turtle.Turtle"]["placeUp()Z"] = function(this) local success = turtle.placeUp() return booleanToInt(success) end natives["cc.turtle.Turtle"]["placeDown()Z"] = function(this) local success = turtle.placeDown() return booleanToInt(success) end natives["cc.turtle.Turtle"]["detect()Z"] = function(this) local success = turtle.detect() return booleanToInt(success) end natives["cc.turtle.Turtle"]["detectUp()Z"] = function(this) local success = turtle.detect() return booleanToInt(success) end natives["cc.turtle.Turtle"]["detectDown()Z"] = function(this) local success = turtle.detect() return booleanToInt(success) end natives["cc.turtle.Turtle"]["inspect()Lcc/turtle/InspectionReport;"] = function(this) local success, data = turtle.inspect() return createInspectionReport(success, data) end natives["cc.turtle.Turtle"]["inspectUp()Lcc/turtle/InspectionReport;"] = function(this) local success, data = turtle.inspectUp() return createInspectionReport(success, data) end natives["cc.turtle.Turtle"]["inspectDown()Lcc/turtle/InspectionReport;"] = function(this) local success, data = turtle.inspectDown() return createInspectionReport(success, data) end function createInspectionReport(success, data) local class = classByName("cc.turtle.InspectionReport") local report = newInstance(class) findMethod(class, "<init>()V")[1](report) if success then setObjectField(report, "success", 1) setObjectField(report, "blockName", toJString(data.name)) setObjectField(report, "blockMetadata", data.metadata) else setObjectField(report, "success", 0) setObjectField(report, "errorMessage", toJString(data)) end return report end natives["cc.turtle.Turtle"]["compare()Z"] = function(this) local success = turtle.compare() return booleanToInt(success) end natives["cc.turtle.Turtle"]["compareUp()Z"] = function(this) local success = turtle.compareUp() return booleanToInt(success) end natives["cc.turtle.Turtle"]["compareDown()Z"] = function(this) local success = turtle.compareDown() return booleanToInt(success) end natives["cc.turtle.Turtle"]["compareTo(I)Z"] = function(this, slot) local success = turtle.compareTo(slot) return booleanToInt(success) end natives["cc.turtle.Turtle"]["drop(I)Z"] = function(this, count) local success = turtle.drop(count) return booleanToInt(success) end natives["cc.turtle.Turtle"]["dropUp(I)Z"] = function(this, count) local success = turtle.dropUp(count) return booleanToInt(success) end natives["cc.turtle.Turtle"]["dropDown(I)Z"] = function(this, count) local success = turtle.dropDown(count) return booleanToInt(success) end natives["cc.turtle.Turtle"]["suck(I)Z"] = function(this, count) local success = turtle.suck(count) return booleanToInt(success) end natives["cc.turtle.Turtle"]["suckUp(I)Z"] = function(this, count) local success = turtle.suckUp(count) return booleanToInt(success) end natives["cc.turtle.Turtle"]["suckDown(I)Z"] = function(count) local success = turtle.suckDown(count) return booleanToInt(success) end natives["cc.turtle.Turtle"]["refuel(I)Z"] = function(quantity) local success = turtle.refuel(quantity) return booleanToInt(success) end natives["cc.turtle.Turtle"]["getFuelLevel()I"] = function() local level = turtle.getFuelLevel() return level end natives["cc.turtle.Turtle"]["getFuelLimit()I"] = function() local level = turtle.getFuelLimit() return level end natives["cc.turtle.Turtle"]["transferTo(II)Z"] = function(slot, quantity) local success = turtle.transferTo(slot, quantity) return booleanToInt(success) end -- crafty turtles only natives["cc.turtle.Turtle"]["craft(I)Z"] = function(quantity) local success = turtle.craft(quantity) return booleanToInt(success) end -- digging, felling, mining, farming turtles natives["cc.turtle.Turtle"]["dig()Z"] = function() local success = turtle.dig() return booleanToInt(success) end natives["cc.turtle.Turtle"]["digUp()Z"] = function() local success = turtle.digUp() return booleanToInt(success) end natives["cc.turtle.Turtle"]["digDown()Z"] = function() local success = turtle.digDown() return booleanToInt(success) end -- all tools only natives["cc.turtle.Turtle"]["attack()Z"] = function() local success = turtle.attack() return booleanToInt(success) end natives["cc.turtle.Turtle"]["attackUp()Z"] = function() local success = turtle.attackUp() return booleanToInt(success) end natives["cc.turtle.Turtle"]["attackDown()Z"] = function() local success = turtle.attackDown() return booleanToInt(success) end
natives["cc.turtle.Turtle"] = natives["cc.turtle.Turtle"] or {} function booleanToInt(b) if b then return 1 else return 0 end end natives["cc.turtle.Turtle"]["forward()Z"] = function(this) local success = turtle.forward() return booleanToInt(success) end natives["cc.turtle.Turtle"]["back()Z"] = function(this) local success = turtle.back() return booleanToInt(success) end natives["cc.turtle.Turtle"]["up()Z"] = function(this) local success = turtle.up() return booleanToInt(success) end natives["cc.turtle.Turtle"]["down()Z"] = function(this) local success = turtle.down() return booleanToInt(success) end natives["cc.turtle.Turtle"]["turnLeft()Z"] = function(this) local success = turtle.turnLeft() return booleanToInt(success) end natives["cc.turtle.Turtle"]["turnRight()Z"] = function(this) local success = turtle.turnRight() return booleanToInt(success) end natives["cc.turtle.Turtle"]["select(I)Z"] = function(this, slot) local success = turtle.select(slot) return booleanToInt(success) end natives["cc.turtle.Turtle"]["getSelectedSlot()I"] = function(this) local slot = turtle.getSelectedSlot() return slot; end natives["cc.turtle.Turtle"]["getItemCount(I)I"] = function(this, slot) local count = turtle.getItemCount(slot); return count; end natives["cc.turtle.Turtle"]["getItemSpace(I)I"] = function(this, slot) local space = turtle.getItemSpace(slot); return space; end natives["cc.turtle.Turtle"]["getItemDetail(I)Lcc/turtle/ItemStack;"] = function(this, slot) local data = turtle.getItemDetail(slot); if data == nil then return null end local class = classByName("cc.turtle.ItemStack") local itemstack = newInstance(class) findMethod(class, "<init>()V")[1](itemstack) setObjectField(itemstack, "name", toJString(data.name)) setObjectField(itemstack, "damage", data.damage) setObjectField(itemstack, "count", data.count) return itemstack; end natives["cc.turtle.Turtle"]["equipLeft()Z"] = function(this) local success = turtle.equipLeft() return success end natives["cc.turtle.Turtle"]["equipRight()Z"] = function(this) local success = turtle.equipRight() return success end natives["cc.turtle.Turtle"]["place(Ljava/lang/String;)Z"] = function(this, text) local success = turtle.place(toLString(text)) return booleanToInt(success) end natives["cc.turtle.Turtle"]["placeUp()Z"] = function(this) local success = turtle.placeUp() return booleanToInt(success) end natives["cc.turtle.Turtle"]["placeDown()Z"] = function(this) local success = turtle.placeDown() return booleanToInt(success) end natives["cc.turtle.Turtle"]["detect()Z"] = function(this) local success = turtle.detect() return booleanToInt(success) end natives["cc.turtle.Turtle"]["detectUp()Z"] = function(this) local success = turtle.detect() return booleanToInt(success) end natives["cc.turtle.Turtle"]["detectDown()Z"] = function(this) local success = turtle.detect() return booleanToInt(success) end natives["cc.turtle.Turtle"]["inspect()Lcc/turtle/InspectionReport;"] = function(this) local success, data = turtle.inspect() return createInspectionReport(success, data) end natives["cc.turtle.Turtle"]["inspectUp()Lcc/turtle/InspectionReport;"] = function(this) local success, data = turtle.inspectUp() return createInspectionReport(success, data) end natives["cc.turtle.Turtle"]["inspectDown()Lcc/turtle/InspectionReport;"] = function(this) local success, data = turtle.inspectDown() return createInspectionReport(success, data) end function createInspectionReport(success, data) local class = classByName("cc.turtle.InspectionReport") local report = newInstance(class) findMethod(class, "<init>()V")[1](report) if success then setObjectField(report, "success", 1) setObjectField(report, "blockName", toJString(data.name)) setObjectField(report, "blockMetadata", data.metadata) else setObjectField(report, "success", 0) setObjectField(report, "errorMessage", toJString(data)) end return report end natives["cc.turtle.Turtle"]["compare()Z"] = function(this) local success = turtle.compare() return booleanToInt(success) end natives["cc.turtle.Turtle"]["compareUp()Z"] = function(this) local success = turtle.compareUp() return booleanToInt(success) end natives["cc.turtle.Turtle"]["compareDown()Z"] = function(this) local success = turtle.compareDown() return booleanToInt(success) end natives["cc.turtle.Turtle"]["compareTo(I)Z"] = function(this, slot) local success = turtle.compareTo(slot) return booleanToInt(success) end natives["cc.turtle.Turtle"]["drop(I)Z"] = function(this, count) local success = turtle.drop(count) return booleanToInt(success) end natives["cc.turtle.Turtle"]["dropUp(I)Z"] = function(this, count) local success = turtle.dropUp(count) return booleanToInt(success) end natives["cc.turtle.Turtle"]["dropDown(I)Z"] = function(this, count) local success = turtle.dropDown(count) return booleanToInt(success) end natives["cc.turtle.Turtle"]["suck(I)Z"] = function(this, count) local success = turtle.suck(count) return booleanToInt(success) end natives["cc.turtle.Turtle"]["suckUp(I)Z"] = function(this, count) local success = turtle.suckUp(count) return booleanToInt(success) end natives["cc.turtle.Turtle"]["suckDown(I)Z"] = function(this, count) local success = turtle.suckDown(count) return booleanToInt(success) end natives["cc.turtle.Turtle"]["refuel(I)Z"] = function(this, quantity) local success = turtle.refuel(quantity) return booleanToInt(success) end natives["cc.turtle.Turtle"]["getFuelLevel()I"] = function(this) local level = turtle.getFuelLevel() return level end natives["cc.turtle.Turtle"]["getFuelLimit()I"] = function(this) local level = turtle.getFuelLimit() return level end natives["cc.turtle.Turtle"]["transferTo(II)Z"] = function(this, slot, quantity) local success = turtle.transferTo(slot, quantity) return booleanToInt(success) end -- crafty turtles only natives["cc.turtle.Turtle"]["craft(I)Z"] = function(this, quantity) local success = turtle.craft(quantity) return booleanToInt(success) end -- digging, felling, mining, farming turtles natives["cc.turtle.Turtle"]["dig()Z"] = function(this) local success = turtle.dig() return booleanToInt(success) end natives["cc.turtle.Turtle"]["digUp()Z"] = function(this) local success = turtle.digUp() return booleanToInt(success) end natives["cc.turtle.Turtle"]["digDown()Z"] = function(this) local success = turtle.digDown() return booleanToInt(success) end -- all tools only natives["cc.turtle.Turtle"]["attack()Z"] = function(this) local success = turtle.attack() return booleanToInt(success) end natives["cc.turtle.Turtle"]["attackUp()Z"] = function(this) local success = turtle.attackUp() return booleanToInt(success) end natives["cc.turtle.Turtle"]["attackDown()Z"] = function(this) local success = turtle.attackDown() return booleanToInt(success) end
Really fixed the turtle methods which interpreted the this parameter wrong
Really fixed the turtle methods which interpreted the this parameter wrong
Lua
mit
apemanzilla/JVML-JIT,Team-CC-Corp/JVML-JIT
b16c93bbe50c72130ef84b5bd508404c10f8426a
frontend/ui/widget/htmlboxwidget.lua
frontend/ui/widget/htmlboxwidget.lua
--[[-- HTML widget (without scroll bars). --]] local Device = require("device") local DrawContext = require("ffi/drawcontext") local Geom = require("ui/geometry") local GestureRange = require("ui/gesturerange") local InputContainer = require("ui/widget/container/inputcontainer") local Mupdf = require("ffi/mupdf") local Screen = require("device").screen local TimeVal = require("ui/timeval") local logger = require("logger") local util = require("util") local HtmlBoxWidget = InputContainer:new{ bb = nil, dimen = nil, document = nil, page_count = 0, page_number = 1, hold_start_pos = nil, hold_start_tv = nil, html_link_tapped_callback = nil, } function HtmlBoxWidget:init() if Device:isTouchDevice() then self.ges_events = { TapText = { GestureRange:new{ ges = "tap", range = function() return self.dimen end, }, }, } end end function HtmlBoxWidget:setContent(body, css, default_font_size) -- fz_set_user_css is tied to the context instead of the document so to easily support multiple -- HTML dictionaries with different CSS, we embed the stylesheet into the HTML instead of using -- that function. local head = "" if css then head = string.format("<head><style>%s</style></head>", css) end local html = string.format("<html>%s<body>%s</body></html>", head, body) -- For some reason in MuPDF <br/> always creates both a line break and an empty line, so we have to -- simulate the normal <br/> behavior. -- https://bugs.ghostscript.com/show_bug.cgi?id=698351 html = html:gsub("%<br ?/?%>", "&nbsp;<div></div>") local ok ok, self.document = pcall(Mupdf.openDocumentFromText, html, "html") if not ok then -- self.document contains the error logger.warn("HTML loading error:", self.document) body = util.htmlToPlainText(body) body = util.htmlEscape(body) -- Normally \n would be replaced with <br/>. See the previous comment regarding the bug in MuPDF. body = body:gsub("\n", "&nbsp;<div></div>") html = string.format("<html>%s<body>%s</body></html>", head, body) ok, self.document = pcall(Mupdf.openDocumentFromText, html, "html") if not ok then error(self.document) end end self.document:layoutDocument(self.dimen.w, self.dimen.h, default_font_size) self.page_count = self.document:getPages() end function HtmlBoxWidget:_render() if self.bb then return end -- In pdfdocument.lua, color is activated only at the moment of -- rendering and then immediately disabled, for safety with kopt. -- We do the same here. Mupdf.color = Screen:isColorEnabled() local page = self.document:openPage(self.page_number) local dc = DrawContext.new() self.bb = page:draw_new(dc, self.dimen.w, self.dimen.h, 0, 0) page:close() Mupdf.color = false end function HtmlBoxWidget:getSize() return self.dimen end function HtmlBoxWidget:paintTo(bb, x, y) self.dimen.x = x self.dimen.y = y self:_render() local size = self:getSize() bb:blitFrom(self.bb, x, y, 0, 0, size.w, size.h) end function HtmlBoxWidget:freeBb() if self.bb and self.bb.free then self.bb:free() end self.bb = nil end -- This will normally be called by our WidgetContainer:free() -- But it SHOULD explicitly be called if we are getting replaced -- (ie: in some other widget's update()), to not leak memory with -- BlitBuffer zombies function HtmlBoxWidget:free() self:freeBb() if self.document then self.document:close() self.document = nil end end function HtmlBoxWidget:onCloseWidget() -- free when UIManager:close() was called self:free() end function HtmlBoxWidget:getPosFromAbsPos(abs_pos) local pos = Geom:new{ x = abs_pos.x - self.dimen.x, y = abs_pos.y - self.dimen.y, } -- check if the coordinates are actually inside our area if pos.x < 0 or pos.x >= self.dimen.w or pos.y < 0 or pos.y >= self.dimen.h then return nil end return pos end function HtmlBoxWidget:onHoldStartText(_, ges) self.hold_start_pos = self:getPosFromAbsPos(ges.pos) self.hold_start_tv = TimeVal.now() return true end function HtmlBoxWidget:getSelectedText(lines, start_pos, end_pos) local found_start = false local words = {} for _, line in pairs(lines) do for _, w in pairs(line) do if type(w) == 'table' then if (not found_start) and (start_pos.x >= w.x0 and start_pos.x < w.x1 and start_pos.y >= w.y0 and start_pos.y < w.y1) then found_start = true end if found_start then table.insert(words, w.word) -- Found the end. if end_pos.x >= w.x0 and end_pos.x < w.x1 and end_pos.y >= w.y0 and end_pos.y < w.y1 then return words end end end end end return words end function HtmlBoxWidget:onHoldReleaseText(callback, ges) if not callback then return false end -- check we have seen a HoldStart event if not self.hold_start_pos then return false end local start_pos = self.hold_start_pos self.hold_start_pos = nil local end_pos = self:getPosFromAbsPos(ges.pos) if not end_pos then return false end local hold_duration = TimeVal.now() - self.hold_start_tv hold_duration = hold_duration.sec + (hold_duration.usec/1000000) local page = self.document:openPage(self.page_number) local lines = page:getPageText() page:close() local words = self:getSelectedText(lines, start_pos, end_pos) local selected_text = table.concat(words, " ") callback(selected_text, hold_duration) return true end function HtmlBoxWidget:getLinkByPosition(pos) local page = self.document:openPage(self.page_number) local links = page:getPageLinks() page:close() for _, link in pairs(links) do if pos.x >= link.x0 and pos.x < link.x1 and pos.y >= link.y0 and pos.y < link.y1 then return link end end end function HtmlBoxWidget:onTapText(arg, ges) if G_reader_settings:isFalse("tap_to_follow_links") then return end if self.html_link_tapped_callback then local pos = self:getPosFromAbsPos(ges.pos) if pos then local link = self:getLinkByPosition(pos) if link then self.html_link_tapped_callback(link) return true end end end end return HtmlBoxWidget
--[[-- HTML widget (without scroll bars). --]] local Device = require("device") local DrawContext = require("ffi/drawcontext") local Geom = require("ui/geometry") local GestureRange = require("ui/gesturerange") local InputContainer = require("ui/widget/container/inputcontainer") local Mupdf = require("ffi/mupdf") local Screen = require("device").screen local TimeVal = require("ui/timeval") local logger = require("logger") local util = require("util") local HtmlBoxWidget = InputContainer:new{ bb = nil, dimen = nil, document = nil, page_count = 0, page_number = 1, hold_start_pos = nil, hold_start_tv = nil, html_link_tapped_callback = nil, } function HtmlBoxWidget:init() if Device:isTouchDevice() then self.ges_events = { TapText = { GestureRange:new{ ges = "tap", range = function() return self.dimen end, }, }, } end end function HtmlBoxWidget:setContent(body, css, default_font_size) -- fz_set_user_css is tied to the context instead of the document so to easily support multiple -- HTML dictionaries with different CSS, we embed the stylesheet into the HTML instead of using -- that function. local head = "" if css then head = string.format("<head><style>%s</style></head>", css) end local html = string.format("<html>%s<body>%s</body></html>", head, body) -- For some reason in MuPDF <br/> always creates both a line break and an empty line, so we have to -- simulate the normal <br/> behavior. -- https://bugs.ghostscript.com/show_bug.cgi?id=698351 html = html:gsub("%<br ?/?%>", "&nbsp;<div></div>") local ok ok, self.document = pcall(Mupdf.openDocumentFromText, html, "html") if not ok then -- self.document contains the error logger.warn("HTML loading error:", self.document) body = util.htmlToPlainText(body) body = util.htmlEscape(body) -- Normally \n would be replaced with <br/>. See the previous comment regarding the bug in MuPDF. body = body:gsub("\n", "&nbsp;<div></div>") html = string.format("<html>%s<body>%s</body></html>", head, body) ok, self.document = pcall(Mupdf.openDocumentFromText, html, "html") if not ok then error(self.document) end end self.document:layoutDocument(self.dimen.w, self.dimen.h, default_font_size) self.page_count = self.document:getPages() end function HtmlBoxWidget:_render() if self.bb then return end -- In pdfdocument.lua, color is activated only at the moment of -- rendering and then immediately disabled, for safety with kopt. -- We do the same here. Mupdf.color = Screen:isColorEnabled() local page = self.document:openPage(self.page_number) local dc = DrawContext.new() self.bb = page:draw_new(dc, self.dimen.w, self.dimen.h, 0, 0) page:close() Mupdf.color = false end function HtmlBoxWidget:getSize() return self.dimen end function HtmlBoxWidget:paintTo(bb, x, y) self.dimen.x = x self.dimen.y = y self:_render() local size = self:getSize() bb:blitFrom(self.bb, x, y, 0, 0, size.w, size.h) end function HtmlBoxWidget:freeBb() if self.bb and self.bb.free then self.bb:free() end self.bb = nil end -- This will normally be called by our WidgetContainer:free() -- But it SHOULD explicitly be called if we are getting replaced -- (ie: in some other widget's update()), to not leak memory with -- BlitBuffer zombies function HtmlBoxWidget:free() self:freeBb() if self.document then self.document:close() self.document = nil end end function HtmlBoxWidget:onCloseWidget() -- free when UIManager:close() was called self:free() end function HtmlBoxWidget:getPosFromAbsPos(abs_pos) local pos = Geom:new{ x = abs_pos.x - self.dimen.x, y = abs_pos.y - self.dimen.y, } -- check if the coordinates are actually inside our area if pos.x < 0 or pos.x >= self.dimen.w or pos.y < 0 or pos.y >= self.dimen.h then return nil end return pos end function HtmlBoxWidget:onHoldStartText(_, ges) self.hold_start_pos = self:getPosFromAbsPos(ges.pos) self.hold_start_tv = TimeVal.now() return true end function HtmlBoxWidget:getSelectedText(lines, start_pos, end_pos) local found_start = false local words = {} for _, line in pairs(lines) do for _, w in pairs(line) do if type(w) == 'table' then if not found_start then if start_pos.x >= w.x0 and start_pos.x < w.x1 and start_pos.y >= w.y0 and start_pos.y < w.y1 then found_start = true elseif end_pos.x >= w.x0 and end_pos.x < w.x1 and end_pos.y >= w.y0 and end_pos.y < w.y1 then -- We found end_pos before start_pos, switch them found_start = true start_pos, end_pos = end_pos, start_pos end end if found_start then table.insert(words, w.word) -- Found the end. if end_pos.x >= w.x0 and end_pos.x < w.x1 and end_pos.y >= w.y0 and end_pos.y < w.y1 then return words end end end end end return words end function HtmlBoxWidget:onHoldReleaseText(callback, ges) if not callback then return false end -- check we have seen a HoldStart event if not self.hold_start_pos then return false end local start_pos = self.hold_start_pos self.hold_start_pos = nil local end_pos = self:getPosFromAbsPos(ges.pos) if not end_pos then return false end local hold_duration = TimeVal.now() - self.hold_start_tv hold_duration = hold_duration.sec + (hold_duration.usec/1000000) local page = self.document:openPage(self.page_number) local lines = page:getPageText() page:close() local words = self:getSelectedText(lines, start_pos, end_pos) local selected_text = table.concat(words, " ") callback(selected_text, hold_duration) return true end function HtmlBoxWidget:getLinkByPosition(pos) local page = self.document:openPage(self.page_number) local links = page:getPageLinks() page:close() for _, link in pairs(links) do if pos.x >= link.x0 and pos.x < link.x1 and pos.y >= link.y0 and pos.y < link.y1 then return link end end end function HtmlBoxWidget:onTapText(arg, ges) if G_reader_settings:isFalse("tap_to_follow_links") then return end if self.html_link_tapped_callback then local pos = self:getPosFromAbsPos(ges.pos) if pos then local link = self:getLinkByPosition(pos) if link then self.html_link_tapped_callback(link) return true end end end end return HtmlBoxWidget
HtmlBoxWidget: fix selection when starting from end (#3632)
HtmlBoxWidget: fix selection when starting from end (#3632)
Lua
agpl-3.0
NiLuJe/koreader,houqp/koreader,poire-z/koreader,mihailim/koreader,poire-z/koreader,koreader/koreader,koreader/koreader,lgeek/koreader,apletnev/koreader,Markismus/koreader,NiLuJe/koreader,Frenzie/koreader,Hzj-jie/koreader,Frenzie/koreader,mwoz123/koreader,pazos/koreader
394c9cf948119eacfe438c72ab79417c648cb3ce
frontend/ui/widget/container/inputcontainer.lua
frontend/ui/widget/container/inputcontainer.lua
local WidgetContainer = require("ui/widget/container/widgetcontainer") local UIManager = require("ui/uimanager") local Screen = require("device").screen local Geom = require("ui/geometry") local Event = require("ui/event") local DEBUG = require("dbg") local _ = require("gettext") --[[ an InputContainer is an WidgetContainer that handles input events an example for a key_event is this: PanBy20 = { { "Shift", Input.group.Cursor }, seqtext = "Shift+Cursor", doc = "pan by 20px", event = "Pan", args = 20, is_inactive = true, }, PanNormal = { { Input.group.Cursor }, seqtext = "Cursor", doc = "pan by 10 px", event = "Pan", args = 10, }, Quit = { {"Home"} }, it is suggested to reference configurable sequences from another table and store that table as configuration setting --]] local InputContainer = WidgetContainer:new{ vertical_align = "top", } function InputContainer:_init() -- we need to do deep copy here local new_key_events = {} if self.key_events then for k,v in pairs(self.key_events) do new_key_events[k] = v end end self.key_events = new_key_events local new_ges_events = {} if self.ges_events then for k,v in pairs(self.ges_events) do new_ges_events[k] = v end end self.ges_events = new_ges_events end function InputContainer:paintTo(bb, x, y) if not self.dimen then self.dimen = self[1]:getSize() end self.dimen.x = x self.dimen.y = y if self[1] then if self.vertical_align == "center" then local content_size = self[1]:getSize() self[1]:paintTo(bb, x, y + math.floor((self.dimen.h - content_size.h)/2)) else self[1]:paintTo(bb, x, y) end end end --[[ the following handler handles keypresses and checks if they lead to a command. if this is the case, we retransmit another event within ourselves --]] function InputContainer:onKeyPress(key) for name, seq in pairs(self.key_events) do if not seq.is_inactive then for _, oneseq in ipairs(seq) do if key:match(oneseq) then local eventname = seq.event or name return self:handleEvent(Event:new(eventname, seq.args, key)) end end end end end function InputContainer:onGesture(ev) for name, gsseq in pairs(self.ges_events) do for _, gs_range in ipairs(gsseq) do --DEBUG("gs_range", gs_range) if gs_range:match(ev) then local eventname = gsseq.event or name return self:handleEvent(Event:new(eventname, gsseq.args, ev)) end end end end function InputContainer:onInput(input) local InputDialog = require("ui/widget/inputdialog") self.input_dialog = InputDialog:new{ title = input.title or "", input = input.input, input_hint = input.hint_func and input.hint_func() or input.hint or "", input_type = input.type or "number", buttons = { { { text = _("Cancel"), callback = function() self:closeInputDialog() end, }, { text = _("OK"), callback = function() input.callback(self.input_dialog:getInputText()) self:closeInputDialog() end, }, }, }, enter_callback = function() input.callback(self.input_dialog:getInputText()) self:closeInputDialog() end, width = Screen:getWidth() * 0.8, height = Screen:getHeight() * 0.2, } self.input_dialog:onShowKeyboard() UIManager:show(self.input_dialog) end function InputContainer:closeInputDialog() self.input_dialog:onClose() UIManager:close(self.input_dialog) end return InputContainer
local WidgetContainer = require("ui/widget/container/widgetcontainer") local UIManager = require("ui/uimanager") local Screen = require("device").screen local Geom = require("ui/geometry") local Event = require("ui/event") local DEBUG = require("dbg") local _ = require("gettext") --[[ an InputContainer is an WidgetContainer that handles input events an example for a key_event is this: PanBy20 = { { "Shift", Input.group.Cursor }, seqtext = "Shift+Cursor", doc = "pan by 20px", event = "Pan", args = 20, is_inactive = true, }, PanNormal = { { Input.group.Cursor }, seqtext = "Cursor", doc = "pan by 10 px", event = "Pan", args = 10, }, Quit = { {"Home"} }, it is suggested to reference configurable sequences from another table and store that table as configuration setting --]] local InputContainer = WidgetContainer:new{ vertical_align = "top", } function InputContainer:_init() -- we need to do deep copy here local new_key_events = {} if self.key_events then for k,v in pairs(self.key_events) do new_key_events[k] = v end end self.key_events = new_key_events local new_ges_events = {} if self.ges_events then for k,v in pairs(self.ges_events) do new_ges_events[k] = v end end self.ges_events = new_ges_events end function InputContainer:paintTo(bb, x, y) if not self.dimen then local content_size = self[1]:getSize() self.dimen = Geom:new{w = content_size.w, h = content_size.h} end self.dimen.x = x self.dimen.y = y if self[1] then if self.vertical_align == "center" then local content_size = self[1]:getSize() self[1]:paintTo(bb, x, y + math.floor((self.dimen.h - content_size.h)/2)) else self[1]:paintTo(bb, x, y) end end end --[[ the following handler handles keypresses and checks if they lead to a command. if this is the case, we retransmit another event within ourselves --]] function InputContainer:onKeyPress(key) for name, seq in pairs(self.key_events) do if not seq.is_inactive then for _, oneseq in ipairs(seq) do if key:match(oneseq) then local eventname = seq.event or name return self:handleEvent(Event:new(eventname, seq.args, key)) end end end end end function InputContainer:onGesture(ev) for name, gsseq in pairs(self.ges_events) do for _, gs_range in ipairs(gsseq) do --DEBUG("gs_range", gs_range) if gs_range:match(ev) then local eventname = gsseq.event or name return self:handleEvent(Event:new(eventname, gsseq.args, ev)) end end end end function InputContainer:onInput(input) local InputDialog = require("ui/widget/inputdialog") self.input_dialog = InputDialog:new{ title = input.title or "", input = input.input, input_hint = input.hint_func and input.hint_func() or input.hint or "", input_type = input.type or "number", buttons = { { { text = _("Cancel"), callback = function() self:closeInputDialog() end, }, { text = _("OK"), callback = function() input.callback(self.input_dialog:getInputText()) self:closeInputDialog() end, }, }, }, enter_callback = function() input.callback(self.input_dialog:getInputText()) self:closeInputDialog() end, width = Screen:getWidth() * 0.8, height = Screen:getHeight() * 0.2, } self.input_dialog:onShowKeyboard() UIManager:show(self.input_dialog) end function InputContainer:closeInputDialog() self.input_dialog:onClose() UIManager:close(self.input_dialog) end return InputContainer
fix dimen returned by getSize used as dimen in inputcontainer
fix dimen returned by getSize used as dimen in inputcontainer
Lua
agpl-3.0
NiLuJe/koreader,koreader/koreader,poire-z/koreader,mwoz123/koreader,pazos/koreader,NiLuJe/koreader,robert00s/koreader,apletnev/koreader,frankyifei/koreader,Hzj-jie/koreader,mihailim/koreader,Markismus/koreader,koreader/koreader,poire-z/koreader,Frenzie/koreader,NickSavage/koreader,chihyang/koreader,Frenzie/koreader,houqp/koreader,lgeek/koreader
c6214faeba114e505abebc26263e6d12ed1dec23
modules/admin-full/luasrc/model/cbi/admin_system/system.lua
modules/admin-full/luasrc/model/cbi/admin_system/system.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.sys") require("luci.sys.zoneinfo") require("luci.tools.webadmin") require("luci.fs") require("luci.config") local m, s, o local has_ntpd = luci.fs.access("/usr/sbin/ntpd") m = Map("system", translate("System"), translate("Here you can configure the basic aspects of your device like its hostname or the timezone.")) m:chain("luci") s = m:section(TypedSection, "system", translate("System Properties")) s.anonymous = true s.addremove = false s:tab("general", translate("General Settings")) s:tab("logging", translate("Logging")) s:tab("language", translate("Language and Style")) -- -- System Properties -- o = s:taboption("general", DummyValue, "_systime", translate("Local Time")) o.template = "admin_system/clock_status" o = s:taboption("general", Value, "hostname", translate("Hostname")) o.datatype = "hostname" function o.write(self, section, value) Value.write(self, section, value) luci.sys.hostname(value) end o = s:taboption("general", ListValue, "zonename", translate("Timezone")) o:value("UTC") for i, zone in ipairs(luci.sys.zoneinfo.TZ) do o:value(zone[1]) end function o.write(self, section, value) local function lookup_zone(title) for _, zone in ipairs(luci.sys.zoneinfo.TZ) do if zone[1] == title then return zone[2] end end end AbstractValue.write(self, section, value) local timezone = lookup_zone(value) or "GMT0" self.map.uci:set("system", section, "timezone", timezone) luci.fs.writefile("/etc/TZ", timezone .. "\n") end -- -- Logging -- o = s:taboption("logging", Value, "log_size", translate("System log buffer size"), "kiB") o.optional = true o.placeholder = 16 o.datatype = "uinteger" o = s:taboption("logging", Value, "log_ip", translate("External system log server")) o.optional = true o.placeholder = "0.0.0.0" o.datatype = "ip4addr" o = s:taboption("logging", Value, "log_port", translate("External system log server port")) o.optional = true o.placeholder = 514 o.datatype = "port" o = s:taboption("logging", ListValue, "conloglevel", translate("Log output level")) o:value(8, translate("Debug")) o:value(7, translate("Info")) o:value(6, translate("Notice")) o:value(5, translate("Warning")) o:value(4, translate("Error")) o:value(3, translate("Critical")) o:value(2, translate("Alert")) o:value(1, translate("Emergency")) o = s:taboption("logging", ListValue, "cronloglevel", translate("Cron Log Level")) o.default = 8 o:value(5, translate("Debug")) o:value(8, translate("Normal")) o:value(9, translate("Warning")) -- -- Langauge & Style -- o = s:taboption("language", ListValue, "_lang", translate("Language")) o:value("auto") local i18ndir = luci.i18n.i18ndir .. "base." for k, v in luci.util.kspairs(luci.config.languages) do local file = i18ndir .. k:gsub("_", "-") if k:sub(1, 1) ~= "." and luci.fs.access(file .. ".lmo") then o:value(k, v) end end function o.cfgvalue(...) return m.uci:get("luci", "main", "lang") end function o.write(self, section, value) m.uci:set("luci", "main", "lang", value) end o = s:taboption("language", ListValue, "_mediaurlbase", translate("Design")) for k, v in pairs(luci.config.themes) do if k:sub(1, 1) ~= "." then o:value(v, k) end end function o.cfgvalue(...) return m.uci:get("luci", "main", "mediaurlbase") end function o.write(self, section, value) m.uci:set("luci", "main", "mediaurlbase", value) end -- -- NTP -- if has_ntpd then s = m:section(TypedSection, "timeserver", translate("Time Synchronization")) s.anonymous = true s.addremove = false function m.on_parse() local has_section = false m.uci:foreach("system", "timeserver", function(s) has_section = true return false end) if not has_section then m.uci:section("system", "timeserver", "ntp") end end o = s:option(Flag, "enable", translate("Enable builtin NTP server")) o.rmempty = false function o.cfgvalue(self) return luci.sys.init.enabled("sysntpd") and self.enabled or self.disabled end function o.write(self, section, value) if value == self.enabled then luci.sys.init.enable("sysntpd") luci.sys.call("env -i /etc/init.d/sysntpd start >/dev/null") else luci.sys.call("env -i /etc/init.d/sysntpd stop >/dev/null") luci.sys.init.disable("sysntpd") end end o = s:option(DynamicList, "server", translate("NTP server candidates")) o.datatype = "host" o:depends("enable", "1") -- retain server list even if disabled function o.remove() end end return m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.sys") require("luci.sys.zoneinfo") require("luci.tools.webadmin") require("luci.fs") require("luci.config") local m, s, o local has_ntpd = luci.fs.access("/usr/sbin/ntpd") m = Map("system", translate("System"), translate("Here you can configure the basic aspects of your device like its hostname or the timezone.")) m:chain("luci") s = m:section(TypedSection, "system", translate("System Properties")) s.anonymous = true s.addremove = false s:tab("general", translate("General Settings")) s:tab("logging", translate("Logging")) s:tab("language", translate("Language and Style")) -- -- System Properties -- o = s:taboption("general", DummyValue, "_systime", translate("Local Time")) o.template = "admin_system/clock_status" o = s:taboption("general", Value, "hostname", translate("Hostname")) o.datatype = "hostname" function o.write(self, section, value) Value.write(self, section, value) luci.sys.hostname(value) end o = s:taboption("general", ListValue, "zonename", translate("Timezone")) o:value("UTC") for i, zone in ipairs(luci.sys.zoneinfo.TZ) do o:value(zone[1]) end function o.write(self, section, value) local function lookup_zone(title) for _, zone in ipairs(luci.sys.zoneinfo.TZ) do if zone[1] == title then return zone[2] end end end AbstractValue.write(self, section, value) local timezone = lookup_zone(value) or "GMT0" self.map.uci:set("system", section, "timezone", timezone) luci.fs.writefile("/etc/TZ", timezone .. "\n") end -- -- Logging -- o = s:taboption("logging", Value, "log_size", translate("System log buffer size"), "kiB") o.optional = true o.placeholder = 16 o.datatype = "uinteger" o = s:taboption("logging", Value, "log_ip", translate("External system log server")) o.optional = true o.placeholder = "0.0.0.0" o.datatype = "ip4addr" o = s:taboption("logging", Value, "log_port", translate("External system log server port")) o.optional = true o.placeholder = 514 o.datatype = "port" o = s:taboption("logging", ListValue, "conloglevel", translate("Log output level")) o:value(8, translate("Debug")) o:value(7, translate("Info")) o:value(6, translate("Notice")) o:value(5, translate("Warning")) o:value(4, translate("Error")) o:value(3, translate("Critical")) o:value(2, translate("Alert")) o:value(1, translate("Emergency")) o = s:taboption("logging", ListValue, "cronloglevel", translate("Cron Log Level")) o.default = 8 o:value(5, translate("Debug")) o:value(8, translate("Normal")) o:value(9, translate("Warning")) -- -- Langauge & Style -- o = s:taboption("language", ListValue, "_lang", translate("Language")) o:value("auto") local i18ndir = luci.i18n.i18ndir .. "base." for k, v in luci.util.kspairs(luci.config.languages) do local file = i18ndir .. k:gsub("_", "-") if k:sub(1, 1) ~= "." and luci.fs.access(file .. ".lmo") then o:value(k, v) end end function o.cfgvalue(...) return m.uci:get("luci", "main", "lang") end function o.write(self, section, value) m.uci:set("luci", "main", "lang", value) end o = s:taboption("language", ListValue, "_mediaurlbase", translate("Design")) for k, v in pairs(luci.config.themes) do if k:sub(1, 1) ~= "." then o:value(v, k) end end function o.cfgvalue(...) return m.uci:get("luci", "main", "mediaurlbase") end function o.write(self, section, value) m.uci:set("luci", "main", "mediaurlbase", value) end -- -- NTP -- if has_ntpd then -- timeserver setup was requested, create section and reload page if m:formvalue("cbid.system._timeserver._enable") then m.uci:section("system", "timeserver", "ntp") m.uci:save("system") luci.http.redirect(luci.dispatcher.build_url("admin/system", arg[1])) return end local has_section = false m.uci:foreach("system", "timeserver", function(s) has_section = true return false end) if not has_section then s = m:section(TypedSection, "timeserver", translate("Time Synchronization")) s.anonymous = true s.cfgsections = function() return { "_timeserver" } end x = s:option(Button, "_enable") x.title = translate("Time Synchronization is not configured yet.") x.inputtitle = translate("Setup Time Synchronization") x.inputstyle = "apply" else s = m:section(TypedSection, "timeserver", translate("Time Synchronization")) s.anonymous = true s.addremove = false o = s:option(Flag, "enable", translate("Enable builtin NTP server")) o.rmempty = false function o.cfgvalue(self) return luci.sys.init.enabled("sysntpd") and self.enabled or self.disabled end function o.write(self, section, value) if value == self.enabled then luci.sys.init.enable("sysntpd") luci.sys.call("env -i /etc/init.d/sysntpd start >/dev/null") else luci.sys.call("env -i /etc/init.d/sysntpd stop >/dev/null") luci.sys.init.disable("sysntpd") end end o = s:option(DynamicList, "server", translate("NTP server candidates")) o.datatype = "host" o:depends("enable", "1") -- retain server list even if disabled function o.remove() end end end return m
admin-full: Better fix for the last change (timeserver setup), add button to add the missing section
admin-full: Better fix for the last change (timeserver setup), add button to add the missing section git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@7915 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
phi-psi/luci,yeewang/openwrt-luci,eugenesan/openwrt-luci,dtaht/cerowrt-luci-3.3,vhpham80/luci,Flexibity/luci,dtaht/cerowrt-luci-3.3,phi-psi/luci,freifunk-gluon/luci,saraedum/luci-packages-old,saraedum/luci-packages-old,gwlim/luci,eugenesan/openwrt-luci,phi-psi/luci,jschmidlapp/luci,Canaan-Creative/luci,freifunk-gluon/luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,ch3n2k/luci,vhpham80/luci,eugenesan/openwrt-luci,ThingMesh/openwrt-luci,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,dtaht/cerowrt-luci-3.3,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,8devices/carambola2-luci,eugenesan/openwrt-luci,ch3n2k/luci,8devices/carambola2-luci,dtaht/cerowrt-luci-3.3,saraedum/luci-packages-old,gwlim/luci,gwlim/luci,Canaan-Creative/luci,ch3n2k/luci,vhpham80/luci,Canaan-Creative/luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,stephank/luci,stephank/luci,ThingMesh/openwrt-luci,jschmidlapp/luci,ch3n2k/luci,zwhfly/openwrt-luci,Flexibity/luci,ThingMesh/openwrt-luci,gwlim/luci,Canaan-Creative/luci,yeewang/openwrt-luci,ThingMesh/openwrt-luci,jschmidlapp/luci,vhpham80/luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,8devices/carambola2-luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,stephank/luci,Canaan-Creative/luci,eugenesan/openwrt-luci,Flexibity/luci,freifunk-gluon/luci,gwlim/luci,Canaan-Creative/luci,zwhfly/openwrt-luci,phi-psi/luci,stephank/luci,jschmidlapp/luci,freifunk-gluon/luci,zwhfly/openwrt-luci,saraedum/luci-packages-old,jschmidlapp/luci,yeewang/openwrt-luci,yeewang/openwrt-luci,phi-psi/luci,eugenesan/openwrt-luci,freifunk-gluon/luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,dtaht/cerowrt-luci-3.3,dtaht/cerowrt-luci-3.3,ThingMesh/openwrt-luci,Flexibity/luci,eugenesan/openwrt-luci,freifunk-gluon/luci,jschmidlapp/luci,saraedum/luci-packages-old,jschmidlapp/luci,ReclaimYourPrivacy/cloak-luci,stephank/luci,Canaan-Creative/luci,zwhfly/openwrt-luci,freifunk-gluon/luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,vhpham80/luci,stephank/luci,ThingMesh/openwrt-luci,Flexibity/luci,vhpham80/luci,8devices/carambola2-luci,Flexibity/luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,gwlim/luci,ch3n2k/luci,8devices/carambola2-luci,saraedum/luci-packages-old,gwlim/luci,yeewang/openwrt-luci,phi-psi/luci,8devices/carambola2-luci
f61147a82b21024c7a030bb53d4eff5db19e3b9b
modules/admin-full/luasrc/model/cbi/admin_index/luci.lua
modules/admin-full/luasrc/model/cbi/admin_index/luci.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.config") m = Map("luci", translate("Web <abbr title=\"User Interface\">UI</abbr>"), translate("Here you can customize the settings and the functionality of <abbr title=\"Lua Configuration Interface\">LuCI</abbr>.")) local fs = require "nixio.fs" -- force reload of global luci config namespace to reflect the changes function m.commit_handler(self) package.loaded["luci.config"] = nil require("luci.config") end c = m:section(NamedSection, "main", "core", translate("General")) l = c:option(ListValue, "lang", translate("Language")) l:value("auto") local i18ndir = luci.i18n.i18ndir .. "base." for k, v in luci.util.kspairs(luci.config.languages) do local file = i18ndir .. k:gsub("_", "-") if k:sub(1, 1) ~= "." and fs.access(file .. ".lmo") then l:value(k, v) end end t = c:option(ListValue, "mediaurlbase", translate("Design")) for k, v in pairs(luci.config.themes) do if k:sub(1, 1) ~= "." then t:value(v, k) end end u = m:section(NamedSection, "uci_oncommit", "event", translate("Post-commit actions"), translate("These commands will be executed automatically when a given <abbr title=\"Unified Configuration Interface\">UCI</abbr> configuration is committed allowing changes to be applied instantly.")) u.dynamic = true f = m:section(NamedSection, "main", "core", translate("Files to be kept when flashing a new firmware")) f:tab("detected", translate("Detected Files"), translate("The following files are detected by the system and will be kept automatically during sysupgrade")) f:tab("custom", translate("Custom Files"), translate("This is a list of shell glob patterns for matching files and directories to include during sysupgrade")) d = f:taboption("detected", DummyValue, "_detected", translate("Detected files")) d.rawhtml = true d.cfgvalue = function(s) local list = io.popen( "( find $(sed -ne '/^[[:space:]]*$/d; /^#/d; p' /etc/sysupgrade.conf " .. "/lib/upgrade/keep.d/* 2>/dev/null) -type f 2>/dev/null; " .. "opkg list-changed-conffiles ) | sort -u" ) if list then local files = { "<ul>" } while true do local ln = list:read("*l") if not ln then break else files[#files+1] = "<li>" files[#files+1] = luci.util.pcdata(ln) files[#files+1] = "</li>" end end list:close() files[#files+1] = "</ul>" return table.concat(files, "") end return "<em>" .. translate("No files found") .. "</em>" end c = f:taboption("custom", TextValue, "_custom", translate("Custom files")) c.rmempty = false c.cols = 70 c.rows = 30 c.cfgvalue = function(self, section) return nixio.fs.readfile("/etc/sysupgrade.conf") end c.write = function(self, section, value) return nixio.fs.writefile("/etc/sysupgrade.conf", value) end return m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.config") m = Map("luci", translate("Web <abbr title=\"User Interface\">UI</abbr>"), translate("Here you can customize the settings and the functionality of <abbr title=\"Lua Configuration Interface\">LuCI</abbr>.")) local fs = require "nixio.fs" -- force reload of global luci config namespace to reflect the changes function m.commit_handler(self) package.loaded["luci.config"] = nil require("luci.config") end c = m:section(NamedSection, "main", "core", translate("General")) l = c:option(ListValue, "lang", translate("Language")) l:value("auto") local i18ndir = luci.i18n.i18ndir .. "base." for k, v in luci.util.kspairs(luci.config.languages) do local file = i18ndir .. k:gsub("_", "-") if k:sub(1, 1) ~= "." and fs.access(file .. ".lmo") then l:value(k, v) end end t = c:option(ListValue, "mediaurlbase", translate("Design")) for k, v in pairs(luci.config.themes) do if k:sub(1, 1) ~= "." then t:value(v, k) end end u = m:section(NamedSection, "uci_oncommit", "event", translate("Post-commit actions"), translate("These commands will be executed automatically when a given <abbr title=\"Unified Configuration Interface\">UCI</abbr> configuration is committed allowing changes to be applied instantly.")) u.dynamic = true f = m:section(NamedSection, "main", "core", translate("Files to be kept when flashing a new firmware")) f:tab("detected", translate("Detected Files"), translate("The following files are detected by the system and will be kept automatically during sysupgrade")) f:tab("custom", translate("Custom Files"), translate("This is a list of shell glob patterns for matching files and directories to include during sysupgrade")) d = f:taboption("detected", DummyValue, "_detected", translate("Detected files")) d.rawhtml = true d.cfgvalue = function(s) local list = io.popen( "( find $(sed -ne '/^[[:space:]]*$/d; /^#/d; p' /etc/sysupgrade.conf " .. "/lib/upgrade/keep.d/* 2>/dev/null) -type f 2>/dev/null; " .. "opkg list-changed-conffiles ) | sort -u" ) if list then local files = { "<ul>" } while true do local ln = list:read("*l") if not ln then break else files[#files+1] = "<li>" files[#files+1] = luci.util.pcdata(ln) files[#files+1] = "</li>" end end list:close() files[#files+1] = "</ul>" return table.concat(files, "") end return "<em>" .. translate("No files found") .. "</em>" end c = f:taboption("custom", TextValue, "_custom", translate("Custom files")) c.rmempty = false c.cols = 70 c.rows = 30 c.cfgvalue = function(self, section) return nixio.fs.readfile("/etc/sysupgrade.conf") end c.write = function(self, section, value) value = value:gsub("\r\n?", "\n") return nixio.fs.writefile("/etc/sysupgrade.conf", value) end return m
modules/admin-full: fixup newlines when storing sysupgrade.conf
modules/admin-full: fixup newlines when storing sysupgrade.conf
Lua
apache-2.0
dwmw2/luci,forward619/luci,openwrt/luci,male-puppies/luci,hnyman/luci,jchuang1977/luci-1,Noltari/luci,jchuang1977/luci-1,sujeet14108/luci,keyidadi/luci,male-puppies/luci,RedSnake64/openwrt-luci-packages,Hostle/openwrt-luci-multi-user,forward619/luci,ff94315/luci-1,bright-things/ionic-luci,chris5560/openwrt-luci,nwf/openwrt-luci,lcf258/openwrtcn,LazyZhu/openwrt-luci-trunk-mod,palmettos/test,david-xiao/luci,palmettos/test,thess/OpenWrt-luci,male-puppies/luci,MinFu/luci,forward619/luci,openwrt-es/openwrt-luci,teslamint/luci,palmettos/cnLuCI,aircross/OpenWrt-Firefly-LuCI,dwmw2/luci,obsy/luci,male-puppies/luci,oneru/luci,jorgifumi/luci,Hostle/luci,artynet/luci,aircross/OpenWrt-Firefly-LuCI,rogerpueyo/luci,openwrt/luci,Hostle/openwrt-luci-multi-user,LuttyYang/luci,shangjiyu/luci-with-extra,tcatm/luci,Hostle/luci,chris5560/openwrt-luci,jchuang1977/luci-1,urueedi/luci,nwf/openwrt-luci,opentechinstitute/luci,openwrt/luci,maxrio/luci981213,Hostle/luci,Hostle/luci,ReclaimYourPrivacy/cloak-luci,keyidadi/luci,hnyman/luci,opentechinstitute/luci,taiha/luci,lcf258/openwrtcn,taiha/luci,deepak78/new-luci,LuttyYang/luci,Kyklas/luci-proto-hso,bright-things/ionic-luci,florian-shellfire/luci,thess/OpenWrt-luci,RuiChen1113/luci,Wedmer/luci,981213/luci-1,lcf258/openwrtcn,joaofvieira/luci,cshore/luci,RuiChen1113/luci,zhaoxx063/luci,maxrio/luci981213,kuoruan/lede-luci,wongsyrone/luci-1,ReclaimYourPrivacy/cloak-luci,zhaoxx063/luci,ollie27/openwrt_luci,aa65535/luci,jchuang1977/luci-1,palmettos/test,aa65535/luci,hnyman/luci,ReclaimYourPrivacy/cloak-luci,cshore/luci,981213/luci-1,artynet/luci,Sakura-Winkey/LuCI,Noltari/luci,shangjiyu/luci-with-extra,forward619/luci,palmettos/test,artynet/luci,keyidadi/luci,male-puppies/luci,zhaoxx063/luci,schidler/ionic-luci,fkooman/luci,Sakura-Winkey/LuCI,mumuqz/luci,zhaoxx063/luci,LuttyYang/luci,NeoRaider/luci,LazyZhu/openwrt-luci-trunk-mod,openwrt/luci,urueedi/luci,david-xiao/luci,palmettos/test,florian-shellfire/luci,tobiaswaldvogel/luci,marcel-sch/luci,nwf/openwrt-luci,Hostle/luci,db260179/openwrt-bpi-r1-luci,bittorf/luci,lbthomsen/openwrt-luci,bright-things/ionic-luci,dwmw2/luci,RuiChen1113/luci,zhaoxx063/luci,LuttyYang/luci,tcatm/luci,kuoruan/lede-luci,hnyman/luci,oneru/luci,tcatm/luci,Wedmer/luci,wongsyrone/luci-1,forward619/luci,lbthomsen/openwrt-luci,dismantl/luci-0.12,kuoruan/luci,remakeelectric/luci,marcel-sch/luci,artynet/luci,MinFu/luci,marcel-sch/luci,Noltari/luci,david-xiao/luci,kuoruan/lede-luci,deepak78/new-luci,palmettos/cnLuCI,LuttyYang/luci,NeoRaider/luci,Hostle/luci,db260179/openwrt-bpi-r1-luci,mumuqz/luci,opentechinstitute/luci,florian-shellfire/luci,deepak78/new-luci,jlopenwrtluci/luci,Hostle/openwrt-luci-multi-user,urueedi/luci,dismantl/luci-0.12,jlopenwrtluci/luci,jorgifumi/luci,nmav/luci,jlopenwrtluci/luci,jorgifumi/luci,fkooman/luci,male-puppies/luci,dismantl/luci-0.12,oneru/luci,taiha/luci,oneru/luci,rogerpueyo/luci,981213/luci-1,chris5560/openwrt-luci,florian-shellfire/luci,hnyman/luci,RedSnake64/openwrt-luci-packages,daofeng2015/luci,palmettos/cnLuCI,sujeet14108/luci,thesabbir/luci,remakeelectric/luci,opentechinstitute/luci,tobiaswaldvogel/luci,cshore/luci,bright-things/ionic-luci,cappiewu/luci,artynet/luci,cshore/luci,Wedmer/luci,Kyklas/luci-proto-hso,LuttyYang/luci,opentechinstitute/luci,joaofvieira/luci,Noltari/luci,rogerpueyo/luci,harveyhu2012/luci,obsy/luci,artynet/luci,openwrt-es/openwrt-luci,kuoruan/luci,palmettos/cnLuCI,dismantl/luci-0.12,Wedmer/luci,david-xiao/luci,lcf258/openwrtcn,shangjiyu/luci-with-extra,MinFu/luci,dismantl/luci-0.12,kuoruan/luci,lbthomsen/openwrt-luci,MinFu/luci,thesabbir/luci,harveyhu2012/luci,dwmw2/luci,opentechinstitute/luci,oyido/luci,taiha/luci,openwrt-es/openwrt-luci,palmettos/test,artynet/luci,cshore-firmware/openwrt-luci,tobiaswaldvogel/luci,db260179/openwrt-bpi-r1-luci,openwrt/luci,RuiChen1113/luci,RedSnake64/openwrt-luci-packages,Kyklas/luci-proto-hso,thess/OpenWrt-luci,nmav/luci,thesabbir/luci,ff94315/luci-1,nmav/luci,florian-shellfire/luci,aa65535/luci,tcatm/luci,florian-shellfire/luci,openwrt/luci,kuoruan/luci,nmav/luci,LazyZhu/openwrt-luci-trunk-mod,slayerrensky/luci,remakeelectric/luci,ReclaimYourPrivacy/cloak-luci,ff94315/luci-1,kuoruan/luci,tobiaswaldvogel/luci,Kyklas/luci-proto-hso,urueedi/luci,mumuqz/luci,Noltari/luci,thesabbir/luci,jorgifumi/luci,LazyZhu/openwrt-luci-trunk-mod,MinFu/luci,Sakura-Winkey/LuCI,urueedi/luci,harveyhu2012/luci,bright-things/ionic-luci,joaofvieira/luci,Hostle/openwrt-luci-multi-user,LazyZhu/openwrt-luci-trunk-mod,daofeng2015/luci,cappiewu/luci,tcatm/luci,kuoruan/lede-luci,urueedi/luci,thess/OpenWrt-luci,jlopenwrtluci/luci,thesabbir/luci,zhaoxx063/luci,jorgifumi/luci,cappiewu/luci,kuoruan/luci,cshore-firmware/openwrt-luci,thesabbir/luci,LuttyYang/luci,sujeet14108/luci,db260179/openwrt-bpi-r1-luci,chris5560/openwrt-luci,oyido/luci,RuiChen1113/luci,openwrt-es/openwrt-luci,ff94315/luci-1,jchuang1977/luci-1,sujeet14108/luci,rogerpueyo/luci,lbthomsen/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,harveyhu2012/luci,openwrt/luci,lbthomsen/openwrt-luci,chris5560/openwrt-luci,nwf/openwrt-luci,Sakura-Winkey/LuCI,cshore/luci,oyido/luci,cshore/luci,bittorf/luci,Hostle/luci,lcf258/openwrtcn,deepak78/new-luci,Hostle/openwrt-luci-multi-user,RedSnake64/openwrt-luci-packages,Kyklas/luci-proto-hso,rogerpueyo/luci,slayerrensky/luci,florian-shellfire/luci,ff94315/luci-1,remakeelectric/luci,ollie27/openwrt_luci,oneru/luci,obsy/luci,artynet/luci,MinFu/luci,fkooman/luci,cappiewu/luci,NeoRaider/luci,ollie27/openwrt_luci,ReclaimYourPrivacy/cloak-luci,tcatm/luci,schidler/ionic-luci,RedSnake64/openwrt-luci-packages,cappiewu/luci,keyidadi/luci,fkooman/luci,RuiChen1113/luci,RuiChen1113/luci,schidler/ionic-luci,obsy/luci,ReclaimYourPrivacy/cloak-luci,openwrt-es/openwrt-luci,schidler/ionic-luci,dwmw2/luci,openwrt/luci,cshore/luci,tobiaswaldvogel/luci,forward619/luci,thess/OpenWrt-luci,openwrt-es/openwrt-luci,lbthomsen/openwrt-luci,sujeet14108/luci,mumuqz/luci,daofeng2015/luci,keyidadi/luci,joaofvieira/luci,ollie27/openwrt_luci,rogerpueyo/luci,lcf258/openwrtcn,Sakura-Winkey/LuCI,david-xiao/luci,Noltari/luci,aa65535/luci,db260179/openwrt-bpi-r1-luci,schidler/ionic-luci,slayerrensky/luci,palmettos/test,keyidadi/luci,nmav/luci,oyido/luci,ReclaimYourPrivacy/cloak-luci,wongsyrone/luci-1,ff94315/luci-1,rogerpueyo/luci,bright-things/ionic-luci,keyidadi/luci,bittorf/luci,opentechinstitute/luci,fkooman/luci,slayerrensky/luci,lcf258/openwrtcn,hnyman/luci,981213/luci-1,nmav/luci,daofeng2015/luci,ff94315/luci-1,marcel-sch/luci,kuoruan/lede-luci,jlopenwrtluci/luci,kuoruan/luci,oyido/luci,lbthomsen/openwrt-luci,daofeng2015/luci,MinFu/luci,Wedmer/luci,wongsyrone/luci-1,mumuqz/luci,lcf258/openwrtcn,mumuqz/luci,slayerrensky/luci,mumuqz/luci,981213/luci-1,sujeet14108/luci,maxrio/luci981213,jlopenwrtluci/luci,Sakura-Winkey/LuCI,dismantl/luci-0.12,palmettos/cnLuCI,hnyman/luci,maxrio/luci981213,aircross/OpenWrt-Firefly-LuCI,cappiewu/luci,LazyZhu/openwrt-luci-trunk-mod,jorgifumi/luci,jorgifumi/luci,Hostle/openwrt-luci-multi-user,ollie27/openwrt_luci,NeoRaider/luci,wongsyrone/luci-1,sujeet14108/luci,tobiaswaldvogel/luci,cappiewu/luci,thess/OpenWrt-luci,harveyhu2012/luci,oneru/luci,schidler/ionic-luci,slayerrensky/luci,obsy/luci,jchuang1977/luci-1,artynet/luci,NeoRaider/luci,nwf/openwrt-luci,jchuang1977/luci-1,palmettos/cnLuCI,oyido/luci,teslamint/luci,remakeelectric/luci,Noltari/luci,ff94315/luci-1,david-xiao/luci,cshore/luci,aircross/OpenWrt-Firefly-LuCI,wongsyrone/luci-1,rogerpueyo/luci,Hostle/openwrt-luci-multi-user,RuiChen1113/luci,ollie27/openwrt_luci,schidler/ionic-luci,bright-things/ionic-luci,harveyhu2012/luci,Kyklas/luci-proto-hso,shangjiyu/luci-with-extra,nwf/openwrt-luci,shangjiyu/luci-with-extra,remakeelectric/luci,forward619/luci,NeoRaider/luci,Noltari/luci,cshore-firmware/openwrt-luci,teslamint/luci,lbthomsen/openwrt-luci,fkooman/luci,lcf258/openwrtcn,Wedmer/luci,Noltari/luci,teslamint/luci,chris5560/openwrt-luci,deepak78/new-luci,forward619/luci,taiha/luci,LazyZhu/openwrt-luci-trunk-mod,thess/OpenWrt-luci,teslamint/luci,maxrio/luci981213,nmav/luci,oyido/luci,Hostle/openwrt-luci-multi-user,tcatm/luci,fkooman/luci,chris5560/openwrt-luci,jorgifumi/luci,mumuqz/luci,marcel-sch/luci,kuoruan/lede-luci,lcf258/openwrtcn,dwmw2/luci,teslamint/luci,tcatm/luci,palmettos/cnLuCI,opentechinstitute/luci,bittorf/luci,bright-things/ionic-luci,dwmw2/luci,cshore-firmware/openwrt-luci,oyido/luci,nmav/luci,remakeelectric/luci,urueedi/luci,LazyZhu/openwrt-luci-trunk-mod,NeoRaider/luci,slayerrensky/luci,aa65535/luci,nmav/luci,wongsyrone/luci-1,nwf/openwrt-luci,shangjiyu/luci-with-extra,dwmw2/luci,joaofvieira/luci,hnyman/luci,shangjiyu/luci-with-extra,taiha/luci,tobiaswaldvogel/luci,teslamint/luci,maxrio/luci981213,male-puppies/luci,slayerrensky/luci,cshore-firmware/openwrt-luci,Sakura-Winkey/LuCI,obsy/luci,thesabbir/luci,cshore-firmware/openwrt-luci,daofeng2015/luci,deepak78/new-luci,cshore-firmware/openwrt-luci,shangjiyu/luci-with-extra,openwrt-es/openwrt-luci,kuoruan/lede-luci,male-puppies/luci,jlopenwrtluci/luci,Kyklas/luci-proto-hso,nwf/openwrt-luci,ReclaimYourPrivacy/cloak-luci,deepak78/new-luci,MinFu/luci,981213/luci-1,Wedmer/luci,schidler/ionic-luci,david-xiao/luci,bittorf/luci,obsy/luci,deepak78/new-luci,db260179/openwrt-bpi-r1-luci,marcel-sch/luci,harveyhu2012/luci,marcel-sch/luci,tobiaswaldvogel/luci,obsy/luci,florian-shellfire/luci,Wedmer/luci,thess/OpenWrt-luci,wongsyrone/luci-1,taiha/luci,aircross/OpenWrt-Firefly-LuCI,kuoruan/luci,oneru/luci,Sakura-Winkey/LuCI,cappiewu/luci,aa65535/luci,ollie27/openwrt_luci,ollie27/openwrt_luci,keyidadi/luci,db260179/openwrt-bpi-r1-luci,jchuang1977/luci-1,marcel-sch/luci,bittorf/luci,aa65535/luci,fkooman/luci,david-xiao/luci,daofeng2015/luci,RedSnake64/openwrt-luci-packages,981213/luci-1,oneru/luci,bittorf/luci,taiha/luci,zhaoxx063/luci,chris5560/openwrt-luci,bittorf/luci,RedSnake64/openwrt-luci-packages,daofeng2015/luci,kuoruan/lede-luci,sujeet14108/luci,NeoRaider/luci,jlopenwrtluci/luci,remakeelectric/luci,palmettos/test,dismantl/luci-0.12,zhaoxx063/luci,aa65535/luci,db260179/openwrt-bpi-r1-luci,joaofvieira/luci,urueedi/luci,cshore-firmware/openwrt-luci,Hostle/luci,LuttyYang/luci,openwrt-es/openwrt-luci,thesabbir/luci,teslamint/luci,maxrio/luci981213,joaofvieira/luci,joaofvieira/luci,palmettos/cnLuCI,maxrio/luci981213,aircross/OpenWrt-Firefly-LuCI
0251603f0aa064109138d40d06aa892f49e7abc7
modules/luci-mod-admin-full/luasrc/model/cbi/admin_system/admin.lua
modules/luci-mod-admin-full/luasrc/model/cbi/admin_system/admin.lua
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local fs = require "nixio.fs" m = Map("system", translate("Router Password"), translate("Changes the administrator password for accessing the device")) s = m:section(TypedSection, "_dummy", "") s.addremove = false s.anonymous = true pw1 = s:option(Value, "pw1", translate("Password")) pw1.password = true pw2 = s:option(Value, "pw2", translate("Confirmation")) pw2.password = true function s.cfgsections() return { "_pass" } end function m.parse(map) local v1 = pw1:formvalue("_pass") local v2 = pw2:formvalue("_pass") if v1 and v2 and #v1 > 0 and #v2 > 0 then if v1 == v2 then if luci.sys.user.setpasswd(luci.dispatcher.context.authuser, v1) == 0 then m.message = translate("Password successfully changed!") else m.message = translate("Unknown Error, password not changed!") end else m.message = translate("Given password confirmation did not match, password not changed!") end end Map.parse(map) end if fs.access("/etc/config/dropbear") then m2 = Map("dropbear", translate("SSH Access"), translate("Dropbear offers <abbr title=\"Secure Shell\">SSH</abbr> network shell access and an integrated <abbr title=\"Secure Copy\">SCP</abbr> server")) s = m2:section(TypedSection, "dropbear", translate("Dropbear Instance")) s.anonymous = true s.addremove = true ni = s:option(Value, "Interface", translate("Interface"), translate("Listen only on the given interface or, if unspecified, on all")) ni.template = "cbi/network_netlist" ni.nocreate = true ni.unspecified = true pt = s:option(Value, "Port", translate("Port"), translate("Specifies the listening port of this <em>Dropbear</em> instance")) pt.datatype = "port" pt.default = 22 pa = s:option(Flag, "PasswordAuth", translate("Password authentication"), translate("Allow <abbr title=\"Secure Shell\">SSH</abbr> password authentication")) pa.enabled = "on" pa.disabled = "off" pa.default = pa.enabled pa.rmempty = false ra = s:option(Flag, "RootPasswordAuth", translate("Allow root logins with password"), translate("Allow the <em>root</em> user to login with password")) ra.enabled = "on" ra.disabled = "off" ra.default = ra.enabled gp = s:option(Flag, "GatewayPorts", translate("Gateway ports"), translate("Allow remote hosts to connect to local SSH forwarded ports")) gp.enabled = "on" gp.disabled = "off" gp.default = gp.disabled s2 = m2:section(TypedSection, "_dummy", translate("SSH-Keys"), translate("Here you can paste public SSH-Keys (one per line) for SSH public-key authentication.")) s2.addremove = false s2.anonymous = true s2.template = "cbi/tblsection" function s2.cfgsections() return { "_keys" } end keys = s2:option(TextValue, "_data", "") keys.wrap = "off" keys.rows = 3 keys.rmempty = false function keys.cfgvalue() return fs.readfile("/etc/dropbear/authorized_keys") or "" end function keys.write(self, section, value) if value then fs.writefile("/etc/dropbear/authorized_keys", value:gsub("\r\n", "\n")) end end end return m, m2
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local fs = require "nixio.fs" m = Map("system", translate("Router Password"), translate("Changes the administrator password for accessing the device")) s = m:section(TypedSection, "_dummy", "") s.addremove = false s.anonymous = true pw1 = s:option(Value, "pw1", translate("Password")) pw1.password = true pw2 = s:option(Value, "pw2", translate("Confirmation")) pw2.password = true function s.cfgsections() return { "_pass" } end function m.parse(map) local v1 = pw1:formvalue("_pass") local v2 = pw2:formvalue("_pass") if v1 and v2 and #v1 > 0 and #v2 > 0 then if v1 == v2 then if luci.sys.user.setpasswd(luci.dispatcher.context.authuser, v1) == 0 then m.message = translate("Password successfully changed!") else m.message = translate("Unknown Error, password not changed!") end else m.message = translate("Given password confirmation did not match, password not changed!") end end Map.parse(map) end if fs.access("/etc/config/dropbear") then m2 = Map("dropbear", translate("SSH Access"), translate("Dropbear offers <abbr title=\"Secure Shell\">SSH</abbr> network shell access and an integrated <abbr title=\"Secure Copy\">SCP</abbr> server")) s = m2:section(TypedSection, "dropbear", translate("Dropbear Instance")) s.anonymous = true s.addremove = true ni = s:option(Value, "Interface", translate("Interface"), translate("Listen only on the given interface or, if unspecified, on all")) ni.template = "cbi/network_netlist" ni.nocreate = true ni.unspecified = true pt = s:option(Value, "Port", translate("Port"), translate("Specifies the listening port of this <em>Dropbear</em> instance")) pt.datatype = "port" pt.default = 22 pa = s:option(Flag, "PasswordAuth", translate("Password authentication"), translate("Allow <abbr title=\"Secure Shell\">SSH</abbr> password authentication")) pa.enabled = "on" pa.disabled = "off" pa.default = pa.enabled pa.rmempty = false ra = s:option(Flag, "RootPasswordAuth", translate("Allow root logins with password"), translate("Allow the <em>root</em> user to login with password")) ra.enabled = "on" ra.disabled = "off" ra.default = ra.enabled gp = s:option(Flag, "GatewayPorts", translate("Gateway ports"), translate("Allow remote hosts to connect to local SSH forwarded ports")) gp.enabled = "on" gp.disabled = "off" gp.default = gp.disabled s2 = m2:section(TypedSection, "_dummy", translate("SSH-Keys"), translate("Here you can paste public SSH-Keys (one per line) for SSH public-key authentication.")) s2.addremove = false s2.anonymous = true s2.template = "cbi/tblsection" function s2.cfgsections() return { "_keys" } end keys = s2:option(TextValue, "_data", "") keys.wrap = "off" keys.rows = 3 function keys.cfgvalue() return fs.readfile("/etc/dropbear/authorized_keys") or "" end function keys.write(self, section, value) return fs.writefile("/etc/dropbear/authorized_keys", value:gsub("\r\n", "\n")) end function keys.remove(self, section, value) return fs.writefile("/etc/dropbear/authorized_keys", "") end end return m, m2
luci-mod-admin-full: fix empty SSH-Keys issue
luci-mod-admin-full: fix empty SSH-Keys issue If you delete all ssh keys in the textarea then LuCI will rais an error. So if you added one ssh-key to the textarea and then you want to delete them again that is not possbile in LuCI. To fix this remove "rmempty" attribute and add a remove function which will called if the textarea is empty. Signed-off-by: Florian Eckert <ee3e4af9c48a69f5a5c47153eb4a777754bfbe6f@dev.tdt.de>
Lua
apache-2.0
kuoruan/luci,kuoruan/lede-luci,rogerpueyo/luci,hnyman/luci,chris5560/openwrt-luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,kuoruan/lede-luci,artynet/luci,artynet/luci,artynet/luci,Noltari/luci,Noltari/luci,openwrt/luci,rogerpueyo/luci,chris5560/openwrt-luci,lbthomsen/openwrt-luci,nmav/luci,rogerpueyo/luci,kuoruan/luci,lbthomsen/openwrt-luci,wongsyrone/luci-1,chris5560/openwrt-luci,artynet/luci,wongsyrone/luci-1,Noltari/luci,lbthomsen/openwrt-luci,kuoruan/luci,hnyman/luci,openwrt/luci,tobiaswaldvogel/luci,openwrt-es/openwrt-luci,Noltari/luci,tobiaswaldvogel/luci,kuoruan/luci,kuoruan/lede-luci,kuoruan/luci,openwrt/luci,openwrt-es/openwrt-luci,wongsyrone/luci-1,wongsyrone/luci-1,chris5560/openwrt-luci,artynet/luci,openwrt-es/openwrt-luci,openwrt/luci,lbthomsen/openwrt-luci,openwrt/luci,rogerpueyo/luci,wongsyrone/luci-1,openwrt/luci,openwrt/luci,rogerpueyo/luci,nmav/luci,nmav/luci,Noltari/luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,openwrt-es/openwrt-luci,Noltari/luci,rogerpueyo/luci,rogerpueyo/luci,lbthomsen/openwrt-luci,hnyman/luci,kuoruan/lede-luci,wongsyrone/luci-1,hnyman/luci,Noltari/luci,nmav/luci,kuoruan/lede-luci,openwrt-es/openwrt-luci,kuoruan/lede-luci,chris5560/openwrt-luci,tobiaswaldvogel/luci,artynet/luci,tobiaswaldvogel/luci,hnyman/luci,hnyman/luci,wongsyrone/luci-1,nmav/luci,tobiaswaldvogel/luci,artynet/luci,nmav/luci,hnyman/luci,wongsyrone/luci-1,chris5560/openwrt-luci,kuoruan/lede-luci,openwrt-es/openwrt-luci,artynet/luci,nmav/luci,Noltari/luci,tobiaswaldvogel/luci,openwrt-es/openwrt-luci,rogerpueyo/luci,artynet/luci,kuoruan/luci,openwrt/luci,lbthomsen/openwrt-luci,kuoruan/luci,chris5560/openwrt-luci,kuoruan/luci,kuoruan/lede-luci,hnyman/luci,Noltari/luci,nmav/luci,nmav/luci,chris5560/openwrt-luci,openwrt-es/openwrt-luci
5bda87845ff706cc16a54d4aa8a559ac48b069f8
lua_modules/yeelink/yeelink_lib.lua
lua_modules/yeelink/yeelink_lib.lua
-- *************************************************************************** -- Yeelink Updata Libiary -- -- Written by Martin -- but based on a script of zhouxu_o from bbs.nodemcu.com -- -- MIT license, http://opensource.org/licenses/MIT -- *************************************************************************** if wifi.sta.getip() == nil then print("Please Connect WIFI First") return nil end --==========================Module Part====================== local moduleName = ... local M = {} _G[moduleName] = M --=========================Local Args======================= local dns = "0.0.0.0" local device = "" local sensor = "" local apikey = "" --================================ local debug = true --<<<<<<<<<<<<< Don't forget to "false" it before using --================================ local sk=net.createConnection(net.TCP, 0) local datapoint = 0 --====DNS the yeelink ip advance(in order to save RAM)===== sk:dns("api.yeelink.net",function(conn,ip) dns=ip print("DNS YEELINK OK... IP: "..dns) end) --========Set the init function=========== --device->number --sensor->number -- apikey must be -> string <- -- e.g. xxx.init(00000,00000,"123j12b3jkb12k4b23bv54i2b5b3o4") --======================================== function M.init(_device, _sensor, _apikey) device = tostring(_device) sensor = tostring(_sensor) apikey = _apikey if dns == "0.0.0.0" then return false else return dns end end --=====Update to Yeelink Sever(At least 10s per sencods))===== -- datapoint->number -- --e.g. xxx.update(233.333) --============================================================ function M.update(_datapoint) datapoint = tostring(_datapoint) sk:on("connection", function(conn) print("connect OK...") local a=[[{"value":]] local b=[[}]] local st=a..datapoint..b sk:send("POST /v1.0/device/"..device.."/sensor/"..sensor.."/datapoints HTTP/1.1\r\n" .."Host: www.yeelink.net\r\n" .."Content-Length: "..string.len(st).."\r\n"--the length of json is important .."Content-Type: application/x-www-form-urlencoded\r\n" .."U-ApiKey:"..apikey.."\r\n" .."Cache-Control: no-cache\r\n\r\n" ..st.."\r\n" ) end) sk:on("receive", function(sck, content) if debug then print("\r\n"..content.."\r\n") else print("Date Receive") end end) sk:connect(80,dns) end --================end========================== return M
-- *************************************************************************** -- Yeelink Updata Libiary Version 0.1.2 -- -- Written by Martin -- but based on a script of zhouxu_o from bbs.nodemcu.com -- -- MIT license, http://opensource.org/licenses/MIT -- *************************************************************************** --==========================Module Part====================== local moduleName = ... local M = {} _G[moduleName] = M --=========================Local Args======================= local dns = "0.0.0.0" local device = "" local sensor = "" local apikey = "" --================================ local debug = true --<<<<<<<<<<<<< Don't forget to "false" it before using --================================ local sk=net.createConnection(net.TCP, 0) local datapoint = 0 --====DNS the yeelink ip advance(in order to save RAM)===== if wifi.sta.getip() == nil then print("Please Connect WIFI First") tmr.alarm(1,1000,1,function () if wifi.sta.getip() ~= nil then tmr.stop(1) sk:dns("api.yeelink.net",function(conn,ip) dns=ip print("DNS YEELINK OK... IP: "..dns) end) end end) end sk:dns("api.yeelink.net",function(conn,ip) dns=ip print("DNS YEELINK OK... IP: "..dns) end) --========Set the init function=========== --device->number --sensor->number -- apikey must be -> string <- -- e.g. xxx.init(00000,00000,"123j12b3jkb12k4b23bv54i2b5b3o4") --======================================== function M.init(_device, _sensor, _apikey) device = tostring(_device) sensor = tostring(_sensor) apikey = _apikey if dns == "0.0.0.0" then tmr.alarm(2,5000,1,function () if dns == "0.0.0.0" then print("Waiting for DNS...") end end) return false else return dns end end --========Check the DNS Status=========== --if DNS success, return the address(string) --if DNS fail(or processing), return nil -- -- --======================================== function M.getDNS() if dns == "0.0.0.0" then return nil else return dns end end --=====Update to Yeelink Sever(At least 10s per sencods))===== -- datapoint->number -- --e.g. xxx.update(233.333) --============================================================ function M.update(_datapoint) datapoint = tostring(_datapoint) sk:on("connection", function(conn) print("connect OK...") local a=[[{"value":]] local b=[[}]] local st=a..datapoint..b sk:send("POST /v1.0/device/"..device.."/sensor/"..sensor.."/datapoints HTTP/1.1\r\n" .."Host: www.yeelink.net\r\n" .."Content-Length: "..string.len(st).."\r\n"--the length of json is important .."Content-Type: application/x-www-form-urlencoded\r\n" .."U-ApiKey:"..apikey.."\r\n" .."Cache-Control: no-cache\r\n\r\n" ..st.."\r\n" ) end) sk:on("receive", function(sck, content) if debug then print("\r\n"..content.."\r\n") else print("Date Receive") end end) sk:connect(80,dns) end --================end========================== return M
Update to Ver0.1.2, fix logic bug
Update to Ver0.1.2, fix logic bug Detail: When require lib before connect to ap, program will return nil but the table.
Lua
mit
vsky279/nodemcu-firmware,radiojam11/nodemcu-firmware,flexiti/nodemcu-firmware,christakahashi/nodemcu-firmware,Alkorin/nodemcu-firmware,FelixPe/nodemcu-firmware,iotcafe/nodemcu-firmware,vowstar/nodemcu-firmware,dnc40085/nodemcu-firmware,daned33/nodemcu-firmware,zhujunsan/nodemcu-firmware,funshine/nodemcu-firmware,iotcafe/nodemcu-firmware,ciufciuf57/nodemcu-firmware,zerog2k/nodemcu-firmware,borromeotlhs/nodemcu-firmware,mikeller/nodemcu-firmware,ruisebastiao/nodemcu-firmware,weera00/nodemcu-firmware,oyooyo/nodemcu-firmware,cs8425/nodemcu-firmware,djphoenix/nodemcu-firmware,TerryE/nodemcu-firmware,SmartArduino/nodemcu-firmware,eku/nodemcu-firmware,daned33/nodemcu-firmware,nwf/nodemcu-firmware,shangwudong/MyNodeMcu,marktsai0316/nodemcu-firmware,TerryE/nodemcu-firmware,sowbug/nodemcu-firmware,luizfeliperj/nodemcu-firmware,natetrue/nodemcu-firmware,devsaurus/nodemcu-firmware,petrkr/nodemcu-firmware,zhujunsan/nodemcu-firmware,karrots/nodemcu-firmware,raburton/nodemcu-firmware,Alkorin/nodemcu-firmware,nwf/nodemcu-firmware,Alkorin/nodemcu-firmware,Andrew-Collins/nodemcu-firmware,ktosiu/nodemcu-firmware,christakahashi/nodemcu-firmware,TerryE/nodemcu-firmware,kbeckmann/nodemcu-firmware,jmattsson/nodemcu-firmware,vsky279/nodemcu-firmware,Kisaua/nodemcu-firmware,FrankX0/nodemcu-firmware,daned33/nodemcu-firmware,yurenyong123/nodemcu-firmware,mikeller/nodemcu-firmware,fetchbot/nodemcu-firmware,ktosiu/nodemcu-firmware,vowstar/nodemcu-firmware,dnc40085/nodemcu-firmware,remspoor/nodemcu-firmware,robertfoss/nodemcu-firmware,kbeckmann/nodemcu-firmware,radiojam11/nodemcu-firmware,christakahashi/nodemcu-firmware,ciufciuf57/nodemcu-firmware,yurenyong123/nodemcu-firmware,rickvanbodegraven/nodemcu-firmware,weera00/nodemcu-firmware,HEYAHONG/nodemcu-firmware,funshine/nodemcu-firmware,HEYAHONG/nodemcu-firmware,dscoolx6/MyESP8266,shangwudong/MyNodeMcu,xatanais/nodemcu-firmware,danronco/nodemcu-firmware,digitalloggers/nodemcu-firmware,petrkr/nodemcu-firmware,bogvak/nodemcu-firmware,devsaurus/nodemcu-firmware,karrots/nodemcu-firmware,oyooyo/nodemcu-firmware,Kisaua/nodemcu-firmware,robertfoss/nodemcu-firmware,natetrue/nodemcu-firmware,abgoyal/nodemcu-firmware,bhrt/nodeMCU,benwolfe/nodemcu-firmware,nodemcu/nodemcu-firmware,anusornc/nodemcu-firmware,marcelstoer/nodemcu-firmware,noahchense/nodemcu-firmware,dnc40085/nodemcu-firmware,FelixPe/nodemcu-firmware,FrankX0/nodemcu-firmware,danronco/nodemcu-firmware,nodemcu/nodemcu-firmware,Andrew-Collins/nodemcu-firmware,nodemcu/nodemcu-firmware,sowbug/nodemcu-firmware,zerog2k/nodemcu-firmware,makefu/nodemcu-firmware,HEYAHONG/nodemcu-firmware,djphoenix/nodemcu-firmware,abgoyal/nodemcu-firmware,Alkorin/nodemcu-firmware,remspoor/nodemcu-firmware,robertfoss/nodemcu-firmware,SmartArduino/nodemcu-firmware,klukonin/nodemcu-firmware,bogvak/nodemcu-firmware,ruisebastiao/nodemcu-firmware,romanchyla/nodemcu-firmware,benwolfe/nodemcu-firmware,petrkr/nodemcu-firmware,digitalloggers/nodemcu-firmware,klukonin/nodemcu-firmware,HEYAHONG/nodemcu-firmware,funshine/nodemcu-firmware,HEYAHONG/nodemcu-firmware,eku/nodemcu-firmware,petrkr/nodemcu-firmware,vsky279/nodemcu-firmware,cs8425/nodemcu-firmware,ruisebastiao/nodemcu-firmware,noahchense/nodemcu-firmware,vowstar/nodemcu-firmware,Alkorin/nodemcu-firmware,devsaurus/nodemcu-firmware,dscoolx6/MyESP8266,karrots/nodemcu-firmware,marktsai0316/nodemcu-firmware,makefu/nodemcu-firmware,xatanais/nodemcu-firmware,raburton/nodemcu-firmware,rickvanbodegraven/nodemcu-firmware,eku/nodemcu-firmware,remspoor/nodemcu-firmware,klukonin/nodemcu-firmware,nodemcu/nodemcu-firmware,anusornc/nodemcu-firmware,marcelstoer/nodemcu-firmware,dan-cleinmark/nodemcu-firmware,karrots/nodemcu-firmware,radiojam11/nodemcu-firmware,sowbug/nodemcu-firmware,anusornc/nodemcu-firmware,kbeckmann/nodemcu-firmware,djphoenix/nodemcu-firmware,zhujunsan/nodemcu-firmware,digitalloggers/nodemcu-firmware,funshine/nodemcu-firmware,TerryE/nodemcu-firmware,fetchbot/nodemcu-firmware,weera00/nodemcu-firmware,jmattsson/nodemcu-firmware,FrankX0/nodemcu-firmware,djphoenix/nodemcu-firmware,luizfeliperj/nodemcu-firmware,luizfeliperj/nodemcu-firmware,makefu/nodemcu-firmware,oyooyo/nodemcu-firmware,dan-cleinmark/nodemcu-firmware,shangwudong/MyNodeMcu,raburton/nodemcu-firmware,FelixPe/nodemcu-firmware,FrankX0/nodemcu-firmware,cs8425/nodemcu-firmware,zerog2k/nodemcu-firmware,christakahashi/nodemcu-firmware,marcelstoer/nodemcu-firmware,dnc40085/nodemcu-firmware,marktsai0316/nodemcu-firmware,yurenyong123/nodemcu-firmware,filug/nodemcu-firmware,TerryE/nodemcu-firmware,vsky279/nodemcu-firmware,filug/nodemcu-firmware,dnc40085/nodemcu-firmware,nodemcu/nodemcu-firmware,remspoor/nodemcu-firmware,ciufciuf57/nodemcu-firmware,dan-cleinmark/nodemcu-firmware,bogvak/nodemcu-firmware,borromeotlhs/nodemcu-firmware,marcelstoer/nodemcu-firmware,bhrt/nodeMCU,luizfeliperj/nodemcu-firmware,kbeckmann/nodemcu-firmware,eku/nodemcu-firmware,funshine/nodemcu-firmware,Audumla/audiot-nodemcu-firmware,FelixPe/nodemcu-firmware,vsky279/nodemcu-firmware,marcelstoer/nodemcu-firmware,dscoolx6/MyESP8266,shangwudong/MyNodeMcu,fetchbot/nodemcu-firmware,devsaurus/nodemcu-firmware,noahchense/nodemcu-firmware,Kisaua/nodemcu-firmware,abgoyal/nodemcu-firmware,fetchbot/nodemcu-firmware,nwf/nodemcu-firmware,romanchyla/nodemcu-firmware,remspoor/nodemcu-firmware,Audumla/audiot-nodemcu-firmware,FrankX0/nodemcu-firmware,mikeller/nodemcu-firmware,bhrt/nodeMCU,shangwudong/MyNodeMcu,iotcafe/nodemcu-firmware,christakahashi/nodemcu-firmware,benwolfe/nodemcu-firmware,filug/nodemcu-firmware,flexiti/nodemcu-firmware,oyooyo/nodemcu-firmware,kbeckmann/nodemcu-firmware,Audumla/audiot-nodemcu-firmware,bhrt/nodeMCU,flexiti/nodemcu-firmware,natetrue/nodemcu-firmware,SmartArduino/nodemcu-firmware,xatanais/nodemcu-firmware,jmattsson/nodemcu-firmware,petrkr/nodemcu-firmware,jmattsson/nodemcu-firmware,borromeotlhs/nodemcu-firmware,Andrew-Collins/nodemcu-firmware,nwf/nodemcu-firmware,danronco/nodemcu-firmware,karrots/nodemcu-firmware,rickvanbodegraven/nodemcu-firmware,bhrt/nodeMCU,ktosiu/nodemcu-firmware,nwf/nodemcu-firmware,jmattsson/nodemcu-firmware,romanchyla/nodemcu-firmware,FelixPe/nodemcu-firmware,devsaurus/nodemcu-firmware
402be3ff795a872da1f1a237924d2696c569bf5d
modules/admin-full/luasrc/model/cbi/admin_network/routes.lua
modules/admin-full/luasrc/model/cbi/admin_network/routes.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.tools.webadmin") m = Map("network", translate("Routes"), translate("a_n_routes1")) local routes6 = luci.sys.net.routes6() local bit = require "bit" s = m:section(TypedSection, "route", translate("Static IPv4 Routes")) s.addremove = true s.anonymous = true s.template = "cbi/tblsection" iface = s:option(ListValue, "interface", translate("Interface")) luci.tools.webadmin.cbi_add_networks(iface) s:option(Value, "target", translate("Target"), translate("Host-<abbr title=\"Internet Protocol Address\">IP</abbr> or Network")) s:option(Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask"), translate("if target is a network")).rmemepty = true s:option(Value, "gateway", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Gateway")) if routes6 then s = m:section(TypedSection, "route6", translate("Static IPv6 Routes")) s.addremove = true s.anonymous = true s.template = "cbi/tblsection" iface = s:option(ListValue, "interface", translate("Interface")) luci.tools.webadmin.cbi_add_networks(iface) s:option(Value, "target", translate("Target"), translate("<abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Address or Network (CIDR)")) s:option(Value, "gateway", translate("<abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Gateway")).rmempty = true end return m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.tools.webadmin") m = Map("network", translate("Routes"), translate("Routes specify over which interface and gateway a certain host or network " .. "can be reached.")) local routes6 = luci.sys.net.routes6() local bit = require "bit" s = m:section(TypedSection, "route", translate("Static IPv4 Routes")) s.addremove = true s.anonymous = true s.template = "cbi/tblsection" iface = s:option(ListValue, "interface", translate("Interface")) luci.tools.webadmin.cbi_add_networks(iface) s:option(Value, "target", translate("Target"), translate("Host-<abbr title=\"Internet Protocol Address\">IP</abbr> or Network")) s:option(Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask"), translate("if target is a network")).rmemepty = true s:option(Value, "gateway", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Gateway")) if routes6 then s = m:section(TypedSection, "route6", translate("Static IPv6 Routes")) s.addremove = true s.anonymous = true s.template = "cbi/tblsection" iface = s:option(ListValue, "interface", translate("Interface")) luci.tools.webadmin.cbi_add_networks(iface) s:option(Value, "target", translate("Target"), translate("<abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Address or Network (CIDR)")) s:option(Value, "gateway", translate("<abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Gateway")).rmempty = true end return m
modules/admin-full: fix static routes page
modules/admin-full: fix static routes page git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@5467 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
gwlim/luci,stephank/luci,Flexibity/luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,gwlim/luci,jschmidlapp/luci,Canaan-Creative/luci,phi-psi/luci,Canaan-Creative/luci,saraedum/luci-packages-old,dtaht/cerowrt-luci-3.3,phi-psi/luci,yeewang/openwrt-luci,freifunk-gluon/luci,freifunk-gluon/luci,8devices/carambola2-luci,stephank/luci,8devices/carambola2-luci,jschmidlapp/luci,saraedum/luci-packages-old,freifunk-gluon/luci,Flexibity/luci,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,yeewang/openwrt-luci,yeewang/openwrt-luci,jschmidlapp/luci,projectbismark/luci-bismark,Flexibity/luci,ch3n2k/luci,eugenesan/openwrt-luci,vhpham80/luci,ThingMesh/openwrt-luci,projectbismark/luci-bismark,zwhfly/openwrt-luci,yeewang/openwrt-luci,vhpham80/luci,vhpham80/luci,Flexibity/luci,projectbismark/luci-bismark,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,jschmidlapp/luci,freifunk-gluon/luci,Canaan-Creative/luci,Flexibity/luci,freifunk-gluon/luci,vhpham80/luci,gwlim/luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,jschmidlapp/luci,phi-psi/luci,eugenesan/openwrt-luci,ch3n2k/luci,projectbismark/luci-bismark,Canaan-Creative/luci,dtaht/cerowrt-luci-3.3,projectbismark/luci-bismark,ThingMesh/openwrt-luci,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,zwhfly/openwrt-luci,Canaan-Creative/luci,eugenesan/openwrt-luci,gwlim/luci,stephank/luci,gwlim/luci,zwhfly/openwrt-luci,freifunk-gluon/luci,gwlim/luci,8devices/carambola2-luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,8devices/carambola2-luci,jschmidlapp/luci,8devices/carambola2-luci,eugenesan/openwrt-luci,stephank/luci,projectbismark/luci-bismark,dtaht/cerowrt-luci-3.3,gwlim/luci,dtaht/cerowrt-luci-3.3,vhpham80/luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,jschmidlapp/luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,yeewang/openwrt-luci,8devices/carambola2-luci,ch3n2k/luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,stephank/luci,stephank/luci,saraedum/luci-packages-old,projectbismark/luci-bismark,Canaan-Creative/luci,ThingMesh/openwrt-luci,saraedum/luci-packages-old,vhpham80/luci,phi-psi/luci,eugenesan/openwrt-luci,ThingMesh/openwrt-luci,phi-psi/luci,phi-psi/luci,zwhfly/openwrt-luci,Flexibity/luci,zwhfly/openwrt-luci,jschmidlapp/luci,ch3n2k/luci,saraedum/luci-packages-old,Canaan-Creative/luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,zwhfly/openwrt-luci,dtaht/cerowrt-luci-3.3,dtaht/cerowrt-luci-3.3,ch3n2k/luci
c5623d15c02486659ca882477c003a05f03bcbe9
spec/unit/statics_spec.lua
spec/unit/statics_spec.lua
local spec_helper = require "spec.spec_helpers" local constants = require "kong.constants" local stringy = require "stringy" local IO = require "kong.tools.io" local fs = require "luarocks.fs" describe("Static files", function() describe("Constants", function() it("version set in constants should match the one in the rockspec", function() local rockspec_path for _, filename in ipairs(fs.list_dir(".")) do if stringy.endswith(filename, "rockspec") then rockspec_path = filename break end end if not rockspec_path then error("Can't find the rockspec file") end local file_content = IO.read_file(rockspec_path) local res = file_content:match("\"+[0-9.-]+[a-z]*[0-9-]*\"+") local extracted_version = res:sub(2, res:len() - 1) assert.are.same(constants.VERSION, extracted_version) end) end) describe("Configuration", function() it("should parse a correct configuration", function() local configuration = IO.read_file(spec_helper.DEFAULT_CONF_FILE) assert.are.same([[ # Available plugins on this server plugins_available: - keyauth - basicauth - ratelimiting - tcplog - udplog - filelog - request_transformer nginx_working_dir: /usr/local/kong/ proxy_port: 8000 admin_api_port: 8001 # Specify the DAO to use database: cassandra # Databases configuration databases_available: cassandra: properties: hosts: "localhost" port: 9042 timeout: 1000 keyspace: kong keepalive: 60000 # Sends anonymous error reports send_anonymous_reports: true nginx_plus_status: false # Cassandra cache configuration cache: expiration: 5 # in seconds nginx: | worker_processes auto; error_log logs/error.log info; daemon on; # Set "worker_rlimit_nofile" to a high value # worker_rlimit_nofile 65536; env KONG_CONF; events { # Set "worker_connections" to a high value worker_connections 1024; } http { resolver 8.8.8.8; charset UTF-8; access_log logs/access.log; access_log on; # Timeouts keepalive_timeout 60s; client_header_timeout 60s; client_body_timeout 60s; send_timeout 60s; # Proxy Settings proxy_buffer_size 128k; proxy_buffers 4 256k; proxy_busy_buffers_size 256k; proxy_ssl_server_name on; # IP Address real_ip_header X-Forwarded-For; set_real_ip_from 0.0.0.0/0; real_ip_recursive on; # Other Settings client_max_body_size 128m; underscores_in_headers on; reset_timedout_connection on; tcp_nopush on; ################################################ # The following code is required to run Kong # # Please be careful if you'd like to change it # ################################################ # Lua Settings lua_package_path ';;'; lua_code_cache on; lua_max_running_timers 4096; lua_max_pending_timers 16384; lua_shared_dict cache 512m; init_by_lua ' kong = require "kong" local status, err = pcall(kong.init) if not status then ngx.log(ngx.ERR, "Startup error: "..err) os.exit(1) end '; server { listen {{proxy_port}}; location / { default_type 'text/plain'; # This property will be used later by proxy_pass set $backend_url nil; # Authenticate the user and load the API info access_by_lua 'kong.exec_plugins_access()'; # Proxy the request proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass $backend_url; # Add additional response headers header_filter_by_lua 'kong.exec_plugins_header_filter()'; # Change the response body body_filter_by_lua 'kong.exec_plugins_body_filter()'; # Log the request log_by_lua 'kong.exec_plugins_log()'; } location /robots.txt { return 200 'User-agent: *\nDisallow: /'; } error_page 500 /500.html; location = /500.html { internal; content_by_lua ' local utils = require "kong.tools.utils" utils.show_error(ngx.status, "Oops, an unexpected error occurred!") '; } } server { listen {{admin_api_port}}; location / { default_type application/json; content_by_lua 'require("lapis").serve("kong.api.app")'; } location /robots.txt { return 200 'User-agent: *\nDisallow: /'; } # Do not remove, additional configuration placeholder for some plugins # {{additional_configuration}} } } ]], configuration) end) end) end)
local spec_helper = require "spec.spec_helpers" local constants = require "kong.constants" local stringy = require "stringy" local IO = require "kong.tools.io" local fs = require "luarocks.fs" describe("Static files", function() describe("Constants", function() it("version set in constants should match the one in the rockspec", function() local rockspec_path for _, filename in ipairs(fs.list_dir(".")) do if stringy.endswith(filename, "rockspec") then rockspec_path = filename break end end if not rockspec_path then error("Can't find the rockspec file") end local file_content = IO.read_file(rockspec_path) local res = file_content:match("\"+[0-9.-]+[a-z]*[0-9-]*\"+") local extracted_version = res:sub(2, res:len() - 1) assert.are.same(constants.VERSION, extracted_version) end) end) describe("Configuration", function() it("should parse a correct configuration", function() local configuration = IO.read_file(spec_helper.DEFAULT_CONF_FILE) assert.are.same([[ # Available plugins on this server plugins_available: - keyauth - basicauth - ratelimiting - tcplog - udplog - filelog - request_transformer nginx_working_dir: /usr/local/kong/ proxy_port: 8000 admin_api_port: 8001 # Specify the DAO to use database: cassandra # Databases configuration databases_available: cassandra: properties: hosts: "localhost" port: 9042 timeout: 1000 keyspace: kong keepalive: 60000 # Sends anonymous error reports send_anonymous_reports: true nginx_plus_status: false # Cassandra cache configuration cache: expiration: 5 # in seconds nginx: | worker_processes auto; error_log logs/error.log info; daemon on; # Set "worker_rlimit_nofile" to a high value # worker_rlimit_nofile 65536; env KONG_CONF; events { # Set "worker_connections" to a high value worker_connections 1024; } http { resolver 8.8.8.8; charset UTF-8; access_log logs/access.log; access_log on; # Timeouts keepalive_timeout 60s; client_header_timeout 60s; client_body_timeout 60s; send_timeout 60s; # Proxy Settings proxy_buffer_size 128k; proxy_buffers 4 256k; proxy_busy_buffers_size 256k; proxy_ssl_server_name on; # IP Address real_ip_header X-Forwarded-For; set_real_ip_from 0.0.0.0/0; real_ip_recursive on; # Other Settings client_max_body_size 128m; underscores_in_headers on; reset_timedout_connection on; tcp_nopush on; ################################################ # The following code is required to run Kong # # Please be careful if you'd like to change it # ################################################ # Lua Settings lua_package_path ';;'; lua_code_cache on; lua_max_running_timers 4096; lua_max_pending_timers 16384; lua_shared_dict cache 512m; lua_socket_log_errors off; init_by_lua ' kong = require "kong" local status, err = pcall(kong.init) if not status then ngx.log(ngx.ERR, "Startup error: "..err) os.exit(1) end '; server { listen {{proxy_port}}; location / { default_type 'text/plain'; # This property will be used later by proxy_pass set $backend_url nil; # Authenticate the user and load the API info access_by_lua 'kong.exec_plugins_access()'; # Proxy the request proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass $backend_url; # Add additional response headers header_filter_by_lua 'kong.exec_plugins_header_filter()'; # Change the response body body_filter_by_lua 'kong.exec_plugins_body_filter()'; # Log the request log_by_lua 'kong.exec_plugins_log()'; } location /robots.txt { return 200 'User-agent: *\nDisallow: /'; } error_page 500 /500.html; location = /500.html { internal; content_by_lua ' local utils = require "kong.tools.utils" utils.show_error(ngx.status, "Oops, an unexpected error occurred!") '; } } server { listen {{admin_api_port}}; location / { default_type application/json; content_by_lua 'require("lapis").serve("kong.api.app")'; } location /robots.txt { return 200 'User-agent: *\nDisallow: /'; } # Do not remove, additional configuration placeholder for some plugins # {{additional_configuration}} } } ]], configuration) end) end) end)
fix: config test broken by 48e69f29cef085
fix: config test broken by 48e69f29cef085
Lua
apache-2.0
beauli/kong,rafael/kong,ccyphers/kong,ind9/kong,salazar/kong,li-wl/kong,vzaramel/kong,Kong/kong,ind9/kong,streamdataio/kong,Kong/kong,jebenexer/kong,ejoncas/kong,akh00/kong,Mashape/kong,xvaara/kong,Kong/kong,ejoncas/kong,streamdataio/kong,icyxp/kong,vzaramel/kong,jerizm/kong,ajayk/kong,shiprabehera/kong,Vermeille/kong,kyroskoh/kong,rafael/kong,isdom/kong,smanolache/kong,kyroskoh/kong,isdom/kong
4694bedd696c9a33116751bf8915f300632ea30c
modules/admin-full/luasrc/model/cbi/admin_system/ipkg.lua
modules/admin-full/luasrc/model/cbi/admin_system/ipkg.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local ipkgfile = "/etc/opkg.conf" f = SimpleForm("ipkgconf", translate("a_s_p_ipkg")) t = f:field(TextValue, "lines") t.rows = 10 function t.cfgvalue() return luci.fs.readfile(ipkgfile) or "" end f:append(Template("admin_system/ipkg")) function f.handle(self, state, data) if state == FORM_VALID then if (luci.fs.readfile(ipkgfile) or "") ~= data.lines then luci.fs.writefile(ipkgfile, data.lines) end end return true end return f
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local ipkgfile = "/etc/opkg.conf" f = SimpleForm("ipkgconf", translate("a_s_p_ipkg")) t = f:field(TextValue, "lines") t.rows = 10 function t.cfgvalue() return luci.fs.readfile(ipkgfile) or "" end function t.write(self, section, data) return luci.fs.writefile(ipkgfile, data) end f:append(Template("admin_system/ipkg")) function f.handle(self, state, data) return true end return f
Fix saving of ipkg configuration file
Fix saving of ipkg configuration file
Lua
apache-2.0
tobiaswaldvogel/luci,aa65535/luci,thess/OpenWrt-luci,forward619/luci,deepak78/new-luci,aa65535/luci,harveyhu2012/luci,bittorf/luci,nwf/openwrt-luci,NeoRaider/luci,daofeng2015/luci,Sakura-Winkey/LuCI,cshore/luci,joaofvieira/luci,bright-things/ionic-luci,kuoruan/lede-luci,MinFu/luci,RedSnake64/openwrt-luci-packages,male-puppies/luci,cshore-firmware/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,obsy/luci,david-xiao/luci,ff94315/luci-1,thess/OpenWrt-luci,Wedmer/luci,fkooman/luci,nmav/luci,oneru/luci,tobiaswaldvogel/luci,joaofvieira/luci,florian-shellfire/luci,981213/luci-1,hnyman/luci,ReclaimYourPrivacy/cloak-luci,dwmw2/luci,bittorf/luci,sujeet14108/luci,oneru/luci,Wedmer/luci,florian-shellfire/luci,slayerrensky/luci,ff94315/luci-1,chris5560/openwrt-luci,shangjiyu/luci-with-extra,maxrio/luci981213,teslamint/luci,nmav/luci,openwrt/luci,openwrt-es/openwrt-luci,jorgifumi/luci,david-xiao/luci,jorgifumi/luci,deepak78/new-luci,marcel-sch/luci,opentechinstitute/luci,Sakura-Winkey/LuCI,palmettos/cnLuCI,Wedmer/luci,mumuqz/luci,oneru/luci,david-xiao/luci,thess/OpenWrt-luci,artynet/luci,david-xiao/luci,NeoRaider/luci,mumuqz/luci,lbthomsen/openwrt-luci,kuoruan/luci,wongsyrone/luci-1,kuoruan/luci,ollie27/openwrt_luci,cshore/luci,keyidadi/luci,dismantl/luci-0.12,daofeng2015/luci,schidler/ionic-luci,daofeng2015/luci,palmettos/test,dismantl/luci-0.12,joaofvieira/luci,urueedi/luci,fkooman/luci,maxrio/luci981213,taiha/luci,cappiewu/luci,cappiewu/luci,fkooman/luci,bright-things/ionic-luci,palmettos/cnLuCI,LazyZhu/openwrt-luci-trunk-mod,david-xiao/luci,rogerpueyo/luci,remakeelectric/luci,bittorf/luci,palmettos/cnLuCI,marcel-sch/luci,Sakura-Winkey/LuCI,taiha/luci,remakeelectric/luci,palmettos/test,tobiaswaldvogel/luci,keyidadi/luci,joaofvieira/luci,cshore/luci,keyidadi/luci,Sakura-Winkey/LuCI,MinFu/luci,aircross/OpenWrt-Firefly-LuCI,palmettos/cnLuCI,palmettos/test,deepak78/new-luci,oneru/luci,thess/OpenWrt-luci,jorgifumi/luci,deepak78/new-luci,MinFu/luci,forward619/luci,remakeelectric/luci,forward619/luci,thesabbir/luci,male-puppies/luci,zhaoxx063/luci,zhaoxx063/luci,slayerrensky/luci,urueedi/luci,maxrio/luci981213,florian-shellfire/luci,kuoruan/luci,hnyman/luci,NeoRaider/luci,Noltari/luci,lcf258/openwrtcn,bittorf/luci,jchuang1977/luci-1,opentechinstitute/luci,slayerrensky/luci,chris5560/openwrt-luci,dwmw2/luci,marcel-sch/luci,bright-things/ionic-luci,RuiChen1113/luci,kuoruan/lede-luci,jchuang1977/luci-1,cappiewu/luci,dwmw2/luci,schidler/ionic-luci,aa65535/luci,remakeelectric/luci,hnyman/luci,NeoRaider/luci,rogerpueyo/luci,cshore-firmware/openwrt-luci,oyido/luci,RuiChen1113/luci,jchuang1977/luci-1,mumuqz/luci,harveyhu2012/luci,lbthomsen/openwrt-luci,artynet/luci,hnyman/luci,jlopenwrtluci/luci,Hostle/luci,LazyZhu/openwrt-luci-trunk-mod,opentechinstitute/luci,RuiChen1113/luci,lbthomsen/openwrt-luci,rogerpueyo/luci,lcf258/openwrtcn,fkooman/luci,thess/OpenWrt-luci,cappiewu/luci,maxrio/luci981213,palmettos/test,Sakura-Winkey/LuCI,opentechinstitute/luci,cshore/luci,obsy/luci,openwrt/luci,bittorf/luci,Noltari/luci,Hostle/luci,jchuang1977/luci-1,obsy/luci,Wedmer/luci,jlopenwrtluci/luci,sujeet14108/luci,bittorf/luci,RedSnake64/openwrt-luci-packages,maxrio/luci981213,lcf258/openwrtcn,Wedmer/luci,nmav/luci,marcel-sch/luci,wongsyrone/luci-1,hnyman/luci,palmettos/test,teslamint/luci,wongsyrone/luci-1,chris5560/openwrt-luci,sujeet14108/luci,artynet/luci,openwrt/luci,Sakura-Winkey/LuCI,zhaoxx063/luci,deepak78/new-luci,jchuang1977/luci-1,Sakura-Winkey/LuCI,nwf/openwrt-luci,sujeet14108/luci,dwmw2/luci,cshore-firmware/openwrt-luci,marcel-sch/luci,RedSnake64/openwrt-luci-packages,mumuqz/luci,oneru/luci,bright-things/ionic-luci,tcatm/luci,lcf258/openwrtcn,teslamint/luci,joaofvieira/luci,palmettos/cnLuCI,schidler/ionic-luci,thesabbir/luci,florian-shellfire/luci,kuoruan/luci,oyido/luci,cshore-firmware/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,david-xiao/luci,oneru/luci,NeoRaider/luci,cshore/luci,ff94315/luci-1,obsy/luci,wongsyrone/luci-1,male-puppies/luci,MinFu/luci,slayerrensky/luci,openwrt-es/openwrt-luci,palmettos/cnLuCI,florian-shellfire/luci,ff94315/luci-1,RedSnake64/openwrt-luci-packages,aa65535/luci,openwrt-es/openwrt-luci,Hostle/openwrt-luci-multi-user,dwmw2/luci,oneru/luci,lbthomsen/openwrt-luci,981213/luci-1,zhaoxx063/luci,MinFu/luci,artynet/luci,joaofvieira/luci,cshore/luci,kuoruan/lede-luci,remakeelectric/luci,rogerpueyo/luci,slayerrensky/luci,RuiChen1113/luci,981213/luci-1,shangjiyu/luci-with-extra,LuttyYang/luci,jorgifumi/luci,palmettos/test,palmettos/test,Kyklas/luci-proto-hso,urueedi/luci,cappiewu/luci,tcatm/luci,daofeng2015/luci,db260179/openwrt-bpi-r1-luci,cappiewu/luci,db260179/openwrt-bpi-r1-luci,taiha/luci,ReclaimYourPrivacy/cloak-luci,marcel-sch/luci,MinFu/luci,lbthomsen/openwrt-luci,ollie27/openwrt_luci,chris5560/openwrt-luci,cappiewu/luci,ff94315/luci-1,NeoRaider/luci,obsy/luci,kuoruan/luci,shangjiyu/luci-with-extra,harveyhu2012/luci,schidler/ionic-luci,ReclaimYourPrivacy/cloak-luci,dismantl/luci-0.12,schidler/ionic-luci,db260179/openwrt-bpi-r1-luci,aircross/OpenWrt-Firefly-LuCI,forward619/luci,teslamint/luci,jorgifumi/luci,remakeelectric/luci,slayerrensky/luci,Wedmer/luci,kuoruan/lede-luci,dismantl/luci-0.12,981213/luci-1,fkooman/luci,jlopenwrtluci/luci,tobiaswaldvogel/luci,harveyhu2012/luci,dismantl/luci-0.12,schidler/ionic-luci,NeoRaider/luci,shangjiyu/luci-with-extra,marcel-sch/luci,Noltari/luci,fkooman/luci,kuoruan/luci,sujeet14108/luci,shangjiyu/luci-with-extra,LazyZhu/openwrt-luci-trunk-mod,aa65535/luci,teslamint/luci,db260179/openwrt-bpi-r1-luci,tobiaswaldvogel/luci,teslamint/luci,Hostle/openwrt-luci-multi-user,wongsyrone/luci-1,florian-shellfire/luci,slayerrensky/luci,ReclaimYourPrivacy/cloak-luci,keyidadi/luci,lcf258/openwrtcn,mumuqz/luci,Hostle/openwrt-luci-multi-user,obsy/luci,openwrt-es/openwrt-luci,artynet/luci,NeoRaider/luci,jorgifumi/luci,RuiChen1113/luci,artynet/luci,Wedmer/luci,florian-shellfire/luci,dwmw2/luci,palmettos/cnLuCI,obsy/luci,thesabbir/luci,chris5560/openwrt-luci,thesabbir/luci,Hostle/luci,deepak78/new-luci,tcatm/luci,Hostle/luci,remakeelectric/luci,MinFu/luci,LazyZhu/openwrt-luci-trunk-mod,LuttyYang/luci,Kyklas/luci-proto-hso,Kyklas/luci-proto-hso,mumuqz/luci,981213/luci-1,urueedi/luci,palmettos/test,lcf258/openwrtcn,RedSnake64/openwrt-luci-packages,oyido/luci,taiha/luci,Wedmer/luci,teslamint/luci,fkooman/luci,lcf258/openwrtcn,harveyhu2012/luci,remakeelectric/luci,chris5560/openwrt-luci,artynet/luci,openwrt-es/openwrt-luci,dismantl/luci-0.12,jorgifumi/luci,nmav/luci,dwmw2/luci,keyidadi/luci,bittorf/luci,Noltari/luci,jlopenwrtluci/luci,ff94315/luci-1,aa65535/luci,Sakura-Winkey/LuCI,db260179/openwrt-bpi-r1-luci,deepak78/new-luci,forward619/luci,fkooman/luci,bittorf/luci,LazyZhu/openwrt-luci-trunk-mod,oyido/luci,hnyman/luci,oyido/luci,opentechinstitute/luci,Hostle/openwrt-luci-multi-user,marcel-sch/luci,MinFu/luci,Kyklas/luci-proto-hso,keyidadi/luci,nwf/openwrt-luci,ollie27/openwrt_luci,zhaoxx063/luci,tobiaswaldvogel/luci,cshore-firmware/openwrt-luci,ff94315/luci-1,keyidadi/luci,bright-things/ionic-luci,maxrio/luci981213,tcatm/luci,hnyman/luci,lbthomsen/openwrt-luci,openwrt/luci,LuttyYang/luci,ReclaimYourPrivacy/cloak-luci,thesabbir/luci,opentechinstitute/luci,wongsyrone/luci-1,LuttyYang/luci,jchuang1977/luci-1,thess/OpenWrt-luci,harveyhu2012/luci,taiha/luci,nmav/luci,nwf/openwrt-luci,maxrio/luci981213,RedSnake64/openwrt-luci-packages,Hostle/openwrt-luci-multi-user,Hostle/luci,kuoruan/lede-luci,tcatm/luci,dismantl/luci-0.12,LuttyYang/luci,nwf/openwrt-luci,wongsyrone/luci-1,Hostle/openwrt-luci-multi-user,aircross/OpenWrt-Firefly-LuCI,oyido/luci,jlopenwrtluci/luci,shangjiyu/luci-with-extra,ReclaimYourPrivacy/cloak-luci,kuoruan/lede-luci,lcf258/openwrtcn,urueedi/luci,LuttyYang/luci,daofeng2015/luci,cshore/luci,jorgifumi/luci,cshore/luci,cshore-firmware/openwrt-luci,ollie27/openwrt_luci,nwf/openwrt-luci,kuoruan/luci,oyido/luci,jchuang1977/luci-1,joaofvieira/luci,openwrt-es/openwrt-luci,harveyhu2012/luci,db260179/openwrt-bpi-r1-luci,Noltari/luci,aircross/OpenWrt-Firefly-LuCI,nwf/openwrt-luci,tobiaswaldvogel/luci,shangjiyu/luci-with-extra,taiha/luci,daofeng2015/luci,nwf/openwrt-luci,RuiChen1113/luci,keyidadi/luci,RedSnake64/openwrt-luci-packages,obsy/luci,urueedi/luci,981213/luci-1,Kyklas/luci-proto-hso,chris5560/openwrt-luci,ollie27/openwrt_luci,openwrt/luci,forward619/luci,openwrt-es/openwrt-luci,lcf258/openwrtcn,aa65535/luci,Hostle/openwrt-luci-multi-user,daofeng2015/luci,artynet/luci,bright-things/ionic-luci,taiha/luci,kuoruan/luci,jchuang1977/luci-1,LazyZhu/openwrt-luci-trunk-mod,male-puppies/luci,schidler/ionic-luci,lcf258/openwrtcn,LazyZhu/openwrt-luci-trunk-mod,lbthomsen/openwrt-luci,opentechinstitute/luci,thess/OpenWrt-luci,cappiewu/luci,openwrt-es/openwrt-luci,schidler/ionic-luci,kuoruan/lede-luci,ReclaimYourPrivacy/cloak-luci,thesabbir/luci,david-xiao/luci,opentechinstitute/luci,male-puppies/luci,jlopenwrtluci/luci,oneru/luci,rogerpueyo/luci,ReclaimYourPrivacy/cloak-luci,zhaoxx063/luci,thess/OpenWrt-luci,hnyman/luci,rogerpueyo/luci,Hostle/openwrt-luci-multi-user,joaofvieira/luci,981213/luci-1,aa65535/luci,david-xiao/luci,nmav/luci,Noltari/luci,Noltari/luci,urueedi/luci,artynet/luci,nmav/luci,oyido/luci,nmav/luci,ollie27/openwrt_luci,forward619/luci,RuiChen1113/luci,forward619/luci,rogerpueyo/luci,cshore-firmware/openwrt-luci,LuttyYang/luci,dwmw2/luci,tcatm/luci,jlopenwrtluci/luci,maxrio/luci981213,thesabbir/luci,tcatm/luci,cshore-firmware/openwrt-luci,LuttyYang/luci,jlopenwrtluci/luci,sujeet14108/luci,male-puppies/luci,urueedi/luci,Hostle/luci,RuiChen1113/luci,sujeet14108/luci,mumuqz/luci,openwrt/luci,male-puppies/luci,bright-things/ionic-luci,aircross/OpenWrt-Firefly-LuCI,bright-things/ionic-luci,tobiaswaldvogel/luci,openwrt/luci,ollie27/openwrt_luci,shangjiyu/luci-with-extra,zhaoxx063/luci,Noltari/luci,taiha/luci,rogerpueyo/luci,mumuqz/luci,florian-shellfire/luci,chris5560/openwrt-luci,teslamint/luci,Noltari/luci,Kyklas/luci-proto-hso,openwrt/luci,slayerrensky/luci,male-puppies/luci,ollie27/openwrt_luci,Hostle/luci,sujeet14108/luci,kuoruan/lede-luci,db260179/openwrt-bpi-r1-luci,deepak78/new-luci,palmettos/cnLuCI,wongsyrone/luci-1,thesabbir/luci,zhaoxx063/luci,db260179/openwrt-bpi-r1-luci,aircross/OpenWrt-Firefly-LuCI,lbthomsen/openwrt-luci,daofeng2015/luci,ff94315/luci-1,Hostle/luci,Kyklas/luci-proto-hso,tcatm/luci,nmav/luci
8e08c191db57540e93bcca14bceea10864301a08
base/gems.lua
base/gems.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 M = {} M.DIAMOND = 1 M.EMERALD = 2 M.RUBY = 3 M.OBSIDIAN = 4 M.SAPPHIRE = 5 M.AMETHYST = 6 M.TOPAZ = 7 M.gemItemId = {} M.gemItemId[M.DIAMOND] = 3520 M.gemItemId[M.EMERALD] = 3523 M.gemItemId[M.RUBY] = 3521 M.gemItemId[M.OBSIDIAN] = 3524 M.gemItemId[M.SAPPHIRE] = 3522 M.gemItemId[M.AMETHYST] = 3519 M.gemItemId[M.TOPAZ] = 3525 local gemDataKey = {} gemDataKey[M.DIAMOND] = "magicalDiamond" gemDataKey[M.EMERALD] = "magicalEmerald" gemDataKey[M.RUBY] = "magicalRuby" gemDataKey[M.OBSIDIAN] = "magicalObsidian" gemDataKey[M.SAPPHIRE] = "magicalSapphire" gemDataKey[M.AMETHYST] = "magicalAmethyst" gemDataKey[M.TOPAZ] = "magicalTopaz" M.levelDataKey = "gemLevel" local gemPrefixDE = {"Latent", "Bedingt", "Leicht", "Mig", "Durchschnittlich", "Bemerkenswert", "Stark", "Sehr stark", "Unglaublich", "Einzigartig"} local gemPrefixEN = {"Latent", "Limited", "Slight", "Moderate", "Average", "Notable", "Strong", "Very Strong", "Unbelievable", "Unique"} local gemLevelRareness = {} gemLevelRareness[1] = ItemLookAt.uncommonItem gemLevelRareness[2] = ItemLookAt.uncommonItem gemLevelRareness[3] = ItemLookAt.uncommonItem gemLevelRareness[4] = ItemLookAt.rareItem gemLevelRareness[5] = ItemLookAt.rareItem gemLevelRareness[6] = ItemLookAt.rareItem gemLevelRareness[7] = ItemLookAt.epicItem gemLevelRareness[8] = ItemLookAt.epicItem gemLevelRareness[9] = ItemLookAt.epicItem gemLevelRareness[10] = ItemLookAt.epicItem local function extractNum(text) if text=="" then return 0 end return tonumber(text) end -- calculates the gem bonus and returns it in % function M.getGemBonus(item) local gemStrength = {} gemStrength[1]=extractNum(item:getData("magicalEmerald")) gemStrength[2]=extractNum(item:getData("magicalRuby")) gemStrength[3]=extractNum(item:getData("magicalTopaz")) gemStrength[4]=extractNum(item:getData("magicalAmethyst")) gemStrength[5]=extractNum(item:getData("magicalSapphire")) gemStrength[6]=extractNum(item:getData("magicalObsidian")) local gemSum=0 local gemMin=1000 -- arbitrarily high number for _, gStrength in pairs(gemStrength) do gemSum=gemSum+gStrength if gStrength<gemMin then gemMin=gStrength end end return gemSum+gemMin*6 end function M.lookAtFilter(user, lookAt, data) local gemLevel = data.gemLevel if gemLevel then if user:getPlayerLanguage() == 0 then lookAt.name = gemPrefixDE[gemLevel] .. " " .. lookAt.name else lookAt.name = gemPrefixEN[gemLevel] .. " " .. lookAt.name end lookAt.rareness = gemLevelRareness[gemLevel] end return lookAt end function M.itemIsMagicGem(item) if item ~= nil then for _, gemId in pairs(M.gemItemId) do if (item.id == gemId) then return true end end end return false end function M.getGemLevel(gem) local level = tonumber(gem:getData(M.levelDataKey)) if not level then level = 1 end return level end function M.getMagicGemId(gem, level) local level = level or 1 return M.gemItemId[gem] end function M.getMagicGemData(level) local level = level or 1 return {gemLevel = level} end function M.itemHasGems(item) return M.getGemBonus(item) > 0 end function M.returnGemsToUser(user, item, isMessage) local showMessage = isMessage or true if ( M.itemHasGems(item) == true ) then for i = 1, #gemDataKey do local itemKey = gemDataKey[i] local level = tonumber(item:getData(itemKey)) if level and level > 0 then common.CreateItem(user, M.gemItemId[i], 1, 999, {[M.levelDataKey] = level}) item:setData(itemKey, "") end end world:changeItem(item) if showMessage then user:inform("Alle Edelsteine wurden aus dem Gegenstand " .. world:getItemName( item.id, 0 ) .. " entfernt und dir zurckgegeben.", "All gems were removed from the item " .. world:getItemName( item.id, 1 ) .. " and returned to your inventory.") end end end function M.getDataKey(itemId) for i, gemId in pairs(M.gemItemId) do if itemId == gemId then return gemDataKey[i] end end return "nokey" 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 M = {} M.DIAMOND = 1 M.EMERALD = 2 M.RUBY = 3 M.OBSIDIAN = 4 M.SAPPHIRE = 5 M.AMETHYST = 6 M.TOPAZ = 7 M.gemItemId = {} M.gemItemId[M.DIAMOND] = 3520 M.gemItemId[M.EMERALD] = 3523 M.gemItemId[M.RUBY] = 3521 M.gemItemId[M.OBSIDIAN] = 3524 M.gemItemId[M.SAPPHIRE] = 3522 M.gemItemId[M.AMETHYST] = 3519 M.gemItemId[M.TOPAZ] = 3525 local gemDataKey = {} gemDataKey[M.DIAMOND] = "magicalDiamond" gemDataKey[M.EMERALD] = "magicalEmerald" gemDataKey[M.RUBY] = "magicalRuby" gemDataKey[M.OBSIDIAN] = "magicalObsidian" gemDataKey[M.SAPPHIRE] = "magicalSapphire" gemDataKey[M.AMETHYST] = "magicalAmethyst" gemDataKey[M.TOPAZ] = "magicalTopaz" M.levelDataKey = "gemLevel" local gemPrefixDE = {"Latent", "Bedingt", "Leicht", "Mig", "Durchschnittlich", "Bemerkenswert", "Stark", "Sehr stark", "Unglaublich", "Einzigartig"} local gemPrefixEN = {"Latent", "Limited", "Slight", "Moderate", "Average", "Notable", "Strong", "Very Strong", "Unbelievable", "Unique"} local gemLevelRareness = {} gemLevelRareness[1] = ItemLookAt.uncommonItem gemLevelRareness[2] = ItemLookAt.uncommonItem gemLevelRareness[3] = ItemLookAt.uncommonItem gemLevelRareness[4] = ItemLookAt.rareItem gemLevelRareness[5] = ItemLookAt.rareItem gemLevelRareness[6] = ItemLookAt.rareItem gemLevelRareness[7] = ItemLookAt.epicItem gemLevelRareness[8] = ItemLookAt.epicItem gemLevelRareness[9] = ItemLookAt.epicItem gemLevelRareness[10] = ItemLookAt.epicItem local function extractNum(text) if text=="" then return 0 end return tonumber(text) end -- calculates the gem bonus and returns it in % function M.getGemBonus(item) local gemStrength = {} gemStrength[1]=extractNum(item:getData("magicalEmerald")) gemStrength[2]=extractNum(item:getData("magicalRuby")) gemStrength[3]=extractNum(item:getData("magicalTopaz")) gemStrength[4]=extractNum(item:getData("magicalAmethyst")) gemStrength[5]=extractNum(item:getData("magicalSapphire")) gemStrength[6]=extractNum(item:getData("magicalObsidian")) local gemSum=0 local gemMin=1000 -- arbitrarily high number for _, gStrength in pairs(gemStrength) do gemSum=gemSum+gStrength if gStrength<gemMin then gemMin=gStrength end end return gemSum+gemMin*6 end function M.lookAtFilter(user, lookAt, data) local gemLevel = data.gemLevel if gemLevel then if user:getPlayerLanguage() == 0 then lookAt.name = gemPrefixDE[gemLevel] .. " " .. lookAt.name else lookAt.name = gemPrefixEN[gemLevel] .. " " .. lookAt.name end lookAt.rareness = gemLevelRareness[gemLevel] end return lookAt end function M.itemIsMagicGem(item) if item ~= nil then for _, gemId in pairs(M.gemItemId) do if (item.id == gemId) then return true end end end return false end function M.getGemLevel(gem) local level = tonumber(gem:getData(M.levelDataKey)) if not level then level = 1 end return level end function M.getMagicGemId(gem, level) return M.gemItemId[gem] end function M.getMagicGemData(level) level = level or 1 return {gemLevel = level} end function M.itemHasGems(item) return M.getGemBonus(item) > 0 end function M.returnGemsToUser(user, item, isMessage) local showMessage = isMessage or true if ( M.itemHasGems(item) == true ) then for i = 1, #gemDataKey do local itemKey = gemDataKey[i] local level = tonumber(item:getData(itemKey)) if level and level > 0 then common.CreateItem(user, M.gemItemId[i], 1, 999, {[M.levelDataKey] = level}) item:setData(itemKey, "") end end world:changeItem(item) if showMessage then user:inform("Alle Edelsteine wurden aus dem Gegenstand " .. world:getItemName( item.id, 0 ) .. " entfernt und dir zurckgegeben.", "All gems were removed from the item " .. world:getItemName( item.id, 1 ) .. " and returned to your inventory.") end end end function M.getDataKey(itemId) for i, gemId in pairs(M.gemItemId) do if itemId == gemId then return gemDataKey[i] end end return "nokey" end return M
Fix variables
Fix variables
Lua
agpl-3.0
Illarion-eV/Illarion-Content
980ebf8ddc96470c4080d78236d06bc6b9047e77
script/watchdog.lua
script/watchdog.lua
require "room" require "player" local function WatchDog() local self = { sid2room = {} } function self.gainRoom(tsid, sid) local room = self.sid2room[sid] if room == nil then room = GameRoom.new(tsid, sid) self.sid2room[sid] = room end return room end function self.dispatch(tsid, sid, uid, pname, data) local room = self.gainRoom(tsid, sid) local proto_name = string.format("%s%s", "proto.C2S", pname) local req = protobuf.decode(proto_name, data) local player = room.uid2player[uid] if not player then if pname == "Login" then player = Player:new(req.user) room.uid2player[uid] = player elseif pname ~= "Logout" then room:OnInvildProto(uid, pname) return end elseif pname == "Login" then print("relogin", uid) return end local method = string.format("On%s", pname) --print(string.format("%s%s%s", "---------", pname, "---------")) player.lastping = os.time() room[method](room, player, req) end function self.giftCb(op, tsid, uid, touid, gid, gcount, orderid) local sid = GiftMgr.orderid2req[orderid] if not sid then return end local room = self.gainRoom(tonumber(tsid, sid)) room:OnGiftCb(tonumber(op), tonumber(uid), tonumber(touid), tonumber(gid), tonumber(gcount), orderid) end return self end local watchdog = WatchDog() return watchdog
require "room" require "player" local function WatchDog() local self = { sid2room = {} } function self.gainRoom(tsid, sid) local room = self.sid2room[sid] if room == nil then room = GameRoom.new(tsid, sid) self.sid2room[sid] = room end return room end function self.dispatch(tsid, sid, uid, pname, data) local room = self.gainRoom(tsid, sid) local proto_name = string.format("%s%s", "proto.C2S", pname) local req = protobuf.decode(proto_name, data) local player = room.uid2player[uid] if not player then if pname == "Login" then player = Player:new(req.user) room.uid2player[uid] = player elseif pname ~= "Logout" then room:OnInvildProto(uid, pname) return end elseif pname == "Login" then print("relogin", uid) return end local method = string.format("On%s", pname) --print(string.format("%s%s%s", "---------", pname, "---------")) player.lastping = os.time() room[method](room, player, req) end function self.giftCb(op, tsid, uid, touid, gid, gcount, orderid) local req = GiftMgr.orderid2req[orderid] if not req or not req["sid"] then tprint("giftcb error", orderid) return end local room = self.gainRoom(tonumber(tsid), req["sid"]) room:OnGiftCb(tonumber(op), tonumber(uid), tonumber(touid), tonumber(gid), tonumber(gcount), orderid) end return self end local watchdog = WatchDog() return watchdog
fix giftcb bug
fix giftcb bug
Lua
apache-2.0
lsaint/act,lsaint/act,lsaint/act
2e825dd0b4a8f93249bce0b24bed9b7890ca4c57
lua/lodbc/luasql.lua
lua/lodbc/luasql.lua
local odbc = require "lodbc" luasql = (type(luasql) == 'table') and luasql or { _COPYRIGHT = "Copyright (C) 2006-2012 Kepler Project"; _DESCRIPTION = "LuaSQL is a simple interface from Lua to a DBMS"; _VERSION = "LuaSQL 2.2.1"; } local Environment = {__metatable = "LuaSQL: you're not allowed to get this metatable"} Environment.__index = Environment local Connection = {__metatable = "LuaSQL: you're not allowed to get this metatable"} Connection.__index = Connection local Cursor = {__metatable = "LuaSQL: you're not allowed to get this metatable"} Cursor.__index = Cursor function Environment_new() local env, err = odbc.environment() if not env then return nil, err end return setmetatable({private_={env = env}}, Environment) end function Environment:close() if not self.private_.env:destroyed() then return self.private_.env:destroy() end return false end function Environment:connect(...) local cnn, err = self.private_.env:connection() if not cnn then return nil, err end local ok ok, err = cnn:connect(...) if not ok then cnn:destroy() return nil, err end return Connection_new(cnn, self) end function Connection_new(cnn, env) assert(cnn) assert(cnn:environment() == env.private_.env) return setmetatable({private_={cnn = cnn;env=env}}, Connection) end function Connection:close() if not self.private_.cnn:destroyed() then return self.private_.cnn:destroy() end return false end function Connection:commit() return self.private_.cnn:commit() end function Connection:rollback() return self.private_.cnn:rollback() end function Connection:setautocommit(val) return self.private_.cnn:setautocommit(val) end function Connection:execute(sql) local stmt, err = self.private_.cnn:statement() if not stmt then return nil, err end local ok ok,err = stmt:execute(sql) if not ok then return nil, err end if stmt:closed() then stmt:destroy() return ok end return Cursor_new(stmt, self) end function Cursor_new(stmt, cnn) assert(stmt) assert(stmt:connection() == cnn.private_.cnn) stmt:setautoclose(true) return setmetatable({private_={stmt=stmt,cnn=cnn}}, Cursor) end function Cursor:close() if not self.private_.stmt:destroyed() then local ret = self.private_.stmt:closed() ret = self.private_.stmt:destroy() and (not ret) return ret end return false end function Cursor:fetch(...) return self.private_.stmt:fetch(...) end function Cursor:getcolnames() return self.private_.stmt:colnames() end function Cursor:getcoltypes() return self.private_.stmt:coltypes() end luasql.odbc = function() return Environment_new() end return luasql
local odbc = require "lodbc" luasql = (type(luasql) == 'table') and luasql or { _COPYRIGHT = "Copyright (C) 2006-2012 Kepler Project"; _DESCRIPTION = "LuaSQL is a simple interface from Lua to a DBMS"; _VERSION = "LuaSQL 2.2.1"; } local Environment = {__metatable = "LuaSQL: you're not allowed to get this metatable"} Environment.__index = Environment local Connection = {__metatable = "LuaSQL: you're not allowed to get this metatable"} Connection.__index = Connection local Cursor = {__metatable = "LuaSQL: you're not allowed to get this metatable"} Cursor.__index = Cursor local Environment_new, Connection_new, Cursor_new function Environment_new() local env, err = odbc.environment() if not env then return nil, err end return setmetatable({private_={env = env}}, Environment) end function Environment:close() if not self.private_.env:destroyed() then return self.private_.env:destroy() end return false end function Environment:connect(...) local cnn, err = self.private_.env:connection() if not cnn then return nil, err end local ok ok, err = cnn:connect(...) if not ok then cnn:destroy() return nil, err end return Connection_new(cnn, self) end function Connection_new(cnn, env) assert(cnn) assert(cnn:environment() == env.private_.env) return setmetatable({private_={cnn = cnn;env=env}}, Connection) end function Connection:close() if not self.private_.cnn:destroyed() then return self.private_.cnn:destroy() end return false end function Connection:commit() return self.private_.cnn:commit() end function Connection:rollback() return self.private_.cnn:rollback() end function Connection:setautocommit(val) return self.private_.cnn:setautocommit(val) end function Connection:execute(sql) local stmt, err = self.private_.cnn:statement() if not stmt then return nil, err end local ok ok,err = stmt:execute(sql) if not ok then return nil, err end if stmt:closed() then stmt:destroy() return ok end return Cursor_new(stmt, self) end function Cursor_new(stmt, cnn) assert(stmt) assert(stmt:connection() == cnn.private_.cnn) stmt:setautoclose(true) return setmetatable({private_={stmt=stmt,cnn=cnn}}, Cursor) end function Cursor:close() if not self.private_.stmt:destroyed() then local ret = self.private_.stmt:closed() ret = self.private_.stmt:destroy() and (not ret) return ret end return false end function Cursor:fetch(...) return self.private_.stmt:fetch(...) end function Cursor:getcolnames() return self.private_.stmt:colnames() end function Cursor:getcoltypes() return self.private_.stmt:coltypes() end luasql.odbc = function() return Environment_new() end return luasql
Fix. lodbc.luasql creates global functions
Fix. lodbc.luasql creates global functions
Lua
mit
moteus/lua-odbc,moteus/lua-odbc,moteus/lua-odbc
a28b21054707b80df39d11e6d28aa4ea3c0af76c
util.lua
util.lua
-- Define the sock_send/recv functions to use asynchronous actor sockets. -- if _G.sock_recv == nil and _G.sock_send == nil and _G.sock_send_recv == nil and _G.asock then function sock_recv(skt, pattern) return asock.recv(apo.self_address(), skt, pattern) end function sock_send(skt, data, from, to) return asock.send(apo.self_address(), skt, data, from, to) end function asock_send_recv(self_addr, skt, msg, recv_callback, pattern) local ok, err = asock.send(self_addr, skt, msg) if not ok then return ok, err end local rv, err = asock.recv(self_addr, skt, pattern or "*l") if rv and recv_callback then recv_callback(rv) end return rv, err end function sock_send_recv(skt, data, recv_callback, pattern) return asock_send_recv(apo.self_address(), skt, data, recv_callback, pattern) end end ---------------------------------------- function upstream_accept(self_addr, server_skt, sess_actor, env) local session_handler = function(upstream_skt) upstream_skt:settimeout(0) apo.spawn_name(sess_actor, "upstream_session", env, upstream_skt) end asock.loop_accept(self_addr, server_skt, session_handler) end ---------------------------------------- -- Parses "host:port" string. -- function host_port(str, default_port) local host = string.match(str, "//([^:/]+)") or string.match(str, "^([^:/]+)") if not host then return nil end local port = string.match(str, ":(%d+)") if port then port = tonumber(port) else port = default_port end return host, port end -- Create a client connection to a "host:port" location. -- function connect(location) local host, port = host_port(location, 11211) if not host then return nil end local sock, err = socket.connect(host, port) if not sock then return nil, nil, nil, err end sock:settimeout(0) return host, port, sock, nil end -- Helper function to close connections, like... -- -- c1, c2, c3 = close(c1, c2, c3) -- local function close(...) for i, skt in ipairs(arg) do skt:close() end return nil end -- Groups items in itr by the key returned by key_func(itr). -- function group_by(arr, key_func) local groups = {} for i = 1, #arr do local x = arr[i] local k = assert(key_func(x)) local g = groups[k] if g then table.insert(g, x) else groups[k] = { x } end end return groups end -- Returns an iterator function for an array. -- function array_iter(arr, start, step) if not start then start = 1 end if not step then step = 1 end local next = start return function() if not arr then return nil end local v = arr[next] next = next + step return v end end -- Returns an array from an iterator function. -- function iter_array(itr) local a = {} for v in itr do a[#a + 1] = v end return a end -- Trace a function with an optional name. -- -- CPS-style from http://lua-users.org. -- function trace(f, name) name = name or tostring(f) local helper = function(...) print("-" .. name) return ... end return function(...) print("+" .. name, ...) return helper(f(...)) end end function trace_table(t) for name, f in pairs(t) do if type(f) == 'function' then t[name] = trace(f, name) end end end ------------------------------------------------------ -- Run all functions that have a "TEST_" prefix. -- function TESTALL() for k, v in pairs(_G) do if string.match(k, "^TEST_") then print("- " .. k) v() end end print("TESTALL - done") end function TEST_array_iter() a = {1,2,3,4,5,6} x = array_iter(a) for i = 1, #a do assert(a[i] == x()) end assert(not x()) assert(not x()) x = array_iter(a, 4, 1) for i = 4, #a do assert(a[i] == x()) end assert(not x()) assert(not x()) assert(iter_array(array_iter({'a'}))[1] == 'a') assert(iter_array(array_iter({'a'}))[2] == nil) end function TEST_host_port() h, p = host_port("127.0.0.1:11211") assert(h == "127.0.0.1") assert(p == 11211) h, p = host_port("memcached://127.0.0.1:11211") assert(h == "127.0.0.1") assert(p == 11211) h, p = host_port("memcached://127.0.0.1", 443322) assert(h == "127.0.0.1") assert(p == 443322) h, p = host_port("memcached://127.0.0.1/foo", 443322) assert(h == "127.0.0.1") assert(p == 443322) end function TEST_group_by() gb = group_by({1, 2, 2, 3, 3, 3}, function(x) return x end) for k, v in pairs(gb) do -- print(k, #v, unpack(v)) assert(k == #v) end end
-- Define the sock_send/recv functions to use asynchronous actor sockets. -- if _G.sock_recv == nil and _G.sock_send == nil and _G.sock_send_recv == nil and _G.asock then function sock_recv(skt, pattern) return asock.recv(apo.self_address(), skt, pattern) end function sock_send(skt, data, from, to) return asock.send(apo.self_address(), skt, data, from, to) end function asock_send_recv(self_addr, skt, msg, recv_callback, pattern) local ok, err = asock.send(self_addr, skt, msg) if not ok then return ok, err end local rv, err = asock.recv(self_addr, skt, pattern or "*l") if rv and recv_callback then recv_callback(rv) end return rv, err end function sock_send_recv(skt, data, recv_callback, pattern) return asock_send_recv(apo.self_address(), skt, data, recv_callback, pattern) end end ---------------------------------------- function upstream_accept(self_addr, server_skt, sess_actor, env) local session_handler = function(upstream_skt) upstream_skt:settimeout(0) apo.spawn_name(sess_actor, "upstream_session", env, upstream_skt) end asock.loop_accept(self_addr, server_skt, session_handler) end ---------------------------------------- -- Parses "host:port" string. -- function host_port(str, default_port) local host = string.match(str, "//([^:/]+)") or string.match(str, "^([^:/]+)") if not host then return nil end local port = string.match(str, ":(%d+)") if port then port = tonumber(port) else port = default_port end return host, port end -- Create a client connection to a "host:port" location. -- function connect(location) local host, port = host_port(location, 11211) if not host then return nil end local sock, err = socket.connect(host, port) if not sock then return nil, nil, nil, err end sock:settimeout(0) return host, port, sock, nil end -- Helper function to close connections, like... -- -- c1, c2, c3 = close(c1, c2, c3) -- local function close(...) for i, skt in ipairs(arg) do skt:close() end return nil end -- Groups items in itr by the key returned by key_func(itr). -- function group_by(arr, key_func) local groups = {} for i = 1, #arr do local x = arr[i] local k = assert(key_func(x)) local g = groups[k] if g then table.insert(g, x) else groups[k] = { x } end end return groups end -- Returns an iterator function for an array. -- function array_iter(arr, start, step) if not start then start = 1 end if not step then step = 1 end local next = start return function() if not arr then return nil end local v = arr[next] next = next + step return v end end -- Returns an array from an iterator function. -- function iter_array(itr) local a = {} for v in itr do a[#a + 1] = v end return a end -- Trace a function with an optional name. -- -- CPS-style from http://lua-users.org. -- function trace(f, name) name = name or tostring(f) local helper = function(...) print("-" .. name, ...) return ... end return function(...) print("+" .. name, ...) return helper(f(...)) end end function trace_table(t, prefix) for name, f in pairs(t) do if type(f) == 'function' then local namex = name if prefix then namex = prefix .. '.' .. namex end t[name] = trace(f, namex) end end end ------------------------------------------------------ -- Run all functions that have a "TEST_" prefix. -- function TESTALL() for k, v in pairs(_G) do if string.match(k, "^TEST_") then print("- " .. k) v() end end print("TESTALL - done") end function TEST_array_iter() a = {1,2,3,4,5,6} x = array_iter(a) for i = 1, #a do assert(a[i] == x()) end assert(not x()) assert(not x()) x = array_iter(a, 4, 1) for i = 4, #a do assert(a[i] == x()) end assert(not x()) assert(not x()) assert(iter_array(array_iter({'a'}))[1] == 'a') assert(iter_array(array_iter({'a'}))[2] == nil) end function TEST_host_port() h, p = host_port("127.0.0.1:11211") assert(h == "127.0.0.1") assert(p == 11211) h, p = host_port("memcached://127.0.0.1:11211") assert(h == "127.0.0.1") assert(p == 11211) h, p = host_port("memcached://127.0.0.1", 443322) assert(h == "127.0.0.1") assert(p == 443322) h, p = host_port("memcached://127.0.0.1/foo", 443322) assert(h == "127.0.0.1") assert(p == 443322) end function TEST_group_by() gb = group_by({1, 2, 2, 3, 3, 3}, function(x) return x end) for k, v in pairs(gb) do -- print(k, #v, unpack(v)) assert(k == #v) end end
trace/trace_table improved with more info and optional prefix
trace/trace_table improved with more info and optional prefix
Lua
apache-2.0
steveyen/moxilua
4734b23481c19a33cb35d7645a7248770f644701
kong/plugins/aws-lambda/schema.lua
kong/plugins/aws-lambda/schema.lua
local typedefs = require "kong.db.schema.typedefs" local REGIONS = { "ap-northeast-1", "ap-northeast-2", "ap-south-1", "ap-southeast-1", "ap-southeast-2", "ca-central-1", "cn-north-1", "cn-northwest-1", "eu-central-1", "eu-west-1", "eu-west-2", "sa-east-1", "us-east-1", "us-east-2", "us-gov-west-1", "us-west-1", "us-west-2", } return { name = "aws-lambda", fields = { { run_on = typedefs.run_on_first }, { protocols = typedefs.protocols_http }, { config = { type = "record", fields = { { timeout = { type = "number", required = true, default = 60000, } }, { keepalive = { type = "number", required = true, default = 60000, } }, { aws_key = { type = "string", } }, { aws_secret = { type = "string", } }, { aws_region = { type = "string", required = true, one_of = REGIONS } }, { function_name = { type = "string", required = true, } }, { qualifier = { type = "string", } }, { invocation_type = { type = "string", required = true, default = "RequestResponse", one_of = { "RequestResponse", "Event", "DryRun" } } }, { log_type = { type = "string", required = true, default = "Tail", one_of = { "Tail", "None" } } }, { port = typedefs.port { default = 443 }, }, { unhandled_status = { type = "integer", between = { 100, 999 }, } }, { forward_request_method = { type = "boolean", default = false, } }, { forward_request_uri = { type = "boolean", default = false, } }, { forward_request_headers = { type = "boolean", default = false, } }, { forward_request_body = { type = "boolean", default = false, } }, { is_proxy_integration = { type = "boolean", default = false, } }, { awsgateway_compatible = { type = "boolean", default = false, } }, { proxy_scheme = { type = "string", one_of = { "http", "https" } } }, { proxy_url = typedefs.url }, { skip_large_bodies = { type = "boolean", default = true, } }, } }, } }, entity_checks = { { mutually_required = { "config.aws_key", "config.aws_secret" } }, { mutually_required = { "config.proxy_scheme", "config.proxy_url" } }, } }
local typedefs = require "kong.db.schema.typedefs" local REGIONS = { "ap-northeast-1", "ap-northeast-2", "ap-south-1", "ap-southeast-1", "ap-southeast-2", "ca-central-1", "cn-north-1", "cn-northwest-1", "eu-central-1", "eu-west-1", "eu-west-2", "sa-east-1", "us-east-1", "us-east-2", "us-gov-west-1", "us-west-1", "us-west-2", } return { name = "aws-lambda", fields = { { protocols = typedefs.protocols_http }, { config = { type = "record", fields = { { timeout = { type = "number", required = true, default = 60000, } }, { keepalive = { type = "number", required = true, default = 60000, } }, { aws_key = { type = "string", } }, { aws_secret = { type = "string", } }, { aws_region = { type = "string", required = true, one_of = REGIONS } }, { function_name = { type = "string", required = true, } }, { qualifier = { type = "string", } }, { invocation_type = { type = "string", required = true, default = "RequestResponse", one_of = { "RequestResponse", "Event", "DryRun" } } }, { log_type = { type = "string", required = true, default = "Tail", one_of = { "Tail", "None" } } }, { port = typedefs.port { default = 443 }, }, { unhandled_status = { type = "integer", between = { 100, 999 }, } }, { forward_request_method = { type = "boolean", default = false, } }, { forward_request_uri = { type = "boolean", default = false, } }, { forward_request_headers = { type = "boolean", default = false, } }, { forward_request_body = { type = "boolean", default = false, } }, { is_proxy_integration = { type = "boolean", default = false, } }, { awsgateway_compatible = { type = "boolean", default = false, } }, { proxy_scheme = { type = "string", one_of = { "http", "https" } } }, { proxy_url = typedefs.url }, { skip_large_bodies = { type = "boolean", default = true, } }, } }, } }, entity_checks = { { mutually_required = { "config.aws_key", "config.aws_secret" } }, { mutually_required = { "config.proxy_scheme", "config.proxy_url" } }, } }
fix(aws-lambda) remove the `run_on` field from plugin config schema (#11)
fix(aws-lambda) remove the `run_on` field from plugin config schema (#11) It is no longer needed as service mesh support is removed from Kong
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
aaf1e4c4b69e6e9ab1790bbc12db8f35395de046
scheduled/scs_skeleton_forest.lua
scheduled/scs_skeleton_forest.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/>. ]] -- Skeleton Forest -- Skeleton Spawn Script require("base.common") module("scheduled.scs_skeleton_forest", package.seeall) function ForestSkells() local Charakters = world:getPlayersInRangeOf(position(780,50,0),30); for i,Char in pairs(Charakters) do RndTry = math.random(1,2) if (RndTry == 1) then if SpawnSkeleton(Char) then return end elseif (RndTry == 2) then base.common.InformNLS(Char,"Du hrst ein leises Knacken im Unterholz und vielleicht ein leises Murmeln.","You hear a quiet cracking in the forest and maybe a muttering."); end end end function SpawnSkeleton(Charakter) local Monsters = world:getMonstersInRangeOf(Charakter.pos,7); if (table.getn(Monsters) > 0) then for i, Monster in Monsters do MonType = Monster:getMonsterType(); if ((MonType>110) and (MonType<121)) then -- Skeletons return false; end end end base.common.InformNLS(Charakter,"Um dich herum raschelt der Wald und du hrt das Klappern von Knochen.","Around you the forest rustles and you hear the clacking of bones."); SpawnSkeletonCycle(Charakter.pos,6,math.random(3,8)); return true; end function SpawnSkeletonCycle(CenterPos,Radius,Anzahl) local irad = math.ceil(Radius); local dim = 2*(irad+1); local x; local y; local map = {} ; local divid = math.ceil((2 * math.pi * irad) / Anzahl); for x = -irad-1, irad do map[x] = {}; for y = -irad-1, irad do map[x][y] = (x+0.5)*(x+0.5)+(y+0.5)*(y+0.5)-irad*irad > 0 end; end; local count = 0; for x = -irad, irad do for y = -irad, irad do if not( map[x][y] and map[x-1][y] and map[x][y-1] and map[x-1][y-1] ) and( map[x][y] or map[x-1][y] or map[x][y-1] or map[x-1][y-1] ) then count = count + 1; if (math.mod(count,divid) == 0) then tPos = position( CenterPos.x + x, CenterPos.y + y, CenterPos.z ) world:createMonster(math.random(111,115),tPos,-15); world:makeSound(5,tPos); end end; end; end; end
--[[ 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/>. ]] -- Skeleton Forest -- Skeleton Spawn Script require("base.common") module("scheduled.scs_skeleton_forest", package.seeall) function ForestSkells() local Charakters = world:getPlayersInRangeOf(position(780,50,0),30); for _,Char in pairs(Charakters) do RndTry = math.random(1,2) if (RndTry == 1) then if SpawnSkeleton(Char) then return end elseif (RndTry == 2) then base.common.InformNLS(Char,"Du hrst ein leises Knacken im Unterholz und vielleicht ein leises Murmeln.","You hear a quiet cracking in the forest and maybe a muttering."); end end end function SpawnSkeleton(Charakter) local Monsters = world:getMonstersInRangeOf(Charakter.pos,7); if (table.getn(Monsters) > 0) then for _, Monster in pairs(Monsters) do MonType = Monster:getMonsterType(); if ((MonType>110) and (MonType<121)) then -- Skeletons return false; end end end base.common.InformNLS(Charakter,"Um dich herum raschelt der Wald und du hrt das Klappern von Knochen.","Around you the forest rustles and you hear the clacking of bones."); SpawnSkeletonCycle(Charakter.pos,6,math.random(3,8)); return true; end function SpawnSkeletonCycle(CenterPos,Radius,Anzahl) local irad = math.ceil(Radius); local dim = 2*(irad+1); local x; local y; local map = {} ; local divid = math.ceil((2 * math.pi * irad) / Anzahl); for x = -irad-1, irad do map[x] = {}; for y = -irad-1, irad do map[x][y] = (x+0.5)*(x+0.5)+(y+0.5)*(y+0.5)-irad*irad > 0 end; end; local count = 0; for x = -irad, irad do for y = -irad, irad do if not( map[x][y] and map[x-1][y] and map[x][y-1] and map[x-1][y-1] ) and( map[x][y] or map[x-1][y] or map[x][y-1] or map[x-1][y-1] ) then count = count + 1; if (math.mod(count,divid) == 0) then tPos = position( CenterPos.x + x, CenterPos.y + y, CenterPos.z ) world:createMonster(math.random(111,115),tPos,-15); world:makeSound(5,tPos); end end; end; end; end
fix bug iterating a list
fix bug iterating a list
Lua
agpl-3.0
Illarion-eV/Illarion-Content,KayMD/Illarion-Content,LaFamiglia/Illarion-Content,Baylamon/Illarion-Content,vilarion/Illarion-Content
406da3d84d61228e42e96d876a8247046d5087c3
src/main/resources/moe/lymia/mppatch/data/patch/lib/mppatch_runtime.lua
src/main/resources/moe/lymia/mppatch/data/patch/lib/mppatch_runtime.lua
-- Copyright (c) 2015-2016 Lymia Alusyia <lymia@lymiahugs.com> -- -- 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. _mpPatch = {} _mpPatch._mt = {} setmetatable(_mpPatch, _mpPatch._mt) local patch = DB.GetMemoryUsage("216f0090-85dd-4061-8371-3d8ba2099a70") if not patch.__mppatch_marker then _mpPatch.enabled = false _mpPatch.canEnable = false function _mpPatch._mt.__index(_, k) error("Access to field "..k.." in MpPatch runtime without patch installed.") end return end _mpPatch.patch = patch _mpPatch.versionString = patch.version.versionString _mpPatch.context = "<init>" _mpPatch.uuid = "df74f698-2343-11e6-89c4-8fef6d8f889e" _mpPatch.enabled = ContentManager.IsActive(_mpPatch.uuid, ContentType.GAMEPLAY) _mpPatch.canEnable = true function _mpPatch.debugPrint(str) print(str) _mpPatch.patch.debugPrint(_mpPatch.fullPath..": "..str) end -- globals from patch local rawset = _mpPatch.patch.globals.rawset -- Metatable __index hooks local indexers = {} function _mpPatch._mt.__index(_, k) for _, fn in ipairs(indexers) do local v = fn(k) if v ~= nil then return v end end error("Access to unknown field "..k.." in MpPatch runtime.") end function _mpPatch._mt.registerIndexer(fn) table.insert(indexers, fn) end -- Metatable __newindex hooks local newIndexers = {} function _mpPatch._mt.__newindex(_, k, v) for _, fn in ipairs(newIndexers) do if fn(k, v) then return end end rawset(_mpPatch, k, v) end function _mpPatch._mt.registerNewIndexer(fn) table.insert(newIndexers, fn) end -- Lazy variables local lazyVals = {} _mpPatch._mt.registerIndexer(function(k) local fn = lazyVals[k] if fn then local v = fn() _mpPatch[k] = v return v end end) function _mpPatch._mt.registerLazyVal(k, fn) lazyVals[k] = fn end -- Properties local properties = {} _mpPatch._mt.registerIndexer(function(k) local p = properties[k] if p then return p.read() end end) _mpPatch._mt.registerNewIndexer(function(k, v) local p = properties[k] if p then if not p.write then error("write to immutable property "..k) end p.write(v) return true end end) function _mpPatch._mt.registerProperty(k, read, write) properties[k] = {read = read, write = write} end include "mppatch_utils.lua" include "mppatch_modutils.lua" include "mppatch_uiutils.lua" include "mppatch_debug.lua" _mpPatch.debugPrint("MPPatch runtime loaded") _mpPatch.context = _mpPatch.fullPath _mpPatch.debugPrint("Current UI path: ".._mpPatch.context)
-- Copyright (c) 2015-2016 Lymia Alusyia <lymia@lymiahugs.com> -- -- 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. _mpPatch = {} _mpPatch._mt = {} setmetatable(_mpPatch, _mpPatch._mt) local patch = DB.GetMemoryUsage("216f0090-85dd-4061-8371-3d8ba2099a70") if not patch.__mppatch_marker then _mpPatch.enabled = false _mpPatch.canEnable = false function _mpPatch._mt.__index(_, k) error("Access to field "..k.." in MpPatch runtime without patch installed.") end return end _mpPatch.patch = patch _mpPatch.versionString = patch.version.versionString _mpPatch.context = "<init>" _mpPatch.uuid = "df74f698-2343-11e6-89c4-8fef6d8f889e" _mpPatch.enabled = ContentManager.IsActive(_mpPatch.uuid, ContentType.GAMEPLAY) _mpPatch.canEnable = true function _mpPatch.debugPrint(...) local args = {...} local accum = "" local count = 0 for _, v in pairs(args) do if v > count then count = v end end for i=1,count do accum = accum .. args[i] if i ~= count then accum = accum .. "\t" end end print(accum) _mpPatch.patch.debugPrint(_mpPatch.fullPath..": "..accum) end -- globals from patch local rawset = _mpPatch.patch.globals.rawset -- Metatable __index hooks local indexers = {} function _mpPatch._mt.__index(_, k) for _, fn in ipairs(indexers) do local v = fn(k) if v ~= nil then return v end end error("Access to unknown field "..k.." in MpPatch runtime.") end function _mpPatch._mt.registerIndexer(fn) table.insert(indexers, fn) end -- Metatable __newindex hooks local newIndexers = {} function _mpPatch._mt.__newindex(_, k, v) for _, fn in ipairs(newIndexers) do if fn(k, v) then return end end rawset(_mpPatch, k, v) end function _mpPatch._mt.registerNewIndexer(fn) table.insert(newIndexers, fn) end -- Lazy variables local lazyVals = {} _mpPatch._mt.registerIndexer(function(k) local fn = lazyVals[k] if fn then local v = fn() _mpPatch[k] = v return v end end) function _mpPatch._mt.registerLazyVal(k, fn) lazyVals[k] = fn end -- Properties local properties = {} _mpPatch._mt.registerIndexer(function(k) local p = properties[k] if p then return p.read() end end) _mpPatch._mt.registerNewIndexer(function(k, v) local p = properties[k] if p then if not p.write then error("write to immutable property "..k) end p.write(v) return true end end) function _mpPatch._mt.registerProperty(k, read, write) properties[k] = {read = read, write = write} end include "mppatch_utils.lua" include "mppatch_modutils.lua" include "mppatch_uiutils.lua" include "mppatch_debug.lua" _mpPatch.debugPrint("MPPatch runtime loaded") _mpPatch.context = _mpPatch.fullPath _mpPatch.debugPrint("Current UI path: ".._mpPatch.context)
Fixed debugPrint for multiple fields.
Fixed debugPrint for multiple fields.
Lua
mit
Lymia/CivV_Mod2DLC,Lymia/MultiverseModManager,Lymia/MPPatch,Lymia/MPPatch,Lymia/MultiverseModManager,Lymia/MPPatch,Lymia/MPPatch
d14323f889aaa77cd758670dd887849599bd212f
test/test_Map.lua
test/test_Map.lua
local Map = require 'pud.level.Map' local MapNode = require 'pud.level.MapNode' local MapType = require 'pud.level.MapType' local Rect = require 'pud.kit.Rect' context('Map', function() context('When instantiating with no arguments', function() local map = Map() test('should exist', function() assert_not_nil(map) assert_true(map:is_a(Map)) end) test('should inherit Rect', function() assert_true(map:is_a(Rect)) end) test('should have correct coordinates', function() assert_equal(map:getX(), 0) assert_equal(map:getY(), 0) end) test('should have correct size', function() assert_equal(map:getWidth(), 0) assert_equal(map:getHeight(), 0) end) test('should not have any locations defined', function() assert_error(function() map:getLocation(0,0) end) assert_error(function() map:getLocation(1,1) end) assert_error(function() map:getLocation(-1,-1) end) assert_error(function() map:getLocation(1,0) end) assert_error(function() map:getLocation(0,1) end) assert_error(function() map:getLocation(10,11) end) assert_error(function() map:getLocation(-3,3) end) end) test('should have an empty __tostring', function() assert_equal(tostring(map), '') end) end) context('When instantiating with arguments', function() local map = Map(3, 15, 21, 50) test('should exist', function() assert_not_nil(map) assert_true(map:is_a(Map)) end) test('should inherit Rect', function() assert_true(map:is_a(Rect)) end) test('should have correct coordinates', function() assert_equal(map:getX(), 3) assert_equal(map:getY(), 15) end) test('should have correct size', function() assert_equal(map:getWidth(), 21) assert_equal(map:getHeight(), 50) end) test('should have empty locations within bounds', function() assert_equal(map:getLocation(1,1):getMapType(), MapType.empty) assert_equal(map:getLocation(10,11):getMapType(), MapType.empty) assert_equal(map:getLocation(map:getSize()):getMapType(), MapType.empty) end) test('should have no locations defined out of bounds', function() assert_error(function() map:getLocation(0,0) end) assert_error(function() map:getLocation(-1,-1) end) assert_error(function() map:getLocation(1,0) end) assert_error(function() map:getLocation(0,1) end) assert_error(function() map:getLocation(-3,3) end) end) test('should have a non-empty __tostring', function() assert_not_nil(tostring(map)) assert_not_equal(tostring(map), '') end) end) context('When setting values', function() local map = Map(0, 0, 20, 20) local node = MapNode(MapType.wall) node:setLit(true) context('for setLocation', function() test('should have correct values', function() map:setLocation(3, 8, node) local testNode = map:getLocation(3, 8) assert_not_nil(testNode) assert_equal(testNode:getMapType(), MapType.wall) end) test('should error on incorrect arguments', function() assert_error(function() map:setLocation() end) assert_error(function() map:setLocation(1) end) assert_error(function() map:setLocation(1, 1) end) assert_error(function() map:setLocation(0, 0, node) end) assert_error(function() map:setLocation('s', 's', 's') end) assert_error(function() map:setLocation(2, 2, {}) end) end) end) context('for setNodeMapType', function() test('should have correct values', function() map:setNodeMapType(map:getLocation(9, 19), MapType.floor) assert_equal(map:getLocation(9, 19):getMapType(), MapType.floor) end) test('should error on incorrect arguments', function() local node = MapNode() assert_error(function() map:setNodeMapType() end) assert_error(function() map:setNodeMapType(4) end) assert_error(function() map:setNodeMapType(MapType.floor) end) assert_error(function() map:setNodeMapType(node) end) assert_error(function() map:setNodeMapType(node, MapType.zzzz) end) end) end) end) end)
local Map = require 'pud.level.Map' local MapNode = require 'pud.level.MapNode' local MapType = require 'pud.level.MapType' local Rect = require 'pud.kit.Rect' context('Map', function() context('When instantiating with no arguments', function() local map = Map() test('should exist', function() assert_not_nil(map) assert_true(map:is_a(Map)) end) test('should inherit Rect', function() assert_true(map:is_a(Rect)) end) test('should have correct coordinates', function() assert_equal(map:getX(), 0) assert_equal(map:getY(), 0) end) test('should have correct size', function() assert_equal(map:getWidth(), 0) assert_equal(map:getHeight(), 0) end) test('should not have any locations defined', function() assert_error(function() map:getLocation(0,0) end) assert_error(function() map:getLocation(1,1) end) assert_error(function() map:getLocation(-1,-1) end) assert_error(function() map:getLocation(1,0) end) assert_error(function() map:getLocation(0,1) end) assert_error(function() map:getLocation(10,11) end) assert_error(function() map:getLocation(-3,3) end) end) test('should have an empty __tostring', function() assert_equal(tostring(map), '') end) end) context('When instantiating with arguments', function() local map = Map(3, 15, 21, 50) test('should exist', function() assert_not_nil(map) assert_true(map:is_a(Map)) end) test('should inherit Rect', function() assert_true(map:is_a(Rect)) end) test('should have correct coordinates', function() assert_equal(map:getX(), 3) assert_equal(map:getY(), 15) end) test('should have correct size', function() assert_equal(map:getWidth(), 21) assert_equal(map:getHeight(), 50) end) test('should have empty locations within bounds', function() assert_equal(map:getLocation(1,1):getMapType(), MapType.empty) assert_equal(map:getLocation(10,11):getMapType(), MapType.empty) assert_equal(map:getLocation(map:getSize()):getMapType(), MapType.empty) end) test('should have no locations defined out of bounds', function() assert_error(function() map:getLocation(0,0) end) assert_error(function() map:getLocation(-1,-1) end) assert_error(function() map:getLocation(1,0) end) assert_error(function() map:getLocation(0,1) end) assert_error(function() map:getLocation(-3,3) end) end) test('should have a correct __tostring', function() local map = Map(0, 0, 10, 10) local mapstr = '' for j=1,10 do for i=1,10 do local node = map:getLocation(i, j) local t = MapType.floor if i%2 == 0 then t = MapType.wall elseif j%2 == 0 then t = MapType.doorC end mapstr = mapstr .. t map:setLocation(i, j, map:setNodeMapType(node, t)) end mapstr = mapstr .. '\n' end assert_not_nil(tostring(map)) assert_equal(tostring(map), mapstr) end) end) context('When setting values', function() local map = Map(0, 0, 20, 20) local node = MapNode(MapType.wall) node:setLit(true) context('for setLocation', function() test('should have correct values', function() map:setLocation(3, 8, node) local testNode = map:getLocation(3, 8) assert_not_nil(testNode) assert_equal(testNode:getMapType(), MapType.wall) end) test('should error on incorrect arguments', function() assert_error(function() map:setLocation() end) assert_error(function() map:setLocation(1) end) assert_error(function() map:setLocation(1, 1) end) assert_error(function() map:setLocation(0, 0, node) end) assert_error(function() map:setLocation('s', 's', 's') end) assert_error(function() map:setLocation(2, 2, {}) end) end) end) context('for setNodeMapType', function() test('should have correct values', function() map:setNodeMapType(map:getLocation(9, 19), MapType.floor) assert_equal(map:getLocation(9, 19):getMapType(), MapType.floor) end) test('should error on incorrect arguments', function() local node = MapNode() assert_error(function() map:setNodeMapType() end) assert_error(function() map:setNodeMapType(4) end) assert_error(function() map:setNodeMapType(MapType.floor) end) assert_error(function() map:setNodeMapType(node) end) assert_error(function() map:setNodeMapType(node, MapType.zzzz) end) end) test('should return the given node', function() local node = MapNode(MapType.doorC) local node2 = map:setNodeMapType(node, MapType.floor) assert_equal(node:getMapType(), MapType.floor) assert_equal(node2:getMapType(), MapType.floor) assert_equal(node, node2) end) end) end) end)
fix Map tostring test
fix Map tostring test
Lua
mit
scottcs/wyx
74a94743d3b98daacb45fa8fc422a6ccec5a4522
share/lua/website/101greatgoals.lua
share/lua/website/101greatgoals.lua
-- libquvi-scripts -- Copyright (C) 2012 quvi project -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -- 02110-1301 USA -- -- Hundred and One Great Goals local HaOgg = {} -- Utility functions specific to this script -- Identify the script. function ident(self) package.path = self.script_dir .. '/?.lua' local C = require 'quvi/const' local r = {} r.domain = "101greatgoals%.com" r.formats = "default" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/gvideos/.+"}) return r end -- Query available formats. function query_formats(self) self.formats = 'default' return HaOgg.check_external_content(self) end -- Parse media URL. function parse(self) self.host_id = "101greatgoals" return HaOgg.check_external_content(self) end -- -- Utility functions -- function HaOgg.check_external_content(self) local p = quvi.fetch(self.page_url) local m = '<div .- id="space4para" class="post%-type%-gvideos">' ..'.-<script (.-)</script>' local a = p:match(m) or error("no match: article") -- Self-hosted, and they use YouTube -- http://www.101greatgoals.com/gvideos/golazo-wanchope-abila-sarmiento-junin-v-merlo-2/ if a:match('id="jwplayer%-1%-div"') then -- get the javascript chunk for jwplayer local U = require 'quvi/util' local s = p:match('"file":"(.-)"') or error('no match: file location') a = U.unescape(s):gsub("\\/", "/") end -- e.g. http://www.101greatgoals.com/gvideos/ea-sports-uefa-euro-2012-launch-trailer/ -- or -- http://www.101greatgoals.com/gvideos/golazo-wanchope-abila-sarmiento-junin-v-merlo-2/ local s = a:match('http://.*youtube.com/embed/([^/"]+)') or a:match('http://.*youtube.com/v/([^/"]+)') or a:match('http://.*youtube.com/watch%?v=([^/"]+)') or a:match('http://.*youtu%.be/([^/"]+)') if s then self.redirect_url = 'http://youtube.com/watch?v=' .. s return self end -- e.g. http://www.101greatgoals.com/gvideos/leicester-1-west-ham-2/ -- or -- http://www.101greatgoals.com/gvideos/golazo-alvaro-negredo-overhead-kick-puts-sevilla-1-0-up-at-getafe/ local s = a:match('http://.*dailymotion.com/embed/video/([^?"]+)') or a:match('http://.*dailymotion.com/swf/video/([^?"]+)') if s then self.redirect_url = 'http://dailymotion.com/video/' .. s return self end -- e.g. http://www.101greatgoals.com/gvideos/2-0-juventus-arturo-vidal-2-v-roma/ local s = a:match('http://.*videa.hu/flvplayer.swf%?v=([^?"]+)') if s then self.redirect_url = 'http://videa.hu/flvplayer.swf?v=' .. s return self end -- e.g. http://www.101greatgoals.com/gvideos/golazo-hulk-porto-v-benfica/ local s = a:match('http://.*sapo.pt/([^?"/]+)') if s then self.redirect_url = 'http://videos.sapo.pt/' .. s return self end -- FIXME rutube support missing -- e.g. http://www.101greatgoals.com/gvideos/allesandro-diamanti-bologna-1-0-golazo-v-cagliari-2/ local s = a:match('http://video.rutube.ru/([^?"]+)') if s then self.redirect_url = 'http://video.rutube.ru/' .. s return self end -- FIXME svt.se support missing -- e.g. http://www.101greatgoals.com/gvideos/gais-2-norrkoping-0/ local s = a:match('http://svt%.se/embededflash/(%d+)/play%.swf') if s then self.redirect_url = 'http://svt.se/embededflash/' .. s .. '/play.swf' return self end -- FIXME lamalla.tv support missing -- e.g. http://www.101greatgoals.com/gvideos/golazo-bakary-espanyol-b-vs-montanesa/ -- FIXME indavideo.hu support missing -- e.g. http://www.101greatgoals.com/gvideos/golazo-michel-bastos-lyon-v-psg-3/ -- FIXME xtsream.dk support missing -- e.g. http://www.101greatgoals.com/gvideos/golazo-the-ball-doesnt-hit-the-floor-viktor-claesson-elfsborg-v-fc-copenhagen-1-22-mins-in/ -- FIXME mslsoccer.com support missing -- e.g. http://www.101greatgoals.com/gvideos/thierry-henry-back-heel-assist-mehdi-ballouchy-v-montreal-impact/ error("FIXME: no support: Unable to determine the media host") end -- vim: set ts=4 sw=4 tw=72 expandtab:
-- libquvi-scripts -- Copyright (C) 2013 Toni Gundogdu <legatvs@gmail.com> -- Copyright (C) 2012 quvi project -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -- 02110-1301 USA -- -- Hundred and One Great Goals (aggregator) local HaOgg = {} -- Utility functions specific to this script -- Identify the script. function ident(self) package.path = self.script_dir .. '/?.lua' local C = require 'quvi/const' local r = {} r.domain = "101greatgoals%.com" r.formats = "default" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/gvideos/.+/$"}) return r end -- Query available formats. function query_formats(self) self.formats = 'default' return HaOgg.chk_ext_content(self) end -- Parse media URL. function parse(self) self.host_id = "101greatgoals" return HaOgg.chk_ext_content(self) end -- -- Utility functions -- function HaOgg.chk_self_hosted(p) -- -- Previously referred to as the "self-hosted" media, although according -- to the old notes, these were typically hosted by YouTube. -- http://is.gd/EKKPy2 -- -- 2013-05-05: The contents of the URL no longer seems to contain the -- "file" value, see chk_embedded for notes; keep this -- function around for now -- local d = p:match('%.setup%((.-)%)') if d then local s = d:match('"file":"(.-)"') or error('no match: file') if #s ==0 then error('empty media URL ("file")') end local U = require 'quvi/util' return (U.slash_unescape(U.unescape(s))) end end function HaOgg.chk_embedded(p) -- -- 2013-05-05: Most of the content appears to be embedded from elsewhere -- -- Instead of trying to check for each, parse the likely embedded source -- and pass it back to libquvi to find a media script that accepts the -- parsed (embedded) media URL. -- -- NOTE: This means that those media scripts must unwrangle the embedded -- media URLs passed from this script -- local s = p:match('class="post%-type%-gvideos">(.-)</') or p:match('id="jwplayer%-1">(.-)</>') or error('unable to determine embedded source') return s:match('value="(.-)"') or s:match('src="(.-)"') end function HaOgg.chk_ext_content(self) local p = quvi.fetch(self.page_url) self.redirect_url = HaOgg.chk_self_hosted(p) or HaOgg.chk_embedded(p) or error('unable to determine media source') return self end -- vim: set ts=4 sw=4 tw=72 expandtab:
FIX: website/101greatgoals.lua: embedded URL patterns
FIX: website/101greatgoals.lua: embedded URL patterns Improve the patterns used to parse the embedded media URLs. Do not attempt to check for the known hosts; leave the determination for libquvi(-scripts) to do. Signed-off-by: Toni Gundogdu <eac2284b3c43676907b96f08de9d3d52d5df0361@gmail.com>
Lua
agpl-3.0
legatvs/libquvi-scripts,legatvs/libquvi-scripts,alech/libquvi-scripts,alech/libquvi-scripts
0844c5bc198e452aa107c3dd15ffcda4d4c43ed1
premake/premake5.lua
premake/premake5.lua
solution "demboyz" basedir ".." location (_ACTION) targetdir "../bin" startproject "demboyz" configurations { "Debug", "Release" } platforms "x32" flags { "MultiProcessorCompile", "Symbols" } defines "_CRT_SECURE_NO_WARNINGS" configuration "Debug" defines { "DEBUG" } configuration "Release" defines { "NDEBUG" } optimize "Full" configuration {} -- GCC specific build options. configuration "gmake" -- Enables C++11 support. buildoptions { "-std=c++0x" } configuration {} project "demboyz" kind "ConsoleApp" language "C++" files { "../demboyz/**.h", "../demboyz/**.cpp" } includedirs { "../external/json_checker/include", "../external/cbase64-1.1/include", "../external/sourcesdk/include", "../external/rapidjson-1.0.2/include", "../external/snappy-1.1.3/include", "../demboyz" } links { "json_checker", "sourcesdk", "celt" } project "*" dofile "json_checker.lua" dofile "snappy.lua" dofile "sourcesdk.lua" dofile "celt.lua"
solution "demboyz" basedir ".." location (_ACTION) targetdir "../bin" startproject "demboyz" configurations { "Debug", "Release" } platforms "x32" flags { "MultiProcessorCompile", "Symbols" } defines "_CRT_SECURE_NO_WARNINGS" configuration "Debug" defines { "DEBUG" } configuration "Release" defines { "NDEBUG" } optimize "Full" configuration {} project "demboyz" kind "ConsoleApp" language "C++" configuration "gmake" -- Enables C++11 support. buildoptions { "-std=c++11" } configuration {} files { "../demboyz/**.h", "../demboyz/**.cpp" } includedirs { "../external/json_checker/include", "../external/cbase64-1.1/include", "../external/sourcesdk/include", "../external/rapidjson-1.0.2/include", "../external/snappy-1.1.3/include", "../demboyz" } links { "json_checker", "sourcesdk", "celt" } project "*" dofile "json_checker.lua" dofile "snappy.lua" dofile "sourcesdk.lua" dofile "celt.lua"
Fixed clang build of celt. Moved -std=c++11 to demboyz project scope.
Fixed clang build of celt. Moved -std=c++11 to demboyz project scope.
Lua
mit
SizzlingStats/demboyz,SizzlingStats/demboyz,SizzlingStats/demboyz
bc97b318134b7f394166cf3caa12a4615b6d0488
hash.lua
hash.lua
local ffi = require 'ffi' local tds = require 'tds.env' local elem = require 'tds.elem' local C = tds.C local hash = {} function hash.new() local self = C.tds_hash_new() if self == nil then error('unable to allocate hash') end self = ffi.cast('tds_hash&', self) ffi.gc(self, C.tds_hash_free) return self end local function findkey(self, lkey) local obj if type(lkey) == 'string' then obj = C.tds_hash_search_string(self, lkey, #lkey) elseif type(lkey) == 'number' then obj = C.tds_hash_search_number(self, lkey) else error('string or number key expected') end return obj end function hash:__newindex(lkey, lval) assert(self) local obj = findkey(self, lkey) if obj ~= nil then if lval then local val = C.tds_hash_object_value(obj) C.tds_elem_free_content(val) elem.set(val, lval) else C.tds_hash_remove(self, obj) C.tds_hash_object_free(obj) end else if lval then local obj = C.tds_hash_object_new() local key = C.tds_hash_object_key(obj) local val = C.tds_hash_object_value(obj) elem.set(val, lval) elem.set(key, lkey) C.tds_hash_insert(self, obj) end end end function hash:__index(lkey) assert(self) local obj = findkey(self, lkey) if obj ~= nil then local val = elem.get(C.tds_hash_object_value(obj)) return val else return rawget(hash, lkey) end end function hash:__len() assert(self) return tonumber(C.tds_hash_size(self)) end function hash:__pairs() assert(self) local iterator = C.tds_hash_iterator_new(self) ffi.gc(iterator, C.tds_hash_iterator_free) return function() local obj = C.tds_hash_iterator_next(iterator) if obj ~= nil then local key = elem.get(C.tds_hash_object_key(obj)) local val = elem.get(C.tds_hash_object_value(obj)) return key, val end end end hash.pairs = hash.__pairs ffi.metatype('tds_hash', hash) if pcall(require, 'torch') and torch.metatype then function hash:write(f) f:writeLong(self:__len()) for k,v in pairs(self) do f:writeObject(k) f:writeObject(v) end end function hash:read(f) local n = f:readLong() for i=1,n do local k = f:readObject() local v = f:readObject() self[k] = v end end local mt = debug.getmetatable(hash.new()) mt.__factory = hash.new mt.__version = 0 torch.metatype('tds_hash', mt) end -- table constructor local hash_ctr = {} setmetatable( hash_ctr, { __index = hash, __newindex = hash, __call = hash.new } ) tds.hash = hash_ctr return hash_ctr
local ffi = require 'ffi' local tds = require 'tds.env' local elem = require 'tds.elem' local C = tds.C local hash = {} function hash.__new() local self = C.tds_hash_new() if self == nil then error('unable to allocate hash') end self = ffi.cast('tds_hash&', self) ffi.gc(self, C.tds_hash_free) return self end local function findkey(self, lkey) local obj if type(lkey) == 'string' then obj = C.tds_hash_search_string(self, lkey, #lkey) elseif type(lkey) == 'number' then obj = C.tds_hash_search_number(self, lkey) else error('string or number key expected') end return obj end function hash:__newindex(lkey, lval) assert(self) local obj = findkey(self, lkey) if obj ~= nil then if lval then local val = C.tds_hash_object_value(obj) C.tds_elem_free_content(val) elem.set(val, lval) else C.tds_hash_remove(self, obj) C.tds_hash_object_free(obj) end else if lval then local obj = C.tds_hash_object_new() local key = C.tds_hash_object_key(obj) local val = C.tds_hash_object_value(obj) elem.set(val, lval) elem.set(key, lkey) C.tds_hash_insert(self, obj) end end end function hash:__index(lkey) assert(self) local obj = findkey(self, lkey) if obj ~= nil then local val = elem.get(C.tds_hash_object_value(obj)) return val else return rawget(hash, lkey) end end function hash:__len() assert(self) return tonumber(C.tds_hash_size(self)) end function hash:__pairs() assert(self) local iterator = C.tds_hash_iterator_new(self) ffi.gc(iterator, C.tds_hash_iterator_free) return function() local obj = C.tds_hash_iterator_next(iterator) if obj ~= nil then local key = elem.get(C.tds_hash_object_key(obj)) local val = elem.get(C.tds_hash_object_value(obj)) return key, val end end end hash.pairs = hash.__pairs ffi.metatype('tds_hash', hash) if pcall(require, 'torch') and torch.metatype then function hash:write(f) f:writeLong(self:__len()) for k,v in pairs(self) do f:writeObject(k) f:writeObject(v) end end function hash:read(f) local n = f:readLong() for i=1,n do local k = f:readObject() local v = f:readObject() self[k] = v end end hash.__factory = hash.__new hash.__version = 0 torch.metatype('tds_hash', hash, 'tds_hash&') end -- table constructor local hash_ctr = {} setmetatable( hash_ctr, { __index = hash, __newindex = hash, __call = hash.__new } ) tds.hash = hash_ctr return hash_ctr
hash: fix type handling with torch
hash: fix type handling with torch
Lua
bsd-3-clause
torch/tds,Moodstocks/tds,jakezhaojb/tds,jakezhaojb/tds,jakezhaojb/tds,jakezhaojb/tds
3d42eeb7e894423fd46d1d057f216bdbaa73f4ae
pud/ui/TextEntry.lua
pud/ui/TextEntry.lua
local Class = require 'lib.hump.class' local Text = getClass 'pud.ui.Text' local KeyboardEvent = getClass 'pud.event.KeyboardEvent' local string_len = string.len local string_sub = string.sub local format = string.format -- TextEntry -- A text frame that gathers keyboard input. local TextEntry = Class{name='TextEntry', inherits=Text, function(self, ...) Text.construct(self, ...) InputEvents:register(self, KeyboardEvent) end } -- destructor function TextEntry:destroy() self._isEnteringText = nil -- Frame will unregister all InputEvents Text.destroy(self) end -- override Frame:onRelease() function TextEntry:onRelease(button, mods, wasInside) if wasInside and 'l' == button then self._isEnteringText = not self._isEnteringText end if self._isEnteringText then self._curStyle = self._activeStyle or self._hoverStyle or self._normalStyle elseif self._hovered then self._curStyle = self._hoverStyle or self._normalStyle else self._curStyle = self._normalStyle end self:_drawFB() end -- override Frame:onHoverIn() function TextEntry:onHoverIn(x, y) if self._isEnteringText then return end Text.onHoverIn(self, x, y) end -- override TextEntry:onHoverOut() function TextEntry:onHoverOut(x, y) if self._isEnteringText then return end Text.onHoverOut(self, x, y) end -- capture text input if in editing mode function TextEntry:KeyboardEvent(e) if not self._isEnteringText then return end if self._text then local text local line = #self._text + 1 repeat line = line - 1 text = self._text[line] until string.len(text) ~= 0 or line < 1 if line < 1 then line = 1 end text = text or self._text[line] local key = e:getKey() switch(key) { backspace = function() text = string_sub(text, 1, -2) end, escape = function() self._isEnteringText = false self:onRelease() end, default = function() text = format('%s%s', text, e:getUnicode()) end, } self._text[line] = text self:_drawFB() else warning('Text is missing!') end end -- the class return TextEntry
local Class = require 'lib.hump.class' local Text = getClass 'pud.ui.Text' local KeyboardEvent = getClass 'pud.event.KeyboardEvent' local string_len = string.len local string_sub = string.sub local format = string.format -- TextEntry -- A text frame that gathers keyboard input. local TextEntry = Class{name='TextEntry', inherits=Text, function(self, ...) Text.construct(self, ...) InputEvents:register(self, KeyboardEvent) end } -- destructor function TextEntry:destroy() self._isEnteringText = nil -- Frame will unregister all InputEvents Text.destroy(self) end -- override Frame:onRelease() function TextEntry:onRelease(button, mods, wasInside) if wasInside and 'l' == button then self._isEnteringText = not self._isEnteringText end if self._isEnteringText then self._curStyle = self._activeStyle or self._hoverStyle or self._normalStyle elseif self._hovered then self._curStyle = self._hoverStyle or self._normalStyle else self._curStyle = self._normalStyle end self:_drawFB() end -- override Frame:onHoverIn() function TextEntry:onHoverIn(x, y) if self._isEnteringText then return end Text.onHoverIn(self, x, y) end -- override TextEntry:onHoverOut() function TextEntry:onHoverOut(x, y) if self._isEnteringText then return end Text.onHoverOut(self, x, y) end -- capture text input if in editing mode function TextEntry:KeyboardEvent(e) if not self._isEnteringText then return end if self._text then local text local line = #self._text + 1 repeat line = line - 1 text = self._text[line] until string.len(text) ~= 0 or line < 1 if line < 1 then line = 1 end text = text or self._text[line] local key = e:getKey() switch(key) { backspace = function() text = string_sub(text, 1, -2) end, escape = function() self._isEnteringText = false self:onRelease() end, default = function() local unicode = e:getUnicode() if unicode then text = format('%s%s', text, unicode) end end, } self._text[line] = text self:_drawFB() else warning('Text is missing!') end end -- the class return TextEntry
fix adding unicode when it's nil
fix adding unicode when it's nil
Lua
mit
scottcs/wyx
2b461a3ac1e6fa1a20ab7c818f848f5aecb27de5
src/pf/savefile.lua
src/pf/savefile.lua
module(...,package.seeall) local ffi = require("ffi") -- PCAP file format: http://wiki.wireshark.org/Development/LibpcapFileFormat/ ffi.cdef[[ struct pcap_file { /* file header */ uint32_t magic_number; /* magic number */ uint16_t version_major; /* major version number */ uint16_t version_minor; /* minor version number */ int32_t thiszone; /* GMT to local correction */ uint32_t sigfigs; /* accuracy of timestamps */ uint32_t snaplen; /* max length of captured packets, in octets */ uint32_t network; /* data link type */ }; struct pcap_record { /* record header */ uint32_t ts_sec; /* timestamp seconds */ uint32_t ts_usec; /* timestamp microseconds */ uint32_t incl_len; /* number of octets of packet saved in file */ uint32_t orig_len; /* actual length of packet */ }; struct pcap_record_extra { /* Extra metadata that we append to the pcap record, after the payload. */ uint32_t port_id; /* port the packet is captured on */ uint32_t flags; /* bit 0 set means input, bit 0 clear means output */ uint64_t reserved0, reserved1, reserved2, reserved3; }; ]] function write_file_header(file) local pcap_file = ffi.new("struct pcap_file") pcap_file.magic_number = 0xa1b2c3d4 pcap_file.version_major = 2 pcap_file.version_minor = 4 pcap_file.snaplen = 65535 pcap_file.network = 1 file:write(ffi.string(pcap_file, ffi.sizeof(pcap_file))) file:flush() end local pcap_extra = ffi.new("struct pcap_record_extra") ffi.fill(pcap_extra, ffi.sizeof(pcap_extra), 0) function write_record (file, ffi_buffer, length) write_record_header(file, length) file:write(ffi.string(ffi_buffer, length)) file:flush() end function write_record_header (file, length) local pcap_record = ffi.new("struct pcap_record") pcap_record.incl_len = length pcap_record.orig_len = length file:write(ffi.string(pcap_record, ffi.sizeof(pcap_record))) end -- Return an iterator for pcap records in FILENAME. function records (filename) local file = io.open(filename, "r") if file == nil then error("Unable to open file: " .. filename) end local pcap_file = readc(file, "struct pcap_file") if pcap_file.magic_number == 0xD4C3B2A1 then error("Endian mismatch in " .. filename) elseif pcap_file.magic_number ~= 0xA1B2C3D4 then error("Bad PCAP magic number in " .. filename) end local function pcap_records_it (t, i) local record = readc(file, "struct pcap_record") if record == nil then return nil end local datalen = math.min(record.orig_len, record.incl_len) local packet = file:read(datalen) local extra = nil if record.incl_len == #packet + ffi.sizeof("struct pcap_record_extra") then extra = readc(file, "struct pcap_record_extra") end return packet, record, extra end return pcap_records_it, true, true end -- Read a C object of TYPE from FILE. Return a pointer to the result. function readc(file, type) local string = file:read(ffi.sizeof(type)) if string == nil then return nil end if #string ~= ffi.sizeof(type) then error("short read of " .. type .. " from " .. tostring(file)) end return ffi.cast(type.."*", string) end
module(...,package.seeall) local ffi = require("ffi") -- PCAP file format: http://wiki.wireshark.org/Development/LibpcapFileFormat/ ffi.cdef[[ struct pcap_file { /* file header */ uint32_t magic_number; /* magic number */ uint16_t version_major; /* major version number */ uint16_t version_minor; /* minor version number */ int32_t thiszone; /* GMT to local correction */ uint32_t sigfigs; /* accuracy of timestamps */ uint32_t snaplen; /* max length of captured packets, in octets */ uint32_t network; /* data link type */ }; struct pcap_record { /* record header */ uint32_t ts_sec; /* timestamp seconds */ uint32_t ts_usec; /* timestamp microseconds */ uint32_t incl_len; /* number of octets of packet saved in file */ uint32_t orig_len; /* actual length of packet */ }; typedef struct pcap_record pcap_pkthdr_t; struct pcap_record_extra { /* Extra metadata that we append to the pcap record, after the payload. */ uint32_t port_id; /* port the packet is captured on */ uint32_t flags; /* bit 0 set means input, bit 0 clear means output */ uint64_t reserved0, reserved1, reserved2, reserved3; }; ]] function write_file_header(file) local pcap_file = ffi.new("struct pcap_file") pcap_file.magic_number = 0xa1b2c3d4 pcap_file.version_major = 2 pcap_file.version_minor = 4 pcap_file.snaplen = 65535 pcap_file.network = 1 file:write(ffi.string(pcap_file, ffi.sizeof(pcap_file))) file:flush() end local pcap_extra = ffi.new("struct pcap_record_extra") ffi.fill(pcap_extra, ffi.sizeof(pcap_extra), 0) function write_record (file, ffi_buffer, length) write_record_header(file, length) file:write(ffi.string(ffi_buffer, length)) file:flush() end function write_record_header (file, length) local pcap_record = ffi.new("struct pcap_record") pcap_record.incl_len = length pcap_record.orig_len = length file:write(ffi.string(pcap_record, ffi.sizeof(pcap_record))) end -- Return an iterator for pcap records in FILENAME. function records (filename) local file = io.open(filename, "r") if file == nil then error("Unable to open file: " .. filename) end local pcap_file = readc(file, "struct pcap_file") if pcap_file.magic_number == 0xD4C3B2A1 then error("Endian mismatch in " .. filename) elseif pcap_file.magic_number ~= 0xA1B2C3D4 then error("Bad PCAP magic number in " .. filename) end local function pcap_records_it (t, i) local record = readc(file, "struct pcap_record") if record == nil then return nil end local datalen = math.min(record.orig_len, record.incl_len) local packet = file:read(datalen) local extra = nil if record.incl_len == #packet + ffi.sizeof("struct pcap_record_extra") then extra = readc(file, "struct pcap_record_extra") end return packet, record, extra end return pcap_records_it, true, true end -- Read a C object of TYPE from FILE. Return a pointer to the result. function readc(file, type) local string = file:read(ffi.sizeof(type)) if string == nil then return nil end if #string ~= ffi.sizeof(type) then error("short read of " .. type .. " from " .. tostring(file)) end return ffi.cast(type.."*", string) end
Fix error related to types
Fix error related to types The last commit missed 'pcap_pkthdr_t'
Lua
apache-2.0
SnabbCo/pflua,mpeterv/pflua
cd114c746bb94864e84703c34751a7bdd4f34331
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
dimitarcl/premake-dev,dimitarcl/premake-dev,dimitarcl/premake-dev
424cf469adea51515ffee27076ba494ce54134e9
config/nvim/lua/file-icons.lua
config/nvim/lua/file-icons.lua
local colors = require("nightfox.colors").init() require "nvim-web-devicons".setup { override = { html = { icon = "", color = colors.pink_br, name = "html" }, css = { icon = "", color = colors.blue, name = "css" }, js = { icon = "", color = colors.yellow_dm, name = "js" }, ts = { icon = "ﯤ", color = colors.blue_br, name = "ts" }, kt = { icon = "󱈙", color = colors.orange, name = "kt" }, png = { icon = "", color = colors.dark_purple, name = "png" }, jpg = { icon = "", color = colors.dark_purple, name = "jpg" }, jpeg = { icon = "", color = "colors.dark_purple", name = "jpeg" }, mp3 = { icon = "", color = colors.white, name = "mp3" }, mp4 = { icon = "", color = colors.white, name = "mp4" }, out = { icon = "", color = colors.white, name = "out" }, Dockerfile = { icon = "", color = colors.cyan, name = "Dockerfile" }, rb = { icon = "", color = colors.red_dm, name = "rb" }, vue = { icon = "﵂", color = colors.green_br, name = "vue" }, py = { icon = "", color = colors.cyan, name = "py" }, toml = { icon = "", color = colors.blue, name = "toml" }, lock = { icon = "", color = colors.red, name = "lock" }, zip = { icon = "", color = colors.sun, name = "zip" }, xz = { icon = "", color = colors.sun, name = "xz" }, deb = { icon = "", color = colors.cyan, name = "deb" }, rpm = { icon = "", color = colors.orange, name = "rpm" } } }
local colors = require("nightfox.colors").init() require "nvim-web-devicons".setup { override = { html = { icon = "", color = colors.pink_br, name = "html" }, css = { icon = "", color = colors.blue, name = "css" }, js = { icon = "", color = colors.yellow_dm, name = "js" }, ts = { icon = "ﯤ", color = colors.blue_br, name = "ts" }, kt = { icon = "󱈙", color = colors.orange, name = "kt" }, png = { icon = "", color = colors.dark_purple, name = "png" }, jpg = { icon = "", color = colors.dark_purple, name = "jpg" }, jpeg = { icon = "", color = "colors.dark_purple", name = "jpeg" }, mp3 = { icon = "", color = colors.white, name = "mp3" }, mp4 = { icon = "", color = colors.white, name = "mp4" }, out = { icon = "", color = colors.white, name = "out" }, Dockerfile = { icon = "", color = colors.cyan, name = "Dockerfile" }, rb = { icon = "", color = colors.red_dm, name = "rb" }, vue = { icon = "﵂", color = colors.green_br, name = "vue" }, py = { icon = "", color = colors.cyan, name = "py" }, toml = { icon = "", color = colors.blue, name = "toml" }, lock = { icon = "", color = colors.red, name = "lock" }, zip = { icon = "", color = colors.sun, name = "zip" }, xz = { icon = "", color = colors.sun, name = "xz" }, deb = { icon = "", color = colors.cyan, name = "deb" }, rpm = { icon = "", color = colors.orange, name = "rpm" } } }
Fix icon colors
Fix icon colors
Lua
mit
lisinge/dotfiles,lisinge/dotfiles
3c1fe57b4c50786be51aee018cab620e531acf93
hammerspoon/hammerspoon.symlink/modules/monitor-monitor.lua
hammerspoon/hammerspoon.symlink/modules/monitor-monitor.lua
local window,screen=require'hs.window',require'hs.screen' local application,spaces=require'hs.application',require'hs.spaces' local drawing,canvas=require'hs.drawing',require'hs.canvas' local uielement=require'hs.uielement' local fnutils=require'hs.fnutils' -- local serial = require("hs._asm.serial") local lastScreenId = -1 -- local usePhysicalIndicator = false local useVirtualIndicator = true local currentIndicator = nil local indicatorBottomHeight = 2 local indicatorTopColor = drawing.color.asRGB({ red = 0.99, green = 0.76, blue = 0.25, alpha = 0.2 }) local indicatorBottomColor = drawing.color.asRGB({ red = 0.99, green = 0.76, blue = 0.25, alpha = 0.6 }) -- ----------------------------------------------------------------------------= Event Handlers =--= function handleMonitorMonitorChange() local focusedWindow = window.focusedWindow() if not focusedWindow then return end local screen = focusedWindow:screen() local screenId = screen:id() if useVirtualIndicator then updateVirtualScreenIndicator(screen, focusedWindow) end if screenId == lastScreenId then return end lastScreenId = screenId -- if usePhysicalIndicator then updatePhysicalScreenIndicator(screenId) end print('Display changed to ' .. screenId) end function handleGlobalAppEvent(name, event, app) if event == application.watcher.launched then watchApp(app) elseif event == application.watcher.terminated then -- Clean up local appWatcher = _monitorAppWatchers[app:pid()] if appWatcher then appWatcher.watcher:stop() for id, watcher in pairs(appWatcher.windows) do watcher:stop() end _monitorAppWatchers[app:pid()] = nil end elseif event == application.watcher.activated then handleMonitorMonitorChange() end end function handleAppEvent(element, event, watcher, info) if event == uielement.watcher.windowCreated then watchWindow(element) elseif event == uielement.watcher.focusedWindowChanged then if element:isWindow() or element:isApplication() then handleMonitorMonitorChange() end end end function handleWindowEvent(win, event, watcher, info) if event == uielement.watcher.elementDestroyed then watcher:stop() _monitorAppWatchers[info.pid].windows[info.id] = nil else handleMonitorMonitorChange() end end -- ------------------------------------------------------------------------= Virtual Indicators =--= -- Based heavily on https://git.io/v6kZN function updateVirtualScreenIndicator(screen, window) clearIndicator() local screeng = screen:fullFrame() local frame = window:frame() local left = frame.x local width = frame.w local menubarHeight = screen:frame().y - screeng.y - 1 local indicatorTopHeight = menubarHeight - indicatorBottomHeight indicator = canvas.new{ x = left, y = screeng.y, w = width, h = menubarHeight }:appendElements( { action = "fill", type = "rectangle", frame = { x = 0, y = 0, w = width, h = indicatorTopHeight }, fillColor = indicatorTopColor }, { action = "fill", type = "rectangle", frame = { x = 0, y = indicatorTopHeight, w = width, h = indicatorBottomHeight }, fillColor = indicatorBottomColor } ) indicator :level(canvas.windowLevels.cursor) :behavior(canvas.windowBehaviors.canJoinAllSpaces) :show() currentIndicator = indicator end function clearIndicator() if currentIndicator ~= nil then currentIndicator:delete() currentIndicator = nil end end -- -----------------------------------------------------------------------= Physical Indicators =--= -- function updatePhysicalScreenIndicator(screenId) -- local devicePath = getSerialOutputDevice() -- if devicePath == "" then return end -- port = serial.port(devicePath):baud(115200):open() -- if port:isOpen() then -- port:write("set " .. screenId .. "\n") -- port:flushBuffer() -- port:close() -- end -- end -- function getSerialOutputDevice() -- local command = "ioreg -c IOSerialBSDClient -r -t " .. -- "| awk 'f;/com_silabs_driver_CP210xVCPDriver/{f=1};/IOCalloutDevice/{exit}' " .. -- "| sed -n 's/.*\"\\(\\/dev\\/.*\\)\".*/\\1/p'" -- local handle = io.popen(command) -- local result = handle:read("*a") -- handle:close() -- -- Strip whitespace - https://www.rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail#Lua -- return result:match("^%s*(.-)%s*$") -- end -- ---------------------------------------------------------------------------= Watcher Helpers =--= -- from https://gist.github.com/cmsj/591624ef07124ad80a1c function attachExistingApps() local apps = application.runningApplications() apps = fnutils.filter(apps, function(app) return app:title() ~= "Hammerspoon" end) fnutils.each(apps, function(app) watchApp(app, true) end) end function watchApp(app, initializing) if _monitorAppWatchers[app:pid()] then return end local watcher = app:newWatcher(handleAppEvent) if not watcher.pid then return end _monitorAppWatchers[app:pid()] = { watcher = watcher, windows = {} } -- kind() returns -1 if the app is prohibited from GUI components if app:kind() == -1 then return end watcher:start({ uielement.watcher.focusedWindowChanged }) -- Watch any windows that already exist for i, window in pairs(app:allWindows()) do watchWindow(window, initializing) end end function watchWindow(win, initializing) local appWindows = _monitorAppWatchers[win:application():pid()].windows if win:isStandard() and not appWindows[win:id()] then local watcher = win:newWatcher(handleWindowEvent, { pid = win:pid(), id = win:id() }) appWindows[win:id()] = watcher watcher:start({ uielement.watcher.elementDestroyed, uielement.watcher.windowResized, uielement.watcher.windowMoved, uielement.watcher.windowMinimized, uielement.watcher.windowUnminimized }) end end -- ----------------------------------------------------------------------------------= Watchers =--= _monitorAppWatchers = {} attachExistingApps() _monitorScreenWatcher = screen.watcher.newWithActiveScreen(handleMonitorMonitorChange):start() _monitorSpaceWatcher = spaces.watcher.new(handleMonitorMonitorChange):start() _monitorAppWatcher = application.watcher.new(handleGlobalAppEvent):start() handleMonitorMonitorChange() -- set the initial screen -- Run this from the Hammerspoon console to get a listing of display IDs function listAllScreens () local primaryId = screen.primaryScreen():id() for _, screen in pairs(screen.allScreens()) do local screenId = screen:id() print( "id: " .. screenId .. " \"" .. screen:name() .. "\"" .. (screenId == primaryId and " (primary)" or "") ) end end
local window,screen=require'hs.window',require'hs.screen' local application,spaces=require'hs.application',require'hs.spaces' local drawing,canvas=require'hs.drawing',require'hs.canvas' local uielement=require'hs.uielement' local fnutils=require'hs.fnutils' -- local serial = require("hs._asm.serial") local lastScreenId = -1 -- local usePhysicalIndicator = false local useVirtualIndicator = true local currentIndicator = nil local indicatorBottomHeight = 2 local indicatorTopColor = drawing.color.asRGB({ red = 0.99, green = 0.76, blue = 0.25, alpha = 0.2 }) local indicatorBottomColor = drawing.color.asRGB({ red = 0.99, green = 0.76, blue = 0.25, alpha = 0.6 }) -- ----------------------------------------------------------------------------= Event Handlers =--= function handleMonitorMonitorChange() local focusedWindow = window.focusedWindow() if not focusedWindow then return end local screen = focusedWindow:screen() local screenId = screen:id() if useVirtualIndicator then updateVirtualScreenIndicator(screen, focusedWindow) end if screenId == lastScreenId then return end lastScreenId = screenId -- if usePhysicalIndicator then updatePhysicalScreenIndicator(screenId) end print('Display changed to ' .. screenId) end function handleGlobalAppEvent(name, event, app) if event == application.watcher.launched then watchApp(app) elseif event == application.watcher.terminated then -- Clean up local appWatcher = _monitorAppWatchers[app:pid()] if appWatcher then appWatcher.watcher:stop() for id, watcher in pairs(appWatcher.windows) do watcher:stop() end _monitorAppWatchers[app:pid()] = nil end elseif event == application.watcher.activated then handleMonitorMonitorChange() end end function handleAppEvent(element, event, watcher, info) if event == uielement.watcher.windowCreated then watchWindow(element) elseif event == uielement.watcher.focusedWindowChanged then if element:isWindow() or element:isApplication() then handleMonitorMonitorChange() end end end function handleWindowEvent(win, event, watcher, info) if event == uielement.watcher.elementDestroyed then watcher:stop() _monitorAppWatchers[info.pid].windows[info.id] = nil else handleMonitorMonitorChange() end end -- ------------------------------------------------------------------------= Virtual Indicators =--= -- Based heavily on https://git.io/v6kZN function updateVirtualScreenIndicator(screen, window) clearIndicator() local screeng = screen:fullFrame() local frame = window:frame() local left = frame.x local width = frame.w local menubarHeight = screen:frame().y - screeng.y - 1 local indicatorTopHeight = menubarHeight - indicatorBottomHeight indicator = canvas.new{ x = left, y = screeng.y, w = width, h = menubarHeight }:appendElements( { action = "fill", type = "rectangle", frame = { x = 0, y = 0, w = width, h = indicatorTopHeight }, fillColor = indicatorTopColor }, { action = "fill", type = "rectangle", frame = { x = 0, y = indicatorTopHeight, w = width, h = indicatorBottomHeight }, fillColor = indicatorBottomColor } ) indicator :level(canvas.windowLevels.cursor) :behavior(canvas.windowBehaviors.canJoinAllSpaces) :show() currentIndicator = indicator end function clearIndicator() if currentIndicator ~= nil then currentIndicator:delete() currentIndicator = nil end end -- -----------------------------------------------------------------------= Physical Indicators =--= -- function updatePhysicalScreenIndicator(screenId) -- local devicePath = getSerialOutputDevice() -- if devicePath == "" then return end -- port = serial.port(devicePath):baud(115200):open() -- if port:isOpen() then -- port:write("set " .. screenId .. "\n") -- port:flushBuffer() -- port:close() -- end -- end -- function getSerialOutputDevice() -- local command = "ioreg -c IOSerialBSDClient -r -t " .. -- "| awk 'f;/com_silabs_driver_CP210xVCPDriver/{f=1};/IOCalloutDevice/{exit}' " .. -- "| sed -n 's/.*\"\\(\\/dev\\/.*\\)\".*/\\1/p'" -- local handle = io.popen(command) -- local result = handle:read("*a") -- handle:close() -- -- Strip whitespace - https://www.rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail#Lua -- return result:match("^%s*(.-)%s*$") -- end -- ---------------------------------------------------------------------------= Watcher Helpers =--= -- from https://gist.github.com/cmsj/591624ef07124ad80a1c function attachExistingApps() local apps = application.runningApplications() apps = fnutils.filter(apps, function(app) return app:title() ~= "Hammerspoon" end) fnutils.each(apps, function(app) watchApp(app, true) end) end function watchApp(app, initializing) if _monitorAppWatchers[app:pid()] then return end local watcher = app:newWatcher(handleAppEvent) if not watcher.pid then return end _monitorAppWatchers[app:pid()] = { watcher = watcher, windows = {} } -- kind() returns -1 if the app is prohibited from GUI components if app:kind() == -1 then return end watcher:start({ uielement.watcher.focusedWindowChanged, uielement.watcher.mainWindowChanged }) -- Watch any windows that already exist for i, window in pairs(app:allWindows()) do watchWindow(window, initializing) end end function watchWindow(win, initializing) local appWindows = _monitorAppWatchers[win:application():pid()].windows if win:isStandard() and not appWindows[win:id()] then local watcher = win:newWatcher(handleWindowEvent, { pid = win:pid(), id = win:id() }) appWindows[win:id()] = watcher watcher:start({ uielement.watcher.elementDestroyed, uielement.watcher.windowCreated, uielement.watcher.windowMoved, uielement.watcher.windowResized, uielement.watcher.windowMinimized, uielement.watcher.windowUnminimized }) end end -- ----------------------------------------------------------------------------------= Watchers =--= _monitorAppWatchers = {} attachExistingApps() _monitorScreenWatcher = screen.watcher.newWithActiveScreen(handleMonitorMonitorChange):start() _monitorSpaceWatcher = spaces.watcher.new(handleMonitorMonitorChange):start() _monitorAppWatcher = application.watcher.new(handleGlobalAppEvent):start() handleMonitorMonitorChange() -- set the initial screen -- Run this from the Hammerspoon console to get a listing of display IDs function listAllScreens () local primaryId = screen.primaryScreen():id() for _, screen in pairs(screen.allScreens()) do local screenId = screen:id() print( "id: " .. screenId .. " \"" .. screen:name() .. "\"" .. (screenId == primaryId and " (primary)" or "") ) end end
fix(hammerspoon): monitor-monitor handle additional window eventing
fix(hammerspoon): monitor-monitor handle additional window eventing
Lua
mit
sethvoltz/dotfiles,sethvoltz/dotfiles,sethvoltz/dotfiles,sethvoltz/dotfiles
5b4dc7d667cea1734dad87d2c7278822b712743e
lua/dynamic.lua
lua/dynamic.lua
local _M = { _VERSION = "2.0.0" } local function check_throw(result, err) if not result then ngx.status = ngx.HTTP_BAD_REQUEST ngx.say(err) ngx.exit(ngx.HTTP_BAD_REQUEST) end return result end local function set_peer(upstream, peer, fun) check_throw(upstream and peer, "upstream and peer arguments required") fun(upstream, ngx.unescape_uri(peer)) end local function set_upstream(upstream_name, upstream_fun, fun) check_throw(upstream_name, "upstream argument required") local ok, peers, err = upstream_fun(upstream_name) check_throw(ok, err) lib.foreachi(peers, function(peer) fun(upstream_name, peer.name) end) end local function set_upstream_primary(mod, name, fun) set_upstream(name, mod.get_primary_peers, fun) end local function set_upstream_backup(mod, name, fun) set_upstream(name, mod.get_backup_peers, fun) end local function disable_peer(mod, b) return function(upstream, peer) return mod.disable_host(peer, b, upstream) end end local function disable(mod, b) return function(upstream) return mod.disable(upstream, b) end end local function disable_ip(mod, b) return function(ip) for u, groups in pairs(assert(mod.status())) do for peer, status in pairs(groups.primary) do if peer:match("^" .. ip) then mod.disable_host(peer, b, u) end end if groups.backup then for peer, status in pairs(groups.backup) do if peer:match("^" .. ip) then mod.disable_host(peer, b, u) end end end end end end local function make_mod(mod) return { enable_peer = function(upstream, peer) set_peer(upstream, peer, disable_peer(mod.healthcheck, false)) end, disable_peer = function(upstream, peer) set_peer(upstream, peer, disable_peer(mod.healthcheck, true)) end, enable_primary_peers = function(upstream) set_upstream_primary(mod.upstream, upstream, disable_peer(mod.healthcheck, false)) end, disable_primary_peers = function(upstream) set_upstream_primary(mod.upstream, upstream, disable_peer(mod.healthcheck, true)) end, enable_backup_peers = function(upstream) set_upstream_backup(mod.upstream, upstream, disable_peer(mod.healthcheck, false)) end, disable_backup_peers = function(upstream) set_upstream_backup(mod.upstream, upstream, disable_peer(mod.healthcheck, true)) end, enable_upstream = function(upstream) mod.healthcheck.disable(upstream, false) end, disable_upstream = function(upstream) mod.healthcheck.disable(upstream, true) end, enable_ip = disable_ip(mod.healthcheck, false), disable_ip = disable_ip(mod.healthcheck, true) } end _M.http = make_mod { healthcheck = require "ngx.healthcheck", upstream = require "ngx.dynamic_upstream" } _M.stream = make_mod { healthcheck = require "ngx.healthcheck.stream", upstream = require "ngx.dynamic_upstream.stream" } return _M
local _M = { _VERSION = "2.0.0" } local function check_throw(result, err) if not result then ngx.status = ngx.HTTP_BAD_REQUEST ngx.say(err) ngx.exit(ngx.HTTP_BAD_REQUEST) end return result end local function set_peer(upstream, peer, fun) check_throw(upstream and peer, "upstream and peer arguments required") fun(upstream, ngx.unescape_uri(peer)) end local function set_upstream(upstream_name, upstream_fun, fun) check_throw(upstream_name, "upstream argument required") local ok, peers, err = upstream_fun(upstream_name) check_throw(ok, err) lib.foreachi(peers, function(peer) fun(upstream_name, peer.name) end) end local function set_upstream_primary(mod, name, fun) set_upstream(name, mod.upstream.get_primary_peers, fun) end local function set_upstream_backup(mod, name, fun) set_upstream(name, mod.upstream.get_backup_peers, fun) end local function disable_peer(mod, b) return function(upstream, peer) local dynamic = mod.healthcheck.get(upstream) if dynamic then mod.healthcheck.disable_host(peer, b, upstream) end if b then mod.upstream.set_peer_down(upstream, peer) else if not dynamic then mod.upstream.set_peer_up(upstream, peer) end end end end local function disable(mod, b) return function(upstream) local dynamic = mod.healthcheck.get(upstream) if dynamic then mod.healthcheck.disable(upstream, b) end set_upstream(upstream, mod.upstream.get_peers, function(upstream, peer) if b then mod.upstream.set_peer_down(upstream, peer) else if not dynamic then mod.upstream.set_peer_up(upstream, peer) end end end) end end local function disable_ip(mod, b) return function(ip) local ok, upstreams, err = mod.upstream.get_upstreams() assert(ok, err) for _,u in ipairs(upstreams) do local ok, peers, err = mod.upstream.get_peers(u) assert(ok, err) for _, peer in ipairs(peers) do if peer.name:match("^" .. ip) then disable_peer(mod, b)(u, peer.name) end end end end end local function make_mod(mod) return { enable_peer = function(upstream, peer) set_peer(upstream, peer, disable_peer(mod, false)) end, disable_peer = function(upstream, peer) set_peer(upstream, peer, disable_peer(mod, true)) end, enable_primary_peers = function(upstream) set_upstream_primary(mod.upstream, upstream, disable_peer(mod, false)) end, disable_primary_peers = function(upstream) set_upstream_primary(mod.upstream, upstream, disable_peer(mod, true)) end, enable_backup_peers = function(upstream) set_upstream_backup(mod.upstream, upstream, disable_peer(mod, false)) end, disable_backup_peers = function(upstream) set_upstream_backup(mod.upstream, upstream, disable_peer(mod, true)) end, enable_upstream = function(upstream) disable(mod, false)(upstream) end, disable_upstream = function(upstream) disable(mod, true)(upstream) end, enable_ip = disable_ip(mod, false), disable_ip = disable_ip(mod, true) } end _M.http = make_mod { healthcheck = require "ngx.healthcheck", upstream = require "ngx.dynamic_upstream" } _M.stream = make_mod { healthcheck = require "ngx.healthcheck.stream", upstream = require "ngx.dynamic_upstream.stream" } return _M
fix dynamic
fix dynamic
Lua
bsd-2-clause
ZigzagAK/nginx-resty-auto-healthcheck-config,ZigzagAK/nginx-resty-auto-healthcheck-config
ef45a2dbd4b7a2b56e971b9bf7f373c2a7c1ebef
lantern/criteria.lua
lantern/criteria.lua
-- -- Definitions of the stopping criteria. -- -- -- Returns true if an improvement has been made over the best value of a metric -- before the past `epochs` epochs during the past `epochs` epochs. This -- stopping criterion is designed to be conservative, and may not be appropriate -- when training large numbers of models. -- function lantern.criterion.max_epochs_per_improvement(epochs) assert(epochs > 0) return function(hist) assert(hist[#hist].train or hist[#hist].test) -- If we want to check for improvement over the past one epoch, -- then we need at least two entries. So if we have fewer than -- `epochs + 1` entries, then we return `true` since we have -- insufficient data. if #hist <= epochs then return true end local best_metrics = { train = lantern.best_metrics(hist, "train", #hist - epochs), test = lantern.best_metrics(hist, "test", #hist - epochs) } if #best_metrics.train == 0 then best_metrics.train = nil end if #best_metrics.test == 0 then best_metrics.test = nil end for i = #hist - epochs + 1, #hist do if best_metrics.train and hist[i].train then if lantern.improvement_made(best_metrics.train, hist[i].train) then return true end end if best_metrics.test and hist[i].test then if lantern.improvement_made(best_metrics.test, hist[i].test) then return true end end end return false end end function lantern.criterion.max_epochs(epochs) assert(epochs > 0) return function(hist) assert(hist[#hist].train or hist[#hist].test) if #hist <= epochs - 1 then return true end return false end end
-- -- Definitions of the stopping criteria. -- -- -- Returns true if an improvement has been made over the best value of a metric -- before the past `epochs` epochs during the past `epochs` epochs. This -- stopping criterion is designed to be conservative, and may not be appropriate -- when training large numbers of models. -- function lantern.criterion.max_epochs_per_improvement(epochs) assert(epochs > 0) return function(hist) assert(hist[#hist].train or hist[#hist].test) -- If we want to check for improvement over the past one epoch, -- then we need at least two entries. So if we have fewer than -- `epochs + 1` entries, then we return `true` since we have -- insufficient data. if #hist <= epochs then return true end local best_metrics = { train = lantern.best_metrics(hist, "train", #hist - epochs), test = lantern.best_metrics(hist, "test", #hist - epochs) } local size = function(table) local count = 0 for k, v in pairs(table) do count = count + 1 end return count end if size(best_metrics.train) == 0 then best_metrics.train = nil end if size(best_metrics.test) == 0 then best_metrics.test = nil end for i = #hist - epochs + 1, #hist do if best_metrics.train and hist[i].train then if lantern.improvement_made(best_metrics.train, hist[i].train) then return true end end if best_metrics.test and hist[i].test then if lantern.improvement_made(best_metrics.test, hist[i].test) then return true end end end return false end end -- -- Returns true if an improvement has been made over the best value of a *test* -- metric before the past `epochs` epochs during the past `epochs` epochs. This -- stopping criterion is designed to be conservative, and may not be appropriate -- when training large numbers of models. -- function lantern.criterion.max_epochs_per_improvement(epochs) assert(epochs > 0) return function(hist) assert(hist[#hist].test) -- If we want to check for improvement over the past one epoch, -- then we need at least two entries. So if we have fewer than -- `epochs + 1` entries, then we return `true` since we have -- insufficient data. if #hist <= epochs then return true end local best_metrics = lantern.best_metrics(hist, "test", #hist - epochs) local size = function(table) local count = 0 for k, v in pairs(table) do count = count + 1 end return count end assert(size(best_metrics) >= 1) for i = #hist - epochs + 1, #hist do if hist[i].test then if lantern.improvement_made(best_metrics, hist[i].test) then return true end end end return false end end function lantern.criterion.max_epochs(epochs) assert(epochs > 0) return function(hist) assert(hist[#hist].train or hist[#hist].test) if #hist <= epochs - 1 then return true end return false end end
Bugfix for max_epochs_for_improvement; added max_epochs_per_test_improvement.
Bugfix for max_epochs_for_improvement; added max_epochs_per_test_improvement.
Lua
bsd-3-clause
adityaramesh/lantern
a1167407bd00d5316b6a0cfdc7bf1cdd9e1f6d24
src/cosy/store.lua
src/cosy/store.lua
local Configuration = require "cosy.configuration" local I18n = require "cosy.i18n" local Redis = require "cosy.redis" local Value = require "cosy.value" local Coromake = require "coroutine.make" local Layer = require "layeredata" Configuration.load { "cosy.methods", } local i18n = I18n.load "cosy.store" local Store = {} local Collection = {} local Document = {} function Store.new () local client = Redis () client:unwatch () return setmetatable ({ __redis = client, __collections = {}, }, Store) end function Store.__index (store, key) local pattern = Configuration.resource [key].key local template = Configuration.resource [key].template assert (pattern, key) template = template and Layer.flatten (template) or {} local collection = setmetatable ({ __store = store, __pattern = pattern, __data = {}, __name = key, __template = Layer.new { name = key, data = template, }, }, Collection) store.__collections [key] = collection return collection end function Store.__newindex () assert (false) end function Store.commit (store) local client = store.__redis client:multi () local ok = pcall (function () for _, collection in pairs (store.__collections) do local pattern = collection.__pattern for key, document in pairs (collection.__data) do if document.__dirty then local name = pattern % { key = key, } local value = document.__data if value == nil then client:del (name) else value.__depends__ = nil local expire_at = value.expire_at client:set (name, Value.encode (Layer.export (value))) if expire_at then client:expireat (name, math.ceil (expire_at)) else client:persist (name) end end end end end end) if ok then if not client:exec () then error { _ = i18n ["redis:retry"], } end else client:discard () end end function Store.exists (collection, key) local store = collection.__store local client = store.__redis local name = collection.__pattern % { key = key, } return client:exists (name) end function Store.filter (collection, filter) local coroutine = Coromake () local client = collection.store.__redis return coroutine.wrap (function () local name = collection.__pattern % { key = filter } local cursor = 0 repeat local t = client:scan (cursor, { match = name, count = 100, }) cursor = t [1] local data = t [2] for i = 1, #data do local key = (collection.__pattern / data [i]).key local value = collection.__data [key] coroutine.yield (key, value) end until cursor == "0" end) end function Collection.__index (collection, key) if not collection.__data [key] then local store = collection.__store local client = store.__redis local name = collection.__pattern % { key = key, } client:watch (name) local value = client:get (name) if value == nil then return nil end local layer = Layer.new { name = key, data = Value.decode (value), } layer.__depends__ = { collection.__template } collection.__data [key] = { __store = store, __dirty = false, __data = layer, } end return Document.new (collection.__data [key]) end function Collection.__newindex (collection, key, value) local store = collection.__store if value == nil then collection.__data [key] = { __store = store, __dirty = true, __layer = nil, __data = nil, } else local layer = Layer.new { name = key, data = value, } if type (value) == "table" then layer.__depends__ = { collection.__template } end collection.__data [key] = { __store = store, __dirty = true, __data = layer, } end end function Collection.__pairs (collection) return Store.filter (collection, "*") end function Collection.__len (collection) local store = collection.__store local client = store.__redis local i = 0 repeat i = i+1 local name = collection.__pattern % { key = i, } local exists = client:exists (name) until not exists return i-1 end function Collection.__ipairs (collection) local coroutine = Coromake () return coroutine.wrap (function () local i = 0 repeat i = i+1 local value = collection [i] if value == nil then return end coroutine.yield (i, value) until true end) end function Document.new (root) return setmetatable ({ __root = root, __data = root.__data, }, Document) end function Document.__index (document, key) local result = document.__data [key] if getmetatable (result) ~= Layer then return result else return setmetatable ({ __root = document.__root, __data = result, }, Document) end end function Document.__newindex (document, key, value) document.__data [key] = value document.__root.__dirty = true end function Document.__pairs (document) local coroutine = Coromake () return coroutine.wrap (function () for k in Layer.pairs (document.__data) do coroutine.yield (k, document [k]) end end) end function Document.__ipairs (document) local coroutine = Coromake () return coroutine.wrap (function () for i = 1, Layer.size (document.__data) do coroutine.yield (i, document [i]) end end) end function Document.__len (document) return Layer.size (document.__data) end return Store
local Configuration = require "cosy.configuration" local I18n = require "cosy.i18n" local Redis = require "cosy.redis" local Value = require "cosy.value" local Coromake = require "coroutine.make" local Layer = require "layeredata" Configuration.load { "cosy.methods", } local i18n = I18n.load "cosy.store" local Store = {} local Collection = {} local Document = {} function Store.new () local client = Redis () client:unwatch () return setmetatable ({ __redis = client, __collections = {}, }, Store) end function Store.__index (store, key) local pattern = Configuration.resource [key].key local template = Configuration.resource [key].template assert (pattern, key) template = template and Layer.flatten (template) or {} local collection = setmetatable ({ __store = store, __pattern = pattern, __data = {}, __name = key, __template = Layer.new { name = key, data = template, }, }, Collection) store.__collections [key] = collection return collection end function Store.__newindex () assert (false) end function Store.commit (store) local client = store.__redis client:multi () local ok = pcall (function () for _, collection in pairs (store.__collections) do local pattern = collection.__pattern for key, document in pairs (collection.__data) do if document.__dirty then local name = pattern % { key = key, } local value = document.__data if value == nil then client:del (name) else value.__depends__ = nil local expire_at = value.expire_at client:set (name, Value.encode (Layer.export (value))) if expire_at then client:expireat (name, math.ceil (expire_at)) else client:persist (name) end end end end end end) if ok then if not client:exec () then error { _ = i18n ["redis:retry"], } end else client:discard () end end function Store.exists (collection, key) local store = collection.__store local client = store.__redis local name = collection.__pattern % { key = key, } return client:exists (name) end function Store.filter (collection, filter) local coroutine = Coromake () local store = collection.__store local client = store.__redis return coroutine.wrap (function () local name = collection.__pattern % { key = filter } local cursor = 0 repeat local t = client:scan (cursor, { match = name, count = 100, }) cursor = t [1] local data = t [2] for i = 1, #data do local key = (collection.__pattern / data [i]).key local value = collection.__data [key] coroutine.yield (key, value) end until cursor == "0" end) end function Collection.__index (collection, key) if not collection.__data [key] then local store = collection.__store local client = store.__redis local name = collection.__pattern % { key = key, } client:watch (name) local value = client:get (name) if value == nil then return nil end local layer = Layer.new { name = key, data = Value.decode (value), } layer.__depends__ = { collection.__template } collection.__data [key] = { __store = store, __dirty = false, __data = layer, } end return Document.new (collection.__data [key]) end function Collection.__newindex (collection, key, value) local store = collection.__store if value == nil then collection.__data [key] = { __store = store, __dirty = true, __layer = nil, __data = nil, } else local layer = Layer.new { name = key, data = value, } if type (value) == "table" then layer.__depends__ = { collection.__template } end collection.__data [key] = { __store = store, __dirty = true, __data = layer, } end end function Collection.__pairs (collection) return Store.filter (collection, "*") end function Collection.__len (collection) local store = collection.__store local client = store.__redis local i = 0 repeat i = i+1 local name = collection.__pattern % { key = i, } local exists = client:exists (name) until not exists return i-1 end function Collection.__ipairs (collection) local coroutine = Coromake () return coroutine.wrap (function () local i = 0 repeat i = i+1 local value = collection [i] if value == nil then return end coroutine.yield (i, value) until true end) end function Document.new (root) return setmetatable ({ __root = root, __data = root.__data, }, Document) end function Document.__index (document, key) local result = document.__data [key] if getmetatable (result) ~= Layer then return result else return setmetatable ({ __root = document.__root, __data = result, }, Document) end end function Document.__newindex (document, key, value) document.__data [key] = value document.__root.__dirty = true end function Document.__pairs (document) local coroutine = Coromake () return coroutine.wrap (function () for k in Layer.pairs (document.__data) do coroutine.yield (k, document [k]) end end) end function Document.__ipairs (document) local coroutine = Coromake () return coroutine.wrap (function () for i = 1, Layer.size (document.__data) do coroutine.yield (i, document [i]) end end) end function Document.__len (document) return Layer.size (document.__data) end return Store
Fix access to redis client.
Fix access to redis client.
Lua
mit
CosyVerif/library,CosyVerif/library,CosyVerif/library
763338c0164a96d74f235cea65fe76fcd1a1687d
share/lua/website/1tvru.lua
share/lua/website/1tvru.lua
-- libquvi-scripts -- Copyright (C) 2012 Mikhail Gusarov <dottedmag@dottedmag.net> -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -- 02110-1301 USA -- local OTvRu = {} -- Utility functions specific to this script -- Identify the script. function ident(self) package.path = self.script_dir .. '/?.lua' local C = require 'quvi/const' local r = {} r.domain = "1tv%.ru" r.formats = "default" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/sprojects_edition/"}) return r end -- Query available formats. function query_formats(self) self.formats = 'default' return self end -- Parse media URL. function parse(self) self.host_id = "1tvru" self.id = self.page_url:match('fi(%d+)') or self.page_url:match('fi=(%d+)') or error("no match: media ID") local p = quvi.fetch(self.page_url) self.title = p:match(OTvRu.pattern('title', '(.-)')) or error("no match: media title") self.url = {p:match(OTvRu.pattern('file', '(.-)')) or error("no match: media stream URL")} self.thumbnail_url = p:match('"og:image" content="(.-)"') or '' return self end function OTvRu.pattern(key_name, value_pattern) return string.format("jwplayer%%('flashvideoportal_1'%%).*'%s': '%s'", key_name, value_pattern) end -- vim: set ts=4 sw=4 tw=72 expandtab:
-- libquvi-scripts -- Copyright (C) 2012 Mikhail Gusarov <dottedmag@dottedmag.net> -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -- 02110-1301 USA -- local OTvRu = {} -- Utility functions specific to this script -- Identify the script. function ident(self) package.path = self.script_dir .. '/?.lua' local C = require 'quvi/const' local r = {} r.domain = "1tv%.ru" r.formats = "default" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/sprojects_edition/"}) return r end -- Query available formats. function query_formats(self) self.formats = 'default' return self end -- Parse media URL. function parse(self) self.host_id = "1tvru" self.id = self.page_url:match('fi(%d+)') or self.page_url:match('fi=(%d+)') or error("no match: media ID") local p = quvi.fetch(self.page_url) self.title = p:match("'title': '(.-)'") or error("no match: media title") self.url = {p:match("'file': '(.-)'") or error("no match: media stream URL")} self.thumbnail_url = p:match('"og:image" content="(.-)"') or '' return self end --[[ function OTvRu.pattern(key_name, value_pattern) return string.format("jwplayer%%('flashvideoportal_1'%%).*'%s': '%s'", key_name, value_pattern) end ]]-- -- vim: set ts=4 sw=4 tw=72 expandtab:
FIX: 1tvru.lua: title and media URL patterns
FIX: 1tvru.lua: title and media URL patterns Only some of the (archived?) videos seem to work (now?). Signed-off-by: Toni Gundogdu <eac2284b3c43676907b96f08de9d3d52d5df0361@gmail.com>
Lua
agpl-3.0
alech/libquvi-scripts,alech/libquvi-scripts,DangerCove/libquvi-scripts,legatvs/libquvi-scripts,legatvs/libquvi-scripts,DangerCove/libquvi-scripts
93ea55da638a4f197a4d90d5185071214b9296f5
core/certmanager.lua
core/certmanager.lua
local configmanager = require "core.configmanager"; local log = require "util.logger".init("certmanager"); local ssl = ssl; local ssl_newcontext = ssl and ssl.newcontext; local setmetatable, tostring = setmetatable, tostring; local prosody = prosody; module "certmanager" -- These are the defaults if not overridden in the config local default_ssl_ctx = { mode = "client", protocol = "sslv23", capath = "/etc/ssl/certs", verify = "none", options = "no_sslv2"; }; local default_ssl_ctx_in = { mode = "server", protocol = "sslv23", capath = "/etc/ssl/certs", verify = "none", options = "no_sslv2"; }; local default_ssl_ctx_mt = { __index = default_ssl_ctx }; local default_ssl_ctx_in_mt = { __index = default_ssl_ctx_in }; -- Global SSL options if not overridden per-host local default_ssl_config = configmanager.get("*", "core", "ssl"); function create_context(host, mode, config) local ssl_config = config and config.core.ssl or default_ssl_config; if ssl and ssl_config then local ctx, err = ssl_newcontext(setmetatable(ssl_config, mode == "client" and default_ssl_ctx_mt or default_ssl_ctx_in_mt)); if not ctx then err = err or "invalid ssl config" local file = err:match("^error loading (.-) %("); if file then if file == "private key" then file = ssl_config.key or "your private key"; elseif file == "certificate" then file = ssl_config.certificate or "your certificate file"; end local reason = err:match("%((.+)%)$") or "some reason"; if reason == "Permission denied" then reason = "Check that the permissions allow Prosody to read this file."; elseif reason == "No such file or directory" then reason = "Check that the path is correct, and the file exists."; elseif reason == "system lib" then reason = "Previous error (see logs), or other system error."; elseif reason == "(null)" or not reason then reason = "Check that the file exists and the permissions are correct"; else reason = "Reason: "..tostring(reason):lower(); end log("error", "SSL/TLS: Failed to load %s: %s", file, reason); else log("error", "SSL/TLS: Error initialising for host %s: %s", host, err ); end ssl = false end return ctx, err; end return nil; end function reload_ssl_config() default_ssl_config = configmanager.get("*", "core", "ssl"); end prosody.events.add_handler("config-reloaded", reload_ssl_config); return _M;
local configmanager = require "core.configmanager"; local log = require "util.logger".init("certmanager"); local ssl = ssl; local ssl_newcontext = ssl and ssl.newcontext; local setmetatable, tostring = setmetatable, tostring; local prosody = prosody; local resolve_path = prosody.resolve_relative_path; module "certmanager" -- Global SSL options if not overridden per-host local default_ssl_config = configmanager.get("*", "core", "ssl"); function create_context(host, mode, config) if not ssl then return nil; end local user_ssl_config = config and config.core.ssl or default_ssl_config; local ssl_config = { mode = mode; protocol = user_ssl_config.protocol or "sslv23"; key = resolve_path(user_ssl_config.key); password = user_ssl_config.password; certificate = resolve_path(user_ssl_config.certificate); capath = resolve_path(user_ssl_config.capath or default_capath); cafile = resolve_path(user_ssl_config.cafile); verify = user_ssl_config.verify or "none"; options = user_ssl_config.options or "no_sslv2"; ciphers = user_ssl_config.ciphers; depth = user_ssl_config.depth; }; log("warn", "keyfile: %q", ssl_config.key); local ctx, err = ssl_newcontext(ssl_config); if not ctx then err = err or "invalid ssl config" local file = err:match("^error loading (.-) %("); if file then if file == "private key" then file = ssl_config.key or "your private key"; elseif file == "certificate" then file = ssl_config.certificate or "your certificate file"; end local reason = err:match("%((.+)%)$") or "some reason"; if reason == "Permission denied" then reason = "Check that the permissions allow Prosody to read this file."; elseif reason == "No such file or directory" then reason = "Check that the path is correct, and the file exists."; elseif reason == "system lib" then reason = "Previous error (see logs), or other system error."; elseif reason == "(null)" or not reason then reason = "Check that the file exists and the permissions are correct"; else reason = "Reason: "..tostring(reason):lower(); end log("error", "SSL/TLS: Failed to load %s: %s", file, reason); else log("error", "SSL/TLS: Error initialising for host %s: %s", host, err ); end ssl = false end return ctx, err; end function reload_ssl_config() default_ssl_config = configmanager.get("*", "core", "ssl"); end prosody.events.add_handler("config-reloaded", reload_ssl_config); return _M;
certmanager: Adjust paths of SSL key/certs to be relative to the config file, fixes #147
certmanager: Adjust paths of SSL key/certs to be relative to the config file, fixes #147
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
b674ffbccc4c21eb2d48d35ddd4ed47bc3f427c0
src/websocket/frame.lua
src/websocket/frame.lua
-- Following Websocket RFC: http://tools.ietf.org/html/rfc6455 local struct = require'struct' local bit = require'websocket.bit' local band = bit.band local bxor = bit.bxor local bor = bit.bor local tremove = table.remove local srep = string.rep local ssub = string.sub local sbyte = string.byte local schar = string.char local tinsert = table.insert local tconcat = table.concat local mmin = math.min local strpack = struct.pack local strunpack = struct.unpack local mfloor = math.floor local mrandom = math.random local bits = function(...) local n = 0 for _,bitn in pairs{...} do n = n + 2^bitn end return n end local bit_7 = bits(7) local bit_0_3 = bits(0,1,2,3) local bit_0_6 = bits(0,1,2,3,4,5,6) local xor_mask = function(encoded,mask,payload) local transformed_arr = {} -- xor chunk-wise to prevent stack overflow. -- sbyte and schar multiple in/out values -- which require stack for p=1,payload,2000 do local transformed = {} local last = mmin(p+1999,payload) local original = {sbyte(encoded,p,last)} for i=1,#original do local j = (i-1) % 4 + 1 transformed[i] = band(bxor(original[i],mask[j]), 0xFF) end local xored = schar(unpack(transformed)) tinsert(transformed_arr,xored) end return tconcat(transformed_arr) end local encode = function(data,opcode,masked,fin) local encoded local header = opcode or 1-- TEXT is default opcode if fin == nil or fin == true then header = bor(header,bit_7) end local payload = 0 if masked then payload = bor(payload,bit_7) end local len = #data if len < 126 then payload = bor(payload,len) encoded = strpack('bb',header,payload) elseif len <= 0xffff then payload = bor(payload,126) encoded = strpack('bb>H',header,payload,len) elseif len < 2^53 then local high = mfloor(len/2^32) local low = len - high*2^32 payload = bor(payload,127) encoded = strpack('bb>I>I',header,payload,high,low) end if not masked then encoded = encoded..data else local m1 = mrandom(0,0xff) local m2 = mrandom(0,0xff) local m3 = mrandom(0,0xff) local m4 = mrandom(0,0xff) local mask = {m1,m2,m3,m4} encoded = tconcat({ encoded, strpack('bbbb',m1,m2,m3,m4), xor_mask(data,mask,#data) }) end return encoded end local decode = function(encoded) local encoded_bak = encoded if #encoded < 2 then return nil,2 end local header,payload,pos = struct.unpack('bb',encoded) local high,low encoded = ssub(encoded,pos) local bytes = 2 local fin = band(header,bit_7) > 0 local opcode = band(header,bit_0_3) local mask = band(payload,bit_7) > 0 payload = band(payload,bit_0_6) if payload > 125 then if payload == 126 then if #encoded < 2 then return nil,2 end payload,pos = struct.unpack('>H',encoded) elseif payload == 127 then if #encoded < 8 then return nil,8 end high,low,pos = struct.unpack('>I>I',encoded) payload = high*2^32 + low if payload < 0xffff or payload > 2^53 then assert(false,'INVALID PAYLOAD '..payload) end else assert(false,'INVALID PAYLOAD '..payload) end encoded = ssub(encoded,pos) bytes = bytes + pos - 1 end local decoded if mask then local bytes_short = payload + 4 - #encoded if bytes_short > 0 then return nil,bytes_short end local m1,m2,m3,m4,pos = struct.unpack('bbbb',encoded) encoded = ssub(encoded,pos) local mask = { m1,m2,m3,m4 } decoded = xor_mask(encoded,mask,payload) bytes = bytes + 4 + payload else local bytes_short = payload - #encoded if bytes_short > 0 then return nil,bytes_short end if #encoded > payload then decoded = ssub(encoded,1,payload) else decoded = encoded end bytes = bytes + payload end return decoded,fin,opcode,encoded_bak:sub(bytes+1),mask end local encode_close = function(code,reason) if code then local data = struct.pack('>H',code) if reason then data = data..tostring(reason) end return data end return '' end local decode_close = function(data) local _,code,reason if data then if #data > 1 then code = struct.unpack('>H',data) end if #data > 2 then reason = data:sub(3) end end return code,reason end return { encode = encode, decode = decode, encode_close = encode_close, decode_close = decode_close, CONTINUATION = 0, TEXT = 1, BINARY = 2, CLOSE = 8, PING = 9, PONG = 10 }
-- Following Websocket RFC: http://tools.ietf.org/html/rfc6455 local struct = require'struct' local bit = require'websocket.bit' local band = bit.band local bxor = bit.bxor local bor = bit.bor local tremove = table.remove local srep = string.rep local ssub = string.sub local sbyte = string.byte local schar = string.char local tinsert = table.insert local tconcat = table.concat local mmin = math.min local strpack = struct.pack local strunpack = struct.unpack local mfloor = math.floor local mrandom = math.random local unpack = unpack or table.unpack local bits = function(...) local n = 0 for _,bitn in pairs{...} do n = n + 2^bitn end return n end local bit_7 = bits(7) local bit_0_3 = bits(0,1,2,3) local bit_0_6 = bits(0,1,2,3,4,5,6) local xor_mask = function(encoded,mask,payload) local transformed,transformed_arr = {},{} -- xor chunk-wise to prevent stack overflow. -- sbyte and schar multiple in/out values -- which require stack for p=1,payload,2000 do local last = mmin(p+1999,payload) local original = {sbyte(encoded,p,last)} for i=1,#original do local j = (i-1) % 4 + 1 transformed[i] = bxor(original[i],mask[j]) end local xored = schar(unpack(transformed,1,#original)) tinsert(transformed_arr,xored) end return tconcat(transformed_arr) end local encode = function(data,opcode,masked,fin) local encoded local header = opcode or 1-- TEXT is default opcode if fin == nil or fin == true then header = bor(header,bit_7) end local payload = 0 if masked then payload = bor(payload,bit_7) end local len = #data if len < 126 then payload = bor(payload,len) encoded = strpack('bb',header,payload) elseif len <= 0xffff then payload = bor(payload,126) encoded = strpack('bb>H',header,payload,len) elseif len < 2^53 then local high = mfloor(len/2^32) local low = len - high*2^32 payload = bor(payload,127) encoded = strpack('bb>I>I',header,payload,high,low) end if not masked then encoded = encoded..data else local m1 = mrandom(0,0xff) local m2 = mrandom(0,0xff) local m3 = mrandom(0,0xff) local m4 = mrandom(0,0xff) local mask = {m1,m2,m3,m4} encoded = tconcat({ encoded, strpack('bbbb',m1,m2,m3,m4), xor_mask(data,mask,#data) }) end return encoded end local decode = function(encoded) local encoded_bak = encoded if #encoded < 2 then return nil,2 end local header,payload,pos = strunpack('bb',encoded) local high,low encoded = ssub(encoded,pos) local bytes = 2 local fin = band(header,bit_7) > 0 local opcode = band(header,bit_0_3) local mask = band(payload,bit_7) > 0 payload = band(payload,bit_0_6) if payload > 125 then if payload == 126 then if #encoded < 2 then return nil,2 end payload,pos = strunpack('>H',encoded) elseif payload == 127 then if #encoded < 8 then return nil,8 end high,low,pos = strunpack('>I>I',encoded) payload = high*2^32 + low if payload < 0xffff or payload > 2^53 then assert(false,'INVALID PAYLOAD '..payload) end else assert(false,'INVALID PAYLOAD '..payload) end encoded = ssub(encoded,pos) bytes = bytes + pos - 1 end local decoded if mask then local bytes_short = payload + 4 - #encoded if bytes_short > 0 then return nil,bytes_short end local m1,m2,m3,m4,pos = strunpack('bbbb',encoded) encoded = ssub(encoded,pos) local mask = { m1,m2,m3,m4 } decoded = xor_mask(encoded,mask,payload) bytes = bytes + 4 + payload else local bytes_short = payload - #encoded if bytes_short > 0 then return nil,bytes_short end if #encoded > payload then decoded = ssub(encoded,1,payload) else decoded = encoded end bytes = bytes + payload end return decoded,fin,opcode,encoded_bak:sub(bytes+1),mask end local encode_close = function(code,reason) if code then local data = strpack('>H',code) if reason then data = data..tostring(reason) end return data end return '' end local decode_close = function(data) local _,code,reason if data then if #data > 1 then code = strunpack('>H',data) end if #data > 2 then reason = data:sub(3) end end return code,reason end return { encode = encode, decode = decode, encode_close = encode_close, decode_close = decode_close, CONTINUATION = 0, TEXT = 1, BINARY = 2, CLOSE = 8, PING = 9, PONG = 10 }
Fix. Use global `unpack` is not compatible with Lua 5.2 Minor performance improvements
Fix. Use global `unpack` is not compatible with Lua 5.2 Minor performance improvements
Lua
mit
lipp/lua-websockets,KSDaemon/lua-websockets,lipp/lua-websockets,enginix/lua-websockets,OptimusLime/lua-websockets,KSDaemon/lua-websockets,KSDaemon/lua-websockets,lipp/lua-websockets,enginix/lua-websockets,enginix/lua-websockets,OptimusLime/lua-websockets,OptimusLime/lua-websockets
820e8d9502d5ad0faf8fe0981e1e32dd3ac48e95
core/sile.lua
core/sile.lua
SILE = {} SILE.version = "0.9.4-unreleased" SILE.utilities = require("core/utilities") SU = SILE.utilities SILE.inputs = {} SILE.Commands = {}; SILE.debugFlags = {} SILE.nodeMakers = {} SILE.tokenizers = {} loadstring = loadstring or load -- 5.3 compatibility if not unpack then unpack = table.unpack end -- 5.3 compatibility std = require("std") SILE.documentState = std.object {}; SILE.scratch = {}; SILE.length = require("core/length") require("core/parserbits") require("core/measurements") require("core/baseclass") SILE.nodefactory = require("core/nodefactory") require("core/settings") require("core/inputs-texlike") require("core/inputs-xml") require("core/inputs-common") require("core/papersizes") require("core/colorparser") require("core/pagebuilder") require("core/typesetter") require("core/hyphenator-liang") require("core/languages") require("core/font") SILE.frameParser = require("core/frameparser") SILE.linebreak = require("core/break") require("core/frame") SILE.init = function() if not SILE.backend then if pcall(function () require("justenoughharfbuzz") end) then SILE.backend = "libtexpdf" elseif pcall(function() require("lgi") end) then SILE.backend = "pangocairo" else SU.error("Neither libtexpdf nor pangocairo backends available!") end end if SILE.backend == "libtexpdf" then require("core/harfbuzz-shaper") require("core/libtexpdf-output") elseif SILE.backend == "pangocairo" then SU.warn("The pangocairo backend is deprecated and will be removed in the next release of SILE") require("core/pango-shaper") require("core/cairo-output") end if SILE.dolua then _, err = pcall(SILE.dolua) if err then error(err) end end end SILE.require = function(d) return require(d) end SILE.parseArguments = function() local parser = std.optparse ("SILE "..SILE.version..[[ Usage: sile [options] file.sil|file.xml The SILE typesetter reads a single input file in either SIL or XML format to generate an output in PDF format. The output will be writted to the same name as the input file with the extention changed to .pdf. Options: -b, --backend=VALUE choose between libtexpdf/pangocairo backends -d, --debug=VALUE debug SILE's operation -e, --evaluate=VALUE evaluate some Lua code before processing file -o, --output=[FILE] explicitly set output file name -I, --include=[FILE] include a class or SILE file before processing input --help display this help, then exit --version display version information, then exit ]]) parser:on ('--', parser.finished) _G.unparsed, _G.opts = parser:parse(_G.arg) SILE.debugFlags = {} if opts.backend then SILE.backend = opts.backend end if opts.debug then for k,v in ipairs(std.string.split(opts.debug, ",")) do SILE.debugFlags[v] = 1 end end if opts.evaluate then SILE.dolua,err = loadstring(opts.evaluate) if err then SU.error(err) end end if opts.output then SILE.outputFilename = opts.output end if opts.include then SILE.preamble = opts.include end end function SILE.initRepl () SILE._repl = require 'repl.console' local has_linenoise = pcall(require, 'linenoise') if has_linenoise then SILE._repl:loadplugin 'linenoise' else -- XXX check that we're not receiving input from a non-tty local has_rlwrap = os.execute('which rlwrap >/dev/null 2>/dev/null') == 0 if has_rlwrap and not os.getenv 'LUA_REPL_RLWRAP' then local command = 'LUA_REPL_RLWRAP=1 rlwrap' local index = 0 while arg[index - 1] do index = index - 1 end while arg[index] do command = string.format('%s %q', command, arg[index]) index = index + 1 end os.execute(command) return end end SILE._repl:loadplugin 'history' SILE._repl:loadplugin 'completion' SILE._repl:loadplugin 'autoreturn' SILE._repl:loadplugin 'rcfile' end function SILE.repl() if not SILE._repl then SILE.initRepl() end SILE._repl:run() end function SILE.readFile(fn) SILE.currentlyProcessingFile = fn fn = SILE.resolveFile(fn) if not fn then SU.error("Could not find file") end local file, err = io.open(fn) if not file then print("Could not open "..fn..": "..err) return end io.write("<"..fn..">\n") -- Sniff first few bytes local sniff = file:read("*l") or "" file:seek("set", 0) local inputsOrder = {} for n in pairs(SILE.inputs) do if SILE.inputs[n].order then table.insert(inputsOrder, n) end end table.sort(inputsOrder,function(a,b) return SILE.inputs[a].order < SILE.inputs[b].order end) for i = 1,#inputsOrder do local input = SILE.inputs[inputsOrder[i]] if input.appropriate(fn, sniff) then input.process(fn) return end end SU.error("No input processor available for "..fn.." (should never happen)",1) end local function file_exists(name) local f=io.open(name,"r") if f~=nil then io.close(f) return true else return false end end function SILE.resolveFile(fn) if file_exists(fn) then return fn end if file_exists(fn..".sil") then return fn..".sil" end local dirname = SILE.masterFilename:match("(.-)[^%/]+$") for k in SU.gtoke(dirname..";"..tostring(os.getenv("SILE_PATH")), ";") do if k.string then local f = std.io.catfile(k.string, fn) if file_exists(f) then return f end if file_exists(f..".sil") then return f..".sil" end end end end function SILE.call(cmd,options, content) SILE.currentCommand = content if not SILE.Commands[cmd] then SU.error("Unknown command "..cmd) end SILE.Commands[cmd](options or {}, content or {}) end return SILE
SILE = {} SILE.version = "0.9.4-unreleased" SILE.utilities = require("core/utilities") SU = SILE.utilities SILE.inputs = {} SILE.Commands = {}; SILE.debugFlags = {} SILE.nodeMakers = {} SILE.tokenizers = {} loadstring = loadstring or load -- 5.3 compatibility if not unpack then unpack = table.unpack end -- 5.3 compatibility std = require("std") SILE.documentState = std.object {}; SILE.scratch = {}; SILE.length = require("core/length") require("core/parserbits") require("core/measurements") require("core/baseclass") SILE.nodefactory = require("core/nodefactory") require("core/settings") require("core/inputs-texlike") require("core/inputs-xml") require("core/inputs-common") require("core/papersizes") require("core/colorparser") require("core/pagebuilder") require("core/typesetter") require("core/hyphenator-liang") require("core/languages") require("core/font") SILE.frameParser = require("core/frameparser") SILE.linebreak = require("core/break") require("core/frame") SILE.init = function() if not SILE.backend then if pcall(function () require("justenoughharfbuzz") end) then SILE.backend = "libtexpdf" elseif pcall(function() require("lgi") end) then SILE.backend = "pangocairo" else SU.error("Neither libtexpdf nor pangocairo backends available!") end end if SILE.backend == "libtexpdf" then require("core/harfbuzz-shaper") require("core/libtexpdf-output") elseif SILE.backend == "pangocairo" then SU.warn("The pangocairo backend is deprecated and will be removed in the next release of SILE") require("core/pango-shaper") require("core/cairo-output") end if SILE.dolua then _, err = pcall(SILE.dolua) if err then error(err) end end end SILE.require = function(d) local f = SILE.resolveFile(d..".lua") if f then return require(f:gsub(".lua$","")) end return require(d) end SILE.parseArguments = function() local parser = std.optparse ("SILE "..SILE.version..[[ Usage: sile [options] file.sil|file.xml The SILE typesetter reads a single input file in either SIL or XML format to generate an output in PDF format. The output will be writted to the same name as the input file with the extention changed to .pdf. Options: -b, --backend=VALUE choose between libtexpdf/pangocairo backends -d, --debug=VALUE debug SILE's operation -e, --evaluate=VALUE evaluate some Lua code before processing file -o, --output=[FILE] explicitly set output file name -I, --include=[FILE] include a class or SILE file before processing input --help display this help, then exit --version display version information, then exit ]]) parser:on ('--', parser.finished) _G.unparsed, _G.opts = parser:parse(_G.arg) SILE.debugFlags = {} if opts.backend then SILE.backend = opts.backend end if opts.debug then for k,v in ipairs(std.string.split(opts.debug, ",")) do SILE.debugFlags[v] = 1 end end if opts.evaluate then SILE.dolua,err = loadstring(opts.evaluate) if err then SU.error(err) end end if opts.output then SILE.outputFilename = opts.output end if opts.include then SILE.preamble = opts.include end end function SILE.initRepl () SILE._repl = require 'repl.console' local has_linenoise = pcall(require, 'linenoise') if has_linenoise then SILE._repl:loadplugin 'linenoise' else -- XXX check that we're not receiving input from a non-tty local has_rlwrap = os.execute('which rlwrap >/dev/null 2>/dev/null') == 0 if has_rlwrap and not os.getenv 'LUA_REPL_RLWRAP' then local command = 'LUA_REPL_RLWRAP=1 rlwrap' local index = 0 while arg[index - 1] do index = index - 1 end while arg[index] do command = string.format('%s %q', command, arg[index]) index = index + 1 end os.execute(command) return end end SILE._repl:loadplugin 'history' SILE._repl:loadplugin 'completion' SILE._repl:loadplugin 'autoreturn' SILE._repl:loadplugin 'rcfile' end function SILE.repl() if not SILE._repl then SILE.initRepl() end SILE._repl:run() end function SILE.readFile(fn) SILE.currentlyProcessingFile = fn fn = SILE.resolveFile(fn) if not fn then SU.error("Could not find file") end local file, err = io.open(fn) if not file then print("Could not open "..fn..": "..err) return end io.write("<"..fn..">\n") -- Sniff first few bytes local sniff = file:read("*l") or "" file:seek("set", 0) local inputsOrder = {} for n in pairs(SILE.inputs) do if SILE.inputs[n].order then table.insert(inputsOrder, n) end end table.sort(inputsOrder,function(a,b) return SILE.inputs[a].order < SILE.inputs[b].order end) for i = 1,#inputsOrder do local input = SILE.inputs[inputsOrder[i]] if input.appropriate(fn, sniff) then input.process(fn) return end end SU.error("No input processor available for "..fn.." (should never happen)",1) end local function file_exists(name) local f=io.open(name,"r") if f~=nil then io.close(f) return true else return false end end function SILE.resolveFile(fn) if file_exists(fn) then return fn end if file_exists(fn..".sil") then return fn..".sil" end local dirname = SILE.masterFilename:match("(.-)[^%/]+$") for k in SU.gtoke(dirname..";"..tostring(os.getenv("SILE_PATH")), ";") do if k.string then local f = std.io.catfile(k.string, fn) if file_exists(f) then return f end if file_exists(f..".sil") then return f..".sil" end end end end function SILE.call(cmd,options, content) SILE.currentCommand = content if not SILE.Commands[cmd] then SU.error("Unknown command "..cmd) end SILE.Commands[cmd](options or {}, content or {}) end return SILE
Resolve classes etc. in the directory of the input file. Fixes #184.
Resolve classes etc. in the directory of the input file. Fixes #184.
Lua
mit
alerque/sile,simoncozens/sile,neofob/sile,neofob/sile,alerque/sile,neofob/sile,alerque/sile,alerque/sile,simoncozens/sile,simoncozens/sile,neofob/sile,simoncozens/sile
2e4ff7013feb07c60c87ad579c5ed140799fc338
mod_auth_dovecot/mod_auth_dovecot.lua
mod_auth_dovecot/mod_auth_dovecot.lua
-- Dovecot authentication backend for Prosody -- -- Copyright (C) 2010 Javier Torres -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- local socket_unix = require "socket.unix"; local datamanager = require "util.datamanager"; local log = require "util.logger".init("auth_dovecot"); local new_sasl = require "util.sasl".new; local nodeprep = require "util.encodings".stringprep.nodeprep; local base64 = require "util.encodings".base64; local pposix = require "util.pposix"; local prosody = _G.prosody; local socket_path = module:get_option_string("dovecot_auth_socket", "/var/run/dovecot/auth-login"); function new_default_provider(host) local provider = { name = "dovecot", request_id = 0 }; log("debug", "initializing dovecot authentication provider for host '%s'", host); local conn; -- Closes the socket function provider.close(self) if conn then conn:close(); conn = nil; end end -- The following connects to a new socket and send the handshake function provider.connect(self) -- Destroy old socket provider:close(); conn = socket.unix(); -- Create a connection to dovecot socket log("debug", "connecting to dovecot socket at '%s'", socket_path); local r, e = conn:connect(socket_path); if (not r) then log("warn", "error connecting to dovecot socket at '%s'. error was '%s'. check permissions", socket_path, e); provider:close(); return false; end -- Send our handshake local pid = pposix.getpid(); log("debug", "sending handshake to dovecot. version 1.1, cpid '%d'", pid); if not provider:send("VERSION\t1\t1\n") then return false end if (not provider:send("CPID\t" .. pid .. "\n")) then return false end -- Parse Dovecot's handshake local done = false; while (not done) do local l = provider:receive(); if (not l) then return false; end log("debug", "dovecot handshake: '%s'", l); parts = string.gmatch(l, "[^\t]+"); first = parts(); if (first == "VERSION") then -- Version should be 1.1 local major_version = parts(); if major_version ~= "1" then log("error", "dovecot server version is not 1.x. it is %s.x", major_version); provider:close(); return false; end elseif (first == "MECH") then -- Mechanisms should include PLAIN local ok = false; for p in parts do if p == "PLAIN" then ok = true; end end if (not ok) then log("warn", "server doesn't support PLAIN mechanism. It supports '%s'", l); provider:close(); return false; end elseif (first == "DONE") then done = true; end end return true; end -- Wrapper for send(). Handles errors function provider.send(self, data) local r, e = conn:send(data); if (not r) then log("warn", "error sending '%s' to dovecot. error was '%s'", data, e); provider:close(); return false; end return true; end -- Wrapper for receive(). Handles errors function provider.receive(self) local r, e = conn:receive(); if (not r) then log("warn", "error receiving data from dovecot. error was '%s'", socket, e); provider:close(); return false; end return r; end function provider.send_auth_request(self, username, password) if not conn then if not provider:connect() then return nil, "Auth failed. Dovecot communications error"; end end -- Send auth data username = username .. "@" .. module.host; -- FIXME: this is actually a hack for my server local b64 = base64.encode(username .. "\0" .. username .. "\0" .. password); provider.request_id = provider.request_id + 1 % 4294967296 local msg = "AUTH\t" .. provider.request_id .. "\tPLAIN\tservice=XMPP\tresp=" .. b64; log("debug", "sending auth request for '%s' with password '%s': '%s'", username, password, msg); if (not provider:send(msg .. "\n")) then return nil, "Auth failed. Dovecot communications error"; end -- Get response local l = provider:receive(); log("debug", "got auth response: '%s'", l); if (not l) then return nil, "Auth failed. Dovecot communications error"; end local parts = string.gmatch(l, "[^\t]+"); -- Check response local status = parts(); local resp_id = tonumber(parts()); if (resp_id ~= provider.request_id) then log("warn", "dovecot response_id(%s) doesn't match request_id(%s)", resp_id, provider.request_id); provider:close(); return nil, "Auth failed. Dovecot communications error"; end return status, parts; end function provider.test_password(username, password) log("debug", "test password '%s' for user %s at host %s", password, username, module.host); local status, extra = provider:send_auth_request(username, password); if (status == "OK") then log("info", "login ok for '%s'", username); return true; else log("info", "login failed for '%s'", username); return nil, "Auth failed. Invalid username or password."; end end function provider.get_password(username) return nil, "Cannot get_password in dovecot backend."; end function provider.set_password(username, password) return nil, "Cannot set_password in dovecot backend."; end function provider.user_exists(username) log("debug", "user_exists for user %s at host %s", username, module.host); -- Send a request. If the response (FAIL) contains an extra -- parameter like user=<username> then it exists. local status, extra = provider:send_auth_request(username, ""); local param = extra(); while (param) do parts = string.gmatch(param, "[^=]+"); name = parts(); value = parts(); if (name == "user") then log("info", "user '%s' exists", username); return true; end param = extra(); end log("info", "user '%s' does not exists (or dovecot didn't send user=<username> parameter)", username); return false; end function provider.create_user(username, password) return nil, "Cannot create_user in dovecot backend."; end function provider.get_sasl_handler() local realm = module:get_option("sasl_realm") or module.host; local getpass_authentication_profile = { plain_test = function(sasl, username, password, realm) local prepped_username = nodeprep(username); if not prepped_username then log("debug", "NODEprep failed on username: %s", username); return "", nil; end return usermanager.test_password(prepped_username, realm, password), true; end }; return new_sasl(realm, getpass_authentication_profile); end return provider; end module:add_item("auth-provider", new_default_provider(module.host));
-- Dovecot authentication backend for Prosody -- -- Copyright (C) 2010 Javier Torres -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- local socket_unix = require "socket.unix"; local datamanager = require "util.datamanager"; local usermanager = require "core.usermanager"; local log = require "util.logger".init("auth_dovecot"); local new_sasl = require "util.sasl".new; local nodeprep = require "util.encodings".stringprep.nodeprep; local base64 = require "util.encodings".base64; local pposix = require "util.pposix"; local prosody = prosody; local socket_path = module:get_option_string("dovecot_auth_socket", "/var/run/dovecot/auth-login"); function new_provider(host) local provider = { name = "dovecot", request_id = 0 }; log("debug", "initializing dovecot authentication provider for host '%s'", host); local conn; -- Closes the socket function provider.close(self) if conn then conn:close(); conn = nil; end end -- The following connects to a new socket and send the handshake function provider.connect(self) -- Destroy old socket provider:close(); conn = socket.unix(); -- Create a connection to dovecot socket log("debug", "connecting to dovecot socket at '%s'", socket_path); local ok, err = conn:connect(socket_path); if not ok then log("error", "error connecting to dovecot socket at '%s'. error was '%s'. check permissions", socket_path, err); provider:close(); return false; end -- Send our handshake local pid = pposix.getpid(); log("debug", "sending handshake to dovecot. version 1.1, cpid '%d'", pid); if not provider:send("VERSION\t1\t1\n") then return false end if not provider:send("CPID\t" .. pid .. "\n") then return false end -- Parse Dovecot's handshake local done = false; while (not done) do local line = provider:receive(); if not line then return false; end log("debug", "dovecot handshake: '%s'", line); local parts = line:gmatch("[^\t]+"); local first = parts(); if first == "VERSION" then -- Version should be 1.1 local major_version = parts(); if major_version ~= "1" then log("error", "dovecot server version is not 1.x. it is %s.x", major_version); provider:close(); return false; end elseif first == "MECH" then -- Mechanisms should include PLAIN local ok = false; for part in parts do if part == "PLAIN" then ok = true; end end if not ok then log("warn", "server doesn't support PLAIN mechanism. It supports '%s'", line); provider:close(); return false; end elseif first == "DONE" then done = true; end end return true; end -- Wrapper for send(). Handles errors function provider.send(self, data) local ok, err = conn:send(data); if not ok then log("error", "error sending '%s' to dovecot. error was '%s'", data, err); provider:close(); return false; end return true; end -- Wrapper for receive(). Handles errors function provider.receive(self) local line, err = conn:receive(); if not line then log("error", "error receiving data from dovecot. error was '%s'", err); provider:close(); return false; end return line; end function provider.send_auth_request(self, username, password) if not conn then if not provider:connect() then return nil, "Auth failed. Dovecot communications error"; end end -- Send auth data username = username .. "@" .. module.host; -- FIXME: this is actually a hack for my server local b64 = base64.encode(username .. "\0" .. username .. "\0" .. password); provider.request_id = provider.request_id + 1 % 4294967296 local msg = "AUTH\t" .. provider.request_id .. "\tPLAIN\tservice=XMPP\tresp=" .. b64; log("debug", "sending auth request for '%s' with password '%s': '%s'", username, password, msg); if not provider:send(msg .. "\n") then return nil, "Auth failed. Dovecot communications error"; end -- Get response local line = provider:receive(); log("debug", "got auth response: '%s'", line); if not line then return nil, "Auth failed. Dovecot communications error"; end local parts = line:gmatch("[^\t]+"); -- Check response local status = parts(); local resp_id = tonumber(parts()); if resp_id ~= provider.request_id then log("warn", "dovecot response_id(%s) doesn't match request_id(%s)", resp_id, provider.request_id); provider:close(); return nil, "Auth failed. Dovecot communications error"; end return status, parts; end function provider.test_password(username, password) log("debug", "test password '%s' for user %s at host %s", password, username, module.host); local status, extra = provider:send_auth_request(username, password); if status == "OK" then log("info", "login ok for '%s'", username); return true; else log("info", "login failed for '%s'", username); return nil, "Auth failed. Invalid username or password."; end end function provider.get_password(username) return nil, "Cannot get_password in dovecot backend."; end function provider.set_password(username, password) return nil, "Cannot set_password in dovecot backend."; end function provider.user_exists(username) log("debug", "user_exists for user %s at host %s", username, module.host); -- Send a request. If the response (FAIL) contains an extra -- parameter like user=<username> then it exists. local status, extra = provider:send_auth_request(username, ""); local param = extra(); while param do local parts = param:gmatch("[^=]+"); local name = parts(); local value = parts(); if name == "user" then log("debug", "user '%s' exists", username); return true; end param = extra(); end log("debug", "user '%s' does not exists (or dovecot didn't send user=<username> parameter)", username); return false; end function provider.create_user(username, password) return nil, "Cannot create_user in dovecot backend."; end function provider.get_sasl_handler() local realm = module:get_option("sasl_realm") or module.host; local getpass_authentication_profile = { plain_test = function(sasl, username, password, realm) local prepped_username = nodeprep(username); if not prepped_username then log("debug", "NODEprep failed on username: %s", username); return "", nil; end return usermanager.test_password(prepped_username, realm, password), true; end }; return new_sasl(realm, getpass_authentication_profile); end return provider; end module:add_item("auth-provider", new_provider(module.host));
mod_auth_dovecot: Fix various global variable sets/gets, log levels, unclear variable names and change coding style to match more closely the rest of the Prosody code.
mod_auth_dovecot: Fix various global variable sets/gets, log levels, unclear variable names and change coding style to match more closely the rest of the Prosody code.
Lua
mit
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
fb4a7eef4f3e8be9ea6360d833c3fad5b72b5264
src/cosy/platform/dummy.lua
src/cosy/platform/dummy.lua
local _ = require "cosy.util.string" local ignore = require "cosy.util.ignore" local logging = require "logging" logging.console = require "logging.console" local logger = logging.console "%level %message\n" local Platform = {} Platform.__index = Platform function Platform:log (message) ignore (self) logger:debug (message) end function Platform:info (message) ignore (self) logger:info (message) end function Platform:warn (message) ignore (self) logger:warn (message) end function Platform:error (message) ignore (self) logger:error (message) end function Platform:send (message) end -- Cosy.models [url] = { -- [VALUE] = <model> -- username = ... -- password = ... -- resource = ... -- editor = ... -- editor.token = ... -- } -- function Platform.new (meta) return setmetatable ({ meta = meta, }, Platform) end function Platform:close () end local Tags = require "cosy.tag" local TYPE = Tags.TYPE local INSTANCE = Tags.INSTANCE local VISIBLE = Tags.VISIBLE local Algorithm = require "cosy.algorithm" local function visible_types (x) return Algorithm.filter (x, function (d) return d [TYPE] () == true and d [VISIBLE] () == true end) end local function visible_instances (x) return Algorithm.filter (x, function (d) return d [INSTANCE] () == true and d [VISIBLE] () == true end) end function instantiate (target_type, data) end function create (source, link_type, target_type, data) end function delete (target) end return Platform
local _ = require "cosy.util.string" local ignore = require "cosy.util.ignore" local logging = require "logging" logging.console = require "logging.console" local logger = logging.console "%level %message\n" local Platform = {} Platform.__index = Platform function Platform:log (message) ignore (self) logger:debug (message) end function Platform:info (message) ignore (self) logger:info (message) end function Platform:warn (message) ignore (self) logger:warn (message) end function Platform:error (message) ignore (self) logger:error (message) end function Platform:send (message) ignore (self, message) end function Platform.new (meta) return setmetatable ({ meta = meta, }, Platform) end function Platform:close () ignore (self) end return Platform
Fix dummy platform.
Fix dummy platform.
Lua
mit
CosyVerif/library,CosyVerif/library,CosyVerif/library
5d80e0d16221099e6b7ea949f47bdb950d9b973d
test/dump.lua
test/dump.lua
local ipairs = ipairs local pairs = pairs local tostring = tostring local type = type local format = string.format local huge = 1/0 local tiny = -1/0 local function dump(v) local builder = {} local i = 1 local depth = 0 local depth8 = 1 local view = 1 local usestack local vars = {'v1', 'v2', 'v3', 'v4', 'v5', 'v6', 'v7', 'v8', 'v1'} local vars2 = {'v1[', 'v2[', 'v3[', 'v4[', 'v5[', 'v6[', 'v7[', 'v8['} local var = 'v1' local nextvar = 'v2' local var2 = 'v1[' local nextvar2 = 'v2[' local function incdepth() depth = depth+1 if depth > 1 then depth8 = depth8+1 if depth8 > 8 then depth8 = 0 end var = nextvar nextvar = vars[depth8+1] var2 = vars2[depth8] if depth >= view+8 then usestack = true view = view+1 builder[i] = 'stack[' builder[i+1] = depth-8 builder[i+2] = ']=' builder[i+3] = var builder[i+4] = '\n' i = i+5 end end end local function decdepth() depth = depth-1 if depth > 0 then depth8 = depth8-1 if depth8 < 1 then depth8 = 8 end nextvar = var var = vars[depth8] nextvar2 = var2 var2 = vars2[depth8] if depth < view then view = view-1 builder[i] = var builder[i+1] = '=stack[' builder[i+2] = depth builder[i+3] = ']\n' i = i+4 end end end local visited = {} local tablefun, tbl local function tableelem(k, v) do local vt = type(v) if vt ~= 'table' then local e = tbl[vt](v) builder[i] = var2 builder[i+1] = k builder[i+2] = ']=' builder[i+3] = e builder[i+4] = '\n' i = i+5 return end end do local olddepth = visited[v] if olddepth then builder[i] = var2 builder[i+1] = k builder[i+2] = ']=' if olddepth >= view then builder[i+3] = vars[olddepth%8] else builder[i+3] = 'stack['..olddepth..']' end builder[i+4] = '\n' i = i+5 return end end do local oldvar2 = var2 incdepth() visited[v] = depth if kt == nextvar then builder[i] = 'vtmp={}\n' builder[i+1] = oldvar2 builder[i+2] = k builder[i+3] = ']=vtmp\n' builder[i+4] = var builder[i+5] = '=vtmp\n' i = i+6 else builder[i] = var builder[i+1] = '={}\n' builder[i+2] = oldvar2 builder[i+3] = k builder[i+4] = ']=' builder[i+5] = var builder[i+6] = '\n' i = i+7 end end tablefun(v) visited[v] = nil decdepth() end function tablefun(o) local l = 0 for j, v in ipairs(o) do l = j tableelem(j, v) end for k, v in pairs(o) do local kt = type(k) if kt ~= 'number' or k < 1 or k > l then k = tbl[kt](k) tableelem(k, v) end end end tbl = { boolean = tostring, table = function(o) do local olddepth = visited[o] if olddepth then if olddepth >= view then return vars[olddepth%8] else return 'stack['..olddepth..']' end end end incdepth() visited[o] = depth builder[i] = var builder[i+1] = '={}\n' i = i+2 tablefun(o) visited[o] = nil decdepth() return nextvar end, string = function(s) return format('%q', s) end, number = function(n) if tiny < n and n < huge then return format('%.17g', n) elseif n == huge then return '1/0' elseif n == tiny then return '-1/0' else return '0/0' end end, __index = function(_) error("illegal val") end } setmetatable(tbl, tbl) builder[i] = 'local ' i = i+1 for j = 1, 8 do builder[i] = vars[j] builder[i+1] = ',' i = i+2 end builder[i] = 'vtmp\n' i = i+1 local stackdecl = i builder[i] = "" i = i+1 local e = tbl[type(v)](v) builder[i] = 'return ' builder[i+1] = e i = i+2 if usestack then builder[stackdecl] = 'local stack={}\n' i = i+1 end return table.concat(builder) end return dump
local ipairs = ipairs local pairs = pairs local tostring = tostring local type = type local format = string.format local huge = 1/0 local tiny = -1/0 local function dump(v) local builder = {} local i = 1 local depth = 0 local depth8 = 0 local view = 1 local usestack local vars = {'v1', 'v2', 'v3', 'v4', 'v5', 'v6', 'v7', 'v8', 'v1'} local vars2 = {'v1[', 'v2[', 'v3[', 'v4[', 'v5[', 'v6[', 'v7[', 'v8['} local var = 'v1' local nextvar = 'v1' local var2 = 'v1[' local nextvar2 = 'v1[' local function incdepth() depth = depth+1 depth8 = depth8+1 if depth8 > 8 then depth8 = 0 end var = nextvar nextvar = vars[depth8+1] var2 = vars2[depth8] if depth >= view+8 then usestack = true view = view+1 builder[i] = 'stack[' builder[i+1] = depth-8 builder[i+2] = ']=' builder[i+3] = var builder[i+4] = '\n' i = i+5 end end local function decdepth() depth = depth-1 depth8 = depth8-1 if depth8 < 1 then depth8 = 8 end nextvar = var var = vars[depth8] nextvar2 = var2 var2 = vars2[depth8] if depth < view and depth > 0 then view = view-1 builder[i] = var builder[i+1] = '=stack[' builder[i+2] = depth builder[i+3] = ']\n' i = i+4 end end local visited = {} local tablefun, tbl local function tableelem(k, v) do local vt = type(v) if vt ~= 'table' then local e = tbl[vt](v) builder[i] = var2 builder[i+1] = k builder[i+2] = ']=' builder[i+3] = e builder[i+4] = '\n' i = i+5 return end end do local olddepth = visited[v] if olddepth then builder[i] = var2 builder[i+1] = k builder[i+2] = ']=' if olddepth >= view then builder[i+3] = vars[olddepth%8] else builder[i+3] = 'stack['..olddepth..']' end builder[i+4] = '\n' i = i+5 return end end do local oldvar2 = var2 incdepth() visited[v] = depth if kt == nextvar then builder[i] = 'vtmp={}\n' builder[i+1] = oldvar2 builder[i+2] = k builder[i+3] = ']=vtmp\n' builder[i+4] = var builder[i+5] = '=vtmp\n' i = i+6 else builder[i] = var builder[i+1] = '={}\n' builder[i+2] = oldvar2 builder[i+3] = k builder[i+4] = ']=' builder[i+5] = var builder[i+6] = '\n' i = i+7 end end tablefun(v) visited[v] = nil decdepth() end function tablefun(o) local l = 0 for j, v in ipairs(o) do l = j tableelem(j, v) end for k, v in pairs(o) do local kt = type(k) if kt ~= 'number' or k < 1 or k > l then k = tbl[kt](k) tableelem(k, v) end end end tbl = { boolean = tostring, table = function(o) do local olddepth = visited[o] if olddepth then if olddepth >= view then return vars[olddepth%8] else return 'stack['..olddepth..']' end end end incdepth() visited[o] = depth builder[i] = var builder[i+1] = '={}\n' i = i+2 tablefun(o) visited[o] = nil decdepth() return nextvar end, string = function(s) return format('%q', s) end, number = function(n) if tiny < n and n < huge then return format('%.17g', n) elseif n == huge then return '1/0' elseif n == tiny then return '-1/0' else return '0/0' end end, __index = function(_) error("illegal val") end } setmetatable(tbl, tbl) builder[i] = 'local ' i = i+1 for j = 1, 8 do builder[i] = vars[j] builder[i+1] = ',' i = i+2 end builder[i] = 'vtmp\n' i = i+1 local stackdecl = i builder[i] = "" i = i+1 local e = tbl[type(v)](v) builder[i] = 'return ' builder[i+1] = e i = i+2 if usestack then builder[stackdecl] = 'local stack={}\n' i = i+1 end return table.concat(builder) end return dump
fix toplevel obj
fix toplevel obj
Lua
mit
tst2005/lunajson,grafi-tt/lunajson,tst2005/lunajson,grafi-tt/lunajson,csteddy/lunajson,bigcrush/lunajson,bigcrush/lunajson,csteddy/lunajson,grafi-tt/lunajson
b1f6e740a3e4af64e0217880b0275b3f28cf9855
modules/console.lua
modules/console.lua
--- Utility functions to output text to the console (i.e., default chat frame). local A, L = unpack(select(2, ...)) local M = A:NewModule("console") A.console = M local PREFIX = A.util:HighlightAddon(A.NAME)..":" local date, format, print, select, strfind, tinsert, tostring = date, format, print, select, strfind, tinsert, tostring local tconcat = table.concat function M:Print(...) print(PREFIX, ...) end function M:Printf(...) print(PREFIX, format(...)) end function M:Errorf(module, ...) print(format("%s: internal error in %s module:", A.util:HighlightAddon(A.NAME.." v"..A.VERSION_PACKAGED)), format(...)) end local function isDebuggingModule(module) return not module or A.DEBUG_MODULES == "*" or strfind(A.DEBUG_MODULES, module:GetName()) end function M:Debug(module, ...) if isDebuggingModule(module) then print("|cff999999["..date("%H:%M:%S").." "..tostring(module or A.NAME).."]|r|cffffcc99", ..., "|r") end end function M:Debugf(module, ...) if isDebuggingModule(module) then print("|cff999999["..date("%H:%M:%S").." "..tostring(module or A.NAME).."]|r|cffffcc99", format(...), "|r") end end function M:DebugMore(module, ...) if isDebuggingModule(module) then print("|cffffcc99", ..., "|r") end end function M:DebugDump(module, ...) local t = {} for i = 1, select("#", ...) do tinsert(t, tostring(select(i, ...))) end M:Debug(module, tconcat(t, ", ")) end
--- Utility functions to output text to the console (i.e., default chat frame). local A, L = unpack(select(2, ...)) local M = A:NewModule("console") A.console = M local PREFIX = A.util:HighlightAddon(A.NAME)..":" local date, format, print, select, strfind, tinsert, tostring, type = date, format, print, select, strfind, tinsert, tostring, type local tconcat = table.concat function M:Print(...) print(PREFIX, ...) end function M:Printf(...) print(PREFIX, format(...)) end function M:Errorf(module, ...) local message if type(module) == "string" then message = format(module, ...) module = false else message = format(...) end module = module and module.GetName and format(" in %s module", module:GetName()) or "" print(format("%s: |cffff3333internal error%s:|r", A.util:HighlightAddon(A.NAME.." v"..A.VERSION_PACKAGED), module), message) end local function isDebuggingModule(module) return not module or A.DEBUG_MODULES == "*" or strfind(A.DEBUG_MODULES, module:GetName()) end function M:Debug(module, ...) if isDebuggingModule(module) then print("|cff999999["..date("%H:%M:%S").." "..tostring(module or A.NAME).."]|r|cffffcc99", ..., "|r") end end function M:Debugf(module, ...) if isDebuggingModule(module) then print("|cff999999["..date("%H:%M:%S").." "..tostring(module or A.NAME).."]|r|cffffcc99", format(...), "|r") end end function M:DebugMore(module, ...) if isDebuggingModule(module) then print("|cffffcc99", ..., "|r") end end function M:DebugDump(module, ...) local t = {} for i = 1, select("#", ...) do tinsert(t, tostring(select(i, ...))) end M:Debug(module, tconcat(t, ", ")) end
Fix error in console:Errorf
Fix error in console:Errorf
Lua
mit
bencvt/FixGroups
226c7da1b473ace716b298fb4f7185c3e1083112
game/scripts/vscripts/util/ability.lua
game/scripts/vscripts/util/ability.lua
function CDOTABaseAbility:HasBehavior(behavior) local abilityBehavior = tonumber(tostring(self:GetBehavior())) return bit.band(abilityBehavior, behavior) == behavior end function AbilityHasBehaviorByName(ability_name, behaviorString) local AbilityBehavior = GetKeyValue(ability_name, "AbilityBehavior") if AbilityBehavior then local AbilityBehaviors = string.split(AbilityBehavior, " | ") return table.includes(AbilityBehaviors, behaviorString) end return false end function CDOTABaseAbility:PerformPrecastActions() if self:IsCooldownReady() and self:IsOwnersManaEnough() then self:PayManaCost() self:AutoStartCooldown() --self:UseResources(true, true, true) -- not works with items? return true end return false end function CDOTABaseAbility:GetMulticastType() if self:IsToggle() then return MULTICAST_TYPE_NONE end if self:HasBehavior(DOTA_ABILITY_BEHAVIOR_PASSIVE) then return MULTICAST_TYPE_NONE end return MULTICAST_ABILITIES[self:GetAbilityName()] or MULTICAST_TYPE_DIFFERENT end function CDOTABaseAbility:ClearFalseInnateModifiers() if self:GetKeyValue("HasInnateModifiers") ~= 1 then for _,v in ipairs(self:GetCaster():FindAllModifiers()) do if v:GetAbility() and v:GetAbility() == self then v:Destroy() end end end end function CDOTABaseAbility:GetReducedCooldown() local biggestReduction = 0 local unit = self:GetCaster() for k,v in pairs(COOLDOWN_REDUCTION_MODIFIERS) do if unit:HasModifier(k) then biggestReduction = math.max(biggestReduction, type(v) == "function" and v(unit) or v) end end return self:GetCooldown(math.max(self:GetLevel() - 1, 1)) * (100 - biggestReduction) * 0.01 end function CDOTABaseAbility:AutoStartCooldown() self:StartCooldown(self:GetReducedCooldown()) end
function CDOTABaseAbility:HasBehavior(behavior) local abilityBehavior = tonumber(tostring(self:GetBehavior())) return bit.band(abilityBehavior, behavior) == behavior end function AbilityHasBehaviorByName(ability_name, behaviorString) local AbilityBehavior = GetKeyValue(ability_name, "AbilityBehavior") if AbilityBehavior then local AbilityBehaviors = string.split(AbilityBehavior, " | ") return table.includes(AbilityBehaviors, behaviorString) end return false end function CDOTABaseAbility:PerformPrecastActions() if self:IsCooldownReady() and self:IsOwnersManaEnough() then self:PayManaCost() self:AutoStartCooldown() --self:UseResources(true, true, true) -- not works with items? return true end return false end function CDOTABaseAbility:GetMulticastType() local name = self:GetAbilityName() if MULTICAST_ABILITIES[name] then return MULTICAST_ABILITIES[name] end if self:IsToggle() then return MULTICAST_TYPE_NONE end if self:HasBehavior(DOTA_ABILITY_BEHAVIOR_PASSIVE) then return MULTICAST_TYPE_NONE end return self:HasBehavior(DOTA_ABILITY_BEHAVIOR_UNIT_TARGET) and MULTICAST_TYPE_DIFFERENT or MULTICAST_TYPE_SAME end function CDOTABaseAbility:ClearFalseInnateModifiers() if self:GetKeyValue("HasInnateModifiers") ~= 1 then for _,v in ipairs(self:GetCaster():FindAllModifiers()) do if v:GetAbility() and v:GetAbility() == self then v:Destroy() end end end end function CDOTABaseAbility:GetReducedCooldown() local biggestReduction = 0 local unit = self:GetCaster() for k,v in pairs(COOLDOWN_REDUCTION_MODIFIERS) do if unit:HasModifier(k) then biggestReduction = math.max(biggestReduction, type(v) == "function" and v(unit) or v) end end return self:GetCooldown(math.max(self:GetLevel() - 1, 1)) * (100 - biggestReduction) * 0.01 end function CDOTABaseAbility:AutoStartCooldown() self:StartCooldown(self:GetReducedCooldown()) end
fix(ogre_magi): multicast works incorrectly on not unit target abilities
fix(ogre_magi): multicast works incorrectly on not unit target abilities
Lua
mit
ark120202/aabs
43fe9760d08cd1cc0ae95bcf5047985b4277df65
lua/utils.lua
lua/utils.lua
-- -*- mode: lua; coding: utf-8 -*- function printTable(table) for index, value in ipairs(table) do io.write(index) io.write(": ") print(value) end end function stringToLines(str, maxColumns, indent, indent1) local indent = indent or "" local indent1 = indent1 or indent local maxColumns = maxColumns or (platform.display.width / platform.display.fontWidth) local lines = {} local currentLine = indent1 local firstLine = true local newlineChunks = {} str:gsub("([^\n]+)(\n*)", function (chunk, newlines) table.insert(newlineChunks, chunk) for i = 1, #newlines - 1, 1 do table.insert(newlineChunks, "") end end) for index, chunk in pairs(newlineChunks) do chunk:gsub("(%s*)()(%S+)()", function (space, start, word, endd) if #currentLine + #space + #word > maxColumns then if firstLine then firstLine = false else table.insert(lines, currentLine) end currentLine = indent..word while #currentLine > maxColumns do table.insert(lines, currentLine:sub(0, maxColumns)) currentLine = currentLine:sub(maxColumns + 1) end else currentLine = currentLine..space..word end end) table.insert(lines, currentLine) currentLine = indent end return lines end function displayMultilineText(text, keyMap, atColumn, atRow, windowColumns, windowRows) local atRow = atRow or 1 local atColumn = atColumn or 1 local fontWidth = platform.display.fontWidth local fontHeight = platform.display.fontHeight local windowColumns = windowColumns or (platform.display.width / fontWidth) local windowRows = windowRows or (platform.display.height / fontHeight) local keyMap = keyMap or {} local needsRedraw = true local lines = stringToLines(text, windowColumns) local currentLineOffset = 0 while true do platform.display.clear((atColumn - 1) * fontWidth, (atRow - 1) * fontHeight, windowColumns * fontWidth, windowRows * fontHeight) local currentLineIndex = currentLineOffset local currentScreenRow = atRow while currentScreenRow - atRow < windowRows do if currentLineIndex < #lines then local line = lines[currentLineIndex + 1] platform.display.printXY(atColumn, currentScreenRow, line) --platform.display.print(string.rep(' ', windowColumns - #line)) else --platform.display.printXY(atColumn, currentScreenRow, string.rep(' ', windowColumns)) end currentScreenRow = currentScreenRow + 1 currentLineIndex = currentLineIndex + 1 end needsRedraw = true if platform.keyboard.hasKeyInBuffer() then local key = platform.keyboard.getKey() if key == platform.keyboard.keyDown then if currentLineOffset < #lines - windowRows then currentLineOffset = currentLineOffset + 1 end elseif key == platform.keyboard.keyUp then if currentLineOffset > 0 then currentLineOffset = currentLineOffset - 1 end elseif key == platform.keyboard.keyCancel then break elseif keyMap[key] then keyMap[key]() else needsRedraw = false end end waitForEvents() end end function displayMenu(entries) local keyMap = {} local text = nil for index, entry in ipairs(entries) do local keyCode = entry.keyCode local trunk = entry.trunk local title = entry.title if not keyCode or not trunk or not title then error(string.format("displayMenu called with broken entry: %s, %s, %s", title, keyCode, trunk)) end keyMap[keyCode] = trunk if text then text = text.."\n"..title else text = title end end displayMultilineText(text, keyMap) end
-- -*- mode: lua; coding: utf-8 -*- function printTable(table) for index, value in ipairs(table) do io.write(index) io.write(": ") print(value) end end function stringToLines(str, maxColumns, indent, indent1) local indent = indent or "" local indent1 = indent1 or indent local maxColumns = maxColumns or (platform.display.width / platform.display.fontWidth) local lines = {} local currentLine = indent1 local firstLine = true local newlineChunks = {} str:gsub("([^\n]+)(\n*)", function (chunk, newlines) table.insert(newlineChunks, chunk) for i = 1, #newlines - 1, 1 do table.insert(newlineChunks, "") end end) for index, chunk in pairs(newlineChunks) do chunk:gsub("(%s*)()(%S+)()", function (space, start, word, endd) if #currentLine + #space + #word > maxColumns then if not firstLine then table.insert(lines, currentLine) end currentLine = indent..word while #currentLine > maxColumns do table.insert(lines, currentLine:sub(0, maxColumns)) currentLine = currentLine:sub(maxColumns + 1) end else currentLine = currentLine..space..word end firstLine = false end) table.insert(lines, currentLine) currentLine = indent end return lines end function displayMultilineText(text, keyMap, atColumn, atRow, windowColumns, windowRows) local atRow = atRow or 1 local atColumn = atColumn or 1 local fontWidth = platform.display.fontWidth local fontHeight = platform.display.fontHeight local windowColumns = windowColumns or (platform.display.width / fontWidth) local windowRows = windowRows or (platform.display.height / fontHeight) local keyMap = keyMap or {} local needsRedraw = true local lines = stringToLines(text, windowColumns) local currentLineOffset = 0 while true do platform.display.clear((atColumn - 1) * fontWidth, (atRow - 1) * fontHeight, windowColumns * fontWidth, windowRows * fontHeight) local currentLineIndex = currentLineOffset local currentScreenRow = atRow while currentScreenRow - atRow < windowRows do if currentLineIndex < #lines then local line = lines[currentLineIndex + 1] platform.display.printXY(atColumn, currentScreenRow, line) --platform.display.print(string.rep(' ', windowColumns - #line)) else --platform.display.printXY(atColumn, currentScreenRow, string.rep(' ', windowColumns)) end currentScreenRow = currentScreenRow + 1 currentLineIndex = currentLineIndex + 1 end needsRedraw = true if platform.keyboard.hasKeyInBuffer() then local key = platform.keyboard.getKey() if key == platform.keyboard.keyDown then if currentLineOffset < #lines - windowRows then currentLineOffset = currentLineOffset + 1 end elseif key == platform.keyboard.keyUp then if currentLineOffset > 0 then currentLineOffset = currentLineOffset - 1 end elseif key == platform.keyboard.keyCancel then break elseif keyMap[key] then keyMap[key]() else needsRedraw = false end end waitForEvents() end end function displayMenu(entries) local keyMap = {} local text = nil for index, entry in ipairs(entries) do local keyCode = entry.keyCode local trunk = entry.trunk local title = entry.title if not keyCode or not trunk or not title then error(string.format("displayMenu called with broken entry: %s, %s, %s", title, keyCode, trunk)) end keyMap[keyCode] = trunk if text then text = text.."\n"..title else text = title end end displayMultilineText(text, keyMap) end
fix line wrapping
fix line wrapping Ignore-this: 718f1d9fc1d3a68072c8a92bf1dd8f1 darcs-hash:20120614101314-6b9e8-54e4b7aabc54c5e3832f79e5b8f01fcf8ee0edc5
Lua
bsd-3-clause
attila-lendvai/moonboots
68c2c8fe22e1388aff56b5b1bb52e939c7a9293b
examples/httpd.lua
examples/httpd.lua
package.path = package.path .. ";../src/?.lua" require "HttpServer"package.path = package.path .. ";../src/?.lua" require "HttpServer" require "VirtualHost" uv = HttpMisc.backend HttpMisc.setupSignals() -- to make sure GC runs htdocs = VirtualHost:new(uv.cwd() .. "/htdocs") :logRequestsTo(HttpLogger:new()) server = HttpServer:new(8080, function(req, res) htdocs:handle(req, res) if res:handled() then return end res:displayError(404, "<h1>Not Found</h1>") end) print "Visit http://127.0.0.1:8080 to see the magic." uv.run() require "VirtualHost" uv = HttpMisc.backend HttpMisc.setupSignals() -- to make sure GC runs htdocs = VirtualHost:new(uv.cwd() .. "/htdocs") :logRequestsTo(HttpLogger:new()) server = HttpServer:new(8080, function(req, res) htdocs:handle(req, res) if res:handled() then return end res:displayError(404, "<h1>Not Found</h1>") end) print "Visit http://127.0.0.1:8080 to see the magic." uv.run()
package.path = package.path .. ";../src/?.lua" require "HttpServer" require "VirtualHost" uv = HttpMisc.backend HttpMisc.setupSignals() -- to make sure GC runs htdocs = VirtualHost:new(uv.cwd() .. "/htdocs") :logRequestsTo(HttpLogger:new()) server = HttpServer:new(8080, function(req, res) htdocs:handle(req, res) if res:handled() then return end res:displayError(404, "<h1>Not Found</h1>") end) print "Visit http://127.0.0.1:8080 to see the magic." uv.run() require "VirtualHost" uv = HttpMisc.backend HttpMisc.setupSignals() -- to make sure GC runs htdocs = VirtualHost:new(uv.cwd() .. "/htdocs") :logRequestsTo(HttpLogger:new()) server = HttpServer:new(8080, function(req, res) htdocs:handle(req, res) if res:handled() then return end res:displayError(404, "<h1>Not Found</h1>") end) print "Visit http://127.0.0.1:8080 to see the magic." uv.run()
Fix example.
Fix example.
Lua
mit
imzyxwvu/objective-and-sync,imzyxwvu/objective-and-sync
32ad9ce6b0760eb7938b4f9eb4c2767eea4b0ef8
cache.lua
cache.lua
local cache = {} local _cache = {} local CACHE_PATH = love.filesystem.getSaveDirectory().."/cache" -- cache format -- TS\tFLAGS\tPATH\n function cache.load() log.info("Loading cache...") for line in io.lines(CACHE_PATH) do local ts,flags,path = line:match("(%d+)\t(%w*)\t(.*)") _cache[path] = { ts = tonumber(ts), flags = {} } for flag in flags:gmatch("[^,]+") do local k,v = flag:match("^([^:]+):(.*)") if k then _cache[path].flags[k] = v else _cache[path].flags[flag] = true end end end end function cache.save() log.info("Saving cache...") local fd = io.open(CACHE_PATH..".tmp", "wb") for path,data in pairs(_cache) do local flags = {} for flag in pairs(data.flags) do table.insert(flags, flag) end fd:write("%d\t%s\t%s\n" % { data.ts, table.concat(flags, ":"), path }) end fd:close() local res,err = os.remove(CACHE_PATH) if res then res,err = os.rename(CACHE_PATH..".tmp", CACHE_PATH) end if not res then log.error("Cache save failed: %s", tostring(err)) end end function cache.get(path) if not _cache[path] then _cache[path] = { ts = 0, flags = {} } end return _cache[path] end function cache.set(path, data) _cache[path] = data end io.open(CACHE_PATH, "a"):close() -- create cache file if it doesn't already exist cache.load() return cache
local cache = {} local _cache = {} local CACHE_PATH = love.filesystem.getSaveDirectory().."/cache" -- cache format -- TS\tFLAGS\tPATH\n function cache.load() log.info("Loading cache...") for line in io.lines(CACHE_PATH) do local ts,flags,path = line:match("(%d+)\t(%w*)\t(.*)") _cache[path] = { ts = tonumber(ts), flags = {} } for flag in flags:gmatch("[^;]+") do local k,v = flag:match("^([^=]+)=(.*)") if k then _cache[path].flags[k] = v else _cache[path].flags[flag] = true end end end end function cache.save() log.info("Saving cache...") local fd = io.open(CACHE_PATH..".tmp", "wb") for path,data in pairs(_cache) do local flags = {} for flag,value in pairs(data.flags) do if value == false then -- skip elseif value == true then table.insert(flags, flag) else table.insert(flags, flag.."="..tostring(value)) end end fd:write("%d\t%s\t%s\n" % { data.ts, table.concat(flags, ";"), path }) end fd:close() local res,err = os.remove(CACHE_PATH) if res then res,err = os.rename(CACHE_PATH..".tmp", CACHE_PATH) end if not res then log.error("Cache save failed: %s", tostring(err)) end end function cache.get(path) if not _cache[path] then _cache[path] = { ts = 0, flags = {} } end return _cache[path] end function cache.set(path, data) _cache[path] = data end io.open(CACHE_PATH, "a"):close() -- create cache file if it doesn't already exist cache.load() return cache
Fix cache reading and writing
Fix cache reading and writing We can get away with this for now because "seen" is the only supported flag. - separate flags with ; rather than : - store values as key=value rather than key:value - do not store keys where the value is false
Lua
mit
ToxicFrog/EmuFun
bbe1ab3d62220922139d4ed78e70f2ef90c8427c
src/npge/model/BlockSet.lua
src/npge/model/BlockSet.lua
local BlockSet = {} local BlockSet_mt = {} local bs_mt = {} BlockSet_mt.__index = BlockSet_mt bs_mt.__index = bs_mt local is_prepangenome = function(seq2fragments) for seq, fragments in pairs(seq2fragments) do local lengths_sum = 0 local prev for _, fragment in ipairs(fragments) do lengths_sum = lengths_sum + fragment:length() if prev and prev:common(fragment) > 0 then return false end prev = fragment end if lengths_sum ~= seq:length() then return false end end return true end local parent_or_fragment = function(self, f) local parent = self._parent_of_parts[f] return parent or f end BlockSet_mt.__call = function(self, sequences, blocks) local name2seq = {} local seq2fragments = {} for _, sequence in ipairs(sequences) do assert(sequence:type() == 'Sequence') assert(not name2seq[sequence:name()]) name2seq[sequence:name()] = sequence seq2fragments[sequence] = {} end local parent_of_parts = {} local block_by_fragment = {} for _, block in ipairs(blocks) do for fragment in block:iter_fragments() do block_by_fragment[fragment] = block local seq = fragment:sequence() local name = seq:name() assert(name2seq[name], ("No sequence with name %q"):format(seq:name())) if not fragment:parted() then table.insert(seq2fragments[seq], fragment) else local a, b = fragment:parts() table.insert(seq2fragments[seq], a) table.insert(seq2fragments[seq], b) parent_of_parts[a] = fragment parent_of_parts[b] = fragment end end end for seq, fragments in pairs(seq2fragments) do table.sort(fragments) end local prepangenome = is_prepangenome(seq2fragments) local bs = {_name2seq=name2seq, _blocks=blocks, _seq2fragments=seq2fragments, _parent_of_parts=parent_of_parts, _block_by_fragment=block_by_fragment, _prepangenome=prepangenome} return setmetatable(bs, bs_mt) end bs_mt.type = function(self) return "BlockSet" end bs_mt.size = function(self) return #(self._blocks) end bs_mt.is_prepangenome = function(self) return self._prepangenome end bs_mt.blocks = function(self) local clone = require 'npge.util.clone' return clone.array(self._blocks) end bs_mt.iter_blocks = function(self) local it, t, index = ipairs(self._blocks) return function() index, block = it(t, index) return block end end bs_mt.fragments = function(self, sequence) local clone = require 'npge.util.clone' return clone.array_from_it(self:iter_fragments(sequence)) end bs_mt.iter_fragments = function(self, sequence) -- iterate pairs (fragment, sub-fragment) local fragments = self._seq2fragments[sequence] assert(fragments, "Sequence not in blockset") local it, t, index = ipairs(fragments) return function() index, fragment = it(t, index) local parent = parent_or_fragment(self, fragment) return parent, fragment end end bs_mt.sequences = function(self) local seqs = {} for name, seq in pairs(self._name2seq) do table.insert(seqs, seq) end return seqs end bs_mt.iter_sequences = function(self) local name, seq return function() name, seq = next(self._name2seq, name) return seq end end bs_mt.has_sequence = function(self, seq) return self._seq2fragments[seq] ~= nil end bs_mt.sequence_by_name = function(self, name) return self._name2seq[name] end bs_mt.block_by_fragment = function(self, fragment) return self._block_by_fragment[fragment] end bs_mt.overlapping_fragments = function(self, fragment) local concat_arrays = require 'npge.util.concat_arrays' local unique = require 'npge.util.unique' if fragment:parted() then local a, b = fragment:parts() return unique(concat_arrays( self:overlapping_fragments(a), self:overlapping_fragments(b))) end local seq = fragment:sequence() local fragments = self._seq2fragments[seq] assert(fragments, "Sequence not in blockset") local result = {} local add_fragment_or_parent = function(f) table.insert(result, parent_or_fragment(self, f)) end local upper = require('npge.util.binary_search').upper local index = upper(fragments, fragment) for i = index, #fragments do if fragment:common(fragments[i]) > 0 then add_fragment_or_parent(fragments[i]) else break end end for i = index - 1, 1, -1 do if fragment:common(fragments[i]) > 0 then add_fragment_or_parent(fragments[i]) else break end end return unique(result) end bs_mt.next = function(self, fragment) if fragment:parted() then local a, b = fragment:parts() local f = (a < b) and a or b return self:next(f) end local seq = fragment:sequence() local fragments = self._seq2fragments[seq] assert(fragments, "Sequence not in blockset") local lower = require('npge.util.binary_search').lower local index = lower(fragments, fragment) assert(fragments[index] == fragment) local f if index < #fragments then f = fragments[index + 1] elseif index == #fragments and seq:circular() then f = fragments[1] else return nil end return parent_or_fragment(self, f) end bs_mt.prev = function(self, fragment) if fragment:parted() then local a, b = fragment:parts() local f = (a < b) and b or a return self:prev(f) end local seq = fragment:sequence() local fragments = self._seq2fragments[seq] assert(fragments, "Sequence not in blockset") local lower = require('npge.util.binary_search').lower local index = lower(fragments, fragment) assert(fragments[index] == fragment) local f if index > 1 then f = fragments[index - 1] elseif index == 1 and seq:circular() then f = fragments[#fragments] else return nil end return parent_or_fragment(self, f) end return setmetatable(BlockSet, BlockSet_mt)
local BlockSet = {} local BlockSet_mt = {} local bs_mt = {} BlockSet_mt.__index = BlockSet_mt bs_mt.__index = bs_mt local is_prepangenome = function(seq2fragments) for seq, fragments in pairs(seq2fragments) do local lengths_sum = 0 local prev for _, fragment in ipairs(fragments) do lengths_sum = lengths_sum + fragment:length() if prev and prev:common(fragment) > 0 then return false end prev = fragment end if lengths_sum ~= seq:length() then return false end end return true end local parent_or_fragment = function(self, f) local parent = self._parent_of_parts[f] return parent or f end BlockSet_mt.__call = function(self, sequences, blocks) local name2seq = {} local seq2fragments = {} for _, sequence in ipairs(sequences) do assert(sequence:type() == 'Sequence') assert(not name2seq[sequence:name()]) name2seq[sequence:name()] = sequence seq2fragments[sequence] = {} end local parent_of_parts = {} local block_by_fragment = {} for _, block in ipairs(blocks) do for fragment in block:iter_fragments() do block_by_fragment[fragment] = block local seq = fragment:sequence() local name = seq:name() assert(name2seq[name], ("No sequence with name %q"):format(seq:name())) if not fragment:parted() then table.insert(seq2fragments[seq], fragment) else local a, b = fragment:parts() table.insert(seq2fragments[seq], a) table.insert(seq2fragments[seq], b) parent_of_parts[a] = fragment parent_of_parts[b] = fragment end end end for seq, fragments in pairs(seq2fragments) do table.sort(fragments) end local prepangenome = is_prepangenome(seq2fragments) local bs = {_name2seq=name2seq, _blocks=blocks, _seq2fragments=seq2fragments, _parent_of_parts=parent_of_parts, _block_by_fragment=block_by_fragment, _prepangenome=prepangenome} return setmetatable(bs, bs_mt) end bs_mt.type = function(self) return "BlockSet" end bs_mt.size = function(self) return #(self._blocks) end bs_mt.is_prepangenome = function(self) return self._prepangenome end bs_mt.blocks = function(self) local clone = require 'npge.util.clone' return clone.array(self._blocks) end bs_mt.iter_blocks = function(self) local it, t, index = ipairs(self._blocks) local block return function() index, block = it(t, index) return block end end bs_mt.fragments = function(self, sequence) local clone = require 'npge.util.clone' return clone.array_from_it(self:iter_fragments(sequence)) end bs_mt.iter_fragments = function(self, sequence) -- iterate pairs (fragment, sub-fragment) local fragments = self._seq2fragments[sequence] assert(fragments, "Sequence not in blockset") local it, t, index = ipairs(fragments) local fragment return function() index, fragment = it(t, index) local parent = parent_or_fragment(self, fragment) return parent, fragment end end bs_mt.sequences = function(self) local seqs = {} for name, seq in pairs(self._name2seq) do table.insert(seqs, seq) end return seqs end bs_mt.iter_sequences = function(self) local name, seq return function() name, seq = next(self._name2seq, name) return seq end end bs_mt.has_sequence = function(self, seq) return self._seq2fragments[seq] ~= nil end bs_mt.sequence_by_name = function(self, name) return self._name2seq[name] end bs_mt.block_by_fragment = function(self, fragment) return self._block_by_fragment[fragment] end bs_mt.overlapping_fragments = function(self, fragment) local concat_arrays = require 'npge.util.concat_arrays' local unique = require 'npge.util.unique' if fragment:parted() then local a, b = fragment:parts() return unique(concat_arrays( self:overlapping_fragments(a), self:overlapping_fragments(b))) end local seq = fragment:sequence() local fragments = self._seq2fragments[seq] assert(fragments, "Sequence not in blockset") local result = {} local add_fragment_or_parent = function(f) table.insert(result, parent_or_fragment(self, f)) end local upper = require('npge.util.binary_search').upper local index = upper(fragments, fragment) for i = index, #fragments do if fragment:common(fragments[i]) > 0 then add_fragment_or_parent(fragments[i]) else break end end for i = index - 1, 1, -1 do if fragment:common(fragments[i]) > 0 then add_fragment_or_parent(fragments[i]) else break end end return unique(result) end bs_mt.next = function(self, fragment) if fragment:parted() then local a, b = fragment:parts() local f = (a < b) and a or b return self:next(f) end local seq = fragment:sequence() local fragments = self._seq2fragments[seq] assert(fragments, "Sequence not in blockset") local lower = require('npge.util.binary_search').lower local index = lower(fragments, fragment) assert(fragments[index] == fragment) local f if index < #fragments then f = fragments[index + 1] elseif index == #fragments and seq:circular() then f = fragments[1] else return nil end return parent_or_fragment(self, f) end bs_mt.prev = function(self, fragment) if fragment:parted() then local a, b = fragment:parts() local f = (a < b) and b or a return self:prev(f) end local seq = fragment:sequence() local fragments = self._seq2fragments[seq] assert(fragments, "Sequence not in blockset") local lower = require('npge.util.binary_search').lower local index = lower(fragments, fragment) assert(fragments[index] == fragment) local f if index > 1 then f = fragments[index - 1] elseif index == 1 and seq:circular() then f = fragments[#fragments] else return nil end return parent_or_fragment(self, f) end return setmetatable(BlockSet, BlockSet_mt)
fix unintended global vars
fix unintended global vars
Lua
mit
starius/lua-npge,npge/lua-npge,npge/lua-npge,starius/lua-npge,starius/lua-npge,npge/lua-npge
33f2fb4957885a853ceb755a05d4ae6f6c83caa1
lua-project/src/creator/components/AnimationComponent.lua
lua-project/src/creator/components/AnimationComponent.lua
local cc = cc local DEBUG_VERBOSE = cc.DEBUG_VERBOSE local ccp = cc.p local ccsize = cc.size local ccrect = cc.rect local ComponentBase = cc.import(".ComponentBase") local AnimationComponent = cc.class("cc.Animation", ComponentBase) local _LOOP_NORMAL = 1 local _LOOP_LOOP = 2 AnimationComponent.LOOP_NORMAL = _LOOP_NORMAL AnimationComponent.LOOP_LOOP = _LOOP_LOOP local _animationCache = cc.AnimationCache:getInstance() local function _createAnimation(uuid, assets) local animation = _animationCache:getAnimation(uuid) if animation then return animation end if cc.DEBUG >= DEBUG_VERBOSE then cc.printdebug("[Assets] - [Animation] create animation %s", uuid) end local clip = assets:getAsset(uuid) clip.speed = clip.speed or 1 local delay = 1.0 / clip.sample / clip.speed animation = cc.Animation:create() animation:setDelayPerUnit(delay) for _, faval in ipairs(clip["curveData"]["comps"]["cc.Sprite"]["spriteFrame"]) do local asset = assets:getAsset(faval["value"]["__uuid__"]) local spriteFrame = assets:_createObject(asset) animation:addSpriteFrame(spriteFrame) end _animationCache:addAnimation(animation, uuid) animation.loop = clip.wrapMode return animation end function AnimationComponent:ctor(props, assets) AnimationComponent.super.ctor(self) self.props = props self._animations = {} for _, clipaval in ipairs(self.props._clips) do local animation, clip = _createAnimation(clipaval.__uuid__, assets) animation:retain() self._animations[#self._animations + 1] = animation end end function AnimationComponent:start(target) if self.props.playOnLoad then self:play(target) end end function AnimationComponent:play(target, callback) if not target.components or not target.components["cc.Sprite"] then cc.printwarn("[Animation] invalid target %s", target.__type) return end local spriteComponent = target.components["cc.Sprite"] local sprite = spriteComponent.node for _, animation in ipairs(self._animations) do local animate = cc.Animate:create(animation) if animation.loop == _LOOP_LOOP then sprite:runAction(cc.RepeatForever:create(animate)) elseif callback then sprite:runAction(cc.Sequence:create({animate, cc.CallFunc:create(callback)})) else sprite:runAction(animate) end end end function AnimationComponent:onDestroy(target) for _, animation in ipairs(self._animations) do animation:release() end self._animations = nil end return AnimationComponent
local cc = cc local DEBUG_VERBOSE = cc.DEBUG_VERBOSE local ccp = cc.p local ccsize = cc.size local ccrect = cc.rect local ComponentBase = cc.import(".ComponentBase") local AnimationComponent = cc.class("cc.Animation", ComponentBase) local _LOOP_NORMAL = 1 local _LOOP_LOOP = 2 AnimationComponent.LOOP_NORMAL = _LOOP_NORMAL AnimationComponent.LOOP_LOOP = _LOOP_LOOP local _animationCache = cc.AnimationCache:getInstance() local function _createAnimation(uuid, assets) local animation = _animationCache:getAnimation(uuid) if animation then return animation end if cc.DEBUG >= DEBUG_VERBOSE then cc.printdebug("[Assets] - [Animation] create animation %s", uuid) end local asset = assets:getAsset(uuid) local clip = {} clip.speed = asset.speed or 1 clip.sample = asset.sample or 60 clip.speed = asset.speed or 1 clip.wrapMode = asset.wrapMode or 0 local delay = 1.0 / clip.sample / clip.speed animation = cc.Animation:create() animation:setDelayPerUnit(delay) for _, faval in ipairs(asset["curveData"]["comps"]["cc.Sprite"]["spriteFrame"]) do local frameAsset = assets:getAsset(faval["value"]["__uuid__"]) local spriteFrame = assets:_createObject(frameAsset) animation:addSpriteFrame(spriteFrame) end _animationCache:addAnimation(animation, uuid) animation.loop = clip.wrapMode return animation end function AnimationComponent:ctor(props, assets) AnimationComponent.super.ctor(self) self.props = props self._animations = {} if not self.props._clips then return end for _, clipaval in ipairs(self.props._clips) do local animation, clip = _createAnimation(clipaval.__uuid__, assets) animation:retain() self._animations[#self._animations + 1] = animation end end function AnimationComponent:start(target) if self.props.playOnLoad then self:play(target) end end function AnimationComponent:play(target, callback) if not target.components or not target.components["cc.Sprite"] then cc.printwarn("[Animation] invalid target %s", target.__type) return end local spriteComponent = target.components["cc.Sprite"] local sprite = spriteComponent.node for _, animation in ipairs(self._animations) do local animate = cc.Animate:create(animation) if animation.loop == _LOOP_LOOP then sprite:runAction(cc.RepeatForever:create(animate)) elseif callback then sprite:runAction(cc.Sequence:create({animate, cc.CallFunc:create(callback)})) else sprite:runAction(animate) end end end function AnimationComponent:onDestroy(target) for _, animation in ipairs(self._animations) do animation:release() end self._animations = nil end return AnimationComponent
fix Animation component
fix Animation component
Lua
mit
dualface/creator-lua,dualface/creator-lua,dualface/creator-lua,dualface/creator-lua,dualface/creator-lua
af45c4df39e9c5cfc6f916ce1b217ec3c25fa9a2
modules/freifunk/luasrc/model/cbi/freifunk/contact.lua
modules/freifunk/luasrc/model/cbi/freifunk/contact.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("freifunk", translate("contact"), translate("contact1")) c = m:section(NamedSection, "contact", "public", "") c:option(Value, "nickname", translate("nickname")) c:option(Value, "name", translate("name")) c:option(Value, "mail", translate("mail"), translate("mail1")) c:option(Value, "phone", translate("phone")) c:option(Value, "location", translate("location")) c:option(Value, "note", translate("note")) m2 = Map("system", translate("geo")) s = m2:section(TypedSection, "system", "") s:option(Value, "latitude", translate("latitude", "Breite")).rmempty = true s:option(Value, "longitude", translate("longitude", "Länge")).rmempty = true return m, m2
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- luci.i18n.loadc("freifunk") m = Map("freifunk", translate("contact"), translate("contact1")) c = m:section(NamedSection, "contact", "public", "") c:option(Value, "nickname", translate("ff_nickname")) c:option(Value, "name", translate("ff_name")) c:option(Value, "mail", translate("ff_mail"), translate("ff_mail1")) c:option(Value, "phone", translate("ff_phone")) c:option(Value, "location", translate("ff_location")) c:option(Value, "note", translate("ff_note")) m2 = Map("system", translate("geo")) s = m2:section(TypedSection, "system", "") s:option(Value, "latitude", translate("latitude", "Breite")).rmempty = true s:option(Value, "longitude", translate("longitude", "Länge")).rmempty = true return m, m2
* luci/modules/freifunk: translation fixes on contact admin page
* luci/modules/freifunk: translation fixes on contact admin page git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@3387 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
freifunk-gluon/luci,Canaan-Creative/luci,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,Canaan-Creative/luci,gwlim/luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,Canaan-Creative/luci,gwlim/luci,ch3n2k/luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,alxhh/piratenluci,Canaan-Creative/luci,phi-psi/luci,yeewang/openwrt-luci,ch3n2k/luci,eugenesan/openwrt-luci,Flexibity/luci,ch3n2k/luci,projectbismark/luci-bismark,alxhh/piratenluci,projectbismark/luci-bismark,ThingMesh/openwrt-luci,freifunk-gluon/luci,8devices/carambola2-luci,projectbismark/luci-bismark,dtaht/cerowrt-luci-3.3,Flexibity/luci,jschmidlapp/luci,jschmidlapp/luci,projectbismark/luci-bismark,8devices/carambola2-luci,gwlim/luci,freifunk-gluon/luci,stephank/luci,zwhfly/openwrt-luci,stephank/luci,eugenesan/openwrt-luci,saraedum/luci-packages-old,dtaht/cerowrt-luci-3.3,jschmidlapp/luci,vhpham80/luci,vhpham80/luci,dtaht/cerowrt-luci-3.3,yeewang/openwrt-luci,projectbismark/luci-bismark,dtaht/cerowrt-luci-3.3,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,freifunk-gluon/luci,saraedum/luci-packages-old,gwlim/luci,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,alxhh/piratenluci,saraedum/luci-packages-old,jschmidlapp/luci,jschmidlapp/luci,zwhfly/openwrt-luci,dtaht/cerowrt-luci-3.3,eugenesan/openwrt-luci,gwlim/luci,vhpham80/luci,jschmidlapp/luci,phi-psi/luci,eugenesan/openwrt-luci,alxhh/piratenluci,ch3n2k/luci,stephank/luci,projectbismark/luci-bismark,projectbismark/luci-bismark,ThingMesh/openwrt-luci,Flexibity/luci,gwlim/luci,gwlim/luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,Canaan-Creative/luci,Flexibity/luci,phi-psi/luci,eugenesan/openwrt-luci,yeewang/openwrt-luci,vhpham80/luci,Canaan-Creative/luci,alxhh/piratenluci,saraedum/luci-packages-old,yeewang/openwrt-luci,stephank/luci,8devices/carambola2-luci,Flexibity/luci,zwhfly/openwrt-luci,8devices/carambola2-luci,jschmidlapp/luci,saraedum/luci-packages-old,ch3n2k/luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,dtaht/cerowrt-luci-3.3,ThingMesh/openwrt-luci,eugenesan/openwrt-luci,jschmidlapp/luci,8devices/carambola2-luci,freifunk-gluon/luci,alxhh/piratenluci,eugenesan/openwrt-luci,yeewang/openwrt-luci,phi-psi/luci,Flexibity/luci,ch3n2k/luci,zwhfly/openwrt-luci,vhpham80/luci,vhpham80/luci,zwhfly/openwrt-luci,8devices/carambola2-luci,stephank/luci,alxhh/piratenluci,phi-psi/luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,saraedum/luci-packages-old,ch3n2k/luci,phi-psi/luci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,projectbismark/luci-bismark,8devices/carambola2-luci,phi-psi/luci,stephank/luci,yeewang/openwrt-luci,zwhfly/openwrt-luci
79c2fc9c2d881940a3a32bed11f29af53f32a995
src/filesize/filesize.lua
src/filesize/filesize.lua
-- lua-filesize, generate a human readable string describing the file size -- Copyright (c) 2016 Boris Nagaev -- See the LICENSE file for terms of use. local si = { bits = {"b", "Kb", "Mb", "Gb", "Tb", "Pb", "Eb", "Zb", "Yb"}, bytes = {"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}, } local function isNan(num) -- http://lua-users.org/wiki/InfAndNanComparisons -- NaN is the only value that doesn't equal itself return num ~= num end local function toFixed(num, digits) local fmt = "%." .. digits .. "f" return fmt:format(num) end local function filesize(size, options) -- copy options to o local o = {} for key, value in pairs(options or {}) do o[key] = value end local function setDefault(name, default) if o[name] == nil then o[name] = default end end setDefault("bits", false) setDefault("unix", false) setDefault("base", 2) setDefault("round", o.unix and 1 or 2) setDefault("spacer", o.unix and "" or " ") setDefault("suffixes", {}) setDefault("output", "string") setDefault("exponent", -1) assert(not isNan(size), "Invalid arguments") local ceil = (o.base > 2) and 1000 or 1024 local negative = (size < 0) if negative then -- Flipping a negative number to determine the size size = -size end local result -- Zero is now a special case because bytes divide by 1 if size == 0 then result = { 0, o.unix and "" or (o.bits and "b" or "B"), } else -- Determining the exponent if o.exponent == -1 or isNan(o.exponent) then o.exponent = math.floor(math.log(size) / math.log(ceil)) end -- Exceeding supported length, time to reduce & multiply if o.exponent > 8 then o.exponent = 8 end local val if o.base == 2 then val = size / math.pow(2, o.exponent * 10) else val = size / math.pow(1000, o.exponent) end if o.bits then val = val * 8 if val > ceil then val = val / ceil o.exponent = o.exponent + 1 end end result = { tonumber(toFixed(val, o.exponent > 0 and o.round or 0)), (o.base == 10 and o.exponent == 1) and (o.bits and "kb" or "kB") or (si[o.bits and "bits" or "bytes"][o.exponent + 1]), } if o.unix then result[2] = result[2]:sub(1, 1) if result[2] == "b" or result[2] == "B" then result ={ math.floor(result[1]), "", } end end end assert(result) -- Decorating a 'diff' if negative then result[1] = -result[1] end -- Applying custom suffix result[2] = o.suffixes[result[2]] or result[2] -- Applying custom suffix result[2] = o.suffixes[result[2]] or result[2] -- Returning Array, Object, or String (default) if o.output == "array" then return result elseif o.output == "exponent" then return o.exponent elseif o.output == "object" then return { value = result[1], suffix = result[2], } elseif o.output == "string" then return table.concat(result, o.spacer) end end return filesize
-- lua-filesize, generate a human readable string describing the file size -- Copyright (c) 2016 Boris Nagaev -- See the LICENSE file for terms of use. local si = { bits = {"b", "Kb", "Mb", "Gb", "Tb", "Pb", "Eb", "Zb", "Yb"}, bytes = {"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}, } local function isNan(num) -- http://lua-users.org/wiki/InfAndNanComparisons -- NaN is the only value that doesn't equal itself return num ~= num end local function toFixed(num, digits) local fmt if digits > 0 then fmt = "%." .. digits .. "f" else fmt = "%d" end return fmt:format(num) end local function filesize(size, options) -- copy options to o local o = {} for key, value in pairs(options or {}) do o[key] = value end local function setDefault(name, default) if o[name] == nil then o[name] = default end end setDefault("bits", false) setDefault("unix", false) setDefault("base", 2) setDefault("round", o.unix and 1 or 2) setDefault("spacer", o.unix and "" or " ") setDefault("suffixes", {}) setDefault("output", "string") setDefault("exponent", -1) assert(not isNan(size), "Invalid arguments") local ceil = (o.base > 2) and 1000 or 1024 local negative = (size < 0) if negative then -- Flipping a negative number to determine the size size = -size end local result -- Zero is now a special case because bytes divide by 1 if size == 0 then result = { 0, o.unix and "" or (o.bits and "b" or "B"), } else -- Determining the exponent if o.exponent == -1 or isNan(o.exponent) then o.exponent = math.floor(math.log(size) / math.log(ceil)) end -- Exceeding supported length, time to reduce & multiply if o.exponent > 8 then o.exponent = 8 end local val if o.base == 2 then val = size / math.pow(2, o.exponent * 10) else val = size / math.pow(1000, o.exponent) end if o.bits then val = val * 8 if val > ceil then val = val / ceil o.exponent = o.exponent + 1 end end result = { tonumber(toFixed(val, o.exponent > 0 and o.round or 0)), (o.base == 10 and o.exponent == 1) and (o.bits and "kb" or "kB") or (si[o.bits and "bits" or "bytes"][o.exponent + 1]), } if o.unix then result[2] = result[2]:sub(1, 1) if result[2] == "b" or result[2] == "B" then result ={ math.floor(result[1]), "", } end end end assert(result) -- Decorating a 'diff' if negative then result[1] = -result[1] end -- Applying custom suffix result[2] = o.suffixes[result[2]] or result[2] -- Applying custom suffix result[2] = o.suffixes[result[2]] or result[2] -- Returning Array, Object, or String (default) if o.output == "array" then return result elseif o.output == "exponent" then return o.exponent elseif o.output == "object" then return { value = result[1], suffix = result[2], } elseif o.output == "string" then return table.concat(result, o.spacer) end end return filesize
fix toFixed() for Lua 5.3
fix toFixed() for Lua 5.3 In Lua 5.3, tostring(double(42)) returns "42.0". In Lua 5.2, tostring(double(42)) returns "42". See https://travis-ci.org/starius/lua-filesize/jobs/103972092
Lua
mit
starius/lua-filesize
bf61e6f0932761b413c7451932e2e9af7441481b
frontend/device/android/powerd.lua
frontend/device/android/powerd.lua
local BasePowerD = require("device/generic/powerd") local _, android = pcall(require, "android") local AndroidPowerD = BasePowerD:new{ fl_min = 0, fl_max = 25, fl_intensity = 10, } function AndroidPowerD:frontlightIntensityHW() return math.floor(android.getScreenBrightness() / 255 * self.fl_max) end function AndroidPowerD:setIntensityHW(intensity) if self.fl_intensity ~= intensity then android.setScreenBrightness(math.floor(255 * intensity / self.fl_max)) end end function AndroidPowerD:getCapacityHW() return android.getBatteryLevel() end function AndroidPowerD:isChargingHW() return android.isCharging() end return AndroidPowerD
local BasePowerD = require("device/generic/powerd") local _, android = pcall(require, "android") local AndroidPowerD = BasePowerD:new{ fl_min = 0, fl_max = 25, fl_intensity = 10, } function AndroidPowerD:frontlightIntensityHW() return math.floor(android.getScreenBrightness() / 255 * self.fl_max) end function AndroidPowerD:setIntensityHW(intensity) android.setScreenBrightness(math.floor(255 * intensity / self.fl_max)) end function AndroidPowerD:getCapacityHW() return android.getBatteryLevel() end function AndroidPowerD:isChargingHW() return android.isCharging() end return AndroidPowerD
[fix] Android frontlight control
[fix] Android frontlight control
Lua
agpl-3.0
poire-z/koreader,poire-z/koreader,NiLuJe/koreader,pazos/koreader,lgeek/koreader,NiLuJe/koreader,koreader/koreader,Frenzie/koreader,koreader/koreader,Frenzie/koreader,Hzj-jie/koreader,mwoz123/koreader,mihailim/koreader,Markismus/koreader,houqp/koreader,apletnev/koreader
320346b8966b3f5b4f8fb36ba7a34f7c469ef4c5
titan-compiler/syntax_errors.lua
titan-compiler/syntax_errors.lua
local syntax_errors = {} local errors = { -- The `0` label is the default "parsing failed" error number [0] = { label = "SyntaxError", msg = "Syntax Error" }, { label = "MalformedNumber", msg = "Malformed number." }, { label = "UnclosedLongString", msg = "Unclosed long string or long comment." }, { label = "UnclosedShortString", msg = "Unclosed short string." }, { label = "InvalidEscape", msg = "Invalid escape character in string." }, --not used currently { label = "MalformedEscape_ddd", msg = "\\ddd escape sequences must have at most three digits." }, { label = "MalformedEscape_u", msg = "\\u escape sequence is malformed." }, { label = "MalformedEscape_x", msg = "\\x escape sequences must have exactly two hexadecimal digits." }, { label = "NameFunc", msg = "Expected a function name after 'function'." }, { label = "LParPList", msg = "Expected '(' for the parameter list." }, { label = "RParPList", msg = "Expected ')' to close the parameter list." }, { label = "ColonFunc", msg = "Expected ':' after the parameter list." }, { label = "TypeFunc", msg = "Expected a type in function declaration." }, { label = "EndFunc", msg = "Expected 'end' to close the function body." }, { label = "AssignVar", msg = "Expected '=' after variable declaration." }, { label = "ExpVarDec", msg = "Expected an expression to initialize variable." }, { label = "NameRecord", msg = "Expected a record name after 'record'." }, { label = "EndRecord", msg = "Expected 'end' to close the record." }, { label = "FieldRecord", msg = "Expected a field in record declaration." }, { label = "NameImport", msg = "Expected a name after 'local'." }, --this label is not thrown in rule 'import' because rule 'toplevelvar' --matches an invalid input like "local bola import" { label = "AssignImport", msg = "Expected '='." }, --this label is not thrown in rule 'import' because rule 'toplevelvar' --matches an input like "local bola = X", given that X is a valid expression, --or throws a label when X is not a valid expression { label = "ImportImport", msg = "Expected 'import' keyword." }, { label = "StringLParImport", msg = "Expected the name of a module after '('." }, { label = "RParImport", msg = "Expected ')' to close import declaration." }, { label = "StringImport", msg = "Expected the name of a module after 'import'." }, { label = "DeclParList", msg = "Expected a variable name after ','." }, { label = "TypeDecl", msg = "Expected a type name after ':'." }, { label = "TypeType", msg = "Expected a type name after '{'." }, { label = "RCurlyType", msg = "Expected '}' to close type specification." }, { label = "TypelistType", msg = "Expected type after ','" }, { label = "RParenTypelist", msg = "Expected ')' to close type list" }, { label = "TypeReturnTypes", msg = "Expected return types after `->` to finish the function type" }, { label = "ColonRecordField", msg = "Expected ':' after the name of a record field." }, { label = "TypeRecordField", msg = "Expected a type name after ':'." }, { label = "EndBlock", msg = "Expected 'end' to close block." }, { label = "ExpWhile", msg = "Expected an expression after 'while'." }, { label = "DoWhile", msg = "Expected 'do' in while statement." }, { label = "EndWhile", msg = "Expected 'end' to close the while statement." }, { label = "UntilRepeat", msg = "Expected 'until' in repeat statement." }, { label = "ExpRepeat", msg = "Expected an expression after 'until'." }, { label = "ExpIf", msg = "Expected an expression after 'if'." }, { label = "ThenIf", msg = "Expected 'then' in if statement." }, { label = "EndIf", msg = "Expected 'end' to close the if statement." }, { label = "DeclFor", msg = "Expected variable declaration in for statement." }, { label = "AssignFor", msg = "Expected '=' after variable declaration in for statement." }, { label = "Exp1For", msg = "Expected an expression after '='." }, { label = "CommaFor", msg = "Expected ',' in for statement." }, { label = "Exp2For", msg = "Expected an expression after ','." }, { label = "Exp3For", msg = "Expected an expression after ','." }, { label = "DoFor", msg = "Expected 'do' in for statement." }, { label = "EndFor", msg = "Expected 'end' to close the for statement." }, { label = "DeclLocal", msg = "Expected variable declaration after 'local'." }, { label = "AssignLocal", msg = "Expected '=' after variable declaration." }, { label = "ExpLocal", msg = "Expected an expression after '='." }, { label = "AssignAssign", msg = "Expected '=' after variable." }, { label = "ExpAssign", msg = "Expected an expression after '='." }, { label = "ExpElseIf", msg = "Expected an expression after 'elseif'." }, { label = "ThenElseIf", msg = "Expected 'then' in elseif statement." }, { label = "OpExp", msg = "Expected an expression after operator." }, -- not used currently because the parser rule is commented { label = "NameColonExpSuf", msg = "Expected a method name after ':'." }, -- not used currently because the parser rule is commented { label = "FuncArgsExpSuf", msg = "Expected a list of arguments." }, { label = "ExpExpSuf", msg = "Expected an expression after '['." }, { label = "RBracketExpSuf", msg = "Expected ']' to match '['." }, { label = "NameDotExpSuf", msg = "Expected a function name after '.'." }, { label = "ExpSimpleExp", msg = "Expected an expression after '('." }, { label = "RParSimpleExp", msg = "Expected ')'to match '('." }, { label = "RParFuncArgs", msg = "Expected ')' to match '('." }, { label = "ExpExpList", msg = "Expected an expression after ','." }, { label = "RCurlyTableCons", msg = "Expected '{' to match '}'." }, { label = "ExpFieldList", msg = "Expected an expression after ',' or ';'." }, } syntax_errors.label_to_msg = {} syntax_errors.label_to_int = {} syntax_errors.int_to_label = {} syntax_errors.int_to_msg = {} do for i, t in pairs(errors) do local label = assert(t.label) local msg = assert(t.msg) syntax_errors.label_to_msg[label] = msg syntax_errors.label_to_int[label] = i syntax_errors.int_to_label[i] = label syntax_errors.int_to_msg[i] = msg end end return syntax_errors
local syntax_errors = {} local errors = { -- The `0` label is the default "parsing failed" error number [0] = { label = "SyntaxError", msg = "Syntax Error" }, { label = "MalformedNumber", msg = "Malformed number." }, { label = "UnclosedLongString", msg = "Unclosed long string or long comment." }, { label = "UnclosedShortString", msg = "Unclosed short string." }, { label = "InvalidEscape", msg = "Invalid escape character in string." }, --not used currently { label = "MalformedEscape_ddd", msg = "\\ddd escape sequences must have at most three digits." }, { label = "MalformedEscape_u", msg = "\\u escape sequence is malformed." }, { label = "MalformedEscape_x", msg = "\\x escape sequences must have exactly two hexadecimal digits." }, { label = "NameFunc", msg = "Expected a function name after 'function'." }, { label = "LParPList", msg = "Expected '(' for the parameter list." }, { label = "RParPList", msg = "Expected ')' to close the parameter list." }, { label = "ColonFunc", msg = "Expected ':' after the parameter list." }, { label = "TypeFunc", msg = "Expected a type in function declaration." }, { label = "EndFunc", msg = "Expected 'end' to close the function body." }, { label = "AssignVar", msg = "Expected '=' after variable declaration." }, { label = "ExpVarDec", msg = "Expected an expression to initialize variable." }, { label = "NameRecord", msg = "Expected a record name after 'record'." }, { label = "EndRecord", msg = "Expected 'end' to close the record." }, { label = "FieldRecord", msg = "Expected a field in record declaration." }, { label = "NameImport", msg = "Expected a name after 'local'." }, --this label is not thrown in rule 'import' because rule 'toplevelvar' --matches an invalid input like "local bola import" { label = "AssignImport", msg = "Expected '='." }, --this label is not thrown in rule 'import' because rule 'toplevelvar' --matches an input like "local bola = X", given that X is a valid expression, --or throws a label when X is not a valid expression { label = "ImportImport", msg = "Expected 'import' keyword." }, { label = "StringLParImport", msg = "Expected the name of a module after '('." }, { label = "RParImport", msg = "Expected ')' to close import declaration." }, { label = "StringImport", msg = "Expected the name of a module after 'import'." }, { label = "DeclParList", msg = "Expected a variable name after ','." }, { label = "TypeDecl", msg = "Expected a type name after ':'." }, { label = "TypeType", msg = "Expected a type name after '{'." }, { label = "RCurlyType", msg = "Expected '}' to close type specification." }, { label = "TypelistType", msg = "Expected type after ','" }, { label = "RParenTypelist", msg = "Expected ')' to close type list" }, { label = "TypeReturnTypes", msg = "Expected return types after `->` to finish the function type" }, { label = "ColonRecordField", msg = "Expected ':' after the name of a record field." }, { label = "TypeRecordField", msg = "Expected a type name after ':'." }, { label = "EndBlock", msg = "Expected 'end' to close block." }, { label = "ExpWhile", msg = "Expected an expression after 'while'." }, { label = "DoWhile", msg = "Expected 'do' in while statement." }, { label = "EndWhile", msg = "Expected 'end' to close the while statement." }, { label = "UntilRepeat", msg = "Expected 'until' in repeat statement." }, { label = "ExpRepeat", msg = "Expected an expression after 'until'." }, { label = "ExpIf", msg = "Expected an expression after 'if'." }, { label = "ThenIf", msg = "Expected 'then' in if statement." }, { label = "EndIf", msg = "Expected 'end' to close the if statement." }, { label = "DeclFor", msg = "Expected variable declaration in for statement." }, { label = "AssignFor", msg = "Expected '=' after variable declaration in for statement." }, { label = "Exp1For", msg = "Expected an expression after '='." }, { label = "CommaFor", msg = "Expected ',' in for statement." }, { label = "Exp2For", msg = "Expected an expression after ','." }, { label = "Exp3For", msg = "Expected an expression after ','." }, { label = "DoFor", msg = "Expected 'do' in for statement." }, { label = "EndFor", msg = "Expected 'end' to close the for statement." }, { label = "DeclLocal", msg = "Expected variable declaration after 'local'." }, { label = "AssignLocal", msg = "Expected '=' after variable declaration." }, { label = "ExpLocal", msg = "Expected an expression after '='." }, { label = "AssignAssign", msg = "Expected '=' after variable." }, { label = "ExpAssign", msg = "Expected an expression after '='." }, { label = "ExpElseIf", msg = "Expected an expression after 'elseif'." }, { label = "ThenElseIf", msg = "Expected 'then' in elseif statement." }, { label = "OpExp", msg = "Expected an expression after operator." }, -- not used currently because the parser rule is commented { label = "NameColonExpSuf", msg = "Expected a method name after ':'." }, -- not used currently because the parser rule is commented { label = "FuncArgsExpSuf", msg = "Expected a list of arguments." }, { label = "ExpExpSuf", msg = "Expected an expression after '['." }, { label = "RBracketExpSuf", msg = "Expected ']' to match '['." }, { label = "NameDotExpSuf", msg = "Expected a function name after '.'." }, { label = "ExpSimpleExp", msg = "Expected an expression after '('." }, { label = "RParSimpleExp", msg = "Expected ')'to match '('." }, { label = "RParFuncArgs", msg = "Expected ')' to match '('." }, { label = "ExpExpList", msg = "Expected an expression after ','." }, { label = "RCurlyTableCons", msg = "Expected '{' to match '}'." }, { label = "ExpFieldList", msg = "Expected an expression after ',' or ';'." }, } syntax_errors.label_to_msg = {} syntax_errors.label_to_int = {} syntax_errors.int_to_label = {} syntax_errors.int_to_msg = {} do for i, t in pairs(errors) do local label = assert(t.label) local msg = assert(t.msg) syntax_errors.label_to_msg[label] = msg syntax_errors.label_to_int[label] = i syntax_errors.int_to_label[i] = label syntax_errors.int_to_msg[i] = msg end end return syntax_errors
Fix indentation in syntax_errors.lua
Fix indentation in syntax_errors.lua
Lua
mit
titan-lang/titan-v0,titan-lang/titan-v0,titan-lang/titan-v0
7a47602b8f42134e08245acd671503a6ed2a7654
Modules/Shared/Binder/Binder.lua
Modules/Shared/Binder/Binder.lua
--- Bind class to Roblox Instance -- @classmod Binder local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore")) local RunService = game:GetService("RunService") local CollectionService = game:GetService("CollectionService") local Maid = require("Maid") local fastSpawn = require("fastSpawn") local Signal = require("Signal") local Binder = {} Binder.__index = Binder Binder.ClassName = "Binder" function Binder.new(tagName, class) local self = setmetatable({}, Binder) self._maid = Maid.new() self._tagName = tagName or error("No tagName") self._class = class or error("No class") self._loading = setmetatable({}, {__mode = "kv"}) delay(5, function() if not self._loaded then warn("Binder is not loaded. Call :Init() on it!") end end) return self end function Binder:Init() if self._loaded then return end self._loaded = true for _, inst in pairs(CollectionService:GetTagged(self._tagName)) do fastSpawn(function() self:_add(inst) end) end self._maid:GiveTask(CollectionService:GetInstanceAddedSignal(self._tagName):Connect(function(inst) self:_add(inst) end)) self._maid:GiveTask(CollectionService:GetInstanceRemovedSignal(self._tagName):Connect(function(inst) self:_remove(inst) end)) end function Binder:GetClassAddedSignal() if self._classAddedSignal then return self._classAddedSignal end self._classAddedSignal = Signal.new() -- :fire(class, inst) self._maid:GiveTask(self._classAddedSignal) return self._classAddedSignal end function Binder:GetClassRemovingSignal() if self._classRemovingSignal then return self._classRemovingSignal end self._classRemovingSignal = Signal.new() -- :fire(class, inst) self._maid:GiveTask(self._classRemovingSignal) return self._classRemovingSignal end function Binder:GetTag() return self._tagName end function Binder:GetAll() local all = {} for _, inst in pairs(CollectionService:GetTagged(self._tagName)) do table.insert(all, self._maid[inst]) end return all end function Binder:Bind(inst) if RunService:IsClient() then warn(("[Binder] - Bindings '%s' done on the client! Will be disrupted upon server replication!") :format(self._tagName)) end CollectionService:AddTag(inst, self._tagName) return self:Get(inst) end function Binder:Unbind(inst) assert(typeof(inst) == "Instance") CollectionService:RemoveTag(inst, self._tagName) end function Binder:Get(inst) assert(typeof(inst) == "Instance", "Argument 'inst' is not an Instance") return self._maid[inst] end function Binder:_add(inst) assert(typeof(inst) == "Instance") if self._loading[inst] then return end self._loading[inst] = true if type(self._class) == "function" then self._maid[inst] = self._class(inst) elseif self._class.Create then self._maid[inst] = self._class:Create(inst) else self._maid[inst] = self._class.new(inst) end if self._classAddedSignal then self._classAddedSignal:Fire(self._maid[inst], inst) end end function Binder:_remove(inst) local class = self._maid[inst] if class and self._classRemovingSignal then self._classRemovingSignal:Fire(class, inst) end self._maid[inst] = nil self._loading[inst] = nil end function Binder:Destroy() self._maid:DoCleaning() end return Binder
--- Bind class to Roblox Instance -- @classmod Binder local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore")) local RunService = game:GetService("RunService") local CollectionService = game:GetService("CollectionService") local Maid = require("Maid") local fastSpawn = require("fastSpawn") local Signal = require("Signal") local Binder = {} Binder.__index = Binder Binder.ClassName = "Binder" function Binder.new(tagName, class) local self = setmetatable({}, Binder) self._maid = Maid.new() self._tagName = tagName or error("No tagName") self._class = class or error("No class") self._loading = setmetatable({}, {__mode = "kv"}) delay(5, function() if not self._loaded then warn("Binder is not loaded. Call :Init() on it!") end end) return self end function Binder:Init() if self._loaded then return end self._loaded = true for _, inst in pairs(CollectionService:GetTagged(self._tagName)) do fastSpawn(function() self:_add(inst) end) end self._maid:GiveTask(CollectionService:GetInstanceAddedSignal(self._tagName):Connect(function(inst) self:_add(inst) end)) self._maid:GiveTask(CollectionService:GetInstanceRemovedSignal(self._tagName):Connect(function(inst) self:_remove(inst) end)) end function Binder:GetClassAddedSignal() if self._classAddedSignal then return self._classAddedSignal end self._classAddedSignal = Signal.new() -- :fire(class, inst) self._maid:GiveTask(self._classAddedSignal) return self._classAddedSignal end function Binder:GetClassRemovingSignal() if self._classRemovingSignal then return self._classRemovingSignal end self._classRemovingSignal = Signal.new() -- :fire(class, inst) self._maid:GiveTask(self._classRemovingSignal) return self._classRemovingSignal end function Binder:GetTag() return self._tagName end function Binder:GetAll() local all = {} for _, inst in pairs(CollectionService:GetTagged(self._tagName)) do table.insert(all, self._maid[inst]) end return all end -- Using this acknowledges that we're intentionally binding on a safe client object, -- i.e. one without replication. function Binder:BindClient(inst) CollectionService:AddTag(inst, self._tagName) return self:Get(inst) end function Binder:Bind(inst) if RunService:IsClient() then warn(("[Binder.Bind] - Bindings '%s' done on the client! Will be disrupted upon server replication!") :format(self._tagName)) end CollectionService:AddTag(inst, self._tagName) return self:Get(inst) end function Binder:Unbind(inst) assert(typeof(inst) == "Instance") CollectionService:RemoveTag(inst, self._tagName) end function Binder:Get(inst) assert(typeof(inst) == "Instance", "Argument 'inst' is not an Instance") return self._maid[inst] end function Binder:_add(inst) assert(typeof(inst) == "Instance") if self._loading[inst] then return end self._loading[inst] = true if type(self._class) == "function" then self._maid[inst] = self._class(inst) elseif self._class.Create then self._maid[inst] = self._class:Create(inst) else self._maid[inst] = self._class.new(inst) end if self._classAddedSignal then self._classAddedSignal:Fire(self._maid[inst], inst) end end function Binder:_remove(inst) local class = self._maid[inst] if class and self._classRemovingSignal then self._classRemovingSignal:Fire(class, inst) end self._maid[inst] = nil self._loading[inst] = nil end function Binder:Destroy() self._maid:DoCleaning() end return Binder
More explicit binding on clients to prevent bugs
More explicit binding on clients to prevent bugs
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
cb2892c0e8cdc9e6f4c8b699fe1eef341c641778
premake4.lua
premake4.lua
-- Clean Function -- newaction { trigger = "clean", description = "clean the software", execute = function () print("clean the build...") os.rmdir("./build") print("done.") end } -- A solution contains projects, and defines the available configurations solution "simhub" configurations { "Debug", "Release", "Debug_AWS" } -- pass in platform helper #defines configuration {"macosx"} defines {"build_macosx"} configuration {""} configuration {"linux"} defines {"build_linux"} configuration {""} defines {"__PLATFORM"} configuration "Debug" defines { "DEBUG" } symbols "On" configuration "Debug_AWS" defines { "DEBUG" , "_AWS_SDK" } symbols "On" links { "aws-cpp-sdk-core", "aws-cpp-sdk-polly", "aws-cpp-sdk-text-to-speech" } configuration "Release" defines { "NDEBUG" } flags { "Optimize" } links { "aws-cpp-sdk-core", "aws-cpp-sdk-polly", "aws-cpp-sdk-text-to-speech" } -- A project defines one build target project "simhub" kind "ConsoleApp" language "C++" files { "src/app/**.cpp", "src/app/**.h", "src/common/**.h", "src/common/**.cpp" } configuration {"Debug"} excludes {"src/common/aws/**"} configuration {} includedirs { "src", "src/app", "src/common", "src/libs", "src/libs/variant/include", "src/libs/variant/include/mpark", "src/libs/queue" } links { "zlog", "pthread", "config++" } targetdir ("bin") buildoptions { "--std=c++14" } configuration { "macosx", "Debug" } postbuildcommands { "dsymutil bin/simhub", "gtags" } configuration {} configuration {"linux"} links {"dl"} configuration {""} project "simhub_tests" kind "ConsoleApp" language "C++" files { "src/common/**.h", "src/common/**.cpp", "src/test/**.h", "src/test/**.cpp", "src/app/simhub.cpp", "src/libs/googletest/src/gtest-all.cc" } configuration {"Debug"} excludes {"src/common/aws/**"} configuration {} includedirs { "src/libs/googletest/include", "src/libs/googletest", "src", "src/app", "src/common", "src/libs/variant/include", "src/libs", "src/libs/variant/include/mpark", "src/libs/queue" } links { "dl", "zlog", "pthread", "config++"} targetdir ("bin") buildoptions { "--std=c++14" } project "prepare3d_plugin" kind "SharedLib" language "C++" targetname "prepare3d" targetdir ("bin/plugins") links { 'uv', 'config++', 'pthread'} files { "src/libs/plugins/prepare3d/**.h", "src/libs/plugins/common/**.cpp", "src/libs/plugins/prepare3d/**.cpp" } includedirs { "src/libs/googletest/include", "src/libs/googletest", "src/common", "src/libs/plugins", "src/libs/variant/include", "src/libs", "src/libs/variant/include/mpark", "src/libs/queue" } buildoptions { "--std=c++14" } project "simplug_devicesource" kind "SharedLib" language "C++" targetname "pokey" targetdir ("bin/plugins") files { "src/libs/plugins/pokey/**.h", "src/libs/plugins/common/**.cpp", "src/libs/plugins/pokey/**.cpp" } includedirs { "src/libs/googletest/include", "src/libs/googletest", "src/common", "src/libs/plugins", "src/libs/variant/include", "src/libs", "src/libs/variant/include/mpark", "src/libs/queue" } links { 'config++', 'pthread'} buildoptions { "--std=c++14" }
-- Clean Function -- newaction { trigger = "clean", description = "clean the software", execute = function () print("clean the build...") os.rmdir("./obj") os.remove("./*.make") os.remove("./Makefile") print("done.") end } -- A solution contains projects, and defines the available configurations solution "simhub" configurations { "Debug", "Release", "Debug_AWS" } -- pass in platform helper #defines configuration {"macosx"} defines {"build_macosx"} configuration {""} configuration {"linux"} defines {"build_linux"} configuration {""} defines {"__PLATFORM"} configuration "Debug" defines { "DEBUG" } symbols "On" configuration "Debug_AWS" defines { "DEBUG" , "_AWS_SDK" } symbols "On" links { "aws-cpp-sdk-core", "aws-cpp-sdk-polly", "aws-cpp-sdk-text-to-speech" } configuration "Release" defines { "NDEBUG" } flags { "Optimize" } links { "aws-cpp-sdk-core", "aws-cpp-sdk-polly", "aws-cpp-sdk-text-to-speech" } -- A project defines one build target project "simhub" kind "ConsoleApp" language "C++" files { "src/app/**.cpp", "src/app/**.h", "src/common/**.h", "src/common/**.cpp" } configuration {"Debug"} excludes {"src/common/aws/**"} configuration {} includedirs { "src", "src/app", "src/common", "src/libs", "src/libs/variant/include", "src/libs/variant/include/mpark", "src/libs/queue" } links { "zlog", "pthread", "config++" } targetdir ("bin") buildoptions { "--std=c++14" } configuration { "macosx", "Debug" } postbuildcommands { "dsymutil bin/simhub", "gtags" } configuration {} configuration {"linux"} links {"dl"} configuration {""} project "simhub_tests" kind "ConsoleApp" language "C++" files { "src/common/**.h", "src/common/**.cpp", "src/test/**.h", "src/test/**.cpp", "src/app/simhub.cpp", "src/libs/googletest/src/gtest-all.cc" } configuration {"Debug"} excludes {"src/common/aws/**"} configuration {} includedirs { "src/libs/googletest/include", "src/libs/googletest", "src", "src/app", "src/common", "src/libs/variant/include", "src/libs", "src/libs/variant/include/mpark", "src/libs/queue" } links { "dl", "zlog", "pthread", "config++"} targetdir ("bin") buildoptions { "--std=c++14" } project "prepare3d_plugin" kind "SharedLib" language "C++" targetname "prepare3d" targetdir ("bin/plugins") links { 'uv', 'config++', 'pthread'} files { "src/libs/plugins/prepare3d/**.h", "src/libs/plugins/common/**.cpp", "src/libs/plugins/prepare3d/**.cpp" } includedirs { "src/libs/googletest/include", "src/libs/googletest", "src/common", "src/libs/plugins", "src/libs/variant/include", "src/libs", "src/libs/variant/include/mpark", "src/libs/queue" } buildoptions { "--std=c++14" } project "simplug_devicesource" kind "SharedLib" language "C++" targetname "pokey" targetdir ("bin/plugins") files { "src/libs/plugins/pokey/**.h", "src/libs/plugins/common/**.cpp", "src/libs/plugins/pokey/**.cpp" } includedirs { "src/libs/googletest/include", "src/libs/googletest", "src/common", "src/libs/plugins", "src/libs/variant/include", "src/libs", "src/libs/variant/include/mpark", "src/libs/queue" } links { 'config++', 'pthread'} buildoptions { "--std=c++14" }
Fixed the premake clean command to actually clean ...
Fixed the premake clean command to actually clean ...
Lua
mit
mteichtahl/simhub,lurkerbot/simhub,lurkerbot/simhub,lurkerbot/simhub,mteichtahl/simhub,mteichtahl/simhub,mteichtahl/simhub,lurkerbot/simhub
47e0c011e1ec98f5fffd138d82aebb97bca73383
game/scripts/vscripts/modules/hero_selection/hero_replacer.lua
game/scripts/vscripts/modules/hero_selection/hero_replacer.lua
function HeroSelection:SelectHero(playerId, heroName, beforeReplace, afterReplace, bSkipPrecache, bUpdateStatus) if bUpdateStatus ~= false then HeroSelection:UpdateStatusForPlayer(playerId, "picked", heroName) end Timers:CreateTimer(function() local connectionState = PlayerResource:GetConnectionState(playerId) if connectionState == DOTA_CONNECTION_STATE_CONNECTED then local function SpawnHero() Timers:CreateTimer(function() connectionState = PlayerResource:GetConnectionState(playerId) if connectionState == DOTA_CONNECTION_STATE_CONNECTED then local heroTableCustom = NPC_HEROES_CUSTOM[heroName] or NPC_HEROES[heroName] local oldhero = PlayerResource:GetSelectedHeroEntity(playerId) local hero local baseNewHero = heroTableCustom.base_hero or heroName if beforeReplace then beforeReplace(oldhero) end if oldhero then Timers:CreateTimer(0.03, function() oldhero:ClearNetworkableEntityInfo() UTIL_Remove(oldhero) end) if oldhero:GetUnitName() == baseNewHero then -- Base unit equals, ReplaceHeroWith won't do anything local temp = PlayerResource:ReplaceHeroWith(playerId, FORCE_PICKED_HERO, 0, 0) Timers:CreateTimer(0.03, function() temp:ClearNetworkableEntityInfo() UTIL_Remove(temp) end) end hero = PlayerResource:ReplaceHeroWith(playerId, baseNewHero, 0, 0) else print("[HeroSelection] For some reason player " .. playerId .. " has no hero. This player can't get a hero. Returning") return end HeroSelection:InitializeHeroClass(hero, heroTableCustom) for i = 0, hero:GetAbilityCount() - 1 do local ability = hero:GetAbilityByIndex(i) if ability and string.starts(ability:GetAbilityName(), "special_bonus_") then UTIL_Remove(ability) end end if heroTableCustom.base_hero then TransformUnitClass(hero, heroTableCustom) hero.UnitName = heroName end if Options:IsEquals("EnableAbilityShop") then for i = 0, hero:GetAbilityCount() - 1 do if hero:GetAbilityByIndex(i) then hero:RemoveAbility(hero:GetAbilityByIndex(i):GetName()) end end hero:AddAbility("ability_empty") hero:AddAbility("ability_empty") hero:AddAbility("ability_empty") hero:AddAbility("ability_empty") hero:AddAbility("ability_empty") hero:AddAbility("ability_empty") end if afterReplace then afterReplace(hero) end else return 0.1 end end) end if bSkipPrecache then SpawnHero() else PrecacheUnitByNameAsync(GetKeyValue(heroName, "base_hero") or heroName, SpawnHero, playerId) end else return 0.1 end end) end function HeroSelection:ChangeHero(playerId, newHeroName, keepExp, duration, item, callback, bUpdateStatus) local hero = PlayerResource:GetSelectedHeroEntity(playerId) if not hero.ForcedHeroChange then if hero:HasModifier("modifier_shredder_chakram_disarm") then Containers:DisplayError(playerId, "#arena_hud_error_cant_change_hero") return false end if hero:HasAbility("centaur_stampede") then local heroTeam = PlayerResource:GetTeam(playerId) for i = 0, 23 do local playerHero = PlayerResource:GetSelectedHeroEntity(i) if playerHero and PlayerResource:GetTeam(i) == heroTeam and playerHero:HasModifier("modifier_centaur_stampede") then Containers:DisplayError(playerId, "#arena_hud_error_cant_change_hero") return false end end end if hero:HasAbility("necrolyte_reapers_scythe") and AnyUnitHasModifier("modifier_necrolyte_reapers_scythe", hero) then Containers:DisplayError(playerId, "#arena_hud_error_cant_change_hero") return false end end local preDuration = 0 if hero:HasAbility("disruptor_thunder_strike") then local disruptor_thunder_strike = hero:FindAbilityByName("disruptor_thunder_strike") preDuration = disruptor_thunder_strike:GetSpecialValueFor("strikes") * disruptor_thunder_strike:GetSpecialValueFor("strike_interval") end hero.ChangingHeroProcessRunning = true ProjectileManager:ProjectileDodge(hero) if hero.PocketItem then hero.PocketHostEntity = nil UTIL_Remove(hero.PocketItem) hero.PocketItem = nil end hero:DestroyAllModifiers() hero:InterruptMotionControllers(false) hero:AddNewModifier(hero, nil, "modifier_hero_selection_transformation", nil) local xp = hero:GetCurrentXP() local fountatin = FindFountain(PlayerResource:GetTeam(playerId)) local location = hero:GetAbsOrigin() if fountatin then location = location or fountatin:GetAbsOrigin() end RemoveAllOwnedUnits(playerId) local startTime = GameRules:GetDOTATime(true, true) local items = {} local duelData = {} Timers:CreateTimer(preDuration, function() HeroSelection:SelectHero(playerId, newHeroName, function(oldHero) for i = DOTA_ITEM_SLOT_1, DOTA_STASH_SLOT_6 do local citem = hero:GetItemInSlot(i) if citem and citem ~= item then local newItem = CreateItem(citem:GetName(), nil, nil) if citem:GetPurchaser() ~= hero then newItem.NotPurchasedByOwner = true newItem:SetPurchaser(citem:GetPurchaser()) end newItem:SetPurchaseTime(citem:GetPurchaseTime()) newItem:SetCurrentCharges(citem:GetCurrentCharges()) if citem:GetCooldownTimeRemaining() > 0 then newItem.SavedCooldown = citem:GetCooldownTimeRemaining() end table.insert(items, newItem) else table.insert(items, CreateItem("item_dummy", hero, hero)) end end duelData.StatusBeforeArena = hero.StatusBeforeArena duelData.OnDuel = hero.OnDuel duelData.ArenaBeforeTpLocation = hero.ArenaBeforeTpLocation duelData.DuelChecked = hero.DuelChecked for team,tab in pairs(Duel.heroes_teams_for_duel or {}) do for i,unit in pairs(tab) do if unit == hero then duelData.path = {team, i} end end end end, function(newHero) newHero:AddNewModifier(newHero, nil, "modifier_hero_selection_transformation", nil) FindClearSpaceForUnit(newHero, location, true) if keepExp then newHero:AddExperience(xp, 0, true, true) end for _,v in ipairs(items) do v:SetOwner(newHero) if not v.NotPurchasedByOwner then v:SetPurchaser(newHero) v.NotPurchasedByOwner = nil end if v.SavedCooldown then v:StartCooldown(v.SavedCooldown) v.SavedCooldown = nil end newHero:AddItem(v) end ClearSlotsFromDummy(newHero) for k,v in pairs(duelData) do if k ~= "path" then newHero[k] = v else Duel.heroes_teams_for_duel[v[1]][v[1]] = newHero end end Timers:CreateTimer(startTime + (duration or 0) - GameRules:GetDOTATime(true, true), function() if IsValidEntity(newHero) then newHero:RemoveModifierByName("modifier_hero_selection_transformation") end end) if callback then callback(newHero) end end, nil, bUpdateStatus) end) return true end
function HeroSelection:SelectHero(playerId, heroName, beforeReplace, afterReplace, bSkipPrecache, bUpdateStatus) if bUpdateStatus ~= false then HeroSelection:UpdateStatusForPlayer(playerId, "picked", heroName) end Timers:CreateTimer(function() local connectionState = PlayerResource:GetConnectionState(playerId) if connectionState == DOTA_CONNECTION_STATE_CONNECTED then local function SpawnHero() Timers:CreateTimer(function() connectionState = PlayerResource:GetConnectionState(playerId) if connectionState == DOTA_CONNECTION_STATE_CONNECTED then local heroTableCustom = NPC_HEROES_CUSTOM[heroName] or NPC_HEROES[heroName] local oldhero = PlayerResource:GetSelectedHeroEntity(playerId) local hero local baseNewHero = heroTableCustom.base_hero or heroName if beforeReplace then beforeReplace(oldhero) end if oldhero then Timers:CreateTimer(0.03, function() oldhero:ClearNetworkableEntityInfo() UTIL_Remove(oldhero) end) if oldhero:GetUnitName() == baseNewHero then -- Base unit equals, ReplaceHeroWith won't do anything local temp = PlayerResource:ReplaceHeroWith(playerId, FORCE_PICKED_HERO, 0, 0) Timers:CreateTimer(0.03, function() temp:ClearNetworkableEntityInfo() UTIL_Remove(temp) end) end hero = PlayerResource:ReplaceHeroWith(playerId, baseNewHero, 0, 0) else print("[HeroSelection] For some reason player " .. playerId .. " has no hero. This player can't get a hero. Returning") return end HeroSelection:InitializeHeroClass(hero, heroTableCustom) for i = 0, hero:GetAbilityCount() - 1 do local ability = hero:GetAbilityByIndex(i) if ability and string.starts(ability:GetAbilityName(), "special_bonus_") then UTIL_Remove(ability) end end if heroTableCustom.base_hero then TransformUnitClass(hero, heroTableCustom) hero.UnitName = heroName end if Options:IsEquals("EnableAbilityShop") then for i = 0, hero:GetAbilityCount() - 1 do if hero:GetAbilityByIndex(i) then hero:RemoveAbility(hero:GetAbilityByIndex(i):GetName()) end end hero:AddAbility("ability_empty") hero:AddAbility("ability_empty") hero:AddAbility("ability_empty") hero:AddAbility("ability_empty") hero:AddAbility("ability_empty") hero:AddAbility("ability_empty") end if afterReplace then afterReplace(hero) end else return 0.1 end end) end if bSkipPrecache then SpawnHero() else PrecacheUnitByNameAsync(GetKeyValue(heroName, "base_hero") or heroName, SpawnHero, playerId) end else return 0.1 end end) end function HeroSelection:ChangeHero(playerId, newHeroName, keepExp, duration, item, callback, bUpdateStatus) local hero = PlayerResource:GetSelectedHeroEntity(playerId) if not hero.ForcedHeroChange then if hero:HasModifier("modifier_shredder_chakram_disarm") then Containers:DisplayError(playerId, "#arena_hud_error_cant_change_hero") return false end if hero:HasAbility("centaur_stampede") then local heroTeam = PlayerResource:GetTeam(playerId) for i = 0, 23 do local playerHero = PlayerResource:GetSelectedHeroEntity(i) if playerHero and PlayerResource:GetTeam(i) == heroTeam and playerHero:HasModifier("modifier_centaur_stampede") then Containers:DisplayError(playerId, "#arena_hud_error_cant_change_hero") return false end end end if hero:HasAbility("necrolyte_reapers_scythe") and AnyUnitHasModifier("modifier_necrolyte_reapers_scythe", hero) then Containers:DisplayError(playerId, "#arena_hud_error_cant_change_hero") return false end end local preDuration = 0 if hero:HasAbility("disruptor_thunder_strike") then local disruptor_thunder_strike = hero:FindAbilityByName("disruptor_thunder_strike") preDuration = disruptor_thunder_strike:GetSpecialValueFor("strikes") * disruptor_thunder_strike:GetSpecialValueFor("strike_interval") end hero.ChangingHeroProcessRunning = true ProjectileManager:ProjectileDodge(hero) if hero.PocketItem then hero.PocketHostEntity = nil UTIL_Remove(hero.PocketItem) hero.PocketItem = nil end hero:DestroyAllModifiers() hero:InterruptMotionControllers(false) hero:AddNewModifier(hero, nil, "modifier_hero_selection_transformation", nil) local xp = hero:GetCurrentXP() local location RemoveAllOwnedUnits(playerId) local startTime = GameRules:GetDOTATime(true, true) local items = {} local duelData = {} Timers:CreateTimer(preDuration, function() HeroSelection:SelectHero(playerId, newHeroName, function(oldHero) location = hero:GetAbsOrigin() local fountatin = FindFountain(PlayerResource:GetTeam(playerId)) if not location and fountatin then location = fountatin:GetAbsOrigin() end for i = DOTA_ITEM_SLOT_1, DOTA_STASH_SLOT_6 do local citem = hero:GetItemInSlot(i) if citem and citem ~= item then local newItem = CreateItem(citem:GetName(), nil, nil) if citem:GetPurchaser() ~= hero then newItem.NotPurchasedByOwner = true newItem:SetPurchaser(citem:GetPurchaser()) end newItem:SetPurchaseTime(citem:GetPurchaseTime()) newItem:SetCurrentCharges(citem:GetCurrentCharges()) if citem:GetCooldownTimeRemaining() > 0 then newItem.SavedCooldown = citem:GetCooldownTimeRemaining() end table.insert(items, newItem) else table.insert(items, CreateItem("item_dummy", hero, hero)) end end duelData.StatusBeforeArena = hero.StatusBeforeArena duelData.OnDuel = hero.OnDuel duelData.ArenaBeforeTpLocation = hero.ArenaBeforeTpLocation duelData.DuelChecked = hero.DuelChecked for team,tab in pairs(Duel.heroes_teams_for_duel or {}) do for i,unit in pairs(tab) do if unit == hero then duelData.path = {team, i} end end end end, function(newHero) newHero:AddNewModifier(newHero, nil, "modifier_hero_selection_transformation", nil) FindClearSpaceForUnit(newHero, location, true) if keepExp then newHero:AddExperience(xp, 0, true, true) end for _,v in ipairs(items) do v:SetOwner(newHero) if not v.NotPurchasedByOwner then v:SetPurchaser(newHero) v.NotPurchasedByOwner = nil end if v.SavedCooldown then v:StartCooldown(v.SavedCooldown) v.SavedCooldown = nil end newHero:AddItem(v) end ClearSlotsFromDummy(newHero) for k,v in pairs(duelData) do if k ~= "path" then newHero[k] = v else Duel.heroes_teams_for_duel[v[1]][v[1]] = newHero end end Timers:CreateTimer(startTime + (duration or 0) - GameRules:GetDOTATime(true, true), function() if IsValidEntity(newHero) then newHero:RemoveModifierByName("modifier_hero_selection_transformation") end end) if callback then callback(newHero) end end, nil, bUpdateStatus) end) return true end
fix(hero_selection): location is stored too early
fix(hero_selection): location is stored too early That allows to dodge unit:Teleport with HeroSelection:ChangeHero. Closes #274.
Lua
mit
ark120202/aabs
0e3f00f3f7adcc8becab35a7142b58dbaadcd01f
Lempel_Ziv_Welch/Lua/Yonaba/lzw.lua
Lempel_Ziv_Welch/Lua/Yonaba/lzw.lua
-- Lempel-Ziv Welch compression data algorithm implementation -- See : http://en.wikipedia.org/wiki/LZW local function lzw_encode(str) local w = '' local result = {} local dict_size = 255 -- Builds the dictionnary local dict = {} for i = 0, dict_size do dict[string.char(i)] = i end local i = dict_size for char in str:gmatch('.') do -- Finds the longest string matching the input local wc = w .. char if dict[wc] then -- Save the current match index w = wc else -- Add the match to the dictionary table.insert(result, dict[w]) i = i + 1 dict[wc] = i w = char end end if w~='' then table.insert(result, dict[w]) end return result end local function lzw_decode(str) local dict_size = 255 -- Builds the dictionary local dict = {} for i = 0, dict_size do dict[i] = string.char(i) end local w = string.char(str[1]) local result = w for i = 2, #str do local k = str[i] local entry = '' if dict[k] then entry = dict[k] elseif k == dict_size then entry = w .. w:sub(1,1) else return nil -- No match found, decoding error end result = result .. entry dict_size = dict_size + 1 dict[dict_size] = w .. entry:sub(1,1) w = entry end return result end return { encode = lzw_encode, decode = lzw_decode, }
-- Lempel-Ziv Welch compression data algorithm implementation -- See : http://en.wikipedia.org/wiki/LZW local function lzw_encode(str) local w = '' local result = {} local dict_size = 256 -- Builds the dictionnary local dict = {} for i = 0, dict_size-1 do dict[string.char(i)] = i end local i = dict_size for char in str:gmatch('.') do -- Finds the longest string matching the input local wc = w .. char if dict[wc] then -- Save the current match index w = wc else -- Add the match to the dictionary table.insert(result, dict[w]) dict[wc] = i i = i + 1 w = char end end if w~='' then table.insert(result, dict[w]) end return result end local function lzw_decode(str) local dict_size = 256 -- Builds the dictionary local dict = {} for i = 0, dict_size-1 do dict[i] = string.char(i) end local w = string.char(str[1]) local result = w for i = 2, #str do local k = str[i] local entry = '' if dict[k] then entry = dict[k] elseif k == dict_size then entry = w .. w:sub(1,1) else return nil -- No match found, decoding error end result = result .. entry dict[dict_size] = w .. entry:sub(1,1) dict_size = dict_size + 1 w = entry end return result end return { encode = lzw_encode, decode = lzw_decode, }
fix LZW decode error
fix LZW decode error
Lua
mit
isalnikov/Algorithm-Implementations,mishin/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,girishramnani/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,rohanp/Algorithm-Implementations,joshimoo/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,kidaa/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,Endika/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,Yonaba/Algorithm-Implementations,movb/Algorithm-Implementations,rohanp/Algorithm-Implementations,kidaa/Algorithm-Implementations,joshimoo/Algorithm-Implementations,warreee/Algorithm-Implementations,joshimoo/Algorithm-Implementations,warreee/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,jb1717/Algorithm-Implementations,rohanp/Algorithm-Implementations,jiang42/Algorithm-Implementations,mishin/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,kidaa/Algorithm-Implementations,kidaa/Algorithm-Implementations,movb/Algorithm-Implementations,jb1717/Algorithm-Implementations,vikas17a/Algorithm-Implementations,Etiene/Algorithm-Implementations,kennyledet/Algorithm-Implementations,Etiene/Algorithm-Implementations,Etiene/Algorithm-Implementations,jb1717/Algorithm-Implementations,Yonaba/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,kidaa/Algorithm-Implementations,jiang42/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,kennyledet/Algorithm-Implementations,movb/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,kennyledet/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,jiang42/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,Etiene/Algorithm-Implementations,mishin/Algorithm-Implementations,jb1717/Algorithm-Implementations,jb1717/Algorithm-Implementations,jb1717/Algorithm-Implementations,vikas17a/Algorithm-Implementations,warreee/Algorithm-Implementations,kennyledet/Algorithm-Implementations,movb/Algorithm-Implementations,rohanp/Algorithm-Implementations,pravsingh/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,pravsingh/Algorithm-Implementations,girishramnani/Algorithm-Implementations,movb/Algorithm-Implementations,warreee/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,imanmafi/Algorithm-Implementations,kennyledet/Algorithm-Implementations,joshimoo/Algorithm-Implementations,Endika/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,joshimoo/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,vikas17a/Algorithm-Implementations,mishin/Algorithm-Implementations,isalnikov/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,girishramnani/Algorithm-Implementations,isalnikov/Algorithm-Implementations,kidaa/Algorithm-Implementations,isalnikov/Algorithm-Implementations,jb1717/Algorithm-Implementations,Endika/Algorithm-Implementations,Yonaba/Algorithm-Implementations,jiang42/Algorithm-Implementations,kidaa/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,joshimoo/Algorithm-Implementations,pravsingh/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,isalnikov/Algorithm-Implementations,imanmafi/Algorithm-Implementations,kennyledet/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,isalnikov/Algorithm-Implementations,Endika/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,Yonaba/Algorithm-Implementations,warreee/Algorithm-Implementations,kidaa/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,girishramnani/Algorithm-Implementations,jb1717/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,rohanp/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,vikas17a/Algorithm-Implementations,vikas17a/Algorithm-Implementations,kennyledet/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,Yonaba/Algorithm-Implementations,joshimoo/Algorithm-Implementations,joshimoo/Algorithm-Implementations,girishramnani/Algorithm-Implementations,Endika/Algorithm-Implementations,Endika/Algorithm-Implementations,pravsingh/Algorithm-Implementations,rohanp/Algorithm-Implementations,movb/Algorithm-Implementations,kidaa/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,warreee/Algorithm-Implementations,rohanp/Algorithm-Implementations,joshimoo/Algorithm-Implementations,kidaa/Algorithm-Implementations,jiang42/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,jiang42/Algorithm-Implementations,kennyledet/Algorithm-Implementations,jb1717/Algorithm-Implementations,girishramnani/Algorithm-Implementations,jiang42/Algorithm-Implementations,Etiene/Algorithm-Implementations,isalnikov/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,mishin/Algorithm-Implementations,isalnikov/Algorithm-Implementations,imanmafi/Algorithm-Implementations,warreee/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,vikas17a/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,Etiene/Algorithm-Implementations,vikas17a/Algorithm-Implementations,warreee/Algorithm-Implementations,warreee/Algorithm-Implementations,pravsingh/Algorithm-Implementations,Endika/Algorithm-Implementations,jiang42/Algorithm-Implementations,imanmafi/Algorithm-Implementations,mishin/Algorithm-Implementations,Etiene/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,isalnikov/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,Yonaba/Algorithm-Implementations,pravsingh/Algorithm-Implementations,girishramnani/Algorithm-Implementations,vikas17a/Algorithm-Implementations,rohanp/Algorithm-Implementations,imanmafi/Algorithm-Implementations,jiang42/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,Etiene/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,imanmafi/Algorithm-Implementations,kennyledet/Algorithm-Implementations,mishin/Algorithm-Implementations,pravsingh/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,warreee/Algorithm-Implementations,pravsingh/Algorithm-Implementations,kennyledet/Algorithm-Implementations,kidaa/Algorithm-Implementations,isalnikov/Algorithm-Implementations,pravsingh/Algorithm-Implementations,imanmafi/Algorithm-Implementations,vikas17a/Algorithm-Implementations,jiang42/Algorithm-Implementations,isalnikov/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,kidaa/Algorithm-Implementations,girishramnani/Algorithm-Implementations,Endika/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,isalnikov/Algorithm-Implementations,Etiene/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,vikas17a/Algorithm-Implementations,isalnikov/Algorithm-Implementations,mishin/Algorithm-Implementations,pravsingh/Algorithm-Implementations,vikas17a/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,vikas17a/Algorithm-Implementations,Yonaba/Algorithm-Implementations,rohanp/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,isalnikov/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,pravsingh/Algorithm-Implementations,mishin/Algorithm-Implementations,Endika/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,imanmafi/Algorithm-Implementations,Endika/Algorithm-Implementations,Yonaba/Algorithm-Implementations,imanmafi/Algorithm-Implementations,jb1717/Algorithm-Implementations,jiang42/Algorithm-Implementations,jb1717/Algorithm-Implementations,rohanp/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,pravsingh/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,imanmafi/Algorithm-Implementations,movb/Algorithm-Implementations,movb/Algorithm-Implementations,rohanp/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,mishin/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,jiang42/Algorithm-Implementations,Endika/Algorithm-Implementations,girishramnani/Algorithm-Implementations,vikas17a/Algorithm-Implementations,Etiene/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,Yonaba/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,Yonaba/Algorithm-Implementations,Etiene/Algorithm-Implementations,Yonaba/Algorithm-Implementations,warreee/Algorithm-Implementations,jiang42/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,vikas17a/Algorithm-Implementations,isalnikov/Algorithm-Implementations,jb1717/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,kidaa/Algorithm-Implementations,rohanp/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,Endika/Algorithm-Implementations,kennyledet/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,joshimoo/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,joshimoo/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,Endika/Algorithm-Implementations,imanmafi/Algorithm-Implementations,pravsingh/Algorithm-Implementations,imanmafi/Algorithm-Implementations,movb/Algorithm-Implementations,Endika/Algorithm-Implementations,Etiene/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,girishramnani/Algorithm-Implementations,kidaa/Algorithm-Implementations,Yonaba/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,mishin/Algorithm-Implementations,kennyledet/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,kidaa/Algorithm-Implementations,kennyledet/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,mishin/Algorithm-Implementations,imanmafi/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,movb/Algorithm-Implementations,movb/Algorithm-Implementations,jb1717/Algorithm-Implementations,jiang42/Algorithm-Implementations,Yonaba/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,warreee/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,jb1717/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,jb1717/Algorithm-Implementations,vikas17a/Algorithm-Implementations,rohanp/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,pravsingh/Algorithm-Implementations,rohanp/Algorithm-Implementations,girishramnani/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,movb/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,rohanp/Algorithm-Implementations,joshimoo/Algorithm-Implementations,kennyledet/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,Endika/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,warreee/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,Etiene/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,warreee/Algorithm-Implementations,mishin/Algorithm-Implementations,joshimoo/Algorithm-Implementations,pravsingh/Algorithm-Implementations,warreee/Algorithm-Implementations,kennyledet/Algorithm-Implementations,movb/Algorithm-Implementations,Etiene/Algorithm-Implementations,imanmafi/Algorithm-Implementations,joshimoo/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,girishramnani/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,Yonaba/Algorithm-Implementations,Yonaba/Algorithm-Implementations,mishin/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,warreee/Algorithm-Implementations,mishin/Algorithm-Implementations,movb/Algorithm-Implementations,jiang42/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,joshimoo/Algorithm-Implementations,imanmafi/Algorithm-Implementations,movb/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations
3d4b64039079336348be5ea51610d17129ac8cda
core/ext/pm/buffer_browser.lua
core/ext/pm/buffer_browser.lua
-- Copyright 2007-2009 Mitchell Foral mitchell<att>caladbolg.net. See LICENSE. local textadept = _G.textadept local locale = _G.locale --- -- Buffer browser for the Textadept project manager. -- It is enabled with the prefix 'buffers' in the project manager entry field. module('textadept.pm.browsers.buffer', package.seeall) if not RESETTING then textadept.pm.add_browser('buffers') end function matches(entry_text) return entry_text:sub(1, 7) == 'buffers' end function get_contents_for() local contents = {} for index, buffer in ipairs(textadept.buffers) do index = string.format("%02i", index) contents[index] = { pixbuf = buffer.dirty and 'gtk-edit' or 'gtk-file', text = (buffer.filename or buffer._type or locale.UNTITLED):match('[^/\\]+$') } end return contents end function perform_action(selected_item) local index = selected_item[2] local buffer = textadept.buffers[tonumber(index)] if buffer then view:goto_buffer(index) view:focus() end end local ID = { NEW = 1, OPEN = 2, SAVE = 3, SAVEAS = 4, CLOSE = 5 } function get_context_menu(selected_item) return { { locale.PM_BROWSER_BUFFER_NEW, ID.NEW }, { locale.PM_BROWSER_BUFFER_OPEN, ID.OPEN }, { locale.PM_BROWSER_BUFFER_SAVE, ID.SAVE }, { locale.PM_BROWSER_BUFFER_SAVEAS, ID.SAVEAS }, { 'separator', 0 }, { locale.PM_BROWSER_BUFFER_CLOSE, ID.CLOSE }, } end local function update_view() if matches(textadept.pm.entry_text) then textadept.pm.activate() for idx, buf in ipairs(textadept.buffers) do if buf == buffer then textadept.pm.cursor = idx - 1 break end end end end function perform_menu_action(menu_id, selected_item) if menu_id == ID.NEW then textadept.new_buffer() elseif menu_id == ID.OPEN then textadept.io.open() elseif menu_id == ID.SAVE then view:goto_buffer(tonumber(selected_item[2])) buffer:save() elseif menu_id == ID.SAVEAS then view:goto_buffer(tonumber(selected_item[2])) buffer:save_as() elseif menu_id == ID.CLOSE then view:goto_buffer(tonumber(selected_item[2])) buffer:close() end update_view() end textadept.events.add_handler('file_opened', update_view) textadept.events.add_handler('buffer_new', update_view) textadept.events.add_handler('buffer_deleted', update_view) textadept.events.add_handler('save_point_reached', update_view) textadept.events.add_handler('save_point_left', update_view) textadept.events.add_handler('buffer_switch', update_view) textadept.events.add_handler('view_switch', update_view)
-- Copyright 2007-2009 Mitchell Foral mitchell<att>caladbolg.net. See LICENSE. local textadept = _G.textadept local locale = _G.locale --- -- Buffer browser for the Textadept project manager. -- It is enabled with the prefix 'buffers' in the project manager entry field. module('textadept.pm.browsers.buffer', package.seeall) if not RESETTING then textadept.pm.add_browser('buffers') end function matches(entry_text) return entry_text:sub(1, 7) == 'buffers' end function get_contents_for() local contents = {} for index, buffer in ipairs(textadept.buffers) do index = string.format("%02i", index) contents[index] = { pixbuf = buffer.dirty and 'gtk-edit' or 'gtk-file', text = (buffer.filename or buffer._type or locale.UNTITLED):match('[^/\\]+$') } end return contents end function perform_action(selected_item) local index = selected_item[2] local buffer = textadept.buffers[tonumber(index)] if buffer then view:goto_buffer(index) view:focus() end end local ID = { NEW = 1, OPEN = 2, SAVE = 3, SAVEAS = 4, CLOSE = 5 } function get_context_menu(selected_item) return { { locale.PM_BROWSER_BUFFER_NEW, ID.NEW }, { locale.PM_BROWSER_BUFFER_OPEN, ID.OPEN }, { locale.PM_BROWSER_BUFFER_SAVE, ID.SAVE }, { locale.PM_BROWSER_BUFFER_SAVEAS, ID.SAVEAS }, { 'separator', 0 }, { locale.PM_BROWSER_BUFFER_CLOSE, ID.CLOSE }, } end function perform_menu_action(menu_id, selected_item) if menu_id == ID.NEW then textadept.new_buffer() elseif menu_id == ID.OPEN then textadept.io.open() elseif menu_id == ID.SAVE then view:goto_buffer(tonumber(selected_item[2])) buffer:save() elseif menu_id == ID.SAVEAS then view:goto_buffer(tonumber(selected_item[2])) buffer:save_as() elseif menu_id == ID.CLOSE then view:goto_buffer(tonumber(selected_item[2])) buffer:close() end textadept.pm.activate() end local function update_view() if matches(textadept.pm.entry_text) then textadept.pm.activate() end end textadept.events.add_handler('file_opened', update_view) textadept.events.add_handler('buffer_new', update_view) textadept.events.add_handler('buffer_deleted', update_view) textadept.events.add_handler('save_point_reached', update_view) textadept.events.add_handler('save_point_left', update_view) textadept.events.add_handler('buffer_switch', update_view) textadept.events.add_handler('view_switch', update_view) local function set_cursor() if matches(textadept.pm.entry_text) then for idx, buf in ipairs(textadept.buffers) do if buf == buffer then textadept.pm.cursor = idx - 1 break end end end end textadept.events.add_handler('pm_view_filled', set_cursor)
Fixed issue with buffer browser cursor saving; core/ext/pm/buffer_browser.lua
Fixed issue with buffer browser cursor saving; core/ext/pm/buffer_browser.lua
Lua
mit
jozadaquebatista/textadept,jozadaquebatista/textadept
a2f970dd4fa6340b14e8e77366b082410ecb35b7
mod_auth_joomla/mod_auth_joomla.lua
mod_auth_joomla/mod_auth_joomla.lua
-- Joomla authentication backend for Prosody -- -- Copyright (C) 2011 Waqas Hussain -- local new_sasl = require "util.sasl".new; local nodeprep = require "util.encodings".stringprep.nodeprep; local saslprep = require "util.encodings".stringprep.saslprep; local DBI = require "DBI" local md5 = require "util.hashes".md5; local uuid_gen = require "util.uuid".generate; local connection; local params = module:get_option("sql"); local resolve_relative_path = require "core.configmanager".resolve_relative_path; local function test_connection() if not connection then return nil; end if connection:ping() then return true; else module:log("debug", "Database connection closed"); connection = nil; end end local function connect() if not test_connection() then prosody.unlock_globals(); local dbh, err = DBI.Connect( params.driver, params.database, params.username, params.password, params.host, params.port ); prosody.lock_globals(); if not dbh then module:log("debug", "Database connection failed: %s", tostring(err)); return nil, err; end module:log("debug", "Successfully connected to database"); dbh:autocommit(true); -- don't run in transaction connection = dbh; return connection; end end do -- process options to get a db connection params = params or { driver = "SQLite3" }; if params.driver == "SQLite3" then params.database = resolve_relative_path(prosody.paths.data or ".", params.database or "prosody.sqlite"); end assert(params.driver and params.database, "Both the SQL driver and the database need to be specified"); assert(connect()); end local function getsql(sql, ...) if params.driver == "PostgreSQL" then sql = sql:gsub("`", "\""); end if not test_connection() then connect(); end -- do prepared statement stuff local stmt, err = connection:prepare(sql); if not stmt and not test_connection() then error("connection failed"); end if not stmt then module:log("error", "QUERY FAILED: %s %s", err, debug.traceback()); return nil, err; end -- run query local ok, err = stmt:execute(...); if not ok and not test_connection() then error("connection failed"); end if not ok then return nil, err; end return stmt; end local function setsql(sql, ...) local stmt, err = getsql(sql, ...); if not stmt then return stmt, err; end return stmt:affected(); end local function get_password(username) local stmt, err = getsql("SELECT `password` FROM `jos_users` WHERE `username`=?", username); if stmt then for row in stmt:rows(true) do return row.password; end end end local function getCryptedPassword(plaintext, salt) local salted = plaintext..salt; return md5(salted, true); end local function joomlaCheckHash(password, hash) local crypt, salt = hash:match("^([^:]*):(.*)$"); return (crypt or hash) == getCryptedPassword(password, salt or ''); end local function joomlaCreateHash(password) local salt = uuid_gen():gsub("%-", ""); local crypt = getCryptedPassword(password, salt); return crypt..':'..salt; end provider = { name = "joomla" }; function provider.test_password(username, password) local hash = get_password(username); return hash and joomlaCheckHash(password, hash); end function provider.user_exists(username) module:log("debug", "test user %s existence", username); return get_password(username) and true; end function provider.get_password(username) return nil, "Getting password is not supported."; end function provider.set_password(username, password) local hash = joomlaCreateHash(password); local stmt, err = setsql("UPDATE `jos_users` SET `password`=? WHERE `username`=?", hash, username); return stmt and true, err; end function provider.create_user(username, password) return nil, "Account creation/modification not supported."; end local escapes = { [" "] = "\\20"; ['"'] = "\\22"; ["&"] = "\\26"; ["'"] = "\\27"; ["/"] = "\\2f"; [":"] = "\\3a"; ["<"] = "\\3c"; [">"] = "\\3e"; ["@"] = "\\40"; ["\\"] = "\\5c"; }; local unescapes = {}; for k,v in pairs(escapes) do unescapes[v] = k; end local function jid_escape(s) return s and (s:gsub(".", escapes)); end local function jid_unescape(s) return s and (s:gsub("\\%x%x", unescapes)); end function provider.get_sasl_handler() local sasl = {}; function sasl:clean_clone() return provider.get_sasl_handler(); end function sasl:mechanisms() return { PLAIN = true; }; end function sasl:select(mechanism) if not self.selected and mechanism == "PLAIN" then self.selected = mechanism; return true; end end function sasl:process(message) if not message then return "failure", "malformed-request"; end local authorization, authentication, password = message:match("^([^%z]*)%z([^%z]+)%z([^%z]+)"); if not authorization then return "failure", "malformed-request"; end authentication = saslprep(authentication); password = saslprep(password); if (not password) or (password == "") or (not authentication) or (authentication == "") then return "failure", "malformed-request", "Invalid username or password."; end local function test(authentication) local prepped = nodeprep(authentication); local normalized = jid_unescape(prepped); return normalized and provider.test_password(normalized, password) and prepped; end local username = test(authentication) or test(jid_escape(authentication)); if username then self.username = username; return "success"; end return "failure", "not-authorized", "Unable to authorize you with the authentication credentials you've sent."; end return sasl; end module:add_item("auth-provider", provider);
-- Joomla authentication backend for Prosody -- -- Copyright (C) 2011 Waqas Hussain -- local new_sasl = require "util.sasl".new; local nodeprep = require "util.encodings".stringprep.nodeprep; local saslprep = require "util.encodings".stringprep.saslprep; local DBI = require "DBI" local md5 = require "util.hashes".md5; local uuid_gen = require "util.uuid".generate; local connection; local params = module:get_option("sql"); local prefix = params and params.prefix or "jos_"; local resolve_relative_path = require "core.configmanager".resolve_relative_path; local function test_connection() if not connection then return nil; end if connection:ping() then return true; else module:log("debug", "Database connection closed"); connection = nil; end end local function connect() if not test_connection() then prosody.unlock_globals(); local dbh, err = DBI.Connect( params.driver, params.database, params.username, params.password, params.host, params.port ); prosody.lock_globals(); if not dbh then module:log("debug", "Database connection failed: %s", tostring(err)); return nil, err; end module:log("debug", "Successfully connected to database"); dbh:autocommit(true); -- don't run in transaction connection = dbh; return connection; end end do -- process options to get a db connection params = params or { driver = "SQLite3" }; if params.driver == "SQLite3" then params.database = resolve_relative_path(prosody.paths.data or ".", params.database or "prosody.sqlite"); end assert(params.driver and params.database, "Both the SQL driver and the database need to be specified"); assert(connect()); end local function getsql(sql, ...) if params.driver == "PostgreSQL" then sql = sql:gsub("`", "\""); end if not test_connection() then connect(); end -- do prepared statement stuff local stmt, err = connection:prepare(sql); if not stmt and not test_connection() then error("connection failed"); end if not stmt then module:log("error", "QUERY FAILED: %s %s", err, debug.traceback()); return nil, err; end -- run query local ok, err = stmt:execute(...); if not ok and not test_connection() then error("connection failed"); end if not ok then return nil, err; end return stmt; end local function setsql(sql, ...) local stmt, err = getsql(sql, ...); if not stmt then return stmt, err; end return stmt:affected(); end local function get_password(username) local stmt, err = getsql("SELECT `password` FROM `"..prefix.."users` WHERE `username`=?", username); if stmt then for row in stmt:rows(true) do return row.password; end end end local function getCryptedPassword(plaintext, salt) local salted = plaintext..salt; return md5(salted, true); end local function joomlaCheckHash(password, hash) local crypt, salt = hash:match("^([^:]*):(.*)$"); return (crypt or hash) == getCryptedPassword(password, salt or ''); end local function joomlaCreateHash(password) local salt = uuid_gen():gsub("%-", ""); local crypt = getCryptedPassword(password, salt); return crypt..':'..salt; end provider = { name = "joomla" }; function provider.test_password(username, password) local hash = get_password(username); return hash and joomlaCheckHash(password, hash); end function provider.user_exists(username) module:log("debug", "test user %s existence", username); return get_password(username) and true; end function provider.get_password(username) return nil, "Getting password is not supported."; end function provider.set_password(username, password) local hash = joomlaCreateHash(password); local stmt, err = setsql("UPDATE `"..prefix.."users` SET `password`=? WHERE `username`=?", hash, username); return stmt and true, err; end function provider.create_user(username, password) return nil, "Account creation/modification not supported."; end local escapes = { [" "] = "\\20"; ['"'] = "\\22"; ["&"] = "\\26"; ["'"] = "\\27"; ["/"] = "\\2f"; [":"] = "\\3a"; ["<"] = "\\3c"; [">"] = "\\3e"; ["@"] = "\\40"; ["\\"] = "\\5c"; }; local unescapes = {}; for k,v in pairs(escapes) do unescapes[v] = k; end local function jid_escape(s) return s and (s:gsub(".", escapes)); end local function jid_unescape(s) return s and (s:gsub("\\%x%x", unescapes)); end function provider.get_sasl_handler() local sasl = {}; function sasl:clean_clone() return provider.get_sasl_handler(); end function sasl:mechanisms() return { PLAIN = true; }; end function sasl:select(mechanism) if not self.selected and mechanism == "PLAIN" then self.selected = mechanism; return true; end end function sasl:process(message) if not message then return "failure", "malformed-request"; end local authorization, authentication, password = message:match("^([^%z]*)%z([^%z]+)%z([^%z]+)"); if not authorization then return "failure", "malformed-request"; end authentication = saslprep(authentication); password = saslprep(password); if (not password) or (password == "") or (not authentication) or (authentication == "") then return "failure", "malformed-request", "Invalid username or password."; end local function test(authentication) local prepped = nodeprep(authentication); local normalized = jid_unescape(prepped); return normalized and provider.test_password(normalized, password) and prepped; end local username = test(authentication) or test(jid_escape(authentication)); if username then self.username = username; return "success"; end return "failure", "not-authorized", "Unable to authorize you with the authentication credentials you've sent."; end return sasl; end module:add_item("auth-provider", provider);
mod_auth_joomla: Added config option sql.prefix (default = "jos_").
mod_auth_joomla: Added config option sql.prefix (default = "jos_").
Lua
mit
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
c1d48327438516ad5c5a69a43fc8c4de655793ff
snapshots.lua
snapshots.lua
local std = stead local type = std.type local SNAPSHOT = false local snap = std.obj { nam = '@snaphots'; data = {}; make = function(s, name) name = name or 'default' local fp = { -- fake file object data = ''; write = function(s, str) s.data = s.data .. str end; } std:save(fp) s.data[name] = fp.data end; exist = function(s, name) name = name or 'default' return s.data[name] end; remove = function(s, name) name = name or 'default' s.data[name] = nil end; restore = function(s, name) -- like std:load() name = name or 'default' if not s:exist(name) then return false end std:reset() std.ref 'game':ini(true) local f, err = std.eval(s.data[name]) if not f then std.err(err, 2) end f(); std.ref 'game':ini() return std.nop() end; } snapshots = snap std.mod_cmd(function() if SNAPSHOT then snap:make(snap.SNAPSHOT) SNAPSHOT = nil end end) std.mod_done(function() snap.data = {} end)
local std = stead local type = std.type local SNAPSHOT = false local snap = std.obj { nam = '@snaphots'; data = {}; write = function(s, name) name = name or 'default' local fp = { -- fake file object data = ''; write = function(s, str) s.data = s.data .. str end; } std:save(fp) s.data[name] = fp.data end; make = function(s) SNAPSHOT = true end; exist = function(s, name) name = name or 'default' return s.data[name] end; remove = function(s, name) name = name or 'default' s.data[name] = nil end; restore = function(s, name) -- like std:load() name = name or 'default' if not s:exist(name) then return false end std:reset() std.ref 'game':ini(true) local f, err = std.eval(s.data[name]) if not f then std.err(err, 2) end f(); std.ref 'game':ini() return std.nop() end; } snapshots = snap std.mod_cmd(function() if SNAPSHOT then snap:write(snap.SNAPSHOT) SNAPSHOT = nil end end) std.mod_done(function() snap.data = {} end)
snap fix
snap fix
Lua
mit
gl00my/stead3
1f46de9d2f7a9420e48c533af7a4b1b6118aa130
scripts/lua/management/lib/tenants.lua
scripts/lua/management/lib/tenants.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 tenants -- Management interface for tenants for the gateway local cjson = require "cjson" local redis = require "lib/redis" local utils = require "lib/utils" local request = require "lib/request" local apis = require "management/lib/apis" local _M = {}; function _M.addTenant(dataStore, decoded, existingTenant) -- Return tenant object local uuid = existingTenant ~= nil and existingTenant.id or utils.uuid() local tenantObj = { id = uuid, namespace = decoded.namespace, instance = decoded.instance } tenantObj = dataStore:addTenant(uuid, tenantObj) return cjson.decode(tenantObj) end --- Get all tenants in redis -- @param ds redis client -- @param queryParams object containing optional query parameters function _M.getAllTenants(dataStore, queryParams) local tenants = dataStore:getAllTenants() local tenantList if next(queryParams) ~= nil then tenantList = filterTenants(tenants, queryParams); end if tenantList == nil then tenantList = {} for k, v in pairs(tenants) do if k%2 == 0 then tenantList[#tenantList+1] = cjson.decode(v) end end end return tenantList end --- Filter tenants based on query parameters -- @param tenants list of tenants -- @param queryParams query parameters to filter tenants function filterTenants(tenants, queryParams) local namespace = queryParams['filter[where][namespace]'] local instance = queryParams['filter[where][instance]'] -- missing or invalid query parameters if (namespace == nil and instance == nil) or (instance ~= nil and namespace == nil) then return nil end -- filter tenants local tenantList = {} for k, v in pairs(tenants) do if k%2 == 0 then local tenant = cjson.decode(v) if (namespace ~= nil and instance == nil and tenant.namespace == namespace) or (namespace ~= nil and instance ~= nil and tenant.namespace == namespace and tenant.instance == instance) then tenantList[#tenantList+1] = tenant end end end return tenantList end --- Get tenant by its id -- @param ds redis client -- @param id tenant id function _M.getTenant(dataStore, id) local tenant = dataStore:getTenant(id) if tenant == nil then request.err(404, utils.concatStrings({"Unknown tenant id ", id })) end return tenant end --- Get APIs associated with tenant -- @param ds redis client -- @param id tenant id -- @param queryParams object containing optional query parameters function _M.getTenantAPIs(dataStore, id, queryParams) local apis = dataStore:getAllAPIs() local apiList if next(queryParams) ~= nil then apiList = filterTenantAPIs(id, apis, queryParams); end if apiList == nil then apiList = {} for k, v in pairs(apis) do if k%2 == 0 then local decoded = cjson.decode(v) if decoded.tenantId == id then apiList[#apiList+1] = decoded end end end end return apiList end --- Filter apis based on query paramters -- @param queryParams query parameters to filter apis function filterTenantAPIs(id, apis, queryParams) local basePath = queryParams['filter[where][basePath]'] basePath = basePath == nil and queryParams['basePath'] or basePath local name = queryParams['filter[where][name]'] name = name == nil and queryParams['title'] or name -- missing query parameters if (basePath == nil and name == nil)then return nil end -- filter apis local apiList = {} for k, v in pairs(apis) do if k%2 == 0 then local api = cjson.decode(v) if api.tenantId == id and ((basePath ~= nil and name == nil and api.basePath == basePath) or (name ~= nil and basePath == nil and api.name == name) or (basePath ~= nil and name ~= nil and api.basePath == basePath and api.name == name)) then apiList[#apiList+1] = api end end end return apiList end --- Delete tenant from gateway -- @param ds redis client -- @param id id of tenant to delete function _M.deleteTenant(dataStore, id) local tenantAPIs = _M.getTenantAPIs(dataStore, id, {}) for _, v in pairs(tenantAPIs) do apis.deleteAPI(dataStore, v.id) end dataStore:deleteTenant(id) return {} 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 tenants -- Management interface for tenants for the gateway local cjson = require "cjson" local redis = require "lib/redis" local utils = require "lib/utils" local request = require "lib/request" local apis = require "management/lib/apis" local _M = {}; function _M.addTenant(dataStore, decoded, existingTenant) -- Return tenant object local uuid = existingTenant ~= nil and existingTenant.id or utils.uuid() local tenantObj = { id = uuid, namespace = decoded.namespace, instance = decoded.instance } tenantObj = dataStore:addTenant(uuid, tenantObj) return cjson.decode(tenantObj) end --- Get all tenants in redis -- @param ds redis client -- @param queryParams object containing optional query parameters function _M.getAllTenants(dataStore, queryParams) local tenants = dataStore:getAllTenants() local tenantList if next(queryParams) ~= nil then tenantList = filterTenants(tenants, queryParams); end if tenantList == nil then tenantList = {} for k, v in pairs(tenants) do if k%2 == 0 then tenantList[#tenantList+1] = cjson.decode(v) end end end return tenantList end --- Filter tenants based on query parameters -- @param tenants list of tenants -- @param queryParams query parameters to filter tenants function filterTenants(tenants, queryParams) local namespace = queryParams['filter[where][namespace]'] local instance = queryParams['filter[where][instance]'] -- missing or invalid query parameters if (namespace == nil and instance == nil) or (instance ~= nil and namespace == nil) then return nil end -- filter tenants local tenantList = {} for k, v in pairs(tenants) do if k%2 == 0 then local tenant = cjson.decode(v) if (namespace ~= nil and instance == nil and tenant.namespace == namespace) or (namespace ~= nil and instance ~= nil and tenant.namespace == namespace and tenant.instance == instance) then tenantList[#tenantList+1] = tenant end end end return tenantList end --- Get tenant by its id -- @param ds redis client -- @param id tenant id function _M.getTenant(dataStore, id) local tenant = dataStore:getTenant(id) if tenant == nil then request.err(404, utils.concatStrings({"Unknown tenant id ", id })) end return tenant end --- Get APIs associated with tenant -- @param ds redis client -- @param id tenant id -- @param queryParams object containing optional query parameters function _M.getTenantAPIs(dataStore, id, queryParams) local apis = dataStore:getAllAPIs() local apiList if next(queryParams) ~= nil then apiList = filterTenantAPIs(id, apis, queryParams); end if apiList == nil then apiList = {} for k, v in pairs(apis) do if k%2 == 0 then local decoded = cjson.decode(v) if decoded.tenantId == id then apiList[#apiList+1] = decoded end end end end if ((queryParams['skip'] == nil and queryParams['limit'] == nil) or table.getn(apiList) == 0) then return apiList else return applyPagingToAPIs(apiList, queryParams) end end -- Apply paging on apis -- @param apis the list of apis -- @param queryparams object containing optional query parameters function applyPagingToAPIs(apiList, queryParams) local skip = queryParams['skip'] == nil and 1 or queryParams['skip'] local limit = queryParams['limit'] == nil and table.getn(apiList) or queryParams['limit'] if (tonumber(limit) < 1) then return {} end if (tonumber(skip) <= 0) then skip = 1 else skip = skip + 1 end if ((skip + limit - 1) > table.getn(apiList)) then limit = table.getn(apiList) else limit = skip + limit - 1 end local apis = {} local idx = 0 for i = skip, limit do apis[idx] = apiList[i] idx = idx + 1 end return apis end --- Filter apis based on query paramters -- @param queryParams query parameters to filter apis function filterTenantAPIs(id, apis, queryParams) local basePath = queryParams['filter[where][basePath]'] basePath = basePath == nil and queryParams['basePath'] or basePath local name = queryParams['filter[where][name]'] name = name == nil and queryParams['title'] or name -- missing query parameters if (basePath == nil and name == nil)then return nil end -- filter apis local apiList = {} for k, v in pairs(apis) do if k%2 == 0 then local api = cjson.decode(v) if api.tenantId == id and ((basePath ~= nil and name == nil and api.basePath == basePath) or (name ~= nil and basePath == nil and api.name == name) or (basePath ~= nil and name ~= nil and api.basePath == basePath and api.name == name)) then apiList[#apiList+1] = api end end end return apiList end --- Delete tenant from gateway -- @param ds redis client -- @param id id of tenant to delete function _M.deleteTenant(dataStore, id) local tenantAPIs = _M.getTenantAPIs(dataStore, id, {}) for _, v in pairs(tenantAPIs) do apis.deleteAPI(dataStore, v.id) end dataStore:deleteTenant(id) return {} end return _M
Add paging to getTenantAPIs (#335)
Add paging to getTenantAPIs (#335) * Fix for https://github.com/apache/incubator-openwhisk/issues/1692#issuecomment-463651323
Lua
unknown
openwhisk/openwhisk-apigateway,alexsong93/openwhisk-apigateway,openwhisk/apigateway,openwhisk/apigateway,openwhisk/apigateway,openwhisk/openwhisk-apigateway,alexsong93/openwhisk-apigateway,alexsong93/openwhisk-apigateway,openwhisk/openwhisk-apigateway
003267b1145b02f7719dc084633bc5cf32e2aedb
usage-detector_0.17.0/usage_detector.lua
usage-detector_0.17.0/usage_detector.lua
--current_machines = {} -- table of: entity + recipe + count -- TODO: Player-specific. Multiplayer support. -- Potential improvement: "How is Iron used?" -- a lot probably goes to iron gear wheel, but how is those gears then used? -- production for transport belts for example uses a lot of gears. -- likewise for production for military science packs. -- Saying "I want to know about Iron, and gears" would be nice -- and then "I want to summarize the results for all transport belts" local function is_using_product(entity, product) local recipe = entity.get_recipe() if entity.type == "furnace" and recipe == nil then recipe = entity.previous_recipe end if not recipe then return nil end for _, ingredient in ipairs(recipe.ingredients) do if ingredient.type == product.type and ingredient.name == product.name then return { recipe = recipe, amount = ingredient.amount } end end return nil end local function add_to_if_using(job, entities, target_list, ingredient_product) for _, entity in ipairs(entities) do local ingredient = is_using_product(entity, ingredient_product) if ingredient then table.insert(target_list, { entity = entity, recipe = ingredient.recipe, amount = ingredient.amount, count = 0, last_progress = entity.crafting_progress }) if not job.results[ingredient.recipe.name] then job.results[ingredient.recipe.name] = { recipe = ingredient.recipe, amount = ingredient.amount, count = 0, machine_count = 0 } end job.results[ingredient.recipe.name].machine_count = job.results[ingredient.recipe.name].machine_count + 1 end end end local function create_empty_job(player, job_name) local player_data = global.player_data[player.index] or { jobs = {} } global.player_data[player.index] = player_data player_data.jobs[job_name] = { current_thing = nil, current_furnaces = {}, current_machines = {}, results = {}, running = false, started_at = 0, stopped_at = 0 } end local function start(player, item_or_fluid, section_name) local player_data = global.player_data[player.index] create_empty_job(player, section_name) local job = player_data.jobs[section_name] job.current_thing = item_or_fluid job.running = true job.started_at = game.tick for _, surface in pairs(game.surfaces) do local furnaces = surface.find_entities_filtered({type = "furnace"}) add_to_if_using(job, furnaces, job.current_furnaces, item_or_fluid) local assembling_machines = surface.find_entities_filtered({type = "assembling-machine"}) add_to_if_using(job, assembling_machines, job.current_machines, item_or_fluid) end end local function check_progress(job, entity_data) if not entity_data.entity.valid then return end if not entity_data.recipe.valid then return end local progress = entity_data.entity.crafting_progress local last_progress = entity_data.last_progress if progress < last_progress then entity_data.count = entity_data.count + 1 job.results[entity_data.recipe.name].count = job.results[entity_data.recipe.name].count + 1 end entity_data.last_progress = progress end local function tick(job) if not job.running then return end for _, furnace in ipairs(job.current_furnaces) do check_progress(job, furnace) end for _, machine in ipairs(job.current_machines) do check_progress(job, machine) end end local function stop(player, section_name) local job = global.player_data[player.index].jobs[section_name] job.running = false job.stopped_at = game.tick end return { start = start, create_empty_job = create_empty_job, onTick = tick, stop = stop }
--current_machines = {} -- table of: entity + recipe + count -- TODO: Player-specific. Multiplayer support. -- Potential improvement: "How is Iron used?" -- a lot probably goes to iron gear wheel, but how is those gears then used? -- production for transport belts for example uses a lot of gears. -- likewise for production for military science packs. -- Saying "I want to know about Iron, and gears" would be nice -- and then "I want to summarize the results for all transport belts" local function is_using_product(entity, product) local recipe = entity.get_recipe() if entity.type == "furnace" and recipe == nil then recipe = entity.previous_recipe end if not recipe then return nil end for _, ingredient in ipairs(recipe.ingredients) do if ingredient.type == product.type and ingredient.name == product.name then return { recipe = recipe, amount = ingredient.amount } end end return nil end local function add_to_if_using(job, entities, target_list, ingredient_product) for _, entity in ipairs(entities) do local ingredient = is_using_product(entity, ingredient_product) if ingredient then table.insert(target_list, { entity = entity, recipe = ingredient.recipe, amount = ingredient.amount, count = 0, last_progress = entity.crafting_progress }) if not job.results[ingredient.recipe.name] then job.results[ingredient.recipe.name] = { recipe = ingredient.recipe, amount = ingredient.amount, count = 0, machine_count = 0 } end job.results[ingredient.recipe.name].machine_count = job.results[ingredient.recipe.name].machine_count + 1 end end end local function create_empty_job(player, job_name) local player_data = global.player_data[player.index] or { jobs = {} } global.player_data[player.index] = player_data player_data.jobs[job_name] = { current_thing = nil, current_furnaces = {}, current_machines = {}, results = {}, running = false, started_at = 0, stopped_at = 0 } end local function start(player, item_or_fluid, section_name) local player_data = global.player_data[player.index] create_empty_job(player, section_name) local job = player_data.jobs[section_name] job.current_thing = item_or_fluid job.running = true job.started_at = game.tick for _, surface in pairs(game.surfaces) do local furnaces = surface.find_entities_filtered({type = "furnace"}) add_to_if_using(job, furnaces, job.current_furnaces, item_or_fluid) local assembling_machines = surface.find_entities_filtered({type = "assembling-machine"}) add_to_if_using(job, assembling_machines, job.current_machines, item_or_fluid) end end local function check_progress(job, entity_data) if not entity_data.entity.valid then return end if not entity_data.recipe.valid then return end local progress = entity_data.entity.crafting_progress local last_progress = entity_data.last_progress if not job.results[entity_data.recipe.name] then -- Bugfix for https://mods.factorio.com/mod/usage-detector/discussion/5c925495cc0838000dcd2e05 return end if progress < last_progress then entity_data.count = entity_data.count + 1 job.results[entity_data.recipe.name].count = job.results[entity_data.recipe.name].count + 1 end entity_data.last_progress = progress end local function tick(job) if not job.running then return end for _, furnace in ipairs(job.current_furnaces) do check_progress(job, furnace) end for _, machine in ipairs(job.current_machines) do check_progress(job, machine) end end local function stop(player, section_name) local job = global.player_data[player.index].jobs[section_name] job.running = false job.stopped_at = game.tick end return { start = start, create_empty_job = create_empty_job, onTick = tick, stop = stop }
Usage Detector: Fix bug with no job results found
Usage Detector: Fix bug with no job results found
Lua
mit
Zomis/FactorioMods
057d9e6200e161cf1b4e832248fe1d59a67142c8
src/lua/css.lua
src/lua/css.lua
local explode = string.explode local string = unicode.utf8 local function new(self) c = { rules = {}, priorities = {}, } setmetatable(c,self) self.__index = self return c end -- sanitize selector and calculate priority local function get_priority( selector ) prio = 0 string.gsub(selector,"[%.#]?[^%s.]+",function ( x ) if string.match(x,"^#") then prio = prio + 100 elseif string.match(x,"^%.") then prio = prio + 10 else prio = prio + 1 end end) local sel = string.gsub(selector,"^%s*(.-)%s*$","%1") return sel,prio end local function parsetxt(self,csstext) csstext = string.gsub(csstext,"%s+"," ") -- remove comments: csstext = string.gsub(csstext,"/%*.-%*/"," ") local stop,selector,selectors,rules,rule,property,expr,rule_stop stop = 0 while true do _,stop,selector = string.find(csstext,"^%s*([^{]+)",stop + 1) if not selector then break end _, stop,rules_text = string.find(csstext,"{([^}]+)}%s*",stop + 1) if not rules_text then return end rules = explode(rules_text,";") local rules_t = {} for i=1,#rules do rule = rules[i] -- if it's not only whitespace if not string.match(rule,"^%s*$") then _,rule_stop,property = string.find(rule,"%s*([^:]+):") _,_,expr = string.find(rule,"^%s*(.-)%s*$",rule_stop + 1) rules_t[property] = expr end end selectors = explode(selector,",") local sel for i=1,#selectors do sel, prio = get_priority(selectors[i]) self.rules[prio] = self.rules[prio] or {} self.rules[prio][sel] = self.rules[prio][sel] or {} for k,v in pairs(rules_t) do self.rules[prio][sel][k] = v end end end local prio_found -- We remember the priority for later use. for prio,_ in pairs(self.rules) do prio_found = false for i=1,#self.priorities do if self.priorities[i] == prio then prio_found = true break end end if prio_found == false then self.priorities[#self.priorities + 1] = prio end end -- now sort the table with the priorities, so we can access the -- rules in the order of priorities (that's the whole point) table.sort( self.priorities,function ( a,b ) return a > b end ) end local function parse( self,filename) local path = kpse.find_file(filename) if not path then err("CSS: cannot find filename %q.",filename or "--") return end log("Loading CSS %q",path) local cssio = io.open(path,"rb") local csstext = cssio:read("*all") cssio:close() return parsetxt(self,csstext) end --- tbl has these entries: --- --- * `id` --- * `class` --- * `element` --- * `parent` --- local function matches_selector(tbl,selector ) local element,class,id = tbl.element,tbl.class,tbl.id local id_found ,class_found ,element_found = false,false,false local id_matches ,class_matches ,element_matches = false,false,false local id_required,class_required,element_required = tbl.id ~= nil, tbl.class ~= nil, tbl.element ~= nil -- todo: element_required is probably never false since the publisher always presents an element name local return_false = false string.gsub(selector,"[%.#]?[^%s.#]+",function ( x ) if string.match(x,"^#") then if not id_required then return_false = true end id_found = true if id and string.match(id,escape_lua_pattern(string.sub(x,2))) then id_matches = true end elseif string.match(x,"^%.") then if not class_required then return_false = true end class_found = true if class and string.match(class,escape_lua_pattern(string.sub(x,2))) then class_matches = true end else if not element_required then return_false = true end element_found = true if element and string.match(element,"^" .. escape_lua_pattern(x) .. "$") then element_matches = true end end end) if return_false then return false end -- We return true if we have found something that matches and if these elements, if found, match the requested ones from the tbl return element_found == element_matches and class_found == class_matches and id_found == id_matches and (class_found or element_found or id_found) end local function matches(self,tbl,level) level = level or 1 local rules,interesting_part,parts for _,v in ipairs(self.priorities) do for selector,rule in pairs(self.rules[v]) do parts = explode(selector," ") -- the interesting part depends on the level: -- level 1: the last part, level 2, the second last part, ... interesting_part = parts[#parts + 1 - level] if matches_selector(tbl,interesting_part) == true then return rule end end end return nil end return { new = new, parse = parse, parsetxt = parsetxt, matches = matches, }
--- This file contains the code for the CSS parser. -- -- css.lua -- speedata publisher -- -- For a list of authors see `git blame' -- See file COPYING in the root directory for license info. local explode = string.explode local string = unicode.utf8 local function new(self) c = { rules = {}, priorities = {}, } setmetatable(c,self) self.__index = self return c end -- sanitize selector and calculate priority local function get_priority( selector ) prio = 0 string.gsub(selector,"[%.#]?[^%s.]+",function ( x ) if string.match(x,"^#") then prio = prio + 100 elseif string.match(x,"^%.") then prio = prio + 10 else prio = prio + 1 end end) local sel = string.gsub(selector,"^%s*(.-)%s*$","%1") return sel,prio end local function parsetxt(self,csstext) csstext = string.gsub(csstext,"%s+"," ") -- remove comments: csstext = string.gsub(csstext,"/%*.-%*/"," ") local stop,selector,selectors,rules,rule,property,expr,rule_stop stop = 0 while true do _,stop,selector = string.find(csstext,"^%s*([^{]+)",stop + 1) if not selector then break end _, stop,rules_text = string.find(csstext,"{([^}]+)}%s*",stop + 1) if not rules_text then return end rules = explode(rules_text,";") local rules_t = {} for i=1,#rules do rule = rules[i] -- if it's not only whitespace if not string.match(rule,"^%s*$") then _,rule_stop,property = string.find(rule,"%s*([^:]+):") _,_,expr = string.find(rule,"^%s*(.-)%s*$",rule_stop + 1) rules_t[property] = expr end end selectors = explode(selector,",") local sel for i=1,#selectors do sel, prio = get_priority(selectors[i]) self.rules[prio] = self.rules[prio] or {} self.rules[prio][sel] = self.rules[prio][sel] or {} for k,v in pairs(rules_t) do self.rules[prio][sel][k] = v end end end local prio_found -- We remember the priority for later use. for prio,_ in pairs(self.rules) do prio_found = false for i=1,#self.priorities do if self.priorities[i] == prio then prio_found = true break end end if prio_found == false then self.priorities[#self.priorities + 1] = prio end end -- now sort the table with the priorities, so we can access the -- rules in the order of priorities (that's the whole point) table.sort( self.priorities,function ( a,b ) return a > b end ) end local function parse( self,filename) local path = kpse.find_file(filename) if not path then err("CSS: cannot find filename %q.",filename or "--") return end log("Loading CSS %q",path) local cssio = io.open(path,"rb") local csstext = cssio:read("*all") cssio:close() return parsetxt(self,csstext) end --- tbl has these entries: --- --- * `id` --- * `class` --- * `element` --- * `parent` --- local function matches_selector(tbl,selector ) local element,class,id = tbl.element,tbl.class,tbl.id local id_found ,class_found ,element_found = false,false,false local id_matches ,class_matches ,element_matches = false,false,false local id_required,class_required,element_required = tbl.id ~= nil, tbl.class ~= nil, tbl.element ~= nil -- todo: element_required is probably never false since the publisher always presents an element name local return_false = false string.gsub(selector,"[%.#]?[^%s.#]+",function ( x ) if string.match(x,"^#") then if not id_required then return_false = true end id_found = true if id and string.match(id,escape_lua_pattern(string.sub(x,2))) then id_matches = true end elseif string.match(x,"^%.") then if not class_required then return_false = true end class_found = true if class and string.match(class,escape_lua_pattern(string.sub(x,2)).. "$") then class_matches = true end else if not element_required then return_false = true end element_found = true if element and string.match(element,"^" .. escape_lua_pattern(x) .. "$") then element_matches = true end end end) if return_false then return false end -- We return true if we have found something that matches and if these elements, if found, match the requested ones from the tbl return element_found == element_matches and class_found == class_matches and id_found == id_matches and (class_found or element_found or id_found) end -- tbl = element, class, id local function matches(self,tbl,level) level = level or 1 local rules,interesting_part,parts for _,v in ipairs(self.priorities) do for selector,rule in pairs(self.rules[v]) do parts = explode(selector," ") -- the interesting part depends on the level: -- level 1: the last part, level 2, the second last part, ... interesting_part = parts[#parts + 1 - level] if matches_selector(tbl,interesting_part) == true then return rule end end end return nil end return { new = new, parse = parse, parsetxt = parsetxt, matches = matches, }
Better match of CSS classes
Better match of CSS classes Don't match if a common prefix matches. This fixes #134.
Lua
agpl-3.0
speedata/publisher,speedata/publisher,speedata/publisher,speedata/publisher
a8d5da851d1d469587adea086c65d61ae20c50ef
xmake/platforms/windows/environment.lua
xmake/platforms/windows/environment.lua
--!The Make-like Build Utility based on Lua -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2017, TBOOX Open Source Group. -- -- @author ruki -- @file environment.lua -- -- imports import("core.project.config") import("core.project.global") -- enter the given environment function _enter(name) -- get vcvarsall local vcvarsall = config.get("__vcvarsall") or global.get("__vcvarsall") if not vcvarsall then return end -- get vs environment for the current arch local vsenv = vcvarsall[config.get("arch") or ""] or {} -- get the pathes for the vs environment local old = nil local new = vsenv[name] if new then -- get the current pathes old = os.getenv(name) or "" -- append the current pathes new = new .. ";" .. old -- update the pathes for the environment os.setenv(name, new) end -- return the previous environment return old end -- leave the given environment function _leave(name, old) -- restore the previous environment if old then os.setenv(name, old) end end -- enter the toolchains environment (vs) function _enter_toolchains() _g.pathes = _enter("path") _g.libs = _enter("lib") _g.includes = _enter("include") _g.libpathes = _enter("libpath") end -- leave the toolchains environment (vs) function _leave_toolchains() _leave("path", _g.pathes) _leave("lib", _g.libs) _leave("include", _g.includes) _leave("libpath", _g.libpathes) end -- enter the toolchains environment (vs) function enter(name) -- the maps local maps = {toolchains = _enter_toolchains} -- enter it local func = maps[name] if func then func() end end -- leave the toolchains environment (vs) function leave(name) -- the maps local maps = {toolchains = _leave_toolchains} -- leave it local func = maps[name] if func then func() end end
--!The Make-like Build Utility based on Lua -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2017, TBOOX Open Source Group. -- -- @author ruki -- @file environment.lua -- -- imports import("core.project.config") import("core.project.global") -- enter the given environment function _enter(name) -- get vcvarsall local vcvarsall = config.get("__vcvarsall") or global.get("__vcvarsall") if not vcvarsall then return end -- get arch local arch = config.get("arch") or global.get("arch") or "" -- get vs environment for the current arch local vsenv = vcvarsall[arch] or {} -- get the pathes for the vs environment local old = nil local new = vsenv[name] if new then -- get the current pathes old = os.getenv(name) or "" -- append the current pathes new = new .. ";" .. old -- update the pathes for the environment os.setenv(name, new) end -- return the previous environment return old end -- leave the given environment function _leave(name, old) -- restore the previous environment if old then os.setenv(name, old) end end -- enter the toolchains environment (vs) function _enter_toolchains() _g.pathes = _enter("path") _g.libs = _enter("lib") _g.includes = _enter("include") _g.libpathes = _enter("libpath") end -- leave the toolchains environment (vs) function _leave_toolchains() _leave("path", _g.pathes) _leave("lib", _g.libs) _leave("include", _g.includes) _leave("libpath", _g.libpathes) end -- enter the toolchains environment (vs) function enter(name) -- the maps local maps = {toolchains = _enter_toolchains} -- enter it local func = maps[name] if func then func() end end -- leave the toolchains environment (vs) function leave(name) -- the maps local maps = {toolchains = _leave_toolchains} -- leave it local func = maps[name] if func then func() end end
fix windows envirnoment for global
fix windows envirnoment for global
Lua
apache-2.0
tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake
45536a8cc0ad553dd8f23d5701ccff902ac8c72b
runtime.lua
runtime.lua
local r = {} function r.newGlobals(spritesheet) local GLOB = { assert=assert, error=error, ipairs=ipairs, pairs=pairs, next=next, pcall=pcall, select=select, tonumber=tonumber, tostring=tostring, type=type, unpack=unpack, _VERSION=_VERSION, xpcall=xpcall, string={ byte=string.byte, char=string.char, find=string.find, format=string.format, gmatch=string.gmatch, gsub=string.gsub, len=string.len, lower=string.lower, match=string.match, rep=string.rep, reverse=string.reverse, sub=string.sub, upper=string.upper }, table={ insert=table.insert, maxn=table.maxn, remove=table.remove, sort=table.sort }, math={ abs=math.abs, acos=math.acos, asin=math.asin, atan=math.atan, atan2=math.atan2, ceil=math.ceil, cos=math.cos, cosh=math.cosh, deg=math.deg, exp=math.exp, floor=math.floor, fmod=math.fmod, frexp=math.frexp, huge=math.huge, ldexp=math.ldexp, log=math.log, log10=math.log10, max=math.max, min=math.min, modf=math.modf, pi=math.pi, pow=math.pow, rad=math.rad, random=math.random, randomseed=math.randomseed, sin=math.sin, sinh=math.sinh, sqrt=math.sqrt, tan=math.tan, tanh=math.tanh, } } local newAPI = api.newAPI(true,spritesheet) for k,v in pairs(newAPI) do GLOB[k] = v end GLOB._G=GLOB --Mirror Mirror return GLOB end local function tr(fnc,...) if not fnc then return end local ok, err = pcall(fnc,...) if not ok then r.onerr(err) r.cg = {} end end function r:compile(code, G, spritesheet) local G = G or r.newGlobals(spritesheet) local chunk, err = loadstring(code or "") if(err and not chunk) then -- maybe it's an expression, not a statement chunk, err = loadstring("return " .. code) if(err and not chunk) then return false, err end end setfenv(chunk,G) self.cg = G return chunk end function r:loadGame(code,spritesheet,onerr) local success, err = pcall(assert(r:compile(code, nil, spritesheet))) if not success then return false, err end self.onerr = onerr or error return true end function r:startGame() api.clear(1) tr(self.cg._init) end function r:_init() self.cg = {} end function r:_update(...) tr(self.cg._update,...) end function r:_mpress(...) tr(self.cg._mpress,...) end function r:_mmove(...) tr(self.cg._mmove,...) end function r:_mrelease(...) tr(self.cg._mrelease,...) end function r:_tpress(...) tr(self.cg._tpress,...) end function r:_tmove(...) tr(self.cg._tmove,...) end function r:_trelease(...) tr(self.cg._trelease,...) end function r:_kpress(...) tr(self.cg._kpress,...) end function r:_krelease(...) tr(self.cg._krelease,...) end function r:_tinput(...) tr(self.cg._tinput,...) end return r
local r = {} function r:newGlobals(spritesheet) local GLOB = { assert=assert, error=error, ipairs=ipairs, pairs=pairs, next=next, pcall=pcall, select=select, tonumber=tonumber, tostring=tostring, type=type, unpack=unpack, _VERSION=_VERSION, xpcall=xpcall, string={ byte=string.byte, char=string.char, find=string.find, format=string.format, gmatch=string.gmatch, gsub=string.gsub, len=string.len, lower=string.lower, match=string.match, rep=string.rep, reverse=string.reverse, sub=string.sub, upper=string.upper }, table={ insert=table.insert, maxn=table.maxn, remove=table.remove, sort=table.sort }, math={ abs=math.abs, acos=math.acos, asin=math.asin, atan=math.atan, atan2=math.atan2, ceil=math.ceil, cos=math.cos, cosh=math.cosh, deg=math.deg, exp=math.exp, floor=math.floor, fmod=math.fmod, frexp=math.frexp, huge=math.huge, ldexp=math.ldexp, log=math.log, log10=math.log10, max=math.max, min=math.min, modf=math.modf, pi=math.pi, pow=math.pow, rad=math.rad, random=math.random, randomseed=math.randomseed, sin=math.sin, sinh=math.sinh, sqrt=math.sqrt, tan=math.tan, tanh=math.tanh, } } local newAPI = api.newAPI(true,spritesheet) for k,v in pairs(newAPI) do GLOB[k] = v end GLOB._G=GLOB --Mirror Mirror return GLOB end local function tr(fnc,...) if not fnc then return end local ok, err = pcall(fnc,...) if not ok then r.onerr(err) r.cg = {} end end function r:compile(code, G, spritesheet) local G = G or r:newGlobals(spritesheet) local chunk, err = loadstring(code or "") if err and not chunk then -- maybe it's an expression, not a statement chunk, err = loadstring("return " .. code) if err and not chunk then return false, err end end setfenv(chunk,G) self.cg = G return chunk end function r:loadGame(code,spritesheet,onerr,...) --[[local success, err = self:compile(code, false, spritesheet, false) if not success then return false, err end self.onerr = onerr or error return true]] -- The loadGame will have it's own loading code because r:compile made by technomancy is so so buggy.. local G = self:newGlobals(spritesheet) local cart, err = loadstring(code or "") if not cart then return err end setfenv(cart,G) local ok, err = pcall(cart,...) if not ok then return err end self.cg = G self.onerr = onerr or error return self end function r:startGame() api.clear(1) tr(self.cg._init) end function r:_init() self.cg = {} end function r:_update(...) tr(self.cg._update,...) end function r:_mpress(...) tr(self.cg._mpress,...) end function r:_mmove(...) tr(self.cg._mmove,...) end function r:_mrelease(...) tr(self.cg._mrelease,...) end function r:_tpress(...) tr(self.cg._tpress,...) end function r:_tmove(...) tr(self.cg._tmove,...) end function r:_trelease(...) tr(self.cg._trelease,...) end function r:_kpress(...) tr(self.cg._kpress,...) end function r:_krelease(...) tr(self.cg._krelease,...) end function r:_tinput(...) tr(self.cg._tinput,...) end return r
Fixed error catching for the run command + fixed the args support
Fixed error catching for the run command + fixed the args support
Lua
mit
RamiLego4Game/LIKO-12
bc4a33a73cd7f4550e6dc547a31505f6865e38fe
packages/rules.lua
packages/rules.lua
SILE.baseClass:loadPackage("raiselower") SILE.baseClass:loadPackage("rebox") SILE.registerCommand("hrule", function (options, _) local width = SU.cast("length", options.width) local height = SU.cast("length", options.height) local depth = SU.cast("length", options.depth) SILE.typesetter:pushHbox({ width = width:absolute(), height = height:absolute(), depth = depth:absolute(), value = options.src, outputYourself= function (self, typesetter, line) local outputWidth = SU.rationWidth(self.width, self.width, line.ratio) local invert = typesetter.frame:writingDirection() == "TTB" and typesetter.frame:pageAdvanceDirection() == "LTR" and -1 or 1 typesetter.frame:advancePageDirection(invert * -self.height) local x = typesetter.frame.state.cursorX local y = typesetter.frame.state.cursorY typesetter.frame:advanceWritingDirection(outputWidth) typesetter.frame:advancePageDirection(invert * (self.height + self.depth)) SILE.outputter:drawRule(x, y, typesetter.frame.state.cursorX - x, typesetter.frame.state.cursorY - y) local x, y = SILE.outputter:getCursor() SU.dump{x, y} end }) end, "Creates a line of width <width> and height <height>") SILE.registerCommand("fullrule", function (options, _) SILE.call("raise", { height = options.raise or "0.5em" }, function () SILE.call("hrule", { height = options.height or "0.2pt", width = options.width or "100%lw" }) end) end, "Draw a full width hrule centered on the current line") SILE.registerCommand("underline", function (_, content) local hbox = SILE.call("hbox", {}, content) local gl = SILE.length() - hbox.width SILE.call("lower", {height = "0.5pt"}, function() SILE.call("hrule", {width = gl.length, height = "0.5pt"}) end) SILE.typesetter:pushGlue({width = hbox.width}) end, "Underlines some content (badly)") SILE.registerCommand("boxaround", function (_, content) local hbox = SILE.call("hbox", {}, content) local gl = SILE.length() - hbox.width SILE.call("rebox", {width = 0}, function() SILE.call("hrule", {width = gl.length-1, height = "0.5pt"}) end) SILE.call("raise", {height = hbox.height}, function () SILE.call("hrule", {width = gl.length-1, height = "0.5pt"}) end) SILE.call("hrule", { height = hbox.height, width = "0.5pt"}) SILE.typesetter:pushGlue({width = hbox.width}) SILE.call("hrule", { height = hbox.height, width = "0.5pt"}) end, "Draws a box around some content") return { documentation = [[\begin{document} The \code{rules} package draws lines. It provides three commands. The first command is \code{\\hrule}, which draws a line of a given length and thickness, although it calls these \code{width} and \code{height}. (A box is just a square line.) Lines are treated just like other text to be output, and so can appear in the middle of a paragraph, like this: \hrule[width=20pt, height=0.5pt] (that one was generated with \code{\\hrule[width=20pt, height=0.5pt]}.) Like images, rules are placed along the baseline of a line of text. The second command provided by \code{rules} is \code{\\underline}, which underlines its contents. \note{ Underlining is horrible typographic practice, and you should \underline{never} do it.} (That was produced with \code{\\underline\{never\}}.) Finally, \code{fullrule} draws a thin line across the width of the current frame. \end{document}]] }
SILE.baseClass:loadPackage("raiselower") SILE.baseClass:loadPackage("rebox") SILE.registerCommand("hrule", function (options, _) local width = SU.cast("length", options.width) local height = SU.cast("length", options.height) local depth = SU.cast("length", options.depth) SILE.typesetter:pushHbox({ width = width:absolute(), height = height:absolute(), depth = depth:absolute(), value = options.src, outputYourself= function (self, typesetter, line) local outputWidth = SU.rationWidth(self.width, self.width, line.ratio) typesetter.frame:advancePageDirection(-self.height) local oldx = typesetter.frame.state.cursorX local oldy = typesetter.frame.state.cursorY typesetter.frame:advanceWritingDirection(outputWidth) typesetter.frame:advancePageDirection(self.height + self.depth) local newx = typesetter.frame.state.cursorX local newy = typesetter.frame.state.cursorY SILE.outputter:drawRule(oldx, oldy, newx - oldx, newy - oldy) end }) end, "Creates a line of width <width> and height <height>") SILE.registerCommand("fullrule", function (options, _) SILE.call("raise", { height = options.raise or "0.5em" }, function () SILE.call("hrule", { height = options.height or "0.2pt", width = options.width or "100%lw" }) end) end, "Draw a full width hrule centered on the current line") SILE.registerCommand("underline", function (_, content) local hbox = SILE.call("hbox", {}, content) local gl = SILE.length() - hbox.width SILE.call("lower", {height = "0.5pt"}, function() SILE.call("hrule", {width = gl.length, height = "0.5pt"}) end) SILE.typesetter:pushGlue({width = hbox.width}) end, "Underlines some content (badly)") SILE.registerCommand("boxaround", function (_, content) local hbox = SILE.call("hbox", {}, content) local gl = SILE.length() - hbox.width SILE.call("rebox", {width = 0}, function() SILE.call("hrule", {width = gl.length-1, height = "0.5pt"}) end) SILE.call("raise", {height = hbox.height}, function () SILE.call("hrule", {width = gl.length-1, height = "0.5pt"}) end) SILE.call("hrule", { height = hbox.height, width = "0.5pt"}) SILE.typesetter:pushGlue({width = hbox.width}) SILE.call("hrule", { height = hbox.height, width = "0.5pt"}) end, "Draws a box around some content") return { documentation = [[\begin{document} The \code{rules} package draws lines. It provides three commands. The first command is \code{\\hrule}, which draws a line of a given length and thickness, although it calls these \code{width} and \code{height}. (A box is just a square line.) Lines are treated just like other text to be output, and so can appear in the middle of a paragraph, like this: \hrule[width=20pt, height=0.5pt] (that one was generated with \code{\\hrule[width=20pt, height=0.5pt]}.) Like images, rules are placed along the baseline of a line of text. The second command provided by \code{rules} is \code{\\underline}, which underlines its contents. \note{ Underlining is horrible typographic practice, and you should \underline{never} do it.} (That was produced with \code{\\underline\{never\}}.) Finally, \code{fullrule} draws a thin line across the width of the current frame. \end{document}]] }
fix(packages): Orient rules for all 8 directions
fix(packages): Orient rules for all 8 directions
Lua
mit
alerque/sile,alerque/sile,alerque/sile,alerque/sile
44a02ca8aac5f326b9a1119fde8df41161535bf5
favorite_face_classifier/classify.lua
favorite_face_classifier/classify.lua
require 'image' require 'torch' require 'inception' local buildEnsembleModel = require 'ensemble' local channels = {'r', 'g', 'b'} local frameWidth = 96 local frameHeight = 96 cmd = torch.CmdLine() cmd:text() cmd:text('Classify a face') cmd:text() cmd:text('Options') -- optional parameters cmd:option('-input', 'pic_to_classify', 'pictures folder to classify a face you like or not') cmd:option('-model', 'model/pretrained_model.net', 'classifier model') cmd:option('-output', 'classify_output', 'face classify output dir') cmd:option('-type', 'cuda', 'model type cuda or cpu') cmd:option('-devid', 1, 'cuda device id') cmd:option('-batchSize', 64, 'prediction batch size') cmd:option('-threshold', 0.99, 'prediction threshold') cmd:option('-ensemble', false, 'use model ensemble, pretrained models must in ensemble folder') cmd:text() -- parse input params opt = cmd:parse(arg) torch.manualSeed(1) torch.setdefaulttensortype('torch.FloatTensor') if opt.type == 'cuda' then print(sys.COLORS.cyan .. 'switching to CUDA') require 'cunn' require 'cudnn' cutorch.setDevice(opt.devid) print(sys.COLORS.cyan .. 'using GPU #' .. cutorch.getDevice()) end print(sys.COLORS.green .. 'processing file in ' .. opt.input) local images = {} local fileNames = {} local originalImages={} local function tableToTensor(table) local tensorSize = table[1]:size() local tensorSizeTable = {-1} for i=1,tensorSize:size(1) do tensorSizeTable[i+1] = tensorSize[i] end local merge = nn.Sequential() :add(nn.JoinTable(1)) :add(nn.View(unpack(tensorSizeTable))) return merge:forward(table) end local function tableSlice(tbl, first, last) local sliced = {} for i = first, last do sliced[#sliced+1] = tbl[i] end return sliced end local function normalize(inputImage) local y = inputImage:clone() local channels = {'r', 'g', 'b'} for i,channel in ipairs(channels) do local mean = {} local std = {} mean[i] = y[{ i,{},{} }]:mean() std[i] = y[{ i,{},{} }]:std() y[{ i,{},{} }]:add(-mean[i]) y[{ i,{},{} }]:div(std[i]) end return y end local function classify(slices, origins, files) if #slices <= 0 then return false end print('slices ' .. #slices) paths.mkdir(opt.output .. opt.threshold) local likePath = paths.concat(opt.output .. opt.threshold, 'like') paths.mkdir(likePath) local unlikePath = paths.concat(opt.output .. opt.threshold, 'unlike') paths.mkdir(unlikePath) local probability = opt.threshold if opt.ensemble then -- reset to 0.5 according to model vote probability = 0.5 end local i = 1 while i + opt.batchSize - 1 < #slices do print(i .. ' - ' .. i + opt.batchSize - 1) subTable = tableSlice(slices, i, i + opt.batchSize - 1) local s = torch.Tensor(tableToTensor(subTable)) s = s:cuda() local result = model:forward(s) if opt.ensemble == false then -- ensemble model output probability[0, 1] -- the others output log probability result = torch.exp(result) end --print(result) for j = 1, result:size()[1] do if result[j][1] >= probability then image.save(paths.concat(likePath, paths.basename(files[i + j - 1])) .. '.png', origins[i + j - 1]) else image.save(paths.concat(unlikePath, paths.basename(files[i + j - 1])) .. '.png', origins[i + j - 1]) end end i = i + opt.batchSize end local mod = #slices % opt.batchSize print(i .. ' - ' .. i + mod) local subTable = tableSlice(slices, i, i + mod) local s = torch.Tensor(tableToTensor(subTable)) s = s:cuda() local result = model:forward(s) if opt.ensemble == false then -- ensemble model output probability[0, 1] -- the others output log probability result = torch.exp(result) end --print(result) for j = 1, result:size()[1] do if result[j][1] >= probability then image.save(paths.concat(likePath, paths.basename(files[i + j - 1])) .. '.png', origins[i + j - 1]) else image.save(paths.concat(unlikePath, paths.basename(files[i + j - 1])) .. '.png', origins[i + j - 1]) end end end local function prepare(file) local inputImage = image.load(file, #channels) local originalImage = inputImage:clone() if inputImage:size()[2] ~= frameHeight and inputImage:size()[3] ~= frameWidth then inputImage = image.scale(inputImage, frameWidth, frameHeight) end images[#images + 1] = inputImage originalImages[#originalImages + 1] = originalImage fileNames[#fileNames + 1] = file end print(sys.COLORS.Yellow .. '====> begin') if opt.ensemble then local ensembleThreshold = opt.threshold -- classifier threshold reset to 0.5 according to model vote print('use ensemble strategy') model = buildEnsembleModel("ensemble", ensembleThreshold) else print('use single model') model = torch.load(opt.model) end if opt.type == 'cuda' then model = model:cuda() end model:evaluate() for file in paths.iterfiles(opt.input) do local f = paths.concat(opt.input, file) pcall(prepare ,f) end classify(images, originalImages, fileNames) print(sys.COLORS._yellow .. '====> end')
require 'image' require 'torch' require 'inception' local buildEnsembleModel = require 'ensemble' local channels = {'r', 'g', 'b'} local frameWidth = 96 local frameHeight = 96 cmd = torch.CmdLine() cmd:text() cmd:text('Classify a face') cmd:text() cmd:text('Options') -- optional parameters cmd:option('-input', 'pic_to_classify', 'pictures folder to classify a face you like or not') cmd:option('-model', 'model/pretrained_model.net', 'classifier model') cmd:option('-output', 'classify_output', 'face classify output dir') cmd:option('-type', 'cuda', 'model type cuda or cpu') cmd:option('-devid', 1, 'cuda device id') cmd:option('-batchSize', 64, 'prediction batch size') cmd:option('-threshold', 0.99, 'prediction threshold') cmd:option('-ensemble', false, 'use model ensemble, pretrained models must in ensemble folder') cmd:text() -- parse input params opt = cmd:parse(arg) torch.manualSeed(1) torch.setdefaulttensortype('torch.FloatTensor') if opt.type == 'cuda' then print(sys.COLORS.cyan .. 'switching to CUDA') require 'cunn' require 'cudnn' cutorch.setDevice(opt.devid) print(sys.COLORS.cyan .. 'using GPU #' .. cutorch.getDevice()) end print(sys.COLORS.green .. 'processing file in ' .. opt.input) local images = {} local fileNames = {} local originalImages={} local function tableToTensor(table) local tensorSize = table[1]:size() local tensorSizeTable = {-1} for i=1,tensorSize:size(1) do tensorSizeTable[i+1] = tensorSize[i] end local merge = nn.Sequential() :add(nn.JoinTable(1)) :add(nn.View(unpack(tensorSizeTable))) return merge:forward(table) end local function tableSlice(tbl, first, last) local sliced = {} for i = first, last do sliced[#sliced+1] = tbl[i] end return sliced end local function normalize(inputImage) local y = inputImage:clone() local channels = {'r', 'g', 'b'} for i,channel in ipairs(channels) do local mean = {} local std = {} mean[i] = y[{ i,{},{} }]:mean() std[i] = y[{ i,{},{} }]:std() y[{ i,{},{} }]:add(-mean[i]) y[{ i,{},{} }]:div(std[i]) end return y end local function classify(slices, origins, files) if #slices <= 0 then return false end print('slices ' .. #slices) paths.mkdir(opt.output .. opt.threshold) local likePath = paths.concat(opt.output .. opt.threshold, 'like') paths.mkdir(likePath) local unlikePath = paths.concat(opt.output .. opt.threshold, 'unlike') paths.mkdir(unlikePath) local probability = opt.threshold if opt.ensemble then -- reset to 0.5 according to model vote probability = 0.5 end local i = 1 while i + opt.batchSize - 1 < #slices do print(i .. ' - ' .. i + opt.batchSize - 1) subTable = tableSlice(slices, i, i + opt.batchSize - 1) local s = torch.Tensor(tableToTensor(subTable)) s = s:cuda() local result = model:forward(s) if opt.ensemble == false then -- ensemble model output probability[0, 1] -- the others output log probability result = torch.exp(result) end --print(result) for j = 1, result:size()[1] do if result[j][1] >= probability then image.save(paths.concat(likePath, paths.basename(files[i + j - 1])) .. '.png', origins[i + j - 1]) else image.save(paths.concat(unlikePath, paths.basename(files[i + j - 1])) .. '.png', origins[i + j - 1]) end end i = i + opt.batchSize end local mod = #slices % opt.batchSize print(i .. ' - ' .. i + mod) local subTable = tableSlice(slices, i, i + mod) local s = torch.Tensor(tableToTensor(subTable)) local hack = false if s:size(1) == 1 then -- hack, see https://github.com/soumith/cudnn.torch/issues/281 local dummy = torch.zeros(1, 3, frameWidth, frameHeight) s = torch.cat(s, dummy, 1) hack = true end s = s:cuda() local result = model:forward(s) if hack == true then result = result[{{1, -2}, {}}] end if opt.ensemble == false then -- ensemble model output probability[0, 1] -- the others output log probability result = torch.exp(result) end --print(result) for j = 1, result:size()[1] do if result[j][1] >= probability then image.save(paths.concat(likePath, paths.basename(files[i + j - 1])) .. '.png', origins[i + j - 1]) else image.save(paths.concat(unlikePath, paths.basename(files[i + j - 1])) .. '.png', origins[i + j - 1]) end end end local function prepare(file) local inputImage = image.load(file, #channels) local originalImage = inputImage:clone() if inputImage:size()[2] ~= frameHeight and inputImage:size()[3] ~= frameWidth then inputImage = image.scale(inputImage, frameWidth, frameHeight) end images[#images + 1] = inputImage originalImages[#originalImages + 1] = originalImage fileNames[#fileNames + 1] = file end print(sys.COLORS.Yellow .. '====> begin') if opt.ensemble then local ensembleThreshold = opt.threshold -- classifier threshold reset to 0.5 according to model vote print('use ensemble strategy') model = buildEnsembleModel("ensemble", ensembleThreshold) else print('use single model') model = torch.load(opt.model) end if opt.type == 'cuda' then model = model:cuda() end model:evaluate() for file in paths.iterfiles(opt.input) do local f = paths.concat(opt.input, file) pcall(prepare ,f) end classify(images, originalImages, fileNames) print(sys.COLORS._yellow .. '====> end')
fix BatchNormalization.lua:43: assertion failed!
fix BatchNormalization.lua:43: assertion failed!
Lua
unlicense
rickerliang/face_filter,rickerliang/face_filter
04a4cdcb576d448c42bd51246819463dc5e7433a
pud/level/TileLevelView.lua
pud/level/TileLevelView.lua
local Class = require 'lib.hump.class' local LevelView = require 'pud.level.LevelView' local MapUpdateFinishedEvent = require 'pud.event.MapUpdateFinishedEvent' -- TileLevelView -- draws tiles for each node in the level map to a framebuffer, which is then -- drawn to screen local TileLevelView = Class{name='TileLevelView', inherits=LevelView, function(self, mapW, mapH) LevelView.construct(self) verify('number', mapW, mapH) self._tileW, self._tileH = 32, 32 self._set = Image.dungeon local w, h = nearestPO2(mapW*self._tileW), nearestPO2(mapH*self._tileH) self._fb = love.graphics.newFramebuffer(w, h) self:_setupQuads() end } -- destructor function TileLevelView:destroy() self:_clearQuads() self._set = nil GameEvent:unregisterAll(self) LevelView.destroy(self) end -- make a quad from the given tile position function TileLevelView:_makeQuad(mapType, variation, x, y) variation = tostring(variation) self._quads[mapType] = self._quads[mapType] or {} self._quads[mapType][variation] = love.graphics.newQuad( self._tileW*(x-1), self._tileH*(y-1), self._tileW, self._tileH, self._set:getWidth(), self._set:getHeight()) end function TileLevelView:_getQuad(node) if self._quads then local mapType = node:getMapType() if not mapType:isType('empty') then local mtype, variation = mapType:get() if not variation then if mapType:isType('wall') then mtype = 'wall' variation = 'V1' elseif mapType:isType('floor') then mtype = 'floor' variation = '1' elseif mapType:isType('torch') then mtype = 'torch' variation = 'A1' elseif mapType:isType('trap') then mtype = 'trap' variation = 'A1' elseif mapType:isType('stairUp') or mapType:isType('stairDown') or mapType:isType('doorOpen') or mapType:isType('doorClosed') then variation = '1' end end if self._quads[mtype] then return self._quads[mtype][variation] end end end return nil end -- clear the quads table function TileLevelView:_clearQuads() if self._quads then for k,v in pairs(self._quads) do self._quads[k] = nil end self._quads = nil end end -- set up the quads function TileLevelView:_setupQuads() self:_clearQuads() self._quads = {} for i=1,4 do self:_makeQuad('wall', 'H'..i, 1, i) self:_makeQuad('wall', 'HWorn'..i, 2, i) self:_makeQuad('wall', 'V'..i, 3, i) self:_makeQuad('torch', 'A'..i, 4, i) self:_makeQuad('torch', 'B'..i, 5, i) self:_makeQuad('floor', i, 6, i) self:_makeQuad('floor', 'Worn'..i, 7, i) self:_makeQuad('floor', 'X'..i, 8, i) self:_makeQuad('floor', 'Rug'..i, 9, i) self:_makeQuad('stairUp', i, 10, i) self:_makeQuad('stairDown', i, 11, i) end for i=1,5 do self:_makeQuad('doorClosed', i, i+(i-1), 5) self:_makeQuad('doorOpen', i, i*2, 5) end for i=1,6 do self:_makeQuad('trap', 'A'..i, i+(i-1), 6) self:_makeQuad('trap', 'B'..i, i*2, 6) end end -- register for events that will cause this view to redraw function TileLevelView:registerEvents() local events = { MapUpdateFinishedEvent, } GameEvent:register(self, events) end -- handle registered events as they are fired function TileLevelView:onEvent(e, ...) if e:is_a(MapUpdateFinishedEvent) then self:drawToFB(e:getMap()) end end -- draw to the framebuffer function TileLevelView:drawToFB(map) if self._fb and self._set and map then self._isDrawing = true love.graphics.setRenderTarget(self._fb) love.graphics.setColor(1,1,1) for y=1,map:getHeight() do local drawY = (y-1)*self._tileH for x=1,map:getWidth() do local node = map:getLocation(x, y) local quad = self:_getQuad(node) if quad then local drawX = (x-1)*self._tileW love.graphics.drawq(self._set, quad, drawX, drawY) elseif not node:getMapType():isType('empty') then warning('no quad found for %s', tostring(node:getMapType())) end end end love.graphics.setRenderTarget() self._isDrawing = false end end -- draw the framebuffer to the screen function TileLevelView:draw() if self._fb and self._isDrawing == false then love.graphics.setColor(1,1,1) love.graphics.draw(self._fb) end end -- the class return TileLevelView
local Class = require 'lib.hump.class' local LevelView = require 'pud.level.LevelView' local MapUpdateFinishedEvent = require 'pud.event.MapUpdateFinishedEvent' -- TileLevelView -- draws tiles for each node in the level map to a framebuffer, which is then -- drawn to screen local TileLevelView = Class{name='TileLevelView', inherits=LevelView, function(self, mapW, mapH) LevelView.construct(self) verify('number', mapW, mapH) self._tileW, self._tileH = 32, 32 self._set = Image.dungeon local w, h = nearestPO2(mapW*self._tileW), nearestPO2(mapH*self._tileH) self._fb = love.graphics.newFramebuffer(w, h) self:_setupQuads() end } -- destructor function TileLevelView:destroy() self:_clearQuads() self._set = nil GameEvent:unregisterAll(self) LevelView.destroy(self) end -- make a quad from the given tile position function TileLevelView:_makeQuad(mapType, variation, x, y) variation = tostring(variation) self._quads[mapType] = self._quads[mapType] or {} self._quads[mapType][variation] = love.graphics.newQuad( self._tileW*(x-1), self._tileH*(y-1), self._tileW, self._tileH, self._set:getWidth(), self._set:getHeight()) end function TileLevelView:_getQuad(node) if self._quads then local mapType = node:getMapType() if not mapType:isType('empty') then local mtype, variation = mapType:get() if not variation then if mapType:isType('wall') then mtype = 'wall' variation = 'V' elseif mapType:isType('torch') then mtype = 'torch' variation = 'A' elseif mapType:isType('trap') then mtype = 'trap' variation = 'A' end end variation = variation or '' variation = variation .. '1' if self._quads[mtype] then return self._quads[mtype][variation] end end end return nil end -- clear the quads table function TileLevelView:_clearQuads() if self._quads then for k,v in pairs(self._quads) do self._quads[k] = nil end self._quads = nil end end -- set up the quads function TileLevelView:_setupQuads() self:_clearQuads() self._quads = {} for i=1,4 do self:_makeQuad('wall', 'H'..i, 1, i) self:_makeQuad('wall', 'HWorn'..i, 2, i) self:_makeQuad('wall', 'V'..i, 3, i) self:_makeQuad('torch', 'A'..i, 4, i) self:_makeQuad('torch', 'B'..i, 5, i) self:_makeQuad('floor', i, 6, i) self:_makeQuad('floor', 'Worn'..i, 7, i) self:_makeQuad('floor', 'X'..i, 8, i) self:_makeQuad('floor', 'Rug'..i, 9, i) self:_makeQuad('stairUp', i, 10, i) self:_makeQuad('stairDown', i, 11, i) end for i=1,5 do self:_makeQuad('doorClosed', i, i+(i-1), 5) self:_makeQuad('doorOpen', i, i*2, 5) end for i=1,6 do self:_makeQuad('trap', 'A'..i, i+(i-1), 6) self:_makeQuad('trap', 'B'..i, i*2, 6) end end -- register for events that will cause this view to redraw function TileLevelView:registerEvents() local events = { MapUpdateFinishedEvent, } GameEvent:register(self, events) end -- handle registered events as they are fired function TileLevelView:onEvent(e, ...) if e:is_a(MapUpdateFinishedEvent) then self:drawToFB(e:getMap()) end end -- draw to the framebuffer function TileLevelView:drawToFB(map) if self._fb and self._set and map then self._isDrawing = true love.graphics.setRenderTarget(self._fb) love.graphics.setColor(1,1,1) for y=1,map:getHeight() do local drawY = (y-1)*self._tileH for x=1,map:getWidth() do local node = map:getLocation(x, y) local quad = self:_getQuad(node) if quad then local drawX = (x-1)*self._tileW love.graphics.drawq(self._set, quad, drawX, drawY) elseif not node:getMapType():isType('empty') then warning('no quad found for %s', tostring(node:getMapType())) end end end love.graphics.setRenderTarget() self._isDrawing = false end end -- draw the framebuffer to the screen function TileLevelView:draw() if self._fb and self._isDrawing == false then love.graphics.setColor(1,1,1) love.graphics.draw(self._fb) end end -- the class return TileLevelView
fix variations
fix variations
Lua
mit
scottcs/wyx
940beff044feb3e4c04abe325d3315a1b3c0526a
frontend/apps/reader/modules/readerrotation.lua
frontend/apps/reader/modules/readerrotation.lua
local InputContainer = require("ui/widget/container/inputcontainer") local Screen = require("ui/screen") local Geom = require("ui/geometry") local Device = require("ui/device") local Event = require("ui/event") local GestureRange = require("ui/gesturerange") local _ = require("gettext") local ReaderRotation = InputContainer:new{ ROTATE_ANGLE_THRESHOLD = 15, current_rotation = 0 } function ReaderRotation:init() if Device:hasKeyboard() then self.key_events = { -- these will all generate the same event, just with different arguments RotateLeft = { {"J"}, doc = "rotate left by 90 degrees", event = "Rotate", args = -90 }, RotateRight = { {"K"}, doc = "rotate right by 90 degrees", event = "Rotate", args = 90 }, } end if Device:isTouchDevice() then self.ges_events = { RotateGes = { GestureRange:new{ ges = "rotate", range = Geom:new{ x = 0, y = 0, w = Screen:getWidth(), h = Screen:getHeight(), } } }, TwoFingerPanRelease = { GestureRange:new{ ges = "two_finger_pan_release", range = Geom:new{ x = 0, y = 0, w = Screen:getWidth(), h = Screen:getHeight(), } } } } end end -- TODO: reset rotation on new document, maybe on new page? function ReaderRotation:onRotate(rotate_by) self.current_rotation = (self.current_rotation + rotate_by) % 360 self.ui:handleEvent(Event:new("RotationUpdate", self.current_rotation)) return true end function ReaderRotation:onRotateGes(arg, ges) self.rotate_angle = ges.angle return true end function ReaderRotation:onTwoFingerPanRelease(arg, ges) if self.rotate_angle and self.rotate_angle > self.ROTATE_ANGLE_THRESHOLD then if Screen:getScreenMode() == "portrait" then self.ui:handleEvent(Event:new("SetScreenMode", "landscape")) else self.ui:handleEvent(Event:new("SetScreenMode", "portrait")) end self.rotate_angle = nil end end return ReaderRotation
local InputContainer = require("ui/widget/container/inputcontainer") local Screen = require("ui/screen") local Geom = require("ui/geometry") local Device = require("ui/device") local Event = require("ui/event") local GestureRange = require("ui/gesturerange") local _ = require("gettext") local ReaderRotation = InputContainer:new{ ROTATE_ANGLE_THRESHOLD = 15, current_rotation = 0 } function ReaderRotation:init() if Device:hasKeyboard() then self.key_events = { -- these will all generate the same event, just with different arguments RotateLeft = { {"J"}, doc = "rotate left by 90 degrees", event = "Rotate", args = -90 }, RotateRight = { {"K"}, doc = "rotate right by 90 degrees", event = "Rotate", args = 90 }, } end if Device:isTouchDevice() then self.ges_events = { RotateGes = { GestureRange:new{ ges = "rotate", range = Geom:new{ x = 0, y = 0, w = Screen:getWidth(), h = Screen:getHeight(), }, rate = 0.3 } }, } end end -- TODO: reset rotation on new document, maybe on new page? function ReaderRotation:onRotate(rotate_by) self.current_rotation = (self.current_rotation + rotate_by) % 360 self.ui:handleEvent(Event:new("RotationUpdate", self.current_rotation)) return true end function ReaderRotation:onRotateGes(arg, ges) if ges.angle and ges.angle > self.ROTATE_ANGLE_THRESHOLD then if Screen:getScreenMode() == "portrait" then self.ui:handleEvent(Event:new("SetScreenMode", "landscape")) else self.ui:handleEvent(Event:new("SetScreenMode", "portrait")) end end return true end return ReaderRotation
fix insensitive rotate gesture detection This should fix #546.
fix insensitive rotate gesture detection This should fix #546.
Lua
agpl-3.0
NiLuJe/koreader,poire-z/koreader,Hzj-jie/koreader,ashhher3/koreader,Frenzie/koreader,Markismus/koreader,robert00s/koreader,houqp/koreader,ashang/koreader,mwoz123/koreader,NiLuJe/koreader,noname007/koreader,chrox/koreader,NickSavage/koreader,koreader/koreader,koreader/koreader,poire-z/koreader,apletnev/koreader,Frenzie/koreader,pazos/koreader,chihyang/koreader,frankyifei/koreader,mihailim/koreader,lgeek/koreader
cdaa5dc5ccab9f53dd0c129abd000ab285f1759b
lib/resty/consul.lua
lib/resty/consul.lua
local pcall = pcall local tostring = tostring local cjson = require('cjson') local json_decode = cjson.decode local json_encode = cjson.encode local tbl_concat = table.concat local tbl_insert = table.insert local ngx = ngx local ngx_log = ngx.log local ngx_ERR = ngx.ERR local ngx_DEBUG = ngx.DEBUG local http = require('resty.http') local _M = { _VERSION = '0.01', } local API_VERSION = "v1" local DEFAULT_HOST = "127.0.0.1" local DEFAULT_PORT = 8500 local DEFAULT_TIMEOUT = 60*1000 -- 60s efault timeout local mt = { __index = _M } function _M.new(_, opts) local self = { host = opts.host or DEFAULT_HOST, port = opts.port or DEFAULT_PORT, connect_timeout = opts.connect_timeout or DEFAULT_TIMEOUT, read_timeout = opts.read_timeout or DEFAULT_TIMEOUT } return setmetatable(self, mt) end function _M.get_client_body_reader(self, ...) return http:get_client_body_reader(...) end local function safe_json_decode(json_str) local ok, json = pcall(json_decode, json_str) if ok then return json else ngx_log(ngx_ERR, json) end end local function build_uri(key, opts) local uri = "/"..API_VERSION..key if opts then local params = {} for k,v in pairs(opts) do tbl_insert(params, k.."="..tostring(v)) end uri = uri.."?"..tbl_concat(params, "&") end return uri end local function connect(self) local httpc = http.new() local connect_timeout = self.connect_timeout if connect_timeout then httpc:set_timeout(connect_timeout) end local ok, err = httpc:connect(self.host, self.port) if not ok then return nil, err end return httpc end local function _get(httpc, key, opts) local uri = build_uri(key, opts) local res, err = httpc:request({path = uri}) if not res then return nil, err end local status = res.status if not status then return nil, "No status from consul" elseif status ~= 200 then if status == 404 then return nil, "Key not found" else return nil, "Consul returned: HTTP "..status end end local body, err = res:read_body() if not body then return nil, err end local response = safe_json_decode(body) local headers = res.headers return response, headers["X-Consul-Lastcontact"], headers["X-Consul-Knownleader"] end function _M.get(self, key, opts) local httpc, err = connect(self) if not httpc then ngx_log(ngx_ERR, err) return nil, err end if opts and (opts.wait or opts.index) then -- Blocking request, increase timeout local timeout = 10 * 60 * 1000 -- Default timeout is 10m if opts.wait then timeout = opts.wait * 1000 end httpc:set_timeout(timeout) else httpc:set_timeout(self.read_timeout) end local res, lastcontact_or_err, knownleader = _get(httpc, key, opts) httpc:set_keepalive() if not res then return nil, lastcontact_or_err end return res, {lastcontact_or_err, knownleader} end function _M.get_decoded(self, key, opts) local res, err = self:get(key, opts) if not res then return nil, err end for _,entry in ipairs(res) do if type(entry.Value) == "string" then local decoded = ngx.decode_base64(entry.Value) if decoded ~= nil then entry.Value = decoded end end end return res, err end function _M.get_json_decoded(self, key, opts) local res, err = self:get_decoded(key, opts) if not res then return nil, err end for _,entry in ipairs(res) do local decoded = safe_json_decode(entry.Value) if decoded ~= nil then entry.Value = decoded end end return res, err end function _M.put(self, key, value, opts) local httpc, err = connect(self) if not httpc then ngx_log(ngx_ERR, err) return nil, err end local uri = build_uri(key, opts) local res, err = httpc:request({ method = "PUT", path = uri, body = value }) if not res then return nil, err end if not res.status then return nil, "No status from consul" end local body, err = res:read_body() if not body then return nil, err end httpc:set_keepalive() return (body == "true\n") end function _M.delete(self, key, recurse) local httpc, err = connect(self) if not httpc then ngx_log(ngx_ERR, err) return nil, err end if recurse then recurse = {recurse = true} end local uri = build_uri(key, recurse) local res, err = httpc:request({ method = "DELETE", path = uri, }) if not res then return nil, err end if not res.status then return nil, "No status from consul" end local body, err = res:read_body() if not body then return nil, err end httpc:set_keepalive() if res.status == 200 then return true end -- DELETE seems to return 200 regardless, but just in case return {status = res.status, body = body, headers = res.headers}, err end return _M
local pcall = pcall local tostring = tostring local cjson = require('cjson') local json_decode = cjson.decode local json_encode = cjson.encode local tbl_concat = table.concat local tbl_insert = table.insert local ngx = ngx local ngx_log = ngx.log local ngx_ERR = ngx.ERR local ngx_DEBUG = ngx.DEBUG local http = require('resty.http') local _M = { _VERSION = '0.01', } local API_VERSION = "v1" local DEFAULT_HOST = "127.0.0.1" local DEFAULT_PORT = 8500 local DEFAULT_TIMEOUT = 60*1000 -- 60s efault timeout local mt = { __index = _M } function _M.new(_, opts) local self = { host = opts.host or DEFAULT_HOST, port = opts.port or DEFAULT_PORT, connect_timeout = opts.connect_timeout or DEFAULT_TIMEOUT, read_timeout = opts.read_timeout or DEFAULT_TIMEOUT } return setmetatable(self, mt) end function _M.get_client_body_reader(self, ...) return http:get_client_body_reader(...) end local function safe_json_decode(json_str) local ok, json = pcall(json_decode, json_str) if ok then return json else ngx_log(ngx_ERR, json) end end local function build_uri(key, opts) local uri = "/"..API_VERSION..key if opts then local params = {} for k,v in pairs(opts) do if k == "wait" then v = v.."s" end tbl_insert(params, k.."="..tostring(v)) end uri = uri.."?"..tbl_concat(params, "&") end return uri end local function connect(self) local httpc = http.new() local connect_timeout = self.connect_timeout if connect_timeout then httpc:set_timeout(connect_timeout) end local ok, err = httpc:connect(self.host, self.port) if not ok then return nil, err end return httpc end local function _get(httpc, key, opts) local uri = build_uri(key, opts) local res, err = httpc:request({path = uri}) if not res then return nil, err end local status = res.status if not status then return nil, "No status from consul" elseif status ~= 200 then if status == 404 then return nil, "Key not found" else return nil, "Consul returned: HTTP "..status end end local body, err = res:read_body() if not body then return nil, err end local response = safe_json_decode(body) local headers = res.headers return response, headers["X-Consul-Lastcontact"], headers["X-Consul-Knownleader"] end function _M.get(self, key, opts) local httpc, err = connect(self) if not httpc then ngx_log(ngx_ERR, err) return nil, err end if opts and (opts.wait or opts.index) then -- Blocking request, increase timeout local timeout = 10 * 60 * 1000 -- Default timeout is 10m if opts.wait then timeout = opts.wait * 1000 end httpc:set_timeout(timeout) else httpc:set_timeout(self.read_timeout) end local res, lastcontact_or_err, knownleader = _get(httpc, key, opts) httpc:set_keepalive() if not res then return nil, lastcontact_or_err end return res, {lastcontact_or_err, knownleader} end function _M.get_decoded(self, key, opts) local res, err = self:get(key, opts) if not res then return nil, err end for _,entry in ipairs(res) do if type(entry.Value) == "string" then local decoded = ngx.decode_base64(entry.Value) if decoded ~= nil then entry.Value = decoded end end end return res, err end function _M.get_json_decoded(self, key, opts) local res, err = self:get_decoded(key, opts) if not res then return nil, err end for _,entry in ipairs(res) do local decoded = safe_json_decode(entry.Value) if decoded ~= nil then entry.Value = decoded end end return res, err end function _M.put(self, key, value, opts) local httpc, err = connect(self) if not httpc then ngx_log(ngx_ERR, err) return nil, err end local uri = build_uri(key, opts) local res, err = httpc:request({ method = "PUT", path = uri, body = value }) if not res then return nil, err end if not res.status then return nil, "No status from consul" end local body, err = res:read_body() if not body then return nil, err end httpc:set_keepalive() return (body == "true\n") end function _M.delete(self, key, recurse) local httpc, err = connect(self) if not httpc then ngx_log(ngx_ERR, err) return nil, err end if recurse then recurse = {recurse = true} end local uri = build_uri(key, recurse) local res, err = httpc:request({ method = "DELETE", path = uri, }) if not res then return nil, err end if not res.status then return nil, "No status from consul" end local body, err = res:read_body() if not body then return nil, err end httpc:set_keepalive() if res.status == 200 then return true end -- DELETE seems to return 200 regardless, but just in case return {status = res.status, body = body, headers = res.headers}, err end return _M
Fix wait query param
Fix wait query param
Lua
mit
hamishforbes/lua-resty-consul
e068ba043c22f6885a1034ec561be6f351326cfe
lua/plugins/ltex.lua
lua/plugins/ltex.lua
require("grammar-guard").init() -- setup LSP config require("lspconfig").grammar_guard.setup({ -- cmd = {'/path/to/ltex-ls'}, -- add this if you install ltex-ls yourself settings = { ltex = { enabled = {"latex", "tex", "bib", "markdown"}, language = "en", diagnosticSeverity = "information", setenceCacheSize = 2000, additionalRules = {enablePickyRules = true, motherTongue = "en"}, trace = {server = "verbose"}, dictionary = {}, disabledRules = {}, hiddenFalsePositives = {} } } })
require("grammar-guard").init() local path = vim.fn.stdpath 'config' .. '/spell/en.utf-8.add' local words = {} for word in io.open(path, 'r'):lines() do table.insert(words, word) end -- setup LSP config require("lspconfig").grammar_guard.setup({ -- cmd = {'/path/to/ltex-ls'}, -- add this if you install ltex-ls yourself settings = { ltex = { enabled = {"latex", "tex", "bib", "markdown"}, language = "en", diagnosticSeverity = "information", setenceCacheSize = 2000, additionalRules = {enablePickyRules = true, motherTongue = "en"}, trace = {server = "verbose"}, dictionary = {['en-US'] = words}, disabledRules = { en = { "WORD_CONTAINS_UNDERSCORE", "SENTENCE_FRAGMENT", "DASH_RULE", "TOO_LONG_SENTENCE", "TOO_LONG_PARAGRAPH", "PASSIVE_VOICE", "PUNCTUATION_PARAGRAPH_END", "COMMA_PARENTHESIS_WHITESPACE" } }, hiddenFalsePositives = {} } } })
ltex fix that did not work
ltex fix that did not work
Lua
mit
shwsun/yavc,shwsun/yavc
a26e1a0c84efd59f85d7a5fc29e4d9326464ac03
contrib/package/iwinfo/src/iwinfo.lua
contrib/package/iwinfo/src/iwinfo.lua
#!/usr/bin/lua require "iwinfo" function printf(fmt, ...) print(string.format(fmt, ...)) end function s(x) if x == nil then return "?" else return tostring(x) end end function n(x) if x == nil then return 0 else return tonumber(x) end end function print_info(api, dev) local iw = iwinfo[api] printf("%-9s Type: %s ESSID: \"%s\"", dev, api, iw.ssid(dev)) printf(" Access Point: %s", iw.bssid(dev)) printf(" Mode: %s Channel: %d (%.3f GHz)", iw.mode(dev), iw.channel(dev), n(iw.frequency(dev)) / 1000) printf(" Tx-Power: %s dBm Link Quality: %s/%s", s(iw.txpower(dev)), s(iw.quality(dev)), s(iw.quality_max(dev))) printf(" Signal: %s dBm Noise: %s dBm", s(iw.signal(dev)), s(iw.noise(dev))) printf(" Bit Rate: %.1f MBit/s", n(iw.bitrate(dev)) / 1000) printf(" Encryption: %s", iw.encryption(dev).description) print("") end function print_scan(api, dev) local iw = iwinfo[api] local sr = iw.scanlist(dev) local si, se if sr and #sr > 0 then for si, se in ipairs(sr) do printf("Cell %02d - Address: %s", si, se.bssid) printf(" ESSID: \"%s\"", s(se.ssid)) printf(" Mode: %s Channel: %d", s(se.mode), n(se.channel)) printf(" Signal: %s dBm Quality: %d/%d", s(se.signal), n(se.quality), n(se.quality_max)) printf(" Encryption: %s", s(se.encryption.description)) print("") end else print("No scan results or scanning not possible") print("") end end function print_txpwrlist(api, dev) local iw = iwinfo[api] local pl = iw.txpwrlist(dev) local cp = n(iw.txpower(dev)) local pe if pl and #pl > 0 then for _, pe in ipairs(pl) do printf("%s%3d dBm (%4d mW)", (cp == pe.dbm) and "*" or " ", pe.dbm, pe.mw) end else print("No TX power information available") end print("") end function print_freqlist(api, dev) local iw = iwinfo[api] local fl = iw.freqlist(dev) local cc = n(iw.channel(dev)) local fe if fl and #fl > 0 then for _, fe in ipairs(fl) do printf("%s %.3f GHz (Channel %d)", (cc == fe.channel) and "*" or " ", n(fe.mhz) / 1000, n(fe.channel)) end else print("No frequency information available") end print("") end function print_assoclist(api, dev) local iw = iwinfo[api] local al = iw.assoclist(dev) local ai, ae if al and next(al) then for ai, ae in pairs(al) do printf("%s %s dBm", ai, s(ae.signal)) end else print("No client connected or no information available") end print("") end if #arg ~= 2 then print("Usage:") print(" iwinfo <device> info") print(" iwinfo <device> scan") print(" iwinfo <device> txpowerlist") print(" iwinfo <device> freqlist") print(" iwinfo <device> assoclist") os.exit(1) end local dev = arg[1] local api = iwinfo.type(dev) if not api then print("No such wireless device: " .. dev) os.exit(1) end if arg[2]:match("^i") then print_info(api, dev) elseif arg[2]:match("^s") then print_scan(api, dev) elseif arg[2]:match("^t") then print_txpwrlist(api, dev) elseif arg[2]:match("^f") then print_freqlist(api, dev) elseif arg[2]:match("^a") then print_assoclist(api, dev) else print("Unknown command: " .. arg[2]) end
#!/usr/bin/lua require "iwinfo" function printf(fmt, ...) print(string.format(fmt, ...)) end function s(x) if x == nil then return "?" else return tostring(x) end end function n(x) if x == nil then return 0 else return tonumber(x) end end function print_info(api, dev) local iw = iwinfo[api] local enc = iw.encryption(dev) printf("%-9s Type: %s ESSID: \"%s\"", dev, api, s(iw.ssid(dev))) printf(" Access Point: %s", s(iw.bssid(dev))) printf(" Mode: %s Channel: %d (%.3f GHz)", iw.mode(dev), n(iw.channel(dev)), n(iw.frequency(dev)) / 1000) printf(" Tx-Power: %s dBm Link Quality: %s/%s", s(iw.txpower(dev)), s(iw.quality(dev)), s(iw.quality_max(dev))) printf(" Signal: %s dBm Noise: %s dBm", s(iw.signal(dev)), s(iw.noise(dev))) printf(" Bit Rate: %.1f MBit/s", n(iw.bitrate(dev)) / 1000) printf(" Encryption: %s", s(enc and enc.description)) print("") end function print_scan(api, dev) local iw = iwinfo[api] local sr = iw.scanlist(dev) local si, se if sr and #sr > 0 then for si, se in ipairs(sr) do printf("Cell %02d - Address: %s", si, se.bssid) printf(" ESSID: \"%s\"", s(se.ssid)) printf(" Mode: %s Channel: %d", s(se.mode), n(se.channel)) printf(" Signal: %s dBm Quality: %d/%d", s(se.signal), n(se.quality), n(se.quality_max)) printf(" Encryption: %s", s(se.encryption.description)) print("") end else print("No scan results or scanning not possible") print("") end end function print_txpwrlist(api, dev) local iw = iwinfo[api] local pl = iw.txpwrlist(dev) local cp = n(iw.txpower(dev)) local pe if pl and #pl > 0 then for _, pe in ipairs(pl) do printf("%s%3d dBm (%4d mW)", (cp == pe.dbm) and "*" or " ", n(pe.dbm), n(pe.mw)) end else print("No TX power information available") end print("") end function print_freqlist(api, dev) local iw = iwinfo[api] local fl = iw.freqlist(dev) local cc = n(iw.channel(dev)) local fe if fl and #fl > 0 then for _, fe in ipairs(fl) do printf("%s %.3f GHz (Channel %d)", (cc == fe.channel) and "*" or " ", n(fe.mhz) / 1000, n(fe.channel)) end else print("No frequency information available") end print("") end function print_assoclist(api, dev) local iw = iwinfo[api] local al = iw.assoclist(dev) local ai, ae if al and next(al) then for ai, ae in pairs(al) do printf("%s %s dBm", ai, s(ae.signal)) end else print("No client connected or no information available") end print("") end if #arg ~= 2 then print("Usage:") print(" iwinfo <device> info") print(" iwinfo <device> scan") print(" iwinfo <device> txpowerlist") print(" iwinfo <device> freqlist") print(" iwinfo <device> assoclist") os.exit(1) end local dev = arg[1] local api = iwinfo.type(dev) if not api then print("No such wireless device: " .. dev) os.exit(1) end if arg[2]:match("^i") then print_info(api, dev) elseif arg[2]:match("^s") then print_scan(api, dev) elseif arg[2]:match("^t") then print_txpwrlist(api, dev) elseif arg[2]:match("^f") then print_freqlist(api, dev) elseif arg[2]:match("^a") then print_assoclist(api, dev) else print("Unknown command: " .. arg[2]) end
[libiwinfo] fix crash in iwinfo cli when operating on monitor interfaces
[libiwinfo] fix crash in iwinfo cli when operating on monitor interfaces
Lua
apache-2.0
deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci
29f1330d57b675b6cdf34a44fe989bd9a86705b6
pud/component/ComponentMediator.lua
pud/component/ComponentMediator.lua
local Class = require 'lib.hump.class' local Component = getClass 'pud.component.Component' local ListenerBag = getClass 'pud.kit.ListenerBag' local property = require 'pud.component.property' local message = require 'pud.component.message' local queryFunc = require 'pud.component.queryFunc' -- ComponentMediator -- local ComponentMediator = Class{name='ComponentMediator', function(self) self._listeners = {} end } -- destructor function ComponentMediator:destroy() for k in pairs(self._listeners) do self._listeners[k]:destroy() self._listeners[k] = nil end self._listeners = nil end -- send a message to all attached components function ComponentMediator:send(msg, ...) if self._listeners[msg] then for comp in self._listeners[msg]:listeners() do comp:receive(message(msg, ...)) end end end -- ask all of the given components to attach themselves to this -- ComponentMediator with messages they wish to listen for. function ComponentMediator:registerComponents(components) for _,comp in pairs(components) do comp:attachMessages(self) end end -- attach a component to the given message -- (component will receive this message) function ComponentMediator:attach(msg, comp) self._listeners[msg] = self._listeners[msg] or ListenerBag() self._listeners[msg]:push(comp) end -- detach a component from the given message -- (component will no longer receive this message) function ComponentMediator:detach(msg, comp) if self._listeners[msg] then self._listeners[msg]:pop(comp) end end -- query all components for a property, collect their responses, then feed the -- responses to the given function and return the result. by default, the -- 'sum' function is used. function ComponentMediator:query(prop, func) prop = property(prop) func = func or queryFunc.sum if type(func) == 'string' then func = queryFunc[func] end verify('function', func) local values = {} local numValues = 1 for k in pairs(self._components) do local v = self._components[k]:getProperty(prop) if v ~= nil then values[numValues] = v numValues = numValues+1 end end return #values > 0 and func(values) or nil end -- the class return ComponentMediator
local Class = require 'lib.hump.class' local Component = getClass 'pud.component.Component' local ListenerBag = getClass 'pud.kit.ListenerBag' local property = require 'pud.component.property' local message = require 'pud.component.message' local queryFunc = require 'pud.component.queryFunc' -- ComponentMediator -- local ComponentMediator = Class{name='ComponentMediator', function(self) self._listeners = {} end } -- destructor function ComponentMediator:destroy() for k in pairs(self._listeners) do self._listeners[k]:destroy() self._listeners[k] = nil end self._listeners = nil end -- send a message to all attached components function ComponentMediator:send(msg, ...) if self._listeners[msg] then for comp in self._listeners[msg]:listeners() do comp:receive(message(msg), ...) end end end -- attach a component to the given message -- (component will receive this message) function ComponentMediator:attach(msg, comp) self._listeners[msg] = self._listeners[msg] or ListenerBag() self._listeners[msg]:push(comp) end -- detach a component from the given message -- (component will no longer receive this message) function ComponentMediator:detach(msg, comp) if self._listeners[msg] then self._listeners[msg]:pop(comp) end end -- query all components for a property, collect their responses, then feed the -- responses to the given function and return the result. by default, the -- 'sum' function is used. function ComponentMediator:query(prop, func) prop = property(prop) func = func or queryFunc.sum if type(func) == 'string' then func = queryFunc[func] end verify('function', func) local values = {} local numValues = 1 for k in pairs(self._components) do local v = self._components[k]:getProperty(prop) if v ~= nil then values[numValues] = v numValues = numValues+1 end end return #values > 0 and func(values) or nil end -- the class return ComponentMediator
fix receive call, remove unused registerComponents()
fix receive call, remove unused registerComponents()
Lua
mit
scottcs/wyx
0cec8ab1430fe368ded705d767ed32ab652d6ed4
L1Penalty.lua
L1Penalty.lua
local L1Penalty, parent = torch.class('nn.L1Penalty','nn.Module') --This module acts as an L1 latent state regularizer, adding the --[gradOutput] to the gradient of the L1 loss. The [input] is copied to --the [output]. function L1Penalty:__init(l1weight, sizeAverage) parent.__init(self) self.l1weight = l1weight self.sizeAverage = sizeAverage or false end function L1Penalty:updateOutput(input) local m = self.l1weight if self.sizeAverage == true then m = m/input:nElement() end local loss = m*input:norm(1) self.loss = loss self.output = input return self.output end function L1Penalty:updateGradInput(input, gradOutput) local m = self.l1weight if self.sizeAverage == true then m = m/input:nElement() end self.gradInput:resizeAs(input):copy(input):sign():mul(m) if self.provideOutput == true then self.gradInput:add(gradOutput) end return self.gradInput end
local L1Penalty, parent = torch.class('nn.L1Penalty','nn.Module') --This module acts as an L1 latent state regularizer, adding the --[gradOutput] to the gradient of the L1 loss. The [input] is copied to --the [output]. function L1Penalty:__init(l1weight, sizeAverage, provideOutput) parent.__init(self) self.l1weight = l1weight self.sizeAverage = sizeAverage or false self.provideOutput = provideOutput or true end function L1Penalty:updateOutput(input) local m = self.l1weight if self.sizeAverage == true then m = m/input:nElement() end local loss = m*input:norm(1) self.loss = loss self.output = input return self.output end function L1Penalty:updateGradInput(input, gradOutput) local m = self.l1weight if self.sizeAverage == true then m = m/input:nElement() end self.gradInput:resizeAs(input):copy(input):sign():mul(m) if self.provideOutput == true then self.gradInput:add(gradOutput) end return self.gradInput end
L1Penalty bug fixed
L1Penalty bug fixed
Lua
bsd-3-clause
jonathantompson/nn,Jeffyrao/nn,GregSatre/nn,ominux/nn,karpathy/nn,Moodstocks/nn,zhangxiangxiao/nn,hery/nn,clementfarabet/nn,joeyhng/nn,noa/nn,xianjiec/nn,sbodenstein/nn,bartvm/nn,rotmanmi/nn,Djabbz/nn,abeschneider/nn,colesbury/nn,witgo/nn,eriche2016/nn,boknilev/nn,Aysegul/nn,vgire/nn,jhjin/nn,jzbontar/nn,andreaskoepf/nn,rickyHong/nn_lib_torch,davidBelanger/nn,mlosch/nn,kmul00/nn,sagarwaghmare69/nn,mys007/nn,lukasc-ch/nn,szagoruyko/nn,adamlerer/nn,LinusU/nn,forty-2/nn,EnjoyHacking/nn,apaszke/nn,eulerreich/nn,PraveerSINGH/nn,nicholas-leonard/nn,aaiijmrtt/nn,fmassa/nn,ivendrov/nn,douwekiela/nn,PierrotLC/nn,elbamos/nn,hughperkins/nn,diz-vara/nn,lvdmaaten/nn,zchengquan/nn,caldweln/nn
9535258191b9187e6ba9987391d6777a71f974bd
xmake/rules/cuda/device_link/xmake.lua
xmake/rules/cuda/device_link/xmake.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2019, TBOOX Open Source Group. -- -- @author ruki -- @file xmake.lua -- -- define rule: device-link rule("cuda.device_link") -- after load after_load(function (target) -- get cuda directory local cuda_dir = assert(get_config("cuda"), "Cuda SDK directory not found!") -- add links target:add("links", "cudadevrt", "cudart_static") if is_plat("linux") then target:add("links", "rt", "pthread", "dl") end if is_plat("windows") then local subdir = is_arch("x64") and "x64" or "Win32" target:add("linkdirs", path.join(cuda_dir, "lib", subdir)) target:add("rpathdirs", path.join(cuda_dir, "lib", subdir)) else target:add("linkdirs", path.join(cuda_dir, "lib")) target:add("rpathdirs", path.join(cuda_dir, "lib")) end end) -- @see https://devblogs.nvidia.com/separate-compilation-linking-cuda-device-code/ before_link(function (target, opt) -- imports import("core.base.option") import("core.theme.theme") import("core.project.config") import("core.project.depend") import("core.tool.linker") -- load linker instance local linkinst = linker.load("gpucode", "cu", {target = target}) -- init culdflags local culdflags = {"-dlink"} -- get link flags local linkflags = linkinst:linkflags({target = target, configs = {force = {culdflags = culdflags}}}) -- get target file local targetfile = target:objectfile(path.join(".cuda", "devlink", target:basename() .. "_gpucode.cu")) -- get object files local objectfiles = nil for sourcekind, sourcebatch in pairs(target:sourcebatches()) do if sourcekind == "cu" then objectfiles = sourcebatch.objectfiles end end if not objectfiles then return end -- insert gpucode.o to the object files table.insert(target:objectfiles(), targetfile) -- load dependent info local dependfile = target:dependfile(targetfile) local dependinfo = option.get("rebuild") and {} or (depend.load(dependfile) or {}) -- need build this target? local depfiles = objectfiles local depvalues = {linkinst:program(), linkflags} if not depend.is_changed(dependinfo, {lastmtime = os.mtime(target:targetfile()), values = depvalues, files = depfiles}) then return end -- is verbose? local verbose = option.get("verbose") -- trace progress info cprintf("${color.build.progress}" .. theme.get("text.build.progress_format") .. ":${clear} ", opt.progress) if verbose then cprint("${dim color.build.target}devlinking.$(mode) %s", path.filename(targetfile)) else cprint("${color.build.target}devlinking.$(mode) %s", path.filename(targetfile)) end -- trace verbose info if verbose then print(linkinst:linkcmd(objectfiles, targetfile, {linkflags = linkflags})) end -- flush io buffer to update progress info io.flush() -- link it assert(linkinst:link(objectfiles, targetfile, {linkflags = linkflags})) -- update files and values to the dependent file dependinfo.files = depfiles dependinfo.values = depvalues depend.save(dependinfo, dependfile) 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 - 2019, TBOOX Open Source Group. -- -- @author ruki -- @file xmake.lua -- -- define rule: device-link rule("cuda.device_link") -- after load after_load(function (target) -- get cuda directory local cuda_dir = assert(get_config("cuda"), "Cuda SDK directory not found!") -- add links target:add("links", "cudadevrt", "cudart_static") if is_plat("linux") then target:add("links", "rt", "pthread", "dl") end if is_plat("windows") then local subdir = is_arch("x64") and "x64" or "Win32" target:add("linkdirs", path.join(cuda_dir, "lib", subdir)) target:add("rpathdirs", path.join(cuda_dir, "lib", subdir)) elseif is_plat("linux") and is_arch("x86_64") then target:add("linkdirs", path.join(cuda_dir, "lib64")) target:add("rpathdirs", path.join(cuda_dir, "lib64")) else target:add("linkdirs", path.join(cuda_dir, "lib")) target:add("rpathdirs", path.join(cuda_dir, "lib")) end end) -- @see https://devblogs.nvidia.com/separate-compilation-linking-cuda-device-code/ before_link(function (target, opt) -- imports import("core.base.option") import("core.theme.theme") import("core.project.config") import("core.project.depend") import("core.tool.linker") -- load linker instance local linkinst = linker.load("gpucode", "cu", {target = target}) -- init culdflags local culdflags = {"-dlink"} -- get link flags local linkflags = linkinst:linkflags({target = target, configs = {force = {culdflags = culdflags}}}) -- get target file local targetfile = target:objectfile(path.join(".cuda", "devlink", target:basename() .. "_gpucode.cu")) -- get object files local objectfiles = nil for sourcekind, sourcebatch in pairs(target:sourcebatches()) do if sourcekind == "cu" then objectfiles = sourcebatch.objectfiles end end if not objectfiles then return end -- insert gpucode.o to the object files table.insert(target:objectfiles(), targetfile) -- load dependent info local dependfile = target:dependfile(targetfile) local dependinfo = option.get("rebuild") and {} or (depend.load(dependfile) or {}) -- need build this target? local depfiles = objectfiles local depvalues = {linkinst:program(), linkflags} if not depend.is_changed(dependinfo, {lastmtime = os.mtime(target:targetfile()), values = depvalues, files = depfiles}) then return end -- is verbose? local verbose = option.get("verbose") -- trace progress info cprintf("${color.build.progress}" .. theme.get("text.build.progress_format") .. ":${clear} ", opt.progress) if verbose then cprint("${dim color.build.target}devlinking.$(mode) %s", path.filename(targetfile)) else cprint("${color.build.target}devlinking.$(mode) %s", path.filename(targetfile)) end -- trace verbose info if verbose then print(linkinst:linkcmd(objectfiles, targetfile, {linkflags = linkflags})) end -- flush io buffer to update progress info io.flush() -- link it assert(linkinst:link(objectfiles, targetfile, {linkflags = linkflags})) -- update files and values to the dependent file dependinfo.files = depfiles dependinfo.values = depvalues depend.save(dependinfo, dependfile) end)
fix device-link linkdirs for linux
fix device-link linkdirs for linux
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
0728c31560098da9a50f06c789717f59f44e0054
ffi/util.lua
ffi/util.lua
--[[ Module for various utility functions ]] local ffi = require "ffi" local bit = require "bit" ffi.cdef[[ struct timeval { long int tv_sec; long int tv_usec; }; int gettimeofday(struct timeval *tp, void *tzp); unsigned int sleep(unsigned int seconds); int usleep(unsigned int usec); struct statvfs { unsigned long int f_bsize; unsigned long int f_frsize; unsigned long int f_blocks; unsigned long int f_bfree; unsigned long int f_bavail; unsigned long int f_files; unsigned long int f_ffree; unsigned long int f_favail; unsigned long int f_fsid; unsigned long int f_flag; unsigned long int f_namemax; int __f_spare[6]; }; int statvfs(const char *path, struct statvfs *buf); ]] local util = {} function util.gettime() local timeval = ffi.new("struct timeval") ffi.C.gettimeofday(timeval, nil) return tonumber(timeval.tv_sec), tonumber(timeval.tv_usec) end util.sleep=ffi.C.sleep util.usleep=ffi.C.usleep function util.df(path) local statvfs = ffi.new("struct statvfs") ffi.C.statvfs(path, statvfs) return tonumber(statvfs.f_blocks * statvfs.f_bsize), tonumber(statvfs.f_bfree * statvfs.f_bsize) end function util.utf8charcode(charstring) local ptr = ffi.cast("uint8_t *", charstring) local len = #charstring local result = 0 if len == 1 then return bit.band(ptr[0], 0x7F) elseif len == 2 then return bit.lshift(bit.band(ptr[0], 0x1F), 6) + bit.band(ptr[1], 0x3F) elseif len == 3 then return bit.lshift(bit.band(ptr[0], 0x0F), 12) + bit.lshift(bit.band(ptr[1], 0x3F), 6) + bit.band(ptr[2], 0x3F) end end function util.isEmulated() if ffi.arch == "arm" then return 0 end return 1 end return util
--[[ Module for various utility functions ]] local ffi = require "ffi" local bit = require "bit" ffi.cdef[[ struct timeval { long int tv_sec; long int tv_usec; }; int gettimeofday(struct timeval *restrict, struct timezone *restrict) __attribute__((__nothrow__, __leaf__)); unsigned int sleep(unsigned int); int usleep(unsigned int); struct statvfs { long unsigned int f_bsize; long unsigned int f_frsize; long unsigned int f_blocks; long unsigned int f_bfree; long unsigned int f_bavail; long unsigned int f_files; long unsigned int f_ffree; long unsigned int f_favail; long unsigned int f_fsid; int __f_unused; long unsigned int f_flag; long unsigned int f_namemax; int __f_spare[6]; }; int statvfs(const char *restrict, struct statvfs *restrict) __attribute__((__nothrow__, __leaf__)); ]] local util = {} local timeval = ffi.new("struct timeval") function util.gettime() ffi.C.gettimeofday(timeval, nil) return tonumber(timeval.tv_sec), tonumber(timeval.tv_usec) end util.sleep=ffi.C.sleep util.usleep=ffi.C.usleep local statvfs = ffi.new("struct statvfs") function util.df(path) ffi.C.statvfs(path, statvfs) return tonumber(statvfs.f_blocks * statvfs.f_bsize), tonumber(statvfs.f_bfree * statvfs.f_bsize) end function util.utf8charcode(charstring) local ptr = ffi.cast("uint8_t *", charstring) local len = #charstring local result = 0 if len == 1 then return bit.band(ptr[0], 0x7F) elseif len == 2 then return bit.lshift(bit.band(ptr[0], 0x1F), 6) + bit.band(ptr[1], 0x3F) elseif len == 3 then return bit.lshift(bit.band(ptr[0], 0x0F), 12) + bit.lshift(bit.band(ptr[1], 0x3F), 6) + bit.band(ptr[2], 0x3F) end end function util.isEmulated() if ffi.arch == "arm" then return 0 end return 1 end return util
Fix segfault in util.df and improve performance by struct preallocation (see #46)
Fix segfault in util.df and improve performance by struct preallocation (see #46)
Lua
agpl-3.0
koreader/koreader-base,koreader/koreader-base,apletnev/koreader-base,Hzj-jie/koreader-base,NiLuJe/koreader-base,NiLuJe/koreader-base,NiLuJe/koreader-base,houqp/koreader-base,houqp/koreader-base,Hzj-jie/koreader-base,Frenzie/koreader-base,houqp/koreader-base,apletnev/koreader-base,Frenzie/koreader-base,Hzj-jie/koreader-base,koreader/koreader-base,Hzj-jie/koreader-base,apletnev/koreader-base,Frenzie/koreader-base,Frenzie/koreader-base,frankyifei/koreader-base,frankyifei/koreader-base,houqp/koreader-base,frankyifei/koreader-base,NiLuJe/koreader-base,frankyifei/koreader-base,apletnev/koreader-base,koreader/koreader-base
774511373b5afb78e0ada2dbd6dcea7f873773f0
lua/entities/gmod_wire_trigger_entity.lua
lua/entities/gmod_wire_trigger_entity.lua
-- Wire Trigger created by mitterdoo AddCSLuaFile() ENT.Base = "base_anim" ENT.Name = "Wire Trigger Entity" ENT.Author = "mitterdoo" function ENT:Initialize() if SERVER then self.EntsLookup = {} self.EntsInside = {} end end function ENT:SetupDataTables() self:NetworkVar( "Entity", 0, "TriggerEntity" ) end function ENT:Reset() self.EntsInside = {} self.EntsLookup = {} local owner = self:GetTriggerEntity() if not IsValid( owner ) then return end WireLib.TriggerOutput( owner, "EntCount", 0 ) WireLib.TriggerOutput( owner, "Entities", self.EntsInside ) end function ENT:StartTouch( ent ) local owner = self:GetTriggerEntity() if not IsValid( owner ) then return end if ent == owner then return end -- this never happens but just in case... if owner:GetFilter() == 1 and not ent:IsPlayer() or owner:GetFilter() == 2 and ent:IsPlayer() then return end local ply = ent:IsPlayer() and ent if owner:GetOwnerOnly() and ( WireLib.GetOwner( ent ) or ply ) ~= WireLib.GetOwner( owner ) then return end self.EntsInside[ #self.EntsInside+1 ] = ent self.EntsLookup[ ent ] = #self.EntsInside WireLib.TriggerOutput( owner, "EntCount", #self.EntsInside ) WireLib.TriggerOutput( owner, "Entities", self.EntsInside ) end function ENT:EndTouch( ent ) local owner = self:GetTriggerEntity() if not IsValid( owner ) then return end if not self.EntsLookup[ ent ] then return end table.remove( self.EntsInside, self.EntsLookup[ ent ] ) self.EntsLookup[ ent ] = nil WireLib.TriggerOutput( owner, "EntCount", #self.EntsInside ) WireLib.TriggerOutput( owner, "Entities", self.EntsInside ) end
-- Wire Trigger created by mitterdoo AddCSLuaFile() ENT.Base = "base_anim" ENT.Name = "Wire Trigger Entity" ENT.Author = "mitterdoo" function ENT:Initialize() if SERVER then self.EntsLookup = {} self.EntsInside = {} end end function ENT:SetupDataTables() self:NetworkVar( "Entity", 0, "TriggerEntity" ) end function ENT:Reset() self.EntsInside = {} self.EntsLookup = {} local owner = self:GetTriggerEntity() if not IsValid( owner ) then return end WireLib.TriggerOutput( owner, "EntCount", 0 ) WireLib.TriggerOutput( owner, "Entities", self.EntsInside ) end function ENT:StartTouch( ent ) local owner = self:GetTriggerEntity() if not IsValid( owner ) then return end if ent == owner then return end -- this never happens but just in case... if owner:GetFilter() == 1 and not ent:IsPlayer() or owner:GetFilter() == 2 and ent:IsPlayer() then return end local ply = ent:IsPlayer() and ent if owner:GetOwnerOnly() and ( WireLib.GetOwner( ent ) or ply ) ~= WireLib.GetOwner( owner ) then return end self.EntsInside[ #self.EntsInside+1 ] = ent self.EntsLookup[ ent ] = true WireLib.TriggerOutput( owner, "EntCount", #self.EntsInside ) WireLib.TriggerOutput( owner, "Entities", self.EntsInside ) end function ENT:EndTouch( ent ) local owner = self:GetTriggerEntity() if not IsValid( owner ) then return end if not self.EntsLookup[ ent ] then return end for i = 1, #self.EntsInside do if self.EntsInside[ i ] == ent then table.remove( self.EntsInside, i ) self.EntsLookup[ ent ] = nil end end WireLib.TriggerOutput( owner, "EntCount", #self.EntsInside ) WireLib.TriggerOutput( owner, "Entities", self.EntsInside ) end
Fixed Trigger not removing correct entity index
Fixed Trigger not removing correct entity index If you put a prop in the trigger, add another prop, then remove the first, the lookup table won't have the correct index anymore because table.remove shifts all values.
Lua
apache-2.0
Grocel/wire,wiremod/wire,bigdogmat/wire,CaptainPRICE/wire,notcake/wire,NezzKryptic/Wire,mms92/wire,garrysmodlua/wire,dvdvideo1234/wire,thegrb93/wire,sammyt291/wire,mitterdoo/wire
51b8568eec22618207aaf9dbd2320e1651fe9651
modules/admin-full/luasrc/model/cbi/admin_system/system.lua
modules/admin-full/luasrc/model/cbi/admin_system/system.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.sys") require("luci.sys.zoneinfo") require("luci.tools.webadmin") require("luci.fs") require("luci.config") m = Map("system", translate("System"), translate("Here you can configure the basic aspects of your device like its hostname or the timezone.")) m:chain("luci") local has_rdate = false m.uci:foreach("system", "rdate", function() has_rdate = true return false end) s = m:section(TypedSection, "system", translate("System Properties")) s.anonymous = true s.addremove = false s:tab("general", translate("General Settings")) s:tab("logging", translate("Logging")) s:tab("language", translate("Language and Style")) -- -- System Properties -- local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo() local uptime = luci.sys.uptime() s:taboption("general", DummyValue, "_system", translate("System")).value = system s:taboption("general", DummyValue, "_cpu", translate("Processor")).value = model s:taboption("general", DummyValue, "_kernel", translate("Kernel")).value = luci.util.exec("uname -r") or "?" local load1, load5, load15 = luci.sys.loadavg() s:taboption("general", DummyValue, "_la", translate("Load")).value = string.format("%.2f, %.2f, %.2f", load1, load5, load15) s:taboption("general", DummyValue, "_memtotal", translate("Memory")).value = string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)", tonumber(memtotal) / 1024, 100 * memcached / memtotal, tostring(translate("cached")), 100 * membuffers / memtotal, tostring(translate("buffered")), 100 * memfree / memtotal, tostring(translate("free")) ) s:taboption("general", DummyValue, "_systime", translate("Local Time")).value = os.date("%c") s:taboption("general", DummyValue, "_uptime", translate("Uptime")).value = luci.tools.webadmin.date_format(tonumber(uptime)) hn = s:taboption("general", Value, "hostname", translate("Hostname")) hn.datatype = "hostname" function hn.write(self, section, value) Value.write(self, section, value) luci.sys.hostname(value) end tz = s:taboption("general", ListValue, "zonename", translate("Timezone")) tz:value("UTC") for i, zone in ipairs(luci.sys.zoneinfo.TZ) do tz:value(zone[1]) end function tz.write(self, section, value) local function lookup_zone(title) for _, zone in ipairs(luci.sys.zoneinfo.TZ) do if zone[1] == title then return zone[2] end end end AbstractValue.write(self, section, value) local timezone = lookup_zone(value) or "GMT0" self.map.uci:set("system", section, "timezone", timezone) luci.fs.writefile("/etc/TZ", timezone .. "\n") end -- -- Logging -- o = s:taboption("logging", Value, "log_size", translate("System log buffer size"), "kiB") o.optional = true o.placeholder = 16 o.datatype = "uinteger" o = s:taboption("logging", Value, "log_ip", translate("External system log server")) o.optional = true o.placeholder = "0.0.0.0" o.datatype = "ip4addr" o = s:taboption("logging", Value, "log_port", translate("External system log server port")) o.optional = true o.placeholder = 514 o.datatype = "port" o = s:taboption("logging", ListValue, "conloglevel", translate("Log output level")) o:value(7, translate("Debug")) o:value(6, translate("Info")) o:value(5, translate("Notice")) o:value(4, translate("Warning")) o:value(3, translate("Error")) o:value(2, translate("Critical")) o:value(1, translate("Alert")) o:value(0, translate("Emergency")) o = s:taboption("logging", ListValue, "cronloglevel", translate("Cron Log Level")) o.default = 8 o:value(5, translate("Debug")) o:value(8, translate("Normal")) o:value(9, translate("Warning")) -- -- Langauge & Style -- o = s:taboption("language", ListValue, "_lang", translate("Language")) o:value("auto") local i18ndir = luci.i18n.i18ndir .. "base." for k, v in luci.util.kspairs(luci.config.languages) do local file = i18ndir .. k:gsub("_", "-") if k:sub(1, 1) ~= "." and luci.fs.access(file .. ".lmo") then o:value(k, v) end end function o.cfgvalue(...) return m.uci:get("luci", "main", "lang") end function o.write(self, section, value) m.uci:set("luci", "main", "lang", value) end o = s:taboption("language", ListValue, "_mediaurlbase", translate("Design")) for k, v in pairs(luci.config.themes) do if k:sub(1, 1) ~= "." then o:value(v, k) end end function o.cfgvalue(...) return m.uci:get("luci", "main", "mediaurlbase") end function o.write(self, section, value) m.uci:set("luci", "main", "mediaurlbase", value) end -- -- Rdate -- if has_rdate then m3= Map("timeserver", translate("Time Server (rdate)")) s = m3:section(TypedSection, "timeserver") s.anonymous = true s.addremove = true s.template = "cbi/tblsection" s.rmempty = true s:option(Value, "hostname", translate("Name")) i = s:option(ListValue, "interface", translate("Interface")) i:value("", translate("Default")) m3.uci:foreach("network", "interface", function (section) local ifc = section[".name"] if ifc ~= "loopback" then i:value(ifc) end end ) end m2 = Map("luci") f = m2:section(NamedSection, "main", "core", translate("Files to be kept when flashing a new firmware")) f:tab("detected", translate("Detected Files"), translate("The following files are detected by the system and will be kept automatically during sysupgrade")) f:tab("custom", translate("Custom Files"), translate("This is a list of shell glob patterns for matching files and directories to include during sysupgrade")) d = f:taboption("detected", DummyValue, "_detected", translate("Detected files")) d.rawhtml = true d.cfgvalue = function(s) local list = io.popen( "( find $(sed -ne '/^[[:space:]]*$/d; /^#/d; p' /etc/sysupgrade.conf " .. "/lib/upgrade/keep.d/* 2>/dev/null) -type f 2>/dev/null; " .. "opkg list-changed-conffiles ) | sort -u" ) if list then local files = { "<ul>" } while true do local ln = list:read("*l") if not ln then break else files[#files+1] = "<li>" files[#files+1] = luci.util.pcdata(ln) files[#files+1] = "</li>" end end list:close() files[#files+1] = "</ul>" return table.concat(files, "") end return "<em>" .. translate("No files found") .. "</em>" end c = f:taboption("custom", TextValue, "_custom", translate("Custom files")) c.rmempty = false c.cols = 70 c.rows = 30 c.cfgvalue = function(self, section) return nixio.fs.readfile("/etc/sysupgrade.conf") end c.write = function(self, section, value) value = value:gsub("\r\n?", "\n") return nixio.fs.writefile("/etc/sysupgrade.conf", value) end return m, m3, m2
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.sys") require("luci.sys.zoneinfo") require("luci.tools.webadmin") require("luci.fs") require("luci.config") m = Map("system", translate("System"), translate("Here you can configure the basic aspects of your device like its hostname or the timezone.")) m:chain("luci") local has_rdate = false m.uci:foreach("system", "rdate", function() has_rdate = true return false end) s = m:section(TypedSection, "system", translate("System Properties")) s.anonymous = true s.addremove = false s:tab("general", translate("General Settings")) s:tab("logging", translate("Logging")) s:tab("language", translate("Language and Style")) -- -- System Properties -- local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo() local uptime = luci.sys.uptime() s:taboption("general", DummyValue, "_system", translate("System")).value = system s:taboption("general", DummyValue, "_cpu", translate("Processor")).value = model s:taboption("general", DummyValue, "_kernel", translate("Kernel")).value = luci.util.exec("uname -r") or "?" local load1, load5, load15 = luci.sys.loadavg() s:taboption("general", DummyValue, "_la", translate("Load")).value = string.format("%.2f, %.2f, %.2f", load1, load5, load15) s:taboption("general", DummyValue, "_memtotal", translate("Memory")).value = string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)", tonumber(memtotal) / 1024, 100 * memcached / memtotal, tostring(translate("cached")), 100 * membuffers / memtotal, tostring(translate("buffered")), 100 * memfree / memtotal, tostring(translate("free")) ) s:taboption("general", DummyValue, "_systime", translate("Local Time")).value = os.date("%c") s:taboption("general", DummyValue, "_uptime", translate("Uptime")).value = luci.tools.webadmin.date_format(tonumber(uptime)) hn = s:taboption("general", Value, "hostname", translate("Hostname")) hn.datatype = "hostname" function hn.write(self, section, value) Value.write(self, section, value) luci.sys.hostname(value) end tz = s:taboption("general", ListValue, "zonename", translate("Timezone")) tz:value("UTC") for i, zone in ipairs(luci.sys.zoneinfo.TZ) do tz:value(zone[1]) end function tz.write(self, section, value) local function lookup_zone(title) for _, zone in ipairs(luci.sys.zoneinfo.TZ) do if zone[1] == title then return zone[2] end end end AbstractValue.write(self, section, value) local timezone = lookup_zone(value) or "GMT0" self.map.uci:set("system", section, "timezone", timezone) luci.fs.writefile("/etc/TZ", timezone .. "\n") end -- -- Logging -- o = s:taboption("logging", Value, "log_size", translate("System log buffer size"), "kiB") o.optional = true o.placeholder = 16 o.datatype = "uinteger" o = s:taboption("logging", Value, "log_ip", translate("External system log server")) o.optional = true o.placeholder = "0.0.0.0" o.datatype = "ip4addr" o = s:taboption("logging", Value, "log_port", translate("External system log server port")) o.optional = true o.placeholder = 514 o.datatype = "port" o = s:taboption("logging", ListValue, "conloglevel", translate("Log output level")) o:value(7, translate("Debug")) o:value(6, translate("Info")) o:value(5, translate("Notice")) o:value(4, translate("Warning")) o:value(3, translate("Error")) o:value(2, translate("Critical")) o:value(1, translate("Alert")) o:value(0, translate("Emergency")) o = s:taboption("logging", ListValue, "cronloglevel", translate("Cron Log Level")) o.default = 8 o:value(5, translate("Debug")) o:value(8, translate("Normal")) o:value(9, translate("Warning")) -- -- Langauge & Style -- o = s:taboption("language", ListValue, "_lang", translate("Language")) o:value("auto") local i18ndir = luci.i18n.i18ndir .. "base." for k, v in luci.util.kspairs(luci.config.languages) do local file = i18ndir .. k:gsub("_", "-") if k:sub(1, 1) ~= "." and luci.fs.access(file .. ".lmo") then o:value(k, v) end end function o.cfgvalue(...) return m.uci:get("luci", "main", "lang") end function o.write(self, section, value) m.uci:set("luci", "main", "lang", value) end o = s:taboption("language", ListValue, "_mediaurlbase", translate("Design")) for k, v in pairs(luci.config.themes) do if k:sub(1, 1) ~= "." then o:value(v, k) end end function o.cfgvalue(...) return m.uci:get("luci", "main", "mediaurlbase") end function o.write(self, section, value) m.uci:set("luci", "main", "mediaurlbase", value) end -- -- Rdate -- if has_rdate then m3= Map("timeserver", translate("Time Server (rdate)")) s = m3:section(TypedSection, "timeserver") s.anonymous = true s.addremove = true s.template = "cbi/tblsection" h = s:option(Value, "hostname", translate("Name")) h.rmempty = true h.datatype = host i = s:option(ListValue, "interface", translate("Interface")) i.rmempty = true i:value("", translate("Default")) m3.uci:foreach("network", "interface", function (section) local ifc = section[".name"] if ifc ~= "loopback" then i:value(ifc) end end ) end m2 = Map("luci") f = m2:section(NamedSection, "main", "core", translate("Files to be kept when flashing a new firmware")) f:tab("detected", translate("Detected Files"), translate("The following files are detected by the system and will be kept automatically during sysupgrade")) f:tab("custom", translate("Custom Files"), translate("This is a list of shell glob patterns for matching files and directories to include during sysupgrade")) d = f:taboption("detected", DummyValue, "_detected", translate("Detected files")) d.rawhtml = true d.cfgvalue = function(s) local list = io.popen( "( find $(sed -ne '/^[[:space:]]*$/d; /^#/d; p' /etc/sysupgrade.conf " .. "/lib/upgrade/keep.d/* 2>/dev/null) -type f 2>/dev/null; " .. "opkg list-changed-conffiles ) | sort -u" ) if list then local files = { "<ul>" } while true do local ln = list:read("*l") if not ln then break else files[#files+1] = "<li>" files[#files+1] = luci.util.pcdata(ln) files[#files+1] = "</li>" end end list:close() files[#files+1] = "</ul>" return table.concat(files, "") end return "<em>" .. translate("No files found") .. "</em>" end c = f:taboption("custom", TextValue, "_custom", translate("Custom files")) c.rmempty = false c.cols = 70 c.rows = 30 c.cfgvalue = function(self, section) return nixio.fs.readfile("/etc/sysupgrade.conf") end c.write = function(self, section, value) value = value:gsub("\r\n?", "\n") return nixio.fs.writefile("/etc/sysupgrade.conf", value) end return m, m3, m2
modules/admin-full: Fixes for rdate config
modules/admin-full: Fixes for rdate config
Lua
apache-2.0
deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,8devices/luci,deepak78/luci
656f02c7f67949096a538353786079e2a9aa6dfe
frontend/apps/filemanager/fm.lua
frontend/apps/filemanager/fm.lua
require "ui/widget/filechooser" require "apps/filemanager/fmhistory" require "apps/filemanager/fmmenu" FileManager = InputContainer:extend{ title = _("FileManager"), width = Screen:getWidth(), height = Screen:getHeight(), root_path = './', -- our own size dimen = Geom:new{ w = 400, h = 600 }, onExit = function() end, } function FileManager:init() local exclude_dirs = {"%.sdr$"} self.show_parent = self.show_parent or self local file_chooser = FileChooser:new{ _name = 'fuck', is_popout = false, is_borderless = true, has_close_button = true, dir_filter = function(dirname) for _, pattern in ipairs(exclude_dirs) do if dirname:match(pattern) then return end end return true end, file_filter = function(filename) if DocumentRegistry:getProvider(filename) then return true end end } function file_chooser:onFileSelect(file) showReaderUI(file) return true end self.banner = FrameContainer:new{ padding = 0, bordersize = 0, TextWidget:new{ face = Font:getFace("tfont", 24), text = self.title, } } self.layout = VerticalGroup:new{ _name = 'fm', self.banner, file_chooser, } local fm_ui = FrameContainer:new{ padding = 0, bordersize = 0, padding = self.padding, background = 0, self.layout, } self[1] = fm_ui self.menu = FileManagerMenu:new{ ui = self } table.insert(self, self.menu) table.insert(self, FileManagerHistory:new{ ui = self, menu = self.menu }) self:handleEvent(Event:new("SetDimensions", self.dimen)) end function FileManager:onClose() UIManager:close(self) if self.onExit then self:onExit() end return true end
require "ui/widget/filechooser" require "apps/filemanager/fmhistory" require "apps/filemanager/fmmenu" FileManager = InputContainer:extend{ title = _("FileManager"), width = Screen:getWidth(), height = Screen:getHeight(), root_path = './', -- our own size dimen = Geom:new{ w = 400, h = 600 }, onExit = function() end, } function FileManager:init() local exclude_dirs = {"%.sdr$"} self.show_parent = self.show_parent or self self.banner = FrameContainer:new{ padding = 0, bordersize = 0, TextWidget:new{ face = Font:getFace("tfont", 24), text = self.title, } } local file_chooser = FileChooser:new{ -- remeber to adjust the height when new item is added to the group height = Screen:getHeight() - self.banner:getSize().h, is_popout = false, is_borderless = true, has_close_button = true, dir_filter = function(dirname) for _, pattern in ipairs(exclude_dirs) do if dirname:match(pattern) then return end end return true end, file_filter = function(filename) if DocumentRegistry:getProvider(filename) then return true end end } function file_chooser:onFileSelect(file) showReaderUI(file) return true end self.layout = VerticalGroup:new{ self.banner, file_chooser, } local fm_ui = FrameContainer:new{ padding = 0, bordersize = 0, background = 0, self.layout, } self[1] = fm_ui self.menu = FileManagerMenu:new{ ui = self } table.insert(self, self.menu) table.insert(self, FileManagerHistory:new{ ui = self, menu = self.menu }) self:handleEvent(Event:new("SetDimensions", self.dimen)) end function FileManager:onClose() UIManager:close(self) if self.onExit then self:onExit() end return true end
fix out-of-bound bug in filemanager
fix out-of-bound bug in filemanager
Lua
agpl-3.0
pazos/koreader,koreader/koreader,robert00s/koreader,frankyifei/koreader,poire-z/koreader,koreader/koreader,ashang/koreader,chrox/koreader,Frenzie/koreader,mwoz123/koreader,houqp/koreader,chihyang/koreader,ashhher3/koreader,mihailim/koreader,NiLuJe/koreader,noname007/koreader,lgeek/koreader,NickSavage/koreader,Markismus/koreader,apletnev/koreader,Hzj-jie/koreader,Frenzie/koreader,poire-z/koreader,NiLuJe/koreader
40fe33005559223610852cb2d204344c80c34049
game_view.lua
game_view.lua
-- imports grid_state = require 'grid_state' glitch_gen = require 'glitchGen' directions = require 'directions' glider = require 'glider' watcher = require 'watcher' player_state = require 'player_state' stack_trace = require 'stackTrace' active_screen = require 'active_screen' game_over_view = require 'game_over_view' grid_normal_color = {180, 230, 255} grid_block_color = {100, 200, 250} grid_line_width = 0.5 grid_unit_size = 32 grid_big_border = 5 -- mouse variables mouse_x = 0; mouse_y = 0; mouseClicked = false; lastFrameMouseClicked = false; -- glider variables rectanglesToDraw = {} numberOfGliders = 0 -- grid state MODE_SIGNAL = 'signal' MODE_EVOLUTION = 'evolution' mode = MODE_SIGNAL evolution_phases = 5 -- visual glitch state glitchUpdateTimer = 0.5 function draw_line(grid_num, x1, y1, x2, y2) local is_main = grid_num % grid_big_border == 0 local color = is_main and grid_block_color or grid_normal_color local width = grid_line_width love.graphics.setLineWidth(width) love.graphics.setColor(color[1], color[2], color[3]) love.graphics.line(x1, y1, x2, y2) end function gliderClicked() lastGlider.direction = directions.rotate_clockwise(lastGlider.direction) end function processGoButtonClicked(grid_state, player_state) player_state:endRound() gliderPlaced = false mode = MODE_EVOLUTION tick_time = 0 evolution_phase = 1 end function exports(round_num) local instance = {} local block_size = grid_unit_size * grid_big_border available_width = 1280 - 250 local xoffsets = available_width % block_size if xoffsets == 0 then xoffsets = block_size end local xoffset = xoffsets / 2 local xcount = (available_width - xoffsets) / grid_unit_size local yoffsets = 720 % block_size local yoffset = yoffsets / 2 local ycount = (720 - yoffsets) / grid_unit_size instance.grid_state = grid_state(xcount, ycount) instance.player_state = player_state(round_num) for watcherI=1,10 do instance.grid_state:add_object(watcher(math.random(0,xcount), math.random(0,ycount), directions.DOWN)) end instance.goButtonImage = love.graphics.newImage( "placeholders/goButton.png" ) local goButtonX = love.window.getWidth()-225 local goButtonY = love.window.getHeight()-yoffset-50 local goButtonWidth = 64 local goButtonHeight = 32 local background = love.graphics.newImage('background/background_light.png') instance.roundImage = love.graphics.newImage("placeholders/round.png") local roundX = (xcount-0.7) * grid_unit_size + xoffset local roundY = 0.4 * grid_unit_size local roundWidth = 24 function instance:draw() love.graphics.setColor(255,255,255) love.graphics.draw(background, 0, 0) -- Draw Grid local current_x = xoffset local grid_num = 0 while grid_num <= xcount do draw_line(grid_num, current_x, yoffset, current_x, yoffset + ycount * grid_unit_size) if mouse_x >= current_x and mouse_x < current_x + grid_unit_size then drawGliderX = grid_num end current_x = current_x + grid_unit_size grid_num = grid_num + 1 end local current_y = yoffset grid_num = 0 while grid_num <= ycount do draw_line(grid_num, xoffset, current_y, xoffset + xcount * grid_unit_size, current_y) if mouse_y >= current_y and mouse_y < current_y + grid_unit_size then drawGliderY = grid_num end current_y = current_y + grid_unit_size grid_num = grid_num + 1 end stack_trace.draw_stack(self.grid_state, love.window.getWidth()-250, 100,love.mouse.getX(),love.mouse.getY(),xoffset,yoffset,current_object) if glitchUpdateTimer > 0.2 then glitchUpdate = true glitchUpdateTimer = glitchUpdateTimer - 0.2 end for i,rect in ipairs(rectanglesToDraw) do glitch_gen.drawGlich(rect["x"], rect["y"], xcount, glitchUpdate) end for x = 1, xcount, 1 do for y = 1, ycount, 1 do if self.grid_state:get_space_at(x, y) then glitch_gen.drawGlich( (x-1) * grid_unit_size + xoffset, (y-1) * grid_unit_size + yoffset, xcount, glitchUpdate) end end end self.grid_state:draw_objects(xoffset, yoffset) glitchUpdate = false if mode == MODE_SIGNAL then -- Button Go to Evolution mode love.graphics.setColor(255, 255, 255) love.graphics.draw(self.goButtonImage, goButtonX, goButtonY) end -- rounds for i = 1, self.player_state.numberOfRounds, 1 do love.graphics.draw(self.roundImage, roundX - (roundWidth+2)*(i-1),roundY) end end function instance:update() if self.player_state.gameOver then active_screen.set(game_over_view()) return end if mode == MODE_SIGNAL then mouse_x, mouse_y = love.mouse.getPosition() lastFrameMouseClicked = mouseClicked mouseClicked = love.mouse.isDown("l") if mouseClicked then target_x = math.floor((mouse_x - xoffset) / grid_unit_size) + 1 target_y = math.floor((mouse_y - yoffset) / grid_unit_size) + 1 if self.grid_state:in_grid(target_x, target_y) and not self.grid_state:get_space_at(target_x, target_y) then if gliderPlaced then if lastGlider.x == target_x and lastGlider.y == target_y and not lastFrameMouseClicked then gliderClicked() elseif self.grid_state:get_object_at(target_x, target_y) == nil then lastGlider.x = target_x lastGlider.y = target_y end elseif self.grid_state:get_object_at(target_x, target_y) == nil then lastGlider = glider(target_x, target_y, directions.DOWN) self.grid_state:add_object(lastGlider) gliderPlaced = true end elseif mouse_x > goButtonX and mouse_x <= goButtonX + goButtonWidth and mouse_y > goButtonY and mouse_y <= goButtonY + goButtonHeight and not lastFrameMouseClicked then processGoButtonClicked(self.grid_state, self.player_state) end end else if tick_time >= 3 then tick_time = 0 if evolution_phase > evolution_phases then mode = MODE_SIGNAL current_object = nil else if current_object == nil then current_object = self.grid_state.first_object end if current_object ~= nil then current_object:update(self.grid_state) current_object = current_object.next if current_object == nil then evolution_phase = evolution_phase + 1 end end end else tick_time = tick_time + 1 end end glitchUpdateTimer = glitchUpdateTimer + 1/60 end return instance end return exports
-- imports grid_state = require 'grid_state' glitch_gen = require 'glitchGen' directions = require 'directions' glider = require 'glider' watcher = require 'watcher' player_state = require 'player_state' stack_trace = require 'stackTrace' active_screen = require 'active_screen' game_over_view = require 'game_over_view' grid_normal_color = {180, 230, 255} grid_block_color = {100, 200, 250} grid_line_width = 0.5 grid_unit_size = 32 grid_big_border = 5 -- mouse variables mouse_x = 0; mouse_y = 0; -- glider variables rectanglesToDraw = {} -- grid state MODE_SIGNAL = 'signal' MODE_EVOLUTION = 'evolution' evolution_phases = 5 -- visual glitch state glitchUpdateTimer = 0.5 function draw_line(grid_num, x1, y1, x2, y2) local is_main = grid_num % grid_big_border == 0 local color = is_main and grid_block_color or grid_normal_color local width = grid_line_width love.graphics.setLineWidth(width) love.graphics.setColor(color[1], color[2], color[3]) love.graphics.line(x1, y1, x2, y2) end function exports(round_num) local instance = {} local mouseClicked = false; local lastFrameMouseClicked = true; local mode = MODE_SIGNAL local function gliderClicked() lastGlider.direction = directions.rotate_clockwise(lastGlider.direction) end local function processGoButtonClicked(grid_state, player_state) player_state:endRound() gliderPlaced = false mode = MODE_EVOLUTION tick_time = 0 evolution_phase = 1 end local block_size = grid_unit_size * grid_big_border available_width = 1280 - 250 local xoffsets = available_width % block_size if xoffsets == 0 then xoffsets = block_size end local xoffset = xoffsets / 2 local xcount = (available_width - xoffsets) / grid_unit_size local yoffsets = 720 % block_size local yoffset = yoffsets / 2 local ycount = (720 - yoffsets) / grid_unit_size instance.grid_state = grid_state(xcount, ycount) instance.player_state = player_state(round_num) for watcherI=1,10 do instance.grid_state:add_object(watcher(math.random(0,xcount), math.random(0,ycount), directions.DOWN)) end instance.goButtonImage = love.graphics.newImage( "placeholders/goButton.png" ) local goButtonX = love.window.getWidth()-225 local goButtonY = love.window.getHeight()-yoffset-50 local goButtonWidth = 64 local goButtonHeight = 32 local background = love.graphics.newImage('background/background_light.png') instance.roundImage = love.graphics.newImage("placeholders/round.png") local roundX = (xcount-0.7) * grid_unit_size + xoffset local roundY = 0.4 * grid_unit_size local roundWidth = 24 function instance:draw() love.graphics.setColor(255,255,255) love.graphics.draw(background, 0, 0) -- Draw Grid local current_x = xoffset local grid_num = 0 while grid_num <= xcount do draw_line(grid_num, current_x, yoffset, current_x, yoffset + ycount * grid_unit_size) if mouse_x >= current_x and mouse_x < current_x + grid_unit_size then drawGliderX = grid_num end current_x = current_x + grid_unit_size grid_num = grid_num + 1 end local current_y = yoffset grid_num = 0 while grid_num <= ycount do draw_line(grid_num, xoffset, current_y, xoffset + xcount * grid_unit_size, current_y) if mouse_y >= current_y and mouse_y < current_y + grid_unit_size then drawGliderY = grid_num end current_y = current_y + grid_unit_size grid_num = grid_num + 1 end stack_trace.draw_stack(self.grid_state, love.window.getWidth()-250, 100,love.mouse.getX(),love.mouse.getY(),xoffset,yoffset,current_object) if glitchUpdateTimer > 0.2 then glitchUpdate = true glitchUpdateTimer = glitchUpdateTimer - 0.2 end for i,rect in ipairs(rectanglesToDraw) do glitch_gen.drawGlich(rect["x"], rect["y"], xcount, glitchUpdate) end for x = 1, xcount, 1 do for y = 1, ycount, 1 do if self.grid_state:get_space_at(x, y) then glitch_gen.drawGlich( (x-1) * grid_unit_size + xoffset, (y-1) * grid_unit_size + yoffset, xcount, glitchUpdate) end end end self.grid_state:draw_objects(xoffset, yoffset) glitchUpdate = false if mode == MODE_SIGNAL then -- Button Go to Evolution mode love.graphics.setColor(255, 255, 255) love.graphics.draw(self.goButtonImage, goButtonX, goButtonY) end -- rounds for i = 1, self.player_state.numberOfRounds, 1 do love.graphics.draw(self.roundImage, roundX - (roundWidth+2)*(i-1),roundY) end end function instance:update() if self.player_state.gameOver then active_screen.set(game_over_view()) return end if mode == MODE_SIGNAL then mouse_x, mouse_y = love.mouse.getPosition() lastFrameMouseClicked = mouseClicked mouseClicked = love.mouse.isDown("l") if mouseClicked then target_x = math.floor((mouse_x - xoffset) / grid_unit_size) + 1 target_y = math.floor((mouse_y - yoffset) / grid_unit_size) + 1 if self.grid_state:in_grid(target_x, target_y) and not self.grid_state:get_space_at(target_x, target_y) then if gliderPlaced then if lastGlider.x == target_x and lastGlider.y == target_y and not lastFrameMouseClicked then gliderClicked() elseif self.grid_state:get_object_at(target_x, target_y) == nil then lastGlider.x = target_x lastGlider.y = target_y end elseif self.grid_state:get_object_at(target_x, target_y) == nil then lastGlider = glider(target_x, target_y, directions.DOWN) self.grid_state:add_object(lastGlider) gliderPlaced = true end elseif mouse_x > goButtonX and mouse_x <= goButtonX + goButtonWidth and mouse_y > goButtonY and mouse_y <= goButtonY + goButtonHeight and not lastFrameMouseClicked then processGoButtonClicked(self.grid_state, self.player_state) end end else if tick_time >= 3 then tick_time = 0 if evolution_phase > evolution_phases then mode = MODE_SIGNAL current_object = nil else if current_object == nil then current_object = self.grid_state.first_object end if current_object ~= nil then current_object:update(self.grid_state) current_object = current_object.next if current_object == nil then evolution_phase = evolution_phase + 1 end end end else tick_time = tick_time + 1 end end glitchUpdateTimer = glitchUpdateTimer + 1/60 end return instance end return exports
Fixed a few bugs.
Fixed a few bugs.
Lua
mit
NamefulTeam/PortoGameJam2015
c7cfd896b9dca86df49ae00b2dcf298f4234d4cd
api/server.lua
api/server.lua
local htmlparser = require("htmlparser") local http = require('socket.http') local app = require('waffle').CmdLine() local search = function(req, res) local query = req.url.args.zoektermen local queryType = tonumber(req.url.args.opZoeken) local queryPage = tonumber(req.url.args.page) or 0 local queryEan = "" if query == nil then res.send("Error") end -- Ean query if queryType == 1 then queryEan = query query = "" end local url = {'http://livaad.nl/app/loaddata.php', '?artq=', query, '&eanq=', queryEan, '&producentq=&p=', queryPage} if queryPage < 1 then url[1] = 'http://livaad.nl/database/' end local body, c, l, h = http.request(table.concat(url, "")) local root = htmlparser.parse(body) if queryPage < 1 then local dataContainer = root:select("#data-container") if #dataContainer>=1 then root = htmlparser.parse(dataContainer[1]:getcontent()) else res.send("Error") end end local products = root:select(".panel") local results = {} -- Get all products print(#products) for i=1,#products do local header = products[i](".panel-heading") if #header >= 1 then local brand, name = unpack(header[1]:select('div')) brand = brand:getcontent() name, c = string.gsub(name:getcontent(), '<(.*)>', "") local rows = products[i]('.row') local attributes = {} for i=1,#rows do local k, v = unpack(rows[i]('div')) attributes[k:getcontent():gsub("[( |:)]", "")] = v:getcontent() end local bsm = "" -- By default TODO local source = "" -- By default TODO -- 1 is free, 2 is contains local _, starch = attributes["Tarwezetmeel"]:gsub("vrij", "vrij") starch = starch > 0 and 1 or 2 local _, lactose = attributes["Lactose"]:gsub("vrij", "vrij") lactose = lactose > 0 and 1 or 2 local datum = string.gsub(attributes["Checkdatum"], '<(.*)>(.*)</(.*)>', ""):gsub(" ", "") results[#results+1] = {name, attributes["EAN"], brand, attributes["Soort"], starch, lactose, bsm, datum, source} end end res.json({api_version=0.2, results=results}) end app.get('/search.php', search) app.get('/glutenvrij/search.php', search) -- 127.0.0.1 app.listen()
local htmlparser = require("htmlparser") local http = require('socket.http') local app = require('waffle').CmdLine() local search = function(req, res) local query = req.url.args.zoektermen local queryType = tonumber(req.url.args.opZoeken) local queryPage = tonumber(req.url.args.page) or 0 local queryEan = "" if query == nil then res.send("Error") end -- Ean query if queryType == 1 then queryEan = query query = "" end local url = {'http://livaad.nl/app/loaddata.php', '?artq=', query, '&eanq=', queryEan, '&producentq=&p=', queryPage} if queryPage < 1 then url[1] = 'http://livaad.nl/database/' end local body, c, l, h = http.request(table.concat(url, "")) local root = htmlparser.parse(body) if queryPage < 1 then local dataContainer = root:select("#data-container") if #dataContainer>=1 then root = htmlparser.parse(dataContainer[1]:getcontent()) else res.send("Error") end end local products = root:select(".panel") local results = {} -- Get all products for i=1,#products do local header = products[i](".panel-heading") if #header >= 1 then local brand, name = unpack(header[1]:select('div')) brand = brand:getcontent() name, c = string.gsub(name:getcontent(), '<(.*)>', "") local rows = products[i]('.row') local attributes = {} for i=1,#rows do local k, v = unpack(rows[i]('div')) attributes[k:getcontent():gsub("[( |:)]", "")] = v:getcontent() end local bsm = "" -- By default TODO local source = "" -- By default TODO -- 1 is free, 2 is contains local _, starch = attributes["Tarwezetmeel"]:gsub("vrij", "vrij") starch = starch > 0 and 1 or 2 local _, lactose = attributes["Lactose"]:gsub("vrij", "vrij") lactose = lactose > 0 and 1 or 2 local datum = string.gsub(attributes["Checkdatum"], '<(.*)>(.*)</(.*)>', ""):gsub(" ", ""):gsub("-201", "") -- TODO: Fix in app results[#results+1] = {name, attributes["EAN"], brand, attributes["Soort"], starch, lactose, bsm, datum, source} end end res.json({api_version=0.2, results=results}) end app.get('/search.php', search) app.get('/glutenvrij/search.php', search) -- 127.0.0.1 app.listen()
Fix data format to app format
Fix data format to app format
Lua
mit
JoostvDoorn/GlutenVrijApp
4a9259586dfac657054ad74b8edd7e16928b7a08
modules/rpc/luasrc/controller/rpc.lua
modules/rpc/luasrc/controller/rpc.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local require = require local pairs = pairs local print = print local pcall = pcall local table = table module "luci.controller.rpc" function index() local function authenticator(validator, accs) local auth = luci.http.formvalue("auth", true) if auth then local user = luci.sauth.read(auth) if user and luci.util.contains(accs, user) then return user, auth end end luci.http.status(403, "Forbidden") end if pcall(require, "luci.model.uci") then uci = entry({"rpc", "uci"}, call("rpc_uci")) uci.sysauth = "root" uci.sysauth_authenticator = authenticator end fs = entry({"rpc", "fs"}, call("rpc_fs")) fs.sysauth = "root" fs.sysauth_authenticator = authenticator sys = entry({"rpc", "sys"}, call("rpc_sys")) sys.sysauth = "root" sys.sysauth_authenticator = authenticator if pcall(require, "luci.model.ipkg") then fs = entry({"rpc", "ipkg"}, call("rpc_ipkg")) fs.sysauth = "root" fs.sysauth_authenticator = authenticator end uci = entry({"rpc", "auth"}, call("rpc_auth")) end function rpc_auth() local jsonrpc = require "luci.jsonrpc" local sauth = require "luci.sauth" local http = require "luci.http" local sys = require "luci.sys" local ltn12 = require "luci.ltn12" http.setfilehandler() local loginstat local server = {} server.login = function(user, pass) local sid if sys.user.checkpasswd(user, pass) then sid = sys.uniqueid(16) http.header("Set-Cookie", "sysauth=" .. sid.."; path=/") sauth.write(sid, user) end return sid end http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(server, http.source()), http.write) end function rpc_uci() local uci = require "luci.controller.rpc.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 "luci.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 sys = require "luci.sys" 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(sys, http.source()), http.write) end function rpc_ipkg() 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
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local require = require local pairs = pairs local print = print local pcall = pcall local table = table module "luci.controller.rpc" function index() local function authenticator(validator, accs) local auth = luci.http.formvalue("auth", true) if auth then local user = luci.sauth.read(auth) if user and luci.util.contains(accs, user) then return user, auth end end luci.http.status(403, "Forbidden") end uci = entry({"rpc", "uci"}, call("rpc_uci")) uci.sysauth = "root" uci.sysauth_authenticator = authenticator fs = entry({"rpc", "fs"}, call("rpc_fs")) fs.sysauth = "root" fs.sysauth_authenticator = authenticator sys = entry({"rpc", "sys"}, call("rpc_sys")) sys.sysauth = "root" sys.sysauth_authenticator = authenticator ipkg = entry({"rpc", "ipkg"}, call("rpc_ipkg")) ipkg.sysauth = "root" ipkg.sysauth_authenticator = authenticator uci = entry({"rpc", "auth"}, call("rpc_auth")) end function rpc_auth() local jsonrpc = require "luci.jsonrpc" local sauth = require "luci.sauth" local http = require "luci.http" local sys = require "luci.sys" local ltn12 = require "luci.ltn12" http.setfilehandler() local loginstat local server = {} server.login = function(user, pass) local sid if sys.user.checkpasswd(user, pass) then sid = sys.uniqueid(16) http.header("Set-Cookie", "sysauth=" .. sid.."; path=/") sauth.write(sid, user) end return sid 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.controller.rpc.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 "luci.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 sys = require "luci.sys" 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(sys, 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
Fixed RPC-API
Fixed RPC-API
Lua
apache-2.0
RuiChen1113/luci,RedSnake64/openwrt-luci-packages,shangjiyu/luci-with-extra,keyidadi/luci,bittorf/luci,kuoruan/lede-luci,RedSnake64/openwrt-luci-packages,jchuang1977/luci-1,RuiChen1113/luci,sujeet14108/luci,db260179/openwrt-bpi-r1-luci,fkooman/luci,harveyhu2012/luci,oyido/luci,oyido/luci,mumuqz/luci,Hostle/openwrt-luci-multi-user,obsy/luci,Sakura-Winkey/LuCI,palmettos/test,palmettos/cnLuCI,aircross/OpenWrt-Firefly-LuCI,jorgifumi/luci,shangjiyu/luci-with-extra,kuoruan/lede-luci,taiha/luci,keyidadi/luci,bittorf/luci,aa65535/luci,zhaoxx063/luci,thess/OpenWrt-luci,zhaoxx063/luci,NeoRaider/luci,forward619/luci,opentechinstitute/luci,keyidadi/luci,opentechinstitute/luci,dwmw2/luci,rogerpueyo/luci,aa65535/luci,aircross/OpenWrt-Firefly-LuCI,bright-things/ionic-luci,lcf258/openwrtcn,jchuang1977/luci-1,nwf/openwrt-luci,schidler/ionic-luci,forward619/luci,male-puppies/luci,jorgifumi/luci,Wedmer/luci,RuiChen1113/luci,jorgifumi/luci,maxrio/luci981213,Hostle/luci,cshore-firmware/openwrt-luci,marcel-sch/luci,taiha/luci,keyidadi/luci,Wedmer/luci,david-xiao/luci,teslamint/luci,aircross/OpenWrt-Firefly-LuCI,keyidadi/luci,mumuqz/luci,thess/OpenWrt-luci,obsy/luci,fkooman/luci,openwrt-es/openwrt-luci,daofeng2015/luci,teslamint/luci,rogerpueyo/luci,lcf258/openwrtcn,cappiewu/luci,lcf258/openwrtcn,ReclaimYourPrivacy/cloak-luci,palmettos/test,ReclaimYourPrivacy/cloak-luci,Sakura-Winkey/LuCI,oneru/luci,RuiChen1113/luci,dwmw2/luci,fkooman/luci,artynet/luci,oneru/luci,ollie27/openwrt_luci,chris5560/openwrt-luci,maxrio/luci981213,cshore/luci,bright-things/ionic-luci,dwmw2/luci,Noltari/luci,lcf258/openwrtcn,teslamint/luci,openwrt/luci,LazyZhu/openwrt-luci-trunk-mod,oneru/luci,dwmw2/luci,jchuang1977/luci-1,oyido/luci,jlopenwrtluci/luci,hnyman/luci,zhaoxx063/luci,wongsyrone/luci-1,daofeng2015/luci,RedSnake64/openwrt-luci-packages,LazyZhu/openwrt-luci-trunk-mod,thesabbir/luci,artynet/luci,NeoRaider/luci,tcatm/luci,cshore-firmware/openwrt-luci,dismantl/luci-0.12,kuoruan/luci,joaofvieira/luci,lcf258/openwrtcn,nmav/luci,thess/OpenWrt-luci,openwrt/luci,lbthomsen/openwrt-luci,ff94315/luci-1,tobiaswaldvogel/luci,opentechinstitute/luci,openwrt/luci,urueedi/luci,NeoRaider/luci,daofeng2015/luci,ff94315/luci-1,remakeelectric/luci,palmettos/cnLuCI,urueedi/luci,chris5560/openwrt-luci,thesabbir/luci,obsy/luci,taiha/luci,aa65535/luci,openwrt-es/openwrt-luci,thesabbir/luci,Kyklas/luci-proto-hso,forward619/luci,cappiewu/luci,marcel-sch/luci,opentechinstitute/luci,tcatm/luci,nmav/luci,openwrt-es/openwrt-luci,Hostle/openwrt-luci-multi-user,nmav/luci,palmettos/test,schidler/ionic-luci,cappiewu/luci,slayerrensky/luci,lbthomsen/openwrt-luci,jchuang1977/luci-1,LuttyYang/luci,obsy/luci,oyido/luci,joaofvieira/luci,hnyman/luci,florian-shellfire/luci,tcatm/luci,RedSnake64/openwrt-luci-packages,openwrt/luci,kuoruan/luci,jorgifumi/luci,keyidadi/luci,daofeng2015/luci,981213/luci-1,teslamint/luci,MinFu/luci,palmettos/test,wongsyrone/luci-1,wongsyrone/luci-1,keyidadi/luci,Noltari/luci,NeoRaider/luci,ReclaimYourPrivacy/cloak-luci,male-puppies/luci,jchuang1977/luci-1,opentechinstitute/luci,Kyklas/luci-proto-hso,maxrio/luci981213,Noltari/luci,david-xiao/luci,lbthomsen/openwrt-luci,jlopenwrtluci/luci,Sakura-Winkey/LuCI,slayerrensky/luci,remakeelectric/luci,kuoruan/luci,cshore-firmware/openwrt-luci,lcf258/openwrtcn,maxrio/luci981213,maxrio/luci981213,LazyZhu/openwrt-luci-trunk-mod,tobiaswaldvogel/luci,nwf/openwrt-luci,opentechinstitute/luci,MinFu/luci,harveyhu2012/luci,palmettos/test,urueedi/luci,RuiChen1113/luci,nwf/openwrt-luci,db260179/openwrt-bpi-r1-luci,Hostle/luci,openwrt/luci,jorgifumi/luci,db260179/openwrt-bpi-r1-luci,cshore/luci,shangjiyu/luci-with-extra,palmettos/cnLuCI,mumuqz/luci,palmettos/cnLuCI,bittorf/luci,harveyhu2012/luci,LuttyYang/luci,rogerpueyo/luci,ollie27/openwrt_luci,maxrio/luci981213,david-xiao/luci,palmettos/cnLuCI,kuoruan/luci,thess/OpenWrt-luci,slayerrensky/luci,openwrt-es/openwrt-luci,schidler/ionic-luci,bittorf/luci,lbthomsen/openwrt-luci,ollie27/openwrt_luci,nwf/openwrt-luci,florian-shellfire/luci,joaofvieira/luci,oneru/luci,bright-things/ionic-luci,kuoruan/lede-luci,florian-shellfire/luci,LuttyYang/luci,Sakura-Winkey/LuCI,slayerrensky/luci,david-xiao/luci,male-puppies/luci,bittorf/luci,db260179/openwrt-bpi-r1-luci,openwrt/luci,kuoruan/lede-luci,cshore-firmware/openwrt-luci,mumuqz/luci,obsy/luci,tobiaswaldvogel/luci,jorgifumi/luci,tcatm/luci,sujeet14108/luci,Noltari/luci,cshore/luci,LazyZhu/openwrt-luci-trunk-mod,openwrt-es/openwrt-luci,kuoruan/luci,oyido/luci,chris5560/openwrt-luci,kuoruan/lede-luci,db260179/openwrt-bpi-r1-luci,nmav/luci,artynet/luci,obsy/luci,jchuang1977/luci-1,MinFu/luci,jlopenwrtluci/luci,NeoRaider/luci,tobiaswaldvogel/luci,bittorf/luci,Noltari/luci,fkooman/luci,marcel-sch/luci,florian-shellfire/luci,Kyklas/luci-proto-hso,ff94315/luci-1,Kyklas/luci-proto-hso,daofeng2015/luci,Kyklas/luci-proto-hso,db260179/openwrt-bpi-r1-luci,LazyZhu/openwrt-luci-trunk-mod,taiha/luci,thesabbir/luci,jchuang1977/luci-1,chris5560/openwrt-luci,lbthomsen/openwrt-luci,joaofvieira/luci,hnyman/luci,lcf258/openwrtcn,urueedi/luci,ReclaimYourPrivacy/cloak-luci,deepak78/new-luci,LuttyYang/luci,jlopenwrtluci/luci,db260179/openwrt-bpi-r1-luci,Hostle/luci,LazyZhu/openwrt-luci-trunk-mod,cshore/luci,tobiaswaldvogel/luci,kuoruan/lede-luci,florian-shellfire/luci,palmettos/test,Sakura-Winkey/LuCI,cshore-firmware/openwrt-luci,shangjiyu/luci-with-extra,male-puppies/luci,mumuqz/luci,thesabbir/luci,harveyhu2012/luci,fkooman/luci,tcatm/luci,mumuqz/luci,aa65535/luci,urueedi/luci,openwrt/luci,joaofvieira/luci,NeoRaider/luci,LuttyYang/luci,marcel-sch/luci,kuoruan/lede-luci,981213/luci-1,joaofvieira/luci,thess/OpenWrt-luci,marcel-sch/luci,MinFu/luci,deepak78/new-luci,oneru/luci,marcel-sch/luci,Wedmer/luci,sujeet14108/luci,shangjiyu/luci-with-extra,male-puppies/luci,rogerpueyo/luci,slayerrensky/luci,NeoRaider/luci,Wedmer/luci,ff94315/luci-1,aircross/OpenWrt-Firefly-LuCI,obsy/luci,rogerpueyo/luci,fkooman/luci,kuoruan/lede-luci,slayerrensky/luci,ollie27/openwrt_luci,ReclaimYourPrivacy/cloak-luci,chris5560/openwrt-luci,lcf258/openwrtcn,artynet/luci,cshore/luci,openwrt-es/openwrt-luci,dwmw2/luci,ff94315/luci-1,nmav/luci,aircross/OpenWrt-Firefly-LuCI,forward619/luci,MinFu/luci,chris5560/openwrt-luci,zhaoxx063/luci,Noltari/luci,palmettos/cnLuCI,dwmw2/luci,aircross/OpenWrt-Firefly-LuCI,slayerrensky/luci,mumuqz/luci,teslamint/luci,chris5560/openwrt-luci,ollie27/openwrt_luci,deepak78/new-luci,kuoruan/luci,david-xiao/luci,dismantl/luci-0.12,Hostle/openwrt-luci-multi-user,teslamint/luci,jlopenwrtluci/luci,zhaoxx063/luci,Sakura-Winkey/LuCI,ollie27/openwrt_luci,dismantl/luci-0.12,openwrt-es/openwrt-luci,thesabbir/luci,Hostle/luci,zhaoxx063/luci,remakeelectric/luci,lbthomsen/openwrt-luci,Kyklas/luci-proto-hso,forward619/luci,wongsyrone/luci-1,Noltari/luci,artynet/luci,cappiewu/luci,forward619/luci,Wedmer/luci,slayerrensky/luci,Hostle/openwrt-luci-multi-user,cappiewu/luci,zhaoxx063/luci,LuttyYang/luci,rogerpueyo/luci,Sakura-Winkey/LuCI,jlopenwrtluci/luci,bright-things/ionic-luci,schidler/ionic-luci,shangjiyu/luci-with-extra,urueedi/luci,jlopenwrtluci/luci,Noltari/luci,urueedi/luci,maxrio/luci981213,harveyhu2012/luci,bright-things/ionic-luci,daofeng2015/luci,RedSnake64/openwrt-luci-packages,schidler/ionic-luci,ollie27/openwrt_luci,wongsyrone/luci-1,tobiaswaldvogel/luci,RuiChen1113/luci,aa65535/luci,ff94315/luci-1,RedSnake64/openwrt-luci-packages,forward619/luci,opentechinstitute/luci,dwmw2/luci,male-puppies/luci,wongsyrone/luci-1,Wedmer/luci,LuttyYang/luci,cshore/luci,aircross/OpenWrt-Firefly-LuCI,sujeet14108/luci,remakeelectric/luci,tcatm/luci,kuoruan/luci,Sakura-Winkey/LuCI,taiha/luci,981213/luci-1,Hostle/luci,RedSnake64/openwrt-luci-packages,sujeet14108/luci,bright-things/ionic-luci,lcf258/openwrtcn,bright-things/ionic-luci,ReclaimYourPrivacy/cloak-luci,dismantl/luci-0.12,ff94315/luci-1,rogerpueyo/luci,981213/luci-1,obsy/luci,tcatm/luci,Hostle/openwrt-luci-multi-user,Wedmer/luci,thesabbir/luci,tcatm/luci,cshore-firmware/openwrt-luci,dismantl/luci-0.12,opentechinstitute/luci,male-puppies/luci,nmav/luci,ff94315/luci-1,LuttyYang/luci,sujeet14108/luci,oneru/luci,schidler/ionic-luci,cappiewu/luci,teslamint/luci,MinFu/luci,deepak78/new-luci,oneru/luci,hnyman/luci,harveyhu2012/luci,thess/OpenWrt-luci,chris5560/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,florian-shellfire/luci,981213/luci-1,981213/luci-1,joaofvieira/luci,daofeng2015/luci,Hostle/openwrt-luci-multi-user,tobiaswaldvogel/luci,artynet/luci,florian-shellfire/luci,Hostle/openwrt-luci-multi-user,dismantl/luci-0.12,nmav/luci,thesabbir/luci,cshore/luci,RuiChen1113/luci,maxrio/luci981213,remakeelectric/luci,jorgifumi/luci,nwf/openwrt-luci,palmettos/test,wongsyrone/luci-1,david-xiao/luci,deepak78/new-luci,urueedi/luci,deepak78/new-luci,hnyman/luci,aa65535/luci,deepak78/new-luci,nwf/openwrt-luci,nwf/openwrt-luci,artynet/luci,RuiChen1113/luci,teslamint/luci,remakeelectric/luci,jchuang1977/luci-1,nmav/luci,deepak78/new-luci,bittorf/luci,bittorf/luci,cappiewu/luci,NeoRaider/luci,joaofvieira/luci,sujeet14108/luci,Noltari/luci,Hostle/luci,remakeelectric/luci,Wedmer/luci,hnyman/luci,oyido/luci,remakeelectric/luci,cappiewu/luci,dismantl/luci-0.12,bright-things/ionic-luci,MinFu/luci,fkooman/luci,harveyhu2012/luci,forward619/luci,shangjiyu/luci-with-extra,male-puppies/luci,MinFu/luci,tobiaswaldvogel/luci,dwmw2/luci,schidler/ionic-luci,david-xiao/luci,Hostle/openwrt-luci-multi-user,lcf258/openwrtcn,aa65535/luci,shangjiyu/luci-with-extra,marcel-sch/luci,ollie27/openwrt_luci,Hostle/luci,981213/luci-1,jlopenwrtluci/luci,nwf/openwrt-luci,marcel-sch/luci,LazyZhu/openwrt-luci-trunk-mod,artynet/luci,wongsyrone/luci-1,thess/OpenWrt-luci,kuoruan/luci,taiha/luci,jorgifumi/luci,taiha/luci,Kyklas/luci-proto-hso,hnyman/luci,nmav/luci,david-xiao/luci,zhaoxx063/luci,palmettos/cnLuCI,openwrt-es/openwrt-luci,mumuqz/luci,db260179/openwrt-bpi-r1-luci,artynet/luci,schidler/ionic-luci,ReclaimYourPrivacy/cloak-luci,daofeng2015/luci,cshore/luci,cshore-firmware/openwrt-luci,cshore-firmware/openwrt-luci,palmettos/cnLuCI,thess/OpenWrt-luci,lbthomsen/openwrt-luci,rogerpueyo/luci,oyido/luci,oneru/luci,lbthomsen/openwrt-luci,aa65535/luci,keyidadi/luci,ReclaimYourPrivacy/cloak-luci,hnyman/luci,openwrt/luci,sujeet14108/luci,palmettos/test,florian-shellfire/luci,taiha/luci,oyido/luci,Hostle/luci,fkooman/luci
3a494b4642ac3fbdb9fbac42346d36f7bc3ba801
mods/soundset/init.lua
mods/soundset/init.lua
minetest.log("action","[mod soundset] Loading...") soundset = {} soundset.file = minetest.get_worldpath() .. "/sounds_config.txt" soundset.gainplayers = {} soundset.tmp = {} local function save_sounds_config() local input = io.open(soundset.file, "w") if input then input:write(minetest.serialize(soundset.gainplayers)) input:close() else minetest.log("action","echec d'ouverture (mode:w) de " .. soundset.file) end end local function load_sounds_config() local file = io.open(soundset.file, "r") if file then soundset.gainplayers = minetest.deserialize(file:read("*all")) file:close() end if soundset.gainplayers == nil or type(soundset.gainplayers) ~= "table" then soundset.gainplayers = {} end end load_sounds_config() soundset.set_sound = function(name, param) if param == "" then minetest.chat_send_player(name, "/setsound <music|ambience|mobs|other> <number>") return end local param_name, param_value = param:match("^(%S+)%s(%S+)$") if param_name == nil or param_value == nil then minetest.chat_send_player(name, "invalid param, /setsound <music|ambience|mobs|other> <number>") return end if param_name ~= "music" and param_name ~= "ambience" and param_name ~= "mobs" and param_name ~= "other" then minetest.chat_send_player(name, "invalid param " .. param_name) return end local value = tonumber(param_value) if value == nil then minetest.chat_send_player(name, "invalid value, " ..param_value .. " must be number") return end if value < 0 then value = 0 elseif value > 100 then value = 100 end if soundset.gainplayers[name][param_name] == value then minetest.chat_send_player(name, "volume " .. param_name .. " already set to " .. value) return end soundset.gainplayers[name][param_name] = value minetest.chat_send_player(name, "sound " .. param_name .. " set to " .. value) save_sounds_config() end soundset.get_gain = function(name, sound_type) if name == nil or name == "" then return 1 end if not soundset.gainplayers[name] then return 1 end local gain = soundset.gainplayers[name][sound_type] if gain == nil then return 1 end return gain/100 end local inc = function(value) value = value + 5 if value > 100 then value = 100 end return value end local dec = function(value) value = value - 5 if value < 0 then value = 0 end return value end local formspec = "size[6,6]".. "label[2,0;Sound Menu]".. "label[0,1.2;MUSIC]".. "image_button[1.6,1;1,1;soundset_dec.png;vmusic;-]".. "label[2.7,1.2;%s]".. "image_button[3.5,1;1,1;soundset_inc.png;vmusic;+]".. "label[0,2.2;AMBIENCE]".. "image_button[1.6,2;1,1;soundset_dec.png;vambience;-]".. "label[2.7,2.2;%s]".. "image_button[3.5,2;1,1;soundset_inc.png;vambience;+]".. "label[0,3.2;OTHER]".. "image_button[1.6,3;1,1;soundset_dec.png;vother;-]".. "label[2.7,3.2;%s]".. "image_button[3.5,3;1,1;soundset_inc.png;vother;+]".. "button_exit[0.5,5.2;1.5,1;abort;Abort]".. "button_exit[4,5.2;1.5,1;abort;Ok]" local on_show_settings = function(name, music, ambience, other) if not soundset.tmp[name] then soundset.tmp[name] = {} end soundset.tmp[name]["music"] = music soundset.tmp[name]["ambience"] = ambience soundset.tmp[name]["other"] = other minetest.show_formspec( name, "soundset:settings", string.format(formspec, tostring(music), tostring(ambience), tostring(other) )) end minetest.register_on_player_receive_fields(function(player, formname, fields) if formname == "soundset:settings" then local name = player:get_player_name() if not name or name == "" then return end local fmusic = soundset.tmp[name]["music"] or 50 local fambience = soundset.tmp[name]["ambience"] or 50 local fother = soundset.tmp[name]["other"] or 50 if fields["abort"] == "Ok" then if soundset.gainplayers[name]["music"] ~= fmusic or soundset.gainplayers[name]["ambience"] ~= fambience or soundset.gainplayers[name]["other"] ~= fother then soundset.gainplayers[name]["music"] = fmusic soundset.gainplayers[name]["ambience"] = fambience soundset.gainplayers[name]["other"] = fother save_sounds_config() end soundset.tmp[name] = nil return elseif fields["abort"] == "Abort" then soundset.tmp[name] = nil return elseif fields["vmusic"] == "+" then fmusic = inc(fmusic) elseif fields["vmusic"] == "-" then fmusic = dec(fmusic) elseif fields["vambience"] == "+" then fambience = inc(fambience) elseif fields["vambience"] == "-" then fambience = dec(fambience) elseif fields["vother"] == "+" then fother = inc(fother) elseif fields["vother"] == "-" then fother = dec(fother) elseif fields["quit"] == "true" then soundset.tmp[name] = nil return else return end on_show_settings(name, fmusic, fambience, fother) end end) if (minetest.get_modpath("unified_inventory")) then unified_inventory.register_button("menu_soundset", { type = "image", image = "soundset_menu_icon.png", tooltip = "sounds menu ", show_with = false, --Modif MFF (Crabman 30/06/2015) action = function(player) local name = player:get_player_name() if not name then return end on_show_settings(name, soundset.gainplayers[name]["music"], soundset.gainplayers[name]["ambience"], soundset.gainplayers[name]["other"]) end, }) end minetest.register_chatcommand("soundset", { params = "", description = "Display volume menu formspec", privs = {interact=true}, func = function(name, param) if not name then return end on_show_settings(name, soundset.gainplayers[name]["music"], soundset.gainplayers[name]["ambience"], soundset.gainplayers[name]["other"]) end }) minetest.register_chatcommand("soundsets", { params = "<music|ambience|mobs|other> <number>", description = "Set volume sound <music|ambience|mobs|other>", privs = {interact=true}, func = soundset.set_sound, }) minetest.register_chatcommand("soundsetg", { params = "", description = "Display volume sound <music|ambience|mobs|other>", privs = {interact=true}, func = function(name, param) local conf = "" for k, v in pairs(soundset.gainplayers[name]) do conf = conf .. " " .. k .. ":" .. v end minetest.chat_send_player(name, "sounds conf " .. conf) minetest.log("action","Player ".. name .. " sound conf " .. conf) end }) minetest.register_on_joinplayer(function(player) local name = player:get_player_name() if soundset.gainplayers[name] == nil then soundset.gainplayers[name] = { ["music"] = 50, ["ambience"] = 50, ["mobs"] = 50, ["other"] = 50 } end end) minetest.log("action","[mod soundset] Loaded")
minetest.log("action","[mod soundset] Loading...") soundset = {} soundset.file = minetest.get_worldpath() .. "/sounds_config.txt" soundset.gainplayers = {} local tmp = {} tmp["music"] = {} tmp["ambience"] = {} tmp["other"] = {} local function save_sounds_config() local input = io.open(soundset.file, "w") if input then input:write(minetest.serialize(soundset.gainplayers)) input:close() else minetest.log("action","echec d'ouverture (mode:w) de " .. soundset.file) end end local function load_sounds_config() local file = io.open(soundset.file, "r") if file then soundset.gainplayers = minetest.deserialize(file:read("*all")) file:close() end if soundset.gainplayers == nil or type(soundset.gainplayers) ~= "table" then soundset.gainplayers = {} end end load_sounds_config() soundset.set_sound = function(name, param) if param == "" then minetest.chat_send_player(name, "/setsound <music|ambience|mobs|other> <number>") return end local param_name, param_value = param:match("^(%S+)%s(%S+)$") if param_name == nil or param_value == nil then minetest.chat_send_player(name, "invalid param, /setsound <music|ambience|mobs|other> <number>") return end if param_name ~= "music" and param_name ~= "ambience" and param_name ~= "mobs" and param_name ~= "other" then minetest.chat_send_player(name, "invalid param " .. param_name) return end local value = tonumber(param_value) if value == nil then minetest.chat_send_player(name, "invalid value, " ..param_value .. " must be number") return end if value < 0 then value = 0 elseif value > 100 then value = 100 end if soundset.gainplayers[name][param_name] == value then minetest.chat_send_player(name, "volume " .. param_name .. " already set to " .. value) return end soundset.gainplayers[name][param_name] = value minetest.chat_send_player(name, "sound " .. param_name .. " set to " .. value) save_sounds_config() end soundset.get_gain = function(name, sound_type) if name == nil or name == "" then return 1 end if not soundset.gainplayers[name] then return 1 end local gain = soundset.gainplayers[name][sound_type] if gain == nil then return 1 end return gain/100 end local inc = function(value) value = value + 5 if value > 100 then value = 100 end return value end local dec = function(value) value = value - 5 if value < 0 then value = 0 end return value end local formspec = "size[6,6]".. "label[2,0;Sound Menu]".. "label[0,1.2;MUSIC]".. "image_button[1.6,1;1,1;soundset_dec.png;vmusic;-]".. "label[2.7,1.2;%s]".. "image_button[3.5,1;1,1;soundset_inc.png;vmusic;+]".. "label[0,2.2;AMBIENCE]".. "image_button[1.6,2;1,1;soundset_dec.png;vambience;-]".. "label[2.7,2.2;%s]".. "image_button[3.5,2;1,1;soundset_inc.png;vambience;+]".. "label[0,3.2;OTHER]".. "image_button[1.6,3;1,1;soundset_dec.png;vother;-]".. "label[2.7,3.2;%s]".. "image_button[3.5,3;1,1;soundset_inc.png;vother;+]".. "button_exit[0.5,5.2;1.5,1;abort;Abort]".. "button_exit[4,5.2;1.5,1;abort;Ok]" local on_show_settings = function(name, music, ambience, other) tmp["music"][name] = music tmp["ambience"][name] = ambience tmp["other"][name] = other minetest.show_formspec( name, "soundset:settings", string.format(formspec, tostring(music), tostring(ambience), tostring(other) )) end local clear_tmp = function(name) tmp["music"][name] = nil tmp["ambience"][name] = nil tmp["other"][name] = nil end minetest.register_on_player_receive_fields(function(player, formname, fields) if formname == "soundset:settings" then local name = player:get_player_name() if not name or name == "" then return end local fmusic = tmp["music"][name] or 50 local fambience = tmp["ambience"][name] or 50 local fother = tmp["other"][name] or 50 if fields["abort"] == "Ok" then if soundset.gainplayers[name]["music"] ~= fmusic or soundset.gainplayers[name]["ambience"] ~= fambience or soundset.gainplayers[name]["other"] ~= fother then soundset.gainplayers[name]["music"] = fmusic soundset.gainplayers[name]["ambience"] = fambience soundset.gainplayers[name]["other"] = fother save_sounds_config() end clear_tmp(name) return elseif fields["abort"] == "Abort" then clear_tmp(name) return elseif fields["vmusic"] == "+" then fmusic = inc(fmusic) elseif fields["vmusic"] == "-" then fmusic = dec(fmusic) elseif fields["vambience"] == "+" then fambience = inc(fambience) elseif fields["vambience"] == "-" then fambience = dec(fambience) elseif fields["vother"] == "+" then fother = inc(fother) elseif fields["vother"] == "-" then fother = dec(fother) elseif fields["quit"] == "true" then clear_tmp(name) return else return end on_show_settings(name, fmusic, fambience, fother) end end) if (minetest.get_modpath("unified_inventory")) then unified_inventory.register_button("menu_soundset", { type = "image", image = "soundset_menu_icon.png", tooltip = "sounds menu ", show_with = false, --Modif MFF (Crabman 30/06/2015) action = function(player) local name = player:get_player_name() if not name then return end on_show_settings(name, soundset.gainplayers[name]["music"], soundset.gainplayers[name]["ambience"], soundset.gainplayers[name]["other"]) end, }) end minetest.register_chatcommand("soundset", { params = "", description = "Display volume menu formspec", privs = {interact=true}, func = function(name, param) if not name then return end on_show_settings(name, soundset.gainplayers[name]["music"], soundset.gainplayers[name]["ambience"], soundset.gainplayers[name]["other"]) end }) minetest.register_chatcommand("soundsets", { params = "<music|ambience|mobs|other> <number>", description = "Set volume sound <music|ambience|mobs|other>", privs = {interact=true}, func = soundset.set_sound, }) minetest.register_chatcommand("soundsetg", { params = "", description = "Display volume sound <music|ambience|mobs|other>", privs = {interact=true}, func = function(name, param) local conf = "" for k, v in pairs(soundset.gainplayers[name]) do conf = conf .. " " .. k .. ":" .. v end minetest.chat_send_player(name, "sounds conf " .. conf) minetest.log("action","Player ".. name .. " sound conf " .. conf) end }) minetest.register_on_joinplayer(function(player) local name = player:get_player_name() if soundset.gainplayers[name] == nil then soundset.gainplayers[name] = { ["music"] = 50, ["ambience"] = 50, ["mobs"] = 50, ["other"] = 50 } end end) minetest.log("action","[mod soundset] Loaded")
fix crash due to lag
fix crash due to lag
Lua
unlicense
MinetestForFun/server-minetestforfun-creative,MinetestForFun/server-minetestforfun-creative,MinetestForFun/server-minetestforfun-creative
311a205d56d3a071b723bb19ed7231934e630094
jvml_data/vm/bindump.lua
jvml_data/vm/bindump.lua
function makeDumpster(platform) local dump = { } local out = "" local function dumpNum(n, bytes, forcedEndianness) if (platform.endianness == 0 or forcedEndianness == 0) and forcedEndianness ~= 1 then for i=bytes-1, 0, -1 do dump.dumpByte(bit.band(bit.brshift(n, i * 8), 0xff)) end elseif platform.endianness == 1 or forcedEndianness == 1 then for i=0, bytes - 1 do dump.dumpByte(bit.band(bit.brshift(n, i * 8), 0xff)) end else error("Unsupported endianness:" .. tostring(platform.endianness)) end end function dump.dumpByte(b) out = out .. string.char(b) end function dump.dumpInteger(n) dumpNum(n, platform.size_int) end function dump.dumpSize_t(n) dumpNum(n, platform.size_t) end function dump.dumpString(s) if s == nil then dump.dumpSize_t(0) else dump.dumpSize_t(#s + 1) for i=1, #s do dump.dumpByte(s:byte(i,i)) end dump.dumpByte(0) end end function dump.dumpNumber(x) --[[ Borrowing this function from LuaLua ============================================================================== Yueliang Copyright (C) 2005-2008 Kein-Hong Man <khman@users.sf.net> Lua 5.0.3 Copyright (C) 2003-2006 Tecgraf, PUC-Rio. Lua 5.1.3 Copyright (C) 1994-2008 Lua.org, PUC-Rio. 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. ]] assert(platform.size_number == 8, "Unsupported number size") local function grab_byte(v) local c = v % 256 return (v - c) / 256, string.char(c) end local sign = 0 if x < 0 then sign = 1; x = -x end local mantissa, exponent = math.frexp(x) if x == 0 then -- zero mantissa, exponent = 0, 0 elseif x == 1/0 then mantissa, exponent = 0, 2047 else mantissa = (mantissa * 2 - 1) * math.ldexp(0.5, 53) exponent = exponent + 1022 end local v, byte = "" -- convert to bytes x = math.floor(mantissa) for i = 1,6 do x, byte = grab_byte(x); v = v..byte -- 47:0 end x, byte = grab_byte(exponent * 16 + x); v = v..byte -- 55:48 x, byte = grab_byte(sign * 128 + x); v = v..byte -- 63:56 if platform.endianness == 1 then return v else return v:reverse() end end function dump.dumpInstruction(inst) dumpNum(inst, platform.size_instruction) end function dump.dumpConstant(const) if type(const) == "nil" then dump.dumpByte(0) elseif type(const) == "boolean" then dump.dumpByte(1) if const then dump.dumpByte(1) else dump.dumpByte(0) end elseif type(const) == "number" then dump.dumpByte(3) dump.dumpNumber(const) elseif type(const) == "string" then dump.dumpByte(4) dump.dumpString(const) else error("Uknown constant type: " .. type(const)) end end function dump.dumpInstructionsList(instns) dump.dumpInteger(#instns) for i,v in ipairs(instns) do dump.dumpInstruction(v) end end function dump.dumpConstantsList(constants, nilIndex) local nilConst = {} local constList = {} for k,v in pairs(constants) do constList[v + 1] = k end if nilIndex then constList[nilIndex] = nilConst end dump.dumpInteger(#constList) for i,v in ipairs(constList) do if v == nilConst then v = nil end dump.dumpConstant(v) end end function dump.dumpSourceLinePositions(sourceLinePositions) dump.dumpInteger(#sourceLinePositions) for i,v in ipairs(sourceLinePositions) do dump.dumpInteger(v) end end function dump.toString() return out end -- Create header local signature = "\27Lua" for i=1,#signature do dump.dumpByte(signature:byte(i,i)) end dump.dumpByte(platform.version) dump.dumpByte(platform.format) dump.dumpByte(platform.endianness) dump.dumpByte(platform.size_int) dump.dumpByte(platform.size_t) dump.dumpByte(platform.size_instruction) dump.dumpByte(platform.size_number) dump.dumpByte(platform.integral) return dump end
function makeDumpster(platform) local dump = { } local out = "" local function dumpNum(n, bytes, forcedEndianness) if (platform.endianness == 0 or forcedEndianness == 0) and forcedEndianness ~= 1 then for i=bytes-1, 0, -1 do dump.dumpByte(bit.band(bit.brshift(n, i * 8), 0xff)) end elseif platform.endianness == 1 or forcedEndianness == 1 then for i=0, bytes - 1 do dump.dumpByte(bit.band(bit.brshift(n, i * 8), 0xff)) end else error("Unsupported endianness:" .. tostring(platform.endianness)) end end function dump.dumpByte(b) out = out .. string.char(b) end function dump.dumpInteger(n) dumpNum(n, platform.size_int) end function dump.dumpSize_t(n) dumpNum(n, platform.size_t) end function dump.dumpString(s) if s == nil then dump.dumpSize_t(0) else dump.dumpSize_t(#s + 1) for i=1, #s do dump.dumpByte(s:byte(i,i)) end dump.dumpByte(0) end end function dump.dumpNumber(x) --[[ Borrowing this function from LuaLua ============================================================================== Yueliang Copyright (C) 2005-2008 Kein-Hong Man <khman@users.sf.net> Lua 5.0.3 Copyright (C) 2003-2006 Tecgraf, PUC-Rio. Lua 5.1.3 Copyright (C) 1994-2008 Lua.org, PUC-Rio. 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. ]] assert(platform.size_number == 8, "Unsupported number size") local function grab_byte(v) local c = v % 256 return (v - c) / 256, string.char(c) end local sign = 0 if x < 0 then sign = 1; x = -x end local mantissa, exponent = math.frexp(x) if x == 0 then -- zero mantissa, exponent = 0, 0 elseif x == 1/0 then mantissa, exponent = 0, 2047 else mantissa = (mantissa * 2 - 1) * math.ldexp(0.5, 53) exponent = exponent + 1022 end local v, byte = "" -- convert to bytes x = math.floor(mantissa) for i = 1,6 do x, byte = grab_byte(x); v = v..byte -- 47:0 end x, byte = grab_byte(exponent * 16 + x); v = v..byte -- 55:48 x, byte = grab_byte(sign * 128 + x); v = v..byte -- 63:56 if platform.endianness == 0 then v = v:reverse() end for i=1,#v do dump.dumpByte(v:byte(i,i)) end end function dump.dumpInstruction(inst) dumpNum(inst, platform.size_instruction) end function dump.dumpConstant(const) if type(const) == "nil" then dump.dumpByte(0) elseif type(const) == "boolean" then dump.dumpByte(1) if const then dump.dumpByte(1) else dump.dumpByte(0) end elseif type(const) == "number" then dump.dumpByte(3) dump.dumpNumber(const) elseif type(const) == "string" then dump.dumpByte(4) dump.dumpString(const) else error("Uknown constant type: " .. type(const)) end end function dump.dumpInstructionsList(instns) dump.dumpInteger(#instns) for i,v in ipairs(instns) do dump.dumpInstruction(v) end end function dump.dumpConstantsList(constants, nilIndex) local nilConst = {} local constList = {} for k,v in pairs(constants) do constList[v + 1] = k end if nilIndex then constList[nilIndex] = nilConst end dump.dumpInteger(#constList) for i,v in ipairs(constList) do if v == nilConst then v = nil end dump.dumpConstant(v) end end function dump.dumpSourceLinePositions(sourceLinePositions) dump.dumpInteger(#sourceLinePositions) for i,v in ipairs(sourceLinePositions) do dump.dumpInteger(v) end end function dump.toString() return out end -- Create header local signature = "\27Lua" for i=1,#signature do dump.dumpByte(signature:byte(i,i)) end dump.dumpByte(platform.version) dump.dumpByte(platform.format) dump.dumpByte(platform.endianness) dump.dumpByte(platform.size_int) dump.dumpByte(platform.size_t) dump.dumpByte(platform.size_instruction) dump.dumpByte(platform.size_number) dump.dumpByte(platform.integral) return dump end
Fixed dumpNumber
Fixed dumpNumber
Lua
mit
Team-CC-Corp/JVML-JIT,apemanzilla/JVML-JIT
bdb5814a666985fea6073a1c8c6cca85c826e72a
model.lua
model.lua
local _ = require 'moses' local nn = require 'nn' local image = require 'image' require 'modules/GradientRescale' local DuelAggregator = require 'modules/DuelAggregator' local model = {} -- Returns optimal module based on type local bestModule = function(mod, ...) if mod == 'relu' then if model.hasCudnn then return cudnn.ReLU(...) else return nn.ReLU(...) end elseif mod == 'conv' then if model.hasCudnn then return cudnn.SpatialConvolution(...) else return nn.SpatialConvolution(...) end end end -- Calculates the output size of a network (returns LongStorage) local calcOutputSize = function(network, inputSizes) if cudnn then return network:cuda():forward(torch.CudaTensor(torch.LongStorage(inputSizes))):size() else return network:forward(torch.Tensor(torch.LongStorage(inputSizes))):size() end end -- Processes a single frame for DQN input model.preprocess = function(observation) -- Load frame model.buffers.frame = observation:float() -- Convert from CudaTensor if necessary -- Perform colour conversion if model.colorSpace ~= 'rgb' then model.buffers.convertedFrame = image['rgb2' .. model.colorSpace](model.buffers.frame) end -- Resize 210x160 screen return image.scale(model.buffers.convertedFrame, model.width, model.height) end -- Creates a dueling DQN based on a number of discrete actions model.create = function(m) -- Network starting with convolutional layers local net = nn.Sequential() net:add(nn.View(model.histLen*model.nChannels, model.height, model.width)) -- Concatenate history in channel dimension net:add(bestModule('conv', model.histLen*model.nChannels, 32, 8, 8, 4, 4)) net:add(bestModule('relu', true)) net:add(bestModule('conv', 32, 64, 4, 4, 2, 2)) net:add(bestModule('relu', true)) net:add(bestModule('conv', 64, 64, 3, 3, 1, 1)) net:add(bestModule('relu', true)) -- Calculate convolutional network output size local convOutputSize = torch.prod(torch.Tensor(calcOutputSize(net, {model.histLen*model.nChannels, model.height, model.width}):totable())) -- Value approximator V^(s) local valStream = nn.Sequential() valStream:add(nn.Linear(convOutputSize, 512)) valStream:add(bestModule('relu', true)) valStream:add(nn.Linear(512, 1)) -- Predicts value for state -- Advantage approximator A^(s, a) local advStream = nn.Sequential() advStream:add(nn.Linear(convOutputSize, 512)) advStream:add(bestModule('relu', true)) advStream:add(nn.Linear(512, m)) -- Predicts action-conditional advantage -- Streams container local streams = nn.ConcatTable() streams:add(valStream) streams:add(advStream) -- Network finishing with fully connected layers net:add(nn.View(convOutputSize)) net:add(nn.GradientRescale(1 / math.sqrt(2), true)) -- Heuristic that mildly increases stability for duel -- Create dueling streams net:add(streams) -- Add dueling streams aggregator module net:add(DuelAggregator(m)) if model.gpu > 0 then require 'cunn' net:cuda() end return net end -- Initialises model model.init = function(opt) -- Extract relevant options model.gpu = opt.gpu model.colorSpace = opt.colorSpace model.width = opt.width model.height = opt.height model.nChannels = opt.nChannels model.histLen = opt.histLen -- Create buffers model.buffers = { frame = torch.FloatTensor(3, 210, 160), convertedFrame = torch.FloatTensor(model.nChannels, 210, 160) } -- Get cuDNN if available model.hasCudnn = pcall(require, 'cudnn') end return model
local _ = require 'moses' local nn = require 'nn' local image = require 'image' require 'modules/GradientRescale' local DuelAggregator = require 'modules/DuelAggregator' local model = {} -- Returns optimal module based on type local bestModule = function(mod, ...) if mod == 'relu' then if model.gpu > 0 and model.hasCudnn then return cudnn.ReLU(...) else return nn.ReLU(...) end elseif mod == 'conv' then if model.gpu > 0 and model.hasCudnn then return cudnn.SpatialConvolution(...) else return nn.SpatialConvolution(...) end end end -- Calculates the output size of a network (returns LongStorage) local calcOutputSize = function(network, inputSizes) if model.gpu > 0 and cudnn then return network:cuda():forward(torch.CudaTensor(torch.LongStorage(inputSizes))):size() else return network:forward(torch.Tensor(torch.LongStorage(inputSizes))):size() end end -- Processes a single frame for DQN input model.preprocess = function(observation) -- Load frame model.buffers.frame = observation:float() -- Convert from CudaTensor if necessary -- Perform colour conversion if model.colorSpace ~= 'rgb' then model.buffers.convertedFrame = image['rgb2' .. model.colorSpace](model.buffers.frame) end -- Resize 210x160 screen return image.scale(model.buffers.convertedFrame, model.width, model.height) end -- Creates a dueling DQN based on a number of discrete actions model.create = function(m) -- Network starting with convolutional layers local net = nn.Sequential() net:add(nn.View(model.histLen*model.nChannels, model.height, model.width)) -- Concatenate history in channel dimension net:add(bestModule('conv', model.histLen*model.nChannels, 32, 8, 8, 4, 4)) net:add(bestModule('relu', true)) net:add(bestModule('conv', 32, 64, 4, 4, 2, 2)) net:add(bestModule('relu', true)) net:add(bestModule('conv', 64, 64, 3, 3, 1, 1)) net:add(bestModule('relu', true)) -- Calculate convolutional network output size local convOutputSize = torch.prod(torch.Tensor(calcOutputSize(net, {model.histLen*model.nChannels, model.height, model.width}):totable())) -- Value approximator V^(s) local valStream = nn.Sequential() valStream:add(nn.Linear(convOutputSize, 512)) valStream:add(bestModule('relu', true)) valStream:add(nn.Linear(512, 1)) -- Predicts value for state -- Advantage approximator A^(s, a) local advStream = nn.Sequential() advStream:add(nn.Linear(convOutputSize, 512)) advStream:add(bestModule('relu', true)) advStream:add(nn.Linear(512, m)) -- Predicts action-conditional advantage -- Streams container local streams = nn.ConcatTable() streams:add(valStream) streams:add(advStream) -- Network finishing with fully connected layers net:add(nn.View(convOutputSize)) net:add(nn.GradientRescale(1 / math.sqrt(2), true)) -- Heuristic that mildly increases stability for duel -- Create dueling streams net:add(streams) -- Add dueling streams aggregator module net:add(DuelAggregator(m)) if model.gpu > 0 then require 'cunn' net:cuda() end return net end -- Initialises model model.init = function(opt) -- Extract relevant options model.gpu = opt.gpu model.colorSpace = opt.colorSpace model.width = opt.width model.height = opt.height model.nChannels = opt.nChannels model.histLen = opt.histLen -- Create buffers model.buffers = { frame = torch.FloatTensor(3, 210, 160), convertedFrame = torch.FloatTensor(model.nChannels, 210, 160) } -- Get cuDNN if available model.hasCudnn = pcall(require, 'cudnn') end return model
CPU-mode fix when cuDNN is installed
CPU-mode fix when cuDNN is installed
Lua
mit
Kaixhin/Atari
70ecf15aacfb57ea3670135c3a1751e701286bc9
conf/utils.lua
conf/utils.lua
local _M = {} local cmsgpack = require "cmsgpack" local inspect = require "inspect" local iputils = require "resty.iputils" local plutils = require "pl.utils" local stringx = require "pl.stringx" local types = require "pl.types" local escape = plutils.escape local is_empty = types.is_empty local pack = cmsgpack.pack local parse_cidrs = iputils.parse_cidrs local split = plutils.split local strip = stringx.strip local unpack = cmsgpack.unpack -- Determine if the table is an array. -- -- In benchmarks, appears faster than moses.isArray implementation. function _M.is_array(obj) if type(obj) ~= "table" then return false end local count = 1 for key, _ in pairs(obj) do if key ~= count then return false end count = count + 1 end return true end -- Append an array to the end of the destination array. -- -- In benchmarks, appears faster than moses.append and pl.tablex.move -- implementations. function _M.append_array(dest, src) if type(dest) ~= "table" or type(src) ~= "table" then return end dest_length = #dest src_length = #src for i=1, src_length do dest[dest_length + i] = src[i] end return dest end function _M.base_url() local protocol = ngx.ctx.protocol local host = ngx.ctx.host local port = ngx.ctx.port local base = protocol .. "://" .. host if (protocol == "http" and port ~= "80") or (protocol == "https" and port ~= "443") then if not host:find(":" .. port .. "$") then base = base .. ":" .. port end end return base end function _M.get_packed(dict, key) local packed = dict:get(key) if packed then return unpack(packed) end end function _M.set_packed(dict, key, value) return dict:set(key, pack(value)) end function _M.deep_merge_overwrite_arrays(dest, src) if not src then return dest end for key, value in pairs(src) do if type(value) == "table" and type(dest[key]) == "table" then if _M.is_array(value) then dest[key] = value else _M.deep_merge_overwrite_arrays(dest[key], src[key]) end else dest[key] = value end end return dest end function _M.cache_computed_settings(settings) if not settings then return end -- Parse and cache the allowed IPs as CIDR ranges. if not is_empty(settings["allowed_ips"]) then settings["_allowed_cidrs"] = parse_cidrs(settings["allowed_ips"]) settings["allowed_ips"] = nil end -- Parse and cache the allowed referers as matchers if not is_empty(settings["allowed_referers"]) then settings["_allowed_referer_matchers"] = {} for _, referer in ipairs(settings["allowed_referers"]) do local matcher = escape(referer) matcher = string.gsub(matcher, "%%%*", ".*") table.insert(settings["_allowed_referer_matchers"], matcher) end settings["allowed_referers"] = nil end if settings["append_query_string"] then settings["_append_query_args"] = ngx.decode_args(settings["append_query_string"]) settings["append_query_string"] = nil end if settings["http_basic_auth"] then settings["_http_basic_auth_header"] = "Basic " .. ngx.encode_base64(settings["http_basic_auth"]) settings["http_basic_auth"] = nil end end function _M.parse_accept(header, supported_media_types) if not header then return nil end local accepts = {} local accept_header = split(header, ",") for _, accept_string in ipairs(accept_header) do local parts = split(accept_string, ";", 2) local media = parts[1] local params = parts[2] if params then params = split(params, ";") end local media_parts = split(media, "/") local media_type = strip(media_parts[1] or "") local media_subtype = strip(media_parts[2] or "") local q = 1 for _, param in ipairs(params) do local param_parts = split(param, "=") local param_key = strip(param_parts[1] or "") local param_value = strip(param_parts[2] or "") if param_key == "q" then q = tonumber(param_value) end end if q == 0 then break end local accept = { media_type = media_type, media_subtype = media_subtype, q = q, } table.insert(accepts, accept) end table.sort(accepts, function(a, b) if a.q < b.q then return false elseif a.q > b.q then return true elseif (a.media_type == "*" and b.media_type ~= "*") or (a.media_subtype == "*" and b.media_subtype ~= "*") then return false elseif (a.media_type ~= "*" and b.media_type == "*") or (a.media_subtype ~= "*" and b.media_subtype == "*") then return true else return true end end) for _, supported in ipairs(supported_media_types) do for _, accept in ipairs(accepts) do if accept.media_type == supported.media_type and accept.media_subtype == supported.media_subtype then return supported.format elseif accept.media_type == supported.media_type and accept.media_subtype == "*" then return supported.format elseif accept.media_type == "*" and accept.media_subtype == "*" then return supported.format else return nil end end end end return _M
local _M = {} local cmsgpack = require "cmsgpack" local inspect = require "inspect" local iputils = require "resty.iputils" local plutils = require "pl.utils" local stringx = require "pl.stringx" local types = require "pl.types" local escape = plutils.escape local is_empty = types.is_empty local pack = cmsgpack.pack local parse_cidrs = iputils.parse_cidrs local split = plutils.split local strip = stringx.strip local unpack = cmsgpack.unpack -- Determine if the table is an array. -- -- In benchmarks, appears faster than moses.isArray implementation. function _M.is_array(obj) if type(obj) ~= "table" then return false end local count = 1 for key, _ in pairs(obj) do if key ~= count then return false end count = count + 1 end return true end -- Append an array to the end of the destination array. -- -- In benchmarks, appears faster than moses.append and pl.tablex.move -- implementations. function _M.append_array(dest, src) if type(dest) ~= "table" or type(src) ~= "table" then return end dest_length = #dest src_length = #src for i=1, src_length do dest[dest_length + i] = src[i] end return dest end function _M.base_url() local protocol = ngx.ctx.protocol local host = ngx.ctx.host local port = ngx.ctx.port local base = protocol .. "://" .. host if (protocol == "http" and port ~= "80") or (protocol == "https" and port ~= "443") then if not host:find(":" .. port .. "$") then base = base .. ":" .. port end end return base end function _M.get_packed(dict, key) local packed = dict:get(key) if packed then return unpack(packed) end end function _M.set_packed(dict, key, value) return dict:set(key, pack(value)) end function _M.deep_merge_overwrite_arrays(dest, src) if not src then return dest end for key, value in pairs(src) do if type(value) == "table" and type(dest[key]) == "table" then if _M.is_array(value) then dest[key] = value else _M.deep_merge_overwrite_arrays(dest[key], src[key]) end else dest[key] = value end end return dest end function _M.cache_computed_settings(settings) if not settings then return end -- Parse and cache the allowed IPs as CIDR ranges. if not is_empty(settings["allowed_ips"]) then settings["_allowed_cidrs"] = parse_cidrs(settings["allowed_ips"]) settings["allowed_ips"] = nil end -- Parse and cache the allowed referers as matchers if not is_empty(settings["allowed_referers"]) then settings["_allowed_referer_matchers"] = {} for _, referer in ipairs(settings["allowed_referers"]) do local matcher = escape(referer) matcher = string.gsub(matcher, "%%%*", ".*") matcher = "^" .. matcher .. "$" table.insert(settings["_allowed_referer_matchers"], matcher) end settings["allowed_referers"] = nil end if settings["append_query_string"] then settings["_append_query_args"] = ngx.decode_args(settings["append_query_string"]) settings["append_query_string"] = nil end if settings["http_basic_auth"] then settings["_http_basic_auth_header"] = "Basic " .. ngx.encode_base64(settings["http_basic_auth"]) settings["http_basic_auth"] = nil end end function _M.parse_accept(header, supported_media_types) if not header then return nil end local accepts = {} local accept_header = split(header, ",") for _, accept_string in ipairs(accept_header) do local parts = split(accept_string, ";", 2) local media = parts[1] local params = parts[2] if params then params = split(params, ";") end local media_parts = split(media, "/") local media_type = strip(media_parts[1] or "") local media_subtype = strip(media_parts[2] or "") local q = 1 for _, param in ipairs(params) do local param_parts = split(param, "=") local param_key = strip(param_parts[1] or "") local param_value = strip(param_parts[2] or "") if param_key == "q" then q = tonumber(param_value) end end if q == 0 then break end local accept = { media_type = media_type, media_subtype = media_subtype, q = q, } table.insert(accepts, accept) end table.sort(accepts, function(a, b) if a.q < b.q then return false elseif a.q > b.q then return true elseif (a.media_type == "*" and b.media_type ~= "*") or (a.media_subtype == "*" and b.media_subtype ~= "*") then return false elseif (a.media_type ~= "*" and b.media_type == "*") or (a.media_subtype ~= "*" and b.media_subtype == "*") then return true else return true end end) for _, supported in ipairs(supported_media_types) do for _, accept in ipairs(accepts) do if accept.media_type == supported.media_type and accept.media_subtype == supported.media_subtype then return supported.format elseif accept.media_type == supported.media_type and accept.media_subtype == "*" then return supported.format elseif accept.media_type == "*" and accept.media_subtype == "*" then return supported.format else return nil end end end end return _M
Fix referrer matching not matching based on the full URL.
Fix referrer matching not matching based on the full URL.
Lua
mit
NREL/api-umbrella,apinf/api-umbrella,apinf/api-umbrella,apinf/api-umbrella,NREL/api-umbrella,apinf/api-umbrella,NREL/api-umbrella,apinf/api-umbrella,NREL/api-umbrella
26a4307db226d2ea80de063db117890648b19050
src/MY_CheckUpdate.lua
src/MY_CheckUpdate.lua
local _L = MY.LoadLangPack() MY_CheckUpdate = { szUrl = "http://j3my.sinaapp.com/interface/my/latest_version.html", szTipId = nil, } RegisterCustomData('MY_CheckUpdate.szTipId') MY_CheckUpdate.bChecked = false MY_CheckUpdate.GetValue = function(szText, szKey) local escape = function(s) return string.gsub(s, '([%(%)%.%%%+%-%*%?%[%^%$%]])', '%%%1') end local nPos1, nPos2 = string.find(szText, '%|'..escape(szKey)..'=[^%|]*') if not nPos1 then return nil else return string.sub(szText, nPos1 + string.len('|'..szKey..'='), nPos2) end end MY.RegisterEvent("LOADING_END", function() if MY_CheckUpdate.bChecked then return end local function escape(w) pattern="[^%w%d%._%-%* ]" s=string.gsub(w,pattern,function(c) local c=string.format("%%%02X",string.byte(c)) return c end) s=string.gsub(s," ","+") return s end local me = GetClientPlayer() MY.RemoteRequest(string.format("%s?n=%s&i=%s&l=%s&f=%s&r=%s&c=%s&t=%s&_=%i", MY_CheckUpdate.szUrl, escape(me.szName), me.dwID, me.nLevel, me.dwForceID, me.nRoleType, me.nCamp, escape(GetTongClient().szTongName), GetCurrentTime()), function(szTitle,szContent) MY_CheckUpdate.bChecked = true local szVersion, nVersion = MY.GetVersion() local nLatestVersion = tonumber(MY_CheckUpdate.GetValue(szContent,'ver')) if nLatestVersion then if nLatestVersion > nVersion then -- new version local szFile = MY_CheckUpdate.GetValue(szContent, 'file') local szPage = MY_CheckUpdate.GetValue(szContent, 'page') local szFeature = MY_CheckUpdate.GetValue(szContent, 'feature') local szAlert = MY_CheckUpdate.GetValue(szContent, 'alert') local szTip = MY_CheckUpdate.GetValue(szContent, 'tip') local szTipId = MY_CheckUpdate.GetValue(szContent, 'tip-id') local szTipRgb = MY_CheckUpdate.GetValue(szContent, 'tip-rgb') MY.Sysmsg(_L["new version found."]..'\n', nil, { 255, 0, 0}) MY.Sysmsg(szFeature..'\n', nil, { 255, 0, 0}) if #szTipId>0 and szTipId~=MY_CheckUpdate.szTipId then local split = function(s, p) local rt= {} string.gsub(s, '[^'..p..']+', function(w) table.insert(rt, w) end ) return rt end local _rgb, rgb = { 255, 0, 0 }, split( szTipRgb, ',' ) rgb[1], rgb[2], rgb[3] = tonumber(rgb[1]), tonumber(rgb[2]), tonumber(rgb[3]) if rgb[1] and rgb[1]>=0 and rgb[1]<=255 then _rgb[1] = rgb[1] end if rgb[2] and rgb[2]>=0 and rgb[2]<=255 then _rgb[2] = rgb[2] end if rgb[3] and rgb[3]>=0 and rgb[3]<=255 then _rgb[3] = rgb[3] end MY.Sysmsg(szTip..'\n', nil, _rgb) MY_CheckUpdate.szTipId = szTipId end if szAlert~='0' then local tVersionInfo = { szName = "MY_VersionInfo", szMessage = string.format("[%s] %s", _L["mingyi plugins"], _L["new version found, would you want to download immediately?"]..((#szFeature>0 and '\n--------------------\n') or '')..szFeature), { szOption = _L['download immediately'], fnAction = function() MY.UI.OpenInternetExplorer(szFile, true) end },{ szOption = _L['see new feature'], fnAction = function() MY.UI.OpenInternetExplorer(szPage, true) end }, {szOption = g_tStrings.STR_HOTKEY_CANCEL,fnAction = function() end}, } MessageBox(tVersionInfo) end end MY.Debug("Latest version: "..nLatestVersion..", local version: "..nVersion..' ('..szVersion..")\n",'MYVC',0) else MY.Debug(L["version check failed, sever resopnse unknow data.\n"],'MYVC',2) end end) MY.Debug('Start Version Check!\n','MYVC',0) end) MY.Debug('Version Check Mod Loaded!\n','MYVC',0)
local _L = MY.LoadLangPack() MY_CheckUpdate = { szUrl = "http://j3my.sinaapp.com/interface/my/latest_version.html", szTipId = nil, } RegisterCustomData('MY_CheckUpdate.szTipId') MY_CheckUpdate.bChecked = false MY_CheckUpdate.GetValue = function(szText, szKey) local escape = function(s) return string.gsub(s, '([%(%)%.%%%+%-%*%?%[%^%$%]])', '%%%1') end local nPos1, nPos2 = string.find(szText, '%|'..escape(szKey)..'=[^%|]*') if not nPos1 then return nil else return string.sub(szText, nPos1 + string.len('|'..szKey..'='), nPos2) end end MY.RegisterEvent("LOADING_END", function() if MY_CheckUpdate.bChecked then return end local function urlencode(w) pattern="[^%w%d%._%-%* ]" s=string.gsub(w,pattern,function(c) local c=string.format("%%%02X",string.byte(c)) return c end) s=string.gsub(s," ","+") return s end local me = GetClientPlayer() MY.RemoteRequest(string.format("%s?n=%s&i=%s&l=%s&f=%s&r=%s&c=%s&t=%s&_=%i", MY_CheckUpdate.szUrl, urlencode(me.szName), me.dwID, me.nLevel, me.dwForceID, me.nRoleType, me.nCamp, urlencode(GetTongClient().szTongName), GetCurrentTime()), function(szTitle,szContent) MY_CheckUpdate.bChecked = true local szVersion, nVersion = MY.GetVersion() local nLatestVersion = tonumber(MY_CheckUpdate.GetValue(szContent,'ver')) local szTip = MY_CheckUpdate.GetValue(szContent, 'tip') local szTipId = MY_CheckUpdate.GetValue(szContent, 'tip-id') local szTipRgb = MY_CheckUpdate.GetValue(szContent, 'tip-rgb') -- push message if #szTipId>0 and szTipId~=MY_CheckUpdate.szTipId then local split = function(s, p) local rt= {} string.gsub(s, '[^'..p..']+', function(w) table.insert(rt, w) end ) return rt end local _rgb, rgb = { 255, 0, 0 }, split( szTipRgb, ',' ) rgb[1], rgb[2], rgb[3] = tonumber(rgb[1]), tonumber(rgb[2]), tonumber(rgb[3]) if rgb[1] and rgb[1]>=0 and rgb[1]<=255 then _rgb[1] = rgb[1] end if rgb[2] and rgb[2]>=0 and rgb[2]<=255 then _rgb[2] = rgb[2] end if rgb[3] and rgb[3]>=0 and rgb[3]<=255 then _rgb[3] = rgb[3] end MY.Sysmsg(szTip..'\n', nil, _rgb) MY_CheckUpdate.szTipId = szTipId end -- version update if nLatestVersion then if nLatestVersion > nVersion then local szFile = MY_CheckUpdate.GetValue(szContent, 'file') local szPage = MY_CheckUpdate.GetValue(szContent, 'page') local szFeature = MY_CheckUpdate.GetValue(szContent, 'feature') local szAlert = MY_CheckUpdate.GetValue(szContent, 'alert') -- new version MY.Sysmsg(_L["new version found."]..'\n', nil, { 255, 0, 0}) MY.Sysmsg(szFeature..'\n', nil, { 255, 0, 0}) if szAlert~='0' then local tVersionInfo = { szName = "MY_VersionInfo", szMessage = string.format("[%s] %s", _L["mingyi plugins"], _L["new version found, would you want to download immediately?"]..((#szFeature>0 and '\n--------------------\n') or '')..szFeature), { szOption = _L['download immediately'], fnAction = function() MY.UI.OpenInternetExplorer(szFile, true) end },{ szOption = _L['see new feature'], fnAction = function() MY.UI.OpenInternetExplorer(szPage, true) end }, {szOption = g_tStrings.STR_HOTKEY_CANCEL,fnAction = function() end}, } MessageBox(tVersionInfo) end end MY.Debug("Latest version: "..nLatestVersion..", local version: "..nVersion..' ('..szVersion..")\n",'MYVC',0) else MY.Debug(L["version check failed, sever resopnse unknow data.\n"],'MYVC',2) end end) MY.Debug('Start Version Check!\n','MYVC',0) end) MY.Debug('Version Check Mod Loaded!\n','MYVC',0)
修复没有更新不会推送消息的BUG
修复没有更新不会推送消息的BUG
Lua
bsd-3-clause
tinymins/MY
f1bec0264638035ea9b51f4bcb92a95263f319cb
MMOCoreORB/bin/scripts/object/resource_container/resource_spawn.lua
MMOCoreORB/bin/scripts/object/resource_container/resource_spawn.lua
object_resource_container_resource_spawn = object_resource_container_shared_simple:new { playerUseMask = ALL, level = 10, maxCondition = 1000, useCount = 1, optionsBitmask = 256, --Default all objects to not display ham bars. pvpStatusBitmask = 0, objectMenuComponent = "TangibleObjectMenuComponent", sliceable = 0, templateType = RESOURCESPAWN, gameObjectType = 4259840 } ObjectTemplates:addTemplate(object_resource_container_resource_spawn, "object/resource_container/resource_spawn.iff")
object_resource_container_resource_spawn = object_resource_container_shared_simple:new { playerUseMask = ALL, level = 10, maxCondition = 1000, useCount = 1, optionsBitmask = 256, --Default all objects to not display ham bars. pvpStatusBitmask = 0, objectMenuComponent = "TangibleObjectMenuComponent", attributeListComponent = "AttributeListComponent", sliceable = 0, templateType = RESOURCESPAWN, gameObjectType = 4259840 } ObjectTemplates:addTemplate(object_resource_container_resource_spawn, "object/resource_container/resource_spawn.iff")
[fixed] stability fixes
[fixed] stability fixes git-svn-id: c34995188cc7e843f8a799edec2d9d4b36f36456@3871 c3d1530f-68f5-4bd0-87dc-8ef779617e40
Lua
agpl-3.0
Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo
44208f18ab1f57bc392b7d3a00fe01cf59ad2476
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) 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
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") if not fp then error("IO error: " .. filename) end 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 local gamma_lcd = 0.454545 im:fromBlob(blob, #blob) if im:colorspace() == "CMYK" then im:colorspace("RGB") end local gamma = math.floor(im:gamma() * 1000000) / 1000000 if gamma ~= 0 and gamma ~= gamma_lcd then im:gammaCorrection(gamma / gamma_lcd) 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 gamma embed PNG
Fix handling for gamma embed PNG
Lua
mit
nagadomi/waifu2x,higankanshi/waifu2x,nagadomi/waifu2x,vitaliylag/waifu2x,vitaliylag/waifu2x,Spitfire1900/upscaler,nagadomi/waifu2x,zyhkz/waifu2x,higankanshi/waifu2x,Spitfire1900/upscaler,zyhkz/waifu2x,vitaliylag/waifu2x,nagadomi/waifu2x,zyhkz/waifu2x,nagadomi/waifu2x,higankanshi/waifu2x,zyhkz/waifu2x
e1ffee056e3cae2ef81710847f0f0f31fe3340a8
model/dictionary.lua
model/dictionary.lua
------------------------------------------------------------------------ --[[ Dictionary ]]-- -- Adapts a nn.LookupTable -- Works on a WordTensor:context() view. ------------------------------------------------------------------------ local Dictionary, parent = torch.class("dp.Dictionary", "dp.Layer") Dictionary.isDictionary = true function Dictionary:__init(config) assert(type(config) == 'table', "Constructor requires key-value arguments") local args, dict_size, output_size, typename = xlua.unpack( {config}, 'Dictionary', 'adapts a nn.LookupTable', {arg='dict_size', type='number', req=true, help='Number of entries in the dictionary (e.g. num of words)'}, {arg='output_size', type='number', req=true, help='Number of neurons per entry.'}, {arg='typename', type='string', default='dictionary', help='identifies Model type in reports.'} ) assert(not config.dropout, "Dictionary doesn't work with dropout") assert(not config.sparse_init, "Dictionary doesn't work with sparse_init") config.sparse_init = false self._dict_size = dict_size self._output_size = output_size self._module = nn.LookupTable(dict_size, output_size) if self._acc_update then self._module:accUpdateOnly() end config.typename = typename config.input_type = 'torch.IntTensor' config.tags = config.tags or {} config.input_view = 'bt' config.output_view = 'bwc' config.output = dp.SequenceView() parent.__init(self, config) end function Dictionary:_backward(carry) local input_grad if self._acc_update then input_grad = self._module:updateGradInput(self:inputAct(), self:outputGrad()) else input_grad = self._module:backward(self:inputAct(), self:outputGrad(), self._acc_scale) end return carry end function Dictionary:_type(type) self._module:type(type) if type == 'torch.FloatTensor' or type == 'torch.DoubleTensor' or type == 'torch.CudaTensor' then self._output_type = type elseif type == 'torch.IntTensor' or type == 'torch.LongTensor' then self._input_type = type end return self end function Dictionary:reset(stdv) self._module:reset(stdv) end function Dictionary:parameters() local module = self._module if self.forwarded then -- only return the parameters affected by the forward/backward local params, gradParams, scales = {}, {}, {} for k,nBackward in pairs(module.inputs) do local kscale = module:scaleUpdateByKey(k) params[k] = module.weight:select(1, k) gradParams[k] = module.gradWeight:select(1, k) scales[k] = module:scaleUpdateByKey(k) end return params, gradParams, scales end return module:parameters() end function Dictionary:share(dict, ...) assert(dict.isDictionary) return parent.share(self, dict, ...) end -- Only affects 2D parameters. -- Assumes that 2D parameters are arranged (input_dim, output_dim) function Dictionary:maxNorm(max_out_norm, max_in_norm) assert(self.backwarded, "Should call maxNorm after a backward pass") local module = self._module max_out_norm = self.mvstate.max_out_norm or max_out_norm max_out_norm = self.mvstate.max_in_norm or max_in_norm or max_out_norm for k,nBackward in pairs(module.inputs) do module.weight:narrow(1, k, 1):renorm(1, 2, max_out_norm) end end function Dictionary:sharedClone() local clone = torch.protoClone(self, { dict_size = 1, output_size = 1, typename=self._typename, gather_stats=self._gather_stats, input_type=self._input_type, output_type=self._output_type, module_type=self._module_type, mvstate=self.mvstate }) clone._dict_size = self._dict_size clone._output_size = self._output_size if self._acc_update then clone._module.gradWeight:resizeAs(self._module.gradWeight) end clone._module.batchSize = self._module.batchSize return self:share(clone, 'weight') end
------------------------------------------------------------------------ --[[ Dictionary ]]-- -- Adapts a nn.LookupTable (often used for language modeling) -- Outputs a SequenceView ------------------------------------------------------------------------ local Dictionary, parent = torch.class("dp.Dictionary", "dp.Layer") Dictionary.isDictionary = true function Dictionary:__init(config) assert(type(config) == 'table', "Constructor requires key-value arguments") local args, dict_size, output_size, typename = xlua.unpack( {config}, 'Dictionary', 'adapts a nn.LookupTable', {arg='dict_size', type='number', req=true, help='Number of entries in the dictionary (e.g. num of words)'}, {arg='output_size', type='number', req=true, help='Number of neurons per entry.'}, {arg='typename', type='string', default='dictionary', help='identifies Model type in reports.'} ) assert(not config.dropout, "Dictionary doesn't work with dropout") assert(not config.sparse_init, "Dictionary doesn't work with sparse_init") config.sparse_init = false self._dict_size = dict_size self._output_size = output_size self._module = nn.LookupTable(dict_size, output_size) config.typename = typename config.input_type = 'torch.IntTensor' config.tags = config.tags or {} config.input_view = 'bt' config.output_view = 'bwc' config.output = dp.SequenceView() parent.__init(self, config) if self._acc_update then self._module:accUpdateOnly() end end function Dictionary:_backward(carry) local input_grad if self._acc_update then input_grad = self._module:updateGradInput(self:inputAct(), self:outputGrad()) else input_grad = self._module:backward(self:inputAct(), self:outputGrad(), self._acc_scale) end return carry end function Dictionary:_type(type) self._module:type(type) if type == 'torch.FloatTensor' or type == 'torch.DoubleTensor' or type == 'torch.CudaTensor' then self._output_type = type elseif type == 'torch.IntTensor' or type == 'torch.LongTensor' then self._input_type = type end return self end function Dictionary:reset(stdv) self._module:reset(stdv) end function Dictionary:parameters() local module = self._module if self.forwarded then -- only return the parameters affected by the forward/backward local params, gradParams, scales = {}, {}, {} for k,nBackward in pairs(module.inputs) do local kscale = module:scaleUpdateByKey(k) params[k] = module.weight:select(1, k) gradParams[k] = module.gradWeight:select(1, k) scales[k] = module:scaleUpdateByKey(k) end return params, gradParams, scales end return module:parameters() end function Dictionary:share(dict, ...) assert(dict.isDictionary) return parent.share(self, dict, ...) end -- Only affects 2D parameters. -- Assumes that 2D parameters are arranged (input_dim, output_dim) function Dictionary:maxNorm(max_out_norm, max_in_norm) assert(self.backwarded, "Should call maxNorm after a backward pass") local module = self._module max_out_norm = self.mvstate.max_out_norm or max_out_norm max_out_norm = self.mvstate.max_in_norm or max_in_norm or max_out_norm for k,nBackward in pairs(module.inputs) do module.weight:narrow(1, k, 1):renorm(1, 2, max_out_norm) end end function Dictionary:sharedClone() local clone = torch.protoClone(self, { dict_size = 1, output_size = 1, typename=self._typename, gather_stats=self._gather_stats, input_type=self._input_type, output_type=self._output_type, module_type=self._module_type, mvstate=self.mvstate }) clone._dict_size = self._dict_size clone._output_size = self._output_size if self._acc_update then clone._module.gradWeight:resizeAs(self._module.gradWeight) end clone._module.batchSize = self._module.batchSize return self:share(clone, 'weight') end
fixed Dictionary acc_update bug
fixed Dictionary acc_update bug
Lua
bsd-3-clause
kracwarlock/dp,jnhwkim/dp,fiskio/dp,sagarwaghmare69/dp,rickyHong/dptorchLib,nicholas-leonard/dp,eulerreich/dp
4e2ded571ec0ff9e4a11713ffb0bdedc426ded61
modules/gamelib/game.lua
modules/gamelib/game.lua
local currentRsa function g_game.getRsa() return currentRsa end function g_game.findPlayerItem(itemId, subType) local localPlayer = g_game.getLocalPlayer() if localPlayer then for slot = InventorySlotFirst, InventorySlotLast do local item = localPlayer:getInventoryItem(slot) if item and item:getId() == itemId and (subType == -1 or item:getSubType() == subType) then return item end end end return g_game.findItemInContainers(itemId, subType) end function g_game.chooseRsa(host) if currentRsa ~= CIPSOFT_RSA and currentRsa ~= OTSERV_RSA then return end if host:ends('.tibia.com') or host:ends('.cipsoft.com') then g_game.setRsa(CIPSOFT_RSA) if g_app.getOs() == 'windows' then g_game.setCustomOs(OsTypes.Windows) else g_game.setCustomOs(OsTypes.Linux) end else if currentRsa == CIPSOFT_RSA then g_game.setCustomOs(-1) end g_game.setRsa(OTSERV_RSA) end -- Hack fix to resolve some 760 login issues if g_game.getClientVersion() <= 760 then g_game.setCustomOs(2) end end function g_game.setRsa(rsa, e) e = e or '65537' g_crypt.rsaSetPublicKey(rsa, e) currentRsa = rsa end function g_game.isOfficialTibia() return currentRsa == CIPSOFT_RSA end function g_game.getSupportedClients() return { 740, 741, 750, 760, 770, 772, 780, 781, 782, 790, 792, 800, 810, 811, 820, 821, 822, 830, 831, 840, 842, 850, 853, 854, 855, 857, 860, 861, 862, 870, 871, 900, 910, 920, 931, 940, 943, 944, 951, 952, 953, 954, 960, 961, 963, 970, 971, 972, 973, 980, 981, 982, 983, 984, 985, 986, 1000, 1001, 1002, 1010, 1011, 1012, 1013, 1020, 1021, 1022, 1030, 1031, 1032, 1033, 1034, 1035, 1036, 1037, 1038, 1039, 1040, 1041, 1050, 1051, 1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1070, 1071, 1072, 1073 } end -- The client version and protocol version where -- unsynchronized for some releases, not sure if this -- will be the normal standard. -- Client Version: Publicly given version when -- downloading Cipsoft client. -- Protocol Version: Previously was the same as -- the client version, but was unsychronized in some -- releases, now it needs to be verified and added here -- if it does not match the client version. -- Reason for defining both: The server now requires a -- Client version and Protocol version from the client. -- Important: Use getClientVersion for specific protocol -- features to ensure we are using the proper version. function g_game.getClientProtocolVersion(client) local clients = { [980] = 971, [981] = 973, [982] = 974, [983] = 975, [984] = 976, [985] = 977, [986] = 978, [1001] = 979, [1002] = 980 } return clients[client] or client end g_game.setRsa(OTSERV_RSA)
function g_game.getRsa() return G.currentRsa end function g_game.findPlayerItem(itemId, subType) local localPlayer = g_game.getLocalPlayer() if localPlayer then for slot = InventorySlotFirst, InventorySlotLast do local item = localPlayer:getInventoryItem(slot) if item and item:getId() == itemId and (subType == -1 or item:getSubType() == subType) then return item end end end return g_game.findItemInContainers(itemId, subType) end function g_game.chooseRsa(host) if G.currentRsa ~= CIPSOFT_RSA and G.currentRsa ~= OTSERV_RSA then return end if host:ends('.tibia.com') or host:ends('.cipsoft.com') then g_game.setRsa(CIPSOFT_RSA) if g_app.getOs() == 'windows' then g_game.setCustomOs(OsTypes.Windows) else g_game.setCustomOs(OsTypes.Linux) end else if G.currentRsa == CIPSOFT_RSA then g_game.setCustomOs(-1) end g_game.setRsa(OTSERV_RSA) end -- Hack fix to resolve some 760 login issues if g_game.getClientVersion() <= 760 then g_game.setCustomOs(2) end end function g_game.setRsa(rsa, e) e = e or '65537' g_crypt.rsaSetPublicKey(rsa, e) G.currentRsa = rsa end function g_game.isOfficialTibia() return G.currentRsa == CIPSOFT_RSA end function g_game.getSupportedClients() return { 740, 741, 750, 760, 770, 772, 780, 781, 782, 790, 792, 800, 810, 811, 820, 821, 822, 830, 831, 840, 842, 850, 853, 854, 855, 857, 860, 861, 862, 870, 871, 900, 910, 920, 931, 940, 943, 944, 951, 952, 953, 954, 960, 961, 963, 970, 971, 972, 973, 980, 981, 982, 983, 984, 985, 986, 1000, 1001, 1002, 1010, 1011, 1012, 1013, 1020, 1021, 1022, 1030, 1031, 1032, 1033, 1034, 1035, 1036, 1037, 1038, 1039, 1040, 1041, 1050, 1051, 1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1070, 1071, 1072, 1073 } end -- The client version and protocol version where -- unsynchronized for some releases, not sure if this -- will be the normal standard. -- Client Version: Publicly given version when -- downloading Cipsoft client. -- Protocol Version: Previously was the same as -- the client version, but was unsychronized in some -- releases, now it needs to be verified and added here -- if it does not match the client version. -- Reason for defining both: The server now requires a -- Client version and Protocol version from the client. -- Important: Use getClientVersion for specific protocol -- features to ensure we are using the proper version. function g_game.getClientProtocolVersion(client) local clients = { [980] = 971, [981] = 973, [982] = 974, [983] = 975, [984] = 976, [985] = 977, [986] = 978, [1001] = 979, [1002] = 980 } return clients[client] or client end if not G.currentRsa then g_game.setRsa(OTSERV_RSA) end
Fixed not being able to relog after reloading gamelib
Fixed not being able to relog after reloading gamelib
Lua
mit
gpedro/otclient,dreamsxin/otclient,Radseq/otclient,dreamsxin/otclient,Cavitt/otclient_mapgen,gpedro/otclient,gpedro/otclient,Cavitt/otclient_mapgen,Radseq/otclient,dreamsxin/otclient
0a7bdb85283accf120e2898724aec8e1a5eff311
volumearc-widget/volumearc.lua
volumearc-widget/volumearc.lua
------------------------------------------------- -- Volume Arc Widget for Awesome Window Manager -- Shows the current volume level -- More details could be found here: -- https://github.com/streetturtle/awesome-wm-widgets/tree/master/volumearc-widget -- @author Pavel Makhov -- @copyright 2018 Pavel Makhov ------------------------------------------------- local awful = require("awful") local beautiful = require("beautiful") local spawn = require("awful.spawn") local watch = require("awful.widget.watch") local wibox = require("wibox") local gears = require("gears") local GET_VOLUME_CMD = 'amixer -D pulse sget Master' local INC_VOLUME_CMD = 'amixer -q -D pulse sset Master 5%+' local DEC_VOLUME_CMD = 'amixer -q -D pulse sset Master 5%-' local TOG_VOLUME_CMD = 'amixer -q -D pulse sset Master toggle' local PATH_TO_ICON = "/usr/share/icons/Arc/status/symbolic/audio-volume-muted-symbolic.svg" local widget = {} local popup = awful.popup{ ontop = true, visible = false, shape = gears.shape.rounded_rect, border_width = 1, border_color = beautiful.bg_focus, maximum_width = 400, offset = { y = 5 }, widget = {} } local rows = { { widget = wibox.widget.textbox }, layout = wibox.layout.fixed.vertical, } local function worker(user_args) local args = user_args or {} local main_color = args.main_color or beautiful.fg_color local bg_color = args.bg_color or '#ffffff11' local mute_color = args.mute_color or beautiful.fg_urgent local path_to_icon = args.path_to_icon or PATH_TO_ICON local thickness = args.thickness or 2 local margins = args.height or 18 local timeout = args.timeout or 1 local get_volume_cmd = args.get_volume_cmd or GET_VOLUME_CMD local inc_volume_cmd = args.inc_volume_cmd or INC_VOLUME_CMD local dec_volume_cmd = args.dec_volume_cmd or DEC_VOLUME_CMD local tog_volume_cmd = args.tog_volume_cmd or TOG_VOLUME_CMD local icon = { id = "icon", image = path_to_icon, resize = true, widget = wibox.widget.imagebox, } local volumearc = wibox.widget { icon, max_value = 1, thickness = thickness, start_angle = 4.71238898, -- 2pi*3/4 forced_height = margins, forced_width = margins, bg = bg_color, paddings = 2, widget = wibox.container.arcchart } local update_graphic = function(_, stdout, _, _, _) local mute = string.match(stdout, "%[(o%D%D?)%]") -- \[(o\D\D?)\] - [on] or [off] local volume = string.match(stdout, "(%d?%d?%d)%%") -- (\d?\d?\d)\%) volume = tonumber(string.format("% 3d", volume)) widget.value = volume / 100; widget.colors = mute == 'off' and { mute_color } or { main_color } end local button_press = args.button_press or function(_, _, _, button) if (button == 4) then awful.spawn(inc_volume_cmd, false) elseif (button == 5) then awful.spawn(dec_volume_cmd, false) elseif (button == 1) then awful.spawn(tog_volume_cmd, false) end spawn.easy_async(get_volume_cmd, function(stdout, stderr, exitreason, exitcode) update_graphic(volumearc, stdout, stderr, exitreason, exitcode) end) end volumearc:connect_signal("button::press", button_press) local rebuild_widget = function(stdout) for i = 0, #rows do rows[i]=nil end for line in stdout:gmatch("[^\r\n]+") do local row = wibox.widget { text = line, widget = wibox.widget.textbox } table.insert(rows, row) end popup:setup(rows) end volumearc:buttons( awful.util.table.join( awful.button({}, 3, function() if popup.visible then popup.visible = not popup.visible else spawn.easy_async([[bash -c "cat /proc/asound/cards"]], function(stdout, stderr) rebuild_widget(stdout, stderr) popup:move_next_to(mouse.current_widget_geometry) end) end end) ) ) watch(get_volume_cmd, timeout, update_graphic, volumearc) return volumearc end return setmetatable(widget, { __call = function(_, ...) return worker(...) end })
------------------------------------------------- -- Volume Arc Widget for Awesome Window Manager -- Shows the current volume level -- More details could be found here: -- https://github.com/streetturtle/awesome-wm-widgets/tree/master/volumearc-widget -- @author Pavel Makhov -- @copyright 2018 Pavel Makhov ------------------------------------------------- local awful = require("awful") local beautiful = require("beautiful") local spawn = require("awful.spawn") local watch = require("awful.widget.watch") local wibox = require("wibox") local gears = require("gears") local GET_VOLUME_CMD = 'amixer -D pulse sget Master' local INC_VOLUME_CMD = 'amixer -q -D pulse sset Master 5%+' local DEC_VOLUME_CMD = 'amixer -q -D pulse sset Master 5%-' local TOG_VOLUME_CMD = 'amixer -q -D pulse sset Master toggle' local PATH_TO_ICON = "/usr/share/icons/Arc/status/symbolic/audio-volume-muted-symbolic.svg" local widget = {} local popup = awful.popup{ ontop = true, visible = false, shape = gears.shape.rounded_rect, border_width = 1, border_color = beautiful.bg_focus, maximum_width = 400, offset = { y = 5 }, widget = {} } local rows = { { widget = wibox.widget.textbox }, layout = wibox.layout.fixed.vertical, } local function worker(user_args) local args = user_args or {} local main_color = args.main_color or beautiful.fg_color local bg_color = args.bg_color or '#ffffff11' local mute_color = args.mute_color or beautiful.fg_urgent local path_to_icon = args.path_to_icon or PATH_TO_ICON local thickness = args.thickness or 2 local margins = args.height or 18 local timeout = args.timeout or 1 local get_volume_cmd = args.get_volume_cmd or GET_VOLUME_CMD local inc_volume_cmd = args.inc_volume_cmd or INC_VOLUME_CMD local dec_volume_cmd = args.dec_volume_cmd or DEC_VOLUME_CMD local tog_volume_cmd = args.tog_volume_cmd or TOG_VOLUME_CMD local icon = { id = "icon", image = path_to_icon, resize = true, widget = wibox.widget.imagebox, } local volumearc = wibox.widget { icon, max_value = 1, thickness = thickness, start_angle = 4.71238898, -- 2pi*3/4 forced_height = margins, forced_width = margins, bg = bg_color, paddings = 2, widget = wibox.container.arcchart } local update_graphic = function(widget, stdout, _, _, _) local mute = "on" local volume = 0 if not (stdout == nil or stdout == '') then mute = string.match(stdout, "%[(o%D%D?)%]") -- \[(o\D\D?)\] - [on] or [off] volume = string.match(tostring(stdout), "(%d?%d?%d)%%") -- (\d?\d?\d)\%) volume = tonumber(string.format("% 3d", volume)) end widget.value = volume / 100; widget.colors = mute == 'off' and { mute_color } or { main_color } end local button_press = args.button_press or function(_, _, _, button) if (button == 4) then awful.spawn(inc_volume_cmd, false) elseif (button == 5) then awful.spawn(dec_volume_cmd, false) elseif (button == 1) then awful.spawn(tog_volume_cmd, false) end spawn.easy_async(get_volume_cmd, function(stdout, stderr, exitreason, exitcode) update_graphic(volumearc, stdout, stderr, exitreason, exitcode) end) end volumearc:connect_signal("button::press", button_press) local rebuild_widget = function(stdout) for i = 0, #rows do rows[i]=nil end for line in stdout:gmatch("[^\r\n]+") do local row = wibox.widget { text = line, widget = wibox.widget.textbox } table.insert(rows, row) end popup:setup(rows) end volumearc:buttons( awful.util.table.join( awful.button({}, 3, function() if popup.visible then popup.visible = not popup.visible else spawn.easy_async([[bash -c "cat /proc/asound/cards"]], function(stdout, stderr) rebuild_widget(stdout, stderr) popup:move_next_to(mouse.current_widget_geometry) end) end end) ) ) watch(get_volume_cmd, timeout, update_graphic, volumearc) return volumearc end return setmetatable(widget, { __call = function(_, ...) return worker(...) end })
fix to prevent stdout from passing a null string
fix to prevent stdout from passing a null string
Lua
mit
streetturtle/awesome-wm-widgets,streetturtle/awesome-wm-widgets
57c03051492e564486a261cab1d381a03cd2b41f
src/lua/sancus/web/resource.lua
src/lua/sancus/web/resource.lua
-- local Class = assert(require"sancus.object").Class local request = assert(require"wsapi.request") local mimeparse = require"mimeparse" local C = Class{ _methods = {'GET', 'HEAD', 'POST', 'PUT', 'DELETE'} } function C:find_supported_methods(d) local l = {} if #d > 0 then for _, k in ipairs(d) do if type(self[k]) == 'function' then l[k] = k end end else for l, v in pairs(d) do if type(self[v]) == 'function' then l[k] = v end end end if l['GET'] and not l['HEAD'] then l['HEAD'] = l['GET'] end return l end function C:supported_methods(environ) local l = self._supported_methods if not l then l = self:find_supported_methods(self._methods) self._supported_methods = l end return l end function C:__call(environ) local method = environ.REQUEST_METHOD local handlers, handler_name, handler local args handlers = self:supported_methods(environ) handler_name = handlers[method] if not handler_name then return 405, { Allow = handlers } end handler = self[handler_name] if self._accepted_types ~= nil then local content_type = mimeparse.best_match(self._accepted_types, environ.HTTP_ACCEPT or "*/*") if content_type == "" then return 406 else environ["sancus.content_type"] = content_type end end args = environ["sancus.routing_args"] or {} environ["sancus.handler_name"] = handler_name environ["sancus.handler"] = handler environ["sancus.named_args"] = args self.status = 200 self.headers = {} self.body = {} if method ~= 'POST' then self.req = request.new(environ, { delay_post = true }) else self.req = request.new(environ) end function self.app_iter() if type(self.body) == "string" then coroutine.yield(self.body) else for _,v in ipairs(self.body) do coroutine.yield(v) end end end local status, headers, iter = handler(self, self.req, args) if status ~= nil then return status, headers, iter end return self.status, self.headers, coroutine.wrap(self.app_iter) end -- -- function MinimalMiddleware(app, interceptor) local function nop() end interceptor = interceptor or {} return function(env) local status, headers, iter = app(env) if interceptor[status] then _, headers, iter = interceptor[status](env) end if headers == nil then headers = { ['Content-Type'] = 'plain/text' } end for k,v in pairs(headers) do if type(v) == 'table' then local t if #v > 0 then t = v else t = {} for kv,_ in pairs(v) do t[#t+1] = kv end end headers[k] = table.concat(t, ", ") end end if iter == nil then iter = coroutine.wrap(nop) end return status, headers, iter end end function RemoveTrailingSlashMiddleware(app) return function(env) local path_info = env.headers["PATH_INFO"] if #path_info > 1 and path_info:sub(-1) == '/' then local headers = { Location = path_info:sub(0, -2) } local function iter() return end return 301, headers, coroutine.wrap(iter) else return app(env) end end end return { Resource = C, MinimalMiddleware = MinimalMiddleware, RemoveTrailingSlashMiddleware = RemoveTrailingSlashMiddleware, }
-- local Class = assert(require"sancus.object").Class local request = assert(require"wsapi.request") local mimeparse = require"mimeparse" local C = Class{ _methods = {'GET', 'HEAD', 'POST', 'PUT', 'DELETE'} } function C:find_supported_methods(d) local l = {} if #d > 0 then for _, k in ipairs(d) do if type(self[k]) == 'function' then l[k] = k end end else for l, v in pairs(d) do if type(self[v]) == 'function' then l[k] = v end end end if l['GET'] and not l['HEAD'] then l['HEAD'] = l['GET'] end return l end function C:supported_methods(environ) local l = self._supported_methods if not l then l = self:find_supported_methods(self._methods) self._supported_methods = l end return l end function C:__call(environ) local method = environ.REQUEST_METHOD local h = environ.headers local handlers, handler_name, handler local args handlers = self:supported_methods(environ) handler_name = handlers[method] if not handler_name then return 405, { Allow = handlers } end handler = self[handler_name] if self._accepted_types ~= nil then local content_type = mimeparse.best_match(self._accepted_types, h.HTTP_ACCEPT or "*/*") if content_type == "" then return 406 else h["sancus.content_type"] = content_type end end args = h["sancus.routing_args"] or {} h["sancus.handler_name"] = handler_name h["sancus.handler"] = handler h["sancus.named_args"] = args self.status = 200 self.headers = {} self.body = {} if method ~= 'POST' then self.req = request.new(environ, { delay_post = true }) else self.req = request.new(environ) end function self.app_iter() if type(self.body) == "string" then coroutine.yield(self.body) else for _,v in ipairs(self.body) do coroutine.yield(v) end end end local status, headers, iter = handler(self, self.req, args) if status ~= nil then return status, headers, iter end return self.status, self.headers, coroutine.wrap(self.app_iter) end -- -- function MinimalMiddleware(app, interceptor) local function nop() end interceptor = interceptor or {} return function(env) local status, headers, iter = app(env) if interceptor[status] then _, headers, iter = interceptor[status](env) end if headers == nil then headers = { ['Content-Type'] = 'plain/text' } end for k,v in pairs(headers) do if type(v) == 'table' then local t if #v > 0 then t = v else t = {} for kv,_ in pairs(v) do t[#t+1] = kv end end headers[k] = table.concat(t, ", ") end end if iter == nil then iter = coroutine.wrap(nop) end return status, headers, iter end end function RemoveTrailingSlashMiddleware(app) return function(env) local path_info = env.headers["PATH_INFO"] if #path_info > 1 and path_info:sub(-1) == '/' then local headers = { Location = path_info:sub(0, -2) } local function iter() return end return 301, headers, coroutine.wrap(iter) else return app(env) end end end return { Resource = C, MinimalMiddleware = MinimalMiddleware, RemoveTrailingSlashMiddleware = RemoveTrailingSlashMiddleware, }
web.resource: fix __call by using the environ.headers table instead of environ
web.resource: fix __call by using the environ.headers table instead of environ
Lua
bsd-2-clause
sancus-project/sancus-lua-web
0996eb01aa5ae1537195a9db3b391afa622975cb
guiexample/test.lua
guiexample/test.lua
-- Mouse enumeration Mouse = {} Mouse.Button = {} Mouse.Button.Left = 1 Mouse.Button.Right = 2 -- Widget Base Class Widget = {} Widget.__index = Widget -- Some Syntactic Sugar, calling a Class table is like calling it's create method. -- Note here 'self' is the class table. function Widget:__call(...) return self:Create(...) end -- Initialisation for all widgets function Widget:init( x, y, w, h, name ) self.name = name self.rect = GUI.Rectangle( self.x, self.y, self.w, self.h ) self.key = '' self.hover = false self.children = {} end -- Normalally these should do nothing unless overriden, however we're doing a demo here! function Widget:OnAction() print( self.name .. ' OnAction' ) end function Widget:OnKeyPress() print( self.name .. ' OnKeyPress' ) return self:OnAction() end function Widget:OnClick() print( self.name .. ' OnClick' ) return self:OnAction() end function Widget:OnAlternateClick() print( self.name .. ' OnAlternateClick' ) end function Widget:OnHover() print( self.name .. ' OnHover' ) end function Widget:OnHoverExit() print( self.name .. ' OnHoverExit' ) end -- Does this widget respond to this key? No? What about it's children? function Widget:KeyPress( key ) if key == self.key then return self:OnKeyPress() else for k, v in pairs( self.children ) do if v:KeyPress( key ) then return true end end end end -- Check if a mouse click is inside the rectangle that is our widget. -- If it is, see if there is a child ( which should fit inside ) that -- is a more specific match for the click position. -- Otherwise respond ourselves. -- -- If the click is outside, ignore it. -- function Widget:MouseClick( button, x, y ) print( 'Mouse clicked', self.name, button, x, y ) if self.rect:isInside( x, y ) then for k, v in pairs( self.children ) do if v:MouseClick( button, x, y ) then return true end end print( 'No child handled click' ) if button == Mouse.Button.Left then return self:OnClick() elseif button == Mouse.Button.Right then return self:OnAlternateClick() end end end function Widget:MouseMove( x, y ) print( self.name .. ' Mouse moved', x, y ) if self.rect:isInside( x, y ) then print( ' Inside ' .. self.name ) if self.hover == false then self.hover = true self:OnHover() end for k, v in pairs( self.children ) do v:MouseMove( x, y ) end else print( ' Outside ' .. self.name ) if self.hover == true then self.hover = false self:OnHoverExit() for k, v in pairs( self.children ) do v:MouseLost() end end end end -- Simpler, faster, version of MouseMove that assumes -- that as the mouse is outside the parent widget, it is -- outside this widget, and therefor the mouse is lost. -- function Widget:MouseLost() print( self.name .. ' has lost the mouse.' ) if self.hover then self.hover = false self:OnHoverExit() for k, v in pairs( self.children ) do v:MouseLost() end end end -- Add a child widget. Child widgets should fit inside their parents -- for the mouse targetting to work correctly. -- function Widget:AddChild( child ) if type( child.MouseMove ) == 'function' then -- Very basic check table.insert( self.children, child ) else error( 'Not a valid type of Widget!' ) end end -- A Push Button Widget. Button = {} Button.__index = Button Button.__base = Widget setmetatable( Button, Widget ) function Button:init( x, y, text ) Button.__base.init( self, x, y, 100, 50, 'Button ' .. text ) self.text = text end -- Override default Widget methods to give default Button actions! function Button:OnAction() print( self.name .. " I've been activated!" ) return true -- Event handled end function Button:OnHover() print( self.name .. ' Light up' ) end function Button:OnHoverExit() print( self.name .. ' Extinguished!' ) end function Button:Create( x, y, text ) local btn = {} setmetatable( btn, Button ) btn:init( x, y, text ) return btn end -- A dialog box widget to hold buttons. -- DialogBox = {} DialogBox.__index = DialogBox DialogBox.__base = Widget setmetatable( DialogBox, Widget ) function DialogBox:Create( x, y, w, h, title ) local dlg = {} setmetatable( dlg, DialogBox ) dlg:init( x, y, w, h, 'DialogBox ' .. title ) return dlg end ------------------------------------------------------------------------------- function test() -- A dilog box with two buttons. mybox = DialogBox( 10, 10, 500, 300, '"Save Game?"' ) ok = Button( 20, 150, 'Ok' ) cancel = Button( 150, 150, 'Cancel' ) mybox:AddChild( ok ) mybox:AddChild( cancel ) print ( 'User moves outside dialog box' ) mybox:MouseMove( 5, 5 ) print( '-------------------------------------' ) print ( 'User moves mouse over "ok"' ) mybox:MouseMove( 22, 153 ) print( '-------------------------------------' ) print ( 'User moves to "cancel"' ) mybox:MouseMove( 155, 156 ) print( '-------------------------------------' ) print ( 'User clicks left button' ) mybox:MouseClick( Mouse.Button.Left, 156, 154 ) print( '-------------------------------------' ) end
-- Mouse enumeration Mouse = {} Mouse.Button = {} Mouse.Button.Left = 1 Mouse.Button.Right = 2 -- Widget Base Class Widget = {} Widget.__index = Widget -- Some Syntactic Sugar, calling a Class table is like calling it's create method. -- Note here 'self' is the class table. function Widget.__call( class, ...) print( ... ) return class.Create(...) end -- Initialisation for all widgets function Widget:init( x, y, w, h, name ) print( 'Initialising ' .. name ) self.name = name self.rect = GUI.Rectangle( x, y, w, h ) self.key = '' self.hover = false self.children = {} end -- Normalally these should do nothing unless overriden, however we're doing a demo here! function Widget:OnAction() print( self.name .. ' OnAction' ) end function Widget:OnKeyPress() print( self.name .. ' OnKeyPress' ) return self:OnAction() end function Widget:OnClick() print( self.name .. ' OnClick' ) return self:OnAction() end function Widget:OnAlternateClick() print( self.name .. ' OnAlternateClick' ) end function Widget:OnHover() print( self.name .. ' OnHover' ) end function Widget:OnHoverExit() print( self.name .. ' OnHoverExit' ) end -- Does this widget respond to this key? No? What about it's children? function Widget:KeyPress( key ) if key == self.key then return self:OnKeyPress() else for k, v in pairs( self.children ) do if v:KeyPress( key ) then return true end end end end -- Check if a mouse click is inside the rectangle that is our widget. -- If it is, see if there is a child ( which should fit inside ) that -- is a more specific match for the click position. -- Otherwise respond ourselves. -- -- If the click is outside, ignore it. -- function Widget:MouseClick( button, x, y ) print( 'Mouse clicked', self.name, button, x, y ) if self.rect:isInside( x, y ) then for k, v in pairs( self.children ) do if v:MouseClick( button, x, y ) then return true end end print( 'No child handled click' ) if button == Mouse.Button.Left then return self:OnClick() elseif button == Mouse.Button.Right then return self:OnAlternateClick() end end end function Widget:MouseMove( x, y ) print( self.name .. ' Mouse moved', x, y ) if self.rect:isInside( x, y ) then print( ' Inside ' .. self.name ) if self.hover == false then self.hover = true self:OnHover() end for k, v in pairs( self.children ) do v:MouseMove( x, y ) end else print( ' Outside ' .. self.name ) if self.hover == true then self.hover = false self:OnHoverExit() for k, v in pairs( self.children ) do v:MouseLost() end end end end -- Simpler, faster, version of MouseMove that assumes -- that as the mouse is outside the parent widget, it is -- outside this widget, and therefor the mouse is lost. -- function Widget:MouseLost() print( self.name .. ' has lost the mouse.' ) if self.hover then self.hover = false self:OnHoverExit() for k, v in pairs( self.children ) do v:MouseLost() end end end -- Add a child widget. Child widgets should fit inside their parents -- for the mouse targetting to work correctly. -- function Widget:AddChild( child ) if type( child.MouseMove ) == 'function' then -- Very basic check table.insert( self.children, child ) else error( 'Not a valid type of Widget!' ) end end -- A Push Button Widget. Button = {} Button.__index = Button Button.__base = Widget setmetatable( Button, Widget ) function Button:init( x, y, text ) Button.__base.init( self, x, y, 100, 50, 'Button ' .. text ) self.text = text end -- Override default Widget methods to give default Button actions! function Button:OnAction() print( self.name .. " I've been activated!" ) return true -- Event handled end function Button:OnHover() print( self.name .. ' Light up' ) end function Button:OnHoverExit() print( self.name .. ' Extinguished!' ) end function Button.Create( x, y, text ) local btn = {} setmetatable( btn, Button ) btn:init( x, y, text ) return btn end -- A dialog box widget to hold buttons. -- DialogBox = {} DialogBox.__index = DialogBox DialogBox.__base = Widget setmetatable( DialogBox, Widget ) function DialogBox.Create( x, y, w, h, title ) local dlg = {} setmetatable( dlg, DialogBox ) dlg:init( x, y, w, h, 'DialogBox ' .. title ) return dlg end ------------------------------------------------------------------------------- function test() -- A dilog box with two buttons. mybox = DialogBox( 10, 10, 500, 300, '"Save Game?"' ) ok = Button( 20, 150, 'Ok' ) cancel = Button( 150, 150, 'Cancel' ) mybox:AddChild( ok ) mybox:AddChild( cancel ) print ( 'User moves outside dialog box' ) mybox:MouseMove( 5, 5 ) print( '-------------------------------------' ) print ( 'User moves mouse over "ok"' ) mybox:MouseMove( 22, 153 ) print( '-------------------------------------' ) print ( 'User moves to "cancel"' ) mybox:MouseMove( 155, 156 ) print( '-------------------------------------' ) print ( 'User clicks left button' ) mybox:MouseClick( Mouse.Button.Left, 156, 154 ) print( '-------------------------------------' ) end
Fix Rectangle params
Fix Rectangle params
Lua
mit
wmAndym/LuaBridgeTest,wmAndym/LuaBridgeTest
f8ea8fc0fc290b7247ba7b4edcd1a57b8788c296
lua/entities/gmod_wire_plug.lua
lua/entities/gmod_wire_plug.lua
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Plug" ENT.Author = "Divran" ENT.Purpose = "Links with a socket" ENT.Instructions = "Move a plug close to a socket to link them, and data will be transferred through the link." ENT.WireDebugName = "Plug" local base = scripted_ents.Get("base_wire_entity") function ENT:GetSocketClass() return "gmod_wire_socket" end function ENT:GetClosestSocket() local sockets = ents.FindInSphere( self:GetPos(), 100 ) local ClosestDist local Closest for k,v in pairs( sockets ) do if (v:GetClass() == self:GetSocketClass() and not v:GetNWBool( "Linked", false )) then local pos, _ = v:GetLinkPos() local Dist = self:GetPos():Distance( pos ) if (ClosestDist == nil or ClosestDist > Dist) then ClosestDist = Dist Closest = v end end end return Closest end if CLIENT then function ENT:DrawEntityOutline() if (GetConVar("wire_plug_drawoutline"):GetBool()) then base.DrawEntityOutline( self ) end end return -- No more client end ------------------------------------------------------------ -- Helper functions & variables ------------------------------------------------------------ local LETTERS = { "A", "B", "C", "D", "E", "F", "G", "H" } local LETTERS_INV = {} for k,v in pairs( LETTERS ) do LETTERS_INV[v] = k end function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self:SetNWBool( "Linked", false ) self.Memory = {} end function ENT:Setup( ArrayInput ) self.ArrayInput = ArrayInput or false if not (self.Inputs and self.Outputs) then if (self.ArrayInput) then self.Inputs = WireLib.CreateInputs( self, { "In [ARRAY]" } ) self.Outputs = WireLib.CreateOutputs( self, { "Out [ARRAY]" } ) else self.Inputs = WireLib.CreateInputs( self, LETTERS ) self.Outputs = WireLib.CreateOutputs( self, LETTERS ) end end self:ShowOutput() end function ENT:TriggerInput( name, value ) if (self.Socket and self.Socket:IsValid()) then self.Socket:SetValue( name, value ) end self:ShowOutput() end function ENT:SetValue( name, value ) if not (self.Socket and self.Socket:IsValid()) then return end if (name == "In") then if (self.ArrayInput) then -- Both have array WireLib.TriggerOutput( self, "Out", table.Copy( value ) ) else -- Target has array, this does not for i=1,#LETTERS do local val = (value or {})[i] if isnumber(val) then WireLib.TriggerOutput( self, LETTERS[i], val ) end end end else if (self.ArrayInput) then -- Target does not have array, this does if (value ~= nil) then local data = table.Copy( self.Outputs.Out.Value ) data[LETTERS_INV[name]] = value WireLib.TriggerOutput( self, "Out", data ) end else -- Niether have array if (value ~= nil) then WireLib.TriggerOutput( self, name, value ) end end end self:ShowOutput() end ------------------------------------------------------------ -- WriteCell -- Hi-speed support ------------------------------------------------------------ function ENT:WriteCell( Address, Value, WriteToMe ) if (WriteToMe) then self.Memory[Address or 1] = Value or 0 return true else if (self.Socket and self.Socket:IsValid()) then self.Socket:WriteCell( Address, Value, true ) return true else return false end end end ------------------------------------------------------------ -- ReadCell -- Hi-speed support ------------------------------------------------------------ function ENT:ReadCell( Address ) return self.Memory[Address or 1] or 0 end function ENT:Think() base.Think( self ) self:SetNWBool( "PlayerHolding", self:IsPlayerHolding() ) end function ENT:ResetValues() if (self.ArrayInput) then WireLib.TriggerOutput( self, "Out", {} ) else for i=1,#LETTERS do WireLib.TriggerOutput( self, LETTERS[i], 0 ) end end self.Memory = {} self:ShowOutput() end ------------------------------------------------------------ -- ResendValues -- Resends the values when plugging in ------------------------------------------------------------ function ENT:ResendValues() if (not self.Socket) then return end if (self.ArrayInput) then self.Socket:SetValue( "In", self.Inputs.In.Value ) else for i=1,#LETTERS do self.Socket:SetValue( LETTERS[i], self.Inputs[LETTERS[i]].Value ) end end end function ENT:ShowOutput() local OutText = "Plug [" .. self:EntIndex() .. "]\n" if (self.ArrayInput) then OutText = OutText .. "Array input/outputs." else OutText = OutText .. "Number input/outputs." end if (self.Socket and self.Socket:IsValid()) then OutText = OutText .. "\nLinked to socket [" .. self.Socket:EntIndex() .. "]" end self:SetOverlayText(OutText) end duplicator.RegisterEntityClass( "gmod_wire_plug", WireLib.MakeWireEnt, "Data", "ArrayInput" ) function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID) if (info.Plug ~= nil) then ent:Setup( info.Plug.ArrayInput ) end base.ApplyDupeInfo(self, ply, ent, info, GetEntByID) end
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Plug" ENT.Author = "Divran" ENT.Purpose = "Links with a socket" ENT.Instructions = "Move a plug close to a socket to link them, and data will be transferred through the link." ENT.WireDebugName = "Plug" local base = scripted_ents.Get("base_wire_entity") function ENT:GetSocketClass() return "gmod_wire_socket" end function ENT:GetClosestSocket() local sockets = ents.FindInSphere( self:GetPos(), 100 ) local ClosestDist local Closest for k,v in pairs( sockets ) do if (v:GetClass() == self:GetSocketClass() and not v:GetNWBool( "Linked", false )) then local pos, _ = v:GetLinkPos() local Dist = self:GetPos():Distance( pos ) if (ClosestDist == nil or ClosestDist > Dist) then ClosestDist = Dist Closest = v end end end return Closest end if CLIENT then function ENT:DrawEntityOutline() if (GetConVar("wire_plug_drawoutline"):GetBool()) then base.DrawEntityOutline( self ) end end return -- No more client end ------------------------------------------------------------ -- Helper functions & variables ------------------------------------------------------------ local LETTERS = { "A", "B", "C", "D", "E", "F", "G", "H" } local LETTERS_INV = {} for k,v in pairs( LETTERS ) do LETTERS_INV[v] = k end function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self:SetNWBool( "Linked", false ) self.Memory = {} end function ENT:Setup( ArrayInput ) local old = self.ArrayInput self.ArrayInput = ArrayInput or false if not (self.Inputs and self.Outputs and self.ArrayInput == old) then if (self.ArrayInput) then self.Inputs = WireLib.CreateInputs( self, { "In [ARRAY]" } ) self.Outputs = WireLib.CreateOutputs( self, { "Out [ARRAY]" } ) else self.Inputs = WireLib.CreateInputs( self, LETTERS ) self.Outputs = WireLib.CreateOutputs( self, LETTERS ) end end self:ShowOutput() end function ENT:TriggerInput( name, value ) if (self.Socket and self.Socket:IsValid()) then self.Socket:SetValue( name, value ) end self:ShowOutput() end function ENT:SetValue( name, value ) if not (self.Socket and self.Socket:IsValid()) then return end if (name == "In") then if (self.ArrayInput) then -- Both have array WireLib.TriggerOutput( self, "Out", table.Copy( value ) ) else -- Target has array, this does not for i=1,#LETTERS do local val = (value or {})[i] if isnumber(val) then WireLib.TriggerOutput( self, LETTERS[i], val ) end end end else if (self.ArrayInput) then -- Target does not have array, this does if (value ~= nil) then local data = table.Copy( self.Outputs.Out.Value ) data[LETTERS_INV[name]] = value WireLib.TriggerOutput( self, "Out", data ) end else -- Niether have array if (value ~= nil) then WireLib.TriggerOutput( self, name, value ) end end end self:ShowOutput() end ------------------------------------------------------------ -- WriteCell -- Hi-speed support ------------------------------------------------------------ function ENT:WriteCell( Address, Value, WriteToMe ) if (WriteToMe) then self.Memory[Address or 1] = Value or 0 return true else if (self.Socket and self.Socket:IsValid()) then self.Socket:WriteCell( Address, Value, true ) return true else return false end end end ------------------------------------------------------------ -- ReadCell -- Hi-speed support ------------------------------------------------------------ function ENT:ReadCell( Address ) return self.Memory[Address or 1] or 0 end function ENT:Think() base.Think( self ) self:SetNWBool( "PlayerHolding", self:IsPlayerHolding() ) end function ENT:ResetValues() if (self.ArrayInput) then WireLib.TriggerOutput( self, "Out", {} ) else for i=1,#LETTERS do WireLib.TriggerOutput( self, LETTERS[i], 0 ) end end self.Memory = {} self:ShowOutput() end ------------------------------------------------------------ -- ResendValues -- Resends the values when plugging in ------------------------------------------------------------ function ENT:ResendValues() if (not self.Socket) then return end if (self.ArrayInput) then self.Socket:SetValue( "In", self.Inputs.In.Value ) else for i=1,#LETTERS do self.Socket:SetValue( LETTERS[i], self.Inputs[LETTERS[i]].Value ) end end end function ENT:ShowOutput() local OutText = "Plug [" .. self:EntIndex() .. "]\n" if (self.ArrayInput) then OutText = OutText .. "Array input/outputs." else OutText = OutText .. "Number input/outputs." end if (self.Socket and self.Socket:IsValid()) then OutText = OutText .. "\nLinked to socket [" .. self.Socket:EntIndex() .. "]" end self:SetOverlayText(OutText) end duplicator.RegisterEntityClass( "gmod_wire_plug", WireLib.MakeWireEnt, "Data", "ArrayInput" ) function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID) if (info.Plug ~= nil) then ent:Setup( info.Plug.ArrayInput ) end base.ApplyDupeInfo(self, ply, ent, info, GetEntByID) end
Fixed undefined variable "old"
Fixed undefined variable "old"
Lua
apache-2.0
garrysmodlua/wire,bigdogmat/wire,sammyt291/wire,wiremod/wire,NezzKryptic/Wire,dvdvideo1234/wire,Grocel/wire,thegrb93/wire
19f77d553c90920edf8274c627667a30d72c91de
src/plugins/core/scripting/preferences.lua
src/plugins/core/scripting/preferences.lua
--- === plugins.core.scripting.preferences === --- --- Scripting Preferences. local require = require local hs = hs local dialog = require("hs.dialog") local ipc = require("hs.ipc") local timer = require("hs.timer") local config = require("cp.config") local html = require("cp.web.html") local i18n = require("cp.i18n") local execute = hs.execute local allowAppleScript = hs.allowAppleScript -------------------------------------------------------------------------------- -- -- THE MODULE: -- -------------------------------------------------------------------------------- local mod = {} -- getCommandLineToolTitle() -> string -- Function -- Returns either "Install" or "Uninstall" as a string. -- -- Parameters: -- * None -- -- Returns: -- * A string local function getCommandLineToolTitle() local cliStatus = ipc.cliStatus() if cliStatus then return i18n("uninstall") else return i18n("install") end end -- updatePreferences() -> none -- Function -- Updates the Preferences Panel UI. -- -- Parameters: -- * None -- -- Returns: -- * None local function updatePreferences() mod.manager.injectScript([[changeCheckedByID('commandLineTool', ]] .. tostring(ipc.cliStatus(nil, true)) .. [[);]]) -------------------------------------------------------------------------------- -- Sometimes it takes a little while to uninstall the CLI: -------------------------------------------------------------------------------- timer.doAfter(0.5, function() mod.manager.injectScript([[changeCheckedByID('commandLineTool', ]] .. tostring(ipc.cliStatus(nil, true)) .. [[);]]) end) end -- toggleCommandLineTool() -> none -- Function -- Toggles the Command Line Tool -- -- Parameters: -- * None -- -- Returns: -- * None local function toggleCommandLineTool() local cliStatus = ipc.cliStatus() if cliStatus then ipc.cliUninstall() else ipc.cliInstall() end local newCliStatus = ipc.cliStatus() if cliStatus == newCliStatus then if cliStatus then dialog.webviewAlert(mod.manager.getWebview(), function() updatePreferences() end, i18n("cliUninstallError"), "", i18n("ok"), nil, "informational") else dialog.webviewAlert(mod.manager.getWebview(), function() updatePreferences() end, i18n("cliInstallError"), "", i18n("ok"), nil, "informational") end else updatePreferences() end end -------------------------------------------------------------------------------- -- -- THE PLUGIN: -- -------------------------------------------------------------------------------- local plugin = { id = "core.preferences.advanced", group = "core", dependencies = { ["core.preferences.manager"] = "manager", ["core.preferences.panels.scripting"] = "scripting", } } function plugin.init(deps) mod.manager = deps.manager local scripting = deps.scripting scripting -------------------------------------------------------------------------------- -- Command Line Tool: -------------------------------------------------------------------------------- :addHeading(1, i18n("scriptingTools")) :addCheckbox(2, { label = i18n("enableCommandLineSupport"), checked = function() return ipc.cliStatus() end, onchange = toggleCommandLineTool, id = "commandLineTool", } ) -------------------------------------------------------------------------------- -- AppleScript: -------------------------------------------------------------------------------- :addCheckbox(3, { label = i18n("enableAppleScriptSupport"), checked = function() return allowAppleScript() end, onchange = function() local value = allowAppleScript() allowAppleScript(not value) end, } ) -------------------------------------------------------------------------------- -- Learn More Button: -------------------------------------------------------------------------------- :addContent(4, [[<br />]], false) :addButton(5, { label = "Learn More...", width = 100, onclick = function() execute("open 'https://help.commandpost.io/advanced/controlling_commandpost'") end, } ) end return plugin
--- === plugins.core.scripting.preferences === --- --- Scripting Preferences. local require = require local hs = hs local dialog = require("hs.dialog") local ipc = require("hs.ipc") local timer = require("hs.timer") local i18n = require("cp.i18n") local execute = hs.execute local allowAppleScript = hs.allowAppleScript -------------------------------------------------------------------------------- -- -- THE MODULE: -- -------------------------------------------------------------------------------- local mod = {} -- updatePreferences() -> none -- Function -- Updates the Preferences Panel UI. -- -- Parameters: -- * None -- -- Returns: -- * None local function updatePreferences() mod.manager.injectScript([[changeCheckedByID('commandLineTool', ]] .. tostring(ipc.cliStatus(nil, true)) .. [[);]]) -------------------------------------------------------------------------------- -- Sometimes it takes a little while to uninstall the CLI: -------------------------------------------------------------------------------- timer.doAfter(0.5, function() mod.manager.injectScript([[changeCheckedByID('commandLineTool', ]] .. tostring(ipc.cliStatus(nil, true)) .. [[);]]) end) end -- toggleCommandLineTool() -> none -- Function -- Toggles the Command Line Tool -- -- Parameters: -- * None -- -- Returns: -- * None local function toggleCommandLineTool() local cliStatus = ipc.cliStatus() if cliStatus then ipc.cliUninstall() else ipc.cliInstall() end local newCliStatus = ipc.cliStatus() if cliStatus == newCliStatus then if cliStatus then dialog.webviewAlert(mod.manager.getWebview(), function() updatePreferences() end, i18n("cliUninstallError"), "", i18n("ok"), nil, "informational") else dialog.webviewAlert(mod.manager.getWebview(), function() updatePreferences() end, i18n("cliInstallError"), "", i18n("ok"), nil, "informational") end else updatePreferences() end end -------------------------------------------------------------------------------- -- -- THE PLUGIN: -- -------------------------------------------------------------------------------- local plugin = { id = "core.preferences.advanced", group = "core", dependencies = { ["core.preferences.manager"] = "manager", ["core.preferences.panels.scripting"] = "scripting", } } function plugin.init(deps) mod.manager = deps.manager local scripting = deps.scripting scripting -------------------------------------------------------------------------------- -- Command Line Tool: -------------------------------------------------------------------------------- :addHeading(1, i18n("scriptingTools")) :addCheckbox(2, { label = i18n("enableCommandLineSupport"), checked = function() return ipc.cliStatus() end, onchange = toggleCommandLineTool, id = "commandLineTool", } ) -------------------------------------------------------------------------------- -- AppleScript: -------------------------------------------------------------------------------- :addCheckbox(3, { label = i18n("enableAppleScriptSupport"), checked = function() return allowAppleScript() end, onchange = function() local value = allowAppleScript() allowAppleScript(not value) end, } ) -------------------------------------------------------------------------------- -- Learn More Button: -------------------------------------------------------------------------------- :addContent(4, [[<br />]], false) :addButton(5, { label = "Learn More...", width = 100, onclick = function() execute("open 'https://help.commandpost.io/advanced/controlling_commandpost'") end, } ) end return plugin
#1692
#1692 - Fixed @stickler-ci errors
Lua
mit
fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost
8f44f417d5b17106312f5aafd4c62a5c934d02b1
examples/test-dns.lua
examples/test-dns.lua
local p = require('lib/utils').prettyPrint local uv = require('luv') uv.getaddrinfo(nil, 80, nil, p) local domains = { "facebook.com", "google.com", "mail.google.com", "maps.google.com", "plus.google.com", "play.google.com", "apple.com", "hp.com", "yahoo.com", "mozilla.com", "developer.mozilla.com", "luvit.io", "creationix.com", "howtonode.org", "github.com", "gist.github.com" } local i = 1 local function next() uv.getaddrinfo(domains[i], nil, { v4mapped = true, all = true, addrconfig = true, canonname = true, numericserv = true, socktype = "STREAM" }, function (data) p(data) i = i + 1 if i <= #domains then next() end end) end next(); repeat print("\nTick..") until uv.run('once') == 0 print("done")
local p = require('lib/utils').prettyPrint local uv = require('luv') uv.getaddrinfo(nil, 80, nil, p) local domains = { "facebook.com", "google.com", "mail.google.com", "maps.google.com", "plus.google.com", "play.google.com", "apple.com", "hp.com", "yahoo.com", "mozilla.com", "developer.mozilla.com", "luvit.io", "creationix.com", "howtonode.org", "github.com", "gist.github.com" } local i = 1 local function next() uv.getaddrinfo(domains[i], nil, { v4mapped = true, all = true, addrconfig = true, canonname = true, numericserv = true, socktype = "stream" }, function (err, data) assert(not err, err) p(data) i = i + 1 if i <= #domains then next() end end) end next(); repeat print("\nTick..") until uv.run('once') == 0 print("done")
Fix dns example
Fix dns example
Lua
apache-2.0
daurnimator/luv,mkschreder/luv,kidaa/luv,daurnimator/luv,zhaozg/luv,NanXiao/luv,joerg-krause/luv,joerg-krause/luv,brimworks/luv,brimworks/luv,RomeroMalaquias/luv,daurnimator/luv,DBarney/luv,NanXiao/luv,RomeroMalaquias/luv,kidaa/luv,leecrest/luv,luvit/luv,luvit/luv,xpol/luv,xpol/luv,RomeroMalaquias/luv,DBarney/luv,zhaozg/luv,leecrest/luv,mkschreder/luv
4c9e9125dea52b1296e096e13812c04b4d3fd637
lib/luvit/luvit.lua
lib/luvit/luvit.lua
--[[ Copyright 2012 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] -- Bootstrap require system local native = require('uv_native') process = { execPath = native.execpath(), cwd = getcwd, argv = argv } _G.getcwd = nil _G.argv = nil require = require('module').require local Emitter = require('core').Emitter local env = require('env') local constants = require('constants') local uv = require('uv') local utils = require('utils') setmetatable(process, Emitter.meta) -- Replace lua's stdio with luvit's -- leave stderr using lua's blocking implementation process.stdin = uv.createReadableStdioStream(0) process.stdout = uv.createWriteableStdioStream(1) process.stderr = uv.createWriteableStdioStream(2) -- clear some globals -- This will break lua code written for other lua runtimes _G.io = nil _G.os = nil _G.math = nil _G.string = nil _G.coroutine = nil _G.jit = nil _G.bit = nil _G.debug = nil _G.table = nil _G.loadfile = nil _G.dofile = nil _G.print = utils.print _G.p = utils.prettyPrint _G.debug = utils.debug -- Move the version variables into a table process.version = VERSION process.versions = { luvit = VERSION, uv = native.VERSION_MAJOR .. "." .. native.VERSION_MINOR .. "-" .. UV_VERSION, luajit = LUAJIT_VERSION, yajl = YAJL_VERSION, http_parser = HTTP_VERSION, } _G.VERSION = nil _G.YAJL_VERSION = nil _G.LUAJIT_VERSION = nil _G.UV_VERSION = nil _G.HTTP_VERSION = nil -- Add a way to exit programs cleanly function process.exit(exit_code) process:emit('exit', exit_code) exitProcess(exit_code or 0) end function process:addHandlerType(name) local code = constants[name] if code then native.activateSignalHandler(code) native.unref() end end function process:missingHandlerType(name, ...) if name == "error" then error(...) elseif name == "SIGINT" or name == "SIGTERM" then process.exit() end end -- Add global access to the environment variables using a dynamic table process.env = setmetatable({}, { __pairs = function (table) local keys = env.keys() local index = 0 return function (...) index = index + 1 local name = keys[index] if name then return name, table[name] end end end, __index = function (table, name) return env.get(name) end, __newindex = function (table, name, value) if value then env.set(name, value, 1) else env.unset(name) end end }) -- Copy date and time over from lua os module into luvit os module local OLD_OS = require('os') local OS_BINDING = require('os_binding') package.loaded.os = OS_BINDING package.preload.os_binding = nil package.loaded.os_binding = nil OS_BINDING.date = OLD_OS.date OS_BINDING.time = OLD_OS.time -- Ignore sigpipe and exit cleanly on SIGINT and SIGTERM -- These shouldn't hold open the event loop if OS_BINDING.type() ~= "win32" then native.activateSignalHandler(constants.SIGPIPE) native.unref() native.activateSignalHandler(constants.SIGINT) native.unref() native.activateSignalHandler(constants.SIGTERM) native.unref() end local traceback = require('debug').traceback -- This is called by all the event sources from C -- The user can override it to hook into event sources function eventSource(name, fn, ...) local args = {...} return assert(xpcall(function () return fn(unpack(args)) end, traceback)) end local function usage() print("Usage: " .. process.argv[0] .. " [options] script.lua [arguments]") print("") print("Options:") print(" -h, --help Print this help screen.") print(" -v, --version Print the version.") print(" -e code_chunk Evaluate code chunk and print result.") print(" -i, --interactive Enter interactive repl after executing script.") print(" (Note, if no script is provided, a repl is run instead.)") print("") end local realAssert = assert function assert(good, error) return realAssert(good, tostring(error)) end assert(xpcall(function () local interactive = false local showrepl = true local file local state = "BEGIN" local to_eval = {} local args = {[0]=process.argv[0]} for i, value in ipairs(process.argv) do if state == "BEGIN" then if value == "-h" or value == "--help" then usage() showrepl = false elseif value == "-v" or value == "--version" then print(process.version) showrepl = false elseif value == "-e" or value == "--eval" then state = "-e" showrepl = false elseif value == "-i" or value == "--interactive" then interactive = true elseif value:sub(1, 1) == "-" then usage() process.exit(1) else file = value showrepl = false state = "USERSPACE" end elseif state == "-e" then to_eval[#to_eval + 1] = value state = "BEGIN" elseif state == "USERSPACE" then args[#args + 1] = value end end if not (state == "BEGIN" or state == "USERSPACE") then usage() process.exit(1) end process.argv = args local repl = require('repl') for i, value in ipairs(to_eval) do repl.evaluateLine(value) end if file then assert(require('module').myloadfile(require('path').resolve(process.cwd(), file)))() elseif not (native.handleType(0) == "TTY") then process.stdin:on("data", function(line) repl.evaluateLine(line) end) process.stdin:readStart() native.run() process.exit(0) end if interactive or showrepl then repl.start() end end, traceback)) -- Start the event loop native.run() -- trigger exit handlers and exit cleanly process.exit(0)
--[[ Copyright 2012 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] -- Bootstrap require system local native = require('uv_native') process = { execPath = native.execpath(), cwd = getcwd, argv = argv } _G.getcwd = nil _G.argv = nil require = require('module').require local Emitter = require('core').Emitter local env = require('env') local constants = require('constants') local uv = require('uv') local utils = require('utils') setmetatable(process, Emitter.meta) -- Replace lua's stdio with luvit's -- leave stderr using lua's blocking implementation process.stdin = uv.createReadableStdioStream(0) process.stdout = uv.createWriteableStdioStream(1) process.stderr = uv.createWriteableStdioStream(2) -- clear some globals -- This will break lua code written for other lua runtimes _G.io = nil _G.os = nil _G.math = nil _G.string = nil _G.coroutine = nil _G.jit = nil _G.bit = nil _G.debug = nil _G.table = nil _G.loadfile = nil _G.dofile = nil _G.print = utils.print _G.p = utils.prettyPrint _G.debug = utils.debug -- Move the version variables into a table process.version = VERSION process.versions = { luvit = VERSION, uv = native.VERSION_MAJOR .. "." .. native.VERSION_MINOR .. "-" .. UV_VERSION, luajit = LUAJIT_VERSION, yajl = YAJL_VERSION, http_parser = HTTP_VERSION, } _G.VERSION = nil _G.YAJL_VERSION = nil _G.LUAJIT_VERSION = nil _G.UV_VERSION = nil _G.HTTP_VERSION = nil -- Add a way to exit programs cleanly function process.exit(exit_code) process:emit('exit', exit_code) exitProcess(exit_code or 0) end function process:addHandlerType(name) local code = constants[name] if code then native.activateSignalHandler(code) native.unref() end end function process:missingHandlerType(name, ...) if name == "error" then error(...) elseif name == "SIGINT" or name == "SIGTERM" then process.exit() end end -- Add global access to the environment variables using a dynamic table process.env = setmetatable({}, { __pairs = function (table) local keys = env.keys() local index = 0 return function (...) index = index + 1 local name = keys[index] if name then return name, table[name] end end end, __index = function (table, name) return env.get(name) end, __newindex = function (table, name, value) if value then env.set(name, value, 1) else env.unset(name) end end }) -- Copy date and time over from lua os module into luvit os module local OLD_OS = require('os') local OS_BINDING = require('os_binding') package.loaded.os = OS_BINDING package.preload.os_binding = nil package.loaded.os_binding = nil OS_BINDING.date = OLD_OS.date OS_BINDING.time = OLD_OS.time -- Ignore sigpipe and exit cleanly on SIGINT and SIGTERM -- These shouldn't hold open the event loop if OS_BINDING.type() ~= "win32" then native.activateSignalHandler(constants.SIGPIPE) native.unref() native.activateSignalHandler(constants.SIGINT) native.unref() native.activateSignalHandler(constants.SIGTERM) native.unref() end local traceback = require('debug').traceback -- This is called by all the event sources from C -- The user can override it to hook into event sources function eventSource(name, fn, ...) local args = {...} return assert(xpcall(function () return fn(unpack(args)) end, traceback)) end local function usage() print("Usage: " .. process.argv[0] .. " [options] script.lua [arguments]") print("") print("Options:") print(" -h, --help Print this help screen.") print(" -v, --version Print the version.") print(" -e code_chunk Evaluate code chunk and print result.") print(" -i, --interactive Enter interactive repl after executing script.") print(" (Note, if no script is provided, a repl is run instead.)") print("") end local realAssert = assert function assert(good, error) return realAssert(good, tostring(error)) end assert(xpcall(function () local interactive = false local showrepl = true local file local state = "BEGIN" local to_eval = {} local args = {[0]=process.argv[0]} for i, value in ipairs(process.argv) do if state == "BEGIN" then if value == "-h" or value == "--help" then usage() showrepl = false elseif value == "-v" or value == "--version" then print(process.version) showrepl = false elseif value == "-e" or value == "--eval" then state = "-e" showrepl = false elseif value == "-i" or value == "--interactive" then interactive = true elseif value:sub(1, 1) == "-" then usage() process.exit(1) else file = value showrepl = false state = "USERSPACE" end elseif state == "-e" then to_eval[#to_eval + 1] = value state = "BEGIN" elseif state == "USERSPACE" then args[#args + 1] = value end end if not (state == "BEGIN" or state == "USERSPACE") then usage() process.exit(1) end process.argv = args local repl = require('repl') for i, value in ipairs(to_eval) do repl.evaluateLine(value) end if file then assert(require('module').myloadfile(require('path').resolve(process.cwd(), file)))() elseif not (native.handleType(0) == "TTY") then process.stdin:on("data", function(line) repl.evaluateLine(line) end) process.stdin:readStart() native.run() process.exit(0) end if interactive or showrepl then if OS_BINDING.type() == "win32" then native.ref() end repl.start() end end, traceback)) -- Start the event loop native.run() -- trigger exit handlers and exit cleanly process.exit(0)
HACK: fix repl on windows
HACK: fix repl on windows the event loop for windows needs to be incremented from zero in order to not exit the loop immediatly. How does this work under Linux? Under Linux ev seems to keep the loop at 1 from the start..
Lua
apache-2.0
GabrielNicolasAvellaneda/luvit-upstream,bsn069/luvit,boundary/luvit,DBarney/luvit,AndrewTsao/luvit,bsn069/luvit,rjeli/luvit,zhaozg/luvit,sousoux/luvit,kaustavha/luvit,GabrielNicolasAvellaneda/luvit-upstream,rjeli/luvit,connectFree/lev,AndrewTsao/luvit,sousoux/luvit,GabrielNicolasAvellaneda/luvit-upstream,connectFree/lev,DBarney/luvit,GabrielNicolasAvellaneda/luvit-upstream,sousoux/luvit,sousoux/luvit,luvit/luvit,sousoux/luvit,luvit/luvit,kaustavha/luvit,zhaozg/luvit,kaustavha/luvit,DBarney/luvit,sousoux/luvit,rjeli/luvit,boundary/luvit,boundary/luvit,rjeli/luvit,boundary/luvit,bsn069/luvit,boundary/luvit,boundary/luvit,AndrewTsao/luvit,DBarney/luvit
290c8e0214be3c9f5814e12515c26c7531310760
mod_host_guard/mod_host_guard.lua
mod_host_guard/mod_host_guard.lua
-- (C) 2011, Marco Cirillo (LW.Org) -- Block or restrict by blacklist remote access to local components or hosts. module:set_global() local guard_blockall = module:get_option_set("host_guard_blockall", {}) local guard_ball_wl = module:get_option_set("host_guard_blockall_exceptions", {}) local guard_protect = module:get_option_set("host_guard_selective", {}) local guard_block_bl = module:get_option_set("host_guard_blacklist", {}) local s2smanager = require "core.s2smanager" local config = require "core.configmanager" local nameprep = require "util.encodings".stringprep.nameprep local _make_connect = s2smanager.make_connect function s2smanager.make_connect(session, connect_host, connect_port) if not session.s2sValidation then if guard_blockall:contains(session.from_host) and not guard_ball_wl:contains(session.to_host) or guard_block_bl:contains(session.to_host) and guard_protect:contains(session.from_host) then module:log("error", "remote service %s attempted to access restricted host %s", session.to_host, session.from_host) s2smanager.destroy_session(session, "You're not authorized, good bye.") return false; end end return _make_connect(session, connect_host, connect_port) end local _stream_opened = s2smanager.streamopened function s2smanager.streamopened(session, attr) local host = attr.to and nameprep(attr.to) local from = attr.from and nameprep(attr.from) if not from then session.s2sValidation = false else session.s2sValidation = true end if guard_blockall:contains(host) and not guard_ball_wl:contains(from) or guard_block_bl:contains(from) and guard_protect:contains(host) then module:log("error", "remote service %s attempted to access restricted host %s", from, host) session:close({condition = "policy-violation", text = "You're not authorized, good bye."}) return false; end _stream_opened(session, attr) end local function sdr_hook (event) local origin, stanza = event.origin, event.stanza if origin.type == "s2sin" or origin.type == "s2sin_unauthed" then if guard_blockall:contains(stanza.attr.to) and not guard_ball_wl:contains(stanza.attr.from) or guard_block_bl:contains(stanza.attr.from) and guard_protect:contains(stanza.attr.to) then module:log("error", "remote service %s attempted to access restricted host %s", stanza.attr.from, stanza.attr.to) origin:close({condition = "policy-violation", text = "You're not authorized, good bye."}) return false end end return nil end local function handle_activation (host) if guard_blockall:contains(host) or guard_protect:contains(host) then if hosts[host] and hosts[host].events then hosts[host].events.add_handler("stanza/jabber:server:dialback:result", sdr_hook, 100) module:log ("debug", "adding host protection for: "..host) end end end local function handle_deactivation (host) if guard_blockall:contains(host) or guard_protect:contains(host) then if hosts[host] and hosts[host].events then hosts[host].events.remove_handler("stanza/jabber:server:dialback:result", sdr_hook) module:log ("debug", "removing host protection for: "..host) end end end local function reload() module:log ("debug", "server configuration reloaded, rehashing plugin tables...") guard_blockall = module:get_option_set("host_guard_blockall", {}) guard_ball_wl = module:get_option_set("host_guard_blockall_exceptions", {}) guard_protect = module:get_option_set("host_guard_components", {}) guard_block_bl = module:get_option_set("host_guard_blacklist", {}) end local function setup() module:log ("debug", "initializing host guard module...") module:hook ("component-activated", handle_activation) module:hook ("component-deactivated", handle_deactivation) module:hook ("config-reloaded", reload) for n,table in pairs(hosts) do if table.type == "component" then if guard_blockall:contains(n) or guard_protect:contains(n) then hosts[n].events.remove_handler("stanza/jabber:server:dialback:result", sdr_hook) handle_activation(n) end end end end if prosody.start_time then setup() else module:hook ("server-started", setup) end
-- (C) 2011, Marco Cirillo (LW.Org) -- Block or restrict by blacklist remote access to local components or hosts. module:set_global() local guard_blockall = module:get_option_set("host_guard_blockall", {}) local guard_ball_wl = module:get_option_set("host_guard_blockall_exceptions", {}) local guard_protect = module:get_option_set("host_guard_selective", {}) local guard_block_bl = module:get_option_set("host_guard_blacklist", {}) local s2smanager = require "core.s2smanager" local config = require "core.configmanager" local nameprep = require "util.encodings".stringprep.nameprep local _make_connect = s2smanager.make_connect function s2smanager.make_connect(session, connect_host, connect_port) if not session.s2sValidation then if guard_blockall:contains(session.from_host) and not guard_ball_wl:contains(session.to_host) or guard_block_bl:contains(session.to_host) and guard_protect:contains(session.from_host) then module:log("error", "remote service %s attempted to access restricted host %s", session.to_host, session.from_host) s2smanager.destroy_session(session, "You're not authorized, good bye.") return false; end end return _make_connect(session, connect_host, connect_port) end local _stream_opened = s2smanager.streamopened function s2smanager.streamopened(session, attr) local host = attr.to and nameprep(attr.to) local from = attr.from and nameprep(attr.from) if not from then session.s2sValidation = false else session.s2sValidation = true end if guard_blockall:contains(host) and not guard_ball_wl:contains(from) or guard_block_bl:contains(from) and guard_protect:contains(host) then module:log("error", "remote service %s attempted to access restricted host %s", from, host) session:close({condition = "policy-violation", text = "You're not authorized, good bye."}) return false; end _stream_opened(session, attr) end local function sdr_hook (event) local origin, stanza = event.origin, event.stanza if origin.type == "s2sin" or origin.type == "s2sin_unauthed" then if guard_blockall:contains(stanza.attr.to) and not guard_ball_wl:contains(stanza.attr.from) or guard_block_bl:contains(stanza.attr.from) and guard_protect:contains(stanza.attr.to) then module:log("error", "remote service %s attempted to access restricted host %s", stanza.attr.from, stanza.attr.to) origin:close({condition = "policy-violation", text = "You're not authorized, good bye."}) return false end end return nil end local function handle_activation (host) if guard_blockall:contains(host) or guard_protect:contains(host) then if hosts[host] and hosts[host].events then hosts[host].events.add_handler("stanza/jabber:server:dialback:result", sdr_hook, 100) module:log ("debug", "adding host protection for: "..host) end end end local function handle_deactivation (host) if guard_blockall:contains(host) or guard_protect:contains(host) then if hosts[host] and hosts[host].events then hosts[host].events.remove_handler("stanza/jabber:server:dialback:result", sdr_hook) module:log ("debug", "removing host protection for: "..host) end end end local function init_hosts() for n,table in pairs(hosts) do hosts[n].events.remove_handler("stanza/jabber:server:dialback:result", sdr_hook) if guard_blockall:contains(n) or guard_protect:contains(n) then handle_activation(n) end end end local function reload() module:log ("debug", "server configuration reloaded, rehashing plugin tables...") guard_blockall = module:get_option_set("host_guard_blockall", {}) guard_ball_wl = module:get_option_set("host_guard_blockall_exceptions", {}) guard_protect = module:get_option_set("host_guard_selective", {}) guard_block_bl = module:get_option_set("host_guard_blacklist", {}) init_hosts() end local function setup() module:log ("debug", "initializing host guard module...") module:hook ("host-activated", handle_activation) module:hook ("host-deactivated", handle_deactivation) module:hook ("config-reloaded", reload) init_hosts() end if prosody.start_time then setup() else module:hook ("server-started", setup) end
mod_host_guard: fixed plugin, minor code refactor.
mod_host_guard: fixed plugin, minor code refactor.
Lua
mit
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
3bd349301417ed09736b8ca3a8e461716bd2e4cc
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) ev.time = TimeVal:now() if ev.type == EV_ABS then -- 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
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) ev.time = TimeVal:now() if ev.type == EV_ABS then -- 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 Remarkable1:suspend() os.execute("systemctl suspend") end function Remarkable2:suspend() os.execute("systemctl suspend") -- While device is suspended, when the user presses the power button and wakes up the device, -- a "Power" event is NOT sent. -- So we schedule a manual `UIManager:resume` call just far enough in the future that it won't -- trigger before the `systemctl suspend` command finishes suspending the device local UIManager = require("ui/uimanager") UIManager:scheduleIn(0.5, function() UIManager:resume() end) 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
Fix double-pressing reMarkable 2 power button twice to wake up (#7065)
Fix double-pressing reMarkable 2 power button twice to wake up (#7065)
Lua
agpl-3.0
NiLuJe/koreader,Hzj-jie/koreader,pazos/koreader,koreader/koreader,Markismus/koreader,poire-z/koreader,Frenzie/koreader,poire-z/koreader,NiLuJe/koreader,mwoz123/koreader,Frenzie/koreader,koreader/koreader
00bfbba25768a37a60af805304c30eda3fe686e1
ProtoplugFiles/include/audiomath.lua
ProtoplugFiles/include/audiomath.lua
-- Support math and low level function to help with plugin development --[[ Functions added to math ------------------------------------------------------------------------------------ --]] -- Initialise the random number generator math.randomseed(os.time()) math.random(); math.random(); math.random() math.boxMuller = function() local U1 = math.random() local U2 = math.random() return math.sqrt(-2*math.log(U1))*math.cos(2*math.pi*U2), math.sqrt(-2*math.log(U1))*math.sin(2*math.pi*U2) end math.gaussianRandom = function(mean, stdDev) return math.boxMuller() * stdDev + mean end ---------------------------------------------------------------------------------------- --[[ Actual audioMath library ------------------------------------------------------------------------------------ --]] local audioMath = {} --Take a nunmber between 0 and 1 and map it exponentionally between low and high function audioMath.expRange(x, low, high) return (low-1) + math.pow(1+high-low, x) end function audioMath.midiToFreq(midiNote) return 440.0 * math.pow(2.0, (midiNote - 69)/12) end function audioMath.freqToMidi(freq) return math.floor(math.log(freq/440.0)/math.log(2) * 12 + 69) end --[[ Utility to add timed midi events, for sequencers etc ------------------------------------------------------------------------------------ --]] audioMath.MidiEventsQueue = { maxBlock = 2^14, currentBlock = 0, events = {}} function audioMath.MidiEventsQueue:registerEvent(event, sampleOffsetToCurrentBlock, blockSize) local blockOffset = math.floor(sampleOffsetToCurrentBlock / blockSize) local sampleOffset = sampleOffsetToCurrentBlock - blockOffset * blockSize event.time = sampleOffset local idx = (self.currentBlock + blockOffset) % self.maxBlock self.events[idx] = self.events[idx] or {} self.events[idx].list = self.events[idx].list or {} table.insert(self.events[idx].list, event) self.events[idx].lastEventTime = self.events[idx].lastEventTime or 0 if sampleOffset >= self.events[idx].lastEventTime then self.events[idx].lastEventTime = sampleOffset self.events[idx].lastEvent = event end end --This function has to be called in each processBlock ! function audioMath.MidiEventsQueue:playEvents(midiBuf) blockEvents = self.events[self.currentBlock] if blockEvents then for i, event in ipairs(blockEvents.list) do midiBuf:addEvent(event) --print(event) end end self.events[self.currentBlock] = nil self.currentBlock = (self.currentBlock + 1) % self.maxBlock end function audioMath.MidiEventsQueue:lastTimeEventInCurrentBlock() blockEvents = self.events[self.currentBlock] if blockEvents then return blockEvents.lastEventTime end return 0 end filters = require("include/filters") ffi = require("ffi") function audioMath.X2Upsampler() --A0 = filters.SecondOrderAllPassSection(0.1380) --A1 = filters.SecondOrderAllPassSection(0.5847) LPS = {} nbLP = 3 for i=1, nbLP do LPS[i] = filters.SecondOrderButterworthLP(0.25) end return function(inSamples, blockSize) --Note inSamples should be floats but -- doubles are supposedly more efficient in LuaJIT so we output that instead outSamples = ffi.new("double[?]", blockSize*2) --[[Polyphase IIR interpolation filter as per http://www.ensilica.com/wp-content/uploads/High_performance_IIR_filters_for_interpolation_and_decimation.pdf--]] for i=0, blockSize-1 do --outSamples[2*i] = A0(inSamples[i]) --outSamples[2*i+1] = A1(inSamples[i]) --Dumb way for now outSamples[2*i] = inSamples[i] outSamples[2*i+1] = 0 end --Dumb way for now for i=0, 2*blockSize-1 do for lp=1, nbLP do outSamples[i] = LPS[lp](outSamples[i]) end end return outSamples end end function audioMath.X2Downsampler() -- TODO ! check values are correct and cutoff still in the right place !? A0 = filters.SecondOrderAllPassSection(0.1380) A1 = filters.SecondOrderAllPassSection(0.5847) return function(inSamples, outSamples, blockSize) --[[Polyphase IIR interpolation filter as per http://www.ensilica.com/wp-content/uploads/High_performance_IIR_filters_for_interpolation_and_decimation.pdf--]] for i=0, blockSize-1 do outSamples[i] = 0.5 * (A0(inSamples[2*i]) + A1(inSamples[2*i+1])) end return outSamples end end return audioMath
-- Support math and low level function to help with plugin development --[[ Functions added to math ------------------------------------------------------------------------------------ --]] -- Initialise the random number generator math.randomseed(os.time()) math.random(); math.random(); math.random() math.boxMuller = function() local U1 = math.random() local U2 = math.random() return math.sqrt(-2*math.log(U1))*math.cos(2*math.pi*U2), math.sqrt(-2*math.log(U1))*math.sin(2*math.pi*U2) end math.gaussianRandom = function(mean, stdDev) return math.boxMuller() * stdDev + mean end ---------------------------------------------------------------------------------------- --[[ Actual audioMath library ------------------------------------------------------------------------------------ --]] local audioMath = {} --Take a nunmber between 0 and 1 and map it exponentionally between low and high function audioMath.expRange(x, low, high) return (low-1) + math.pow(1+high-low, x) end function audioMath.midiToFreq(midiNote) return 440.0 * math.pow(2.0, (midiNote - 69)/12) end function audioMath.freqToMidi(freq) return math.floor(math.log(freq/440.0)/math.log(2) * 12 + 69) end --[[ Utility to add timed midi events, for sequencers etc ------------------------------------------------------------------------------------ --]] audioMath.MidiEventsQueue = { maxBlock = 2^14, currentBlock = 0, events = {}} function audioMath.MidiEventsQueue:registerEvent(event, sampleOffsetToCurrentBlock, blockSize) local blockOffset = math.floor(sampleOffsetToCurrentBlock / blockSize) local sampleOffset = sampleOffsetToCurrentBlock - blockOffset * blockSize event.time = sampleOffset local idx = (self.currentBlock + blockOffset) % self.maxBlock self.events[idx] = self.events[idx] or {} self.events[idx].list = self.events[idx].list or {} table.insert(self.events[idx].list, event) self.events[idx].lastEventTime = self.events[idx].lastEventTime or 0 if sampleOffset >= self.events[idx].lastEventTime then self.events[idx].lastEventTime = sampleOffset self.events[idx].lastEvent = event end end --This function has to be called in each processBlock ! function audioMath.MidiEventsQueue:playEvents(midiBuf) local blockEvents = self.events[self.currentBlock] if blockEvents then for i, event in ipairs(blockEvents.list) do midiBuf:addEvent(event) --print(event) end end self.events[self.currentBlock] = nil self.currentBlock = (self.currentBlock + 1) % self.maxBlock end function audioMath.MidiEventsQueue:lastTimeEventInCurrentBlock() local blockEvents = self.events[self.currentBlock] if blockEvents then return blockEvents.lastEventTime end return 0 end filters = require("include/filters") ffi = require("ffi") function audioMath.X2Upsampler() --local A0 = filters.SecondOrderAllPassSection(0.1380) --local A1 = filters.SecondOrderAllPassSection(0.5847) local LPS = {} local nbLP = 3 for i=1, nbLP do LPS[i] = filters.SecondOrderButterworthLP(0.25) end --Note inSamples should be floats but -- doubles are supposedly more efficient in LuaJIT so we output that instead local bufferSize = 2048 local outSamples = ffi.new("double[?]", bufferSize) return function(inSamples, blockSize) if bufferSize < blockSize * 2 then bufferSize = blockSize * 2 outSamples = ffi.new("double[?]", bufferSize) end --[[Polyphase IIR interpolation filter as per http://www.ensilica.com/wp-content/uploads/High_performance_IIR_filters_for_interpolation_and_decimation.pdf--]] for i=0, blockSize-1 do --outSamples[2*i] = A0(inSamples[i]) --outSamples[2*i+1] = A1(inSamples[i]) --Dumb way for now outSamples[2*i] = inSamples[i] outSamples[2*i+1] = 0 end --Dumb way for now for i=0, 2*blockSize-1 do for lp=1, nbLP do outSamples[i] = LPS[lp](outSamples[i]) end end return outSamples end end function audioMath.X2Downsampler() -- TODO ! check values are correct and cutoff still in the right place !? local A0 = filters.SecondOrderAllPassSection(0.1380) local A1 = filters.SecondOrderAllPassSection(0.5847) return function(inSamples, outSamples, blockSize) --[[Polyphase IIR interpolation filter as per http://www.ensilica.com/wp-content/uploads/High_performance_IIR_filters_for_interpolation_and_decimation.pdf--]] for i=0, blockSize-1 do outSamples[i] = 0.5 * (A0(inSamples[2*i]) + A1(inSamples[2*i+1])) end return outSamples end end return audioMath
Fixed some missing locals and also avoid dynamic allocation for the upsampler
Fixed some missing locals and also avoid dynamic allocation for the upsampler
Lua
mit
JTriggerFish/protoplug,JTriggerFish/protoplug,JTriggerFish/protoplug,JTriggerFish/protoplug,JTriggerFish/protoplug,JTriggerFish/protoplug
0d59587b1cf55c923586f0a609903ae60c328183
MMOCoreORB/bin/scripts/screenplays/tasks/naboo/librarian.lua
MMOCoreORB/bin/scripts/screenplays/tasks/naboo/librarian.lua
npcMapLibrarian = { { spawnData = { planetName = "naboo", npcTemplate = "librarian", x = 40.7, z = 33, y = -93.9, direction = -97, cellID = 1688867, position = STAND }, npcNumber = 1, stfFile = "@celebrity/librarian", }, } Librarian = ThemeParkLogic:new { numberOfActs = 1, npcMap = npcMapLibrarian, permissionMap = {}, className = "Librarian", screenPlayState = "librarian", distance = 500, missionDescriptionStf = "", missionCompletionMessageStf = "", } registerScreenPlay("Librarian", true) librarian_handler = Object:new { } function librarian_handler:getNextConversationScreen(pConversationTemplate, pPlayer, selectedOption, pConversingNpc) local player = LuaCreatureObject(pPlayer) 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 function librarian_handler:getInitialScreen(pPlayer, npc, pConversationTemplate) local convoTemplate = LuaConversationTemplate(pConversationTemplate) local conversingPlayer = LuaCreatureObject(pPlayer) local pPlayerObject = conversingPlayer:getPlayerObject() local conversingObject = LuaSceneObject(pPlayer) if (pPlayerObject == nil) then return nil end local objectID = conversingPlayer:getObjectID() writeData(objectID .. ":librarian", 1) local playerObject = LuaPlayerObject(pPlayerObject) return convoTemplate:getScreen("want_trivia") end function librarian_handler:runScreenHandlers(conversationTemplate, conversingPlayer, conversingNPC, selectedOption, conversationScreen) local screen = LuaConversationScreen(conversationScreen) local screenID = screen:getScreenID() rightResponses = { "winner_is_you", "you_are_right", "good_answer", "correct", "correctamundo", "you_got_it" } wrongResponses = { "too_bad_so_sad", "worst_ever_guesser", "thats_not_it", "no_sir", "you_are_wrong", "incorrect", "buzz_wrong_answer", "couldnt_be_wronger", "most_wrong", "bad_answer", "most_unfortunate", "most_incorrect", "worst_answer_ever", "wrongest", "wrong_squared", "you_are_weakest_link", "not_even_trying" } local player = LuaCreatureObject(conversingPlayer) local objectID = player:getObjectID() local playerObjectPointer = player:getPlayerObject() conversationScreen = screen:cloneScreen() local clonedConversation = LuaConversationScreen(conversationScreen) if (string.find(screenID, "question") ~= nil) then local questionNum = string.match(screenID, '%d+') local possibleAnswers = { { "wrong_one_" .. questionNum, wrongResponses[math.random(#wrongResponses)] }, { "wrong_two_" .. questionNum, wrongResponses[math.random(#wrongResponses)] }, { "wrong_three_" .. questionNum, wrongResponses[math.random(#wrongResponses)] } } if questionNum == "20" then possibleAnswers[#possibleAnswers+1] = { "right_" .. questionNum, "done" } else possibleAnswers[#possibleAnswers+1] = { "right_" .. questionNum, rightResponses[math.random(#rightResponses)] } end possibleAnswers = self:shuffleAnswers(possibleAnswers) writeData(objectID .. ":librarian", questionNum) clonedConversation:addOption("@celebrity/librarian:" .. possibleAnswers[1][1], possibleAnswers[1][2]) clonedConversation:addOption("@celebrity/librarian:" .. possibleAnswers[2][1], possibleAnswers[2][2]) clonedConversation:addOption("@celebrity/librarian:" .. possibleAnswers[3][1], possibleAnswers[3][2]) clonedConversation:addOption("@celebrity/librarian:" .. possibleAnswers[4][1], possibleAnswers[4][2]) end if (self:existsInTable(rightResponses, screenID)) then nextQuestion = readData(objectID .. ":librarian") + 1 clonedConversation:addOption("@celebrity/librarian:yes", "question_" .. nextQuestion) clonedConversation:addOption("@celebrity/librarian:no", "good_bye") end if (self:existsInTable(wrongResponses, screenID)) then writeData(objectID .. ":librarian", 1) clonedConversation:addOption("@celebrity/librarian:yes", "question_1") clonedConversation:addOption("@celebrity/librarian:no", "good_bye") end if (screenID == "done") then if playerObjectPointer ~= nil then local ghost = LuaPlayerObject(playerObjectPointer) ghost:awardBadge(111) end end return conversationScreen end function librarian_handler:shuffleAnswers(array) local arrayCount = #array for i = arrayCount, 2, -1 do local j = math.random(1, i) array[i], array[j] = array[j], array[i] end return array end function librarian_handler:existsInTable(table, item) for key, value in pairs(table) do if value == item then return true end end return false end
npcMapLibrarian = { { spawnData = { planetName = "naboo", npcTemplate = "librarian", x = 40.7, z = 33, y = -93.9, direction = -97, cellID = 1688867, position = STAND }, npcNumber = 1, stfFile = "@celebrity/librarian", }, } Librarian = ThemeParkLogic:new { numberOfActs = 1, npcMap = npcMapLibrarian, permissionMap = {}, className = "Librarian", screenPlayState = "librarian", distance = 500, missionDescriptionStf = "", missionCompletionMessageStf = "", } registerScreenPlay("Librarian", true) librarian_handler = Object:new { } function librarian_handler:getNextConversationScreen(pConversationTemplate, pPlayer, selectedOption, pConversingNpc) local player = LuaCreatureObject(pPlayer) 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 function librarian_handler:getInitialScreen(pPlayer, npc, pConversationTemplate) local convoTemplate = LuaConversationTemplate(pConversationTemplate) local conversingPlayer = LuaCreatureObject(pPlayer) local pPlayerObject = conversingPlayer:getPlayerObject() local conversingObject = LuaSceneObject(pPlayer) if (pPlayerObject == nil) then return nil end local objectID = conversingPlayer:getObjectID() writeData(objectID .. ":librarian", 1) local playerObject = LuaPlayerObject(pPlayerObject) return convoTemplate:getScreen("want_trivia") end function librarian_handler:runScreenHandlers(conversationTemplate, conversingPlayer, conversingNPC, selectedOption, conversationScreen) local screen = LuaConversationScreen(conversationScreen) local screenID = screen:getScreenID() rightResponses = { "winner_is_you", "you_are_right", "good_answer", "correct", "correctamundo", "you_got_it" } wrongResponses = { "too_bad_so_sad", "worst_ever_guesser", "thats_not_it", "no_sir", "you_are_wrong", "incorrect", "buzz_wrong_answer", "couldnt_be_wronger", "most_wrong", "bad_answer", "most_unfortunate", "most_incorrect", "worst_answer_ever", "wrongest", "wrong_squared", "you_are_weakest_link", "not_even_trying" } local player = LuaCreatureObject(conversingPlayer) local objectID = player:getObjectID() local playerObjectPointer = player:getPlayerObject() conversationScreen = screen:cloneScreen() local clonedConversation = LuaConversationScreen(conversationScreen) if (string.find(screenID, "question") ~= nil) then local questionNum = string.match(screenID, '%d+') local possibleAnswers = { { "wrong_one_" .. questionNum, wrongResponses[math.random(#wrongResponses)] }, { "wrong_two_" .. questionNum, wrongResponses[math.random(#wrongResponses)] }, { "wrong_three_" .. questionNum, wrongResponses[math.random(#wrongResponses)] } } if questionNum == "20" then possibleAnswers[#possibleAnswers+1] = { "right_" .. questionNum, "done" } else possibleAnswers[#possibleAnswers+1] = { "right_" .. questionNum, rightResponses[math.random(#rightResponses)] } end possibleAnswers = self:shuffleAnswers(possibleAnswers) writeData(objectID .. ":librarian", questionNum) clonedConversation:addOption("@celebrity/librarian:" .. possibleAnswers[1][1], possibleAnswers[1][2]) clonedConversation:addOption("@celebrity/librarian:" .. possibleAnswers[2][1], possibleAnswers[2][2]) clonedConversation:addOption("@celebrity/librarian:" .. possibleAnswers[3][1], possibleAnswers[3][2]) clonedConversation:addOption("@celebrity/librarian:" .. possibleAnswers[4][1], possibleAnswers[4][2]) end if (self:existsInTable(rightResponses, screenID)) then nextQuestion = readData(objectID .. ":librarian") + 1 clonedConversation:addOption("@celebrity/librarian:yes", "question_" .. nextQuestion) clonedConversation:addOption("@celebrity/librarian:no", "good_bye") end if (self:existsInTable(wrongResponses, screenID)) then currentQuestion = readData(objectID .. ":librarian") writeData(objectID .. ":librarian", 1) clonedConversation:addOption("@celebrity/librarian:yes", "question_" .. currentQuestion) clonedConversation:addOption("@celebrity/librarian:no", "good_bye") end if (screenID == "done") then if playerObjectPointer ~= nil then local ghost = LuaPlayerObject(playerObjectPointer) ghost:awardBadge(111) end end return conversationScreen end function librarian_handler:shuffleAnswers(array) local arrayCount = #array for i = arrayCount, 2, -1 do local j = math.random(1, i) array[i], array[j] = array[j], array[i] end return array end function librarian_handler:existsInTable(table, item) for key, value in pairs(table) do if value == item then return true end end return false end
[fixed] Naboo Librarian no longer starts from beginning after wrong answer.
[fixed] Naboo Librarian no longer starts from beginning after wrong answer. Change-Id: I10c5fc4259fbc29fa00becedb6fadb76781c69db
Lua
agpl-3.0
Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo
03b0b7174dec3658c548795fdd99b45b68682dbc
Examples/opensuse-sandbox.cfg.lua
Examples/opensuse-sandbox.cfg.lua
-- this is an example config for sandbox that use external opensuse rootfs as base. -- config based on debian-sandbox.cfg.lua, and will be maintained as small as possible - most notes removed. -- see ubuntu-sandbox.cfg.lua and example.cfg.lua for more comments and information about config options -- this example config is compatible with external root-fs archives that was downloaded and extracted by running: -- download-opensuse-42.2-chroot.sh - download opensuse 42.2 x86_64 distribution from docker repository -- download-opensuse-tumbleweed-chroot.sh - download opensuse tumbleweed x86_64 distribution from docker repository -- THIS CONFIG WILL CREATE REGULAR SANDBOXED ENV FROM CHROOT DIRECTORY, THAT WAS PREVIOUSLY SETUP WITH opensuse-setup.cfg.lua. -- it is strongly recommended to use this config rather than opensuse-setup.cfg.lua to run regular software, most of desktop integration options enabled by default with this config. tunables.chrootdir=loader.path.combine(loader.workdir,"opensuse_chroot") dofile(loader.path.combine(loader.workdir,"opensuse-version-probe.lua.in")) -- detect os, version and arch tunables.etchost_path=loader.path.combine(tunables.chrootdir,"etc") tunables.features.dbus_search_prefix=tunables.chrootdir tunables.features.xpra_search_prefix=tunables.chrootdir tunables.features.gvfs_fix_search_prefix=tunables.chrootdir tunables.features.x11util_build=os_id.."-"..os_version.."-"..os_arch tunables.features.pulse_env_alsa_config="skip" defaults.recalculate() sandbox={ features={ "dbus", "gvfs_fix", "pulse", "x11host", "envfix", }, setup={ executor_build=os_id.."-"..os_version.."-"..os_arch, commands={ defaults.commands.machineid_static, defaults.commands.passwd, defaults.commands.resolvconf, defaults.commands.home, defaults.commands.home_gui_config, defaults.commands.var_cache, defaults.commands.var_tmp, }, env_whitelist={ "LANG", "LC_ALL", }, env_set={ {"PATH","/usr/local/bin:/usr/bin:/bin:/usr/games:/usr/lib/mit/bin:/usr/lib/mit/sbin"}, defaults.env.set_xdg_runtime, defaults.env.set_home, }, mounts={ defaults.mounts.system_group, defaults.mounts.xdg_runtime_dir, defaults.mounts.home_mount, defaults.mounts.var_cache_mount, defaults.mounts.var_tmp_mount, defaults.mounts.var_lib_mount, defaults.mounts.bin_ro_mount, defaults.mounts.usr_ro_mount, defaults.mounts.lib_ro_mount, defaults.mounts.lib64_ro_mount, defaults.mounts.sbin_ro_mount, {prio=10,"ro-bind",loader.path.combine(tunables.chrootdir,"srv"),"/srv"}, {prio=10,"ro-bind",loader.path.combine(tunables.chrootdir,"opt"),"/opt"}, defaults.mounts.host_etc_mount, defaults.mounts.passwd_mount, defaults.mounts.machineid_mount, defaults.mounts.resolvconf_mount, defaults.mounts.devsnd_mount, defaults.mounts.devdri_mount, defaults.mounts.devinput_mount, defaults.mounts.sys_mount, }, }, bwrap={ defaults.bwrap.unshare_user, -- defaults.bwrap.unshare_ipc, defaults.bwrap.unshare_pid, -- defaults.bwrap.unshare_net, defaults.bwrap.unshare_uts, -- defaults.bwrap.unshare_cgroup, defaults.bwrap.uid, defaults.bwrap.gid, } } shell={ exec="/bin/bash", args={"-l"}, path="/", env_set={ {"TERM",os.getenv("TERM")}, }, term_signal=defaults.signals.SIGHUP, attach=true, pty=true, } function trim_args(t1) table.remove(t1,1) table.remove(t1,1) return t1 end -- invocation example: sandboxer opensuse-sandbox.cfg.lua cmd_exec / /bin/ls -la -- execution is performed by using execvp call, so you must provide absolute path for target binary cmd_exec={ exec=loader.args[2], path=loader.args[1], args=trim_args(loader.args), term_signal=defaults.signals.SIGTERM, attach=true, pty=false, }
-- this is an example config for sandbox that use external opensuse rootfs as base. -- config based on debian-sandbox.cfg.lua, and will be maintained as small as possible - most notes removed. -- see ubuntu-sandbox.cfg.lua and example.cfg.lua for more comments and information about config options -- this example config is compatible with external root-fs archives that was downloaded and extracted by running: -- download-opensuse-42.2-chroot.sh - download opensuse 42.2 x86_64 distribution from docker repository -- download-opensuse-tumbleweed-chroot.sh - download opensuse tumbleweed x86_64 distribution from docker repository -- THIS CONFIG WILL CREATE REGULAR SANDBOXED ENV FROM CHROOT DIRECTORY, THAT WAS PREVIOUSLY SETUP WITH opensuse-setup.cfg.lua. -- it is strongly recommended to use this config rather than opensuse-setup.cfg.lua to run regular software, most of desktop integration options enabled by default with this config. tunables.chrootdir=loader.path.combine(loader.workdir,"opensuse_chroot") dofile(loader.path.combine(loader.workdir,"opensuse-version-probe.lua.in")) -- detect os, version and arch tunables.etchost_path=loader.path.combine(tunables.chrootdir,"etc") tunables.features.dbus_search_prefix=tunables.chrootdir tunables.features.xpra_search_prefix=tunables.chrootdir tunables.features.gvfs_fix_search_prefix=tunables.chrootdir tunables.features.x11util_build=os_id.."-"..os_version.."-"..os_arch tunables.features.pulse_env_alsa_config="skip" defaults.recalculate() sandbox={ features={ "dbus", "gvfs_fix", "pulse", "x11host", "envfix", }, setup={ executor_build=os_id.."-"..os_version.."-"..os_arch, commands={ defaults.commands.machineid_static, defaults.commands.passwd, defaults.commands.resolvconf, defaults.commands.home, defaults.commands.home_gui_config, defaults.commands.var_cache, defaults.commands.var_tmp, }, env_whitelist={ "LANG", "LC_ALL", }, env_set={ {"PATH","/usr/local/bin:/usr/bin:/bin:/usr/games:/usr/lib/mit/bin:/usr/lib/mit/sbin"}, defaults.env.set_xdg_runtime, defaults.env.set_home, }, mounts={ defaults.mounts.system_group, defaults.mounts.xdg_runtime_dir, defaults.mounts.home_mount, defaults.mounts.var_cache_mount, defaults.mounts.var_tmp_mount, defaults.mounts.var_lib_mount, defaults.mounts.bin_ro_mount, defaults.mounts.usr_ro_mount, defaults.mounts.lib_ro_mount, defaults.mounts.lib64_ro_mount, defaults.mounts.sbin_ro_mount, {prio=10,"ro-bind",loader.path.combine(tunables.chrootdir,"srv"),"/srv"}, {prio=10,"ro-bind",loader.path.combine(tunables.chrootdir,"opt"),"/opt"}, defaults.mounts.host_etc_mount, defaults.mounts.passwd_mount, defaults.mounts.machineid_mount, defaults.mounts.resolvconf_mount, defaults.mounts.devsnd_mount, defaults.mounts.devdri_mount, defaults.mounts.devinput_mount, defaults.mounts.sys_mount, }, }, bwrap={ defaults.bwrap.unshare_user, -- defaults.bwrap.unshare_ipc, defaults.bwrap.unshare_pid, -- defaults.bwrap.unshare_net, defaults.bwrap.unshare_uts, -- defaults.bwrap.unshare_cgroup, defaults.bwrap.uid, defaults.bwrap.gid, } } shell={ exec="/bin/bash", args={"-l"}, path="/", env_set={ {"TERM",os.getenv("TERM")}, }, term_signal=defaults.signals.SIGHUP, attach=true, pty=true, } function trim_args(target) local result={} assert(type(target)=="table", "trim_args: target must be a table!") for i = #target, 3, -1 do table.insert(result, 1, target[i]) end return result end -- invocation example: sandboxer opensuse-sandbox.cfg.lua cmd_exec / /bin/ls -la -- execution is performed by using execvp call, so you must provide absolute path for target binary cmd_exec={ exec=loader.args[2], path=loader.args[1], args=trim_args(loader.args), term_signal=defaults.signals.SIGTERM, attach=true, pty=false, }
Examples: fix trim_args function at opensuse-sandbox.cfg.lua
Examples: fix trim_args function at opensuse-sandbox.cfg.lua
Lua
mit
DarkCaster/Sandboxer,DarkCaster/Sandboxer