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
ecefe356aef54f353603c574460b99403dc64db0
MMOCoreORB/bin/scripts/object/weapon/melee/unarmed/unarmed_default_player.lua
MMOCoreORB/bin/scripts/object/weapon/melee/unarmed/unarmed_default_player.lua
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_weapon_melee_unarmed_unarmed_default_player = object_weapon_melee_unarmed_shared_unarmed_default_player:new { -- ALL, ALLSEXES, ALLFACTIONS, HUMANOIDS, HUMANOID_FOOTWEAR, HUMANOID_MALES, HUMANOID_FEMALES, HUMANOID_IMPERIALS, HUMANOID_REBELS, WOOKIES, ITHORIANS, TWILEKS playerUseMask = ALL, -- RANGEDATTACK, MELEEATTACK, FORCEATTACK, TRAPATTACK, GRENADEATTACK, HEAVYACIDBEAMATTACK, -- HEAVYLIGHTNINGBEAMATTACK, HEAVYPARTICLEBEAMATTACK, HEAVYROCKETLAUNCHERATTACK, HEAVYLAUNCHERATTACK attackType = MELEEATTACK, -- ENERGY, KINETIC, ELECTRICITY, STUN, BLAST, HEAT, COLD, ACID, FORCE, LIGHTSABER damageType = KINETIC, -- NONE, LIGHT, MEDIUM, HEAVY armorPiercing = NONE, -- combat_rangedspecialize_bactarifle, combat_rangedspecialize_rifle, combat_rangedspecialize_pistol, combat_rangedspecialize_heavy, combat_rangedspecialize_carbine -- combat_meleespecialize_unarmed, combat_meleespecialize_twohand, combat_meleespecialize_polearm, combat_meleespecialize_onehand, combat_general, -- combat_meleespecialize_twohandlightsaber, combat_meleespecialize_polearmlightsaber, combat_meleespecialize_onehandlightsaber xpType = "combat_meleespecialize_unarmed", -- See http://www.ocdsoft.com/files/certifications.xls certificationsRequired = { }, -- See http://www.ocdsoft.com/files/accuracy.xls creatureAccuracyModifiers = { "unarmed_accuracy" }, -- See http://www.ocdsoft.com/files/defense.xls defenderDefenseModifiers = { "unarmed_passive_defense", "melee_defense" }, -- can be dodge, counterattack, or block or a combination -- Secondary defense when equipped defenderSecondaryDefenseModifiers = { "dodge", "counterattack" }, -- See http://www.ocdsoft.com/files/speed.xls speedModifiers = { "unarmed_speed" }, -- carbine_damage, onehandmelee_damage, pistol_damage, rifle_damage, twohandmelee_damage, unarmed_damage damageModifiers = { "unarmed_damage" }, -- The values below are the default values. To be used for blue frog objects primarily healthAttackCost = 10, actionAttackCost = 10, mindAttackCost = 10, forceCost = 0, pointBlankAccuracy = 0, pointBlankRange = 15, idealRange = 5, idealAccuracy = 3, maxRange = 5, maxRangeAccuracy = 5, minDamage = 20, maxDamage = 90, attackSpeed = 2 } ObjectTemplates:addTemplate(object_weapon_melee_unarmed_unarmed_default_player, "object/weapon/melee/unarmed/unarmed_default_player.iff")
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_weapon_melee_unarmed_unarmed_default_player = object_weapon_melee_unarmed_shared_unarmed_default_player:new { -- ALL, ALLSEXES, ALLFACTIONS, HUMANOIDS, HUMANOID_FOOTWEAR, HUMANOID_MALES, HUMANOID_FEMALES, HUMANOID_IMPERIALS, HUMANOID_REBELS, WOOKIES, ITHORIANS, TWILEKS playerUseMask = ALL, -- RANGEDATTACK, MELEEATTACK, FORCEATTACK, TRAPATTACK, GRENADEATTACK, HEAVYACIDBEAMATTACK, -- HEAVYLIGHTNINGBEAMATTACK, HEAVYPARTICLEBEAMATTACK, HEAVYROCKETLAUNCHERATTACK, HEAVYLAUNCHERATTACK attackType = MELEEATTACK, -- ENERGY, KINETIC, ELECTRICITY, STUN, BLAST, HEAT, COLD, ACID, FORCE, LIGHTSABER damageType = KINETIC, -- NONE, LIGHT, MEDIUM, HEAVY armorPiercing = NONE, -- combat_rangedspecialize_bactarifle, combat_rangedspecialize_rifle, combat_rangedspecialize_pistol, combat_rangedspecialize_heavy, combat_rangedspecialize_carbine -- combat_meleespecialize_unarmed, combat_meleespecialize_twohand, combat_meleespecialize_polearm, combat_meleespecialize_onehand, combat_general, -- combat_meleespecialize_twohandlightsaber, combat_meleespecialize_polearmlightsaber, combat_meleespecialize_onehandlightsaber xpType = "combat_meleespecialize_unarmed", -- See http://www.ocdsoft.com/files/certifications.xls certificationsRequired = { }, -- See http://www.ocdsoft.com/files/accuracy.xls creatureAccuracyModifiers = { "unarmed_accuracy" }, -- See http://www.ocdsoft.com/files/defense.xls defenderDefenseModifiers = { "unarmed_passive_defense", "melee_defense" }, -- can be dodge, counterattack, or block or a combination -- Secondary defense when equipped defenderSecondaryDefenseModifiers = { "dodge", "counterattack" }, -- See http://www.ocdsoft.com/files/speed.xls speedModifiers = { "unarmed_speed" }, -- carbine_damage, onehandmelee_damage, pistol_damage, rifle_damage, twohandmelee_damage, unarmed_damage -- unarmed_damage didn't work in pre-cu damageModifiers = { }, -- The values below are the default values. To be used for blue frog objects primarily healthAttackCost = 10, actionAttackCost = 10, mindAttackCost = 10, forceCost = 0, pointBlankAccuracy = 0, pointBlankRange = 15, idealRange = 5, idealAccuracy = 3, maxRange = 5, maxRangeAccuracy = 5, minDamage = 20, maxDamage = 90, attackSpeed = 2 } ObjectTemplates:addTemplate(object_weapon_melee_unarmed_unarmed_default_player, "object/weapon/melee/unarmed/unarmed_default_player.iff")
[fixed] Fists doing so much more damage than a VK
[fixed] Fists doing so much more damage than a VK git-svn-id: c34995188cc7e843f8a799edec2d9d4b36f36456@2710 c3d1530f-68f5-4bd0-87dc-8ef779617e40
Lua
agpl-3.0
lasko2112/legend-of-hondo,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,Tatwi/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
fe6b05bfcfdda461f5ea6d76f441b922724d7380
testserver/item/doors.lua
testserver/item/doors.lua
require("base.common") require("base.doors") module("item.doors", package.seeall) -- UPDATE common SET com_script='item.doors' WHERE com_itemid IN (86, 87,927,317,476,477,478,479,499,900,901,902,484,485,924,923,668,669,660,661,684,685,664,665,670,666,671,667,662,686,663,687,715,714,712,713,497,922,925,926,480,481,482,483,903,904,905,906,486,487,496,920,656,657,648,649,652,653,644,645,658,654,659,655,650,646,651,647,711,710,708,709); function UseItem(User,SourceItem,TargetItem,counter,param) if User.pos.z==100 or User.pos.z==101 then --On Noobia: Doors must not be closed. base.common.InformNLS(User,"Die Tr klemmt und kann nicht geschlossen werden.","The door is jammed and won't close."); return; --bailing out end --Noobia end if base.doors.CloseDoor(SourceItem) then base.common.InformNLS(User,"Du schliet die Tr.","You close the door."); else local OpenDoor,OpenOK=base.doors.OpenDoor(SourceItem); if OpenOK then base.common.InformNLS(User,"Du ffnest die Tr.","You open the door."); elseif OpenDoor then base.common.InformNLS(User,"Du versuchst die Tr zu ffnen, doch sie ist verschlossen.","You try to open the door, but the door is locked."); end end end function LookAtItem(User,Item) local DataVal=Item.data; if (specialnames==nil) then specialnames={}; --nothing defined yet end local lang=User:getPlayerLanguage(); if (specialnames[DataVal]~=nil) then if (lang==0) then world:itemInform(User,Item,world:getItemName(Item.id,0).." \""..specialnames[DataVal][1].."\""); else world:itemInform(User,Item,world:getItemName(Item.id,1).." \""..specialnames[DataVal][2].."\""); end else if (lang==0) then world:itemInform(User,Item,world:getItemName(Item.id,0)); else world:itemInform(User,Item,world:getItemName(Item.id,1)); end end end
require("base.common") require("base.doors") module("item.doors", package.seeall) -- UPDATE common SET com_script='item.doors' WHERE com_itemid IN (86, 87,927,317,476,477,478,479,499,900,901,902,484,485,924,923,668,669,660,661,684,685,664,665,670,666,671,667,662,686,663,687,715,714,712,713,497,922,925,926,480,481,482,483,903,904,905,906,486,487,496,920,656,657,648,649,652,653,644,645,658,654,659,655,650,646,651,647,711,710,708,709); function UseItem(User,SourceItem,TargetItem,counter,param) if User.pos.z==100 or User.pos.z==101 then --On Noobia: Doors must not be closed. base.common.InformNLS(User,"Die Tr klemmt und kann nicht geschlossen werden.","The door is jammed and won't close."); return; --bailing out end --Noobia end if base.doors.CloseDoor(SourceItem) then base.common.InformNLS(User,"Du schliet die Tr.","You close the door."); else local OpenDoor,OpenOK=base.doors.OpenDoor(SourceItem); if OpenOK then base.common.InformNLS(User,"Du ffnest die Tr.","You open the door."); elseif OpenDoor then base.common.InformNLS(User,"Du versuchst die Tr zu ffnen, doch sie ist verschlossen.","You try to open the door, but the door is locked."); end end end function LookAtItem(User,Item) world:itemInform(User,Item,base.lookat.GenerateLookAt(User, Item, base.lookat.NONE)); end
fixed lookat
fixed lookat
Lua
agpl-3.0
vilarion/Illarion-Content,LaFamiglia/Illarion-Content,KayMD/Illarion-Content,Baylamon/Illarion-Content,Illarion-eV/Illarion-Content
b45f47f2acd92f065055923d0ba9c4a3419f824f
Utilities/openLuup_install.lua
Utilities/openLuup_install.lua
-- first-time download and install of openLuup files from GitHub -- 2018.02.17 add local ./www/ directory -- 2018.08.05 use servertables for myIP (thanks @samunders) -- 2018.08.10 add parameter for install branch (thanks @vwout) -- 2019.02.12 fix tslv1_2 protocol error local lua = "lua5.1" -- change this to "lua" if required local x = os.execute local p = print local branch = arg[1] or "master" p "openLuup_install 2019.02.12 @akbooer" local http = require "socket.http" local https = require "ssl.https" local ltn12 = require "ltn12" local lfs = require "lfs" p ("getting openLuup version tar file from GitHub branch " .. branch .. "...") local _, code = https.request{ url = "https://codeload.github.com/akbooer/openLuup/tar.gz/" .. branch, sink = ltn12.sink.file(io.open("latest.tar.gz", "wb")) } assert (code == 200, "GitHub download failed with code " .. code) p "un-zipping download files..." x "tar -xf latest.tar.gz" x ("mv openLuup-" .. branch .. "/openLuup/ .") x ("rm -r openLuup-" .. branch .. "/") p "getting dkjson.lua..." _, code = http.request{ url = "http://dkolf.de/src/dkjson-lua.fsl/raw/dkjson.lua?name=16cbc26080996d9da827df42cb0844a25518eeb3", sink = ltn12.sink.file(io.open("dkjson.lua", "wb")), protocol = "tlsv1_2", } assert (code == 200, "GitHub download failed with code " .. code) p "creating required files and folders" lfs.mkdir "www" lfs.mkdir "files" lfs.mkdir "icons" lfs.mkdir "backup" -- thanks @a-lurker local vfs = require "openLuup.virtualfilesystem" local function add_vfs_file (name) local f = io.open (name, "wb") f: write (vfs.read (name)) f: close () end add_vfs_file "index.html" local reload = "openLuup_reload" local pathSeparator = package.config:sub(1,1) -- thanks to @vosmont for this Windows/Unix discriminator if pathSeparator ~= '/' then reload = reload .. ".bat" end -- Windows version add_vfs_file (reload) p "initialising..." x "chmod a+x openLuup_reload" local s= require "openLuup.servertables" local ip = s.myIP or "openLuupIP" p "downloading and installing AltUI..." x (lua .. " openLuup/init.lua altui") x "./openLuup_reload &" p "openLuup downloaded, installed, and running..." p ("visit http://" .. ip .. ":3480 to start using the system") -----
-- first-time download and install of openLuup files from GitHub -- 2018.02.17 add local ./www/ directory -- 2018.08.05 use servertables for myIP (thanks @samunders) -- 2018.08.10 add parameter for install branch (thanks @vwout) -- 2019.02.15 fix tslv1_2 protocol error (properly, this time!) local lua = "lua5.1" -- change this to "lua" if required local x = os.execute local p = print local branch = arg[1] or "master" p "openLuup_install 2019.02.15 @akbooer" local http = require "socket.http" local https = require "ssl.https" local ltn12 = require "ltn12" local lfs = require "lfs" p ("getting openLuup version tar file from GitHub branch " .. branch .. "...") local _, code = https.request{ url = "https://codeload.github.com/akbooer/openLuup/tar.gz/" .. branch, sink = ltn12.sink.file(io.open("latest.tar.gz", "wb")), protocol = "tlsv1_2", } assert (code == 200, "GitHub download failed with code " .. code) p "un-zipping download files..." x "tar -xf latest.tar.gz" x ("mv openLuup-" .. branch .. "/openLuup/ .") x ("rm -r openLuup-" .. branch .. "/") p "getting dkjson.lua..." _, code = http.request{ url = "http://dkolf.de/src/dkjson-lua.fsl/raw/dkjson.lua?name=16cbc26080996d9da827df42cb0844a25518eeb3", sink = ltn12.sink.file(io.open("dkjson.lua", "wb")), } assert (code == 200, "GitHub download failed with code " .. code) p "creating required files and folders" lfs.mkdir "www" lfs.mkdir "files" lfs.mkdir "icons" lfs.mkdir "backup" -- thanks @a-lurker local vfs = require "openLuup.virtualfilesystem" local function add_vfs_file (name) local f = io.open (name, "wb") f: write (vfs.read (name)) f: close () end add_vfs_file "index.html" local reload = "openLuup_reload" local pathSeparator = package.config:sub(1,1) -- thanks to @vosmont for this Windows/Unix discriminator if pathSeparator ~= '/' then reload = reload .. ".bat" end -- Windows version add_vfs_file (reload) p "initialising..." x "chmod a+x openLuup_reload" local s= require "openLuup.servertables" local ip = s.myIP or "openLuupIP" p "downloading and installing AltUI..." x (lua .. " openLuup/init.lua altui") x "./openLuup_reload &" p "openLuup downloaded, installed, and running..." p ("visit http://" .. ip .. ":3480 to start using the system") -----
2019.02.15
2019.02.15 - fix tslv1_2 protocol error (properly, this time!)
Lua
apache-2.0
akbooer/openLuup
953835020d18263fd7a422b0bb6d48b15c50f3ef
modules/textadept/command_entry.lua
modules/textadept/command_entry.lua
-- Copyright 2007-2014 Mitchell mitchell.att.foicica.com. See LICENSE. -- Abbreviated environment and commands from Jay Gould. local M = ui.command_entry --[[ This comment is for LuaDoc. --- -- Textadept's Command Entry. -- -- ## Modes -- -- The command entry supports multiple [modes](#keys.Modes) that have their own -- sets of key bindings stored in a separate table in `_G.keys` under a mode -- prefix key. Mode names are arbitrary, but cannot conflict with lexer names or -- key sequence strings (e.g. `'lua'` or `'send'`) due to the method Textadept -- uses for looking up key bindings. An example mode is "lua_command" mode for -- executing Lua commands: -- -- local function complete_lua() ... end -- local function execute_lua() ... end -- keys['ce'] = {ui.command_entry.enter_mode, 'lua_command'} -- keys.lua_command = setmetatable({ -- ['\t'] = complete_lua, -- ['\n'] = {ui.command_entry.finish_mode, execute_lua} -- }, ui.command_entry.editing_keys) -- -- In this case, `Ctrl+E` opens the command entry and enters "lua_command" key -- mode where the `Tab` and `Enter` keys have special, defined functionality. -- (By default, Textadept pre-defines `Esc` to exit any command entry mode.) -- `Tab` shows a list of Lua completions for the entry text and `Enter` exits -- "lua_command" key mode and executes the entered code. The command entry -- handles all other editing and movement keys normally. -- @field height (number) -- The height in pixels of the command entry. module('ui.command_entry')]] --- -- A metatable with typical platform-specific key bindings for text entries. -- This metatable may be used to add basic editing keys to command entry modes. -- @usage setmetatable(keys.my_mode, ui.command_entry.editing_keys) -- @class table -- @name editing_keys M.editing_keys = {__index = { [not OSX and 'cx' or 'mx'] = {buffer.cut, M}, [not OSX and 'cc' or 'mc'] = {buffer.copy, M}, [not OSX and 'cv' or 'mv'] = {buffer.paste, M}, [not OSX and not CURSES and 'ca' or 'ma'] = {buffer.select_all, M}, [not OSX and 'cz' or 'mz'] = {buffer.undo, M}, [not OSX and 'cZ' or 'mZ'] = {buffer.redo, M}, cy = {buffer.redo, M}, -- Movement keys. [(OSX or CURSES) and 'cf' or '\0'] = {buffer.char_right, M}, [(OSX or CURSES) and 'cb' or '\0'] = {buffer.char_left, M}, [(OSX or CURSES) and 'ca' or '\0'] = {buffer.vc_home, M}, [(OSX or CURSES) and 'ce' or '\0'] = {buffer.line_end, M}, [(OSX or CURSES) and 'cd' or '\0'] = {buffer.clear, M} }} --- -- Opens the command entry in key mode *mode*. -- Key bindings will be looked up in `keys[mode]` instead of `keys`. The `Esc` -- key exits the current mode, closes the command entry, and restores normal key -- lookup. -- This function is useful for binding keys to enter a command entry mode. -- @param mode The key mode to enter into, or `nil` to exit the current mode. -- @usage keys['ce'] = {ui.command_entry.enter_mode, 'command_entry'} -- @see _G.keys.MODE -- @name enter_mode function M.enter_mode(mode) keys.MODE = mode if mode and not keys[mode]['esc'] then keys[mode]['esc'] = M.enter_mode end M:select_all() M.focus() end --- -- Exits the current key mode, closes the command entry, and calls function *f* -- (if given) with the command entry's text as an argument. -- This is useful for binding keys to exit a command entry mode and perform an -- action with the entered text. -- @param f Optional function to call. It should accept the command entry text -- as an argument. -- @usage keys['\n'] = {ui.command_entry.finish_mode, ui.print} -- @name finish_mode function M.finish_mode(f) if M:auto_c_active() then return false end -- allow Enter to autocomplete M.enter_mode(nil) if f then f(M:get_text()) end end -- Environment for abbreviated Lua commands. -- @class table -- @name env local env = setmetatable({}, { __index = function(t, k) local f = buffer[k] if f and type(f) == 'function' then f = function(...) buffer[k](buffer, ...) end elseif f == nil then f = view[k] or ui[k] or _G[k] end return f end, __newindex = function(t, k, v) for _, t2 in ipairs{buffer, view, ui} do if t2[k] ~= nil then t2[k] = v return end end rawset(t, k, v) end, }) -- Executes string *code* as Lua code that is subject to an "abbreviated" -- environment. -- In this environment, the contents of the `buffer`, `view`, and `ui` tables -- are also considered as global functions and fields. -- Prints the results of '=' expressions like in the Lua prompt. -- @param code The Lua code to execute. local function execute_lua(code) if code:find('^=') then code = 'return '..code:sub(2) end local result = assert(load(code, nil, 'bt', env))() if result ~= nil or code:find('^return ') then ui.print(result) end events.emit(events.UPDATE_UI) end args.register('-e', '--execute', 1, execute_lua, 'Execute Lua code') -- Shows a set of Lua code completions for string *code* or the entry's text. -- Completions are subject to an "abbreviated" environment where the `buffer`, -- `view`, and `ui` tables are also considered as globals. -- @param code The Lua code to complete. The default value is the entry's text. local function complete_lua(code) if not code then code = M:get_text() end local symbol, op, part = code:match('([%w_.]-)([%.:]?)([%w_]*)$') local ok, result = pcall((load('return ('..symbol..')', nil, 'bt', env))) local cmpls = {} part = '^'..part if (not ok or type(result) ~= 'table') and symbol ~= '' then return end if not ok then -- shorthand notation local pool = { buffer, view, ui, _G, _SCINTILLA.functions, _SCINTILLA.properties } for i = 1, #pool do for k in pairs(pool[i]) do if type(k) == 'string' and k:find(part) then cmpls[#cmpls + 1] = k end end end else for k in pairs(result) do if type(k) == 'string' and k:find(part) then cmpls[#cmpls + 1] = k end end if symbol == 'buffer' and op == ':' then for f in pairs(_SCINTILLA.functions) do if f:find(part) then cmpls[#cmpls + 1] = f end end elseif symbol == 'buffer' and op == '.' then for p in pairs(_SCINTILLA.properties) do if p:find(part) then cmpls[#cmpls + 1] = p end end end end table.sort(cmpls) M:auto_c_show(#part - 1, table.concat(cmpls, ' ')) end -- Define key mode for entering Lua commands. keys.lua_command = setmetatable({ ['\t'] = complete_lua, ['\n'] = {M.finish_mode, execute_lua}, }, M.editing_keys) -- Configure the command entry's default properties. events.connect(events.INITIALIZED, function() if not arg then return end -- no need to reconfigure on reset M.h_scroll_bar, M.v_scroll_bar = false, false M.margin_width_n[0], M.margin_width_n[1], M.margin_width_n[2] = 0, 0, 0 if not CURSES then M.height = M:text_height(1) end M:set_lexer('lua') end) --[[ The function below is a Lua C function. --- -- Opens the Lua command entry. -- @class function -- @name focus local focus ]]
-- Copyright 2007-2014 Mitchell mitchell.att.foicica.com. See LICENSE. -- Abbreviated environment and commands from Jay Gould. local M = ui.command_entry --[[ This comment is for LuaDoc. --- -- Textadept's Command Entry. -- -- ## Modes -- -- The command entry supports multiple [modes](#keys.Modes) that have their own -- sets of key bindings stored in a separate table in `_G.keys` under a mode -- prefix key. Mode names are arbitrary, but cannot conflict with lexer names or -- key sequence strings (e.g. `'lua'` or `'send'`) due to the method Textadept -- uses for looking up key bindings. An example mode is "lua_command" mode for -- executing Lua commands: -- -- local function complete_lua() ... end -- local function execute_lua() ... end -- keys['ce'] = {ui.command_entry.enter_mode, 'lua_command'} -- keys.lua_command = setmetatable({ -- ['\t'] = complete_lua, -- ['\n'] = {ui.command_entry.finish_mode, execute_lua} -- }, ui.command_entry.editing_keys) -- -- In this case, `Ctrl+E` opens the command entry and enters "lua_command" key -- mode where the `Tab` and `Enter` keys have special, defined functionality. -- (By default, Textadept pre-defines `Esc` to exit any command entry mode.) -- `Tab` shows a list of Lua completions for the entry text and `Enter` exits -- "lua_command" key mode and executes the entered code. The command entry -- handles all other editing and movement keys normally. -- @field height (number) -- The height in pixels of the command entry. module('ui.command_entry')]] --- -- A metatable with typical platform-specific key bindings for text entries. -- This metatable may be used to add basic editing keys to command entry modes. -- @usage setmetatable(keys.my_mode, ui.command_entry.editing_keys) -- @class table -- @name editing_keys M.editing_keys = {__index = { [not OSX and 'cx' or 'mx'] = {buffer.cut, M}, [not OSX and 'cc' or 'mc'] = {buffer.copy, M}, [not OSX and 'cv' or 'mv'] = {buffer.paste, M}, [not OSX and not CURSES and 'ca' or 'ma'] = {buffer.select_all, M}, [not OSX and 'cz' or 'mz'] = {buffer.undo, M}, [not OSX and 'cZ' or 'mZ'] = {buffer.redo, M}, cy = {buffer.redo, M}, -- Movement keys. [(OSX or CURSES) and 'cf' or '\0'] = {buffer.char_right, M}, [(OSX or CURSES) and 'cb' or '\0'] = {buffer.char_left, M}, [(OSX or CURSES) and 'ca' or '\0'] = {buffer.vc_home, M}, [(OSX or CURSES) and 'ce' or '\0'] = {buffer.line_end, M}, [(OSX or CURSES) and 'cd' or '\0'] = {buffer.clear, M} }} --- -- Opens the command entry in key mode *mode*. -- Key bindings will be looked up in `keys[mode]` instead of `keys`. The `Esc` -- key exits the current mode, closes the command entry, and restores normal key -- lookup. -- This function is useful for binding keys to enter a command entry mode. -- @param mode The key mode to enter into, or `nil` to exit the current mode. -- @usage keys['ce'] = {ui.command_entry.enter_mode, 'command_entry'} -- @see _G.keys.MODE -- @name enter_mode function M.enter_mode(mode) if M:auto_c_active() then M:auto_c_cancel() end -- may happen in curses keys.MODE = mode if mode and not keys[mode]['esc'] then keys[mode]['esc'] = M.enter_mode end M:select_all() M.focus() end --- -- Exits the current key mode, closes the command entry, and calls function *f* -- (if given) with the command entry's text as an argument. -- This is useful for binding keys to exit a command entry mode and perform an -- action with the entered text. -- @param f Optional function to call. It should accept the command entry text -- as an argument. -- @usage keys['\n'] = {ui.command_entry.finish_mode, ui.print} -- @name finish_mode function M.finish_mode(f) if M:auto_c_active() then return false end -- allow Enter to autocomplete M.enter_mode(nil) if f then f(M:get_text()) end end -- Environment for abbreviated Lua commands. -- @class table -- @name env local env = setmetatable({}, { __index = function(t, k) local f = buffer[k] if f and type(f) == 'function' then f = function(...) buffer[k](buffer, ...) end elseif f == nil then f = view[k] or ui[k] or _G[k] end return f end, __newindex = function(t, k, v) for _, t2 in ipairs{buffer, view, ui} do if t2[k] ~= nil then t2[k] = v return end end rawset(t, k, v) end, }) -- Executes string *code* as Lua code that is subject to an "abbreviated" -- environment. -- In this environment, the contents of the `buffer`, `view`, and `ui` tables -- are also considered as global functions and fields. -- Prints the results of '=' expressions like in the Lua prompt. -- @param code The Lua code to execute. local function execute_lua(code) if code:find('^=') then code = 'return '..code:sub(2) end local result = assert(load(code, nil, 'bt', env))() if result ~= nil or code:find('^return ') then ui.print(result) end events.emit(events.UPDATE_UI) end args.register('-e', '--execute', 1, execute_lua, 'Execute Lua code') -- Shows a set of Lua code completions for the entry's text, subject to an -- "abbreviated" environment where the `buffer`, `view`, and `ui` tables are -- also considered as globals. local function complete_lua() local symbol, op, part = M:get_text():match('([%w_.]-)([%.:]?)([%w_]*)$') local ok, result = pcall((load('return ('..symbol..')', nil, 'bt', env))) local cmpls = {} part = '^'..part if (not ok or type(result) ~= 'table') and symbol ~= '' then return end if not ok then -- shorthand notation local pool = { buffer, view, ui, _G, _SCINTILLA.functions, _SCINTILLA.properties } for i = 1, #pool do for k in pairs(pool[i]) do if type(k) == 'string' and k:find(part) then cmpls[#cmpls + 1] = k end end end else for k in pairs(result) do if type(k) == 'string' and k:find(part) then cmpls[#cmpls + 1] = k end end if symbol == 'buffer' and op == ':' then for f in pairs(_SCINTILLA.functions) do if f:find(part) then cmpls[#cmpls + 1] = f end end elseif symbol == 'buffer' and op == '.' then for p in pairs(_SCINTILLA.properties) do if p:find(part) then cmpls[#cmpls + 1] = p end end end end table.sort(cmpls) M:auto_c_show(#part - 1, table.concat(cmpls, ' ')) end -- Define key mode for entering Lua commands. keys.lua_command = setmetatable({ ['\t'] = complete_lua, ['\n'] = {M.finish_mode, execute_lua}, }, M.editing_keys) -- Configure the command entry's default properties. events.connect(events.INITIALIZED, function() if not arg then return end -- no need to reconfigure on reset M.h_scroll_bar, M.v_scroll_bar = false, false M.margin_width_n[0], M.margin_width_n[1], M.margin_width_n[2] = 0, 0, 0 if not CURSES then M.height = M:text_height(1) end M:set_lexer('lua') end) --[[ The function below is a Lua C function. --- -- Opens the Lua command entry. -- @class function -- @name focus local focus ]]
Fixed autocomplete bug in curses; modules/textadept/command_entry.lua
Fixed autocomplete bug in curses; modules/textadept/command_entry.lua
Lua
mit
rgieseke/textadept,rgieseke/textadept
8b13d4ab9b3bd805cf062643fba4aa37f6b9d527
Modules/Shared/Character/HumanoidTracker.lua
Modules/Shared/Character/HumanoidTracker.lua
--- Tracks a player's character's humanoid -- @classmod HumanoidTracker local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore")) local fastSpawn = require("fastSpawn") local Maid = require("Maid") local Signal = require("Signal") local ValueObject = require("ValueObject") local Promise = require("Promise") local HumanoidTracker = {} HumanoidTracker.ClassName = "HumanoidTracker" HumanoidTracker.__index = HumanoidTracker function HumanoidTracker.new(player) local self = setmetatable({}, HumanoidTracker) self._player = player or error("No player") self._maid = Maid.new() --- Tracks the current character humanoid, may be nil self.Humanoid = ValueObject.new() self._maid:GiveTask(self.Humanoid) --- Tracks the alive humanoid, may be nil self.AliveHumanoid = ValueObject.new() self._maid:GiveTask(self.AliveHumanoid) self._maid:GiveTask(self.Humanoid.Changed:Connect(function(newHumanoid, oldHumanoid, maid) self:_handleHumanoidChanged(newHumanoid, oldHumanoid, maid) end)) self._maid:GiveTask(self._player.CharacterAdded:Connect(function(character) self:_handleCharacter(character) end)) if self._player.Character then fastSpawn(self._handleCharacter, self, self._player.Character) end self.HumanoidDied = Signal.new() self._maid:GiveTask(self.HumanoidDied) return self end function HumanoidTracker:PromiseNextHumanoid() if self.Humanoid.Value then return Promise.resolved(self.Humanoid.Value) end if self._maid._nextHumanoidPromise then return self._maid._nextHumanoidPromise end local promise = Promise.new() local conn = self.Humanoid.Changed:Connect(function(newValue) if newValue then promise:Resolve(newValue) end end) promise:Finally(function() conn:Disconnect() end) self._maid._nextHumanoidPromise = promise return promise end function HumanoidTracker:_handleCharacter(character) local maid = Maid.new() self._maid._characterMaid = maid local humanoid = character:FindFirstChildOfClass("Humanoid") if humanoid then self.Humanoid.Value = humanoid return end self.Humanoid.Value = nil -- Listen for changes maid._childAdded = character.ChildAdded:Connect(function(child) if child:IsA("Humanoid") then maid._childAdded = nil self.Humanoid.Value = child end end) end function HumanoidTracker:_handleHumanoidChanged(newHumanoid, oldHumanoid, maid) if not newHumanoid then self.AliveHumanoid.Value = nil return end if newHumanoid.Health <= 0 then self.AliveHumanoid.Value = nil return end self.AliveHumanoid.Value = newHumanoid maid:GiveTask(newHumanoid.Died:Connect(function() self.AliveHumanoid.Value = nil -- AliveHumanoid changing may proc .Destroy method if self.Destroy then self.HumanoidDied:Fire(newHumanoid) end end)) end function HumanoidTracker:Destroy() self._maid:DoCleaning() setmetatable(self, nil) end return HumanoidTracker
--- Tracks a player's character's humanoid -- @classmod HumanoidTracker local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore")) local fastSpawn = require("fastSpawn") local Maid = require("Maid") local Signal = require("Signal") local ValueObject = require("ValueObject") local Promise = require("Promise") local HumanoidTracker = {} HumanoidTracker.ClassName = "HumanoidTracker" HumanoidTracker.__index = HumanoidTracker function HumanoidTracker.new(player) local self = setmetatable({}, HumanoidTracker) self._player = player or error("No player") self._maid = Maid.new() --- Tracks the current character humanoid, may be nil self.Humanoid = ValueObject.new() self._maid:GiveTask(self.Humanoid) --- Tracks the alive humanoid, may be nil self.AliveHumanoid = ValueObject.new() self._maid:GiveTask(self.AliveHumanoid) self._maid:GiveTask(self.Humanoid.Changed:Connect(function(newHumanoid, oldHumanoid, maid) self:_handleHumanoidChanged(newHumanoid, oldHumanoid, maid) end)) self._maid:GiveTask(self._player:GetPropertyChangedSignal("Character"):Connect(function() self:_onCharacterChanged() end)) fastSpawn(self._onCharacterChanged, self) self.HumanoidDied = Signal.new() self._maid:GiveTask(self.HumanoidDied) return self end function HumanoidTracker:PromiseNextHumanoid() if self.Humanoid.Value then return Promise.resolved(self.Humanoid.Value) end if self._maid._nextHumanoidPromise then return self._maid._nextHumanoidPromise end local promise = Promise.new() local conn = self.Humanoid.Changed:Connect(function(newValue) if newValue then promise:Resolve(newValue) end end) promise:Finally(function() conn:Disconnect() end) self._maid._nextHumanoidPromise = promise return promise end function HumanoidTracker:_onCharacterChanged() local maid = Maid.new() self._maid._characterMaid = maid local character = self._player.Character if not character then self.Humanoid.Value = nil return end local humanoid = character:FindFirstChildOfClass("Humanoid") if humanoid then self.Humanoid.Value = humanoid -- TODO: Track if this humanoid goes away return end self.Humanoid.Value = nil -- Listen for changes maid._childAdded = character.ChildAdded:Connect(function(child) if child:IsA("Humanoid") then maid._childAdded = nil self.Humanoid.Value = child -- TODO: Track if this humanoid goes away end end) end function HumanoidTracker:_handleHumanoidChanged(newHumanoid, oldHumanoid, maid) if not newHumanoid then self.AliveHumanoid.Value = nil return end if newHumanoid.Health <= 0 then self.AliveHumanoid.Value = nil return end self.AliveHumanoid.Value = newHumanoid maid:GiveTask(newHumanoid.Died:Connect(function() self.AliveHumanoid.Value = nil -- AliveHumanoid changing may proc .Destroy method if self.Destroy then self.HumanoidDied:Fire(newHumanoid) end end)) end function HumanoidTracker:Destroy() self._maid:DoCleaning() setmetatable(self, nil) end return HumanoidTracker
Fix humanoid tracking so it untracks on character change
Fix humanoid tracking so it untracks on character change
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
2420557085ecd34a330b786437c296121bcfc4a0
frontend/document/doccache.lua
frontend/document/doccache.lua
--[[ "Global" LRU cache used by Document & friends. --]] local Cache = require("cache") local CanvasContext = require("document/canvascontext") local DataStorage = require("datastorage") local lfs = require("libs/libkoreader-lfs") local logger = require("logger") local md5 = require("ffi/sha2").md5 local util = require("util") local DHINTCOUNT = G_defaults:readSetting("DHINTCOUNT") local function calcCacheMemSize() local min = G_defaults:readSetting("DGLOBAL_CACHE_SIZE_MINIMUM") local max = G_defaults:readSetting("DGLOBAL_CACHE_SIZE_MAXIMUM") local calc = util.calcFreeMem() * (G_defaults:readSetting("DGLOBAL_CACHE_FREE_PROPORTION") or 0) return math.min(max, math.max(min, calc)) end local doccache_size = calcCacheMemSize() local function computeCacheSize() local mb_size = doccache_size / 1024 / 1024 -- If we end up with a not entirely ridiculous cache size, use that... if mb_size >= 8 then logger.dbg(string.format("Allocating a %dMB budget for the global document cache", mb_size)) return doccache_size else return nil end end local function computeCacheSlots() local mb_size = doccache_size / 1024 / 1024 --- ...otherwise, effectively disable the cache by making it single slot... if mb_size < 8 then logger.dbg(string.format("Setting up a minimal single slot global document cache")) return 1 else return nil end end local DocCache = Cache:new{ slots = computeCacheSlots(), size = computeCacheSize(), -- Average item size is a screen's worth of bitmap, mixed with a few much smaller tables (pgdim, pglinks, etc.), hence the / 3 avg_itemsize = math.floor(CanvasContext:getWidth() * CanvasContext:getHeight() * (CanvasContext.is_color_rendering_enabled and 4 or 1) / 3), -- Rely on CacheItem's eviction callback to free resources *immediately* on eviction. enable_eviction_cb = true, disk_cache = true, cache_path = DataStorage:getDataDir() .. "/cache/", } function DocCache:serialize(doc_path) if not self.disk_cache then return end -- Calculate the current disk cache size local cached_size = 0 local sorted_caches = {} for _, file in pairs(self.cached) do table.insert(sorted_caches, {file=file, time=lfs.attributes(file, "access")}) cached_size = cached_size + (lfs.attributes(file, "size") or 0) end table.sort(sorted_caches, function(v1, v2) return v1.time > v2.time end) -- Rewind a bit in order to serialize the currently *displayed* page for the current document, -- as the actual MRU item would be the most recently *hinted* page, which wouldn't be helpful ;). if doc_path then local mru_key local mru_found = 0 for key, item in self.cache:pairs() do -- Only dump items that actually request persistence and match the current document. if item.persistent and item.dump and item.doc_path == doc_path then mru_key = key mru_found = mru_found + 1 if mru_found >= (1 + DHINTCOUNT) then -- We found the right item, i.e., the *displayed* page break end end end if mru_key then local cache_full_path = self.cache_path .. md5(mru_key) local cache_file_exists = lfs.attributes(cache_full_path) if not cache_file_exists then logger.dbg("Dumping cache item", mru_key) local cache_item = self.cache:get(mru_key) local cache_size = cache_item:dump(cache_full_path) if cache_size then cached_size = cached_size + cache_size end end end end -- Allocate the same amount of storage to the disk cache than the memory cache while cached_size > self.size do -- discard the least recently used cache local discarded = table.remove(sorted_caches) if discarded then cached_size = cached_size - lfs.attributes(discarded.file, "size") os.remove(discarded.file) else logger.warn("Cache accounting is broken") break end end -- We may have updated the disk cache's content, so refresh its state self:refreshSnapshot() end return DocCache
--[[ "Global" LRU cache used by Document & friends. --]] local Cache = require("cache") local CanvasContext = require("document/canvascontext") local DataStorage = require("datastorage") local lfs = require("libs/libkoreader-lfs") local logger = require("logger") local md5 = require("ffi/sha2").md5 local util = require("util") local DHINTCOUNT = G_defaults:readSetting("DHINTCOUNT") local function calcCacheMemSize() local min = G_defaults:readSetting("DGLOBAL_CACHE_SIZE_MINIMUM") local max = G_defaults:readSetting("DGLOBAL_CACHE_SIZE_MAXIMUM") local memfree, _ = util.calcFreeMem() or 0, 0 local calc = memfree * G_defaults:readSetting("DGLOBAL_CACHE_FREE_PROPORTION") return math.min(max, math.max(min, calc)) end local doccache_size = calcCacheMemSize() local function computeCacheSize() local mb_size = doccache_size / 1024 / 1024 -- If we end up with a not entirely ridiculous cache size, use that... if mb_size >= 8 then logger.dbg(string.format("Allocating a %dMB budget for the global document cache", mb_size)) return doccache_size else return nil end end local function computeCacheSlots() local mb_size = doccache_size / 1024 / 1024 --- ...otherwise, effectively disable the cache by making it single slot... if mb_size < 8 then logger.dbg(string.format("Setting up a minimal single slot global document cache")) return 1 else return nil end end local DocCache = Cache:new{ slots = computeCacheSlots(), size = computeCacheSize(), -- Average item size is a screen's worth of bitmap, mixed with a few much smaller tables (pgdim, pglinks, etc.), hence the / 3 avg_itemsize = math.floor(CanvasContext:getWidth() * CanvasContext:getHeight() * (CanvasContext.is_color_rendering_enabled and 4 or 1) / 3), -- Rely on CacheItem's eviction callback to free resources *immediately* on eviction. enable_eviction_cb = true, disk_cache = true, cache_path = DataStorage:getDataDir() .. "/cache/", } function DocCache:serialize(doc_path) if not self.disk_cache then return end -- Calculate the current disk cache size local cached_size = 0 local sorted_caches = {} for _, file in pairs(self.cached) do table.insert(sorted_caches, {file=file, time=lfs.attributes(file, "access")}) cached_size = cached_size + (lfs.attributes(file, "size") or 0) end table.sort(sorted_caches, function(v1, v2) return v1.time > v2.time end) -- Rewind a bit in order to serialize the currently *displayed* page for the current document, -- as the actual MRU item would be the most recently *hinted* page, which wouldn't be helpful ;). if doc_path then local mru_key local mru_found = 0 for key, item in self.cache:pairs() do -- Only dump items that actually request persistence and match the current document. if item.persistent and item.dump and item.doc_path == doc_path then mru_key = key mru_found = mru_found + 1 if mru_found >= (1 + DHINTCOUNT) then -- We found the right item, i.e., the *displayed* page break end end end if mru_key then local cache_full_path = self.cache_path .. md5(mru_key) local cache_file_exists = lfs.attributes(cache_full_path) if not cache_file_exists then logger.dbg("Dumping cache item", mru_key) local cache_item = self.cache:get(mru_key) local cache_size = cache_item:dump(cache_full_path) if cache_size then cached_size = cached_size + cache_size end end end end -- Allocate the same amount of storage to the disk cache than the memory cache while cached_size > self.size do -- discard the least recently used cache local discarded = table.remove(sorted_caches) if discarded then cached_size = cached_size - lfs.attributes(discarded.file, "size") os.remove(discarded.file) else logger.warn("Cache accounting is broken") break end end -- We may have updated the disk cache's content, so refresh its state self:refreshSnapshot() end return DocCache
DocCache: Unbreak on !Linux platforms (#9566)
DocCache: Unbreak on !Linux platforms (#9566) Regression since #9529 Fix #9565
Lua
agpl-3.0
poire-z/koreader,Frenzie/koreader,NiLuJe/koreader,poire-z/koreader,NiLuJe/koreader,koreader/koreader,Frenzie/koreader,koreader/koreader
623359772af1753844cd3e6826ed41b252993f94
scripts/tundra/path.lua
scripts/tundra/path.lua
-- Copyright 2010 Andreas Fredriksson -- -- This file is part of Tundra. -- -- Tundra is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- Tundra is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with Tundra. If not, see <http://www.gnu.org/licenses/>. module(..., package.seeall) local native = require "tundra.native" function split(fn) local dir, file = fn:match("^(.*)[/\\]([^\\/]*)$") if not dir then return ".", fn else return dir, file end end normalize = native.sanitize_path function join(dir, fn) return normalize(dir .. '/' .. fn) end function get_filename_dir(fn) return select(1, split(fn)) end function get_filename(fn) return select(2, split(fn)) end function get_extension(fn) return fn:match("(%.[^.]+)$") or "" end function drop_suffix(fn) assert(type(fn) == "string") return fn:match("^(.*)%.[^./\\]+$") or fn end function get_filename_base(fn) assert(fn, "nil filename") local _,_,stem = fn:find("([^/\\]+)%.[^.]*$") if stem then return stem end _,_,stem = fn:find("([^/\\]+)$") return stem end function make_object_filename(env, src_fn, suffix) local object_fn -- Drop leading $(OBJECTDIR)[/\\] in the input filename. do local pname = src_fn:match("^%$%(OBJECTDIR%)[/\\](.*)$") if pname then object_fn = pname else object_fn = src_fn end end -- Compute path under OBJECTDIR we want for the resulting object file. -- Replace ".." with "dotdot" to avoid creating files outside the -- object directory. do local relative_name = drop_suffix(object_fn:gsub("%.%.", "dotdot")) object_fn = "$(OBJECTDIR)/$(UNIT_PREFIX)/" .. relative_name .. suffix end return object_fn end
-- Copyright 2010 Andreas Fredriksson -- -- This file is part of Tundra. -- -- Tundra is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- Tundra is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with Tundra. If not, see <http://www.gnu.org/licenses/>. module(..., package.seeall) local native = require "tundra.native" function split(fn) local dir, file = fn:match("^(.*)[/\\]([^\\/]*)$") if not dir then return ".", fn else return dir, file end end normalize = native.sanitize_path function join(dir, fn) return normalize(dir .. '/' .. fn) end function get_filename_dir(fn) return select(1, split(fn)) end function get_filename(fn) return select(2, split(fn)) end function get_extension(fn) return fn:match("(%.[^.]+)$") or "" end function drop_suffix(fn) assert(type(fn) == "string") return fn:match("^(.*)%.[^./\\]+$") or fn end function get_filename_base(fn) assert(fn, "nil filename") local _,_,stem = fn:find("([^/\\]+)%.[^.]*$") if stem then return stem end _,_,stem = fn:find("([^/\\]+)$") return stem end function make_object_filename(env, src_fn, suffix) local object_fn local src_suffix = get_extension(src_fn):sub(2) -- Drop leading $(OBJECTDIR)[/\\] in the input filename. do local pname = src_fn:match("^%$%(OBJECTDIR%)[/\\](.*)$") if pname then object_fn = pname else object_fn = src_fn end end -- Compute path under OBJECTDIR we want for the resulting object file. -- Replace ".." with "dotdot" to avoid creating files outside the -- object directory. Also salt the generated object name with the source -- suffix, so that multiple source files with the same base name don't end -- up clobbering each other (Tundra emits an error for this when checking -- the DAG) do local relative_name = drop_suffix(object_fn:gsub("%.%.", "dotdot")) object_fn = "$(OBJECTDIR)/$(UNIT_PREFIX)/" .. relative_name .. "__" .. src_suffix .. suffix end return object_fn end
Add source suffix to object filenames.
Add source suffix to object filenames. This allows code to have multiple source files with the same base name, for example foo.c and foo.asm can both be used in the same unit. Previously, an error was printed in this case due to a DAG conflict.
Lua
mit
bmharper/tundra,deplinenoise/tundra,deplinenoise/tundra,bmharper/tundra,deplinenoise/tundra,bmharper/tundra,bmharper/tundra
2f8a38258d654e8f2448e9266aa42427770c34ba
entity/bump.lua
entity/bump.lua
local Bump = {} Bump.__index = Bump function Bump.create(def, game) local bump = { game = game, x = def.x, y = def.y, timer = 0 } setmetatable(bump, Bump) table.insert(game.bumps, bump) bump.body = love.physics.newBody(game.world, def.x, def.y,"static") bump.body:setUserData(bump) local fixture = love.physics.newFixture(bump.body, love.physics.newCircleShape(BUMP_RADIUS), 1) return bump end function Bump:collisionBegin(other, collision) local body = other:getBody(); if body then local x, y = body:getPosition(); local dirX, dirY = vector.normalize(vector.sub(self.x, self.y, x, y)); body:setLinearVelocity(vector.mul(-1 * BUMP_FORCE, dirX, dirY)) self.timer = BUMP_PUSH_ANIMATION end end function Bump:update(dt) if self.timer > 0 then self.timer = self.timer - dt; end end function Bump:draw() local alpha = self.timer / BUMP_PUSH_ANIMATION; if(alpha <= 0) then alpha = 0 end alpha = alpha * 0.75 + 0.25 love.graphics.setColor(255,255,255, alpha * 255) love.graphics.circle('fill', self.x, self.y, BUMP_RADIUS) end return Bump
local Bump = {} Bump.__index = Bump function Bump.create(def, game) local bump = { game = game, x = def.x, y = def.y, timer = 0 } setmetatable(bump, Bump) table.insert(game.bumps, bump) bump.body = love.physics.newBody(game.world, def.x, def.y,"static") bump.body:setUserData(bump) local fixture = love.physics.newFixture(bump.body, love.physics.newCircleShape(BUMP_RADIUS), 1) return bump end function Bump:collisionBegin(other, collision) local body = other:getBody(); if body then local x, y = body:getPosition(); local dirX, dirY = vector.normalize(vector.sub(self.x, self.y, x, y)); body:setLinearVelocity(vector.mul(-1 * BUMP_FORCE, dirX, dirY)) self.timer = BUMP_PUSH_ANIMATION end end function Bump:update(dt) if self.timer > 0 then self.timer = self.timer - dt; end end function Bump:draw() local alpha = self.timer / BUMP_PUSH_ANIMATION; if(alpha <= 0) then alpha = 0 end alpha = alpha * 0.75 + 0.25 love.graphics.setColor(255,255,255, alpha * 255) love.graphics.circle('fill', self.x, self.y, BUMP_RADIUS) love.graphics.setColor(255,255,255,255) end return Bump
Fix transparency issue
Fix transparency issue
Lua
mit
GuiSim/pixel
678c0b2d5ba77092ca4c422b6a3c3e3eefe86b01
applications/luci-app-mwan3/luasrc/model/cbi/mwan/rule.lua
applications/luci-app-mwan3/luasrc/model/cbi/mwan/rule.lua
-- Copyright 2014 Aedan Renner <[email protected]> -- Copyright 2018 Florian Eckert <[email protected]> -- Licensed to the public under the GNU General Public License v2. local dsp = require "luci.dispatcher" local uci = require "uci" local m, mwan_rule, src_ip, src_port, dest_ip, dest_port, proto, use_policy function ruleCheck() local rule_error = {} uci.cursor():foreach("mwan3", "rule", function (section) rule_error[section[".name"]] = false local uci = uci.cursor(nil, "/var/state") local sourcePort = uci:get("mwan3", section[".name"], "src_port") local destPort = uci:get("mwan3", section[".name"], "dest_port") if sourcePort ~= nil or destPort ~= nil then local protocol = uci:get("mwan3", section[".name"], "proto") if protocol == nil or protocol == "all" then rule_error[section[".name"]] = true end end end ) return rule_error end function ruleWarn(rule_error) local warnings = "" for i, k in pairs(rule_error) do if rule_error[i] == true then warnings = warnings .. string.format("<strong>%s</strong><br />", translatef("WARNING: Rule %s have a port configured with no or improper protocol specified!", i) ) end end return warnings end m = Map("mwan3", translate("MWAN - Rules"), ruleWarn(ruleCheck()) ) mwan_rule = m:section(TypedSection, "rule", nil, translate("Rules specify which traffic will use a particular MWAN policy<br />" .. "Rules are based on IP address, port or protocol<br />" .. "Rules are matched from top to bottom<br />" .. "Rules below a matching rule are ignored<br />" .. "Traffic not matching any rule is routed using the main routing table<br />" .. "Traffic destined for known (other than default) networks is handled by the main routing table<br />" .. "Traffic matching a rule, but all WAN interfaces for that policy are down will be blackholed<br />" .. "Names may contain characters A-Z, a-z, 0-9, _ and no spaces<br />" .. "Rules may not share the same name as configured interfaces, members or policies")) mwan_rule.addremove = true mwan_rule.anonymous = false mwan_rule.dynamic = false mwan_rule.sectionhead = translate("Rule") mwan_rule.sortable = true mwan_rule.template = "cbi/tblsection" mwan_rule.extedit = dsp.build_url("admin", "network", "mwan", "rule", "%s") function mwan_rule.create(self, section) TypedSection.create(self, section) m.uci:save("mwan3") luci.http.redirect(dsp.build_url("admin", "network", "mwan", "rule", section)) end src_ip = mwan_rule:option(DummyValue, "src_ip", translate("Source address")) src_ip.rawhtml = true function src_ip.cfgvalue(self, s) return self.map:get(s, "src_ip") or "&#8212;" end src_port = mwan_rule:option(DummyValue, "src_port", translate("Source port")) src_port.rawhtml = true function src_port.cfgvalue(self, s) return self.map:get(s, "src_port") or "&#8212;" end dest_ip = mwan_rule:option(DummyValue, "dest_ip", translate("Destination address")) dest_ip.rawhtml = true function dest_ip.cfgvalue(self, s) return self.map:get(s, "dest_ip") or "&#8212;" end dest_port = mwan_rule:option(DummyValue, "dest_port", translate("Destination port")) dest_port.rawhtml = true function dest_port.cfgvalue(self, s) return self.map:get(s, "dest_port") or "&#8212;" end proto = mwan_rule:option(DummyValue, "proto", translate("Protocol")) proto.rawhtml = true function proto.cfgvalue(self, s) return self.map:get(s, "proto") or "all" end use_policy = mwan_rule:option(DummyValue, "use_policy", translate("Policy assigned")) use_policy.rawhtml = true function use_policy.cfgvalue(self, s) return self.map:get(s, "use_policy") or "&#8212;" end return m
-- Copyright 2014 Aedan Renner <[email protected]> -- Copyright 2018 Florian Eckert <[email protected]> -- Licensed to the public under the GNU General Public License v2. local dsp = require "luci.dispatcher" local uci = require "uci" local m, mwan_rule, src_ip, src_port, dest_ip, dest_port, proto, use_policy function ruleCheck() local rule_error = {} uci.cursor():foreach("mwan3", "rule", function (section) rule_error[section[".name"]] = false local uci = uci.cursor(nil, "/var/state") local sourcePort = uci:get("mwan3", section[".name"], "src_port") local destPort = uci:get("mwan3", section[".name"], "dest_port") if sourcePort ~= nil or destPort ~= nil then local protocol = uci:get("mwan3", section[".name"], "proto") if protocol == nil or protocol == "all" then rule_error[section[".name"]] = true end end end ) return rule_error end function ruleWarn(rule_error) local warnings = "" for i, k in pairs(rule_error) do if rule_error[i] == true then warnings = warnings .. string.format("<strong>%s</strong><br />", translatef("WARNING: Rule %s have a port configured with no or improper protocol specified!", i) ) end end return warnings end m = Map("mwan3", translate("MWAN - Rules"), ruleWarn(ruleCheck()) ) mwan_rule = m:section(TypedSection, "rule", nil, translate("Rules specify which traffic will use a particular MWAN policy<br />" .. "Rules are based on IP address, port or protocol<br />" .. "Rules are matched from top to bottom<br />" .. "Rules below a matching rule are ignored<br />" .. "Traffic not matching any rule is routed using the main routing table<br />" .. "Traffic destined for known (other than default) networks is handled by the main routing table<br />" .. "Traffic matching a rule, but all WAN interfaces for that policy are down will be blackholed<br />" .. "Names may contain characters A-Z, a-z, 0-9, _ and no spaces<br />" .. "Rules may not share the same name as configured interfaces, members or policies")) mwan_rule.addremove = true mwan_rule.anonymous = false mwan_rule.dynamic = false mwan_rule.sectionhead = translate("Rule") mwan_rule.sortable = true mwan_rule.template = "cbi/tblsection" mwan_rule.extedit = dsp.build_url("admin", "network", "mwan", "rule", "%s") function mwan_rule.create(self, section) if #section > 15 then self.invalid_cts = true else TypedSection.create(self, section) m.uci:save("mwan3") luci.http.redirect(dsp.build_url("admin", "network", "mwan", "rule", section)) end end src_ip = mwan_rule:option(DummyValue, "src_ip", translate("Source address")) src_ip.rawhtml = true function src_ip.cfgvalue(self, s) return self.map:get(s, "src_ip") or "&#8212;" end src_port = mwan_rule:option(DummyValue, "src_port", translate("Source port")) src_port.rawhtml = true function src_port.cfgvalue(self, s) return self.map:get(s, "src_port") or "&#8212;" end dest_ip = mwan_rule:option(DummyValue, "dest_ip", translate("Destination address")) dest_ip.rawhtml = true function dest_ip.cfgvalue(self, s) return self.map:get(s, "dest_ip") or "&#8212;" end dest_port = mwan_rule:option(DummyValue, "dest_port", translate("Destination port")) dest_port.rawhtml = true function dest_port.cfgvalue(self, s) return self.map:get(s, "dest_port") or "&#8212;" end proto = mwan_rule:option(DummyValue, "proto", translate("Protocol")) proto.rawhtml = true function proto.cfgvalue(self, s) return self.map:get(s, "proto") or "all" end use_policy = mwan_rule:option(DummyValue, "use_policy", translate("Policy assigned")) use_policy.rawhtml = true function use_policy.cfgvalue(self, s) return self.map:get(s, "use_policy") or "&#8212;" end return m
luci-app-mwan3: check rule name length on create
luci-app-mwan3: check rule name length on create fixes #13499 Signed-off-by: Florian Eckert <[email protected]>
Lua
apache-2.0
lbthomsen/openwrt-luci,hnyman/luci,hnyman/luci,hnyman/luci,hnyman/luci,openwrt/luci,hnyman/luci,hnyman/luci,lbthomsen/openwrt-luci,openwrt/luci,hnyman/luci,hnyman/luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,openwrt/luci,lbthomsen/openwrt-luci,openwrt/luci,openwrt/luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,openwrt/luci,lbthomsen/openwrt-luci,openwrt/luci,openwrt/luci
a520d887d67fb32b4e781d6ad914f4c5eee96f2d
test_scripts/Defects/5_0/2670_4_GetInteriorVD_after_ignition_off.lua
test_scripts/Defects/5_0/2670_4_GetInteriorVD_after_ignition_off.lua
--------------------------------------------------------------------------------------------------- -- User story: https://github.com/smartdevicelink/sdl_core/issues/2670 -- -- Steps to reproduce: -- 1. default section in preloaded_pt.json is defined without moduleType parameter -- 2. Update groups in default with "RemoteControl" group -- 3. Register RC app -- 4. App requests GetInteriorVD with module_1 with DISALLOWED resultCode in response from SDL -- 5. AApp requests GetInteriorVD with module_2 with DISALLOWED resultCode in response from SDL -- 6. Perform IGN_OFF and IGN_ON -- 7. Register same RC app -- 8. Request GetInteriorVD with allowed module_1 -- 9. Request GetInteriorVD with allowed module_2 -- SDL must: -- 1. process GetInteriorVD with not allowed module_1 and respond with DISALLOWED resultCode to mobile app -- 2. process GetInteriorVD with not allowed module_2 and respond with DISALLOWED resultCode to mobile app --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local runner = require('user_modules/script_runner') local commonRC = require('test_scripts/RC/commonRC') local actions = require("user_modules/sequences/actions") local test = require("user_modules/dummy_connecttest") local commonPreconditions = require('user_modules/shared_testcases/commonPreconditions') local commonFunctions = require("user_modules/shared_testcases/commonFunctions") local json = require("modules/json") local utils = require('user_modules/utils') --[[ Test Configuration ]] runner.testSettings.isSelfIncluded = false --[[ Local function ]] local function updatePreloadedPT() local preloadedFile = commonPreconditions:GetPathToSDL() .. commonFunctions:read_parameter_from_smart_device_link_ini("PreloadedPT") local preloadedTable = utils.jsonFileToTable(preloadedFile) preloadedTable.policy_table.functional_groupings["DataConsent-2"].rpcs = json.null preloadedTable.policy_table.functional_groupings["RemoteControl"].rpcs.OnRCStatus = { hmi_levels = { "FULL", "BACKGROUND", "LIMITED", "NONE" } } preloadedTable.policy_table.app_policies.default.groups = {"Base-4", "RemoteControl"} preloadedTable.policy_table.app_policies.default.moduleType = nil utils.tableToJsonFile(preloadedTable, preloadedFile) end local function preconditions() actions.preconditions() updatePreloadedPT() end local function ignitionOff() actions.getHMIConnection():SendNotification("BasicCommunication.OnExitAllApplications", { reason = "SUSPEND" }) EXPECT_HMINOTIFICATION("BasicCommunication.OnSDLPersistenceComplete") :Do(function() actions.getHMIConnection():SendNotification("BasicCommunication.OnExitAllApplications",{ reason = "IGNITION_OFF" }) actions.getMobileSession():ExpectNotification("OnAppInterfaceUnregistered", { reason = "IGNITION_OFF" }) end) EXPECT_HMINOTIFICATION("BasicCommunication.OnAppUnregistered", { unexpectedDisconnect = false }) EXPECT_HMINOTIFICATION("BasicCommunication.OnSDLClose") :Do(function() test.mobileSession[1] = nil StopSDL() end) end --[[ Scenario ]] runner.Title("Preconditions") runner.Step("Clean environment", preconditions) runner.Step("Backup preloaded pt", commonPreconditions.BackupFile, { test, "sdl_preloaded_pt.json" }) runner.Step("Start SDL, HMI, connect Mobile, start Session", actions.start) runner.Step("RAI", actions.registerAppWOPTU) runner.Step("Activate App", actions.activateApp) -- runner.Title("Test") runner.Step("GetInteriorVehicleData SEAT", commonRC.rpcDenied, { "SEAT", 1, "GetInteriorVehicleData", "DISALLOWED" }) runner.Step("GetInteriorVehicleData RADIO", commonRC.rpcDenied, { "RADIO", 1, "GetInteriorVehicleData", "DISALLOWED" }) runner.Step("ignitionOff", ignitionOff) runner.Step("Start SDL, HMI, connect Mobile, start Session", actions.start) runner.Step("RAI", actions.registerAppWOPTU) runner.Step("Activate App", actions.activateApp) runner.Step("GetInteriorVehicleData SEAT", commonRC.rpcDenied, { "SEAT", 1, "GetInteriorVehicleData", "DISALLOWED" }) runner.Step("GetInteriorVehicleData RADIO", commonRC.rpcDenied, { "RADIO", 1, "GetInteriorVehicleData", "DISALLOWED" }) runner.Title("Postconditions") runner.Step("Restore preloaded pt", commonPreconditions.RestoreFile, { test, "sdl_preloaded_pt.json" }) runner.Step("Stop SDL", actions.postconditions)
--------------------------------------------------------------------------------------------------- -- User story: https://github.com/smartdevicelink/sdl_core/issues/2670 -- -- Steps to reproduce: -- 1. default section in preloaded_pt.json is defined without moduleType parameter -- 2. Update groups in default with "RemoteControl" group -- 3. Register RC app -- 4. App requests GetInteriorVD with module_1 with DISALLOWED resultCode in response from SDL -- 5. AApp requests GetInteriorVD with module_2 with DISALLOWED resultCode in response from SDL -- 6. Perform IGN_OFF and IGN_ON -- 7. Register same RC app -- 8. Request GetInteriorVD with allowed module_1 -- 9. Request GetInteriorVD with allowed module_2 -- SDL must: -- 1. process GetInteriorVD with not allowed module_1 and respond with DISALLOWED resultCode to mobile app -- 2. process GetInteriorVD with not allowed module_2 and respond with DISALLOWED resultCode to mobile app --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local runner = require('user_modules/script_runner') local commonRC = require('test_scripts/RC/commonRC') local actions = require("user_modules/sequences/actions") --[[ Test Configuration ]] runner.testSettings.isSelfIncluded = false --[[ Local function ]] local function updatePreloadedPT() local preloadedTable = actions.sdl.getPreloadedPT() preloadedTable.policy_table.functional_groupings["DataConsent-2"].rpcs = actions.json.null preloadedTable.policy_table.functional_groupings["RemoteControl"].rpcs.OnRCStatus = { hmi_levels = { "FULL", "BACKGROUND", "LIMITED", "NONE" } } preloadedTable.policy_table.app_policies.default.groups = {"Base-4", "RemoteControl"} preloadedTable.policy_table.app_policies.default.moduleType = nil actions.sdl.setPreloadedPT(preloadedTable) end local function ignitionOff() actions.getHMIConnection():SendNotification("BasicCommunication.OnExitAllApplications", { reason = "SUSPEND" }) EXPECT_HMINOTIFICATION("BasicCommunication.OnSDLPersistenceComplete") :Do(function() actions.getHMIConnection():SendNotification("BasicCommunication.OnExitAllApplications",{ reason = "IGNITION_OFF" }) actions.getMobileSession():ExpectNotification("OnAppInterfaceUnregistered", { reason = "IGNITION_OFF" }) end) EXPECT_HMINOTIFICATION("BasicCommunication.OnAppUnregistered", { unexpectedDisconnect = false }) EXPECT_HMINOTIFICATION("BasicCommunication.OnSDLClose") :Do(function() actions.mobile.closeSession() StopSDL() end) end --[[ Scenario ]] runner.Title("Preconditions") runner.Step("Clean environment", actions.preconditions) runner.Step("Update SDL preloadedPT", updatePreloadedPT) runner.Step("Start SDL, HMI, connect Mobile, start Session", actions.start) runner.Step("RAI", actions.registerAppWOPTU) runner.Step("Activate App", actions.activateApp) -- runner.Title("Test") runner.Step("GetInteriorVehicleData SEAT", commonRC.rpcDenied, { "SEAT", 1, "GetInteriorVehicleData", "DISALLOWED" }) runner.Step("GetInteriorVehicleData RADIO", commonRC.rpcDenied, { "RADIO", 1, "GetInteriorVehicleData", "DISALLOWED" }) runner.Step("ignitionOff", ignitionOff) runner.Step("Start SDL, HMI, connect Mobile, start Session", actions.start) runner.Step("RAI", actions.registerAppWOPTU) runner.Step("Activate App", actions.activateApp) runner.Step("GetInteriorVehicleData SEAT", commonRC.rpcDenied, { "SEAT", 1, "GetInteriorVehicleData", "DISALLOWED" }) runner.Step("GetInteriorVehicleData RADIO", commonRC.rpcDenied, { "RADIO", 1, "GetInteriorVehicleData", "DISALLOWED" }) runner.Title("Postconditions") runner.Step("Stop SDL", actions.postconditions)
Fix update/restore SDL PreloadedPT
Fix update/restore SDL PreloadedPT
Lua
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
2a7403274511ba008d4a9427f9e676d21786f074
mods/default/craftitems.lua
mods/default/craftitems.lua
-- mods/default/craftitems.lua minetest.register_craftitem("default:stick", { description = "Stick", inventory_image = "default_stick.png", groups = {stick = 1, flammable = 2}, }) minetest.register_craftitem("default:paper", { description = "Paper", inventory_image = "default_paper.png", groups = {flammable = 3}, }) local lpp = 14 -- Lines per book's page local function book_on_use(itemstack, user) local player_name = user:get_player_name() local meta = itemstack:get_meta() local title, text, owner = "", "", player_name local page, page_max, lines, string = 1, 1, {}, "" -- Backwards compatibility local old_data = minetest.deserialize(itemstack:get_metadata()) if old_data then meta:from_table({ fields = old_data }) end local data = meta:to_table().fields if data.owner then title = data.title text = data.text owner = data.owner for str in (text .. "\n"):gmatch("([^\n]*)[\n]") do lines[#lines+1] = str end if data.page then page = data.page page_max = data.page_max for i = ((lpp * page) - lpp) + 1, lpp * page do if not lines[i] then break end string = string .. lines[i] .. "\n" end end end local formspec if owner == player_name then formspec = "size[8,8]" .. default.gui_bg .. default.gui_bg_img .. "field[0.5,1;7.5,0;title;Title:;" .. minetest.formspec_escape(title) .. "]" .. "textarea[0.5,1.5;7.5,7;text;Contents:;" .. minetest.formspec_escape(text) .. "]" .. "button_exit[2.5,7.5;3,1;save;Save]" else formspec = "size[8,8]" .. default.gui_bg .. default.gui_bg_img .. "label[0.5,0.5;by " .. owner .. "]" .. "tablecolumns[color;text]" .. "tableoptions[background=#00000000;highlight=#00000000;border=false]" .. "table[0.4,0;7,0.5;title;#FFFF00," .. minetest.formspec_escape(title) .. "]" .. "textarea[0.5,1.5;7.5,7;;" .. minetest.formspec_escape(string ~= "" and string or text) .. ";]" .. "button[2.4,7.6;0.8,0.8;book_prev;<]" .. "label[3.2,7.7;Page " .. page .. " of " .. page_max .. "]" .. "button[4.9,7.6;0.8,0.8;book_next;>]" end minetest.show_formspec(player_name, "default:book", formspec) end minetest.register_on_player_receive_fields(function(player, formname, fields) if formname ~= "default:book" then return end local inv = player:get_inventory() local stack = player:get_wielded_item() if fields.save and fields.title ~= "" and fields.text ~= "" then local new_stack, data if stack:get_name() ~= "default:book_written" then local count = stack:get_count() if count == 1 then stack:set_name("default:book_written") else stack:set_count(count - 1) new_stack = ItemStack("default:book_written") end else data = stack:get_meta():to_table().fields end if not data then data = {} end data.title = fields.title data.owner = player:get_player_name() data.description = "\""..fields.title.."\" by "..data.owner data.text = fields.text data.text_len = #data.text data.page = 1 data.page_max = math.ceil((#data.text:gsub("[^\n]", "") + 1) / lpp) if new_stack then new_stack:get_meta():from_table({ fields = data }) if inv:room_for_item("main", new_stack) then inv:add_item("main", new_stack) else minetest.add_item(player:getpos(), new_stack) end else stack:get_meta():from_table({ fields = data }) end elseif fields.book_next or fields.book_prev then local data = stack:get_meta():to_table().fields if not data or not data.page then return end data.page = tonumber(data.page) data.page_max = tonumber(data.page_max) if fields.book_next then data.page = data.page + 1 if data.page > data.page_max then data.page = 1 end else data.page = data.page - 1 if data.page == 0 then data.page = data.page_max end end local data_str = minetest.serialize(data) stack:set_metadata(data_str) book_on_use(stack, player) end player:set_wielded_item(stack) end) minetest.register_craftitem("default:book", { description = "Book", inventory_image = "default_book.png", groups = {book = 1, flammable = 3}, on_use = book_on_use, }) minetest.register_craftitem("default:book_written", { description = "Book With Text", inventory_image = "default_book_written.png", groups = {book = 1, not_in_creative_inventory = 1, flammable = 3}, stack_max = 1, on_use = book_on_use, }) minetest.register_craft({ type = "shapeless", output = "default:book_written", recipe = {"default:book", "default:book_written"} }) minetest.register_on_craft(function(itemstack, player, old_craft_grid, craft_inv) if itemstack:get_name() ~= "default:book_written" then return end local original local index for i = 1, player:get_inventory():get_size("craft") do if old_craft_grid[i]:get_name() == "default:book_written" then original = old_craft_grid[i] index = i end end if not original then return end local copymeta = original:get_metadata() -- copy of the book held by player's mouse cursor itemstack:set_metadata(copymeta) -- put the book with metadata back in the craft grid craft_inv:set_stack("craft", index, original) end) minetest.register_craftitem("default:coal_lump", { description = "Coal Lump", inventory_image = "default_coal_lump.png", groups = {coal = 1, flammable = 1} }) minetest.register_craftitem("default:iron_lump", { description = "Iron Lump", inventory_image = "default_iron_lump.png", }) minetest.register_craftitem("default:copper_lump", { description = "Copper Lump", inventory_image = "default_copper_lump.png", }) minetest.register_craftitem("default:mese_crystal", { description = "Mese Crystal", inventory_image = "default_mese_crystal.png", }) minetest.register_craftitem("default:gold_lump", { description = "Gold Lump", inventory_image = "default_gold_lump.png", }) minetest.register_craftitem("default:diamond", { description = "Diamond", inventory_image = "default_diamond.png", }) minetest.register_craftitem("default:clay_lump", { description = "Clay Lump", inventory_image = "default_clay_lump.png", }) minetest.register_craftitem("default:steel_ingot", { description = "Steel Ingot", inventory_image = "default_steel_ingot.png", }) minetest.register_craftitem("default:copper_ingot", { description = "Copper Ingot", inventory_image = "default_copper_ingot.png", }) minetest.register_craftitem("default:bronze_ingot", { description = "Bronze Ingot", inventory_image = "default_bronze_ingot.png", }) minetest.register_craftitem("default:gold_ingot", { description = "Gold Ingot", inventory_image = "default_gold_ingot.png" }) minetest.register_craftitem("default:mese_crystal_fragment", { description = "Mese Crystal Fragment", inventory_image = "default_mese_crystal_fragment.png", }) minetest.register_craftitem("default:clay_brick", { description = "Clay Brick", inventory_image = "default_clay_brick.png", }) minetest.register_craftitem("default:obsidian_shard", { description = "Obsidian Shard", inventory_image = "default_obsidian_shard.png", }) minetest.register_craftitem("default:flint", { description = "Flint", inventory_image = "default_flint.png" })
-- mods/default/craftitems.lua minetest.register_craftitem("default:stick", { description = "Stick", inventory_image = "default_stick.png", groups = {stick = 1, flammable = 2}, }) minetest.register_craftitem("default:paper", { description = "Paper", inventory_image = "default_paper.png", groups = {flammable = 3}, }) local lpp = 14 -- Lines per book's page local function book_on_use(itemstack, user) local player_name = user:get_player_name() local meta = itemstack:get_meta() local title, text, owner = "", "", player_name local page, page_max, lines, string = 1, 1, {}, "" -- Backwards compatibility local old_data = minetest.deserialize(itemstack:get_metadata()) if old_data then meta:from_table({ fields = old_data }) end local data = meta:to_table().fields if data.owner then title = data.title text = data.text owner = data.owner for str in (text .. "\n"):gmatch("([^\n]*)[\n]") do lines[#lines+1] = str end if data.page then page = data.page page_max = data.page_max for i = ((lpp * page) - lpp) + 1, lpp * page do if not lines[i] then break end string = string .. lines[i] .. "\n" end end end local formspec if owner == player_name then formspec = "size[8,8]" .. default.gui_bg .. default.gui_bg_img .. "field[0.5,1;7.5,0;title;Title:;" .. minetest.formspec_escape(title) .. "]" .. "textarea[0.5,1.5;7.5,7;text;Contents:;" .. minetest.formspec_escape(text) .. "]" .. "button_exit[2.5,7.5;3,1;save;Save]" else formspec = "size[8,8]" .. default.gui_bg .. default.gui_bg_img .. "label[0.5,0.5;by " .. owner .. "]" .. "tablecolumns[color;text]" .. "tableoptions[background=#00000000;highlight=#00000000;border=false]" .. "table[0.4,0;7,0.5;title;#FFFF00," .. minetest.formspec_escape(title) .. "]" .. "textarea[0.5,1.5;7.5,7;;" .. minetest.formspec_escape(string ~= "" and string or text) .. ";]" .. "button[2.4,7.6;0.8,0.8;book_prev;<]" .. "label[3.2,7.7;Page " .. page .. " of " .. page_max .. "]" .. "button[4.9,7.6;0.8,0.8;book_next;>]" end minetest.show_formspec(player_name, "default:book", formspec) return itemstack end minetest.register_on_player_receive_fields(function(player, formname, fields) if formname ~= "default:book" then return end local inv = player:get_inventory() local stack = player:get_wielded_item() if fields.save and fields.title ~= "" and fields.text ~= "" then local new_stack, data if stack:get_name() ~= "default:book_written" then local count = stack:get_count() if count == 1 then stack:set_name("default:book_written") else stack:set_count(count - 1) new_stack = ItemStack("default:book_written") end else data = stack:get_meta():to_table().fields end if not data then data = {} end data.title = fields.title data.owner = player:get_player_name() data.description = "\""..fields.title.."\" by "..data.owner data.text = fields.text data.text_len = #data.text data.page = 1 data.page_max = math.ceil((#data.text:gsub("[^\n]", "") + 1) / lpp) if new_stack then new_stack:get_meta():from_table({ fields = data }) if inv:room_for_item("main", new_stack) then inv:add_item("main", new_stack) else minetest.add_item(player:getpos(), new_stack) end else stack:get_meta():from_table({ fields = data }) end elseif fields.book_next or fields.book_prev then local data = stack:get_meta():to_table().fields if not data or not data.page then return end data.page = tonumber(data.page) data.page_max = tonumber(data.page_max) if fields.book_next then data.page = data.page + 1 if data.page > data.page_max then data.page = 1 end else data.page = data.page - 1 if data.page == 0 then data.page = data.page_max end end stack:get_meta():from_table(data) stack = book_on_use(stack, player) end -- Update stack player:set_wielded_item(stack) end) minetest.register_craftitem("default:book", { description = "Book", inventory_image = "default_book.png", groups = {book = 1, flammable = 3}, on_use = book_on_use, }) minetest.register_craftitem("default:book_written", { description = "Book With Text", inventory_image = "default_book_written.png", groups = {book = 1, not_in_creative_inventory = 1, flammable = 3}, stack_max = 1, on_use = book_on_use, }) minetest.register_craft({ type = "shapeless", output = "default:book_written", recipe = {"default:book", "default:book_written"} }) minetest.register_on_craft(function(itemstack, player, old_craft_grid, craft_inv) if itemstack:get_name() ~= "default:book_written" then return end local original local index for i = 1, player:get_inventory():get_size("craft") do if old_craft_grid[i]:get_name() == "default:book_written" then original = old_craft_grid[i] index = i end end if not original then return end local copymeta = original:get_meta():to_table() -- copy of the book held by player's mouse cursor itemstack:get_meta():from_table(copymeta) -- put the book with metadata back in the craft grid craft_inv:set_stack("craft", index, original) end) minetest.register_craftitem("default:coal_lump", { description = "Coal Lump", inventory_image = "default_coal_lump.png", groups = {coal = 1, flammable = 1} }) minetest.register_craftitem("default:iron_lump", { description = "Iron Lump", inventory_image = "default_iron_lump.png", }) minetest.register_craftitem("default:copper_lump", { description = "Copper Lump", inventory_image = "default_copper_lump.png", }) minetest.register_craftitem("default:mese_crystal", { description = "Mese Crystal", inventory_image = "default_mese_crystal.png", }) minetest.register_craftitem("default:gold_lump", { description = "Gold Lump", inventory_image = "default_gold_lump.png", }) minetest.register_craftitem("default:diamond", { description = "Diamond", inventory_image = "default_diamond.png", }) minetest.register_craftitem("default:clay_lump", { description = "Clay Lump", inventory_image = "default_clay_lump.png", }) minetest.register_craftitem("default:steel_ingot", { description = "Steel Ingot", inventory_image = "default_steel_ingot.png", }) minetest.register_craftitem("default:copper_ingot", { description = "Copper Ingot", inventory_image = "default_copper_ingot.png", }) minetest.register_craftitem("default:bronze_ingot", { description = "Bronze Ingot", inventory_image = "default_bronze_ingot.png", }) minetest.register_craftitem("default:gold_ingot", { description = "Gold Ingot", inventory_image = "default_gold_ingot.png" }) minetest.register_craftitem("default:mese_crystal_fragment", { description = "Mese Crystal Fragment", inventory_image = "default_mese_crystal_fragment.png", }) minetest.register_craftitem("default:clay_brick", { description = "Clay Brick", inventory_image = "default_clay_brick.png", }) minetest.register_craftitem("default:obsidian_shard", { description = "Obsidian Shard", inventory_image = "default_obsidian_shard.png", }) minetest.register_craftitem("default:flint", { description = "Flint", inventory_image = "default_flint.png" })
Books: Fix backwards compatibility issues
Books: Fix backwards compatibility issues Commit c68b8274fed183f30bd7609018766a261448b83d prevented books from being copied in the crafting grid, and made it so that old books, though seemingly successfully transferred to the new format, could not be written to as the old data still persisted.
Lua
lgpl-2.1
evrooije/beerarchy,evrooije/beerarchy,evrooije/beerarchy
b8a7b3d8e12ea941537d5443bd36445fda529986
mods/mobs/dungeonmaster.lua
mods/mobs/dungeonmaster.lua
-- Dungeon Master by PilzAdam -- Node which cannot be destroyed by DungeonMasters' fireballs local excluded = {"nether:netherrack","default:obsidian_glass","doors:door_steel_b_1","doors:door_steel_t_1","doors:door_steel_b_2","doors:door_steel_t_2","default:chest_locked"} mobs:register_mob("mobs:dungeon_master", { -- animal, monster, npc, barbarian type = "monster", -- aggressive, shoots fireballs at player passive = false, damage = 13, attack_type = "shoot", shoot_interval = 2.5, arrow = "mobs:fireball", shoot_offset = 0, -- health & armor hp_min = 50, hp_max = 60, armor = 60, -- textures and model collisionbox = {-0.7, -0.01, -0.7, 0.7, 2.6, 0.7}, visual = "mesh", mesh = "mobs_dungeon_master.x", drawtype = "front", available_textures = { total = 3, texture_1 = {"mobs_dungeon_master.png"}, texture_2 = {"mobs_dungeon_master_cobblestone.png"}, texture_3 = {"mobs_dungeon_master_strangewhite.png"}, }, visual_size = {x=8, y=8}, blood_texture = "mobs_blood.png", -- sounds makes_footstep_sound = true, sounds = { random = "mobs_dungeonmaster", attack = "mobs_fireball", }, -- speed and jump walk_velocity = 1, run_velocity = 2, jump = false, view_range = 16, -- drops mese or diamond when dead drops = { {name = "default:mese_crystal_fragment", chance = 1, min = 1, max = 3,}, {name = "default:diamond", chance = 5, min = 1, max = 3,}, {name = "default:mese_crystal", chance = 2, min = 1, max = 3,}, {name = "default:diamond_block", chance = 30, min = 1, max = 1,}, {name = "maptools:gold_coin", chance = 15, min = 1, max = 2,}, {name = "maptools:silver_coin", chance = 1, min = 2, max = 10,}, }, -- damaged by water_damage = 1, lava_damage = 1, light_damage = 0, -- model animation animation = { stand_start = 0, stand_end = 19, walk_start = 20, walk_end = 35, punch_start = 36, punch_end = 48, speed_normal = 15, speed_run = 15, }, }) -- spawn on stone between 20 and -1 light, 1 in 7000 chance, 1 dungeon master in area starting at -100 and below mobs:register_spawn("mobs:dungeon_master", {"default:stone, nether:netherrack"}, 20, -1, 7000, 1, -100) -- register spawn egg mobs:register_egg("mobs:dungeon_master", "Dungeon Master", "fire_basic_flame.png", 1) -- Fireball (dungeon masters weapon) mobs:register_arrow("mobs:fireball", { visual = "sprite", visual_size = {x=1, y=1}, textures = {"mobs_fireball.png"}, velocity = 5, -- direct hit, no fire... just plenty of pain hit_player = function(self, player) local s = self.object:getpos() local p = player:getpos() player:punch(self.object, 1.0, { full_punch_interval=1.0, damage_groups = {fleshy=13}, }, 0) end, -- node hit, bursts into flame (cannot blast through obsidian or protection redo mod items) hit_node = function(self, pos, node) for dx=-1,1 do for dy=-1,1 do for dz=-1,1 do local p = {x=pos.x+dx, y=pos.y+dy, z=pos.z+dz} local n = minetest.get_node(p).name local excluding = minetest.get_item_group(n.name, "unbreakable") == 1 or n:split(":")[1] == "nether" or next(areas:getAreasAtPos(p)) ~= nil for _,i in ipairs(excluded) do if i == n then excluding = true end end --if p.y < -19600 and including and n:split(":")[1] == "nether" then if excluding then return end if n == "default:chest" then meta = minetest.get_meta(p) inv = meta:get_inventory() for i = 1,32 do m_stack = inv:get_stack("main",i) obj = minetest.add_item(pos,m_stack) if obj then obj:setvelocity({x=math.random(-2,1), y=7, z=math.random(-2,1)}) end end end if minetest.registered_nodes[n].groups.flammable or math.random(1, 100) <= 30 then minetest.set_node(p, {name="fire:basic_flame"}) else minetest.set_node(p, {name="air"}) end if n == "doors:door_wood_b_1" then minetest.remove_node({x=p.x,y=p.y+1,z=p.z}) elseif n == "doors:door_wood_t_1" then minetest.remove_node({x=p.x,y=p.y-1,z=p.z}) end end end end end })
-- Dungeon Master by PilzAdam -- Node which cannot be destroyed by DungeonMasters' fireballs local excluded = {"nether:netherrack","default:obsidian_glass","default:obsidian","default:bedrock", "doors:door_steel_b_1", "doors:door_steel_t_1", "doors:door_steel_b_2", "doors:door_steel_t_2","default:chest_locked"} mobs:register_mob("mobs:dungeon_master", { -- animal, monster, npc, barbarian type = "monster", -- aggressive, shoots fireballs at player passive = false, damage = 13, attack_type = "shoot", shoot_interval = 2.5, arrow = "mobs:fireball", shoot_offset = 0, -- health & armor hp_min = 50, hp_max = 60, armor = 60, -- textures and model collisionbox = {-0.7, -0.01, -0.7, 0.7, 2.6, 0.7}, visual = "mesh", mesh = "mobs_dungeon_master.x", drawtype = "front", available_textures = { total = 3, texture_1 = {"mobs_dungeon_master.png"}, texture_2 = {"mobs_dungeon_master_cobblestone.png"}, texture_3 = {"mobs_dungeon_master_strangewhite.png"}, }, visual_size = {x=8, y=8}, blood_texture = "mobs_blood.png", -- sounds makes_footstep_sound = true, sounds = { random = "mobs_dungeonmaster", attack = "mobs_fireball", }, -- speed and jump walk_velocity = 1, run_velocity = 2, jump = false, view_range = 16, -- drops mese or diamond when dead drops = { {name = "default:mese_crystal_fragment", chance = 1, min = 1, max = 3,}, {name = "default:diamond", chance = 5, min = 1, max = 3,}, {name = "default:mese_crystal", chance = 2, min = 1, max = 3,}, {name = "default:diamond_block", chance = 30, min = 1, max = 1,}, {name = "maptools:gold_coin", chance = 15, min = 1, max = 2,}, {name = "maptools:silver_coin", chance = 1, min = 2, max = 10,}, }, -- damaged by water_damage = 1, lava_damage = 1, light_damage = 0, -- model animation animation = { stand_start = 0, stand_end = 19, walk_start = 20, walk_end = 35, punch_start = 36, punch_end = 48, speed_normal = 15, speed_run = 15, }, }) -- spawn on stone between 20 and -1 light, 1 in 7000 chance, 1 dungeon master in area starting at -100 and below mobs:register_spawn("mobs:dungeon_master", {"default:stone, nether:netherrack"}, 20, -1, 7000, 1, -100) -- register spawn egg mobs:register_egg("mobs:dungeon_master", "Dungeon Master", "fire_basic_flame.png", 1) -- Fireball (dungeon masters weapon) mobs:register_arrow("mobs:fireball", { visual = "sprite", visual_size = {x=1, y=1}, textures = {"mobs_fireball.png"}, velocity = 5, -- direct hit, no fire... just plenty of pain hit_player = function(self, player) local s = self.object:getpos() local p = player:getpos() player:punch(self.object, 1.0, { full_punch_interval=1.0, damage_groups = {fleshy=13}, }, 0) end, -- node hit, bursts into flame (cannot blast through obsidian or protection redo mod items) hit_node = function(self, pos, node) for dx=-1,1 do for dy=-1,1 do for dz=-1,1 do local p = {x=pos.x+dx, y=pos.y+dy, z=pos.z+dz} local n = minetest.get_node(p).name local excluding = minetest.get_item_group(n, "unbreakable") == 1 or n:split(":")[1] == "nether" or next(areas:getAreasAtPos(p)) ~= nil for _,i in ipairs(excluded) do if i == n then excluding = true end end --if p.y < -19600 and including and n:split(":")[1] == "nether" then if excluding then return end if n == "default:chest" then meta = minetest.get_meta(p) inv = meta:get_inventory() for i = 1,32 do m_stack = inv:get_stack("main",i) obj = minetest.add_item(pos,m_stack) if obj then obj:setvelocity({x=math.random(-2,1), y=7, z=math.random(-2,1)}) end end end if minetest.registered_nodes[n].groups.flammable or math.random(1, 100) <= 30 then minetest.set_node(p, {name="fire:basic_flame"}) else minetest.set_node(p, {name="air"}) end if n == "doors:door_wood_b_1" then minetest.remove_node({x=p.x,y=p.y+1,z=p.z}) elseif n == "doors:door_wood_t_1" then minetest.remove_node({x=p.x,y=p.y-1,z=p.z}) end end end end end })
add obsidian and fix wrong var
add obsidian and fix wrong var
Lua
unlicense
Gael-de-Sailly/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,crabman77/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,sys4-fr/server-minetestforfun,Ombridride/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,Coethium/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Coethium/server-minetestforfun,Coethium/server-minetestforfun,sys4-fr/server-minetestforfun,crabman77/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server
720a8356c8b447d764f8d139ce281dcf34b78d6f
src/plugins/core/webapp/init.lua
src/plugins/core/webapp/init.lua
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- W E B A P P -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- --- === plugins.core.webapp === --- --- WebApp Plugin. -------------------------------------------------------------------------------- -- -- EXTENSIONS: -- -------------------------------------------------------------------------------- local log = require("hs.logger").new("webapp") local hsminweb = require("hs.httpserver.hsminweb") local inspect = require("hs.inspect") local pasteboard = require("hs.pasteboard") local timer = require("hs.timer") local config = require("cp.config") local tools = require("cp.tools") -------------------------------------------------------------------------------- -- -- THE MODULE: -- -------------------------------------------------------------------------------- local mod = {} mod.DEFAULT_PORT = 12345 mod.DEFAULT_SETTING = false mod.PREFERENCE_NAME = "enableWebApp" function mod.start() if mod._server then log.df("CommandPost WebApp Already Running") else mod._server = hsminweb.new() :name("CommandPost Webapp") :port(mod.DEFAULT_PORT) :cgiEnabled(true) :documentRoot(mod.path) :luaTemplateExtension("lp") :directoryIndex({"index.lp"}) :start() log.df("Started CommandPost WebApp.") end return mod end function mod.stop() mod._server:stop() mod._server = nil log.df("Stopped CommandPost WebApp") end function mod.copyLinkToClipboard() pasteboard.setContents(mod.hostname) end function mod.update() if mod.enabled() then mod.stop() else mod.start() end end mod.enabled = config.prop(mod.PREFERENCE_NAME, mod.DEFAULT_SETTING):watch(mod.update) -------------------------------------------------------------------------------- -- GET HOSTNAME: -------------------------------------------------------------------------------- local function getHostname() local _hostname, _status = hs.execute("hostname") if _status and _hostname then return "http://" .. tools.trim(_hostname) .. ":" .. mod.DEFAULT_PORT else return nil end end -------------------------------------------------------------------------------- -- -- THE PLUGIN: -- -------------------------------------------------------------------------------- local plugin = { id = "core.webapp", group = "core", dependencies = { ["core.preferences.panels.webapp"] = "webappPreferences", } } -------------------------------------------------------------------------------- -- INITIALISE PLUGIN: -------------------------------------------------------------------------------- function plugin.init(deps, env) -------------------------------------------------------------------------------- -- Get Hostname: -------------------------------------------------------------------------------- mod.hostname = getHostname() or i18n("webappUnresolvedHostname") -------------------------------------------------------------------------------- -- Get Path: -------------------------------------------------------------------------------- mod.path = env:pathToAbsolute("html") -------------------------------------------------------------------------------- -- Setup Preferences: -------------------------------------------------------------------------------- deps.webappPreferences:addHeading(10, i18n ("webappIntroduction")) :addParagraph(15, i18n("webappInstructions"), true) :addHeading(25, i18n("webappSettings")) :addCheckbox(30, { label = i18n("webappEnable"), onchange = function() mod.enabled:toggle() end, checked = mod.enabled, } ) :addHeading(40, i18n("webappHostname")) :addParagraph(45, mod.hostname) :addButton(50, { label = "Copy Link to Clipboard", onclick = mod.copyLinkToClipboard } ) return mod end function plugin.postInit() -------------------------------------------------------------------------------- -- Start the WebApp if Enabled: -------------------------------------------------------------------------------- if mod.enabled() then timer.doAfter(1, mod.start) end end return plugin
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- W E B A P P -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- --- === plugins.core.webapp === --- --- WebApp Plugin. -------------------------------------------------------------------------------- -- -- EXTENSIONS: -- -------------------------------------------------------------------------------- local log = require("hs.logger").new("webapp") local hsminweb = require("hs.httpserver.hsminweb") local inspect = require("hs.inspect") local pasteboard = require("hs.pasteboard") local timer = require("hs.timer") local config = require("cp.config") local tools = require("cp.tools") -------------------------------------------------------------------------------- -- -- THE MODULE: -- -------------------------------------------------------------------------------- local mod = {} mod.DEFAULT_PORT = 12345 mod.DEFAULT_SETTING = false mod.PREFERENCE_NAME = "enableWebApp" function mod.start() if mod._server then log.df("CommandPost WebApp Already Running") else mod._server = hsminweb.new() :name("CommandPost Webapp") :port(mod.DEFAULT_PORT) :cgiEnabled(true) :documentRoot(mod.path) :luaTemplateExtension("lp") :directoryIndex({"index.lp"}) :start() log.df("Started CommandPost WebApp.") end return mod end function mod.stop() if mod._server then mod._server:stop() mod._server = nil log.df("Stopped CommandPost WebApp") end end function mod.copyLinkToClipboard() pasteboard.setContents(mod.hostname) end function mod.update() if mod.enabled() then mod.start() else mod.stop() end end mod.enabled = config.prop(mod.PREFERENCE_NAME, mod.DEFAULT_SETTING):watch(mod.update) -------------------------------------------------------------------------------- -- GET HOSTNAME: -------------------------------------------------------------------------------- local function getHostname() local _hostname, _status = hs.execute("hostname") if _status and _hostname then return "http://" .. tools.trim(_hostname) .. ":" .. mod.DEFAULT_PORT else return nil end end -------------------------------------------------------------------------------- -- -- THE PLUGIN: -- -------------------------------------------------------------------------------- local plugin = { id = "core.webapp", group = "core", dependencies = { ["core.preferences.panels.webapp"] = "webappPreferences", } } -------------------------------------------------------------------------------- -- INITIALISE PLUGIN: -------------------------------------------------------------------------------- function plugin.init(deps, env) -------------------------------------------------------------------------------- -- Get Hostname: -------------------------------------------------------------------------------- mod.hostname = getHostname() or i18n("webappUnresolvedHostname") -------------------------------------------------------------------------------- -- Get Path: -------------------------------------------------------------------------------- mod.path = env:pathToAbsolute("html") -------------------------------------------------------------------------------- -- Setup Preferences: -------------------------------------------------------------------------------- deps.webappPreferences:addHeading(10, i18n ("webappIntroduction")) :addParagraph(15, i18n("webappInstructions"), true) :addHeading(25, i18n("webappSettings")) :addCheckbox(30, { label = i18n("webappEnable"), onchange = function() mod.enabled:toggle() end, checked = mod.enabled, } ) :addHeading(40, i18n("webappHostname")) :addParagraph(45, mod.hostname) :addButton(50, { label = "Copy Link to Clipboard", onclick = mod.copyLinkToClipboard } ) return mod end function plugin.postInit() -------------------------------------------------------------------------------- -- Start the WebApp if Enabled: -------------------------------------------------------------------------------- if mod.enabled() then timer.doAfter(1, mod.start) end end return plugin
Fixed Bug in WebApp
Fixed Bug in WebApp
Lua
mit
cailyoung/CommandPost,fcpxhacks/fcpxhacks,cailyoung/CommandPost,CommandPost/CommandPost,CommandPost/CommandPost,cailyoung/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost
6ac92a9967bd4f14b4f729b45aac1222e24d6cba
lib/switchboard_modules/lua_script_debugger/premade_scripts/12_rtc_triggered_logging.lua
lib/switchboard_modules/lua_script_debugger/premade_scripts/12_rtc_triggered_logging.lua
print("Log voltage of AIN1 to file every 10 minutes. RTC value checked every 1000ms.") --Requires micro SD Card installed inside the T7 or T7-Pro. --Requires FW 1.0150 or newer. --T7 uSD card. http://labjack.com/support/datasheets/t7/sd-card --Timestamp (real-time-clock) available on T7-Pro only --Note that as of Firmware v1.0150, some SD cards do not work. --Check for the latest firwmare updates http://labjack.com/support/firmware/t7/beta local hardware = MB.R(60010, 1) local passed = 1 if(bit.band(hardware, 8) ~= 8) then print("uSD card not detected") passed = 0 end if(bit.band(hardware, 4) ~= 4) then print("RTC module not detected") passed = 0 end if(passed == 0) then print("This Lua script requires an RTC and a microSD card, but one or both are not detected. These features are only preinstalled on the T7-Pro. Script Stopping.") MB.W(6000, 1, 0)--stop script end local mbRead=MB.R --local functions for faster processing local mbWrite=MB.W local mbReadArray=MB.RA local Filepre = "RTWi_" local Filesuf = ".csv" local NumFn = 0 local Filename = Filepre..string.format("%02d", NumFn)..Filesuf local voltage = 0 local Modulo = 0 local delimiter = "," local dateStr = "" local voltageStr = "" local f = nil local RTCPollinterval = 1000 --interval in ms, 1000 for 1000ms local PollsPerMinute = 60 --60 RTC polls per minute, since each is 1000ms local Loginterval_min = 10 --10 for 10 minute interval local PollCount = 0 local Minute = 0 --a variable for the minutes from the RTC local dateTbl = {} dateTbl[1] = 0 --year dateTbl[2] = 0 --month dateTbl[3] = 0 --day dateTbl[4] = 0 --hour dateTbl[5] = 0 --minute dateTbl[6] = 0 --second mbWrite(48005,0,1) --ensure analog is on LJ.IntervalConfig(0, RTCPollinterval) local checkInterval=LJ.CheckInterval local checkFileFlag=LJ.CheckFileFlag f = io.open(Filename, "r") if f ~= nil then f:close() f = io.open(Filename, "a+") --File exists, Append to file print ("Appending to file") else f = io.open(Filename, "w") --Create or replace file print ("Creating new file") end while true do if checkInterval(0) then --RTC polling interval completed local fg = 0 dateTbl, error = mbReadArray(61510, 0, 6) --Read the RTC timestamp, -Pro only dateStr = string.format("%04d/%02d/%02d %02d:%02d.%02d", dateTbl[1], dateTbl[2], dateTbl[3], dateTbl[4], dateTbl[5], dateTbl[6]) print("DateTime: ", dateStr) Minute = dateTbl[5] Modulo = Minute - math.floor(Minute/Loginterval_min)*Loginterval_min PollCount = PollCount + 1 print ("RTC poll events since last save: ", PollCount) fg = checkFileFlag() --host software wants to read LUAs active file? W 1 to address 6500, U32 if fg == 1 then NumFn = NumFn + 1 --increment filename Filename = Filepre..string.format("%02d", NumFn)..Filesuf f:close() LJ.ClearFileFlag() --inform host that previous file is available. R 0 from address 6500, U32 f = io.open(Filename, "w") --create or replace new file print ("Command issued by host to create new file") end if Modulo == 0 and PollCount > PollsPerMinute then --minutes digit matches rollover condition -> log to file PollCount = 0 --reset the PollCount voltage = mbRead(2, 3) --voltage on AIN1, address is 2, type is 3 print("AIN1: ", voltage, "V") voltageStr = string.format("%.6f", voltage) stringResult = dateStr..delimiter..voltageStr.."\n" print ("Appending to file") f:write(stringResult) end end end
--[[ Name: 12_rtc_triggered_logging.lua Desc: Example showing how to log AIN values to file on an SD card Note: Requires a micro SD Card installed inside the T7 or T7-Pro T7 uSD card: http://labjack.com/support/datasheets/t7/sd-card Timestamp (real-time-clock) is only available on the T7-Pro As of Firmware v1.0150, some SD cards do not work. Check for the latest firwmare updates at: http://labjack.com/support/firmware/t7/beta Requires FW 1.0150 or newer --]] print("Log voltage of AIN1 to file every 10 minutes. RTC value checked every 1000ms.") -- Get statuses of the device hardware modules local hardware = MB.readName("HARDWARE_INSTALLED") local passed = 1 -- The 7th bit of hardware holds the sd card status if(bit.band(hardware, 8) ~= 8) then print("uSD card not detected") passed = 0 end -- the 3rd bit holds of hardware holds the RTC module status if(bit.band(hardware, 4) ~= 4) then print("RTC module not detected") passed = 0 end if(passed == 0) then print("This Lua script requires an RTC and a microSD card, but one or both are not detected. These features are only preinstalled on the T7-Pro. Script Stopping.") MB.W(6000, 1, 0) end local filepre = "RTWi_" local filesuf = ".csv" local numfn = 0 local filename = filepre..string.format("%02d", numfn)..filesuf local voltage = 0 local modulo = 0 local delimiter = "," local stringdate = "" local voltagestr = "" local f = nil -- Interval in ms for polling local pollinterval = 1000 local pollpermin = 60*1000 / pollinterval -- Use a 10 minute logging interval local loginterval = 10 local pollcount = 0 -- Minutes returned from the RTC local minute = 0 local date = {} date[1] = 0 --year date[2] = 0 --month date[3] = 0 --day date[4] = 0 --hour date[5] = 0 --minute date[6] = 0 --second -- Ensure that analog is on MB.writeName("POWER_AIN",1) LJ.IntervalConfig(0, pollinterval) f = io.open(filename, "r") -- If the file exists append to the end of it if f ~= nil then f:close() f = io.open(filename, "a+") print ("Appending to file") -- If the file does not exist create it and write to it else f = io.open(filename, "w") print ("Creating new file") end -- Run the program in an infinite loop while true do -- If the RTC polling interval completed if LJ.CheckInterval(0) then local fg = 0 -- Read the RTC timestamp -Pro only date, error = MB.RA(61510, 0, 6) stringdate = string.format( "%04d/%02d/%02d %02d:%02d.%02d", date[1], date[2], date[3], date[4], date[5], date[6] ) print("DateTime: ", stringdate) minute = date[5] modulo = minute - math.floor(minute/loginterval)*loginterval pollcount = pollcount + 1 print ("RTC poll events since last save: ", pollcount) -- If the host software wants to read the active file write 1 to address 6500, U32 fg = LJ.CheckFileFlag() -- If the file flag is set start logging data in a new file if fg == 1 then numfn = numfn + 1 --increment filename filename = filepre..string.format("%02d", numfn)..filesuf f:close() -- Inform the host that previous file is available LJ.ClearFileFlag() -- Create or replace a new file f = io.open(filename, "w") print ("Command issued by host to create a new file") end -- If the minutes digit matches the rollover condition log to file if modulo == 0 and pollcount > pollpermin then -- Reset the poll count pollcount = 0 voltage = MB.readName("AIN1") print("AIN1: ", voltage, "V") voltagestr = string.format("%.6f", voltage) -- Create a string holding a timestamp and the AIN voltage stringResult = stringdate..delimiter..voltagestr.."\n" print ("Appending to file") -- Write the log data to file f:write(stringResult) end end end
Fixed up the formatting of the rtc triggered logging example
Fixed up the formatting of the rtc triggered logging example
Lua
mit
chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager
5dfbad3a970a7ed7f368adf93b52d1ed0d46c6ed
lib/resty/kafka/broker.lua
lib/resty/kafka/broker.lua
-- Copyright (C) Dejiang Zhu(doujiang24) local response = require "resty.kafka.response" local to_int32 = response.to_int32 local setmetatable = setmetatable local tcp = ngx.socket.tcp local _M = { _VERSION = "0.01" } local mt = { __index = _M } function _M.new(self, host, port, socket_config) return setmetatable({ host = host, port = port, config = socket_config, }, mt) end function _M.send_receive(self, request) local sock, err = tcp() if not sock then return nil, err, true end sock:settimeout(self.config.socket_timeout) local ok, err = sock:connect(self.host, self.port) if not ok then return nil, err, true end local bytes, err = sock:send(request:package()) if not bytes then return nil, err end local data, err = sock:receive(4) if not data then if err == "timeout" then sock:close() end return nil, err end local len = to_int32(data) local data, err = sock:receive(len) if not data then if err == "timeout" then sock:close() end return nil, err end sock:setkeepalive(self.config.keepalive_timeout, self.config.keepalive_size) return response:new(data), nil, true end return _M
-- Copyright (C) Dejiang Zhu(doujiang24) local response = require "resty.kafka.response" local to_int32 = response.to_int32 local setmetatable = setmetatable local tcp = ngx.socket.tcp local _M = { _VERSION = "0.01" } local mt = { __index = _M } function _M.new(self, host, port, socket_config) return setmetatable({ host = host, port = port, config = socket_config, }, mt) end function _M.send_receive(self, request) local sock, err = tcp() if not sock then return nil, err, true end sock:settimeout(self.config.socket_timeout) local ok, err = sock:connect(self.host, self.port) if not ok then return nil, err, true end local bytes, err = sock:send(request:package()) if not bytes then return nil, err, true end local data, err = sock:receive(4) if not data then if err == "timeout" then sock:close() return nil, err end return nil, err, true end local len = to_int32(data) local data, err = sock:receive(len) if not data then if err == "timeout" then sock:close() return nil, err end return nil, err, true end sock:setkeepalive(self.config.keepalive_timeout, self.config.keepalive_size) return response:new(data), nil, true end return _M
bugfix: only recieve timeout can not be safe retry in socket errors
bugfix: only recieve timeout can not be safe retry in socket errors
Lua
bsd-3-clause
wangfakang/lua-resty-kafka,wzb56/lua-resty-kafka,doujiang24/lua-resty-kafka
f6b3d4e7334d5f5f71e334a998037ca01b234086
src/Options.lua
src/Options.lua
local Log = require 'Log' local P = {} P.__index = P function P:new(config) local this = { config = { long = {}, short = {} }, init = {} } setmetatable(this, self) for _, item in ipairs(config or {}) do local opt, cfg = {}, '' if type(item[1]) == 'string' then cfg = item[1] table.remove(item, 1) end local names, value = table.unpack(cfg:split('=')) local long, short = table.unpack(names:split(',')) opt.long = assert(long) if short then opt.short = short end if value then opt.needs_value = value end if item[1] ~= nil then this.init[long] = item[1] table.remove(item, 1) else this.init[long] = false end if item[1] ~= nil then opt.max_value = item[1] table.remove(item, 1) end this.config.long[long] = opt if short and #short > 0 then this.config.short[short] = opt end end return this end function P:is_option(arg) return string.sub(arg, 1, 1) == '-' end function P:is_short(arg) return arg and string.sub(arg, 1, 1) == '-' and string.sub(arg, 2, 2) ~= '-' end function P:is_long(arg) return arg and string.sub(arg, 1, 1) == '-' and string.sub(arg, 2, 2) == '-' end function P:is_eoa(arg) return P:is_long(arg) and #arg == 2 end local function result_tostring(self) local lines = {} local function append(value) table.insert(lines, value) end for k, v in pairs(self) do if type(v) == 'table' then append(string.format('--%s', k)) end end return table.concat(lines, ' ') end function P:parse(args) local result = copy(self.init) setmetatable(result, { __tostring = result_tostring }) local read_nth, eoa local function set_value(n, opt, val) if opt.needs_value == 'n' then local num = tonumber(val) if not num then Log.error("option '%s' (%s) requires a number value but the specified value '%s' is not a number", opt.long, opt.short, val) return end result[opt.long] = num else result[opt.long] = val end return true end local function read_value(n, opt) local arg = args[n] local value if arg and not self:is_option(arg) then value = arg else value = opt.max_value end if not set_value(n, opt, value) then return end return read_nth(n+1) end local function read_long(n) local patterns = { '^%-%-([%w-]+)=(.*)$', '^%-%-([%w-]+)' } local arg = args[n] local name, value for pattern in each(patterns) do name, value = string.match(arg, pattern) if name then break end end local opt = self.config.long[name] if not opt then Log.error('invalid option: %s', arg) return end if opt.needs_value then if value then if not set_value(n, opt, value) then return end else return read_value(n+1, opt) end else if not result[name] then result[name] = {} end result[name].long = true end return read_nth(n+1) end local function read_optstring(n, optstring) local a = string.sub(optstring, 1, 1) if #a < 1 then return read_nth(n+1) end local rest = string.sub(optstring, 2) local opt = self.config.short[a] if not opt then Log.error('invalid option: -%s', a) return end if opt.needs_value then if #rest > 0 then if set_value(n, opt, rest) then return read_nth(n+1) else return end else return read_value(n+1, opt) end else if not result[opt.long] then result[opt.long] = {} end result[opt.long].short = true return read_optstring(n, rest) end end local function read_short(n) local arg = args[n] return read_optstring(n, string.sub(arg, 2)) end read_nth = function (n) local arg = args[n] if not arg then return result end if eoa then result._args = append(result._args, args[n]) else if self:is_eoa(arg) then eoa = true elseif self:is_long(arg) then return read_long(n) elseif self:is_short(arg) then return read_short(n) else table.insert(result, args[n]) end end return read_nth(n+1, args) end return read_nth(1) end return P
local Log = require 'Log' local P = {} P.__index = P function P:new(config) local this = { config = { long = {}, short = {} }, init = {} } setmetatable(this, self) for _, item in ipairs(config or {}) do local opt, cfg = {}, '' if type(item[1]) == 'string' then cfg = item[1] table.remove(item, 1) end local names, value = table.unpack(cfg:split('=')) local long, short = table.unpack(names:split(',')) opt.long = assert(long) if short then opt.short = short end if value then opt.needs_value = value end if item[1] ~= nil then this.init[long] = item[1] table.remove(item, 1) else this.init[long] = false end if item[1] ~= nil then opt.max_value = item[1] table.remove(item, 1) end this.config.long[long] = opt if short and #short > 0 then this.config.short[short] = opt end end return this end function P:is_option(arg) return string.sub(arg, 1, 1) == '-' end function P:is_short(arg) return arg and string.sub(arg, 1, 1) == '-' and string.sub(arg, 2, 2) ~= '-' end function P:is_long(arg) return arg and string.sub(arg, 1, 1) == '-' and string.sub(arg, 2, 2) == '-' end function P:is_eoa(arg) return P:is_long(arg) and #arg == 2 end local function result_tostring(self) local lines = {} local function append(value) table.insert(lines, value) end for k, v in pairs(self) do if v == true or (type(v) == 'table' and (v.short == true or v.long == true)) then append(string.format('--%s', k)) end end return table.concat(lines, ' ') end function P:parse(args) local result = copy(self.init) setmetatable(result, { __tostring = result_tostring }) local read_nth, eoa local function set_value(n, opt, val) if opt.needs_value == 'n' then local num = tonumber(val) if not num then Log.error("option '%s' (%s) requires a number value but the specified value '%s' is not a number", opt.long, opt.short, val) return end result[opt.long] = num else result[opt.long] = val end return true end local function read_value(n, opt) local arg = args[n] local value if arg and not self:is_option(arg) then value = arg else value = opt.max_value end if not set_value(n, opt, value) then return end return read_nth(n+1) end local function read_long(n) local patterns = { '^%-%-([%w-]+)=(.*)$', '^%-%-([%w-]+)' } local arg = args[n] local name, value for pattern in each(patterns) do name, value = string.match(arg, pattern) if name then break end end local opt = self.config.long[name] if not opt then Log.error('invalid option: %s', arg) return end if opt.needs_value then if value then if not set_value(n, opt, value) then return end else return read_value(n+1, opt) end else if not result[name] then result[name] = {} end result[name].long = true end return read_nth(n+1) end local function read_optstring(n, optstring) local a = string.sub(optstring, 1, 1) if #a < 1 then return read_nth(n+1) end local rest = string.sub(optstring, 2) local opt = self.config.short[a] if not opt then Log.error('invalid option: -%s', a) return end if opt.needs_value then if #rest > 0 then if set_value(n, opt, rest) then return read_nth(n+1) else return end else return read_value(n+1, opt) end else if not result[opt.long] then result[opt.long] = {} end result[opt.long].short = true return read_optstring(n, rest) end end local function read_short(n) local arg = args[n] return read_optstring(n, string.sub(arg, 2)) end read_nth = function (n) local arg = args[n] if not arg then return result end if eoa then result._args = append(result._args, args[n]) else if self:is_eoa(arg) then eoa = true elseif self:is_long(arg) then return read_long(n) elseif self:is_short(arg) then return read_short(n) else table.insert(result, args[n]) end end return read_nth(n+1, args) end return read_nth(1) end return P
Fix args stringification ignoring some flags
Fix args stringification ignoring some flags String conversion function of Options was incorrect causing it to miss true/false values. In particular --quiet which is supposed to be set implicitly for build command without arguments. The regression introduced in b05cfbee.
Lua
mit
bazurbat/jagen
93f68201992bd34d5db235076e793d36faf40061
Hydra/screen.lua
Hydra/screen.lua
doc.screen.__doc = [[ Manipulate screens (i.e. monitors). You usually get a screen through a window (see `window.screen`). But you can get screens by themselves through this module, albeit not in any defined/useful order. Hydra's coordinate system assumes a grid that is the union of every screen's rect (see `screen.frame_including_dock_and_menu`). Every window's position (i.e. `topleft`) and size are relative to this grid, and they're usually within the grid. A window that's semi-offscreen only intersects the grid.]] doc.screen.frame_including_dock_and_menu = {"screen:frame_including_dock_and_menu() -> rect", "Returns the screen's rect in absolute coordinates, including the dock and menu."} function screen:frame_including_dock_and_menu() local primary_screen = screen.allscreens()[1] local f = self:frame() f.y = primary_screen:frame().h - f.h - f.y return f end doc.screen.frame_without_dock_or_menu = {"screen:frame_without_dock_or_menu() -> rect", "Returns the screen's rect in absolute coordinates, without the dock or menu."} function screen:frame_without_dock_or_menu() local primary_screen = screen.allscreens()[1] local f = self:visibleframe() f.y = primary_screen:frame().h - f.h - f.y return f end doc.screen.next = {"screen:next() -> screen", "Returns the screen 'after' this one; I have no idea how they're ordered though."} function screen:next() local screens = screen.allscreens() local i = fnutils.indexof(screens, self) + 1 if i > # screens then i = 1 end return screens[i] end doc.screen.previous = {"screen:previous() -> screen", "Returns the screen 'before' this one; I have no idea how they're ordered though."} function screen:previous() local screens = screen.allscreens() local i = fnutils.indexof(screens, self) - 1 if i < 1 then i = # screens end return screens[i] end
doc.screen.__doc = [[ Manipulate screens (i.e. monitors). You usually get a screen through a window (see `window.screen`). But you can get screens by themselves through this module, albeit not in any defined/useful order. Hydra's coordinate system assumes a grid that is the union of every screen's rect (see `screen.frame_including_dock_and_menu`). Every window's position (i.e. `topleft`) and size are relative to this grid, and they're usually within the grid. A window that's semi-offscreen only intersects the grid.]] doc.screen.frame_including_dock_and_menu = {"screen:frame_including_dock_and_menu() -> rect", "Returns the screen's rect in absolute coordinates, including the dock and menu."} function screen:frame_including_dock_and_menu() local primary_screen = screen.allscreens()[1] local f = self:frame() f.y = primary_screen:frame().h - f.h - f.y return f end doc.screen.frame_without_dock_or_menu = {"screen:frame_without_dock_or_menu() -> rect", "Returns the screen's rect in absolute coordinates, without the dock or menu."} function screen:frame_without_dock_or_menu() local primary_screen = screen.allscreens()[1] local f = self:visibleframe() f.y = primary_screen:frame().h - f.h - f.y return f end doc.screen.next = {"screen:next() -> screen", "Returns the screen 'after' this one (I have no idea how they're ordered though); this method wraps around to the first screen."} function screen:next() local screens = screen.allscreens() local i = fnutils.indexof(screens, self) + 1 if i > # screens then i = 1 end return screens[i] end doc.screen.previous = {"screen:previous() -> screen", "Returns the screen 'before' this one (I have no idea how they're ordered though); this method wraps around to the last screen."} function screen:previous() local screens = screen.allscreens() local i = fnutils.indexof(screens, self) - 1 if i < 1 then i = # screens end return screens[i] end
Mention that screen methods wrap; fixes #126.
Mention that screen methods wrap; fixes #126.
Lua
mit
lowne/hammerspoon,chrisjbray/hammerspoon,chrisjbray/hammerspoon,wsmith323/hammerspoon,Hammerspoon/hammerspoon,junkblocker/hammerspoon,wsmith323/hammerspoon,knu/hammerspoon,cmsj/hammerspoon,emoses/hammerspoon,wvierber/hammerspoon,wvierber/hammerspoon,dopcn/hammerspoon,Hammerspoon/hammerspoon,asmagill/hammerspoon,zzamboni/hammerspoon,TimVonsee/hammerspoon,latenitefilms/hammerspoon,knl/hammerspoon,ocurr/hammerspoon,hypebeast/hammerspoon,Habbie/hammerspoon,Habbie/hammerspoon,peterhajas/hammerspoon,heptal/hammerspoon,TimVonsee/hammerspoon,TimVonsee/hammerspoon,heptal/hammerspoon,emoses/hammerspoon,latenitefilms/hammerspoon,dopcn/hammerspoon,latenitefilms/hammerspoon,chrisjbray/hammerspoon,hypebeast/hammerspoon,peterhajas/hammerspoon,bradparks/hammerspoon,knu/hammerspoon,kkamdooong/hammerspoon,peterhajas/hammerspoon,lowne/hammerspoon,nkgm/hammerspoon,chrisjbray/hammerspoon,peterhajas/hammerspoon,CommandPost/CommandPost-App,knu/hammerspoon,lowne/hammerspoon,joehanchoi/hammerspoon,cmsj/hammerspoon,wsmith323/hammerspoon,CommandPost/CommandPost-App,joehanchoi/hammerspoon,Hammerspoon/hammerspoon,emoses/hammerspoon,wvierber/hammerspoon,CommandPost/CommandPost-App,asmagill/hammerspoon,CommandPost/CommandPost-App,lowne/hammerspoon,dopcn/hammerspoon,cmsj/hammerspoon,zzamboni/hammerspoon,ocurr/hammerspoon,TimVonsee/hammerspoon,chrisjbray/hammerspoon,Stimim/hammerspoon,asmagill/hammerspoon,asmagill/hammerspoon,junkblocker/hammerspoon,ocurr/hammerspoon,emoses/hammerspoon,CommandPost/CommandPost-App,hypebeast/hammerspoon,hypebeast/hammerspoon,lowne/hammerspoon,Habbie/hammerspoon,junkblocker/hammerspoon,knl/hammerspoon,latenitefilms/hammerspoon,bradparks/hammerspoon,Hammerspoon/hammerspoon,knu/hammerspoon,Habbie/hammerspoon,asmagill/hammerspoon,hypebeast/hammerspoon,tmandry/hammerspoon,junkblocker/hammerspoon,wvierber/hammerspoon,Stimim/hammerspoon,dopcn/hammerspoon,kkamdooong/hammerspoon,tmandry/hammerspoon,tmandry/hammerspoon,nkgm/hammerspoon,kkamdooong/hammerspoon,knu/hammerspoon,asmagill/hammerspoon,nkgm/hammerspoon,Hammerspoon/hammerspoon,trishume/hammerspoon,kkamdooong/hammerspoon,cmsj/hammerspoon,knl/hammerspoon,zzamboni/hammerspoon,heptal/hammerspoon,knu/hammerspoon,Habbie/hammerspoon,Hammerspoon/hammerspoon,cmsj/hammerspoon,trishume/hammerspoon,zzamboni/hammerspoon,wsmith323/hammerspoon,dopcn/hammerspoon,ocurr/hammerspoon,CommandPost/CommandPost-App,junkblocker/hammerspoon,ocurr/hammerspoon,nkgm/hammerspoon,Habbie/hammerspoon,wvierber/hammerspoon,heptal/hammerspoon,emoses/hammerspoon,latenitefilms/hammerspoon,bradparks/hammerspoon,wsmith323/hammerspoon,joehanchoi/hammerspoon,cmsj/hammerspoon,chrisjbray/hammerspoon,zzamboni/hammerspoon,nkgm/hammerspoon,heptal/hammerspoon,joehanchoi/hammerspoon,bradparks/hammerspoon,Stimim/hammerspoon,TimVonsee/hammerspoon,knl/hammerspoon,trishume/hammerspoon,zzamboni/hammerspoon,Stimim/hammerspoon,joehanchoi/hammerspoon,latenitefilms/hammerspoon,knl/hammerspoon,bradparks/hammerspoon,kkamdooong/hammerspoon,Stimim/hammerspoon,peterhajas/hammerspoon
5f0b31c9341ba87574acfa68a647de0af8862738
watcher.lua
watcher.lua
directions = require 'directions' local function exports(x, y, direction) assert(directions.is_direction(direction)) local instance = {} instance.type = 'watcher' instance.x = x instance.y = y instance.direction = direction instance.image = love.graphics.newImage('placeholders/watcher.png') instance.quad = love.graphics.newQuad(0, 0, 32, 32, 32, 32) function instance:update(grid) assert(grid:in_grid(self.x, self.y)) --find dirty cells if grid:get_space_at(self.x+1, self.y) then self.direction = directions.RIGHT elseif grid:get_space_at(self.x-1, self.y) then self.direction = directions.LEFT elseif grid:get_space_at(self.x, self.y+1) then self.direction = directions.DOWN elseif grid:get_space_at(self.x, self.y-1) then self.direction = directions.UP end local next_x = self.x + directions.get_x_diff(self.direction) local next_y = self.y + directions.get_y_diff(self.direction) if grid:in_grid(next_x, next_y) then if grid:get_space_at(next_x, next_y) then grid:set_space_at(next_x, next_y, false) end local object = grid:get_object_at(next_x, next_y) if object and object.type == 'glider' then grid:delete_object_at(next_x, next_y) self.x = next_x self.y = next_y elseif object and object.type == 'watcher' then self.direction = directions.invert(self.direction) else self.x = next_x self.y = next_y end else self.direction = directions.invert(self.direction) end end function instance:draw(offset_x, offset_y) local actual_x = offset_x + self.x * 32 local actual_y = offset_y + self.y * 32 love.graphics.draw(self.image, self.quad, actual_x - 16, actual_y - 16, directions.get_angle(self.direction), 1, 1, 16, 16) end return instance end return exports
directions = require 'directions' local function exports(x, y, direction) assert(directions.is_direction(direction)) local instance = {} instance.type = 'watcher' instance.x = x instance.y = y instance.direction = direction instance.image = love.graphics.newImage('placeholders/watcher.png') instance.quad = love.graphics.newQuad(0, 0, 32, 32, 32, 32) function instance:update(grid) assert(grid:in_grid(self.x, self.y)) --find dirty cells if grid:get_space_at(self.x+1, self.y) then self.direction = directions.RIGHT elseif grid:get_space_at(self.x-1, self.y) then self.direction = directions.LEFT elseif grid:get_space_at(self.x, self.y+1) then self.direction = directions.DOWN elseif grid:get_space_at(self.x, self.y-1) then self.direction = directions.UP end --find close gliders if grid:get_object_at(self.x+1, self.y) and grid:get_object_at(self.x+1, self.y).type == 'glider' then self.direction = directions.RIGHT elseif grid:get_object_at(self.x-1, self.y) and grid:get_object_at(self.x-1, self.y).type == 'glider'then self.direction = directions.LEFT elseif grid:get_object_at(self.x, self.y+1) and grid:get_object_at(self.x, self.y+1).type == 'glider' then self.direction = directions.DOWN elseif grid:get_object_at(self.x, self.y-1) and grid:get_object_at(self.x, self.y-1).type == 'glider' then self.direction = directions.UP end local next_x = self.x + directions.get_x_diff(self.direction) local next_y = self.y + directions.get_y_diff(self.direction) if grid:in_grid(next_x, next_y) then if grid:get_space_at(next_x, next_y) then grid:set_space_at(next_x, next_y, false) end local object = grid:get_object_at(next_x, next_y) if object and object.type == 'glider' then grid:delete_object(object) self.x = next_x self.y = next_y elseif object and object.type == 'watcher' then self.direction = directions.invert(self.direction) else self.x = next_x self.y = next_y end else self.direction = directions.invert(self.direction) end end function instance:draw(offset_x, offset_y) local actual_x = offset_x + self.x * 32 local actual_y = offset_y + self.y * 32 love.graphics.draw(self.image, self.quad, actual_x - 16, actual_y - 16, directions.get_angle(self.direction), 1, 1, 16, 16) end return instance end return exports
Fix glider kill.
Fix glider kill.
Lua
mit
NamefulTeam/PortoGameJam2015
578a2ebf3043ba5fe8dee7073359f0db01776331
LibGuildStorage-1.0.lua
LibGuildStorage-1.0.lua
-- This library handles storing information in officer notes. It -- streamlines and optimizes access to these notes. The API is as -- follows: -- -- GetNote(name): Returns the officer note of member 'name' -- -- SetNote(name, note): Sets the officer note of member 'name' to -- 'note' -- -- GetClass(name): Returns the class of member 'name' -- -- GetGuildInfo(): Returns the guild info text -- -- ProtectActionButton(button): Enables and disables buttons -- accordingly depending on the state of the library to avoid data -- corruption. -- -- The library also fires the following messages, which you can -- register for through RegisterCallback and unregister through -- UnregisterCallback. You can also unregister all messages through -- UnregisterAllCallbacks. -- -- GuildInfoChanged(info): Fired when guild info has changed since its -- previous state. The info is the new guild info. -- -- GuildNoteChanged(name, note): Fired when a guild note changes. The -- name is the name of the member of which the note changed and the -- note is the new note. local MAJOR_VERSION = "LibGuildStorage-1.0" local MINOR_VERSION = tonumber(("$Revision$"):match("%d+")) or 0 local lib, oldMinor = LibStub:NewLibrary(MAJOR_VERSION, MINOR_VERSION) if not lib then return end local CallbackHandler = LibStub("CallbackHandler-1.0") if not lib.callbacks then lib.callbacks = CallbackHandler:New(lib) end local callbacks = lib.callbacks if lib.frame then lib.frame:UnregisterAllEvents() lib.frame:SetScript("OnEvent", nil) lib.frame:SetScript("OnUpdate", nil) else lib.frame = CreateFrame("Frame", MAJOR_VERSION .. "_Frame") end local frame = lib.frame local state = "STALE" local protected_buttons = {} local function LockActionButtons() for button in pairs(protected_buttons) do button:Disable() end end local function RestoreActionButtons() for button in pairs(protected_buttons) do button:SetCurrentState() end end local timers = LibStub("AceTimer-3.0") -- We want to not call GuildRoster continuously if we are doing a lot -- of changes so delay it by 10 milliseconds. If another request comes -- in to update the roster in the meantime cancel the current one and -- schedule another after 10 milliseconds. local guildroster_timer local function GuildRosterDelayed() timers:CancelTimer(guildroster_timer, true) guildroster_timer = timers:ScheduleTimer(GuildRoster, 0.01) end frame:SetScript("OnEvent", function(this, event, ...) lib[event](lib, ...) end) -- Cache is indexed by name and a table with index, class and note local cache = {} local guild_info = "" local next_index = 1 local function UpdateGuildRoster() if next_index == 1 then local new_guild_info = GetGuildInfoText() or "" if new_guild_info ~= guild_info then guild_info = new_guild_info callbacks:Fire("GuildInfoChanged", guild_info) end end -- Read up to 100 members at a time. local e = math.min(next_index + 99, GetNumGuildMembers(true)) for i = next_index, e do local name, _, _, _, _, _, _, note, _, _, class = GetGuildRosterInfo(i) if name then local t = cache[name] if not t then t = {} cache[name] = t end t.index = i t.class = class if t.note ~= note then t.note = note callbacks:Fire("GuildNoteChanged", name, note) end end end next_index = e + 1 if next_index > GetNumGuildMembers(true) then frame:Hide() if state == "STALE" then RestoreActionButtons() state = "CURRENT" elseif state == "LOCAL_PENDING" then RestoreActionButtons() SendAddonMessage("EPGP", "CHANGES_FLUSHED", "GUILD") state = "CURRENT" elseif state == "REMOTE_FLUSHED" then RestoreActionButtons() state = "CURRENT" end end end frame:SetScript("OnUpdate", UpdateGuildRoster) frame:RegisterEvent("PLAYER_GUILD_UPDATE") frame:RegisterEvent("GUILD_ROSTER_UPDATE") frame:RegisterEvent("CHAT_MSG_ADDON") function lib:CHAT_MSG_ADDON(prefix, msg, type, sender) if prefix == "EPGP" and sender ~= UnitName("player") then if msg == "CHANGES_PENDING" then LockActionButtons() state = "REMOTE_PENDING" elseif msg == "CHANGES_FLUSHED" then GuildRosterDelayed() state = "REMOTE_FLUSHED" end end end function lib:PLAYER_GUILD_UPDATE() -- Hide the frame to stop OnUpdate from reading guild information if frame:IsShown() and not IsInGuild() then frame:Hide() end GuildRosterDelayed() end function lib:GUILD_ROSTER_UPDATE(loc) if loc then GuildRosterDelayed() return end -- Show the frame to make the OnUpdate handler to be called next_index = 1 frame:Show() end function lib:GetNote(name) local entry = cache[name] if not entry then return nil end return entry.note end function lib:SetNote(name, note) LockActionButtons() -- Also lock down all other clients as well if not changes_pending then SendAddonMessage("EPGP", "CHANGES_PENDING", "GUILD") end state = "LOCAL_PENDING" local entry = cache[name] if not entry then return end -- We do not update the note here. We are going to wait until the -- next GUILD_ROSTER_UPDATE and fire a GuildNoteChanged callback. -- TODO(alkis): Investigate performance issues in case we want to -- verify if this is the right index or not. GuildRosterSetOfficerNote(entry.index, note) end function lib:GetClass(name) local entry = cache[name] if not entry then return end return entry.class end function lib:GetGuildInfo() return guild_info end function lib:ProtectActionButton(button) assert(button:IsObjectType("Button"), "Argument must be a Button") protected_buttons[button] = true end GuildRosterDelayed() last_guildroster_time = GetTime() frame:Hide()
-- This library handles storing information in officer notes. It -- streamlines and optimizes access to these notes. The API is as -- follows: -- -- GetNote(name): Returns the officer note of member 'name' -- -- SetNote(name, note): Sets the officer note of member 'name' to -- 'note' -- -- GetClass(name): Returns the class of member 'name' -- -- GetGuildInfo(): Returns the guild info text -- -- ProtectActionButton(button): Enables and disables buttons -- accordingly depending on the state of the library to avoid data -- corruption. -- -- The library also fires the following messages, which you can -- register for through RegisterCallback and unregister through -- UnregisterCallback. You can also unregister all messages through -- UnregisterAllCallbacks. -- -- GuildInfoChanged(info): Fired when guild info has changed since its -- previous state. The info is the new guild info. -- -- GuildNoteChanged(name, note): Fired when a guild note changes. The -- name is the name of the member of which the note changed and the -- note is the new note. local MAJOR_VERSION = "LibGuildStorage-1.0" local MINOR_VERSION = tonumber(("$Revision$"):match("%d+")) or 0 local lib, oldMinor = LibStub:NewLibrary(MAJOR_VERSION, MINOR_VERSION) if not lib then return end local CallbackHandler = LibStub("CallbackHandler-1.0") if not lib.callbacks then lib.callbacks = CallbackHandler:New(lib) end local callbacks = lib.callbacks if lib.frame then lib.frame:UnregisterAllEvents() lib.frame:SetScript("OnEvent", nil) lib.frame:SetScript("OnUpdate", nil) else lib.frame = CreateFrame("Frame", MAJOR_VERSION .. "_Frame") end local frame = lib.frame -- Possible states: STALE, LOCAL_PENDING, REMOTE_PENDING, CURRENT local state = "STALE" local protected_buttons = {} local function LockActionButtons() for button in pairs(protected_buttons) do button:Disable() end end local function RestoreActionButtons() for button in pairs(protected_buttons) do button:SetCurrentState() end end local timers = LibStub("AceTimer-3.0") -- We want to not call GuildRoster continuously if we are doing a lot -- of changes so delay it by 10 milliseconds. If another request comes -- in to update the roster in the meantime cancel the current one and -- schedule another after 10 milliseconds. local guildroster_timer local function GuildRosterDelayed() timers:CancelTimer(guildroster_timer, true) guildroster_timer = timers:ScheduleTimer(GuildRoster, 0.01) end frame:SetScript("OnEvent", function(this, event, ...) lib[event](lib, ...) end) -- Cache is indexed by name and a table with index, class and note local cache = {} local guild_info = "" local next_index = 1 local function UpdateGuildRoster() if next_index == 1 then local new_guild_info = GetGuildInfoText() or "" if new_guild_info ~= guild_info then guild_info = new_guild_info callbacks:Fire("GuildInfoChanged", guild_info) end end -- Read up to 100 members at a time. local e = math.min(next_index + 99, GetNumGuildMembers(true)) for i = next_index, e do local name, _, _, _, _, _, _, note, _, _, class = GetGuildRosterInfo(i) if name then local t = cache[name] if not t then t = {} cache[name] = t end t.index = i t.class = class if t.note ~= note then t.note = note callbacks:Fire("GuildNoteChanged", name, note) end end end next_index = e + 1 if next_index > GetNumGuildMembers(true) then frame:Hide() if state == "STALE" then RestoreActionButtons() state = "CURRENT" elseif state == "LOCAL_PENDING" then RestoreActionButtons() SendAddonMessage("EPGP", "CHANGES_FLUSHED", "GUILD") state = "CURRENT" elseif state == "REMOTE_FLUSHED" then RestoreActionButtons() state = "CURRENT" end end end frame:SetScript("OnUpdate", UpdateGuildRoster) frame:RegisterEvent("PLAYER_GUILD_UPDATE") frame:RegisterEvent("GUILD_ROSTER_UPDATE") frame:RegisterEvent("CHAT_MSG_ADDON") function lib:CHAT_MSG_ADDON(prefix, msg, type, sender) if prefix == "EPGP" and sender ~= UnitName("player") then if msg == "CHANGES_PENDING" then LockActionButtons() state = "REMOTE_PENDING" elseif msg == "CHANGES_FLUSHED" then GuildRosterDelayed() state = "REMOTE_FLUSHED" end end end function lib:PLAYER_GUILD_UPDATE() -- Hide the frame to stop OnUpdate from reading guild information if frame:IsShown() and not IsInGuild() then frame:Hide() end GuildRosterDelayed() end function lib:GUILD_ROSTER_UPDATE(loc) if loc then GuildRosterDelayed() return end -- Show the frame to make the OnUpdate handler to be called next_index = 1 frame:Show() end function lib:GetNote(name) local entry = cache[name] if not entry then return nil end return entry.note end function lib:SetNote(name, note) -- Also lock down all other clients as well if state == "CURRENT" then LockActionButtons() SendAddonMessage("EPGP", "CHANGES_PENDING", "GUILD") state = "LOCAL_PENDING" end local entry = cache[name] if not entry then return end -- We do not update the note here. We are going to wait until the -- next GUILD_ROSTER_UPDATE and fire a GuildNoteChanged callback. -- TODO(alkis): Investigate performance issues in case we want to -- verify if this is the right index or not. GuildRosterSetOfficerNote(entry.index, note) end function lib:GetClass(name) local entry = cache[name] if not entry then return end return entry.class end function lib:GetGuildInfo() return guild_info end function lib:ProtectActionButton(button) assert(button:IsObjectType("Button"), "Argument must be a Button") protected_buttons[button] = true end GuildRosterDelayed() last_guildroster_time = GetTime() frame:Hide()
Fix thinko and add some documentation about the states.
Fix thinko and add some documentation about the states.
Lua
bsd-3-clause
sheldon/epgp,hayword/tfatf_epgp,protomech/epgp-dkp-reloaded,sheldon/epgp,ceason/epgp-tfatf,protomech/epgp-dkp-reloaded,hayword/tfatf_epgp,ceason/epgp-tfatf
4f744b474d17073d6a7d13d3e6af7e807e358a53
stock-widget.lua
stock-widget.lua
local wibox = require("wibox") local awful = require("awful") awful.util = require("awful.util") local os = require("os") local function color_tags(color) if color then return '<span color="' .. color .. '">', '</span>' else return '', '' end end local function substitute(template, context) if type(template) == "string" then return (template:gsub("%${([%w_]+)}", function(key) return tostring(context[key] or "Err!") end)) else -- function / functor: return template(context) end end local stock_widget = {} function stock_widget:new(args) return setmetatable({}, {__index = self}):init(args) end function stock_widget:init(args) if args.symbol == nil then error("symbol is require") end self.symbol = args.symbol self.widget = wibox.widget.textbox() self.text_format = args.text_format or ( "${symbol_color_on}${symbol}${symbol_color_off} ${price_color_on}\$${price}${price_color_off} ${change_color_on}${change}%${change_color_off}") self.symbol_color = args.symbol_color or "white" self.price_color = args.price_color or nil self.gain_color = args.gain_color or "green" self.loss_color = args.loss_color or "red" self.get_stock_price_location = args.get_stock_price_location if self.get_stock_price_location == nil then local home = os.getenv("HOME") local base_config_location = home .. "/.config/awesome" local sub_module_location = home .. "/.config/awesome/stock-widget" if awful.util.file_readable(base_config_location .. "/get_stock_price.py") then self.get_stock_price_location = base_config_location elseif awful.util.file_readable(sub_module_location .. "/get_stock_price.py") then self.get_stock_price_location = sub_module_location else error("could not find get_stock_price.py") end end self.timer = timer({ timeout = args.timeout or 60 }) self.timer:connect_signal("timeout", function() self:update() end) self.timer:start() self:update() return self end function stock_widget:get_stock_info() local f = assert(io.popen(self.get_stock_price_location .. "/get_stock_price.py" .. " " .. self.symbol, "r")) local stock_info = assert(f:read("*a")) f:close() -- split output on space local items = {} for item in stock_info:gmatch("%S+") do table.insert(items, item) end return { price = items[1], change = items[2] } end function stock_widget:update() local data = self:get_stock_info() data.symbol = self.symbol -- colors data.symbol_color_on, data.symbol_color_off = color_tags(self.symbol_color) data.price_color_on, data.price_color_off = color_tags(self.price_color) local change_color = self.gain_color if data.change:sub(1,1) == "-" then change_color = self.loss_color end data.change_color_on, data.change_color_off = color_tags(change_color) self.widget:set_markup(substitute(self.text_format, data)) end return setmetatable(stock_widget, {__call = stock_widget.new})
local wibox = require("wibox") local awful = require("awful") awful.util = require("awful.util") local os = require("os") local naughty = require("naughty") local function color_tags(color) if color then return '<span color="' .. color .. '">', '</span>' else return '', '' end end local function substitute(template, context) if type(template) == "string" then return (template:gsub("%${([%w_]+)}", function(key) return tostring(context[key] or "Err!") end)) else -- function / functor: return template(context) end end local stock_widget = {} function stock_widget:new(args) return setmetatable({}, {__index = self}):init(args) end function stock_widget:init(args) if args.symbol == nil then error("symbol is require") end self.symbol = args.symbol self.widget = wibox.widget.textbox() self.text_format = args.text_format or ( "${symbol_color_on}${symbol}${symbol_color_off} ${price_color_on}\$${price}${price_color_off} ${change_color_on}${change}%${change_color_off}") self.symbol_color = args.symbol_color or "white" self.price_color = args.price_color or nil self.gain_color = args.gain_color or "green" self.loss_color = args.loss_color or "red" self.get_stock_price_location = args.get_stock_price_location if self.get_stock_price_location == nil then local home = os.getenv("HOME") local base_config_location = home .. "/.config/awesome" local sub_module_location = home .. "/.config/awesome/stock-widget" if awful.util.file_readable(base_config_location .. "/get_stock_price.py") then self.get_stock_price_location = base_config_location elseif awful.util.file_readable(sub_module_location .. "/get_stock_price.py") then self.get_stock_price_location = sub_module_location else error("could not find get_stock_price.py") end end self.timer = timer({ timeout = args.timeout or 60 }) self.timer:connect_signal("timeout", function() self:update() end) self.timer:start() self:update() return self end function stock_widget:get_stock_info() local f = assert(io.popen(self.get_stock_price_location .. "/get_stock_price.py" .. " " .. self.symbol, "r")) local stock_info = assert(f:read("*a")) f:close() -- TODO: it would be nice if I could check the exit code here -- split output on space local items = {} for item in stock_info:gmatch("%S+") do table.insert(items, item) end return { price = items[1], change = items[2] } end function stock_widget:update() local data = self:get_stock_info() if data.price == nil or data.change == nil then naughty.notify({ text = "Error getting stock info for " .. self.symbol }) self.timer:stop() return end data.symbol = self.symbol -- colors data.symbol_color_on, data.symbol_color_off = color_tags(self.symbol_color) data.price_color_on, data.price_color_off = color_tags(self.price_color) local change_color = self.gain_color if data.change:sub(1,1) == "-" then change_color = self.loss_color end data.change_color_on, data.change_color_off = color_tags(change_color) self.widget:set_markup(substitute(self.text_format, data)) end return setmetatable(stock_widget, {__call = stock_widget.new})
Basic notification for errors getting stock info
Basic notification for errors getting stock info - Fixes #1
Lua
mit
whwright/stock-widget
722e67faf14f80b46c7f89cbd73f4a3378917c49
spec/model/row_spec.lua
spec/model/row_spec.lua
local model = require 'npge.model' local Row = model.Row describe("model.row", function() it("throws on empty string", function() assert.has_error(function() Row("") end) end) it("uses row A-T-G-C", function() local r = Row("A-T-G-C") assert.are.equal(r:length(), 7) assert.are.equal(r:fragment_length(), 4) assert.are.equal(r:text(), 'N-N-N-N') -- block2fragment assert.are.equal(r:block2fragment(0), 0) assert.are.equal(r:block2fragment(1), -1) assert.are.equal(r:block2fragment(2), 1) assert.are.equal(r:block2fragment(3), -1) assert.are.equal(r:block2fragment(4), 2) assert.are.equal(r:block2fragment(5), -1) assert.are.equal(r:block2fragment(6), 3) assert.has_error(function() r:block2fragment(-1) end) assert.has_error(function() r:block2fragment(-100) end) assert.has_error(function() r:block2fragment(7) end) assert.has_error(function() r:block2fragment(100) end) -- fragment2block assert.are.equal(r:fragment2block(0), 0) assert.are.equal(r:fragment2block(1), 2) assert.are.equal(r:fragment2block(2), 4) assert.are.equal(r:fragment2block(3), 6) assert.has_error(function() r:fragment2block(-1) end) assert.has_error(function() r:fragment2block(-100) end) assert.has_error(function() r:fragment2block(4) end) assert.has_error(function() r:fragment2block(100) end) end) local check_row = function(text) local Block = require 'npge.model.Block' text = Block.to_atgcn_and_gap(text) return function() local r = Row(text) assert.are.equal(r:length(), #text) local Sequence = require 'npge.model.Sequence' local ungapped = Sequence.to_atgcn(text) assert.are.equal(r:fragment_length(), #ungapped) local text1 = text:gsub('[^-]', 'N') assert.are.equal(r:text(), text1) local fp = 0 for bp = 0, #text - 1 do local char = text:sub(bp + 1, bp + 1) if char ~= '-' then assert.are.equal(r:block2fragment(bp), fp) assert.are.equal(r:fragment2block(fp), bp) fp = fp + 1 else assert.are.equal(r:block2fragment(bp), -1) end end assert.has_error(function() r:block2fragment(-1) end) assert.has_error(function() r:block2fragment(-100) end) assert.has_error(function() r:block2fragment(#text) end) assert.has_error(function() r:block2fragment(2 * #text) end) assert.has_error(function() r:fragment2block(-1) end) assert.has_error(function() r:fragment2block(-100) end) assert.has_error(function() r:fragment2block(#ungapped) end) assert.has_error(function() r:fragment2block(#ungapped * 2) end) end end it("uses row A-T-G-C (2)", function() return check_row("A-T-G-C") end) it("uses row ATGC", function() return check_row("ATGC") end) it("uses row A", function() return check_row("A") end) it("uses row --A-", function() return check_row("--A-") end) it("uses long row", function() return check_row([[ TCACCATTATACAGTTATGGTATGAACTGGGTCTTCAT-AA------AA-AAAAATATTT TTTTTTGTTTATGCCATCATAGTTGTTCAATTATGCTAGTTT-----------GAATACC GAGCAAGAGCCACGTGCTTGAAAATCTTGCAAGCACTTTGAGGGGGAGCATTTTGAAAGC TTAAGTTTGACTCAATAACTGCGATGGTTGAGGGTAAT----------------TT-ATG -ATATATGACTTGCTTTCATCAAGTATGTCGCGTGATTACTGAAGCTTTCTCTGCCCTGC ATAATGACCTATAATTATTC-----CAAAAAGCTTACTC ]]) end) end)
local model = require 'npge.model' local Row = model.Row describe("model.row", function() it("throws on empty string", function() assert.has_error(function() Row("") end) end) it("uses row A-T-G-C", function() local r = Row("A-T-G-C") assert.are.equal(r:length(), 7) assert.are.equal(r:fragment_length(), 4) assert.are.equal(r:text(), 'N-N-N-N') -- block2fragment assert.are.equal(r:block2fragment(0), 0) assert.are.equal(r:block2fragment(1), -1) assert.are.equal(r:block2fragment(2), 1) assert.are.equal(r:block2fragment(3), -1) assert.are.equal(r:block2fragment(4), 2) assert.are.equal(r:block2fragment(5), -1) assert.are.equal(r:block2fragment(6), 3) assert.has_error(function() r:block2fragment(-1) end) assert.has_error(function() r:block2fragment(-100) end) assert.has_error(function() r:block2fragment(7) end) assert.has_error(function() r:block2fragment(100) end) -- fragment2block assert.are.equal(r:fragment2block(0), 0) assert.are.equal(r:fragment2block(1), 2) assert.are.equal(r:fragment2block(2), 4) assert.are.equal(r:fragment2block(3), 6) assert.has_error(function() r:fragment2block(-1) end) assert.has_error(function() r:fragment2block(-100) end) assert.has_error(function() r:fragment2block(4) end) assert.has_error(function() r:fragment2block(100) end) end) local check_row = function(text) local Block = require 'npge.model.Block' text = Block.to_atgcn_and_gap(text) return function() local r = Row(text) assert.are.equal(r:length(), #text) local Sequence = require 'npge.model.Sequence' local ungapped = Sequence.to_atgcn(text) assert.are.equal(r:fragment_length(), #ungapped) local text1 = text:gsub('[^-]', 'N') assert.are.equal(r:text(), text1) local fp = 0 for bp = 0, #text - 1 do local char = text:sub(bp + 1, bp + 1) if char ~= '-' then assert.are.equal(r:block2fragment(bp), fp) assert.are.equal(r:fragment2block(fp), bp) fp = fp + 1 else assert.are.equal(r:block2fragment(bp), -1) end end assert.has_error(function() r:block2fragment(-1) end) assert.has_error(function() r:block2fragment(-100) end) assert.has_error(function() r:block2fragment(#text) end) assert.has_error(function() r:block2fragment(2 * #text) end) assert.has_error(function() r:fragment2block(-1) end) assert.has_error(function() r:fragment2block(-100) end) assert.has_error(function() r:fragment2block(#ungapped) end) assert.has_error(function() r:fragment2block(#ungapped * 2) end) end end it("uses row A-T-G-C (2)", check_row("A-T-G-C")) it("uses row ATGC", check_row("ATGC")) it("uses row A", check_row("A")) it("uses row --A-", check_row("--A-")) it("uses long row", check_row([[ TCACCATTATACAGTTATGGTATGAACTGGGTCTTCAT-AA------AA-AAAAATATTT TTTTTTGTTTATGCCATCATAGTTGTTCAATTATGCTAGTTT-----------GAATACC GAGCAAGAGCCACGTGCTTGAAAATCTTGCAAGCACTTTGAGGGGGAGCATTTTGAAAGC TTAAGTTTGACTCAATAACTGCGATGGTTGAGGGTAAT----------------TT-ATG -ATATATGACTTGCTTTCATCAAGTATGTCGCGTGATTACTGAAGCTTTCTCTGCCCTGC ATAATGACCTATAATTATTC-----CAAAAAGCTTACTC ]])) end)
fix error in row_spec
fix error in row_spec tests were not applied :(
Lua
mit
starius/lua-npge,starius/lua-npge,npge/lua-npge,npge/lua-npge,npge/lua-npge,starius/lua-npge
2d7f26d689c17f9e0f7d9a05681e7647e1c02703
stdlib/log/logger.lua
stdlib/log/logger.lua
--- Logger module -- @module log Logger = {} --- Creates a new logger object -- In debug mode, the logger writes immediately. Otherwise it buffers lines. -- Logger flushes after 60 seconds has elapsed since the last message. -- @param mod_name [required] the name of the mod to create the logger for -- @param log_name (optional, default: 'main') the name of the logger -- @param debug_mode (optional, default: false) toggles the debug state of logger. -- @param options (optional) table with optional arguments -- @return the logger instance function Logger.new(mod_name, log_name, debug_mode, options) if not mod_name then error("Logger must be given a mod_name as the first argument") end if not log_name then log_name = "main" end local Logger = {mod_name = mod_name, log_name = log_name, debug_mode = debug_mode, buffer = {}, last_written = 0, ever_written = false} --- Logger options Logger.options = { log_ticks = options.log_ticks or false, -- whether to add the ticks in the timestamp, default false file_extension = options.file_extension or 'log', -- extension of the file, default: log } Logger.file_name = 'logs/' .. Logger.mod_name .. '/' .. Logger.log_name .. '.' .. Logger.options.file_extension --- Logs a message -- @param msg a string, the message to log -- @return true if the message was written, false if it was queued for a later write function Logger.log(msg) local format = string.format if _G["game"] then local tick = game.tick local floor = math.floor local time_s = floor(tick/60) local time_minutes = floor(time_s/60) local time_hours = floor(time_minutes/60) if Logger.options.log_ticks then table.insert(Logger.buffer, format("%02d:%02d:%02d.%02d: %s\n", time_hours, time_minutes % 60, time_s % 60, tick - time_s*60, msg)) else table.insert(Logger.buffer, format("%02d:%02d:%02d: %s\n", time_hours, time_minutes % 60, time_s % 60, msg)) end -- write the log every minute if (Logger.debug_mode or (tick - Logger.last_written) > 3600) then return Logger.write() end else table.insert(Logger.buffer, format("00:00:00: %s\n", msg)) end return false end --- Writes out all buffered messages immediately -- @return true if there any messages were written, false if not function Logger.write() if _G["game"] then Logger.last_written = game.tick game.write_file(Logger.file_name, table.concat(Logger.buffer), Logger.ever_written) Logger.buffer = {} Logger.ever_written = true return true end return false end return Logger end return Logger
--- Logger module -- @module log Logger = {} --- Creates a new logger object -- In debug mode, the logger writes immediately. Otherwise it buffers lines. -- Logger flushes after 60 seconds has elapsed since the last message. -- @param mod_name [required] the name of the mod to create the logger for -- @param log_name (optional, default: 'main') the name of the logger -- @param debug_mode (optional, default: false) toggles the debug state of logger. -- @param options (optional) table with optional arguments -- @return the logger instance function Logger.new(mod_name, log_name, debug_mode, options) if not mod_name then error("Logger must be given a mod_name as the first argument") end if not log_name then log_name = "main" end if not options then options = {} end local Logger = {mod_name = mod_name, log_name = log_name, debug_mode = debug_mode, buffer = {}, last_written = 0, ever_written = false} --- Logger options Logger.options = { log_ticks = options.log_ticks or false, -- whether to add the ticks in the timestamp, default false file_extension = options.file_extension or 'log', -- extension of the file, default: log } Logger.file_name = 'logs/' .. Logger.mod_name .. '/' .. Logger.log_name .. '.' .. Logger.options.file_extension --- Logs a message -- @param msg a string, the message to log -- @return true if the message was written, false if it was queued for a later write function Logger.log(msg) local format = string.format if _G["game"] then local tick = game.tick local floor = math.floor local time_s = floor(tick/60) local time_minutes = floor(time_s/60) local time_hours = floor(time_minutes/60) if Logger.options.log_ticks then table.insert(Logger.buffer, format("%02d:%02d:%02d.%02d: %s\n", time_hours, time_minutes % 60, time_s % 60, tick - time_s*60, msg)) else table.insert(Logger.buffer, format("%02d:%02d:%02d: %s\n", time_hours, time_minutes % 60, time_s % 60, msg)) end -- write the log every minute if (Logger.debug_mode or (tick - Logger.last_written) > 3600) then return Logger.write() end else table.insert(Logger.buffer, format("00:00:00: %s\n", msg)) end return false end --- Writes out all buffered messages immediately -- @return true if there any messages were written, false if not function Logger.write() if _G["game"] then Logger.last_written = game.tick game.write_file(Logger.file_name, table.concat(Logger.buffer), Logger.ever_written) Logger.buffer = {} Logger.ever_written = true return true end return false end return Logger end return Logger
Fix invalid default value for logger options
Fix invalid default value for logger options
Lua
isc
Afforess/Factorio-Stdlib
c8cef7fcb008f9d33a7ef1c689e5a6481177a3ec
src/actions/vstudio/vs2005.lua
src/actions/vstudio/vs2005.lua
-- -- actions/vstudio/vs2005.lua -- Add support for the Visual Studio 2005 project formats. -- Copyright (c) 2008-2013 Jason Perkins and the Premake project -- premake.vstudio.vs2005 = {} local vs2005 = premake.vstudio.vs2005 local vstudio = premake.vstudio --- -- Register a command-line action for Visual Studio 2006. --- function vs2005.generateSolution(sln) io.eol = "\r\n" io.esc = vs2005.esc premake.generate(sln, ".sln", vstudio.sln2005.generate) end function vs2005.generateProject(prj) io.eol = "\r\n" io.esc = vs2005.esc if premake.project.isdotnet(prj) then premake.generate(prj, ".csproj", vstudio.cs2005.generate) premake.generate(prj, ".csproj.user", vstudio.cs2005.generate_user) elseif premake.project.iscpp(prj) then premake.generate(prj, ".vcproj", vstudio.vc200x.generate) premake.generate(prj, ".vcproj.user", vstudio.vc200x.generate_user) end end --- -- Apply XML escaping on a value to be included in an -- exported project file. --- function vs2005.esc(value) value = string.gsub(value, '&', "&amp;") value = value:gsub('"', "&quot;") value = value:gsub("'", "&apos;") value = value:gsub('<', "&lt;") value = value:gsub('>', "&gt;") value = value:gsub('\r', "&#x0D;") value = value:gsub('\n', "&#x0A;") return value end --- -- Define the Visual Studio 2005 export action. --- newaction { -- Metadata for the command line and help system trigger = "vs2005", shortname = "Visual Studio 2005", description = "Generate Visual Studio 2005 project files", -- Visual Studio always uses Windows path and naming conventions os = "windows", -- The capabilities of this action valid_kinds = { "ConsoleApp", "WindowedApp", "StaticLib", "SharedLib", "Makefile", "None" }, valid_languages = { "C", "C++", "C#" }, valid_tools = { cc = { "msc" }, dotnet = { "msnet" }, }, -- Solution and project generation logic onsolution = vstudio.vs2005.generateSolution, onproject = vstudio.vs2005.generateProject, oncleansolution = vstudio.cleanSolution, oncleanproject = vstudio.cleanProject, oncleantarget = vstudio.cleanTarget, -- This stuff is specific to the Visual Studio exporters vstudio = { csprojSchemaVersion = "2.0", productVersion = "8.0.50727", solutionVersion = "9", versionName = "2005", } }
-- -- actions/vstudio/vs2005.lua -- Add support for the Visual Studio 2005 project formats. -- Copyright (c) 2008-2013 Jason Perkins and the Premake project -- premake.vstudio.vs2005 = {} local vs2005 = premake.vstudio.vs2005 local vstudio = premake.vstudio --- -- Register a command-line action for Visual Studio 2006. --- function vs2005.generateSolution(sln) io.indent = nil -- back to default io.eol = "\r\n" io.esc = vs2005.esc premake.generate(sln, ".sln", vstudio.sln2005.generate) end function vs2005.generateProject(prj) io.eol = "\r\n" io.esc = vs2005.esc if premake.project.isdotnet(prj) then premake.generate(prj, ".csproj", vstudio.cs2005.generate) premake.generate(prj, ".csproj.user", vstudio.cs2005.generate_user) elseif premake.project.iscpp(prj) then premake.generate(prj, ".vcproj", vstudio.vc200x.generate) premake.generate(prj, ".vcproj.user", vstudio.vc200x.generate_user) end end --- -- Apply XML escaping on a value to be included in an -- exported project file. --- function vs2005.esc(value) value = string.gsub(value, '&', "&amp;") value = value:gsub('"', "&quot;") value = value:gsub("'", "&apos;") value = value:gsub('<', "&lt;") value = value:gsub('>', "&gt;") value = value:gsub('\r', "&#x0D;") value = value:gsub('\n', "&#x0A;") return value end --- -- Define the Visual Studio 2005 export action. --- newaction { -- Metadata for the command line and help system trigger = "vs2005", shortname = "Visual Studio 2005", description = "Generate Visual Studio 2005 project files", -- Visual Studio always uses Windows path and naming conventions os = "windows", -- The capabilities of this action valid_kinds = { "ConsoleApp", "WindowedApp", "StaticLib", "SharedLib", "Makefile", "None" }, valid_languages = { "C", "C++", "C#" }, valid_tools = { cc = { "msc" }, dotnet = { "msnet" }, }, -- Solution and project generation logic onsolution = vstudio.vs2005.generateSolution, onproject = vstudio.vs2005.generateProject, oncleansolution = vstudio.cleanSolution, oncleanproject = vstudio.cleanProject, oncleantarget = vstudio.cleanTarget, -- This stuff is specific to the Visual Studio exporters vstudio = { csprojSchemaVersion = "2.0", productVersion = "8.0.50727", solutionVersion = "9", versionName = "2005", } }
This fixes issue #41 by simply resetting the indentation to its default at the beginning of solution generation, i.e. in vs2005.generateSolution, shared by all VS implementations
This fixes issue #41 by simply resetting the indentation to its default at the beginning of solution generation, i.e. in vs2005.generateSolution, shared by all VS implementations
Lua
bsd-3-clause
dimitarcl/premake-dev,dimitarcl/premake-dev,dimitarcl/premake-dev
b4f76da576e577944521d50663b84a1780ffa2cb
test_scripts/RC/ButtonPress/005_check_rpc_paramters_for_button_press.lua
test_scripts/RC/ButtonPress/005_check_rpc_paramters_for_button_press.lua
--------------------------------------------------------------------------------------------------- -- RPC: ButtonPress -- Script: 005 --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local commonRC = require('test_scripts/RC/commonRC') local runner = require('user_modules/script_runner') local commonTestCases = require('user_modules/shared_testcases/commonTestCases') --[[ Local variables for tests ]] local climate_button_names = { "AC_MAX", "AC", "RECIRCULATE", "FAN_UP", "FAN_DOWN", "TEMP_UP", "TEMP_DOWN", "DEFROST_MAX", "DEFROST", "DEFROST_REAR", "UPPER_VENT", "LOWER_VENT" } local radio_button_names = { "VOLUME_UP", "VOLUME_DOWN", "EJECT", "SOURCE", "SHUFFLE", "REPEAT", } local climate_params = { moduleType = "CLIMATE", buttonName = "AC_MAX", buttonPressMode = "SHORT" -- LONG, SHORT } local radio_params = { moduleType = "RADIO", buttonName = "VOLUME_UP", buttonPressMode = "LONG" } commonRC.timeout = 1000 --[[ Local Functions ]] local function reset_climate_params( ... ) return {moduleType = "CLIMATE", buttonName = "AC", buttonPressMode = "SHORT"} end local function reset_radio_params( ... ) return {moduleType = "RADIO", buttonName = "VOLUME_UP", buttonPressMode = "SHORT"} end local function SendButtonPressPositive(button_press_params, self) local cid = self.mobileSession:SendRPC("ButtonPress", button_press_params) EXPECT_HMICALL("Buttons.ButtonPress", { appID = self.applications["Test Application"], moduleType = button_press_params.moduleType, buttonName = button_press_params.buttonName, buttonPressMode = button_press_params.buttonPressMode }) :Times(1) :Do(function(_, data) self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {}) end) EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS" }) commonTestCases:DelayedExp(commonRC.timeout) end local function SendButtonPressNegative(button_press_params, self) local cid = self.mobileSession:SendRPC("ButtonPress", button_press_params) EXPECT_HMICALL("Buttons.ButtonPress") :Times(0) EXPECT_RESPONSE(cid, { success = false, resultCode = "INVALID_DATA" }) commonTestCases:DelayedExp(commonRC.timeout) end --[[ Positive Scenario - check all positive climate names params]] climate_params = reset_climate_params() runner.Title("Preconditions") runner.Step("Clean environment", commonRC.preconditions) runner.Step("Start SDL, HMI, connect Mobile, start Session", commonRC.start) runner.Step("RAI, PTU", commonRC.rai_ptu) for _, button_name_value in pairs( climate_button_names ) do climate_params.buttonPressMode = "SHORT" climate_params.buttonName = button_name_value runner.Title("Test - ButtonPress with buttonName " .. button_name_value) runner.Step("ButtonPress_CLIMATE_" .. button_name_value .. "_SHORT", SendButtonPressPositive, {climate_params}) climate_params.buttonPressMode = "LONG" runner.Step("ButtonPress_CLIMATE_" .. button_name_value .. "_LONG", SendButtonPressPositive, {climate_params}) end --[[ Positive Scenario - check all positive radio names params]] radio_params = reset_radio_params() for _, button_name_value in pairs( radio_button_names ) do radio_params.buttonPressMode = "SHORT" radio_params.buttonName = button_name_value runner.Title("Test - ButtonPress with buttonName " .. button_name_value) runner.Step("ButtonPress_RADIO_" .. button_name_value .. "_SHORT", SendButtonPressPositive, {radio_params}) radio_params.buttonPressMode = "LONG" runner.Step("ButtonPress_RADIO_" .. button_name_value .. "_LONG", SendButtonPressPositive, {radio_params}) end --[[ Negative Scenario - invalid value of buttonName in mobile request]] climate_params = reset_climate_params() radio_params = reset_radio_params() climate_params.buttonName = "invalid_name" radio_params.buttonName = "invalid_name" runner.Title("Test - negative, invalid value of buttonName in mobile request") runner.Step("ButtonPress_CLIMATE", SendButtonPressNegative, {climate_params}) runner.Step("ButtonPress_RADIO", SendButtonPressNegative, {radio_params}) climate_params = reset_climate_params() radio_params = reset_radio_params() --[[ Negative Scenario - invalid value of buttonPressMode in mobile request]] climate_params.buttonPressMode = "invalid_name" radio_params.buttonPressMode = "invalid_name" runner.Title("Test - negative, invalid value of buttonPressMode in mobile request") runner.Step("ButtonPress_CLIMATE", SendButtonPressNegative, {climate_params}) runner.Step("ButtonPress_RADIO", SendButtonPressNegative, {radio_params}) climate_params = reset_climate_params() radio_params = reset_radio_params() --[[ Negative Scenario - not matched params in mobile request]] climate_params.buttonName = "VOLUME_UP" radio_params.buttonName = "AC" runner.Title("Test - negative, not matched params in mobile request") runner.Step("ButtonPress_CLIMATE", SendButtonPressNegative, {climate_params}) runner.Step("ButtonPress_RADIO", SendButtonPressNegative, {radio_params}) runner.Title("Postconditions") runner.Step("Stop SDL", commonRC.postconditions)
--------------------------------------------------------------------------------------------------- -- RPC: ButtonPress -- Script: 005 --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local commonRC = require('test_scripts/RC/commonRC') local runner = require('user_modules/script_runner') local commonTestCases = require('user_modules/shared_testcases/commonTestCases') --[[ Local variables for tests ]] local climate_button_names = { "AC_MAX", "AC", "RECIRCULATE", "FAN_UP", "FAN_DOWN", "TEMP_UP", "TEMP_DOWN", "DEFROST_MAX", "DEFROST", "DEFROST_REAR", "UPPER_VENT", "LOWER_VENT" } local radio_button_names = { "VOLUME_UP", "VOLUME_DOWN", "EJECT", "SOURCE", "SHUFFLE", "REPEAT", } --[[ Local Functions ]] local function reset_climate_params() return {moduleType = "CLIMATE", buttonName = "AC", buttonPressMode = "SHORT"} end local function reset_radio_params() return {moduleType = "RADIO", buttonName = "VOLUME_UP", buttonPressMode = "SHORT"} end local function SendButtonPressPositive(button_press_params, self) local cid = self.mobileSession:SendRPC("ButtonPress", button_press_params) EXPECT_HMICALL("Buttons.ButtonPress", { appID = self.applications["Test Application"], moduleType = button_press_params.moduleType, buttonName = button_press_params.buttonName, buttonPressMode = button_press_params.buttonPressMode }) :Times(1) :Do(function(_, data) self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {}) end) EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS" }) end local function SendButtonPressNegative(button_press_params, self) local cid = self.mobileSession:SendRPC("ButtonPress", button_press_params) EXPECT_HMICALL("Buttons.ButtonPress") :Times(0) EXPECT_RESPONSE(cid, { success = false, resultCode = "INVALID_DATA" }) commonTestCases:DelayedExp(commonRC.timeout) end --[[ Positive Scenario - check all positive climate names params]] local climate_params = reset_climate_params() runner.Title("Preconditions") runner.Step("Clean environment", commonRC.preconditions) runner.Step("Start SDL, HMI, connect Mobile, start Session", commonRC.start) runner.Step("RAI, PTU", commonRC.rai_ptu) for _, button_name_value in pairs( climate_button_names ) do climate_params.buttonPressMode = "SHORT" climate_params.buttonName = button_name_value runner.Title("Test - ButtonPress with buttonName " .. button_name_value) runner.Step("ButtonPress_CLIMATE_" .. button_name_value .. "_SHORT", SendButtonPressPositive, {climate_params}) climate_params.buttonPressMode = "LONG" runner.Step("ButtonPress_CLIMATE_" .. button_name_value .. "_LONG", SendButtonPressPositive, {climate_params}) end --[[ Positive Scenario - check all positive radio names params]] local radio_params = reset_radio_params() for _, button_name_value in pairs( radio_button_names ) do radio_params.buttonPressMode = "SHORT" radio_params.buttonName = button_name_value runner.Title("Test - ButtonPress with buttonName " .. button_name_value) runner.Step("ButtonPress_RADIO_" .. button_name_value .. "_SHORT", SendButtonPressPositive, {radio_params}) radio_params.buttonPressMode = "LONG" runner.Step("ButtonPress_RADIO_" .. button_name_value .. "_LONG", SendButtonPressPositive, {radio_params}) end --[[ Negative Scenario - invalid value of buttonName in mobile request]] climate_params = reset_climate_params() radio_params = reset_radio_params() climate_params.buttonName = "invalid_name" radio_params.buttonName = "invalid_name" runner.Title("Test - negative, invalid value of buttonName in mobile request") runner.Step("ButtonPress_CLIMATE", SendButtonPressNegative, {climate_params}) runner.Step("ButtonPress_RADIO", SendButtonPressNegative, {radio_params}) climate_params = reset_climate_params() radio_params = reset_radio_params() --[[ Negative Scenario - invalid value of buttonPressMode in mobile request]] climate_params.buttonPressMode = "invalid_name" radio_params.buttonPressMode = "invalid_name" runner.Title("Test - negative, invalid value of buttonPressMode in mobile request") runner.Step("ButtonPress_CLIMATE", SendButtonPressNegative, {climate_params}) runner.Step("ButtonPress_RADIO", SendButtonPressNegative, {radio_params}) climate_params = reset_climate_params() radio_params = reset_radio_params() --[[ Negative Scenario - not matched params in mobile request]] climate_params.buttonName = "VOLUME_UP" radio_params.buttonName = "AC" runner.Title("Test - negative, not matched params in mobile request") runner.Step("ButtonPress_CLIMATE", SendButtonPressNegative, {climate_params}) runner.Step("ButtonPress_RADIO", SendButtonPressNegative, {radio_params}) runner.Title("Postconditions") runner.Step("Stop SDL", commonRC.postconditions)
fix issues according to pull request comments
fix issues according to pull request comments
Lua
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
d53f0daa86d210e2e60b4ac8c68e8b4fb18b3a66
nvim/nvim/lua/_/completion.lua
nvim/nvim/lua/_/completion.lua
local has_cmp, cmp = pcall(require, 'cmp') local has_lspkind, lspkind = pcall(require, 'lspkind') local utils = require '_.utils' local M = {} local check_back_space = function() local col = vim.fn.col('.') - 1 if col == 0 or vim.fn.getline('.'):sub(col, col):match('%s') then return true else return false end end -- Use (s-)tab to: --- move to prev/next item in completion menuone --- jump to prev/next snippet's placeholder _G._.tab_complete = function() if vim.fn.pumvisible() == 1 then return utils.t '<C-n>' elseif vim.fn.call('vsnip#available', {1}) == 1 then return utils.t '<Plug>(vsnip-expand-or-jump)' elseif check_back_space() then return utils.t '<Tab>' else return vim.fn['compe#complete']() end end _G._.s_tab_complete = function() if vim.fn.pumvisible() == 1 then return utils.t '<C-p>' elseif vim.fn.call('vsnip#jumpable', {-1}) == 1 then return utils.t '<Plug>(vsnip-jump-prev)' else return utils.t '<S-Tab>' end end local format = {} if has_lspkind then format = lspkind.cmp_format({ mode='symbol', -- show only symbol annotations maxwidth=50 -- prevent the popup from showing more than provided characters (e.g 50 will not show more than 50 characters) }) end M.setup = function() if has_cmp then cmp.setup({ formatting={format=format}, snippet={ -- REQUIRED - you must specify a snippet engine expand=function(args) vim.fn['vsnip#anonymous'](args.body) -- For `vsnip` users. end }, mapping={ ['<C-b>']=cmp.mapping(cmp.mapping.scroll_docs(-4), {'i', 'c'}), ['<C-f>']=cmp.mapping(cmp.mapping.scroll_docs(4), {'i', 'c'}), ['<C-Space>']=cmp.mapping(cmp.mapping.complete(), {'i', 'c'}), ['<C-y>']=cmp.config.disable, -- Specify `cmp.config.disable` if you want to remove the default `<C-y>` mapping. ['<C-e>']=cmp.mapping({i=cmp.mapping.abort(), c=cmp.mapping.close()}), ['<CR>']=cmp.mapping.confirm({select=true}) }, sources=cmp.config.sources({ {name='nvim_lsp'}, {name='vsnip'}, {name='tmux'}, {name='path'} }, {{name='buffer'}}) }) -- Use buffer source for `/` (if you enabled `native_menu`, this won't work anymore). cmp.setup.cmdline('/', {sources={{name='buffer'}}}) -- Use cmdline & path source for ':' (if you enabled `native_menu`, this won't work anymore). cmp.setup.cmdline(':', { sources=cmp.config.sources({{name='path'}}, {{name='cmdline'}}) }) end end return M
local has_cmp, cmp = pcall(require, 'cmp') local has_lspkind, lspkind = pcall(require, 'lspkind') local utils = require '_.utils' local M = {} local check_back_space = function() local col = vim.fn.col('.') - 1 if col == 0 or vim.fn.getline('.'):sub(col, col):match('%s') then return true else return false end end -- Use (s-)tab to: --- move to prev/next item in completion menuone --- jump to prev/next snippet's placeholder _G._.tab_complete = function() if vim.fn.pumvisible() == 1 then return utils.t '<C-n>' elseif vim.fn.call('vsnip#available', {1}) == 1 then return utils.t '<Plug>(vsnip-expand-or-jump)' elseif check_back_space() then return utils.t '<Tab>' else return vim.fn['compe#complete']() end end _G._.s_tab_complete = function() if vim.fn.pumvisible() == 1 then return utils.t '<C-p>' elseif vim.fn.call('vsnip#jumpable', {-1}) == 1 then return utils.t '<Plug>(vsnip-jump-prev)' else return utils.t '<S-Tab>' end end local format = {} if has_lspkind then format = lspkind.cmp_format({ mode='symbol', -- show only symbol annotations maxwidth=50 -- prevent the popup from showing more than provided characters (e.g 50 will not show more than 50 characters) }) end M.setup = function() if has_cmp then cmp.setup({ formatting={format=format}, snippet={ -- REQUIRED - you must specify a snippet engine expand=function(args) vim.fn['vsnip#anonymous'](args.body) -- For `vsnip` users. end }, window={ -- completion = cmp.config.window.bordered(), -- documentation = cmp.config.window.bordered(), }, mapping=cmp.mapping.preset.insert({ ['<C-b>']=cmp.mapping.scroll_docs(-4), ['<C-f>']=cmp.mapping.scroll_docs(4), ['<C-Space>']=cmp.mapping.complete(), ['<C-e>']=cmp.mapping.abort(), ['<CR>']=cmp.mapping.confirm({select=true}) -- Accept currently selected item. Set `select` to `false` to only confirm explicitly selected items. }), sources=cmp.config.sources({ {name='nvim_lsp'}, {name='vsnip'}, {name='tmux'}, {name='path'} }, {{name='buffer'}}) }) -- Set configuration for specific filetype. cmp.setup.filetype('gitcommit', { sources=cmp.config.sources({ {name='cmp_git'} -- You can specify the `cmp_git` source if you were installed it. }, {{name='buffer'}}) }) -- Use buffer source for `/` (if you enabled `native_menu`, this won't work anymore). cmp.setup.cmdline('/', { mapping=cmp.mapping.preset.cmdline(), sources={{name='buffer'}} }) -- Use cmdline & path source for ':' (if you enabled `native_menu`, this won't work anymore). cmp.setup.cmdline(':', { mapping=cmp.mapping.preset.cmdline(), sources=cmp.config.sources({{name='path'}}, {{name='cmdline'}}) }) end end return M
fix(nvim): completion of nvim-cmp
fix(nvim): completion of nvim-cmp
Lua
mit
skyuplam/dotfiles,skyuplam/dotfiles
95b15ae1bb5546be54bd94e563a404d89e36e110
lib/switchboard_modules/lua_script_debugger/premade_scripts/digital_io_ef/PWM_Library.lua
lib/switchboard_modules/lua_script_debugger/premade_scripts/digital_io_ef/PWM_Library.lua
--This script can be used as a library of functions to configure the PWM registers for output and write new duty cycles to the PWM channel. --PWM is available on the T7 on FIO0-FIO5 (T4 PWM is on FIO6 & FIO7) --See the device datasheet for more information on PWM output. --Functions to configure T7/T4 outPin = 0--FIO0. Changed if T4 instead of T7 -- devType = MB.R(60000, 3) -- if devType == 4 then -- outPin = 6--FIO6 on T4 -- end -- Create PWM library. PWM = {}--add local variables here function PWM.init (self, ichan, ifreq, iduty, iclk, idivisor)--duty should be in %, not decimal irollValue = (80000000/ifreq)/idivisor self.rollValue = irollValue--store local values for future use vvvv self.chan = ichan self.freq = ifreq self.duty = iduty self.clk = iclk self.divisor = idivisor--store local values for future use ^^^^ MB.W(44900+iclk*10, 0, 0)--Disable clock source --Set Clock# divisor and roll value to configure frequency MB.W(44901+iclk*10, 0, idivisor)--Configure Clock# divisor MB.W(44904+iclk*10, 1, irollValue)--Configure Clock# roll value MB.W(44900+iclk*10, 0, 1)--enable clock source --Configure EF Channel Registers: MB.W(44000+ichan*2, 1, 0)--Disable the EF system for initial configuration MB.W(44100+ichan*2, 1, 0)--Configure EF system for PWM MB.W(44200+ichan*2, 1, iclk)--Configure what clock source to use: Clock# MB.W(44300+ichan*2, 1, irollValue*iduty/100)--Configure duty cycle end function PWM.enable (self) MB.W(44000+self.chan*2, 1, 1)--enable the EF system end function PWM.disable (self) MB.W(44000+self.chan*2, 1, 0)--disable the EF system end function PWM.changeFreq (self, ifreq) irollValue = (80000000/ifreq)/self.divisor self.rollValue = irollValue--store local values for future use self.freq = ifreq MB.W(44904+self.clk*10, 1, self.rollValue)--Configure Clock# roll value MB.W(44300+self.chan*2, 1, self.rollValue*self.duty/100)--reconfigure duty cycle end function PWM.changeDutyCycle (self, iduty) self.duty = iduty--re-store local value MB.W(44300+self.chan*2, 1, self.rollValue*self.duty/100)--Configure duty cycle end myPWM = PWM myPWM.init(myPWM, 0, 50, 5, 0, 1)--init on outPin with 50Hz (20ms) and 5% duty cycle myPWM.enable(myPWM) LJ.IntervalConfig(1, 1000) while true do --you can test the function an using an LED or an oscilloscope on the FIO pin if LJ.CheckInterval(1) then newDC = MB.R(46000, 3) newFreq = MB.R(46002, 3) if myPWM.duty ~= newDC then myPWM.changeDutyCycle(myPWM, newDC) end if (myPWM.freq ~= newFreq and newFreq ~= 0) then myPWM.changeFreq(myPWM, newFreq) end print("On FIO0 a ", myPWM.freq, "Hz signal at a ", myPWM.duty, "% duty cycle has been generated")--print out what is being generated end end
--This script can be used as a library of functions to configure the PWM registers for output and write new duty cycles to the PWM channel. --PWM is available on the T7 on FIO0-FIO5 (T4 PWM is on FIO6 & FIO7) --See the device datasheet for more information on PWM output. -- Details about compatible DIO channels (tables 13.2-1 and -2): https://labjack.com/support/datasheets/t-series/digital-io/extended-features -- PWM specific details: https://labjack.com/support/datasheets/t-series/digital-io/extended-features/pwm-out --Functions to configure T7/T4 outPin = 0--FIO0. Changed if T4 instead of T7 pwmFrequency = 50 -- 50 Hz pwmDutyCycle = 5 -- 5% -- devType = MB.R(60000, 3) -- if devType == 4 then -- outPin = 6--FIO6 on T4 -- end -- Create PWM library. PWM = {}--add local variables here function PWM.init (self, ichan, ifreq, iduty, iclk, idivisor)--duty should be in %, not decimal irollValue = (80000000/ifreq)/idivisor self.rollValue = irollValue--store local values for future use vvvv self.chan = ichan self.freq = ifreq self.duty = iduty self.clk = iclk self.divisor = idivisor--store local values for future use ^^^^ MB.W(44900+iclk*10, 0, 0)--Disable clock source --Set Clock# divisor and roll value to configure frequency MB.W(44901+iclk*10, 0, idivisor)--Configure Clock# divisor MB.W(44904+iclk*10, 1, irollValue)--Configure Clock# roll value MB.W(44900+iclk*10, 0, 1)--enable clock source --Configure EF Channel Registers: MB.W(44000+ichan*2, 1, 0)--Disable the EF system for initial configuration MB.W(44100+ichan*2, 1, 0)--Configure EF system for PWM MB.W(44200+ichan*2, 1, iclk)--Configure what clock source to use: Clock# MB.W(44300+ichan*2, 1, irollValue*iduty/100)--Configure duty cycle end function PWM.enable (self) MB.W(44000+self.chan*2, 1, 1)--enable the EF system end function PWM.disable (self) MB.W(44000+self.chan*2, 1, 0)--disable the EF system end function PWM.changeFreq (self, ifreq) irollValue = (80000000/ifreq)/self.divisor self.rollValue = irollValue--store local values for future use self.freq = ifreq MB.W(44904+self.clk*10, 1, self.rollValue)--Configure Clock# roll value MB.W(44300+self.chan*2, 1, self.rollValue*self.duty/100)--reconfigure duty cycle end function PWM.changeDutyCycle (self, iduty) self.duty = iduty--re-store local value MB.W(44300+self.chan*2, 1, self.rollValue*self.duty/100)--Configure duty cycle end myPWM = PWM myPWM.init(myPWM, 0, pwmFrequency, pwmDutyCycle, 0, 1)--init on outPin with 50Hz (20ms) and 50% duty cycle myPWM.enable(myPWM) -- Initialize the user RAM registers 46000 and 46002 registers. MB.W(46002, 3, pwmFrequency) MB.W(46000, 3, pwmDutyCycle) LJ.IntervalConfig(1, 1000) while true do --you can test the function an using an LED or an oscilloscope on the FIO pin if LJ.CheckInterval(1) then newDC = MB.R(46000, 3) newFreq = MB.R(46002, 3) if myPWM.duty ~= newDC then myPWM.changeDutyCycle(myPWM, newDC) end if (myPWM.freq ~= newFreq and newFreq ~= 0) then myPWM.changeFreq(myPWM, newFreq) end print("On FIO0 a ", myPWM.freq, "Hz signal at a ", myPWM.duty, "% duty cycle has been generated")--print out what is being generated end end
Update PWM_Library.lua
Update PWM_Library.lua Fixed issue where duty cycle was immediately set to 0% after initializing. Added additional comments about T-Series PWM features.
Lua
mit
chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager
f4e34264f309cbb67099febffe45734e6d2c77aa
src/module/settings.lua
src/module/settings.lua
-- This module adds a settings API. local obj = {} obj._init = function() -- Define global cfg object cfg = {} cfg.data = {} cfg.file = 'settings.json' obj.load() end obj._configuration_fields = function() return { sta_ssid = {}, sta_psk = {}, ap_psk = { default = 'ESP-8266' }, ws_port = { type = 'number', min = '1', max = '65535', default = 80 }, cfg_pin = { type = 'number', default = 4 }, mqtt_user = { default = 'user' }, mqtt_password = { default = 'password' }, mqtt_host = { default = 'mqtt.local' }, mqtt_port = { type = 'number', min = '1', max = '65535', default = 1337 }, mqtt_secure = { type = 'boolean', default = false }, sleep = { type = 'boolean', default = false }, report_interval = { type = 'number', min = '30', max = '604800', default = 60 } } end -- Load cfg fields from modules obj.fields = function() local gathered = triggerModules('_configuration_fields') local merged = tablesMerge(gathered) local gathered = nil collectgarbage() return merged end -- Load cfg obj.load = function() if file.open(cfg.file, "r") then local json = require "cjson" local content = file.read() if content ~= nil and content ~= "null" then cfg.data = json.decode(content) end file.close() end -- Populate empty fields with default data local fields = obj.fields() for k, v in pairs(fields) do if cfg.data[k] == nil then cfg.data[k] = v.default end end fields = nil json = nil content = nil collectgarbage() end obj.save = function() local json = require "cjson" file.open(cfg.file, "w+") local content = json.encode(cfg.data) file.write(content) file.close() collectgarbage() end return function(fnc, args) if obj[fnc] then return obj[fnc](args) end end
-- This module adds a settings API. local obj = {} obj._init = function() -- Define global cfg object cfg = {} cfg.data = {} cfg.file = 'settings.json' obj.load() end obj._configuration_fields = function() return { sta_ssid = { type = 'text', default = '' }, sta_psk = { type = 'text', default = '' }, ap_psk = { type = 'text', default = 'ESP-8266' }, ws_port = { type = 'number', min = '1', max = '65535', default = 80 }, cfg_pin = { type = 'number', default = 4 }, mqtt_user = { type = 'text', default = 'user' }, mqtt_password = { type = 'text', default = 'password' }, mqtt_host = { type = 'text', default = 'mqtt.local' }, mqtt_port = { type = 'number', min = '1', max = '65535', default = 1337 }, mqtt_secure = { type = 'boolean', default = false }, sleep = { type = 'boolean', default = false }, report_interval = { type = 'number', min = '30', max = '604800', default = 60 } } end -- Load cfg fields from modules obj.fields = function() local gathered = triggerModules('_configuration_fields') local merged = tablesMerge(gathered) local gathered = nil collectgarbage() return merged end -- Load cfg obj.load = function() if file.open(cfg.file, "r") then local json = require "cjson" local content = file.read() if content ~= nil and content ~= "null" then cfg.data = json.decode(content) end file.close() end -- Populate empty fields with default data local fields = obj.fields() for k, v in pairs(fields) do if cfg.data[k] == nil then cfg.data[k] = v.default end end fields = nil json = nil content = nil collectgarbage() end obj.save = function() local json = require "cjson" file.open(cfg.file, "w+") local content = json.encode(cfg.data) file.write(content) file.close() collectgarbage() end return function(fnc, args) if obj[fnc] then return obj[fnc](args) end end
bugfixes
bugfixes Signed-off-by: Kalman Olah <[email protected]>
Lua
mit
kalmanolah/kalmon-ESP8266
6c0489b5f3f7161d1c9a7e535d2f892a2a533ad3
mods/BeardLib-Editor/Classes/Map/Elements/filterelement.lua
mods/BeardLib-Editor/Classes/Map/Elements/filterelement.lua
EditorFilter = EditorFilter or class(MissionScriptEditor) function EditorFilter:create_element() self.super.create_element(self) self._element.class = "ElementFilter" self._element.values.difficulty_easy = true self._element.values.difficulty_normal = true self._element.values.difficulty_hard = true self._element.values.difficulty_overkill = true self._element.values.difficulty_overkill_145 = true self._element.values.difficulty_easy_wish = nil self._element.values.difficulty_overkill_290 = nil self._element.values.difficulty_sm_wish = nil self._element.values.player_1 = true self._element.values.player_2 = true self._element.values.player_3 = true self._element.values.player_4 = true self._element.values.platform_win32 = true self._element.values.mode_assault = true self._element.values.mode_control = true end function EditorFilter:_build_panel() if self._element.values.difficulty_overkill_290 == nil then self._element.values.difficulty_overkill_290 = self._element.values.difficulty_overkill_145 end self:_create_panel() self:Text("Difficulty") self:BooleanCtrl("difficulty_easy", {text = "Easy"}) self:BooleanCtrl("difficulty_normal", {text = "Normal"}) self:BooleanCtrl("difficulty_hard", {text = "Hard"}) self:BooleanCtrl("difficulty_overkill", {text = "Very Hard"}) self:BooleanCtrl("difficulty_overkill_145", {text = "Overkill"}) self:BooleanCtrl("difficulty_easy_wish", {text = "Mayhem"}) self:BooleanCtrl("difficulty_overkill_290", {text = "Death Wish"}) self:BooleanCtrl("difficulty_sm_wish", {text = "One Down"}) self:Text("Players") self:BooleanCtrl("player_1", {text = "One Player"}) self:BooleanCtrl("player_2", {text = "Two Players"}) self:BooleanCtrl("player_3", {text = "Three Players"}) self:BooleanCtrl("player_4", {text = "Four Players"}) self:Text("Mode") self:BooleanCtrl("mode_control", {text = "Control"}) self:BooleanCtrl("mode_assault", {text = "Assault"}) end
EditorFilter = EditorFilter or class(MissionScriptEditor) function EditorFilter:create_element() self.super.create_element(self) self._element.class = "ElementFilter" self._element.values.difficulty_easy = true self._element.values.difficulty_normal = true self._element.values.difficulty_hard = true self._element.values.difficulty_overkill = true self._element.values.difficulty_overkill_145 = true self._element.values.difficulty_easy_wish = true self._element.values.difficulty_overkill_290 = true self._element.values.difficulty_sm_wish = true self._element.values.player_1 = true self._element.values.player_2 = true self._element.values.player_3 = true self._element.values.player_4 = true self._element.values.platform_win32 = true self._element.values.mode_assault = true self._element.values.mode_control = true end function EditorFilter:_build_panel() self:_create_panel() self:Text("Difficulty") self:BooleanCtrl("difficulty_easy", {text = "Easy"}) self:BooleanCtrl("difficulty_normal", {text = "Normal"}) self:BooleanCtrl("difficulty_hard", {text = "Hard"}) self:BooleanCtrl("difficulty_overkill", {text = "Very Hard"}) self:BooleanCtrl("difficulty_overkill_145", {text = "Overkill"}) self:BooleanCtrl("difficulty_easy_wish", {text = "Mayhem"}) self:BooleanCtrl("difficulty_overkill_290", {text = "Death Wish"}) self:BooleanCtrl("difficulty_sm_wish", {text = "One Down"}) self:Text("Players") self:BooleanCtrl("player_1", {text = "One Player"}) self:BooleanCtrl("player_2", {text = "Two Players"}) self:BooleanCtrl("player_3", {text = "Three Players"}) self:BooleanCtrl("player_4", {text = "Four Players"}) self:Text("Mode") self:BooleanCtrl("mode_control", {text = "Control"}) self:BooleanCtrl("mode_assault", {text = "Assault"}) end
Fixed filter element
Fixed filter element Added the missing true values on the new difficulties. Removed unused code : if self._element.values.difficulty_overkill_290 == nil then self._element.values.difficulty_overkill_290 = self._element.values.difficulty_overkill_145 end
Lua
mit
simon-wh/PAYDAY-2-BeardLib-Editor
525da459d78596cfc8dce9ed2fc690fb395b5a55
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 <[email protected]> Copyright 2011 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- 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 <[email protected]> Copyright 2011 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- 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
Lua
apache-2.0
palmettos/test,palmettos/test,tcatm/luci,NeoRaider/luci,cappiewu/luci,bright-things/ionic-luci,Wedmer/luci,deepak78/new-luci,wongsyrone/luci-1,Hostle/luci,deepak78/new-luci,slayerrensky/luci,zhaoxx063/luci,shangjiyu/luci-with-extra,ollie27/openwrt_luci,maxrio/luci981213,ff94315/luci-1,harveyhu2012/luci,hnyman/luci,lcf258/openwrtcn,jorgifumi/luci,obsy/luci,zhaoxx063/luci,harveyhu2012/luci,deepak78/new-luci,Sakura-Winkey/LuCI,artynet/luci,ReclaimYourPrivacy/cloak-luci,Wedmer/luci,cappiewu/luci,db260179/openwrt-bpi-r1-luci,taiha/luci,Sakura-Winkey/LuCI,teslamint/luci,MinFu/luci,cshore/luci,oneru/luci,jchuang1977/luci-1,ollie27/openwrt_luci,remakeelectric/luci,marcel-sch/luci,opentechinstitute/luci,keyidadi/luci,nwf/openwrt-luci,rogerpueyo/luci,aa65535/luci,mumuqz/luci,MinFu/luci,lcf258/openwrtcn,dwmw2/luci,RuiChen1113/luci,cshore/luci,Sakura-Winkey/LuCI,marcel-sch/luci,tobiaswaldvogel/luci,tcatm/luci,thess/OpenWrt-luci,Sakura-Winkey/LuCI,981213/luci-1,male-puppies/luci,urueedi/luci,zhaoxx063/luci,forward619/luci,oneru/luci,male-puppies/luci,chris5560/openwrt-luci,openwrt/luci,forward619/luci,lbthomsen/openwrt-luci,thess/OpenWrt-luci,dismantl/luci-0.12,LazyZhu/openwrt-luci-trunk-mod,mumuqz/luci,mumuqz/luci,jlopenwrtluci/luci,taiha/luci,Kyklas/luci-proto-hso,thesabbir/luci,obsy/luci,LazyZhu/openwrt-luci-trunk-mod,lcf258/openwrtcn,ff94315/luci-1,nwf/openwrt-luci,Sakura-Winkey/LuCI,opentechinstitute/luci,palmettos/cnLuCI,slayerrensky/luci,sujeet14108/luci,obsy/luci,LazyZhu/openwrt-luci-trunk-mod,kuoruan/luci,harveyhu2012/luci,thesabbir/luci,dwmw2/luci,cshore/luci,deepak78/new-luci,hnyman/luci,cshore-firmware/openwrt-luci,palmettos/test,hnyman/luci,tcatm/luci,opentechinstitute/luci,tobiaswaldvogel/luci,bright-things/ionic-luci,RuiChen1113/luci,Kyklas/luci-proto-hso,daofeng2015/luci,RuiChen1113/luci,jorgifumi/luci,openwrt-es/openwrt-luci,david-xiao/luci,bright-things/ionic-luci,lcf258/openwrtcn,Hostle/luci,dwmw2/luci,NeoRaider/luci,openwrt/luci,rogerpueyo/luci,bittorf/luci,wongsyrone/luci-1,jorgifumi/luci,mumuqz/luci,openwrt-es/openwrt-luci,lcf258/openwrtcn,RuiChen1113/luci,thesabbir/luci,jlopenwrtluci/luci,nmav/luci,palmettos/test,dismantl/luci-0.12,joaofvieira/luci,ollie27/openwrt_luci,taiha/luci,oneru/luci,nmav/luci,bittorf/luci,dismantl/luci-0.12,remakeelectric/luci,jorgifumi/luci,Hostle/luci,dwmw2/luci,florian-shellfire/luci,kuoruan/lede-luci,bright-things/ionic-luci,thesabbir/luci,daofeng2015/luci,jlopenwrtluci/luci,tcatm/luci,Noltari/luci,remakeelectric/luci,nwf/openwrt-luci,rogerpueyo/luci,bittorf/luci,mumuqz/luci,kuoruan/lede-luci,LazyZhu/openwrt-luci-trunk-mod,slayerrensky/luci,jchuang1977/luci-1,oneru/luci,maxrio/luci981213,deepak78/new-luci,aa65535/luci,obsy/luci,ollie27/openwrt_luci,wongsyrone/luci-1,hnyman/luci,dwmw2/luci,LazyZhu/openwrt-luci-trunk-mod,urueedi/luci,Hostle/openwrt-luci-multi-user,Noltari/luci,joaofvieira/luci,maxrio/luci981213,taiha/luci,aircross/OpenWrt-Firefly-LuCI,ff94315/luci-1,dismantl/luci-0.12,Sakura-Winkey/LuCI,wongsyrone/luci-1,oneru/luci,hnyman/luci,thesabbir/luci,chris5560/openwrt-luci,kuoruan/lede-luci,wongsyrone/luci-1,urueedi/luci,ff94315/luci-1,david-xiao/luci,RedSnake64/openwrt-luci-packages,openwrt-es/openwrt-luci,jlopenwrtluci/luci,artynet/luci,aa65535/luci,nwf/openwrt-luci,zhaoxx063/luci,schidler/ionic-luci,ReclaimYourPrivacy/cloak-luci,thess/OpenWrt-luci,slayerrensky/luci,tobiaswaldvogel/luci,artynet/luci,joaofvieira/luci,urueedi/luci,fkooman/luci,shangjiyu/luci-with-extra,florian-shellfire/luci,harveyhu2012/luci,zhaoxx063/luci,LuttyYang/luci,florian-shellfire/luci,981213/luci-1,florian-shellfire/luci,bright-things/ionic-luci,RedSnake64/openwrt-luci-packages,Hostle/openwrt-luci-multi-user,openwrt-es/openwrt-luci,artynet/luci,Wedmer/luci,jlopenwrtluci/luci,cshore/luci,Hostle/luci,Hostle/openwrt-luci-multi-user,artynet/luci,bittorf/luci,maxrio/luci981213,jorgifumi/luci,aircross/OpenWrt-Firefly-LuCI,nmav/luci,kuoruan/luci,opentechinstitute/luci,jchuang1977/luci-1,cshore-firmware/openwrt-luci,lbthomsen/openwrt-luci,marcel-sch/luci,MinFu/luci,ff94315/luci-1,kuoruan/luci,sujeet14108/luci,jlopenwrtluci/luci,aircross/OpenWrt-Firefly-LuCI,joaofvieira/luci,daofeng2015/luci,forward619/luci,artynet/luci,deepak78/new-luci,slayerrensky/luci,RedSnake64/openwrt-luci-packages,RuiChen1113/luci,fkooman/luci,nmav/luci,Hostle/openwrt-luci-multi-user,MinFu/luci,shangjiyu/luci-with-extra,daofeng2015/luci,Wedmer/luci,obsy/luci,tcatm/luci,cshore/luci,aa65535/luci,teslamint/luci,forward619/luci,LuttyYang/luci,NeoRaider/luci,bright-things/ionic-luci,thess/OpenWrt-luci,urueedi/luci,981213/luci-1,Wedmer/luci,wongsyrone/luci-1,Hostle/luci,mumuqz/luci,lcf258/openwrtcn,Hostle/openwrt-luci-multi-user,jorgifumi/luci,aircross/OpenWrt-Firefly-LuCI,Wedmer/luci,artynet/luci,LazyZhu/openwrt-luci-trunk-mod,RedSnake64/openwrt-luci-packages,slayerrensky/luci,kuoruan/luci,daofeng2015/luci,obsy/luci,openwrt/luci,chris5560/openwrt-luci,dwmw2/luci,florian-shellfire/luci,florian-shellfire/luci,db260179/openwrt-bpi-r1-luci,chris5560/openwrt-luci,shangjiyu/luci-with-extra,remakeelectric/luci,Kyklas/luci-proto-hso,Hostle/openwrt-luci-multi-user,fkooman/luci,openwrt-es/openwrt-luci,opentechinstitute/luci,wongsyrone/luci-1,teslamint/luci,david-xiao/luci,shangjiyu/luci-with-extra,cshore-firmware/openwrt-luci,thess/OpenWrt-luci,ff94315/luci-1,openwrt/luci,ollie27/openwrt_luci,cshore/luci,sujeet14108/luci,LuttyYang/luci,NeoRaider/luci,schidler/ionic-luci,palmettos/cnLuCI,remakeelectric/luci,lbthomsen/openwrt-luci,rogerpueyo/luci,oneru/luci,LuttyYang/luci,aircross/OpenWrt-Firefly-LuCI,chris5560/openwrt-luci,nwf/openwrt-luci,florian-shellfire/luci,cappiewu/luci,jorgifumi/luci,deepak78/new-luci,forward619/luci,teslamint/luci,Hostle/openwrt-luci-multi-user,cshore/luci,ReclaimYourPrivacy/cloak-luci,aa65535/luci,jchuang1977/luci-1,ollie27/openwrt_luci,palmettos/test,bright-things/ionic-luci,joaofvieira/luci,NeoRaider/luci,david-xiao/luci,urueedi/luci,lbthomsen/openwrt-luci,openwrt/luci,zhaoxx063/luci,forward619/luci,nwf/openwrt-luci,male-puppies/luci,david-xiao/luci,MinFu/luci,LuttyYang/luci,cappiewu/luci,david-xiao/luci,chris5560/openwrt-luci,dismantl/luci-0.12,db260179/openwrt-bpi-r1-luci,bittorf/luci,florian-shellfire/luci,deepak78/new-luci,marcel-sch/luci,taiha/luci,schidler/ionic-luci,obsy/luci,cappiewu/luci,remakeelectric/luci,palmettos/cnLuCI,aa65535/luci,cshore-firmware/openwrt-luci,lbthomsen/openwrt-luci,thess/OpenWrt-luci,sujeet14108/luci,Kyklas/luci-proto-hso,ReclaimYourPrivacy/cloak-luci,fkooman/luci,teslamint/luci,cshore-firmware/openwrt-luci,nmav/luci,981213/luci-1,ReclaimYourPrivacy/cloak-luci,male-puppies/luci,nmav/luci,RedSnake64/openwrt-luci-packages,ff94315/luci-1,openwrt-es/openwrt-luci,rogerpueyo/luci,oyido/luci,rogerpueyo/luci,palmettos/cnLuCI,opentechinstitute/luci,Noltari/luci,chris5560/openwrt-luci,schidler/ionic-luci,sujeet14108/luci,shangjiyu/luci-with-extra,palmettos/test,palmettos/cnLuCI,cshore-firmware/openwrt-luci,sujeet14108/luci,daofeng2015/luci,oyido/luci,dismantl/luci-0.12,cappiewu/luci,forward619/luci,harveyhu2012/luci,lcf258/openwrtcn,jchuang1977/luci-1,lcf258/openwrtcn,maxrio/luci981213,LazyZhu/openwrt-luci-trunk-mod,aircross/OpenWrt-Firefly-LuCI,tobiaswaldvogel/luci,jchuang1977/luci-1,openwrt-es/openwrt-luci,oyido/luci,RuiChen1113/luci,urueedi/luci,oneru/luci,Hostle/luci,schidler/ionic-luci,slayerrensky/luci,oneru/luci,bittorf/luci,tobiaswaldvogel/luci,shangjiyu/luci-with-extra,981213/luci-1,male-puppies/luci,marcel-sch/luci,kuoruan/lede-luci,openwrt/luci,nmav/luci,keyidadi/luci,palmettos/cnLuCI,mumuqz/luci,jlopenwrtluci/luci,oyido/luci,kuoruan/luci,lcf258/openwrtcn,tcatm/luci,harveyhu2012/luci,wongsyrone/luci-1,schidler/ionic-luci,teslamint/luci,lbthomsen/openwrt-luci,ReclaimYourPrivacy/cloak-luci,rogerpueyo/luci,slayerrensky/luci,dwmw2/luci,obsy/luci,ReclaimYourPrivacy/cloak-luci,Kyklas/luci-proto-hso,joaofvieira/luci,palmettos/cnLuCI,nmav/luci,openwrt/luci,bright-things/ionic-luci,db260179/openwrt-bpi-r1-luci,aircross/OpenWrt-Firefly-LuCI,jchuang1977/luci-1,oyido/luci,Hostle/luci,palmettos/cnLuCI,maxrio/luci981213,RuiChen1113/luci,thesabbir/luci,marcel-sch/luci,keyidadi/luci,dwmw2/luci,tobiaswaldvogel/luci,LuttyYang/luci,kuoruan/lede-luci,teslamint/luci,opentechinstitute/luci,urueedi/luci,MinFu/luci,remakeelectric/luci,cappiewu/luci,MinFu/luci,lbthomsen/openwrt-luci,artynet/luci,thess/OpenWrt-luci,Noltari/luci,ff94315/luci-1,ReclaimYourPrivacy/cloak-luci,opentechinstitute/luci,oyido/luci,taiha/luci,marcel-sch/luci,keyidadi/luci,dismantl/luci-0.12,fkooman/luci,nmav/luci,nwf/openwrt-luci,kuoruan/lede-luci,LuttyYang/luci,Wedmer/luci,MinFu/luci,RedSnake64/openwrt-luci-packages,Hostle/openwrt-luci-multi-user,aa65535/luci,jlopenwrtluci/luci,kuoruan/luci,Noltari/luci,ollie27/openwrt_luci,NeoRaider/luci,db260179/openwrt-bpi-r1-luci,fkooman/luci,schidler/ionic-luci,thesabbir/luci,cshore-firmware/openwrt-luci,male-puppies/luci,981213/luci-1,fkooman/luci,sujeet14108/luci,Noltari/luci,openwrt-es/openwrt-luci,keyidadi/luci,teslamint/luci,db260179/openwrt-bpi-r1-luci,RuiChen1113/luci,rogerpueyo/luci,cshore-firmware/openwrt-luci,hnyman/luci,Kyklas/luci-proto-hso,oyido/luci,nwf/openwrt-luci,LuttyYang/luci,kuoruan/luci,kuoruan/lede-luci,bittorf/luci,fkooman/luci,openwrt/luci,kuoruan/luci,LazyZhu/openwrt-luci-trunk-mod,ollie27/openwrt_luci,taiha/luci,kuoruan/lede-luci,bittorf/luci,cappiewu/luci,daofeng2015/luci,tobiaswaldvogel/luci,Noltari/luci,thesabbir/luci,schidler/ionic-luci,chris5560/openwrt-luci,jorgifumi/luci,aa65535/luci,hnyman/luci,tcatm/luci,NeoRaider/luci,Sakura-Winkey/LuCI,joaofvieira/luci,tcatm/luci,keyidadi/luci,male-puppies/luci,lbthomsen/openwrt-luci,zhaoxx063/luci,oyido/luci,db260179/openwrt-bpi-r1-luci,db260179/openwrt-bpi-r1-luci,remakeelectric/luci,cshore/luci,Hostle/luci,palmettos/test,Noltari/luci,palmettos/test,mumuqz/luci,RedSnake64/openwrt-luci-packages,keyidadi/luci,maxrio/luci981213,Sakura-Winkey/LuCI,keyidadi/luci,NeoRaider/luci,david-xiao/luci,Kyklas/luci-proto-hso,thess/OpenWrt-luci,981213/luci-1,artynet/luci,shangjiyu/luci-with-extra,zhaoxx063/luci,maxrio/luci981213,sujeet14108/luci,joaofvieira/luci,lcf258/openwrtcn,tobiaswaldvogel/luci,jchuang1977/luci-1,male-puppies/luci,taiha/luci,Wedmer/luci,daofeng2015/luci,hnyman/luci,harveyhu2012/luci,marcel-sch/luci,Noltari/luci,david-xiao/luci,forward619/luci
a329dfbd1a047f3e7b64fab2e73680cdf9e3d10c
lantern/core/history.lua
lantern/core/history.lua
-- -- Utility functions for measuring improvements in the training and testing -- metrics. -- function lantern.improved_metrics(old, new) local improved = {} for k, v in pairs(old) do local dir = lantern.performance_metrics[k] if not new[k] and dir then improved[k] = v elseif new[k] and dir == "increasing" then if v > old[k] then improved[k] = v end elseif new[k] and dir == "decreasing" then if v < old[k] then improved[k] = v end end end return improved end function lantern.improvement_made(old, new) return #lantern.improved_metrics(old, new) > 0 end function lantern.best_metrics(hist, mode, epochs) epochs = epochs or #hist assert(epochs >= 1) assert(epochs <= #hist) assert(mode == "train" or mode == "test") local update_metrics = function(prev_best, cur) for k, v in pairs(cur) do -- If `dir` is not defined for a metric, then we assume -- that it does not make sense to measure whether it has -- improved or not. So we avoid tracking it. local dir = lantern.performance_metrics[k] if not prev_best[k] and dir then prev_best[k] = v elseif prev_best[k] and dir == "increasing" then if v > prev_best[k] then prev_best[k] = v end elseif prev_best[k] and dir == "decreasing" then if v < prev_best[k] then prev_best[k] = v end end end end local best_metrics = {} for i = 1, epochs do if hist[i][mode] then update_metrics(best_metrics, hist[i][mode]) end end return best_metrics end
-- -- Utility functions for measuring improvements in the training and testing -- metrics. -- function lantern.improved_metrics(old, new) local improved = {} for k, v in pairs(old) do local dir = lantern.performance_metrics[k] if not new[k] and dir then improved[k] = v elseif new[k] and dir == "increasing" then if v > old[k] then improved[k] = v end elseif new[k] and dir == "decreasing" then if v < old[k] then improved[k] = v end end end return improved end function lantern.improvement_made(old, new) local improved = lantern.improved_metrics(old, new) local count = 0 for k, v in pairs(improved) do count = count + 1 end return count end function lantern.best_metrics(hist, mode, epochs) epochs = epochs or #hist assert(epochs >= 1) assert(epochs <= #hist) assert(mode == "train" or mode == "test") local update_metrics = function(prev_best, cur) for k, v in pairs(cur) do -- If `dir` is not defined for a metric, then we assume -- that it does not make sense to measure whether it has -- improved or not. So we avoid tracking it. local dir = lantern.performance_metrics[k] if not prev_best[k] and dir then prev_best[k] = v elseif prev_best[k] and dir == "increasing" then if v > prev_best[k] then prev_best[k] = v end elseif prev_best[k] and dir == "decreasing" then if v < prev_best[k] then prev_best[k] = v end end end end local best_metrics = {} for i = 1, epochs do if hist[i][mode] then update_metrics(best_metrics, hist[i][mode]) end end return best_metrics end
Fixed bug.
Fixed bug.
Lua
bsd-3-clause
adityaramesh/lantern
4ec7ae1e199b1ddf5ba8a8913a3a6b4a85d76755
src/register.lua
src/register.lua
-- register.lua -- Hardware device register abstraction module(...,package.seeall) --- ### Register object --- There are three types of register objects, set by the mode when created: --- * `RO` - read only. --- * `RW` - read-write. --- * `RC` - read-only and return the sum of all values read. This --- mode is for counter registers that clear back to zero when read. Register = {} --- Read a standard register function Register:read () return self.ptr[0] end --- Read a counter register function Register:readrc () local value = self.ptr[0] self.acc = (self.acc or 0) + value return self.acc end --- Write a register function Register:write (value) self.ptr[0] = value return value end --- Set and clear specific masked bits. function Register:set (bitmask) self(bit.bor(self(), bitmask)) end function Register:clr (bitmask) self(bit.band(self(), bit.bnot(bitmask))) end --- Block until applying `bitmask` to the register value gives `value`. --- If `value` is not given then until all bits in the mask are set. function Register:wait (bitmask, value) lib.waitfor(function () return bit.band(self(), bitmask) == (value or bitmask) end) end --- For type `RC`: Reset the accumulator to 0. function Register:reset () self.acc = 0 end --- For other registers provide a noop function Register:noop () end --- Register objects are "callable" as functions for convenience: --- reg() <=> reg:read() --- reg(value) <=> reg:write(value) function Register:__call (value) if value then return self:write(value) else return self:read() end end --- Registers print as `$NAME:$HEXVALUE` to make debugging easy. function Register:__tostring () return self.name..":"..bit.tohex(self()) end --- Metatables for the three different types of register local mt = { RO = {__index = { read=Register.read, wait=Register.wait, reset=Register.noop}, __call = Register.read, __tostring = Register.__tostring}, RW = {__index = { read=Register.read, write=Register.write, wait=Register.wait, set=Register.set, clr=Register.clr, reset=Register.noop}, __call = Register.__call, __tostring = Register.__tostring}, RC = {__index = { read=Register.readrc, reset=Register.reset}, __call = Register.readrc, __tostring = Register.__tostring}, } --- Create a register `offset` bytes from `base_ptr`. --- --- Example: --- register.new("TPT", "Total Packets Transmitted", 0x040D4, ptr, "RC") function new (name, longname, offset, base_ptr, mode) local o = { name=name, longname=longname, ptr=base_ptr + offset/4 } local mt = mt[mode] assert(mt) return setmetatable(o, mt) end --- ### Define registers from string description. --- Define a set of registers described by a string. --- The register objects become named entries in `table`. --- --- This is an example line for a register description: --- TXDCTL 0x06028 +0x40*0..127 (RW) Transmit Descriptor Control --- --- and this is the grammar: --- Register ::= Name Offset Indexing Mode Longname --- Name ::= <identifier> --- Indexing ::= "-" --- ::= "+" OffsetStep "*" Min ".." Max --- Mode ::= "RO" | "RW" | "RC" --- Longname ::= <string> --- Offset ::= OffsetStep ::= Min ::= Max ::= <number> function define (description, table, base_ptr) local pattern = [[ *(%S+) +(%S+) +(%S+) +(%S+) (.-) ]] for name,offset,index,perm,longname in description:gmatch(pattern) do table[name] = new(name, longname, tonumber(offset), base_ptr, perm) end end -- Print a pretty-printed register dump for a table of register objects. function dump (tab, iscounters) print "Register dump:" local strings = {} for _,reg in pairs(tab) do if iscounters == nil or reg() > 0 then table.insert(strings, reg) end end table.sort(strings, function(a,b) return a.name < b.name end) for _,reg in pairs(strings) do if iscounters then io.write(("%20s %16s %s\n"):format(reg.name, lib.comma_value(reg()), reg.longname)) else io.write(("%20s %s\n"):format(reg, reg.longname)) end end end
-- register.lua -- Hardware device register abstraction module(...,package.seeall) --- ### Register object --- There are three types of register objects, set by the mode when created: --- * `RO` - read only. --- * `RW` - read-write. --- * `RC` - read-only and return the sum of all values read. This --- mode is for counter registers that clear back to zero when read. Register = {} --- Read a standard register function Register:read () return self.ptr[0] end --- Read a counter register function Register:readrc () -- XXX JIT of this function is causing register value to be misread. jit.off(true,true) local value = self.ptr[0] self.acc = (self.acc or 0) + value return self.acc end --- Write a register function Register:write (value) self.ptr[0] = value return value end --- Set and clear specific masked bits. function Register:set (bitmask) self(bit.bor(self(), bitmask)) end function Register:clr (bitmask) self(bit.band(self(), bit.bnot(bitmask))) end --- Block until applying `bitmask` to the register value gives `value`. --- If `value` is not given then until all bits in the mask are set. function Register:wait (bitmask, value) lib.waitfor(function () return bit.band(self(), bitmask) == (value or bitmask) end) end --- For type `RC`: Reset the accumulator to 0. function Register:reset () self.acc = 0 end --- For other registers provide a noop function Register:noop () end --- Register objects are "callable" as functions for convenience: --- reg() <=> reg:read() --- reg(value) <=> reg:write(value) function Register:__call (value) if value then return self:write(value) else return self:read() end end --- Registers print as `$NAME:$HEXVALUE` to make debugging easy. function Register:__tostring () return self.name..":"..bit.tohex(self()) end --- Metatables for the three different types of register local mt = { RO = {__index = { read=Register.read, wait=Register.wait, reset=Register.noop}, __call = Register.read, __tostring = Register.__tostring}, RW = {__index = { read=Register.read, write=Register.write, wait=Register.wait, set=Register.set, clr=Register.clr, reset=Register.noop}, __call = Register.__call, __tostring = Register.__tostring}, RC = {__index = { read=Register.readrc, reset=Register.reset}, __call = Register.readrc, __tostring = Register.__tostring}, } --- Create a register `offset` bytes from `base_ptr`. --- --- Example: --- register.new("TPT", "Total Packets Transmitted", 0x040D4, ptr, "RC") function new (name, longname, offset, base_ptr, mode) local o = { name=name, longname=longname, ptr=base_ptr + offset/4 } local mt = mt[mode] assert(mt) return setmetatable(o, mt) end --- ### Define registers from string description. --- Define a set of registers described by a string. --- The register objects become named entries in `table`. --- --- This is an example line for a register description: --- TXDCTL 0x06028 +0x40*0..127 (RW) Transmit Descriptor Control --- --- and this is the grammar: --- Register ::= Name Offset Indexing Mode Longname --- Name ::= <identifier> --- Indexing ::= "-" --- ::= "+" OffsetStep "*" Min ".." Max --- Mode ::= "RO" | "RW" | "RC" --- Longname ::= <string> --- Offset ::= OffsetStep ::= Min ::= Max ::= <number> function define (description, table, base_ptr) local pattern = [[ *(%S+) +(%S+) +(%S+) +(%S+) (.-) ]] for name,offset,index,perm,longname in description:gmatch(pattern) do table[name] = new(name, longname, tonumber(offset), base_ptr, perm) end end -- Print a pretty-printed register dump for a table of register objects. function dump (tab, iscounters) print "Register dump:" local strings = {} for _,reg in pairs(tab) do if iscounters == nil or reg() > 0 then table.insert(strings, reg) end end table.sort(strings, function(a,b) return a.name < b.name end) for _,reg in pairs(strings) do if iscounters then io.write(("%20s %16s %s\n"):format(reg.name, lib.comma_value(reg()), reg.longname)) else io.write(("%20s %s\n"):format(reg, reg.longname)) end end end
register.lua: Workaround JIT bug (?) on readrc() with jit.off().
register.lua: Workaround JIT bug (?) on readrc() with jit.off().
Lua
apache-2.0
SnabbCo/snabbswitch,Igalia/snabb,andywingo/snabbswitch,SnabbCo/snabbswitch,dwdm/snabbswitch,Igalia/snabb,mixflowtech/logsensor,dpino/snabb,Igalia/snabb,SnabbCo/snabbswitch,aperezdc/snabbswitch,dpino/snabb,alexandergall/snabbswitch,wingo/snabbswitch,wingo/snabb,dpino/snabbswitch,dpino/snabbswitch,snabbnfv-goodies/snabbswitch,kellabyte/snabbswitch,pavel-odintsov/snabbswitch,kellabyte/snabbswitch,hb9cwp/snabbswitch,plajjan/snabbswitch,heryii/snabb,fhanik/snabbswitch,plajjan/snabbswitch,xdel/snabbswitch,eugeneia/snabb,Igalia/snabb,eugeneia/snabb,mixflowtech/logsensor,dpino/snabb,justincormack/snabbswitch,Igalia/snabb,Igalia/snabb,heryii/snabb,andywingo/snabbswitch,snabbco/snabb,snabbco/snabb,Igalia/snabbswitch,eugeneia/snabb,mixflowtech/logsensor,lukego/snabbswitch,wingo/snabbswitch,eugeneia/snabbswitch,eugeneia/snabbswitch,Igalia/snabbswitch,wingo/snabb,javierguerragiraldez/snabbswitch,javierguerragiraldez/snabbswitch,kellabyte/snabbswitch,snabbco/snabb,kbara/snabb,lukego/snabb,virtualopensystems/snabbswitch,hb9cwp/snabbswitch,alexandergall/snabbswitch,aperezdc/snabbswitch,hb9cwp/snabbswitch,eugeneia/snabb,Igalia/snabbswitch,snabbnfv-goodies/snabbswitch,heryii/snabb,virtualopensystems/snabbswitch,alexandergall/snabbswitch,snabbco/snabb,lukego/snabb,kbara/snabb,andywingo/snabbswitch,andywingo/snabbswitch,eugeneia/snabb,pavel-odintsov/snabbswitch,alexandergall/snabbswitch,snabbco/snabb,alexandergall/snabbswitch,wingo/snabbswitch,aperezdc/snabbswitch,heryii/snabb,wingo/snabb,dwdm/snabbswitch,eugeneia/snabb,pirate/snabbswitch,plajjan/snabbswitch,wingo/snabbswitch,heryii/snabb,pavel-odintsov/snabbswitch,eugeneia/snabb,pirate/snabbswitch,aperezdc/snabbswitch,dpino/snabb,plajjan/snabbswitch,snabbco/snabb,snabbco/snabb,heryii/snabb,wingo/snabb,kbara/snabb,fhanik/snabbswitch,virtualopensystems/snabbswitch,xdel/snabbswitch,xdel/snabbswitch,dpino/snabb,dpino/snabb,mixflowtech/logsensor,eugeneia/snabbswitch,Igalia/snabb,pirate/snabbswitch,lukego/snabbswitch,snabbnfv-goodies/snabbswitch,hb9cwp/snabbswitch,justincormack/snabbswitch,kbara/snabb,alexandergall/snabbswitch,dpino/snabb,kbara/snabb,alexandergall/snabbswitch,SnabbCo/snabbswitch,javierguerragiraldez/snabbswitch,lukego/snabb,eugeneia/snabb,mixflowtech/logsensor,Igalia/snabb,dpino/snabbswitch,dwdm/snabbswitch,Igalia/snabbswitch,lukego/snabb,justincormack/snabbswitch,eugeneia/snabbswitch,fhanik/snabbswitch,snabbco/snabb,wingo/snabb,snabbnfv-goodies/snabbswitch,dpino/snabbswitch,wingo/snabb,kbara/snabb,lukego/snabbswitch,alexandergall/snabbswitch,justincormack/snabbswitch,lukego/snabbswitch,Igalia/snabbswitch
b7a473545fd7373dfb3ccb197546c872313370cc
lstm/MemoryChain.lua
lstm/MemoryChain.lua
local MemoryChain, parent = torch.class('lstm.MemoryChain', 'nn.Module') function MemoryChain:__init(inputSize, hiddenSize, maxLength) print("MemoryChain("..inputSize..','..hiddenSize..','..maxLength..')') parent.__init(self) self.inputSize = inputSize self.hiddenSize = hiddenSize self.maxLength = maxLength self.gradInput = nil self.lstms = {} print("Creating MemoryChain") -- make enough lstm cells for the longest sequence for i=1,maxLength do self.lstms[i] = lstm.MemoryCell(inputSize, hiddenSize) if i == 1 then self.lstm_params, self.lstm_grad_params = self.lstms[1]:parameters() else -- share parameters local clone_params, clone_grad_params = self.lstms[i]:parameters() for k=1, #clone_params do clone_params[k]:set(self.lstm_params[k]) clone_grad_params[k]:set(self.lstm_grad_params[k]) end end end end function MemoryChain:reset(radius) local par = self:parameters() for i=1, #par do par[i]:uniform(-radius, radius) end end function MemoryChain:parameters() return self.lstm_params, self.lstm_grad_params end function MemoryChain:updateOutput(input) local h = torch.zeros(1, self.hiddenSize) local c = torch.zeros(1, self.hiddenSize) self.hidden_states = {[0] = h} self.memories = {[0] = c} local len = input:size(1) for i=1,len do local x = input[i]:view(1,-1) self.lstms[i]:forward({x, h, c}) h, c = unpack(self.lstms[i].output) self.hidden_states[i] = h self.memories[i] = c end self.output = self.lstms[len].output return self.output end function MemoryChain:updateGradInput(input, gradOutput) local h,c local len = input:size(1) self.gradInput = torch.Tensor(len, self.inputSize) for i=len,1,-1 do local x = input[i] h = self.hidden_states[i-1] c = self.memories[i-1] self.lstms[i]:backward({x,h,c}, gradOutput) gradOutput = self.lstms[i].gradInput -- Only h and c propagate back to the next cell, the gradient wrt x gets stored -- in gradInput. self.gradInput[i]:copy(gradOutput[1]) gradOutput = {gradOutput[2], gradOutput[3]} end return self.gradInput end -- This happens automatically when calling backward on the individual memory -- cells in updateGradInput. Not sure what to do about the scale parameter. function MemoryChain:accGradParameters(input, gradOutput, scale) end function MemoryChain:type(type) self.gradInput = {} return parent.type(self, type) end return MemoryChain -- END
local MemoryChain, parent = torch.class('lstm.MemoryChain', 'nn.Module') function MemoryChain:__init(inputSize, hiddenSize, maxLength) print("MemoryChain("..inputSize..','..hiddenSize..','..maxLength..')') parent.__init(self) self.inputSize = inputSize self.hiddenSize = hiddenSize self.maxLength = maxLength self.gradInput = nil self.lstms = {} print("Creating MemoryChain") -- make enough lstm cells for the longest sequence for i=1,maxLength do self.lstms[i] = lstm.MemoryCell(inputSize, hiddenSize) end -- We will use the firt cell as the storage for shared parameters, but -- we can't share them until later, after the whole network is created -- because getParameters will point the tensors to new storage. self.lstm_params, self.lstm_grad_params = self.lstms[1]:parameters() end -- share parameters among all memory cells function MemoryChain:share() -- make all other parameter tensors reference that memory. for i=2,self.maxLength do local cell_params, cell_grad_params = self.lstms[i]:parameters() for k=1, #cell_params do cell_params[k]:set(self.lstm_params[k]) cell_grad_params[k]:set(self.lstm_grad_params[k]) end end end function MemoryChain:reset(radius) local par = self:parameters() for i=1, #par do par[i]:uniform(-radius, radius) end end function MemoryChain:parameters() return self.lstm_params, self.lstm_grad_params end function MemoryChain:updateOutput(input) local h = torch.zeros(1, self.hiddenSize) local c = torch.zeros(1, self.hiddenSize) self.hidden_states = {[0] = h} self.memories = {[0] = c} local len = input:size(1) for i=1,len do local x = input[i]:view(1,-1) self.lstms[i]:forward({x, h, c}) h, c = unpack(self.lstms[i].output) self.hidden_states[i] = h self.memories[i] = c end self.output = self.lstms[len].output return self.output end function MemoryChain:updateGradInput(input, gradOutput) local h,c local len = input:size(1) self.gradInput = torch.Tensor(len, self.inputSize) for i=len,1,-1 do local x = input[i] h = self.hidden_states[i-1] c = self.memories[i-1] self.lstms[i]:backward({x,h,c}, gradOutput) gradOutput = self.lstms[i].gradInput -- Only h and c propagate back to the next cell, the gradient wrt x gets stored -- in gradInput. self.gradInput[i]:copy(gradOutput[1]) gradOutput = {gradOutput[2], gradOutput[3]} end return self.gradInput end -- This happens automatically when calling backward on the individual memory -- cells in updateGradInput. Not sure what to do about the scale parameter. function MemoryChain:accGradParameters(input, gradOutput, scale) end function MemoryChain:type(type) self.gradInput = {} return parent.type(self, type) end return MemoryChain -- END
fixed bug that broke parameter sharing
fixed bug that broke parameter sharing
Lua
mit
kbullaughey/lstm-play,kbullaughey/lstm-play,kbullaughey/lstm-play
14622912424da6a4668a2856cbbaf5841359bfa8
src/loader.lua
src/loader.lua
local Gamestate = require 'vendor/gamestate' local Level = require 'level' local window = require 'window' local fonts = require 'fonts' local state = Gamestate.new() local home = require 'menu' local nextState = 'home' function state:init() state.finished = false state.current = 1 state.assets = {} fonts.set( 'big' ) table.insert(state.assets, function() Gamestate.load('valley', Level.new('valley')) end) table.insert(state.assets, function() Gamestate.load('gay-island', Level.new('gay-island')) end) table.insert(state.assets, function() Gamestate.load('gay-island2', Level.new('gay-island2')) end) table.insert(state.assets, function() Gamestate.load('abedtown', Level.new('newtown')) end) table.insert(state.assets, function() Gamestate.load('lab', Level.new('lab')) end) table.insert(state.assets, function() Gamestate.load('house', Level.new('house')) end) table.insert(state.assets, function() Gamestate.load('studyroom', Level.new('studyroom')) end) table.insert(state.assets, function() Gamestate.load('hallway', Level.new('hallway')) end) table.insert(state.assets, function() Gamestate.load('forest', Level.new('forest')) end) table.insert(state.assets, function() Gamestate.load('forest2', Level.new('forest2')) end) table.insert(state.assets, function() Gamestate.load('village-forest', Level.new('village-forest')) end) table.insert(state.assets, function() Gamestate.load('town', Level.new('town')) end) table.insert(state.assets, function() Gamestate.load('tavern', Level.new('tavern')) end) table.insert(state.assets, function() Gamestate.load('blacksmith', Level.new('blacksmith')) end) table.insert(state.assets, function() Gamestate.load('greendale-exterior', Level.new('greendale-exterior')) end) table.insert(state.assets, function() Gamestate.load('deans-office-1', Level.new('deans-office-1')) end) table.insert(state.assets, function() Gamestate.load('deans-office-2', Level.new('deans-office-2')) end) table.insert(state.assets, function() Gamestate.load('deans-closet', Level.new('deans-closet')) end) table.insert(state.assets, function() Gamestate.load('baseball', Level.new('baseball')) end) table.insert(state.assets, function() Gamestate.load('dorm-lobby', Level.new('dorm-lobby')) end) table.insert(state.assets, function() Gamestate.load('borchert-hallway', Level.new('borchert-hallway')) end) table.insert(state.assets, function() Gamestate.load('admin-hallway', Level.new('admin-hallway')) end) table.insert(state.assets, function() Gamestate.load('class-hallway-1', Level.new('class-hallway-1')) end) table.insert(state.assets, function() Gamestate.load('class-hallway-2', Level.new('class-hallway-2')) end) table.insert(state.assets, function() Gamestate.load('rave-hallway', Level.new('rave-hallway')) end) table.insert(state.assets, function() Gamestate.load('class-basement', Level.new('class-basement')) end) table.insert(state.assets, function() Gamestate.load('gazette-office-1', Level.new('gazette-office-1')) end) table.insert(state.assets, function() Gamestate.load('gazette-office-2', Level.new('gazette-office-2')) end) table.insert(state.assets, function() Gamestate.load('overworld', require 'overworld') end) table.insert(state.assets, function() Gamestate.load('credits', require 'credits') end) table.insert(state.assets, function() Gamestate.load('select', require 'select') end) table.insert(state.assets, function() Gamestate.load('home', require 'menu') end) table.insert(state.assets, function() Gamestate.load('pause', require 'pause') end) table.insert(state.assets, function() Gamestate.load('cheatscreen', require 'cheatscreen') end) table.insert(state.assets, function() Gamestate.load('instructions', require 'instructions') end) table.insert(state.assets, function() Gamestate.load('options', require 'options') end) table.insert(state.assets, function() Gamestate.load('blackjackgame', require 'blackjackgame') end) state.step = 240 / # self.assets state.messages = { "terminal://", "operations://load program:(true)", "program: journey_to_the_center_of_hawkthorne", "loading simulation...", "5465415151", "5413572495", "7342195434", "8432159965", "3141592653", "5897932384", "1678942348", "1123581321", "9437832123", "1359756423" } state.orig_font = love.graphics.getFont() love.graphics.setFont( love.graphics.newFont("courier.ttf", 20 ) ) end function state:update(dt) if self.finished then love.graphics.setFont( self.orig_font ) return end local asset = state.assets[self.current] if asset ~= nil then asset() self.current = self.current + 1 else self.finished = true self:switch() end end function state:switch() Gamestate.switch(nextState) end function state:target(state) nextState = state end function state:draw() progress = (self.current-1) / #self.assets lineCount = math.floor(#self.messages * progress) love.graphics.setColor(88, 246, 0) for i = 1,lineCount do if i <= 4 then love.graphics.print(self.messages[i], 50, 15*(i+1), 0, 0.6, 0.5) else for j = 1,math.min(lineCount-i+1, 5) do love.graphics.print(self.messages[i], 60*j, 15*(i+1), 0, 0.4, 0.4) end end end love.graphics.setColor(255, 255, 255) end return state
local Gamestate = require 'vendor/gamestate' local Level = require 'level' local window = require 'window' local fonts = require 'fonts' local state = Gamestate.new() local home = require 'menu' local nextState = 'home' function state:init() state.finished = false state.current = 1 state.assets = {} fonts.set( 'big' ) table.insert(state.assets, function() Gamestate.load('valley', Level.new('valley')) end) table.insert(state.assets, function() Gamestate.load('gay-island', Level.new('gay-island')) end) table.insert(state.assets, function() Gamestate.load('gay-island2', Level.new('gay-island2')) end) table.insert(state.assets, function() Gamestate.load('abedtown', Level.new('newtown')) end) table.insert(state.assets, function() Gamestate.load('lab', Level.new('lab')) end) table.insert(state.assets, function() Gamestate.load('house', Level.new('house')) end) table.insert(state.assets, function() Gamestate.load('studyroom', Level.new('studyroom')) end) table.insert(state.assets, function() Gamestate.load('hallway', Level.new('hallway')) end) table.insert(state.assets, function() Gamestate.load('forest', Level.new('forest')) end) table.insert(state.assets, function() Gamestate.load('forest2', Level.new('forest2')) end) table.insert(state.assets, function() Gamestate.load('village-forest', Level.new('village-forest')) end) table.insert(state.assets, function() Gamestate.load('town', Level.new('town')) end) table.insert(state.assets, function() Gamestate.load('tavern', Level.new('tavern')) end) table.insert(state.assets, function() Gamestate.load('blacksmith', Level.new('blacksmith')) end) table.insert(state.assets, function() Gamestate.load('greendale-exterior', Level.new('greendale-exterior')) end) table.insert(state.assets, function() Gamestate.load('deans-office-1', Level.new('deans-office-1')) end) table.insert(state.assets, function() Gamestate.load('deans-office-2', Level.new('deans-office-2')) end) table.insert(state.assets, function() Gamestate.load('deans-closet', Level.new('deans-closet')) end) table.insert(state.assets, function() Gamestate.load('baseball', Level.new('baseball')) end) table.insert(state.assets, function() Gamestate.load('dorm-lobby', Level.new('dorm-lobby')) end) table.insert(state.assets, function() Gamestate.load('borchert-hallway', Level.new('borchert-hallway')) end) table.insert(state.assets, function() Gamestate.load('admin-hallway', Level.new('admin-hallway')) end) table.insert(state.assets, function() Gamestate.load('class-hallway-1', Level.new('class-hallway-1')) end) table.insert(state.assets, function() Gamestate.load('class-hallway-2', Level.new('class-hallway-2')) end) table.insert(state.assets, function() Gamestate.load('rave-hallway', Level.new('rave-hallway')) end) table.insert(state.assets, function() Gamestate.load('class-basement', Level.new('class-basement')) end) table.insert(state.assets, function() Gamestate.load('gazette-office-1', Level.new('gazette-office-1')) end) table.insert(state.assets, function() Gamestate.load('gazette-office-2', Level.new('gazette-office-2')) end) table.insert(state.assets, function() Gamestate.load('overworld', require 'overworld') end) table.insert(state.assets, function() Gamestate.load('credits', require 'credits') end) table.insert(state.assets, function() Gamestate.load('select', require 'select') end) table.insert(state.assets, function() Gamestate.load('home', require 'menu') end) table.insert(state.assets, function() Gamestate.load('pause', require 'pause') end) table.insert(state.assets, function() Gamestate.load('cheatscreen', require 'cheatscreen') end) table.insert(state.assets, function() Gamestate.load('instructions', require 'instructions') end) table.insert(state.assets, function() Gamestate.load('options', require 'options') end) table.insert(state.assets, function() Gamestate.load('blackjackgame', require 'blackjackgame') end) state.step = 240 / # self.assets end function state:update(dt) if self.finished then return end local asset = state.assets[self.current] if asset ~= nil then asset() self.current = self.current + 1 else self.finished = true self:switch() end end function state:switch() Gamestate.switch(nextState) end function state:target(state) nextState = state end function state:draw() love.graphics.rectangle('line', window.width / 2 - 120, window.height / 2 - 10, 240, 20) love.graphics.rectangle('fill', window.width / 2 - 120, window.height / 2 - 10, (self.current - 1) * self.step, 20) end return state
Fixing master branch commit issue
Fixing master branch commit issue
Lua
mit
hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua
fdf44a0b6b4296fbb467eda64fcee4235a94d257
irc/handlers.lua
irc/handlers.lua
local pairs = pairs local error = error local tonumber = tonumber local print=print module "irc" handlers = {} handlers["PING"] = function(o, prefix, query) o:send("PONG :%s", query) end handlers["001"] = function(o, prefix, me) o.authed = true o.nick = me end handlers["PRIVMSG"] = function(o, prefix, channel, message) o:invoke("OnChat", parsePrefix(prefix), channel, message) end handlers["NOTICE"] = function(o, prefix, channel, message) o:invoke("OnNotice", parsePrefix(prefix), channel, message) end handlers["JOIN"] = function(o, prefix, channel) local user = parsePrefix(prefix) if o.track_users then if user.nick == o.nick then o.channels[channel] = {users = {}} else o.channels[channel].users[user.nick] = user end end o:invoke("OnJoin", user, channel) end handlers["PART"] = function(o, prefix, channel, reason) local user = parsePrefix(prefix) if o.track_users then if user.nick == o.nick then o.channels[channel] = nil else o.channels[channel].users[user.nick] = nil end end o:invoke("OnPart", user, channel, reason) end handlers["QUIT"] = function(o, prefix, msg) local user = parsePrefix(prefix) if o.track_users then for channel, v in pairs(o.channels) do v.users[user.nick] = nil end end o:invoke("OnQuit", user, msg) end handlers["NICK"] = function(o, prefix, newnick) local user = parsePrefix(prefix) if o.track_users then for channel, v in pairs(o.channels) do local users = v.users local oldinfo = users[user.nick] if oldinfo then users[newnick] = oldinfo users[newnick].nick = newnick users[newnick].fullhost = users[newnick].nick.."!"..users[newnick].username.."@"..users[newnick].host users[user.nick] = nil o:invoke("NickChange", user, newnick, channel) end end else o:invoke("NickChange", user, newnick) end end --WHO list handlers["352"] = function(o, prefix, me, channel, name1, host, serv, name, access1 ,something, something2) if o.track_users then local user = {nick=name, host=host, username=name1, serv=serv, access=parseWhoAccess(access1), fullhost=name.."!"..name1.."@"..host} --print(user.nick,user.host,user.ID,user.serv,user.access) o.channels[channel].users[user.nick] = user end end --NAMES list handlers["353"] = function(o, prefix, me, chanType, channel, names) if o.track_users then o.channels[channel] = o.channels[channel] or {users = {}, type = chanType} local users = o.channels[channel].users for nick in names:gmatch("(%S+)") do local access, name = parseNick(nick) users[name] = {type = access} end end end --end of NAMES handlers["366"] = function(o, prefix, me, channel, msg) if o.track_users then o:invoke("NameList", channel, msg) end end --no topic handlers["331"] = function(o, prefix, me, channel) o:invoke("OnTopic", channel, nil) end --new topic handlers["TOPIC"] = function(o, prefix, channel, topic) o:invoke("OnTopic", channel, topic) end handlers["332"] = function(o, prefix, me, channel, topic) o:invoke("OnTopic", channel, topic) end --topic creation info handlers["333"] = function(o, prefix, me, channel, nick, time) o:invoke("OnTopicInfo", channel, nick, tonumber(time)) end handlers["KICK"] = function(o, prefix, channel, kicked, reason) o:invoke("OnKick", channel, kicked, parsePrefix(prefix), reason) end --RPL_UMODEIS --To answer a query about a client's own mode, RPL_UMODEIS is sent back handlers["221"] = function(o, prefix, user, modes) o:invoke("OnUserMode", modes) end --RPL_CHANNELMODEIS --The result from common irc servers differs from that defined by the rfc handlers["324"] = function(o, prefix, user, channel, modes) o:invoke("OnChannelMode", channel, modes) end handlers["MODE"] = function(o, prefix, targetchan, modes, ...) print(prefix,target,modes, ...) if o.track_users then --TODO: track user access changes. end o:invoke("OnModeChange", parsePrefix(prefix), target, modes, ...) end handlers["ERROR"] = function(o, prefix, message) o:invoke("OnDisconnect", message, true) o:shutdown() error(message, 3) end
local pairs = pairs local error = error local tonumber = tonumber local print=print module "irc" handlers = {} handlers["PING"] = function(o, prefix, query) o:send("PONG :%s", query) end handlers["001"] = function(o, prefix, me) o.authed = true o.nick = me end handlers["PRIVMSG"] = function(o, prefix, channel, message) o:invoke("OnChat", parsePrefix(prefix), channel, message) end handlers["NOTICE"] = function(o, prefix, channel, message) o:invoke("OnNotice", parsePrefix(prefix), channel, message) end handlers["JOIN"] = function(o, prefix, channel) local user = parsePrefix(prefix) if o.track_users then if user.nick == o.nick then o.channels[channel] = {users = {}} else o.channels[channel].users[user.nick] = user end end o:invoke("OnJoin", user, channel) end handlers["PART"] = function(o, prefix, channel, reason) local user = parsePrefix(prefix) if o.track_users then if user.nick == o.nick then o.channels[channel] = nil else o.channels[channel].users[user.nick] = nil end end o:invoke("OnPart", user, channel, reason) end handlers["QUIT"] = function(o, prefix, msg) local user = parsePrefix(prefix) if o.track_users then for channel, v in pairs(o.channels) do v.users[user.nick] = nil end end o:invoke("OnQuit", user, msg) end handlers["NICK"] = function(o, prefix, newnick) local user = parsePrefix(prefix) if o.track_users then for channel, v in pairs(o.channels) do local users = v.users local oldinfo = users[user.nick] if oldinfo then users[newnick] = oldinfo users[newnick].nick = newnick if users[newnick].fullhost then users[newnick].fullhost = users[newnick].nick.."!"..users[newnick].username.."@"..users[newnick].host end users[user.nick] = nil o:invoke("NickChange", user, newnick, channel) end end else o:invoke("NickChange", user, newnick) end end --WHO list handlers["352"] = function(o, prefix, me, channel, name1, host, serv, name, access1 ,something, something2) if o.track_users then local user = {nick=name, host=host, username=name1, serv=serv, access=parseWhoAccess(access1), fullhost=name.."!"..name1.."@"..host} --print(user.nick,user.host,user.ID,user.serv,user.access) o.channels[channel].users[user.nick] = user end end --NAMES list handlers["353"] = function(o, prefix, me, chanType, channel, names) if o.track_users then o.channels[channel] = o.channels[channel] or {users = {}, type = chanType} local users = o.channels[channel].users for nick in names:gmatch("(%S+)") do local access, name = parseNick(nick) users[name] = {type = access} end end end --end of NAMES handlers["366"] = function(o, prefix, me, channel, msg) if o.track_users then o:invoke("NameList", channel, msg) end end --no topic handlers["331"] = function(o, prefix, me, channel) o:invoke("OnTopic", channel, nil) end --new topic handlers["TOPIC"] = function(o, prefix, channel, topic) o:invoke("OnTopic", channel, topic) end handlers["332"] = function(o, prefix, me, channel, topic) o:invoke("OnTopic", channel, topic) end --topic creation info handlers["333"] = function(o, prefix, me, channel, nick, time) o:invoke("OnTopicInfo", channel, nick, tonumber(time)) end handlers["KICK"] = function(o, prefix, channel, kicked, reason) o:invoke("OnKick", channel, kicked, parsePrefix(prefix), reason) end --RPL_UMODEIS --To answer a query about a client's own mode, RPL_UMODEIS is sent back handlers["221"] = function(o, prefix, user, modes) o:invoke("OnUserMode", modes) end --RPL_CHANNELMODEIS --The result from common irc servers differs from that defined by the rfc handlers["324"] = function(o, prefix, user, channel, modes) o:invoke("OnChannelMode", channel, modes) end handlers["MODE"] = function(o, prefix, targetchan, modes, ...) print(prefix,target,modes, ...) if o.track_users then --TODO: track user access changes. end o:invoke("OnModeChange", parsePrefix(prefix), target, modes, ...) end handlers["ERROR"] = function(o, prefix, message) o:invoke("OnDisconnect", message, true) o:shutdown() error(message, 3) end
fix possible crash when someone changes nicks
fix possible crash when someone changes nicks
Lua
mit
Brilliant-Minds/BMNBot-2,wolfy1339/WolfyBot,wolfy1339/WolfyBot,cracker64/Crackbot,GLolol/Crackbot,Brilliant-Minds/BMNBot-2,GLolol/Crackbot,wolfy1339/WolfyBot,cracker64/Crackbot
7937f5507396a780d8c9aa390f5978828706a6d8
premake4.lua
premake4.lua
-- -- Premake 5.x build configuration script -- Use this script to configure the project with Premake4. -- -- -- Define the project. Put the release configuration first so it will be the -- default when folks build using the makefile. That way they don't have to -- worry about the /scripts argument and all that. -- solution "Premake5" configurations { "Release", "Debug" } location ( _OPTIONS["to"] ) project "Premake5" targetname "premake5" language "C" kind "ConsoleApp" flags { "No64BitChecks", "ExtraWarnings", "StaticRuntime" } includedirs { "src/host/lua-5.1.4/src" } files { "*.txt", "**.lua", "src/**.h", "src/**.c", "src/host/scripts.c" } excludes { "src/host/lua-5.1.4/src/lua.c", "src/host/lua-5.1.4/src/luac.c", "src/host/lua-5.1.4/src/print.c", "src/host/lua-5.1.4/**.lua", "src/host/lua-5.1.4/etc/*.c" } configuration "Debug" targetdir "bin/debug" defines "_DEBUG" flags { "Symbols" } configuration "Release" targetdir "bin/release" defines "NDEBUG" flags { "OptimizeSize" } configuration "vs*" defines { "_CRT_SECURE_NO_WARNINGS" } configuration "vs2005" defines {"_CRT_SECURE_NO_DEPRECATE" } configuration "windows" links { "ole32" } configuration "linux or bsd or hurd" defines { "LUA_USE_POSIX", "LUA_USE_DLOPEN" } links { "m" } linkoptions { "-rdynamic" } configuration "linux or hurd" links { "dl" } configuration "macosx" defines { "LUA_USE_MACOSX" } links { "CoreServices.framework" } configuration { "macosx", "gmake" } -- toolset "clang" (not until a 5.0 binary is available) buildoptions { "-mmacosx-version-min=10.4" } linkoptions { "-mmacosx-version-min=10.4" } configuration { "solaris" } linkoptions { "-Wl,--export-dynamic" } configuration "aix" defines { "LUA_USE_POSIX", "LUA_USE_DLOPEN" } links { "m" } -- -- A more thorough cleanup. -- if _ACTION == "clean" then os.rmdir("bin") os.rmdir("build") end -- -- Use the --to=path option to control where the project files get generated. I use -- this to create project files for each supported toolset, each in their own folder, -- in preparation for deployment. -- newoption { trigger = "to", value = "path", description = "Set the output location for the generated files" } -- -- Use the embed action to convert all of the Lua scripts into C strings, which -- can then be built into the executable. Always embed the scripts before creating -- a release build. -- dofile("scripts/embed.lua") newaction { trigger = "embed", description = "Embed scripts in scripts.c; required before release builds", execute = doembed } -- -- Use the release action to prepare source and binary packages for a new release. -- This action isn't complete yet; a release still requires some manual work. -- dofile("scripts/release.lua") newaction { trigger = "release", description = "Prepare a new release (incomplete)", execute = dorelease }
-- -- Premake 5.x build configuration script -- Use this script to configure the project with Premake4. -- -- -- Define the project. Put the release configuration first so it will be the -- default when folks build using the makefile. That way they don't have to -- worry about the /scripts argument and all that. -- solution "Premake5" configurations { "Release", "Debug" } location ( _OPTIONS["to"] ) project "Premake5" targetname "premake5" language "C" kind "ConsoleApp" flags { "No64BitChecks", "ExtraWarnings", "StaticRuntime" } includedirs { "src/host/lua-5.1.4/src" } files { "*.txt", "**.lua", "src/**.h", "src/**.c", "src/host/scripts.c" } excludes { "src/host/lua-5.1.4/src/lauxlib.c", "src/host/lua-5.1.4/src/lua.c", "src/host/lua-5.1.4/src/luac.c", "src/host/lua-5.1.4/src/print.c", "src/host/lua-5.1.4/**.lua", "src/host/lua-5.1.4/etc/*.c" } configuration "Debug" targetdir "bin/debug" defines "_DEBUG" flags { "Symbols" } configuration "Release" targetdir "bin/release" defines "NDEBUG" flags { "OptimizeSize" } configuration "vs*" defines { "_CRT_SECURE_NO_WARNINGS" } configuration "vs2005" defines {"_CRT_SECURE_NO_DEPRECATE" } configuration "windows" links { "ole32" } configuration "linux or bsd or hurd" defines { "LUA_USE_POSIX", "LUA_USE_DLOPEN" } links { "m" } linkoptions { "-rdynamic" } configuration "linux or hurd" links { "dl" } configuration "macosx" defines { "LUA_USE_MACOSX" } links { "CoreServices.framework" } configuration { "macosx", "gmake" } -- toolset "clang" (not until a 5.0 binary is available) buildoptions { "-mmacosx-version-min=10.4" } linkoptions { "-mmacosx-version-min=10.4" } configuration { "solaris" } linkoptions { "-Wl,--export-dynamic" } configuration "aix" defines { "LUA_USE_POSIX", "LUA_USE_DLOPEN" } links { "m" } -- -- A more thorough cleanup. -- if _ACTION == "clean" then os.rmdir("bin") os.rmdir("build") end -- -- Use the --to=path option to control where the project files get generated. I use -- this to create project files for each supported toolset, each in their own folder, -- in preparation for deployment. -- newoption { trigger = "to", value = "path", description = "Set the output location for the generated files" } -- -- Use the embed action to convert all of the Lua scripts into C strings, which -- can then be built into the executable. Always embed the scripts before creating -- a release build. -- dofile("scripts/embed.lua") newaction { trigger = "embed", description = "Embed scripts in scripts.c; required before release builds", execute = doembed } -- -- Use the release action to prepare source and binary packages for a new release. -- This action isn't complete yet; a release still requires some manual work. -- dofile("scripts/release.lua") newaction { trigger = "release", description = "Prepare a new release (incomplete)", execute = dorelease }
Fix bootstrapping with premake4
Fix bootstrapping with premake4
Lua
bsd-3-clause
Meoo/premake-core,Yhgenomics/premake-core,jstewart-amd/premake-core,dcourtois/premake-core,PlexChat/premake-core,jstewart-amd/premake-core,xriss/premake-core,xriss/premake-core,premake/premake-core,Yhgenomics/premake-core,sleepingwit/premake-core,mendsley/premake-core,kankaristo/premake-core,saberhawk/premake-core,PlexChat/premake-core,mendsley/premake-core,aleksijuvani/premake-core,dcourtois/premake-core,Zefiros-Software/premake-core,premake/premake-core,starkos/premake-core,bravnsgaard/premake-core,CodeAnxiety/premake-core,premake/premake-core,PlexChat/premake-core,CodeAnxiety/premake-core,alarouche/premake-core,dcourtois/premake-core,felipeprov/premake-core,Tiger66639/premake-core,TurkeyMan/premake-core,bravnsgaard/premake-core,starkos/premake-core,martin-traverse/premake-core,jsfdez/premake-core,noresources/premake-core,Yhgenomics/premake-core,prapin/premake-core,grbd/premake-core,tritao/premake-core,dcourtois/premake-core,mendsley/premake-core,akaStiX/premake-core,soundsrc/premake-core,jstewart-amd/premake-core,akaStiX/premake-core,aleksijuvani/premake-core,akaStiX/premake-core,tvandijck/premake-core,TurkeyMan/premake-core,martin-traverse/premake-core,tvandijck/premake-core,noresources/premake-core,Tiger66639/premake-core,Tiger66639/premake-core,kankaristo/premake-core,noresources/premake-core,Blizzard/premake-core,saberhawk/premake-core,Blizzard/premake-core,mendsley/premake-core,tvandijck/premake-core,starkos/premake-core,Zefiros-Software/premake-core,starkos/premake-core,saberhawk/premake-core,noresources/premake-core,grbd/premake-core,prapin/premake-core,dcourtois/premake-core,sleepingwit/premake-core,noresources/premake-core,Zefiros-Software/premake-core,tritao/premake-core,lizh06/premake-core,tvandijck/premake-core,PlexChat/premake-core,lizh06/premake-core,Zefiros-Software/premake-core,martin-traverse/premake-core,Blizzard/premake-core,tritao/premake-core,resetnow/premake-core,aleksijuvani/premake-core,starkos/premake-core,tvandijck/premake-core,alarouche/premake-core,jsfdez/premake-core,sleepingwit/premake-core,Meoo/premake-core,resetnow/premake-core,martin-traverse/premake-core,xriss/premake-core,premake/premake-core,felipeprov/premake-core,grbd/premake-core,resetnow/premake-core,felipeprov/premake-core,soundsrc/premake-core,bravnsgaard/premake-core,resetnow/premake-core,lizh06/premake-core,bravnsgaard/premake-core,LORgames/premake-core,aleksijuvani/premake-core,Blizzard/premake-core,saberhawk/premake-core,akaStiX/premake-core,alarouche/premake-core,premake/premake-core,mandersan/premake-core,Tiger66639/premake-core,starkos/premake-core,mendsley/premake-core,TurkeyMan/premake-core,sleepingwit/premake-core,dcourtois/premake-core,mandersan/premake-core,Yhgenomics/premake-core,kankaristo/premake-core,xriss/premake-core,noresources/premake-core,mandersan/premake-core,LORgames/premake-core,LORgames/premake-core,soundsrc/premake-core,soundsrc/premake-core,resetnow/premake-core,TurkeyMan/premake-core,jstewart-amd/premake-core,mandersan/premake-core,aleksijuvani/premake-core,mandersan/premake-core,grbd/premake-core,premake/premake-core,LORgames/premake-core,TurkeyMan/premake-core,soundsrc/premake-core,CodeAnxiety/premake-core,Meoo/premake-core,starkos/premake-core,kankaristo/premake-core,jsfdez/premake-core,noresources/premake-core,CodeAnxiety/premake-core,felipeprov/premake-core,dcourtois/premake-core,Zefiros-Software/premake-core,lizh06/premake-core,premake/premake-core,LORgames/premake-core,CodeAnxiety/premake-core,sleepingwit/premake-core,xriss/premake-core,bravnsgaard/premake-core,Blizzard/premake-core,prapin/premake-core,Blizzard/premake-core,Meoo/premake-core,jstewart-amd/premake-core,tritao/premake-core,alarouche/premake-core,prapin/premake-core,jsfdez/premake-core
88adae0d3de046e5ac0f44c8662f51051b737e43
premake5.lua
premake5.lua
workspace "Dab" location "build" configurations { "Debug", "Release" } function dab_common_setup(name) project(name) kind "ConsoleApp" language "C++" targetdir "bin/" flags "C++11" warnings "Extra" flags "FatalCompileWarnings" files { "src/cshared/**.h", "src/cshared/**.cpp" } files { "src/"..name.."/**.h", "src/"..name.."/**.cpp" } links { "dl" } linkoptions { "-rdynamic" } filter "configurations:Debug" defines { "DEBUG" } symbols "On" filter "configurations:Release" optimize "On" filter "action:xcode4" buildoptions "-stdlib=libc++" linkoptions "-stdlib=libc++" filter "action:xcode4" buildoptions "-std=c++11" end dab_common_setup("cvm") dab_common_setup("cdisasm") dab_common_setup("cdumpcov")
workspace "Dab" location "build" configurations { "Debug", "Release" } function dab_common_setup(name) project(name) kind "ConsoleApp" language "C++" targetdir "bin/" flags "C++11" warnings "Extra" flags "FatalCompileWarnings" files { "src/cshared/**.h", "src/cshared/**.cpp" } files { "src/"..name.."/**.h", "src/"..name.."/**.cpp" } filter "configurations:Debug" defines { "DEBUG" } symbols "On" filter "configurations:Release" optimize "On" filter "action:xcode4" buildoptions "-stdlib=libc++" linkoptions "-stdlib=libc++" filter "action:xcode4" buildoptions "-std=c++11" filter "system:not windows" links "dl" linkoptions "-rdynamic" end dab_common_setup("cvm") dab_common_setup("cdisasm") dab_common_setup("cdumpcov")
premake: fix configuration for windows
premake: fix configuration for windows
Lua
mit
thomas-pendragon/dablang,thomas-pendragon/dablang,thomas-pendragon/dablang,thomas-pendragon/dablang
4ce917a633c080dd0955f856e6e64efe69f948b6
src/table/src/Shared/Table.lua
src/table/src/Shared/Table.lua
--[=[ Provide a variety of utility table operations @class Table ]=] local Table = {} --[=[ Concats `target` with `source`. @param target table -- Table to append to @param source table -- Table read from @return table -- parameter table ]=] function Table.append(target, source) for _, value in pairs(source) do target[#target+1] = value end return target end --[=[ Shallow merges two tables without modifying either. @param orig table -- Original table @param new table -- Result @return table ]=] function Table.merge(orig, new) local result = {} for key, val in pairs(orig) do result[key] = val end for key, val in pairs(new) do result[key] = val end return result end --[=[ Reverses the list and returns the reversed copy @param orig table -- Original table @return table ]=] function Table.reverse(orig) local new = {} for i=#orig, 1, -1 do table.insert(new, orig[i]) end return new end --[=[ Returns a list of all of the values that a table has. @param source table -- Table source to extract values from @return table -- A list with all the values the table has ]=] function Table.values(source) local new = {} for _, val in pairs(source) do table.insert(new, val) end return new end --[=[ Returns a list of all of the keys that a table has. (In order of pairs) @param source table -- Table source to extract keys from @return table -- A list with all the keys the table has ]=] function Table.keys(source) local new = {} for key, _ in pairs(source) do table.insert(new, key) end return new end --[=[ Shallow merges two lists without modifying either. @param orig table -- Original table @param new table -- Result @return table ]=] function Table.mergeLists(orig, new) local _table = {} for _, val in pairs(orig) do table.insert(_table, val) end for _, val in pairs(new) do table.insert(_table, val) end return _table end --[=[ Swaps keys with values, overwriting additional values if duplicated. @param orig table -- Original table @return table ]=] function Table.swapKeyValue(orig) local tab = {} for key, val in pairs(orig) do tab[val] = key end return tab end --[=[ Converts a table to a list. @param _table table -- Table to convert to a list @return table ]=] function Table.toList(_table) local list = {} for _, item in pairs(_table) do table.insert(list, item) end return list end --[=[ Counts the number of items in `_table`. Useful since `__len` on table in Lua 5.2 returns just the array length. @param _table table -- Table to count @return number -- count ]=] function Table.count(_table) local count = 0 for _, _ in pairs(_table) do count = count + 1 end return count end --[=[ Shallow copies a table from target into a new table @param target table -- Table to copy @return table -- Result ]=] function Table.copy(target) local new = {} for key, value in pairs(target) do new[key] = value end return new end --[=[ Deep copies a table including metatables @param target table -- Table to deep copy @param _context table? -- Cntext to deepCopy the value in @return table -- Result ]=] function Table.deepCopy(target, _context) _context = _context or {} if _context[target] then return _context[target] end if type(target) == "table" then local new = {} _context[target] = new for index, value in pairs(target) do new[Table.deepCopy(index, _context)] = Table.deepCopy(value, _context) end return setmetatable(new, Table.deepCopy(getmetatable(target), _context)) else return target end end --[=[ Overwrites a table's value @param target table -- Target table @param source table -- Table to read from @return table -- target ]=] function Table.deepOverwrite(target, source) for index, value in pairs(source) do if type(target[index]) == "table" and type(value) == "table" then target[index] = Table.deepOverwrite(target[index], value) else target[index] = value end end return target end --[=[ Gets an index by value, returning `nil` if no index is found. @param haystack table -- To search in @param needle Value to search for @return The index of the value, if found @return nil -- if not found ]=] function Table.getIndex(haystack, needle) assert(needle ~= nil, "Needle cannot be nil") for index, item in pairs(haystack) do if needle == item then return index end end return nil end --[=[ Recursively prints the table. Does not handle recursive tables. @param _table table -- Table to stringify @param indent number? -- Indent level @param output string? -- Output string, used recursively @return string -- The table in string form ]=] function Table.stringify(_table, indent, output) output = output or tostring(_table) indent = indent or 0 for key, value in pairs(_table) do local formattedText = "\n" .. string.rep(" ", indent) .. tostring(key) .. ": " if type(value) == "table" then output = output .. formattedText output = Table.stringify(value, indent + 1, output) else output = output .. formattedText .. tostring(value) end end return output end --[=[ Returns whether `value` is within `table` @param _table table -- To search in for value @param value any -- Value to search for @return boolean -- `true` if within, `false` otherwise ]=] function Table.contains(_table, value) for _, item in pairs(_table) do if item == value then return true end end return false end --[=[ Overwrites an existing table with the source values. @param target table -- Table to overwite @param source table -- Source table to read from @return table -- target ]=] function Table.overwrite(target, source) for index, item in pairs(source) do target[index] = item end return target end --[=[ Takes `count` entries from the table. If the table does not have that many entries, will return up to the number the table has to provide. @param source table -- Source table to retrieve values from @param count number -- Number of entries to take @return table -- List with the entries retrieved ]=] function Table.take(source, count) local newTable = {} for i=1, math.min(#source, count) do newTable[i] = source[i] end return newTable end local function errorOnIndex(_, index) error(("Bad index %q"):format(tostring(index)), 2) end local READ_ONLY_METATABLE = { __index = errorOnIndex; __newindex = errorOnIndex; } --[=[ Sets a metatable on a table such that it errors when indexing a nil value @param target table -- Table to error on indexing @return table -- The same table, with the metatable set to readonly ]=] function Table.readonly(target) return setmetatable(target, READ_ONLY_METATABLE) end --[=[ Recursively sets the table as ReadOnly @param target table -- Table to error on indexing @return table -- The same table ]=] function Table.deepReadonly(target) for _, item in pairs(target) do if type(item) == "table" then Table.deepReadonly(item) end end return Table.readonly(target) end return Table
--[=[ Provide a variety of utility table operations @class Table ]=] local Table = {} --[=[ Concats `target` with `source`. @param target table -- Table to append to @param source table -- Table read from @return table -- parameter table ]=] function Table.append(target, source) for _, value in pairs(source) do target[#target+1] = value end return target end --[=[ Shallow merges two tables without modifying either. @param orig table -- Original table @param new table -- Result @return table ]=] function Table.merge(orig, new) local result = {} for key, val in pairs(orig) do result[key] = val end for key, val in pairs(new) do result[key] = val end return result end --[=[ Reverses the list and returns the reversed copy @param orig table -- Original table @return table ]=] function Table.reverse(orig) local new = {} for i=#orig, 1, -1 do table.insert(new, orig[i]) end return new end --[=[ Returns a list of all of the values that a table has. @param source table -- Table source to extract values from @return table -- A list with all the values the table has ]=] function Table.values(source) local new = {} for _, val in pairs(source) do table.insert(new, val) end return new end --[=[ Returns a list of all of the keys that a table has. (In order of pairs) @param source table -- Table source to extract keys from @return table -- A list with all the keys the table has ]=] function Table.keys(source) local new = {} for key, _ in pairs(source) do table.insert(new, key) end return new end --[=[ Shallow merges two lists without modifying either. @param orig table -- Original table @param new table -- Result @return table ]=] function Table.mergeLists(orig, new) local _table = {} for _, val in pairs(orig) do table.insert(_table, val) end for _, val in pairs(new) do table.insert(_table, val) end return _table end --[=[ Swaps keys with values, overwriting additional values if duplicated. @param orig table -- Original table @return table ]=] function Table.swapKeyValue(orig) local tab = {} for key, val in pairs(orig) do tab[val] = key end return tab end --[=[ Converts a table to a list. @param _table table -- Table to convert to a list @return table ]=] function Table.toList(_table) local list = {} for _, item in pairs(_table) do table.insert(list, item) end return list end --[=[ Counts the number of items in `_table`. Useful since `__len` on table in Lua 5.2 returns just the array length. @param _table table -- Table to count @return number -- count ]=] function Table.count(_table) local count = 0 for _, _ in pairs(_table) do count = count + 1 end return count end --[=[ Shallow copies a table from target into a new table @param target table -- Table to copy @return table -- Result ]=] Table.copy = table.clone --[=[ Deep copies a table including metatables @param target table -- Table to deep copy @param _context table? -- Cntext to deepCopy the value in @return table -- Result ]=] function Table.deepCopy(target, _context) _context = _context or {} if _context[target] then return _context[target] end if type(target) == "table" then local new = {} _context[target] = new for index, value in pairs(target) do new[Table.deepCopy(index, _context)] = Table.deepCopy(value, _context) end return setmetatable(new, Table.deepCopy(getmetatable(target), _context)) else return target end end --[=[ Overwrites a table's value @param target table -- Target table @param source table -- Table to read from @return table -- target ]=] function Table.deepOverwrite(target, source) for index, value in pairs(source) do if type(target[index]) == "table" and type(value) == "table" then target[index] = Table.deepOverwrite(target[index], value) else target[index] = value end end return target end --[=[ Gets an index by value, returning `nil` if no index is found. @param haystack table -- To search in @param needle Value to search for @return The index of the value, if found @return nil -- if not found ]=] function Table.getIndex(haystack, needle) assert(needle ~= nil, "Needle cannot be nil") for index, item in pairs(haystack) do if needle == item then return index end end return nil end --[=[ Recursively prints the table. Does not handle recursive tables. @param _table table -- Table to stringify @param indent number? -- Indent level @param output string? -- Output string, used recursively @return string -- The table in string form ]=] function Table.stringify(_table, indent, output) output = output or tostring(_table) indent = indent or 0 for key, value in pairs(_table) do local formattedText = "\n" .. string.rep(" ", indent) .. tostring(key) .. ": " if type(value) == "table" then output = output .. formattedText output = Table.stringify(value, indent + 1, output) else output = output .. formattedText .. tostring(value) end end return output end --[=[ Returns whether `value` is within `table` @param _table table -- To search in for value @param value any -- Value to search for @return boolean -- `true` if within, `false` otherwise ]=] function Table.contains(_table, value) for _, item in pairs(_table) do if item == value then return true end end return false end --[=[ Overwrites an existing table with the source values. @param target table -- Table to overwite @param source table -- Source table to read from @return table -- target ]=] function Table.overwrite(target, source) for index, item in pairs(source) do target[index] = item end return target end --[=[ Takes `count` entries from the table. If the table does not have that many entries, will return up to the number the table has to provide. @param source table -- Source table to retrieve values from @param count number -- Number of entries to take @return table -- List with the entries retrieved ]=] function Table.take(source, count) local newTable = {} for i=1, math.min(#source, count) do newTable[i] = source[i] end return newTable end local function errorOnIndex(_, index) error(("Bad index %q"):format(tostring(index)), 2) end local READ_ONLY_METATABLE = { __index = errorOnIndex; __newindex = errorOnIndex; } --[=[ Sets a metatable on a table such that it errors when indexing a nil value @param target table -- Table to error on indexing @return table -- The same table, with the metatable set to readonly ]=] function Table.readonly(target) return setmetatable(target, READ_ONLY_METATABLE) end --[=[ Recursively sets the table as ReadOnly @param target table -- Table to error on indexing @return table -- The same table ]=] function Table.deepReadonly(target) for _, item in pairs(target) do if type(item) == "table" then Table.deepReadonly(item) end end return Table.readonly(target) end return Table
fix: Use table.clone for table.copy
fix: Use table.clone for table.copy
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
cd544009babb29cf54a1e8d31da94833c178a4f8
lua/entities/gmod_wire_spawner.lua
lua/entities/gmod_wire_spawner.lua
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Prop Spawner" ENT.RenderGroup = RENDERGROUP_BOTH ENT.WireDebugName = "Prop Spawner" if CLIENT then return end -- No more client local GlobalUndoList = {} hook.Add("EntityRemoved", "wire_spawner_EntityRemoved", function(ent) if not GlobalUndoList[ent] then return end GlobalUndoList[ent]:CheckEnts(ent) GlobalUndoList[ent] = nil end) local function MakePropNoEffect(...) local backup = DoPropSpawnedEffect DoPropSpawnedEffect = function() end local ret = MakeProp(...) DoPropSpawnedEffect = backup return ret end function ENT:Initialize() self:SetMoveType( MOVETYPE_NONE ) self:PhysicsInit( SOLID_VPHYSICS ) self:SetCollisionGroup( COLLISION_GROUP_WEAPON ) self:DrawShadow( false ) local phys = self:GetPhysicsObject() if (phys:IsValid()) then phys:Wake() end self.UndoList = {} -- Spawner is "edge-triggered" self.SpawnLastValue = 0 self.UndoLastValue = 0 -- Made more efficient by updating the overlay text and -- Wire output only when number of active props changes (TheApathetic) self.CurrentPropCount = 0 -- Add inputs/outputs (TheApathetic) self.Inputs = WireLib.CreateSpecialInputs(self, { "Spawn", "Undo", "UndoEnt", "SpawnEffect" }, { "NORMAL", "NORMAL", "ENTITY", "NORMAL" }) self.Outputs = WireLib.CreateSpecialOutputs(self, { "Out", "LastSpawned", "Props" }, { "NORMAL", "ENTITY", "ARRAY" }) Wire_TriggerOutput(self, "Props", self.UndoList) end function ENT:Setup( delay, undo_delay, spawn_effect, mat, r, g, b, a, skin ) self.delay = delay self.undo_delay = undo_delay self.spawn_effect = spawn_effect if r then self.mat = mat self.r = r self.g = g self.b = b self.a = a self.skin = skin self:SetRenderMode(3) self:SetMaterial(mat or "") self:SetSkin(skin or 0) self:SetColor(Color(r or 255, g or 255, b or 255, 100)) end self:ShowOutput() end function ENT:DoSpawn( pl, down ) local ent = self if (not ent:IsValid()) then return end local phys = ent:GetPhysicsObject() if (not phys:IsValid()) then return end local Pos = ent:GetPos() local Ang = ent:GetAngles() local model = ent:GetModel() local prop = nil if self.spawn_effect ~= 0 then prop = MakeProp( pl, Pos, Ang, model, {}, {} ) else prop = MakePropNoEffect( pl, Pos, Ang, model, {}, {} ) end if not IsValid(prop) then return end prop:SetMaterial( ent:GetMaterial() ) prop:SetColor(Color(self.r, self.g, self.b, self.a)) prop:SetSkin( ent:GetSkin() or 0 ) -- apply the physic's objects properties local phys2 = prop:GetPhysicsObject() phys2:SetMass( phys:GetMass() ) -- known issue: while being held with the physgun, the spawner spawns 45k mass props. Could be worked around with a Think hook, but nah... if not ent:IsPlayerHolding() then -- minge protection :) phys2:SetVelocity( phys:GetVelocity() ) phys2:AddAngleVelocity( phys:GetAngleVelocity() - phys2:GetAngleVelocity() ) -- No SetAngleVelocity, so we must subtract the current angular velocity end local nocollide = constraint.NoCollide( prop, ent, 0, 0 ) if (nocollide:IsValid()) then prop:DeleteOnRemove( nocollide ) end undo.Create("Prop") undo.AddEntity( prop ) undo.AddEntity( nocollide ) undo.SetPlayer( pl ) undo.Finish() -- Check if the player is NULL (ab0mbs) if IsValid(pl) then pl:AddCleanup( "props", prop ) pl:AddCleanup( "props", nocollide ) end table.insert( self.UndoList, 1, prop ) GlobalUndoList[prop] = self Wire_TriggerOutput(self, "LastSpawned", prop) self.CurrentPropCount = #self.UndoList Wire_TriggerOutput(self, "Out", self.CurrentPropCount) Wire_TriggerOutput(self, "Props", self.UndoList) self:ShowOutput() if (self.undo_delay == 0) then return end timer.Simple( self.undo_delay, function() if prop:IsValid() then prop:Remove() end end ) end function ENT:DoUndo( pl ) if not next(self.UndoList) then return end local ent = table.remove(self.UndoList, #self.UndoList) if not IsValid(ent) then return self:DoUndo(pl) end ent:Remove() WireLib.AddNotify(pl, "Undone Prop", NOTIFY_UNDO, 2 ) end function ENT:DoUndoEnt( pl, ent ) if not IsValid(ent) then return end if GlobalUndoList[ent] ~= self then return end ent:Remove() WireLib.AddNotify(pl, "Undone Prop", NOTIFY_UNDO, 2 ) end function ENT:CheckEnts(removed_entity) -- Purge list of no longer existing props for i = #self.UndoList,1,-1 do local ent = self.UndoList[i] if not IsValid(ent) or ent == removed_entity then table.remove(self.UndoList, i) end end -- Check to see if active prop count has changed if (#self.UndoList ~= self.CurrentPropCount) then self.CurrentPropCount = #self.UndoList Wire_TriggerOutput(self, "Out", self.CurrentPropCount) Wire_TriggerOutput(self, "Props", self.UndoList) self:ShowOutput() end end function ENT:TriggerInput(iname, value) local pl = self:GetPlayer() if (iname == "Spawn") then -- Spawner is "edge-triggered" (TheApathetic) local SpawnThisValue = value > 0 if (SpawnThisValue == self.SpawnLastValue) then return end self.SpawnLastValue = SpawnThisValue if (SpawnThisValue) then -- Simple copy/paste of old numpad Spawn with a few modifications if (self.delay == 0) then self:DoSpawn( pl ) return end local TimedSpawn = function ( ent, pl ) if not IsValid(ent) then return end ent:DoSpawn( pl ) end timer.Simple( self.delay, function() TimedSpawn(self, pl) end ) end elseif (iname == "Undo") then -- Same here local UndoThisValue = value > 0 if (UndoThisValue == self.UndoLastValue) then return end self.UndoLastValue = UndoThisValue if (UndoThisValue) then self:DoUndo(pl) end elseif (iname == "UndoEnt") then self:DoUndoEnt(pl, value) elseif (iname == "SpawnEffect") then self.spawn_effect = value end end function ENT:ShowOutput() self:SetOverlayText("Spawn Delay: "..self.delay.."\nUndo Delay: "..self.undo_delay.."\nActive Props: "..self.CurrentPropCount) end function ENT:OnRemove() -- unregister spawned props from GlobalUndoList for _,ent in ipairs(self.UndoList) do GlobalUndoList[ent] = nil end end duplicator.RegisterEntityClass("gmod_wire_spawner", WireLib.MakeWireEnt, "Data", "delay", "undo_delay", "spawn_effect", "mat", "r", "g", "b", "a", "skin")
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Prop Spawner" ENT.RenderGroup = RENDERGROUP_BOTH ENT.WireDebugName = "Prop Spawner" if CLIENT then return end -- No more client local wire_spawner_delay = CreateConVar( "wire_spawner_delay", game.SinglePlayer() and 0 or 0.2 ) local GlobalUndoList = {} hook.Add("EntityRemoved", "wire_spawner_EntityRemoved", function(ent) if not GlobalUndoList[ent] then return end GlobalUndoList[ent]:CheckEnts(ent) GlobalUndoList[ent] = nil end) local function MakePropNoEffect(...) local backup = DoPropSpawnedEffect DoPropSpawnedEffect = function() end local ret = MakeProp(...) DoPropSpawnedEffect = backup return ret end function ENT:Initialize() self:SetMoveType( MOVETYPE_NONE ) self:PhysicsInit( SOLID_VPHYSICS ) self:SetCollisionGroup( COLLISION_GROUP_WEAPON ) self:DrawShadow( false ) self:SetTrigger( true ) -- enables receiving StartTouch/EndTouch calls self.DisabledByTouch = false self.DisabledByTimeUntil = CurTime() local phys = self:GetPhysicsObject() if (phys:IsValid()) then phys:Wake() end self.UndoList = {} -- Spawner is "edge-triggered" self.SpawnLastValue = 0 self.UndoLastValue = 0 -- Made more efficient by updating the overlay text and -- Wire output only when number of active props changes (TheApathetic) self.CurrentPropCount = 0 -- Add inputs/outputs (TheApathetic) self.Inputs = WireLib.CreateSpecialInputs(self, { "Spawn", "Undo", "UndoEnt", "SpawnEffect" }, { "NORMAL", "NORMAL", "ENTITY", "NORMAL" }) self.Outputs = WireLib.CreateSpecialOutputs(self, { "Out", "LastSpawned", "Props" }, { "NORMAL", "ENTITY", "ARRAY" }) Wire_TriggerOutput(self, "Props", self.UndoList) end function ENT:Setup( delay, undo_delay, spawn_effect, mat, r, g, b, a, skin ) self.delay = delay self.undo_delay = undo_delay self.spawn_effect = spawn_effect if r then self.mat = mat self.r = r self.g = g self.b = b self.a = a self.skin = skin self:SetRenderMode(3) self:SetMaterial(mat or "") self:SetSkin(skin or 0) self:SetColor(Color(r or 255, g or 255, b or 255, 100)) end self:ShowOutput() end function ENT:StartTouch( ent ) -- we handle touch blocking in DoSpawn, as otherwise we can get -- a StartTouch before we've added the prop to our local undo list. end function ENT:EndTouch( ent ) if ent.PropSpawner == self then self.DisabledByTouch = false end end function ENT:DoSpawn( pl, down ) if self.DisabledByTouch or self.DisabledByTimeUntil > CurTime() then return end local ent = self if (not ent:IsValid()) then return end local phys = ent:GetPhysicsObject() if (not phys:IsValid()) then return end local Pos = ent:GetPos() local Ang = ent:GetAngles() local model = ent:GetModel() local prop = nil if self.spawn_effect ~= 0 then prop = MakeProp( pl, Pos, Ang, model, {}, {} ) else prop = MakePropNoEffect( pl, Pos, Ang, model, {}, {} ) end if not IsValid(prop) then return end prop:SetMaterial( ent:GetMaterial() ) prop:SetColor(Color(self.r, self.g, self.b, self.a)) prop:SetSkin( ent:GetSkin() or 0 ) prop.PropSpawner = self -- apply the physic's objects properties local phys2 = prop:GetPhysicsObject() phys2:SetMass( phys:GetMass() ) -- known issue: while being held with the physgun, the spawner spawns 45k mass props. Could be worked around with a Think hook, but nah... if not ent:IsPlayerHolding() then -- minge protection :) phys2:SetVelocity( phys:GetVelocity() ) phys2:AddAngleVelocity( phys:GetAngleVelocity() - phys2:GetAngleVelocity() ) -- No SetAngleVelocity, so we must subtract the current angular velocity end local nocollide = constraint.NoCollide( prop, ent, 0, 0 ) if (nocollide:IsValid()) then prop:DeleteOnRemove( nocollide ) end undo.Create("Prop") undo.AddEntity( prop ) undo.AddEntity( nocollide ) undo.SetPlayer( pl ) undo.Finish() -- Check if the player is NULL (ab0mbs) if IsValid(pl) then pl:AddCleanup( "props", prop ) pl:AddCleanup( "props", nocollide ) end table.insert( self.UndoList, 1, prop ) GlobalUndoList[prop] = self Wire_TriggerOutput(self, "LastSpawned", prop) self.CurrentPropCount = #self.UndoList Wire_TriggerOutput(self, "Out", self.CurrentPropCount) Wire_TriggerOutput(self, "Props", self.UndoList) self:ShowOutput() self.DisabledByTouch = true self.DisabledByTimeUntil = CurTime() + wire_spawner_delay:GetFloat() if (self.undo_delay == 0) then return end timer.Simple( self.undo_delay, function() if prop:IsValid() then prop:Remove() end end ) end function ENT:DoUndo( pl ) if not next(self.UndoList) then return end local ent = table.remove(self.UndoList, #self.UndoList) if not IsValid(ent) then return self:DoUndo(pl) end ent:Remove() WireLib.AddNotify(pl, "Undone Prop", NOTIFY_UNDO, 2 ) end function ENT:DoUndoEnt( pl, ent ) if not IsValid(ent) then return end if GlobalUndoList[ent] ~= self then return end ent:Remove() WireLib.AddNotify(pl, "Undone Prop", NOTIFY_UNDO, 2 ) end function ENT:CheckEnts(removed_entity) -- Purge list of no longer existing props for i = #self.UndoList,1,-1 do local ent = self.UndoList[i] if not IsValid(ent) or ent == removed_entity then table.remove(self.UndoList, i) end end -- Check to see if active prop count has changed if (#self.UndoList ~= self.CurrentPropCount) then self.CurrentPropCount = #self.UndoList Wire_TriggerOutput(self, "Out", self.CurrentPropCount) Wire_TriggerOutput(self, "Props", self.UndoList) self:ShowOutput() end end function ENT:TriggerInput(iname, value) local pl = self:GetPlayer() if (iname == "Spawn") then -- Spawner is "edge-triggered" (TheApathetic) local SpawnThisValue = value > 0 if (SpawnThisValue == self.SpawnLastValue) then return end self.SpawnLastValue = SpawnThisValue if (SpawnThisValue) then -- Simple copy/paste of old numpad Spawn with a few modifications if (self.delay == 0) then self:DoSpawn( pl ) return end local TimedSpawn = function ( ent, pl ) if not IsValid(ent) then return end ent:DoSpawn( pl ) end timer.Simple( self.delay, function() TimedSpawn(self, pl) end ) end elseif (iname == "Undo") then -- Same here local UndoThisValue = value > 0 if (UndoThisValue == self.UndoLastValue) then return end self.UndoLastValue = UndoThisValue if (UndoThisValue) then self:DoUndo(pl) end elseif (iname == "UndoEnt") then self:DoUndoEnt(pl, value) elseif (iname == "SpawnEffect") then self.spawn_effect = value end end function ENT:ShowOutput() self:SetOverlayText("Spawn Delay: "..self.delay.."\nUndo Delay: "..self.undo_delay.."\nActive Props: "..self.CurrentPropCount) end function ENT:OnRemove() -- unregister spawned props from GlobalUndoList for _,ent in ipairs(self.UndoList) do GlobalUndoList[ent] = nil end end duplicator.RegisterEntityClass("gmod_wire_spawner", WireLib.MakeWireEnt, "Data", "delay", "undo_delay", "spawn_effect", "mat", "r", "g", "b", "a", "skin")
Fix #553. Nerf the prop spawner.
Fix #553. Nerf the prop spawner. It now can't spawn props if one of its spawned props is already inside it, or after a fixed delay (controlled by convar wire_spawner_delay).
Lua
apache-2.0
NezzKryptic/Wire,garrysmodlua/wire,immibis/wiremod,plinkopenguin/wiremod,thegrb93/wire,sammyt291/wire,bigdogmat/wire,notcake/wire,mms92/wire,Grocel/wire,Python1320/wire,rafradek/wire,CaptainPRICE/wire,dvdvideo1234/wire,wiremod/wire,mitterdoo/wire
9a72ae7d82f622ea051a101b5c5918147be03a65
prosody-modules/mod_auth_external.lua
prosody-modules/mod_auth_external.lua
-- -- Prosody IM -- Copyright (C) 2010 Waqas Hussain -- Copyright (C) 2010 Jeff Mitchell -- Copyright (C) 2013 Mikael Nordfeldth -- Copyright (C) 2013 Matthew Wild, finally came to fix it all -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local usermanager = require "core.usermanager"; local new_sasl = require "util.sasl".new; local server = require "net.server"; local have_async, async = pcall(require, "util.async"); local log = module._log; local host = module.host; local script_type = module:get_option_string("external_auth_protocol", "generic"); local command = module:get_option_string("external_auth_command", ""); local read_timeout = module:get_option_number("external_auth_timeout", 5); local blocking = module:get_option_boolean("external_auth_blocking", not(have_async and server.event and lpty.getfd)); local auth_processes = module:get_option_number("external_auth_processes", 1); local lpty, pty_options; if command:sub(1,1) == "@" then -- Use a socket connection lpty = module:require "pseudolpty"; log("info", "External auth with pseudolpty socket to %s", command:sub(2)); pty_options = { log = log }; else lpty = assert(require "lpty", "mod_auth_external requires lpty: https://modules.prosody.im/mod_auth_external.html#installation"); log("info", "External auth with pty command %s", command); pty_options = { throw_errors = false, no_local_echo = true, use_path = false }; end assert(script_type == "ejabberd" or script_type == "generic", "Config error: external_auth_protocol must be 'ejabberd' or 'generic'"); assert(not host:find(":"), "Invalid hostname"); if not blocking then log("debug", "External auth in non-blocking mode, yay!") waiter, guard = async.waiter, async.guarder(); elseif auth_processes > 1 then log("warn", "external_auth_processes is greater than 1, but we are in blocking mode - reducing to 1"); auth_processes = 1; end local ptys = {}; for i = 1, auth_processes do ptys[i] = lpty.new(pty_options); end function module.unload() for i = 1, auth_processes do ptys[i]:endproc(); end end module:hook_global("server-cleanup", module.unload); local curr_process = 0; function send_query(text) curr_process = (curr_process%auth_processes)+1; local pty = ptys[curr_process]; local finished_with_pty if not blocking then finished_with_pty = guard(pty); -- Prevent others from crossing this line while we're busy end if not pty:hasproc() then local status, ret = pty:exitstatus(); if status and (status ~= "exit" or ret ~= 0) then log("warn", "Auth process exited unexpectedly with %s %d, restarting", status, ret or 0); return nil; end local ok, err = pty:startproc(command); if not ok then log("error", "Failed to start auth process '%s': %s", command, err); return nil; end log("debug", "Started auth process"); end pty:send(text); pty:flush("i"); if blocking then local response; response = pty:read(read_timeout); if response == text then response = pty:read(read_timeout); end return response; else local response; local wait, done = waiter(); server.addevent(pty:getfd(), server.event.EV_READ, function () response = pty:read(); if not response == text then done(); end return -1; end); wait(); finished_with_pty(); return response; end end function do_query(kind, username, password) if not username then return nil, "not-acceptable"; end local query = (password and "%s:%s:%s:%s" or "%s:%s:%s"):format(kind, username, host, password); local len = #query if len > 1000 then return nil, "policy-violation"; end if script_type == "ejabberd" then local lo = len % 256; local hi = (len - lo) / 256; query = string.char(hi, lo)..query; elseif script_type == "generic" then query = query..'\n'; end local response, err = send_query(query); if response then log("debug", "Response: %s", response ); end if not response then log("warn", "Error while waiting for result from auth process: %s", err or "unknown error"); elseif (script_type == "ejabberd" and response == "\0\2\0\0") or (script_type == "generic" and response:gsub("\r?\n$", "") == "0") then return nil, "not-authorized"; elseif (script_type == "ejabberd" and response == "\0\2\0\1") or (script_type == "generic" and response:gsub("\r?\n$", "") == "1") then return true; else log("warn", "Unable to interpret data from auth process, %s", (response:match("^error:") and response) or ("["..#response.." bytes]")); return nil, "internal-server-error"; end end local provider = {}; function provider.test_password(username, password) return do_query("auth", username, password); end function provider.set_password(username, password) return do_query("setpass", username, password); end function provider.user_exists(username) return do_query("isuser", username); end function provider.create_user(username, password) -- luacheck: ignore 212 return nil, "Account creation/modification not available."; end function provider.get_sasl_handler() local testpass_authentication_profile = { plain_test = function(sasl, username, password, realm) return usermanager.test_password(username, realm, password), true; end, }; return new_sasl(host, testpass_authentication_profile); end module:provides("auth", provider);
-- -- Prosody IM -- Copyright (C) 2010 Waqas Hussain -- Copyright (C) 2010 Jeff Mitchell -- Copyright (C) 2013 Mikael Nordfeldth -- Copyright (C) 2013 Matthew Wild, finally came to fix it all -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local usermanager = require "core.usermanager"; local new_sasl = require "util.sasl".new; local server = require "net.server"; local have_async, async = pcall(require, "util.async"); local log = module._log; local host = module.host; local script_type = module:get_option_string("external_auth_protocol", "generic"); local command = module:get_option_string("external_auth_command", ""); local read_timeout = module:get_option_number("external_auth_timeout", 5); local auth_processes = module:get_option_number("external_auth_processes", 1); local lpty, pty_options; if command:sub(1,1) == "@" then -- Use a socket connection lpty = module:require "pseudolpty"; log("info", "External auth with pseudolpty socket to %s", command:sub(2)); pty_options = { log = log }; else lpty = assert(require "lpty", "mod_auth_external requires lpty: https://modules.prosody.im/mod_auth_external.html#installation"); log("info", "External auth with pty command %s", command); pty_options = { throw_errors = false, no_local_echo = true, use_path = false }; end local blocking = module:get_option_boolean("external_auth_blocking", not(have_async and server.event and lpty.getfd)); assert(script_type == "ejabberd" or script_type == "generic", "Config error: external_auth_protocol must be 'ejabberd' or 'generic'"); assert(not host:find(":"), "Invalid hostname"); if not blocking then log("debug", "External auth in non-blocking mode, yay!") waiter, guard = async.waiter, async.guarder(); elseif auth_processes > 1 then log("warn", "external_auth_processes is greater than 1, but we are in blocking mode - reducing to 1"); auth_processes = 1; end local ptys = {}; for i = 1, auth_processes do ptys[i] = lpty.new(pty_options); end function module.unload() for i = 1, auth_processes do ptys[i]:endproc(); end end module:hook_global("server-cleanup", module.unload); local curr_process = 0; function send_query(text) curr_process = (curr_process%auth_processes)+1; local pty = ptys[curr_process]; local finished_with_pty if not blocking then finished_with_pty = guard(pty); -- Prevent others from crossing this line while we're busy end if not pty:hasproc() then local status, ret = pty:exitstatus(); if status and (status ~= "exit" or ret ~= 0) then log("warn", "Auth process exited unexpectedly with %s %d, restarting", status, ret or 0); return nil; end local ok, err = pty:startproc(command); if not ok then log("error", "Failed to start auth process '%s': %s", command, err); return nil; end log("debug", "Started auth process"); end pty:send(text); pty:flush("i"); if blocking then local response; response = pty:read(read_timeout); if response == text then response = pty:read(read_timeout); end return response; else local response; local wait, done = waiter(); server.addevent(pty:getfd(), server.event.EV_READ, function () response = pty:read(); if not response == text then done(); end return -1; end); wait(); finished_with_pty(); return response; end end function do_query(kind, username, password) if not username then return nil, "not-acceptable"; end local query = (password and "%s:%s:%s:%s" or "%s:%s:%s"):format(kind, username, host, password); local len = #query if len > 1000 then return nil, "policy-violation"; end if script_type == "ejabberd" then local lo = len % 256; local hi = (len - lo) / 256; query = string.char(hi, lo)..query; elseif script_type == "generic" then query = query..'\n'; end local response, err = send_query(query); if response then log("debug", "Response: %s", response ); end if not response then log("warn", "Error while waiting for result from auth process: %s", err or "unknown error"); elseif (script_type == "ejabberd" and response == "\0\2\0\0") or (script_type == "generic" and response:gsub("\r?\n$", "") == "0") then return nil, "not-authorized"; elseif (script_type == "ejabberd" and response == "\0\2\0\1") or (script_type == "generic" and response:gsub("\r?\n$", "") == "1") then return true; else log("warn", "Unable to interpret data from auth process, %s", (response:match("^error:") and response) or ("["..#response.." bytes]")); return nil, "internal-server-error"; end end local provider = {}; function provider.test_password(username, password) return do_query("auth", username, password); end function provider.set_password(username, password) return do_query("setpass", username, password); end function provider.user_exists(username) return do_query("isuser", username); end function provider.create_user(username, password) -- luacheck: ignore 212 return nil, "Account creation/modification not available."; end function provider.get_sasl_handler() local testpass_authentication_profile = { plain_test = function(sasl, username, password, realm) return usermanager.test_password(username, realm, password), true; end, }; return new_sasl(host, testpass_authentication_profile); end module:provides("auth", provider);
Fix "attempt to index global 'lpty' (a nil value)" on Prosody 0.11
Fix "attempt to index global 'lpty' (a nil value)" on Prosody 0.11 In reference to https://github.com/jsxc/xmpp-cloud-auth/issues/74 Moved line 23 below line 36. I guess it's because Prosody 0.11 supports async while 0.10 does not.
Lua
mit
jsxc/xmpp-cloud-auth,jsxc/xmpp-cloud-auth,jsxc/xmpp-cloud-auth,jsxc/xmpp-cloud-auth
342b0ed11f771fc3157efdd37a6450267fc064f3
scripts/bimg.lua
scripts/bimg.lua
-- -- Copyright 2010-2017 Branimir Karadzic. All rights reserved. -- License: https://github.com/bkaradzic/bx#license-bsd-2-clause -- project "bimg" kind "StaticLib" includedirs { path.join(BX_DIR, "include"), path.join(BIMG_DIR, "include"), } files { path.join(BIMG_DIR, "src/image.*"), } project "bimg_decode" kind "StaticLib" includedirs { path.join(BX_DIR, "include"), path.join(BIMG_DIR, "include"), path.join(BIMG_DIR, "3rdparty"), path.join(BIMG_DIR, "3rdparty/nvtt"), path.join(BIMG_DIR, "3rdparty/iqa/include"), } files { path.join(BIMG_DIR, "src/image_decode.*"), } project "bimg_encode" kind "StaticLib" includedirs { path.join(BX_DIR, "include"), path.join(BIMG_DIR, "include"), path.join(BIMG_DIR, "3rdparty"), path.join(BIMG_DIR, "3rdparty/nvtt"), path.join(BIMG_DIR, "3rdparty/iqa/include"), } files { path.join(BIMG_DIR, "src/image_encode.*"), path.join(BIMG_DIR, "3rdparty/libsquish/**.cpp"), path.join(BIMG_DIR, "3rdparty/libsquish/**.h"), path.join(BIMG_DIR, "3rdparty/edtaa3/**.cpp"), path.join(BIMG_DIR, "3rdparty/edtaa3/**.h"), path.join(BIMG_DIR, "3rdparty/etc1/**.cpp"), path.join(BIMG_DIR, "3rdparty/etc1/**.h"), path.join(BIMG_DIR, "3rdparty/etc2/**.cpp"), path.join(BIMG_DIR, "3rdparty/etc2/**.hpp"), path.join(BIMG_DIR, "3rdparty/nvtt/**.cpp"), path.join(BIMG_DIR, "3rdparty/nvtt/**.h"), path.join(BIMG_DIR, "3rdparty/pvrtc/**.cpp"), path.join(BIMG_DIR, "3rdparty/pvrtc/**.h"), path.join(BIMG_DIR, "3rdparty/tinyexr/**.h"), path.join(BIMG_DIR, "3rdparty/iqa/include/**.h"), path.join(BIMG_DIR, "3rdparty/iqa/source/**.c"), }
-- -- Copyright 2010-2017 Branimir Karadzic. All rights reserved. -- License: https://github.com/bkaradzic/bx#license-bsd-2-clause -- project "bimg" kind "StaticLib" includedirs { path.join(BX_DIR, "include"), path.join(BIMG_DIR, "include"), } files { path.join(BIMG_DIR, "src/image.*"), } configuration { "linux-*" } buildoptions { "-fPIC", } configuration {} project "bimg_decode" kind "StaticLib" includedirs { path.join(BX_DIR, "include"), path.join(BIMG_DIR, "include"), path.join(BIMG_DIR, "3rdparty"), path.join(BIMG_DIR, "3rdparty/nvtt"), path.join(BIMG_DIR, "3rdparty/iqa/include"), } files { path.join(BIMG_DIR, "src/image_decode.*"), } configuration { "linux-*" } buildoptions { "-fPIC", } configuration {} project "bimg_encode" kind "StaticLib" includedirs { path.join(BX_DIR, "include"), path.join(BIMG_DIR, "include"), path.join(BIMG_DIR, "3rdparty"), path.join(BIMG_DIR, "3rdparty/nvtt"), path.join(BIMG_DIR, "3rdparty/iqa/include"), } files { path.join(BIMG_DIR, "src/image_encode.*"), path.join(BIMG_DIR, "3rdparty/libsquish/**.cpp"), path.join(BIMG_DIR, "3rdparty/libsquish/**.h"), path.join(BIMG_DIR, "3rdparty/edtaa3/**.cpp"), path.join(BIMG_DIR, "3rdparty/edtaa3/**.h"), path.join(BIMG_DIR, "3rdparty/etc1/**.cpp"), path.join(BIMG_DIR, "3rdparty/etc1/**.h"), path.join(BIMG_DIR, "3rdparty/etc2/**.cpp"), path.join(BIMG_DIR, "3rdparty/etc2/**.hpp"), path.join(BIMG_DIR, "3rdparty/nvtt/**.cpp"), path.join(BIMG_DIR, "3rdparty/nvtt/**.h"), path.join(BIMG_DIR, "3rdparty/pvrtc/**.cpp"), path.join(BIMG_DIR, "3rdparty/pvrtc/**.h"), path.join(BIMG_DIR, "3rdparty/tinyexr/**.h"), path.join(BIMG_DIR, "3rdparty/iqa/include/**.h"), path.join(BIMG_DIR, "3rdparty/iqa/source/**.c"), } configuration { "linux-*" } buildoptions { "-fPIC", } configuration {}
Fixed shared lib build.
Fixed shared lib build.
Lua
bsd-2-clause
bkaradzic/bimg,bkaradzic/bimg
cc25601b2f1b999cc7ecbc750efb132176cd60aa
home/lib/mpm/rstools.lua
home/lib/mpm/rstools.lua
----------------------------------------------------- --name : home/lib/mpm/rstools.lua --description: a library that makes working with redstone easier --author : mpmxyz --github page: https://github.com/mpmxyz/ocprograms --forum page : http://oc.cil.li/index.php?/topic/ ----------------------------------------------------- local component = require("component") local sides = require("sides") local colors = require("colors") local rstools = {} local function invert(value) if type(value) == "number" then return (value > 0) and 0 or math.huge elseif type(value) == "boolean" then return not value elseif type(value) == "table" then local inverted = {} for i = 0, 15 do inverted[i] = invert(value[i]) end return inverted elseif value then --to cause errors when using wrong types return value end end local function toDigital(value) if type(value) == "table" then local newValue = {} for i = 0, 15 do newValue[i] = toDigital(value[i]) end return newValue elseif type(value) == "number" then return (value > 0) end end local function toAnalog(value) if type(value) == "table" then local newValue = {} for i = 0, 15 do newValue[i] = toAnalog(value[i]) end return newValue elseif type(value) == "boolean" then return value and math.huge or 0 end end local function append(value, a, ...) if a ~= nil then return a, append(value, ...) else return value end end local function wrapGetterSetter(getter, setter, ...) local args = table.pack(...) return function(value) if value == nil then return getter(table.unpack(args, 1, args.n)) elseif setter then return setter(append(value, table.unpack(args, 1, args.n))) else error("read only connection", 2) end end end local function wrapProxyFunctions(proxy, getterName, setterName, ...) return wrapGetterSetter(proxy[getterName], proxy[setterName], ...) end local function wrapAnalog(typ, address, side, color) local proxy = component.proxy(address) local args, infix local getterName, setterName if side == "wireless" then args = {} infix = "Wireless" else if type(side) == "string" then side = sides[side] assert(type(side) == "number", "invalid side") end if color then if type(color) == "string" then if color == "all" then color = nil else color = colors[color] assert(type(color) == "number", "invalid color") end end args = {side, color} infix = "Bundled" else args = {side} infix = "" end end if typ == "input" then getterName = "get#Input" setterName = "" --> becomes nil else getterName = "get#Output" setterName = "set#Output" end return wrapProxyFunctions(proxy, getterName:gsub("#", infix), setterName:gsub("#", infix), table.unpack(args)) end local methods = {} function methods:toggle() return self(invert(self())) end function methods:pulse(duration, value) checkArg(1, duration, "number") local oldValue = self() if value == nil then value = invert(oldValue) end self(value) os.sleep(duration) return self(oldValue) end local function newTable(f) local normal = setmetatable({}, { __index = methods, __call = function(_, value) return f(value) end, }) local inverted = setmetatable({}, { __index = methods, __call = function(_, value) return inverted(f(inverted(value))) end, }) normal.inverted = inverted inverted.inverted = normal return normal end function rstools.analog(typ, address, side, color) checkArg(1, typ, "string") checkArg(2, address, "string") checkArg(3, side, "number", "string") checkArg(4, color, "number", "string", "nil") local funcAnalog = wrapAnalog(typ, address, side, color) local permittedType = (color == "all") and "table" or "boolean" return newTable(function(value) checkArg(1, value, permittedType, "nil") value = funcAnalog(value) return value end) end function rstools.digital(typ, address, side, color) checkArg(1, typ, "string") checkArg(2, address, "string") checkArg(3, side, "number", "string") checkArg(4, color, "number", "string", "nil") local funcAnalog = wrapAnalog(typ, address, side, color) local permittedType = (color == "all") and "table" or "boolean" return newTable(function(value) checkArg(1, value, permittedType, "nil") return toDigital(funcAnalog(toAnalog(value))) end) end return rstools
----------------------------------------------------- --name : home/lib/mpm/rstools.lua --description: a library that makes working with redstone easier --author : mpmxyz --github page: https://github.com/mpmxyz/ocprograms --forum page : http://oc.cil.li/index.php?/topic/ ----------------------------------------------------- local component = require("component") local sides = require("sides") local colors = require("colors") local rstools = {} local function invert(value) if type(value) == "number" then return (value > 0) and 0 or math.huge elseif type(value) == "boolean" then return not value elseif type(value) == "table" then local inverted = {} for i = 0, 15 do inverted[i] = invert(value[i]) end return inverted elseif value then --to cause errors when using wrong types return value end end local function toDigital(value) if type(value) == "table" then local newValue = {} for i = 0, 15 do newValue[i] = toDigital(value[i]) end return newValue elseif type(value) == "number" then return (value > 0) end end local function toAnalog(value) if type(value) == "table" then local newValue = {} for i = 0, 15 do newValue[i] = toAnalog(value[i]) end return newValue elseif type(value) == "boolean" then return value and math.huge or 0 end end local function wrapTransform(f, input, output) return function(...) return output(f(input(...))) end end local function append(value, a, ...) if a ~= nil then return a, append(value, ...) else return value end end local function wrapGetterSetter(getter, setter, args) return function(value) if value == nil then return getter(table.unpack(args)) elseif setter then return setter(append(value, table.unpack(args))) else error("read only connection", 2) end end end local function wrapProxyFunctions(proxy, getterName, setterName, args) return wrapGetterSetter(proxy[getterName], proxy[setterName], args) end local function wrapRaw(typ, address, side, color) local proxy = (type(address) == "table") and address or component.proxy(address) local args, infix local getterName, setterName if side == "wireless" then args = {} infix = "Wireless" else if type(side) == "string" then side = sides[side] assert(type(side) == "number", "invalid side") end if color then if type(color) == "string" then if color == "all" then color = nil else color = colors[color] assert(type(color) == "number", "invalid color") end end args = {side, color} infix = "Bundled" else args = {side} infix = "" end end if typ == "input" then getterName = "get#Input" setterName = "" --> becomes nil elseif typ == "output" then getterName = "get#Output" setterName = "set#Output" else error("Expected type 'input' or 'output'.") end return wrapProxyFunctions(proxy, getterName:gsub("#", infix), setterName:gsub("#", infix), args) end local methods = {} function methods:toggle() return self(invert(self())) end function methods:pulse(duration, value, oldValue) checkArg(1, duration, "number") if oldValue == nil then oldValue = self() end if value == nil then value = invert(oldValue) end self(value) os.sleep(duration) return self(oldValue) end local function newTable(f, typ) local isOutput = (typ == "output") local normal = setmetatable({}, { __index = isOutput and methods or nil, __call = function(_, value) return f(value) end, }) local inverted = setmetatable({}, { __index = isOutput and methods or nil, __call = function(_, value) return invert(f(invert(value))) end, }) normal.inverted = inverted inverted.inverted = normal return normal end --rstools.analog("input"/"output", address/proxy, side/"wireless", color) -> object --object(value) -> sets output --object() -> returns current input/output --object.inverted -> object with inverted inputs/outputs (only useful for digital interfaces) --object:toggle() -> toggles output (only useful for digital interfaces) --object:pulse(duration, value[, original]) -> overrides output value for 'duration' seconds, then restores original value function rstools.analog(typ, address, side, color) checkArg(1, typ, "string") checkArg(2, address, "string", "table") checkArg(3, side, "number", "string") checkArg(4, color, "number", "string", "nil") local func = wrapRaw(typ, address, side, color) if side == "wireless" then func = wrapTransform(func, toDigital, toAnalog) end local permittedType = (color == "all") and "table" or "number" return newTable(function(value) checkArg(1, value, permittedType, "nil") return (func(value)) end, typ) end --rstools.analog("input"/"output", address/proxy, side/"wireless", color) -> object --object(value) -> sets output --object() -> returns current input/output --object.inverted -> object with inverted inputs/outputs (only useful for digital interfaces) --object:toggle() -> toggles output (only useful for digital interfaces) --object:pulse(duration, value[, original]) -> overrides output value for 'duration' seconds, then restores original value function rstools.digital(typ, address, side, color) checkArg(1, typ, "string") checkArg(2, address, "string", "table") checkArg(3, side, "number", "string") checkArg(4, color, "number", "string", "nil") local func = wrapRaw(typ, address, side, color) if side ~= "wireless" then func = wrapTransform(func, toAnalog, toDigital) end local permittedType = (color == "all") and "table" or "boolean" return newTable(function(value) checkArg(1, value, permittedType, "nil") return (func(value)) end) end return rstools
mpm.rstools: fixed some bugs, "address" can now be a proxy table, added documentation
mpm.rstools: fixed some bugs, "address" can now be a proxy table, added documentation
Lua
mit
mpmxyz/ocprograms
ee610b780b6891bc68da151f809a7a4111fe24dd
spec/plugins/basicauth/access_spec.lua
spec/plugins/basicauth/access_spec.lua
local spec_helper = require "spec.spec_helpers" local http_client = require "kong.tools.http_client" local cjson = require "cjson" local STUB_GET_URL = spec_helper.STUB_GET_URL local STUB_POST_URL = spec_helper.STUB_POST_URL describe("Authentication Plugin", function() setup(function() spec_helper.prepare_db() spec_helper.insert_fixtures { api = { {name = "tests basicauth", public_dns = "basicauth.com", target_url = "http://mockbin.org"} }, consumer = { {username = "basicauth_tests_consuser"} }, plugin_configuration = { {name = "basicauth", value = {}, __api = 1} }, basicauth_credential = { {username = "username", password = "password", __consumer = 1} } } spec_helper.start_kong() end) teardown(function() spec_helper.stop_kong() end) describe("Basic Authentication", function() it("should return invalid credentials when the credential is missing", function() local response, status = http_client.get(STUB_GET_URL, {}, {host = "basicauth.com"}) local body = cjson.decode(response) assert.equal(401, status) assert.equal("Unauthorized", body.message) end) it("should return invalid credentials when the credential value is wrong", function() local response, status = http_client.get(STUB_GET_URL, {}, {host = "basicauth.com", authorization = "asd"}) local body = cjson.decode(response) assert.equal(403, status) assert.equal("Invalid authentication credentials", body.message) end) it("should return invalid credentials when the credential value is wrong in proxy-authorization", function() local response, status = http_client.get(STUB_GET_URL, {}, {host = "basicauth.com", ["proxy-authorization"] = "asd"}) local body = cjson.decode(response) assert.equal(403, status) assert.equal("Invalid authentication credentials", body.message) end) it("should not pass when passing only the password", function() local response, status = http_client.get(STUB_GET_URL, {}, {host = "basicauth.com", authorization = "Basic OmFwaWtleTEyMw=="}) local body = cjson.decode(response) assert.equal(403, status) assert.equal("Invalid authentication credentials", body.message) end) it("should not pass when passing only the username", function() local response, status = http_client.get(STUB_GET_URL, {}, {host = "basicauth.com", authorization = "Basic dXNlcjEyMzo="}) local body = cjson.decode(response) assert.equal(403, status) assert.equal("Invalid authentication credentials", body.message) end) it("should reply 401 when authorization is missing", function() local response, status = http_client.get(STUB_GET_URL, {}, {host = "basicauth.com", authorization123 = "Basic dXNlcm5hbWU6cGFzc3dvcmQ="}) local body = cjson.decode(response) assert.equal(401, status) assert.equal("Unauthorized", body.message) end) it("should pass with GET", function() print(STUB_GET_URL) local response, status = http_client.get(STUB_GET_URL, {}, {host = "basicauth.com", authorization = "Basic dXNlcm5hbWU6cGFzc3dvcmQ="}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.equal("Basic dXNlcm5hbWU6cGFzc3dvcmQ=", parsed_response.headers.authorization) end) it("should pass with GET and proxy-authorization", function() local response, status = http_client.get(STUB_GET_URL, {}, {host = "basicauth.com", ["proxy-authorization"] = "Basic dXNlcm5hbWU6cGFzc3dvcmQ="}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.equal("Basic dXNlcm5hbWU6cGFzc3dvcmQ=", parsed_response.headers["proxy-authorization"]) end) it("should pass with POST", function() local response, status = http_client.post(STUB_POST_URL, {}, {host = "basicauth.com", authorization = "Basic dXNlcm5hbWU6cGFzc3dvcmQ="}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.equal("Basic dXNlcm5hbWU6cGFzc3dvcmQ=", parsed_response.headers.authorization) end) it("should pass with GET and valid authorization and wrong proxy-authorization", function() local response, status = http_client.get(STUB_GET_URL, {}, {host = "basicauth.com", ["proxy-authorization"] = "hello", authorization = "Basic dXNlcm5hbWU6cGFzc3dvcmQ="}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.equal("Basic dXNlcm5hbWU6cGFzc3dvcmQ=", parsed_response.headers["proxy-authorization"]) end) it("should pass with GET and invalid authorization and valid proxy-authorization", function() local response, status = http_client.get(STUB_GET_URL, {}, {host = "basicauth.com", authorization = "hello", ["proxy-authorization"] = "Basic dXNlcm5hbWU6cGFzc3dvcmQ="}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.equal("Basic dXNlcm5hbWU6cGFzc3dvcmQ=", parsed_response.headers["proxy-authorization"]) end) end) end)
local spec_helper = require "spec.spec_helpers" local http_client = require "kong.tools.http_client" local cjson = require "cjson" local PROXY_URL = spec_helper.PROXY_URL describe("Authentication Plugin", function() setup(function() spec_helper.prepare_db() spec_helper.insert_fixtures { api = { {name = "tests basicauth", public_dns = "basicauth.com", target_url = "http://httpbin.org"} }, consumer = { {username = "basicauth_tests_consuser"} }, plugin_configuration = { {name = "basicauth", value = {}, __api = 1} }, basicauth_credential = { {username = "username", password = "password", __consumer = 1} } } spec_helper.start_kong() end) teardown(function() spec_helper.stop_kong() end) describe("Basic Authentication", function() it("should return invalid credentials when the credential is missing", function() local response, status = http_client.get(PROXY_URL.."/get", {}, {host = "basicauth.com"}) local body = cjson.decode(response) assert.equal(401, status) assert.equal("Unauthorized", body.message) end) it("should return invalid credentials when the credential value is wrong", function() local response, status = http_client.get(PROXY_URL.."/get", {}, {host = "basicauth.com", authorization = "asd"}) local body = cjson.decode(response) assert.equal(403, status) assert.equal("Invalid authentication credentials", body.message) end) it("should return invalid credentials when the credential value is wrong in proxy-authorization", function() local response, status = http_client.get(PROXY_URL.."/get", {}, {host = "basicauth.com", ["proxy-authorization"] = "asd"}) local body = cjson.decode(response) assert.equal(403, status) assert.equal("Invalid authentication credentials", body.message) end) it("should not pass when passing only the password", function() local response, status = http_client.get(PROXY_URL.."/get", {}, {host = "basicauth.com", authorization = "Basic OmFwaWtleTEyMw=="}) local body = cjson.decode(response) assert.equal(403, status) assert.equal("Invalid authentication credentials", body.message) end) it("should not pass when passing only the username", function() local response, status = http_client.get(PROXY_URL.."/get", {}, {host = "basicauth.com", authorization = "Basic dXNlcjEyMzo="}) local body = cjson.decode(response) assert.equal(403, status) assert.equal("Invalid authentication credentials", body.message) end) it("should reply 401 when authorization is missing", function() local response, status = http_client.get(PROXY_URL.."/get", {}, {host = "basicauth.com", authorization123 = "Basic dXNlcm5hbWU6cGFzc3dvcmQ="}) local body = cjson.decode(response) assert.equal(401, status) assert.equal("Unauthorized", body.message) end) it("should pass with GET", function() local response, status = http_client.get(PROXY_URL.."/get", {}, {host = "basicauth.com", authorization = "Basic dXNlcm5hbWU6cGFzc3dvcmQ="}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.equal("Basic dXNlcm5hbWU6cGFzc3dvcmQ=", parsed_response.headers.Authorization) end) it("should pass with GET and proxy-authorization", function() local response, status = http_client.get(PROXY_URL.."/get", {}, {host = "basicauth.com", ["proxy-authorization"] = "Basic dXNlcm5hbWU6cGFzc3dvcmQ="}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.equal("Basic dXNlcm5hbWU6cGFzc3dvcmQ=", parsed_response.headers["Proxy-Authorization"]) end) it("should pass with POST", function() local response, status = http_client.post(PROXY_URL.."/post", {}, {host = "basicauth.com", authorization = "Basic dXNlcm5hbWU6cGFzc3dvcmQ="}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.equal("Basic dXNlcm5hbWU6cGFzc3dvcmQ=", parsed_response.headers.Authorization) end) it("should pass with GET and valid authorization and wrong proxy-authorization", function() local response, status = http_client.get(PROXY_URL.."/get", {}, {host = "basicauth.com", ["proxy-authorization"] = "hello", authorization = "Basic dXNlcm5hbWU6cGFzc3dvcmQ="}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.equal("hello", parsed_response.headers["Proxy-Authorization"]) assert.equal("Basic dXNlcm5hbWU6cGFzc3dvcmQ=", parsed_response.headers.Authorization) end) it("should pass with GET and invalid authorization and valid proxy-authorization", function() local response, status = http_client.get(PROXY_URL.."/get", {}, {host = "basicauth.com", authorization = "hello", ["proxy-authorization"] = "Basic dXNlcm5hbWU6cGFzc3dvcmQ="}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.equal("Basic dXNlcm5hbWU6cGFzc3dvcmQ=", parsed_response.headers["Proxy-Authorization"]) end) end) end)
Fixing test
Fixing test
Lua
apache-2.0
peterayeni/kong
6a3145acab79dc0b1f2c4124ed13e9f8e355543f
deps/require.lua
deps/require.lua
if exports then exports.name = "luvit/require" exports.version = "0.2.1" end local luvi = require('luvi') local bundle = luvi.bundle local pathJoin = luvi.path.join local env = require('env') local os = require('ffi').os local uv = require('uv') local realRequire = _G.require local tmpBase = os == "Windows" and (env.get("TMP") or uv.cwd()) or (env.get("TMPDIR") or '/tmp') local binExt = os == "Windows" and ".dll" or ".so" -- Package sources -- $author/$name@$version -> resolves to hash, cached in memory -- bundle:full/bundle/path -- full/unix/path -- C:\\full\windows\path local fileCache = {} local function readFile(path) assert(path) local data = fileCache[path] if data ~= nil then return data end local prefix = path:match("^bundle:/*") if prefix then data = bundle.readfile(path:sub(#prefix + 1)) else local stat = uv.fs_stat(path) if stat and stat.type == "file" then local fd = uv.fs_open(path, "r", 511) if fd then data = uv.fs_read(fd, stat.size, -1) uv.fs_close(fd) end end end fileCache[path] = data and true or false return data end local dirCache = {} local function isDir(path) assert(path) local is = dirCache[path] if is ~= nil then return is end local prefix = path:match("^bundle:/*") local stat if prefix then stat = bundle.stat(path:sub(#prefix + 1)) else stat = uv.fs_stat(path) end is = stat and (stat.type == "directory") or false dirCache[path] = is return is end local types = { ".lua", binExt } local function fixedRequire(path) assert(path) local fullPath = path local data = readFile(fullPath) if not data then for i = 1, #types do fullPath = path .. types[i] data = readFile(fullPath) if data then break end fullPath = pathJoin(path, "init" .. types[i]) data = readFile(fullPath) if data then break end end if not data then return end end local prefix = fullPath:match("^bundle:") if prefix == "bundle:" and bundle.base then fullPath = fullPath:gsub(prefix, bundle.base) end return data, fullPath end local skips = {} local function moduleRequire(base, name) assert(base and name) while true do if not skips[base] then local mod, path if isDir(pathJoin(base, "libs")) then mod, path = fixedRequire(pathJoin(base, "libs", name)) if mod then return mod, path end end if isDir(pathJoin(base, "deps")) then mod, path = fixedRequire(pathJoin(base, "deps", name)) if mod then return mod, path end end end -- Stop at filesystem or prefix root (58 is ":") if base == "/" or base:byte(-1) == 58 then break end base = pathJoin(base, "..") end -- If we didn't find it outside the bundle, look inside the bundle. if not base:match("^bundle:/*") then return moduleRequire("bundle:", name) end end local moduleCache = {} local function generator(modulePath) assert(modulePath, "Missing path to require generator") -- Convert windows paths to unix paths (mostly) local path = modulePath:gsub("\\", "/") -- Normalize slashes around prefix to be exactly one after path = path:gsub("^/*([^/:]+:)/*", "%1/") local base = pathJoin(path, "..") local function resolve(name) assert(name, "Missing name to resolve") if name:byte(1) == 46 then -- Starts with "." return fixedRequire(pathJoin(base, name)) elseif name:byte(1) == 47 then -- Starts with "/" return fixedRequire(name) end return moduleRequire(base, name) end local function require(name) assert(name, "Missing name to require") if package.preload[name] or package.loaded[name] then return realRequire(name) end -- Resolve the path local success, data, path = xpcall(function () return resolve(name) end, debug.traceback) assert(success, data) -- local data, path = resolve(name) if not path then local success, value = pcall(realRequire, name) if success then return value end if not success then error("No such module '" .. name .. "' in '" .. modulePath .. "'") end end -- Check in the cache for this module local module = moduleCache[path] if module then return module.exports end -- Put a new module in the cache if not module = { path = path, dir = pathJoin(path, ".."), exports = {} } moduleCache[path] = module local ext = path:match("%.[^/]+$") if ext == ".lua" then local fn = assert(loadstring(data, path)) local global = { module = module, exports = module.exports } global.require, module.resolve = generator(path) setfenv(fn, setmetatable(global, { __index = _G })) local ret = fn() -- Allow returning the exports as well if ret then module.exports = ret end elseif ext == binExt then local fnName = "luaopen_" .. name:match("[^/]+$"):match("^[^%.]+") local fn if uv.fs_access(path, "r") then -- If it's a real file, load it directly fn = assert(package.loadlib(path, fnName)) else -- Otherwise, copy to a temporary folder and read from there local dir = assert(uv.fs_mkdtemp(pathJoin(tmpBase, "lib-XXXXXX"))) local fd = uv.fs_open(path, "w", 384) -- 0600 uv.fs_write(fd, data, 0) uv.fs_close(fd) fn = assert(package.loadlib(path, fnName)) uv.fs_unlink(path) uv.fs_rmdir(dir) end module.exports = fn() else error("Unknown type at '" .. path .. "' for '" .. name .. "' in '" .. modulePath .. "'") end return module.exports end return require, resolve, moduleCache end return generator
if exports then exports.name = "luvit/require" exports.version = "0.2.1" end local luvi = require('luvi') local bundle = luvi.bundle local pathJoin = luvi.path.join local env = require('env') local os = require('ffi').os local uv = require('uv') local realRequire = _G.require local tmpBase = os == "Windows" and (env.get("TMP") or uv.cwd()) or (env.get("TMPDIR") or '/tmp') local binExt = os == "Windows" and ".dll" or ".so" -- Package sources -- $author/$name@$version -> resolves to hash, cached in memory -- bundle:full/bundle/path -- full/unix/path -- C:\\full\windows\path local fileCache = {} local function readFile(path) assert(path) local data = fileCache[path] if data ~= nil then return data end local prefix = path:match("^bundle:/*") if prefix then data = bundle.readfile(path:sub(#prefix + 1)) else local stat = uv.fs_stat(path) if stat and stat.type == "file" then local fd = uv.fs_open(path, "r", 511) if fd then data = uv.fs_read(fd, stat.size, -1) uv.fs_close(fd) end end end fileCache[path] = data and true or false return data end local dirCache = {} local function isDir(path) assert(path) local is = dirCache[path] if is ~= nil then return is end local prefix = path:match("^bundle:/*") local stat if prefix then stat = bundle.stat(path:sub(#prefix + 1)) else stat = uv.fs_stat(path) end is = stat and (stat.type == "directory") or false dirCache[path] = is return is end local types = { ".lua", binExt } local function fixedRequire(path) assert(path) local fullPath = path local data = readFile(fullPath) if not data then for i = 1, #types do fullPath = path .. types[i] data = readFile(fullPath) if data then break end fullPath = pathJoin(path, "init" .. types[i]) data = readFile(fullPath) if data then break end end if not data then return end end local prefix = fullPath:match("^bundle:") local normalizedPath = fullPath if prefix == "bundle:" and bundle.base then normalizedPath = fullPath:gsub(prefix, bundle.base) end return data, fullPath, normalizedPath end local skips = {} local function moduleRequire(base, name) assert(base and name) while true do if not skips[base] then local mod, path, key if isDir(pathJoin(base, "libs")) then mod, path, key = fixedRequire(pathJoin(base, "libs", name)) if mod then return mod, path, key end end if isDir(pathJoin(base, "deps")) then mod, path, key = fixedRequire(pathJoin(base, "deps", name)) if mod then return mod, path, key end end end -- Stop at filesystem or prefix root (58 is ":") if base == "/" or base:byte(-1) == 58 then break end base = pathJoin(base, "..") end -- If we didn't find it outside the bundle, look inside the bundle. if not base:match("^bundle:/*") then return moduleRequire("bundle:", name) end end local moduleCache = {} local function generator(modulePath) assert(modulePath, "Missing path to require generator") -- Convert windows paths to unix paths (mostly) local path = modulePath:gsub("\\", "/") -- Normalize slashes around prefix to be exactly one after path = path:gsub("^/*([^/:]+:)/*", "%1/") local base = pathJoin(path, "..") local function resolve(name) assert(name, "Missing name to resolve") if name:byte(1) == 46 then -- Starts with "." return fixedRequire(pathJoin(base, name)) elseif name:byte(1) == 47 then -- Starts with "/" return fixedRequire(name) end return moduleRequire(base, name) end local function require(name) assert(name, "Missing name to require") if package.preload[name] or package.loaded[name] then return realRequire(name) end -- Resolve the path local data, path, key = resolve(name) if not path then local success, value = pcall(realRequire, name) if success then return value end if not success then error("No such module '" .. name .. "' in '" .. modulePath .. "'") end end -- Check in the cache for this module local module = moduleCache[key] if module then return module.exports end -- Put a new module in the cache if not module = { path = path, dir = pathJoin(path, ".."), exports = {} } moduleCache[key] = module local ext = path:match("%.[^/]+$") if ext == ".lua" then local fn = assert(loadstring(data, path)) local global = { module = module, exports = module.exports } global.require, module.resolve = generator(path) setfenv(fn, setmetatable(global, { __index = _G })) local ret = fn() -- Allow returning the exports as well if ret then module.exports = ret end elseif ext == binExt then local fnName = "luaopen_" .. name:match("[^/]+$"):match("^[^%.]+") local fn if uv.fs_access(path, "r") then -- If it's a real file, load it directly fn = assert(package.loadlib(path, fnName)) else -- Otherwise, copy to a temporary folder and read from there local dir = assert(uv.fs_mkdtemp(pathJoin(tmpBase, "lib-XXXXXX"))) local fd = uv.fs_open(path, "w", 384) -- 0600 uv.fs_write(fd, data, 0) uv.fs_close(fd) fn = assert(package.loadlib(path, fnName)) uv.fs_unlink(path) uv.fs_rmdir(dir) end module.exports = fn() else error("Unknown type at '" .. path .. "' for '" .. name .. "' in '" .. modulePath .. "'") end return module.exports end return require, resolve, moduleCache end return generator
Import key vs logical path fix from luvit require
Import key vs logical path fix from luvit require
Lua
apache-2.0
kidaa/lit,squeek502/lit,DBarney/lit,james2doyle/lit,lduboeuf/lit,1yvT0s/lit,zhaozg/lit,luvit/lit,kaustavha/lit
6d740ea2674ed03394555d54854e3967f7e00bef
nyagos.lua
nyagos.lua
-------------------------------------------------------------------------- -- DO NOT EDIT THIS. PLEASE EDIT ~\.nyagos OR ADD SCRIPT INTO nyagos.d\ -- -------------------------------------------------------------------------- if nyagos == nil then print("This is the startup script for NYAGOS") print("Do not run this with lua.exe") os.exit(0) end print("Nihongo Yet Another GOing Shell " .. (nyagos.version or nyagos.stamp)) print("Copyright (c) 2014,2015 HAYAMA_Kaoru and NYAOS.ORG") print("Powered by ".._VERSION ) local function include(fname) local chank,err=loadfile(fname) if err then print(err) elseif chank then local ok,err=pcall(chank) if not ok then print(fname .. ": " ..err) end else print(fname .. ":fail to load") end end local addons=nyagos.glob((nyagos.exe:gsub("%.[eE][xX][eE]$",".d\\*.lua"))) for i=1,#addons do include(addons[i]) end local home = nyagos.getenv("HOME") or nyagos.getenv("USERPROFILE") if home then local dotfile = nyagos.pathjoin(home,'.nyagos') local fd=io.open(dotfile) if fd then fd:close() include(dotfile) end end
-------------------------------------------------------------------------- -- DO NOT EDIT THIS. PLEASE EDIT ~\.nyagos OR ADD SCRIPT INTO nyagos.d\ -- -------------------------------------------------------------------------- if nyagos == nil then print("This is the startup script for NYAGOS") print("Do not run this with lua.exe") os.exit(0) end print(string.format("Nihongo Yet Another GOing Shell %s Powered by %s", (nyagos.version or "v"..nyagos.stamp), _VERSION )) print("Copyright (c) 2014,2015 HAYAMA_Kaoru and NYAOS.ORG") local function include(fname) local chank,err=loadfile(fname) if err then print(err) elseif chank then local ok,err=pcall(chank) if not ok then print(fname .. ": " ..err) end else print(fname .. ":fail to load") end end local addons=nyagos.glob((nyagos.exe:gsub("%.[eE][xX][eE]$",".d\\*.lua"))) for i=1,#addons do include(addons[i]) end local home = nyagos.getenv("HOME") or nyagos.getenv("USERPROFILE") if home then local dotfile = nyagos.pathjoin(home,'.nyagos') local fd=io.open(dotfile) if fd then fd:close() include(dotfile) end end
Fix (c) on nyagos.lua
Fix (c) on nyagos.lua
Lua
bsd-3-clause
hattya/nyagos,nocd5/nyagos,hattya/nyagos,kissthink/nyagos,tyochiai/nyagos,zetamatta/nyagos,tsuyoshicho/nyagos,hattya/nyagos,kissthink/nyagos,kissthink/nyagos
5b752c101afea99d38eda304663b17a601240bba
spec/env/env.lua
spec/env/env.lua
local inspect = require 'spec.env.inspect' local http = require 'spec.env.http' local sha = require 'spec.env.sha' local bucket = require 'spec.env.bucket' local Console = require 'spec.env.console' local send = require 'spec.env.send' local metric = require 'spec.env.metric' local xml = require 'lxp' -- luarocks install LuaExpat local cjson = require 'cjson' -- luarocks install cjson local mime = require 'mime' -- luarocks install luasocket local env = {} function env.new(spec) local base64 = { decode = mime.unb64, encode = mime.b64 } local time = { seconds = os.time, http = os.time, now = os.time } local hmac = { sha256 = sha.hash256 } local console = Console.new() local trace = { link = "<trace_link>" } local h = http.new(spec) local b = bucket.new(spec) local s = send.new(spec) local m = metric.new(spec) return { console = console, inspect = inspect, -- just ngx.log log = log, base64 = base64, hmac = hmac, time = time, trace = trace, json = cjson, xml = xml, http = h, bucket = b, send = s, metric = m } end return env
local inspect = require 'spec.env.inspect' local http = require 'spec.env.http' local sha = require 'spec.env.sha' local bucket = require 'spec.env.bucket' local Console = require 'spec.env.console' local send = require 'spec.env.send' local metric = require 'spec.env.metric' local xml = require 'lxp' -- luarocks install LuaExpat local cjson = require 'cjson' -- luarocks install cjson local mime = require 'mime' -- luarocks install luasocket local env = {} function env.new(spec) local base64 = { decode = mime.unb64, encode = mime.b64 } local time = { seconds = os.time, -- avoid warnings when passing params http = function() return os.time() end, now = os.time } local hmac = { sha256 = sha.hash256 } local console = Console.new() local trace = { link = "<trace_link>" } local h = http.new(spec) local b = bucket.new(spec) local s = send.new(spec) local m = metric.new(spec) return { console = console, inspect = inspect, -- just ngx.log log = log, base64 = base64, hmac = hmac, time = time, trace = trace, json = cjson, xml = xml, http = h, bucket = b, send = s, metric = m } end return env
Fix timer.http method
Fix timer.http method
Lua
mit
APItools/middleware
6e747a0221f1770b3362a234d0ffe6bcb50353b4
core/xmlhandlers.lua
core/xmlhandlers.lua
-- Prosody IM -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- require "util.stanza" local st = stanza; local tostring = tostring; local pairs = pairs; local ipairs = ipairs; local t_insert = table.insert; local t_concat = table.concat; local default_log = require "util.logger".init("xmlhandlers"); local error = error; module "xmlhandlers" local ns_prefixes = { ["http://www.w3.org/XML/1998/namespace"] = "xml"; } function init_xmlhandlers(session, stream_callbacks) local ns_stack = { "" }; local curr_ns, name = ""; local curr_tag; local chardata = {}; local xml_handlers = {}; local log = session.log or default_log; local cb_streamopened = stream_callbacks.streamopened; local cb_streamclosed = stream_callbacks.streamclosed; local cb_error = stream_callbacks.error or function (session, e) error("XML stream error: "..tostring(e)); end; local cb_handlestanza = stream_callbacks.handlestanza; local stream_tag = stream_callbacks.stream_tag; local stream_default_ns = stream_callbacks.default_ns; local stanza function xml_handlers:StartElement(tagname, attr) if stanza and #chardata > 0 then -- We have some character data in the buffer stanza:text(t_concat(chardata)); chardata = {}; end local curr_ns,name = tagname:match("^(.-)|?([^%|]-)$"); if not name then curr_ns, name = "", curr_ns; end if curr_ns ~= stream_default_ns then attr.xmlns = curr_ns; end -- FIXME !!!!! for i=1,#attr do local k = attr[i]; attr[i] = nil; local ns, nm = k:match("^([^|]+)|?([^|]-)$") if ns and nm then ns = ns_prefixes[ns]; if ns then attr[ns..":"..nm] = attr[k]; attr[k] = nil; end end end if not stanza then --if we are not currently inside a stanza if session.notopen then if tagname == stream_tag then if cb_streamopened then cb_streamopened(session, attr); end else -- Garbage before stream? cb_error(session, "no-stream"); end return; end if curr_ns == "jabber:client" and name ~= "iq" and name ~= "presence" and name ~= "message" then cb_error(session, "invalid-top-level-element"); end stanza = st.stanza(name, attr); curr_tag = stanza; else -- we are inside a stanza, so add a tag attr.xmlns = nil; if curr_ns ~= stream_default_ns then attr.xmlns = curr_ns; end stanza:tag(name, attr); end end function xml_handlers:CharacterData(data) if stanza then t_insert(chardata, data); end end function xml_handlers:EndElement(tagname) curr_ns,name = tagname:match("^(.-)|?([^%|]-)$"); if not name then curr_ns, name = "", curr_ns; end if (not stanza) or (#stanza.last_add > 0 and name ~= stanza.last_add[#stanza.last_add].name) then if tagname == stream_tag then if cb_streamclosed then cb_streamclosed(session); end return; elseif name == "error" then cb_error(session, "stream-error", stanza); else cb_error(session, "parse-error", "unexpected-element-close", name); end end if #chardata > 0 then -- We have some character data in the buffer stanza:text(t_concat(chardata)); chardata = {}; end -- Complete stanza if #stanza.last_add == 0 then cb_handlestanza(session, stanza); stanza = nil; else stanza:up(); end end return xml_handlers; end return init_xmlhandlers;
-- Prosody IM -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- require "util.stanza" local st = stanza; local tostring = tostring; local pairs = pairs; local ipairs = ipairs; local t_insert = table.insert; local t_concat = table.concat; local default_log = require "util.logger".init("xmlhandlers"); local error = error; module "xmlhandlers" local ns_prefixes = { ["http://www.w3.org/XML/1998/namespace"] = "xml"; } function init_xmlhandlers(session, stream_callbacks) local ns_stack = { "" }; local curr_ns, name = ""; local curr_tag; local chardata = {}; local xml_handlers = {}; local log = session.log or default_log; local cb_streamopened = stream_callbacks.streamopened; local cb_streamclosed = stream_callbacks.streamclosed; local cb_error = stream_callbacks.error or function (session, e) error("XML stream error: "..tostring(e)); end; local cb_handlestanza = stream_callbacks.handlestanza; local stream_tag = stream_callbacks.stream_tag; local stream_default_ns = stream_callbacks.default_ns; local stanza function xml_handlers:StartElement(tagname, attr) if stanza and #chardata > 0 then -- We have some character data in the buffer stanza:text(t_concat(chardata)); chardata = {}; end local curr_ns,name = tagname:match("^(.-)|?([^%|]-)$"); if not name then curr_ns, name = "", curr_ns; end if curr_ns ~= stream_default_ns then attr.xmlns = curr_ns; end -- FIXME !!!!! for i=1,#attr do local k = attr[i]; attr[i] = nil; local ns, nm = k:match("^([^|]+)|?([^|]-)$") if ns and nm then ns = ns_prefixes[ns]; if ns then attr[ns..":"..nm] = attr[k]; attr[k] = nil; end end end if not stanza then --if we are not currently inside a stanza if session.notopen then if tagname == stream_tag then if cb_streamopened then cb_streamopened(session, attr); end else -- Garbage before stream? cb_error(session, "no-stream"); end return; end if curr_ns == "jabber:client" and name ~= "iq" and name ~= "presence" and name ~= "message" then cb_error(session, "invalid-top-level-element"); end stanza = st.stanza(name, attr); curr_tag = stanza; else -- we are inside a stanza, so add a tag attr.xmlns = nil; if curr_ns ~= stream_default_ns then attr.xmlns = curr_ns; end stanza:tag(name, attr); end end function xml_handlers:CharacterData(data) if stanza then t_insert(chardata, data); end end function xml_handlers:EndElement(tagname) curr_ns,name = tagname:match("^(.-)|?([^%|]-)$"); if not name then curr_ns, name = "", curr_ns; end if (not stanza) or (#stanza.last_add > 0 and name ~= stanza.last_add[#stanza.last_add].name) then if tagname == stream_tag then if cb_streamclosed then cb_streamclosed(session); end elseif name == "error" then cb_error(session, "stream-error", stanza); else cb_error(session, "parse-error", "unexpected-element-close", name); end stanza, chardata = nil, {}; return; end if #chardata > 0 then -- We have some character data in the buffer stanza:text(t_concat(chardata)); chardata = {}; end -- Complete stanza if #stanza.last_add == 0 then cb_handlestanza(session, stanza); stanza = nil; else stanza:up(); end end return xml_handlers; end return init_xmlhandlers;
xmlhandlers: Reset state on error or stream close, fixes possible traceback
xmlhandlers: Reset state on error or stream close, fixes possible traceback
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
f0231a2dd7ca04a274e2aaeaba3a98dc5d779be3
kong/api/routes/upstreams.lua
kong/api/routes/upstreams.lua
local endpoints = require "kong.api.endpoints" local utils = require "kong.tools.utils" local knode = (kong and kong.node) and kong.node or require "kong.pdk.node".new() local unescape_uri = ngx.unescape_uri local escape_uri = ngx.escape_uri local null = ngx.null local fmt = string.format local function select_upstream(db, upstream_id, opts) local id = unescape_uri(upstream_id) if utils.is_valid_uuid(id) then return db.upstreams:select({ id = id }, opts) end return db.upstreams:select_by_name(id, opts) end local function select_target(db, upstream, target_id, opts) local id = unescape_uri(target_id) local filter = utils.is_valid_uuid(id) and { id = id } or { target = id } return db.targets:select_by_upstream_filter({ id = upstream.id }, filter, opts) end local function post_health(self, db, is_healthy) local args = self.args.post local opts = endpoints.extract_options(args, db.upstreams.schema, "select") local upstream, _, err_t = select_upstream(db, self.params.upstreams, opts) if err_t then return endpoints.handle_error(err_t) end if not upstream then return kong.response.exit(404, { message = "Not found" }) end opts = endpoints.extract_options(args, db.targets.schema, "select", opts) local target, _, err_t = select_target(db, upstream, self.params.targets, opts) if err_t then return endpoints.handle_error(err_t) end if target then local ok, err = db.targets:post_health(upstream, target, is_healthy) if not ok then local body = utils.get_default_exit_body(400, err) return kong.response.exit(400, body) end end return kong.response.exit(204) -- no content end return { ["/upstreams/:upstreams/health"] = { GET = function(self, db) local args = self.args.uri local opts = endpoints.extract_options(args, db.upstreams.schema, "select") local upstream, _, err_t = select_upstream(db, self.params.upstreams, opts) if err_t then return endpoints.handle_error(err_t) end if not upstream then return kong.response.exit(404, { message = "Not found" }) end local upstream_pk = { id = upstream.id } local size, err = endpoints.get_page_size(args) if err then return endpoints.handle_error(db.targets.errors:invalid_size(err)) end opts = endpoints.extract_options(args, db.targets.schema, "select") local targets_with_health, _, err_t, offset = db.targets:page_for_upstream_with_health(upstream_pk, size, args.offset, opts) if err_t then return endpoints.handle_error(err_t) end local next_page = offset and fmt("/upstreams/%s/health?offset=%s", escape_uri(upstream.id), escape_uri(offset)) or null local node_id, err = knode.get_id() if err then ngx.log(ngx.ERR, "failed getting node id: ", err) end return kong.response.exit(200, { data = targets_with_health, offset = offset, next = next_page, node_id = node_id, }) end }, ["/upstreams/:upstreams/targets/all"] = { GET = function(self, db) local args = self.args.uri local opts = endpoints.extract_options(args, db.upstreams.schema, "select") local upstream, _, err_t = select_upstream(db, self.params.upstreams, opts) if err_t then return endpoints.handle_error(err_t) end if not upstream then return kong.response.exit(404, { message = "Not found" }) end local upstream_pk = { id = upstream.id } local opts = endpoints.extract_options(args, db.targets.schema, "select") local size, err = endpoints.get_page_size(args) if err then return endpoints.handle_error(db.targets.errors:invalid_size(err)) end local targets, _, err_t, offset = db.targets:page_for_upstream_raw(upstream_pk, size, args.offset, opts) if err_t then return endpoints.handle_error(err_t) end local next_page = offset and fmt("/upstreams/%s/targets/all?offset=%s", escape_uri(upstream.id), escape_uri(offset)) or null return kong.response.exit(200, { data = targets, offset = offset, next = next_page, }) end }, ["/upstreams/:upstreams/targets/:targets/healthy"] = { POST = function(self, db) return post_health(self, db, true) end, }, ["/upstreams/:upstreams/targets/:targets/unhealthy"] = { POST = function(self, db) return post_health(self, db, false) end, }, ["/upstreams/:upstreams/targets/:targets"] = { DELETE = function(self, db) local args = self.args.uri local opts = endpoints.extract_options(args, db.upstreams.schema, "select") local upstream, _, err_t = select_upstream(db, self.params.upstreams, opts) if err_t then return endpoints.handle_error(err_t) end if not upstream then return kong.response.exit(404, { message = "Not found" }) end opts = endpoints.extract_options(args, db.targets.schema, "select") local target, _, err_t = select_target(db, upstream, self.params.targets, opts) if err_t then return endpoints.handle_error(err_t) end if target then opts = endpoints.extract_options(args, db.targets.schema, "delete") local _, _, err_t = db.targets:delete({ id = target.id }, opts) if err_t then return endpoints.handle_error(err_t) end end return kong.response.exit(204) -- no content end }, }
local endpoints = require "kong.api.endpoints" local utils = require "kong.tools.utils" local knode = (kong and kong.node) and kong.node or require "kong.pdk.node".new() local unescape_uri = ngx.unescape_uri local escape_uri = ngx.escape_uri local null = ngx.null local fmt = string.format local function post_health(self, db, is_healthy) local upstream, _, err_t = endpoints.select_entity(self, db, db.upstreams.schema) if err_t then return endpoints.handle_error(err_t) end if not upstream then return kong.response.exit(404, { message = "Not found" }) end local target if utils.is_valid_uuid(unescape_uri(self.params.targets)) then target, _, err_t = endpoints.select_entity(self, db, db.targets.schema) else local opts = endpoints.extract_options(self.args.uri, db.targets.schema, "select") local upstream_pk = db.upstreams.schema:extract_pk_values(upstream) local filter = { target = unescape_uri(self.params.targets) } target, _, err_t = db.targets:select_by_upstream_filter(upstream_pk, filter, opts) end if err_t then return endpoints.handle_error(err_t) end if not target or target.upstream.id ~= upstream.id then return kong.response.exit(404, { message = "Not found" }) end local ok, err = db.targets:post_health(upstream, target, is_healthy) if not ok then return kong.response.exit(400, { message = err }) end return kong.response.exit(204) end return { ["/upstreams/:upstreams/health"] = { GET = function(self, db) local upstream, _, err_t = endpoints.select_entity(self, db, db.upstreams.schema) if err_t then return endpoints.handle_error(err_t) end if not upstream then return kong.response.exit(404, { message = "Not found" }) end self.params.targets = db.upstreams.schema:extract_pk_values(upstream) local targets_with_health, _, err_t, offset = endpoints.page_collection(self, db, db.targets.schema, "page_for_upstream_with_health") if err_t then return endpoints.handle_error(err_t) end local next_page = offset and fmt("/upstreams/%s/health?offset=%s", escape_uri(upstream.id), escape_uri(offset)) or null local node_id, err = knode.get_id() if err then ngx.log(ngx.ERR, "failed getting node id: ", err) end return kong.response.exit(200, { data = targets_with_health, offset = offset, next = next_page, node_id = node_id, }) end }, ["/upstreams/:upstreams/targets"] = { GET = endpoints.get_collection_endpoint(kong.db.targets.schema, kong.db.upstreams.schema, "upstream", "page_for_upstream"), }, ["/upstreams/:upstreams/targets/all"] = { GET = endpoints.get_collection_endpoint(kong.db.targets.schema, kong.db.upstreams.schema, "upstream", "page_for_upstream_raw") }, ["/upstreams/:upstreams/targets/:targets/healthy"] = { POST = function(self, db) return post_health(self, db, true) end, }, ["/upstreams/:upstreams/targets/:targets/unhealthy"] = { POST = function(self, db) return post_health(self, db, false) end, }, ["/upstreams/:upstreams/targets/:targets"] = { DELETE = function(self, db) local upstream, _, err_t = endpoints.select_entity(self, db, db.upstreams.schema) if err_t then return endpoints.handle_error(err_t) end if not upstream then return kong.response.exit(404, { message = "Not found" }) end local target if utils.is_valid_uuid(unescape_uri(self.params.targets)) then target, _, err_t = endpoints.select_entity(self, db, db.targets.schema) else local opts = endpoints.extract_options(self.args.uri, db.targets.schema, "select") local upstream_pk = db.upstreams.schema:extract_pk_values(upstream) local filter = { target = unescape_uri(self.params.targets) } target, _, err_t = db.targets:select_by_upstream_filter(upstream_pk, filter, opts) end if err_t then return endpoints.handle_error(err_t) end if not target or target.upstream.id ~= upstream.id then return kong.response.exit(404, { message = "Not found" }) end self.params.targets = db.upstreams.schema:extract_pk_values(target) _, _, err_t = endpoints.delete_entity(self, db, db.targets.schema) if err_t then return endpoints.handle_error(err_t) end return kong.response.exit(204) -- no content end }, }
fix(api) catch invalid inputs in upstream endpoints
fix(api) catch invalid inputs in upstream endpoints Refactors the upstream endpoints using new functionality from `kong.api.endpoints` in order to produce 404 upon invalid targets (instead of failing with 500). Includes a performance improvement (avoiding needless queries) when fetching targets by uuid. Fixes #4132.
Lua
apache-2.0
Mashape/kong,Kong/kong,Kong/kong,Kong/kong
dba1668011baba6bb37a3d7c0e759beb96352c30
build/scripts/common.lua
build/scripts/common.lua
-- Configuration gnrale configurations { -- "DebugStatic", -- "ReleaseStatic", "DebugDLL", "ReleaseDLL" } defines "NAZARA_BUILD" language "C++" location(_ACTION) includedirs { "../include", "../src/", "../extlibs/include" } libdirs "../lib" if (_OPTIONS["x64"]) then libdirs "../extlibs/lib/x64" end libdirs "../extlibs/lib/x86" targetdir "../lib" configuration "Debug*" defines "NAZARA_DEBUG" flags "Symbols" configuration "Release*" flags { "EnableSSE2", "Optimize", "OptimizeSpeed", "NoFramePointer", "NoRTTI" } configuration "*Static" defines "NAZARA_STATIC" kind "StaticLib" configuration "*DLL" kind "SharedLib" configuration "DebugStatic" targetsuffix "-s-d" configuration "ReleaseStatic" targetsuffix "-s" configuration "DebugDLL" targetsuffix "-d" configuration "codeblocks or codelite or gmake or xcode3*" buildoptions "-std=c++11" configuration { "linux or bsd or macosx", "gmake" } buildoptions "-fvisibility=hidden"
-- Configuration gnrale configurations { -- "DebugStatic", -- "ReleaseStatic", "DebugDLL", "ReleaseDLL" } defines "NAZARA_BUILD" language "C++" location(_ACTION) includedirs { "../include", "../src/", "../extlibs/include" } libdirs "../lib" if (_OPTIONS["x64"]) then libdirs "../extlibs/lib/x64" end libdirs "../extlibs/lib/x86" targetdir "../lib" configuration "Debug*" defines "NAZARA_DEBUG" flags "Symbols" configuration "Release*" flags { "EnableSSE", "EnableSSE2", "Optimize", "OptimizeSpeed", "NoFramePointer", "NoRTTI" } configuration "*Static" defines "NAZARA_STATIC" kind "StaticLib" configuration "*DLL" kind "SharedLib" configuration "DebugStatic" targetsuffix "-s-d" configuration "ReleaseStatic" targetsuffix "-s" configuration "DebugDLL" targetsuffix "-d" configuration "codeblocks or codelite or gmake or xcode3*" buildoptions { "-mfpmath=sse", "-std=c++11" } configuration { "linux or bsd or macosx", "gmake" } buildoptions "-fvisibility=hidden"
Fixed SSE2 not being enabled
Fixed SSE2 not being enabled Former-commit-id: b4b6b3e014bac4dedfe684a30f9729b4c8f03a36
Lua
mit
DigitalPulseSoftware/NazaraEngine
00f8b0fd1ec140d21ae9b303c5824788bc083272
kong/plugins/session/schema.lua
kong/plugins/session/schema.lua
local typedefs = require "kong.db.schema.typedefs" local Schema = require "kong.db.schema" local utils = require("kong.tools.utils") local char = string.char local rand = math.random local encode_base64 = ngx.encode_base64 local samesite = Schema.define { type = "string", default = "Strict", one_of = { "Strict", "Lax", "off", } } --- kong.utils.random_string with 32 bytes instead -- @returns random string of length 44 local function random_string() return encode_base64(utils.get_rand_bytes(32, true)) :gsub("/", char(rand(48, 57))) -- 0 - 10 :gsub("+", char(rand(65, 90))) -- A - Z :gsub("=", char(rand(97, 122))) -- a - z end return { name = "session", endpoint_key = "session_id", fields = { { config = { type = "record", fields = { { consumer = typedefs.no_consumer }, { secret = { type = "string", required = false, default = random_string(), }, }, { cookie_name = { type = "string", default = "session" } }, { cookie_lifetime = { type = "number", default = 3600 } }, { cookie_renew = { type = "number", default = 600 } }, { cookie_path = { type = "string", default = "/" } }, { cookie_domain = { type = "string" } }, { cookie_samesite = samesite }, { cookie_httponly = { type = "boolean", default = true } }, { cookie_secure = { type = "boolean", default = true } }, { cookie_discard = { type = "number", default = 10 } }, { storage = { required = false, type = "string", enum = { "cookie", "kong", }, default = "cookie", } }, { logout_methods = { type = "array", elements = { type = "string", one_of = { "GET", "POST", "DELETE" }, }, default = { "POST", "DELETE" }, } }, { logout_query_arg = { required = false, type = "string", default = "session_logout", } }, { logout_post_arg = { required = false, type = "string", default = "session_logout", }, }, }, }, }, }, }
local typedefs = require "kong.db.schema.typedefs" local Schema = require "kong.db.schema" local utils = require("kong.tools.utils") local char = string.char local rand = math.random local encode_base64 = ngx.encode_base64 local samesite = Schema.define { type = "string", default = "Strict", one_of = { "Strict", "Lax", "off", } } --- kong.utils.random_string with 32 bytes instead -- @returns random string of length 44 local function random_string() return encode_base64(utils.get_rand_bytes(32, true)) :gsub("/", char(rand(48, 57))) -- 0 - 10 :gsub("+", char(rand(65, 90))) -- A - Z :gsub("=", char(rand(97, 122))) -- a - z end return { name = "session", fields = { { config = { type = "record", fields = { { consumer = typedefs.no_consumer }, { secret = { type = "string", required = false, default = random_string(), }, }, { cookie_name = { type = "string", default = "session" } }, { cookie_lifetime = { type = "number", default = 3600 } }, { cookie_renew = { type = "number", default = 600 } }, { cookie_path = { type = "string", default = "/" } }, { cookie_domain = { type = "string" } }, { cookie_samesite = samesite }, { cookie_httponly = { type = "boolean", default = true } }, { cookie_secure = { type = "boolean", default = true } }, { cookie_discard = { type = "number", default = 10 } }, { storage = { required = false, type = "string", one_of = { "cookie", "kong", }, default = "cookie", } }, { logout_methods = { type = "array", elements = { type = "string", one_of = { "GET", "POST", "DELETE" }, }, default = { "POST", "DELETE" }, } }, { logout_query_arg = { required = false, type = "string", default = "session_logout", } }, { logout_post_arg = { required = false, type = "string", default = "session_logout", }, }, }, }, }, }, }
fix(session) schema errors
fix(session) schema errors * remove unused endpoint_key * enum -> one_of
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
a483a6bed3c41af57c21536dea88e90eafa50bb3
plugins/mod_saslauth.lua
plugins/mod_saslauth.lua
-- Prosody IM v0.4 -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local st = require "util.stanza"; local sm_bind_resource = require "core.sessionmanager".bind_resource; local sm_make_authenticated = require "core.sessionmanager".make_authenticated; local base64 = require "util.encodings".base64; local datamanager_load = require "util.datamanager".load; local usermanager_validate_credentials = require "core.usermanager".validate_credentials; local t_concat, t_insert = table.concat, table.insert; local tostring = tostring; local jid_split = require "util.jid".split local md5 = require "util.hashes".md5; local config = require "core.configmanager"; local log = module._log; local xmlns_sasl ='urn:ietf:params:xml:ns:xmpp-sasl'; local xmlns_bind ='urn:ietf:params:xml:ns:xmpp-bind'; local xmlns_stanzas ='urn:ietf:params:xml:ns:xmpp-stanzas'; local new_sasl = require "util.sasl".new; local function build_reply(status, ret, err_msg) local reply = st.stanza(status, {xmlns = xmlns_sasl}); if status == "challenge" then log("debug", ret or ""); reply:text(base64.encode(ret or "")); elseif status == "failure" then reply:tag(ret):up(); if err_msg then reply:tag("text"):text(err_msg); end elseif status == "success" then log("debug", ret or ""); reply:text(base64.encode(ret or "")); else error("Unknown sasl status: "..status); end return reply; end local function handle_status(session, status) if status == "failure" then session.sasl_handler = nil; elseif status == "success" then if not session.sasl_handler.username then error("SASL succeeded but we didn't get a username!"); end -- TODO move this to sessionmanager sm_make_authenticated(session, session.sasl_handler.username); session.sasl_handler = nil; session:reset_stream(); end end local function password_callback(node, host, mechanism, decoder) local password = (datamanager_load(node, host, "accounts") or {}).password; -- FIXME handle hashed passwords local func = function(x) return x; end; if password then if mechanism == "PLAIN" then return func, password; elseif mechanism == "DIGEST-MD5" then if decoder then node, host, password = decoder(node), decoder(host), decoder(password); end return func, md5(node..":"..host..":"..password); end end return func, nil; end local function sasl_handler(session, stanza) if stanza.name == "auth" then -- FIXME ignoring duplicates because ejabberd does if config.get(session.host or "*", "core", "anonymous_login") and stanza.attr.mechanism ~= "ANONYMOUS" then return session.send(build_reply("failure", "invalid-mechanism")); elseif stanza.attr.mechanism == "ANONYMOUS" then return session.send(build_reply("failure", "mechanism-too-weak")); end session.sasl_handler = new_sasl(stanza.attr.mechanism, session.host, password_callback); if not session.sasl_handler then return session.send(build_reply("failure", "invalid-mechanism")); end elseif not session.sasl_handler then return; -- FIXME ignoring out of order stanzas because ejabberd does end local text = stanza[1]; if text then text = base64.decode(text); log("debug", text); if not text then session.sasl_handler = nil; session.send(build_reply("failure", "incorrect-encoding")); return; end end local status, ret, err_msg = session.sasl_handler:feed(text); handle_status(session, status); local s = build_reply(status, ret, err_msg); log("debug", "sasl reply: "..tostring(s)); session.send(s); end module:add_handler("c2s_unauthed", "auth", xmlns_sasl, sasl_handler); module:add_handler("c2s_unauthed", "abort", xmlns_sasl, sasl_handler); module:add_handler("c2s_unauthed", "response", xmlns_sasl, sasl_handler); local mechanisms_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-sasl' }; local bind_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-bind' }; local xmpp_session_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-session' }; module:add_event_hook("stream-features", function (session, features) if not session.username then features:tag("mechanisms", mechanisms_attr); -- TODO: Provide PLAIN only if TLS is active, this is a SHOULD from the introduction of RFC 4616. This behavior could be overridden via configuration but will issuing a warning or so. if config.get(session.host or "*", "core", "anonymous_login") then features:tag("mechanism"):text("ANONYMOUS"):up(); else features:tag("mechanism"):text("DIGEST-MD5"):up(); features:tag("mechanism"):text("PLAIN"):up(); end features:up(); else features:tag("bind", bind_attr):tag("required"):up():up(); features:tag("session", xmpp_session_attr):up(); end end); module:add_iq_handler("c2s", "urn:ietf:params:xml:ns:xmpp-bind", function (session, stanza) log("debug", "Client tried to bind to a resource"); local resource; if stanza.attr.type == "set" then local bind = stanza.tags[1]; if bind and bind.attr.xmlns == xmlns_bind then resource = bind:child_with_name("resource"); if resource then resource = resource[1]; end end end local success, err_type, err, err_msg = sm_bind_resource(session, resource); if not success then session.send(st.error_reply(stanza, err_type, err, err_msg)); else session.send(st.reply(stanza) :tag("bind", { xmlns = xmlns_bind}) :tag("jid"):text(session.full_jid)); end end); module:add_iq_handler("c2s", "urn:ietf:params:xml:ns:xmpp-session", function (session, stanza) log("debug", "Client tried to bind to a resource"); session.send(st.reply(stanza)); end);
-- Prosody IM v0.4 -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local st = require "util.stanza"; local sm_bind_resource = require "core.sessionmanager".bind_resource; local sm_make_authenticated = require "core.sessionmanager".make_authenticated; local base64 = require "util.encodings".base64; local datamanager_load = require "util.datamanager".load; local usermanager_validate_credentials = require "core.usermanager".validate_credentials; local t_concat, t_insert = table.concat, table.insert; local tostring = tostring; local jid_split = require "util.jid".split local md5 = require "util.hashes".md5; local config = require "core.configmanager"; local log = module._log; local xmlns_sasl ='urn:ietf:params:xml:ns:xmpp-sasl'; local xmlns_bind ='urn:ietf:params:xml:ns:xmpp-bind'; local xmlns_stanzas ='urn:ietf:params:xml:ns:xmpp-stanzas'; local new_sasl = require "util.sasl".new; local function build_reply(status, ret, err_msg) local reply = st.stanza(status, {xmlns = xmlns_sasl}); if status == "challenge" then log("debug", "%s", ret or ""); reply:text(base64.encode(ret or "")); elseif status == "failure" then reply:tag(ret):up(); if err_msg then reply:tag("text"):text(err_msg); end elseif status == "success" then log("debug", "%s", ret or ""); reply:text(base64.encode(ret or "")); else error("Unknown sasl status: "..status); end return reply; end local function handle_status(session, status) if status == "failure" then session.sasl_handler = nil; elseif status == "success" then if not session.sasl_handler.username then error("SASL succeeded but we didn't get a username!"); end -- TODO move this to sessionmanager sm_make_authenticated(session, session.sasl_handler.username); session.sasl_handler = nil; session:reset_stream(); end end local function password_callback(node, host, mechanism, decoder) local password = (datamanager_load(node, host, "accounts") or {}).password; -- FIXME handle hashed passwords local func = function(x) return x; end; if password then if mechanism == "PLAIN" then return func, password; elseif mechanism == "DIGEST-MD5" then if decoder then node, host, password = decoder(node), decoder(host), decoder(password); end return func, md5(node..":"..host..":"..password); end end return func, nil; end local function sasl_handler(session, stanza) if stanza.name == "auth" then -- FIXME ignoring duplicates because ejabberd does if config.get(session.host or "*", "core", "anonymous_login") and stanza.attr.mechanism ~= "ANONYMOUS" then return session.send(build_reply("failure", "invalid-mechanism")); elseif stanza.attr.mechanism == "ANONYMOUS" then return session.send(build_reply("failure", "mechanism-too-weak")); end session.sasl_handler = new_sasl(stanza.attr.mechanism, session.host, password_callback); if not session.sasl_handler then return session.send(build_reply("failure", "invalid-mechanism")); end elseif not session.sasl_handler then return; -- FIXME ignoring out of order stanzas because ejabberd does end local text = stanza[1]; if text then text = base64.decode(text); log("debug", "%s", text); if not text then session.sasl_handler = nil; session.send(build_reply("failure", "incorrect-encoding")); return; end end local status, ret, err_msg = session.sasl_handler:feed(text); handle_status(session, status); local s = build_reply(status, ret, err_msg); log("debug", "sasl reply: %s", tostring(s)); session.send(s); end module:add_handler("c2s_unauthed", "auth", xmlns_sasl, sasl_handler); module:add_handler("c2s_unauthed", "abort", xmlns_sasl, sasl_handler); module:add_handler("c2s_unauthed", "response", xmlns_sasl, sasl_handler); local mechanisms_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-sasl' }; local bind_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-bind' }; local xmpp_session_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-session' }; module:add_event_hook("stream-features", function (session, features) if not session.username then features:tag("mechanisms", mechanisms_attr); -- TODO: Provide PLAIN only if TLS is active, this is a SHOULD from the introduction of RFC 4616. This behavior could be overridden via configuration but will issuing a warning or so. if config.get(session.host or "*", "core", "anonymous_login") then features:tag("mechanism"):text("ANONYMOUS"):up(); else features:tag("mechanism"):text("DIGEST-MD5"):up(); features:tag("mechanism"):text("PLAIN"):up(); end features:up(); else features:tag("bind", bind_attr):tag("required"):up():up(); features:tag("session", xmpp_session_attr):up(); end end); module:add_iq_handler("c2s", "urn:ietf:params:xml:ns:xmpp-bind", function (session, stanza) log("debug", "Client requesting a resource bind"); local resource; if stanza.attr.type == "set" then local bind = stanza.tags[1]; if bind and bind.attr.xmlns == xmlns_bind then resource = bind:child_with_name("resource"); if resource then resource = resource[1]; end end end local success, err_type, err, err_msg = sm_bind_resource(session, resource); if not success then session.send(st.error_reply(stanza, err_type, err, err_msg)); else session.send(st.reply(stanza) :tag("bind", { xmlns = xmlns_bind}) :tag("jid"):text(session.full_jid)); end end); module:add_iq_handler("c2s", "urn:ietf:params:xml:ns:xmpp-session", function (session, stanza) log("debug", "Client requesting a session"); session.send(st.reply(stanza)); end);
mod_saslauth: Various logging fixes
mod_saslauth: Various logging fixes
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
8fe8b3e13b0fdede1fd908cdc0ff3b1bdb405870
Modules/Shared/Events/StepUtils.lua
Modules/Shared/Events/StepUtils.lua
--- Binds animations into step, where the animation only runs as needed -- @module StepUtils -- @author Quenty local HttpService = game:GetService("HttpService") local RunService = game:GetService("RunService") local StepUtils = {} -- update should return true while it needs to update function StepUtils.bindToRenderStep(update) assert(type(update) == "function") local conn = nil local function disconnect() if conn then conn:Disconnect() conn = nil end end local function connect(...) -- Ignore if we have an existing connection if conn and conn.Connected then return end -- Check to see if we even need to bind an update if not update(...) then return end -- Usually contains just the self arg! local args = {...} -- Bind to render stepped conn = RunService.RenderStepped:Connect(function() if not update(unpack(args)) then disconnect() end end) end return connect, disconnect end function StepUtils.onceAtRenderPriority(priority, func) assert(type(priority) == "number") assert(type(func) == "function") local key = ("StepUtils.onceAtPriority_%s"):format(HttpService:GenerateGUID(false)) local function cleanup() RunService:UnbindFromRenderStep(key) end RunService:BindToRenderStep(key, priority, function() cleanup() func() end) return cleanup end return StepUtils
--- Binds animations into step, where the animation only runs as needed -- @module StepUtils -- @author Quenty local HttpService = game:GetService("HttpService") local RunService = game:GetService("RunService") local StepUtils = {} -- update should return true while it needs to update function StepUtils.bindToRenderStep(update) assert(type(update) == "function") local conn = nil local function disconnect() if conn then conn:Disconnect() conn = nil end end local function connect(...) -- Ignore if we have an existing connection if conn and conn.Connected then return end -- Check to see if we even need to bind an update if not update(...) then return end -- Avoid reentrance, if update() triggers another connection, we'll already be connected. if conn and conn.Connected then return end -- Usually contains just the self arg! local args = {...} -- Bind to render stepped conn = RunService.RenderStepped:Connect(function() if not update(unpack(args)) then disconnect() end end) end return connect, disconnect end function StepUtils.onceAtRenderPriority(priority, func) assert(type(priority) == "number") assert(type(func) == "function") local key = ("StepUtils.onceAtPriority_%s"):format(HttpService:GenerateGUID(false)) local function cleanup() RunService:UnbindFromRenderStep(key) end RunService:BindToRenderStep(key, priority, function() cleanup() func() end) return cleanup end return StepUtils
Fix reentrance issue with step utils
Fix reentrance issue with step utils
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
e708a666c77bf8b66526325d6a8bef99d8f23eb4
init.lua
init.lua
-- Copyright 2016 BMC Software, Inc. -- -- -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- -- you may not use this file except in compliance with the License. -- -- You may obtain a copy of the License at -- -- -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- -- -- Unless required by applicable law or agreed to in writing, software -- -- distributed under the License is distributed on an "AS IS" BASIS, -- -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- -- See the License for the specific language governing permissions and -- -- limitations under the License. local framework = require('framework.lua') local Plugin = framework.Plugin local DataSource = framework.DataSource local Emitter = require('core').Emitter local stringutils = framework.string local math = require('math') local json = require('json') local net = require('net') -- TODO: This dependency will be moved to the framework. local http = require('http') local table = require('table') local url = require('url') require('fun')(true) local params = framework.boundary.param local HttpDataSource = DataSource:extend() local RandomDataSource = DataSource:extend() local KeystoneClient = Emitter:extend() function KeystoneClient:initialize(host, port, tenantName, username, password) self.host = host self.port = port self.tenantName = tenantName self.username = username self.password = password end local get = framework.table.get local post = framework.http.post local request = framework.http.get local Nothing = { _create = function () return Nothing end, __index = _create, isNothing = true } setmetatable(Nothing, Nothing) function Nothing.isNothing(value) return value and value.isNothing end function Nothing:apply(map) if type(map) ~= 'table' then return end local mt = self or Nothing setmetatable(map, mt) for _, v in pairs(map) do apply(v) end end function KeystoneClient:buildData(tenantName, username, password) local data = json.stringify({auth = { tenantName = tenantName, passwordCredentials ={username = username, password = password}} }) return data end function KeystoneClient:getToken(callback) local data = self:buildData(self.tenantName, self.username, self.password) local path = '/v2.0/tokens' local options = { host = self.host, port = self.port, path = path } local req = post(options, data, callback, 'json') -- Propagate errors req:on('error', function (err) self:emit("error","_bevent:" .. "OpenStack Plugin:" .. " error: Could not connect to the specified host [" .. self.host .. "]|t:error|tags:lua,plugin") print("_bevent:" .. "OpenStack Plugin:" .. " error: Could not connect to the specified host [" .. self.host .. "]|t:error|tags:lua,plugin") end) end function getEndpoint(name, endpoints) return nth(1, totable(filter(function (e) return e.name == name end, endpoints))) end function getAdminUrl(endpoint) return get('adminURL', nth(1, get('endpoints', endpoint))) end function getToken(data) return get('id', (get('token',(get('access', data))))) end local CeilometerClient = Emitter:extend() function CeilometerClient:initialize(host, port, tenant, username, password) self.host = host self.port = port self.tenant = tenant self.username = username self.password = password end function CeilometerClient:getMetric(metric, period, callback) local client = KeystoneClient:new(self.host, self.port, self.tenant, self.username, self.password) client:propagate('error', self) client:getToken(function (data) local hasError = get('error', data) if hasError ~= nil then -- Propagate errors self:emit('error', data) else local token = getToken(data) local endpoints = get('serviceCatalog', get('access', data)) local adminUrl = getAdminUrl(getEndpoint('ceilometer', endpoints)) local headers = {} headers['X-Auth-Token'] = token local path = '/v2/meters/' .. metric .. '/statistics?period=' .. period local urlParts = url.parse(adminUrl) local options = { host = urlParts.hostname, port = urlParts.port, path = path, headers = headers } local req = request(options, nil, function (res) if callback then callback(res) end end, 'json', false) req:propagate('error', self) -- Propagate errors end end) end local mapping = {} mapping['cpu_util'] = {avg = 'OS_CPUUTIL_AVG', sum = 'OS_CPUUTIL_SUM', min = 'OS_CPUUTIL_MIN', max = 'OS_CPUUTIL_MAX'} mapping['cpu'] = {avg = 'OS_CPU_AVG', sum = 'OS_CPU_SUM'} mapping['instance'] = {sum = 'OS_INSTANCE_SUM', max = 'OS_INSTANCE_MAX'} mapping['memory'] = {sum = 'OS_MEMORY_SUM', avg = 'OS_MEMORY_AVG'} mapping['memory.usage'] = {sum = 'OS_MEMORY_USAGE_SUM', avg = 'OS_MEMORY_USAGE_AVG'} mapping['volume.size'] = {avg = 'OS_VOLUME_AVG', sum = 'OS_VOLUME_SUM'} mapping['image'] = {sum = 'OS_IMAGE_SUM', avg = 'OS_IMAGE_AVG'} mapping['image.size'] = {avg = 'OS_IMAGE_SIZE_AVG', sum = 'OS_IMAGE_SIZE_SUM'} mapping['disk.read.requests.rate'] = {sum = 'OS_DISK_READ_RATE_SUM', avg = 'OS_DISK_READ_RATE_AVG'} mapping['disk.write.requests.rate'] = {sum = 'OS_DISK_WRITE_RATE_SUM', avg = 'OS_DISK_WRITE_RATE_AVG'} mapping['network.incoming.bytes'] = {sum = 'OS_NETWORK_IN_BYTES_SUM', avg = 'OS_NETWORK_IN_BYTES_AVG'} mapping['network.outgoing.bytes'] = {sum = 'OS_NETWORK_OUT_BYTES_SUM', avg = 'OS_NETWORK_OUT_BYTES_AVG'} mapping['memory.resident'] = {sum = 'OS_MEMORY_RESIDENT_SUM', avg = 'OS_MEMORY_RESIDENT_AVG'} local OpenStackDataSource = DataSource:extend() function OpenStackDataSource:initialize(host, port, tenant, username, password) self.host = host self.port = port self.tenant = tenant self.username = username self.password = password end function OpenStackDataSource:fetch(context, callback) local ceilometer = CeilometerClient:new(self.host, self.port, self.tenant, self.username, self.password) ceilometer:on('error', function (err) p(err.message) end) for metric,v in pairs(mapping) do ceilometer:getMetric(metric, 300, function (result) if callback then callback(metric, result) end end ) end end local dataSource = OpenStackDataSource:new(params.service_host, params.service_port, params.service_tenant, params.service_username, params.service_password) local plugin = Plugin:new(params, dataSource) function plugin:onParseValues(metric, data) local result = {} if data == nil then return {} end local m = mapping[metric] local data = nth(1, data) for col, boundaryName in pairs(m) do result[boundaryName] = tonumber(get(col, data)) end return result end plugin:poll()
-- Copyright 2016 BMC Software, Inc. -- -- -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- -- you may not use this file except in compliance with the License. -- -- You may obtain a copy of the License at -- -- -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- -- -- Unless required by applicable law or agreed to in writing, software -- -- distributed under the License is distributed on an "AS IS" BASIS, -- -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- -- See the License for the specific language governing permissions and -- -- limitations under the License. local framework = require('framework.lua') local Plugin = framework.Plugin local DataSource = framework.DataSource local Emitter = require('core').Emitter local stringutils = framework.string local math = require('math') local json = require('json') local net = require('net') -- TODO: This dependency will be moved to the framework. local http = require('http') local table = require('table') local url = require('url') require('fun')(true) local params = framework.boundary.param local HttpDataSource = DataSource:extend() local RandomDataSource = DataSource:extend() local KeystoneClient = Emitter:extend() function KeystoneClient:initialize(host, port, tenantName, username, password) self.host = host self.port = port self.tenantName = tenantName self.username = username self.password = password end local get = framework.table.get local post = framework.http.post local request = framework.http.get local Nothing = { _create = function () return Nothing end, __index = _create, isNothing = true } setmetatable(Nothing, Nothing) function Nothing.isNothing(value) return value and value.isNothing end function Nothing:apply(map) if type(map) ~= 'table' then return end local mt = self or Nothing setmetatable(map, mt) for _, v in pairs(map) do apply(v) end end function KeystoneClient:buildData(tenantName, username, password) local data = json.stringify({auth = { tenantName = tenantName, passwordCredentials ={username = username, password = password}} }) return data end function KeystoneClient:getToken(callback) local data = self:buildData(self.tenantName, self.username, self.password) local path = '/v2.0/tokens' local options = { host = self.host, port = self.port, path = path } local req = post(options, data, callback, 'json') -- Propagate errors req:on('error', function (err) self:emit("error","_bevent:" .. "OpenStack Plugin:" .. " error: Could not connect to the specified host [" .. self.host .. "]|t:error|tags:lua,plugin") print("_bevent:" .. "OpenStack Plugin:" .. " error: Could not connect to the specified host [" .. self.host .. "]|t:error|tags:lua,plugin") end) end function getEndpoint(name, endpoints) return nth(1, totable(filter(function (e) return e.name == name end, endpoints))) end function getAdminUrl(endpoint) return get('adminURL', nth(1, get('endpoints', endpoint))) end function getToken(data) return get('id', (get('token',(get('access', data))))) end local CeilometerClient = Emitter:extend() function CeilometerClient:initialize(host, port, tenant, username, password) self.host = host self.port = port self.tenant = tenant self.username = username self.password = password end function CeilometerClient:getMetric(metric, period, callback) local client = KeystoneClient:new(self.host, self.port, self.tenant, self.username, self.password) client:propagate('error', self) client:getToken(function (data) local hasError = get('error', data) if hasError ~= nil then -- Propagate errors self:emit('error', data) print("_bevent:" .. "OpenStack Plugin:" .. " error: Authentication failed for specified host [" .. self.host .. "]|t:error|tags:lua,plugin") else local token = getToken(data) local endpoints = get('serviceCatalog', get('access', data)) local adminUrl = getAdminUrl(getEndpoint('ceilometer', endpoints)) local headers = {} headers['X-Auth-Token'] = token local path = '/v2/meters/' .. metric .. '/statistics?period=' .. period local urlParts = url.parse(adminUrl) local options = { host = urlParts.hostname, port = urlParts.port, path = path, headers = headers } local req = request(options, nil, function (res) if callback then callback(res) end end, 'json', false) req:propagate('error', self) -- Propagate errors end end) end local mapping = {} mapping['cpu_util'] = {avg = 'OS_CPUUTIL_AVG', sum = 'OS_CPUUTIL_SUM', min = 'OS_CPUUTIL_MIN', max = 'OS_CPUUTIL_MAX'} mapping['cpu'] = {avg = 'OS_CPU_AVG', sum = 'OS_CPU_SUM'} mapping['instance'] = {sum = 'OS_INSTANCE_SUM', max = 'OS_INSTANCE_MAX'} mapping['memory'] = {sum = 'OS_MEMORY_SUM', avg = 'OS_MEMORY_AVG'} mapping['memory.usage'] = {sum = 'OS_MEMORY_USAGE_SUM', avg = 'OS_MEMORY_USAGE_AVG'} mapping['volume.size'] = {avg = 'OS_VOLUME_AVG', sum = 'OS_VOLUME_SUM'} mapping['image'] = {sum = 'OS_IMAGE_SUM', avg = 'OS_IMAGE_AVG'} mapping['image.size'] = {avg = 'OS_IMAGE_SIZE_AVG', sum = 'OS_IMAGE_SIZE_SUM'} mapping['disk.read.requests.rate'] = {sum = 'OS_DISK_READ_RATE_SUM', avg = 'OS_DISK_READ_RATE_AVG'} mapping['disk.write.requests.rate'] = {sum = 'OS_DISK_WRITE_RATE_SUM', avg = 'OS_DISK_WRITE_RATE_AVG'} mapping['network.incoming.bytes'] = {sum = 'OS_NETWORK_IN_BYTES_SUM', avg = 'OS_NETWORK_IN_BYTES_AVG'} mapping['network.outgoing.bytes'] = {sum = 'OS_NETWORK_OUT_BYTES_SUM', avg = 'OS_NETWORK_OUT_BYTES_AVG'} mapping['memory.resident'] = {sum = 'OS_MEMORY_RESIDENT_SUM', avg = 'OS_MEMORY_RESIDENT_AVG'} local OpenStackDataSource = DataSource:extend() function OpenStackDataSource:initialize(host, port, tenant, username, password) self.host = host self.port = port self.tenant = tenant self.username = username self.password = password end function OpenStackDataSource:fetch(context, callback) local ceilometer = CeilometerClient:new(self.host, self.port, self.tenant, self.username, self.password) ceilometer:on('error', function (err) p(err.message) end) for metric,v in pairs(mapping) do ceilometer:getMetric(metric, 300, function (result) if callback then callback(metric, result) end end ) end end local dataSource = OpenStackDataSource:new(params.service_host, params.service_port, params.service_tenant, params.service_username, params.service_password) local plugin = Plugin:new(params, dataSource) function plugin:onParseValues(metric, data) local result = {} if data == nil then return {} end local m = mapping[metric] local data = nth(1, data) for col, boundaryName in pairs(m) do result[boundaryName] = tonumber(get(col, data)) end return result end plugin:poll()
Jira-PLUG-118 issue fixed
Jira-PLUG-118 issue fixed
Lua
apache-2.0
boundary/boundary-plugin-openstack
75cb0ba631b9849435444a266c0d14fef7c7f73c
joinme/joinme.lua
joinme/joinme.lua
-- joinme.lua -- do initial wifi config for NodeMCU over HTTP -- preliminaries joinme = {} nu = require("nmutils") -- debug code print("are we running on NodeMCU? ", nu.isnodemcu()) -- config data local conffile = "joinmeconf.lua" -- local utilities local function printip() print("Wifi station ip: ", wifi.sta.getip()) end local function conf2string(conf) buf = "{\n" for k, v in pairs(conf) do buf = buf .. string.format(' %s = "%s",\n', k, v) end buf = buf .. "}\n" return buf end local wifiform = [=[ <p>Choose a wifi access point to join: <form action="chooseap"> <ol> _ITEMS_ </ol> <br/> <input type="submit" value="Submit"> </form></p> ]=] function genform(aplist) -- takes list of APs buf = "" for ssid, _ in pairs(aplist) do buf = buf .. ' <li>SSID: <input type="radio" name="' .. ssid .. '" value="' .. ssid .. '">' .. ssid .. '<br/>\n' end return string.gsub(wifiform, "_ITEMS_", buf) end -- exports function joinme.p(fmt, ...) return print(string.format(fmt, ...)) end function joinme.sayhi() joinme.p("Fishy wifi up and swimming...") joinme.p('MAC: %s; chip: %s; heap: %s', wifi.sta.getmac(), node.chipid(), node.heap()) printip() end function joinme.t2s(t) -- one-level table to string for k,v in pairs(t) do print(k.." : "..v) end end function joinme.getconf() status, results = pcall(dofile, conffile) if status then return results else return nil end end function joinme.writeconf(conf) f = file.open(conffile, "w") if not f then return nil end file.write("return " .. conf2string(conf)) file.close() return true end function joinme.joinwifi(conf) joinme.p("config incoming:") joinme.p(conf2string(conf)) wifi.setmode(wifi.STATION) wifi.sta.config(conf.ssid, conf.key) wifi.sta.connect() tmr.alarm(0, 5000, 0, function() printip() end) end function joinme.chooserpage(aplist) -- TODO header and footer return genform(aplist) end return joinme
-- joinme.lua -- do initial wifi config for NodeMCU over HTTP -- preliminaries joinme = {} nu = require("nmutils") -- debug code print("are we running on NodeMCU? ", nu.isnodemcu()) -- config data local conffile = "joinmeconf.lua" -- local utilities local function printip() print("Wifi station ip: ", wifi.sta.getip()) end local function conf2string(conf) buf = "{\n" for k, v in pairs(conf) do buf = buf .. string.format(' %s = "%s",\n', k, v) end buf = buf .. "}\n" return buf end local wifiform = [=[ <p>Choose a wifi access point to join: <form action="chooseap"> <ol> _ITEMS_ </ol> <br/> <input type="submit" value="Submit"> </form></p> ]=] -- comment needed to prevent upload issue function genform(aplist) -- takes list of APs buf = "" for ssid, _ in pairs(aplist) do buf = buf .. ' <li>SSID: <input type="radio" name="' .. ssid .. '" value="' .. ssid .. '">' .. ssid .. '<br/>\n' end return string.gsub(wifiform, "_ITEMS_", buf) end -- exports function joinme.p(fmt, ...) return print(string.format(fmt, ...)) end function joinme.sayhi() joinme.p("Fishy wifi up and swimming...") joinme.p('MAC: %s; chip: %s; heap: %s', wifi.sta.getmac(), node.chipid(), node.heap()) printip() end function joinme.t2s(t) -- one-level table to string for k,v in pairs(t) do print(k.." : "..v) end end function joinme.getconf() status, results = pcall(dofile, conffile) if status then return results else return nil end end function joinme.writeconf(conf) f = file.open(conffile, "w") if not f then return nil end file.write("return " .. conf2string(conf)) file.close() return true end function joinme.joinwifi(conf) joinme.p("config incoming:") joinme.p(conf2string(conf)) wifi.setmode(wifi.STATION) wifi.sta.config(conf.ssid, conf.key) wifi.sta.connect() tmr.alarm(0, 5000, 0, function() printip() end) end function joinme.chooserpage(aplist) -- TODO header and footer return genform(aplist) end return joinme
fix uploader issue
fix uploader issue
Lua
agpl-3.0
hamishcunningham/fishy-wifi,pastukhov/fishy-wifi,pastukhov/fishy-wifi,hamishcunningham/fishy-wifi,hamishcunningham/fishy-wifi,hamishcunningham/fishy-wifi,pastukhov/fishy-wifi,hamishcunningham/fishy-wifi,hamishcunningham/fishy-wifi,pastukhov/fishy-wifi
8543df2868f809dcdb8c25039e0edcd21b73d5c9
cookie-cutter/cookie-cutter.lua
cookie-cutter/cookie-cutter.lua
-- Cookie cutter module local cookie_cutter_module = {} function cookie_cutter_module.svg_extrude_centered(filename, dpi, height) local svg_shapes = svg_ex(filename, dpi) for i, contour in pairs(svg_shapes) do obj = linear_extrude( v(0, 0, height), contour:outline()) --obj = scale(-1, 1, 1) * obj bb = bbox(obj):center() obj = translate(-1 * bb) * obj return obj end end function cookie_cutter_module.dilate_it(shape, cfg) --obj_bb = bbox(obj):extent() --factor = math.max( -- (obj_bb.x + 2*cfg.thickness) / obj_bb.x, -- (obj_bb.y + 2*cfg.thickness) / obj_bb.y) local factor = cfg.thickness local dilated = scale(1, 1, 3) * dilate(shape, factor) local dilated_bb = bbox(dilated):extent() local cutter = difference( intersection{ dilated, ccube(dilated_bb.x + 3* cfg.thickness, dilated_bb.y + 3 * cfg.thickness, cfg.height) }, shape) return cutter end function cookie_cutter_module.create(cfg) if cfg.filename == nil then error("filename is mandotary") end if cfg.thickness == nil then cfg.thickness = 0.6 end if cfg.height == nil then cfg.height = 10 end if cfg.base == nil then cfg.base = 2 end if cfg.dpi == nil then cfg.dpi = 90 end local obj = cookie_cutter_module.svg_extrude_centered(cfg.filename, 90, cfg.height) local cutter = cookie_cutter_module.dilate_it(obj, cfg) --emit(cutter) local base_cfg = {} base_cfg.height = cfg.base base_cfg.thickness = 5 support = translate(0, 0, (cfg.base-cfg.height)/2) * cookie_cutter_module.dilate_it(obj, base_cfg) return union(cutter, support) end function cookie_cutter_module.ui_create(cfg) cfg.height = ui_scalar('height', 10, 0.1, 50) cfg.thickness = ui_scalar('cutter thickness', 0.6, 0.1, 5) -- = 2 * nozzle_width cfg.base = ui_scalar('base', 1, 0.1, cfg.height) cfg.dpi = 90 return cookie_cutter_module.create(cfg) end -- If used as main script then display samples -- see http://stackoverflow.com/questions/4521085/main-function-in-lua if not pcall(getfenv, 4) then emit(cookie_cutter_module.ui_create{filename='pi.svg'}) end return cookie_cutter_module
-- Cookie cutter module local cookie_cutter_module = {} function cookie_cutter_module.svg_extrude_centered(filename, dpi, height) local svg_shapes = svg_ex(filename, dpi) local shapes = {} for i, contour in pairs(svg_shapes) do obj = linear_extrude( v(0, 0, height), contour:outline()) --obj = scale(-1, 1, 1) * obj table.insert(shapes, obj) end local alls = union(shapes) bb = bbox(alls):center() for i, _ in pairs(shapes) do shapes[i] = translate(-1 * bb) * shapes[i] end if table.getn(shapes) == 1 then return shapes[1] else return shapes end end function cookie_cutter_module.dilate_it(shape, cfg) if type(shape) == 'table' then local results = {} for i, _ in pairs(shape) do results[i] = cookie_cutter_module.dilate_it(shape[i], cfg) end return union(results) end --obj_bb = bbox(obj):extent() --factor = math.max( -- (obj_bb.x + 2*cfg.thickness) / obj_bb.x, -- (obj_bb.y + 2*cfg.thickness) / obj_bb.y) local factor = cfg.thickness local dilated = scale(1, 1, 3) * dilate(shape, factor) local dilated_bb = bbox(dilated) local dilated_bb_p1 = dilated_bb:center() local dilated_bb_size = dilated_bb:extent() local cutter = difference( intersection{ dilated, translate(dilated_bb_p1.x, dilated_bb_p1.y, 0) * ccube(dilated_bb_size.x + 3* cfg.thickness, dilated_bb_size.y + 3 * cfg.thickness, cfg.height) }, shape) return cutter end function cookie_cutter_module.create(cfg) if cfg.filename == nil then error("filename is mandatory") end if cfg.thickness == nil then cfg.thickness = 0.6 end if cfg.height == nil then cfg.height = 10 end if cfg.base == nil then cfg.base = 2 end if cfg.dpi == nil then cfg.dpi = 90 end local obj = cookie_cutter_module.svg_extrude_centered(cfg.filename, 90, cfg.height) local cutter = cookie_cutter_module.dilate_it(obj, cfg) local base_cfg = {} base_cfg.height = cfg.base base_cfg.thickness = 5 support = translate(0, 0, (cfg.base-cfg.height)/2) * cookie_cutter_module.dilate_it(obj, base_cfg) return union(cutter, support) end function cookie_cutter_module.ui_create(cfg) cfg.height = ui_scalar('height', 10, 0.1, 50) cfg.thickness = ui_scalar('cutter thickness', 0.6, 0.1, 5) -- = 2 * nozzle_width cfg.base = ui_scalar('base', 1, 0.1, cfg.height) cfg.dpi = 90 return cookie_cutter_module.create(cfg) end -- If used as main script then display samples -- see http://stackoverflow.com/questions/4521085/main-function-in-lua if not pcall(getfenv, 4) then emit(cookie_cutter_module.ui_create{filename='pi.svg'}) end return cookie_cutter_module
fix(cookie-cutter): Handle multiple paths
fix(cookie-cutter): Handle multiple paths
Lua
mit
loic-fejoz/loic-fejoz-fabmoments,loic-fejoz/loic-fejoz-fabmoments,loic-fejoz/loic-fejoz-fabmoments
1c22a4ecf43224ec665d7e184d1bd9f400babd55
lunaci/Worker.lua
lunaci/Worker.lua
module("lunaci.Worker", package.seeall) local log = require "lunaci.log" local utils = require "lunaci.utils" local config = require "lunaci.config" local PackageReport = require "lunaci.PackageReport" local Package = require "rocksolver.Package" local pl = require "pl.import_into"() local Worker = {} Worker.__index = Worker setmetatable(Worker, { __call = function(self, name, versions, manifest) pl.utils.assert_string(1, name) pl.utils.assert_arg(2, versions, "table") pl.utils.assert_arg(3, manifest, "table") local self = setmetatable({}, Worker) self.package_name = name self.package_versions = versions self.manifest = manifest self.report = PackageReport(name) return self end }) -- Run the worker on all the given targets and tasks. function Worker:run(targets, tasks) pl.utils.assert_arg(1, targets, "table") pl.utils.assert_arg(2, tasks, "table") for version, spec in pl.tablex.sort(self.package_versions, utils.sortVersions) do local package = self:get_package(self.package_name, version, spec) for _, target in pairs(targets) do self:run_target(package, target, tasks) end -- Clean package version deploy dir pl.dir.rmtree(pl.path.join(config.deploy_dir, ("%s-%s"):format(package.name, version))) end end -- Run tasks for the package on a given targets. function Worker:run_target(package, target, tasks) pl.utils.assert_arg(1, package, "table") pl.utils.assert_arg(2, target, "table") pl.utils.assert_arg(3, tasks, "table") log:debug("Running target %s on %s", target.name, package) local deploy_dir = self:prepare_target(package, target) local continue = true for _, task in pairs(tasks) do if not continue then self.report:add_output(package, target, task, config.STATUS_NA, "Task chain ended.") else local ok, success, output, cont = pcall(task.call, package, target, deploy_dir, self.manifest) if ok then -- Task run without runtime errors self.report:add_output(package, target, task, success, output) -- Task finished unsuccessfully - task chain should end if not cont then continue = false end else -- Runtime error while running the task local msg = "Error running task: " .. success -- success contains lua error message log:error(msg) self.report:add_output(package, target, task, config.STATUS_INT, msg) end end end self:cleanup_target(deploy_dir, package, target) end function Worker:prepare_target(package, target) local path = pl.path local target_base = path.basename(target.deploy_dir) local deploy_dir = path.join(config.deploy_dir, ("%s-%s"):format(package.name, package.version), target_base) log:debug("Deploy directory: " .. deploy_dir) utils.force_makepath(deploy_dir) -- Copy target base deploy dir local ok, code, out, err = utils.copydir(target.deploy_dir, pl.path.dirname(deploy_dir)) if not ok then error("Could not copy target base deploy directory " .. target.deploy_dir .. ": " .. err) end return deploy_dir end function Worker:cleanup_target(deploy_dir, package, target) return pl.dir.rmtree(deploy_dir) end -- Ge the PackageReport with the output from the runs. function Worker:get_report() return self.report end -- TODO use LuaDist2 for this when it's ready function Worker:get_package(name, version, spec) local path = pl.path local tmp_dir = path.join(config.tmp_dir, "rockspecs") pl.dir.makepath(tmp_dir) local rockspec_filename = name .. "-" .. version .. ".rockspec" local remote_url = ("https://raw.githubusercontent.com/LuaDist2/%s/%s/%s"):format(name, version, rockspec_filename) local rockspec_path = path.join(tmp_dir, rockspec_filename) -- Download rockspec from GitHub if not path.exists(rockspec_path) then local ok, code, out, err = utils.dir_exec(tmp_dir, ("curl -fksSL '%s'"):format(remote_url)) if not ok then log:error("Could not download rockspec for %s-%s", name, version) return Package(name, version, spec) end pl.file.write(rockspec_path, out) end -- Load rockspec from file local contents = pl.file.read(rockspec_path) local lines = pl.stringx.splitlines(contents) -- Remove possible hashbangs if lines[1]:match("^#!.*") then table.remove(lines, 1) end -- Load rockspec file as table local rockspec = pl.pretty.load(pl.stringx.join("\n", lines), nil, false) return Package.from_rockspec(rockspec) end return Worker
module("lunaci.Worker", package.seeall) local log = require "lunaci.log" local utils = require "lunaci.utils" local config = require "lunaci.config" local PackageReport = require "lunaci.PackageReport" local Package = require "rocksolver.Package" local pl = require "pl.import_into"() local Worker = {} Worker.__index = Worker setmetatable(Worker, { __call = function(self, name, versions, manifest) pl.utils.assert_string(1, name) pl.utils.assert_arg(2, versions, "table") pl.utils.assert_arg(3, manifest, "table") local self = setmetatable({}, Worker) self.package_name = name self.package_versions = versions self.manifest = manifest self.report = PackageReport(name) return self end }) -- Run the worker on all the given targets and tasks. function Worker:run(targets, tasks) pl.utils.assert_arg(1, targets, "table") pl.utils.assert_arg(2, tasks, "table") for version, spec in pl.tablex.sort(self.package_versions, utils.sortVersions) do local package = self:get_package(self.package_name, version, spec) for _, target in pairs(targets) do self:run_target(package, target, tasks) end -- Clean package version deploy dir pl.dir.rmtree(pl.path.join(config.deploy_dir, ("%s-%s"):format(package.name, version))) end end -- Run tasks for the package on a given targets. function Worker:run_target(package, target, tasks) pl.utils.assert_arg(1, package, "table") pl.utils.assert_arg(2, target, "table") pl.utils.assert_arg(3, tasks, "table") log:debug("Running target %s on %s", target.name, package) local deploy_dir = self:prepare_target(package, target) local continue = true for _, task in pairs(tasks) do if not continue then self.report:add_output(package, target, task, config.STATUS_NA, "Task chain ended.") else local ok, success, output, cont = pcall(task.call, package, target, deploy_dir, self.manifest) if ok then -- Task run without runtime errors self.report:add_output(package, target, task, success, output) -- Task finished unsuccessfully - task chain should end if not cont then continue = false end else -- Runtime error while running the task local msg = "Error running task: " .. success -- success contains lua error message log:error(msg) self.report:add_output(package, target, task, config.STATUS_INT, msg) end end end self:cleanup_target(deploy_dir, package, target) end function Worker:prepare_target(package, target) local path = pl.path local target_base = path.basename(target.deploy_dir) local deploy_dir = path.join(config.deploy_dir, ("%s-%s"):format(package.name, package.version), target_base) log:debug("Deploy directory: " .. deploy_dir) utils.force_makepath(deploy_dir) -- Copy target base deploy dir local ok, code, out, err = utils.copydir(target.deploy_dir, pl.path.dirname(deploy_dir)) if not ok then error("Could not copy target base deploy directory " .. target.deploy_dir .. ": " .. err) end return deploy_dir end function Worker:cleanup_target(deploy_dir, package, target) return pl.dir.rmtree(deploy_dir) end -- Ge the PackageReport with the output from the runs. function Worker:get_report() return self.report end -- TODO use LuaDist2 for this when it's ready function Worker:get_package(name, version, spec) local path = pl.path local tmp_dir = path.join(config.tmp_dir, "rockspecs") pl.dir.makepath(tmp_dir) local rockspec_filename = name .. "-" .. version .. ".rockspec" local remote_url = ("https://raw.githubusercontent.com/LuaDist2/%s/%s/%s"):format(name, version, rockspec_filename) local rockspec_path = path.join(tmp_dir, rockspec_filename) -- Download rockspec from GitHub if not path.exists(rockspec_path) then local ok, code, out, err = utils.dir_exec(tmp_dir, ("curl -fksSL '%s'"):format(remote_url)) if not ok then log:error("Could not download rockspec for %s-%s", name, version) return Package(name, version, spec) end pl.file.write(rockspec_path, out) end -- Load rockspec from file local contents = pl.file.read(rockspec_path) local lines = pl.stringx.splitlines(contents) -- Remove possible hashbangs for i, line in ipairs(lines) do if line:match("^#!.*") then table.remove(lines, i) end end -- Load rockspec file as table local rockspec = pl.pretty.load(pl.stringx.join("\n", lines), nil, false) if type(rockspec) ~= 'table' then log:warn("Corrupted rockspec file: %s", rockspec_path) return Package(name, version, spec) end return Package.from_rockspec(rockspec) end return Worker
Fix rockspec loading
Fix rockspec loading
Lua
mit
smasty/LunaCI,smasty/LunaCI
33a25cb86021ab29ed93f7586dd013d07c5b688e
lua/framework/graphics/init.lua
lua/framework/graphics/init.lua
--=========== Copyright © 2018, Planimeter, All rights reserved. =============-- -- -- Purpose: -- --============================================================================-- require( "framework.graphics.opengl" ) require( "framework.graphics.primitive" ) require( "framework.graphics.shader" ) require( "framework.graphics.transformation" ) local GL = require( "opengl" ) local ffi = require( "ffi" ) local SDL = require( "sdl" ) local kazmath = require( "kazmath" ) local bit = require( "bit" ) local framework = framework local require = require local tostring = tostring module( "framework.graphics" ) function draw( drawable, x, y, r, sx, sy, ox, oy, kx, ky ) x = x or 0 y = y or 0 drawable:draw( x, y, r, sx, sy, ox, oy, kx, ky ) end function getFont() return _font end function getFramebuffer() return _framebuffer end function getPolygonMode() local mode = ffi.new( "GLint[1]" ) GL.glGetIntegerv( GL.GL_POLYGON_MODE, mode ) if ( mode[0] == GL.GL_LINE ) then return "line" elseif( mode[0] == GL.GL_FILL ) then return "fill" end end function getSize() local width = ffi.new( "int[1]" ) local height = ffi.new( "int[1]" ) SDL.SDL_GL_GetDrawableSize( framework.window._window, width, height ) return width[0], height[0] end function newCubemap( type, filenames ) require( "framework.graphics.cubemap" ) local cubemap = framework.graphics.cubemap return cubemap( type, filenames ) end function newFont( filename, size ) require( "framework.graphics.font" ) local font = framework.graphics.font return font( filename, size ) end function newFramebuffer( type, width, height ) require( "framework.graphics.framebuffer" ) local framebuffer = framework.graphics.framebuffer return framebuffer( type, width, height ) end function newImage( filename, params ) require( "framework.graphics.image" ) local image = framework.graphics.image return image( filename, params ) end function newModel( filename ) require( "framework.graphics.model" ) local model = framework.graphics.model return model( filename ) end function print( text, x, y, r, sx, sy, ox, oy, kx, ky ) text = tostring( text ) x = x or 0 y = y or 0 local font = getFont() font:print( text, x, y, r, sx, sy, ox, oy, kx, ky ) end function setBackgroundColor( color ) GL.glClearColor( ( color[ 1 ] or 0 ) / 255, ( color[ 2 ] or 0 ) / 255, ( color[ 3 ] or 0 ) / 255, ( color[ 4 ] or 0 ) ) end function setFont( font ) _font = font end function setFramebuffer( framebuffer ) if ( framebuffer ) then GL.glBindFramebuffer( GL.GL_FRAMEBUFFER, framebuffer.framebuffer[0] ) local mode = framework.graphics.getMatrixMode() framework.graphics.setMatrixMode( "projection" ) framework.graphics.push() local mat4 = framework.graphics.getTransformation() local width = framebuffer.width local height = framebuffer.height kazmath.kmMat4OrthographicProjection( mat4, 0, width, 0, height, -1.0, 1.0 ) framework.graphics.setMatrixMode( mode ) local dpiScale = framework.window.getPixelScale() setViewport( 0, 0, width * dpiScale, height * dpiScale ) else GL.glBindFramebuffer( GL.GL_FRAMEBUFFER, 0 ) framework.graphics.setOrthographicProjection( width, height ) local width, height = getSize() setViewport( 0, 0, width, height ) end _framebuffer = framebuffer end function setPolygonMode( mode ) if ( mode == "line" ) then mode = GL.GL_LINE elseif ( mode == "fill" ) then mode = GL.GL_FILL end GL.glPolygonMode( GL.GL_FRONT_AND_BACK, mode ) end function setScissor( x, y, width, height ) if ( _framebuffer ~= nil ) then GL.glScissor( x, y, width, height ) else GL.glScissor( x, _viewport.height - ( y + height ), width, height ) end end _viewport = _viewport or { x = 0, y = 0, width = 800, height = 600 } function setViewport( x, y, width, height ) GL.glViewport( x, y, width, height ) _viewport.x = x _viewport.y = y _viewport.width = width _viewport.height = height end function setVSync( vsync ) SDL.SDL_GL_SetSwapInterval( vsync and 1 or 0 ) end function clear() GL.glClear( bit.bor( GL.GL_COLOR_BUFFER_BIT, GL.GL_DEPTH_BUFFER_BIT ) ) end
--=========== Copyright © 2018, Planimeter, All rights reserved. =============-- -- -- Purpose: -- --============================================================================-- require( "framework.graphics.opengl" ) require( "framework.graphics.primitive" ) require( "framework.graphics.shader" ) require( "framework.graphics.transformation" ) local GL = require( "opengl" ) local ffi = require( "ffi" ) local SDL = require( "sdl" ) local kazmath = require( "kazmath" ) local bit = require( "bit" ) local framework = framework local require = require local tostring = tostring module( "framework.graphics" ) function draw( drawable, x, y, r, sx, sy, ox, oy, kx, ky ) x = x or 0 y = y or 0 drawable:draw( x, y, r, sx, sy, ox, oy, kx, ky ) end function getFont() return _font end function getFramebuffer() return _framebuffer end function getPolygonMode() local mode = ffi.new( "GLint[1]" ) GL.glGetIntegerv( GL.GL_POLYGON_MODE, mode ) if ( mode[0] == GL.GL_LINE ) then return "line" elseif( mode[0] == GL.GL_FILL ) then return "fill" end end function getSize() local width = ffi.new( "int[1]" ) local height = ffi.new( "int[1]" ) SDL.SDL_GL_GetDrawableSize( framework.window._window, width, height ) return width[0], height[0] end function newCubemap( type, filenames ) require( "framework.graphics.cubemap" ) local cubemap = framework.graphics.cubemap return cubemap( type, filenames ) end function newFont( filename, size ) require( "framework.graphics.font" ) local font = framework.graphics.font return font( filename, size ) end function newFramebuffer( type, width, height ) require( "framework.graphics.framebuffer" ) local framebuffer = framework.graphics.framebuffer return framebuffer( type, width, height ) end function newImage( filename, params ) require( "framework.graphics.image" ) local image = framework.graphics.image return image( filename, params ) end function newModel( filename ) require( "framework.graphics.model" ) local model = framework.graphics.model return model( filename ) end function print( text, x, y, r, sx, sy, ox, oy, kx, ky ) text = tostring( text ) x = x or 0 y = y or 0 local font = getFont() font:print( text, x, y, r, sx, sy, ox, oy, kx, ky ) end function setBackgroundColor( color ) GL.glClearColor( ( color[ 1 ] or 0 ) / 255, ( color[ 2 ] or 0 ) / 255, ( color[ 3 ] or 0 ) / 255, ( color[ 4 ] or 0 ) ) end function setFont( font ) _font = font end function setFramebuffer( framebuffer ) if ( framebuffer ) then GL.glBindFramebuffer( GL.GL_FRAMEBUFFER, framebuffer.framebuffer[0] ) local mode = framework.graphics.getMatrixMode() framework.graphics.setMatrixMode( "projection" ) local mat4 = framework.graphics.getTransformation() local width = framebuffer.width local height = framebuffer.height kazmath.kmMat4OrthographicProjection( mat4, 0, width, 0, height, -1.0, 1.0 ) framework.graphics.setMatrixMode( mode ) framework.graphics.updateTransformations() local dpiScale = framework.window.getPixelScale() setViewport( 0, 0, width * dpiScale, height * dpiScale ) else GL.glBindFramebuffer( GL.GL_FRAMEBUFFER, 0 ) framework.graphics.setOrthographicProjection( width, height ) local width, height = getSize() setViewport( 0, 0, width, height ) end _framebuffer = framebuffer end function setPolygonMode( mode ) if ( mode == "line" ) then mode = GL.GL_LINE elseif ( mode == "fill" ) then mode = GL.GL_FILL end GL.glPolygonMode( GL.GL_FRONT_AND_BACK, mode ) end function setScissor( x, y, width, height ) if ( _framebuffer ~= nil ) then GL.glScissor( x, y, width, height ) else GL.glScissor( x, _viewport.height - ( y + height ), width, height ) end end _viewport = _viewport or { x = 0, y = 0, width = 800, height = 600 } function setViewport( x, y, width, height ) GL.glViewport( x, y, width, height ) _viewport.x = x _viewport.y = y _viewport.width = width _viewport.height = height end function setVSync( vsync ) SDL.SDL_GL_SetSwapInterval( vsync and 1 or 0 ) end function clear() GL.glClear( bit.bor( GL.GL_COLOR_BUFFER_BIT, GL.GL_DEPTH_BUFFER_BIT ) ) end
Fix matrix stack leak
Fix matrix stack leak
Lua
mit
Planimeter/lgameframework,Planimeter/lgameframework,Planimeter/lgameframework
b07a44acf7695abefdb1a4e880c521118519f191
src/apps/config/alarm_codec.lua
src/apps/config/alarm_codec.lua
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(...,package.seeall) local S = require("syscall") local channel = require("apps.config.channel") local ffi = require("ffi") local UINT32_MAX = 0xffffffff local alarm_names = { 'raise_alarm', 'clear_alarm' } local alarm_codes = {} for i, name in ipairs(alarm_names) do alarm_codes[name] = i end local alarms = {} function alarms.raise_alarm (codec, resource, alarm_type_id, alarm_type_qualifier, perceived_severity, alarm_text) local resource = codec:string(resource) local alarm_type_id = codec:string(alarm_type_id) local alarm_type_qualifier = codec:string(alarm_type_qualifier) local perceived_severity = codec:maybe_string(perceived_severity) local alarm_text = codec:maybe_string(alarm_text) return codec:finish(resource, alarm_type_id, alarm_type_qualifier, perceived_severity, alarm_text) end function alarms.clear_alarm (codec, resource, alarm_type_id, alarm_type_qualifier) local resource = codec:string(resource) local alarm_type_id = codec:string(alarm_type_id) local alarm_type_qualifier = codec:string(alarm_type_qualifier) return codec:finish(resource, alarm_type_id, alarm_type_qualifier) end local function encoder() local encoder = { out = {} } function encoder:uint32(len) table.insert(self.out, ffi.new('uint32_t[1]', len)) end function encoder:string(str) self:uint32(#str) local buf = ffi.new('uint8_t[?]', #str) ffi.copy(buf, str, #str) table.insert(self.out, buf) end function encoder:maybe_string(str) if str == nil then self:uint32(UINT32_MAX) else self:string(str) end end function encoder:finish() local size = 0 for _,src in ipairs(self.out) do size = size + ffi.sizeof(src) end local dst = ffi.new('uint8_t[?]', size) local pos = 0 for _,src in ipairs(self.out) do ffi.copy(dst + pos, src, ffi.sizeof(src)) pos = pos + ffi.sizeof(src) end return dst, size end return encoder end function encode_raise_alarm (...) local codec = encoder() codec:uint32(assert(alarm_codes['raise_alarm'])) return assert(alarms['raise_alarm'])(codec, ...) end function encode_clear_alarm (...) local codec = encoder() codec:uint32(assert(alarm_codes['clear_alarm'])) return assert(alarms['clear_alarm'])(codec, ...) end local uint32_ptr_t = ffi.typeof('uint32_t*') local function decoder(buf, len) local decoder = { buf=buf, len=len, pos=0 } function decoder:read(count) local ret = self.buf + self.pos self.pos = self.pos + count assert(self.pos <= self.len) return ret end function decoder:uint32() return ffi.cast(uint32_ptr_t, self:read(4))[0] end function decoder:string() local len = self:uint32() return ffi.string(self:read(len), len) end function decoder:maybe_string() local len = self:uint32() if len == UINT32_MAX then return nil end return ffi.string(self:read(len), len) end function decoder:finish(...) return { ... } end return decoder end function decode(buf, len) local codec = decoder(buf, len) local name = assert(alarm_names[codec:uint32()]) return { name, assert(alarms[name], name)(codec) } end --- local alarms_channel function get_channel() if alarms_channel then return alarms_channel end local name = '/'..S.getpid()..'/alarms-follower-channel' local success, value = pcall(channel.open, name) if success then alarms_channel = value else alarms_channel = channel.create('alarms-follower-channel', 1e6) end return alarms_channel end local key_attrs = {'resource', 'alarm_type_id', 'alarm_type_qualifier'} local args_attrs = {'perceived_severity', 'alarm_text'} local function normalize (t, attrs) t = t or {} local ret = {} for _, k in ipairs(attrs) do table.insert(ret, t[k]) end return ret end local function normalize_key (t) return normalize(t, key_attrs) end local function normalize_args (t) return normalize(t, args_attrs) end -- To be used by the leader to group args into key and args. function parse_args (args) local resource, alarm_type_id, alarm_type_qualifier, perceived_severity, alarm_text = unpack(args) local key = { resource = resource, alarm_type_id = alarm_type_id, alarm_type_qualifier = alarm_type_qualifier, } local args = { perceived_severity = perceived_severity, alarm_text = alarm_text, } return key, args end function raise_alarm (key, args) local channel = get_channel() if channel then local resource, alarm_type_id, alarm_type_qualifier = unpack(normalize_key(key)) local perceived_severity, alarm_text = unpack(normalize_args(args)) local buf, len = encode_raise_alarm( resource, alarm_type_id, alarm_type_qualifier, perceived_severity, alarm_text ) channel:put_message(buf, len) end end function clear_alarm (key) local channel = get_channel() if channel then local resource, alarm_type_id, alarm_type_qualifier = unpack(normalize_key(key)) local buf, len = encode_clear_alarm(resource, alarm_type_id, alarm_type_qualifier) channel:put_message(buf, len) end end function selftest () print('selftest: apps.config.alarm_codec') local lib = require("core.lib") local function test_alarm (name, args) local encoded, len if name == 'raise_alarm' then encoded, len = encode_raise_alarm(unpack(args)) elseif name == 'clear_alarm' then encoded, len = encode_clear_alarm(unpack(args)) else error('not valid alarm name: '..alarm) end local decoded = decode(encoded, len) assert(lib.equal({name, args}, decoded)) end local function test_raise_alarm () local key = {resource='res1', alarm_type_id='type1', alarm_type_qualifier=''} local args = {perceived_severity='critical'} local resource, alarm_type_id, alarm_type_qualifier = unpack(normalize_key(key)) local perceived_severity, alarm_text = unpack(normalize_args(args)) local alarm = {resource, alarm_type_id, alarm_type_qualifier, perceived_severity, alarm_text} test_alarm('raise_alarm', alarm) end local function test_clear_alarm () local key = {resource='res1', alarm_type_id='type1', alarm_type_qualifier=''} local resource, alarm_type_id, alarm_type_qualifier = unpack(normalize_key(key)) local alarm = {resource, alarm_type_id, alarm_type_qualifier} test_alarm('clear_alarm', alarm) end test_raise_alarm() test_clear_alarm() print('selftest: ok') end
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(...,package.seeall) local S = require("syscall") local channel = require("apps.config.channel") local ffi = require("ffi") local UINT32_MAX = 0xffffffff local alarm_names = { 'raise_alarm', 'clear_alarm' } local alarm_codes = {} for i, name in ipairs(alarm_names) do alarm_codes[name] = i end local alarms = {} function alarms.raise_alarm (codec, resource, alarm_type_id, alarm_type_qualifier, perceived_severity, alarm_text) local resource = codec:string(resource) local alarm_type_id = codec:string(alarm_type_id) local alarm_type_qualifier = codec:string(alarm_type_qualifier) local perceived_severity = codec:maybe_string(perceived_severity) local alarm_text = codec:maybe_string(alarm_text) return codec:finish(resource, alarm_type_id, alarm_type_qualifier, perceived_severity, alarm_text) end function alarms.clear_alarm (codec, resource, alarm_type_id, alarm_type_qualifier) local resource = codec:string(resource) local alarm_type_id = codec:string(alarm_type_id) local alarm_type_qualifier = codec:string(alarm_type_qualifier) return codec:finish(resource, alarm_type_id, alarm_type_qualifier) end local function encoder() local encoder = { out = {} } function encoder:uint32(len) table.insert(self.out, ffi.new('uint32_t[1]', len)) end function encoder:string(str) self:uint32(#str) local buf = ffi.new('uint8_t[?]', #str) ffi.copy(buf, str, #str) table.insert(self.out, buf) end function encoder:maybe_string(str) if str == nil then self:uint32(UINT32_MAX) else self:string(str) end end function encoder:finish() local size = 0 for _,src in ipairs(self.out) do size = size + ffi.sizeof(src) end local dst = ffi.new('uint8_t[?]', size) local pos = 0 for _,src in ipairs(self.out) do ffi.copy(dst + pos, src, ffi.sizeof(src)) pos = pos + ffi.sizeof(src) end return dst, size end return encoder end function encode_raise_alarm (...) local codec = encoder() codec:uint32(assert(alarm_codes['raise_alarm'])) return assert(alarms['raise_alarm'])(codec, ...) end function encode_clear_alarm (...) local codec = encoder() codec:uint32(assert(alarm_codes['clear_alarm'])) return assert(alarms['clear_alarm'])(codec, ...) end local uint32_ptr_t = ffi.typeof('uint32_t*') local function decoder(buf, len) local decoder = { buf=buf, len=len, pos=0 } function decoder:read(count) local ret = self.buf + self.pos self.pos = self.pos + count assert(self.pos <= self.len) return ret end function decoder:uint32() return ffi.cast(uint32_ptr_t, self:read(4))[0] end function decoder:string() local len = self:uint32() return ffi.string(self:read(len), len) end function decoder:maybe_string() local len = self:uint32() if len == UINT32_MAX then return nil end return ffi.string(self:read(len), len) end function decoder:finish(...) return { ... } end return decoder end function decode(buf, len) local codec = decoder(buf, len) local name = assert(alarm_names[codec:uint32()]) return { name, assert(alarms[name], name)(codec) } end --- local alarms_channel function get_channel() if alarms_channel then return alarms_channel end local name = '/'..S.getpid()..'/alarms-follower-channel' local success, value = pcall(channel.open, name) if success then alarms_channel = value else alarms_channel = channel.create('alarms-follower-channel', 1e6) end return alarms_channel end local key_attrs = {'resource', 'alarm_type_id', 'alarm_type_qualifier'} local args_attrs = {'perceived_severity', 'alarm_text'} local function normalize (t, attrs) t = t or {} local ret = {} for i, k in ipairs(attrs) do ret[i] = t[k] end return ret end local function normalize_key (t) return normalize(t, key_attrs) end local function normalize_args (t) return normalize(t, args_attrs) end -- To be used by the leader to group args into key and args. function parse_args (args) local resource, alarm_type_id, alarm_type_qualifier, perceived_severity, alarm_text = unpack(args) local key = { resource = resource, alarm_type_id = alarm_type_id, alarm_type_qualifier = alarm_type_qualifier, } local args = { perceived_severity = perceived_severity, alarm_text = alarm_text, } return key, args end function raise_alarm (key, args) local channel = get_channel() if channel then local resource, alarm_type_id, alarm_type_qualifier = unpack(normalize_key(key)) local perceived_severity, alarm_text = unpack(normalize_args(args)) local buf, len = encode_raise_alarm( resource, alarm_type_id, alarm_type_qualifier, perceived_severity, alarm_text ) channel:put_message(buf, len) end end function clear_alarm (key) local channel = get_channel() if channel then local resource, alarm_type_id, alarm_type_qualifier = unpack(normalize_key(key)) local buf, len = encode_clear_alarm(resource, alarm_type_id, alarm_type_qualifier) channel:put_message(buf, len) end end function selftest () print('selftest: apps.config.alarm_codec') local lib = require("core.lib") local function test_alarm (name, args) local encoded, len if name == 'raise_alarm' then encoded, len = encode_raise_alarm(unpack(args)) elseif name == 'clear_alarm' then encoded, len = encode_clear_alarm(unpack(args)) else error('not valid alarm name: '..alarm) end local decoded = decode(encoded, len) assert(lib.equal({name, args}, decoded)) end local function test_raise_alarm () local key = {resource='res1', alarm_type_id='type1', alarm_type_qualifier=''} local args = {perceived_severity='critical'} local resource, alarm_type_id, alarm_type_qualifier = unpack(normalize_key(key)) local perceived_severity, alarm_text = unpack(normalize_args(args)) local alarm = {resource, alarm_type_id, alarm_type_qualifier, perceived_severity, alarm_text} test_alarm('raise_alarm', alarm) end local function test_clear_alarm () local key = {resource='res1', alarm_type_id='type1', alarm_type_qualifier=''} local resource, alarm_type_id, alarm_type_qualifier = unpack(normalize_key(key)) local alarm = {resource, alarm_type_id, alarm_type_qualifier} test_alarm('clear_alarm', alarm) end test_raise_alarm() test_clear_alarm() local a, b = unpack(normalize({b='foo'}, {'a', 'b'})) assert(a == nil and b == 'foo') print('selftest: ok') end
Fix unroll of sparse table
Fix unroll of sparse table
Lua
apache-2.0
Igalia/snabbswitch,eugeneia/snabb,eugeneia/snabb,eugeneia/snabbswitch,Igalia/snabb,alexandergall/snabbswitch,Igalia/snabb,eugeneia/snabb,dpino/snabbswitch,eugeneia/snabbswitch,SnabbCo/snabbswitch,Igalia/snabbswitch,dpino/snabb,eugeneia/snabb,dpino/snabb,eugeneia/snabb,alexandergall/snabbswitch,dpino/snabbswitch,eugeneia/snabbswitch,Igalia/snabb,alexandergall/snabbswitch,snabbco/snabb,Igalia/snabbswitch,snabbco/snabb,eugeneia/snabbswitch,Igalia/snabbswitch,Igalia/snabb,SnabbCo/snabbswitch,dpino/snabb,dpino/snabbswitch,alexandergall/snabbswitch,dpino/snabb,eugeneia/snabb,alexandergall/snabbswitch,Igalia/snabbswitch,alexandergall/snabbswitch,snabbco/snabb,snabbco/snabb,alexandergall/snabbswitch,Igalia/snabb,dpino/snabb,snabbco/snabb,snabbco/snabb,Igalia/snabb,Igalia/snabb,snabbco/snabb,eugeneia/snabb,dpino/snabbswitch,snabbco/snabb,SnabbCo/snabbswitch,SnabbCo/snabbswitch,alexandergall/snabbswitch,eugeneia/snabb,dpino/snabb,dpino/snabb,Igalia/snabb
945047f381384d74193ed412da89fc2556649daf
extensions/hints/init.lua
extensions/hints/init.lua
--- === hs.hints === --- --- Switch focus with a transient per-application keyboard shortcut local hints = require "hs.hints.internal" local screen = require "hs.screen" local window = require "hs.window" local hotkey = require "hs.hotkey" local modal_hotkey = hotkey.modal --- hs.hints.hintChars --- Variable --- This controls the set of characters that will be used for window hints. They must be characters found in hs.keycodes.map --- The default is the letters A-Z. hints.hintChars = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"} --- hs.hints.style --- Variable --- If this is set to "vimperator", every window hint starts with the first character --- of the parent application's title hints.style = "default" --- hs.hints.fontName --- Variable --- A fully specified family-face name, preferrably the PostScript name, such as Helvetica-BoldOblique or Times-Roman. (The Font Book app displays PostScript names of fonts in the Font Info panel.) --- The default value is the system font hints.fontName = nil --- hs.hints.fontSize --- Variable --- The size of font that should be used. A value of 0.0 will use the default size. hints.fontSize = 0.0 local openHints = {} local takenPositions = {} local hintDict = {} local modalKey = nil local bumpThresh = 40^2 local bumpMove = 80 function hints.bumpPos(x,y) for i, pos in ipairs(takenPositions) do if ((pos.x-x)^2 + (pos.y-y)^2) < bumpThresh then return hints.bumpPos(x,y+bumpMove) end end return {x = x,y = y} end function hints.addWindow(dict, win) local n = dict['count'] if n == nil then dict['count'] = 0 n = 0 end local m = (n % #hints.hintChars) + 1 local char = hints.hintChars[m] if n < #hints.hintChars then dict[char] = win else if type(dict[char]) == "userdata" then -- dict[m] is already occupied by another window -- which me must convert into a new dictionary local otherWindow = dict[char] dict[char] = {} hints.addWindow(dict, otherWindow) end hints.addWindow(dict[char], win) end dict['count'] = dict['count'] + 1 end function hints.displayHintsForDict(dict, prefixstring) for key, val in pairs(dict) do if type(val) == "userdata" then -- this is a window local win = val local app = win:application() local fr = win:frame() local sfr = win:screen():frame() if app and win:isStandard() then local c = {x = fr.x + (fr.w/2) - sfr.x, y = fr.y + (fr.h/2) - sfr.y} local d = hints.bumpPos(c.x, c.y) if d.y > (sfr.y + sfr.h - bumpMove) then d.x = d.x + bumpMove d.y = fr.y + (fr.h/2) - sfr.y d = hints.bumpPos(d.x, d.y) end c = d if c.y < 0 then print("hs.hints: Skipping offscreen window: "..win:title()) else -- print(win:title().." x:"..c.x.." y:"..c.y) -- debugging local hint = hints.new(c.x, c.y, prefixstring .. key, app:bundleID(), win:screen(), hints.fontName, hints.fontSize) table.insert(takenPositions, c) table.insert(openHints, hint) end end elseif type(val) == "table" then -- this is another window dict hints.displayHintsForDict(val, prefixstring .. key) end end end function hints.processChar(char) if hintDict[char] ~= nil then hints.closeHints() if type(hintDict[char]) == "userdata" then if hintDict[char] then hintDict[char]:focus() end modalKey:exit() elseif type(hintDict[char]) == "table" then hintDict = hintDict[char] if hintDict.count == 1 then hintDict.A:focus() modalKey:exit() else takenPositions = {} hints.displayHintsForDict(hintDict, "") end end end end function hints.setupModal() k = modal_hotkey.new(nil, nil) k:bind({}, 'escape', function() hints.closeHints(); k:exit() end) for _, c in ipairs(hints.hintChars) do k:bind({}, c, function() hints.processChar(c) end) end return k end --- hs.hints.windowHints() --- Function --- Displays a keyboard hint for switching focus to each window --- --- Parameters: --- * None --- --- Returns: --- * None --- --- Notes: --- * If there are more windows open than there are characters available in hs.hints.hintChars, --- we resort to multi-character hints --- * If hints.style is set to "vimperator", every window hint is prefixed with the first --- character of the parent application's name function hints.windowHints(windows) windows = windows or window.allWindows() if (modalKey == nil) then modalKey = hints.setupModal() end hints.closeHints() hintDict = {} for i, win in ipairs(windows) do local app = win:application() if app and win:isStandard() then if hints.style == "vimperator" then if app and win:isStandard() then local appchar = string.upper(string.sub(app:title(), 1, 1)) modalKey:bind({}, appchar, function() hints.processChar(appchar) end) if hintDict[appchar] == nil then hintDict[appchar] = {} end hints.addWindow(hintDict[appchar], win) end else hints.addWindow(hintDict, win) end end end takenPositions = {} if next(hintDict) ~= nil then hints.displayHintsForDict(hintDict, "") modalKey:enter() end end function hints.closeHints() for _, hint in ipairs(openHints) do hint:close() end openHints = {} takenPositions = {} end return hints
--- === hs.hints === --- --- Switch focus with a transient per-application keyboard shortcut local hints = require "hs.hints.internal" local screen = require "hs.screen" local window = require "hs.window" local hotkey = require "hs.hotkey" local modal_hotkey = hotkey.modal --- hs.hints.hintChars --- Variable --- This controls the set of characters that will be used for window hints. They must be characters found in hs.keycodes.map --- The default is the letters A-Z. hints.hintChars = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"} --- hs.hints.style --- Variable --- If this is set to "vimperator", every window hint starts with the first character --- of the parent application's title hints.style = "default" --- hs.hints.fontName --- Variable --- A fully specified family-face name, preferrably the PostScript name, such as Helvetica-BoldOblique or Times-Roman. (The Font Book app displays PostScript names of fonts in the Font Info panel.) --- The default value is the system font hints.fontName = nil --- hs.hints.fontSize --- Variable --- The size of font that should be used. A value of 0.0 will use the default size. hints.fontSize = 0.0 local openHints = {} local takenPositions = {} local hintDict = {} local modalKey = nil local bumpThresh = 40^2 local bumpMove = 80 function hints.bumpPos(x,y) for i, pos in ipairs(takenPositions) do if ((pos.x-x)^2 + (pos.y-y)^2) < bumpThresh then return hints.bumpPos(x,y+bumpMove) end end return {x = x,y = y} end function hints.addWindow(dict, win) local n = dict['count'] if n == nil then dict['count'] = 0 n = 0 end local m = (n % #hints.hintChars) + 1 local char = hints.hintChars[m] if n < #hints.hintChars then dict[char] = win else if type(dict[char]) == "userdata" then -- dict[m] is already occupied by another window -- which me must convert into a new dictionary local otherWindow = dict[char] dict[char] = {} hints.addWindow(dict, otherWindow) end hints.addWindow(dict[char], win) end dict['count'] = dict['count'] + 1 end function hints.displayHintsForDict(dict, prefixstring) for key, val in pairs(dict) do if type(val) == "userdata" then -- this is a window local win = val local app = win:application() local fr = win:frame() local sfr = win:screen():frame() if app and win:isStandard() then local c = {x = fr.x + (fr.w/2) - sfr.x, y = fr.y + (fr.h/2) - sfr.y} local d = hints.bumpPos(c.x, c.y) if d.y > (sfr.y + sfr.h - bumpMove) then d.x = d.x + bumpMove d.y = fr.y + (fr.h/2) - sfr.y d = hints.bumpPos(d.x, d.y) end c = d if c.y < 0 then print("hs.hints: Skipping offscreen window: "..win:title()) else -- print(win:title().." x:"..c.x.." y:"..c.y) -- debugging local hint = hints.new(c.x, c.y, prefixstring .. key, app:bundleID(), win:screen(), hints.fontName, hints.fontSize) table.insert(takenPositions, c) table.insert(openHints, hint) end end elseif type(val) == "table" then -- this is another window dict hints.displayHintsForDict(val, prefixstring .. key) end end end function hints.processChar(char) if hintDict[char] ~= nil then hints.closeHints() if type(hintDict[char]) == "userdata" then if hintDict[char] then hintDict[char]:focus() end modalKey:exit() elseif type(hintDict[char]) == "table" then hintDict = hintDict[char] if hintDict.count == 1 then hintDict.A:focus() modalKey:exit() else takenPositions = {} hints.displayHintsForDict(hintDict, "") end end end end function hints.setupModal() k = modal_hotkey.new(nil, nil) k:bind({}, 'escape', function() hints.closeHints(); k:exit() end) for _, c in ipairs(hints.hintChars) do k:bind({}, c, function() hints.processChar(c) end) end return k end --- hs.hints.windowHints(windows) --- Function --- Displays a keyboard hint for switching focus to each window --- --- Parameters: --- * windows - A table containing some `hs.window` objects --- --- Returns: --- * None --- --- Notes: --- * If there are more windows open than there are characters available in hs.hints.hintChars, --- we resort to multi-character hints --- * If hints.style is set to "vimperator", every window hint is prefixed with the first --- character of the parent application's name --- * To display hints only for the currently focused application, try something like: --- * `hs.hints.windowHints(hs.window.focusedWindow():application():allWindows())` function hints.windowHints(windows) windows = windows or window.allWindows() if (modalKey == nil) then modalKey = hints.setupModal() end hints.closeHints() hintDict = {} for i, win in ipairs(windows) do local app = win:application() if app and win:isStandard() then if hints.style == "vimperator" then if app and win:isStandard() then local appchar = string.upper(string.sub(app:title(), 1, 1)) modalKey:bind({}, appchar, function() hints.processChar(appchar) end) if hintDict[appchar] == nil then hintDict[appchar] = {} end hints.addWindow(hintDict[appchar], win) end else hints.addWindow(hintDict, win) end end end takenPositions = {} if next(hintDict) ~= nil then hints.displayHintsForDict(hintDict, "") modalKey:enter() end end function hints.closeHints() for _, hint in ipairs(openHints) do hint:close() end openHints = {} takenPositions = {} end return hints
Fix up docs for preceeding PR
Fix up docs for preceeding PR
Lua
mit
Stimim/hammerspoon,latenitefilms/hammerspoon,hypebeast/hammerspoon,zzamboni/hammerspoon,Stimim/hammerspoon,chrisjbray/hammerspoon,tmandry/hammerspoon,latenitefilms/hammerspoon,Hammerspoon/hammerspoon,lowne/hammerspoon,zzamboni/hammerspoon,kkamdooong/hammerspoon,cmsj/hammerspoon,CommandPost/CommandPost-App,asmagill/hammerspoon,knu/hammerspoon,CommandPost/CommandPost-App,asmagill/hammerspoon,Habbie/hammerspoon,Hammerspoon/hammerspoon,emoses/hammerspoon,chrisjbray/hammerspoon,wsmith323/hammerspoon,joehanchoi/hammerspoon,knu/hammerspoon,junkblocker/hammerspoon,emoses/hammerspoon,wvierber/hammerspoon,chrisjbray/hammerspoon,heptal/hammerspoon,junkblocker/hammerspoon,Hammerspoon/hammerspoon,Hammerspoon/hammerspoon,ocurr/hammerspoon,peterhajas/hammerspoon,peterhajas/hammerspoon,nkgm/hammerspoon,chrisjbray/hammerspoon,Habbie/hammerspoon,CommandPost/CommandPost-App,peterhajas/hammerspoon,zzamboni/hammerspoon,bradparks/hammerspoon,emoses/hammerspoon,CommandPost/CommandPost-App,peterhajas/hammerspoon,zzamboni/hammerspoon,cmsj/hammerspoon,tmandry/hammerspoon,nkgm/hammerspoon,kkamdooong/hammerspoon,junkblocker/hammerspoon,zzamboni/hammerspoon,TimVonsee/hammerspoon,CommandPost/CommandPost-App,trishume/hammerspoon,kkamdooong/hammerspoon,junkblocker/hammerspoon,nkgm/hammerspoon,TimVonsee/hammerspoon,wvierber/hammerspoon,Hammerspoon/hammerspoon,Habbie/hammerspoon,asmagill/hammerspoon,dopcn/hammerspoon,knu/hammerspoon,wvierber/hammerspoon,lowne/hammerspoon,trishume/hammerspoon,wvierber/hammerspoon,knu/hammerspoon,hypebeast/hammerspoon,hypebeast/hammerspoon,lowne/hammerspoon,cmsj/hammerspoon,latenitefilms/hammerspoon,dopcn/hammerspoon,dopcn/hammerspoon,CommandPost/CommandPost-App,emoses/hammerspoon,knl/hammerspoon,asmagill/hammerspoon,bradparks/hammerspoon,asmagill/hammerspoon,Habbie/hammerspoon,Habbie/hammerspoon,ocurr/hammerspoon,heptal/hammerspoon,joehanchoi/hammerspoon,TimVonsee/hammerspoon,joehanchoi/hammerspoon,wsmith323/hammerspoon,knl/hammerspoon,nkgm/hammerspoon,cmsj/hammerspoon,knl/hammerspoon,knl/hammerspoon,ocurr/hammerspoon,Stimim/hammerspoon,joehanchoi/hammerspoon,zzamboni/hammerspoon,wvierber/hammerspoon,chrisjbray/hammerspoon,ocurr/hammerspoon,latenitefilms/hammerspoon,TimVonsee/hammerspoon,tmandry/hammerspoon,hypebeast/hammerspoon,bradparks/hammerspoon,bradparks/hammerspoon,TimVonsee/hammerspoon,nkgm/hammerspoon,Stimim/hammerspoon,peterhajas/hammerspoon,lowne/hammerspoon,ocurr/hammerspoon,joehanchoi/hammerspoon,emoses/hammerspoon,cmsj/hammerspoon,knu/hammerspoon,cmsj/hammerspoon,Habbie/hammerspoon,wsmith323/hammerspoon,dopcn/hammerspoon,kkamdooong/hammerspoon,wsmith323/hammerspoon,hypebeast/hammerspoon,lowne/hammerspoon,latenitefilms/hammerspoon,wsmith323/hammerspoon,asmagill/hammerspoon,kkamdooong/hammerspoon,dopcn/hammerspoon,knl/hammerspoon,Stimim/hammerspoon,Hammerspoon/hammerspoon,chrisjbray/hammerspoon,knu/hammerspoon,bradparks/hammerspoon,heptal/hammerspoon,junkblocker/hammerspoon,heptal/hammerspoon,trishume/hammerspoon,latenitefilms/hammerspoon,heptal/hammerspoon
eabe8561139b46728a8ead4ca23bf3ab07c4119d
lua/tests/types/undefined_t.lua
lua/tests/types/undefined_t.lua
-- Copyright (c) 2009-2010 Incremental IP Limited -- see LICENSE for license information local type = type local series = require("test.series") local undefined_t = require("rima.types.undefined_t") local object = require("rima.lib.object") local rima = require("rima") module(...) -- Tests ----------------------------------------------------------------------- function test(options) local T = series:new(_M, options) T:test(undefined_t:isa(undefined_t:new()), "isa(undefined_t:new(), undefined_t)") T:check_equal(object.type(undefined_t:new()), 'undefined_t', "type(undefined_t:new()) == 'undefined_t'") T:check_equal(undefined_t:new(), 'undefined', "repr(undefined_t:new()) == 'undefined'") T:check_equal(undefined_t:new():describe("a"), 'a undefined', "undefined:describe()'") T:check_equal(undefined_t:new():describe("b"), 'b undefined', "undefined:describe()'") T:test(undefined_t:new():includes(1), "undefined:includes()'") T:test(undefined_t:new():includes("a"), "undefined:includes()'") T:test(undefined_t:new():includes({}), "undefined:includes()'") T:test(undefined_t:new():includes(nil), "undefined:includes()'") do local x = rima.R"x" local S = { x = undefined_t:new() } T:check_equal(rima.E(x), "x") T:check_equal(rima.E(x + 1), "1 + x") end return T:close() end -- EOF -------------------------------------------------------------------------
-- Copyright (c) 2009-2010 Incremental IP Limited -- see LICENSE for license information local type = type local series = require("test.series") local undefined_t = require("rima.types.undefined_t") local object = require("rima.lib.object") local lib = require("rima.lib") local core = require("rima.core") local rima = require("rima") module(...) -- Tests ----------------------------------------------------------------------- function test(options) local T = series:new(_M, options) local E = core.eval T:test(undefined_t:isa(undefined_t:new()), "isa(undefined_t:new(), undefined_t)") T:check_equal(object.type(undefined_t:new()), 'undefined_t', "type(undefined_t:new()) == 'undefined_t'") T:check_equal(undefined_t:new(), 'undefined', "repr(undefined_t:new()) == 'undefined'") T:check_equal(undefined_t:new():describe("a"), 'a undefined', "undefined:describe()'") T:check_equal(undefined_t:new():describe("b"), 'b undefined', "undefined:describe()'") T:test(undefined_t:new():includes(1), "undefined:includes()'") T:test(undefined_t:new():includes("a"), "undefined:includes()'") T:test(undefined_t:new():includes({}), "undefined:includes()'") T:test(undefined_t:new():includes(nil), "undefined:includes()'") do local x = rima.R"x" local S = rima.scope.new{ x = undefined_t:new() } T:check_equal(E(x, S), "x") T:check_equal(E(x + 1, S), "1 + x") end do local x, y, z = rima.R"x, y, z" local S = rima.scope.new{ x = { undefined_t:new() }} local e = rima.sum{y=x}(x[y]) T:check_equal(E(e, S), "x[1]") T:check_equal(lib.dump(E(e, S)), "index(ref(x), address{1})") end return T:close() end -- EOF -------------------------------------------------------------------------
rima: fixed up tests for undefined_t
rima: fixed up tests for undefined_t
Lua
mit
geoffleyland/rima,geoffleyland/rima,geoffleyland/rima
9591f86d1807be9ce29c2e0ed2b327d410d3d411
mod_auth_ldap/mod_auth_ldap.lua
mod_auth_ldap/mod_auth_ldap.lua
-- mod_auth_ldap local new_sasl = require "util.sasl".new; local lualdap = require "lualdap"; local function ldap_filter_escape(s) return (s:gsub("[\\*\\(\\)\\\\%z]", function(c) return ("\\%02x"):format(c:byte()) end)); end -- Config options local ldap_server = module:get_option_string("ldap_server", "localhost"); local ldap_rootdn = module:get_option_string("ldap_rootdn", ""); local ldap_password = module:get_option_string("ldap_password", ""); local ldap_tls = module:get_option_boolean("ldap_tls"); local ldap_scope = module:get_option_string("ldap_scope", "onelevel"); local ldap_filter = module:get_option_string("ldap_filter", "(uid=$user)"):gsub("%%s", "$user", 1); local ldap_base = assert(module:get_option_string("ldap_base"), "ldap_base is a required option for ldap"); local ldap_mode = module:get_option_string("ldap_mode", "getpasswd"); local host = ldap_filter_escape(module:get_option_string("realm", module.host)); -- Initiate connection local ld = assert(lualdap.open_simple(ldap_server, ldap_rootdn, ldap_password, ldap_tls)); module.unload = function() ld:close(); end local function get_user(username) module:log("debug", "get_user(%q)", username); return ld:search({ base = ldap_base; scope = ldap_scope; filter = ldap_filter:gsub("%$(%a+)", { user = ldap_filter_escape(username); host = host; }); })(); end local provider = {}; function provider.create_user(username, password) return nil, "Account creation not available with LDAP."; end function provider.user_exists(username) return not not get_user(username); end function provider.set_password(username, password) local dn, attr = get_user(username); if not dn then return nil, attr end if attr.userPassword == password then return true end return ld:modify(dn, { '=', userPassword = password })(); end if ldap_mode == "getpasswd" then function provider.get_password(username) local dn, attr = get_user(username); if dn and attr then return attr.userPassword; end end function provider.test_password(username, password) return provider.get_password(username) == password; end function provider.get_sasl_handler() return new_sasl(module.host, { plain = function(sasl, username) local password = provider.get_password(username); if not password then return "", nil; end return password, true; end }); end elseif ldap_mode == "bind" then local function test_password(userdn, password) return not not lualdap.open_simple(ldap_server, userdn, password, ldap_tls); end function provider.test_password(username, password) local dn = get_user(username); if not dn then return end return test_password(dn, password) end function provider.get_sasl_handler() return new_sasl(module.host, { plain_test = function(sasl, username, password) return provider.test_password(username, password), true; end }); end else module:log("error", "Unsupported ldap_mode %s", tostring(ldap_mode)); end module:provides("auth", provider);
-- mod_auth_ldap local new_sasl = require "util.sasl".new; local lualdap = require "lualdap"; local function ldap_filter_escape(s) return (s:gsub("[\\*\\(\\)\\\\%z]", function(c) return ("\\%02x"):format(c:byte()) end)); end -- Config options local ldap_server = module:get_option_string("ldap_server", "localhost"); local ldap_rootdn = module:get_option_string("ldap_rootdn", ""); local ldap_password = module:get_option_string("ldap_password", ""); local ldap_tls = module:get_option_boolean("ldap_tls"); local ldap_scope = module:get_option_string("ldap_scope", "onelevel"); local ldap_filter = module:get_option_string("ldap_filter", "(uid=$user)"):gsub("%%s", "$user", 1); local ldap_base = assert(module:get_option_string("ldap_base"), "ldap_base is a required option for ldap"); local ldap_mode = module:get_option_string("ldap_mode", "getpasswd"); local host = ldap_filter_escape(module:get_option_string("realm", module.host)); -- Initiate connection local ld = assert(lualdap.open_simple(ldap_server, ldap_rootdn, ldap_password, ldap_tls)); module.unload = function() ld:close(); end local function get_user(username) module:log("debug", "get_user(%q)", username); for dn, attr in ld:search({ base = ldap_base; scope = ldap_scope; filter = ldap_filter:gsub("%$(%a+)", { user = ldap_filter_escape(username); host = host; }); }) do return dn, attr; end end local provider = {}; function provider.create_user(username, password) return nil, "Account creation not available with LDAP."; end function provider.user_exists(username) return not not get_user(username); end function provider.set_password(username, password) local dn, attr = get_user(username); if not dn then return nil, attr end if attr.userPassword == password then return true end return ld:modify(dn, { '=', userPassword = password })(); end if ldap_mode == "getpasswd" then function provider.get_password(username) local dn, attr = get_user(username); if dn and attr then return attr.userPassword; end end function provider.test_password(username, password) return provider.get_password(username) == password; end function provider.get_sasl_handler() return new_sasl(module.host, { plain = function(sasl, username) local password = provider.get_password(username); if not password then return "", nil; end return password, true; end }); end elseif ldap_mode == "bind" then local function test_password(userdn, password) return not not lualdap.open_simple(ldap_server, userdn, password, ldap_tls); end function provider.test_password(username, password) local dn = get_user(username); if not dn then return end return test_password(dn, password) end function provider.get_sasl_handler() return new_sasl(module.host, { plain_test = function(sasl, username, password) return provider.test_password(username, password), true; end }); end else module:log("error", "Unsupported ldap_mode %s", tostring(ldap_mode)); end module:provides("auth", provider);
mod_auth_ldap: Fix issue with some versions of LuaLDAP
mod_auth_ldap: Fix issue with some versions of LuaLDAP
Lua
mit
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
6cf7b83cee5bcd2c0923b09700851c4bed09ab54
mod_seclabels/mod_seclabels.lua
mod_seclabels/mod_seclabels.lua
local st = require "util.stanza"; local xmlns_label = "urn:xmpp:sec-label:0"; local xmlns_label_catalog = "urn:xmpp:sec-label:catalog:0"; module:add_feature(xmlns_label); local labels = { Classified = { SECRET = { color = "black", bgcolor = "aqua", label = "THISISSECRET" }; PUBLIC = { label = "THISISPUBLIC" }; }; }; module:hook("iq/self/"..xmlns_label_catalog..":catalog", function (request) local catalog_request = request.stanza.tags[1]; local reply = st.reply(request.stanza) :tag("catalog", { xmlns = xmlns_label_catalog, to = catalog_request.attr.to, name = "Default", desc = "My labels" }); local function add_labels(catalog, labels, selector) for name, value in pairs(labels) do if value.label then catalog:tag("securitylabel", { xmlns = xmlns_label, selector = selector..name }) :tag("displaymarking", { fgcolor = value.color or "black", bgcolor = value.bgcolor or "white", }):text(value.name or name):up() :tag("label"); if type(value.label) == "string" then catalog:text(value.label); else catalog:add_child(value.label); end catalog:up():up(); else add_labels(catalog, value, (selector or "")..name.."|"); end end end add_labels(reply, labels); request.origin.send(reply); return true; end);
local st = require "util.stanza"; local xmlns_label = "urn:xmpp:sec-label:0"; local xmlns_label_catalog = "urn:xmpp:sec-label:catalog:0"; module:add_feature(xmlns_label); module:hook("account-disco-info", function(event) local stanza = event.stanza; stanza:tag('feature', {var=xmlns_label}):up(); stanza:tag('feature', {var=xmlns_label_catalog}):up(); end); local labels = { Classified = { SECRET = { color = "black", bgcolor = "aqua", label = "THISISSECRET" }; PUBLIC = { label = "THISISPUBLIC" }; }; }; module:hook("iq/self/"..xmlns_label_catalog..":catalog", function (request) local catalog_request = request.stanza.tags[1]; local reply = st.reply(request.stanza) :tag("catalog", { xmlns = xmlns_label_catalog, to = catalog_request.attr.to, name = "Default", desc = "My labels" }); local function add_labels(catalog, labels, selector) for name, value in pairs(labels) do if value.label then catalog:tag("securitylabel", { xmlns = xmlns_label, selector = selector..name }) :tag("displaymarking", { fgcolor = value.color or "black", bgcolor = value.bgcolor or "white", }):text(value.name or name):up() :tag("label"); if type(value.label) == "string" then catalog:text(value.label); else catalog:add_child(value.label); end catalog:up():up(); else add_labels(catalog, value, (selector or "")..name.."|"); end end end add_labels(reply, labels); request.origin.send(reply); return true; end);
mod_seclabels: Advertise features in account disco#info, fixes interop with Swift
mod_seclabels: Advertise features in account disco#info, fixes interop with Swift
Lua
mit
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
80b9a2414f9f2b6b5ff946cf8ebe43e796770d2d
lua-binding/CCB/Loader.lua
lua-binding/CCB/Loader.lua
local CCBLoader = {} local function fillCallbacks(proxy, owner, names, nodes, events) if not owner then return end --Callbacks for i = 1, #names do local callbackName = names[i] local callbackNode = tolua.cast(nodes[i],"cc.Node") proxy:setCallback(callbackNode, function(sender, event) if owner and owner[callbackName] and "function" == type(owner[callbackName]) then owner[callbackName](owner, sender, event) else print("Warning: Cannot find lua function:" .. ":" .. callbackName .. " for selector") end end, events[i]) end end local function fillMembers(owner, names, nodes) if not owner then return end --Variables for i = 1, #names do local outletName = names[i] local outletNode = tolua.cast(nodes[i],"cc.Node") owner[outletName] = outletNode -- print("fillMembers:", outletName, outletNode) end end local function extend(node, name) local codePath = (CCBLoader.codeRootPath and CCBLoader.codeRootPath ~= "") and CCBLoader.codeRootPath .. "." .. name or name local luaObj = require(codePath) for k,v in pairs(luaObj) do node[k] = v end end local function fillNode(proxy, ccbReader, owner) local rootName = ccbReader:getDocumentControllerName() local animationManager = ccbReader:getActionManager() local node = animationManager:getRootNode() -- print("fillNode:", rootName, node) --owner set in readCCBFromFile is proxy if nil ~= owner then --Callbacks local ownerCallbackNames = ccbReader:getOwnerCallbackNames() local ownerCallbackNodes = ccbReader:getOwnerCallbackNodes() local ownerCallbackControlEvents = ccbReader:getOwnerCallbackControlEvents() fillCallbacks(proxy, owner, ownerCallbackNames, ownerCallbackNodes, ownerCallbackControlEvents) --Variables local ownerOutletNames = ccbReader:getOwnerOutletNames() local ownerOutletNodes = ccbReader:getOwnerOutletNodes() fillMembers(owner, ownerOutletNames, ownerOutletNodes) end --document root if "" ~= rootName then extend(node, rootName) node.animationManager = animationManager --Callbacks local documentCallbackNames = animationManager:getDocumentCallbackNames() local documentCallbackNodes = animationManager:getDocumentCallbackNodes() local documentCallbackControlEvents = animationManager:getDocumentCallbackControlEvents() fillCallbacks(proxy, node, documentCallbackNames, documentCallbackNodes, documentCallbackControlEvents) --Variables local documentOutletNames = animationManager:getDocumentOutletNames() local documentOutletNodes = animationManager:getDocumentOutletNodes() fillMembers(node, documentOutletNames, documentOutletNodes) --[[ if (typeof(controller.onDidLoadFromCCB) == "function") controller.onDidLoadFromCCB(); ]]-- --Setup timeline callbacks local keyframeCallbacks = animationManager:getKeyframeCallbacks() for i = 1 , #keyframeCallbacks do local callbackCombine = keyframeCallbacks[i] local beignIndex,endIndex = string.find(callbackCombine,":") local callbackType = tonumber(string.sub(callbackCombine,1,beignIndex - 1)) local callbackName = string.sub(callbackCombine,endIndex + 1, -1) --Document callback if 1 == callbackType then local callfunc = cc.CallFunc:create(function(sender, event) if node and node[callbackName] and type(node[callbackName]) == "function" then node[callbackName](node, sender, event) else print("Warning: Cannot find lua function:" .. callbackName .. " for animation selector") end end) animationManager:setCallFuncForLuaCallbackNamed(callfunc, callbackCombine); elseif 2 == callbackType and nil ~= owner then --Owner callback local callfunc = cc.CallFunc:create(owner[callbackName])--need check animationManager:setCallFuncForLuaCallbackNamed(callfunc, callbackCombine) end end --start animation local autoPlaySeqId = animationManager:getAutoPlaySequenceId() if -1 ~= autoPlaySeqId then animationManager:runAnimationsForSequenceIdTweenDuration(autoPlaySeqId, 0) end end --subReaders local subReaders = ccbReader:getSubReaders() -- print("subReaders:", subReaders and #subReaders or 0, subReaders) -- table.dump(subReaders) if subReaders then for i=1, #subReaders do local reader = subReaders[i] fillNode(proxy, reader, owner) end end end local function doLoad(fileName, proxy, owner) if nil == proxy then return nil end local strFilePath = (CCBLoader.ccbiRootPath and CCBLoader.ccbiRootPath ~= "") and CCBLoader.ccbiRootPath .. fileName or fileName local ccbReader = proxy:createCCBReader() local node = ccbReader:load(strFilePath) fillNode(proxy, ccbReader, owner) return node end ------------------------------------------------------------ function CCBLoader:setRootPath(codeRoot, ccbiRoot) if ccbiRoot and string.sub(ccbiRoot, -1) ~= "/" then ccbiRoot = ccbiRoot .. "/" end self.codeRootPath = codeRoot or self.codeRootPath self.ccbiRootPath = ccbiRoot or self.ccbiRootPath end function CCBLoader:load(fileName, owner) local proxy = cc.CCBProxy:create() return doLoad(fileName, proxy, owner) end return CCBLoader
local CCBLoader = {} local function fillCallbacks(proxy, owner, names, nodes, events) if not owner then return end --Callbacks for i = 1, #names do local callbackName = names[i] local callbackNode = tolua.cast(nodes[i],"cc.Node") proxy:setCallback(callbackNode, function(sender, event) if owner and owner[callbackName] and "function" == type(owner[callbackName]) then owner[callbackName](owner, sender, event) else print("Warning: Cannot find lua function:" .. ":" .. callbackName .. " for selector") end end, events[i]) end end local function fillMembers(owner, names, nodes) if not owner then return end --Variables for i = 1, #names do local outletName = names[i] local outletNode = tolua.cast(nodes[i],"cc.Node") owner[outletName] = outletNode -- print("fillMembers:", outletName, outletNode) end end local function extend(node, name, isRoot) local codePath = (CCBLoader.codeRootPath and CCBLoader.codeRootPath ~= "") and CCBLoader.codeRootPath .. "." .. name or name local luaObj = require(codePath) for k,v in pairs(luaObj) do node[k] = v end if not isRoot then node:ctor() end end local function fillNode(proxy, ccbReader, owner, isRoot) local rootName = ccbReader:getDocumentControllerName() local animationManager = ccbReader:getActionManager() local node = animationManager:getRootNode() -- print("fillNode:", rootName, node) --owner set in readCCBFromFile is proxy if nil ~= owner then --Callbacks local ownerCallbackNames = ccbReader:getOwnerCallbackNames() local ownerCallbackNodes = ccbReader:getOwnerCallbackNodes() local ownerCallbackControlEvents = ccbReader:getOwnerCallbackControlEvents() fillCallbacks(proxy, owner, ownerCallbackNames, ownerCallbackNodes, ownerCallbackControlEvents) --Variables local ownerOutletNames = ccbReader:getOwnerOutletNames() local ownerOutletNodes = ccbReader:getOwnerOutletNodes() fillMembers(owner, ownerOutletNames, ownerOutletNodes) end --document root if "" ~= rootName then extend(node, rootName, isRoot) node.animationManager = animationManager --Callbacks local documentCallbackNames = animationManager:getDocumentCallbackNames() local documentCallbackNodes = animationManager:getDocumentCallbackNodes() local documentCallbackControlEvents = animationManager:getDocumentCallbackControlEvents() fillCallbacks(proxy, node, documentCallbackNames, documentCallbackNodes, documentCallbackControlEvents) --Variables local documentOutletNames = animationManager:getDocumentOutletNames() local documentOutletNodes = animationManager:getDocumentOutletNodes() fillMembers(node, documentOutletNames, documentOutletNodes) --[[ if (typeof(controller.onDidLoadFromCCB) == "function") controller.onDidLoadFromCCB(); ]]-- --Setup timeline callbacks local keyframeCallbacks = animationManager:getKeyframeCallbacks() for i = 1 , #keyframeCallbacks do local callbackCombine = keyframeCallbacks[i] local beignIndex,endIndex = string.find(callbackCombine,":") local callbackType = tonumber(string.sub(callbackCombine,1,beignIndex - 1)) local callbackName = string.sub(callbackCombine,endIndex + 1, -1) --Document callback if 1 == callbackType then local callfunc = cc.CallFunc:create(function(sender, event) if node and node[callbackName] and type(node[callbackName]) == "function" then node[callbackName](node, sender, event) else print("Warning: Cannot find lua function:" .. callbackName .. " for animation selector") end end) animationManager:setCallFuncForLuaCallbackNamed(callfunc, callbackCombine); elseif 2 == callbackType and nil ~= owner then --Owner callback local callfunc = cc.CallFunc:create(owner[callbackName])--need check animationManager:setCallFuncForLuaCallbackNamed(callfunc, callbackCombine) end end --start animation local autoPlaySeqId = animationManager:getAutoPlaySequenceId() if -1 ~= autoPlaySeqId then animationManager:runAnimationsForSequenceIdTweenDuration(autoPlaySeqId, 0) end end --subReaders local subReaders = ccbReader:getSubReaders() -- print("subReaders:", subReaders and #subReaders or 0, subReaders) -- table.dump(subReaders) if subReaders then for i=1, #subReaders do local reader = subReaders[i] fillNode(proxy, reader, owner, false) end end end local function doLoad(fileName, proxy, owner) if nil == proxy then return nil end local strFilePath = (CCBLoader.ccbiRootPath and CCBLoader.ccbiRootPath ~= "") and CCBLoader.ccbiRootPath .. fileName or fileName local ccbReader = proxy:createCCBReader() local node = ccbReader:load(strFilePath) fillNode(proxy, ccbReader, owner, true) return node end ------------------------------------------------------------ function CCBLoader:setRootPath(codeRoot, ccbiRoot) if ccbiRoot and string.sub(ccbiRoot, -1) ~= "/" then ccbiRoot = ccbiRoot .. "/" end self.codeRootPath = codeRoot or self.codeRootPath self.ccbiRootPath = ccbiRoot or self.ccbiRootPath end function CCBLoader:load(fileName, owner) local proxy = cc.CCBProxy:create() return doLoad(fileName, proxy, owner) end return CCBLoader
solve sub node ctor not called bug
solve sub node ctor not called bug
Lua
mit
Jennal/CocosBuilder,Jennal/CocosBuilder,Jennal/CocosBuilder,Jennal/CocosBuilder,Jennal/CocosBuilder
31eb022a200a9f3fa11ff33b7129482a17f63953
fblualib/util/test/digraph_test.lua
fblualib/util/test/digraph_test.lua
-- -- Copyright (c) 2014, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. -- local digraph = require('fb.util.digraph') local pl = require('pl.import_into')() require('fb.luaunit') local function sorted(t) return pl.List(t):sort() end local function print_values(t) for _, v in ipairs(t) do print(v) end end local function check_topo_sort(ts, edges) local imap = pl.tablex.index_map(ts) for _, edge in ipairs(edges) do local v, w = table.unpack(edge) assertTrue(imap[v] < imap[w]) end end TestDigraph = {} function TestDigraph:setUp() self.G = digraph.Digraph() for i = 1, 10 do self.G:add_vertex(i) end for i = 1, 9 do self.G:add_edge(i + 1, i, i * 10) end end function TestDigraph:testBasic() local G = self.G assertEquals(10, #G) assertEquals(10, G:vertex_count()) assertEquals(9, G:edge_count()) assertEquals({10}, G:sources()) assertEquals({1}, G:sinks()) assertTrue(pl.tablex.compare_no_order( {[4] = 40}, G:out_edges(5))) assertTrue(pl.tablex.compare_no_order( {[5] = 40}, G:in_edges(4))) G:add_edge(1, 3) assertEquals({}, G:sinks()) assertEquals({}, G:predecessors(1)) assertEquals({3}, sorted(G:successors(1))) assertEquals({1, 4}, sorted(G:predecessors(3))) assertEquals({2}, G:successors(3)) end function TestDigraph:testForEach() local G = self.G local seen = {} G:for_each(function(v) seen[v] = (seen[v] or 0) + 1 end) assertEquals(pl.Set(seen), pl.Set({1, 1, 1, 1, 1, 1, 1, 1, 1, 1})) end function TestDigraph:testTopoSort1() local G = self.G assertEquals({10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, G:topo_sort()); assertEquals({1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, G:reverse_topo_sort()); G:add_edge(1, 5); assertError(G.topo_sort, G); assertError(G.reverse_topo_sort, G); end function TestDigraph:testClone() local G = self.G:clone( function(v) return string.format('v%d', v) end, function(e) return string.format('e%d', e) end) assertEquals(10, #G) assertEquals(10, G:vertex_count()) assertEquals(9, G:edge_count()) assertEquals({'v10'}, G:sources()) assertEquals({'v1'}, G:sinks()) assertTrue(pl.tablex.compare_no_order( {v4 = 'e40'}, G:out_edges('v5'))) assertTrue(pl.tablex.compare_no_order( {v5 = 'e40'}, G:in_edges('v4'))) G:add_edge('v1', 'v3') assertEquals({}, G:sinks()) assertEquals({}, G:predecessors('v1')) assertEquals({'v3'}, sorted(G:successors('v1'))) assertEquals({'v1', 'v4'}, sorted(G:predecessors('v3'))) assertEquals({'v2'}, G:successors('v3')) end function testCross() local G1 = digraph.Digraph() local cross_from = {} for i = 1, 10 do table.insert(cross_from, i + 10) G1:add_vertex(i) G1:add_vertex(i + 10) G1:add_edge(i, i + 10) end assertEquals(20, #G1) local cross_to = {} local G2 = digraph.Digraph() for i = 101, 110 do table.insert(cross_to, i) G2:add_vertex(i) G2:add_vertex(i + 10) G2:add_edge(i, i + 10) end assertEquals(20, #G2) G1:cross(G2) assertEquals(40, #G1) assertEquals(0, #G2) for i = 1, 10 do assertEquals({}, G1:predecessors(i)) assertEquals({i + 10}, G1:successors(i)) assertEquals({i}, G1:predecessors(i + 10)) assertEquals(cross_to, sorted(G1:successors(i + 10))) assertEquals(cross_from, sorted(G1:predecessors(i + 100))) assertEquals({i + 110}, G1:successors(i + 100)) assertEquals({i + 100}, G1:predecessors(i + 110)) assertEquals({}, G1:successors(i + 110)) end end function testForEachCycle() local G = digraph.Digraph() G:add_vertex(1) G:add_vertex(2) G:add_edge(1, 2) G:add_edge(2, 1) local seen = {} G:for_each(function(v) seen[v] = (seen[v] or 0) + 1 end) assertEquals(pl.Set(seen), pl.Set({1, 1})) end LuaUnit:main()
-- -- Copyright (c) 2014, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. -- local digraph = require('fb.util.digraph') local pl = require('pl.import_into')() require('fb.luaunit') local function sorted(t) return pl.List(t):sort() end TestDigraph = {} function TestDigraph:setUp() self.G = digraph.Digraph() for i = 1, 10 do self.G:add_vertex(i) end for i = 1, 9 do self.G:add_edge(i + 1, i, i * 10) end end function TestDigraph:testBasic() local G = self.G assertEquals(10, #G) assertEquals(10, G:vertex_count()) assertEquals(9, G:edge_count()) assertEquals({10}, G:sources()) assertEquals({1}, G:sinks()) assertTrue(pl.tablex.compare_no_order( {[4] = 40}, G:out_edges(5))) assertTrue(pl.tablex.compare_no_order( {[5] = 40}, G:in_edges(4))) G:add_edge(1, 3) assertEquals({}, G:sinks()) assertEquals({}, G:predecessors(1)) assertEquals({3}, sorted(G:successors(1))) assertEquals({1, 4}, sorted(G:predecessors(3))) assertEquals({2}, G:successors(3)) end function TestDigraph:testForEach() local G = self.G local seen = {} G:for_each(function(v) seen[v] = (seen[v] or 0) + 1 end) assertEquals(pl.Set(seen), pl.Set({1, 1, 1, 1, 1, 1, 1, 1, 1, 1})) end function TestDigraph:testTopoSort1() local G = self.G assertEquals({10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, G:topo_sort()); assertEquals({1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, G:reverse_topo_sort()); G:add_edge(1, 5); assertError(G.topo_sort, G); assertError(G.reverse_topo_sort, G); end function TestDigraph:testClone() local G = self.G:clone( function(v) return string.format('v%d', v) end, function(e) return string.format('e%d', e) end) assertEquals(10, #G) assertEquals(10, G:vertex_count()) assertEquals(9, G:edge_count()) assertEquals({'v10'}, G:sources()) assertEquals({'v1'}, G:sinks()) assertTrue(pl.tablex.compare_no_order( {v4 = 'e40'}, G:out_edges('v5'))) assertTrue(pl.tablex.compare_no_order( {v5 = 'e40'}, G:in_edges('v4'))) G:add_edge('v1', 'v3') assertEquals({}, G:sinks()) assertEquals({}, G:predecessors('v1')) assertEquals({'v3'}, sorted(G:successors('v1'))) assertEquals({'v1', 'v4'}, sorted(G:predecessors('v3'))) assertEquals({'v2'}, G:successors('v3')) end function testCross() local G1 = digraph.Digraph() local cross_from = {} for i = 1, 10 do table.insert(cross_from, i + 10) G1:add_vertex(i) G1:add_vertex(i + 10) G1:add_edge(i, i + 10) end assertEquals(20, #G1) local cross_to = {} local G2 = digraph.Digraph() for i = 101, 110 do table.insert(cross_to, i) G2:add_vertex(i) G2:add_vertex(i + 10) G2:add_edge(i, i + 10) end assertEquals(20, #G2) G1:cross(G2) assertEquals(40, #G1) assertEquals(0, #G2) for i = 1, 10 do assertEquals({}, G1:predecessors(i)) assertEquals({i + 10}, G1:successors(i)) assertEquals({i}, G1:predecessors(i + 10)) assertEquals(cross_to, sorted(G1:successors(i + 10))) assertEquals(cross_from, sorted(G1:predecessors(i + 100))) assertEquals({i + 110}, G1:successors(i + 100)) assertEquals({i + 100}, G1:predecessors(i + 110)) assertEquals({}, G1:successors(i + 110)) end end function testForEachCycle() local G = digraph.Digraph() G:add_vertex(1) G:add_vertex(2) G:add_edge(1, 2) G:add_edge(2, 1) local seen = {} G:for_each(function(v) seen[v] = (seen[v] or 0) + 1 end) assertEquals(pl.Set(seen), pl.Set({1, 1})) end LuaUnit:main()
Fix unused variables in `digraph_test.lua`
Fix unused variables in `digraph_test.lua` Summary: doesexactlywhatitsaysonthetin Test Plan: ``` ∴ fbconfig fblualib/util/test && mt ... fblualib/util/test:error_handling_test: 0s fblualib/util/test:find_test: 6s fblualib/util/test:reactor_test: 0s fblualib/util/test:trace_test: 0s fblualib/util/test:util_test: 0s Test Results Summary: Passed: 35 100% successful ``` Reviewed By: [email protected] FB internal diff: D1658248 Tasks: 5539137 Signature: t1:1658248:1415134581:5072820a46ff73c84493e105dc08b6e598de563e
Lua
bsd-3-clause
facebook/fblualib,soumith/fblualib,facebook/fblualib,szagoruyko/fblualib,raphaelamorim/fblualib,szagoruyko/fblualib,raphaelamorim/fblualib,soumith/fblualib
c5ac3c2ae2d2bdf9283ba0e6dce21dde811e8629
lua/json/decode/util.lua
lua/json/decode/util.lua
--[[ Licensed according to the included 'LICENSE' document Author: Thomas Harning Jr <[email protected]> ]] local lpeg = require("lpeg") local select = select local pairs, ipairs = pairs, ipairs local tonumber = tonumber local string_char = require("string").char local rawset = rawset local jsonutil = require("json.util") local error = error local setmetatable = setmetatable local table_concat = require("table").concat local merge = require("json.util").merge local is_52 = _VERSION == "Lua 5.2" local _G = _G if is_52 then _ENV = nil end local function build_report(msg) local fmt = msg:gsub("%%", "%%%%") .. " @ character: %i %i:%i [%s] line:\n%s" return lpeg.P(function(data, pos) local line, line_index, bad_char, last_line = get_invalid_character_info(data, pos) local text = fmt:format(pos, line, line_index, bad_char, last_line) error(text) end) end local function unexpected() local msg = "unexpected character" return build_report(msg) end local function expected(...) local items = {...} local msg if #items > 1 then msg = "expected one of '" .. table_concat(items, "','") .. "'" else msg = "expected '" .. items[1] .. "'" end return build_report(msg) end local function denied(item, option) local msg if option then msg = ("'%s' denied by option set '%s'"):format(item, option) else msg = ("'%s' denied"):format(item) end return build_report(msg) end -- 09, 0A, 0B, 0C, 0D, 20 local ascii_space = lpeg.S("\t\n\v\f\r ") local unicode_space do local chr = string_char local u_space = ascii_space -- \u0085 \u00A0 u_space = u_space + lpeg.P(chr(0xC2)) * lpeg.S(chr(0x85) .. chr(0xA0)) -- \u1680 \u180E u_space = u_space + lpeg.P(chr(0xE1)) * (lpeg.P(chr(0x9A, 0x80)) + chr(0xA0, 0x8E)) -- \u2000 - \u200A, also 200B local spacing_end = "" for i = 0x80,0x8b do spacing_end = spacing_end .. chr(i) end -- \u2028 \u2029 \u202F spacing_end = spacing_end .. chr(0xA8) .. chr(0xA9) .. chr(0xAF) u_space = u_space + lpeg.P(chr(0xE2, 0x80)) * lpeg.S(spacing_end) -- \u205F u_space = u_space + lpeg.P(chr(0xE2, 0x81, 0x9F)) -- \u3000 u_space = u_space + lpeg.P(chr(0xE3, 0x80, 0x80)) -- BOM \uFEFF u_space = u_space + lpeg.P(chr(0xEF, 0xBB, 0xBF)) unicode_space = u_space end local identifier = lpeg.R("AZ","az","__") * lpeg.R("AZ","az", "__", "09") ^0 local hex = lpeg.R("09","AF","af") local hexpair = hex * hex local comments = { cpp = lpeg.P("//") * (1 - lpeg.P("\n"))^0 * lpeg.P("\n"), c = lpeg.P("/*") * (1 - lpeg.P("*/"))^0 * lpeg.P("*/") } local comment = comments.cpp + comments.c local ascii_ignored = (ascii_space + comment)^0 local unicode_ignored = (unicode_space + comment)^0 -- Parse the lpeg version skipping patch-values -- LPEG <= 0.7 have no version value... so 0.7 is value local DecimalLpegVersion = lpeg.version and tonumber(lpeg.version():match("^(%d+%.%d+)")) or 0.7 local function get_invalid_character_info(input, index) local parsed = input:sub(1, index) local bad_character = input:sub(index, index) local _, line_number = parsed:gsub('\n',{}) local last_line = parsed:match("\n([^\n]+.)$") or parsed return line_number, #last_line, bad_character, last_line end local function setObjectKeyForceNumber(t, key, value) key = tonumber(key) or key return rawset(t, key, value) end local util = { unexpected = unexpected, expected = expected, denied = denied, ascii_space = ascii_space, unicode_space = unicode_space, identifier = identifier, hex = hex, hexpair = hexpair, comments = comments, comment = comment, ascii_ignored = ascii_ignored, unicode_ignored = unicode_ignored, DecimalLpegVersion = DecimalLpegVersion, get_invalid_character_info = get_invalid_character_info, setObjectKeyForceNumber = setObjectKeyForceNumber } if not is_52 then _G.json = _G.json or {} _G.json.decode = _G.json.decode or {} _G.json.decode.util = util end return util
--[[ Licensed according to the included 'LICENSE' document Author: Thomas Harning Jr <[email protected]> ]] local lpeg = require("lpeg") local select = select local pairs, ipairs = pairs, ipairs local tonumber = tonumber local string_char = require("string").char local rawset = rawset local jsonutil = require("json.util") local error = error local setmetatable = setmetatable local table_concat = require("table").concat local merge = require("json.util").merge local is_52 = _VERSION == "Lua 5.2" local _G = _G if is_52 then _ENV = nil end local function get_invalid_character_info(input, index) local parsed = input:sub(1, index) local bad_character = input:sub(index, index) local _, line_number = parsed:gsub('\n',{}) local last_line = parsed:match("\n([^\n]+.)$") or parsed return line_number, #last_line, bad_character, last_line end local function build_report(msg) local fmt = msg:gsub("%%", "%%%%") .. " @ character: %i %i:%i [%s] line:\n%s" return lpeg.P(function(data, pos) local line, line_index, bad_char, last_line = get_invalid_character_info(data, pos) local text = fmt:format(pos, line, line_index, bad_char, last_line) error(text) end) end local function unexpected() local msg = "unexpected character" return build_report(msg) end local function expected(...) local items = {...} local msg if #items > 1 then msg = "expected one of '" .. table_concat(items, "','") .. "'" else msg = "expected '" .. items[1] .. "'" end return build_report(msg) end local function denied(item, option) local msg if option then msg = ("'%s' denied by option set '%s'"):format(item, option) else msg = ("'%s' denied"):format(item) end return build_report(msg) end -- 09, 0A, 0B, 0C, 0D, 20 local ascii_space = lpeg.S("\t\n\v\f\r ") local unicode_space do local chr = string_char local u_space = ascii_space -- \u0085 \u00A0 u_space = u_space + lpeg.P(chr(0xC2)) * lpeg.S(chr(0x85) .. chr(0xA0)) -- \u1680 \u180E u_space = u_space + lpeg.P(chr(0xE1)) * (lpeg.P(chr(0x9A, 0x80)) + chr(0xA0, 0x8E)) -- \u2000 - \u200A, also 200B local spacing_end = "" for i = 0x80,0x8b do spacing_end = spacing_end .. chr(i) end -- \u2028 \u2029 \u202F spacing_end = spacing_end .. chr(0xA8) .. chr(0xA9) .. chr(0xAF) u_space = u_space + lpeg.P(chr(0xE2, 0x80)) * lpeg.S(spacing_end) -- \u205F u_space = u_space + lpeg.P(chr(0xE2, 0x81, 0x9F)) -- \u3000 u_space = u_space + lpeg.P(chr(0xE3, 0x80, 0x80)) -- BOM \uFEFF u_space = u_space + lpeg.P(chr(0xEF, 0xBB, 0xBF)) unicode_space = u_space end local identifier = lpeg.R("AZ","az","__") * lpeg.R("AZ","az", "__", "09") ^0 local hex = lpeg.R("09","AF","af") local hexpair = hex * hex local comments = { cpp = lpeg.P("//") * (1 - lpeg.P("\n"))^0 * lpeg.P("\n"), c = lpeg.P("/*") * (1 - lpeg.P("*/"))^0 * lpeg.P("*/") } local comment = comments.cpp + comments.c local ascii_ignored = (ascii_space + comment)^0 local unicode_ignored = (unicode_space + comment)^0 -- Parse the lpeg version skipping patch-values -- LPEG <= 0.7 have no version value... so 0.7 is value local DecimalLpegVersion = lpeg.version and tonumber(lpeg.version():match("^(%d+%.%d+)")) or 0.7 local function setObjectKeyForceNumber(t, key, value) key = tonumber(key) or key return rawset(t, key, value) end local util = { unexpected = unexpected, expected = expected, denied = denied, ascii_space = ascii_space, unicode_space = unicode_space, identifier = identifier, hex = hex, hexpair = hexpair, comments = comments, comment = comment, ascii_ignored = ascii_ignored, unicode_ignored = unicode_ignored, DecimalLpegVersion = DecimalLpegVersion, get_invalid_character_info = get_invalid_character_info, setObjectKeyForceNumber = setObjectKeyForceNumber } if not is_52 then _G.json = _G.json or {} _G.json.decode = _G.json.decode or {} _G.json.decode.util = util end return util
decoder: fixes missing symbol problem in enhanced error reporting
decoder: fixes missing symbol problem in enhanced error reporting
Lua
mit
renchunxiao/luajson
a13ec1a67a6c2c5a38363a89971aa75aba40d970
cache_table.lua
cache_table.lua
-- Copyright (C) 2012 Matthieu Tourne -- @author Matthieu Tourne <[email protected]> -- Simple Cached table - Use with openresty or ngx_lua -- A cache_table is a Full Lua table -- All the magic for caching lives in the metatable -- It can be serialized like a normal table (json etc) -- Usage : -- local my_table = { ip = 'xx.xx.xx.xx', session = "foo" } -- my_table = cache_table:new(60, ngx.shared.cached_sessions, my_table) -- local my_table, cached = my_table:load("key") -- *Note:* this means that "self" is itself a table, -- and self:load cannot change self itself. -- cache_table:load() will always return a new instance. module("cache_table", package.seeall) local cmsgpack = require("cmsgpack") -- Control caching for failed lookups local DEFAULT_FAILED_LOOKUP_CACHE_TTL = 10 local DEBUG = false local pack = cmsgpack.pack local unpack = cmsgpack.unpack local class = cache_table -- cache_table:new(ttl, shared_dict, [table], [opts]) -- shared_dict: a ngx.shared.DICT, declared in nginx.conf -- ttl: caching time, in seconds. -- table: pre-initalized table function new(self, ttl, shared_dict, table, opts) local err = nil local opts = opts or {} if not opts.failed_ttl then -- opts.failed_ttl: caching time for ("empty entries"), default 10secs opts.failed_ttl = DEFAULT_FAILED_LOOKUP_CACHE_TTL end local mt = { __index = class, __internal = { shared_dict = shared_dict, ttl = ttl, cache_status = 'MISS', opts = opts, } } local table = table or {} local res = setmetatable(table, mt) -- not passing a ngx.shared.DICT turns off all the cache if not shared_dict then if DEBUG then ngx.log(ngx.CRIT, 'Caching is disabled. ', debug.traceback()) end mt.__internal.cache_status = 'DISABLED' res.save = res._save_off res.load = res._load_off err = 'Caching is disabled' end return res, err end function get_internal_table(self) local mt = self:getmetatable() return mt.__internal end function get_internal(self, key) local mt = self:getmetatable() return mt.__internal[key] end function set_internal(self, key, val) local mt = self:getmetatable() mt.__internal[key] = val end function get_shared_dict(self) return self:get_internal('shared_dict') end -- cache_table:load(key) -- Loads the table from a shared dict -- @returns (loaded table, cached) function load(self, key) local shared_dict = self:get_shared_dict() local serialized = shared_dict:get(key) if serialized then if DEBUG then self:set_internal('serialized', serialized) end self:set_internal('serialized_size', #serialized) self:set_internal('cache_status', 'HIT') local mt = self:getmetatable() local new_table = self:deserialize(serialized) setmetatable(new_table, mt) return new_table, true end return self, false end -- cache_table:save(key, [lookup_success]) function save(self, key, lookup_succes) local lookup_succes = lookup_succes or true local serialized = self:serialize(self) self:set_internal('serialized_size', #serialized) if DEBUG then self:set_internal('serialized', serialized) end local shared_dict = self:get_shared_dict() local ttl = DEFAULT_FAILED_LOOKUP_CACHE_TTL if lookup_success then ttl = self:get_internal('ttl') else local opts = self:get_internal('opts') ttl = opts.failed_ttl ngx.log(ngx.DEBUG, 'Failed Lookup TTL: ', ttl) end return shared_dict:set(key, serialized, ttl) end -- default serializer function function serialize(self, table) return pack(table) end function deserialize(self, serialized) return unpack(serialized) end -- debug functions to turn off caching function _load_off(self, key) if DEBUG then self.internals = self:get_internal_table() end ngx.log(ngx.WARN, 'Unable to load object, check your configuration. ', debug.traceback()) return nil end function _save_off(self, key) if DEBUG then self.internals = self:get_internal_table() end ngx.log(ngx.WARN, 'Unable to save object, check your configuration. ', debug.traceback()) return nil end -- safety net getmetatable(class).__newindex = ( function (table, key, val) error('attempt to write to undeclared variable "' .. key .. '"') end)
-- Copyright (C) 2012 Matthieu Tourne -- @author Matthieu Tourne <[email protected]> -- Simple Cached table - Use with openresty or ngx_lua -- A cache_table is a Full Lua table -- All the magic for caching lives in the metatable -- It can be serialized like a normal table (json etc) -- Usage : -- local my_table = { ip = 'xx.xx.xx.xx', session = "foo" } -- my_table = cache_table:new(60, ngx.shared.cached_sessions, my_table) -- local my_table, cached = my_table:load("key") -- *Note:* this means that "self" is itself a table, -- and self:load cannot change self itself. -- cache_table:load() will always return a new instance. module(..., package.seeall) local cmsgpack = require("cmsgpack") local debug = require("debug") -- Control caching for failed lookups local DEFAULT_FAILED_LOOKUP_CACHE_TTL = 10 local DEBUG = false local pack = cmsgpack.pack local unpack = cmsgpack.unpack local class = _M -- cache_table:new(ttl, shared_dict, [table], [opts]) -- shared_dict: a ngx.shared.DICT, declared in nginx.conf -- ttl: caching time, in seconds. -- table: pre-initalized table function new(self, ttl, shared_dict, table, opts) local err = nil local opts = opts or {} if not opts.failed_ttl then -- opts.failed_ttl: caching time for ("empty entries"), default 10secs opts.failed_ttl = DEFAULT_FAILED_LOOKUP_CACHE_TTL end local mt = { __index = class, __internal = { shared_dict = shared_dict, ttl = ttl, cache_status = 'MISS', opts = opts, } } local table = table or {} local res = setmetatable(table, mt) -- not passing a ngx.shared.DICT turns off all the cache if not shared_dict then if DEBUG then ngx.log(ngx.CRIT, 'Caching is disabled. ', debug.traceback()) end mt.__internal.cache_status = 'DISABLED' res.save = res._save_off res.load = res._load_off err = 'Caching is disabled' end return res, err end function get_internal_table(self) local mt = self:getmetatable() return mt.__internal end function get_internal(self, key) local mt = self:getmetatable() return mt.__internal[key] end function set_internal(self, key, val) local mt = self:getmetatable() mt.__internal[key] = val end function get_shared_dict(self) return self:get_internal('shared_dict') end -- cache_table:load(key) -- Loads the table from a shared dict -- @returns (loaded table, cached) function load(self, key) local shared_dict = self:get_shared_dict() local serialized = shared_dict:get(key) if serialized then if DEBUG then self:set_internal('serialized', serialized) end self:set_internal('serialized_size', #serialized) self:set_internal('cache_status', 'HIT') local mt = self:getmetatable() local new_table = self:deserialize(serialized) setmetatable(new_table, mt) return new_table, true end return self, false end -- cache_table:save(key, [lookup_success]) function save(self, key, lookup_succes) local lookup_succes = lookup_succes or true local serialized = self:serialize(self) self:set_internal('serialized_size', #serialized) if DEBUG then self:set_internal('serialized', serialized) end local shared_dict = self:get_shared_dict() local ttl = DEFAULT_FAILED_LOOKUP_CACHE_TTL if lookup_success then ttl = self:get_internal('ttl') else local opts = self:get_internal('opts') ttl = opts.failed_ttl ngx.log(ngx.DEBUG, 'Failed Lookup TTL: ', ttl) end return shared_dict:set(key, serialized, ttl) end -- default serializer function function serialize(self, table) return pack(table) end function deserialize(self, serialized) return unpack(serialized) end -- debug functions to turn off caching function _load_off(self, key) if DEBUG then self.internals = self:get_internal_table() end ngx.log(ngx.WARN, 'Unable to load object, check your configuration. ', debug.traceback()) return self, false end function _save_off(self, key) if DEBUG then self.internals = self:get_internal_table() end ngx.log(ngx.WARN, 'Unable to save object, check your configuration. ', debug.traceback()) return self, false end -- safety net getmetatable(class).__newindex = ( function (table, key, val) error('Attempt to write to undeclared variable "' .. key .. '"') end)
Fix API when caching is turned off
Fix API when caching is turned off
Lua
bsd-2-clause
mtourne/ngx.cache_table
e20451c7997a930b4e8ff8d25a5da6265e1529bf
scripts/texturec.lua
scripts/texturec.lua
-- -- Copyright 2010-2015 Branimir Karadzic. All rights reserved. -- License: http://www.opensource.org/licenses/BSD-2-Clause -- project "texturec" uuid "838801ee-7bc3-11e1-9f19-eae7d36e7d26" kind "ConsoleApp" includedirs { path.join(BX_DIR, "include"), path.join(BGFX_DIR, "include"), path.join(BGFX_DIR, "src"), } files { path.join(BGFX_DIR, "src/image.*"), path.join(BGFX_DIR, "tools/texturec/**.cpp"), path.join(BGFX_DIR, "tools/texturec/**.h"), } links { -- "bgfx", } configuration { "osx" } links { "Cocoa.framework", }
-- -- Copyright 2010-2015 Branimir Karadzic. All rights reserved. -- License: http://www.opensource.org/licenses/BSD-2-Clause -- project "texturec" uuid "838801ee-7bc3-11e1-9f19-eae7d36e7d26" kind "ConsoleApp" defines { "ENTRY_CONFIG_PROFILER=0", } includedirs { path.join(BX_DIR, "include"), path.join(BGFX_DIR, "include"), path.join(BGFX_DIR, "src"), } files { path.join(BGFX_DIR, "src/image.*"), path.join(BGFX_DIR, "tools/texturec/**.cpp"), path.join(BGFX_DIR, "tools/texturec/**.h"), } links { -- "bgfx", } configuration { "osx" } links { "Cocoa.framework", }
Fixed texturec build with --with-profiler enabled
Fixed texturec build with --with-profiler enabled
Lua
bsd-2-clause
v3n/bgfx,marco-we/bgfx,jpcy/bgfx,elmindreda/bgfx,mmicko/bgfx,emoon/bgfx,mendsley/bgfx,jdryg/bgfx,jdryg/bgfx,emoon/bgfx,v3n/bgfx,attilaz/bgfx,mendsley/bgfx,attilaz/bgfx,attilaz/bgfx,bkaradzic/bgfx,LWJGL-CI/bgfx,LWJGL-CI/bgfx,0-wiz-0/bgfx,andr3wmac/bgfx,aonorin/bgfx,bkaradzic/bgfx,0-wiz-0/bgfx,kondrak/bgfx,jpcy/bgfx,0-wiz-0/bgfx,mmicko/bgfx,jdryg/bgfx,septag/bgfx,LWJGL-CI/bgfx,fluffyfreak/bgfx,fluffyfreak/bgfx,emoon/bgfx,andr3wmac/bgfx,MikePopoloski/bgfx,fluffyfreak/bgfx,septag/bgfx,marco-we/bgfx,aonorin/bgfx,MikePopoloski/bgfx,MikePopoloski/bgfx,bkaradzic/bgfx,septag/bgfx,kondrak/bgfx,elmindreda/bgfx,Synxis/bgfx,v3n/bgfx,marco-we/bgfx,mmicko/bgfx,kondrak/bgfx,jpcy/bgfx,fluffyfreak/bgfx,aonorin/bgfx,jpcy/bgfx,bkaradzic/bgfx,andr3wmac/bgfx,mendsley/bgfx,LWJGL-CI/bgfx,Synxis/bgfx,jdryg/bgfx,elmindreda/bgfx,Synxis/bgfx
2398c22a91ae286011f90fc0bb4ce17f64d39239
src/cosy/nginx/conf.lua
src/cosy/nginx/conf.lua
return function (loader) local Lfs = loader.require "lfs" local Default = loader.load "cosy.configuration.layers".default -- Compute www path: local main = loader.hotswap.searchpath ("cosy.nginx", package.path) if main:sub (1, 1) == "." then main = Lfs.currentdir () .. "/" .. main end Default.http = { nginx = "nginx", hostname = nil, interface = "*", port = 80, timeout = 5, pid = os.getenv "HOME" .. "/.cosy/nginx.pid", configuration = os.getenv "HOME" .. "/.cosy/nginx.conf", error = os.getenv "HOME" .. "/.cosy/nginx.log", directory = os.getenv "HOME" .. "/.cosy/nginx", uploads = os.getenv "HOME" .. "/.cosy/nginx/uploads", www = main:gsub ("cosy/nginx.*", "cosy/www"), } Default.upload = { timeout = 5 * 60, -- 5 minutes } Default.dependencies = { expiration = 24 * 3600, -- 1 day ["/js/lua.vm.js"] = "https://kripken.github.io/lua.vm.js/lua.vm.js", ["/js/sjcl.js" ] = "http://bitwiseshiftleft.github.io/sjcl/sjcl.js", ["/js/jquery.js"] = "http://code.jquery.com/jquery-2.1.4.min.js", ["/js/map.js"] = "https://maps.googleapis.com/maps/api/js?v=3&sensor=false", ["/js/mapcluster.js"] = "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer_compiled.js", ["/js/recaptcha/api.js"] = "https://www.google.com/recaptcha/api.js", ["/js/bootstrap.min.js"] = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js", ["/css/bootstrap.min.css"] = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css", ["/css/font-awesome.min.css"] = "https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css", ["/fonts/fontawesome-webfont.woff2"] = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/fonts/fontawesome-webfont.woff2", ["/fonts/fontawesome-webfont.woff"] = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/fonts/fontawesome-webfont.woff", ["/fonts/fontawesome-webfont.ttf"] = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/fonts/fontawesome-webfont.ttf", ["/fonts/glyphicons-halflings-regular.woff2"] = "https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/fonts/glyphicons-halflings-regular.woff2", ["/fonts/glyphicons-halflings-regular.woff"] = "https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/fonts/glyphicons-halflings-regular.woff", ["/fonts/glyphicons-halflings-regular.ttf"] = "https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/fonts/glyphicons-halflings-regular.ttf", ["/ext/maps" ] = "http://maps.googleapis.com/maps/api/geocode/json", } end
return function (loader) local Lfs = loader.require "lfs" local Default = loader.load "cosy.configuration.layers".default -- Compute www path: local main = loader.hotswap.searchpath ("cosy.nginx", package.path) if main:sub (1, 1) == "." then main = Lfs.currentdir () .. "/" .. main end Default.http = { nginx = os.getenv "COSY_PREFIX" .. "/nginx/sbin/nginx", hostname = nil, interface = "*", port = 80, timeout = 5, pid = os.getenv "HOME" .. "/.cosy/nginx.pid", configuration = os.getenv "HOME" .. "/.cosy/nginx.conf", error = os.getenv "HOME" .. "/.cosy/nginx.log", directory = os.getenv "HOME" .. "/.cosy/nginx", uploads = os.getenv "HOME" .. "/.cosy/nginx/uploads", www = main:gsub ("cosy/nginx.*", "cosy/www"), } Default.upload = { timeout = 5 * 60, -- 5 minutes } Default.dependencies = { expiration = 24 * 3600, -- 1 day ["/js/lua.vm.js"] = "https://kripken.github.io/lua.vm.js/lua.vm.js", ["/js/sjcl.js" ] = "http://bitwiseshiftleft.github.io/sjcl/sjcl.js", ["/js/jquery.js"] = "http://code.jquery.com/jquery-2.1.4.min.js", ["/js/map.js"] = "https://maps.googleapis.com/maps/api/js?v=3&sensor=false", ["/js/mapcluster.js"] = "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer_compiled.js", ["/js/recaptcha/api.js"] = "https://www.google.com/recaptcha/api.js", ["/js/bootstrap.min.js"] = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js", ["/css/bootstrap.min.css"] = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css", ["/css/font-awesome.min.css"] = "https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css", ["/fonts/fontawesome-webfont.woff2"] = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/fonts/fontawesome-webfont.woff2", ["/fonts/fontawesome-webfont.woff"] = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/fonts/fontawesome-webfont.woff", ["/fonts/fontawesome-webfont.ttf"] = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/fonts/fontawesome-webfont.ttf", ["/fonts/glyphicons-halflings-regular.woff2"] = "https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/fonts/glyphicons-halflings-regular.woff2", ["/fonts/glyphicons-halflings-regular.woff"] = "https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/fonts/glyphicons-halflings-regular.woff", ["/fonts/glyphicons-halflings-regular.ttf"] = "https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/fonts/glyphicons-halflings-regular.ttf", ["/ext/maps" ] = "http://maps.googleapis.com/maps/api/geocode/json", } end
Fix nginx path.
Fix nginx path.
Lua
mit
CosyVerif/library,CosyVerif/library,CosyVerif/library
92f7cc2ef47eaf7a0de8c9722a1f5ef64139a23c
source/main.lua
source/main.lua
-- Commands interface. A simple way to handle dispatching commands and parse -- arguments. -- -- This file is licensed under the BSD 2-Clause license. -- -- Copyright (c) 2016 Aaron Bolyard. local command = require 'command' local crypto = require 'crypto' local database = require 'database' local function write(...) io.write(string.format(...)) end local function write_line(...) io.write(string.format(...), "\n") end local Main = command.create() function Main.create(path) write_line("Creating new password database.") local passphrase repeat local a = crypto.read_passphrase("Enter passphrase: ") local b = crypto.read_passphrase("Verify passphrase: ") if crypto.compare_passphrases(a, b) then passphrase = a crypto.free_passphrase(b) else write_line("Passphrases don't match! Try again.") crypto.free_passphrase(a) crypto.free_passphrase(b) end until passphrase ~= nil local d = database.create(passphrase) d:save(path) crypto.free_passphrase(passphrase) d:destroy() return false, string.format("Success! Created database '%s'.", path) end function Main.open(path) local passphrase = crypto.read_passphrase("Enter passphrase: ") local success, d = database.load(path, passphrase) if not success then return false, "Unable to open database. Wrong passphrase?" end return true, d end function Main.help() write_line("blobby <open/create/help> [path]") write_line("\topen\t\tdecrypt database at 'path' and begin session") write_line("\tcreate\t\tcreate database at 'path'") write_line("\thelp\t\tthis message") return false, nil end local function session_loop() end local function start(...) local success, a, b = Main(...) if not success then io.stderr:write(a) os.exit(1) end if a then session_loop(b) else if b then write_line(b) end end end start(...)
-- Blobby application implementation. -- -- This file is licensed under the BSD 2-Clause license. -- -- Copyright (c) 2016 Aaron Bolyard. local command = require 'command' local crypto = require 'crypto' local database = require 'database' local function write(...) io.write(string.format(...)) end local function write_line(...) io.write(string.format(...), "\n") end local function read_line(...) write(...) return io.read("*l") end local function require_argument(name, v) if not v then error(string.format("argument '%s' required", name)) end end local function validate_enum(v, e) local match = false for i = 1, #e do if v == e[i] then match = true break end end if not match then local m = string.format( "value '%s' is not valid; must be one of:\n\t%s", v, table.concat(e, ", ")) error(m) end end local Confirm = command.create() function Confirm.yes() return true end function Confirm.no() return false end function ask_confirmation(message) write_line(message) local success, result while not success do local c = read_line("Enter 'yes' to confirm, 'no' to cancel: ") success, result = Confirm(c) if not success then write_line("Invalid option.") end end return result end local State = {} local Session = command.create() function Session.list(field, pattern) field = field or 'all' validate_enum(field, { 'all', 'domain', 'username', 'category' }) local success, result = State.database:query_list(field, pattern) if not success then write_line("Error: %s", result) end write_line("%20s %20s %20s", "username", "domain", "category") local matches = 0 local entry = result() while entry do write_line( "%20s %20s %20s", entry.username, entry.domain, entry.category) matches = matches + 1 entry = result() end write_line("\nFound %d matches.", matches) end function Session.add(username, domain, category) require_argument("username", username) require_argument("domain", domain) local success, entry = State.database:add_entry(username, domain, category) if success then State.active = entry write_line("Entry successfully created.") else write_line("Entry already exists in database.") end end function Session.remove() if State.active == nil then write_line("No active entry. Select an entry and then try again.") else local m = string.format( "Are you sure you want to remove '%s' from '%s'?", State.active.username, State.active.domain) if ask_confirmation(m) then local result = State.database:remove_entry(State.active) if not result then write_line("Entry was not in database.") end State.active = nil else write_line("No action taken.") end end end function Session.exit() if ask_confirmation("Save any changes?") then State.database:save(State.database.path) end return 'exit' end local Main = command.create() function Main.create(path) write_line("Creating new password database.") local passphrase repeat local a = crypto.read_passphrase("Enter passphrase: ") local b = crypto.read_passphrase("Verify passphrase: ") if crypto.compare_passphrases(a, b) then passphrase = a crypto.free_passphrase(b) else write_line("Passphrases don't match! Try again.") crypto.free_passphrase(a) crypto.free_passphrase(b) end until passphrase ~= nil local d = database.create(passphrase) d:save(path) crypto.free_passphrase(passphrase) d:destroy() return false, string.format("Success! Created database '%s'.", path) end function Main.open(path) local passphrase = crypto.read_passphrase("Enter passphrase: ") local success, d = database.load(path, passphrase) if not success then return false, "Unable to open database. Wrong passphrase?" else write_line("Successfully opened '%s'.", path) end crypto.free_passphrase(passphrase) return true, d end function Main.help() write_line("blobby <open/create/help> [path]") write_line("\topen\t\tdecrypt database at 'path' and begin session") write_line("\tcreate\t\tcreate database at 'path'") write_line("\thelp\t\tthis message") return false, nil end local function session_loop(d, path) State.database = d local is_running = true while is_running do local c = read_line("> ") local success, result = Session(command.parse_arguments(c)) if not success then write_line("Error: %s", result) end if result == 'exit' then is_running = false end end State.database:destroy() end local function start(...) local success, a, b = Main(...) if not success then io.stderr:write(a) os.exit(1) end if a then session_loop(b) else if b then write_line(b) end end end start(...)
Added main logic loop and a few commands.
Added main logic loop and a few commands. * Added logic loop to use commands on the database. * Implemented 'add', 'remove', 'list', and 'exit' commands. * Fixed copy-paste in the file header for 'main.lua'.
Lua
bsd-2-clause
aaronbolyard/blobby
6717a04e73a0f030cc53c69eb6e199f114fa94c2
src/accuracy.lua
src/accuracy.lua
-- Adapted from https://github.com/hpenedones/metrics ROC = {} ROC.__index = ROC function variance_explained(Yf, preds) local num_seqs = Yf:dataspaceSize()[1] local Ydim = Yf:dataspaceSize()[2] local R2s = torch.Tensor(Ydim) for yi = 1,Ydim do -- read Yi from file local Yi = Yf:partial({1,num_seqs},{yi,yi}):squeeze() -- subset to preds i local preds_i = preds[{{},yi}] -- compute variances local Yi_var = Yi:var() local preds_var = preds_i:var() -- save R2s[yi] = 1.0 - preds_var/Yi_var end return R2s end -- auxiliary method that quickly simulates the ROC curve computation -- just to estimate how many points the curve will have, -- in order to later allocate just that much memory local function determine_roc_points_needed(responses_sorted, labels_sorted) local npoints = 1 local i = 1 local nsamples = responses_sorted:size()[1] while i<nsamples do local split = responses_sorted[i] while i <= nsamples and responses_sorted[i] == split do i = i+1 end while i <= nsamples and labels_sorted[i] == 0 do i = i+1 end npoints = npoints + 1 end return npoints + 1 end function ROC.points(responses, labels) -- assertions about the data format expected assert(responses:size():size() == 1, "responses should be a 1D vector") assert(labels:size():size() == 1 , "labels should be a 1D vector") -- assuming labels {0, 1} local npositives = torch.sum(torch.eq(labels, 1)) local nnegatives = torch.sum(torch.eq(labels, 0)) local nsamples = npositives + nnegatives assert(nsamples == responses:size()[1], "labels should contain only 0 or 1 values") -- sort by response value local responses_sorted, indexes_sorted = torch.sort(responses) local labels_sorted = labels:index(1, indexes_sorted) -- one could allocate a lua table and grow its size dynamically -- and at the end convert to torch tensor, but here I am chosing -- to allocate only the exact memory needed, and doing two passes -- over the data to estimate first how many points will need local roc_num_points = determine_roc_points_needed(responses_sorted, labels_sorted) local roc_points = torch.Tensor(roc_num_points, 2) roc_points[roc_num_points][1], roc_points[roc_num_points][2] = 1.0, 1.0 local npoints = 1 local true_negatives = 0 local false_negatives = 0 local i = 1 while i<nsamples do local split = responses_sorted[i] -- if samples have exactly the same response, can't distinguish -- between them with a threshold in the middle while i <= nsamples and responses_sorted[i] == split do if labels_sorted[i] == 0 then true_negatives = true_negatives + 1 else false_negatives = false_negatives + 1 end i = i+1 end while i <= nsamples and labels_sorted[i] == 0 do true_negatives = true_negatives + 1 i = i+1 end npoints = npoints + 1 local false_positives = nnegatives - true_negatives local true_positives = npositives - false_negatives local false_positive_rate = 1.0*false_positives/nnegatives local true_positive_rate = 1.0*true_positives/npositives roc_points[roc_num_points - npoints + 1][1] = false_positive_rate roc_points[roc_num_points - npoints + 1][2] = true_positive_rate end assert(roc_num_points - npoints + 1 == 2, "missed pre-allocated table target") roc_points[1][1], roc_points[1][2] = 0.0, 0.0 return roc_points end function ROC.area(roc_points) local area = 0.0 local npoints = roc_points:size()[1] for i=1,npoints-1 do local width = (roc_points[i+1][1] - roc_points[i][1]) local avg_height = (roc_points[i][2]+roc_points[i+1][2])/2.0 area = area + width*avg_height end return area end
-- Adapted from https://github.com/hpenedones/metrics ROC = {} ROC.__index = ROC function variance_explained(Yf, preds) local num_seqs = Yf:dataspaceSize()[1] local Ydim = Yf:dataspaceSize()[2] local R2s = torch.Tensor(Ydim) for yi = 1,Ydim do -- read Yi from file local Yi = Yf:partial({1,num_seqs},{yi,yi}):squeeze() Yi = Yi:float() -- subset to preds i local preds_i = preds[{{},yi}] -- compute variances local Yi_var = (Yi - Yi:mean()):var() local preds_var = (Yi - preds_i):var() -- save R2s[yi] = 1.0 - preds_var/Yi_var end return R2s end function spearmanr(Yf, preds) local num_seqs = Yf:dataspaceSize()[1] local Ydim = Yf:dataspaceSize()[2] local n_denom = num_seqs*(num_seqs^2 - 1) local cors = torch.Tensor(Ydim) for yi = 1,Ydim do -- read Yi from file local Yi = Yf:partial({1,num_seqs},{yi,yi}):squeeze() -- subset to preds i local preds_i = preds[{{},yi}] -- argsort local _, Y_si = Yi:sort() local _, preds_si = preds_i:sort() -- assign ranks local Y_ranks = Y_si:clone() local preds_ranks = preds_si:clone() for ri = 1,num_seqs do Y_ranks[Y_si[ri]] = ri preds_ranks[preds_si[ri]] = ri end local d2_sum = (Y_ranks - preds_ranks):float():pow(2):sum() -- save cors[yi] = 1.0 - 6.0*d2_sum/n_denom end return cors end -- auxiliary method that quickly simulates the ROC curve computation -- just to estimate how many points the curve will have, -- in order to later allocate just that much memory local function determine_roc_points_needed(responses_sorted, labels_sorted) local npoints = 1 local i = 1 local nsamples = responses_sorted:size()[1] while i<nsamples do local split = responses_sorted[i] while i <= nsamples and responses_sorted[i] == split do i = i+1 end while i <= nsamples and labels_sorted[i] == 0 do i = i+1 end npoints = npoints + 1 end return npoints + 1 end function ROC.points(responses, labels) -- assertions about the data format expected assert(responses:size():size() == 1, "responses should be a 1D vector") assert(labels:size():size() == 1 , "labels should be a 1D vector") -- assuming labels {0, 1} local npositives = torch.sum(torch.eq(labels, 1)) local nnegatives = torch.sum(torch.eq(labels, 0)) local nsamples = npositives + nnegatives assert(nsamples == responses:size()[1], "labels should contain only 0 or 1 values") -- sort by response value local responses_sorted, indexes_sorted = torch.sort(responses) local labels_sorted = labels:index(1, indexes_sorted) -- one could allocate a lua table and grow its size dynamically -- and at the end convert to torch tensor, but here I am chosing -- to allocate only the exact memory needed, and doing two passes -- over the data to estimate first how many points will need local roc_num_points = determine_roc_points_needed(responses_sorted, labels_sorted) local roc_points = torch.Tensor(roc_num_points, 2) roc_points[roc_num_points][1], roc_points[roc_num_points][2] = 1.0, 1.0 local npoints = 1 local true_negatives = 0 local false_negatives = 0 local i = 1 while i<nsamples do local split = responses_sorted[i] -- if samples have exactly the same response, can't distinguish -- between them with a threshold in the middle while i <= nsamples and responses_sorted[i] == split do if labels_sorted[i] == 0 then true_negatives = true_negatives + 1 else false_negatives = false_negatives + 1 end i = i+1 end while i <= nsamples and labels_sorted[i] == 0 do true_negatives = true_negatives + 1 i = i+1 end npoints = npoints + 1 local false_positives = nnegatives - true_negatives local true_positives = npositives - false_negatives local false_positive_rate = 1.0*false_positives/nnegatives local true_positive_rate = 1.0*true_positives/npositives roc_points[roc_num_points - npoints + 1][1] = false_positive_rate roc_points[roc_num_points - npoints + 1][2] = true_positive_rate end assert(roc_num_points - npoints + 1 == 2, "missed pre-allocated table target") roc_points[1][1], roc_points[1][2] = 0.0, 0.0 return roc_points end function ROC.area(roc_points) local area = 0.0 local npoints = roc_points:size()[1] for i=1,npoints-1 do local width = (roc_points[i+1][1] - roc_points[i][1]) local avg_height = (roc_points[i][2]+roc_points[i+1][2])/2.0 area = area + width*avg_height end return area end
R2 bug and spearmanr
R2 bug and spearmanr
Lua
mit
davek44/Basset,davek44/Basset
95919e775c1b10a0f40d7159133002afb1751453
build.lua
build.lua
--[[ MIT License Copyright (c) 2017-2018 Cody Tilkins 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. --]] -- uncomment below or use -Dplat=Windows -- Linux -- MacOSX -- plat = os.types.Windows -- os.types.Linux -- os.types.MacOSX if(plat == nil)then error("Please define `plat` as Windows, Linux, or MacOSX") end require("luaadd") require("build_func") -- TODO: local no_additions local lua_ver = choose_opt("lua51", "luajit-5.1", "luajit-5.1") local lua_define = " -DLUA_JIT_51" local lua_includes = choose_opt("", "/usr/local/include/luajit-2.0", "/usr/local/include/luajit-2.0") --[[ gcc setup --]] local gcc = { gcc_name = "gcc"; debug = false; warnings = " -Wall"; windows = choose_opt(true, false, false); extra_warnings = ""; include_dir = " -I. -Iinclude"; library_dir = " -L. -Llib -Lobj -Ldll"; ccextras = " -s" .. lua_define; ldextras = choose_opt(" -s", " -s -fPIC -Wl,-E", " -s -Wl,-E"); defines = choose_opt(" -D__USE_MINGW_ANSI_STDIO=1", "", ""); } gcc.g = gcc.debug and 3 or 0 gcc.O = gcc.debug and 0 or 2 local install_path = plat == os.types.Windows and (gcc.debug and ("bin\\Debug") or ("bin\\Release")) or ((plat == os.types.Linux or plat == os.types.MacOSX) and (gcc.debug and ("bin/Debug") or ("bin/Release"))) -- this is only a print local targ_dir = (gcc.debug and "DEBUG" or "RELEASE") --[[ cache setup --]] local targ1_exe = {enc_exe("luaw")} local targ1_compile_units = {"consolew.c", "jitsupport.c", "darr.c"} local targ2_dll = {enc_dll("luaadd")} local targ2_compile_units = {"additions.c"} local exe_test = true if(no_cache == nil and force == nil) then if(cache == nil)then targ1_compile_units = check_cache(targ1_compile_units, "src/", "obj/", "o") targ2_compile_units = check_cache(targ2_compile_units, "src/", "obj/", "o") exe_test = check_bin_cache(targ1_exe, "src/", install_path .. "\\", targ1_compile_units) or check_bin_cache(targ1_exe, "src/", install_path .. "\\", targ2_compile_units) or check_bin_cache(targ2_dll, "src/", install_path .. "\\", targ1_compile_units) or check_bin_cache(targ2_dll, "src/", install_path .. "\\", targ2_compile_units) end if(#targ1_compile_units == 0 and #targ2_compile_units == 0 and not exe_test)then print("Done. Up to date.") return end end --[[ objects setup --]] local std_libs = enc_dll(" dll/" .. lua_ver) .. choose_opt("", " -lm -ldl", " -lm -ldl") local targ1_luaw_exe = enc_exe("luaw") local targ1_luaw_exe_o = {"consolew.o", "jitsupport.o", "darr.o"} local targ1_lua_exe_libs = std_libs local targ2_luaadd_dll_a = nil local targ2_luaadd_dll = enc_dll("luaadd") local targ2_luaadd_o = {"additions.o"} local targ2_luaadd_libs = std_libs --[[ compiler/linker strings --]] -- compile string local compile_str1 = gcc_c( gcc.g, gcc.O, gcc.warnings, gcc.extra_warnings, gcc.defines, gcc.ccextras, gcc.include_dir, gcc.library_dir, targ1_compile_units) local compile_str2 = gcc_c( gcc.g, gcc.O, gcc.warnings, gcc.extra_warnings, gcc.defines, gcc.ccextras, gcc.include_dir, gcc.library_dir, targ2_compile_units) -- generate additions dll/so string local linker_str_dll1 = choose_gcc_dll()( targ2_luaadd_dll_a, gcc.g, gcc.O, gcc.warnings, gcc.extra_warnings, gcc.defines, gcc.ldextras, gcc.include_dir, gcc.library_dir, targ2_luaadd_dll, targ2_luaadd_o, targ2_luaadd_libs) -- luaw linker string local linker_str_exe1 = gcc_l( gcc.windows, gcc.g, gcc.O, gcc.warnings, gcc.extra_warnings, gcc.ldextras, gcc.include_dir, gcc.library_dir, targ1_luaw_exe, targ1_luaw_exe_o, targ1_lua_exe_libs) --[[ command procedurals --]] -- compile if(#targ1_compile_units > 0 or exe_test or force)then compiler_exec(targ_dir, compile_str1) obj_transfer() end if(#targ2_compile_units > 0 or exe_test or force)then compiler_exec(targ_dir, compile_str2) obj_transfer() end -- link/file manage if(#targ1_compile_units + #targ2_compile_units > 0 or exe_test or force)then -- link dll linker_exec(enc_dll(" luaadd"), linker_str_dll1) obj_transfer() -- link exe linker_exec("luaw", linker_str_exe1) -- strip redundancy if(not gcc.debug)then strip_targ(enc_exe("luaw")) end -- setup migrate_binaries(install_path, {enc_exe("luaw"), enc_dll("luaadd")}) end print("Done. Up to date.")
--[[ MIT License Copyright (c) 2017-2018 Cody Tilkins 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. --]] -- uncomment below or use -Dplat=Windows -- Linux -- MacOSX -- plat = os.types.Windows -- os.types.Linux -- os.types.MacOSX if(plat == nil)then error("Please define `plat` as Windows, Linux, or MacOSX") end require("luaadd") require("build_func") local lua_ver = choose_opt("lua51", "luajit-5.1", "luajit-5.1") local lua_define = " -DLUA_JIT_51" local lua_includes = " " --[[ gcc setup --]] local gcc = { gcc_name = "gcc"; debug = false; warnings = " -Wall"; windows = choose_opt(true, false, false); extra_warnings = ""; include_dir = " -I. -Iinclude" .. lua_includes; library_dir = " -L. -Llib -Lobj -Ldll"; ccextras = " -s" .. lua_define; ldextras = choose_opt(" -s", " -s -fPIC -Wl,-E", " -s -Wl,-E"); defines = choose_opt(" -D__USE_MINGW_ANSI_STDIO=1", "", ""); } gcc.g = gcc.debug and 3 or 0 gcc.O = gcc.debug and 0 or 2 local install_path = plat == os.types.Windows and (gcc.debug and ("bin\\Debug") or ("bin\\Release")) or ((plat == os.types.Linux or plat == os.types.MacOSX) and (gcc.debug and ("bin/Debug") or ("bin/Release"))) -- this is only a print() local targ_dir = (gcc.debug and "DEBUG" or "RELEASE") --[[ cache setup --]] local targ1_exe = {enc_exe("luaw")} local targ1_compile_units = {"consolew.c", "jitsupport.c", "darr.c"} local targ2_dll = {enc_dll("luaadd")} local targ2_compile_units = {"additions.c"} local exe_test = true if(no_cache == nil and force == nil) then if(cache == nil)then targ1_compile_units = check_cache(targ1_compile_units, "src/", "obj/", "o") targ2_compile_units = check_cache(targ2_compile_units, "src/", "obj/", "o") exe_test = check_bin_cache(targ1_exe, "src/", install_path .. "\\", targ1_compile_units) or check_bin_cache(targ1_exe, "src/", install_path .. "\\", targ2_compile_units) or check_bin_cache(targ2_dll, "src/", install_path .. "\\", targ1_compile_units) or check_bin_cache(targ2_dll, "src/", install_path .. "\\", targ2_compile_units) end if(#targ1_compile_units == 0 and #targ2_compile_units == 0 and not exe_test)then print("Done. Up to date.") return end end --[[ objects setup --]] local std_libs = enc_dll(" dll/" .. lua_ver) .. choose_opt("", " -lm -ldl", " -lm -ldl") local targ1_luaw_exe = enc_exe("luaw") local targ1_luaw_exe_o = {"consolew.o", "jitsupport.o", "darr.o"} local targ1_lua_exe_libs = std_libs local targ2_luaadd_dll_a = nil local targ2_luaadd_dll = enc_dll("luaadd") local targ2_luaadd_o = {"additions.o"} local targ2_luaadd_libs = std_libs --[[ compiler/linker strings --]] -- compile string local compile_str1 = gcc_c( gcc.g, gcc.O, gcc.warnings, gcc.extra_warnings, gcc.defines, gcc.ccextras, gcc.include_dir, gcc.library_dir, targ1_compile_units) local compile_str2 = gcc_c( gcc.g, gcc.O, gcc.warnings, gcc.extra_warnings, gcc.defines, gcc.ccextras, gcc.include_dir, gcc.library_dir, targ2_compile_units) -- generate additions dll/so string local linker_str_dll1 = choose_gcc_dll()( targ2_luaadd_dll_a, gcc.g, gcc.O, gcc.warnings, gcc.extra_warnings, gcc.defines, gcc.ldextras, gcc.include_dir, gcc.library_dir, targ2_luaadd_dll, targ2_luaadd_o, targ2_luaadd_libs) -- luaw linker string local linker_str_exe1 = gcc_l( gcc.windows, gcc.g, gcc.O, gcc.warnings, gcc.extra_warnings, gcc.ldextras, gcc.include_dir, gcc.library_dir, targ1_luaw_exe, targ1_luaw_exe_o, targ1_lua_exe_libs) --[[ command procedurals --]] -- compile if(#targ1_compile_units > 0 or exe_test or force)then compiler_exec(targ_dir, compile_str1) obj_transfer() end if(#targ2_compile_units > 0 or exe_test or force)then compiler_exec(targ_dir, compile_str2) obj_transfer() end -- link/file manage if(#targ1_compile_units + #targ2_compile_units > 0 or exe_test or force)then -- link dll linker_exec(enc_dll(" luaadd"), linker_str_dll1) obj_transfer() -- link exe linker_exec("luaw", linker_str_exe1) -- strip redundancy if(not gcc.debug)then strip_targ(enc_exe("luaw")) end -- setup migrate_binaries(install_path, {enc_exe("luaw"), enc_dll("luaadd")}) end print("Done. Up to date.")
Updated a few things...
Updated a few things... - Dropped need to -DLUA_51, etc (except for LUA_JIT_51) - Defaulted to luajit - Updated gcc table parameters - Indented a lot to make it look neat - Fixed up a few comments - lua_define now works as a variable
Lua
mit
Hydroque/LuaConsole,Hydroque/LuaConsole,Hydroque/LuaConsole
f6fffa683c30c24d19a10cbd962138cd1825e74a
scripts/walk.lua
scripts/walk.lua
local scene = Ogre.getSceneManager() am = AnimationManager.getSingleton() nv = NavigationMesh( Vector3.ZERO, Quaternion.IDENTITY, Vector3.UNIT_SCALE ) scene:destroyEntity'Nav' ne = scene:createEntity( 'FloorNav.mesh' ) nv:buildFromEntity( ne ) function moveTo( v ) local ma = MovementAnimation( player.node, v, player.walkspeed ) am:add(ma) ma:start() return ma end function rotateTo( heading ) local src = player.node:getOrientation() * Vector3.UNIT_X -- Prevent toppling over by restricting rotation to Y heading.y = src.y local quat = src:getRotationTo( heading, Vector3.UNIT_Y ) local ra = RotationAnimation( player.node, quat, 5 ) am:add(ra) ra:start() return ra end function getDirectionTo( v ) local d = v - player.node:getPosition() d:normalise() return d end function followList( list ) if type(list) ~= 'table' then return end local wa = MeshAnimation( player.mesh, 'Walk' ) am:add(wa) wa:setWeight(0) wa:setFadeSpeed(2) wa:start() wa:fadeIn() player.walking = true player.stopwalking = false player.walkspeed = 15 for i, vector in pairs(list) do if i ~= 1 then print( 'Turning to face ', vector ) local r = rotateTo( getDirectionTo( vector ) ) print( 'Heading off to ', vector ) local m = moveTo( vector ) while not m:isFinished() and not player.stopwalking do yield() end if player.stopwalking == true then m:stop() am:remove(m) break end end end player.walking = false wa:fadeOut() while wa:isFadingOut() do yield() end am:remove(wa) end function getpath() local p = player.node:getPosition() local d = base:hitPosition(_X,_Y) local maxAngle = Radian( Degree(90) ) return nv:findPath( p, d, maxAngle, 5 ) end function walkTask() player.stopwalking = true while player.walking == true do yield() end followList(path) end function walk() path = getpath() createTask( walkTask ) end bind( KeyCodes.KC_G, walk )
local scene = Ogre.getSceneManager() am = AnimationManager.getSingleton() nv = NavigationMesh( Vector3.ZERO, Quaternion.IDENTITY, Vector3.UNIT_SCALE ) scene:destroyEntity'Nav' ne = scene:createEntity( 'FloorNav.mesh' ) nv:buildFromEntity( ne ) function moveTo( v ) local ma = MovementAnimation( player.node, v, player.walkspeed ) am:add(ma) ma:start() return ma end function rotateTo( heading ) local src = player.node:getOrientation() * Vector3.UNIT_X -- Prevent toppling over by restricting rotation to Y heading.y = src.y local quat = src:getRotationTo( heading, Vector3.UNIT_Y ) local ra = RotationAnimation( player.node, quat, 5 ) am:add(ra) ra:start() return ra end function getDirectionTo( v ) local d = v - player.node:getPosition() d:normalise() return d end function followList( list ) if type(list) ~= 'table' then return end local wa = MeshAnimation( player.mesh, 'Walk' ) am:add(wa) wa:setWeight(0) wa:setFadeSpeed(2) wa:start() wa:fadeIn() player.walking = true player.stopwalking = false player.walkspeed = 15 for i, vector in pairs(list) do if i ~= 1 then local r if r ~= nil and r:isFinished() == false then r:stop(); print 'Stopping previous turn' end local r = rotateTo( getDirectionTo( vector ) ) local m = moveTo( vector ) while not m:isFinished() and not player.stopwalking do yield() end if player.stopwalking == true then m:stop() am:remove(m) break end end end player.walking = false wa:fadeOut() while wa:isFadingOut() do yield() end am:remove(wa) end function getpath() local p = player.node:getPosition() local d = base:hitPosition(_X,_Y) local maxAngle = Radian( Degree(90) ) return nv:findPath( p, d, maxAngle, 5 ) end function walkTask() player.stopwalking = true while player.walking == true do yield() end startwalk = false followList(path) end function walk() if startwalk then return end startwalk = true path = getpath() createTask( walkTask ) end bind( KeyCodes.KC_G, walk )
Fix race condidtion in walking code
Fix race condidtion in walking code When the walk function is called, and it is already waiting for the previous walk task to finish, it simply exits. This only happens when called repeativly very quickly.
Lua
mit
merlinblack/Game-Engine-Testbed,merlinblack/Game-Engine-Testbed,merlinblack/Game-Engine-Testbed,merlinblack/Game-Engine-Testbed
11e7b164ae26f151e21d051fb2757af193d3443c
src/main/resources/wol/Vec3.lua
src/main/resources/wol/Vec3.lua
-- Lua Module for the Vec3 class require "wol.Check" -- Checks if obj is an instance of Vec3. If not, a error is thrown. -- TODO provide a generic function in check that can do this. function Check.isVec3(obj,i) local ok=instanceOf(Vec3,obj) if i==nil then assert(ok, "bad argument (Vec3 expected, got %s)", type(obj)) elseif tonumber(i) then assert(ok, "bad argument #%d (Vec3 expected, got %s)", i, type(obj)) elseif type(i)=="string" then assert(ok, "bad argument '%s' (Vec3 expected, got %s)", i, type(obj)) else error("Illegal position argument for check call: %s", i) end end function Vec3.from(x,y,z) Check.isNumber(x,1) Check.isNumber(y,2) Check.isNumber(z,3) return Vec3.new({x=x,y=y,z=z}) end -- This declares a convenient 'constructor' delegating to Vec3.from() -- Use it like this: v=Vec3(x,y,z) local mt = {__call=function(tbl,x,y,z) return Vec3.from(x,y,z) end;} setmetatable(Vec3,mt) function Vec3.new(o) o = o or {} o.x = o.x or 0 o.y = o.y or 0 o.z = o.z or 0 Check.isNumber(o.x,"o.x") Check.isNumber(o.y,"o.y") Check.isNumber(o.z,"o.z") setmetatable(o, Vec3) return o end function Vec3:tostring() return "{" .. self.x .. ", " .. self.y .. ", " .. self.z .. "}" end Vec3.__tostring = Vec3.tostring function Vec3.add(v1,v2) Check.isVec3(v1,1) Check.isVec3(v2,2) local x = v1.x+v2.x local y = v1.y+v2.y local z = v1.z+v2.z return Vec3.from(x,y,z) end Vec3.__add = Vec3.add function Vec3.substract(v1,v2) Check.isVec3(v1,1) Check.isVec3(v2,2) local x = v1.x-v2.x local y = v1.y-v2.y local z = v1.z-v2.z return Vec3.from(x,y,z) end Vec3.__sub = Vec3.substract function Vec3:sqrMagnitude() return self.x*self.x + self.y*self.y + self.z*self.z end function Vec3:magnitude() return math.sqrt(self:sqrMagnitude()) end function Vec3.dotProduct(v1,v2) Check.isVec3(v1,1) Check.isVec3(v2,2) return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z end function Vec3.scale(a,b) local v,f if tonumber(a) then Check.isVec3(b,2) v,f=b,a elseif instanceOf(Vec3,a) then Check.isNumber(b,2) v,f=a,b else error("bad argument #%d (number or Vec3 expected, got %s)",1,type(a)) end return Vec3.from(v.x*f, v.y*f, v.z*f) end Vec3.__mul = function(a,b) if tonumber(a) or tonumber(b) then return Vec3.scale(a,b) else return Vec3.dotProduct(a,b) end end function Vec3.invert(v1) Check.isVec3(v1,1) return Vec3.from(-v1.x, -v1.y, -v1.z) end Vec3.__unm = Vec3.invert function Vec3.__concat(a,b) return tostring(a)..tostring(b) end function Vec3.__eq(a,b) return a.x==b.x and a.y==b.y and a.z==b.z end function Vec3:normalize() local len=self:magnitude() if len==0 then error("Can't normalize the null vector!") end local result=self*(1/len) return result end -- Here is some example code of how you could create a subclass of Vec3 --[[ declare("Vec3n",Vec3) function Vec3n.new(o) o = Vec3.new(o) o.n = o.n or "noname" Check.isString(o.n,"o.n") setmetatable(o, Vec3n) return o end --]]
-- Lua Module for the Vec3 class require "wol.Check" -- Checks if obj is an instance of Vec3. If not, a error is thrown. -- TODO provide a generic function in check that can do this. function Check.isVec3(obj,i) local ok=instanceOf(Vec3,obj) if i==nil then assert(ok, "bad argument (Vec3 expected, got %s)", type(obj)) elseif tonumber(i) then assert(ok, "bad argument #%d (Vec3 expected, got %s)", i, type(obj)) elseif type(i)=="string" then assert(ok, "bad argument '%s' (Vec3 expected, got %s)", i, type(obj)) else error("Illegal position argument for check call: %s", i) end end function Vec3.from(x,y,z) Check.isNumber(x,1) Check.isNumber(y,2) Check.isNumber(z,3) return Vec3.new({x=x,y=y,z=z}) end -- This declares a convenient 'constructor' delegating to Vec3.from() -- Use it like this: v=Vec3(x,y,z) local mt = {__call=function(tbl,x,y,z) return Vec3.from(x,y,z) end;} setmetatable(Vec3,mt) function Vec3.new(o) o = o or {} o.x = o.x or 0 o.y = o.y or 0 o.z = o.z or 0 Check.isNumber(o.x,"o.x") Check.isNumber(o.y,"o.y") Check.isNumber(o.z,"o.z") setmetatable(o, Vec3) return o end function Vec3:tostring() return "{" .. self.x .. ", " .. self.y .. ", " .. self.z .. "}" end Vec3.__tostring = Vec3.tostring function Vec3.add(v1,v2) Check.isVec3(v1,1) Check.isVec3(v2,2) local x = v1.x+v2.x local y = v1.y+v2.y local z = v1.z+v2.z return Vec3.from(x,y,z) end Vec3.__add = Vec3.add function Vec3.substract(v1,v2) Check.isVec3(v1,1) Check.isVec3(v2,2) local x = v1.x-v2.x local y = v1.y-v2.y local z = v1.z-v2.z return Vec3.from(x,y,z) end Vec3.__sub = Vec3.substract function Vec3:sqrMagnitude() return self.x*self.x + self.y*self.y + self.z*self.z end function Vec3:magnitude() return math.sqrt(self:sqrMagnitude()) end function Vec3.dotProduct(v1,v2) Check.isVec3(v1,1) Check.isVec3(v2,2) return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z end function Vec3.scale(a,b) local v,f if tonumber(a) then Check.isVec3(b,2) v,f=b,a elseif instanceOf(Vec3,a) then Check.isNumber(b,2) v,f=a,b else error("bad argument #%d (number or Vec3 expected, got %s)",1,type(a)) end return Vec3.from(v.x*f, v.y*f, v.z*f) end Vec3.__mul = function(a,b) if tonumber(a) or tonumber(b) then return Vec3.scale(a,b) else return Vec3.dotProduct(a,b) end end function Vec3.invert(v1) Check.isVec3(v1,1) return Vec3.from(-v1.x, -v1.y, -v1.z) end Vec3.__unm = Vec3.invert function Vec3.__concat(a,b) return tostring(a)..tostring(b) end function Vec3.__eq(a,b) return a.x==b.x and a.y==b.y and a.z==b.z end function Vec3:normalize() local len=self:magnitude() if len==0 then error("Can't normalize the null vector!") end local result=self*(1/len) return result end function Vec3:floor() return Vec3( math.floor(self.x), math.floor(self.y), math.floor(self.z)) end -- Here is some example code of how you could create a subclass of Vec3 --[[ declare("Vec3n",Vec3) function Vec3n.new(o) o = Vec3.new(o) o.n = o.n or "noname" Check.isString(o.n,"o.n") setmetatable(o, Vec3n) return o end --]]
Fixes #150 - Add Vec3.floor()
Fixes #150 - Add Vec3.floor()
Lua
apache-2.0
mkarneim/luamod
0aee02485b3093db9362b1f7e4f6f07d69050c68
durden/tools/advfloat/spawnctl.lua
durden/tools/advfloat/spawnctl.lua
gconfig_register("advfloat_spawn", "auto"); gconfig_register("advfloat_actionreg", false); local pending, pending_vid; local function setup_cursor_pick(wm, wnd) wnd:hide(); pending = wnd; local w = math.ceil(wm.width * 0.15); local h = math.ceil(wm.height * 0.15); pending_vid = null_surface(w, h); link_image(pending_vid, mouse_state().cursor); image_sharestorage(wnd.canvas, pending_vid); blend_image(pending_vid, 1.0, 10); image_inherit_order(pending_vid, true); order_image(pending_vid, -1); nudge_image(pending_vid, mouse_state().size[1] * 0.75, mouse_state().size[2] * 0.75); shader_setup(pending_vid, "ui", "regmark", "active"); end local function activate_pending() delete_image(pending_vid); pending = nil; end local function wnd_attach(wm, wnd) wnd:ws_attach(true); if (wnd.wm:active_space().mode ~= "float") then return; end if (pending) then activate_pending(); if (DURDEN_REGIONSEL_TRIGGER) then suppl_region_stop(); end end local mode = gconfig_get("advfloat_spawn"); if (mode == "click") then setup_cursor_pick(wm, wnd); iostatem_save(); local col = null_surface(1, 1); mouse_select_begin(col); dispatch_meta_reset(); dispatch_symbol_lock(); durden_input = durden_regionsel_input; -- the region setup and accept/fail is really ugly, but reworking it -- right now is not really an option DURDEN_REGIONFAIL_TRIGGER = function() activate_pending(); wnd:show(); DURDEN_REGIONFAIL_TRIGGER = nil; end DURDEN_REGIONSEL_TRIGGER = function() activate_pending(); if (wnd.show) then wnd:show(); end DURDEN_REGIONFAIL_TRIGGER = nil; end elseif (mode == "draw") then setup_cursor_pick(wm, wnd); DURDEN_REGIONFAIL_TRIGGER = function() activate_pending(); DURDEN_REGIONFAIL_TRIGGER = nil; end suppl_region_select(200, 198, 36, function(x1, y1, x2, y2) activate_pending(); local w = x2 - x1; local h = y2 - y1; if (w > 64 and h > 64) then wnd:resize(w, h); end wnd:move(x1, y1, false, true, true); wnd:show(); end); -- auto should really be to try and calculate the best fitting free space elseif (mode == "cursor") then local x, y = mouse_xy(); if (x + wnd.width > wnd.wm.effective_width) then x = wnd.wm.effective_width - wnd.width; end if (y + wnd.width > wnd.wm.effective_height) then y = wnd.wm.effective_height - wnd.height; end wnd:move(x, y, false, true, true); else end end --- hook displays so we can decide spawn mode between things like --- spawn hidden, cursor-click to position, draw to spawn display_add_listener( function(event, name, tiler, id) if (event == "added" and tiler) then tiler.attach_hook = wnd_attach; end end );
gconfig_register("advfloat_spawn", "auto"); gconfig_register("advfloat_actionreg", false); local pending, pending_vid; local function setup_cursor_pick(wm, wnd) wnd:hide(); pending = wnd; local w = math.ceil(wm.width * 0.15); local h = math.ceil(wm.height * 0.15); pending_vid = null_surface(w, h); link_image(pending_vid, mouse_state().cursor); image_sharestorage(wnd.canvas, pending_vid); blend_image(pending_vid, 1.0, 10); image_inherit_order(pending_vid, true); order_image(pending_vid, -1); nudge_image(pending_vid, mouse_state().size[1] * 0.75, mouse_state().size[2] * 0.75); shader_setup(pending_vid, "ui", "regmark", "active"); end local function activate_pending() delete_image(pending_vid); pending = nil; end local function wnd_attach(wm, wnd) wnd:ws_attach(true); if (wnd.wm:active_space().mode ~= "float") then return; end if (pending) then activate_pending(); if (DURDEN_REGIONSEL_TRIGGER) then suppl_region_stop(); end end local mode = gconfig_get("advfloat_spawn"); if (mode == "click") then setup_cursor_pick(wm, wnd); iostatem_save(); local col = null_surface(1, 1); mouse_select_begin(col); dispatch_meta_reset(); dispatch_symbol_lock(); durden_input = durden_regionsel_input; -- the region setup and accept/fail is really ugly, but reworking it -- right now is not really an option DURDEN_REGIONFAIL_TRIGGER = function() activate_pending(); wnd:show(); DURDEN_REGIONFAIL_TRIGGER = nil; end DURDEN_REGIONSEL_TRIGGER = function() activate_pending(); if (wnd.show) then wnd:show(); end DURDEN_REGIONFAIL_TRIGGER = nil; end elseif (mode == "draw") then setup_cursor_pick(wm, wnd); DURDEN_REGIONFAIL_TRIGGER = function() activate_pending(); DURDEN_REGIONFAIL_TRIGGER = nil; end suppl_region_select(200, 198, 36, function(x1, y1, x2, y2) activate_pending(); local w = x2 - x1; local h = y2 - y1; if (w > 64 and h > 64) then wnd:resize(w, h); -- get control of the 'spawn' animation used here, might fight with flair later instant_image_transform(wnd.anchor); instant_image_transform(wnd.canvas); instant_image_transform(wnd.border); wnd.titlebar:resize(wnd.titlebar.width, wnd.titlebar.height, 0); end wnd:move(x1, y1, false, true, 0); wnd:show(); end); -- auto should really be to try and calculate the best fitting free space elseif (mode == "cursor") then local x, y = mouse_xy(); if (x + wnd.width > wnd.wm.effective_width) then x = wnd.wm.effective_width - wnd.width; end if (y + wnd.width > wnd.wm.effective_height) then y = wnd.wm.effective_height - wnd.height; end wnd:move(x, y, false, true, true); else end end --- hook displays so we can decide spawn mode between things like --- spawn hidden, cursor-click to position, draw to spawn display_add_listener( function(event, name, tiler, id) if (event == "added" and tiler) then tiler.attach_hook = wnd_attach; end end );
spawnctl - superflous animation fix
spawnctl - superflous animation fix
Lua
bsd-3-clause
letoram/durden
9744d8983ef5507bd29d4c990704b75fad4dae99
.hammerspoon/bindings.lua
.hammerspoon/bindings.lua
-- -- Key binding setup for all modules and misc functionality -- local bindings = {} local uapp = require('utils.app') -- define some modifier key combinations local mod = { cc = {'cmd', 'ctrl'}, ca = {'cmd', 'alt'}, as = {'alt', 'shift'}, cas = {'cmd', 'alt', 'shift'}, hyper = {'cmd', 'alt', 'ctrl'}, -- mapped to L_CTRL with Karabiner and Seil shyper = {'cmd', 'alt', 'ctrl', 'shift'}, } function bindings.bind() -- launch and focus applications -- (all use hyper key) hs.fnutils.each({ {key = 'b', app = 'Google Chrome'}, -- "b"rowser {key = 'c', app = 'Slack'}, -- "c"hat {key = 'f', app = 'Finder'}, {key = 'i', app = 'iTunes'}, {key = 'm', app = 'Messages'}, {key = 'q', app = 'Qbserve'}, {key = 's', app = 'Spotify'}, {key = 't', app = 'iTerm'}, -- "t"erminal {key = 'v', app = 'nvimOpen'}, -- "v"im {key = '\'', app = 'Color Picker'}, }, function(item) local appActivation = function() hs.application.launchOrFocus(item.app) local app = hs.appfinder.appFromName(item.app) if app then app:activate() app:unhide() end end hs.hotkey.bind(mod.hyper, item.key, appActivation) end) -- toggle the hammerspoon console, focusing on the previous app when hidden local lastApp = nil local function toggleConsole() local frontmost = hs.application.frontmostApplication() hs.toggleConsole() if frontmost:bundleID() == 'org.hammerspoon.Hammerspoon' then if lastApp ~= nil then lastApp:activate() lastApp = nil end else lastApp = frontmost end end local function maximizeFrontmost() local win = hs.application.frontmostApplication():focusedWindow() if not win:isFullScreen() then win:maximize() end end -- module key bindings -- (all using shift-hyper) hs.fnutils.each({ {key = '0', fn = hsm.worktime.nextMode}, {key = '1', fn = hsm.songs.rateSong1}, {key = '2', fn = hsm.songs.rateSong2}, {key = '3', fn = hsm.songs.rateSong3}, {key = '4', fn = hsm.songs.rateSong4}, {key = '5', fn = hsm.songs.rateSong5}, {key = '8', fn = hsm.worktime.pauseUnpause}, {key = '9', fn = hsm.worktime.reset}, {key = '[', fn = hsm.songs.prevTrack}, {key = '\\', fn = hsm.caffeine.toggle}, {key = ']', fn = hsm.songs.nextTrack}, {key = '`', fn = hsm.songs.rateSong0}, {key = 'c', fn = hsm.cheatsheet.cycle}, {key = 'm', fn = uapp.toggleSkypeMute}, {key = 'p', fn = hsm.songs.playPause}, {key = 'r', fn = hs_reload}, {key = 's', fn = hsm.cheatsheet.toggle}, {key = 't', fn = hsm.songs.getInfo}, {key = 'v', fn = uapp.forcePaste}, {key = 'x', fn = hsm.cheatsheet.chooserToggle}, {key = 'y', fn = toggleConsole}, {key = 'z', fn = maximizeFrontmost}, }, function(object) hs.hotkey.bind(mod.shyper, object.key, object.fn) end) -- bindings for the spacebar hs.hotkey.bind({'alt'}, hs.keycodes.map.space, hsm.scratchpad.toggle) hs.hotkey.bind(mod.as, hs.keycodes.map.space, hsm.timer.toggle) hs.hotkey.bind(mod.hyper, hs.keycodes.map.space, hsm.notational.toggle) hs.hotkey.bind(mod.shyper, hs.keycodes.map.space, function() hsm.notational.toggle(hsm.notational.cfg.path.til) end) end return bindings
-- -- Key binding setup for all modules and misc functionality -- local bindings = {} local uapp = require('utils.app') -- define some modifier key combinations local mod = { s = {'shift'}, a = {'alt'}, cc = {'cmd', 'ctrl'}, ca = {'cmd', 'alt'}, as = {'alt', 'shift'}, cas = {'cmd', 'alt', 'shift'}, } -- Hyper key in Sierra local hyper = hs.hotkey.modal.new({}, 'F17') -- Enter/Exit Hyper Mode when F18 is pressed/released local pressedF18 = function() hyper:enter() end local releasedF18 = function() hyper:exit() end -- Bind the Hyper key -- Also requires Karabiner-Elements to bind left_control to F18 hs.hotkey.bind({}, 'F18', pressedF18, releasedF18) hs.hotkey.bind(mod.s, 'F18', pressedF18, releasedF18) function bindings.bind() -- launch and focus applications -- (all use hyper key) hs.fnutils.each({ {key = 'b', app = 'Google Chrome'}, -- "b"rowser {key = 'c', app = 'Slack'}, -- "c"hat {key = 'f', app = 'Finder'}, {key = 'i', app = 'iTunes'}, {key = 'm', app = 'Messages'}, {key = 'q', app = 'Qbserve'}, {key = 's', app = 'Spotify'}, {key = 't', app = 'iTerm'}, -- "t"erminal {key = 'v', app = 'nvimOpen'}, -- "v"im {key = '\'', app = 'Color Picker'}, }, function(item) local appActivation = function() hs.application.launchOrFocus(item.app) local app = hs.appfinder.appFromName(item.app) if app then app:activate() app:unhide() end end hyper:bind({}, item.key, appActivation) end) -- toggle the hammerspoon console, focusing on the previous app when hidden local lastApp = nil local function toggleConsole() local frontmost = hs.application.frontmostApplication() hs.toggleConsole() if frontmost:bundleID() == 'org.hammerspoon.Hammerspoon' then if lastApp ~= nil then lastApp:activate() lastApp = nil end else lastApp = frontmost end end local function maximizeFrontmost() local win = hs.application.frontmostApplication():focusedWindow() if not win:isFullScreen() then win:maximize() end end -- module key bindings -- (all using shift-hyper) hs.fnutils.each({ {key = '0', fn = hsm.worktime.nextMode}, {key = '1', fn = hsm.songs.rateSong1}, {key = '2', fn = hsm.songs.rateSong2}, {key = '3', fn = hsm.songs.rateSong3}, {key = '4', fn = hsm.songs.rateSong4}, {key = '5', fn = hsm.songs.rateSong5}, {key = '8', fn = hsm.worktime.pauseUnpause}, {key = '9', fn = hsm.worktime.reset}, {key = '[', fn = hsm.songs.prevTrack}, {key = '\\', fn = hsm.caffeine.toggle}, {key = ']', fn = hsm.songs.nextTrack}, {key = '`', fn = hsm.songs.rateSong0}, {key = 'c', fn = hsm.cheatsheet.cycle}, {key = 'm', fn = uapp.toggleSkypeMute}, {key = 'p', fn = hsm.songs.playPause}, {key = 'r', fn = hs_reload}, {key = 's', fn = hsm.cheatsheet.toggle}, {key = 't', fn = hsm.songs.getInfo}, {key = 'v', fn = uapp.forcePaste}, {key = 'x', fn = hsm.cheatsheet.chooserToggle}, {key = 'y', fn = toggleConsole}, {key = 'z', fn = maximizeFrontmost}, }, function(object) hyper:bind(mod.s, object.key, object.fn) end) -- bindings for the spacebar hs.hotkey.bind(mod.a, hs.keycodes.map.space, hsm.scratchpad.toggle) hs.hotkey.bind(mod.as, hs.keycodes.map.space, hsm.timer.toggle) hyper:bind({}, hs.keycodes.map.space, hsm.notational.toggle) hyper:bind(mod.s, hs.keycodes.map.space, function() hsm.notational.toggle(hsm.notational.cfg.path.til) end) end return bindings
Fix Hyper key in Sierra
Fix Hyper key in Sierra
Lua
mit
scottcs/dot_hammerspoon
ac18db705bc39e00f316cebf315435a019fca7d0
build/scripts/Torque6.lua
build/scripts/Torque6.lua
function Torque6() project "Torque6" targetname "Torque6" language "C++" kind "SharedLib" targetdir (BUILD_DIR) includedirs { path.join(LIB_DIR, "assimp/include"), path.join(LIB_DIR, "bgfx/include"), path.join(LIB_DIR, "bullet"), path.join(LIB_DIR, "bgfx/3rdparty"), path.join(LIB_DIR, "bgfx/common"), path.join(LIB_DIR, "zlib"), path.join(LIB_DIR, "lpng"), path.join(LIB_DIR, "ljpeg"), path.join(LIB_DIR, "openal/win32"), SRC_DIR, path.join(SRC_DIR, "persistence/rapidjson/include"), path.join(SRC_DIR, "persistence/libjson"), path.join(SRC_DIR, "testing/googleTest"), path.join(SRC_DIR, "testing/googleTest/include"), path.join(SRC_DIR, "spine"), } files { path.join(SRC_DIR, "**.h"), path.join(SRC_DIR, "**.cc"), path.join(SRC_DIR, "**.cpp"), path.join(SRC_DIR, "**.c"), } removefiles { path.join(SRC_DIR, "console/runtimeClassRep.cc"), path.join(SRC_DIR, "exe/**"), path.join(SRC_DIR, "input/leapMotion/**"), path.join(SRC_DIR, "graphics/bitmapPvr.cc"), path.join(SRC_DIR, "math/mMathAMD.cc"), path.join(SRC_DIR, "math/mMathSSE.cc"), path.join(SRC_DIR, "persistence/rapidjson/example/**"), path.join(SRC_DIR, "persistence/rapidjson/test/**"), path.join(SRC_DIR, "persistence/rapidjson/thirdparty/**"), path.join(SRC_DIR, "testing/googleTest/**"), } links { "assimp", "bgfx", "bullet", "ljpeg", "lpng", "zlib", } configuration { "windows", "x32", "Release" } targetdir (BUILD_DIR .. "/windows.x32.release") configuration { "windows", "x32", "Debug" } targetdir (BUILD_DIR .. "/windows.x32.debug") configuration { "windows", "x64", "Release" } targetdir (BUILD_DIR .. "/windows.x64.release") configuration { "windows", "x64", "Debug" } targetdir (BUILD_DIR .. "/windows.x64.debug") configuration "Release" defines { "TORQUE_ENABLE_PROFILER" } configuration "Debug" targetname "Torque6_DEBUG" defines { "TORQUE_DEBUG", "TORQUE_ENABLE_PROFILER", "TORQUE_DEBUG_GUARD", } flags { "Symbols" } configuration "vs*" defines { "_CRT_SECURE_NO_WARNINGS", "UNICODE" } flags { "NoNativeWChar" } buildoptions { "/wd4100", "/wd4800" } includedirs { path.join(LIB_DIR, "bgfx/include/compat/msvc"), } configuration "vs2015" windowstargetplatformversion "10.0.10240.0" configuration "windows" links { "COMCTL32", "COMDLG32", "USER32", "ADVAPI32", "GDI32", "RPCRT4", "WINMM", "WSOCK32", "vfw32", "Imm32", "shell32", "shlwapi", "ole32", "psapi", "d3dcompiler", "dxguid", } removefiles { path.join(SRC_DIR, "platform/**.unix.cc"), path.join(SRC_DIR, "platformAndroid/**"), path.join(SRC_DIR, "platformEmscripten/**"), path.join(SRC_DIR, "platformiOS/**"), path.join(SRC_DIR, "platformOSX/**"), path.join(SRC_DIR, "platformX86UNIX/**"), } configuration "linux" defines { "linux" } links { "stdc++", "m", "dl", "pthread", "rt", "X11", "Xft", "SDL", "openal" } includedirs { "/usr/include/freetype2" } removefiles { path.join(SRC_DIR, "input/leapMotion/**"), path.join(SRC_DIR, "platformX86UNIX/x86UNIXDedicatedStub.cc"), path.join(SRC_DIR, "platformAndroid/**"), path.join(SRC_DIR, "platformEmscripten/**"), path.join(SRC_DIR, "platformiOS/**"), path.join(SRC_DIR, "platformOSX/**"), path.join(SRC_DIR, "platformWin32/**"), } configuration "linux or bsd" links { "m" } linkoptions { "-rdynamic", "-shared" } buildoptions { "-std=c++0x", "-fpermissive", "-fPIC" } configuration "macosx" links { "CoreServices.framework" } linkoptions { "-framework Cocoa", "-framework Metal", "-framework QuartzCore", "-framework OpenAL", } includedirs { path.join(LIB_DIR, "bgfx/include/compat/osx"), } files { path.join(SRC_DIR, "platformOSX/**.mm"), } removefiles { path.join(SRC_DIR, "input/leapMotion/**"), path.join(SRC_DIR, "platformX86UNIX/x86UNIXDedicatedStub.cc"), path.join(SRC_DIR, "platformAndroid/**"), path.join(SRC_DIR, "platformEmscripten/**"), path.join(SRC_DIR, "platformiOS/**"), path.join(SRC_DIR, "platformWin32/**"), path.join(SRC_DIR, "platformX86UNIX/**"), path.join(SRC_DIR, "testing/**"), } end
function Torque6() project "Torque6" targetname "Torque6" language "C++" kind "SharedLib" targetdir (BUILD_DIR) includedirs { path.join(LIB_DIR, "assimp/include"), path.join(LIB_DIR, "bgfx/include"), path.join(LIB_DIR, "bullet"), path.join(LIB_DIR, "bgfx/3rdparty"), path.join(LIB_DIR, "bgfx/common"), path.join(LIB_DIR, "zlib"), path.join(LIB_DIR, "lpng"), path.join(LIB_DIR, "ljpeg"), path.join(LIB_DIR, "openal/win32"), SRC_DIR, path.join(SRC_DIR, "persistence/rapidjson/include"), path.join(SRC_DIR, "persistence/libjson"), path.join(SRC_DIR, "testing/googleTest"), path.join(SRC_DIR, "testing/googleTest/include"), path.join(SRC_DIR, "spine"), } files { path.join(SRC_DIR, "**.h"), path.join(SRC_DIR, "**.cc"), path.join(SRC_DIR, "**.cpp"), path.join(SRC_DIR, "**.c"), } removefiles { path.join(SRC_DIR, "console/runtimeClassRep.cc"), path.join(SRC_DIR, "exe/**"), path.join(SRC_DIR, "input/leapMotion/**"), path.join(SRC_DIR, "graphics/bitmapPvr.cc"), path.join(SRC_DIR, "math/mMathAMD.cc"), path.join(SRC_DIR, "math/mMathSSE.cc"), path.join(SRC_DIR, "persistence/rapidjson/example/**"), path.join(SRC_DIR, "persistence/rapidjson/test/**"), path.join(SRC_DIR, "persistence/rapidjson/thirdparty/**"), path.join(SRC_DIR, "testing/googleTest/**"), } links { "assimp", "bgfx", "bullet", "ljpeg", "lpng", "zlib", } configuration { "windows", "x32", "Release" } targetdir (BUILD_DIR .. "/windows.x32.release") configuration { "windows", "x32", "Debug" } targetdir (BUILD_DIR .. "/windows.x32.debug") configuration { "windows", "x64", "Release" } targetdir (BUILD_DIR .. "/windows.x64.release") configuration { "windows", "x64", "Debug" } targetdir (BUILD_DIR .. "/windows.x64.debug") configuration "Release" defines { "TORQUE_ENABLE_PROFILER" } configuration "Debug" targetname "Torque6_DEBUG" defines { "TORQUE_DEBUG", "TORQUE_ENABLE_PROFILER", "TORQUE_DEBUG_GUARD", } flags { "Symbols" } configuration "vs*" defines { "_CRT_SECURE_NO_WARNINGS", "UNICODE" } flags { "NoNativeWChar" } buildoptions { "/wd4100", "/wd4800" } includedirs { path.join(LIB_DIR, "bgfx/include/compat/msvc"), } configuration "vs2015" windowstargetplatformversion "10.0.10240.0" configuration "windows" links { "COMCTL32", "COMDLG32", "USER32", "ADVAPI32", "GDI32", "RPCRT4", "WINMM", "WSOCK32", "vfw32", "Imm32", "shell32", "shlwapi", "ole32", "psapi", "d3dcompiler", "dxguid", } removefiles { path.join(SRC_DIR, "platform/**.unix.cc"), path.join(SRC_DIR, "platformAndroid/**"), path.join(SRC_DIR, "platformEmscripten/**"), path.join(SRC_DIR, "platformiOS/**"), path.join(SRC_DIR, "platformOSX/**"), path.join(SRC_DIR, "platformX86UNIX/**"), } configuration "linux" defines { "linux" } links { "stdc++", "m", "dl", "pthread", "rt", "X11", "Xft", "SDL", "openal" } includedirs { "/usr/include/freetype2" } removefiles { path.join(SRC_DIR, "input/leapMotion/**"), path.join(SRC_DIR, "platformX86UNIX/x86UNIXDedicatedStub.cc"), path.join(SRC_DIR, "platformAndroid/**"), path.join(SRC_DIR, "platformEmscripten/**"), path.join(SRC_DIR, "platformiOS/**"), path.join(SRC_DIR, "platformOSX/**"), path.join(SRC_DIR, "platformWin32/**"), } configuration "linux or bsd" links { "m" } linkoptions { "-rdynamic", "-shared" } buildoptions { "-std=c++0x", "-fpermissive", "-fPIC" } configuration { "linux", "x32" } buildoptions { "-m32" } configuration "macosx" links { "CoreServices.framework" } linkoptions { "-framework Cocoa", "-framework Metal", "-framework QuartzCore", "-framework OpenAL", } includedirs { path.join(LIB_DIR, "bgfx/include/compat/osx"), } files { path.join(SRC_DIR, "platformOSX/**.mm"), } removefiles { path.join(SRC_DIR, "input/leapMotion/**"), path.join(SRC_DIR, "platformX86UNIX/x86UNIXDedicatedStub.cc"), path.join(SRC_DIR, "platformAndroid/**"), path.join(SRC_DIR, "platformEmscripten/**"), path.join(SRC_DIR, "platformiOS/**"), path.join(SRC_DIR, "platformWin32/**"), path.join(SRC_DIR, "platformX86UNIX/**"), path.join(SRC_DIR, "testing/**"), } end
Potential fix for linux 32-bit builds.
Potential fix for linux 32-bit builds.
Lua
mit
JeffProgrammer/Torque6,lukaspj/Torque6,RichardRanft/Torque6,JeffProgrammer/Torque6,andr3wmac/Torque6,andr3wmac/Torque6,lukaspj/Torque6,JeffProgrammer/Torque6,JeffProgrammer/Torque6,andr3wmac/Torque6,lukaspj/Torque6,lukaspj/Torque6,RichardRanft/Torque6,JeffProgrammer/Torque6,JeffProgrammer/Torque6,RichardRanft/Torque6,RichardRanft/Torque6,lukaspj/Torque6,lukaspj/Torque6,lukaspj/Torque6,andr3wmac/Torque6,andr3wmac/Torque6,JeffProgrammer/Torque6,RichardRanft/Torque6,andr3wmac/Torque6,andr3wmac/Torque6,JeffProgrammer/Torque6,andr3wmac/Torque6,RichardRanft/Torque6,RichardRanft/Torque6,lukaspj/Torque6,RichardRanft/Torque6
3a2142f9370433773c2c9fad14e0b6a50026c5bd
lua/framework/graphics/font.lua
lua/framework/graphics/font.lua
--=========== Copyright © 2018, Planimeter, All rights reserved. =============-- -- -- Purpose: -- --============================================================================-- require( "class" ) local FT = require( "freetype" ) local ffi = require( "ffi" ) local GL = require( "opengl" ) local ft = ffi.new( "FT_Library[1]" ) FT.FT_Init_FreeType( ft ) class( "framework.graphics.font" ) local font = framework.graphics.font function font:font( filename, size ) size = size or 16 self.face = ffi.new( "FT_Face[1]" ) self.buffer, self.length = framework.filesystem.read( filename ) if ( self.buffer == nil ) then FT.FT_Done_Face( self.face ) error( self.length, 3 ) end FT.FT_New_Memory_Face( ft[0], self.buffer, self.length, 0, self.face ) self.size = size size = size * framework.window.getPixelScale() FT.FT_Set_Pixel_Sizes( self.face[0], 0, size ) self.texture = ffi.new( "GLuint[1]" ) GL.glGenTextures( 1, self.texture ) GL.glBindTexture( GL.GL_TEXTURE_2D, self.texture[0] ) GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_BASE_LEVEL, 0 ) GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAX_LEVEL, 0 ) local o = GL.GL_ONE local r = GL.GL_RED local mask = ffi.new( "GLint[4]", o, o, o, r ) GL.glTexParameteriv( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_SWIZZLE_RGBA, mask ) local s = self.face[0].size.metrics; self.advance = bit.rshift( tonumber( s.max_advance ), 6 ) self.ascent = bit.rshift( tonumber( s.ascender ), 6 ) self.descent = bit.rshift( tonumber( s.descender ), 6 ) self.height = bit.rshift( tonumber( s.height ), 6 ) setproxy( self ) end function font:getWidth( text ) local width = 0 local face = self.face[0] for i = 1, #text do local char = string.sub( text, i, i ) if ( FT.FT_Load_Char( face, string.byte( char ), 4 ) == 0 ) then local g = face.glyph local bw = g.bitmap.width width = width + bw else error( "Could not load character '" .. char .. "'", 3 ) end end return tonumber( width ) end function font:getHeight() return math.floor( self.height / framework.window.getPixelScale() + 0.5 ) end function font:getWrap() -- TODO: Implement me. return 0, {} end function font:print( text, x, y, r, sx, sy, ox, oy, kx, ky ) local defaultVBO = framework.graphics._defaultVBO local shader = framework.graphics.getShader() local position = GL.glGetAttribLocation( shader, "position" ) local stride = 4 * ffi.sizeof( "GLfloat" ) local texcoord = GL.glGetAttribLocation( shader, "texcoord" ) local pointer = ffi.cast( "GLvoid *", 2 * ffi.sizeof( "GLfloat" ) ) GL.glBindBuffer( GL.GL_ARRAY_BUFFER, defaultVBO[0] ) GL.glVertexAttribPointer( position, 2, GL.GL_FLOAT, 0, stride, nil ) GL.glEnableVertexAttribArray( texcoord ) GL.glVertexAttribPointer( texcoord, 2, GL.GL_FLOAT, 0, stride, pointer ) framework.graphics.updateTransformations() GL.glBindTexture( GL.GL_TEXTURE_2D, self.texture[0] ) GL.glPixelStorei( GL.GL_UNPACK_ALIGNMENT, 1 ) local face = self.face[0] local _x = x for i = 1, #text do local char = string.sub( text, i, i ) if ( FT.FT_Load_Char( face, string.byte( char ), 4 ) == 0 ) then if ( char == "\n" ) then x = _x y = y + self:getHeight() else local g = face.glyph local gx = x + g.bitmap_left local gy = y + face.size.metrics.ascender / 64 - g.bitmap_top local width = g.bitmap.width local height = g.bitmap.rows local vertices = { -- vertex -- texcoord gx, gy + height, 0.0, 1.0, gx + width, gy + height, 1.0, 1.0, gx, gy, 0.0, 0.0, gx + width, gy + height, 1.0, 1.0, gx + width, gy, 1.0, 0.0, gx, gy, 0.0, 0.0 } local pVertices = ffi.new( "GLfloat[?]", #vertices, vertices ) local size = ffi.sizeof( pVertices ) GL.glBufferData( GL.GL_ARRAY_BUFFER, size, pVertices, GL.GL_STREAM_DRAW ) GL.glTexImage2D( GL.GL_TEXTURE_2D, 0, GL.GL_RED, g.bitmap.width, g.bitmap.rows, 0, GL.GL_RED, GL.GL_UNSIGNED_BYTE, g.bitmap.buffer ) framework.graphics.drawArrays( GL.GL_TRIANGLES, 0, #vertices / 4 ) x = x + ( g.advance.x / 64 ) y = y + ( g.advance.y / 64 ) end else error( "Could not load character '" .. char .. "'", 3 ) end end GL.glPixelStorei( GL.GL_UNPACK_ALIGNMENT, 4 ) end function font:__gc() GL.glDeleteTextures( 1, self.texture ) FT.FT_Done_Face( self.face[0] ) end
--=========== Copyright © 2018, Planimeter, All rights reserved. =============-- -- -- Purpose: -- --============================================================================-- require( "class" ) local FT = require( "freetype" ) local ffi = require( "ffi" ) local GL = require( "opengl" ) local ft = ffi.new( "FT_Library[1]" ) FT.FT_Init_FreeType( ft ) class( "framework.graphics.font" ) local font = framework.graphics.font function font:font( filename, size ) size = size or 16 self.face = ffi.new( "FT_Face[1]" ) self.buffer, self.length = framework.filesystem.read( filename ) if ( self.buffer == nil ) then FT.FT_Done_Face( self.face ) error( self.length, 3 ) end FT.FT_New_Memory_Face( ft[0], self.buffer, self.length, 0, self.face ) self.size = size size = size * framework.window.getPixelScale() FT.FT_Set_Pixel_Sizes( self.face[0], 0, size ) self.texture = ffi.new( "GLuint[1]" ) GL.glGenTextures( 1, self.texture ) GL.glBindTexture( GL.GL_TEXTURE_2D, self.texture[0] ) GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_BASE_LEVEL, 0 ) GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAX_LEVEL, 0 ) local o = GL.GL_ONE local r = GL.GL_RED local mask = ffi.new( "GLint[4]", o, o, o, r ) GL.glTexParameteriv( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_SWIZZLE_RGBA, mask ) local s = self.face[0].size.metrics; self.advance = bit.rshift( tonumber( s.max_advance ), 6 ) self.ascent = bit.rshift( tonumber( s.ascender ), 6 ) self.descent = bit.rshift( tonumber( s.descender ), 6 ) self.height = bit.rshift( tonumber( s.height ), 6 ) setproxy( self ) end function font:getWidth( text ) local width = 0 local face = self.face[0] for i = 1, #text do local char = string.sub( text, i, i ) if ( FT.FT_Load_Char( face, string.byte( char ), 4 ) == 0 ) then local g = face.glyph width = width + ( g.advance.x / 64 ) else error( "Could not load character '" .. char .. "'", 3 ) end end return tonumber( width ) end function font:getHeight() return math.floor( self.height / framework.window.getPixelScale() + 0.5 ) end function font:getWrap() -- TODO: Implement me. return 0, {} end function font:print( text, x, y, r, sx, sy, ox, oy, kx, ky ) local defaultVBO = framework.graphics._defaultVBO local shader = framework.graphics.getShader() local position = GL.glGetAttribLocation( shader, "position" ) local stride = 4 * ffi.sizeof( "GLfloat" ) local texcoord = GL.glGetAttribLocation( shader, "texcoord" ) local pointer = ffi.cast( "GLvoid *", 2 * ffi.sizeof( "GLfloat" ) ) GL.glBindBuffer( GL.GL_ARRAY_BUFFER, defaultVBO[0] ) GL.glVertexAttribPointer( position, 2, GL.GL_FLOAT, 0, stride, nil ) GL.glEnableVertexAttribArray( texcoord ) GL.glVertexAttribPointer( texcoord, 2, GL.GL_FLOAT, 0, stride, pointer ) framework.graphics.updateTransformations() GL.glBindTexture( GL.GL_TEXTURE_2D, self.texture[0] ) GL.glPixelStorei( GL.GL_UNPACK_ALIGNMENT, 1 ) local face = self.face[0] local _x = x for i = 1, #text do local char = string.sub( text, i, i ) if ( FT.FT_Load_Char( face, string.byte( char ), 4 ) == 0 ) then if ( char == "\n" ) then x = _x y = y + self:getHeight() else local g = face.glyph local gx = x + g.bitmap_left local gy = y + face.size.metrics.ascender / 64 - g.bitmap_top local width = g.bitmap.width local height = g.bitmap.rows local vertices = { -- vertex -- texcoord gx, gy + height, 0.0, 1.0, gx + width, gy + height, 1.0, 1.0, gx, gy, 0.0, 0.0, gx + width, gy + height, 1.0, 1.0, gx + width, gy, 1.0, 0.0, gx, gy, 0.0, 0.0 } local pVertices = ffi.new( "GLfloat[?]", #vertices, vertices ) local size = ffi.sizeof( pVertices ) GL.glBufferData( GL.GL_ARRAY_BUFFER, size, pVertices, GL.GL_STREAM_DRAW ) GL.glTexImage2D( GL.GL_TEXTURE_2D, 0, GL.GL_RED, g.bitmap.width, g.bitmap.rows, 0, GL.GL_RED, GL.GL_UNSIGNED_BYTE, g.bitmap.buffer ) framework.graphics.drawArrays( GL.GL_TRIANGLES, 0, #vertices / 4 ) x = x + ( g.advance.x / 64 ) y = y + ( g.advance.y / 64 ) end else error( "Could not load character '" .. char .. "'", 3 ) end end GL.glPixelStorei( GL.GL_UNPACK_ALIGNMENT, 4 ) end function font:__gc() GL.glDeleteTextures( 1, self.texture ) FT.FT_Done_Face( self.face[0] ) end
Fix `font:getWidth()` not using glyph advances
Fix `font:getWidth()` not using glyph advances
Lua
mit
Planimeter/lgameframework,Planimeter/lgameframework,Planimeter/lgameframework
ac2bc3c8fe4cc8b4070b0e2e0edba01c1373fa2a
src/extensions/cp/ui/StaticText.lua
src/extensions/cp/ui/StaticText.lua
--- === cp.ui.StaticText === --- --- Static Text Module. local require = require local timer = require("hs.timer") local Element = require("cp.ui.element") local notifier = require("cp.ui.notifier") local prop = require("cp.prop") local delayedTimer = timer.delayed local StaticText = Element:subclass("cp.ui.StaticText") --- cp.ui.StaticText.matches(element) -> boolean --- Function --- Checks if the element is a Static Text element. --- --- Parameters: --- * element - The `axuielement` to check. --- --- Returns: --- * If `true`, the element is a Static Text element. function StaticText.static.matches(element) return Element.matches(element) and element:attributeValue("AXRole") == "AXStaticText" end --- cp.ui.StaticText(parent, uiFinder[, convertFn]) -> StaticText --- Method --- Creates a new StaticText. They have a parent and a finder function. --- Additionally, an optional `convert` function can be provided, with the following signature: --- --- `function(textValue) -> anything` --- --- The `value` will be passed to the function before being returned, if present. All values --- passed into `value(x)` will be converted to a `string` first via `tostring`. --- --- For example, to have the value be converted into a `number`, simply use `tonumber` like this: --- --- ```lua --- local numberField = StaticText(parent, function() return ... end, tonumber) --- ``` --- --- Parameters: --- * parent - The parent object. --- * uiFinder - The function will return the `axuielement` for the StaticText. --- * convertFn - (optional) If provided, will be passed the `string` value when returning. --- --- Returns: --- * The new `StaticText`. function StaticText:initialize(parent, uiFinder, convertFn) Element.initialize(self, parent, uiFinder) self._convertFn = convertFn -- watch for changes in parent visibility, and update the notifier if it changes. if prop.is(parent.isShowing) then self.isShowing:monitor(parent.isShowing) self.isShowing:watch(function() self:notifier():update() end) end end --- cp.ui.StaticText.value <cp.prop: anything> --- Field --- The current value of the text field. function StaticText.lazy.prop:value() local value = self.UI:mutate( function(original) local ui = original() local value = ui and ui:attributeValue("AXValue") or nil if value and self._convertFn then value = self._convertFn(value) end return value end, function(value, original) local ui = original() if ui then value = tostring(value) local focused = ui:attributeValue("AXFocused") ui:setAttributeValue("AXFocused", true) ui:setAttributeValue("AXValue", value) ui:performAction("AXConfirm") ui:setAttributeValue("AXFocused", focused) end end ) ----------------------------------------------------------------------- -- Reduce the amount of AX notifications when timecode is updated: ----------------------------------------------------------------------- local timecodeUpdater timecodeUpdater = delayedTimer.new(0.001, function() value:update() end) -- wire up a notifier to watch for value changes. value:preWatch(function() self:notifier():watchFor("AXValueChanged", function() timecodeUpdater:start() end):start() end) return value end -- Deprecated: use the `value` property directly function StaticText:getValue() return self:value() end -- Deprecated: use the `value` property directly function StaticText:setValue(value) self.value:set(value) return self end --- cp.ui.StaticText:clear() -> self --- Method --- Clears the value of a Static Text box. --- --- Parameters: --- * None --- --- Returns: --- * Self function StaticText:clear() self.value:set("") return self end function StaticText.lazy.method:notifier() return notifier.new(self:app():bundleID(), self.UI) end --- cp.ui.StaticText:saveLayout() -> table --- Method --- Saves the current Static Text layout to a table. --- --- Parameters: --- * None --- --- Returns: --- * A table containing the current Static Text Layout. function StaticText:saveLayout() local layout = {} layout.value = self:getValue() return layout end --- cp.ui.StaticText:loadLayout(layout) -> none --- Method --- Loads a Static Text layout. --- --- Parameters: --- * layout - A table containing the Static Text layout settings - created using `cp.ui.StaticText:saveLayout()`. --- --- Returns: --- * None function StaticText:loadLayout(layout) if layout then self:setValue(layout.value) end end -- cp.ui.xxx:__call(parent, value) -> parent, string -- Method -- Allows the StaticText instance to be called as a function/method which will get/set the value. -- -- Parameters: -- * parent - (optional) The parent object. -- * value - The value you want to set the slider to. -- -- Returns: -- * The value of the Static Text box. function StaticText:__call(parent, value) if parent and parent ~= self:parent() then value = parent end return self:value(value) end return StaticText
--- === cp.ui.StaticText === --- --- Static Text Module. local require = require local timer = require "hs.timer" local Element = require "cp.ui.Element" local notifier = require "cp.ui.notifier" local prop = require "cp.prop" local delayedTimer = timer.delayed local StaticText = Element:subclass("cp.ui.StaticText") --- cp.ui.StaticText.matches(element) -> boolean --- Function --- Checks if the element is a Static Text element. --- --- Parameters: --- * element - The `axuielement` to check. --- --- Returns: --- * If `true`, the element is a Static Text element. function StaticText.static.matches(element) return Element.matches(element) and element:attributeValue("AXRole") == "AXStaticText" end --- cp.ui.StaticText(parent, uiFinder[, convertFn]) -> StaticText --- Method --- Creates a new StaticText. They have a parent and a finder function. --- Additionally, an optional `convert` function can be provided, with the following signature: --- --- `function(textValue) -> anything` --- --- The `value` will be passed to the function before being returned, if present. All values --- passed into `value(x)` will be converted to a `string` first via `tostring`. --- --- For example, to have the value be converted into a `number`, simply use `tonumber` like this: --- --- ```lua --- local numberField = StaticText(parent, function() return ... end, tonumber) --- ``` --- --- Parameters: --- * parent - The parent object. --- * uiFinder - The function will return the `axuielement` for the StaticText. --- * convertFn - (optional) If provided, will be passed the `string` value when returning. --- --- Returns: --- * The new `StaticText`. function StaticText:initialize(parent, uiFinder, convertFn) Element.initialize(self, parent, uiFinder) self._convertFn = convertFn -- watch for changes in parent visibility, and update the notifier if it changes. if prop.is(parent.isShowing) then self.isShowing:monitor(parent.isShowing) self.isShowing:watch(function() self:notifier():update() end) end end --- cp.ui.StaticText.value <cp.prop: anything> --- Field --- The current value of the text field. function StaticText.lazy.prop:value() local value = self.UI:mutate( function(original) local ui = original() local value = ui and ui:attributeValue("AXValue") or nil if value and self._convertFn then value = self._convertFn(value) end return value end, function(value, original) local ui = original() if ui then value = tostring(value) local focused = ui:attributeValue("AXFocused") ui:setAttributeValue("AXFocused", true) ui:setAttributeValue("AXValue", value) ui:performAction("AXConfirm") ui:setAttributeValue("AXFocused", focused) end end ) ----------------------------------------------------------------------- -- Reduce the amount of AX notifications when timecode is updated: ----------------------------------------------------------------------- local timecodeUpdater timecodeUpdater = delayedTimer.new(0.001, function() value:update() end) -- wire up a notifier to watch for value changes. value:preWatch(function() self:notifier():watchFor("AXValueChanged", function() timecodeUpdater:start() end):start() end) return value end -- Deprecated: use the `value` property directly function StaticText:getValue() return self:value() end -- Deprecated: use the `value` property directly function StaticText:setValue(value) self.value:set(value) return self end --- cp.ui.StaticText:clear() -> self --- Method --- Clears the value of a Static Text box. --- --- Parameters: --- * None --- --- Returns: --- * Self function StaticText:clear() self.value:set("") return self end function StaticText.lazy.method:notifier() return notifier.new(self:app():bundleID(), self.UI) end --- cp.ui.StaticText:saveLayout() -> table --- Method --- Saves the current Static Text layout to a table. --- --- Parameters: --- * None --- --- Returns: --- * A table containing the current Static Text Layout. function StaticText:saveLayout() local layout = {} layout.value = self:getValue() return layout end --- cp.ui.StaticText:loadLayout(layout) -> none --- Method --- Loads a Static Text layout. --- --- Parameters: --- * layout - A table containing the Static Text layout settings - created using `cp.ui.StaticText:saveLayout()`. --- --- Returns: --- * None function StaticText:loadLayout(layout) if layout then self:setValue(layout.value) end end -- cp.ui.xxx:__call(parent, value) -> parent, string -- Method -- Allows the StaticText instance to be called as a function/method which will get/set the value. -- -- Parameters: -- * parent - (optional) The parent object. -- * value - The value you want to set the slider to. -- -- Returns: -- * The value of the Static Text box. function StaticText:__call(parent, value) if parent and parent ~= self:parent() then value = parent end return self:value(value) end return StaticText
Bug Fix
Bug Fix - Fixed typo in `cp.ui.StaticText` which caused CommandPost to fail to load on case-sensitive file systems. - Closes #2006
Lua
mit
CommandPost/CommandPost,fcpxhacks/fcpxhacks,fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost
4a64d1ca11b090e529f44cedbf33f746710c80b4
pud/component/AttachmentComponent.lua
pud/component/AttachmentComponent.lua
local Class = require 'lib.hump.class' local ModelComponent = getClass 'pud.component.ModelComponent' local EntityArray = getClass 'pud.entity.EntityArray' local property = require 'pud.component.property' local message = require 'pud.component.message' -- AttachmentComponent -- local AttachmentComponent = Class{name='AttachmentComponent', inherits=ModelComponent, function(self, properties, family, max) max = max or 1 verify('number', max) verify('string', family) ModelComponent._addRequiredProperties(self, {'AttachedEntities'}) ModelComponent.construct(self, properties) self:_addMessages(message('ALL')) self._entities = EntityArray() self._max = max self._family = family end } -- destructor function AttachmentComponent:destroy() self._entities:destroy() self._entities = nil ModelComponent.destroy(self) end function AttachmentComponent:_setProperty(prop, data) prop = property(prop) if nil == data then data = property.default(prop) end if prop == property('AttachedEntities') then verify('table', data) else error('AttachmentComponent does not support property: %s', tostring(prop)) end ModelComponent._setProperty(self, prop, data) end function AttachmentComponent:receive(msg, ...) local continue = false if msg == message('ATTACHMENT_ATTACH') then self:_attach(...) continue = false elseif msg == message('ATTACHMENT_DETACH') then self:_detach(...) continue = false end if continue then for id in self._entities:iterate() do local entity = EntityRegistry:get(id) entity:send(msg, ...) end end end function AttachmentComponent:_attach(...) local num = select('#', ...) if num > 0 then local msg = message('ATTACHMENT_ATTACHED') local size = self._entities:size() local max = self._max - size local loop = max > num and num or max for i=1,loop do local id = select(i, ...) local entity = EntityRegistry:get(id) local efamily = entity:getFamily() if efamily == self._family then if self._entities:add(id) then entity:send(msg, self) end end end end end function AttachmentComponent:_remove(...) local num = select('#', ...) if num > 0 then local msg = message('ATTACHMENT_DETACHED') for i=1,num do local id = select(i, ...) if self._entities:remove(id) then local entity = EntityRegistry:get(id) entity:send(msg, self) end end end end function AttachmentComponent:getProperty(p, intermediate, ...) if p == property('AttachedEntities') then local entities = intermediate or {} local num = #entities for id in self._entities:iterate() do num = num + 1 entities[num] = id end return entities else return ModelComponent.getProperty(self, p, intermediate, ...) end end -- the class return AttachmentComponent
local Class = require 'lib.hump.class' local ModelComponent = getClass 'pud.component.ModelComponent' local EntityArray = getClass 'pud.entity.EntityArray' local property = require 'pud.component.property' local message = require 'pud.component.message' -- AttachmentComponent -- local AttachmentComponent = Class{name='AttachmentComponent', inherits=ModelComponent, function(self, properties, family, max) max = max or 1 verify('number', max) verify('string', family) ModelComponent._addRequiredProperties(self, {'AttachedEntities'}) ModelComponent.construct(self, properties) self:_addMessages(message('ALL')) self._entities = EntityArray() self._max = max self._family = family end } -- destructor function AttachmentComponent:destroy() self._entities:destroy() self._entities = nil ModelComponent.destroy(self) end function AttachmentComponent:_setProperty(prop, data) prop = property(prop) if nil == data then data = property.default(prop) end if prop == property('AttachedEntities') then verify('table', data) else error('AttachmentComponent does not support property: %s', tostring(prop)) end ModelComponent._setProperty(self, prop, data) end function AttachmentComponent:receive(msg, ...) local continue = false if msg == message('ATTACHMENT_ATTACH') then self:_attach(...) continue = false elseif msg == message('ATTACHMENT_DETACH') then self:_detach(...) continue = false end if continue then for id in self._entities:iterate() do local entity = EntityRegistry:get(id) entity:send(msg, ...) end end end function AttachmentComponent:_attach(...) local num = select('#', ...) if num > 0 then local msg = message('ATTACHMENT_ATTACHED') local size = self._entities:size() local max = self._max - size local loop = max > num and num or max for i=1,loop do local id = select(i, ...) local entity = EntityRegistry:get(id) local efamily = entity:getFamily() if efamily == self._family then if self._entities:add(id) then entity:send(msg, self) end end end end end function AttachmentComponent:_remove(...) local num = select('#', ...) if num > 0 then local msg = message('ATTACHMENT_DETACHED') for i=1,num do local id = select(i, ...) if self._entities:remove(id) then local entity = EntityRegistry:get(id) entity:send(msg, self) end end end end function AttachmentComponent:getProperty(p, intermediate, ...) if p == property('AttachedEntities') then if self._entities:size() == 0 then return intermediate end local entities = intermediate or {} local num = #entities for id in self._entities:iterate() do num = num + 1 entities[num] = id end return entities else return ModelComponent.getProperty(self, p, intermediate, ...) end end -- the class return AttachmentComponent
fix getProperty to not return empty table when empty
fix getProperty to not return empty table when empty
Lua
mit
scottcs/wyx
d7abdc92283842fe36e2f20df333825441ca15c4
qtlua/packages/qttorch/init.lua
qtlua/packages/qttorch/init.lua
require 'qt' require 'torch' require 'libqttorch' qt.QImage.fromTensor = function(tensor, scale) return tensor.qttorch.QImageFromTensor(tensor, scale) end qt.QImage.toTensor = function(self, tensor, scale) if type(tensor) == 'userdata' then return tensor.qttorch.QImageToTensor(self, tensor, scale) else error('tensor expected') end end
require 'qt' require 'torch' require 'libqttorch' qt.QImage.fromTensor = function(tensor, scale) return tensor.qttorch.QImageFromTensor(tensor, scale) end qt.QImage.toTensor = function(self, tensor, scale) if type(tensor) == 'userdata' then return tensor.qttorch.QImageToTensor(self, tensor, scale) else local t = torch.getmetatable(torch.getdefaulttensortype()) return t.qttorch.QImageToTensor(self, tensor, scale) end end
Little fix to allow QImage.toTensor to create tensors on the fly.
Little fix to allow QImage.toTensor to create tensors on the fly.
Lua
bsd-3-clause
soumith/TH,soumith/TH,soumith/TH,soumith/TH
f1fe86fd766b3b5dd17a0e2e0221d0e7f00a768b
vim/plugin/setup.lua
vim/plugin/setup.lua
-- vim.lsp.set_log_level("debug") local lspconfig = require "lspconfig" local lsp_spinner = require "lsp_spinner" lsp_spinner.setup { placeholder = " ", } require("lsp-inlayhints").setup() local function on_attach(client, bufnr) require("lsp_spinner").on_attach(client, bufnr) require("lsp-inlayhints").on_attach(client, bufnr) end vim.lsp.handlers["textDocument/publishDiagnostics"] = vim.lsp.with(vim.lsp.diagnostic.on_publish_diagnostics, { virtual_text = { prefix = "", spacing = 2, }, }) local capabilities = vim.lsp.protocol.make_client_capabilities() capabilities.textDocument.completion.completionItem.snippetSupport = true capabilities.textDocument.completion.completionItem.resolveSupport = { properties = { "documentation", "detail", "additionalTextEdits", }, } lsp_spinner.init_capabilities(capabilities) local nvim_lsp = require "lspconfig" local servers = { "bashls", "clangd", "cmake", "gopls", "graphql", "pyright", "rust_analyzer", "terraformls", "zls", } for _, lsp in ipairs(servers) do nvim_lsp[lsp].setup { capabilities = capabilities, on_attach = on_attach, } end require("lspconfig").sourcekit.setup { capabilities = capabilities, filetypes = { "swift" }, on_attach = on_attach, } require("lsp_signature").on_attach { bind = true, hint_prefix = "", -- TODO: the border is huge, but these don't seem to work -- handler_opts = { -- border = "single" -- }, } require("compe").setup { enabled = true, autocomplete = true, debug = false, min_length = 1, preselect = "enable", throttle_time = 80, source_timeout = 200, incomplete_delay = 400, max_abbr_width = 100, max_kind_width = 100, max_menu_width = 100, documentation = true, source = { path = true, buffer = { ignored_filetypes = { "gitconfig", "gitcommit", "gitrebase", "git" }, }, nvim_lsp = true, nvim_lua = true, }, } function has_highlights(lang) local supported = { c = true, cpp = true, } return supported[lang] ~= nil end require("nvim-treesitter.configs").setup { ensure_installed = "all", ignore_install = { "phpdoc", -- https://github.com/nvim-treesitter/nvim-treesitter/issues/2837 "zig", -- https://github.com/nvim-treesitter/nvim-treesitter/issues/2049 }, highlight = { enable = true, additional_vim_regex_highlighting = false, is_supported = has_highlights, }, textsubjects = { enable = true, keymaps = { ["."] = "textsubjects-smart", }, }, textobjects = { select = { enable = true, keymaps = { ["af"] = "@function.outer", ["if"] = "@function.inner", ["ic"] = "@call.outer", }, }, lsp_interop = { enable = true, peek_definition_code = { ["df"] = "@function.outer", ["dF"] = "@class.outer", }, }, }, }
-- vim.lsp.set_log_level("debug") local lspconfig = require "lspconfig" local lsp_spinner = require "lsp_spinner" lsp_spinner.setup { placeholder = " ", } require("lsp-inlayhints").setup() local function on_attach(client, bufnr) require("lsp_spinner").on_attach(client, bufnr) require("lsp-inlayhints").on_attach(client, bufnr) end vim.lsp.handlers["textDocument/publishDiagnostics"] = vim.lsp.with(vim.lsp.diagnostic.on_publish_diagnostics, { virtual_text = { prefix = "", spacing = 2, }, }) local capabilities = vim.lsp.protocol.make_client_capabilities() capabilities.textDocument.completion.completionItem.snippetSupport = true capabilities.textDocument.completion.completionItem.resolveSupport = { properties = { "documentation", "detail", "additionalTextEdits", }, } lsp_spinner.init_capabilities(capabilities) local nvim_lsp = require "lspconfig" local servers = { "bashls", "clangd", "cmake", "gopls", "graphql", "rust_analyzer", "terraformls", "zls", } for _, lsp in ipairs(servers) do nvim_lsp[lsp].setup { capabilities = capabilities, on_attach = on_attach, } end -- https://github.com/microsoft/pyright/issues/128 require("lspconfig").pyright.setup { capabilities = capabilities, filetypes = { "python" }, on_attach = on_attach, settings = { python = { analysis = { -- autoSearchPaths = true, -- useLibraryCodeForTypes = true, diagnosticMode = "openFilesOnly", }, }, }, } require("lspconfig").sourcekit.setup { capabilities = capabilities, filetypes = { "swift" }, on_attach = on_attach, } require("lsp_signature").on_attach { bind = true, hint_prefix = "", -- TODO: the border is huge, but these don't seem to work -- handler_opts = { -- border = "single" -- }, } require("compe").setup { enabled = true, autocomplete = true, debug = false, min_length = 1, preselect = "enable", throttle_time = 80, source_timeout = 200, incomplete_delay = 400, max_abbr_width = 100, max_kind_width = 100, max_menu_width = 100, documentation = true, source = { path = true, buffer = { ignored_filetypes = { "gitconfig", "gitcommit", "gitrebase", "git" }, }, nvim_lsp = true, nvim_lua = true, }, } function has_highlights(lang) local supported = { c = true, cpp = true, } return supported[lang] ~= nil end require("nvim-treesitter.configs").setup { ensure_installed = "all", ignore_install = { "phpdoc", -- https://github.com/nvim-treesitter/nvim-treesitter/issues/2837 "zig", -- https://github.com/nvim-treesitter/nvim-treesitter/issues/2049 }, highlight = { enable = true, additional_vim_regex_highlighting = false, is_supported = has_highlights, }, textsubjects = { enable = true, keymaps = { ["."] = "textsubjects-smart", }, }, textobjects = { select = { enable = true, keymaps = { ["af"] = "@function.outer", ["if"] = "@function.inner", ["ic"] = "@call.outer", }, }, lsp_interop = { enable = true, peek_definition_code = { ["df"] = "@function.outer", ["dF"] = "@class.outer", }, }, }, }
[nvim] Manually configure pyright
[nvim] Manually configure pyright I think this fixes a CPU issue I had where pyright would consume 100% CPU forever even when I didn't have any python files open, but I'm not entirely sure.
Lua
mit
keith/dotfiles,keith/dotfiles,keith/dotfiles,keith/dotfiles,keith/dotfiles,keith/dotfiles
d83135627d0cf3bebd7802565c76a812b37e8407
Engine/coreg.lua
Engine/coreg.lua
--Corouting Registry: this file is responsible for providing LIKO12 it's api-- local coreg = {reg={}} --Returns the current active coroutine if exists function coreg:getCoroutine() return self.co end --Sets the current active coroutine function coreg:setCoroutine(co) self.co = co return self end local function extractArgs(args,factor) local nargs = {} for k,v in ipairs(args) do if k > factor then table.insert(nargs,v) end end return nargs end --Resumes the current active coroutine if exists. function coreg:resumeCoroutine(...) if not self.co or coroutine.status(self.co) == "dead" then return end local args = {coroutine.resume(self.co,...)} if not args[1] then error(args[2]) end --Should have a better error handelling if not args[2] then --if self.co:status() == "dead" then error("done") return end --OS finished ?? --self:resumeCoroutine() self.co = nil return end args = {self:trigger(args[2],unpack(extractArgs(args,2)))} if not args[1] then self:resumeCoroutine(args[1],unpack(extractArgs(args,1))) end if not(type(args[1]) == "number" and args[1] == 2) then self:resumeCoroutine(true,unpack(extractArgs(args,1))) end end function coreg:sandboxCoroutine(f) 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, getfenv=getfenv, setfenv=setfenv, 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=love.math.random, --Replaced with love.math versions randomseed=love.math.setRandomSeed, sin=math.sin, sinh=math.sinh, sqrt=math.sqrt, tan=math.tan, tanh=math.tanh, noise = love.math.noise --LOVE releated apis }, coroutine={ resume = coroutine.resume, yield = coroutine.yield, status = coroutine.status }, os={ time=os.time, clock=os.clock } } GLOB.loadstring = function(...) local chunk, err = loadstring(...) if not chunk then return nil, err end setfenv(chunk,GLOB) return chunk end GLOB.coroutine.create = function(...) local co,err = pcall(coroutine.create,...) if not co then return error(err) end setfenv(co,GLOB) return co end GLOB._G=GLOB --Mirror Mirror setfenv(f,GLOB) end --Register a value to a specific key. --If the value is a table, then the values in the table will be registered at key:tableValueKey --If the value is a function, then it will be called instantly, and it must return true as the first argument to tell that it ran successfully. --Else, the value will be returned to the liko12 code. function coreg:register(value,key) local key = key or "none" if type(value) == "table" then for k,v in pairs(value) do self.reg[key..":"..k] = v end end self.reg[key] = value end --Trigger a value in a key. --If the value is a function, then it will call it instant. --Else, it will return the value. --Notice that the first return value is a number of "did it ran successfully", if false, the second return value is the error message. --Also the first return value could be also a number that specifies how should the coroutine resume (true boolean defaults to 1) --Corouting resumming codes: 1: resume instantly, 2: stop resuming (Will be yeild later, like when love.update is called). function coreg:trigger(key,...) local key = key or "none" if type(self.reg[key]) == "nil" then return false, "error, key not found !" end if type(self.reg[key]) == "function" then return self.reg[key](...) else return true, self.reg[key] end end --Returns the value registered in a specific key. --Returns: value then the given key. function coreg:get(key) local key = key or "none" return self.reg[key], key end --Returns a table containing the list of the registered keys. --list[key] = type function coreg:index() local list = {} for k,v in pairs(self.reg) do list[k] = type(v) end return list end --Returns a clone of the registry table. function coreg:registry() local reg = {} for k,v in pairs(self.reg) do reg[k] = v end return reg end return coreg
--Corouting Registry: this file is responsible for providing LIKO12 it's api-- local coreg = {reg={}} --Returns the current active coroutine if exists function coreg:getCoroutine() return self.co, self.coglob end --Sets the current active coroutine function coreg:setCoroutine(co,glob) self.co = co self.coglob = glob return self end local function extractArgs(args,factor) local nargs = {} for k,v in ipairs(args) do if k > factor then table.insert(nargs,v) end end return nargs end --Resumes the current active coroutine if exists. function coreg:resumeCoroutine(...) if not self.co or coroutine.status(self.co) == "dead" then return end local args = {coroutine.resume(self.co,...)} if not args[1] then error(args[2]) end --Should have a better error handelling if not args[2] then --if self.co:status() == "dead" then error("done") return end --OS finished ?? --self:resumeCoroutine() self.co = nil return end args = {self:trigger(args[2],unpack(extractArgs(args,2)))} if not args[1] then self:resumeCoroutine(args[1],unpack(extractArgs(args,1))) end if not(type(args[1]) == "number" and args[1] == 2) then self:resumeCoroutine(true,unpack(extractArgs(args,1))) end end function coreg:sandbox(f) if self.co and self.coglob then setfenv(f,self.coglob) return end 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, getfenv=getfenv, setfenv=setfenv, 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=love.math.random, --Replaced with love.math versions randomseed=love.math.setRandomSeed, sin=math.sin, sinh=math.sinh, sqrt=math.sqrt, tan=math.tan, tanh=math.tanh, noise = love.math.noise --LOVE releated apis }, coroutine={ resume = coroutine.resume, yield = coroutine.yield, status = coroutine.status }, os={ time=os.time, clock=os.clock } } GLOB.loadstring = function(...) local chunk, err = loadstring(...) if not chunk then return nil, err end setfenv(chunk,GLOB) return chunk end GLOB.coroutine.create = function(...) local co,err = pcall(coroutine.create,...) if not co then return error(err) end setfenv(co,GLOB) return co end GLOB._G=GLOB --Mirror Mirror setfenv(f,GLOB) return GLOB end --Register a value to a specific key. --If the value is a table, then the values in the table will be registered at key:tableValueKey --If the value is a function, then it will be called instantly, and it must return true as the first argument to tell that it ran successfully. --Else, the value will be returned to the liko12 code. function coreg:register(value,key) local key = key or "none" if type(value) == "table" then for k,v in pairs(value) do self.reg[key..":"..k] = v end end self.reg[key] = value end --Trigger a value in a key. --If the value is a function, then it will call it instant. --Else, it will return the value. --Notice that the first return value is a number of "did it ran successfully", if false, the second return value is the error message. --Also the first return value could be also a number that specifies how should the coroutine resume (true boolean defaults to 1) --Corouting resumming codes: 1: resume instantly, 2: stop resuming (Will be yeild later, like when love.update is called). function coreg:trigger(key,...) local key = key or "none" if type(self.reg[key]) == "nil" then return false, "error, key not found !" end if type(self.reg[key]) == "function" then return self.reg[key](...) else return true, self.reg[key] end end --Returns the value registered in a specific key. --Returns: value then the given key. function coreg:get(key) local key = key or "none" return self.reg[key], key end --Returns a table containing the list of the registered keys. --list[key] = type function coreg:index() local list = {} for k,v in pairs(self.reg) do list[k] = type(v) end return list end --Returns a clone of the registry table. function coreg:registry() local reg = {} for k,v in pairs(self.reg) do reg[k] = v end return reg end return coreg
Bugfixes
Bugfixes
Lua
mit
RamiLego4Game/LIKO-12
2f9cec7d502fcfcdfee3eb165961721d3e83143d
mods/BeardLib-Editor/Hooks/Fixes.lua
mods/BeardLib-Editor/Hooks/Fixes.lua
if not Global.editor_mode then return end local F = table.remove(RequiredScript:split("/")) local UnitIds = Idstring("unit") local civ = F == "elementspawncivilian" if civ or F == "elementspawnenemydummy" then local C = civ and ElementSpawnCivilian or ElementSpawnEnemyDummy --Makes sure unit path is updated. Hooks:PostHook(C, "_finalize_values", "EditorFinalizeValues", function(self) self._enemy_name = self._values.enemy and Idstring(self._values.enemy) or nil if not self._enemy_name then if civ then self._enemy_name = Idstring("units/characters/civilians/dummy_civilian_1/dummy_civilian_1") else self._enemy_name = Idstring("units/payday2/characters/ene_swat_1/ene_swat_1") end end end) --Makes sure element doesn't crash in editor. local orig = C.produce function C:produce(params, ...) local enemy = self._enemy_name or self:value("enemy") if (not params or not params.name) and (not enemy or not PackageManager:has(UnitIds, enemy:id())) then return end return orig(self, params, ...) end end
if not Global.editor_mode then return end local F = table.remove(RequiredScript:split("/")) local UnitIds = Idstring("unit") local civ = F == "elementspawncivilian" if civ or F == "elementspawnenemydummy" then local C = civ and ElementSpawnCivilian or ElementSpawnEnemyDummy --Makes sure unit path is updated. Hooks:PostHook(C, "_finalize_values", "EditorFinalizeValues", function(self) if self._values.enemy then self._enemy_name = self._values.enemy and Idstring(self._values.enemy) or nil end if not self._enemy_name then if civ then self._enemy_name = Idstring("units/characters/civilians/dummy_civilian_1/dummy_civilian_1") else self._enemy_name = Idstring("units/payday2/characters/ene_swat_1/ene_swat_1") end end end) --Makes sure element doesn't crash in editor. local orig = C.produce function C:produce(params, ...) local enemy = self._enemy_name or self:value("enemy") if (not params or not params.name) and (not enemy or not PackageManager:has(UnitIds, enemy:id())) then return end return orig(self, params, ...) end end
Fixed #210
Fixed #210
Lua
mit
simon-wh/PAYDAY-2-BeardLib-Editor
df9c883bd00348e2556d90ce5b894e0b8caa460a
lua/autorun/mediaplayer.lua
lua/autorun/mediaplayer.lua
local basepath = "mediaplayer/" local function IncludeMP( filepath ) include( basepath .. filepath ) end local function LoadMediaPlayer() print( "Loading 'mediaplayer' addon..." ) -- Check if MediaPlayer has already been loaded if MediaPlayer then MediaPlayer.__refresh = true end -- shared includes IncludeCS "includes/extensions/sh_file.lua" IncludeCS "includes/extensions/sh_math.lua" IncludeCS "includes/extensions/sh_table.lua" IncludeCS "includes/extensions/sh_url.lua" IncludeCS "includes/modules/EventEmitter.lua" if SERVER then -- download clientside includes AddCSLuaFile "includes/modules/browserpool.lua" AddCSLuaFile "includes/modules/control.lua" AddCSLuaFile "includes/modules/htmlmaterial.lua" AddCSLuaFile "includes/modules/spritesheet.lua" AddCSLuaFile "includes/extensions/cl_draw.lua" -- initialize serverside mediaplayer IncludeMP "init.lua" else -- clientside includes include "includes/modules/browserpool.lua" include "includes/modules/control.lua" include "includes/modules/htmlmaterial.lua" include "includes/modules/spritesheet.lua" include "includes/extensions/cl_draw.lua" -- initialize clientside mediaplayer IncludeMP "cl_init.lua" end -- Sandbox includes; these must always be included as the gamemode is still -- set as 'base' when the addon is loading. Can't check if gamemode derives -- Sandbox. IncludeCS "menubar/mp_options.lua" include "properties/mediaplayer.lua" -- -- Media Player menu includes; remove these if you would rather not include -- the sidebar menu. -- if SERVER then AddCSLuaFile "mp_menu/cl_init.lua" include "mp_menu/init.lua" else include "mp_menu/cl_init.lua" end if SERVER then -- Reinstall media players on Lua refresh for _, mp in pairs(MediaPlayer.GetAll()) do if mp:GetType() == 'entity' and IsValid(mp) then local ent = mp:GetEntity() local listeners = table.Copy(mp:GetListeners()) -- remove media player mp:Remove() -- install new media player ent:InstallMediaPlayer() -- reinitialize settings mp = ent._mp -- TODO: implement memento pattern for reloading MP state. -- reapply listeners mp:SetListeners( listeners ) mp:BroadcastUpdate() end end end end -- First time load LoadMediaPlayer()
local basepath = "mediaplayer/" local function IncludeMP( filepath ) include( basepath .. filepath ) end local function LoadMediaPlayer() print( "Loading 'mediaplayer' addon..." ) -- Check if MediaPlayer has already been loaded if MediaPlayer then MediaPlayer.__refresh = true -- HACK: Lua refresh fix; access local variable of baseclass lib local _, BaseClassTable = debug.getupvalue(baseclass.Get, 1) for classname, _ in pairs(BaseClassTable) do if classname:find("mp_") then BaseClassTable[classname] = nil end end end -- shared includes IncludeCS "includes/extensions/sh_file.lua" IncludeCS "includes/extensions/sh_math.lua" IncludeCS "includes/extensions/sh_table.lua" IncludeCS "includes/extensions/sh_url.lua" IncludeCS "includes/modules/EventEmitter.lua" if SERVER then -- download clientside includes AddCSLuaFile "includes/modules/browserpool.lua" AddCSLuaFile "includes/modules/control.lua" AddCSLuaFile "includes/modules/htmlmaterial.lua" AddCSLuaFile "includes/modules/spritesheet.lua" AddCSLuaFile "includes/extensions/cl_draw.lua" -- initialize serverside mediaplayer IncludeMP "init.lua" else -- clientside includes include "includes/modules/browserpool.lua" include "includes/modules/control.lua" include "includes/modules/htmlmaterial.lua" include "includes/modules/spritesheet.lua" include "includes/extensions/cl_draw.lua" -- initialize clientside mediaplayer IncludeMP "cl_init.lua" end -- Sandbox includes; these must always be included as the gamemode is still -- set as 'base' when the addon is loading. Can't check if gamemode derives -- Sandbox. IncludeCS "menubar/mp_options.lua" include "properties/mediaplayer.lua" -- -- Media Player menu includes; remove these if you would rather not include -- the sidebar menu. -- if SERVER then AddCSLuaFile "mp_menu/cl_init.lua" include "mp_menu/init.lua" else include "mp_menu/cl_init.lua" end if SERVER then -- Reinstall media players on Lua refresh for _, mp in pairs(MediaPlayer.GetAll()) do if mp:GetType() == 'entity' and IsValid(mp) then local ent = mp:GetEntity() local listeners = table.Copy(mp:GetListeners()) -- remove media player mp:Remove() -- install new media player ent:InstallMediaPlayer() -- reinitialize settings mp = ent._mp -- TODO: implement memento pattern for reloading MP state. -- reapply listeners mp:SetListeners( listeners ) mp:BroadcastUpdate() end end end end -- First time load LoadMediaPlayer()
Readded baseclass Lua refresh fix to the mediaplayer loader.
Readded baseclass Lua refresh fix to the mediaplayer loader.
Lua
mit
pixeltailgames/gm-mediaplayer,pixeltailgames/gm-mediaplayer
11a7b884345c5b0ab2278255674e70c458ca9c77
mods/dye/init.lua
mods/dye/init.lua
-- minetest/dye/init.lua -- To make recipes that will work with any dye ever made by anybody, define -- them based on groups. -- You can select any group of groups, based on your need for amount of colors. -- basecolor: 9, excolor: 17, unicolor: 89 -- -- Example of one shapeless recipe using a color group: -- Note: As this uses basecolor_*, you'd need 9 of these. -- minetest.register_craft({ -- type = "shapeless", -- output = '<mod>:item_yellow', -- recipe = {'<mod>:item_no_color', 'group:basecolor_yellow'}, -- }) -- Other mods can use these for looping through available colors local dye = {} dye.basecolors = {"white", "grey", "black", "red", "yellow", "green", "cyan", "blue", "magenta"} dye.excolors = {"white", "lightgrey", "grey", "darkgrey", "black", "red", "orange", "yellow", "lime", "green", "aqua", "cyan", "sky_blue", "blue", "violet", "magenta", "red_violet"} -- Base color groups: -- - basecolor_white -- - basecolor_grey -- - basecolor_black -- - basecolor_red -- - basecolor_yellow -- - basecolor_green -- - basecolor_cyan -- - basecolor_blue -- - basecolor_magenta -- Extended color groups (* = equal to a base color): -- * excolor_white -- - excolor_lightgrey -- * excolor_grey -- - excolor_darkgrey -- * excolor_black -- * excolor_red -- - excolor_orange -- * excolor_yellow -- - excolor_lime -- * excolor_green -- - excolor_aqua -- * excolor_cyan -- - excolor_sky_blue -- * excolor_blue -- - excolor_violet -- * excolor_magenta -- - excolor_red_violet -- The whole unifieddyes palette as groups: -- - unicolor_<excolor> -- For the following, no white/grey/black is allowed: -- - unicolor_medium_<excolor> -- - unicolor_dark_<excolor> -- - unicolor_light_<excolor> -- - unicolor_<excolor>_s50 -- - unicolor_medium_<excolor>_s50 -- - unicolor_dark_<excolor>_s50 -- Local stuff local dyelocal = {} -- This collection of colors is partly a historic thing, partly something else. dyelocal.dyes = { {"white", "White dye", {dye=1, basecolor_white=1, excolor_white=1, unicolor_white=1}}, {"grey", "Grey dye", {dye=1, basecolor_grey=1, excolor_grey=1, unicolor_grey=1}}, {"dark_grey", "Dark grey dye", {dye=1, basecolor_grey=1, excolor_darkgrey=1, unicolor_darkgrey=1}}, {"black", "Black dye", {dye=1, basecolor_black=1, excolor_black=1, unicolor_black=1}}, {"violet", "Violet dye", {dye=1, basecolor_magenta=1, excolor_violet=1, unicolor_violet=1}}, {"blue", "Blue dye", {dye=1, basecolor_blue=1, excolor_blue=1, unicolor_blue=1}}, {"cyan", "Cyan dye", {dye=1, basecolor_cyan=1, excolor_cyan=1, unicolor_cyan=1}}, {"dark_green", "Dark green dye",{dye=1, basecolor_green=1, excolor_green=1, unicolor_dark_green=1}}, {"green", "Green dye", {dye=1, basecolor_green=1, excolor_green=1, unicolor_green=1}}, {"yellow", "Yellow dye", {dye=1, basecolor_yellow=1, excolor_yellow=1, unicolor_yellow=1}}, {"brown", "Brown dye", {dye=1, basecolor_brown=1, excolor_orange=1, unicolor_dark_orange=1}}, {"orange", "Orange dye", {dye=1, basecolor_orange=1, excolor_orange=1, unicolor_orange=1}}, {"red", "Red dye", {dye=1, basecolor_red=1, excolor_red=1, unicolor_red=1}}, {"magenta", "Magenta dye", {dye=1, basecolor_magenta=1, excolor_red_violet=1,unicolor_red_violet=1}}, {"pink", "Pink dye", {dye=1, basecolor_red=1, excolor_red=1, unicolor_light_red=1}}, } -- Define items for _, row in ipairs(dyelocal.dyes) do local name = row[1] local description = row[2] local groups = row[3] local item_name = "dye:"..name local item_image = "dye_"..name..".png" minetest.register_craftitem(item_name, { inventory_image = item_image, description = description, groups = groups }) minetest.register_craft({ type = "shapeless", output = item_name.." 4", recipe = {"group:flower,color_"..name}, }) end -- manually add coal->black dye minetest.register_craft({ type = "shapeless", output = "dye:black 4", recipe = {"group:coal"}, }) -- Mix recipes -- Just mix everything to everything somehow sanely dyelocal.mixbases = {"magenta", "red", "orange", "brown", "yellow", "green", "dark_green", "cyan", "blue", "violet", "black", "dark_grey", "grey", "white"} dyelocal.mixes = { -- magenta, red, orange, brown, yellow, green, dark_green, cyan, blue, violet, black, dark_grey, grey, white white = {"pink", "pink", "orange", "orange", "yellow", "green", "green", "grey", "cyan", "violet", "grey", "grey", "white", "white"}, grey = {"pink", "pink", "orange", "orange", "yellow", "green", "green", "grey", "cyan", "pink", "dark_grey","grey", "grey"}, dark_grey={"brown","brown", "brown", "brown", "brown","dark_green","dark_green","blue","blue","violet","black", "black"}, black = {"black", "black", "black", "black", "black", "black", "black", "black", "black", "black", "black"}, violet= {"magenta","magenta","red", "brown", "red", "cyan", "brown", "blue", "violet","violet"}, blue = {"violet", "magenta","brown","brown","dark_green","cyan","cyan", "cyan", "blue"}, cyan = {"blue","brown","dark_green","dark_grey","green","cyan","dark_green","cyan"}, dark_green={"brown","brown","brown", "brown", "green", "green", "dark_green"}, green = {"brown", "yellow","yellow","dark_green","green","green"}, yellow= {"red", "orange", "yellow","orange", "yellow"}, brown = {"brown", "brown","orange", "brown"}, orange= {"red", "orange","orange"}, red = {"magenta","red"}, magenta={"magenta"}, } for one,results in pairs(dyelocal.mixes) do for i,result in ipairs(results) do local another = dyelocal.mixbases[i] minetest.register_craft({ type = "shapeless", output = 'dye:'..result..' 2', recipe = {'dye:'..one, 'dye:'..another}, }) end end -- Hide dyelocal dyelocal = nil -- EOF
-- minetest/dye/init.lua -- To make recipes that will work with any dye ever made by anybody, define -- them based on groups. -- You can select any group of groups, based on your need for amount of colors. -- basecolor: 9, excolor: 17, unicolor: 89 -- -- Example of one shapeless recipe using a color group: -- Note: As this uses basecolor_*, you'd need 9 of these. -- minetest.register_craft({ -- type = "shapeless", -- output = '<mod>:item_yellow', -- recipe = {'<mod>:item_no_color', 'group:basecolor_yellow'}, -- }) -- Other mods can use these for looping through available colors dye = {} dye.basecolors = {"white", "grey", "black", "red", "yellow", "green", "cyan", "blue", "magenta"} dye.excolors = {"white", "lightgrey", "grey", "darkgrey", "black", "red", "orange", "yellow", "lime", "green", "aqua", "cyan", "sky_blue", "blue", "violet", "magenta", "red_violet"} -- Base color groups: -- - basecolor_white -- - basecolor_grey -- - basecolor_black -- - basecolor_red -- - basecolor_yellow -- - basecolor_green -- - basecolor_cyan -- - basecolor_blue -- - basecolor_magenta -- Extended color groups (* = equal to a base color): -- * excolor_white -- - excolor_lightgrey -- * excolor_grey -- - excolor_darkgrey -- * excolor_black -- * excolor_red -- - excolor_orange -- * excolor_yellow -- - excolor_lime -- * excolor_green -- - excolor_aqua -- * excolor_cyan -- - excolor_sky_blue -- * excolor_blue -- - excolor_violet -- * excolor_magenta -- - excolor_red_violet -- The whole unifieddyes palette as groups: -- - unicolor_<excolor> -- For the following, no white/grey/black is allowed: -- - unicolor_medium_<excolor> -- - unicolor_dark_<excolor> -- - unicolor_light_<excolor> -- - unicolor_<excolor>_s50 -- - unicolor_medium_<excolor>_s50 -- - unicolor_dark_<excolor>_s50 -- Local stuff local dyelocal = {} -- This collection of colors is partly a historic thing, partly something else. dyelocal.dyes = { {"white", "White dye", {dye=1, basecolor_white=1, excolor_white=1, unicolor_white=1}}, {"grey", "Grey dye", {dye=1, basecolor_grey=1, excolor_grey=1, unicolor_grey=1}}, {"dark_grey", "Dark grey dye", {dye=1, basecolor_grey=1, excolor_darkgrey=1, unicolor_darkgrey=1}}, {"black", "Black dye", {dye=1, basecolor_black=1, excolor_black=1, unicolor_black=1}}, {"violet", "Violet dye", {dye=1, basecolor_magenta=1, excolor_violet=1, unicolor_violet=1}}, {"blue", "Blue dye", {dye=1, basecolor_blue=1, excolor_blue=1, unicolor_blue=1}}, {"cyan", "Cyan dye", {dye=1, basecolor_cyan=1, excolor_cyan=1, unicolor_cyan=1}}, {"dark_green", "Dark green dye",{dye=1, basecolor_green=1, excolor_green=1, unicolor_dark_green=1}}, {"green", "Green dye", {dye=1, basecolor_green=1, excolor_green=1, unicolor_green=1}}, {"yellow", "Yellow dye", {dye=1, basecolor_yellow=1, excolor_yellow=1, unicolor_yellow=1}}, {"brown", "Brown dye", {dye=1, basecolor_brown=1, excolor_orange=1, unicolor_dark_orange=1}}, {"orange", "Orange dye", {dye=1, basecolor_orange=1, excolor_orange=1, unicolor_orange=1}}, {"red", "Red dye", {dye=1, basecolor_red=1, excolor_red=1, unicolor_red=1}}, {"magenta", "Magenta dye", {dye=1, basecolor_magenta=1, excolor_red_violet=1,unicolor_red_violet=1}}, {"pink", "Pink dye", {dye=1, basecolor_red=1, excolor_red=1, unicolor_light_red=1}}, } -- Define items for _, row in ipairs(dyelocal.dyes) do local name = row[1] local description = row[2] local groups = row[3] local item_name = "dye:"..name local item_image = "dye_"..name..".png" minetest.register_craftitem(item_name, { inventory_image = item_image, description = description, groups = groups }) minetest.register_craft({ type = "shapeless", output = item_name.." 4", recipe = {"group:flower,color_"..name}, }) end -- manually add coal->black dye minetest.register_craft({ type = "shapeless", output = "dye:black 4", recipe = {"group:coal"}, }) -- Mix recipes -- Just mix everything to everything somehow sanely dyelocal.mixbases = {"magenta", "red", "orange", "brown", "yellow", "green", "dark_green", "cyan", "blue", "violet", "black", "dark_grey", "grey", "white"} dyelocal.mixes = { -- magenta, red, orange, brown, yellow, green, dark_green, cyan, blue, violet, black, dark_grey, grey, white white = {"pink", "pink", "orange", "orange", "yellow", "green", "green", "grey", "cyan", "violet", "grey", "grey", "white", "white"}, grey = {"pink", "pink", "orange", "orange", "yellow", "green", "green", "grey", "cyan", "pink", "dark_grey","grey", "grey"}, dark_grey={"brown","brown", "brown", "brown", "brown","dark_green","dark_green","blue","blue","violet","black", "black"}, black = {"black", "black", "black", "black", "black", "black", "black", "black", "black", "black", "black"}, violet= {"magenta","magenta","red", "brown", "red", "cyan", "brown", "blue", "violet","violet"}, blue = {"violet", "magenta","brown","brown","dark_green","cyan","cyan", "cyan", "blue"}, cyan = {"blue","brown","dark_green","dark_grey","green","cyan","dark_green","cyan"}, dark_green={"brown","brown","brown", "brown", "green", "green", "dark_green"}, green = {"brown", "yellow","yellow","dark_green","green","green"}, yellow= {"red", "orange", "yellow","orange", "yellow"}, brown = {"brown", "brown","orange", "brown"}, orange= {"red", "orange","orange"}, red = {"magenta","red"}, magenta={"magenta"}, } for one,results in pairs(dyelocal.mixes) do for i,result in ipairs(results) do local another = dyelocal.mixbases[i] minetest.register_craft({ type = "shapeless", output = 'dye:'..result..' 2', recipe = {'dye:'..one, 'dye:'..another}, }) end end
Fix visibility of global/local dye tables
Fix visibility of global/local dye tables
Lua
lgpl-2.1
evrooije/beerarchy,evrooije/beerarchy,evrooije/beerarchy
f0520cd46c7e413e2ca991fa3c979b3addac449c
deployment_scripts/puppet/modules/lma_collector/files/plugins/common/lma_utils.lua
deployment_scripts/puppet/modules/lma_collector/files/plugins/common/lma_utils.lua
-- Copyright 2015 Mirantis, Inc. -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. local cjson = require 'cjson' local string = require 'string' local extra = require 'extra_fields' local patt = require 'patterns' local pairs = pairs local inject_message = inject_message local inject_payload = inject_payload local read_message = read_message local pcall = pcall local M = {} setfenv(1, M) -- Remove external access to contain everything in the module severity_to_label_map = { [0] = 'EMERGENCY', [1] = 'ALERT', [2] = 'CRITICAL', [3] = 'ERROR', [4] = 'WARNING', [5] = 'NOTICE', [6] = 'INFO', [7] = 'DEBUG', } label_to_severity_map = { EMERGENCY = 0, ALERT = 1, CRITICAL = 2, ERROR = 3, WARNING = 4, NOTICE = 5, INFO= 6, DEBUG = 7, } metric_type = { COUNTER = "counter", GAUGE = "gauge", DERIVE = "derive", } local default_severity = 7 local bulk_datapoints = {} -- Add a datapoint to the bulk metric message function add_to_bulk_metric(name, value, tags) bulk_datapoints[#bulk_datapoints+1] = { name = name, value = value, tags = tags or {}, } end -- Send the bulk metric message to the Heka pipeline function inject_bulk_metric(ts, hostname, source) if #bulk_datapoints == 0 then return end local payload = safe_json_encode(bulk_datapoints) if not payload then return end local msg = { Hostname = hostname, Timestamp = ts, Payload = payload, Type = 'bulk_metric', -- prepended with 'heka.sandbox' Severity = label_to_severity_map.INFO, Fields = { hostname = hostname, source = source } } -- reset the local table storing the datapoints bulk_datapoints = {} inject_tags(msg) safe_inject_message(msg) end -- Encode a Lua variable as JSON without raising an exception if the encoding -- fails for some reason (for instance, the encoded buffer exceeds the sandbox -- limit) function safe_json_encode(v) local ok, data = pcall(cjson.encode, v) if not ok then return end return data end -- Call inject_payload() wrapped by pcall() function safe_inject_payload(payload_type, payload_name, data) local ok, err_msg = pcall(inject_payload, payload_type, payload_name, data) if not ok then return -1, err_msg else return 0 end end -- Call inject_message() wrapped by pcall() function safe_inject_message(msg) local ok, err_msg = pcall(inject_message, msg) if not ok then return -1, err_msg else return 0 end end -- Parse a Syslog-based payload and update the Heka message -- Return true if successful, false otherwise function parse_syslog_message(grammar, payload, msg) -- capture everything after the first backslash because syslog_grammar will -- drop it local extra_msg = string.match(payload, '^[^\n]+\n(.+)\n$') local fields = grammar:match(payload) if not fields then return false end msg.Timestamp = fields.timestamp fields.timestamp = nil msg.Hostname = fields.hostname fields.hostname = nil msg.Pid = fields.syslogtag.pid or 0 fields.programname = fields.syslogtag.programname fields.syslogtag = nil if fields.pri then msg.Severity = fields.pri.severity fields.syslogfacility = fields.pri.facility fields.pri = nil else msg.Severity = fields.syslogseverity or fields["syslogseverity-text"] or fields.syslogpriority or fields["syslogpriority-text"] or default_severity fields.syslogseverity = nil fields["syslogseverity-text"] = nil fields.syslogpriority = nil fields["syslogpriority-text"] = nil end fields.severity_label = severity_to_label_map[msg.Severity] if extra_msg ~= nil then msg.Payload = fields.msg .. "\n" .. extra_msg else msg.Payload = fields.msg end fields.msg = nil msg.Fields = fields inject_tags(msg) return true end -- Inject tags into the Heka message function inject_tags(msg) for k,v in pairs(extra.tags) do if msg.Fields[k] == nil then msg.Fields[k] = v end end end -- Convert a datetime string to the RFC3339 format -- it supports a variety of datetime formats. -- Return the string unmodified if the datetime couldn't be parsed function format_datetime (raw_datetime) local datetime local t = patt.TimestampTable:match(raw_datetime) if t then local frac = 0 local offset_sign = '+' local offset_hour = 0 local offset_min = 0 if t.sec_frac then frac = t.sec_frac end if t.offset_sign then offset_sign = t.offset_sign end if t.offset_hour then offset_hour = t.offset_hour end if t.offset_min then offset_min = t.offset_min end datetime = string.format("%04d-%02d-%02dT%02d:%02d:%02d.%06d%s%02d:%02d", t.year, t.month, t.day, t.hour, t.min, t.sec, frac*1e6, offset_sign, offset_hour, offset_min) end return datetime end function chomp(s) return string.gsub(s, "\n$", "") end function truncate(str, max_length, delimiter) if string.len(str) <= max_length then return str end local pos = 1 while true do local next_pos1, next_pos2 = string.find(str, delimiter, pos) if not next_pos1 or next_pos1 - 1 > max_length then pos = pos - string.len(delimiter) - 1 if pos < 1 then pos = max_length end break end pos = next_pos2 + 1 end return string.sub(str, 1, pos) end return M
-- Copyright 2015 Mirantis, Inc. -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. local cjson = require 'cjson' local string = require 'string' local extra = require 'extra_fields' local patt = require 'patterns' local pairs = pairs local inject_message = inject_message local inject_payload = inject_payload local read_message = read_message local pcall = pcall local M = {} setfenv(1, M) -- Remove external access to contain everything in the module severity_to_label_map = { [0] = 'EMERGENCY', [1] = 'ALERT', [2] = 'CRITICAL', [3] = 'ERROR', [4] = 'WARNING', [5] = 'NOTICE', [6] = 'INFO', [7] = 'DEBUG', } label_to_severity_map = { EMERGENCY = 0, ALERT = 1, CRITICAL = 2, ERROR = 3, WARNING = 4, NOTICE = 5, INFO= 6, DEBUG = 7, } metric_type = { COUNTER = "counter", GAUGE = "gauge", DERIVE = "derive", } local default_severity = 7 local bulk_datapoints = {} -- Add a datapoint to the bulk metric message function add_to_bulk_metric(name, value, tags) bulk_datapoints[#bulk_datapoints+1] = { name = name, value = value, tags = tags or {}, } end -- Send the bulk metric message to the Heka pipeline function inject_bulk_metric(ts, hostname, source) if #bulk_datapoints == 0 then return end local payload = safe_json_encode(bulk_datapoints) if not payload then -- Reset the table otherwise it may grow infinitely and the sandbox -- will eventually be killed by Heka. -- See https://bugs.launchpad.net/lma-toolchain/+bug/1545743 bulk_datapoints = {} return end local msg = { Hostname = hostname, Timestamp = ts, Payload = payload, Type = 'bulk_metric', -- prepended with 'heka.sandbox' Severity = label_to_severity_map.INFO, Fields = { hostname = hostname, source = source } } -- reset the local table storing the datapoints bulk_datapoints = {} inject_tags(msg) safe_inject_message(msg) end -- Encode a Lua variable as JSON without raising an exception if the encoding -- fails for some reason (for instance, the encoded buffer exceeds the sandbox -- limit) function safe_json_encode(v) local ok, data = pcall(cjson.encode, v) if not ok then return end return data end -- Call inject_payload() wrapped by pcall() function safe_inject_payload(payload_type, payload_name, data) local ok, err_msg = pcall(inject_payload, payload_type, payload_name, data) if not ok then return -1, err_msg else return 0 end end -- Call inject_message() wrapped by pcall() function safe_inject_message(msg) local ok, err_msg = pcall(inject_message, msg) if not ok then return -1, err_msg else return 0 end end -- Parse a Syslog-based payload and update the Heka message -- Return true if successful, false otherwise function parse_syslog_message(grammar, payload, msg) -- capture everything after the first backslash because syslog_grammar will -- drop it local extra_msg = string.match(payload, '^[^\n]+\n(.+)\n$') local fields = grammar:match(payload) if not fields then return false end msg.Timestamp = fields.timestamp fields.timestamp = nil msg.Hostname = fields.hostname fields.hostname = nil msg.Pid = fields.syslogtag.pid or 0 fields.programname = fields.syslogtag.programname fields.syslogtag = nil if fields.pri then msg.Severity = fields.pri.severity fields.syslogfacility = fields.pri.facility fields.pri = nil else msg.Severity = fields.syslogseverity or fields["syslogseverity-text"] or fields.syslogpriority or fields["syslogpriority-text"] or default_severity fields.syslogseverity = nil fields["syslogseverity-text"] = nil fields.syslogpriority = nil fields["syslogpriority-text"] = nil end fields.severity_label = severity_to_label_map[msg.Severity] if extra_msg ~= nil then msg.Payload = fields.msg .. "\n" .. extra_msg else msg.Payload = fields.msg end fields.msg = nil msg.Fields = fields inject_tags(msg) return true end -- Inject tags into the Heka message function inject_tags(msg) for k,v in pairs(extra.tags) do if msg.Fields[k] == nil then msg.Fields[k] = v end end end -- Convert a datetime string to the RFC3339 format -- it supports a variety of datetime formats. -- Return the string unmodified if the datetime couldn't be parsed function format_datetime (raw_datetime) local datetime local t = patt.TimestampTable:match(raw_datetime) if t then local frac = 0 local offset_sign = '+' local offset_hour = 0 local offset_min = 0 if t.sec_frac then frac = t.sec_frac end if t.offset_sign then offset_sign = t.offset_sign end if t.offset_hour then offset_hour = t.offset_hour end if t.offset_min then offset_min = t.offset_min end datetime = string.format("%04d-%02d-%02dT%02d:%02d:%02d.%06d%s%02d:%02d", t.year, t.month, t.day, t.hour, t.min, t.sec, frac*1e6, offset_sign, offset_hour, offset_min) end return datetime end function chomp(s) return string.gsub(s, "\n$", "") end function truncate(str, max_length, delimiter) if string.len(str) <= max_length then return str end local pos = 1 while true do local next_pos1, next_pos2 = string.find(str, delimiter, pos) if not next_pos1 or next_pos1 - 1 > max_length then pos = pos - string.len(delimiter) - 1 if pos < 1 then pos = max_length end break end pos = next_pos2 + 1 end return string.sub(str, 1, pos) end return M
Fix the OOM of heka monitoring filter
Fix the OOM of heka monitoring filter This change resets the table that holds data for the heka monitoring filter. Otherwise the table may grow infinitely and the sandbox will eventually be killed by Heka. Change-Id: If8c07944e42700d913831b500466b33831a41482 Partial-Bug: #1545743
Lua
apache-2.0
stackforge/fuel-plugin-lma-collector,stackforge/fuel-plugin-lma-collector,stackforge/fuel-plugin-lma-collector,stackforge/fuel-plugin-lma-collector,stackforge/fuel-plugin-lma-collector
0156744164f4aab43d8e3562855874626fcddd91
game/scripts/vscripts/util/playerresource.lua
game/scripts/vscripts/util/playerresource.lua
function CDOTA_PlayerResource:SetPlayerStat(PlayerID, key, value) local pd = PLAYER_DATA[PlayerID] if not pd.HeroStats then pd.HeroStats = {} end pd.HeroStats[key] = value end function CDOTA_PlayerResource:GetPlayerStat(PlayerID, key) local pd = PLAYER_DATA[PlayerID] return pd.HeroStats == nil and 0 or (pd.HeroStats[key] or 0) end function CDOTA_PlayerResource:ModifyPlayerStat(PlayerID, key, value) local v = PlayerResource:GetPlayerStat(PlayerID, key) + value PlayerResource:SetPlayerStat(PlayerID, key, v) return v end function CDOTA_PlayerResource:SetPlayerTeam(playerId, newTeam) local oldTeam = PlayerResource:GetTeam(playerId) local player = PlayerResource:GetPlayer(playerId) local hero = PlayerResource:GetSelectedHeroEntity(playerId) PlayerTables:RemovePlayerSubscription("dynamic_minimap_points_" .. oldTeam, playerId) local playerPickData = {} local tableData = PlayerTables:GetTableValue("hero_selection", oldTeam) if tableData and tableData[playerId] then table.merge(playerPickData, tableData[playerId]) tableData[playerId] = nil PlayerTables:SetTableValue("hero_selection", oldTeam, tableData) end for _,v in ipairs(FindAllOwnedUnits(player)) do v:SetTeam(newTeam) end player:SetTeam(newTeam) PlayerResource:UpdateTeamSlot(playerId, newTeam, 1) PlayerResource:SetCustomTeamAssignment(playerId, newTeam) local newTableData = PlayerTables:GetTableValue("hero_selection", newTeam) if newTableData and playerPickData then newTableData[playerId] = playerPickData PlayerTables:SetTableValue("hero_selection", newTeam, newTableData) end --[[for _, v in ipairs(Entities:FindAllByClassname("npc_dota_courier") ) do v:SetControllableByPlayer(playerId, v:GetTeamNumber() == newTeam) end]] --FindCourier(oldTeam):SetControllableByPlayer(playerId, false) local targetCour = FindCourier(newTeam) if IsValidEntity(targetCour) then targetCour:SetControllableByPlayer(playerId, true) end PlayerTables:RemovePlayerSubscription("dynamic_minimap_points_" .. oldTeam, playerId) PlayerTables:AddPlayerSubscription("dynamic_minimap_points_" .. newTeam, playerId) for i = 0, hero:GetAbilityCount() - 1 do local skill = hero:GetAbilityByIndex(i) if skill then --print(skill.GetIntrinsicModifierName and skill:GetIntrinsicModifierName()) if ( skill.GetIntrinsicModifierName and skill:GetIntrinsicModifierName() and skill:GetAbilityName() ~= "meepo_divided_we_stand" ) then RecreateAbility(hero, skill) end end end CustomGameEventManager:Send_ServerToPlayer(player, "arena_team_changed_update", {}) Teams:RecalculateKillWeight(oldTeam) Teams:RecalculateKillWeight(newTeam) end function CDOTA_PlayerResource:SetDisableHelpForPlayerID(nPlayerID, nOtherPlayerID, disabled) if nPlayerID == nOtherPlayerID then return end -- TODO: Add all other share masks PlayerResource:SetUnitShareMaskForPlayer(nPlayerID, nOtherPlayerID, 4, disabled) local disable_help_data = PlayerTables:GetTableValue("disable_help_data", nPlayerID) disable_help_data[nOtherPlayerID] = PLAYER_DATA[nPlayerID][nOtherPlayerID] PlayerTables:SetTableValue("disable_help_data", disable_help_data) end -- Unused function CDOTA_PlayerResource:IsDisableHelpSetForPlayerID(nPlayerID, nOtherPlayerID) return ( PlayerResource:GetTeam(nPlayerID) == PlayerResource:GetTeam(nOtherPlayerID) and bit.band(PlayerResource:GetUnitShareMaskForPlayer(nPlayerID, nOtherPlayerID), 4) == 4 ) end function CDOTA_PlayerResource:KickPlayer(nPlayerID) local usid = PLAYER_DATA[nPlayerID].UserID if usid then SendToServerConsole("kickid " .. usid) return true end return false end function CDOTA_PlayerResource:IsPlayerAbandoned(playerId) return PLAYER_DATA[playerId].IsAbandoned == true end function CDOTA_PlayerResource:IsBanned(playerId) return PLAYER_DATA[playerId].isBanned == true end function CDOTA_PlayerResource:MakePlayerAbandoned(playerId) if PlayerResource:IsPlayerAbandoned(playerId) then return end PlayerResource:RemoveAllUnits(playerId) local heroname = HeroSelection:GetSelectedHeroName(playerId) --local notLinked = true if heroname then Notifications:TopToAll({hero=heroname, duration=10}) Notifications:TopToAll({text=PlayerResource:GetPlayerName(playerId), continue=true, style={color=ColorTableToCss(PLAYER_DATA[playerId].Color or {0, 0, 0})}}) Notifications:TopToAll({text="#game_player_abandoned_game", continue=true}) for _,v in ipairs(HeroSelection:GetLinkedHeroNames(heroname)) do local linkedHeroOwner = HeroSelection:GetSelectedHeroPlayer(v) if linkedHeroOwner then HeroSelection:ForceChangePlayerHeroMenu(linkedHeroOwner) end end end --if notLinked then HeroSelection:UpdateStatusForPlayer(playerId, "hover", "npc_dota_hero_abaddon") --end PLAYER_DATA[playerId].IsAbandoned = true PlayerTables:SetTableValue("players_abandoned", playerId, true) Teams:RecalculateKillWeight(PlayerResource:GetTeam(playerId)) if not GameRules:IsCheatMode() then local teamLeft = GetOneRemainingTeam() if teamLeft then Timers:CreateTimer(30, function() local teamLeft = GetOneRemainingTeam() if teamLeft then GameMode:OnOneTeamLeft(teamLeft) end end) end end Duel:EndIfFinished() end function CDOTA_PlayerResource:RemoveAllUnits(playerId) RemoveAllOwnedUnits(playerId) local hero = PlayerResource:GetSelectedHeroEntity(playerId) if not IsValidEntity(hero) then return end hero:ClearNetworkableEntityInfo() hero:Stop() for i = 0, hero:GetAbilityCount() - 1 do local ability = hero:GetAbilityByIndex(i) if ability then if ability:GetKeyValue("NoAbandonCleanup") ~= 1 then ability:SetLevel(0) end ability:SetHidden(true) ability:SetActivated(false) --UTIL_Remove(ability) end end hero:InterruptMotionControllers(false) hero:DestroyAllModifiers() hero:AddNewModifier(hero, nil, "modifier_hero_out_of_game", nil) end function CDOTA_PlayerResource:GetRealSteamID(PlayerID) local id = tostring(PlayerResource:GetSteamID(PlayerID)) return id == "0" and tostring(PlayerID) or id end
function CDOTA_PlayerResource:SetPlayerStat(PlayerID, key, value) local pd = PLAYER_DATA[PlayerID] if not pd.HeroStats then pd.HeroStats = {} end pd.HeroStats[key] = value end function CDOTA_PlayerResource:GetPlayerStat(PlayerID, key) local pd = PLAYER_DATA[PlayerID] return pd.HeroStats == nil and 0 or (pd.HeroStats[key] or 0) end function CDOTA_PlayerResource:ModifyPlayerStat(PlayerID, key, value) local v = PlayerResource:GetPlayerStat(PlayerID, key) + value PlayerResource:SetPlayerStat(PlayerID, key, v) return v end function CDOTA_PlayerResource:SetPlayerTeam(playerId, newTeam) local oldTeam = PlayerResource:GetTeam(playerId) local player = PlayerResource:GetPlayer(playerId) local hero = PlayerResource:GetSelectedHeroEntity(playerId) PlayerTables:RemovePlayerSubscription("dynamic_minimap_points_" .. oldTeam, playerId) local playerPickData = {} local tableData = PlayerTables:GetTableValue("hero_selection", oldTeam) if tableData and tableData[playerId] then table.merge(playerPickData, tableData[playerId]) tableData[playerId] = nil PlayerTables:SetTableValue("hero_selection", oldTeam, tableData) end GameRules:SetCustomGameTeamMaxPlayers(newTeam, GameRules:GetCustomGameTeamMaxPlayers(newTeam) + 1) for _,v in ipairs(FindAllOwnedUnits(player)) do v:SetTeam(newTeam) end PlayerResource:UpdateTeamSlot(playerId, newTeam, 1) PlayerResource:SetCustomTeamAssignment(playerId, newTeam) GameRules:SetCustomGameTeamMaxPlayers(oldTeam, GameRules:GetCustomGameTeamMaxPlayers(oldTeam) - 1) local newTableData = PlayerTables:GetTableValue("hero_selection", newTeam) if newTableData and playerPickData then newTableData[playerId] = playerPickData PlayerTables:SetTableValue("hero_selection", newTeam, newTableData) end --[[for _, v in ipairs(Entities:FindAllByClassname("npc_dota_courier") ) do v:SetControllableByPlayer(playerId, v:GetTeamNumber() == newTeam) end]] --FindCourier(oldTeam):SetControllableByPlayer(playerId, false) local targetCour = FindCourier(newTeam) if IsValidEntity(targetCour) then targetCour:SetControllableByPlayer(playerId, true) end PlayerTables:RemovePlayerSubscription("dynamic_minimap_points_" .. oldTeam, playerId) PlayerTables:AddPlayerSubscription("dynamic_minimap_points_" .. newTeam, playerId) for i = 0, hero:GetAbilityCount() - 1 do local skill = hero:GetAbilityByIndex(i) if skill then --print(skill.GetIntrinsicModifierName and skill:GetIntrinsicModifierName()) if ( skill.GetIntrinsicModifierName and skill:GetIntrinsicModifierName() and skill:GetAbilityName() ~= "meepo_divided_we_stand" ) then RecreateAbility(hero, skill) end end end CustomGameEventManager:Send_ServerToPlayer(player, "arena_team_changed_update", {}) Teams:RecalculateKillWeight(oldTeam) Teams:RecalculateKillWeight(newTeam) end function CDOTA_PlayerResource:SetDisableHelpForPlayerID(nPlayerID, nOtherPlayerID, disabled) if nPlayerID == nOtherPlayerID then return end -- TODO: Add all other share masks PlayerResource:SetUnitShareMaskForPlayer(nPlayerID, nOtherPlayerID, 4, disabled) local disable_help_data = PlayerTables:GetTableValue("disable_help_data", nPlayerID) disable_help_data[nOtherPlayerID] = PLAYER_DATA[nPlayerID][nOtherPlayerID] PlayerTables:SetTableValue("disable_help_data", disable_help_data) end -- Unused function CDOTA_PlayerResource:IsDisableHelpSetForPlayerID(nPlayerID, nOtherPlayerID) return ( PlayerResource:GetTeam(nPlayerID) == PlayerResource:GetTeam(nOtherPlayerID) and bit.band(PlayerResource:GetUnitShareMaskForPlayer(nPlayerID, nOtherPlayerID), 4) == 4 ) end function CDOTA_PlayerResource:KickPlayer(nPlayerID) local usid = PLAYER_DATA[nPlayerID].UserID if usid then SendToServerConsole("kickid " .. usid) return true end return false end function CDOTA_PlayerResource:IsPlayerAbandoned(playerId) return PLAYER_DATA[playerId].IsAbandoned == true end function CDOTA_PlayerResource:IsBanned(playerId) return PLAYER_DATA[playerId].isBanned == true end function CDOTA_PlayerResource:MakePlayerAbandoned(playerId) if PlayerResource:IsPlayerAbandoned(playerId) then return end PlayerResource:RemoveAllUnits(playerId) local heroname = HeroSelection:GetSelectedHeroName(playerId) --local notLinked = true if heroname then Notifications:TopToAll({hero=heroname, duration=10}) Notifications:TopToAll({text=PlayerResource:GetPlayerName(playerId), continue=true, style={color=ColorTableToCss(PLAYER_DATA[playerId].Color or {0, 0, 0})}}) Notifications:TopToAll({text="#game_player_abandoned_game", continue=true}) for _,v in ipairs(HeroSelection:GetLinkedHeroNames(heroname)) do local linkedHeroOwner = HeroSelection:GetSelectedHeroPlayer(v) if linkedHeroOwner then HeroSelection:ForceChangePlayerHeroMenu(linkedHeroOwner) end end end --if notLinked then HeroSelection:UpdateStatusForPlayer(playerId, "hover", "npc_dota_hero_abaddon") --end PLAYER_DATA[playerId].IsAbandoned = true PlayerTables:SetTableValue("players_abandoned", playerId, true) Teams:RecalculateKillWeight(PlayerResource:GetTeam(playerId)) if not GameRules:IsCheatMode() then local teamLeft = GetOneRemainingTeam() if teamLeft then Timers:CreateTimer(30, function() local teamLeft = GetOneRemainingTeam() if teamLeft then GameMode:OnOneTeamLeft(teamLeft) end end) end end Duel:EndIfFinished() end function CDOTA_PlayerResource:RemoveAllUnits(playerId) RemoveAllOwnedUnits(playerId) local hero = PlayerResource:GetSelectedHeroEntity(playerId) if not IsValidEntity(hero) then return end hero:ClearNetworkableEntityInfo() hero:Stop() for i = 0, hero:GetAbilityCount() - 1 do local ability = hero:GetAbilityByIndex(i) if ability then if ability:GetKeyValue("NoAbandonCleanup") ~= 1 then ability:SetLevel(0) end ability:SetHidden(true) ability:SetActivated(false) --UTIL_Remove(ability) end end hero:InterruptMotionControllers(false) hero:DestroyAllModifiers() hero:AddNewModifier(hero, nil, "modifier_hero_out_of_game", nil) end function CDOTA_PlayerResource:GetRealSteamID(PlayerID) local id = tostring(PlayerResource:GetSteamID(PlayerID)) return id == "0" and tostring(PlayerID) or id end
fix(utils): SetPlayerTeam not extends team slots
fix(utils): SetPlayerTeam not extends team slots
Lua
mit
ark120202/aabs
7b33b1154b77ed7e573a6e23ded6526845e8a23c
src_trunk/resources/social-system/s_friends.lua
src_trunk/resources/social-system/s_friends.lua
-- //////////////////////////////////// -- // MYSQL // -- //////////////////////////////////// sqlUsername = exports.mysql:getMySQLUsername() sqlPassword = exports.mysql:getMySQLPassword() sqlDB = exports.mysql:getMySQLDBName() sqlHost = exports.mysql:getMySQLHost() sqlPort = exports.mysql:getMySQLPort() handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort) function checkMySQL() if not (mysql_ping(handler)) then handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort) end end setTimer(checkMySQL, 300000, 0) function closeMySQL() if (handler) then mysql_close(handler) end end addEventHandler("onResourceStop", getResourceRootElement(getThisResource()), closeMySQL) -- //////////////////////////////////// -- // MYSQL END // -- //////////////////////////////////// ----------------------[KEY BINDS]-------------------- function bindKeys() local players = exports.pool:getPoolElementsByType("player") for k, arrayPlayer in ipairs(players) do setElementData(arrayPlayer, "friends.visible", 0) --if not(isKeyBound(arrayPlayer, "o", "down", toggleFriends)) then -- bindKey(arrayPlayer, "o", "down", toggleFriends) --end --if not(isKeyBound(arrayPlayer, "m", "down", toggleCursor)) then -- bindKey(arrayPlayer, "m", "down", toggleCursor) --end end end function bindKeysOnJoin() bindKey(source, "o", "down", toggleFriends) --bindKey(source, "m", "down", toggleCursor) setElementData(source, "friends.visible", 0) end addEventHandler("onResourceStart", getRootElement(), bindKeys) addEventHandler("onPlayerJoin", getRootElement(), bindKeysOnJoin) -- function togles the cursor for the player function toggleCursor(source) if(isCursorShowing(source)) then showCursor(source, false) else showCursor(source, true) end end function toggleFriends(source) local logged = getElementData(source, "gameaccountloggedin") if (logged==1) then local visible = getElementData(source, "friends.visible") if (visible==0) then -- not already showing local accid = tonumber(getElementData(source, "gameaccountid")) local result = mysql_query(handler, "SELECT friends, friendsmessage FROM accounts WHERE id='" .. accid .. "' LIMIT 1") if (result) then local sfriends = mysql_result(result, 1, 1) local fmessage = mysql_result(result, 1, 2) if (tostring(sfriends)==tostring(mysql_null())) then sfriends = "" end if (tostring(fmessage)==tostring(mysql_null())) then fmessage = "" end local friends = { } local count = 1 for i=1, 100 do local fid = gettok(sfriends, i, 59) if (fid) then local fresult = mysql_query(handler, "SELECT username, friendsmessage, yearday, year, country, os FROM accounts WHERE id='" .. fid .. "' LIMIT 1") local aresult = mysql_query(handler, "SELECT id FROM achievements WHERE account='" .. fid .. "'") local numachievements = mysql_num_rows(aresult) mysql_free_result(aresult) friends[i] = { } friends[i][1] = tonumber(fid) -- USER ID friends[i][2] = mysql_result(fresult, 1, 1) -- USERNAME friends[i][3] = mysql_result(fresult, 1, 2) -- MESSAGE friends[i][4] = mysql_result(fresult, 1, 5) -- COUNTRY friends[i][7] = tostring(mysql_result(fresult, 1, 6)) -- OPERATING SYSTEM friends[i][8] = tostring(numachievements) -- NUM ACHIEVEMENTS -- Last online local time = getRealTime() local days = time.monthday local months = (time.month+1) local years = (1900+time.year) local yearday = time.yearday local fyearday = tonumber(mysql_result(fresult, 1, 3)) -- YEAR DAY local fyear = tonumber(mysql_result(fresult, 1, 4)) -- YEAR local found, player = false for key, value in ipairs(exports.pool:getPoolElementsByType("player")) do if (tonumber(getElementData(value, "gameaccountid"))==friends[i][1]) then found = true player = value end end if (found) then friends[i][5] = "Online" friends[i][6] = getPlayerName(player) elseif (years~=fyear) then friends[i][5] = "Last Seen: Last Year" elseif (yearday==fyearday) then friends[i][5] = "Last Seen: Today" else local diff = yearday - fyearday friends[i][5] = "Last Seen: " .. tostring(diff) .. " days ago." end mysql_free_result(fresult) else break end end mysql_free_result(result) setElementData(source, "friends.visible", 1) triggerClientEvent(source, "showFriendsList", source, friends) else outputChatBox("Error 600000 - Could not retrieve friends list.", source, 255, 0, 0) end end end end addEvent("sendFriends", false) addEventHandler("sendFriends", getRootElement(), toggleFriends) function updateFriendsMessage(message) local safemessage = mysql_escape_string(handler, tostring(message)) local accid = getElementData(source, "gameaccountid") local query = mysql_query(handler, "UPDATE accounts SET friendsmessage='" .. safemessage .. "' WHERE id='" .. accid .. "'") if (query) then setElementData(source, "friends.visible", 0) setElementData(source, "friends.message", tostring(safemessage)) mysql_free_result(query) toggleFriends(source) else outputChatBox("Error updating friends message - ensure you used no special characters!", source, 255, 0, 0) end end addEvent("updateFriendsMessage", true) addEventHandler("updateFriendsMessage", getRootElement(), updateFriendsMessage) function removeFriend(id, username, dontShowFriends) local accid = tonumber(getElementData(source, "gameaccountid")) local result = mysql_query(handler, "SELECT friends, friendsmessage FROM accounts WHERE id='" .. accid .. "' LIMIT 1") if (result) then local sfriends = mysql_result(result, 1, 1) local fmessage = mysql_result(result, 1, 2) local friendstring = "" local count = 1 for i=1, 100 do local fid = gettok(sfriends, i, 59) if (fid) then if not (tonumber(fid)==id) then friendstring = friendstring .. fid .. ";" end end end mysql_query(handler, "UPDATE accounts SET friends='" .. friendstring .. "' WHERE id='" .. accid .. "'") mysql_free_result(result) outputChatBox("You removed '" .. username .. "' from your friends list.", source, 255, 194, 14) setElementData(source, "friends.visible", 0) if (dontShowFriends==false) then toggleFriends(source) end end end addEvent("removeFriend", true) addEventHandler("removeFriend", getRootElement(), removeFriend)
-- //////////////////////////////////// -- // MYSQL // -- //////////////////////////////////// sqlUsername = exports.mysql:getMySQLUsername() sqlPassword = exports.mysql:getMySQLPassword() sqlDB = exports.mysql:getMySQLDBName() sqlHost = exports.mysql:getMySQLHost() sqlPort = exports.mysql:getMySQLPort() handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort) function checkMySQL() if not (mysql_ping(handler)) then handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort) end end setTimer(checkMySQL, 300000, 0) function closeMySQL() if (handler) then mysql_close(handler) end end addEventHandler("onResourceStop", getResourceRootElement(getThisResource()), closeMySQL) -- //////////////////////////////////// -- // MYSQL END // -- //////////////////////////////////// ----------------------[KEY BINDS]-------------------- function bindKeys() local players = exports.pool:getPoolElementsByType("player") for k, arrayPlayer in ipairs(players) do setElementData(arrayPlayer, "friends.visible", 0) if not(isKeyBound(arrayPlayer, "o", "down", toggleFriends)) then bindKey(arrayPlayer, "o", "down", toggleFriends) end end end function bindKeysOnJoin() bindKey(source, "o", "down", toggleFriends) setElementData(source, "friends.visible", 0) end addEventHandler("onResourceStart", getRootElement(), bindKeys) addEventHandler("onPlayerJoin", getRootElement(), bindKeysOnJoin) function toggleFriends(source) local logged = getElementData(source, "gameaccountloggedin") if (logged==1) then local visible = getElementData(source, "friends.visible") if (visible==0) then -- not already showing local accid = tonumber(getElementData(source, "gameaccountid")) local result = mysql_query(handler, "SELECT friends, friendsmessage FROM accounts WHERE id='" .. accid .. "' LIMIT 1") if (result) then local sfriends = mysql_result(result, 1, 1) local fmessage = mysql_result(result, 1, 2) if (tostring(sfriends)==tostring(mysql_null())) then sfriends = "" end if (tostring(fmessage)==tostring(mysql_null())) then fmessage = "" end local friends = { } local count = 1 for i=1, 100 do local fid = gettok(sfriends, i, 59) if (fid) then local fresult = mysql_query(handler, "SELECT username, friendsmessage, yearday, year, country, os FROM accounts WHERE id='" .. fid .. "' LIMIT 1") local aresult = mysql_query(handler, "SELECT id FROM achievements WHERE account='" .. fid .. "'") local numachievements = mysql_num_rows(aresult) mysql_free_result(aresult) friends[i] = { } friends[i][1] = tonumber(fid) -- USER ID friends[i][2] = mysql_result(fresult, 1, 1) -- USERNAME friends[i][3] = mysql_result(fresult, 1, 2) -- MESSAGE friends[i][4] = mysql_result(fresult, 1, 5) -- COUNTRY friends[i][7] = tostring(mysql_result(fresult, 1, 6)) -- OPERATING SYSTEM friends[i][8] = tostring(numachievements) -- NUM ACHIEVEMENTS -- Last online local time = getRealTime() local days = time.monthday local months = (time.month+1) local years = (1900+time.year) local yearday = time.yearday local fyearday = tonumber(mysql_result(fresult, 1, 3)) -- YEAR DAY local fyear = tonumber(mysql_result(fresult, 1, 4)) -- YEAR local found, player = false for key, value in ipairs(exports.pool:getPoolElementsByType("player")) do if (tonumber(getElementData(value, "gameaccountid"))==friends[i][1]) then found = true player = value end end if (found) then friends[i][5] = "Online" friends[i][6] = getPlayerName(player) elseif (years~=fyear) then friends[i][5] = "Last Seen: Last Year" elseif (yearday==fyearday) then friends[i][5] = "Last Seen: Today" else local diff = yearday - fyearday friends[i][5] = "Last Seen: " .. tostring(diff) .. " days ago." end mysql_free_result(fresult) else break end end mysql_free_result(result) setElementData(source, "friends.visible", 1) triggerClientEvent(source, "showFriendsList", source, friends) else outputChatBox("Error 600000 - Could not retrieve friends list.", source, 255, 0, 0) end end end end addEvent("sendFriends", false) addEventHandler("sendFriends", getRootElement(), toggleFriends) function updateFriendsMessage(message) local safemessage = mysql_escape_string(handler, tostring(message)) local accid = getElementData(source, "gameaccountid") local query = mysql_query(handler, "UPDATE accounts SET friendsmessage='" .. safemessage .. "' WHERE id='" .. accid .. "'") if (query) then setElementData(source, "friends.visible", 0) setElementData(source, "friends.message", tostring(safemessage)) mysql_free_result(query) toggleFriends(source) else outputChatBox("Error updating friends message - ensure you used no special characters!", source, 255, 0, 0) end end addEvent("updateFriendsMessage", true) addEventHandler("updateFriendsMessage", getRootElement(), updateFriendsMessage) function removeFriend(id, username, dontShowFriends) local accid = tonumber(getElementData(source, "gameaccountid")) local result = mysql_query(handler, "SELECT friends, friendsmessage FROM accounts WHERE id='" .. accid .. "' LIMIT 1") if (result) then local sfriends = mysql_result(result, 1, 1) local fmessage = mysql_result(result, 1, 2) local friendstring = "" local count = 1 for i=1, 100 do local fid = gettok(sfriends, i, 59) if (fid) then if not (tonumber(fid)==id) then friendstring = friendstring .. fid .. ";" end end end mysql_query(handler, "UPDATE accounts SET friends='" .. friendstring .. "' WHERE id='" .. accid .. "'") mysql_free_result(result) outputChatBox("You removed '" .. username .. "' from your friends list.", source, 255, 194, 14) setElementData(source, "friends.visible", 0) if (dontShowFriends==false) then toggleFriends(source) end end end addEvent("removeFriend", true) addEventHandler("removeFriend", getRootElement(), removeFriend)
Bug fix for friends
Bug fix for friends git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@258 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
090d600351bfd88cd7470408ea5c69936143bb69
modules/title/post/olds.lua
modules/title/post/olds.lua
local sql = require'lsqlite3' local date = require'date' local uri = require"handler.uri" local uri_parse = uri.parse local patterns = { -- X://Y url "^(https?://%S+)", "^<(https?://%S+)>", "%f[%S](https?://%S+)", -- www.X.Y url "^(www%.[%w_-%%]+%.%S+)", "%f[%S](www%.[%w_-%%]+%.%S+)", } local openDB = function() local dbfilename = string.format("cache/urls.%s.sql", ivar2.network) local db = sql.open(dbfilename) db:exec([[ CREATE TABLE IF NOT EXISTS urls ( nick text, timestamp integer, url text, channel text ); ]]) return db end -- check for existing url local checkOld = function(source, destination, url) -- Don't lookup root path URLs. local info = uri_parse(url) if(info.path == '' or info.path == '/') then return end local db = openDB() -- create a select handle local sth = db:prepare([[ SELECT nick, timestamp FROM urls WHERE url=? AND channel=? ORDER BY timestamp ASC ]]) -- execute select with a url bound to variable sth:bind_values(url, destination) local count, first = 0 while(sth:step() == sql.ROW) do count = count + 1 if(count == 1) then first = sth:get_named_values() end end sth:finalize() db:close() if(count > 0) then local age = date.relativeTimeShort(first.timestamp) return first.nick, count, age end end local updateDB = function(source, destination, url) local db = openDB() local sth = db:prepare[[ INSERT INTO urls(nick, channel, url, timestamp) values(?, ?, ?, ?) ]] sth:bind_values(source.nick, destination, url, os.time()) sth:step() sth:finalize() end do return function(source, destination, queue) local nick, count, age = checkOld(source, destination, queue.url) updateDB(source, destination, queue.url) -- relativeTimeShort() returns nil if it gets fed os.time(). if(not age) then return end local prepend if(count > 1) then prepend = string.format("Old! %s times, first by %s %s ago", count, nick, age) else prepend = string.format("Old! Linked by %s %s ago", nick, age) end if(queue.output) then queue.output = string.format("%s - %s", prepend, queue.output) else queue.output = prepend end end end
local sql = require'lsqlite3' local date = require'date' local uri = require"handler.uri" local uri_parse = uri.parse local patterns = { -- X://Y url "^(https?://%S+)", "^<(https?://%S+)>", "%f[%S](https?://%S+)", -- www.X.Y url "^(www%.[%w_-%%]+%.%S+)", "%f[%S](www%.[%w_-%%]+%.%S+)", } local openDB = function() local dbfilename = string.format("cache/urls.%s.sql", ivar2.network) local db = sql.open(dbfilename) db:exec([[ CREATE TABLE IF NOT EXISTS urls ( nick text, timestamp integer, url text, channel text ); ]]) return db end -- check for existing url local checkOld = function(source, destination, url) -- Don't lookup root path URLs. local info = uri_parse(url) if(info.path == '' or info.path == '/') then return end local db = openDB() -- create a select handle local sth = db:prepare([[ SELECT nick, timestamp FROM urls WHERE url=? AND channel=? ORDER BY timestamp ASC ]]) -- execute select with a url bound to variable sth:bind_values(url, destination) local count, first = 0 while(sth:step() == sql.ROW) do count = count + 1 if(count == 1) then first = sth:get_named_values() end end sth:finalize() db:close() if(count > 0) then local age = date.relativeTimeShort(first.timestamp) return first.nick, count, age end end local updateDB = function(source, destination, url) local db = openDB() local sth = db:prepare[[ INSERT INTO urls(nick, channel, url, timestamp) values(?, ?, ?, ?) ]] sth:bind_values(source.nick, destination, url, os.time()) sth:step() sth:finalize() end do return function(source, destination, queue) local nick, count, age = checkOld(source, destination, queue.url) updateDB(source, destination, queue.url) -- relativeTimeShort() returns nil if it gets fed os.time(). -- Don't yell if it's the initial poster. if(not age or (nick and nick:lower() == source.nick:lower())) then return end local prepend if(count > 1) then prepend = string.format("Old! %s times, first by %s %s ago", count, nick, age) else prepend = string.format("Old! Linked by %s %s ago", nick, age) end if(queue.output) then queue.output = string.format("%s - %s", prepend, queue.output) else queue.output = prepend end end end
title/olds: Don't yell if the poster is the same as the first.
title/olds: Don't yell if the poster is the same as the first. Fixes #45.
Lua
mit
haste/ivar2,torhve/ivar2,torhve/ivar2,torhve/ivar2
46258028054ebb3ba39b3a134921b95db7cd5c84
nvim/.config/nvim/lua/configs.lua
nvim/.config/nvim/lua/configs.lua
-- nvim-treesitter require "nvim-treesitter.configs".setup { ensure_installed = "all", highlight = {enable = true}, refactor = { highlight_definitions = {enable = false}, highlight_current_scope = {enable = false} }, textobjects = { select = { enable = true, keymaps = { ["af"] = "@function.outer", ["if"] = "@function.inner", ["ac"] = "@class.outer", ["ic"] = "@class.inner" } } }, playground = { enable = true, disable = {}, updatetime = 500, -- Debounced time for highlighting nodes in the playground from source code persist_queries = false -- Whether the query persists across vim sessions } } -- lsp local lsp_attach = function(client) require "diagnostic".on_attach(client) require "lsp-status".on_attach(client) end require "nvim_lsp".pyls.setup {on_attach = lsp_attach} require "nvim_lsp".rust_analyzer.setup {on_attach = lsp_attach} require "nvim_lsp".html.setup {on_attach = lsp_attach} -- npm install -g vscode-html-languageserver-bin require "nvim_lsp".tsserver.setup {on_attach = lsp_attach} require "nvim_lsp".vimls.setup {on_attach = lsp_attach} -- npm install -g vim-language-server require "nvim_lsp".gopls.setup {on_attach = lsp_attach} require "nvim_lsp".bashls.setup {filetypes = {"sh", "zsh"}, on_attach = lsp_attach} require "nvim_lsp".cssls.setup {on_attach = lsp_attach} -- npm install -g vscode-css-languageserver-bin require "nvim_lsp".dockerls.setup {on_attach = lsp_attach} -- npm install -g dockerfile-language-server-nodejs require "nvim_lsp".sumneko_lua.setup { on_attach = lsp_attach, settings = { Lua = { diagnostics = {enable = true, globals = {"hs", "vim", "describe", "it", "before_each", "after_each"}} } }, cmd = { "/Users/meain/.cache/nvim/nvim_lsp/sumneko_lua/lua-language-server/bin/macOS/lua-language-server", "-E", "/Users/meain/.cache/nvim/nvim_lsp/sumneko_lua/lua-language-server/main.lua" } } -- lsp status require "lsp-status".register_progress()
-- nvim-treesitter require "nvim-treesitter.configs".setup { ensure_installed = "all", highlight = {enable = true}, refactor = { highlight_definitions = {enable = false}, highlight_current_scope = {enable = false} }, textobjects = { select = { enable = true, keymaps = { ["af"] = "@function.outer", ["if"] = "@function.inner", ["ac"] = "@class.outer", ["ic"] = "@class.inner" } } }, playground = { enable = true, disable = {}, updatetime = 500, -- Debounced time for highlighting nodes in the playground from source code persist_queries = false -- Whether the query persists across vim sessions } } -- lsp local lsp_attach = function(client) require "lsp-status".on_attach(client) end require "lspconfig".pyls.setup {on_attach = lsp_attach} require "lspconfig".rust_analyzer.setup {on_attach = lsp_attach} require "lspconfig".html.setup {on_attach = lsp_attach} -- npm install -g vscode-html-languageserver-bin require "lspconfig".tsserver.setup {on_attach = lsp_attach} require "lspconfig".vimls.setup {on_attach = lsp_attach} -- npm install -g vim-language-server require "lspconfig".gopls.setup {on_attach = lsp_attach} require "lspconfig".bashls.setup {filetypes = {"sh", "zsh"}, on_attach = lsp_attach} require "lspconfig".cssls.setup {on_attach = lsp_attach} -- npm install -g vscode-css-languageserver-bin require "lspconfig".dockerls.setup {on_attach = lsp_attach} -- npm install -g dockerfile-language-server-nodejs require "lspconfig".sumneko_lua.setup { on_attach = lsp_attach, settings = { Lua = { diagnostics = {enable = true, globals = {"hs", "vim", "describe", "it", "before_each", "after_each"}} } }, cmd = { "/Users/meain/.cache/nvim/nvim_lsp/sumneko_lua/lua-language-server/bin/macOS/lua-language-server", "-E", "/Users/meain/.cache/nvim/nvim_lsp/sumneko_lua/lua-language-server/main.lua" } } -- lsp status require "lsp-status".register_progress()
[nvim] more fixes for changes in lsp config
[nvim] more fixes for changes in lsp config
Lua
mit
meain/dotfiles,meain/dotfiles,meain/dotfiles,meain/dotfiles,meain/dotfiles,meain/dotfiles
5bcaf6c90585d6d37263bfa7ad77a31eb2996048
share/lua/meta/art/02_frenchtv.lua
share/lua/meta/art/02_frenchtv.lua
--[[ Gets an artwork from amazon $Id$ Copyright © 2007 the VideoLAN team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] function descriptor() return { scope="network" } end -- Return the artwork function fetch_art() local urlsForChannel = { -- on http://cyril.bourreau.free.fr/Vectoriel/ ["TF1"] = "http://cyril.bourreau.free.fr/Vectoriel/TF1-2006.png", ["France 2"] = "http://cyril.bourreau.free.fr/Vectoriel/FR2-DSK-couleur.png", ["France 3"] = "http://cyril.bourreau.free.fr/Vectoriel/FR3-DSK-couleur.png", ["France 4"] = "http://cyril.bourreau.free.fr/Vectoriel/FR4-DSK-couleur.png", ["France 5"] = "http://cyril.bourreau.free.fr/Vectoriel/FR5-DSK-couleur.png", ["Direct 8"] = "http://cyril.bourreau.free.fr/Vectoriel/Direct8-2009.png", ["NRJ 12"] = "http://cyril.bourreau.free.fr/Vectoriel/NRJ12-2009.png", ["iTele"] = "http://cyril.bourreau.free.fr/Vectoriel/iTELE-2008.png", ["W9"] = "http://cyril.bourreau.free.fr/Vectoriel/W9.png", ["Arte"] = "http://www.artepro.com/fr_fichiers/upload/10594.jpg", ["TMC"] = "http://upload.wikimedia.org/wikipedia/fr/4/4b/Logo_de_TMC.gif", ["i> TELE"] = "http://upload.wikimedia.org/wikipedia/fr/5/56/Logo_I_tele.png", ["BFM TV"] = "http://upload.wikimedia.org/wikipedia/fr/3/30/Bfm_tv.jpg", ["Virgin 17"] = "http://upload.wikimedia.org/wikipedia/fr/3/39/Virgin17logo.png", ["La Chaîne Parlementaire"] = "http://upload.wikimedia.org/wikipedia/fr/9/98/Public-Senat-LCP-An_logo_2010.png" } local meta = vlc.item:metas(); local channel if meta["title"] then channel = meta["title"] else channel = meta["filename"] end -- Replace "France 2 HD" by "France 2" channel = string.gsub(channel, "^(.-)%sHD%s*$", "%1") -- Replace "France 2 (bas débit)" by "France 2" channel = string.gsub(channel, "^(.-)%s%(bas débit%)%s*$", "%1") -- trim channel = string.gsub(channel, "^%s*(.-)%s*$", "%1") return urlsForChannel[channel] end
--[[ Gets an artwork from amazon $Id$ Copyright © 2007 the VideoLAN team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] function descriptor() return { scope="network" } end -- Return the artwork function fetch_art() local urlsForChannel = { -- on http://cyril.bourreau.free.fr/Vectoriel/ ["TF1"] = "http://cyril.bourreau.free.fr/Vectoriel/TF1-2006.png", ["France 2"] = "http://cyril.bourreau.free.fr/Vectoriel/FR2-DSK-couleur.png", ["France 3"] = "http://cyril.bourreau.free.fr/Vectoriel/FR3-DSK-couleur.png", ["France 4"] = "http://cyril.bourreau.free.fr/Vectoriel/FR4-DSK-couleur.png", ["France 5"] = "http://cyril.bourreau.free.fr/Vectoriel/FR5-DSK-couleur.png", ["Direct 8"] = "http://cyril.bourreau.free.fr/Vectoriel/Direct8-2009.png", ["NRJ 12"] = "http://cyril.bourreau.free.fr/Vectoriel/NRJ12-2009.png", ["iTele"] = "http://cyril.bourreau.free.fr/Vectoriel/iTELE-2008.png", ["W9"] = "http://cyril.bourreau.free.fr/Vectoriel/W9.png", ["Arte"] = "http://www.artepro.com/fr_fichiers/upload/10594.jpg", ["TMC"] = "http://upload.wikimedia.org/wikipedia/fr/2/2e/TMC_new.svg", ["i> TELE"] = "http://upload.wikimedia.org/wikipedia/commons/a/a6/Logo_i_TELE_2013.png", ["BFM TV"] = "http://upload.wikimedia.org/wikipedia/fr/c/c9/BFMTV_HD.png", ["Virgin 17"] = "http://upload.wikimedia.org/wikipedia/fr/3/39/Virgin17logo.png", ["La Chaîne Parlementaire"] = "http://upload.wikimedia.org/wikipedia/fr/1/1f/LCP-Public_Senat_logo.png" } local meta = vlc.item:metas(); local channel if meta["title"] then channel = meta["title"] else channel = meta["filename"] end -- Replace "France 2 HD" by "France 2" channel = string.gsub(channel, "^(.-)%sHD%s*$", "%1") -- Replace "France 2 (bas débit)" by "France 2" channel = string.gsub(channel, "^(.-)%s%(bas débit%)%s*$", "%1") -- trim channel = string.gsub(channel, "^%s*(.-)%s*$", "%1") return urlsForChannel[channel] end
Fix links to French TV icons
Fix links to French TV icons Control: forwarded -1 [email protected] Hi, Some links pointing to TV icons were broken. Attached patch fixes that. Original report: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=782229 Typical output: [0x1e2ba18] access_http access error: error: HTTP/1.1 404 Not Found [0x1e2ba18] access_http access error: error: HTTP/1.1 404 Not Found [0x1e2ba18] access_mms access error: error: HTTP/1.1 403 Requested target domain not allowed. [0x1b3f7a8] main playlist error: no suitable access module for `http://upload.wikimedia.org/wikipedia/fr/4/4b/Logo_de_TMC.gif' [0x1e3fbc8] access_http access error: error: HTTP/1.1 404 Not Found [0x1e3fbc8] access_http access error: error: HTTP/1.1 404 Not Found [0x1e3fbc8] access_mms access error: error: HTTP/1.1 403 Requested target domain not allowed. [0x1b3f7a8] main playlist error: no suitable access module for `http://upload.wikimedia.org/wikipedia/fr/4/4b/Logo_de_TMC.gif' [0x4b52bc8] access_http access error: error: HTTP/1.1 404 Not Found [0x4b52bc8] access_http access error: error: HTTP/1.1 404 Not Found [0x4b52bc8] access_mms access error: error: HTTP/1.1 403 Requested target domain not allowed. [0x1b3f7a8] main playlist error: no suitable access module for `http://upload.wikimedia.org/wikipedia/fr/9/98/Public-Senat-LCP-An_logo_2010.png' [0x7fd8cc0133e8] access_http access error: error: HTTP/1.1 404 Not Found [0x7fd8cc0133e8] access_http access error: error: HTTP/1.1 404 Not Found [0x7fd8cc0133e8] access_mms access error: error: HTTP/1.1 403 Requested target domain not allowed. [0x1b3f7a8] main playlist error: no suitable access module for `http://upload.wikimedia.org/wikipedia/fr/9/98/Public-Senat-LCP-An_logo_2010.png' [0x3567038] access_http access error: error: HTTP/1.1 404 Not Found [0x3567038] access_http access error: error: HTTP/1.1 404 Not Found [0x3567038] access_mms access error: error: HTTP/1.1 403 Requested target domain not allowed. [0x1b3f7a8] main playlist error: no suitable access module for `http://upload.wikimedia.org/wikipedia/fr/3/30/Bfm_tv.jpg' [0x1ba7748] access_http access error: error: HTTP/1.1 404 Not Found [0x1ba7748] access_http access error: error: HTTP/1.1 404 Not Found [0x1ba7748] access_mms access error: error: HTTP/1.1 403 Requested target domain not allowed. [0x1b3f7a8] main playlist error: no suitable access module for `http://upload.wikimedia.org/wikipedia/fr/3/30/Bfm_tv.jpg' [0x1ba7748] access_http access error: error: HTTP/1.1 404 Not Found [0x1ba7748] access_http access error: error: HTTP/1.1 404 Not Found [0x1ba7748] access_mms access error: error: HTTP/1.1 403 Requested target domain not allowed. [0x1b3f7a8] main playlist error: no suitable access module for `http://upload.wikimedia.org/wikipedia/fr/3/30/Bfm_tv.jpg' [0x1ba7748] access_http access error: error: HTTP/1.1 404 Not Found [0x1ba7748] access_http access error: error: HTTP/1.1 404 Not Found [0x1ba7748] access_mms access error: error: HTTP/1.1 403 Requested target domain not allowed. [0x1b3f7a8] main playlist error: no suitable access module for `http://upload.wikimedia.org/wikipedia/fr/5/56/Logo_I_tele.png' Description: Fix broken links Author: Mathieu Malaterre <[email protected]> Bug-Debian: https://bugs.debian.org/ Signed-off-by: Jean-Baptiste Kempf <[email protected]>
Lua
lgpl-2.1
vlc-mirror/vlc,shyamalschandra/vlc,vlc-mirror/vlc,xkfz007/vlc,shyamalschandra/vlc,vlc-mirror/vlc,vlc-mirror/vlc,xkfz007/vlc,xkfz007/vlc,krichter722/vlc,shyamalschandra/vlc,krichter722/vlc,vlc-mirror/vlc,shyamalschandra/vlc,vlc-mirror/vlc,xkfz007/vlc,krichter722/vlc,shyamalschandra/vlc,shyamalschandra/vlc,xkfz007/vlc,shyamalschandra/vlc,krichter722/vlc,krichter722/vlc,vlc-mirror/vlc,krichter722/vlc,xkfz007/vlc,xkfz007/vlc,krichter722/vlc
8f141323bf8df14be16f54d5f74cb8329f797a81
kong/plugins/session/schema.lua
kong/plugins/session/schema.lua
local utils = require("kong.tools.utils") local char = string.char local rand = math.random local encode_base64 = ngx.encode_base64 -- kong.utils.random_string with number of bytes config local function random_string(n_bytes) return encode_base64(get_rand_bytes(n_bytes or 32, true)) :gsub("/", char(rand(48, 57))) -- 0 - 10 :gsub("+", char(rand(65, 90))) -- A - Z :gsub("=", char(rand(97, 122))) -- a - z end return { no_consumer = true, fields = { secret = { type = "string", required = false, default = random_string, }, cookie_name = { type = "string", default = "session" }, cookie_lifetime = { type = "number", default = 3600 }, cookie_renew = { type = "number", default = 600 }, cookie_path = { type = "string", default = "/" }, cookie_domain = { type = "string" }, cookie_samesite = { type = "string", default = "Strict", one_of = { "Strict", "Lax", "off" } }, cookie_httponly = { type = "boolean", default = true }, cookie_secure = { type = "boolean", default = true }, cookie_discard = { type = "number", default = 10 }, storage = { required = false, type = "string", enum = { "cookie", "kong", }, default = "cookie", }, logout_methods = { type = "array", enum = { "POST", "GET", "DELETE" }, default = { "POST", "DELETE" } }, logout_query_arg = { required = false, type = "string", default = "session_logout", }, logout_post_arg = { required = false, type = "string", default = "session_logout", }, } }
local utils = require("kong.tools.utils") local char = string.char local rand = math.random local encode_base64 = ngx.encode_base64 --- kong.utils.random_string with 32 bytes instead -- @returns random string of length 44 local function random_string() return encode_base64(utils.get_rand_bytes(32, true)) :gsub("/", char(rand(48, 57))) -- 0 - 10 :gsub("+", char(rand(65, 90))) -- A - Z :gsub("=", char(rand(97, 122))) -- a - z end return { no_consumer = true, fields = { secret = { type = "string", required = false, default = random_string, }, cookie_name = { type = "string", default = "session" }, cookie_lifetime = { type = "number", default = 3600 }, cookie_renew = { type = "number", default = 600 }, cookie_path = { type = "string", default = "/" }, cookie_domain = { type = "string" }, cookie_samesite = { type = "string", default = "Strict", one_of = { "Strict", "Lax", "off" } }, cookie_httponly = { type = "boolean", default = true }, cookie_secure = { type = "boolean", default = true }, cookie_discard = { type = "number", default = 10 }, storage = { required = false, type = "string", enum = { "cookie", "kong", }, default = "cookie", }, logout_methods = { type = "array", enum = { "POST", "GET", "DELETE" }, default = { "POST", "DELETE" } }, logout_query_arg = { required = false, type = "string", default = "session_logout", }, logout_post_arg = { required = false, type = "string", default = "session_logout", }, } }
fix(session) fix random string arg since config is passed
fix(session) fix random string arg since config is passed
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
3557f5138405ddbcb2d409c8bd266de834208bea
otouto/plugins/antilink.lua
otouto/plugins/antilink.lua
local bindings = require('otouto.bindings') local utilities = require('otouto.utilities') local autils = require('otouto.administration') local antilink = {} function antilink:init() assert(self.named_plugins.flags, antilink.name .. ' requires flags') self.named_plugins.flags.flags[antilink.name] = 'Posting links to other groups is not allowed.' -- Build the antilink patterns. Additional future domains can be added to -- this list to keep it up to date. antilink.patterns = {} for _, domain in pairs{ 'telegram.me', 'telegram.dog', 'tlgrm.me', 't.me' } do local s = '' -- We build the pattern character by character from the domains. -- May become an issue when emoji TLDs become mainstream. ;) for char in domain:gmatch('.') do if char:match('%l') then s = s .. '[' .. char:upper() .. char .. ']' -- all characters which must be escaped elseif char:match('[%%%.%^%$%+%-%*%?]') then s = s .. '%' .. char else s = s .. char end end table.insert(antilink.patterns, s) end antilink.triggers = antilink.patterns antilink.internal = true end function antilink:action(msg, group, user) if not group.flags.antilink then return true end if user.rank > 1 then return true end if msg.forward_from and ( (msg.forward_from.id == self.info.id) or (msg.forward_from.id == self.config.log_chat) or (msg.forward_from.id == self.config.administration.log_chat) ) then return true end if antilink.check(self, msg) then autils.strike(self, msg, antilink.name) else return true end end antilink.edit_action = antilink.action -- Links can come from the message text or from entities, and can be joinchat -- links (t.me/joinchat/abcdefgh), username links (t.me/abcdefgh), or usernames -- (@abcdefgh). function antilink.check(self, msg) for _, pattern in pairs(antilink.patterns) do -- Iterate through links in the message, and determine if they refer to -- external groups. for link in msg.text:gmatch(pattern..'%g*') do if antilink.parse_and_detect(self, link, pattern) then return true end end -- Iterate through the messages's entities, if any, and determine if -- they're links to external groups. if msg.entities then for _, entity in ipairs(msg.entities) do if entity.url and antilink.parse_and_detect(self, entity.url, pattern) then return true end end end end -- Iterate through all usernames in the message text, and determine if they -- are external group links. for username in msg.text:gmatch('@([%w_]+)') do if antilink.is_username_external(self, username) then return true end end end -- This function takes a link or username (parsed from a message or found in an -- entity) and returns true if that link or username refers to a supergroup -- outside of the realm. function antilink.parse_and_detect(self, link, pattern) local code = link:match(pattern .. -- /joinchat/ABC-def_123 '/[Jj][Oo][Ii][Nn][Cc][Hh][Aa][Tt]/([%w_%-]+)') local username = link:match(pattern .. '/([%w_]+)') if (code and antilink.is_code_external(self, code)) or (username and antilink.is_username_external(self, username)) then return true end end -- This function determines whether or not a given joinchat "code" refers to -- a group outside the realm (true/false) function antilink.is_code_external(self, code) -- Prepare the code to be used as a pattern by escaping any hyphens. -- Also, add an anchor. local pattern = '/' .. code:gsub('%-', '%%-') .. '$' -- Iterate through groups and return false if the joinchat code belongs to -- any one of them. for _, group in pairs(self.database.administration.groups) do if group.link:match(pattern) then return false end end return true end -- This function determines whether or not a username refers to a supergroup -- outside the realm (true/false). function antilink.is_username_external(self, username) local res = bindings.getChat{chat_id = '@' .. username} -- If the username is an external supergroup or channel, return true. if res and (res.result.type=='supergroup' or res.result.type=='channel') and not self.database.administration.groups[tostring(res.result.id)] then return true end return false end return antilink
local bindings = require('otouto.bindings') local utilities = require('otouto.utilities') local autils = require('otouto.administration') local antilink = {} function antilink:init() assert(self.named_plugins.flags, antilink.name .. ' requires flags') self.named_plugins.flags.flags[antilink.name] = 'Posting links to other groups is not allowed.' -- Build the antilink patterns. Additional future domains can be added to -- this list to keep it up to date. antilink.patterns = {} for _, domain in pairs{ 'telegram.me', 'telegram.dog', 'tlgrm.me', 't.me' } do local s = '' -- We build the pattern character by character from the domains. -- May become an issue when emoji TLDs become mainstream. ;) for char in domain:gmatch('.') do if char:match('%l') then s = s .. '[' .. char:upper() .. char .. ']' -- all characters which must be escaped elseif char:match('[%%%.%^%$%+%-%*%?]') then s = s .. '%' .. char else s = s .. char end end table.insert(antilink.patterns, s) end antilink.triggers = utilities.clone_table(antilink.patterns) table.insert(antilink.triggers, '@[%w_]+') -- Infractions are stored, and users are globally banned after three. if not self.database.administration.antilink then self.database.administration.antilink = {} end antilink.store = self.database.administration.antilink antilink.internal = true end function antilink:action(msg, group, user) if not group.flags.antilink then return true end if user.rank > 1 then return true end if msg.forward_from and ( (msg.forward_from.id == self.info.id) or (msg.forward_from.id == self.config.log_chat) or (msg.forward_from.id == self.config.administration.log_chat) ) then return true end if antilink.check(self, msg) then antilink.store[user.id_str] = antilink.store[user.id_str] or { count = 0, groups = {}, } antilink.store[user.id_str].count = antilink.store[user.id_str].count +1 antilink.store[user.id_str].groups[tostring(msg.chat.id)] = true antilink.store[user.id_str].latest = os.time() if antilink.store[user.id_str].count == 3 then self.database.administration.hammers[user.id_str] = true autils.log(self, msg.chat.title, msg.from.id, 'Globally banned', 'antilink', 'Three illegal links within a day.') for chat_id_str in pairs(antilink.store[user.id_str].groups) do bindings.kickChatMember{ chat_id = chat_id_str, target = msg.from.id } end antilink.store[user.id_str] = nil else autils.strike(self, msg, antilink.name) end else return true end end function antilink:cron() if antilink.last_clear ~= os.date('%H') then for id_str, store in pairs(antilink.store) do if store.latest + 86400 > os.time() then antilink.store[id_str] = nil end end antilink.last_clear = os.date('%H') end end antilink.edit_action = antilink.action -- Links can come from the message text or from entities, and can be joinchat -- links (t.me/joinchat/abcdefgh), username links (t.me/abcdefgh), or usernames -- (@abcdefgh). function antilink.check(self, msg) for _, pattern in pairs(antilink.patterns) do -- Iterate through links in the message, and determine if they refer to -- external groups. for link in msg.text:gmatch(pattern..'%g*') do if antilink.parse_and_detect(self, link, pattern) then return true end end -- Iterate through the messages's entities, if any, and determine if -- they're links to external groups. if msg.entities then for _, entity in ipairs(msg.entities) do if entity.url and antilink.parse_and_detect(self, entity.url, pattern) then return true end end end end -- Iterate through all usernames in the message text, and determine if they -- are external group links. for username in msg.text:gmatch('@([%w_]+)') do if antilink.is_username_external(self, username) then return true end end end -- This function takes a link or username (parsed from a message or found in an -- entity) and returns true if that link or username refers to a supergroup -- outside of the realm. function antilink.parse_and_detect(self, link, pattern) local code = link:match(pattern .. -- /joinchat/ABC-def_123 '/[Jj][Oo][Ii][Nn][Cc][Hh][Aa][Tt]/([%w_%-]+)') local username = link:match(pattern .. '/([%w_]+)') if (code and antilink.is_code_external(self, code)) or (username and antilink.is_username_external(self, username)) then return true end end -- This function determines whether or not a given joinchat "code" refers to -- a group outside the realm (true/false) function antilink.is_code_external(self, code) -- Prepare the code to be used as a pattern by escaping any hyphens. -- Also, add an anchor. local pattern = '/' .. code:gsub('%-', '%%-') .. '$' -- Iterate through groups and return false if the joinchat code belongs to -- any one of them. for _, group in pairs(self.database.administration.groups) do if group.link:match(pattern) then return false end end return true end -- This function determines whether or not a username refers to a supergroup -- outside the realm (true/false). function antilink.is_username_external(self, username) local res = bindings.getChat{chat_id = '@' .. username} -- If the username is an external supergroup or channel, return true. if res and (res.result.type=='supergroup' or res.result.type=='channel') and not self.database.administration.groups[tostring(res.result.id)] then return true end return false end return antilink
Fixed bug where usernames were not triggering antilink by adding a trigger for usernames (duh). Also added functionality to antilink to ban a user for three antilink triggers within one day of eachother.
Fixed bug where usernames were not triggering antilink by adding a trigger for usernames (duh). Also added functionality to antilink to ban a user for three antilink triggers within one day of eachother.
Lua
agpl-3.0
topkecleon/otouto
52debf3294a11ea9706d7b73828f4616e7457aba
groupped-list.lua
groupped-list.lua
-- cached id list key local idListKey = KEYS[1]; -- meta key local metadataKey = KEYS[2]; -- stringified [key]: [aggregateMethod] pairs local aggregates = ARGV[1]; -- local cache local rcall = redis.call; local tinsert = table.insert; local jsonAggregates = cjson.decode(aggregates); local aggregateKeys = {}; local result = {}; local function anynumber(a) return try { function() local num = tonumber(a); return num ~= nil and num or tonumber(cjson.decode(a)); end, catch { function() return nil; end } } end local function aggregateSum(value1, value2) local num1 = anynumber(value1) or 0; local num2 = anynumber(value2) or 0; return value1 + value2; end local aggregateType = { sum = aggregateSum }; for key, method in pairs(jsonAggregates) do tinsert(aggregateKeys, key); result[key] = 0; if type(aggregateType[method]) ~= "function" then return error("not supported op: " .. method); end end local valuesToGroup = rcall("LRANGE", idListKey, 0, -1); -- group for _, id in ipairs(valuesToGroup) do -- metadata is stored here local metaKey = metadataKey:gsub("*", id, 1); -- pull information about required aggregate keys -- only 1 operation is supported now - sum -- but we can calculate multiple values local values = rcall("HMGET", metaKey, unpack(aggregateKeys)); for i, aggregateKey in ipairs(aggregateKeys) do local aggregateMethod = aggregateType[jsonAggregates[aggregateKey]]; local value = tonumber(values[i] or 0); result[aggregateKey] = aggregateMethod(result[aggregateKey], value); end end return cjson.encode(result);
-- cached id list key local idListKey = KEYS[1]; -- meta key local metadataKey = KEYS[2]; -- stringified [key]: [aggregateMethod] pairs local aggregates = ARGV[1]; -- local cache local rcall = redis.call; local tinsert = table.insert; local jsonAggregates = cjson.decode(aggregates); local aggregateKeys = {}; local result = {}; local function try(what) local status, result = pcall(what[1]); if not status then return what[2](result); end return result; end local function catch(what) return what[1] end local function anynumber(a) return try { function() local num = tonumber(a); return num ~= nil and num or tonumber(cjson.decode(a)); end, catch { function() return nil; end } } end local function aggregateSum(value1, value2) local num1 = anynumber(value1) or 0; local num2 = anynumber(value2) or 0; return value1 + value2; end local aggregateType = { sum = aggregateSum }; for key, method in pairs(jsonAggregates) do tinsert(aggregateKeys, key); result[key] = 0; if type(aggregateType[method]) ~= "function" then return error("not supported op: " .. method); end end local valuesToGroup = rcall("LRANGE", idListKey, 0, -1); -- group for _, id in ipairs(valuesToGroup) do -- metadata is stored here local metaKey = metadataKey:gsub("*", id, 1); -- pull information about required aggregate keys -- only 1 operation is supported now - sum -- but we can calculate multiple values local values = rcall("HMGET", metaKey, unpack(aggregateKeys)); for i, aggregateKey in ipairs(aggregateKeys) do local aggregateMethod = aggregateType[jsonAggregates[aggregateKey]]; local value = tonumber(values[i] or 0); result[aggregateKey] = aggregateMethod(result[aggregateKey], value); end end return cjson.encode(result);
fix: try/catch local funcs
fix: try/catch local funcs
Lua
mit
makeomatic/redis-filtered-sort,makeomatic/redis-filtered-sort
7701d61b55d991f11c6823bae55ec190f77be7d5
mods/mesecons/mesecons_receiver/init.lua
mods/mesecons/mesecons_receiver/init.lua
rcvboxes = { { -3/16, -3/16, -8/16 , 3/16, 3/16 , -13/32 }, -- the smaller bump { -1/32, -1/32, -3/2 , 1/32, 1/32 , -1/2 }, -- the wire through the block { -2/32, -1/2 , -.5 , 2/32, 0 , -.5002+3/32 }, -- the vertical wire bit { -2/32, -1/2 , -7/16+0.002 , 2/32, -14/32, 16/32+0.001 } -- the horizontal wire } local receiver_get_rules = function (node) local rules = { {x = 1, y = 0, z = 0}, {x = -2, y = 0, z = 0}} if node.param2 == 2 then rules = mesecon.rotate_rules_left(rules) elseif node.param2 == 3 then rules = mesecon.rotate_rules_right(mesecon.rotate_rules_right(rules)) elseif node.param2 == 0 then rules = mesecon.rotate_rules_right(rules) end return rules end minetest.register_node("mesecons_receiver:receiver_on", { drawtype = "nodebox", tiles = { "receiver_top_on.png", "receiver_bottom_on.png", "receiver_lr_on.png", "receiver_lr_on.png", "receiver_fb_on.png", "receiver_fb_on.png", }, paramtype = "light", paramtype2 = "facedir", sunlight_propagates = true, walkable = false, selection_box = { type = "fixed", fixed = { -3/16, -8/16, -8/16, 3/16, 3/16, 8/16 } }, node_box = { type = "fixed", fixed = rcvboxes }, groups = {dig_immediate = 3, not_in_creative_inventory = 1}, drop = "mesecons:wire_00000000_off", mesecons = {conductor = { state = mesecon.state.on, rules = receiver_get_rules, offstate = "mesecons_receiver:receiver_off" }} }) minetest.register_node("mesecons_receiver:receiver_off", { drawtype = "nodebox", description = "You hacker you", tiles = { "receiver_top_off.png", "receiver_bottom_off.png", "receiver_lr_off.png", "receiver_lr_off.png", "receiver_fb_off.png", "receiver_fb_off.png", }, paramtype = "light", paramtype2 = "facedir", sunlight_propagates = true, walkable = false, selection_box = { type = "fixed", fixed = { -3/16, -8/16, -8/16, 3/16, 3/16, 8/16 } }, node_box = { type = "fixed", fixed = rcvboxes }, groups = {dig_immediate = 3, not_in_creative_inventory = 1}, drop = "mesecons:wire_00000000_off", mesecons = {conductor = { state = mesecon.state.off, rules = receiver_get_rules, onstate = "mesecons_receiver:receiver_on" }} }) function mesecon.receiver_get_pos_from_rcpt(pos, param2) local rules = {{x = 2, y = 0, z = 0}} if param2 == nil then param2 = minetest.get_node(pos).param2 end if param2 == 2 then rules = mesecon.rotate_rules_left(rules) elseif param2 == 3 then rules = mesecon.rotate_rules_right(mesecon.rotate_rules_right(rules)) elseif param2 == 0 then rules = mesecon.rotate_rules_right(rules) end local np = { x = pos.x + rules[1].x, y = pos.y + rules[1].y, z = pos.z + rules[1].z} return np end function mesecon.receiver_place(rcpt_pos) local node = minetest.get_node(rcpt_pos) local pos = mesecon.receiver_get_pos_from_rcpt(rcpt_pos, node.param2) local nn = minetest.get_node(pos) if string.find(nn.name, "mesecons:wire_") ~= nil then minetest.dig_node(pos) if mesecon.is_power_on(rcpt_pos) then minetest.set_node(pos, {name = "mesecons_receiver:receiver_on", param2 = node.param2}) mesecon.receptor_on(pos, receiver_get_rules(node)) else minetest.set_node(pos, {name = "mesecons_receiver:receiver_off", param2 = node.param2}) end mesecon.update_autoconnect(pos) end end function mesecon.receiver_remove(rcpt_pos, dugnode) local pos = mesecon.receiver_get_pos_from_rcpt(rcpt_pos, dugnode.param2) local nn = minetest.get_node(pos) if string.find(nn.name, "mesecons_receiver:receiver_") ~=nil then minetest.dig_node(pos) local node = {name = "mesecons:wire_00000000_off"} minetest.set_node(pos, node) mesecon.update_autoconnect(pos) mesecon.on_placenode(pos, node) end end minetest.register_on_placenode(function (pos, node) if minetest.get_item_group(node.name, "mesecon_needs_receiver") == 1 then mesecon.receiver_place(pos) end end) minetest.register_on_dignode(function(pos, node) if minetest.get_item_group(node.name, "mesecon_needs_receiver") == 1 then mesecon.receiver_remove(pos, node) end end) minetest.register_on_placenode(function (pos, node) if string.find(node.name, "mesecons:wire_") ~=nil then local rules = { {x = 2, y = 0, z = 0}, {x =-2, y = 0, z = 0}, {x = 0, y = 0, z = 2}, {x = 0, y = 0, z =-2}} local i = 1 while rules[i] ~= nil do local np = { x = pos.x + rules[i].x, y = pos.y + rules[i].y, z = pos.z + rules[i].z} if minetest.get_item_group(minetest.get_node(np).name, "mesecon_needs_receiver") == 1 then mesecon.receiver_place(np) end i = i + 1 end end end)
rcvboxes = { { -3/16, -3/16, -8/16 , 3/16, 3/16 , -13/32 }, -- the smaller bump { -1/32, -1/32, -3/2 , 1/32, 1/32 , -1/2 }, -- the wire through the block { -2/32, -1/2 , -.5 , 2/32, 0 , -.5002+3/32 }, -- the vertical wire bit { -2/32, -1/2 , -7/16+0.002 , 2/32, -14/32, 16/32+0.001 } -- the horizontal wire } local receiver_get_rules = function (node) local rules = { {x = 1, y = 0, z = 0}, {x = -2, y = 0, z = 0}} if node.param2 == 2 then rules = mesecon.rotate_rules_left(rules) elseif node.param2 == 3 then rules = mesecon.rotate_rules_right(mesecon.rotate_rules_right(rules)) elseif node.param2 == 0 then rules = mesecon.rotate_rules_right(rules) end return rules end minetest.register_node("mesecons_receiver:receiver_on", { drawtype = "nodebox", tiles = { "receiver_top_on.png", "receiver_bottom_on.png", "receiver_lr_on.png", "receiver_lr_on.png", "receiver_fb_on.png", "receiver_fb_on.png", }, paramtype = "light", paramtype2 = "facedir", sunlight_propagates = true, walkable = false, selection_box = { type = "fixed", fixed = { -3/16, -8/16, -8/16, 3/16, 3/16, 8/16 } }, node_box = { type = "fixed", fixed = rcvboxes }, groups = {dig_immediate = 3, not_in_creative_inventory = 1}, drop = "mesecons:wire_00000000_off", mesecons = {conductor = { state = mesecon.state.on, rules = receiver_get_rules, offstate = "mesecons_receiver:receiver_off" }} }) minetest.register_node("mesecons_receiver:receiver_off", { drawtype = "nodebox", description = "You hacker you", tiles = { "receiver_top_off.png", "receiver_bottom_off.png", "receiver_lr_off.png", "receiver_lr_off.png", "receiver_fb_off.png", "receiver_fb_off.png", }, paramtype = "light", paramtype2 = "facedir", sunlight_propagates = true, walkable = false, selection_box = { type = "fixed", fixed = { -3/16, -8/16, -8/16, 3/16, 3/16, 8/16 } }, node_box = { type = "fixed", fixed = rcvboxes }, groups = {dig_immediate = 3, not_in_creative_inventory = 1}, drop = "mesecons:wire_00000000_off", mesecons = {conductor = { state = mesecon.state.off, rules = receiver_get_rules, onstate = "mesecons_receiver:receiver_on" }} }) function mesecon.receiver_get_pos_from_rcpt(pos, param2) local rules = {{x = 2, y = 0, z = 0}} if param2 == nil then param2 = minetest.get_node(pos).param2 end if param2 == 2 then rules = mesecon.rotate_rules_left(rules) elseif param2 == 3 then rules = mesecon.rotate_rules_right(mesecon.rotate_rules_right(rules)) elseif param2 == 0 then rules = mesecon.rotate_rules_right(rules) end local np = { x = pos.x + rules[1].x, y = pos.y + rules[1].y, z = pos.z + rules[1].z} return np end function mesecon.receiver_place(rcpt_pos) local node = minetest.get_node(rcpt_pos) local pos = mesecon.receiver_get_pos_from_rcpt(rcpt_pos, node.param2) local nn = minetest.get_node(pos) if string.find(nn.name, "mesecons:wire_") ~= nil then --minetest.dig_node(pos) <-- Bug duplication if mesecon.is_power_on(rcpt_pos) then minetest.set_node(pos, {name = "mesecons_receiver:receiver_on", param2 = node.param2}) mesecon.receptor_on(pos, receiver_get_rules(node)) else minetest.set_node(pos, {name = "mesecons_receiver:receiver_off", param2 = node.param2}) end mesecon.update_autoconnect(pos) end end function mesecon.receiver_remove(rcpt_pos, dugnode) local pos = mesecon.receiver_get_pos_from_rcpt(rcpt_pos, dugnode.param2) local nn = minetest.get_node(pos) if string.find(nn.name, "mesecons_receiver:receiver_") ~=nil then --minetest.dig_node(pos) <-- Bug duplication local node = {name = "mesecons:wire_00000000_off"} minetest.set_node(pos, node) mesecon.update_autoconnect(pos) mesecon.on_placenode(pos, node) end end minetest.register_on_placenode(function (pos, node) if minetest.get_item_group(node.name, "mesecon_needs_receiver") == 1 then mesecon.receiver_place(pos) end end) minetest.register_on_dignode(function(pos, node) if minetest.get_item_group(node.name, "mesecon_needs_receiver") == 1 then mesecon.receiver_remove(pos, node) end end) minetest.register_on_placenode(function (pos, node) if string.find(node.name, "mesecons:wire_") ~=nil then local rules = { {x = 2, y = 0, z = 0}, {x =-2, y = 0, z = 0}, {x = 0, y = 0, z = 2}, {x = 0, y = 0, z =-2}} local i = 1 while rules[i] ~= nil do local np = { x = pos.x + rules[i].x, y = pos.y + rules[i].y, z = pos.z + rules[i].z} if minetest.get_item_group(minetest.get_node(np).name, "mesecon_needs_receiver") == 1 then mesecon.receiver_place(np) end i = i + 1 end end end)
Fix duplication bug when place or remove mesecons receiver
Fix duplication bug when place or remove mesecons receiver
Lua
unlicense
sys4-fr/server-minetestforfun,sys4-fr/server-minetestforfun,sys4-fr/server-minetestforfun
f31adf071cd0ba8580a2ccd5ed2bfa58c5f44d75
splash/lua_modules/wraputils.lua
splash/lua_modules/wraputils.lua
-- -- This modules provides utilities to access Python -- objects from Lua. It should be used together with -- utilities in qtrender_lua. -- -- This function works very much like standard Lua assert, but: -- -- * the first argument is the stack level to report the error at (1 being -- current level, like for `error` function) -- * it strips the flag if it evaluates to true -- * it does not take a message parameter and thus will always preserve all -- elements of the tuple -- local function assertx(nlevels, ok, ...) if not ok then -- print("Assertx nlevels=", nlevels, "tb: ", debug.traceback()) local msg = tostring(select(1, ...)) error(msg, 1 + nlevels) else return ... end end -- Python Splash commands return -- -- operation, [ result1, result2, ... ] -- -- tuples. Operation can be one of the following: -- -- * "return": return the rest of the tuple -- -- * "yield": yield the rest of the tuple with coroutine.yield -- -- * "raise": raise an error using the rest of the tuple -- local function unwrap_python_result(error_nlevels, op, ...) if op == 'return' then return ... elseif op == 'raise' then assertx(error_nlevels, nil, ...) elseif op == 'yield' then return unwrap_python_result(error_nlevels, coroutine.yield(...)) else error('Invalid operation: ' .. tostring(op)) end end local function unwraps_python_result(func, nlevels) if nlevels == nil then -- nlevels is passed straight to the corresponding assertx func. nlevels = 1 end return function(...) return unwrap_python_result(1 + nlevels, func(...)) end end -- -- Python methods don't want explicit 'self' argument; -- this decorator adds a dummy 'self' argument to allow Lua -- methods syntax. -- local function drops_self_argument(func) return function(self, ...) return func(...) end end -- -- A decorator that fixes an issue with passing callbacks from Lua to Python -- by putting the callback to a table provided by the caller. -- See https://github.com/scoder/lupa/pull/49 for more. -- local function sets_callback(func, storage) return function(cb, ...) storage[1] = cb return func(...) end end local PRIVATE_PREFIX = "private_" local function is_private_name(key) return string.find(key, "^" .. PRIVATE_PREFIX) ~= nil end -- -- Create a Lua wrapper for a Python object. -- -- * Lua methods are created for Python methods wrapped in @command. -- * Async methods are wrapped with `coroutine.yield`. -- * Lua <-> Python error handling is fixed. -- * Private methods are stored in `private_self`, public methods are -- stored in `self`. -- local function setup_commands(py_object, self, private_self) -- Create lua_object:<...> methods from py_object methods: for key, opts in pairs(py_object.commands) do local command = py_object[key] if opts.sets_callback then command = sets_callback(command, py_object.tmp_storage) end command = drops_self_argument(command) local nlevels = 1 if is_private_name(key) then -- private functions are wrapped, so nlevels is set to 2 to show error -- line number in user code nlevels = 2 end command = unwraps_python_result(command, nlevels) if is_private_name(key) then local short_key = string.sub(key, PRIVATE_PREFIX:len() + 1) private_self[short_key] = command else -- avoid custom setter rawset(self, key, command) end end end -- -- Handle @lua_property decorators. -- local function setup_property_access(py_object, self, cls) rawset(self, '__getters', {}) rawset(self, '__setters', {}) for name, opts in pairs(py_object.lua_properties) do self.__getters[name] = unwraps_python_result(drops_self_argument(py_object[opts.getter])) if opts.setter ~= nil then self.__setters[name] = unwraps_python_result(drops_self_argument(py_object[opts.setter])) else self.__setters[name] = function() error("Attribute " .. name .. " is read-only.", 2) end end end end -- -- Create a Lua wrapper for a Python object. -- local function wrap_exposed_object(py_object, self, cls, private_self) setmetatable(self, cls) setup_commands(py_object, self, private_self) setup_property_access(py_object, self, cls) end -- -- Return a metatable for a wrapped Python object -- local function create_metatable() local cls = { __wrapped = true } return cls end -- -- Return true if an object is a wrapped Python object -- local function is_wrapped(obj) local mt = getmetatable(obj) if type(mt) ~= 'table' then return false end return mt.__wrapped == true end -- -- Set metamethods for accessing custom getters and setters -- local function set_metamethods(cls) cls.__index = function(self, index) if self.__getters[index] then return self.__getters[index](self) else return rawget(cls, index) end end cls.__newindex = function(self, index, value) if self.__setters[index] then return self.__setters[index](self, value) else return rawset(self, index, value) end end end -- Exposed API return { assertx = assertx, unwraps_python_result = unwraps_python_result, drops_self_argument = drops_self_argument, raises_async = raises_async, yields_result = yields_result, sets_callback = sets_callback, is_private_name = is_private_name, setup_commands = setup_commands, setup_property_access = setup_property_access, wrap_exposed_object = wrap_exposed_object, create_metatable = create_metatable, set_metamethods = set_metamethods, is_wrapped = is_wrapped, }
-- -- This modules provides utilities to access Python -- objects from Lua. It should be used together with -- utilities in qtrender_lua. -- -- This function works very much like standard Lua assert, but: -- -- * the first argument is the stack level to report the error at (1 being -- current level, like for `error` function) -- * it strips the flag if it evaluates to true -- * it does not take a message parameter and thus will always preserve all -- elements of the tuple -- local function assertx(nlevels, ok, ...) if not ok then -- print("Assertx nlevels=", nlevels, "tb: ", debug.traceback()) local msg = tostring(select(1, ...)) error(msg, 1 + nlevels) else return ... end end -- Python Splash commands return -- -- operation, [ result1, result2, ... ] -- -- tuples. Operation can be one of the following: -- -- * "return": return the rest of the tuple -- -- * "yield": yield the rest of the tuple with coroutine.yield -- -- * "raise": raise an error using the rest of the tuple -- local function unwrap_python_result(error_nlevels, op, ...) if op == 'return' then return ... elseif op == 'raise' then assertx(error_nlevels, nil, ...) elseif op == 'yield' then return unwrap_python_result(error_nlevels, coroutine.yield(...)) else error('Invalid operation: ' .. tostring(op)) end end local function unwraps_python_result(func, nlevels) if nlevels == nil then -- nlevels is passed straight to the corresponding assertx func. nlevels = 1 end return function(...) return unwrap_python_result(1 + nlevels, func(...)) end end -- -- Python methods don't want explicit 'self' argument; -- this decorator adds a dummy 'self' argument to allow Lua -- methods syntax. -- local function drops_self_argument(func) return function(self, ...) return func(...) end end -- -- A decorator that fixes an issue with passing callbacks from Lua to Python -- by putting the callback to a table provided by the caller. -- See https://github.com/scoder/lupa/pull/49 for more. -- local function sets_callback(func, storage) return function(cb, ...) storage[1] = cb return func(...) end end local PRIVATE_PREFIX = "private_" local function is_private_name(key) return string.find(key, "^" .. PRIVATE_PREFIX) ~= nil end -- -- Create a Lua wrapper for a Python object. -- -- * Lua methods are created for Python methods wrapped in @command. -- * Async methods are wrapped with `coroutine.yield`. -- * Lua <-> Python error handling is fixed. -- * Private methods are stored in `private_self`, public methods are -- stored in `self`. -- local function setup_commands(py_object, self, private_self) -- Create lua_object:<...> methods from py_object methods: for key, opts in pairs(py_object.commands) do local command = py_object[key] if opts.sets_callback then command = sets_callback(command, py_object.tmp_storage) end command = drops_self_argument(command) local nlevels = 1 if is_private_name(key) then -- private functions are wrapped, so nlevels is set to 2 to show error -- line number in user code nlevels = 2 end command = unwraps_python_result(command, nlevels) if is_private_name(key) then local short_key = string.sub(key, PRIVATE_PREFIX:len() + 1) private_self[short_key] = command else -- avoid custom setter rawset(self, key, command) end end end -- -- Handle @lua_property decorators. -- local function setup_property_access(py_object, self, cls) rawset(self, '__getters', {}) rawset(self, '__setters', {}) for name, opts in pairs(py_object.lua_properties) do self.__getters[name] = unwraps_python_result(drops_self_argument(py_object[opts.getter])) if opts.setter ~= nil then self.__setters[name] = unwraps_python_result(drops_self_argument(py_object[opts.setter])) else self.__setters[name] = function() error("Attribute " .. name .. " is read-only.", 2) end end end end -- -- Create a Lua wrapper for a Python object. -- local function wrap_exposed_object(py_object, self, cls, private_self) setmetatable(self, cls) setup_commands(py_object, self, private_self) setup_property_access(py_object, self, cls) end -- -- Return a metatable for a wrapped Python object -- local function create_metatable() local cls = { __wrapped = true } return cls end -- -- Return true if an object is a wrapped Python object -- local function is_wrapped(obj) local mt = getmetatable(obj) if type(mt) ~= 'table' then return false end return mt.__wrapped == true end -- -- Set metamethods for accessing custom getters and setters -- -- FIXME: move this function to `create_metatable` function local function set_metamethods(cls) cls.__index = function(self, index) if self.__getters[index] then return self.__getters[index](self) else return rawget(cls, index) end end cls.__newindex = function(self, index, value) if self.__setters[index] then return self.__setters[index](self, value) else return rawset(self, index, value) end end end -- Exposed API return { assertx = assertx, unwraps_python_result = unwraps_python_result, drops_self_argument = drops_self_argument, raises_async = raises_async, yields_result = yields_result, sets_callback = sets_callback, is_private_name = is_private_name, setup_commands = setup_commands, setup_property_access = setup_property_access, wrap_exposed_object = wrap_exposed_object, create_metatable = create_metatable, set_metamethods = set_metamethods, is_wrapped = is_wrapped, }
add FIXME
add FIXME
Lua
bsd-3-clause
pawelmhm/splash,pawelmhm/splash,pawelmhm/splash
309bd27e0d4d4df4e85ba76f44ff13f955017fb3
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 <[email protected]> Copyright 2008 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local 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 <[email protected]> Copyright 2008 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local 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 git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@4042 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
ThingMesh/openwrt-luci,8devices/carambola2-luci,vhpham80/luci,gwlim/luci,yeewang/openwrt-luci,alxhh/piratenluci,gwlim/luci,vhpham80/luci,phi-psi/luci,eugenesan/openwrt-luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,gwlim/luci,8devices/carambola2-luci,jschmidlapp/luci,phi-psi/luci,jschmidlapp/luci,stephank/luci,freifunk-gluon/luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,dtaht/cerowrt-luci-3.3,alxhh/piratenluci,yeewang/openwrt-luci,projectbismark/luci-bismark,ThingMesh/openwrt-luci,Flexibity/luci,freifunk-gluon/luci,jschmidlapp/luci,eugenesan/openwrt-luci,stephank/luci,eugenesan/openwrt-luci,Flexibity/luci,projectbismark/luci-bismark,yeewang/openwrt-luci,alxhh/piratenluci,eugenesan/openwrt-luci,dtaht/cerowrt-luci-3.3,phi-psi/luci,jschmidlapp/luci,eugenesan/openwrt-luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,zwhfly/openwrt-luci,stephank/luci,gwlim/luci,alxhh/piratenluci,projectbismark/luci-bismark,Flexibity/luci,8devices/carambola2-luci,saraedum/luci-packages-old,projectbismark/luci-bismark,projectbismark/luci-bismark,phi-psi/luci,saraedum/luci-packages-old,dtaht/cerowrt-luci-3.3,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,gwlim/luci,phi-psi/luci,eugenesan/openwrt-luci,saraedum/luci-packages-old,Canaan-Creative/luci,alxhh/piratenluci,zwhfly/openwrt-luci,freifunk-gluon/luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci,gwlim/luci,dtaht/cerowrt-luci-3.3,Flexibity/luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,vhpham80/luci,alxhh/piratenluci,8devices/carambola2-luci,ch3n2k/luci,ch3n2k/luci,Canaan-Creative/luci,ch3n2k/luci,ch3n2k/luci,Canaan-Creative/luci,saraedum/luci-packages-old,zwhfly/openwrt-luci,yeewang/openwrt-luci,yeewang/openwrt-luci,gwlim/luci,ThingMesh/openwrt-luci,stephank/luci,Canaan-Creative/luci,saraedum/luci-packages-old,freifunk-gluon/luci,zwhfly/openwrt-luci,phi-psi/luci,zwhfly/openwrt-luci,jschmidlapp/luci,vhpham80/luci,projectbismark/luci-bismark,ch3n2k/luci,zwhfly/openwrt-luci,dtaht/cerowrt-luci-3.3,Flexibity/luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,Flexibity/luci,phi-psi/luci,vhpham80/luci,projectbismark/luci-bismark,freifunk-gluon/luci,yeewang/openwrt-luci,Canaan-Creative/luci,stephank/luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,alxhh/piratenluci,Canaan-Creative/luci,freifunk-gluon/luci,8devices/carambola2-luci,stephank/luci,dtaht/cerowrt-luci-3.3,ThingMesh/openwrt-luci,saraedum/luci-packages-old,jschmidlapp/luci,projectbismark/luci-bismark,8devices/carambola2-luci,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,Flexibity/luci,Canaan-Creative/luci,saraedum/luci-packages-old
80581dc1e7722459086e0888fc05fa596f557c11
src/servicebag/src/Shared/ServiceBag.lua
src/servicebag/src/Shared/ServiceBag.lua
--- -- @classmod ServiceBag -- @author Quenty local require = require(script.Parent.loader).load(script) local Signal = require("Signal") local BaseObject = require("BaseObject") local ServiceBag = setmetatable({}, BaseObject) ServiceBag.ClassName = "ServiceBag" ServiceBag.__index = ServiceBag -- parentProvider is optional function ServiceBag.new(parentProvider) local self = setmetatable(BaseObject.new(), ServiceBag) self._services = {} self._parentProvider = parentProvider self._serviceTypesToInitializeSet = {} self._initializedServiceTypeSet = {} self._initializing = false self._serviceTypesToStart = {} self._destroying = Signal.new() self._maid:GiveTask(self._destroying) return self end function ServiceBag.isServiceBag(serviceBag) return type(serviceBag) == "table" and serviceBag.ClassName == "ServiceBag" end function ServiceBag:GetService(serviceType) if typeof(serviceType) == "Instance" then serviceType = require(serviceType) end local service = self._services[serviceType] if service then self:_ensureInitialization(serviceType) return self._services[serviceType] else if self._parentProvider then return self._parentProvider:GetService(serviceType) end -- Try to add the service if we're still initializing services self:_addServiceType(serviceType) self:_ensureInitialization(serviceType) return self._services[serviceType] end end function ServiceBag:HasService(serviceType) if self._services[serviceType] then return true else return false end end function ServiceBag:Init() assert(not self._initializing, "Already initializing") assert(self._serviceTypesToInitializeSet, "Already initialized") self._initializing = true while next(self._serviceTypesToInitializeSet) do local serviceType = next(self._serviceTypesToInitializeSet) self._serviceTypesToInitializeSet[serviceType] = nil self:_ensureInitialization(serviceType) end self._serviceTypesToInitializeSet = nil self._initializing = false end function ServiceBag:Start() assert(self._serviceTypesToStart, "Already started") assert(not self._initializing, "Still initializing") while next(self._serviceTypesToStart) do local serviceType = table.remove(self._serviceTypesToStart) local service = assert(self._services[serviceType], "No service") if service.Start then service:Start() end end self._serviceTypesToStart = nil end function ServiceBag:CreateScope() local provider = ServiceBag.new(self) self:_addServiceType(provider) -- Remove from parent provider self._maid[provider] = provider._destroying:Connect(function() self._maid[provider] = nil self._services[provider] = nil end) return provider end --- Adds a service to this provider only function ServiceBag:_addServiceType(serviceType) if not self._serviceTypesToInitializeSet then error(("Already finished initializing, cannot add %q"):format(tostring(serviceType))) return end -- Already added if self._services[serviceType] then return end -- Construct a new version of this service so we're isolated local service = setmetatable({}, { __index = serviceType }) self._services[serviceType] = service self:_ensureInitialization(serviceType) end function ServiceBag:_ensureInitialization(serviceType) if self._initializedServiceTypeSet[serviceType] then return end if self._initializing then self._serviceTypesToInitializeSet[serviceType] = nil self._initializedServiceTypeSet[serviceType] = true self:_initService(serviceType) elseif self._serviceTypesToInitializeSet then self._serviceTypesToInitializeSet[serviceType] = true else error("[ServiceBag._ensureInitialization] - Cannot initialize past initializing phase ") end end function ServiceBag:_initService(serviceType) local service = assert(self._services[serviceType], "No service") if service.Init then service:Init(self) end table.insert(self._serviceTypesToStart, serviceType) end function ServiceBag:Destroy() local super = getmetatable(ServiceBag) self._destroying:Fire() local services = self._services local key, service = next(services) while service ~= nil do services[key] = nil if service.Destroy then service:Destroy() end key, service = next(services) end super.Destroy(self) end return ServiceBag
--- -- @classmod ServiceBag -- @author Quenty local require = require(script.Parent.loader).load(script) local Signal = require("Signal") local BaseObject = require("BaseObject") local ServiceBag = setmetatable({}, BaseObject) ServiceBag.ClassName = "ServiceBag" ServiceBag.__index = ServiceBag -- parentProvider is optional function ServiceBag.new(parentProvider) local self = setmetatable(BaseObject.new(), ServiceBag) self._services = {} self._parentProvider = parentProvider self._serviceTypesToInitializeSet = {} self._initializedServiceTypeSet = {} self._initializing = false self._serviceTypesToStart = {} self._destroying = Signal.new() self._maid:GiveTask(self._destroying) return self end function ServiceBag.isServiceBag(serviceBag) return type(serviceBag) == "table" and serviceBag.ClassName == "ServiceBag" end function ServiceBag:GetService(serviceType) if typeof(serviceType) == "Instance" then serviceType = require(serviceType) end assert(type(serviceType) == "table", "Bad serviceType definition") local service = self._services[serviceType] if service then self:_ensureInitialization(serviceType) return self._services[serviceType] else if self._parentProvider then return self._parentProvider:GetService(serviceType) end -- Try to add the service if we're still initializing services self:_addServiceType(serviceType) self:_ensureInitialization(serviceType) return self._services[serviceType] end end function ServiceBag:HasService(serviceType) if self._services[serviceType] then return true else return false end end function ServiceBag:Init() assert(not self._initializing, "Already initializing") assert(self._serviceTypesToInitializeSet, "Already initialized") self._initializing = true while next(self._serviceTypesToInitializeSet) do local serviceType = next(self._serviceTypesToInitializeSet) self._serviceTypesToInitializeSet[serviceType] = nil self:_ensureInitialization(serviceType) end self._serviceTypesToInitializeSet = nil self._initializing = false end function ServiceBag:Start() assert(self._serviceTypesToStart, "Already started") assert(not self._initializing, "Still initializing") while next(self._serviceTypesToStart) do local serviceType = table.remove(self._serviceTypesToStart) local service = assert(self._services[serviceType], "No service") if service.Start then service:Start() end end self._serviceTypesToStart = nil end function ServiceBag:CreateScope() local provider = ServiceBag.new(self) self:_addServiceType(provider) -- Remove from parent provider self._maid[provider] = provider._destroying:Connect(function() self._maid[provider] = nil self._services[provider] = nil end) return provider end --- Adds a service to this provider only function ServiceBag:_addServiceType(serviceType) if not self._serviceTypesToInitializeSet then error(("Already finished initializing, cannot add %q"):format(tostring(serviceType))) return end -- Already added if self._services[serviceType] then return end -- Construct a new version of this service so we're isolated local service = setmetatable({}, { __index = serviceType }) self._services[serviceType] = service self:_ensureInitialization(serviceType) end function ServiceBag:_ensureInitialization(serviceType) if self._initializedServiceTypeSet[serviceType] then return end if self._initializing then self._serviceTypesToInitializeSet[serviceType] = nil self._initializedServiceTypeSet[serviceType] = true self:_initService(serviceType) elseif self._serviceTypesToInitializeSet then self._serviceTypesToInitializeSet[serviceType] = true else error("[ServiceBag._ensureInitialization] - Cannot initialize past initializing phase ") end end function ServiceBag:_initService(serviceType) local service = assert(self._services[serviceType], "No service") if service.Init then service:Init(self) end table.insert(self._serviceTypesToStart, serviceType) end function ServiceBag:Destroy() local super = getmetatable(ServiceBag) self._destroying:Fire() local services = self._services local key, service = next(services) while service ~= nil do services[key] = nil if service.Destroy then service:Destroy() end key, service = next(services) end super.Destroy(self) end return ServiceBag
fix: Better error messages
fix: Better error messages
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
d824f74ba25f0c19691eeb86aaa712250bd1b300
jet/socket.lua
jet/socket.lua
local ev = require'ev' local socket = require'socket' local cjson = require'cjson' require'pack' -- blends pack/unpack into string table local print = print local pairs = pairs local tinsert = table.insert local tconcat = table.concat local ipairs = ipairs local assert = assert local spack = string.pack local sunpack = string.unpack local error = error local log = print local pcall = pcall module('jet.socket') local wrap_sync = function(sock) assert(sock) local wrapped = {} sock:setoption('tcp-nodelay',true) wrapped.send = function(_,message_object) local json_message = cjson.encode(message_object) sock:send(spack('>I',#json_message)) sock:send(json_message) end wrapped.receive = function(_) local bin_len = sock:receive(4) local _,len = bin_len:unpack('>I') local json_message = sock:receive(len) return cjson.decode(json_message) end return wrapped end local wrap = function(sock,args) assert(sock) assert(args.on_close) assert(args.on_message) assert(args.on_error) assert(args.loop) -- set non blocking sock:settimeout(0) -- send message asap sock:setoption('tcp-nodelay',true) -- enable keep alive for detecting broken connections sock:setoption('keepalive',true) local on_message = args.on_message local on_close = args.on_close local on_error = args.on_error local encode = not args.dont_encode local decode = not args.dont_decode local loop = args.loop local send_buffer = '' local wrapped = {} local send_message = function(loop,write_io) local sent,err,sent_so_far = sock:send(send_buffer,pos) if sent then -- log('sent',#send_buffer,send_buffer:sub(5)) assert(sent==#send_buffer) send_buffer = '' write_io:stop(loop) elseif err == 'timeout' then log('sent timeout',pos) pos = sent_so_far elseif err == 'closed' then log('sent closed',pos) write_io:stop(loop) on_close(wrapped) else log('sent error',err) write_io:stop(loop) on_close(wrapped) log('unknown error:'..err) end end local fd = sock:getfd() assert(fd > -1) local send_io = ev.IO.new(send_message,fd,ev.WRITE) -- sends asynchronous the supplied message object -- -- the message format is 32bit big endian integer -- denoting the size of the JSON following wrapped.send = function(_,message) -- log('sending',cjson.encode(message)) if encode then message = cjson.encode(message) end -- assert(cjson.decode(message) ~= cjson.null) send_buffer = send_buffer..spack('>I',#message)..message if not send_io:is_active() then -- log('strting io') send_io:start(loop) end end wrapped.close = function() sock:shutdown() sock:close() end local read_io wrapped.read_io = function() if not read_io then local len local len_bin local json_message local _ local receive_message = function(loop,read_io) -- print('eee2') while true do if not len_bin or #len_bin < 4 then -- print('eee3') local err,sub len_bin,err,sub = sock:receive(4,len_bin) -- print(len_bin,err,sub) if len_bin then _,len = sunpack(len_bin,'>I') -- print(#len_bin,len,_) elseif err == 'timeout' then len_bin = sub return elseif err == 'closed' then read_io:stop(loop) on_close(wrapped) return else log('WTF?!',err) read_io:stop(loop) on_error(wrapped,err) end end if len then if len > 1000000 then local err = 'message too big:'..len..'bytes' print('jet.socket error',err) on_error(wrapped,err) read_io:stop(loop) sock:close() return end -- print('eee4',len) json_message,err,sub = sock:receive(len,json_message) if json_message then -- log('recv',len,json_message) if decode then local ok,message = pcall(cjson.decode,json_message) if ok then on_message(wrapped,message) else on_message(wrapped,nil,message) end else on_message(wrapped,json_message) end len = nil len_bin = nil json_message = nil elseif err == 'timeout' then json_message = sub return elseif err == 'closed' then read_io:stop(loop) on_close(wrapped) return else read_io:stop(loop) on_error(wrapped,err) return end end end -- print('eee5',len) end local fd = sock:getfd() assert(fd > -1) read_io = ev.IO.new(receive_message,fd,ev.READ) end return read_io end return wrapped end local mod = { wrap = wrap, wrap_sync = wrap_sync } return mod
local ev = require'ev' local socket = require'socket' local cjson = require'cjson' require'pack' -- blends pack/unpack into string table local print = print local pairs = pairs local tinsert = table.insert local tconcat = table.concat local ipairs = ipairs local assert = assert local spack = string.pack local sunpack = string.unpack local error = error local log = print local pcall = pcall module('jet.socket') local wrap_sync = function(sock) assert(sock) local wrapped = {} sock:setoption('tcp-nodelay',true) wrapped.send = function(_,message_object) local json_message = cjson.encode(message_object) sock:send(spack('>I',#json_message)) sock:send(json_message) end wrapped.receive = function(_) local bin_len = sock:receive(4) local _,len = bin_len:unpack('>I') local json_message = sock:receive(len) return cjson.decode(json_message) end return wrapped end local wrap = function(sock,args) assert(sock) assert(args.on_close) assert(args.on_message) assert(args.on_error) assert(args.loop) -- set non blocking sock:settimeout(0) -- send message asap sock:setoption('tcp-nodelay',true) -- enable keep alive for detecting broken connections sock:setoption('keepalive',true) local on_message = args.on_message local on_close = args.on_close local on_error = args.on_error local encode = not args.dont_encode local decode = not args.dont_decode local loop = args.loop local send_buffer = '' local wrapped = {} local send_pos local send_message = function(loop,write_io) local sent,err,sent_so_far = sock:send(send_buffer,send_pos) if sent then -- log('sent',#send_buffer,send_buffer:sub(5)) assert(sent==#send_buffer) send_buffer = '' write_io:stop(loop) elseif err == 'timeout' then log('sent timeout',send_pos) send_pos = sent_so_far elseif err == 'closed' then -- log('sent closed',pos) write_io:stop(loop) on_close(wrapped) else log('sent error',err) write_io:stop(loop) on_close(wrapped) log('unknown error:'..err) end end local fd = sock:getfd() assert(fd > -1) local send_io = ev.IO.new(send_message,fd,ev.WRITE) -- sends asynchronous the supplied message object -- -- the message format is 32bit big endian integer -- denoting the size of the JSON following wrapped.send = function(_,message) -- log('sending',cjson.encode(message)) if encode then message = cjson.encode(message) end -- assert(cjson.decode(message) ~= cjson.null) send_buffer = send_buffer..spack('>I',#message)..message send_pos = 0 if not send_io:is_active() then -- log('strting io') send_io:start(loop) end end wrapped.close = function() sock:shutdown() sock:close() end local read_io wrapped.read_io = function() if not read_io then local len local len_bin local json_message local _ local receive_message = function(loop,read_io) -- print('eee2') while true do if not len_bin or #len_bin < 4 then -- print('eee3') local err,sub len_bin,err,sub = sock:receive(4,len_bin) -- print(len_bin,err,sub) if len_bin then _,len = sunpack(len_bin,'>I') -- print(#len_bin,len,_) elseif err == 'timeout' then len_bin = sub return elseif err == 'closed' then read_io:stop(loop) on_close(wrapped) return else log('WTF?!',err) read_io:stop(loop) on_error(wrapped,err) end end if len then if len > 1000000 then local err = 'message too big:'..len..'bytes' print('jet.socket error',err) on_error(wrapped,err) read_io:stop(loop) sock:close() return end -- print('eee4',len) json_message,err,sub = sock:receive(len,json_message) if json_message then -- log('recv',len,json_message) if decode then local ok,message = pcall(cjson.decode,json_message) if ok then on_message(wrapped,message) else on_message(wrapped,nil,message) end else on_message(wrapped,json_message) end len = nil len_bin = nil json_message = nil elseif err == 'timeout' then json_message = sub return elseif err == 'closed' then read_io:stop(loop) on_close(wrapped) return else read_io:stop(loop) on_error(wrapped,err) return end end end -- print('eee5',len) end local fd = sock:getfd() assert(fd > -1) read_io = ev.IO.new(receive_message,fd,ev.READ) end return read_io end return wrapped end local mod = { wrap = wrap, wrap_sync = wrap_sync } return mod
bugfix unprobable send error
bugfix unprobable send error
Lua
mit
lipp/lua-jet
db83e9ede06dedf89112a7d9d76e185df90f6dba
classes/jplain.lua
classes/jplain.lua
-- Basic! Transitional! In development! Not very good! Don't use it! local plain = require("classes.plain") local jplain = pl.class(plain) jplain._name = "jplain" jplain.defaultFrameset.content = { left = "8.3%pw", top = "11.6%ph", gridsize = 10, linegap = 7, linelength = 50, linecount = 30 } function jplain:_j_common () self:loadPackage("font-fallback") self:loadPackage("hanmenkyoshi") self:registerPostinit(function (class) class:bidiDisableTypesetter(SILE.typesetter) class:bidiDisableTypesetter(SILE.defaultTypesetter) SILE.call("font:add-fallback", { family = "Noto Sans CJK JP" }) end) self.defaultFrameset.content.tate = self.options.layout == "tate" self:declareHanmenFrame("content", self.defaultFrameset.content) SILE.settings:set("document.parindent", SILE.nodefactory.glue("10pt")) end function jplain:_init (options) if self._legacy and not self._deprecated then return self:_deprecator(jplain) end plain._init(self, options) self:_j_common() return self end function jplain:declareOptions () plain.declareOptions(self) self:declareOption("layout", function (_, value) if value then self.layout = value if value == "tate" then self:loadPackage("tate") end end return self.layout end) end function jplain:setOptions (options) options.layout = options.layout or "yoko" plain.setOptions(self, options) end return jplain
-- Basic! Transitional! In development! Not very good! Don't use it! local plain = require("classes.plain") local jplain = pl.class(plain) jplain._name = "jplain" jplain.defaultFrameset.content = { left = "8.3%pw", top = "11.6%ph", gridsize = 10, linegap = 7, linelength = 50, linecount = 30 } function jplain:_j_common () self:loadPackage("font-fallback") self:loadPackage("hanmenkyoshi") self:registerPostinit(function (class) class:bidiDisableTypesetter(SILE.typesetter) class:bidiDisableTypesetter(SILE.defaultTypesetter) end) self.defaultFrameset.content.tate = self.options.layout == "tate" self:declareHanmenFrame("content", self.defaultFrameset.content) SILE.settings:set("document.parindent", SILE.nodefactory.glue("10pt")) if SILE.settings:get("document.language") ~= "ja" then SU.deprecated("document.language ≠ \"ja\" & jplain:…", nil, "0.13.2", "0.14.0", "Prior to SILE v0.13.2, `jplain`, despite its name, did not enforce the use of Japanese in its documents. To use a class like `jplain` for other languages, please base a *new* custom class off of `jplain`; do not use `jplain` itself. To use `jplain` for Japanese, you *must* specify \\language[main=ja]. This will become a hard error in SILE v0.14.") --[[ @alerque — Remove these lines post v0.14.0! ]] self:registerPostinit(function (_) SILE.call("font:add-fallback", { family = "Noto Sans CJK JP" }) end) SILE.settings:set("document.language", "ja") SILE.languageSupport.loadLanguage("ja") end end function jplain:_init (options) if self._legacy and not self._deprecated then return self:_deprecator(jplain) end plain._init(self, options) self:_j_common() return self end function jplain:declareOptions () plain.declareOptions(self) self:declareOption("layout", function (_, value) if value then self.layout = value if value == "tate" then self:loadPackage("tate") end end return self.layout end) end function jplain:setOptions (options) options.layout = options.layout or "yoko" plain.setOptions(self, options) end return jplain
fix(classes): Clarify the scopes of `tate` and `jplain`
fix(classes): Clarify the scopes of `tate` and `jplain` As I've been attempting to enforce through my commits, counter to how Simon did things initially: * `tate` and `ruby`: General purpose libraries that *should not be loading any fonts* or *assuming a Japanese document*. * `jplain`: The Japanese language class, *may* enforce `\language[main=ja]` but I didn't for backwards compatibility.
Lua
mit
alerque/sile,alerque/sile,alerque/sile,alerque/sile
05f293a0c0467f63975172e25dfe2f2cb92e71a6
test/test.lua
test/test.lua
#!/usr/bin/env lua addonData = { ["Version"] = "1.0", } require "wowTest" test.outFileName = "testOut.xml" -- Figure out how to parse the XML here, until then.... GoldRate_Frame = CreateFrame() --SendMailNameEditBox = CreateFontString("SendMailNameEditBox") -- require the file to test package.path = "../src/?.lua;'" .. package.path require "GoldRate" -- addon setup function test.before() GoldRate.OnLoad() GoldRate.ADDON_LOADED() myCopper = 150000 end function test.after() end function test.testCommand_Blank() -- These are here basicly to assure that the command does not error GoldRate.Command( "" ) end function test.testCommand_Help() -- These are here basicly to assure that the command does not error GoldRate.Command( "help" ) end function test.testCapture_SetsRealm() GoldRate.PLAYER_MONEY() assertTrue( GoldRate_data.testRealm ) end function test.testCapture_SetsName() GoldRate.PLAYER_MONEY() assertTrue( GoldRate_data.testRealm.testPlayer ) end function test.testCapture_GoldAmount_PlayerMoney_Last() -- Assert that PLAYER_MONEY event takes a snapshot of the current toon's money amount local now = time() GoldRate.PLAYER_MONEY() -- Capture the amount assertEquals( 150000, GoldRate_data.testRealm.testPlayer["last"] ) end function test.testCapture_GoldAmount_PlayerMoney_TimeStamp() -- Assert that PLAYER_MONEY event takes a snapshot of the current toon's money amount local now = time() GoldRate.PLAYER_MONEY() -- Capture the amount assertEquals( 150000, GoldRate_data.testRealm.testPlayer[now] ) end function test.testCapture_GoldAmount_EnteringWorld_Last() -- Assert that PLAYER_MONEY event takes a snapshot of the current toon's money amount local now = time() GoldRate.PLAYER_ENTERING_WORLD() -- Capture the amount assertEquals( 150000, GoldRate_data.testRealm.testPlayer["last"] ) end function test.testCapture_GoldAmount_EnteringWorld_TimeStamp() -- Assert that PLAYER_MONEY event takes a snapshot of the current toon's money amount local now = time() GoldRate.PLAYER_ENTERING_WORLD() -- Capture the amount assertEquals( 150000, GoldRate_data.testRealm.testPlayer[now] ) end test.run()
#!/usr/bin/env lua addonData = { ["Version"] = "1.0", } require "wowTest" test.outFileName = "testOut.xml" -- Figure out how to parse the XML here, until then.... GoldRate_Frame = CreateFrame() --SendMailNameEditBox = CreateFontString("SendMailNameEditBox") -- require the file to test package.path = "../src/?.lua;'" .. package.path require "GoldRate" -- addon setup function test.before() GoldRate.OnLoad() GoldRate.ADDON_LOADED() myCopper = 150000 end function test.after() end function test.testCommand_Blank() -- These are here basicly to assure that the command does not error GoldRate.Command( "" ) end function test.testCommand_Help() -- These are here basicly to assure that the command does not error GoldRate.Command( "help" ) end function test.testCapture_SetsRealm() GoldRate.PLAYER_MONEY() assertTrue( GoldRate_data.testRealm ) end function test.testCapture_SetsFaction() GoldRate.PLAYER_MONEY() assertTrue( GoldRate_data.testRealm.Alliance ) end function test.testCapture_SetsName() GoldRate.PLAYER_MONEY() assertTrue( GoldRate_data.testRealm.Alliance.testPlayer ) end function test.testCapture_GoldAmount_PlayerMoney_Last() -- Assert that PLAYER_MONEY event takes a snapshot of the current toon's money amount local now = time() GoldRate.PLAYER_MONEY() -- Capture the amount assertEquals( 150000, GoldRate_data.testRealm.Alliance.testPlayer["last"] ) end function test.testCapture_GoldAmount_PlayerMoney_TimeStamp() -- Assert that PLAYER_MONEY event takes a snapshot of the current toon's money amount local now = time() GoldRate.PLAYER_MONEY() -- Capture the amount assertEquals( 150000, GoldRate_data.testRealm.Alliance.testPlayer[now] ) end function test.testCapture_GoldAmount_EnteringWorld_Last() -- Assert that PLAYER_MONEY event takes a snapshot of the current toon's money amount local now = time() GoldRate.PLAYER_ENTERING_WORLD() -- Capture the amount assertEquals( 150000, GoldRate_data.testRealm.Alliance.testPlayer["last"] ) end function test.testCapture_GoldAmount_EnteringWorld_TimeStamp() -- Assert that PLAYER_MONEY event takes a snapshot of the current toon's money amount local now = time() GoldRate.PLAYER_ENTERING_WORLD() -- Capture the amount assertEquals( 150000, GoldRate_data.testRealm.Alliance.testPlayer[now] ) end test.run()
Fixing tests for faction
Fixing tests for faction
Lua
mit
opussf/GoldRate,opussf/GoldRate