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
|
---|---|---|---|---|---|---|---|---|---|
36c844c8839e2afc134913803a71fad41ff305e6
|
src/plugins/core/tangent/manager/action.lua
|
src/plugins/core/tangent/manager/action.lua
|
--- === plugins.core.tangent.manager.action ===
---
--- Represents a Tangent Action
local require = require
local is = require "cp.is"
local prop = require "cp.prop"
local x = require "cp.web.xml"
local named = require "named"
local format = string.format
local action = named:subclass "core.tangent.manager.action"
--- plugins.core.tangent.manager.action(id[, name[, parent[, localActive]]]) -> action
--- Constructor
--- Creates a new `Action` instance.
---
--- Parameters:
--- * id - The ID number of the action.
--- * name - The name of the action.
--- * parent - The parent group. (optional)
--- * localActive - If set to `true`, the parent's `active` state will be ignored when determining if this action is active. Defaults to `false`.
---
--- Returns:
--- * the new `action`.
function action:initialize(id, name, parent, localActive)
named.initialize(self, id, name, parent)
self._localActive = localActive
end
--- plugins.core.tangent.manager.action.localActive <cp.prop: boolean>
--- Field
--- Indicates if the action should ignore the parent's `enabled` state when determining if the action is active.
function action.lazy.prop:localActive()
return prop.THIS(self._localActive == true)
end
--- plugin.core.tangent.manager.action.active <cp.prop: boolean; read-only>
--- Field
--- Indicates if the action is active. It will only be active if
--- the current action is `enabled` and if the parent group (if present) is `active`.
function action.lazy.prop:active()
local parent = self:parent()
return parent and prop.AND(self.localActive:OR(parent.active), self.enabled) or self.enabled:IMMUTABLE()
end
--- plugins.core.tangent.manager.action.is() -> boolean
--- Method
--- Is an object an action?
---
--- Parameters:
--- * otherThing - Object to test.
---
--- Returns:
--- * `true` if the object is an action otherwise `false`.
function action.static.is(thing)
return type(thing) == "table" and thing.isInstanceOf ~= nil and thing:isInstanceOf(action)
end
--- plugins.core.tangent.manager.action:onPress(pressFn) -> self
--- Method
--- Sets the function that will be called when the Tangent sends a 'action on' request.
--- This function should have this signature:
---
--- `function() -> nil`
---
--- Parameters:
--- * pressFn - The function to call when the Tangent requests the action on.
---
--- Returns:
--- * The `parameter` instance.
function action:onPress(pressFn)
if is.nt.callable(pressFn) then
error(format("Please provide a function: %s", type(pressFn)))
end
self._press = pressFn
return self
end
--- plugins.core.tangent.manager.parameter:press() -> nil
--- Method
--- Executes the `press` function, if present.
---
--- Parameters:
--- * None
---
--- Returns:
--- * `nil`
function action:press()
if self._press and self:active() then
self._press()
end
end
--- plugins.core.tangent.manager.action:onRelease(releaseFn) -> self
--- Method
--- Sets the function that will be called when the Tangent sends a 'action off' request.
--- This function should have this signature:
---
--- `function() -> nil`
---
--- Parameters:
--- * releaseFn - The function to call when the Tangent requests the action off.
---
--- Returns:
--- * The `parameter` instance.
function action:onRelease(releaseFn)
if is.nt.fn(releaseFn) then
error("Please provide a function: %s", type(releaseFn))
end
self._release = releaseFn
return self
end
--- plugins.core.tangent.manager.parameter:release() -> nil
--- Method
--- Executes the `release` function, if present.
---
--- Parameters:
--- * None
---
--- Returns:
--- * `nil`
function action:release()
if self._release and self:active() then
self._release()
end
end
--- plugins.core.tangent.manager.action:xml() -> cp.web.xml
--- Method
--- Returns the `xml` configuration for the Action.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `xml` for the Action.
function action:xml()
return x.Action { id=format("%#010x", self.id) } (
named.xml(self)
)
end
function action:__tostring()
return format("action: %s (%#010x)", self:name(), self.id)
end
return action
|
--- === plugins.core.tangent.manager.action ===
---
--- Represents a Tangent Action
local require = require
local is = require "cp.is"
local prop = require "cp.prop"
local x = require "cp.web.xml"
local named = require "named"
local format = string.format
local action = named:subclass "core.tangent.manager.action"
--- plugins.core.tangent.manager.action(id[, name[, parent[, localActive]]]) -> action
--- Constructor
--- Creates a new `Action` instance.
---
--- Parameters:
--- * id - The ID number of the action.
--- * name - The name of the action.
--- * parent - The parent group. (optional)
--- * localActive - If set to `true`, the parent's `active` state will be ignored when determining if this action is active. Defaults to `false`.
---
--- Returns:
--- * the new `action`.
function action:initialize(id, name, parent, localActive)
named.initialize(self, id, name, parent)
self._localActive = localActive
end
--- plugins.core.tangent.manager.action.localActive <cp.prop: boolean>
--- Field
--- Indicates if the action should ignore the parent's `enabled` state when determining if the action is active.
function action.lazy.prop:localActive()
return prop.THIS(self._localActive == true)
end
--- plugin.core.tangent.manager.action.active <cp.prop: boolean; read-only>
--- Field
--- Indicates if the action is active. It will only be active if
--- the current action is `enabled` and if the parent group (if present) is `active`.
function action.lazy.prop:active()
local parent = self:parent()
return parent and prop.AND(self.localActive:OR(parent.active), self.enabled) or self.enabled:IMMUTABLE()
end
--- plugins.core.tangent.manager.action.is() -> boolean
--- Method
--- Is an object an action?
---
--- Parameters:
--- * otherThing - Object to test.
---
--- Returns:
--- * `true` if the object is an action otherwise `false`.
function action.static.is(thing)
return type(thing) == "table" and thing.isInstanceOf ~= nil and thing:isInstanceOf(action)
end
--- plugins.core.tangent.manager.action:onPress(pressFn) -> self
--- Method
--- Sets the function that will be called when the Tangent sends a 'action on' request.
--- This function should have this signature:
---
--- `function() -> nil`
---
--- Parameters:
--- * pressFn - The function to call when the Tangent requests the action on.
---
--- Returns:
--- * The `parameter` instance.
function action:onPress(pressFn)
if pressFn and is.nt.callable(pressFn) then
error(format("Please provide a function: %s", type(pressFn)), 2)
end
self._press = pressFn
return self
end
--- plugins.core.tangent.manager.parameter:press() -> nil
--- Method
--- Executes the `press` function, if present.
---
--- Parameters:
--- * None
---
--- Returns:
--- * `nil`
function action:press()
if self._press and self:active() then
self._press()
end
end
--- plugins.core.tangent.manager.action:onRelease(releaseFn) -> self
--- Method
--- Sets the function that will be called when the Tangent sends a 'action off' request.
--- This function should have this signature:
---
--- `function() -> nil`
---
--- Parameters:
--- * releaseFn - The function to call when the Tangent requests the action off.
---
--- Returns:
--- * The `parameter` instance.
function action:onRelease(releaseFn)
if releaseFn and is.nt.fn(releaseFn) then
error(format("Please provide a function: %s", type(releaseFn)), 2)
end
self._release = releaseFn
return self
end
--- plugins.core.tangent.manager.parameter:release() -> nil
--- Method
--- Executes the `release` function, if present.
---
--- Parameters:
--- * None
---
--- Returns:
--- * `nil`
function action:release()
if self._release and self:active() then
self._release()
end
end
--- plugins.core.tangent.manager.action:xml() -> cp.web.xml
--- Method
--- Returns the `xml` configuration for the Action.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `xml` for the Action.
function action:xml()
return x.Action { id=format("%#010x", self.id) } (
named.xml(self)
)
end
function action:__tostring()
return format("action: %s (%#010x)", self:name(), self.id)
end
return action
|
* Fixed bug in error handling in `action`.
|
* Fixed bug in error handling in `action`.
|
Lua
|
mit
|
CommandPost/CommandPost,CommandPost/CommandPost,fcpxhacks/fcpxhacks,fcpxhacks/fcpxhacks,CommandPost/CommandPost
|
2010c907d73dcfc093180637d910c30684c22715
|
mods/mff/mff_quests/init.lua
|
mods/mff/mff_quests/init.lua
|
mff.quests = {}
mff.QPREFIX = "mff_quests:"
mff.QNOPREFIX = function(s) return s:sub(mff.QPREFIX:len()+1) end
mff.quests.quests = {
still_testing_quests = {
title = "Stone digger",
description = "TEST QUEST!\nGet a Super Apple at the end!",
repeating = 60*60*24,
awards = {["maptools:superapple"] = 1},
tasks = {
diggy = {
title = "Dig 99 stone",
description = "Show you can dig through stone",
max = 99,
objective = {
dig = {"default:stone"}
}
},
diggysrevenge = {
title = "Dig the last stone",
description = "You really thought 99 was a good number? Dig the last one.",
requires = {"diggy"},
max = 1,
objective = {
dig = {"default:stone"}
}
}
}
},
still_testing_quests2 = {
title = "Coal digger",
description = "TEST QUEST!\nGet a Diamond at the end!",
repeating = 60*60*24,
awards = {["default:diamond"] = 1},
tasks = {
diggy = {
title = "Dig 19 coal",
description = "Get the fire mineral",
max = 19,
objective = {
dig = {"default:stone_with_coal"}
}
},
diggysrevenge = {
title = "Dig the last one",
description = "I do this because of a technical issue, sorry",
requires = {"diggy"},
max = 1,
objective = {
dig = {"default:stone_with_coal"}
}
}
}
},
still_testing_quests3 = {
title = "Shiny diamonds",
description = "TEST QUEST!\nGet a mithril ingot at the end!",
repeating = 60*60*24,
awards = {["moreores:mithril_ingot"] = 1},
tasks = {
diggy = {
title = "Dig 4 diamond",
description = "Yarr harr fiddle dee-dee, being a pirate is alright with me! Do what you want 'cause a pirate is free, you are a pirate! Go get the precious booty... underground. Mine it :/",
max = 4,
objective = {
dig = {"default:stone_with_diamond"}
}
},
diggysrevenge = {
title = "Ultimate calbon atom alignement",
description = "Really, we must fix this",
requires = {"diggy"},
max = 1,
objective = {
dig = {"default:stone_with_diamond"}
}
}
}
}
}
function table.contains(table, element)
for _, value in pairs(table) do
if value == element then
return true
end
end
return false
end
function mff.quests.start_quest(playername, qname, meta)
quests.start_quest(playername, mff.QPREFIX .. qname, meta)
end
function mff.quests.handle_quest_end(playername, questname, metadata)
for item, count in pairs(mff.quests.quests[mff.QNOPREFIX(questname)].awards) do
minetest.add_item(minetest.get_player_by_name(playername):getpos(), {name=item, count=count, wear=0, metadata=""})
end
end
-- Register the quests defined above
for qname, quest in pairs(mff.quests.quests) do
quest.completecallback = mff.quests.handle_quest_end
local ret = quests.register_quest(mff.QPREFIX .. qname, quest)
end
-- TODO
-- implement magical iterator, going through BOTH the simple quests
-- AND tasked quests objectives, returning a tuple like this:
-- questname, questdef, taskname (nil?), taskdef (nil?), objective_container (that is, either questdef or taskdef), pointer_to_function_to_update_the_objective_progress_with_only_one_parameter_the_others_being_automagically_passed_to_the_quests_API_so_that_we_dont_have_to_write_ifs_and_elses_everywhere_to_handle_both_quest_and_tasks_cases_because_it_would_give_crap_code
minetest.register_on_dignode(function(pos, oldnode, digger)
if not digger then return end
local pname = digger:get_player_name()
for qname, quest in pairs(mff.quests.quests) do
if quest.tasks then
for tname, task in pairs(quest.tasks) do
if quests.is_task_visible(pname, mff.QPREFIX .. qname, tname)
and not quests.is_task_disabled(pname, mff.QPREFIX .. qname, tname)
and task.objective.dig then
if table.contains(task.objective.dig, oldnode.name) then
quests.update_quest_task(pname, mff.QPREFIX .. qname, tname, 1)
end
end
end
end
end
end)
minetest.register_on_joinplayer(function (player)
local playername = player:get_player_name()
for _, qname in ipairs({"still_testing_quests", "still_testing_quests2", "still_testing_quests3"}) do
if not quests.quest_restarting_in(playername, mff.QPREFIX .. qname) then
mff.quests.start_quest(playername, qname)
end
end
end)
|
mff.quests = {}
mff.QPREFIX = "mff_quests:"
mff.QNOPREFIX = function(s) return s:sub(mff.QPREFIX:len()+1) end
mff.quests.quests = {
still_testing_quests = {
title = "Stone digger",
description = "TEST QUEST!\nGet a Super Apple at the end!",
repeating = 60*60*24,
awards = {["maptools:superapple"] = 1},
tasks = {
diggy = {
title = "Dig 99 stone",
description = "Show you can dig through stone",
max = 99,
objective = {
dig = {"default:stone"}
}
},
diggysrevenge = {
title = "Dig the last stone",
description = "You really thought 99 was a good number? Dig the last one.",
requires = {"diggy"},
max = 1,
objective = {
dig = {"default:stone"}
}
}
}
},
still_testing_quests2 = {
title = "Coal digger",
description = "TEST QUEST!\nGet a Diamond at the end!",
repeating = 60*60*24,
awards = {["default:diamond"] = 1},
tasks = {
diggy = {
title = "Dig 19 coal",
description = "Get the fire mineral",
max = 19,
objective = {
dig = {"default:stone_with_coal"}
}
},
diggysrevenge = {
title = "Dig the last one",
description = "I do this because of a technical issue, sorry",
requires = {"diggy"},
max = 1,
objective = {
dig = {"default:stone_with_coal"}
}
}
}
},
still_testing_quests3 = {
title = "Shiny diamonds",
description = "TEST QUEST!\nGet a mithril ingot at the end!",
repeating = 60*60*24,
awards = {["moreores:mithril_ingot"] = 1},
tasks = {
diggy = {
title = "Dig 4 diamond",
description = "Yarr harr fiddle dee-dee, being a pirate is alright with me! Do what you want 'cause a pirate is free, you are a pirate! Go get the precious booty... underground. Mine it :/",
max = 4,
objective = {
dig = {"default:stone_with_diamond"}
}
},
diggysrevenge = {
title = "Ultimate calbon atom alignement",
description = "Really, we must fix this",
requires = {"diggy"},
max = 1,
objective = {
dig = {"default:stone_with_diamond"}
}
}
}
}
}
function table.contains(table, element)
for _, value in pairs(table) do
if value == element then
return true
end
end
return false
end
function mff.quests.start_quest(playername, qname, meta)
quests.start_quest(playername, mff.QPREFIX .. qname, meta)
end
function mff.quests.handle_quest_end(playername, questname, metadata)
for item, count in pairs(mff.quests.quests[mff.QNOPREFIX(questname)].awards) do
local p = minetest.get_player_by_name(playername)
if p then
minetest.add_item(p:getpos(), {name=item, count=count, wear=0, metadata=""})
end
end
end
-- Register the quests defined above
for qname, quest in pairs(mff.quests.quests) do
quest.completecallback = mff.quests.handle_quest_end
local ret = quests.register_quest(mff.QPREFIX .. qname, quest)
end
-- TODO
-- implement magical iterator, going through BOTH the simple quests
-- AND tasked quests objectives, returning a tuple like this:
-- questname, questdef, taskname (nil?), taskdef (nil?), objective_container (that is, either questdef or taskdef), pointer_to_function_to_update_the_objective_progress_with_only_one_parameter_the_others_being_automagically_passed_to_the_quests_API_so_that_we_dont_have_to_write_ifs_and_elses_everywhere_to_handle_both_quest_and_tasks_cases_because_it_would_give_crap_code
minetest.register_on_dignode(function(pos, oldnode, digger)
if not digger then return end
local pname = digger:get_player_name()
for qname, quest in pairs(mff.quests.quests) do
if quest.tasks then
for tname, task in pairs(quest.tasks) do
if quests.is_task_visible(pname, mff.QPREFIX .. qname, tname)
and not quests.is_task_disabled(pname, mff.QPREFIX .. qname, tname)
and task.objective.dig then
if table.contains(task.objective.dig, oldnode.name) then
quests.update_quest_task(pname, mff.QPREFIX .. qname, tname, 1)
end
end
end
end
end
end)
minetest.register_on_joinplayer(function (player)
local playername = player:get_player_name()
for _, qname in ipairs({"still_testing_quests", "still_testing_quests2", "still_testing_quests3"}) do
if not quests.quest_restarting_in(playername, mff.QPREFIX .. qname) then
mff.quests.start_quest(playername, qname)
end
end
end)
|
Fix crash in mff's quests
|
Fix crash in mff's quests
|
Lua
|
unlicense
|
Ombridride/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Coethium/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,Coethium/server-minetestforfun,sys4-fr/server-minetestforfun,sys4-fr/server-minetestforfun,MinetestForFun/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,Coethium/server-minetestforfun,Ombridride/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server
|
371f9bb5afb96fa0518bb813df4d813a9716114e
|
frontend/ui/reader/readerpanning.lua
|
frontend/ui/reader/readerpanning.lua
|
ReaderPanning = InputContainer:new{
key_events = {
-- these will all generate the same event, just with different arguments
MoveUp = { {"Up"}, doc = "move focus up", event = "Panning", args = {0, -1} },
MoveDown = { {"Down"}, doc = "move focus down", event = "Panning", args = {0, 1} },
MoveLeft = { {"Left"}, doc = "move focus left", event = "Panning", args = {-1, 0} },
MoveRight = { {"Right"}, doc = "move focus right", event = "Panning", args = {1, 0} },
},
-- defaults
panning_steps = {
normal = 50,
alt = 25,
shift = 10,
altshift = 5
},
}
function ReaderPanning:onSetDimensions(dimensions)
self.dimen = dimensions
end
function ReaderPanning:onPanning(args, key)
local dx, dy = unpack(args)
DEBUG("key =", key)
-- for now, bounds checking/calculation is done in the view
self.view:PanningUpdate(
dx * self.panning_steps.normal * self.dimen.w / 100,
dy * self.panning_steps.normal * self.dimen.h / 100)
return true
end
|
ReaderPanning = InputContainer:new{
key_events = {
-- these will all generate the same event, just with different arguments
MoveUp = { {"Up"}, doc = "move visible area up", event = "Panning", args = {0, -1} },
MoveDown = { {"Down"}, doc = "move visible area down", event = "Panning", args = {0, 1} },
MoveLeft = { {"Left"}, doc = "move visible area left", event = "Panning", args = {-1, 0} },
MoveRight = { {"Right"}, doc = "move visible area right", event = "Panning", args = {1, 0} },
},
-- defaults
panning_steps = {
normal = 50,
alt = 25,
shift = 10,
altshift = 5
},
}
function ReaderPanning:onSetDimensions(dimensions)
self.dimen = dimensions
end
function ReaderPanning:onPanning(args, key)
local dx, dy = unpack(args)
DEBUG("key =", key)
-- for now, bounds checking/calculation is done in the view
self.view:PanningUpdate(
dx * self.panning_steps.normal * self.dimen.w / 100,
dy * self.panning_steps.normal * self.dimen.h / 100)
return true
end
|
fix doc for key events
|
fix doc for key events
|
Lua
|
agpl-3.0
|
houqp/koreader-base,NiLuJe/koreader-base,poire-z/koreader,Frenzie/koreader-base,frankyifei/koreader-base,Frenzie/koreader-base,robert00s/koreader,NiLuJe/koreader-base,Markismus/koreader,Hzj-jie/koreader,Frenzie/koreader,mihailim/koreader,apletnev/koreader-base,houqp/koreader-base,mwoz123/koreader,frankyifei/koreader-base,apletnev/koreader-base,chihyang/koreader,frankyifei/koreader-base,NiLuJe/koreader-base,frankyifei/koreader-base,apletnev/koreader-base,houqp/koreader,NiLuJe/koreader-base,NiLuJe/koreader,Hzj-jie/koreader-base,Frenzie/koreader,NiLuJe/koreader,pazos/koreader,Frenzie/koreader-base,houqp/koreader-base,Frenzie/koreader-base,NickSavage/koreader,lgeek/koreader,ashang/koreader,koreader/koreader,apletnev/koreader,poire-z/koreader,apletnev/koreader-base,frankyifei/koreader,Hzj-jie/koreader-base,koreader/koreader-base,koreader/koreader-base,Hzj-jie/koreader-base,chrox/koreader,Hzj-jie/koreader-base,houqp/koreader-base,ashhher3/koreader,koreader/koreader,koreader/koreader-base,noname007/koreader,koreader/koreader-base
|
32d85cfaaed2c69f84f0ef0fa18b76eb2360f63e
|
MTCompatto.lua
|
MTCompatto.lua
|
--[[
Tabella contenente le MT e le MN delle varie generazioni
Può essere chiamato con il nome della pagina
{{#invoke: MTCompatto | MTCompatto | {{BASEPAGENAME}} }}
oppure con il nome di una mossa
{{#invoke: MTCompatto | MTCompatto | Surf }}
oppure specificando le generazioni da mostrare
{{#invoke: MTCompatto | MTCompatto | 123 | tipo = pcwiki }}
Si può anche usare MTGen per avere la tabella di una sola generazione
{{#invoke: MTCompatto | MTGen | 4 | width = 65% }}
--]]
local m = {}
local mw = require('mw')
local w = require('Wikilib')
local tab = require('Wikilib-tables') -- luacheck: no unused
local txt = require('Wikilib-strings') -- luacheck: no unused
local multigen = require('Wikilib-multigen')
local links = require('AbbrLink')
local css = require('Css')
local machines = require("Machines-data")
local gens = require("Gens-data")
local moves = require("Move-data")
local strings = {
MAIN_BOX = [=[
<div class="roundy pull-center text-center mw-collapsible${collapsed} width-xl-55 width-md-75 width-sm-100" style="${bg} padding: 0.5ex; padding-bottom: 0.01ex;">
<div class="roundy text-center black-text" style="font-weight: bold; margin-bottom: 0.5ex;">[[MT]] nelle varie generazioni</div>
<div class="mw-collapsible-content">${mtGens}
</div></div>
[[Categoria:Mosse Macchina]]]=],
GEN_BOX = [=[
<div class="roundy text-center pull-center text-small" style="${bg} width: ${wd}; padding: 0.5ex; margin-bottom: 0.5ex;">
${listmt}${listmn}${listdt}
</div>]=],
LIST_BOX = [=[
<div class="black-text" style="margin-top: 2px; font-weight: bold;">[[${kind}]] di [[${gen} generazione]]</div>
<div class="${roundy}" style="background: #eaeaea; margin-bottom: 2px; padding: 0px 2px;">${list}</div>
]=],
}
--[[
A partire da una lista di MT/MN del Modulo:Machines/data,
ritorna una stringa che contiene i link a
tutte le mosse in essa contenuta
--]]
local makeMachinesList = function(list)
return table.concat(table.map(list, function(move, num)
num = string.format('%02d', num)
if type(move) == 'table' then
return string.interp('${num} (${games})',
{
num = num,
games = table.concat(table.map(move, function(movegame)
local games, move = movegame[1], movegame[2]
games = mw.text.split(games:upper(), ' ')
local keyGame = table.remove(games, 1)
return links[keyGame .. 'Lua']{games = games,
multigen.getGenValue(moves[move].name) }
end), ' | ')
})
else
return string.interp("[[${mv}|${num}]]",
{
mv = multigen.getGenValue(moves[move].name),
num = num
})
end
end), " | ")
end
--[[
Ritorna un div che contente le MT e MN
di una certa generazione.
width è opzionale, default 65%
--]]
local MTGen = function(gen, width)
return string.interp(strings.GEN_BOX,
{
bg = css.horizGradLua{type = gens[gen].region},
wd = width or "65%",
gen = gens[gen].ext,
listmt = string.interp(strings.LIST_BOX,
{
kind = "MT",
roundy = (machines[gen].MN or machines[gen].DT) and ''
or 'roundybottom',
list = makeMachinesList(machines[gen].MT),
gen = gens[gen].ext,
}),
listmn = machines[gen].MN and string.interp(strings.LIST_BOX,
{
kind = "MN",
roundy = "roundybottom",
list = makeMachinesList(machines[gen].MN),
gen = gens[gen].ext,
}) or '',
listdt = machines[gen].DT and string.interp(strings.LIST_BOX,
{
kind = "DT",
roundy = "roundybottom",
list = makeMachinesList(machines[gen].DT),
gen = gens[gen].ext,
}) or '',
})
end
--[[
Come il template MT compatto:
Prende in input il nome della pagina e restituisce la
tabella contenente le sottotabelle delle generazioni
in cui la mossa è un'MT o MN
--]]
m.MTCompatto = function(frame)
local params = w.trimAndMap(frame.args, string.lower)
local gens = {}
local color
local move = params[1] or mw.getCurrentTitle().text
local moveData = moves[move]
if not moveData then
move = mw.text.decode(move)
moveData = moves[move]
end
if moveData then
color = multigen.getGenValue(moveData.type)
for gen, genMc in ipairs(machines) do
if table.deepSearch(genMc, move) then
table.insert(gens, MTGen(gen, "auto"))
end
end
else
color = params.tipo or 'pcwiki'
gens = mw.text.split(params[1], '', true)
table.sort(gens)
gens = table.map(gens, function(gen)
return MTGen(tonumber(gen), "auto")
end)
end
return string.interp(strings.MAIN_BOX,
{
bg = css.horizGradLua{type = color},
collapsed = #gens > 1 and " mw-collapsed" or "",
mtGens = table.concat(gens)
})
end
m.MTGen = function(frame)
local params = w.trimAll(frame.args)
return MTGen(tonumber(params[1]), params.width) ..
"[[Categoria:Mosse Macchina]]"
end
return m
|
--[[
Tabella contenente le MT e le MN delle varie generazioni
Può essere chiamato con il nome della pagina
{{#invoke: MTCompatto | MTCompatto | {{BASEPAGENAME}} }}
oppure con il nome di una mossa
{{#invoke: MTCompatto | MTCompatto | Surf }}
oppure specificando le generazioni da mostrare
{{#invoke: MTCompatto | MTCompatto | 123 | tipo = pcwiki }}
Si può anche usare MTGen per avere la tabella di una sola generazione
{{#invoke: MTCompatto | MTGen | 4 | width = 65% }}
--]]
local m = {}
local mw = require('mw')
local w = require('Wikilib')
local tab = require('Wikilib-tables') -- luacheck: no unused
local txt = require('Wikilib-strings') -- luacheck: no unused
local multigen = require('Wikilib-multigen')
local links = require('AbbrLink')
local css = require('Css')
local machines = require("Machines-data")
local gens = require("Gens-data")
local moves = require("Move-data")
local strings = {
MAIN_BOX = [=[
<div class="roundy pull-center text-center mw-collapsible${collapsed} width-xl-55 width-md-75 width-sm-100" style="${bg} padding: 0.5ex; padding-bottom: 0.01ex;">
<div class="roundy text-center black-text" style="font-weight: bold; margin-bottom: 0.5ex;">[[MT]] nelle varie generazioni</div>
<div class="mw-collapsible-content">${mtGens}
</div></div>
[[Categoria:Mosse Macchina]]]=],
GEN_BOX = [=[
<div class="roundy text-center pull-center text-small" style="${bg} width: ${wd}; padding: 0.5ex; margin-bottom: 0.5ex;">
${listmt}${listmn}${listdt}
</div>]=],
LIST_BOX = [=[
<div class="black-text" style="margin-top: 2px; font-weight: bold;">[[${kind}]] di [[${gen} generazione]]</div>
<div class="${roundy}" style="background: #eaeaea; margin-bottom: 2px; padding: 0px 2px;">${list}</div>
]=],
}
--[[
A partire da una lista di MT/MN del Modulo:Machines/data,
ritorna una stringa che contiene i link a
tutte le mosse in essa contenuta
--]]
local makeMachinesList = function(list)
local mapped = table.map(list, function(move, num)
num = string.format('%02d', num)
if type(move) == 'table' then
return string.interp('${num} (${games})', {
num = num,
games = table.concat(table.map(move, function(movegame)
local games, locmove = movegame[1], movegame[2]
games = mw.text.split(games:upper(), ' ')
local keyGame = table.remove(games, 1)
return links[keyGame .. 'Lua']{games = games,
multigen.getGenValue(moves[locmove].name) }
end), ' | ')
})
else
return string.interp("[[${mv}|${num}]]", {
mv = multigen.getGenValue(moves[move].name),
num = num
})
end
end)
if mapped[0] then
return mapped[0] .. " | " .. table.concat(mapped, " | ")
else
return table.concat(mapped, " | ")
end
end
--[[
Ritorna un div che contente le MT e MN
di una certa generazione.
width è opzionale, default 65%
--]]
local MTGen = function(gen, width)
return string.interp(strings.GEN_BOX,
{
bg = css.horizGradLua{type = gens[gen].region},
wd = width or "65%",
gen = gens[gen].ext,
listmt = string.interp(strings.LIST_BOX,
{
kind = "MT",
roundy = (machines[gen].MN or machines[gen].DT) and ''
or 'roundybottom',
list = makeMachinesList(machines[gen].MT),
gen = gens[gen].ext,
}),
listmn = machines[gen].MN and string.interp(strings.LIST_BOX,
{
kind = "MN",
roundy = "roundybottom",
list = makeMachinesList(machines[gen].MN),
gen = gens[gen].ext,
}) or '',
listdt = machines[gen].DT and string.interp(strings.LIST_BOX,
{
kind = "DT",
roundy = "roundybottom",
list = makeMachinesList(machines[gen].DT),
gen = gens[gen].ext,
}) or '',
})
end
--[[
Come il template MT compatto:
Prende in input il nome della pagina e restituisce la
tabella contenente le sottotabelle delle generazioni
in cui la mossa è un'MT o MN
--]]
m.MTCompatto = function(frame)
local params = w.trimAndMap(frame.args, string.lower)
local gens = {}
local color
local move = params[1] or mw.getCurrentTitle().text
local moveData = moves[move]
if not moveData then
move = mw.text.decode(move)
moveData = moves[move]
end
if moveData then
color = multigen.getGenValue(moveData.type)
for gen, genMc in ipairs(machines) do
if table.deepSearch(genMc, move) then
table.insert(gens, MTGen(gen, "auto"))
end
end
else
color = params.tipo or 'pcwiki'
gens = mw.text.split(params[1], '', true)
table.sort(gens)
gens = table.map(gens, function(gen)
return MTGen(tonumber(gen), "auto")
end)
end
return string.interp(strings.MAIN_BOX,
{
bg = css.horizGradLua{type = color},
collapsed = #gens > 1 and " mw-collapsed" or "",
mtGens = table.concat(gens)
})
end
m.MTGen = function(frame)
local params = w.trimAll(frame.args)
return MTGen(tonumber(params[1]), params.width) ..
"[[Categoria:Mosse Macchina]]"
end
return m
|
Fixed MTCompatto bug that hided MT00 and DT00
|
Fixed MTCompatto bug that hided MT00 and DT00
|
Lua
|
cc0-1.0
|
pokemoncentral/wiki-lua-modules
|
c875d6d58e6b5edc7ceba4c8bbd05ae9aea3f299
|
vrp_mysql/MySQL.lua
|
vrp_mysql/MySQL.lua
|
-- begin MySQL module
local MySQL = {}
MySQL.debug = false
local dpaths = {}
local tasks = {}
--[[
local function tick()
SetTimeout(1, function() -- protect errors from breaking the loop
SetTimeout(1000, tick)
local rmtasks = {}
for id,cb in pairs(tasks) do
local r = exports.vrp_mysql:checkTask(id)
if r.status == 1 then
cb(r.rows,r.affected) -- rows, affected
table.insert(rmtasks, id)
elseif r.status == -1 then
print("[vRP] task "..id.." failed.")
table.insert(rmtasks, id)
end
end
-- remove done tasks
for k,v in pairs(rmtasks) do
tasks[v] = nil
end
end)
end
tick()
--]]
AddEventHandler("vRP:MySQL_task", function(task_id, data)
-- print("vRP:MySQL_task "..task_id)
local cb = tasks[task_id]
if cb then
if data.status == 1 then
cb(data.rows or {},data.affected or 0) -- rows, affected
elseif r.status == -1 then
print("[vRP] task "..id.." failed.")
end
if MySQL.debug then
print("[vRP] MySQL end query "..dpaths[task_id].." ("..task_id..")")
dpaths[task_id] = nil
end
tasks[task_id] = nil
end
end)
local task_id = -1
AddEventHandler("vRP:MySQL_taskid", function(_task_id)
-- print("vRP:MySQL_task "..task_id)
task_id = _task_id
end)
-- host can be "host" or "host:port"
function MySQL.createConnection(name,host,user,password,db,debug)
-- print("[vRP] try to create connection "..name)
-- parse port in host as "ip:port"
local host_parts = splitString(host,":")
if #host_parts >= 2 then
host = host_parts[1]..";port="..host_parts[2]
end
local config = "server="..host..";uid="..user..";pwd="..password..";database="..db..";"
-- TriggerEvent("vRP:MySQL:createConnection", name, config)
exports.vrp_mysql:createConnection(name, config)
end
function MySQL.createCommand(path, query)
-- print("[vRP] try to create command "..path)
-- TriggerEvent("vRP:MySQL:createCommand", path, query)
exports.vrp_mysql:createCommand(path, query)
end
function MySQL.query(path, args, cb)
-- TriggerEvent("vRP:MySQL:query", path, args)
if not (type(args) == "table") then
args = {}
end
-- force args to be a C# dictionary
args._none = " "
-- exports.vrp_mysql:query(path, args)
TriggerEvent("vRP:MySQL_query", path, args)
-- print("[vRP] try to query "..path.." id "..task_id)
if MySQL.debug then
print("[vRP] MySQL begin query "..path.." ("..task_id..")")
dpaths[task_id] = path
end
tasks[task_id] = cb
end
-- return module
return MySQL
|
-- begin MySQL module
local MySQL = {}
MySQL.debug = false
local dpaths = {}
local tasks = {}
--[[
local function tick()
SetTimeout(1, function() -- protect errors from breaking the loop
SetTimeout(1000, tick)
local rmtasks = {}
for id,cb in pairs(tasks) do
local r = exports.vrp_mysql:checkTask(id)
if r.status == 1 then
cb(r.rows,r.affected) -- rows, affected
table.insert(rmtasks, id)
elseif r.status == -1 then
print("[vRP] task "..id.." failed.")
table.insert(rmtasks, id)
end
end
-- remove done tasks
for k,v in pairs(rmtasks) do
tasks[v] = nil
end
end)
end
tick()
--]]
AddEventHandler("vRP:MySQL_task", function(task_id, data)
-- print("vRP:MySQL_task "..task_id)
local cb = tasks[task_id]
if cb then
if data.status == 1 then
cb(data.rows or {},data.affected or 0) -- rows, affected
elseif r.status == -1 then
print("[vRP] task "..id.." failed.")
end
tasks[task_id] = nil
end
if MySQL.debug and dpaths[task_id] then
print("[vRP] MySQL end query "..dpaths[task_id].." ("..task_id..")")
dpaths[task_id] = nil
end
end)
local task_id = -1
AddEventHandler("vRP:MySQL_taskid", function(_task_id)
-- print("vRP:MySQL_task "..task_id)
task_id = _task_id
end)
-- host can be "host" or "host:port"
function MySQL.createConnection(name,host,user,password,db,debug)
-- print("[vRP] try to create connection "..name)
-- parse port in host as "ip:port"
local host_parts = splitString(host,":")
if #host_parts >= 2 then
host = host_parts[1]..";port="..host_parts[2]
end
local config = "server="..host..";uid="..user..";pwd="..password..";database="..db..";"
-- TriggerEvent("vRP:MySQL:createConnection", name, config)
exports.vrp_mysql:createConnection(name, config)
end
function MySQL.createCommand(path, query)
-- print("[vRP] try to create command "..path)
-- TriggerEvent("vRP:MySQL:createCommand", path, query)
exports.vrp_mysql:createCommand(path, query)
end
function MySQL.query(path, args, cb)
-- TriggerEvent("vRP:MySQL:query", path, args)
if not (type(args) == "table") then
args = {}
end
-- force args to be a C# dictionary
args._none = " "
-- exports.vrp_mysql:query(path, args)
TriggerEvent("vRP:MySQL_query", path, args)
-- print("[vRP] try to query "..path.." id "..task_id)
if MySQL.debug then
print("[vRP] MySQL begin query "..path.." ("..task_id..")")
dpaths[task_id] = path
end
tasks[task_id] = cb
end
-- return module
return MySQL
|
Fix missing MySQL debug print.
|
Fix missing MySQL debug print.
|
Lua
|
mit
|
ImagicTheCat/vRP,ImagicTheCat/vRP
|
b59c90f98daf4c5c0c13aff1e0afb31d6ac15c87
|
lib/acid/redis_proxy.lua
|
lib/acid/redis_proxy.lua
|
local acid_json = require("acid.json")
local strutil = require("acid.strutil")
local tableutil = require("acid.tableutil")
local redis_chash = require("acid.redis_chash")
local aws_authenticator = require("resty.awsauth.aws_authenticator")
local _M = {}
local mt = { __index = _M }
local to_str = strutil.to_str
local ERR_CODE = {
NotFound = ngx.HTTP_NOT_FOUND,
InvalidRequest = ngx.HTTP_BAD_REQUEST,
InvalidCommand = ngx.HTTP_FORBIDDEN,
QuorumNotEnough = ngx.HTTP_SERVICE_UNAVAILABLE,
RequestForbidden = ngx.HTTP_FORBIDDEN,
InvalidSignature = ngx.HTTP_FORBIDDEN,
}
-- http method, redis opeartion, count of args, need value args, optional args name
local redis_cmd_model = {
-- get(key)
GET = {'GET', 'get', 1, false, {}},
-- set(key, val, expire=nil)
SET = {'PUT', 'set', 2, true, {'expire'}},
-- hget(hashname, hashkey)
HGET = {'GET', 'hget', 2, false, {}},
-- hset(hashname, hashkey, val, expire=nil)
HSET = {'PUT', 'hset', 3, true, {'expire'}},
}
local redis_cmd_names = tableutil.keys(redis_cmd_model)
local function get_secret_key(access_key, secret_key)
return function(ctx)
if ctx.access_key ~= access_key then
return nil, 'InvalidAccessKey', 'access key does not exists: ' .. ctx.access_key
end
return secret_key
end
end
local function check_auth(self)
if ngx.var.server_addr == '127.0.0.1'
or self.access_key == nil
or self.secret_key == nil then
return
end
local authenticator = aws_authenticator.new(self.get_secret_key)
local ctx, err_code, err_msg = authenticator:authenticate()
if err_code ~= nil then
ngx.log(ngx.INFO, err_code, ':', err_msg)
return nil, 'InvalidSignature', 'signature is not correct'
end
if ctx.anonymous == true then
return nil, 'RequestForbidden', 'anonymous user are not allowed'
end
end
local function output(rst, err_code, err_msg)
local status, body, headers = 200, '', {}
local request_id = ngx.var.requestid
if err_code ~= nil then
ngx.log( ngx.WARN, "requestid: ", request_id,
" err_code: ", err_code, " err_msg: ", err_msg )
status = ERR_CODE[err_code] or ngx.HTTP_BAD_REQUEST
headers["Content-Type"] = "application/json"
local Error = {
Code = err_code,
Message = err_msg,
RequestId = request_id,
}
body = acid_json.enc( Error )
else
rst = rst or {}
headers['X-REDIS-ADDR'] = rst.addr
body = rst.value or ''
end
ngx.header["request-id"] = ngx.var.requestid
headers['Content-Length'] = #body
ngx.status = status
for k, v in pairs(headers) do
ngx.header[k] = v
end
ngx.say(body)
ngx.eof()
ngx.exit(ngx.HTTP_OK)
end
local function read_cmd_value()
local headers = ngx.req.get_headers()
local content_length = tonumber(headers['content-length'])
if content_length == nil then
return nil, 'InvalidRequest', 'Content-Length is nil'
elseif content_length == 0 then
return ''
end
ngx.req.read_body()
local value = ngx.req.get_body_data()
if value == nil then
return nil, 'InvalidRequest', 'Invalid request body'
end
return value
end
local function get_cmd_args()
--local uri_ptr = '^/redisproxy/v\\d+/(\\S+)/(\\S+)$'
local uri_ptr = '^/redisproxy/v\\d+/(\\S+?)/(\\S+)$'
local urilist = ngx.re.match(ngx.var.uri, uri_ptr, 'o')
if urilist == nil then
return nil, 'InvalidRequest', 'uri must like:'.. uri_ptr
end
local cmd = urilist[1]
local cmd_args = strutil.split(urilist[2], '/')
local cmd_model = redis_cmd_model[cmd]
if cmd_model == nil then
return nil, 'InvalidCommand', to_str('just support: ', redis_cmd_names)
end
local http_method, cmd, nargs, needed_value, _ = unpack(cmd_model)
if http_method ~= ngx.var.request_method then
return nil, 'InvalidRequest',
to_str(cmd, ' cmd request method must be ', http_method)
end
if needed_value then
local cmd_val, err_code, err_msg = read_cmd_value()
if err_code ~= nil then
return nil, err_code, err_msg
end
table.insert(cmd_args, cmd_val)
end
if #(cmd_args) ~= nargs then
return nil, 'InvalidCommand', to_str(cmd, ' need ', nargs, ' args')
end
local qs = ngx.req.get_uri_args()
return {
cmd = cmd,
cmd_args = cmd_args,
expire = tonumber(qs.expire),
n = tonumber(qs.n) or 1,
w = tonumber(qs.w) or 1,
r = tonumber(qs.r) or 1,
}
end
function _M.new(_, access_key, secret_key, get_redis_servers, opts)
local obj = {
access_key = access_key,
secret_key = secret_key,
get_secret_key = get_secret_key(access_key, secret_key),
redis_chash = redis_chash:new(
"cluster_redisproxy", get_redis_servers, opts)
}
return setmetatable( obj, mt )
end
function _M.proxy(self)
local _, err_code, err_msg = check_auth(self)
if err_code ~= nil then
return output(nil, err_code, err_msg)
end
local args, err_code, err_msg = get_cmd_args()
if err_code ~= nil then
return output(nil, err_code, err_msg)
end
local cmd, cmd_args, expire = args.cmd, args.cmd_args, args.expire
local n, w, r = args.n, args.w, args.r
local rst, err_code, err_msg
if cmd == 'hget' then
rst, err_code, err_msg = self.redis_chash:hget(cmd_args, n, r)
elseif cmd == 'hset' then
rst, err_code, err_msg = self.redis_chash:hset(cmd_args, n, w, expire)
elseif cmd == 'get' then
rst, err_code, err_msg = self.redis_chash:get(cmd_args, n, r)
elseif cmd == 'set' then
rst, err_code, err_msg = self.redis_chash:set(cmd_args, n, w, expire)
end
return output(rst, err_code, err_msg)
end
return _M
|
local acid_json = require("acid.json")
local acid_nwr = require("acid.nwr")
local strutil = require("acid.strutil")
local tableutil = require("acid.tableutil")
local redis_chash = require("acid.redis_chash")
local aws_authenticator = require("resty.awsauth.aws_authenticator")
local _M = { _VERSION = "0.1" }
local mt = { __index = _M }
local to_str = strutil.to_str
local ERR_CODE = {
NotFound = ngx.HTTP_NOT_FOUND,
InvalidRequest = ngx.HTTP_BAD_REQUEST,
InvalidCommand = ngx.HTTP_FORBIDDEN,
QuorumNotEnough = ngx.HTTP_SERVICE_UNAVAILABLE,
RequestForbidden = ngx.HTTP_FORBIDDEN,
InvalidSignature = ngx.HTTP_FORBIDDEN,
}
-- http method, redis opeartion, count of args, need value args, optional args name
local redis_cmd_model = {
-- get(key)
GET = {'GET', 'get', 1, false, {}},
-- set(key, val, expire=nil)
SET = {'PUT', 'set', 2, true, {'expire'}},
-- hget(hashname, hashkey)
HGET = {'GET', 'hget', 2, false, {}},
-- hset(hashname, hashkey, val, expire=nil)
HSET = {'PUT', 'hset', 3, true, {'expire'}},
}
local redis_cmd_names = tableutil.keys(redis_cmd_model)
local function get_secret_key(access_key, secret_key)
return function(ctx)
if ctx.access_key ~= access_key then
return nil, 'InvalidAccessKey', 'access key does not exists: ' .. ctx.access_key
end
return secret_key
end
end
local function check_auth(self)
if ngx.var.server_addr == '127.0.0.1'
or self.access_key == nil
or self.secret_key == nil then
return
end
local authenticator = aws_authenticator.new(self.get_secret_key)
local ctx, err_code, err_msg = authenticator:authenticate()
if err_code ~= nil then
ngx.log(ngx.INFO, err_code, ':', err_msg)
return nil, 'InvalidSignature', 'signature is not correct'
end
if ctx.anonymous == true then
return nil, 'RequestForbidden', 'anonymous user are not allowed'
end
end
local function output(rst, err_code, err_msg)
local status, body, headers = 200, '', {}
local request_id = ngx.var.requestid
if err_code ~= nil then
ngx.log( ngx.WARN, "requestid: ", request_id,
" err_code: ", err_code, " err_msg: ", err_msg )
status = ERR_CODE[err_code] or ngx.HTTP_BAD_REQUEST
headers["Content-Type"] = "application/json"
local Error = {
Code = err_code,
Message = err_msg,
RequestId = request_id,
}
body = acid_json.enc( Error )
else
rst = rst or {}
headers['X-REDIS-ADDR'] = rst.addr
body = rst.value or ''
end
ngx.header["request-id"] = ngx.var.requestid
headers['Content-Length'] = #body
ngx.status = status
for k, v in pairs(headers) do
ngx.header[k] = v
end
ngx.say(body)
ngx.eof()
ngx.exit(ngx.HTTP_OK)
end
local function read_cmd_value()
local headers = ngx.req.get_headers()
local content_length = tonumber(headers['content-length'])
if content_length == nil then
return nil, 'InvalidRequest', 'Content-Length is nil'
elseif content_length == 0 then
return ''
end
ngx.req.read_body()
local value = ngx.req.get_body_data()
if value == nil then
return nil, 'InvalidRequest', 'Invalid request body'
end
return value
end
local function get_cmd_args()
local uri_regex = '^/redisproxy/v\\d+/(\\S+?)/(\\S+)$'
local urilist = ngx.re.match(ngx.var.uri, uri_regex, 'o')
if urilist == nil then
return nil, 'InvalidRequest', 'uri must like:'.. uri_regex
end
local cmd = urilist[1]
local cmd_args = strutil.split(urilist[2], '/')
local cmd_model = redis_cmd_model[cmd]
if cmd_model == nil then
return nil, 'InvalidCommand', to_str('just support: ', redis_cmd_names)
end
local http_method, cmd, nargs, needed_value, _ = unpack(cmd_model)
if http_method ~= ngx.var.request_method then
return nil, 'InvalidRequest',
to_str(cmd, ' cmd request method must be ', http_method)
end
if needed_value then
local cmd_val, err_code, err_msg = read_cmd_value()
if err_code ~= nil then
return nil, err_code, err_msg
end
table.insert(cmd_args, cmd_val)
end
if #(cmd_args) ~= nargs then
return nil, 'InvalidCommand', to_str(cmd, ' need ', nargs, ' args')
end
local qs = ngx.req.get_uri_args()
return {
cmd = cmd,
cmd_args = cmd_args,
expire = tonumber(qs.expire),
nwr = {
tonumber(qs.n) or 1,
tonumber(qs.w) or 1,
tonumber(qs.r) or 1,
},
}
end
function _M.new(_, access_key, secret_key, get_redis_servers, opts)
local obj = {
access_key = access_key,
secret_key = secret_key,
get_secret_key = get_secret_key(access_key, secret_key),
redis_chash = redis_chash:new(
"cluster_redisproxy", get_redis_servers, opts)
}
return setmetatable( obj, mt )
end
function _M.proxy(self)
local _, err_code, err_msg = check_auth(self)
if err_code ~= nil then
return output(nil, err_code, err_msg)
end
local args, err_code, err_msg = get_cmd_args()
if err_code ~= nil then
return output(nil, err_code, err_msg)
end
local cmd, cmd_args, nwr, expire =
args.cmd, args.cmd_args, args.nwr, args.expire
local nok, rst, err_code, err_msg
if cmd == 'set' or cmd == 'hset' then
nok, err_code, err_msg =
self.redis_chash[cmd](self.redis_chash, cmd_args, nwr[1], expire)
if err_code == nil then
_, err_code, err_msg = acid_nwr.assert_w_ok(nwr, nok)
end
else
rst, err_code, err_msg = self.redis_chash[cmd](self.redis_chash, cmd_args, nwr[3])
end
return output(rst, err_code, err_msg)
end
return _M
|
fix redis_proxy.lua
|
fix redis_proxy.lua
|
Lua
|
mit
|
baishancloud/lua-acid,baishancloud/lua-acid,baishancloud/lua-acid
|
236609c4310514f47429d7da34122e1e58ddc725
|
frontend/ui/data/keyboardlayouts/ar_AA_keyboard.lua
|
frontend/ui/data/keyboardlayouts/ar_AA_keyboard.lua
|
local en_popup = require("ui/data/keyboardlayouts/keypopup/en_popup")
local ar_popup = require("ui/data/keyboardlayouts/keypopup/ar_AA_popup")
local com = en_popup.com -- comma (,)
local prd = en_popup.prd -- period (.)
local _at = en_popup._at
local _eq = en_popup._eq -- equals sign (=)
local alef = ar_popup.alef
local ba = ar_popup.ba
local jeem = ar_popup.jeem
local daal = ar_popup.daal
local h_aa = ar_popup.h_aa -- This is Arabic letter هـ / as in English "hello".
local waw = ar_popup.waw
local zay = ar_popup.zay
local ha = ar_popup.ha -- while this is Arabic letter ح / as in the sound you make when blowing on a glass to clean it.
local tah = ar_popup.tah
local yaa = ar_popup.yaa
local kaf = ar_popup.kaf
local lam = ar_popup.lam
local meem = ar_popup.meem
local nun = ar_popup.nun
local seen = ar_popup.seen
local ayin = ar_popup.ayin
local fah = ar_popup.fah
local saad = ar_popup.saad
local qaf = ar_popup.qaf
local raa = ar_popup.raa
local sheen = ar_popup.sheen
local taa = ar_popup.taa
local thaa = ar_popup.thaa
local thaal = ar_popup.thaal
local dhad = ar_popup.dhad
local ghayn = ar_popup.ghayn
local khaa = ar_popup.khaa
local hamza = ar_popup.hamza
local wawhamza = ar_popup.wawhamza
local laa = ar_popup.laa
local alefmaqsoura = ar_popup.alefmaqsoura
local taamarbouta = ar_popup.taamarbouta
local diacritics = ar_popup.diacritics
local diacritic_fat_ha = ar_popup.diacritic_fat_ha
local diacritic_damma = ar_popup.diacritic_damma
local diacritic_kasra = ar_popup.diacritic_kasra
local diacritic_sukoon = ar_popup.diacritic_sukoon
local diacritic_shadda = ar_popup.diacritic_shadda
local diacritic_tanween_fath = ar_popup.diacritic_tanween_fath
local diacritic_tanween_damm = ar_popup.diacritic_tanween_damm
local diacritic_tanween_kasr = ar_popup.diacritic_tanween_kasr
local arabic_comma = ar_popup.arabic_comma
return {
min_layer = 1,
max_layer = 4,
shiftmode_keys = {["بدّل"] = true}, -- بدّل means "Shift".
symbolmode_keys = {["رمز"] = true,["حرف"]=true}, -- رمز means "Symbol", حرف means "letter" (traditionally "ABC" on QWERTY layouts)
utf8mode_keys = {["🌐"] = true}, -- The famous globe key for layout switching
umlautmode_keys = {["Äéß"] = false}, -- No need for this keyboard panel
keys = {
-- first row
{ -- 1 2 3 4
{ diacritic_fat_ha, dhad, "„", "0", },
{ diacritic_tanween_fath, saad, "!", "1", },
{ diacritic_damma, thaa, _at, "2", },
{ diacritic_tanween_damm, qaf, "#", "3", },
{ "ﻹ", fah, "+", _eq, },
{ "إ", ghayn, "€", "(", },
{ "`", ayin, "‰", ")", },
{ "÷", h_aa, "|", "ـ", },
{ "×", khaa, "?", "ّ", },
{ "؛", ha, "~", "ٌ", },
{ "<", jeem, "<", "ً", },
{ ">", daal, ">", "~", },
},
-- second row
{ -- 1 2 3 4
{ diacritic_kasra, sheen, "…", "4", },
{ diacritic_tanween_kasr, seen, "$", "5", },
{ "]", yaa, "%", "6", },
{ "[", ba, "^", ";", },
{ "ﻷ", lam, ":", "'", },
{ "أ", alef, '"', "\\", },
{ "ـ", taa, "}", "ّ", },
{ "،", nun, "{", "'", },
{ "/", meem, "_", "ِ", },
{ ":", kaf, "÷", "ُ", },
{ "\"", tah, "×", "َ", },
},
-- third row
{ -- 1 2 3 4
{ diacritic_shadda, thaal, "&", "7", },
{ diacritic_sukoon, hamza, "*", "8", },
{ "}", wawhamza, "£", "9", },
{ "{", raa, "_", com, },
{ "ﻵ", laa, "/", prd, },
{ "آ", alefmaqsoura, "‘", "[", },
{ "'", taamarbouta, "'", "]", },
{ arabic_comma, waw, "#", "↑", },
{ ".", zay, "@", "↓", },
{ "؟", thaa, "!", _at, },
{ label = "Backspace",
icon = "resources/icons/appbar.clear.reflect.horizontal.png",
width = 1.5
},
},
-- fourth row
{
{ "بدّل", "بدّل", "بدّل", "بدّل",
width = 1.40},
{ label = "🌐", },
{ "رمز", "رمز", "حرف", "حرف",
width = 1.20},
{ label = "مسافة",
" ", " ", " ", " ",
width = 3.0},
{ com, arabic_comma, "“", "←", },
{ prd, prd, "”", "→", },
{ label = "حركات", diacritics, diacritics, diacritics, diacritics,
width = 1.5},
{ label = "Enter",
"\n", "\n", "\n", "\n",
icon = "resources/icons/appbar.arrow.enter.png",
width = 1.5,
},
},
},
}
|
local en_popup = require("ui/data/keyboardlayouts/keypopup/en_popup")
local ar_popup = require("ui/data/keyboardlayouts/keypopup/ar_AA_popup")
local com = en_popup.com -- comma (,)
local prd = en_popup.prd -- period (.)
local _at = en_popup._at
local _eq = en_popup._eq -- equals sign (=)
local alef = ar_popup.alef
local ba = ar_popup.ba
local jeem = ar_popup.jeem
local daal = ar_popup.daal
local h_aa = ar_popup.h_aa -- This is Arabic letter هـ / as in English "hello".
local waw = ar_popup.waw
local zay = ar_popup.zay
local ha = ar_popup.ha -- while this is Arabic letter ح / as in the sound you make when blowing on a glass to clean it.
local tah = ar_popup.tah
local yaa = ar_popup.yaa
local kaf = ar_popup.kaf
local lam = ar_popup.lam
local meem = ar_popup.meem
local nun = ar_popup.nun
local seen = ar_popup.seen
local ayin = ar_popup.ayin
local fah = ar_popup.fah
local saad = ar_popup.saad
local qaf = ar_popup.qaf
local raa = ar_popup.raa
local sheen = ar_popup.sheen
local taa = ar_popup.taa
local thaa = ar_popup.thaa
local thaal = ar_popup.thaal
local dhad = ar_popup.dhad
local ghayn = ar_popup.ghayn
local khaa = ar_popup.khaa
local hamza = ar_popup.hamza
local wawhamza = ar_popup.wawhamza
local laa = ar_popup.laa
local alefmaqsoura = ar_popup.alefmaqsoura
local taamarbouta = ar_popup.taamarbouta
local diacritics = ar_popup.diacritics
local diacritic_fat_ha = ar_popup.diacritic_fat_ha
local diacritic_damma = ar_popup.diacritic_damma
local diacritic_kasra = ar_popup.diacritic_kasra
local diacritic_sukoon = ar_popup.diacritic_sukoon
local diacritic_shadda = ar_popup.diacritic_shadda
local diacritic_tanween_fath = ar_popup.diacritic_tanween_fath
local diacritic_tanween_damm = ar_popup.diacritic_tanween_damm
local diacritic_tanween_kasr = ar_popup.diacritic_tanween_kasr
local arabic_comma = ar_popup.arabic_comma
return {
min_layer = 1,
max_layer = 4,
shiftmode_keys = {["بدّل"] = true}, -- بدّل means "Shift".
symbolmode_keys = {["رمز"] = true,["حرف"]=true}, -- رمز means "Symbol", حرف means "letter" (traditionally "ABC" on QWERTY layouts)
utf8mode_keys = {["🌐"] = true}, -- The famous globe key for layout switching
umlautmode_keys = {["Äéß"] = false}, -- No need for this keyboard panel
keys = {
-- first row
{ -- 1 2 3 4
{ diacritic_fat_ha, dhad, "„", "0", },
{ diacritic_tanween_fath, saad, "!", "1", },
{ diacritic_damma, thaa, _at, "2", },
{ diacritic_tanween_damm, qaf, "#", "3", },
{ "ﻹ", fah, "+", _eq, },
{ "إ", ghayn, "€", "(", },
{ "`", ayin, "‰", ")", },
{ "÷", h_aa, "|", "ـ", },
{ "×", khaa, "?", "ّ", },
{ "؛", ha, "~", "ٌ", },
{ "<", jeem, "<", "ً", },
{ ">", daal, ">", "~", },
},
-- second row
{ -- 1 2 3 4
{ diacritic_kasra, sheen, "…", "4", },
{ diacritic_tanween_kasr, seen, "$", "5", },
{ "]", yaa, "%", "6", },
{ "[", ba, "^", ";", },
{ "ﻷ", lam, ":", "'", },
{ "أ", alef, '"', "\\", },
{ "ـ", taa, "}", "ّ", },
{ "،", nun, "{", "'", },
{ "/", meem, "_", "ِ", },
{ ":", kaf, "÷", "ُ", },
{ "\"", tah, "×", "َ", },
},
-- third row
{ -- 1 2 3 4
{ diacritic_shadda, thaal, "&", "7", },
{ diacritic_sukoon, hamza, "*", "8", },
{ "}", wawhamza, "£", "9", },
{ "{", raa, "_", com, },
{ "ﻵ", laa, "/", prd, },
{ "آ", alefmaqsoura, "‘", "[", },
{ "'", taamarbouta, "'", "]", },
{ arabic_comma, waw, "#", "↑", },
{ ".", zay, "@", "↓", },
{ "؟", thaa, "!", _at, },
{ label = "",
width = 1.5,
bold = false
},
},
-- fourth row
{
{ "بدّل", "بدّل", "بدّل", "بدّل",
width = 1.40},
{ label = "🌐", },
{ "رمز", "رمز", "حرف", "حرف",
width = 1.20},
{ label = "مسافة",
" ", " ", " ", " ",
width = 3.0},
{ com, arabic_comma, "“", "←", },
{ prd, prd, "”", "→", },
{ label = "حركات", diacritics, diacritics, diacritics, diacritics,
width = 1.5},
{ label = "⮠",
"\n", "\n", "\n", "\n",
width = 1.5,
},
},
},
}
|
fix arabic keyboard to conform to #5639 (#5793)
|
fix arabic keyboard to conform to #5639 (#5793)
Fixes #5792
|
Lua
|
agpl-3.0
|
mwoz123/koreader,poire-z/koreader,poire-z/koreader,NiLuJe/koreader,Frenzie/koreader,pazos/koreader,koreader/koreader,Hzj-jie/koreader,NiLuJe/koreader,Frenzie/koreader,Markismus/koreader,mihailim/koreader,koreader/koreader
|
1614bb7b9cae730411d9b9949aca58c10cd48627
|
dxgui/components/dxCheckBox.lua
|
dxgui/components/dxCheckBox.lua
|
--[[
/***************************************************************************************************************
*
* PROJECT: dxGUI
* LICENSE: See LICENSE in the top level directory
* FILE: components/dxCheckBox.lua
* PURPOSE: All checkbox functions.
* DEVELOPERS: Skyline <[email protected]>
*
* dxGUI is available from http://community.mtasa.com/index.php?p=resources&s=details&id=4871
*
****************************************************************************************************************/
]]
-- // Initializing
--[[!
Crea un check box.
@param x Es la componente x de la posición del check box
@param y Es la componente y de la posición del check box
@param width Es la anchura del checkbox
@param height Es la altura del checkbox
@param text Es el texto que contendrá el checkbox
@param relative Indica si la posición y las dimensiones son relativas al elemento padre
@param Es el elemento padre, por defecto, dxGetRootPane()
@param selected Es un valor booleano indicando si el checkbox esta marcado inicialmente.
@param color Es el color, por defecto, white
@param font Es la fuente de texto, por defecto, "default"
@param theme Es el estilo, por defecto, dxGetDefaultTheme()
]]
function dxCreateCheckBox(x,y,width,height,text,relative,parent,selected,color,font,theme)
checkargs("dxCreateCheckBox", 1, "number", x, "number", y, "number", width, "number", height, "string", text, "boolean", relative);
checkoptionalcontaienr("dxCreateCheckBox", 7, parent);
checkoptionalargs("dxCreateCheckBox", 8, "boolean", selected, "number", color, "string", font, {"string", "dxTheme"}, theme);
x, y, width, height = trimPosAndSize(x, y, width, height, relative, parent);
if not selected then
selected = false
end
if not parent then
parent = dxGetRootPane()
end
if not color then
color = tocolor(255,255,255,255)
end
if not font then
font = "default"
end
if not theme then
theme = dxGetDefaultTheme()
end
if type(theme) == "string" then
theme = dxGetTheme(theme)
end
assert(theme, "dxCreateCheckBox didn't find the main theme");
local checkbox = createElement("dxCheckBox")
setElementParent(checkbox,parent)
setElementData(checkbox,"resource",sourceResource)
setElementData(checkbox,"x",x)
setElementData(checkbox,"y",y)
setElementData(checkbox,"width",width)
setElementData(checkbox,"height",height)
setElementData(checkbox,"text",text)
setElementData(checkbox,"visible",true)
setElementData(checkbox,"colorcoded",false)
setElementData(checkbox,"hover",false)
setElementData(checkbox,"selected",selected)
setElementData(checkbox,"font",font)
setElementData(checkbox,"theme",theme)
setElementData(checkbox,"parent",parent)
setElementData(checkbox,"container",false)
setElementData(checkbox,"postGUI",false)
setElementData(checkbox,"ZOrder",getElementData(parent,"ZIndex")+1)
setElementData(parent,"ZIndex",getElementData(parent,"ZIndex")+1)
return checkbox
end
-- // Functions
--[[!
@return Devuelve un valor booleano indicando si el checkbox está seleccionado.
]]
function dxCheckBoxGetSelected(dxElement)
checkargs("dxCheckBoxGetSelected", 1, "dxCheckBox", dxElement);
return getElementData(dxElement,"selected")
end
--[[!
Selecciona o deselecciona el check box
@param dxElement Es el checkbox
@param selected Un valor booleano que indica si el checkbox debe ser seleccionado.
]]
function dxCheckBoxSetSelected(dxElement,selected)
checkargs("dxCheckBoxSetSelected", 1, "dxCheckBox", dxElement, "boolean", selected);
setElementData(dxElement,"selected",selected)
triggerEvent("onClientDXPropertyChanged",dxElement,"selected",selected)
end
-- // Events
addEventHandler("onClientDXClick",getRootElement(),
function(button, state, absoluteX, absoluteY, worldX, worldY, worldZ, clickedWorld)
if (button=="left" and state=="up") and (source and getElementType(source) == "dxCheckBox") then
local checked = not dxCheckBoxGetSelected(source)
triggerEvent("onClientDXChanged",source,checked)
if not wasEventCancelled() then
dxCheckBoxSetSelected(source,checked)
end
end
end)
-- // Render
function dxCheckBoxRender(component,cpx,cpy,cpg, alphaFactor)
if not cpx then cpx = 0 end
if not cpy then cpy = 0 end
-- // Initializing
local cTheme = dxGetElementTheme(component)
or dxGetElementTheme(getElementParent(component))
local cx,cy = getElementData(component, "x"), getElementData(component, "y");
local cw,ch = getElementData(component, "width"), getElementData(component, "height");
local color = getElementData(component,"color")
local font = getElementData(component, "font");
-- Change alpha component based on parent´s alpha factor
color = multiplyalpha(color, alphaFactor);
local checked = dxCheckBoxGetSelected(component)
local imageset = "CheckboxNormal"
if not checked then
if (getElementData(component,"hover")) then
imageset = "CheckboxHover"--
else
imageset = "CheckboxMark"
end
else
if (getElementData(component,"hover")) then
imageset = "CheckboxMarkHover" --
else
imageset = "CheckboxNormal" --
end
end
dxDrawImageSection(cpx+cx,cpy+cy,cw,ch,
getElementData(cTheme,imageset..":X"),getElementData(cTheme,imageset..":Y"),
getElementData(cTheme,imageset..":Width"),getElementData(cTheme,imageset..":Height"),
getElementData(cTheme,imageset..":images"),0,0,0,color,cpg)
local title,font = dxGetText(component),dxGetFont(component)
local tx = cx
local th = ch
local textHeight = dxGetFontHeight(1,font)
local textX = cpx+cx+cw+5
local textY = cpy+cy+((th-textHeight)/2)
if (dxGetColorCoded(component)) then
dxDrawColorText(title,textX,textY,textX,textY,color,1,font,"left","top",false,false,cpg)
else
dxDrawText(title,textX,textY,textX,textY,color,1,font,"left","top",false,false,cpg)
end
end
|
--[[
/***************************************************************************************************************
*
* PROJECT: dxGUI
* LICENSE: See LICENSE in the top level directory
* FILE: components/dxCheckBox.lua
* PURPOSE: All checkbox functions.
* DEVELOPERS: Skyline <[email protected]>
*
* dxGUI is available from http://community.mtasa.com/index.php?p=resources&s=details&id=4871
*
****************************************************************************************************************/
]]
-- // Initializing
--[[!
Crea un check box.
@param x Es la componente x de la posición del check box
@param y Es la componente y de la posición del check box
@param width Es la anchura del checkbox
@param height Es la altura del checkbox
@param text Es el texto que contendrá el checkbox
@param selected Es un valor booleano indicando si el checkbox esta marcado inicialmente.
@param relative Indica si la posición y las dimensiones son relativas al elemento padre
@param Es el elemento padre, por defecto, dxGetRootPane()
@param color Es el color, por defecto, white
@param font Es la fuente de texto, por defecto, "default"
@param theme Es el estilo, por defecto, dxGetDefaultTheme()
]]
function dxCreateCheckBox(x,y,width,height,text,relative,selected,parent,color,font,theme)
checkargs("dxCreateCheckBox", 1, "number", x, "number", y, "number", width, "number", height, "string", text, "boolean", selected, "boolean", relative);
checkoptionalcontainer("dxCreateCheckBox", 7, parent);
checkoptionalargs("dxCreateCheckBox", 9, "number", color, "string", font, {"string", "dxTheme"}, theme);
x, y, width, height = trimPosAndSize(x, y, width, height, relative, parent);
if not parent then
parent = dxGetRootPane()
end
if not color then
color = tocolor(255,255,255,255)
end
if not font then
font = "default"
end
if not theme then
theme = dxGetDefaultTheme()
end
if type(theme) == "string" then
theme = dxGetTheme(theme)
end
assert(theme, "dxCreateCheckBox didn't find the main theme");
local checkbox = createElement("dxCheckBox")
setElementParent(checkbox,parent)
setElementData(checkbox,"resource",sourceResource)
setElementData(checkbox,"x",x)
setElementData(checkbox,"y",y)
setElementData(checkbox,"width",width)
setElementData(checkbox,"height",height)
setElementData(checkbox,"text",text)
setElementData(checkbox,"visible",true)
setElementData(checkbox,"colorcoded",false)
setElementData(checkbox,"hover",false)
setElementData(checkbox,"selected",selected)
setElementData(checkbox,"font",font)
setElementData(checkbox,"theme",theme)
setElementData(checkbox,"parent",parent)
setElementData(checkbox,"container",false)
setElementData(checkbox,"postGUI",false)
setElementData(checkbox,"ZOrder",getElementData(parent,"ZIndex")+1)
setElementData(parent,"ZIndex",getElementData(parent,"ZIndex")+1)
return checkbox
end
-- // Functions
--[[!
@return Devuelve un valor booleano indicando si el checkbox está seleccionado.
]]
function dxCheckBoxGetSelected(dxElement)
checkargs("dxCheckBoxGetSelected", 1, "dxCheckBox", dxElement);
return getElementData(dxElement,"selected")
end
--[[!
Selecciona o deselecciona el check box
@param dxElement Es el checkbox
@param selected Un valor booleano que indica si el checkbox debe ser seleccionado.
]]
function dxCheckBoxSetSelected(dxElement,selected)
checkargs("dxCheckBoxSetSelected", 1, "dxCheckBox", dxElement, "boolean", selected);
setElementData(dxElement,"selected",selected)
triggerEvent("onClientDXPropertyChanged",dxElement,"selected",selected)
end
-- // Events
addEventHandler("onClientDXClick",getRootElement(),
function(button, state, absoluteX, absoluteY, worldX, worldY, worldZ, clickedWorld)
if (button=="left" and state=="up") and (source and getElementType(source) == "dxCheckBox") then
local checked = not dxCheckBoxGetSelected(source)
triggerEvent("onClientDXChanged",source,checked)
if not wasEventCancelled() then
dxCheckBoxSetSelected(source,checked)
end
end
end)
-- // Render
function dxCheckBoxRender(component,cpx,cpy,cpg, alphaFactor)
if not cpx then cpx = 0 end
if not cpy then cpy = 0 end
-- // Initializing
local cTheme = dxGetElementTheme(component)
or dxGetElementTheme(getElementParent(component))
local cx,cy = getElementData(component, "x"), getElementData(component, "y");
local cw,ch = getElementData(component, "width"), getElementData(component, "height");
local color = getElementData(component,"color")
local font = getElementData(component, "font");
-- Change alpha component based on parent´s alpha factor
color = multiplyalpha(color, alphaFactor);
local checked = dxCheckBoxGetSelected(component)
local imageset = "CheckboxNormal"
if not checked then
if (getElementData(component,"hover")) then
imageset = "CheckboxHover"--
else
imageset = "CheckboxMark"
end
else
if (getElementData(component,"hover")) then
imageset = "CheckboxMarkHover" --
else
imageset = "CheckboxNormal" --
end
end
dxDrawImageSection(cpx+cx,cpy+cy,cw,ch,
getElementData(cTheme,imageset..":X"),getElementData(cTheme,imageset..":Y"),
getElementData(cTheme,imageset..":Width"),getElementData(cTheme,imageset..":Height"),
getElementData(cTheme,imageset..":images"),0,0,0,color,cpg)
local title,font = dxGetText(component),dxGetFont(component)
local tx = cx
local th = ch
local textHeight = dxGetFontHeight(1,font)
local textX = cpx+cx+cw+5
local textY = cpy+cy+((th-textHeight)/2)
if (dxGetColorCoded(component)) then
dxDrawColorText(title,textX,textY,textX,textY,color,1,font,"left","top",false,false,cpg)
else
dxDrawText(title,textX,textY,textX,textY,color,1,font,"left","top",false,false,cpg)
end
end
|
Se arregla bug
|
Se arregla bug
|
Lua
|
mit
|
morfeo642/mta_plr_server
|
79d44b2fed1a5201b955b9fd553747e95963aeaf
|
swig/ft/hello3.lua
|
swig/ft/hello3.lua
|
local fb = require("swig_fribidi")
local iconv = require("iconv")
local hb = require("harfbuzz")
local cairo = require("cairo")
local ft = require("freetype")
local xcb = require("xcb")
local text8 = "Ленивый рыжий кот شَدَّة latin العَرَبِية";
local ic = assert(iconv.open("utf-32le", "utf-8"))
local text = ic:iconv(text8)
local nLineSize = #text/4
local textArray = fb.new_Uint32Array(nLineSize)
fb.memcpy_Uint32Array(textArray, text, #text)
local pTempLogicalLine = fb.new_FriBidiCharArray(nLineSize)
local pTempVisualLine = fb.new_FriBidiCharArray(nLineSize)
local pTempPositionLogicToVisual = fb.new_FriBidiStrIndexArray(nLineSize)
local pTempBidiTypes = fb.new_FriBidiCharTypeArray(nLineSize)
local pTempEmbeddingLevels = fb.new_FriBidiLevelArray(nLineSize)
local pTempJtypes = fb.new_FriBidiJoiningTypeArray(nLineSize)
local pTempArProps = fb.new_FriBidiArabicPropArray(nLineSize)
--for i = 1, #text, 4 do
--local c = (string.byte(text,i+3) << 24)|(string.byte(text,i+2) << 16|(string.byte(text,i+1) << 8))|(string.byte(text,i))
--fb.FriBidiCharArray_setitem(pTempLogicalLine, (i-1)//4, c)
--end
fb.memcpy_FriBidiCharArray(pTempLogicalLine, text, #text)
fb.fribidi_get_bidi_types(pTempLogicalLine, nLineSize, pTempBidiTypes);
local resolveParDir, baseDirection = fb.get_par_embedding_levels_ref(pTempBidiTypes, nLineSize, fb.FRIBIDI_PAR_LTR, pTempEmbeddingLevels)
fb.fribidi_get_joining_types(pTempLogicalLine, nLineSize, pTempJtypes);
fb.memcpy_FriBidiJoiningTypeArray(pTempArProps, pTempJtypes, nLineSize);
fb.fribidi_join_arabic(pTempBidiTypes, nLineSize, pTempEmbeddingLevels, pTempArProps);
fb.fribidi_shape(fb.FRIBIDI_FLAG_SHAPE_MIRRORING | fb.FRIBIDI_FLAG_SHAPE_ARAB_PRES | fb.FRIBIDI_FLAG_SHAPE_ARAB_LIGA, pTempEmbeddingLevels, nLineSize, pTempArProps, pTempLogicalLine);
fb.memcpy_FriBidiCharArray2(pTempVisualLine, pTempLogicalLine, nLineSize);
for i = 0, nLineSize-1 do
fb.FriBidiStrIndexArray_setitem(pTempPositionLogicToVisual, i, i)
end
local levels = fb.fribidi_reorder_line(fb.FRIBIDI_FLAGS_ARABIC, pTempBidiTypes, nLineSize, 0, baseDirection, pTempEmbeddingLevels, pTempVisualLine, pTempPositionLogicToVisual);
--for i = 0, nLineSize-1 do
--print(string.format("%i ====> %i", i, fb.FriBidiStrIndexArray_getitem(pTempPositionLogicToVisual, i)))
--end
local chunks = {}
local chunkStart = 0
local currentScript = hb.unicodeScript(fb.castInt32(fb.Uint32Array_getitem(textArray, chunkStart)))
for j = 1,nLineSize-1 do
local script = hb.unicodeScript(fb.castInt32(fb.Uint32Array_getitem(textArray, j)))
if (script ~= currentScript and script ~= hb.Script.Inherited) then
local chunk = {
start = chunkStart,
length = j - chunkStart,
script = currentScript,
}
table.insert(chunks,chunk)
chunkStart = j
currentScript = script
end
end
local currentSymbol = fb.Uint32Array_getitem(textArray, chunkStart)
if (chunkStart <= nLineSize) then
local chunk = {
start = chunkStart,
length = nLineSize - chunkStart,
script = currentScript,
}
table.insert(chunks,chunk)
end
-------------------- drawing ----------------
local ft_library = ft.initFreeType()
local ptSize = 40.0;
local device_hdpi = 100;
local device_vdpi = 100;
local width = 1000;
local height = 500;
local fontPath = "fonts/arial.ttf"
local ft_face = ft_library:newFace(fontPath)
ft_face:setCharSize(ptSize*64.0, device_hdpi, device_vdpi)
local hb_font = hb.ftFontCreate(ft_face)
--hb.otFontSetFuncs(hb_font)
--local charmap_arr = ft_face:getCharMapArray()
--for i = 1,#charmap_arr do
--if (charmap_arr[i].platform_id == 0 and charmap_arr[i].encoding_id == 3) then
--ft_face:setCharMap(charmap_arr[i])
--break
--elseif (charmap_arr[i].platform_id == 3 and charmap_arr[i].encoding_id == 1) then
--ft_face:setCharMap(charmap_arr[i])
--break
--end
--end
--TODO: work out u32_t type issues
local buf = hb.bufferCreate()
local x = 20
local y = 100
local cairo_glyphs = cairo.newGlyphsArray(nLineSize)
local c = 0
local function chunkToCairo(chunk)
--print(string.format("st=%i, l=%i, script=%s", chunk.start, chunk.length, chunk.script))
buf:clearContents()
--buf:setScript(chunk.script)
--buf:setDirection(hb.Direction.LTR)
buf:setScriptAndDirection(chunk.script)
buf:addUtf32(textArray, nLineSize, chunk.start, chunk.length)
buf:shape(hb_font)
local glyph_infos = buf:getGlyphInfos()
local glyph_positions = buf:getGlyphPositions()
--print(string.format("l=%i x=%i", chunk.length, #glyph_positions))
for j = 1, #glyph_positions do
--print(string.format("x=%i, y=%i", x, y))
--print(string.format(" j=%i, v=%i", j-1, chunk.start + j - 1))
--local o = fb.FriBidiStrIndexArray_getitem(pTempPositionLogicToVisual, chunk.start + j - 1)
--local i = o - chunk.start + 1
i = j
--print(string.format("o=%i j=%i x=%i i=%i", o, j, chunk.start+j-1, i))
local cairo_glyph = cairo.newGlyph()
local position = glyph_positions[i]
local info = glyph_infos[i]
cairo_glyph.index = info.codepoint
cairo_glyph.x = x + (position.x_offset//64)
cairo_glyph.y = y - (position.y_offset//64)
print(string.format("cp=%i xo=%i xa=%i (lua)", info.codepoint,
(position.x_offset), (position.x_advance)))
x = x + (position.x_advance//64)
y = y - (position.y_advance//64)
--c = c + 1
cairo_glyphs[j] = cairo_glyph
end
end
for _,chunk in ipairs(chunks) do
chunkToCairo(chunk)
end
------------------------- display -----------------------
--local conn = xcb.connect()
--local screen = conn:getSetup():setupRootsIterator().data
--local window = conn:createWindow({
--parent=screen.root,
--visual=screen.root_visual,
--x=20, y=20, w=width, h=height, border=10,
--class = xcb.WindowClass.InputOutput,
--mask=xcb.CW.BackPixel | xcb.CW.EventMask,
--value0=screen.black_pixel,
--value1=xcb.EventMask.Exposure | xcb.EventMask.KeyPress
--})
--conn:mapWindow(window)
--conn:flush()
--local visual = cairo.findVisual(conn, screen.root_visual)
--conn:flush()
--local cairo_ft_face = cairo.fontFaceCreateForFtFace(ft_face, 0)
--local surface = cairo.xcbSurfaceCreate(conn, window.id, visual, width, height)
--local cr = surface:cairoCreate()
--cr:setFontSize(ptSize)
--cr:setFontFace(cairo_ft_face)
--local e = conn:waitForEvent()
--while (e) do
--local response_type = e.response_type
--if (response_type == xcb.EventType.Expose) then
--cr:setSourceRgb(0.0, 0.0, 0.0)
--cr:paint()
--cr:setSourceRgba(0.5, 0.5, 0.5, 1.0)
--cr:showGlyphs(cairo_glyphs)
--surface:flush()
--conn:flush()
--elseif (response_type == xcb.EventType.KeyPress) then
--break
--end
--e = conn:waitForEvent()
--end
--conn:disconnect()
|
local fb = require("swig_fribidi")
local iconv = require("iconv")
local hb = require("harfbuzz")
local cairo = require("cairo")
local ft = require("freetype")
local xcb = require("xcb")
local text8 = "Ленивый рыжий кот شَدَّة latin العَرَبِية";
local ic = assert(iconv.open("utf-32le", "utf-8"))
local text = ic:iconv(text8)
local nLineSize = #text/4
local textArray = fb.new_Uint32Array(nLineSize)
fb.memcpy_Uint32Array(textArray, text, #text)
local pTempLogicalLine = fb.new_FriBidiCharArray(nLineSize)
local pTempVisualLine = fb.new_FriBidiCharArray(nLineSize)
local pTempPositionLogicToVisual = fb.new_FriBidiStrIndexArray(nLineSize)
local pTempBidiTypes = fb.new_FriBidiCharTypeArray(nLineSize)
local pTempEmbeddingLevels = fb.new_FriBidiLevelArray(nLineSize)
local pTempJtypes = fb.new_FriBidiJoiningTypeArray(nLineSize)
local pTempArProps = fb.new_FriBidiArabicPropArray(nLineSize)
--for i = 1, #text, 4 do
--local c = (string.byte(text,i+3) << 24)|(string.byte(text,i+2) << 16|(string.byte(text,i+1) << 8))|(string.byte(text,i))
--fb.FriBidiCharArray_setitem(pTempLogicalLine, (i-1)//4, c)
--end
fb.memcpy_FriBidiCharArray(pTempLogicalLine, text, #text)
fb.fribidi_get_bidi_types(pTempLogicalLine, nLineSize, pTempBidiTypes);
local resolveParDir, baseDirection = fb.get_par_embedding_levels_ref(pTempBidiTypes, nLineSize, fb.FRIBIDI_PAR_LTR, pTempEmbeddingLevels)
fb.fribidi_get_joining_types(pTempLogicalLine, nLineSize, pTempJtypes);
fb.memcpy_FriBidiJoiningTypeArray(pTempArProps, pTempJtypes, nLineSize);
fb.fribidi_join_arabic(pTempBidiTypes, nLineSize, pTempEmbeddingLevels, pTempArProps);
fb.fribidi_shape(fb.FRIBIDI_FLAG_SHAPE_MIRRORING | fb.FRIBIDI_FLAG_SHAPE_ARAB_PRES | fb.FRIBIDI_FLAG_SHAPE_ARAB_LIGA, pTempEmbeddingLevels, nLineSize, pTempArProps, pTempLogicalLine);
fb.memcpy_FriBidiCharArray2(pTempVisualLine, pTempLogicalLine, nLineSize);
for i = 0, nLineSize-1 do
fb.FriBidiStrIndexArray_setitem(pTempPositionLogicToVisual, i, i)
end
local levels = fb.fribidi_reorder_line(fb.FRIBIDI_FLAGS_ARABIC, pTempBidiTypes, nLineSize, 0, baseDirection, pTempEmbeddingLevels, pTempVisualLine, pTempPositionLogicToVisual);
--for i = 0, nLineSize-1 do
--print(string.format("%i ====> %i", i, fb.FriBidiStrIndexArray_getitem(pTempPositionLogicToVisual, i)))
--end
local chunks = {}
local chunkStart = 0
local currentScript = hb.unicodeScript(fb.castInt32(fb.Uint32Array_getitem(textArray, chunkStart)))
for j = 1,nLineSize-1 do
local script = hb.unicodeScript(fb.castInt32(fb.Uint32Array_getitem(textArray, j)))
if (script ~= currentScript and script ~= hb.Script.Inherited) then
local chunk = {
start = chunkStart,
length = j - chunkStart,
script = currentScript,
}
table.insert(chunks,chunk)
chunkStart = j
currentScript = script
end
end
local currentSymbol = fb.Uint32Array_getitem(textArray, chunkStart)
if (chunkStart <= nLineSize) then
local chunk = {
start = chunkStart,
length = nLineSize - chunkStart,
script = currentScript,
}
table.insert(chunks,chunk)
end
-------------------- drawing ----------------
local ft_library = ft.initFreeType()
local ptSize = 40.0;
local device_hdpi = 100;
local device_vdpi = 100;
local width = 1000;
local height = 500;
local fontPath = "fonts/arial.ttf"
local ft_face = ft_library:newFace(fontPath)
ft_face:setCharSize(ptSize*64.0, device_hdpi, device_vdpi)
local hb_font = hb.ftFontCreate(ft_face)
--hb.otFontSetFuncs(hb_font)
--local charmap_arr = ft_face:getCharMapArray()
--for i = 1,#charmap_arr do
--if (charmap_arr[i].platform_id == 0 and charmap_arr[i].encoding_id == 3) then
--ft_face:setCharMap(charmap_arr[i])
--break
--elseif (charmap_arr[i].platform_id == 3 and charmap_arr[i].encoding_id == 1) then
--ft_face:setCharMap(charmap_arr[i])
--break
--end
--end
--TODO: work out u32_t type issues
local buf = hb.bufferCreate()
local x = 20
local y = 100
local cairo_glyphs = cairo.newGlyphsArray(nLineSize)
local c = 0
local function chunkToCairo(chunk)
--print(string.format("st=%i, l=%i, script=%s", chunk.start, chunk.length, chunk.script))
buf:clearContents()
--buf:setScript(chunk.script)
--buf:setDirection(hb.Direction.LTR)
buf:setScriptAndDirection(chunk.script)
buf:addUtf32(textArray, nLineSize, chunk.start, chunk.length)
buf:shape(hb_font)
local glyph_infos = buf:getGlyphInfos()
local glyph_positions = buf:getGlyphPositions()
--print(string.format("l=%i x=%i", chunk.length, #glyph_positions))
for j = 1, #glyph_positions do
--print(string.format("x=%i, y=%i", x, y))
--print(string.format(" j=%i, v=%i", j-1, chunk.start + j - 1))
--local o = fb.FriBidiStrIndexArray_getitem(pTempPositionLogicToVisual, chunk.start + j - 1)
--local i = o - chunk.start + 1
local i = j
--print(string.format("o=%i j=%i x=%i i=%i", o, j, chunk.start+j-1, i))
local cairo_glyph = cairo.newGlyph()
local position = glyph_positions[i]
local info = glyph_infos[i]
cairo_glyph.index = info.codepoint
cairo_glyph.x = x + (position.x_offset//64)
cairo_glyph.y = y - (position.y_offset//64)
print(string.format("cp=%i xo=%i xa=%i (lua)", info.codepoint,
(position.x_offset), (position.x_advance)))
x = x + (position.x_advance//64)
y = y - (position.y_advance//64)
c = c + 1
cairo_glyphs[c] = cairo_glyph
end
end
for _,chunk in ipairs(chunks) do
chunkToCairo(chunk)
end
------------------------- display -----------------------
local conn = xcb.connect()
local screen = conn:getSetup():setupRootsIterator().data
local window = conn:createWindow({
parent=screen.root,
visual=screen.root_visual,
x=20, y=20, w=width, h=height, border=10,
class = xcb.WindowClass.InputOutput,
mask=xcb.CW.BackPixel | xcb.CW.EventMask,
value0=screen.black_pixel,
value1=xcb.EventMask.Exposure | xcb.EventMask.KeyPress
})
conn:mapWindow(window)
conn:flush()
local visual = cairo.findVisual(conn, screen.root_visual)
conn:flush()
local cairo_ft_face = cairo.fontFaceCreateForFtFace(ft_face, 0)
local surface = cairo.xcbSurfaceCreate(conn, window.id, visual, width, height)
local cr = surface:cairoCreate()
cr:setFontSize(ptSize)
cr:setFontFace(cairo_ft_face)
local e = conn:waitForEvent()
while (e) do
local response_type = e.response_type
if (response_type == xcb.EventType.Expose) then
cr:setSourceRgb(0.0, 0.0, 0.0)
cr:paint()
cr:setSourceRgba(0.5, 0.5, 0.5, 1.0)
cr:showGlyphs(cairo_glyphs)
surface:flush()
conn:flush()
elseif (response_type == xcb.EventType.KeyPress) then
break
end
e = conn:waitForEvent()
end
conn:disconnect()
|
fixed hello3
|
fixed hello3
|
Lua
|
mit
|
juanchanco/lua-xcb,juanchanco/lua-xcb,juanchanco/lua-xcb
|
5cbc2685aab6d8ba1bd65803e09c9a2ecae73264
|
MMOCoreORB/bin/scripts/screenplays/caves/tatooine_sennex_cave.lua
|
MMOCoreORB/bin/scripts/screenplays/caves/tatooine_sennex_cave.lua
|
SennexCaveScreenPlay = ScreenPlay:new {
numberOfActs = 1,
lootContainers = {
134411,
8496263,
8496262,
8496261,
8496260
},
lootLevel = 26,
lootGroups = {
{
groups = {
{group = "color_crystals", chance = 160000},
{group = "junk", chance = 8600000},
{group = "rifles", chance = 500000},
{group = "pistols", chance = 500000},
{group = "clothing_attachments", chance = 300000},
{group = "armor_attachments", chance = 300000}
},
lootChance = 8000000
}
},
lootContainerRespawn = 1800 -- 30 minutes
}
registerScreenPlay("SennexCaveScreenPlay", true)
function SennexCaveScreenPlay:start()
self:spawnMobiles()
self:initializeLootContainers()
end
function SennexCaveScreenPlay:spawnMobiles()
--spawnMobile("tatooine", "jabba_enforcer", 200, -3.5, -12.7, -6.7, 24, 4235585)
end
function SennexCaveScreenPlay:initializeLootContainers()
for k,v in pairs(self.lootContainers) do
local pContainer = getSceneObject(v)
createObserver(OPENCONTAINER, "SennexCaveScreenPlay", "spawnContainerLoot", pContainer)
self:spawnContainerLoot(pContainer)
end
end
function SennexCaveScreenPlay:spawnContainerLoot(pContainer)
if (pContainer == nil) then
return
end
local container = LuaSceneObject(pContainer)
local time = getTimestamp()
if (readData(container:getObjectID()) > time) then
return
end
--If it has loot already, then exit.
if (container:getContainerObjectsSize() > 0) then
return
end
createLootFromCollection(pContainer, self.lootGroups, self.lootLevel)
writeData(container:getObjectID(), time + self.lootContainerRespawn)
end
|
SennexCaveScreenPlay = ScreenPlay:new {
numberOfActs = 1,
lootContainers = {
134411,
8496263,
8496262,
8496261,
8496260
},
lootLevel = 26,
lootGroups = {
{
groups = {
{group = "color_crystals", chance = 160000},
{group = "junk", chance = 8600000},
{group = "rifles", chance = 500000},
{group = "pistols", chance = 500000},
{group = "clothing_attachments", chance = 300000},
{group = "armor_attachments", chance = 300000}
},
lootChance = 8000000
}
},
lootContainerRespawn = 1800 -- 30 minutes
}
registerScreenPlay("SennexCaveScreenPlay", true)
function SennexCaveScreenPlay:start()
if (isZoneEnabled("tatooine")) then
self:spawnMobiles()
self:initializeLootContainers()
end
end
function SennexCaveScreenPlay:spawnMobiles()
--spawnMobile("tatooine", "jabba_enforcer", 200, -3.5, -12.7, -6.7, 24, 4235585)
end
function SennexCaveScreenPlay:initializeLootContainers()
for k,v in pairs(self.lootContainers) do
local pContainer = getSceneObject(v)
createObserver(OPENCONTAINER, "SennexCaveScreenPlay", "spawnContainerLoot", pContainer)
self:spawnContainerLoot(pContainer)
end
end
function SennexCaveScreenPlay:spawnContainerLoot(pContainer)
if (pContainer == nil) then
return
end
local container = LuaSceneObject(pContainer)
local time = getTimestamp()
if (readData(container:getObjectID()) > time) then
return
end
--If it has loot already, then exit.
if (container:getContainerObjectsSize() > 0) then
return
end
createLootFromCollection(pContainer, self.lootGroups, self.lootLevel)
writeData(container:getObjectID(), time + self.lootContainerRespawn)
end
|
(unstable) [fixed] script issue if tatooine disabled.
|
(unstable) [fixed] script issue if tatooine disabled.
git-svn-id: e4cf3396f21da4a5d638eecf7e3b4dd52b27f938@5538 c3d1530f-68f5-4bd0-87dc-8ef779617e40
|
Lua
|
agpl-3.0
|
Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo
|
bffe35f3ae1a2940be8e1c7c61c153982c8acef5
|
Boilerplate_Resource/src/Boilerplate_Resource.lua
|
Boilerplate_Resource/src/Boilerplate_Resource.lua
|
--------------------------------------------------------
-- This file is part of the JX3 Plugin Project.
-- @desc : Դ
-- @copyright: Copyright (c) 2009 Kingsoft Co., Ltd.
--------------------------------------------------------
-------------------------------------------------------------------------------------------------------
-- these global functions are accessed all the time by the event handler
-- so caching them is worth the effort
-------------------------------------------------------------------------------------------------------
local setmetatable = setmetatable
local ipairs, pairs, next, pcall, select = ipairs, pairs, next, pcall, select
local byte, char, len, find, format = string.byte, string.char, string.len, string.find, string.format
local gmatch, gsub, dump, reverse = string.gmatch, string.gsub, string.dump, string.reverse
local match, rep, sub, upper, lower = string.match, string.rep, string.sub, string.upper, string.lower
local type, tonumber, tostring = type, tonumber, tostring
local HUGE, PI, random, randomseed = math.huge, math.pi, math.random, math.randomseed
local min, max, floor, ceil, abs = math.min, math.max, math.floor, math.ceil, math.abs
local mod, modf, pow, sqrt = math['mod'] or math['fmod'], math.modf, math.pow, math.sqrt
local sin, cos, tan, atan, atan2 = math.sin, math.cos, math.tan, math.atan, math.atan2
local insert, remove, concat = table.insert, table.remove, table.concat
local pack, unpack = table['pack'] or function(...) return {...} end, table['unpack'] or unpack
local sort, getn = table.sort, table['getn'] or function(t) return #t end
-- jx3 apis caching
local wsub, wlen, wfind, wgsub = wstring.sub, wstring.len, StringFindW, StringReplaceW
local GetTime, GetLogicFrameCount, GetCurrentTime = GetTime, GetLogicFrameCount, GetCurrentTime
local GetClientTeam, UI_GetClientPlayerID = GetClientTeam, UI_GetClientPlayerID
local GetClientPlayer, GetPlayer, GetNpc, IsPlayer = GetClientPlayer, GetPlayer, GetNpc, IsPlayer
-- lib apis caching
local LIB = Boilerplate
local UI, GLOBAL, CONSTANT = LIB.UI, LIB.GLOBAL, LIB.CONSTANT
local PACKET_INFO, DEBUG_LEVEL, PATH_TYPE = LIB.PACKET_INFO, LIB.DEBUG_LEVEL, LIB.PATH_TYPE
local wsub, count_c, lodash = LIB.wsub, LIB.count_c, LIB.lodash
local pairs_c, ipairs_c, ipairs_r = LIB.pairs_c, LIB.ipairs_c, LIB.ipairs_r
local spairs, spairs_r, sipairs, sipairs_r = LIB.spairs, LIB.spairs_r, LIB.sipairs, LIB.sipairs_r
local IsNil, IsEmpty, IsEquals, IsString = LIB.IsNil, LIB.IsEmpty, LIB.IsEquals, LIB.IsString
local IsBoolean, IsNumber, IsHugeNumber = LIB.IsBoolean, LIB.IsNumber, LIB.IsHugeNumber
local IsTable, IsArray, IsDictionary = LIB.IsTable, LIB.IsArray, LIB.IsDictionary
local IsFunction, IsUserdata, IsElement = LIB.IsFunction, LIB.IsUserdata, LIB.IsElement
local EncodeLUAData, DecodeLUAData = LIB.EncodeLUAData, LIB.DecodeLUAData
local GetTraceback, RandomChild, GetGameAPI = LIB.GetTraceback, LIB.RandomChild, LIB.GetGameAPI
local Get, Set, Clone, GetPatch, ApplyPatch = LIB.Get, LIB.Set, LIB.Clone, LIB.GetPatch, LIB.ApplyPatch
local Call, XpCall, SafeCall, NSFormatString = LIB.Call, LIB.XpCall, LIB.SafeCall, LIB.NSFormatString
-------------------------------------------------------------------------------------------------------
local PLUGIN_NAME = NSFormatString('{$NS}_Resource')
local PLUGIN_ROOT = PACKET_INFO.ROOT .. PLUGIN_NAME
local MODULE_NAME = NSFormatString('{$NS}_Resource')
local _L = LIB.LoadLangPack(PLUGIN_ROOT .. '/lang/')
--------------------------------------------------------------------------
if not LIB.AssertVersion(MODULE_NAME, _L[MODULE_NAME], '^0.0.0') then
return
end
--------------------------------------------------------------------------
local C, D = {}, {}
C.aSound = {
-- {
-- type = _L['Wuer'],
-- { id = 2, file = 'WE/voice-52001.ogg' },
-- { id = 3, file = 'WE/voice-52002.ogg' },
-- },
}
do
local root = PLUGIN_ROOT .. '/audio/'
local function GetSoundList(tSound)
local t = {}
if tSound.type then
t.szType = tSound.type
elseif tSound.id then
t.dwID = tSound.id
t.szName = _L[tSound.file]
t.szPath = root .. tSound.file
end
for _, v in ipairs(tSound) do
local t1 = GetSoundList(v)
if t1 then
insert(t, t1)
end
end
return t
end
function D.GetSoundList()
return GetSoundList(C.aSound)
end
end
do
local BUTTON_STYLE_CONFIG = {
FLAT = LIB.SetmetaReadonly({
nWidth = 100,
nHeight = 25,
szImage = PACKET_INFO.FRAMEWORK_ROOT .. 'img/WndButton.UITex',
nNormalGroup = 8,
nMouseOverGroup = 9,
nMouseDownGroup = 10,
nDisableGroup = 11,
}),
FLAT_LACE_BORDER = LIB.SetmetaReadonly({
nWidth = 148,
nHeight = 33,
szImage = PACKET_INFO.FRAMEWORK_ROOT .. 'img/WndButton.UITex',
nNormalGroup = 0,
nMouseOverGroup = 1,
nMouseDownGroup = 2,
nDisableGroup = 3,
}),
SKEUOMORPHISM = LIB.SetmetaReadonly({
nWidth = 148,
nHeight = 33,
szImage = PACKET_INFO.FRAMEWORK_ROOT .. 'img/WndButton.UITex',
nNormalGroup = 4,
nMouseOverGroup = 5,
nMouseDownGroup = 6,
nDisableGroup = 7,
}),
SKEUOMORPHISM_LACE_BORDER = LIB.SetmetaReadonly({
nWidth = 224,
nHeight = 64,
nMarginTop = 2,
nMarginRight = 9,
nMarginBottom = 10,
nMarginLeft = 6,
szImage = PACKET_INFO.FRAMEWORK_ROOT .. 'img/WndButton.UITex',
nNormalGroup = 12,
nMouseOverGroup = 13,
nMouseDownGroup = 14,
nDisableGroup = 15,
}),
}
function D.GetWndButtonStyleName(szImage, nNormalGroup)
for e, p in ipairs(BUTTON_STYLE_CONFIG) do
if p.szImage == szImage and p.nNormalGroup == nNormalGroup then
return e
end
end
end
function D.GetWndButtonStyleConfig(eStyle)
return BUTTON_STYLE_CONFIG[eStyle]
end
end
-- Global exports
do
local settings = {
exports = {
{
fields = {
GetSoundList = D.GetSoundList,
GetWndButtonStyle = D.GetWndButtonStyle,
},
},
},
}
_G[MODULE_NAME] = LIB.GeneGlobalNS(settings)
end
|
--------------------------------------------------------
-- This file is part of the JX3 Plugin Project.
-- @desc : Դ
-- @copyright: Copyright (c) 2009 Kingsoft Co., Ltd.
--------------------------------------------------------
-------------------------------------------------------------------------------------------------------
-- these global functions are accessed all the time by the event handler
-- so caching them is worth the effort
-------------------------------------------------------------------------------------------------------
local setmetatable = setmetatable
local ipairs, pairs, next, pcall, select = ipairs, pairs, next, pcall, select
local byte, char, len, find, format = string.byte, string.char, string.len, string.find, string.format
local gmatch, gsub, dump, reverse = string.gmatch, string.gsub, string.dump, string.reverse
local match, rep, sub, upper, lower = string.match, string.rep, string.sub, string.upper, string.lower
local type, tonumber, tostring = type, tonumber, tostring
local HUGE, PI, random, randomseed = math.huge, math.pi, math.random, math.randomseed
local min, max, floor, ceil, abs = math.min, math.max, math.floor, math.ceil, math.abs
local mod, modf, pow, sqrt = math['mod'] or math['fmod'], math.modf, math.pow, math.sqrt
local sin, cos, tan, atan, atan2 = math.sin, math.cos, math.tan, math.atan, math.atan2
local insert, remove, concat = table.insert, table.remove, table.concat
local pack, unpack = table['pack'] or function(...) return {...} end, table['unpack'] or unpack
local sort, getn = table.sort, table['getn'] or function(t) return #t end
-- jx3 apis caching
local wsub, wlen, wfind, wgsub = wstring.sub, wstring.len, StringFindW, StringReplaceW
local GetTime, GetLogicFrameCount, GetCurrentTime = GetTime, GetLogicFrameCount, GetCurrentTime
local GetClientTeam, UI_GetClientPlayerID = GetClientTeam, UI_GetClientPlayerID
local GetClientPlayer, GetPlayer, GetNpc, IsPlayer = GetClientPlayer, GetPlayer, GetNpc, IsPlayer
-- lib apis caching
local LIB = Boilerplate
local UI, GLOBAL, CONSTANT = LIB.UI, LIB.GLOBAL, LIB.CONSTANT
local PACKET_INFO, DEBUG_LEVEL, PATH_TYPE = LIB.PACKET_INFO, LIB.DEBUG_LEVEL, LIB.PATH_TYPE
local wsub, count_c, lodash = LIB.wsub, LIB.count_c, LIB.lodash
local pairs_c, ipairs_c, ipairs_r = LIB.pairs_c, LIB.ipairs_c, LIB.ipairs_r
local spairs, spairs_r, sipairs, sipairs_r = LIB.spairs, LIB.spairs_r, LIB.sipairs, LIB.sipairs_r
local IsNil, IsEmpty, IsEquals, IsString = LIB.IsNil, LIB.IsEmpty, LIB.IsEquals, LIB.IsString
local IsBoolean, IsNumber, IsHugeNumber = LIB.IsBoolean, LIB.IsNumber, LIB.IsHugeNumber
local IsTable, IsArray, IsDictionary = LIB.IsTable, LIB.IsArray, LIB.IsDictionary
local IsFunction, IsUserdata, IsElement = LIB.IsFunction, LIB.IsUserdata, LIB.IsElement
local EncodeLUAData, DecodeLUAData = LIB.EncodeLUAData, LIB.DecodeLUAData
local GetTraceback, RandomChild, GetGameAPI = LIB.GetTraceback, LIB.RandomChild, LIB.GetGameAPI
local Get, Set, Clone, GetPatch, ApplyPatch = LIB.Get, LIB.Set, LIB.Clone, LIB.GetPatch, LIB.ApplyPatch
local Call, XpCall, SafeCall, NSFormatString = LIB.Call, LIB.XpCall, LIB.SafeCall, LIB.NSFormatString
-------------------------------------------------------------------------------------------------------
local PLUGIN_NAME = NSFormatString('{$NS}_Resource')
local PLUGIN_ROOT = PACKET_INFO.ROOT .. PLUGIN_NAME
local MODULE_NAME = NSFormatString('{$NS}_Resource')
local _L = LIB.LoadLangPack(PLUGIN_ROOT .. '/lang/')
--------------------------------------------------------------------------
if not LIB.AssertVersion(MODULE_NAME, _L[MODULE_NAME], '^0.0.0') then
return
end
--------------------------------------------------------------------------
local C, D = {}, {}
C.aSound = {
-- {
-- type = _L['Wuer'],
-- { id = 2, file = 'WE/voice-52001.ogg' },
-- { id = 3, file = 'WE/voice-52002.ogg' },
-- },
}
do
local root = PLUGIN_ROOT .. '/audio/'
local function GetSoundList(tSound)
local t = {}
if tSound.type then
t.szType = tSound.type
elseif tSound.id then
t.dwID = tSound.id
t.szName = _L[tSound.file]
t.szPath = root .. tSound.file
end
for _, v in ipairs(tSound) do
local t1 = GetSoundList(v)
if t1 then
insert(t, t1)
end
end
return t
end
function D.GetSoundList()
return GetSoundList(C.aSound)
end
end
do
local BUTTON_STYLE_CONFIG = {
FLAT = LIB.SetmetaReadonly({
nWidth = 100,
nHeight = 25,
szImage = PACKET_INFO.FRAMEWORK_ROOT .. 'img/WndButton.UITex',
nNormalGroup = 8,
nMouseOverGroup = 9,
nMouseDownGroup = 10,
nDisableGroup = 11,
}),
FLAT_LACE_BORDER = LIB.SetmetaReadonly({
nWidth = 148,
nHeight = 33,
szImage = PACKET_INFO.FRAMEWORK_ROOT .. 'img/WndButton.UITex',
nNormalGroup = 0,
nMouseOverGroup = 1,
nMouseDownGroup = 2,
nDisableGroup = 3,
}),
SKEUOMORPHISM = LIB.SetmetaReadonly({
nWidth = 148,
nHeight = 33,
szImage = PACKET_INFO.FRAMEWORK_ROOT .. 'img/WndButton.UITex',
nNormalGroup = 4,
nMouseOverGroup = 5,
nMouseDownGroup = 6,
nDisableGroup = 7,
}),
SKEUOMORPHISM_LACE_BORDER = LIB.SetmetaReadonly({
nWidth = 224,
nHeight = 64,
nMarginTop = 2,
nMarginRight = 9,
nMarginBottom = 10,
nMarginLeft = 6,
szImage = PACKET_INFO.FRAMEWORK_ROOT .. 'img/WndButton.UITex',
nNormalGroup = 12,
nMouseOverGroup = 13,
nMouseDownGroup = 14,
nDisableGroup = 15,
}),
}
function D.GetWndButtonStyleName(szImage, nNormalGroup)
for e, p in ipairs(BUTTON_STYLE_CONFIG) do
if p.szImage == szImage and p.nNormalGroup == nNormalGroup then
return e
end
end
end
function D.GetWndButtonStyleConfig(eStyle)
return BUTTON_STYLE_CONFIG[eStyle]
end
end
-- Global exports
do
local settings = {
exports = {
{
fields = {
GetSoundList = D.GetSoundList,
GetWndButtonStyleName = D.GetWndButtonStyleName,
GetWndButtonStyleConfig = D.GetWndButtonStyleConfig,
},
},
},
}
_G[MODULE_NAME] = LIB.GeneGlobalNS(settings)
end
|
fix: 资源库按钮样式导出
|
fix: 资源库按钮样式导出
|
Lua
|
bsd-3-clause
|
tinymins/MY
|
dafab63ab29c507ebf5a0b756231371add948d4f
|
share/lua/playlist/appletrailers.lua
|
share/lua/playlist/appletrailers.lua
|
--[[
Translate trailers.apple.com video webpages URLs to the corresponding
movie URL
$Id$
Copyright © 2007-2010 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.
--]]
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "trailers.apple.com" )
and string.match( vlc.path, "web.inc" )
end
function find( haystack, needle )
local _,_,r = string.find( haystack, needle )
return r
end
function sort(a, b)
if(a == nil) then return false end
if(b == nil) then return false end
local str_a
local str_b
if(string.find(a.name, '%(') == 1) then
str_a = tonumber(string.sub(a.name, 2, string.find(a.name, 'p') - 1))
str_b = tonumber(string.sub(b.name, 2, string.find(b.name, 'p') - 1))
else
str_a = string.sub(a.name, 1, string.find(a.name, '%(') - 2)
str_b = string.sub(b.name, 1, string.find(b.name, '%(') - 2)
if(str_a == str_b) then
str_a = tonumber(string.sub(a.name, string.len(str_a) + 3, string.find(a.name, 'p', string.len(str_a) + 3) - 1))
str_b = tonumber(string.sub(b.name, string.len(str_b) + 3, string.find(b.name, 'p', string.len(str_b) + 3) - 1))
end
end
if(str_a > str_b) then return false else return true end
end
-- Parse function.
function parse()
local playlist = {}
local description = ''
local art_url = ''
while true
do
line = vlc.readline()
if not line then break end
if string.match( line, "h3>.-</h3" ) then
description = find( line, "h3>(.-)</h3")
vlc.msg.dbg(description)
end
if string.match( line, 'img src=') then
for img in string.gmatch(line, '<img src="(http://.*%.jpg)" ') do
art_url = img
end
for i,value in pairs(playlist) do
if value.arturl == '' then
playlist[i].arturl = art_url
end
end
end
if string.match( line, 'class="hd".-%.mov') then
for urlline,resolution in string.gmatch(line, 'class="hd".-href="(.-%.mov)".->(%d+.-p)') do
urlline = string.gsub( urlline, "_"..resolution, "_h"..resolution )
table.insert( playlist, { path = urlline,
name = description.." "..resolution,
arturl = art_url,
options = {":http-user-agent=QuickTime/7.5", ":play-and-pause", ":demux=avformat"} } )
end
end
end
return playlist
end
|
--[[
Translate trailers.apple.com video webpages URLs to the corresponding
movie URL
$Id$
Copyright © 2007-2010 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.
--]]
-- Probe function
function probe()
return (vlc.access == "http" or vlc.access == "https")
and string.match( vlc.path, "^trailers%.apple%.com/trailers/.+/.+" )
end
function find( haystack, needle )
local _,_,r = string.find( haystack, needle )
return r
end
function parse_json(url)
vlc.msg.dbg("Trying to parse JSON from " .. url)
local json = require ("dkjson")
-- Use vlc.stream to grab a remote json file, place it in a string,
-- decode it and return the decoded data.
local stream = vlc.stream(url)
local string = ""
local line = ""
if not stream then return false end
while true do
line = stream:readline()
if not line then break end
string = string .. line
end
return json.decode(string)
end
-- Parse function.
function parse()
local video_id = nil
local playlist = {}
while true do
line = vlc.readline()
if not line then break end
if string.match(line, "FilmId%s+=%s+'%d+'") then
video_id = find(line, "FilmId%s+=%s+'(%d+)'")
vlc.msg.dbg("Found FilmId " .. video_id)
break
end
end
-- Found a video id
if video_id ~= nil then
-- Lookup info from the json endpoint
local info = filmid_info(video_id)
-- Parse data
if info["clips"] == nil then
vlc.msg.err("Unexpected JSON response from Apple trailers")
return playlist
end
local movietitle = lookup_keys(info, "details/locale/en/movie_title")
local desc = lookup_keys(info, "details/locale/en/synopsis")
for _, clip in ipairs(info["clips"]) do
local item = {}
if clip["title"] == nil then
item["name"] = movietitle
else
item["name"] = movietitle .. " (" .. clip["title"] .. ")"
end
item["path"] = get_preferred_src(clip)
item["artist"] = clip["artist"]
item["arturl"] = clip["thumb"]
item["description"] = desc
item["url"] = vlc.path
table.insert(playlist, item)
end
else
vlc.msg.err("Couldn't extract trailer video URL")
end
return playlist
end
-- Request, parse and return the info for a FilmID
function filmid_info(id)
local film_url = "https://trailers.apple.com/trailers/feeds/data/" .. id .. ".json"
vlc.msg.dbg("Fetching FilmID info from " .. film_url)
return parse_json(film_url)
end
-- Get the user-preferred quality src
function get_preferred_src(clip)
local resolution = vlc.var.inherit(nil, "preferred-resolution")
if resolution == -1 then
return lookup_keys(clip, "versions/enus/sizes/hd1080/srcAlt")
end
if resolution >= 1080 then
return lookup_keys(clip, "versions/enus/sizes/hd1080/srcAlt")
end
if resolution >= 720 then
return lookup_keys(clip, "versions/enus/sizes/hd720/srcAlt")
end
return lookup_keys(clip, "versions/enus/sizes/sd/srcAlt")
end
-- Resolve a "path" in a table or return nil if any of
-- the keys are not found
function lookup_keys(table, path)
local value = table
for token in path:gmatch( "[^/]+" ) do
value = value[token]
if value == nil then
break
end
end
return value
end
|
appletrailers.lua: Fix script for website changes
|
appletrailers.lua: Fix script for website changes
Fix the Script to work again with the changed
Apple trailers website.
Signed-off-by: Pierre Ynard <[email protected]>
|
Lua
|
lgpl-2.1
|
xkfz007/vlc,xkfz007/vlc,xkfz007/vlc,xkfz007/vlc,xkfz007/vlc,xkfz007/vlc,xkfz007/vlc
|
bc396c252ce406984e8113046bb20cfcedd157b6
|
lua/entities/gmod_wire_expression2/core/custom/remoteupload.lua
|
lua/entities/gmod_wire_expression2/core/custom/remoteupload.lua
|
E2Lib.RegisterExtension("remoteupload", false)
local antispam = {}
local function check(ply)
if antispam[ply] and antispam[ply] > CurTime() then
return false
else
antispam[ply] = CurTime() + 1
return true
end
end
umsg.PoolString("e2_remoteupload_request")
__e2setcost(1000)
e2function void entity:remoteUpload( string filepath )
if not this or not this:IsValid() or this:GetClass() ~= "gmod_wire_expression2" then return end
if not E2Lib.isOwner( self, this ) then return end
if not check(self.player) then return end
umsg.Start( "e2_remoteupload_request", self.player )
umsg.Entity( this )
umsg.String( filepath )
umsg.End()
end
__e2setcost(250)
e2function void entity:remoteSetCode( string code )
if not this or not this:IsValid() or this:GetClass() ~= "gmod_wire_expression2" then return end
if not E2Lib.isOwner( self, this ) then return end
this:Setup( code, {} )
end
e2function void entity:remoteSetCode( string main, table includes )
if not this or not this:IsValid() or this:GetClass() ~= "gmod_wire_expression2" then return end
if not E2Lib.isOwner( self, this ) then return end
local luatable = {}
for k,v in pairs( includes.s ) do
if includes.stypes[k] == "s" and k ~= "main" then
luatable[k] = v
else
error( "Non-string value given to remoteSetCode", 2 )
end
end
this:Setup( main, luatable )
end
e2function string getCode()
local main, _ = self.entity:GetCode()
return main
end
e2function table getCodeIncludes()
local _, includes = self.entity:GetCode()
local e2table = {n={},ntypes={},s={},stypes={},size=0}
for k,v in pairs( includes ) do
e2table.s[k] = v
e2table.stypes[k] = "s"
end
return e2table
end
|
E2Lib.RegisterExtension("remoteupload", false)
local antispam = {}
local function check(ply)
if antispam[ply] and antispam[ply] > CurTime() then
return false
else
antispam[ply] = CurTime() + 1
return true
end
end
umsg.PoolString("e2_remoteupload_request")
__e2setcost(1000)
e2function void entity:remoteUpload( string filepath )
if not this or not this:IsValid() or this:GetClass() ~= "gmod_wire_expression2" then return end
if not E2Lib.isOwner( self, this ) then return end
if not check(self.player) then return end
umsg.Start( "e2_remoteupload_request", self.player )
umsg.Entity( this )
umsg.String( filepath )
umsg.End()
end
__e2setcost(250)
e2function void entity:remoteSetCode( string code )
if not this or not this:IsValid() or this:GetClass() ~= "gmod_wire_expression2" then return end
if not E2Lib.isOwner( self, this ) then return end
this:Setup( code, {} )
end
e2function void entity:remoteSetCode( string main, table includes )
if not this or not this:IsValid() or this:GetClass() ~= "gmod_wire_expression2" then return end
if not E2Lib.isOwner( self, this ) then return end
local luatable = {}
for k,v in pairs( includes.s ) do
self.prf = self.prf + 0.3
if includes.stypes[k] == "s" then
luatable[k] = v
else
error( "Non-string value given to remoteSetCode", 2 )
end
end
this:Setup( main, luatable )
end
__e2setcost(20)
e2function string getCode()
local main, _ = self.entity:GetCode()
return main
end
e2function table getCodeIncludes()
local _, includes = self.entity:GetCode()
local e2table = {n={},ntypes={},s={},stypes={},size=0}
local size = 0
for k,v in pairs( includes ) do
size = size + 1
e2table.s[k] = v
e2table.stypes[k] = "s"
end
self.prf = self.prf + size * 0.3
e2table.size = size
return e2table
end
|
Fixed getCode op cost and forgotten table size
|
Fixed getCode op cost and forgotten table size
|
Lua
|
apache-2.0
|
rafradek/wire,dvdvideo1234/wire,garrysmodlua/wire,mitterdoo/wire,plinkopenguin/wiremod,bigdogmat/wire,CaptainPRICE/wire,Python1320/wire,mms92/wire,thegrb93/wire,wiremod/wire,notcake/wire,Grocel/wire,NezzKryptic/Wire,sammyt291/wire,immibis/wiremod
|
cec461c50598d0df95fb9c9abc3ae461d1448e22
|
filters/addpoints.lua
|
filters/addpoints.lua
|
-- Author: Carsten Gips <[email protected]>
-- Copyright: (c) 2018 Carsten Gips
-- License: MIT
-- count of all points
points = 0
-- add points of headers with attributes `{punkte=42}`
function addPoints(el)
points = points + (tonumber(el.attributes["punkte"]) or 0)
end
-- check `points` field in global metadata
function checkPoints(meta)
if meta["points"] or points > 0 then
if tonumber(meta["points"]) ~= points then
-- check expectation and real value
io.stderr:write("\n\n" .. "Expected " .. (meta["points"] or "NO") .. " points.\n")
io.stderr:write("Found " .. points .. " points!" .. '\n\n\n')
end
end
end
return { { Header = addPoints }, { Meta = checkPoints } }
|
-- Author: Carsten Gips <[email protected]>
-- Copyright: (c) 2018 Carsten Gips
-- License: MIT
-- count of all points
points = 0
-- add points of headers with attributes `{punkte=42}`
function addPoints(el)
points = points + (tonumber(el.attributes["punkte"]) or 0)
end
-- check `points` field in global metadata
function checkPoints(meta)
if meta.points or points > 0 then
-- meta.points is either nil, MetaString or MetaInlines
local mpts = (type(meta.points) == "table" and pandoc.utils.stringify(meta.points)) or meta.points or "NO"
if tonumber(mpts) ~= points then
-- check expectation and real value
io.stderr:write("\n\n" .. "Expected " .. mpts .. " points.\n")
io.stderr:write("Found " .. points .. " points!" .. '\n\n\n')
end
end
end
return { { Header = addPoints }, { Meta = checkPoints } }
|
fix script breakup due to modified handling of YAML in Pandoc 2.2.3
|
fix script breakup due to modified handling of YAML in Pandoc 2.2.3
In Pandoc 2.2.2 and earlier, a YAML element
---
foo: 42
...
would produce a `MetaString`.
Since Pandoc 2.2.3 this will result in a `MetaInlines`.
(see https://github.com/jgm/pandoc/issues/4819)
|
Lua
|
mit
|
cagix/pandoc-lecture
|
f18253e2ce5f3c58c2a391afae8eb69fe24bb9f9
|
init.lua
|
init.lua
|
local textadept = require("textadept")
local events = require("events")
local constants = require("textadept-nim.constants")
local icons = require("textadept-nim.icons")
local nimsuggest = require("textadept-nim.nimsuggest")
local check_executable = require("textadept-nim.utils").check_executable
local sessions = require("textadept-nim.sessions")
local nim_shutdown_all_sessions = function() sessions:stop_all() end
-- Keybinds:
-- API Helper key
local api_helper_key = "ch"
-- GoTo Definition key
local goto_definition_key = "cG"
local on_buffer_delete = function()
-- Checks if any nimsuggest session left without
-- binding to buffer.
-- All unbound sessions will be closed
local to_remove = {}
for k, v in pairs(sessions.session_of) do
local keep = false
for i, b in ipairs(_BUFFERS) do
if b.filename ~= nil then
if b.filename == k then keep = true end
end
end
if not keep then table.insert(to_remove, k) end
end
for i, v in pairs(to_remove) do
sessions:detach(v)
end
end
local on_file_load = function()
-- Called when editor loads file.
-- Trying to get information about project and starts nimsuggest
if buffer ~= nil and buffer:get_lexer(true) == "nim" then
buffer.use_tabs = false
buffer.tab_width = 2
buffer.nim_backend = "c"
end
end
local function gotoDeclaration(position)
-- Puts cursor to declaration
local answer = nimsuggest.definition(position)
if #answer > 0 then
local path = answer[1].file
local line = tonumber(answer[1].line) - 1
local col = tonumber(answer[1].column)
if path ~= buffer.filename then
ui.goto_file(path, false, view)
end
local pos = buffer:find_column(line, col)
buffer:goto_pos(pos)
buffer:vertical_centre_caret()
buffer:word_right_end_extend()
end
end
-- list of additional actions on symbol encountering
-- for further use
local actions_on_symbol = {
[40] = function(pos)
local suggestions = nimsuggest.context(pos)
for i, v in pairs(suggestions) do
local brackets = v.type:match("%((.*)%)")
buffer:call_tip_show(pos, brackets)
end
end,
[46] = function(pos)
textadept.editing.autocomplete("nim")
end,
}
local function check_syntax()
-- Performs syntax check and shows errors
if buffer:get_lexer() ~= "nim" then return end
nimsuggest.check()
end
local function nim_complete(name)
-- Returns a list of suggestions for autocompletion
local shift = 0
for i = 1, buffer.column[buffer.current_pos] do
local c = buffer.char_at[buffer.current_pos - i]
if (c >= 32 and c <= 47)or(c >= 58 and c <= 64)then
shift = i - 1
break
end
end
local suggestions = {}
local token_list = nimsuggest.suggest(buffer.current_pos-shift)
for i, v in pairs(token_list) do
table.insert(suggestions, v.name.."?"..icons[v.skind])
end
if #suggestions == 0 then
return textadept.editing.autocompleters.word(name)
end
icons:register()
return shift, suggestions
end
if check_executable(constants.nimsuggest_exe) then
events.connect(events.FILE_AFTER_SAVE, check_syntax)
events.connect(events.QUIT, nim_shutdown_all_sessions)
events.connect(events.FILE_OPENED, on_file_load)
events.connect(events.FILE_OPENED, check_syntax)
events.connect(events.BUFFER_DELETED, on_buffer_delete)
events.connect(events.CHAR_ADDED, function(ch)
if buffer:get_lexer() ~= "nim" or ch > 90 or actions_on_symbol[ch] == nil
then return end
actions_on_symbol[ch](buffer.current_pos)
end)
keys.nim = {
-- Documentation loader on Ctrl-H
[api_helper_key] = function()
if buffer:get_lexer() == "nim" then
if textadept.editing.api_files.nim == nil then
textadept.editing.api_files.nim = {}
end
local answer = nimsuggest.definition(buffer.current_pos)
if #answer > 0 then
buffer:call_tip_show(buffer.current_pos,
answer[1].skind:match("sk(.*)").." "..answer[1].name..": "..
answer[1].type.."\n"..answer[1].comment)
end
end
end,
-- Goto definition on Ctrl-Shift-G
[goto_definition_key] = function()
gotoDeclaration(buffer.current_pos)
end,
}
textadept.editing.autocompleters.nim = nim_complete
end
if check_executable(constants.nim_compiler_exe) then
textadept.run.compile_commands.nim = function () return nim_compiler.." "..buffer.nim_backend.." %p" end
textadept.run.run_commands.nim = function () return nim_compiler.." "..buffer.nim_backend.." --run %p" end
end
|
local textadept = require("textadept")
local events = require("events")
local constants = require("textadept-nim.constants")
local icons = require("textadept-nim.icons")
local nimsuggest = require("textadept-nim.nimsuggest")
local check_executable = require("textadept-nim.utils").check_executable
local sessions = require("textadept-nim.sessions")
local nim_shutdown_all_sessions = function() sessions:stop_all() end
-- Keybinds:
-- API Helper key
local api_helper_key = "ch"
-- GoTo Definition key
local goto_definition_key = "cG"
local on_buffer_delete = function()
-- Checks if any nimsuggest session left without
-- binding to buffer.
-- All unbound sessions will be closed
local to_remove = {}
for k, v in pairs(sessions.session_of) do
local keep = false
for i, b in ipairs(_BUFFERS) do
if b.filename ~= nil then
if b.filename == k then keep = true end
end
end
if not keep then table.insert(to_remove, k) end
end
for i, v in pairs(to_remove) do
sessions:detach(v)
end
end
local on_file_load = function()
-- Called when editor loads file.
-- Trying to get information about project and starts nimsuggest
if buffer ~= nil and buffer:get_lexer(true) == "nim" then
buffer.use_tabs = false
buffer.tab_width = 2
buffer.nim_backend = "c"
end
end
local function gotoDeclaration(position)
-- Puts cursor to declaration
local answer = nimsuggest.definition(position)
if #answer > 0 then
local path = answer[1].file
local line = tonumber(answer[1].line) - 1
local col = tonumber(answer[1].column)
if path ~= buffer.filename then
ui.goto_file(path, false, view)
end
local pos = buffer:find_column(line, col)
buffer:goto_pos(pos)
buffer:vertical_centre_caret()
buffer:word_right_end_extend()
end
end
-- list of additional actions on symbol encountering
-- for further use
local actions_on_symbol = {
[40] = function(pos)
local suggestions = nimsuggest.context(pos)
for i, v in pairs(suggestions) do
local brackets = v.type:match("%((.*)%)")
buffer:call_tip_show(pos, brackets)
end
end,
[46] = function(pos)
textadept.editing.autocomplete("nim")
end,
}
local function check_syntax()
-- Performs syntax check and shows errors
if buffer:get_lexer() ~= "nim" then return end
nimsuggest.check()
end
local function nim_complete(name)
-- Returns a list of suggestions for autocompletion
local shift = 0
for i = 1, buffer.column[buffer.current_pos] do
local c = buffer.char_at[buffer.current_pos - i]
if (c >= 32 and c <= 47)or(c >= 58 and c <= 64)then
shift = i - 1
break
end
end
local suggestions = {}
local token_list = nimsuggest.suggest(buffer.current_pos-shift)
for i, v in pairs(token_list) do
table.insert(suggestions, v.name.."?"..icons[v.skind])
end
if #suggestions == 0 then
return textadept.editing.autocompleters.word(name)
end
icons:register()
return shift, suggestions
end
if check_executable(constants.nimsuggest_exe) then
events.connect(events.FILE_AFTER_SAVE, check_syntax)
events.connect(events.QUIT, nim_shutdown_all_sessions)
events.connect(events.RESET_BEFORE, nim_shutdown_all_sessions)
events.connect(events.FILE_OPENED, on_file_load)
events.connect(events.FILE_OPENED, check_syntax)
events.connect(events.BUFFER_DELETED, on_buffer_delete)
events.connect(events.CHAR_ADDED, function(ch)
if buffer:get_lexer() ~= "nim" or ch > 90 or actions_on_symbol[ch] == nil
then return end
actions_on_symbol[ch](buffer.current_pos)
end)
keys.nim = {
-- Documentation loader on Ctrl-H
[api_helper_key] = function()
if buffer:get_lexer() == "nim" then
if textadept.editing.api_files.nim == nil then
textadept.editing.api_files.nim = {}
end
local answer = nimsuggest.definition(buffer.current_pos)
if #answer > 0 then
buffer:call_tip_show(buffer.current_pos,
answer[1].skind:match("sk(.*)").." "..answer[1].name..": "..
answer[1].type.."\n"..answer[1].comment)
end
end
end,
-- Goto definition on Ctrl-Shift-G
[goto_definition_key] = function()
gotoDeclaration(buffer.current_pos)
end,
}
textadept.editing.autocompleters.nim = nim_complete
end
if check_executable(constants.nim_compiler_exe) then
textadept.run.compile_commands.nim = function () return nim_compiler.." "..buffer.nim_backend.." %p" end
textadept.run.run_commands.nim = function () return nim_compiler.." "..buffer.nim_backend.." --run %p" end
end
|
Fixed nimsuggest multiple processes on reset
|
Fixed nimsuggest multiple processes on reset
|
Lua
|
mit
|
xomachine/textadept-nim
|
f3359f91423bda4bc629d4bcd098aa7a04762287
|
main.lua
|
main.lua
|
--[[
~ Copyright (c) 2014 by Adam Hellberg <[email protected]>.
~
~ Permission is hereby granted, free of charge, to any person obtaining a copy
~ of this software and associated documentation files (the "Software"), to deal
~ in the Software without restriction, including without limitation the rights
~ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
~ copies of the Software, and to permit persons to whom the Software is
~ furnished to do so, subject to the following conditions:
~
~ The above copyright notice and this permission notice shall be included in
~ all copies or substantial portions of the Software.
~
~ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
~ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
~ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
~ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
~ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
~ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
~ THE SOFTWARE.
--]]
local NAME, T = ...
assert(type(T.EventManager) == "table", "LOAD ORDER ERROR: main.lua was loaded before events.lua")
local Db = T.Database
local EM = T.EventManager
local Debug
function T:ADDON_LOADED(name)
if name == NAME then
Db:Load()
Debug = Db:Get("debug", false)
EM:Fire(NAME:upper() .. "_LOADED")
end
end
function T:DebugCheck()
if not Debug then return end
if Debug.Value then _G[NAME] = T end
end
function T:SetDebug(enabled)
if not Debug then return end
Debug.Value = enabled
self:DebugCheck()
end
function T:ToggleDebug()
self:SetDebug(not Debug.Value)
end
function T:IsDebugEnabled()
if not Debug then return nil end
return Debug.Value
end
|
--[[
~ Copyright (c) 2014 by Adam Hellberg <[email protected]>.
~
~ Permission is hereby granted, free of charge, to any person obtaining a copy
~ of this software and associated documentation files (the "Software"), to deal
~ in the Software without restriction, including without limitation the rights
~ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
~ copies of the Software, and to permit persons to whom the Software is
~ furnished to do so, subject to the following conditions:
~
~ The above copyright notice and this permission notice shall be included in
~ all copies or substantial portions of the Software.
~
~ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
~ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
~ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
~ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
~ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
~ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
~ THE SOFTWARE.
--]]
local NAME, T = ...
assert(type(T.EventManager) == "table", "LOAD ORDER ERROR: main.lua was loaded before events.lua")
local Db = T.Database
local EM = T.EventManager
function T:ADDON_LOADED(name)
if name == NAME then
Db:Load()
Db:Get("debug", false)
EM:Fire(NAME:upper() .. "_LOADED")
end
end
function T:DebugCheck()
if Db:Get("debug", false) then _G[NAME] = T end
end
function T:SetDebug(enabled)
Db:Set("debug", enabled)
self:DebugCheck()
end
function T:ToggleDebug()
self:SetDebug(not Db:Get("debug", false))
end
function T:IsDebugEnabled()
return Db:Get("debug", false)
end
|
Fix db issue in main
|
Fix db issue in main
|
Lua
|
mit
|
SharpWoW/ShareXP
|
413579c2e296d147521e5c73d7c1dbe8706f8caf
|
lua/settings/init.lua
|
lua/settings/init.lua
|
local nvim = require('nvim')
local api = nvim.api
local sys = require('sys')
local plugs = require('nvim').plugs
local parent = require('sys').data
local mkdir = require('nvim').fn.mkdir
local isdirectory = require('nvim').fn.isdirectory
local tools = require('tools')
local function isempty(s)
return (s == nil or s == '') and 1 or 0
end
local dirpaths = {
backup = 'backupdir',
swap = 'directory',
undo = 'undodir',
cache = '',
sessions = '',
}
for dirname,dir_setting in pairs(dirpaths) do
if isdirectory(parent .. '/' .. dirname) == 0 then
mkdir(parent .. '/' .. dirname, 'p')
end
if isempty(dir_setting) == 0 then
nvim.o[dir_setting] = parent .. '/' .. dirname
end
end
nvim.g.lua_complete_omni = 1
nvim.g.c_syntax_for_h = 1
nvim.g.terminal_scrollback_buffer_size = 100000
nvim.o.shada = "!,/1000,'1000,<1000,:1000,s10000,h"
nvim.o.expandtab = true
nvim.o.shiftround = true
nvim.o.tabstop = 4
nvim.o.shiftwidth = 0
nvim.o.softtabstop = -1
nvim.o.scrollback = -1
nvim.o.updatetime = 1000
nvim.o.sidescrolloff = 5
nvim.o.scrolloff = 1
nvim.o.undolevels = 10000
nvim.o.inccommand = 'split'
nvim.o.winaltkeys = 'no'
nvim.o.virtualedit = 'block'
nvim.o.formatoptions = 'tcqrolnj'
nvim.o.backupcopy = 'yes'
nvim.o.complete = '.,w,b,u,t'
nvim.o.completeopt = 'menuone,noselect'
nvim.o.tags = '.git/tags,./tags;,tags'
nvim.o.display = 'lastline,msgsep'
nvim.o.fileformats = 'unix,dos'
nvim.o.wildmenu = true
nvim.o.wildmode = 'full'
nvim.o.pumblend = 20
nvim.o.winblend = 10
nvim.o.showbreak = '↪\\'
nvim.o.listchars = 'tab:▸ ,trail:•,extends:❯,precedes:❮'
nvim.o.sessionoptions = 'buffers,curdir,folds,globals,localoptions,options,resize,tabpages,winpos,winsize'
nvim.o.cpoptions = 'aAceFs_B'
if sys.name == 'windows' then
nvim.o.sessionoptions = nvim.o.sessionoptions .. ',slash,unix'
end
nvim.o.lazyredraw = true
nvim.o.showmatch = true
nvim.o.splitright = true
nvim.o.splitbelow = true
nvim.o.backup = true
nvim.o.undofile = true
nvim.o.termguicolors = true
nvim.o.infercase = true
nvim.o.ignorecase = true
nvim.o.smartindent = true
nvim.o.copyindent = true
nvim.o.expandtab = true
nvim.o.joinspaces = false
nvim.o.showmode = false
nvim.o.visualbell = true
nvim.o.shiftround = true
nvim.o.hidden = true
nvim.o.autowrite = true
nvim.o.autowriteall = true
nvim.o.fileencoding = 'utf-8'
if nvim.g.gonvim_running ~= nil then
nvim.o.showmode = false
nvim.o.ruler = false
else
nvim.o.titlestring = '%t (%f)'
nvim.o.title = true
end
-- Default should be internal,filler,closeoff
if nvim.has('nvim-0.3.3') then
nvim.o.diffopt = nvim.o.diffopt .. ',vertical,iwhiteall,iwhiteeol,indent-heuristic,algorithm:minimal,hiddenoff'
else
nvim.o.diffopt = 'vertical,iwhite'
end
nvim.o.grepprg = tools.select_grep(false)
nvim.o.grepformat = tools.select_grep(false, 'grepformat')
if plugs['vim-fugitive'] ~= nil and plugs['vim-airline'] == nil then
nvim.o.statusline = '%<%f %h%m%r%{FugitiveStatusline()}%=%-14.(%l,%c%V%) %P'
end
-- Window options
nvim.wo.breakindent = true
nvim.wo.relativenumber = true
nvim.wo.number = true
nvim.wo.list = true
nvim.wo.wrap = false
nvim.wo.foldenable = false
nvim.wo.colorcolumn = '80'
nvim.wo.foldmethod = 'syntax'
nvim.wo.signcolumn = 'auto'
nvim.wo.numberwidth = 1
nvim.wo.foldlevel = 99
nvim.wo.foldcolumn = '0'
local wildignores = {
'*.spl',
'*.aux',
'*.out',
'*.o',
'*.pyc',
'*.gz',
'*.pdf',
'*.sw',
'*.swp',
'*.swap',
'*.com',
'*.exe',
'*.so',
'*/cache/*',
'*/__pycache__/*',
}
local no_backup = {
'.git/*',
'.svn/*',
'.xml',
'*.log',
'*.bin',
'*.7z',
'*.dmg',
'*.gz',
'*.iso',
'*.jar',
'*.rar',
'*.tar',
'*.zip',
'TAGS',
'tags',
'GTAGS',
'COMMIT_EDITMSG',
}
nvim.o.wildignore = table.concat(wildignores, ',')
nvim.o.backupskip = table.concat(no_backup, ',') .. ',' .. table.concat(wildignores, ',')
if nvim.env.SSH_CONNECTION == nil then
nvim.o.mouse = 'a'
nvim.o.clipboard = 'unnamedplus,unnamed'
else
nvim.o.mouse = ''
end
|
local nvim = require('nvim')
local api = nvim.api
local sys = require('sys')
local plugs = require('nvim').plugs
local parent = require('sys').data
local mkdir = require('nvim').fn.mkdir
local isdirectory = require('nvim').fn.isdirectory
local tools = require('tools')
local function isempty(s)
return (s == nil or s == '') and 1 or 0
end
local dirpaths = {
backup = 'backupdir',
swap = 'directory',
undo = 'undodir',
cache = '',
sessions = '',
}
for dirname,dir_setting in pairs(dirpaths) do
if isdirectory(parent .. '/' .. dirname) == 0 then
mkdir(parent .. '/' .. dirname, 'p')
end
if isempty(dir_setting) == 0 then
nvim.o[dir_setting] = parent .. '/' .. dirname
end
end
nvim.g.lua_complete_omni = 1
nvim.g.c_syntax_for_h = 1
nvim.g.terminal_scrollback_buffer_size = 100000
nvim.o.shada = "!,/1000,'1000,<1000,:1000,s10000,h"
nvim.o.expandtab = true
nvim.o.shiftround = true
nvim.o.tabstop = 4
nvim.o.shiftwidth = 0
nvim.o.softtabstop = -1
nvim.o.scrollback = -1
nvim.o.updatetime = 1000
nvim.o.sidescrolloff = 5
nvim.o.scrolloff = 1
nvim.o.undolevels = 10000
nvim.o.inccommand = 'split'
nvim.o.winaltkeys = 'no'
nvim.o.virtualedit = 'block'
nvim.o.formatoptions = 'tcqrolnj'
nvim.o.backupcopy = 'yes'
nvim.o.complete = '.,w,b,u,t'
nvim.o.completeopt = 'menuone,noselect'
nvim.o.tags = '.git/tags,./tags;,tags'
nvim.o.display = 'lastline,msgsep'
nvim.o.fileformats = 'unix,dos'
nvim.o.wildmenu = true
nvim.o.wildmode = 'full'
nvim.o.pumblend = 20
nvim.o.winblend = 10
nvim.o.showbreak = '↪\\'
nvim.o.listchars = 'tab:▸ ,trail:•,extends:❯,precedes:❮'
nvim.o.sessionoptions = 'buffers,curdir,folds,globals,localoptions,options,resize,tabpages,winpos,winsize'
nvim.o.cpoptions = 'aAceFs_B'
if sys.name == 'windows' then
nvim.o.sessionoptions = nvim.o.sessionoptions .. ',slash,unix'
end
nvim.o.lazyredraw = true
nvim.o.showmatch = true
nvim.o.splitright = true
nvim.o.splitbelow = true
nvim.o.backup = true
nvim.o.undofile = true
nvim.o.termguicolors = true
nvim.o.infercase = true
nvim.o.ignorecase = true
nvim.o.smartindent = true
nvim.o.copyindent = true
nvim.o.expandtab = true
nvim.o.joinspaces = false
nvim.o.showmode = false
nvim.o.visualbell = true
nvim.o.shiftround = true
nvim.o.hidden = true
nvim.o.autowrite = true
nvim.o.autowriteall = true
nvim.o.fileencoding = 'utf-8'
if nvim.g.gonvim_running ~= nil then
nvim.o.showmode = false
nvim.o.ruler = false
else
nvim.o.titlestring = '%t (%f)'
nvim.o.title = true
end
-- Default should be internal,filler,closeoff
if nvim.has('nvim-0.3.3') then
nvim.o.diffopt = nvim.o.diffopt .. ',vertical,iwhiteall,iwhiteeol,indent-heuristic,algorithm:minimal,hiddenoff'
else
nvim.o.diffopt = 'vertical,iwhite'
end
nvim.o.grepprg = tools.select_grep(false)
nvim.o.grepformat = tools.select_grep(false, 'grepformat')
if plugs['vim-fugitive'] ~= nil and plugs['vim-airline'] == nil then
nvim.o.statusline = '%<%f %h%m%r%{FugitiveStatusline()}%=%-14.(%l,%c%V%) %P'
end
-- Window options
nvim.wo.breakindent = true
nvim.wo.relativenumber = true
nvim.wo.number = true
nvim.wo.list = true
nvim.wo.wrap = false
nvim.wo.foldenable = false
nvim.wo.colorcolumn = '80'
nvim.wo.foldmethod = 'syntax'
nvim.wo.signcolumn = 'auto'
nvim.wo.numberwidth = 1
nvim.wo.foldlevel = 99
-- Changes in nvim master
-- nvim.wo.foldcolumn = 'auto'
local wildignores = {
'*.spl',
'*.aux',
'*.out',
'*.o',
'*.pyc',
'*.gz',
'*.pdf',
'*.sw',
'*.swp',
'*.swap',
'*.com',
'*.exe',
'*.so',
'*/cache/*',
'*/__pycache__/*',
}
local no_backup = {
'.git/*',
'.svn/*',
'.xml',
'*.log',
'*.bin',
'*.7z',
'*.dmg',
'*.gz',
'*.iso',
'*.jar',
'*.rar',
'*.tar',
'*.zip',
'TAGS',
'tags',
'GTAGS',
'COMMIT_EDITMSG',
}
nvim.o.wildignore = table.concat(wildignores, ',')
nvim.o.backupskip = table.concat(no_backup, ',') .. ',' .. table.concat(wildignores, ',')
if nvim.env.SSH_CONNECTION == nil then
nvim.o.mouse = 'a'
nvim.o.clipboard = 'unnamedplus,unnamed'
else
nvim.o.mouse = ''
end
|
fix: Remove foldcolumn settings
|
fix: Remove foldcolumn settings
Neovim HEAD have changes in foldcolumn usage, temporally disable it
|
Lua
|
mit
|
Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim
|
bda613589e7b28d8b268d9d1e3ae3ee08bcc4bef
|
entities/ui/wheel.lua
|
entities/ui/wheel.lua
|
local Wheel = Class('Wheel')
function Wheel:initialize(parent, props)
self.parent = parent
self.radius = 40
self.inactiveColor = {255, 255, 255}
self.pressColor = {400, 400, 400}
self.position = Vector(0, 0)
self.angle = 0
self.locked = {cw = true, ccw = true}
self.onClicked = function(rotDir) end
for k, prop in pairs(props) do
self[k] = prop
end
self.isPressed = false
self.beganPress = false
self.rotationAccumulator = 0
self.startAngle = self.angle
self.activeRotDirection = "cw"
self.bindingSpinMultiplier = .5
self.mouseSpinMultiplier = 1
self.beingMoved = false
self.lastBeingMoved = false
self.position.y = self.position.y - 1
self.handleImage = love.graphics.newImage('assets/images/Dynamo/dynamo_smallbutton.png')
self.arrowImage = love.graphics.newImage('assets/images/Dynamo/dynamo_arrow_right.png')
end
function Wheel:activate()
self.activated = true
local possibles = {}
if not self.locked.cw then table.insert(possibles, 0) end
if not self.locked.ccw then table.insert(possibles, 1) end
local randomDir = possibles[love.math.random(1, #possibles)]
if randomDir == 0 then
self.activeRotDirection = "cw"
elseif randomDir == 1 then
self.activeRotDirection = "ccw"
else
error("Unexpected var for randDir: " .. randDir)
end
self.startAngle = self.angle
self.rotationAccumulator = 0
end
function Wheel:getPressed(x, y)
return Lume.distance(self.position.x, self.position.y, x, y) <= self.radius
end
function Wheel:update(dt)
if self.beingMoved and not self.lastBeingMoved then
Signal.emit("Wheel Spin Start")
elseif not self.beingMoved and self.lastBeingMoved then
Signal.emit("Wheel Spin Stop")
end
self.lastBeingMoved = self.beingMoved
end
function Wheel:mousepressed(x, y, mbutton)
if self.locked.cw and
self.locked.ccw then
return
end
self.isPressed = false
self.beingMoved = false
if mbutton == 1 and self:getPressed(x, y) then
self.beingMoved = true
self.isPressed = true
self.beganPress = true
--self.rotationAccumulator = 0
--self.startAngle = self.angle
end
end
function Wheel:mousemoved(x, y, dx, dy, istouch)
if self.isPressed then
-- makes a good spinning behavior regardless of how far inside or outside of the wheel the mouse is
local dist = Lume.distance(self.position.x, self.position.y, x, y)
local currentAngle = Lume.angle(self.position.x, self.position.y, x, y)
local extrapLength = math.max(self.radius, dist)
local extrapOffset = Vector(math.cos(currentAngle)*extrapLength, math.sin(currentAngle)*extrapLength)
extrapOffset = extrapOffset - Vector(dx, dy)
local prevAngle = Lume.angle(0, 0, extrapOffset.x, extrapOffset.y)
local deltaAngle = (currentAngle - prevAngle) * self.mouseSpinMultiplier
self:solveAngle(deltaAngle)
end
end
function Wheel:solveAngle(deltaAngle)
-- idea: be able to treat the skip from 180deg to -180deg as no big deal
-- fairly hacky
if deltaAngle >= math.pi then
deltaAngle = 2*math.pi - deltaAngle
elseif deltaAngle <= -math.pi then
deltaAngle = -2*math.pi - deltaAngle
end
self.angle = self.angle + deltaAngle
self.rotationAccumulator = self.rotationAccumulator + deltaAngle
if self.rotationAccumulator >= 2*math.pi then
self.rotationAccumulator = self.rotationAccumulator - 2*math.pi
if self.activated then
if self.activeRotDirection == "cw" then
self.activated = false
self.onClicked(self.position, "cw")
else
Signal.emit("Dynamo Incorrect", "wheel")
end
end
elseif self.rotationAccumulator <= -2*math.pi then
self.rotationAccumulator = self.rotationAccumulator + 2*math.pi
if self.activated then
if self.activeRotDirection == "ccw" then
self.activated = false
self.onClicked(self.position, "ccw")
else
Signal.emit("Dynamo Incorrect", "wheel")
end
end
end
if self.angle >= 2*math.pi then
self.angle = self.angle - 2*math.pi
elseif self.angle <= -2*math.pi then
self.angle = self.angle + 2*math.pi
end
end
function Wheel:mousereleased(x, y, mbutton)
if self.locked.cw and
self.locked.ccw then
return
end
if mbutton == 1 and self.isPressed then
self.beingMoved = false
self.isPressed = false
self.beganPress = false
--self.rotationAccumulator = 0
end
end
function Wheel:wheelmoved(x, y)
if self.locked.cw then y = math.max(0, y) end
if self.locked.ccw then y = math.min(0, y) end
self.beingMoved = false
if y <= 0 then
self.beingMoved = true
end
self:solveAngle(-y * self.bindingSpinMultiplier)
end
function Wheel:draw()
if self.locked.cw and
self.locked.ccw then
return
end
love.graphics.setColor(self.inactiveColor)
if self.activated then
love.graphics.setColor(self.pressColor)
end
local angle1Raw, angle2Raw = self.startAngle, self.startAngle + self.rotationAccumulator
local angle1, angle2 = math.min(angle1Raw, angle2Raw), math.max(angle1Raw, angle2Raw)
--love.graphics.arc('line', self.position.x, self.position.y, self.radius + 5, angle1, angle2)
--love.graphics.circle('line', self.position.x, self.position.y, self.radius)
local radius = self.radius - 2
local handleX, handleY = self.position.x + math.cos(self.angle)*radius, self.position.y + math.sin(self.angle)*radius
love.graphics.draw(self.handleImage, math.floor(handleX), math.floor(handleY), 0, 1, 1, self.handleImage:getWidth()/2, self.handleImage:getHeight()/2)
--love.graphics.circle('fill', handleX, handleY , 6)
love.graphics.setColor(255, 255, 255)
if self.activated then
local deltaRad
if self.activeRotDirection == "cw" then
local x, y = self.position.x, self.position.y
x = x + 19
y = y - 1
love.graphics.draw(self.arrowImage, math.floor(x), math.floor(y), 0, -1, -1)
deltaRad = math.pi/4
elseif self.activeRotDirection == "ccw" then
local x, y = self.position.x, self.position.y
x = x - 17
y = y + 4
love.graphics.draw(self.arrowImage, math.floor(x), math.floor(y))
deltaRad = -math.pi/4
end
-- love.graphics.line(handleX, handleY, handleX + math.cos(self.angle+deltaRad)*20, handleY + math.sin(self.angle+deltaRad)*20)
end
--love.graphics.print(math.deg(self.rotationAccumulator), self.position.x, self.position.y)
end
return Wheel
|
local Wheel = Class('Wheel')
function Wheel:initialize(parent, props)
self.parent = parent
self.radius = 40
self.inactiveColor = {255, 255, 255}
self.pressColor = {400, 400, 400}
self.position = Vector(0, 0)
self.angle = 0
self.locked = {cw = true, ccw = true}
self.onClicked = function(rotDir) end
for k, prop in pairs(props) do
self[k] = prop
end
self.isPressed = false
self.beganPress = false
self.rotationAccumulator = 0
self.startAngle = self.angle
self.activeRotDirection = "cw"
self.bindingSpinMultiplier = .5
self.mouseSpinMultiplier = 1
self.beingMoved = false
self.lastBeingMoved = false
self.position.y = self.position.y - 1
self.handleImage = love.graphics.newImage('assets/images/Dynamo/dynamo_smallbutton.png')
self.arrowImage = love.graphics.newImage('assets/images/Dynamo/dynamo_arrow_right.png')
end
function Wheel:activate()
self.activated = true
local possibles = {}
if not self.locked.cw then table.insert(possibles, 0) end
if not self.locked.ccw then table.insert(possibles, 1) end
local randomDir = possibles[love.math.random(1, #possibles)]
if randomDir == 0 then
self.activeRotDirection = "cw"
elseif randomDir == 1 then
self.activeRotDirection = "ccw"
else
error("Unexpected var for randDir: " .. randDir)
end
self.startAngle = self.angle
self.rotationAccumulator = 0
end
function Wheel:getPressed(x, y)
-- some extra leeway
return Lume.distance(self.position.x, self.position.y, x, y) <= self.radius + 5
end
function Wheel:update(dt)
if self.beingMoved and not self.lastBeingMoved then
Signal.emit("Wheel Spin Start")
elseif not self.beingMoved and self.lastBeingMoved then
Signal.emit("Wheel Spin Stop")
end
self.lastBeingMoved = self.beingMoved
end
function Wheel:mousepressed(x, y, mbutton)
if self.locked.cw and
self.locked.ccw then
return
end
self.isPressed = false
self.beingMoved = false
if mbutton == 1 and self:getPressed(x, y) then
self.beingMoved = true
self.isPressed = true
self.beganPress = true
--self.rotationAccumulator = 0
--self.startAngle = self.angle
end
end
function Wheel:mousemoved(x, y, dx, dy, istouch)
if self.isPressed then
-- makes a good spinning behavior regardless of how far inside or outside of the wheel the mouse is
local dist = Lume.distance(self.position.x, self.position.y, x, y)
local currentAngle = Lume.angle(self.position.x, self.position.y, x, y)
local extrapLength = math.max(self.radius, dist)
local extrapOffset = Vector(math.cos(currentAngle)*extrapLength, math.sin(currentAngle)*extrapLength)
extrapOffset = extrapOffset - Vector(dx, dy)
local prevAngle = Lume.angle(0, 0, extrapOffset.x, extrapOffset.y)
local deltaAngle = (currentAngle - prevAngle) * self.mouseSpinMultiplier
self:solveAngle(deltaAngle)
end
end
function Wheel:solveAngle(deltaAngle)
-- idea: be able to treat the skip from 180deg to -180deg as no big deal
-- fairly hacky
if deltaAngle >= math.pi then
deltaAngle = 2*math.pi - deltaAngle
elseif deltaAngle <= -math.pi then
deltaAngle = -2*math.pi - deltaAngle
end
self.angle = self.angle + deltaAngle
self.rotationAccumulator = self.rotationAccumulator + deltaAngle
if self.rotationAccumulator >= 2*math.pi then
self.rotationAccumulator = self.rotationAccumulator - 2*math.pi
if self.activated then
if self.activeRotDirection == "cw" then
self.activated = false
self.onClicked(self.position, "cw")
else
Signal.emit("Dynamo Incorrect", "wheel")
end
end
elseif self.rotationAccumulator <= -2*math.pi then
self.rotationAccumulator = self.rotationAccumulator + 2*math.pi
if self.activated then
if self.activeRotDirection == "ccw" then
self.activated = false
self.onClicked(self.position, "ccw")
else
Signal.emit("Dynamo Incorrect", "wheel")
end
end
end
if self.angle >= 2*math.pi then
self.angle = self.angle - 2*math.pi
elseif self.angle <= -2*math.pi then
self.angle = self.angle + 2*math.pi
end
end
function Wheel:mousereleased(x, y, mbutton)
if self.locked.cw and
self.locked.ccw then
return
end
if mbutton == 1 and self.isPressed then
self.beingMoved = false
self.isPressed = false
self.beganPress = false
--self.rotationAccumulator = 0
end
end
function Wheel:wheelmoved(x, y)
if self.locked.cw then y = math.max(0, y) end
if self.locked.ccw then y = math.min(0, y) end
self.beingMoved = false
if y <= 0 then
self.beingMoved = true
end
self:solveAngle(-y * self.bindingSpinMultiplier)
end
function Wheel:draw()
if self.locked.cw and
self.locked.ccw then
return
end
love.graphics.setColor(self.inactiveColor)
if self.activated then
love.graphics.setColor(self.pressColor)
end
local angle1Raw, angle2Raw = self.startAngle, self.startAngle + self.rotationAccumulator
local angle1, angle2 = math.min(angle1Raw, angle2Raw), math.max(angle1Raw, angle2Raw)
--love.graphics.arc('line', self.position.x, self.position.y, self.radius + 5, angle1, angle2)
--love.graphics.circle('line', self.position.x, self.position.y, self.radius)
local radius = self.radius - 2
local handleX, handleY = self.position.x + math.cos(self.angle)*radius, self.position.y + math.sin(self.angle)*radius
love.graphics.draw(self.handleImage, math.floor(handleX), math.floor(handleY), 0, 1, 1, self.handleImage:getWidth()/2, self.handleImage:getHeight()/2)
--love.graphics.circle('fill', handleX, handleY , 6)
love.graphics.setColor(255, 255, 255)
if self.activated then
local deltaRad
if self.activeRotDirection == "cw" then
local x, y = self.position.x, self.position.y
--x = x + 19
x = x - self.arrowImage:getWidth()/2 + 1
y = y - 1
love.graphics.draw(self.arrowImage, math.floor(x), math.floor(y), 0, 1, -1)
deltaRad = math.pi/4
elseif self.activeRotDirection == "ccw" then
local x, y = self.position.x, self.position.y
x = x - 17
y = y + 4
love.graphics.draw(self.arrowImage, math.floor(x), math.floor(y))
deltaRad = -math.pi/4
end
-- love.graphics.line(handleX, handleY, handleX + math.cos(self.angle+deltaRad)*20, handleY + math.sin(self.angle+deltaRad)*20)
end
--love.graphics.print(math.deg(self.rotationAccumulator), self.position.x, self.position.y)
end
return Wheel
|
fixed wheel art positioning
|
fixed wheel art positioning
|
Lua
|
mit
|
Nuthen/ludum-dare-39
|
94bcd70e9735b9308558a4d929b9d59818019b2b
|
applications/luci-app-dockerman/luasrc/model/cbi/dockerman/volumes.lua
|
applications/luci-app-dockerman/luasrc/model/cbi/dockerman/volumes.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2019 lisaac <https://github.com/lisaac/luci-app-dockerman>
]]--
local docker = require "luci.model.docker"
local dk = docker.new()
local m, s, o
local res, containers, volumes
function get_volumes()
local data = {}
for i, v in ipairs(volumes) do
local index = v.Name
data[index]={}
data[index]["_selected"] = 0
data[index]["_nameraw"] = v.Name
data[index]["_name"] = v.Name:sub(1,12)
for ci,cv in ipairs(containers) do
if cv.Mounts and type(cv.Mounts) ~= "table" then
break
end
for vi, vv in ipairs(cv.Mounts) do
if v.Name == vv.Name then
data[index]["_containers"] = (data[index]["_containers"] and (data[index]["_containers"] .. " | ") or "")..
'<a href='..luci.dispatcher.build_url("admin/docker/container/"..cv.Id)..' class="dockerman_link" title="'..translate("Container detail")..'">'.. cv.Names[1]:sub(2)..'</a>'
end
end
end
data[index]["_driver"] = v.Driver
data[index]["_mountpoint"] = nil
for v1 in v.Mountpoint:gmatch('[^/]+') do
if v1 == index then
data[index]["_mountpoint"] = data[index]["_mountpoint"] .."/" .. v1:sub(1,12) .. "..."
else
data[index]["_mountpoint"] = (data[index]["_mountpoint"] and data[index]["_mountpoint"] or "").."/".. v1
end
end
data[index]["_created"] = v.CreatedAt
end
return data
end
res = dk.volumes:list()
if res.code <300 then
volumes = res.body.Volumes
else
return
end
res = dk.containers:list({
query = {
all=true
}
})
if res.code <300 then
containers = res.body
else
return
end
local volume_list = get_volumes()
m = SimpleForm("docker", translate("Docker"))
m.submit=false
m.reset=false
s = m:section(Table, volume_list, translate("Volumes"))
o = s:option(Flag, "_selected","")
o.disabled = 0
o.enabled = 1
o.default = 0
o.write = function(self, section, value)
volume_list[section]._selected = value
end
o = s:option(DummyValue, "_name", translate("Name"))
o = s:option(DummyValue, "_driver", translate("Driver"))
o = s:option(DummyValue, "_containers", translate("Containers"))
o.rawhtml = true
o = s:option(DummyValue, "_mountpoint", translate("Mount Point"))
o = s:option(DummyValue, "_created", translate("Created"))
s = m:section(SimpleSection)
s.template = "dockerman/apply_widget"
s.err=docker:read_status()
s.err=s.err and s.err:gsub("\n","<br>"):gsub(" "," ")
if s.err then
docker:clear_status()
end
s = m:section(Table,{{}})
s.notitle=true
s.rowcolors=false
s.template="cbi/nullsection"
o = s:option(Button, "remove")
o.inputtitle= translate("Remove")
o.template = "dockerman/cbi/inlinebutton"
o.inputstyle = "remove"
o.forcewrite = true
o.write = function(self, section)
local volume_selected = {}
for _, volume_table_sid in ipairs(volume_list) do
if volume_list[volume_table_sid]._selected == 1 then
volume_selected[#volume_selected+1] = volume_table_sid
end
end
if next(volume_selected) ~= nil then
local success = true
docker:clear_status()
for _,vol in ipairs(volume_selected) do
docker:append_status("Volumes: " .. "remove" .. " " .. vol .. "...")
local msg = dk.volumes["remove"](dk, {id = vol})
if msg.code ~= 204 then
docker:append_status("code:" .. msg.code.." ".. (msg.body.message and msg.body.message or msg.message).. "\n")
success = false
else
docker:append_status("done\n")
end
end
if success then
docker:clear_status()
end
luci.http.redirect(luci.dispatcher.build_url("admin/docker/volumes"))
end
end
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2019 lisaac <https://github.com/lisaac/luci-app-dockerman>
]]--
local docker = require "luci.model.docker"
local dk = docker.new()
local m, s, o
local res, containers, volumes
function get_volumes()
local data = {}
for i, v in ipairs(volumes) do
local index = v.Name
data[index]={}
data[index]["_selected"] = 0
data[index]["_nameraw"] = v.Name
data[index]["_name"] = v.Name:sub(1,12)
for ci,cv in ipairs(containers) do
if cv.Mounts and type(cv.Mounts) ~= "table" then
break
end
for vi, vv in ipairs(cv.Mounts) do
if v.Name == vv.Name then
data[index]["_containers"] = (data[index]["_containers"] and (data[index]["_containers"] .. " | ") or "")..
'<a href='..luci.dispatcher.build_url("admin/docker/container/"..cv.Id)..' class="dockerman_link" title="'..translate("Container detail")..'">'.. cv.Names[1]:sub(2)..'</a>'
end
end
end
data[index]["_driver"] = v.Driver
data[index]["_mountpoint"] = nil
for v1 in v.Mountpoint:gmatch('[^/]+') do
if v1 == index then
data[index]["_mountpoint"] = data[index]["_mountpoint"] .."/" .. v1:sub(1,12) .. "..."
else
data[index]["_mountpoint"] = (data[index]["_mountpoint"] and data[index]["_mountpoint"] or "").."/".. v1
end
end
data[index]["_created"] = v.CreatedAt
end
return data
end
res = dk.volumes:list()
if res.code <300 then
volumes = res.body.Volumes
else
return
end
res = dk.containers:list({
query = {
all=true
}
})
if res.code <300 then
containers = res.body
else
return
end
local volume_list = get_volumes()
m = SimpleForm("docker", translate("Docker"))
m.submit=false
m.reset=false
s = m:section(Table, volume_list, translate("Volumes"))
o = s:option(Flag, "_selected","")
o.disabled = 0
o.enabled = 1
o.default = 0
o.write = function(self, section, value)
volume_list[section]._selected = value
end
o = s:option(DummyValue, "_name", translate("Name"))
o = s:option(DummyValue, "_driver", translate("Driver"))
o = s:option(DummyValue, "_containers", translate("Containers"))
o.rawhtml = true
o = s:option(DummyValue, "_mountpoint", translate("Mount Point"))
o = s:option(DummyValue, "_created", translate("Created"))
s = m:section(SimpleSection)
s.template = "dockerman/apply_widget"
s.err=docker:read_status()
s.err=s.err and s.err:gsub("\n","<br>"):gsub(" "," ")
if s.err then
docker:clear_status()
end
s = m:section(Table,{{}})
s.notitle=true
s.rowcolors=false
s.template="cbi/nullsection"
o = s:option(Button, "remove")
o.inputtitle= translate("Remove")
o.template = "dockerman/cbi/inlinebutton"
o.inputstyle = "remove"
o.forcewrite = true
o.write = function(self, section)
local volume_selected = {}
for k in pairs(volume_list) do
if volume_list[k]._selected == 1 then
volume_selected[#volume_selected+1] = k
end
end
if next(volume_selected) ~= nil then
local success = true
docker:clear_status()
for _,vol in ipairs(volume_selected) do
docker:append_status("Volumes: " .. "remove" .. " " .. vol .. "...")
local msg = dk.volumes["remove"](dk, {id = vol})
if msg.code ~= 204 then
docker:append_status("code:" .. msg.code.." ".. (msg.body.message and msg.body.message or msg.message).. "\n")
success = false
else
docker:append_status("done\n")
end
end
if success then
docker:clear_status()
end
luci.http.redirect(luci.dispatcher.build_url("admin/docker/volumes"))
end
end
return m
|
luci-app-dockerman: cbi/volmes fix volume remove
|
luci-app-dockerman: cbi/volmes fix volume remove
Signed-off-by: Florian Eckert <[email protected]>
|
Lua
|
apache-2.0
|
openwrt/luci,openwrt/luci,openwrt/luci,hnyman/luci,lbthomsen/openwrt-luci,hnyman/luci,lbthomsen/openwrt-luci,hnyman/luci,hnyman/luci,openwrt/luci,openwrt/luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,hnyman/luci,openwrt/luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,hnyman/luci,lbthomsen/openwrt-luci,hnyman/luci,openwrt/luci,hnyman/luci,openwrt/luci,lbthomsen/openwrt-luci
|
aec028dac76127cc74df74f89a9d3cd4cc53f2bb
|
makefiles/premake/RendererModules/OpenGLGUIRenderer/premake.lua
|
makefiles/premake/RendererModules/OpenGLGUIRenderer/premake.lua
|
--
-- OpenGLGUIRenderer premake script
--
cegui_dynamic("OpenGLGUIRenderer")
package.files =
{
matchfiles(pkgdir.."*.cpp"),
matchfiles(pkgdir.."*.h"),
}
include(pkgdir)
include(rootdir)
library("OpenGL32")
library("GLU32")
dependency("CEGUIBase")
if OPENGL_IMAGECODEC == "devil" then
dependency("CEGUIDevILImageCodec")
define("USE_DEVIL_LIBRARY")
elseif OPENGL_IMAGECODEC == "freeimage" then
library("FreeImage", "d")
dependency("CEGUIFreeImageImageCodec")
define("USE_FREEIMAGE_LIBRARY")
elseif OPENGL_IMAGECODEC == "corona" then
library("corona", "_d")
dependency("CEGUICoronaImageCodec")
define("USE_CORONA_LIBRARY")
elseif OPENGL_IMAGECODEC == "silly" then
library("SILLY", "_d")
dependency("CEGUISILLYImageCodec")
define("USE_SILLY_LIBRARY")
else
dependency("CEGUITGAImageCodec")
end
define("OPENGL_GUIRENDERER_EXPORTS")
|
--
-- OpenGLGUIRenderer premake script
--
cegui_dynamic("OpenGLGUIRenderer")
package.files =
{
matchfiles(pkgdir.."*.cpp"),
matchfiles(pkgdir.."*.h"),
}
include(pkgdir)
include(rootdir)
if windows then
library("OpenGL32")
library("GLU32")
define("NOMINMAX")
end
dependency("CEGUIBase")
if OPENGL_IMAGECODEC == "devil" then
dependency("CEGUIDevILImageCodec")
define("USE_DEVIL_LIBRARY")
elseif OPENGL_IMAGECODEC == "freeimage" then
library("FreeImage", "d")
dependency("CEGUIFreeImageImageCodec")
define("USE_FREEIMAGE_LIBRARY")
elseif OPENGL_IMAGECODEC == "corona" then
library("corona", "_d")
dependency("CEGUICoronaImageCodec")
define("USE_CORONA_LIBRARY")
elseif OPENGL_IMAGECODEC == "silly" then
library("SILLY", "_d")
dependency("CEGUISILLYImageCodec")
define("USE_SILLY_LIBRARY")
else
dependency("CEGUITGAImageCodec")
end
define("OPENGL_GUIRENDERER_EXPORTS")
|
Bug fix: Apparently in some cases OpenGLRenderer needs NOMINMAX in Win32 (Mantis #63)
|
Bug fix: Apparently in some cases OpenGLRenderer needs NOMINMAX in Win32 (Mantis #63)
|
Lua
|
mit
|
ruleless/CEGUI,OpenTechEngine/CEGUI,ruleless/CEGUI,OpenTechEngine/CEGUI,ruleless/CEGUI,ruleless/CEGUI,OpenTechEngine/CEGUI,OpenTechEngine/CEGUI
|
4bc8e76fac4688d0430cbeea50c3a959c6b1c72a
|
premake.lua
|
premake.lua
|
project.name = "Premake4"
-- Project options
addoption("no-tests", "Build without automated tests")
-- Output directories
project.config["Debug"].bindir = "bin/debug"
project.config["Release"].bindir = "bin/release"
-- Packages
dopackage("src")
-- Cleanup code
function doclean(cmd, arg)
docommand(cmd, arg)
os.rmdir("bin")
os.rmdir("doc")
end
-- Release code
REPOS = "https://premake.svn.sourceforge.net/svnroot/premake"
TRUNK = "/trunk"
BRANCHES = "/branches/4.0-alpha/"
function dorelease(cmd, arg)
if (not arg) then
error "You must specify a version"
end
-------------------------------------------------------------------
-- Make sure everything is good before I start
-------------------------------------------------------------------
print("")
print("PRE-FLIGHT CHECKLIST")
print(" * is README up-to-date?")
print(" * is CHANGELOG up-to-date?")
print(" * did you test build with GCC?")
print(" * did you test build with Doxygen?")
print(" * are 'svn' (all) and '7z' (Windows) available?")
print("")
print("Press [Enter] to continue or [^C] to quit.")
io.stdin:read("*l")
-------------------------------------------------------------------
-- Set up environment
-------------------------------------------------------------------
local version = arg
os.mkdir("releases")
local folder = "premake-"..version
local trunk = REPOS..TRUNK
local branch = REPOS..BRANCHES..version
-------------------------------------------------------------------
-- Build and run all automated tests
-------------------------------------------------------------------
print("Building tests on working copy...")
os.execute("premake --target gnu > ../releases/release.log")
result = os.execute("make CONFIG=Release >../releases/release.log")
if (result ~= 0) then
error("Test build failed; see release.log for details")
end
-------------------------------------------------------------------
-- Look for a release branch in SVN, and create one from trunk if necessary
-------------------------------------------------------------------
print("Checking for release branch...")
os.chdir("releases")
result = os.execute(string.format("svn ls %s >release.log 2>&1", branch))
if (result ~= 0) then
print("Creating release branch...")
result = os.execute(string.format('svn copy %s %s -m "Creating release branch for %s" >release.log', trunk, branch, version))
if (result ~= 0) then
error("Failed to create release branch at "..branch)
end
end
-------------------------------------------------------------------
-- Checkout a local copy of the release branch
-------------------------------------------------------------------
print("Getting source code from release branch...")
os.execute(string.format("svn co %s %s >release.log", branch, folder))
if (not os.fileexists(folder.."/README.txt")) then
error("Unable to checkout from repository at "..branch)
end
-------------------------------------------------------------------
-- Embed version numbers into the files
-------------------------------------------------------------------
print("TODO - set version number in premake")
-------------------------------------------------------------------
-- Build the release binary for this platform
-------------------------------------------------------------------
print("Building release version...")
os.execute("premake --clean --no-tests --target gnu >../release.log")
os.execute("make CONFIG=Release >../release.log")
if (windows) then
result = os.execute(string.format("7z a -tzip ..\\premake-win32-%s.zip bin\\release\\premake4.exe >../release.log", version))
elseif (macosx) then
error("OSX binary not implemented yet")
else
error("Linux binary not implemented yet")
end
if (result ~= 0) then
error("Failed to build binary package; see release.log for details")
end
-------------------------------------------------------------------
-- Clean up
-------------------------------------------------------------------
print("Cleaning up...")
os.chdir("..")
os.rmdir(folder)
os.remove("release.log")
end
|
project.name = "Premake4"
-- Project options
addoption("no-tests", "Build without automated tests")
-- Output directories
project.config["Debug"].bindir = "bin/debug"
project.config["Release"].bindir = "bin/release"
-- Packages
dopackage("src")
-- Cleanup code
function doclean(cmd, arg)
docommand(cmd, arg)
os.rmdir("bin")
os.rmdir("doc")
end
-- Release code
REPOS = "https://premake.svn.sourceforge.net/svnroot/premake"
TRUNK = "/trunk"
BRANCHES = "/branches/4.0-alpha/"
function dorelease(cmd, arg)
if (not arg) then
error "You must specify a version"
end
-------------------------------------------------------------------
-- Make sure everything is good before I start
-------------------------------------------------------------------
print("")
print("PRE-FLIGHT CHECKLIST")
print(" * is README up-to-date?")
print(" * is CHANGELOG up-to-date?")
print(" * did you test build with GCC?")
print(" * did you test build with Doxygen?")
print(" * are 'svn' (all) and '7z' (Windows) available?")
print("")
print("Press [Enter] to continue or [^C] to quit.")
io.stdin:read("*l")
-------------------------------------------------------------------
-- Set up environment
-------------------------------------------------------------------
local version = arg
os.mkdir("releases")
local folder = "premake-"..version
local trunk = REPOS..TRUNK
local branch = REPOS..BRANCHES..version
-------------------------------------------------------------------
-- Build and run all automated tests on working copy
-------------------------------------------------------------------
print("Building tests on working copy...")
os.execute("premake --target gnu >releases/release.log")
result = os.execute("make CONFIG=Release >releases/release.log")
if (result ~= 0) then
error("Test build failed; see release.log for details")
end
-------------------------------------------------------------------
-- Look for a release branch in SVN, and create one from trunk if necessary
-------------------------------------------------------------------
print("Checking for release branch...")
os.chdir("releases")
result = os.execute(string.format("svn ls %s >release.log 2>&1", branch))
if (result ~= 0) then
print("Creating release branch...")
result = os.execute(string.format('svn copy %s %s -m "Creating release branch for %s" >release.log', trunk, branch, version))
if (result ~= 0) then
error("Failed to create release branch at "..branch)
end
end
-------------------------------------------------------------------
-- Checkout a local copy of the release branch
-------------------------------------------------------------------
print("Getting source code from release branch...")
os.execute(string.format("svn co %s %s >release.log", branch, folder))
if (not os.fileexists(folder.."/README.txt")) then
error("Unable to checkout from repository at "..branch)
end
-------------------------------------------------------------------
-- Embed version numbers into the files
-------------------------------------------------------------------
print("TODO - set version number in premake")
-------------------------------------------------------------------
-- Build the release binary for this platform
-------------------------------------------------------------------
print("Building release version...")
os.chdir(folder)
os.execute("premake --clean --no-tests --target gnu >../release.log")
os.execute("make CONFIG=Release >../release.log")
if (windows) then
result = os.execute(string.format("7z a -tzip ..\\premake-win32-%s.zip bin\\release\\premake4.exe >../release.log", version))
elseif (macosx) then
error("OSX binary not implemented yet")
else
error("Linux binary not implemented yet")
end
if (result ~= 0) then
error("Failed to build binary package; see release.log for details")
end
-------------------------------------------------------------------
-- Clean up
-------------------------------------------------------------------
print("Cleaning up...")
os.chdir("..")
os.rmdir(folder)
os.remove("release.log")
end
|
Minor fixes to release script
|
Minor fixes to release script
|
Lua
|
bsd-3-clause
|
starkos/premake-core,alarouche/premake-core,tvandijck/premake-core,soundsrc/premake-stable,premake/premake-4.x,CodeAnxiety/premake-core,jsfdez/premake-core,lizh06/premake-core,Blizzard/premake-core,tvandijck/premake-core,resetnow/premake-core,martin-traverse/premake-core,Blizzard/premake-core,xriss/premake-core,saberhawk/premake-core,LORgames/premake-core,Yhgenomics/premake-core,Meoo/premake-core,tvandijck/premake-core,tritao/premake-core,dcourtois/premake-core,soundsrc/premake-stable,grbd/premake-core,lizh06/premake-core,Blizzard/premake-core,sleepingwit/premake-core,aleksijuvani/premake-core,PlexChat/premake-core,premake/premake-core,saberhawk/premake-core,mandersan/premake-core,bravnsgaard/premake-core,dcourtois/premake-core,CodeAnxiety/premake-core,aleksijuvani/premake-core,Blizzard/premake-core,saberhawk/premake-core,noresources/premake-core,resetnow/premake-core,Tiger66639/premake-core,Zefiros-Software/premake-core,jsfdez/premake-core,soundsrc/premake-core,starkos/premake-core,kankaristo/premake-core,Blizzard/premake-core,mandersan/premake-core,Zefiros-Software/premake-core,jsfdez/premake-core,soundsrc/premake-stable,felipeprov/premake-core,Zefiros-Software/premake-core,felipeprov/premake-core,jstewart-amd/premake-core,sleepingwit/premake-core,lizh06/premake-4.x,jstewart-amd/premake-core,LORgames/premake-core,bravnsgaard/premake-core,bravnsgaard/premake-core,Tiger66639/premake-core,LORgames/premake-core,CodeAnxiety/premake-core,resetnow/premake-core,noresources/premake-core,premake/premake-4.x,grbd/premake-core,tritao/premake-core,ryanjmulder/premake-4.x,starkos/premake-core,TurkeyMan/premake-core,PlexChat/premake-core,Yhgenomics/premake-core,kankaristo/premake-core,jstewart-amd/premake-core,TurkeyMan/premake-core,ryanjmulder/premake-4.x,grbd/premake-core,xriss/premake-core,jstewart-amd/premake-core,premake/premake-4.x,premake/premake-core,starkos/premake-core,noresources/premake-core,noresources/premake-core,PlexChat/premake-core,akaStiX/premake-core,grbd/premake-core,Zefiros-Software/premake-core,ryanjmulder/premake-4.x,starkos/premake-core,LORgames/premake-core,dcourtois/premake-core,premake/premake-core,LORgames/premake-core,saberhawk/premake-core,soundsrc/premake-core,akaStiX/premake-core,aleksijuvani/premake-core,noresources/premake-core,aleksijuvani/premake-core,mandersan/premake-core,resetnow/premake-core,soundsrc/premake-core,Meoo/premake-core,Yhgenomics/premake-core,mendsley/premake-core,mendsley/premake-core,CodeAnxiety/premake-core,bravnsgaard/premake-core,dcourtois/premake-core,noresources/premake-core,Meoo/premake-core,tvandijck/premake-core,TurkeyMan/premake-core,TurkeyMan/premake-core,tritao/premake-core,mandersan/premake-core,dcourtois/premake-core,premake/premake-core,premake/premake-core,premake/premake-core,martin-traverse/premake-core,xriss/premake-core,soundsrc/premake-core,TurkeyMan/premake-core,Zefiros-Software/premake-core,lizh06/premake-4.x,starkos/premake-core,lizh06/premake-core,premake/premake-core,aleksijuvani/premake-core,sleepingwit/premake-core,resetnow/premake-core,alarouche/premake-core,sleepingwit/premake-core,starkos/premake-core,felipeprov/premake-core,alarouche/premake-core,mendsley/premake-core,lizh06/premake-core,Tiger66639/premake-core,soundsrc/premake-stable,sleepingwit/premake-core,tritao/premake-core,Yhgenomics/premake-core,dcourtois/premake-core,tvandijck/premake-core,premake/premake-4.x,martin-traverse/premake-core,bravnsgaard/premake-core,prapin/premake-core,Tiger66639/premake-core,lizh06/premake-4.x,alarouche/premake-core,xriss/premake-core,prapin/premake-core,kankaristo/premake-core,jsfdez/premake-core,xriss/premake-core,soundsrc/premake-core,prapin/premake-core,prapin/premake-core,martin-traverse/premake-core,lizh06/premake-4.x,dcourtois/premake-core,kankaristo/premake-core,jstewart-amd/premake-core,mendsley/premake-core,mandersan/premake-core,noresources/premake-core,akaStiX/premake-core,akaStiX/premake-core,ryanjmulder/premake-4.x,Blizzard/premake-core,Meoo/premake-core,PlexChat/premake-core,mendsley/premake-core,felipeprov/premake-core,CodeAnxiety/premake-core
|
f5857da6f46ce6cd9994c6547e51251a9e806986
|
profile.lua
|
profile.lua
|
-- Begin of globals
bollards_whitelist = { [""] = true, ["cattle_grid"] = true, ["border_control"] = true, ["toll_booth"] = true, ["no"] = true}
access_tag_whitelist = { ["yes"] = true, ["motorcar"] = true, ["motor_vehicle"] = true, ["vehicle"] = true, ["permissive"] = true, ["designated"] = true }
access_tag_blacklist = { ["no"] = true, ["private"] = true, ["agricultural"] = true, ["forestery"] = true }
access_tag_restricted = { ["destination"] = true, ["delivery"] = true }
access_tags = { "motor_vehicle", "vehicle" }
service_tag_restricted = { ["parking_aisle"] = true }
ignore_in_grid = { ["ferry"] = true, ["pier"] = true }
speed_profile = {
["motorway"] = 90,
["motorway_link"] = 75,
["trunk"] = 85,
["trunk_link"] = 70,
["primary"] = 65,
["primary_link"] = 60,
["secondary"] = 55,
["secondary_link"] = 50,
["tertiary"] = 40,
["tertiary_link"] = 30,
["unclassified"] = 25,
["residential"] = 25,
["living_street"] = 10,
["service"] = 15,
-- ["track"] = 5,
["ferry"] = 5,
["pier"] = 5,
["default"] = 50
}
take_minimum_of_speeds = true
obey_oneway = true
-- End of globals
function node_function (node)
local barrier = node.tags:Find ("barrier")
local access = node.tags:Find ("access")
local traffic_signal = node.tags:Find("highway")
if traffic_signal == "traffic_signals" then
node.traffic_light = true;
end
if access_tag_blacklist[barrier] then
node.bollard = true;
end
if not bollards_whitelist[barrier] and not access_tag_whitelist[barrier] then
node.bollard = true;
end
return 1
end
function way_function (way, numberOfNodesInWay)
-- A way must have two nodes or more
if(numberOfNodesInWay < 2) then
return 0;
end
-- First, get the properties of each way that we come across
local highway = way.tags:Find("highway")
local name = way.tags:Find("name")
local ref = way.tags:Find("ref")
local junction = way.tags:Find("junction")
local route = way.tags:Find("route")
local maxspeed = parseMaxspeed(way.tags:Find ( "maxspeed") )
local man_made = way.tags:Find("man_made")
local barrier = way.tags:Find("barrier")
local oneway = way.tags:Find("oneway")
local cycleway = way.tags:Find("cycleway")
local duration = way.tags:Find("duration")
local service = way.tags:Find("service")
local area = way.tags:Find("area")
local access = way.tags:Find("access")
-- Second parse the way according to these properties
if("yes" == area) then
return 0
end
-- Check if we are allowed to access the way
if access_tag_blacklist[access] ~=nil and access_tag_blacklist[access] then
return 0;
end
-- Check if our vehicle types are forbidden
for i,v in ipairs(access_tags) do
local mode_value = way.tags:Find(v)
if nil ~= mode_value and "no" == mode_value then
return 0;
end
end
-- Set the name that will be used for instructions
if "" ~= ref then
way.name = ref
elseif "" ~= name then
way.name = name
end
if "roundabout" == junction then
way.roundabout = true;
end
-- Handling ferries and piers
if (speed_profile[route] ~= nil and speed_profile[route] > 0) or
(speed_profile[man_made] ~= nil and speed_profile[man_made] > 0)
then
if durationIsValid(duration) then
way.speed = parseDuration / math.max(1, numberOfSegments-1);
way.is_duration_set = true;
end
way.direction = Way.bidirectional;
if speed_profile[route] ~= nil then
highway = route;
elseif speed_profile[man_made] ~= nil then
highway = man_made;
end
if not way.is_duration_set then
way.speed = speed_profile[highway]
end
end
-- Set the avg speed on the way if it is accessible by road class
if (speed_profile[highway] ~= nil and way.speed == -1 ) then
if (0 < maxspeed and not take_minimum_of_speeds) or (maxspeed == 0) then
maxspeed = math.huge
end
way.speed = math.min(speed_profile[highway], maxspeed)
end
-- Set the avg speed on ways that are marked accessible
if access_tag_whitelist[access] and way.speed == -1 then
if (0 < maxspeed and not take_minimum_of_speeds) or maxspeed == 0 then
maxspeed = math.huge
end
way.speed = math.min(speed_profile["default"], maxspeed)
end
-- Set access restriction flag if access is allowed under certain restrictions only
if access ~= "" and access_tag_restricted[access] then
way.is_access_restricted = true
end
-- Set access restriction flag if service is allowed under certain restrictions only
if service ~= "" and service_tag_restricted[service] then
way.is_access_restricted = true
end
-- Set direction according to tags on way
if obey_oneway then
if oneway == "no" or oneway == "0" or oneway == "false" then
way.direction = Way.bidirectional
elseif oneway == "-1" then
way.direction = Way.opposite
elseif oneway == "yes" or oneway == "1" or oneway == "true" or junction == "roundabout" or highway == "motorway_link" or highway == "motorway" then
way.direction = Way.oneway
else
way.direction = Way.bidirectional
end
else
way.direction = Way.bidirectional
end
-- Override general direction settings of there is a specific one for our mode of travel
if ignore_in_grid[highway] ~= nil and ignore_in_grid[highway] then
way.ignore_in_grid = true
end
way.type = 1
return 1
end
|
-- Begin of globals
bollards_whitelist = { [""] = true, ["cattle_grid"] = true, ["border_control"] = true, ["toll_booth"] = true, ["no"] = true}
access_tag_whitelist = { ["yes"] = true, ["motorcar"] = true, ["motor_vehicle"] = true, ["vehicle"] = true, ["permissive"] = true, ["designated"] = true }
access_tag_blacklist = { ["no"] = true, ["private"] = true, ["agricultural"] = true, ["forestery"] = true }
access_tag_restricted = { ["destination"] = true, ["delivery"] = true }
access_tags = { "motorcar", "motor_vehicle", "vehicle" }
service_tag_restricted = { ["parking_aisle"] = true }
ignore_in_grid = { ["ferry"] = true, ["pier"] = true }
speed_profile = {
["motorway"] = 90,
["motorway_link"] = 75,
["trunk"] = 85,
["trunk_link"] = 70,
["primary"] = 65,
["primary_link"] = 60,
["secondary"] = 55,
["secondary_link"] = 50,
["tertiary"] = 40,
["tertiary_link"] = 30,
["unclassified"] = 25,
["residential"] = 25,
["living_street"] = 10,
["service"] = 15,
-- ["track"] = 5,
["ferry"] = 5,
["pier"] = 5,
["default"] = 50
}
take_minimum_of_speeds = true
obey_oneway = true
-- End of globals
function node_function (node)
local barrier = node.tags:Find ("barrier")
local access = node.tags:Find ("access")
local traffic_signal = node.tags:Find("highway")
--flag node if it carries a traffic light
if traffic_signal == "traffic_signals" then
node.traffic_light = true;
end
--flag node as unpassable if it black listed as unpassable
if access_tag_blacklist[barrier] then
node.bollard = true;
end
--reverse the previous flag if there is an access tag specifying entrance
if node.bollard and not bollards_whitelist[barrier] and not access_tag_whitelist[barrier] then
node.bollard = false;
end
return 1
end
function way_function (way, numberOfNodesInWay)
-- A way must have two nodes or more
if(numberOfNodesInWay < 2) then
return 0;
end
-- First, get the properties of each way that we come across
local highway = way.tags:Find("highway")
local name = way.tags:Find("name")
local ref = way.tags:Find("ref")
local junction = way.tags:Find("junction")
local route = way.tags:Find("route")
local maxspeed = parseMaxspeed(way.tags:Find ( "maxspeed") )
local man_made = way.tags:Find("man_made")
local barrier = way.tags:Find("barrier")
local oneway = way.tags:Find("oneway")
local cycleway = way.tags:Find("cycleway")
local duration = way.tags:Find("duration")
local service = way.tags:Find("service")
local area = way.tags:Find("area")
local access = way.tags:Find("access")
-- Second parse the way according to these properties
if("yes" == area) then
return 0
end
-- Check if we are allowed to access the way
if access_tag_blacklist[access] ~=nil and access_tag_blacklist[access] then
return 0;
end
-- Check if our vehicle types are forbidden
for i,v in ipairs(access_tags) do
local mode_value = way.tags:Find(v)
if nil ~= mode_value and "no" == mode_value then
return 0;
end
end
-- Set the name that will be used for instructions
if "" ~= ref then
way.name = ref
elseif "" ~= name then
way.name = name
end
if "roundabout" == junction then
way.roundabout = true;
end
-- Handling ferries and piers
if (speed_profile[route] ~= nil and speed_profile[route] > 0) or
(speed_profile[man_made] ~= nil and speed_profile[man_made] > 0)
then
if durationIsValid(duration) then
way.speed = parseDuration / math.max(1, numberOfSegments-1);
way.is_duration_set = true;
end
way.direction = Way.bidirectional;
if speed_profile[route] ~= nil then
highway = route;
elseif speed_profile[man_made] ~= nil then
highway = man_made;
end
if not way.is_duration_set then
way.speed = speed_profile[highway]
end
end
-- Set the avg speed on the way if it is accessible by road class
if (speed_profile[highway] ~= nil and way.speed == -1 ) then
if (0 < maxspeed and not take_minimum_of_speeds) or (maxspeed == 0) then
maxspeed = math.huge
end
way.speed = math.min(speed_profile[highway], maxspeed)
end
-- Set the avg speed on ways that are marked accessible
if access_tag_whitelist[access] and way.speed == -1 then
if (0 < maxspeed and not take_minimum_of_speeds) or maxspeed == 0 then
maxspeed = math.huge
end
way.speed = math.min(speed_profile["default"], maxspeed)
end
-- Set access restriction flag if access is allowed under certain restrictions only
if access ~= "" and access_tag_restricted[access] then
way.is_access_restricted = true
end
-- Set access restriction flag if service is allowed under certain restrictions only
if service ~= "" and service_tag_restricted[service] then
way.is_access_restricted = true
end
-- Set direction according to tags on way
if obey_oneway then
if oneway == "no" or oneway == "0" or oneway == "false" then
way.direction = Way.bidirectional
elseif oneway == "-1" then
way.direction = Way.opposite
elseif oneway == "yes" or oneway == "1" or oneway == "true" or junction == "roundabout" or highway == "motorway_link" or highway == "motorway" then
way.direction = Way.oneway
else
way.direction = Way.bidirectional
end
else
way.direction = Way.bidirectional
end
-- Override general direction settings of there is a specific one for our mode of travel
if ignore_in_grid[highway] ~= nil and ignore_in_grid[highway] then
way.ignore_in_grid = true
end
way.type = 1
return 1
end
|
Fixes issue #394
|
Fixes issue #394
|
Lua
|
bsd-2-clause
|
tkhaxton/osrm-backend,KnockSoftware/osrm-backend,alex85k/Project-OSRM,nagyistoce/osrm-backend,arnekaiser/osrm-backend,raymond0/osrm-backend,ammeurer/osrm-backend,frodrigo/osrm-backend,agruss/osrm-backend,raymond0/osrm-backend,raymond0/osrm-backend,Conggge/osrm-backend,Project-OSRM/osrm-backend,atsuyim/osrm-backend,neilbu/osrm-backend,stevevance/Project-OSRM,ibikecph/osrm-backend,ammeurer/osrm-backend,nagyistoce/osrm-backend,beemogmbh/osrm-backend,ramyaragupathy/osrm-backend,frodrigo/osrm-backend,arnekaiser/osrm-backend,beemogmbh/osrm-backend,arnekaiser/osrm-backend,bjtaylor1/Project-OSRM-Old,stevevance/Project-OSRM,duizendnegen/osrm-backend,bitsteller/osrm-backend,prembasumatary/osrm-backend,keesklopt/matrix,Tristramg/osrm-backend,alex85k/Project-OSRM,Tristramg/osrm-backend,arnekaiser/osrm-backend,alex85k/Project-OSRM,Project-OSRM/osrm-backend,yuryleb/osrm-backend,deniskoronchik/osrm-backend,ammeurer/osrm-backend,yuryleb/osrm-backend,Project-OSRM/osrm-backend,oxidase/osrm-backend,Conggge/osrm-backend,Conggge/osrm-backend,skyborla/osrm-backend,neilbu/osrm-backend,hydrays/osrm-backend,bjtaylor1/osrm-backend,stevevance/Project-OSRM,frodrigo/osrm-backend,antoinegiret/osrm-backend,bjtaylor1/osrm-backend,Carsten64/OSRM-aux-git,beemogmbh/osrm-backend,bjtaylor1/osrm-backend,bitsteller/osrm-backend,bjtaylor1/Project-OSRM-Old,jpizarrom/osrm-backend,chaupow/osrm-backend,ammeurer/osrm-backend,ammeurer/osrm-backend,hydrays/osrm-backend,stevevance/Project-OSRM,bitsteller/osrm-backend,keesklopt/matrix,chaupow/osrm-backend,beemogmbh/osrm-backend,prembasumatary/osrm-backend,duizendnegen/osrm-backend,skyborla/osrm-backend,raymond0/osrm-backend,neilbu/osrm-backend,hydrays/osrm-backend,antoinegiret/osrm-backend,oxidase/osrm-backend,chaupow/osrm-backend,deniskoronchik/osrm-backend,yuryleb/osrm-backend,KnockSoftware/osrm-backend,duizendnegen/osrm-backend,Carsten64/OSRM-aux-git,tkhaxton/osrm-backend,yuryleb/osrm-backend,hydrays/osrm-backend,antoinegiret/osrm-geovelo,bjtaylor1/Project-OSRM-Old,ramyaragupathy/osrm-backend,ammeurer/osrm-backend,antoinegiret/osrm-backend,tkhaxton/osrm-backend,bjtaylor1/osrm-backend,keesklopt/matrix,neilbu/osrm-backend,Conggge/osrm-backend,KnockSoftware/osrm-backend,Carsten64/OSRM-aux-git,oxidase/osrm-backend,antoinegiret/osrm-geovelo,frodrigo/osrm-backend,Tristramg/osrm-backend,oxidase/osrm-backend,jpizarrom/osrm-backend,Project-OSRM/osrm-backend,felixguendling/osrm-backend,ramyaragupathy/osrm-backend,ammeurer/osrm-backend,skyborla/osrm-backend,ibikecph/osrm-backend,duizendnegen/osrm-backend,keesklopt/matrix,prembasumatary/osrm-backend,atsuyim/osrm-backend,KnockSoftware/osrm-backend,deniskoronchik/osrm-backend,agruss/osrm-backend,ibikecph/osrm-backend,jpizarrom/osrm-backend,nagyistoce/osrm-backend,deniskoronchik/osrm-backend,atsuyim/osrm-backend,felixguendling/osrm-backend,bjtaylor1/Project-OSRM-Old,Carsten64/OSRM-aux-git,felixguendling/osrm-backend,agruss/osrm-backend,antoinegiret/osrm-geovelo
|
c55a27d3c2cb278bb1e758ef0605b1253e3cd7b4
|
src/logfactory/LogLoader.lua
|
src/logfactory/LogLoader.lua
|
local LogLoader = {};
-- ------------------------------------------------
-- Constants
-- ------------------------------------------------
local LOG_FOLDER = 'logs';
local LOG_FILE = 'log.txt';
local INFO_FILE = 'info.lua';
local TAG_INFO = 'info: ';
local ROOT_FOLDER = 'root';
local WARNING_TITLE = 'No git log found.';
local WARNING_MESSAGE = [[
Looks like you are using LoGiVi for the first time. An example git log has been created in the save directory. Press 'Yes' to open the save directory.
Press 'Show Help' to view the wiki (online) for more information on how to generate a proper log.
Press 'No' to proceed to the selection screen from where you can view the example project.
]];
local EXAMPLE_TEMPLATE_PATH = 'res/templates/example_log.txt';
local EXAMPLE_TARGET_PATH = 'logs/example/';
-- ------------------------------------------------
-- Local variables
-- ------------------------------------------------
local list;
-- ------------------------------------------------
-- Local Functions
-- ------------------------------------------------
---
-- Remove the specified tag from the line.
-- @param line
-- @param tag
--
local function removeTag(line, tag)
return line:gsub(tag, '');
end
---
-- @param author
--
local function splitLine(line, delimiter)
local tmp = {}
for part in line:gmatch('[^' .. delimiter .. ']+') do
tmp[#tmp + 1] = part;
end
return tmp;
end
---
-- Creates a list of all folders found in the LOG_FOLDER directory, which
-- contain a LOG_FILE. Returns a sequence which contains the names of the folders
-- and the path to the log files in those folders.
-- @param dir
--
local function fetchProjectFolders(dir)
local folders = {};
for _, name in ipairs(love.filesystem.getDirectoryItems(dir)) do
local subdir = dir .. '/' .. name;
if love.filesystem.isDirectory(subdir) and love.filesystem.isFile(subdir .. '/' .. LOG_FILE) then
folders[#folders + 1] = { name = name, path = subdir .. '/' .. LOG_FILE };
end
end
return folders;
end
---
-- Reads the whole log file and stores each line in a sequence.
-- @param path
--
local function parseLog(path)
local file = {};
for line in love.filesystem.lines(path) do
if line ~= '' then
file[#file + 1] = line;
end
end
return file;
end
---
-- Turns a unix timestamp into a human readable date string.
-- @param timestamp
--
local function createDateFromUnixTimestamp(timestamp)
local date = os.date('*t', tonumber(timestamp));
return string.format("%02d:%02d:%02d - %02d-%02d-%04d", date.hour, date.min, date.sec, date.day, date.month, date.year);
end
---
-- Splits the log table into commits. Each commit is a new nested table.
-- @param log
--
local function splitCommits(log)
local commits = {};
local index = 0;
for i = 1, #log do
local line = log[i];
if line:find(TAG_INFO) then
index = index + 1;
commits[index] = {};
local info = splitLine(removeTag(line, TAG_INFO), '|');
commits[index].author, commits[index].email, commits[index].date = info[1], info[2], info[3];
-- Transform unix timestamp to a table containing a human-readable date.
commits[index].date = createDateFromUnixTimestamp(commits[index].date);
elseif commits[index] then
-- Split the whole change line into modifier, file name and file path fields.
local path = line:gsub("^(%a)%s*", ''); -- Remove modifier and whitespace.
local file = path:match("/?([^/]+)$"); -- Get the the filename at the end.
path = path:gsub("/?([^/]+)$", ''); -- Remove the filename from the path.
if path ~= '' then
path = '/' .. path;
end
commits[index][#commits[index] + 1] = { modifier = line:sub(1, 1), path = ROOT_FOLDER .. path, file = file };
end
end
return commits;
end
---
-- Returns the index of a stored log if it can be found.
-- @param name
--
local function searchLog(name)
for i, log in ipairs(list) do
if log.name == name then
return i;
end
end
end
---
-- Checks if the log folder exists and if it is empty or not.
--
local function hasLogs()
return (love.filesystem.isDirectory('logs') and #list ~= 0);
end
---
-- Displays a warning message for the user which gives him the option
-- to open the wiki page or the folder in which the logs need to be placed.
--
local function showWarning()
local buttons = { "Yes", "No", "Show Help (Online)", enterbutton = 1, escapebutton = 2 };
local pressedbutton = love.window.showMessageBox(WARNING_TITLE, WARNING_MESSAGE, buttons, 'warning', false);
if pressedbutton == 1 then
love.system.openURL('file://' .. love.filesystem.getSaveDirectory() .. '/logs');
elseif pressedbutton == 3 then
love.system.openURL('https://github.com/rm-code/logivi/wiki#instructions');
end
end
---
-- Write an example log file to the save directory.
--
local function createExample()
love.filesystem.createDirectory(EXAMPLE_TARGET_PATH);
if not love.filesystem.isFile(EXAMPLE_TARGET_PATH .. LOG_FILE) then
local example = love.filesystem.read(EXAMPLE_TEMPLATE_PATH);
love.filesystem.write(EXAMPLE_TARGET_PATH .. LOG_FILE, example);
end
end
-- ------------------------------------------------
-- Public Functions
-- ------------------------------------------------
---
-- Try to load a certain log stored in the list.
--
function LogLoader.load(log)
local index = searchLog(log);
local rawLog = parseLog(list[index].path);
return splitCommits(rawLog);
end
---
-- Loads information about a git repository.
-- @param name
--
function LogLoader.loadInfo(name)
if love.filesystem.isFile(LOG_FOLDER .. '/' .. name .. '/' .. INFO_FILE) then
local info = love.filesystem.load(LOG_FOLDER .. '/' .. name .. '/' .. INFO_FILE)();
info.firstCommit = createDateFromUnixTimestamp(info.firstCommit);
info.latestCommit = createDateFromUnixTimestamp(info.latestCommit);
info.aliases = info.aliases or {};
info.avatars = info.avatars or {};
info.colors = info.colors or {};
return info;
end
return {
name = name,
firstCommit = '<no information available>',
latestCommit = '<no information available>',
totalCommits = '<no information available>',
aliases = {},
avatars = {},
colors = {},
};
end
---
-- Initialises the LogLoader. It will fetch a list of all folders
-- containing a log file. If the list is empty it will display a
-- warning to the user.
--
function LogLoader.init()
list = fetchProjectFolders(LOG_FOLDER);
if not hasLogs() then
createExample();
showWarning();
list = fetchProjectFolders(LOG_FOLDER);
end
return list;
end
return LogLoader;
|
local LogLoader = {};
-- ------------------------------------------------
-- Constants
-- ------------------------------------------------
local LOG_FOLDER = 'logs';
local LOG_FILE = 'log.txt';
local INFO_FILE = 'info.lua';
local TAG_INFO = 'info: ';
local ROOT_FOLDER = 'root';
local WARNING_TITLE = 'No git log found.';
local WARNING_MESSAGE = [[
Looks like you are using LoGiVi for the first time. An example git log has been created in the save directory. Press 'Yes' to open the save directory.
Press 'Show Help' to view the wiki (online) for more information on how to generate a proper log.
Press 'No' to proceed to the selection screen from where you can view the example project.
]];
local EXAMPLE_TEMPLATE_PATH = 'res/templates/example_log.txt';
local EXAMPLE_TARGET_PATH = 'logs/example/';
-- ------------------------------------------------
-- Local variables
-- ------------------------------------------------
local list;
-- ------------------------------------------------
-- Local Functions
-- ------------------------------------------------
---
-- Remove the specified tag from the line.
-- @param line
-- @param tag
--
local function removeTag(line, tag)
return line:gsub(tag, '');
end
---
-- @param author
--
local function splitLine(line, delimiter)
local tmp = {}
for part in line:gmatch('[^' .. delimiter .. ']+') do
tmp[#tmp + 1] = part;
end
return tmp;
end
---
-- Creates a list of all folders found in the LOG_FOLDER directory, which
-- contain a LOG_FILE. Returns a sequence which contains the names of the folders
-- and the path to the log files in those folders.
-- @param dir
--
local function fetchProjectFolders(dir)
local folders = {};
for _, name in ipairs(love.filesystem.getDirectoryItems(dir)) do
local subdir = dir .. '/' .. name;
if love.filesystem.isDirectory(subdir) and love.filesystem.isFile(subdir .. '/' .. LOG_FILE) then
folders[#folders + 1] = { name = name, path = subdir .. '/' .. LOG_FILE };
end
end
return folders;
end
---
-- Reads the whole log file and stores each line in a sequence.
-- @param path
--
local function parseLog(path)
local file = {};
for line in love.filesystem.lines(path) do
if line ~= '' then
file[#file + 1] = line;
end
end
return file;
end
---
-- Turns a unix timestamp into a human readable date string.
-- @param timestamp
--
local function createDateFromUnixTimestamp(timestamp)
local date = os.date('*t', tonumber(timestamp));
return string.format("%02d:%02d:%02d - %02d-%02d-%04d", date.hour, date.min, date.sec, date.day, date.month, date.year);
end
---
-- Splits the log table into commits. Each commit is a new nested table.
-- @param log
--
local function splitCommits(log)
local commits = {};
local index = 0;
for i = 1, #log do
local line = log[i];
if line:find(TAG_INFO) then
index = index + 1;
commits[index] = {};
local info = splitLine(removeTag(line, TAG_INFO), '|');
commits[index].author, commits[index].email, commits[index].date = info[1], info[2], info[3];
-- Transform unix timestamp to a table containing a human-readable date.
commits[index].date = createDateFromUnixTimestamp(commits[index].date);
elseif commits[index] then
-- Split the whole change line into modifier, file name and file path fields.
local path = line:gsub("^(%a)%s*", ''); -- Remove modifier and whitespace.
local file = path:match("/?([^/]+)$"); -- Get the the filename at the end.
path = path:gsub("/?([^/]+)$", ''); -- Remove the filename from the path.
if path ~= '' then
path = '/' .. path;
end
commits[index][#commits[index] + 1] = { modifier = line:sub(1, 1), path = ROOT_FOLDER .. path, file = file };
end
end
return commits;
end
---
-- Returns the index of a stored log if it can be found.
-- @param name
--
local function searchLog(name)
for i, log in ipairs(list) do
if log.name == name then
return i;
end
end
end
---
-- Checks if the log folder exists and if it is empty or not.
--
local function hasLogs()
return (love.filesystem.isDirectory('logs') and #list ~= 0);
end
---
-- Displays a warning message for the user which gives him the option
-- to open the wiki page or the folder in which the logs need to be placed.
--
local function showWarning()
local buttons = { "Yes", "No", "Show Help (Online)", enterbutton = 1, escapebutton = 2 };
local pressedbutton = love.window.showMessageBox(WARNING_TITLE, WARNING_MESSAGE, buttons, 'warning', false);
if pressedbutton == 1 then
love.system.openURL('file://' .. love.filesystem.getSaveDirectory() .. '/logs');
elseif pressedbutton == 3 then
love.system.openURL('https://github.com/rm-code/logivi/wiki#instructions');
end
end
---
-- Write an example log file to the save directory.
--
local function createExample()
love.filesystem.createDirectory(EXAMPLE_TARGET_PATH);
if not love.filesystem.isFile(EXAMPLE_TARGET_PATH .. LOG_FILE) then
local example = love.filesystem.read(EXAMPLE_TEMPLATE_PATH);
love.filesystem.write(EXAMPLE_TARGET_PATH .. LOG_FILE, example);
end
end
-- ------------------------------------------------
-- Public Functions
-- ------------------------------------------------
---
-- Try to load a certain log stored in the list.
--
function LogLoader.load(log)
local index = searchLog(log);
local rawLog = parseLog(list[index].path);
return splitCommits(rawLog);
end
---
-- Loads information about a git repository.
-- @param name
--
function LogLoader.loadInfo(name)
if love.filesystem.isFile(LOG_FOLDER .. '/' .. name .. '/' .. INFO_FILE) then
local successful, info = pcall(love.filesystem.load, LOG_FOLDER .. '/' .. name .. '/' .. INFO_FILE);
if successful then
info = info(); -- Run the lua file.
info.firstCommit = createDateFromUnixTimestamp(info.firstCommit);
info.latestCommit = createDateFromUnixTimestamp(info.latestCommit);
info.aliases = info.aliases or {};
info.avatars = info.avatars or {};
info.colors = info.colors or {};
return info;
end
end
return {
name = name,
firstCommit = '<no information available>',
latestCommit = '<no information available>',
totalCommits = '<no information available>',
aliases = {},
avatars = {},
colors = {},
};
end
---
-- Initialises the LogLoader. It will fetch a list of all folders
-- containing a log file. If the list is empty it will display a
-- warning to the user.
--
function LogLoader.init()
list = fetchProjectFolders(LOG_FOLDER);
if not hasLogs() then
createExample();
showWarning();
list = fetchProjectFolders(LOG_FOLDER);
end
return list;
end
return LogLoader;
|
Fix #42 - Encapsulate love.filesystem.load in pcall to prevent crash
|
Fix #42 - Encapsulate love.filesystem.load in pcall to prevent crash
This basically runs the function in a protected environment and catches
any errors. If everything works out fine it returns true and the
function's return values.
|
Lua
|
mit
|
rm-code/logivi
|
6d52800c279974affdc8a5c244c56f88ab53bada
|
core/ext/pm/buffer_browser.lua
|
core/ext/pm/buffer_browser.lua
|
-- Copyright 2007-2008 Mitchell Foral mitchell<att>caladbolg.net. See LICENSE.
---
-- Buffer browser for the Textadept project manager.
-- It is enabled with the prefix 'buffers' in the project manager entry field.
module('textadept.pm.browsers.buffer', package.seeall)
function matches(entry_text)
return entry_text:sub(1, 7) == 'buffers'
end
function get_contents_for()
local contents = {}
for index, buffer in ipairs(textadept.buffers) do
index = string.format("%02i", index)
contents[index] = {
pixbuf = buffer.dirty and 'gtk-edit' or 'gtk-file',
text = (buffer.filename or 'Untitled'):match('[^/]+$')
}
end
return contents
end
function perform_action(selected_item)
local index = selected_item[2]
local buffer = textadept.buffers[ tonumber(index) ]
if buffer then view:goto_buffer(index) view:focus() end
end
function get_context_menu(selected_item)
return { '_New', '_Open', '_Save', 'Save _As...', 'separator', '_Close' }
end
function perform_menu_action(menu_item, selected_item)
if menu_item == 'New' then
textadept.new_buffer()
elseif menu_item == 'Open' then
textadept.io.open()
elseif menu_item == 'Save' then
textadept.buffers[ tonumber( selected_item[2] ) ]:save()
elseif menu_item == 'Save As...' then
textadept.buffers[ tonumber( selected_item[2] ) ]:save_as()
elseif menu_item == 'Close' then
textadept.buffers[ tonumber( selected_item[2] ) ]:close()
end
textadept.pm.activate()
end
local add_handler = textadept.events.add_handler
local function update_view()
if matches(textadept.pm.entry_text) then textadept.pm.activate() end
end
add_handler('file_opened', update_view)
add_handler('buffer_new', update_view)
add_handler('buffer_deleted', update_view)
add_handler('save_point_reached', update_view)
add_handler('save_point_left', update_view)
|
-- Copyright 2007-2008 Mitchell Foral mitchell<att>caladbolg.net. See LICENSE.
---
-- Buffer browser for the Textadept project manager.
-- It is enabled with the prefix 'buffers' in the project manager entry field.
module('textadept.pm.browsers.buffer', package.seeall)
function matches(entry_text)
return entry_text:sub(1, 7) == 'buffers'
end
function get_contents_for()
local contents = {}
for index, buffer in ipairs(textadept.buffers) do
index = string.format("%02i", index)
contents[index] = {
pixbuf = buffer.dirty and 'gtk-edit' or 'gtk-file',
text = (buffer.filename or 'Untitled'):match('[^/]+$')
}
end
return contents
end
function perform_action(selected_item)
local index = selected_item[2]
local buffer = textadept.buffers[ tonumber(index) ]
if buffer then view:goto_buffer(index) view:focus() end
end
function get_context_menu(selected_item)
return { '_New', '_Open', '_Save', 'Save _As...', 'separator', '_Close' }
end
function perform_menu_action(menu_item, selected_item)
if menu_item == 'New' then
textadept.new_buffer()
elseif menu_item == 'Open' then
textadept.io.open()
elseif menu_item == 'Save' then
view:goto_buffer( tonumber( selected_item[2] ) )
buffer:save()
elseif menu_item == 'Save As...' then
view:goto_buffer( tonumber( selected_item[2] ) )
buffer:save_as()
elseif menu_item == 'Close' then
view:goto_buffer( tonumber( selected_item[2] ) )
buffer:close()
end
textadept.pm.activate()
end
local add_handler = textadept.events.add_handler
local function update_view()
if matches(textadept.pm.entry_text) then textadept.pm.activate() end
end
add_handler('file_opened', update_view)
add_handler('buffer_new', update_view)
add_handler('buffer_deleted', update_view)
add_handler('save_point_reached', update_view)
add_handler('save_point_left', update_view)
|
Fixed bug for menu actions on non-focused buffer; core/ext/pm/buffer_browser.lua
|
Fixed bug for menu actions on non-focused buffer; core/ext/pm/buffer_browser.lua
|
Lua
|
mit
|
jozadaquebatista/textadept,jozadaquebatista/textadept
|
eb22714863cfd95a2a2d866efb63787fc137092e
|
game/scripts/vscripts/modules/structures/modifier_fountain_aura_arena.lua
|
game/scripts/vscripts/modules/structures/modifier_fountain_aura_arena.lua
|
local FOUNTAIN_PERCENTAGE_MANA_REGEN = 15
local FOUNTAIN_PERCENTAGE_HEALTH_REGEN = 15
modifier_fountain_aura_arena = class({
IsPurgable = function() return false end,
GetModifierHealthRegenPercentage = function() return FOUNTAIN_PERCENTAGE_MANA_REGEN end,
GetModifierTotalPercentageManaRegen = function() return FOUNTAIN_PERCENTAGE_HEALTH_REGEN end,
GetTexture = function() return "fountain_heal" end,
})
function modifier_fountain_aura_arena:DeclareFunctions()
return {
MODIFIER_PROPERTY_HEALTH_REGEN_PERCENTAGE,
MODIFIER_PROPERTY_MANA_REGEN_TOTAL_PERCENTAGE
}
end
if IsServer() then
function modifier_fountain_aura_arena:OnCreated()
self:StartIntervalThink(0.25)
self:OnIntervalThink()
end
function modifier_fountain_aura_arena:OnDestroy()
self:GetParent():RemoveModifierByName("modifier_fountain_aura_invulnerability")
end
local centralBossKilled = false
Events:Register("bosses/kill/central", "fountain", function ()
centralBossKilled = true
end)
Events:Register("bosses/respawn/central", "fountain", function ()
centralBossKilled = false
end)
function modifier_fountain_aura_arena:OnIntervalThink()
local parent = self:GetParent()
while parent:HasModifier("modifier_saber_mana_burst_active") do
parent:RemoveModifierByName("modifier_saber_mana_burst_active")
end
if parent:IsCourier() then return end
for i = 0, 11 do
local item = parent:GetItemInSlot(i)
if item and item:GetAbilityName() == "item_bottle_arena" then
item:SetCurrentCharges(3)
end
end
local hasMod = parent:HasModifier("modifier_fountain_aura_invulnerability")
if not centralBossKilled and not hasMod then
parent:AddNewModifier(parent, nil, "modifier_fountain_aura_invulnerability", nil)
elseif centralBossKilled and hasMod then
parent:RemoveModifierByName("modifier_fountain_aura_invulnerability")
end
end
end
modifier_fountain_aura_invulnerability = class({
IsPurgable = function() return false end,
GetMinHealth = function() return 1 end,
GetAbsoluteNoDamagePhysical = function() return 1 end,
GetAbsoluteNoDamageMagical = function() return 1 end,
GetAbsoluteNoDamagePure = function() return 1 end,
GetTexture = function() return "modifier_invulnerable" end,
})
function modifier_fountain_aura_invulnerability:DeclareFunctions()
return {
MODIFIER_PROPERTY_MIN_HEALTH,
MODIFIER_PROPERTY_ABSOLUTE_NO_DAMAGE_PHYSICAL,
MODIFIER_PROPERTY_ABSOLUTE_NO_DAMAGE_MAGICAL,
MODIFIER_PROPERTY_ABSOLUTE_NO_DAMAGE_PURE,
MODIFIER_PROPERTY_TOOLTIP
}
end
|
local FOUNTAIN_PERCENTAGE_MANA_REGEN = 15
local FOUNTAIN_PERCENTAGE_HEALTH_REGEN = 15
modifier_fountain_aura_arena = class({
IsPurgable = function() return false end,
GetModifierHealthRegenPercentage = function() return FOUNTAIN_PERCENTAGE_MANA_REGEN end,
GetModifierTotalPercentageManaRegen = function() return FOUNTAIN_PERCENTAGE_HEALTH_REGEN end,
GetTexture = function() return "fountain_heal" end,
})
function modifier_fountain_aura_arena:DeclareFunctions()
return {
MODIFIER_PROPERTY_HEALTH_REGEN_PERCENTAGE,
MODIFIER_PROPERTY_MANA_REGEN_TOTAL_PERCENTAGE
}
end
if IsServer() then
function modifier_fountain_aura_arena:OnCreated()
self:StartIntervalThink(0.25)
self:OnIntervalThink()
end
function modifier_fountain_aura_arena:OnDestroy()
self:GetParent():RemoveModifierByName("modifier_fountain_aura_invulnerability")
end
local centralBossKilled = false
Events:Register("bosses/kill/central", "fountain", function ()
centralBossKilled = true
end)
Events:Register("bosses/respawn/central", "fountain", function ()
centralBossKilled = false
end)
function modifier_fountain_aura_arena:OnIntervalThink()
local parent = self:GetParent()
while parent:HasModifier("modifier_saber_mana_burst_active") do
parent:RemoveModifierByName("modifier_saber_mana_burst_active")
end
local hasMod = parent:HasModifier("modifier_fountain_aura_invulnerability")
if not centralBossKilled and not hasMod then
parent:AddNewModifier(parent, nil, "modifier_fountain_aura_invulnerability", nil)
elseif centralBossKilled and hasMod then
parent:RemoveModifierByName("modifier_fountain_aura_invulnerability")
end
if parent:IsCourier() then return end
for i = 0, 11 do
local item = parent:GetItemInSlot(i)
if item and item:GetAbilityName() == "item_bottle_arena" then
item:SetCurrentCharges(3)
end
end
end
end
modifier_fountain_aura_invulnerability = class({
IsPurgable = function() return false end,
GetMinHealth = function() return 1 end,
GetAbsoluteNoDamagePhysical = function() return 1 end,
GetAbsoluteNoDamageMagical = function() return 1 end,
GetAbsoluteNoDamagePure = function() return 1 end,
GetTexture = function() return "modifier_invulnerable" end,
})
function modifier_fountain_aura_invulnerability:DeclareFunctions()
return {
MODIFIER_PROPERTY_MIN_HEALTH,
MODIFIER_PROPERTY_ABSOLUTE_NO_DAMAGE_PHYSICAL,
MODIFIER_PROPERTY_ABSOLUTE_NO_DAMAGE_MAGICAL,
MODIFIER_PROPERTY_ABSOLUTE_NO_DAMAGE_PURE,
MODIFIER_PROPERTY_TOOLTIP
}
end
|
fix)ability): parent check worked incorrectly
|
fix)ability): parent check worked incorrectly
|
Lua
|
mit
|
ark120202/aabs
|
ed61f27fe85bb861d943eb4a6d433a2b4e5b08ba
|
.conky.d/github_grass.lua
|
.conky.d/github_grass.lua
|
#!/usr/bin/lua
local https = require 'ssl.https'
require 'os'
require 'rsvg'
require 'cairo'
user = "kizkoh"
start_match = " <svg width=\"676\" height=\"104\" class=\"js-calendar-graph-svg\">"
end_match = "</svg>"
after_date = os.date("%Y.%m.%d", os.time() - 60 * 60 * 24 * (169 + tonumber(os.date("%u", os.time()), 10) - 1))
today_date = os.date("%Y.%m.%d")
alert_color = "#D104D1"
function conky_get_github_grass()
local resp = {}
tmpfile = io.open("/dev/shm/grass.tmp", "w")
local one, code, headers, status = https.request{
url = "http://github.com/" .. user,
sink = ltn12.sink.file(tmpfile),
protocol = "tlsv1"
}
local tmpfile = io.open("/dev/shm/grass.tmp", "r")
local svgfile = io.open("/dev/shm/grass.svg", "w")
local in_svg = false
local in_exclude = false
local in_week = false
horizon_pos = 13
for line in tmpfile:lines() do
if not in_svg and line == start_match then
in_svg = true
end
if in_svg then
if not in_exclude then
if line:find("<g transform=\"translate%(0, 0%)\">") ~= nil then
in_exclude = true
else
if string.find(line, "Sun") ~= nil then
in_week = true
elseif string.find(line, "Sat") ~= nil then
line = ""
in_week = false
end
if in_week then
line = ""
end
-- Date matches today
if string.find(line, today_date) ~= nil then
line = string.gsub(line, "#ebedf0", alert_color)
end
-- Generate new translate
if string.find(line, "<g transform=\"translate%(%d+, 0%)\">") ~= nil then
line = " <g transform=\"translate(" .. tostring(horizon_pos) .. ", 0)\">"
horizon_pos_tmp = horizon_pos + 13
horizon_pos = horizon_pos_tmp
end
if line:find("<text .*") ~= nil then
line = ""
end
svgfile:write(line .. "\n")
end
else
if string.find(line, after_date) ~= nil then
svgfile:write(" <g transform=\"translate(0, 0)\">" .. "\n")
svgfile:write(line .. "\n")
in_exclude = false
end
end
if in_svg and line == end_match then
break
end
end
end
tmpfile:close()
svgfile:close()
end
function conky_draw_github_grass_pre()
if conky_window == nil then
return
end
cairo_surface = cairo_xlib_surface_create(conky_window.display,
conky_window.drawable,
conky_window.visual,
conky_window.width,
conky_window.height)
local cairo = cairo_create(cairo_surface)
cairo_translate(cairo, 0, 640)
cairo_scale(cairo, 1.6, 1.6)
rsvg_handle_render_cairo(rsvg_handle, cairo)
cairo_destroy(cairo)
end
function conky_draw_github_grass_post()
cairo_surface_destroy(cairo_surface)
end
rsvg_handle = rsvg_create_handle_from_file("/dev/shm/grass.svg")
conky_get_github_grass()
cairo_surface = nil
cairo = nil
|
#!/usr/bin/lua
local https = require 'ssl.https'
require 'os'
require 'rsvg'
require 'cairo'
user = "kizkoh"
start_match = " <svg width=\"676\" height=\"104\" class=\"js-calendar-graph-svg\">"
end_match = "</svg>"
after_date = os.date("%Y.%m.%d", os.time() - 60 * 60 * 24 * (169 + tonumber(os.date("%u", os.time()), 10) - 1))
today_date = os.date("%Y.%m.%d")
alert_color = "#D104D1"
function conky_get_github_grass()
local resp = {}
tmpfile = io.open("/dev/shm/grass.tmp", "w")
local one, code, headers, status = https.request{
url = "http://github.com/" .. user,
sink = ltn12.sink.file(tmpfile),
protocol = "tlsv1"
}
local tmpfile = io.open("/dev/shm/grass.tmp", "r")
local svgfile = io.open("/dev/shm/grass.svg", "w")
local in_svg = false
local in_exclude = false
local in_week = false
horizon_pos = 13
for line in tmpfile:lines() do
if not in_svg and line == start_match then
in_svg = true
end
if in_svg then
if not in_exclude then
if line:find("<g transform=\"translate%(0, 0%)\">") ~= nil then
in_exclude = true
else
if string.find(line, "Sun") ~= nil then
in_week = true
elseif string.find(line, "Sat") ~= nil then
line = ""
in_week = false
end
if in_week then
line = ""
end
-- Date matches today
if string.find(line, today_date) ~= nil then
line = string.gsub(line, "#ebedf0", alert_color)
end
-- Generate new translate
if string.find(line, "<g transform=\"translate%(%d+, 0%)\">") ~= nil then
line = " <g transform=\"translate(" .. tostring(horizon_pos) .. ", 0)\">"
horizon_pos_tmp = horizon_pos + 13
horizon_pos = horizon_pos_tmp
end
if line:find("<text .*") ~= nil then
line = ""
end
svgfile:write(line .. "\n")
end
else
if string.find(line, after_date) ~= nil then
svgfile:write(" <g transform=\"translate(0, 0)\">" .. "\n")
svgfile:write(line .. "\n")
in_exclude = false
end
end
if in_svg and line == end_match then
break
end
end
end
tmpfile:close()
svgfile:close()
end
function conky_draw_github_grass_pre()
if conky_window == nil then
return
end
cairo_surface = cairo_xlib_surface_create(conky_window.display,
conky_window.drawable,
conky_window.visual,
conky_window.width,
conky_window.height)
local cairo = cairo_create(cairo_surface)
cairo_translate(cairo, 0, 640)
cairo_scale(cairo, 1.6, 1.6)
rsvg_handle_render_cairo(rsvg_handle, cairo)
cairo_destroy(cairo)
end
function conky_draw_github_grass_post()
cairo_surface_destroy(cairo_surface)
end
conky_get_github_grass()
rsvg_handle = rsvg_create_handle_from_file("/dev/shm/grass.svg")
cairo_surface = nil
cairo = nil
|
Fix rsvg create handle position
|
Fix rsvg create handle position
|
Lua
|
bsd-3-clause
|
kinoo/dotfiles,kinoo/dotfiles,kizkoh/dotfiles,kizkoh/dotfiles,kinoo/dotfiles
|
4da322ad2696a9cf2b87eeb8365ae696016a9a09
|
applications/luci-statistics/src/model/cbi/admin_statistics/iptables.lua
|
applications/luci-statistics/src/model/cbi/admin_statistics/iptables.lua
|
--[[
Luci configuration model for statistics - collectd iptables plugin configuration
(c) 2008 Freifunk Leipzig / 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("ffluci.sys.iptparser")
ip = ffluci.sys.iptparser.IptParser()
chains = { }
targets = { }
for i, rule in ipairs( ip:find() ) do
chains[rule.chain] = true
targets[rule.target] = true
end
m = Map("luci_statistics", "Iptables Plugin",
[[Das Iptables-Plugin ermöglicht die Überwachung bestimmter Firewallregeln um
Werte wie die Anzahl der verarbeiteten Pakete oder die insgesamt erfasste Datenmenge
zu speichern.]])
-- collectd_iptables config section
s = m:section( NamedSection, "collectd_iptables", "luci_statistics", "Pluginkonfiguration" )
-- collectd_iptables.enable
enable = s:option( Flag, "enable", "Plugin aktivieren" )
enable.default = 0
-- collectd_iptables_match config section (Chain directives)
rule = m:section( TypedSection, "collectd_iptables_match", "Regel hinzufügen",
[[Hier werden die Kriterien festgelegt, nach welchen die Firewall-Regeln zur Überwachung
ausgewählt werden.]])
rule.addremove = true
rule.anonymous = true
-- collectd_iptables_match.name
rule_table = rule:option( Value, "name", "Name der Regel", "wird im Diagram verwendet" )
-- collectd_iptables_match.table
rule_table = rule:option( ListValue, "table", "Firewall-Tabelle" )
rule_table.default = "filter"
rule_table.rmempty = true
rule_table.optional = true
rule_table:value("")
rule_table:value("filter")
rule_table:value("nat")
rule_table:value("mangle")
-- collectd_iptables_match.chain
rule_chain = rule:option( ListValue, "chain", "Firewall-Kette (Chain)" )
rule_chain.rmempty = true
rule_chain.optional = true
rule_chain:value("")
for chain, void in pairs( chains ) do
rule_chain:value( chain )
end
-- collectd_iptables_match.target
rule_target = rule:option( ListValue, "target", "Firewall-Aktion (Target)" )
rule_target.rmempty = true
rule_target.optional = true
rule_target:value("")
for target, void in pairs( targets ) do
rule_target:value( target )
end
-- collectd_iptables_match.protocol
rule_protocol = rule:option( ListValue, "protocol", "Netzwerkprotokoll" )
rule_protocol.rmempty = true
rule_protocol.optional = true
rule_protocol:value("")
rule_protocol:value("tcp")
rule_protocol:value("udp")
rule_protocol:value("icmp")
-- collectd_iptables_match.source
rule_source = rule:option( Value, "source", "Quell-IP-Bereich", "Bereich in CIDR Notation" )
rule_source.default = "0.0.0.0/0"
rule_source.rmempty = true
rule_source.optional = true
-- collectd_iptables_match.destination
rule_destination = rule:option( Value, "destination", "Ziel-IP-Bereich", "Bereich in CIDR Notation" )
rule_destination.default = "0.0.0.0/0"
rule_destination.rmempty = true
rule_destination.optional = true
-- collectd_iptables_match.inputif
rule_inputif = rule:option( Value, "inputif", "eingehende Schnittstelle", "z.B. eth0.0" )
rule_inputif.default = "0.0.0.0/0"
rule_inputif.rmempty = true
rule_inputif.optional = true
-- collectd_iptables_match.outputif
rule_outputif = rule:option( Value, "outputif", "ausgehende Schnittstelle", "z.B. eth0.1" )
rule_outputif.default = "0.0.0.0/0"
rule_outputif.rmempty = true
rule_outputif.optional = true
-- collectd_iptables_match.options
rule_options = rule:option( Value, "options", "Optionen", "z.B. reject-with tcp-reset" )
rule_options.default = "0.0.0.0/0"
rule_options.rmempty = true
rule_options.optional = true
return m
|
--[[
Luci configuration model for statistics - collectd iptables plugin configuration
(c) 2008 Freifunk Leipzig / 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("ffluci.sys.iptparser")
ip = ffluci.sys.iptparser.IptParser()
chains = { }
targets = { }
for i, rule in ipairs( ip:find() ) do
chains[rule.chain] = true
targets[rule.target] = true
end
m = Map("luci_statistics", "Iptables Plugin",
[[Das Iptables-Plugin ermöglicht die Überwachung bestimmter Firewallregeln um
Werte wie die Anzahl der verarbeiteten Pakete oder die insgesamt erfasste Datenmenge
zu speichern.]])
-- collectd_iptables config section
s = m:section( NamedSection, "collectd_iptables", "luci_statistics", "Pluginkonfiguration" )
-- collectd_iptables.enable
enable = s:option( Flag, "enable", "Plugin aktivieren" )
enable.default = 0
-- collectd_iptables_match config section (Chain directives)
rule = m:section( TypedSection, "collectd_iptables_match", "Regel hinzufügen",
[[Hier werden die Kriterien festgelegt, nach welchen die Firewall-Regeln zur Überwachung
ausgewählt werden.]])
rule.addremove = true
rule.anonymous = true
-- collectd_iptables_match.name
rule_table = rule:option( Value, "name", "Name der Regel", "wird im Diagram verwendet" )
-- collectd_iptables_match.table
rule_table = rule:option( ListValue, "table", "Firewall-Tabelle" )
rule_table.default = "filter"
rule_table.rmempty = true
rule_table.optional = true
rule_table:value("")
rule_table:value("filter")
rule_table:value("nat")
rule_table:value("mangle")
-- collectd_iptables_match.chain
rule_chain = rule:option( ListValue, "chain", "Firewall-Kette (Chain)" )
rule_chain.rmempty = true
rule_chain.optional = true
rule_chain:value("")
for chain, void in pairs( chains ) do
rule_chain:value( chain )
end
-- collectd_iptables_match.target
rule_target = rule:option( ListValue, "target", "Firewall-Aktion (Target)" )
rule_target.rmempty = true
rule_target.optional = true
rule_target:value("")
for target, void in pairs( targets ) do
rule_target:value( target )
end
-- collectd_iptables_match.protocol
rule_protocol = rule:option( ListValue, "protocol", "Netzwerkprotokoll" )
rule_protocol.rmempty = true
rule_protocol.optional = true
rule_protocol:value("")
rule_protocol:value("tcp")
rule_protocol:value("udp")
rule_protocol:value("icmp")
-- collectd_iptables_match.source
rule_source = rule:option( Value, "source", "Quell-IP-Bereich", "Bereich in CIDR Notation" )
rule_source.default = "0.0.0.0/0"
rule_source.rmempty = true
rule_source.optional = true
-- collectd_iptables_match.destination
rule_destination = rule:option( Value, "destination", "Ziel-IP-Bereich", "Bereich in CIDR Notation" )
rule_destination.default = "0.0.0.0/0"
rule_destination.rmempty = true
rule_destination.optional = true
-- collectd_iptables_match.inputif
rule_inputif = rule:option( Value, "inputif", "eingehende Schnittstelle", "z.B. eth0.0" )
rule_inputif.rmempty = true
rule_inputif.optional = true
-- collectd_iptables_match.outputif
rule_outputif = rule:option( Value, "outputif", "ausgehende Schnittstelle", "z.B. eth0.1" )
rule_outputif.rmempty = true
rule_outputif.optional = true
-- collectd_iptables_match.options
rule_options = rule:option( Value, "options", "Optionen", "z.B. reject-with tcp-reset" )
rule_options.rmempty = true
rule_options.optional = true
return m
|
* ffluci/statistics: fix c'n'p errors in iptables cbi model
|
* ffluci/statistics: fix c'n'p errors in iptables cbi model
git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@2092 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,saraedum/luci-packages-old,Flexibity/luci,Canaan-Creative/luci,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,jschmidlapp/luci,8devices/carambola2-luci,Flexibity/luci,stephank/luci,8devices/carambola2-luci,Canaan-Creative/luci,jschmidlapp/luci,freifunk-gluon/luci,yeewang/openwrt-luci,vhpham80/luci,alxhh/piratenluci,8devices/carambola2-luci,projectbismark/luci-bismark,alxhh/piratenluci,alxhh/piratenluci,gwlim/luci,eugenesan/openwrt-luci,8devices/carambola2-luci,eugenesan/openwrt-luci,ThingMesh/openwrt-luci,Canaan-Creative/luci,freifunk-gluon/luci,vhpham80/luci,alxhh/piratenluci,phi-psi/luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,Canaan-Creative/luci,stephank/luci,eugenesan/openwrt-luci,ch3n2k/luci,alxhh/piratenluci,gwlim/luci,yeewang/openwrt-luci,stephank/luci,gwlim/luci,ThingMesh/openwrt-luci,yeewang/openwrt-luci,Flexibity/luci,8devices/carambola2-luci,dtaht/cerowrt-luci-3.3,jschmidlapp/luci,jschmidlapp/luci,projectbismark/luci-bismark,zwhfly/openwrt-luci,freifunk-gluon/luci,saraedum/luci-packages-old,zwhfly/openwrt-luci,gwlim/luci,dtaht/cerowrt-luci-3.3,saraedum/luci-packages-old,alxhh/piratenluci,dtaht/cerowrt-luci-3.3,ThingMesh/openwrt-luci,phi-psi/luci,Flexibity/luci,projectbismark/luci-bismark,ThingMesh/openwrt-luci,8devices/carambola2-luci,saraedum/luci-packages-old,freifunk-gluon/luci,freifunk-gluon/luci,jschmidlapp/luci,ThingMesh/openwrt-luci,ch3n2k/luci,jschmidlapp/luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,alxhh/piratenluci,saraedum/luci-packages-old,Canaan-Creative/luci,phi-psi/luci,vhpham80/luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,Flexibity/luci,Canaan-Creative/luci,yeewang/openwrt-luci,stephank/luci,projectbismark/luci-bismark,eugenesan/openwrt-luci,Flexibity/luci,dtaht/cerowrt-luci-3.3,freifunk-gluon/luci,Flexibity/luci,saraedum/luci-packages-old,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,vhpham80/luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,yeewang/openwrt-luci,projectbismark/luci-bismark,jschmidlapp/luci,stephank/luci,freifunk-gluon/luci,phi-psi/luci,dtaht/cerowrt-luci-3.3,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,gwlim/luci,ch3n2k/luci,jschmidlapp/luci,ch3n2k/luci,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,Flexibity/luci,phi-psi/luci,Canaan-Creative/luci,projectbismark/luci-bismark,projectbismark/luci-bismark,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,dtaht/cerowrt-luci-3.3,projectbismark/luci-bismark,eugenesan/openwrt-luci,gwlim/luci,stephank/luci,ch3n2k/luci,gwlim/luci,ch3n2k/luci
|
efb939c3fbea7727908ef9dbc07c89a9bbb51052
|
cherry/screens/leaderboard.lua
|
cherry/screens/leaderboard.lua
|
--------------------------------------------------------------------------------
local _ = require 'cherry.libs.underscore'
local gesture = require 'cherry.libs.gesture'
local group = require 'cherry.libs.group'
local http = require 'cherry.libs.http'
local Background = require 'cherry.components.background'
local Button = require 'cherry.components.button'
local Text = require 'cherry.components.text'
local json = require 'dkjson'
--------------------------------------------------------------------------------
local scene = _G.composer.newScene()
local selectedButton = nil
local board = nil
local boardData = {}
local CLOSED_Y = 35
local OPEN_Y = 70
local BOARD_CENTER_X = display.contentWidth * 0.5
local BOARD_CENTER_Y = display.contentHeight * 0.5 + 100
local BOARD_WIDTH = display.contentWidth * 0.9
local BOARD_HEIGHT = display.contentHeight * 0.85
--------------------------------------------------------------------------------
local function fetchData(field, next)
_G.log('Fetching data')
local url = App.API_GATEWAY_URL .. '/leaderboard/' .. App.name .. '/' .. field.name
http.get(url, function(event)
local data = json.decode(event.response)
local lines = {}
for position,entry in pairs(data.Items) do
local num = #lines + 1
local value = entry[field.name].N
if(num > 1 and lines[num - 1][field.name] == value) then
position = lines[num - 1].position
end
lines[num] = {
playerName = entry.playerName.S,
playerId = entry.playerId.S,
position = position
}
lines[num][field.name] = value
end
boardData[field.name] = lines
next(field)
end)
end
--------------------------------------------------------------------------------
local function displayData(field)
local lines = boardData[field.name]
for i, line in pairs(lines) do
local color = '#ffffff'
if(line.playerId == App.user:id()) then
color = '#32cd32'
end
timer.performWithDelay(math.random(100, 700), function()
if(board.field ~= field) then return end
Text:create({
parent = board,
value = line.position,
x = BOARD_CENTER_X - BOARD_WIDTH * 0.5 + 30,
y = BOARD_CENTER_Y - BOARD_HEIGHT * 0.5 + 50 + (i - 1) * 50,
color = color,
font = _G.FONT,
fontSize = 45,
anchorX = 0,
grow = true
})
end)
timer.performWithDelay(math.random(100, 700), function()
if(board.field ~= field) then return end
Text:create({
parent = board,
value = line.playerName,
x = BOARD_CENTER_X - BOARD_WIDTH * 0.5 + 80,
y = BOARD_CENTER_Y - BOARD_HEIGHT * 0.5 + 50 + (i - 1) * 50,
color = color,
font = _G.FONT,
fontSize = 45,
anchorX = 0,
grow = true
})
end)
timer.performWithDelay(math.random(100, 700), function()
if(board.field ~= field) then return end
Text:create({
parent = board,
value = line[field.name],
x = BOARD_CENTER_X + BOARD_WIDTH * 0.5 - 100,
y = BOARD_CENTER_Y - BOARD_HEIGHT * 0.5 + 50 + (i - 1) * 50,
color = color,
font = _G.FONT,
fontSize = 45,
anchorX = 0,
grow = true
})
end)
end
end
--------------------------------------------------------------------------------
local function refreshBoard(field)
if(board) then
group.destroy(board)
end
board = display.newGroup()
board.field = field
App.hud:insert(board)
local bg = display.newRect(
board,
BOARD_CENTER_X,
BOARD_CENTER_Y,
BOARD_WIDTH,
BOARD_HEIGHT
)
bg:setFillColor(0, 0, 0, 0.7)
if(not boardData[field.name]) then
local message = Text:create({
parent = board,
value = 'Connecting...',
font = _G.FONT,
fontSize = 40,
x = BOARD_CENTER_X,
y = BOARD_CENTER_Y
})
timer.performWithDelay(1000, function()
if(not http.networkConnection()) then
if(message) then
message:setValue('No connection')
end
return
end
fetchData(field, refreshBoard)
end)
else
displayData(field)
end
end
--------------------------------------------------------------------------------
local function select(button)
if(selectedButton) then
if(button == selectedButton) then return end
transition.to(selectedButton, {
y = CLOSED_Y,
time = 250,
transition = easing.outBack
})
end
selectedButton = button
transition.to(button, {
y = OPEN_Y,
time = 250,
transition = easing.outBack
})
refreshBoard(button.field)
end
--------------------------------------------------------------------------------
local function drawBackArrow()
Button:icon({
parent = App.hud,
type = 'back',
x = 50,
y = 50,
scale = 0.7,
action = function()
Router:open(Router.HOME)
end
})
end
--------------------------------------------------------------------------------
local function drawButton(num)
local field = _.defaults(App.scoreFields[num], {
scale = 1
})
----------------------
local button = display.newGroup()
App.hud:insert(button)
button.field = field
button.x = 250 + (num - 1) * 150
button.y = CLOSED_Y
----------------------
display.newImage(
button,
'cherry/assets/images/gui/buttons/tab-vertical.png'
)
----------------------
local icon = display.newImage(
button,
field.image,
0, 10
)
icon:scale(field.scale, field.scale)
----------------------
display.newText({
parent = button,
y = -50,
text = field.label,
font = _G.FONT,
fontSize = 40
})
----------------------
gesture.onTap(button, function()
select(button)
end)
return button
end
--------------------------------------------------------------------------------
function scene:create( event )
end
function scene:show( event )
if ( event.phase == 'did' ) then
boardData = {}
Background:darken()
drawBackArrow()
local buttons = {}
for i = 1, #App.scoreFields do
buttons[i] = drawButton(i)
end
select(buttons[1])
end
end
function scene:hide( event )
board.field = nil
end
function scene:destroy( event )
end
--------------------------------------------------------------------------------
scene:addEventListener( 'create', scene )
scene:addEventListener( 'show', scene )
scene:addEventListener( 'hide', scene )
scene:addEventListener( 'destroy', scene )
--------------------------------------------------------------------------------
return scene
|
--------------------------------------------------------------------------------
local _ = require 'cherry.libs.underscore'
local gesture = require 'cherry.libs.gesture'
local group = require 'cherry.libs.group'
local http = require 'cherry.libs.http'
local Background = require 'cherry.components.background'
local Button = require 'cherry.components.button'
local Text = require 'cherry.components.text'
local json = require 'dkjson'
--------------------------------------------------------------------------------
local scene = _G.composer.newScene()
local selectedButton = nil
local board = nil
local boardData = {}
local CLOSED_Y = 35
local OPEN_Y = 70
local BOARD_CENTER_X = display.contentWidth * 0.5
local BOARD_CENTER_Y = display.contentHeight * 0.5 + 100
local BOARD_WIDTH = display.contentWidth * 0.9
local BOARD_HEIGHT = display.contentHeight * 0.85
--------------------------------------------------------------------------------
local function fetchData(field, next)
local url = App.API_GATEWAY_URL .. '/leaderboard/' .. App.name .. '/' .. field.name
http.get(url, function(event)
if(Router.view ~= Router.LEADERBOARD) then
_G.log({v= Router.view})
return
end
local data = json.decode(event.response)
local lines = {}
for position,entry in pairs(data.Items) do
local num = #lines + 1
local value = entry[field.name].N
if(num > 1 and lines[num - 1][field.name] == value) then
position = lines[num - 1].position
end
lines[num] = {
playerName = entry.playerName.S,
playerId = entry.playerId.S,
position = position
}
lines[num][field.name] = value
end
boardData[field.name] = lines
next(field)
end)
end
--------------------------------------------------------------------------------
local function displayData(field)
local lines = boardData[field.name]
for i, line in pairs(lines) do
local color = '#ffffff'
if(line.playerId == App.user:id()) then
color = '#32cd32'
end
timer.performWithDelay(math.random(100, 700), function()
if(board.field ~= field) then return end
Text:create({
parent = board,
value = line.position,
x = BOARD_CENTER_X - BOARD_WIDTH * 0.5 + 30,
y = BOARD_CENTER_Y - BOARD_HEIGHT * 0.5 + 50 + (i - 1) * 50,
color = color,
font = _G.FONT,
fontSize = 45,
anchorX = 0,
grow = true
})
end)
timer.performWithDelay(math.random(100, 700), function()
if(board.field ~= field) then return end
Text:create({
parent = board,
value = line.playerName,
x = BOARD_CENTER_X - BOARD_WIDTH * 0.5 + 80,
y = BOARD_CENTER_Y - BOARD_HEIGHT * 0.5 + 50 + (i - 1) * 50,
color = color,
font = _G.FONT,
fontSize = 45,
anchorX = 0,
grow = true
})
end)
timer.performWithDelay(math.random(100, 700), function()
if(board.field ~= field) then return end
Text:create({
parent = board,
value = line[field.name],
x = BOARD_CENTER_X + BOARD_WIDTH * 0.5 - 100,
y = BOARD_CENTER_Y - BOARD_HEIGHT * 0.5 + 50 + (i - 1) * 50,
color = color,
font = _G.FONT,
fontSize = 45,
anchorX = 0,
grow = true
})
end)
end
end
--------------------------------------------------------------------------------
local function refreshBoard(field)
if(board) then
group.destroy(board)
end
board = display.newGroup()
board.field = field
App.hud:insert(board)
local bg = display.newRect(
board,
BOARD_CENTER_X,
BOARD_CENTER_Y,
BOARD_WIDTH,
BOARD_HEIGHT
)
bg:setFillColor(0, 0, 0, 0.7)
if(not boardData[field.name]) then
local message = Text:create({
parent = board,
value = 'Connecting...',
font = _G.FONT,
fontSize = 40,
x = BOARD_CENTER_X,
y = BOARD_CENTER_Y
})
if(not http.networkConnection()) then
if(message) then
message:setValue('No connection')
end
return
end
fetchData(field, refreshBoard)
else
displayData(field)
end
end
--------------------------------------------------------------------------------
local function select(button)
if(selectedButton) then
if(button == selectedButton) then return end
transition.to(selectedButton, {
y = CLOSED_Y,
time = 250,
transition = easing.outBack
})
end
selectedButton = button
transition.to(button, {
y = OPEN_Y,
time = 250,
transition = easing.outBack
})
refreshBoard(button.field)
end
--------------------------------------------------------------------------------
local function drawBackArrow()
Button:icon({
parent = App.hud,
type = 'back',
x = 50,
y = 50,
scale = 0.7,
action = function()
Router:open(Router.HOME)
end
})
end
--------------------------------------------------------------------------------
local function drawButton(num)
local field = _.defaults(App.scoreFields[num], {
scale = 1
})
----------------------
local button = display.newGroup()
App.hud:insert(button)
button.field = field
button.x = 250 + (num - 1) * 150
button.y = CLOSED_Y
----------------------
display.newImage(
button,
'cherry/assets/images/gui/buttons/tab-vertical.png'
)
----------------------
local icon = display.newImage(
button,
field.image,
0, 10
)
icon:scale(field.scale, field.scale)
----------------------
display.newText({
parent = button,
y = -50,
text = field.label,
font = _G.FONT,
fontSize = 40
})
----------------------
gesture.onTap(button, function()
select(button)
end)
return button
end
--------------------------------------------------------------------------------
function scene:create( event )
end
function scene:show( event )
if ( event.phase == 'did' ) then
boardData = {}
Background:darken()
drawBackArrow()
local buttons = {}
for i = 1, #App.scoreFields do
buttons[i] = drawButton(i)
end
select(buttons[1])
end
end
function scene:hide( event )
board.field = nil
end
function scene:destroy( event )
end
--------------------------------------------------------------------------------
scene:addEventListener( 'create', scene )
scene:addEventListener( 'show', scene )
scene:addEventListener( 'hide', scene )
scene:addEventListener( 'destroy', scene )
--------------------------------------------------------------------------------
return scene
|
fixed leaderboard loading https://github.com/chrisdugne/kodo/issues/39
|
fixed leaderboard loading https://github.com/chrisdugne/kodo/issues/39
|
Lua
|
bsd-3-clause
|
chrisdugne/cherry
|
46c68d1775da24c0749465736f46ded3bb6a7060
|
vrp/client/veh_blacklist.lua
|
vrp/client/veh_blacklist.lua
|
if not vRP.modules.veh_blacklist then return end
local VehBlacklist = class("VehBlacklist", vRP.Extension)
-- METHODS
function VehBlacklist:__construct()
vRP.Extension.__construct(self)
self.veh_models = {} -- map of model hash
self.interval = 10000
-- task: remove vehicles
Citizen.CreateThread(function()
while true do
Citizen.Wait(self.interval)
local vehicles = {}
local it, veh = FindFirstVehicle()
if veh then table.insert(vehicles, veh) end
while true do
local ok, veh = FindNextVehicle(it)
if ok and veh then
table.insert(vehicles, veh)
else
EndFindVehicle(it)
break
end
end
for _, veh in ipairs(vehicles) do
if self.veh_models[GetEntityModel(veh)] then
SetEntityAsMissionEntity(veh, true, true)
local vehPlate = GetVehicleNumberPlateText(veh)
local vehPlateInit = string.sub(vehPlate, 1,1)
if vehPlateInit ~= "P" then
DeleteVehicle(veh)
end
end
end
end
end)
end
-- TUNNEL
VehBlacklist.tunnel = {}
function VehBlacklist.tunnel:setConfig(cfg)
for _, model in pairs(cfg.veh_models) do
local hash
if type(model) == "string" then
hash = GetHashKey(model)
else
hash = model
end
self.veh_models[hash] = true
end
self.interval = cfg.remove_interval
end
vRP:registerExtension(VehBlacklist)
|
if not vRP.modules.veh_blacklist then return end
local VehBlacklist = class("VehBlacklist", vRP.Extension)
-- METHODS
function VehBlacklist:__construct()
vRP.Extension.__construct(self)
self.veh_models = {} -- map of model hash
self.interval = 10000
-- task: remove vehicles
Citizen.CreateThread(function()
while true do
Citizen.Wait(self.interval)
local vehicles = {}
local it, veh = FindFirstVehicle()
if veh then table.insert(vehicles, veh) end
while true do
local ok, veh = FindNextVehicle(it)
if ok and veh then
table.insert(vehicles, veh)
else
EndFindVehicle(it)
break
end
end
for _, veh in ipairs(vehicles) do
if self.veh_models[GetEntityModel(veh)] then
local cid, model = vRP.EXT.Garage:getVehicleInfo(veh)
if not cid and vRP.EXT.Base.cid ~= cid then
SetEntityAsMissionEntity(veh, true, true)
DeleteVehicle(veh)
end
end
end
end
end)
end
-- TUNNEL
VehBlacklist.tunnel = {}
function VehBlacklist.tunnel:setConfig(cfg)
for _, model in pairs(cfg.veh_models) do
local hash
if type(model) == "string" then
hash = GetHashKey(model)
else
hash = model
end
self.veh_models[hash] = true
end
self.interval = cfg.remove_interval
end
vRP:registerExtension(VehBlacklist)
|
Fix - Using Garage module vRP
|
Fix - Using Garage module vRP
|
Lua
|
mit
|
ImagicTheCat/vRP,ImagicTheCat/vRP
|
699343a325878122e03051cdd180a6e85296c436
|
hostinfo/lsyncd.lua
|
hostinfo/lsyncd.lua
|
--[[
Copyright 2015 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local HostInfo = require('./base').HostInfo
local Transform = require('stream').Transform
local misc = require('./misc')
local async = require('async')
--------------------------------------------------------------------------------------------------------------------
local Reader = Transform:extend()
function Reader:initialize()
Transform.initialize(self, {objectMode = true})
end
function Reader:_transform(line, cb)
-- 'root root root root 1 lsyncd /etc/lsyncd/lsyncd.conf.lua' -> '/etc/lsyncd/lsyncd.conf.lua'
local config = line:match('%slsyncd%s*(%S+)')
if config then self:push(config) end
cb()
end
--------------------------------------------------------------------------------------------------------------------
--[[ Checks lsyncd ]]--
local Info = HostInfo:extend()
function Info:initialize()
HostInfo.initialize(self)
end
function Info:_run(callback)
local errTable, outTable, callbacked = {}, {}, false
local function finalCb()
if not callbacked then
callbacked = true
self:_pushParams(errTable, outTable)
callback()
end
end
local function getLsyncdBin(cb)
local options = {
ubuntu = '/usr/local/bin/lsyncd',
default = '/usr/bin/lsyncd'
}
local lsyncPath = misc.getInfoByVendor(options)
if lsyncPath then
cb({bin = lsyncPath})
else
-- Callback out of this hostinfo early
table.insert(errTable, 'Couldnt determine OS for lsyncd')
finalCb()
end
end
local function getLsyncProc(cb)
local configs, err = {}, {}
local lsyncd_status_ok
local counter = 2
local function finish()
counter = counter - 1
if counter == 0 then cb({
staus = lsyncd_status_ok,
config_file = configs
})
end
end
local child = misc.run('sh', {'-c', 'ps -eo euser,ruser,suser,fuser,f,cmd|grep lsync | grep -v grep'})
local reader = Reader:new()
child:pipe(reader)
-- There's a good chance the user just doesnt have lsyncd, error out quickly in that case
child:on('error', function(error)
table.insert(errTable, 'Lsyncd not found: ' .. error)
finalCb()
child:emit('end')
end)
reader:on('data', function(data)
configs[data] = 1 -- get unique config files only
end)
reader:on('error', function(error)
table.insert(err, error)
end)
reader:once('end', function()
-- flatten configs, theres usually only 1, and reorg to have uniques only and get rid of the values of 1
if #configs == 1 then configs = configs[1] end
local temp = {}
table.foreach(configs, function(k)
table.insert(temp, k)
end)
configs = temp
return finish()
end)
child:once('end', function()
if configs and not err then lsyncd_status_ok = true else lsyncd_status_ok = false end
return finish()
end)
end
async.parallel({
function(cb)
getLsyncdBin(function(out)
misc.safeMerge(outTable, out)
cb()
end)
end,
function(cb)
getLsyncProc(function(out)
misc.safeMerge(outTable, out)
cb()
end)
end
}, finalCb)
end
function Info:getPlatforms()
return {'linux'}
end
function Info:getType()
return 'LSYNCD'
end
exports.Info = Info
exports.Reader = Reader
|
--[[
Copyright 2015 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local HostInfo = require('./base').HostInfo
local Transform = require('stream').Transform
local misc = require('./misc')
local async = require('async')
--------------------------------------------------------------------------------------------------------------------
local Reader = Transform:extend()
function Reader:initialize()
Transform.initialize(self, {objectMode = true})
end
function Reader:_transform(line, cb)
-- 'root root root root 1 lsyncd /etc/lsyncd/lsyncd.conf.lua' -> '/etc/lsyncd/lsyncd.conf.lua'
local config = line:match('%slsyncd%s*(%S+)')
if config then self:push(config) end
cb()
end
--------------------------------------------------------------------------------------------------------------------
--[[ Checks lsyncd ]]--
local Info = HostInfo:extend()
function Info:initialize()
HostInfo.initialize(self)
end
function Info:_run(callback)
local errTable, outTable, callbacked = {}, {}, false
local function finalCb()
if not callbacked then
callbacked = true
self:_pushParams(errTable, outTable)
callback()
end
end
local function getLsyncdBin(cb)
local options = {
default = '/usr/bin/lsyncd'
}
local lsyncPath = misc.getInfoByVendor(options)
if lsyncPath then
cb({bin = lsyncPath})
else
-- Callback out of this hostinfo early
table.insert(errTable, 'Couldnt determine OS for lsyncd')
finalCb()
end
end
local function checkLsyncIsInstalled(cb)
local isInstalled = false
local lsyncCmd = outTable.bin
local child = misc.run(lsyncCmd, {'-version'})
-- If we can get data from running the lsync cmd its installed else not
child:on('data', function(data)
isInstalled = true
end)
child:once('end', function()
cb({installed = isInstalled})
end)
end
local function getLsyncProc(cb)
local configs, err = {}, {}
local lsyncd_status_ok
local counter = 2
local function finish()
counter = counter - 1
if counter == 0 then cb({
status = lsyncd_status_ok,
config_file = configs
})
end
end
local child = misc.run('sh', {'-c', 'ps -eo euser,ruser,suser,fuser,f,cmd|grep lsync | grep -v grep'})
local reader = Reader:new()
child:pipe(reader)
-- There's a good chance the user just doesnt have lsyncd, error out quickly in that case
child:on('error', function(error)
table.insert(errTable, 'Lsyncd not found: ' .. error)
finalCb()
child:emit('end')
end)
reader:on('data', function(data)
configs[data] = 1 -- get unique config files only
end)
reader:on('error', function(error)
table.insert(err, error)
end)
reader:once('end', function()
-- flatten configs, theres usually only 1, and reorg to have uniques only and get rid of the values of 1
if #configs == 1 then configs = configs[1] end
local temp = {}
table.foreach(configs, function(k)
table.insert(temp, k)
end)
configs = temp
return finish()
end)
child:once('end', function()
if configs and not err then lsyncd_status_ok = true else lsyncd_status_ok = false end
return finish()
end)
end
async.parallel({
function(cb)
getLsyncdBin(function(out)
misc.safeMerge(outTable, out)
cb()
end)
end,
function(cb)
getLsyncProc(function(out)
misc.safeMerge(outTable, out)
cb()
end)
end
}, function()
checkLsyncIsInstalled(function(out)
misc.safeMerge(outTable, out)
finalCb()
end)
end)
end
function Info:getPlatforms()
return {'linux'}
end
function Info:getType()
return 'LSYNCD'
end
exports.Info = Info
exports.Reader = Reader
|
fix(lsyncd): Typo fix and add functionality to check if lsyncd is installed and fix on ubuntu
|
fix(lsyncd): Typo fix and add functionality to check if lsyncd is installed and fix on ubuntu
|
Lua
|
apache-2.0
|
virgo-agent-toolkit/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent
|
1dce464c98387b6a3b9ef0f39fe748b6cefce1f8
|
config/nvim/lua/file-icons.lua
|
config/nvim/lua/file-icons.lua
|
local colors = require("tokyonight.colors").setup()
require "nvim-web-devicons".setup {
override = {
html = {
icon = "",
color = colors.baby_pink,
name = "html"
},
css = {
icon = "",
color = colors.blue,
name = "css"
},
js = {
icon = "",
color = colors.sun,
name = "js"
},
ts = {
icon = "ﯤ",
color = colors.teal,
name = "ts"
},
kt = {
icon = "",
color = colors.orange,
name = "kt"
},
png = {
icon = "",
color = colors.dark_purple,
name = "png"
},
jpg = {
icon = "",
color = colors.dark_purple,
name = "jpg"
},
jpeg = {
icon = "",
color = "colors.dark_purple",
name = "jpeg"
},
mp3 = {
icon = "",
color = colors.white,
name = "mp3"
},
mp4 = {
icon = "",
color = colors.white,
name = "mp4"
},
out = {
icon = "",
color = colors.white,
name = "out"
},
Dockerfile = {
icon = "",
color = colors.cyan,
name = "Dockerfile"
},
rb = {
icon = "",
color = colors.pink,
name = "rb"
},
vue = {
icon = "﵂",
color = colors.vibrant_green,
name = "vue"
},
py = {
icon = "",
color = colors.cyan,
name = "py"
},
toml = {
icon = "",
color = colors.blue,
name = "toml"
},
lock = {
icon = "",
color = colors.red,
name = "lock"
},
zip = {
icon = "",
color = colors.sun,
name = "zip"
},
xz = {
icon = "",
color = colors.sun,
name = "xz"
},
deb = {
icon = "",
color = colors.cyan,
name = "deb"
},
rpm = {
icon = "",
color = colors.orange,
name = "rpm"
}
}
}
|
local colors = require("nightfox.colors").init()
require "nvim-web-devicons".setup {
override = {
html = {
icon = "",
color = colors.pink_br,
name = "html"
},
css = {
icon = "",
color = colors.blue,
name = "css"
},
js = {
icon = "",
color = colors.yellow_dm,
name = "js"
},
ts = {
icon = "ﯤ",
color = colors.blue_br,
name = "ts"
},
kt = {
icon = "",
color = colors.orange,
name = "kt"
},
png = {
icon = "",
color = colors.dark_purple,
name = "png"
},
jpg = {
icon = "",
color = colors.dark_purple,
name = "jpg"
},
jpeg = {
icon = "",
color = "colors.dark_purple",
name = "jpeg"
},
mp3 = {
icon = "",
color = colors.white,
name = "mp3"
},
mp4 = {
icon = "",
color = colors.white,
name = "mp4"
},
out = {
icon = "",
color = colors.white,
name = "out"
},
Dockerfile = {
icon = "",
color = colors.cyan,
name = "Dockerfile"
},
rb = {
icon = "",
color = colors.red_dm,
name = "rb"
},
vue = {
icon = "﵂",
color = colors.green_br,
name = "vue"
},
py = {
icon = "",
color = colors.cyan,
name = "py"
},
toml = {
icon = "",
color = colors.blue,
name = "toml"
},
lock = {
icon = "",
color = colors.red,
name = "lock"
},
zip = {
icon = "",
color = colors.sun,
name = "zip"
},
xz = {
icon = "",
color = colors.sun,
name = "xz"
},
deb = {
icon = "",
color = colors.cyan,
name = "deb"
},
rpm = {
icon = "",
color = colors.orange,
name = "rpm"
}
}
}
|
Fix colors
|
Fix colors
|
Lua
|
mit
|
lisinge/dotfiles,lisinge/dotfiles
|
f6e1fef4211423e89a7d00bea4cccbc46719a97a
|
kong/plugins/aws-lambda/aws-serializer.lua
|
kong/plugins/aws-lambda/aws-serializer.lua
|
-- serializer to wrap the current request into the Amazon API gateway
-- format as described here:
-- https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format
local request_util = require "kong.plugins.aws-lambda.request-util"
local EMPTY = {}
local ngx_req_get_headers = ngx.req.get_headers
local ngx_req_get_uri_args = ngx.req.get_uri_args
local ngx_encode_base64 = ngx.encode_base64
return function(ctx, config)
ctx = ctx or ngx.ctx
local var = ngx.var
-- prepare headers
local headers = ngx_req_get_headers()
local multiValueHeaders = {}
for hname, hvalue in pairs(headers) do
if type(hvalue) == "table" then
-- multi value
multiValueHeaders[hname] = hvalue
headers[hname] = hvalue[1]
else
-- single value
multiValueHeaders[hname] = { hvalue }
end
end
-- prepare url-captures/path-parameters
local pathParameters = {}
for name, value in pairs(ctx.router_matches.uri_captures or EMPTY) do
if type(name) == "string" then -- skip numerical indices, only named
pathParameters[name] = value
end
end
-- query parameters
local queryStringParameters = ngx_req_get_uri_args()
local multiValueQueryStringParameters = {}
for qname, qvalue in pairs(queryStringParameters) do
if type(qvalue) == "table" then
-- multi value
multiValueQueryStringParameters[qname] = qvalue
queryStringParameters[qname] = qvalue[1]
else
-- single value
multiValueQueryStringParameters[qname] = { qvalue }
end
end
-- prepare body
local body, isBase64Encoded
local skip_large_bodies = config and config.skip_large_bodies or true
do
body = request_util.read_request_body(skip_large_bodies)
if body ~= "" then
body = ngx_encode_base64(body)
isBase64Encoded = true
else
isBase64Encoded = false
end
end
-- prepare path
local path = var.request_uri:match("^([^%?]+)") -- strip any query args
local request = {
resource = ctx.router_matches.uri,
path = path,
httpMethod = var.request_method,
headers = headers,
multiValueHeaders = multiValueHeaders,
pathParameters = pathParameters,
queryStringParameters = queryStringParameters,
multiValueQueryStringParameters = multiValueQueryStringParameters,
body = body,
isBase64Encoded = isBase64Encoded,
}
return request
end
|
-- serializer to wrap the current request into the Amazon API gateway
-- format as described here:
-- https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format
local request_util = require "kong.plugins.aws-lambda.request-util"
local EMPTY = {}
local ngx_req_get_headers = ngx.req.get_headers
local ngx_req_get_uri_args = ngx.req.get_uri_args
local ngx_encode_base64 = ngx.encode_base64
return function(ctx, config)
ctx = ctx or ngx.ctx
local var = ngx.var
-- prepare headers
local headers = ngx_req_get_headers()
local multiValueHeaders = {}
for hname, hvalue in pairs(headers) do
if type(hvalue) == "table" then
-- multi value
multiValueHeaders[hname] = hvalue
headers[hname] = hvalue[1]
else
-- single value
multiValueHeaders[hname] = { hvalue }
end
end
-- prepare url-captures/path-parameters
local pathParameters = {}
for name, value in pairs(ctx.router_matches.uri_captures or EMPTY) do
if type(name) == "string" then -- skip numerical indices, only named
pathParameters[name] = value
end
end
-- query parameters
local queryStringParameters = ngx_req_get_uri_args()
local multiValueQueryStringParameters = {}
for qname, qvalue in pairs(queryStringParameters) do
if type(qvalue) == "table" then
-- multi value
multiValueQueryStringParameters[qname] = qvalue
queryStringParameters[qname] = qvalue[1]
else
-- single value
multiValueQueryStringParameters[qname] = { qvalue }
end
end
-- prepare body
local body, isBase64Encoded
local skip_large_bodies = true
if config and config.skip_large_bodies ~= nil then
skip_large_bodies = config.skip_large_bodies
end
do
body = request_util.read_request_body(skip_large_bodies)
if body ~= "" then
body = ngx_encode_base64(body)
isBase64Encoded = true
else
isBase64Encoded = false
end
end
-- prepare path
local path = var.request_uri:match("^([^%?]+)") -- strip any query args
local request = {
resource = ctx.router_matches.uri,
path = path,
httpMethod = var.request_method,
headers = headers,
multiValueHeaders = multiValueHeaders,
pathParameters = pathParameters,
queryStringParameters = queryStringParameters,
multiValueQueryStringParameters = multiValueQueryStringParameters,
body = body,
isBase64Encoded = isBase64Encoded,
}
return request
end
|
fix(aws-lambda) honor skip_large_bodies for aws-gateway format
|
fix(aws-lambda) honor skip_large_bodies for aws-gateway format
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
fc6ee384b81066ffac264d4b1fa5a56236b2671c
|
lua/LUA/ak/public-transport/Platform.lua
|
lua/LUA/ak/public-transport/Platform.lua
|
local Platform = {}
---@class Platform
---@field type string
---@field id string
---@field roadStation RoadStation
---@field platformNumber number
--- Creates a new Bus or Tram Station
---@param roadStation RoadStation a roadstation
---@param platformNumber number number of the platform starting with 1
---@return Platform
function Platform:new(roadStation, platformNumber)
assert(type(roadStation) == "table", "Need 'roadStation' as RoadStation")
assert(roadStation.type == "RoadStation", "Need 'roadStation' as RoadStation")
assert(type(platformNumber) == "number", "Need 'platformNumber' as number")
local o = {}
o.type = "Platform"
o.id = roadStation.name .. "#" .. platformNumber
o.roadStation = roadStation
o.platformNumber = platformNumber
self.__index = self
setmetatable(o, self)
return o
end
function Platform:addDisplay(structureName, displayModel)
self.roadStation:addDisplay(structureName, displayModel, self.platformNumber)
end
return Platform
|
---@class Platform
---@field type string
---@field id string
---@field roadStation RoadStation
---@field platformNumber number
local Platform = {}
--- Creates a new Bus or Tram Station
---@param roadStation RoadStation a roadstation
---@param platformNumber number number of the platform starting with 1
---@return Platform
function Platform:new(roadStation, platformNumber)
assert(type(roadStation) == "table", "Need 'roadStation' as RoadStation")
assert(roadStation.type == "RoadStation", "Need 'roadStation' as RoadStation")
assert(type(platformNumber) == "number", "Need 'platformNumber' as number")
local o = {}
o.type = "Platform"
o.id = roadStation.name .. "#" .. platformNumber
o.roadStation = roadStation
o.platformNumber = platformNumber
self.__index = self
setmetatable(o, self)
return o
end
function Platform:addDisplay(structureName, displayModel)
self.roadStation:addDisplay(structureName, displayModel, self.platformNumber)
end
return Platform
|
fix emmylua
|
fix emmylua
|
Lua
|
mit
|
Andreas-Kreuz/ak-lua-skripte-fuer-eep,Andreas-Kreuz/ak-lua-skripte-fuer-eep
|
b0f4960cff9e66ab4b88834a4bdaa26dfef5ef78
|
libs/web/luasrc/dispatcher.lua
|
libs/web/luasrc/dispatcher.lua
|
--[[
LuCI - Dispatcher
Description:
The request dispatcher and module dispatcher generators
FileId:
$Id$
License:
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
module("luci.dispatcher", package.seeall)
require("luci.http")
require("luci.sys")
require("luci.fs")
-- Local dispatch database
local tree = {nodes={}}
-- Index table
local index = {}
-- Indexdump
local indexcache = "/tmp/.luciindex"
-- Global request object
request = {}
-- Active dispatched node
dispatched = nil
-- Status fields
built_index = false
built_tree = false
-- Builds a URL
function build_url(...)
return luci.http.dispatcher() .. "/" .. table.concat(arg, "/")
end
-- Sends a 404 error code and renders the "error404" template if available
function error404(message)
luci.http.status(404, "Not Found")
message = message or "Not Found"
require("luci.template")
if not pcall(luci.template.render, "error404") then
luci.http.prepare_content("text/plain")
print(message)
end
return false
end
-- Sends a 500 error code and renders the "error500" template if available
function error500(message)
luci.http.status(500, "Internal Server Error")
require("luci.template")
if not pcall(luci.template.render, "error500", {message=message}) then
luci.http.prepare_content("text/plain")
print(message)
end
return false
end
-- Creates a request object for dispatching
function httpdispatch()
local pathinfo = luci.http.env.PATH_INFO or ""
local c = tree
for s in pathinfo:gmatch("([%w_]+)") do
table.insert(request, s)
end
dispatch()
end
-- Dispatches a request
function dispatch()
if not built_tree then
createtree()
end
local c = tree
local track = {}
for i, s in ipairs(request) do
c = c.nodes[s]
if not c then
break
end
for k, v in pairs(c) do
track[k] = v
end
end
if track.i18n then
require("luci.i18n").loadc(track.i18n)
end
if track.setgroup then
luci.sys.process.setgroup(track.setgroup)
end
if track.setuser then
luci.sys.process.setuser(track.setuser)
end
-- Init template engine
local tpl = require("luci.template")
tpl.viewns.translate = function(...) return require("luci.i18n").translate(...) end
tpl.viewns.controller = luci.http.dispatcher()
tpl.viewns.uploadctrl = luci.http.dispatcher_upload()
tpl.viewns.media = luci.config.main.mediaurlbase
tpl.viewns.resource = luci.config.main.resourcebase
-- Load default translation
require("luci.i18n").loadc("default")
if c and type(c.target) == "function" then
dispatched = c
stat, err = pcall(c.target)
if not stat then
error500(err)
end
else
error404()
end
end
-- Generates the dispatching tree
function createindex()
index = {}
local path = luci.sys.libpath() .. "/controller/"
local suff = ".lua"
if pcall(require, "fastindex") then
createindex_fastindex(path, suff)
else
createindex_plain(path, suff)
end
built_index = true
end
-- Uses fastindex to create the dispatching tree
function createindex_fastindex(path, suffix)
local fi = fastindex.new("index")
fi.add(path .. "*" .. suffix)
fi.add(path .. "*/*" .. suffix)
fi.scan()
for k, v in pairs(fi.indexes) do
index[v[2]] = v[1]
end
end
-- Calls the index function of all available controllers
function createindex_plain(path, suffix)
local cachetime = nil
local controllers = luci.util.combine(
luci.fs.glob(path .. "*" .. suffix) or {},
luci.fs.glob(path .. "*/*" .. suffix) or {}
)
if indexcache then
cachetime = luci.fs.mtime(indexcache)
if not cachetime then
luci.fs.mkdir(indexcache)
luci.fs.chmod(indexcache, "a=,u=rwx")
end
end
if not cachetime or luci.fs.mtime(path) > cachetime then
for i,c in ipairs(controllers) do
c = "luci.controller." .. c:sub(#path+1, #c-#suffix):gsub("/", ".")
stat, mod = pcall(require, c)
if stat and mod and type(mod.index) == "function" then
index[c] = mod.index
if indexcache then
luci.fs.writefile(indexcache .. "/" .. c, string.dump(mod.index))
end
end
end
if indexcache then
luci.fs.unlink(indexcache .. "/.index")
luci.fs.writefile(indexcache .. "/.index", "")
end
else
for i,c in ipairs(luci.fs.dir(indexcache)) do
if c:sub(1) ~= "." then
index[c] = loadfile(indexcache .. "/" .. c)
end
end
end
end
-- Creates the dispatching tree from the index
function createtree()
if not built_index then
createindex()
end
for k, v in pairs(index) do
luci.util.updfenv(v, _M)
local stat, mod = pcall(require, k)
if stat then
luci.util.updfenv(v, mod)
end
pcall(v)
end
built_tree = true
end
-- Shortcut for creating a dispatching node
function entry(path, target, title, order, add)
add = add or {}
local c = node(path)
c.target = target
c.title = title
c.order = order
for k,v in pairs(add) do
c[k] = v
end
return c
end
-- Fetch a dispatching node
function node(...)
local c = tree
if arg[1] and type(arg[1]) == "table" then
arg = arg[1]
end
for k,v in ipairs(arg) do
if not c.nodes[v] then
c.nodes[v] = {nodes={}}
end
c = c.nodes[v]
end
return c
end
-- Subdispatchers --
function alias(...)
local req = arg
return function()
request = req
dispatch()
end
end
function template(name)
require("luci.template")
return function() luci.template.render(name) end
end
function cbi(model)
require("luci.cbi")
require("luci.template")
return function()
local stat, res = pcall(luci.cbi.load, model)
if not stat then
error500(res)
return true
end
local stat, err = pcall(res.parse, res)
if not stat then
error500(err)
return true
end
luci.template.render("cbi/header")
res:render()
luci.template.render("cbi/footer")
end
end
|
--[[
LuCI - Dispatcher
Description:
The request dispatcher and module dispatcher generators
FileId:
$Id$
License:
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
module("luci.dispatcher", package.seeall)
require("luci.http")
require("luci.sys")
require("luci.fs")
-- Local dispatch database
local tree = {nodes={}}
-- Index table
local index = {}
-- Indexdump
local indexcache = "/tmp/.luciindex"
-- Global request object
request = {}
-- Active dispatched node
dispatched = nil
-- Status fields
built_index = false
built_tree = false
-- Builds a URL
function build_url(...)
return luci.http.dispatcher() .. "/" .. table.concat(arg, "/")
end
-- Sends a 404 error code and renders the "error404" template if available
function error404(message)
luci.http.status(404, "Not Found")
message = message or "Not Found"
require("luci.template")
if not pcall(luci.template.render, "error404") then
luci.http.prepare_content("text/plain")
print(message)
end
return false
end
-- Sends a 500 error code and renders the "error500" template if available
function error500(message)
luci.http.status(500, "Internal Server Error")
require("luci.template")
if not pcall(luci.template.render, "error500", {message=message}) then
luci.http.prepare_content("text/plain")
print(message)
end
return false
end
-- Creates a request object for dispatching
function httpdispatch()
local pathinfo = luci.http.env.PATH_INFO or ""
local c = tree
for s in pathinfo:gmatch("([%w_]+)") do
table.insert(request, s)
end
dispatch()
end
-- Dispatches a request
function dispatch()
if not built_tree then
createtree()
end
local c = tree
local track = {}
for i, s in ipairs(request) do
c = c.nodes[s]
if not c then
break
end
for k, v in pairs(c) do
track[k] = v
end
end
if track.i18n then
require("luci.i18n").loadc(track.i18n)
end
if track.setgroup then
luci.sys.process.setgroup(track.setgroup)
end
if track.setuser then
luci.sys.process.setuser(track.setuser)
end
-- Init template engine
local tpl = require("luci.template")
tpl.viewns.translate = function(...) return require("luci.i18n").translate(...) end
tpl.viewns.controller = luci.http.dispatcher()
tpl.viewns.uploadctrl = luci.http.dispatcher_upload()
tpl.viewns.media = luci.config.main.mediaurlbase
tpl.viewns.resource = luci.config.main.resourcebase
-- Load default translation
require("luci.i18n").loadc("default")
if c and type(c.target) == "function" then
dispatched = c
stat, err = pcall(c.target)
if not stat then
error500(err)
end
else
error404()
end
end
-- Generates the dispatching tree
function createindex()
index = {}
local path = luci.sys.libpath() .. "/controller/"
local suff = ".lua"
if pcall(require, "fastindex") then
createindex_fastindex(path, suff)
else
createindex_plain(path, suff)
end
built_index = true
end
-- Uses fastindex to create the dispatching tree
function createindex_fastindex(path, suffix)
local fi = fastindex.new("index")
fi.add(path .. "*" .. suffix)
fi.add(path .. "*/*" .. suffix)
fi.scan()
for k, v in pairs(fi.indexes) do
index[v[2]] = v[1]
end
end
-- Calls the index function of all available controllers
function createindex_plain(path, suffix)
local cachetime = nil
local controllers = luci.util.combine(
luci.fs.glob(path .. "*" .. suffix) or {},
luci.fs.glob(path .. "*/*" .. suffix) or {}
)
if indexcache then
cachetime = luci.fs.mtime(indexcache)
if not cachetime then
luci.fs.mkdir(indexcache)
luci.fs.chmod(indexcache, "a=,u=rwx")
end
end
if not cachetime then
for i,c in ipairs(controllers) do
c = "luci.controller." .. c:sub(#path+1, #c-#suffix):gsub("/", ".")
stat, mod = pcall(require, c)
if stat and mod and type(mod.index) == "function" then
index[c] = mod.index
if indexcache then
luci.fs.writefile(indexcache .. "/" .. c, string.dump(mod.index))
end
end
end
else
for i,c in ipairs(luci.fs.dir(indexcache)) do
if c:sub(1) ~= "." then
index[c] = loadfile(indexcache .. "/" .. c)
end
end
end
end
-- Creates the dispatching tree from the index
function createtree()
if not built_index then
createindex()
end
for k, v in pairs(index) do
luci.util.updfenv(v, _M)
local stat, mod = pcall(require, k)
if stat then
luci.util.updfenv(v, mod)
end
pcall(v)
end
built_tree = true
end
-- Shortcut for creating a dispatching node
function entry(path, target, title, order, add)
add = add or {}
local c = node(path)
c.target = target
c.title = title
c.order = order
for k,v in pairs(add) do
c[k] = v
end
return c
end
-- Fetch a dispatching node
function node(...)
local c = tree
if arg[1] and type(arg[1]) == "table" then
arg = arg[1]
end
for k,v in ipairs(arg) do
if not c.nodes[v] then
c.nodes[v] = {nodes={}}
end
c = c.nodes[v]
end
return c
end
-- Subdispatchers --
function alias(...)
local req = arg
return function()
request = req
dispatch()
end
end
function template(name)
require("luci.template")
return function() luci.template.render(name) end
end
function cbi(model)
require("luci.cbi")
require("luci.template")
return function()
local stat, res = pcall(luci.cbi.load, model)
if not stat then
error500(res)
return true
end
local stat, err = pcall(res.parse, res)
if not stat then
error500(err)
return true
end
luci.template.render("cbi/header")
res:render()
luci.template.render("cbi/footer")
end
end
|
* Fixed caching mechanism
|
* Fixed caching mechanism
git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@2160 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
alxhh/piratenluci,projectbismark/luci-bismark,vhpham80/luci,phi-psi/luci,dtaht/cerowrt-luci-3.3,ReclaimYourPrivacy/cloak-luci,gwlim/luci,8devices/carambola2-luci,jschmidlapp/luci,vhpham80/luci,Canaan-Creative/luci,projectbismark/luci-bismark,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci,ch3n2k/luci,zwhfly/openwrt-luci,projectbismark/luci-bismark,stephank/luci,Flexibity/luci,projectbismark/luci-bismark,jschmidlapp/luci,gwlim/luci,dtaht/cerowrt-luci-3.3,saraedum/luci-packages-old,alxhh/piratenluci,alxhh/piratenluci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,zwhfly/openwrt-luci,Flexibity/luci,yeewang/openwrt-luci,jschmidlapp/luci,Canaan-Creative/luci,jschmidlapp/luci,Canaan-Creative/luci,freifunk-gluon/luci,8devices/carambola2-luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,alxhh/piratenluci,Canaan-Creative/luci,eugenesan/openwrt-luci,eugenesan/openwrt-luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,stephank/luci,jschmidlapp/luci,alxhh/piratenluci,phi-psi/luci,zwhfly/openwrt-luci,gwlim/luci,ThingMesh/openwrt-luci,Flexibity/luci,8devices/carambola2-luci,saraedum/luci-packages-old,phi-psi/luci,zwhfly/openwrt-luci,ch3n2k/luci,jschmidlapp/luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,dtaht/cerowrt-luci-3.3,8devices/carambola2-luci,gwlim/luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,gwlim/luci,eugenesan/openwrt-luci,gwlim/luci,stephank/luci,saraedum/luci-packages-old,freifunk-gluon/luci,Flexibity/luci,Canaan-Creative/luci,projectbismark/luci-bismark,dtaht/cerowrt-luci-3.3,alxhh/piratenluci,Flexibity/luci,yeewang/openwrt-luci,projectbismark/luci-bismark,ch3n2k/luci,Flexibity/luci,eugenesan/openwrt-luci,phi-psi/luci,Canaan-Creative/luci,freifunk-gluon/luci,8devices/carambola2-luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,vhpham80/luci,stephank/luci,8devices/carambola2-luci,yeewang/openwrt-luci,ch3n2k/luci,8devices/carambola2-luci,phi-psi/luci,Canaan-Creative/luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,dtaht/cerowrt-luci-3.3,projectbismark/luci-bismark,eugenesan/openwrt-luci,ReclaimYourPrivacy/cloak-luci,saraedum/luci-packages-old,ThingMesh/openwrt-luci,vhpham80/luci,freifunk-gluon/luci,Canaan-Creative/luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,projectbismark/luci-bismark,gwlim/luci,jschmidlapp/luci,freifunk-gluon/luci,Flexibity/luci,ch3n2k/luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,alxhh/piratenluci,yeewang/openwrt-luci,stephank/luci,stephank/luci,ch3n2k/luci,saraedum/luci-packages-old,ch3n2k/luci,saraedum/luci-packages-old,vhpham80/luci,vhpham80/luci,yeewang/openwrt-luci,dtaht/cerowrt-luci-3.3,yeewang/openwrt-luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci
|
c0ac4cc651c537c67f901cbe1f33a879e19e15b4
|
src/cosy/server.lua
|
src/cosy/server.lua
|
local loader = require "cosy.loader"
local hotswap = loader.hotswap
local Server = {}
function Server.get (http)
if http.request.method ~= "GET" then
http.response.status = 405
http.response.message = "Method Not Allowed"
elseif http.request.headers ["upgrade"] == "websocket" then
http () -- send response
http.socket:send "\r\n"
return Server.wsloop (http)
elseif http.request.method == "GET" then
if http.request.path:sub (-1) == "/" then
http.request.path = http.request.path .. "index.html"
end
if http.request.path:sub (-9) == "cosy.conf" then
http.response.status = 403
http.response.message = "Forbidden"
http.response.body = "Nice try ;-)\n"
else
for path in package.path:gmatch "([^;]+)" do
if path:sub (-5) == "?.lua" then
path = path:sub (1, #path - 5) .. http.request.path
local file = io.open (path, "r")
if file then
http.response.status = 200
http.response.message = "OK"
http.response.body = file:read "*all"
file:close ()
return
end
end
end
end
http.response.status = 404
http.response.message = "Not Found"
else
http.response.status = 500
http.response.message = "Internal Server Error"
end
end
function Server.request (message)
local loader = hotswap "cosy.loader"
local i18n = loader.i18n
local function translate (x)
i18n (x)
return x
end
local decoded, request = pcall (loader.value.decode, message)
if not decoded or type (request) ~= "table" then
return loader.value.expression (translate {
success = false,
error = {
_ = "rpc:invalid",
reason = message,
},
})
end
local identifier = request.identifier
local operation = request.operation
local parameters = request.parameters
local Methods = loader.methods
local method = Methods [operation]
if not method then
return loader.value.expression (translate {
identifier = identifier,
success = false,
error = {
_ = "rpc:no-operation",
reason = operation,
},
})
end
local result, err = method (parameters or {})
if not result then
print ("error:", loader.value.expression (err))
print (debug.traceback())
return loader.value.expression (translate {
identifier = identifier,
success = false,
error = err,
})
end
return loader.value.expression (translate {
identifier = identifier,
success = true,
response = result,
})
end
function Server.wsloop (http)
while http.websocket.client.state ~= "CLOSED" do
local message = http.websocket.client:receive ()
if message then
local result = Server.request (message)
if result then
http.websocket.client:send (result)
end
else
http.websocket.client:close ()
end
end
end
do
local socket = hotswap "socket"
local scheduler = loader.scheduler
local configuration = loader.configuration
local host = configuration.server.host._
local port = configuration.server.port._
local skt = socket.bind (host, port)
scheduler.addserver (skt, function (socket)
local Http = hotswap "httpserver"
local http = Http.new {
hotswap = hotswap,
socket = socket,
websocket = {
protocols = { "cosy" },
},
}
pcall (function ()
repeat
http ()
Server.get (http)
local continue = http ()
until not continue
end)
end)
loader.logger.debug {
_ = "server:listening",
host = host,
port = port,
}
-- local profiler = require "ProFi"
-- profiler:start ()
scheduler.loop ()
-- profiler:stop ()
-- profiler:writeReport "profiler.txt"
end
|
local loader = require "cosy.loader"
local hotswap = loader.hotswap
local Server = {}
function Server.get (http)
if http.request.method ~= "GET" then
http.response.status = 405
http.response.message = "Method Not Allowed"
elseif http.request.headers ["upgrade"] == "websocket" then
http () -- send response
http.socket:send "\r\n"
return Server.wsloop (http)
elseif http.request.method == "GET" then
if http.request.path:sub (-1) == "/" then
http.request.path = http.request.path .. "index.html"
end
if http.request.path:sub (-9) == "cosy.conf" then
http.response.status = 403
http.response.message = "Forbidden"
http.response.body = "Nice try ;-)\n"
else
for path in package.path:gmatch "([^;]+)" do
if path:sub (-5) == "?.lua" then
path = path:sub (1, #path - 5) .. http.request.path
local file = io.open (path, "r")
if file then
http.response.status = 200
http.response.message = "OK"
http.response.body = file:read "*all"
file:close ()
return
end
end
end
end
http.response.status = 404
http.response.message = "Not Found"
else
http.response.status = 500
http.response.message = "Internal Server Error"
end
end
function Server.request (message)
local loader = hotswap "cosy.loader"
local i18n = loader.i18n
local function translate (x)
i18n (x)
return x
end
local decoded, request = pcall (loader.value.decode, message)
if not decoded or type (request) ~= "table" then
return loader.value.expression (translate {
success = false,
error = {
_ = "rpc:invalid",
reason = message,
},
})
end
local identifier = request.identifier
local operation = request.operation
local parameters = request.parameters
local Methods = loader.methods
local method = Methods [operation]
if not method then
return loader.value.expression (translate {
identifier = identifier,
success = false,
error = {
_ = "rpc:no-operation",
reason = operation,
},
})
end
local result, err = method (parameters or {})
if not result then
loader.logger.warning ("error: " .. loader.value.expression (err))
loader.logger.warning (debug.traceback())
return loader.value.expression (translate {
identifier = identifier,
success = false,
error = err,
})
end
return loader.value.expression (translate {
identifier = identifier,
success = true,
response = result,
})
end
function Server.wsloop (http)
while http.websocket.client.state ~= "CLOSED" do
local message = http.websocket.client:receive ()
if message then
local result = Server.request (message)
if result then
http.websocket.client:send (result)
end
else
http.websocket.client:close ()
end
end
end
do
local socket = hotswap "socket"
local scheduler = loader.scheduler
local configuration = loader.configuration
local host = configuration.server.host._
local port = configuration.server.port._
local skt = socket.bind (host, port)
scheduler.addserver (skt, function (socket)
local Http = hotswap "httpserver"
local http = Http.new {
hotswap = hotswap,
socket = socket,
websocket = {
protocols = { "cosy" },
},
}
pcall (function ()
repeat
http ()
Server.get (http)
local continue = http ()
until not continue
end)
end)
loader.logger.debug {
_ = "server:listening",
host = host,
port = port,
}
-- local profiler = require "ProFi"
-- profiler:start ()
scheduler.loop ()
-- profiler:stop ()
-- profiler:writeReport "profiler.txt"
end
|
Fix error printing.
|
Fix error printing.
|
Lua
|
mit
|
CosyVerif/library,CosyVerif/library,CosyVerif/library
|
a94ac96c993f7ebce059a20e911cd008844442b0
|
src/models/upload.lua
|
src/models/upload.lua
|
--- A basic lower upload API
--
module(..., package.seeall)
require 'posix'
local http = require 'lglib.http'
local normalizePath = require('lglib.path').normalize
local Model = require 'bamboo.model'
local Form = require 'bamboo.form'
local function calcNewFilename(dir, oldname)
-- separate the base name and extense name of a filename
local main, ext = oldname:match('^(.+)(%.%w+)$')
if not ext then
main = oldname
ext = ''
end
-- check if exists the same name file
local tstr = ''
local i = 0
while posix.stat( dir + main + tstr + ext ) do
i = i + 1
tstr = '_' + tostring(i)
end
-- concat to new filename
local newbasename = main + tstr
return newbasename, ext
end
--- here, we temprorily only consider the file data is passed wholly by zeromq
-- and save by bamboo
-- @field t.req
-- @field t.file_obj
-- @field t.dest_dir
-- @field t.prefix
-- @field t.postfix
--
local function savefile(t)
local req, file_obj = t.req, t.file_obj
local dest_dir = t.dest_dir and ('/uploads/' + t.dest_dir + '/') or '/uploads/'
dest_dir = normalizePath(dest_dir)
local prefix = t.prefix or ''
local postfix = t.postfix or ''
local filename = ''
local body = ''
local rename_func = t.rename_func or nil
-- if upload in html5 way
if req.headers['x-requested-with'] then
-- when html5 upload, we think of the name of that file was stored in header x-file-name
-- if this info missing, we may consider the filename was put in the query string
filename = req.headers['x-file-name'] or Form:parseQuery(req)['filename']
-- TODO:
-- req.body contains all file binary data
body = req.body
else
checkType(file_obj, 'table')
-- Notice: the filename in the form string are quoted by ""
-- this pattern rule can deal with the windows style directory delimiter
-- file_obj['content-disposition'] contains many file associated info
filename = file_obj['content-disposition'].filename:sub(2, -2):match('\\?([^\\]-%.%w+)$')
body = file_obj.body
end
if isFalse(filename) or isFalse(body) then return nil, nil end
if not req.ajax then
filename = http.encodeURL(filename)
end
if not posix.stat(dest_dir) then
-- why posix have no command like " mkdir -p "
os.execute('mkdir -p ' + dest_dir)
end
local newfilename = filename
-- if passed in a rename function, use it to replace the orignial filename
if rename_func and type(rename_func) == 'function' then
newfilename = rename_func(filename)
end
local newbasename, ext = calcNewFilename(dest_dir, newfilename)
local newname = prefix + newbasename + postfix + ext
local path = dest_dir + newname
-- write file to disk
local fd = io.open(path, "wb")
fd:write(body)
fd:close()
return newname, path, filename
end
local Upload = Model:extend {
__name = 'Upload';
__primarykey = "path";
__fields = {
['name'] = {},
['path'] = {unique=true},
['size'] = {},
['timestamp'] = {},
['desc'] = {},
};
__decorators = {
del = function (odel)
return function (self, ...)
I_AM_INSTANCE_OR_QUERY_SET(self)
-- if self is query set
if isQuerySet(self) then
for _, v in ipairs(self) do
-- remove file from disk
os.execute('rm ' + v.path)
end
else
-- remove file from disk
os.execute('rm ' + self.path)
end
return odel(self, ...)
end
end
};
init = function (self, t)
if not t then return self end
self.oldname = t.oldname
self.name = t.name
self.path = t.path or 'media/uploads/default'
self.size = posix.stat(self.path).size
self.timestamp = os.time()
-- according the current design, desc field is nil
self.desc = t.desc or ''
return self
end;
--- For traditional Html4 form upload
--
batch = function (self, req, params, dest_dir, prefix, postfix, rename_func)
I_AM_CLASS(self)
local file_objs = List()
-- file data are stored as arraies in params
for i, v in ipairs(params) do
local name, path = savefile { req = req, file_obj = v, dest_dir = dest_dir, prefix = prefix, postfix = postfix, rename_func = rename_func }
if not path or not name then return nil end
-- create file instance
local file_instance = self { name = name, path = path }
if file_instance then
-- store to db
-- file_instance:save()
-- fix the id sequence
-- file_instance.id = file_instance.id + i - 1
file_objs:append(file_instance)
end
end
-- a file object list
return file_objs
end;
process = function (self, web, req, dest_dir, prefix, postfix, rename_func)
I_AM_CLASS(self)
assert(web, '[Error] Upload input parameter: "web" must be not nil.')
assert(req, '[Error] Upload input parameter: "req" must be not nil.')
-- current scheme: for those larger than PRESIZE, send a ABORT signal, and abort immediately
if req.headers['x-mongrel2-upload-start'] then
print('return blank to abort upload.')
web.conn:reply(req, '')
return nil, 'Uploading file is too large.'
end
-- if upload in html5 way
if req.headers['x-requested-with'] then
-- stored to disk
local name, path, oldname = savefile { req = req, dest_dir = dest_dir, prefix = prefix, postfix = postfix, rename_func = rename_func }
if not path or not name then return nil, '[Error] empty file.' end
local file_instance = self { name = name, path = path, oldname = oldname }
if file_instance then
-- file_instance:save()
return file_instance, 'single'
end
else
-- for uploading in html4 way
-- here, in formal html4 form, req.POST always has value in,
local params = req.POST -- or Form:parse(req)
assert(#params > 0, '[Error] No valid file data contained.')
local files = self:batch ( req, params, dest_dir, prefix, postfix, rename_func )
if files:isEmpty() then return nil, '[Error] empty file.' end
if #files == 1 then
-- even only one file upload, batch function will return a list
return files[1], 'single'
else
return files, 'multiple'
end
end
end;
calcNewFilename = function (self, dest_dir, oldname)
return calcNewFilename(dest_dir, oldname)
end;
-- this function, encorage override by child model, to execute their own delete action
-- specDelete = function (self)
-- I_AM_INSTANCE(self)
-- -- remove file from disk
-- os.execute('rm ' + self.path)
-- return self
-- end;
}
return Upload
|
--- A basic lower upload API
--
module(..., package.seeall)
require 'posix'
local http = require 'lglib.http'
local normalizePath = require('lglib.path').normalize
local Model = require 'bamboo.model'
local Form = require 'bamboo.form'
local function calcNewFilename(dir, oldname)
-- separate the base name and extense name of a filename
local main, ext = oldname:match('^(.+)(%.%w+)$')
if not ext then
main = oldname
ext = ''
end
-- check if exists the same name file
local tstr = ''
local i = 0
while posix.stat( dir + main + tstr + ext ) do
i = i + 1
tstr = '_' + tostring(i)
end
-- concat to new filename
local newbasename = main + tstr
return newbasename, ext
end
--- here, we temprorily only consider the file data is passed wholly by zeromq
-- and save by bamboo
-- @field t.req
-- @field t.file_obj
-- @field t.dest_dir
-- @field t.prefix
-- @field t.postfix
--
local function savefile(t)
local req, file_obj = t.req, t.file_obj
local export_dir = t.dest_dir and ('/uploads/' + t.dest_dir + '/') or '/uploads/'
export_dir = normalizePath(export_dir)
local dest_dir = 'media'.. export_dir
local prefix = t.prefix or ''
local postfix = t.postfix or ''
local filename = ''
local body = ''
local rename_func = t.rename_func or nil
-- if upload in html5 way
if req.headers['x-requested-with'] then
-- when html5 upload, we think of the name of that file was stored in header x-file-name
-- if this info missing, we may consider the filename was put in the query string
filename = req.headers['x-file-name'] or Form:parseQuery(req)['filename']
-- TODO:
-- req.body contains all file binary data
body = req.body
else
checkType(file_obj, 'table')
-- Notice: the filename in the form string are quoted by ""
-- this pattern rule can deal with the windows style directory delimiter
-- file_obj['content-disposition'] contains many file associated info
filename = file_obj['content-disposition'].filename:sub(2, -2):match('\\?([^\\]-%.%w+)$')
body = file_obj.body
end
if isFalse(filename) or isFalse(body) then return nil, nil end
if not req.ajax then
filename = http.encodeURL(filename)
end
if not posix.stat(dest_dir) then
-- why posix have no command like " mkdir -p "
os.execute('mkdir -p ' + dest_dir)
end
local newfilename = filename
-- if passed in a rename function, use it to replace the orignial filename
if rename_func and type(rename_func) == 'function' then
newfilename = rename_func(filename)
end
local newbasename, ext = calcNewFilename(dest_dir, newfilename)
local newname = prefix + newbasename + postfix + ext
local export_path = export_dir + newname
local path = dest_dir + newname
-- write file to disk
local fd = io.open(path, "wb")
fd:write(body)
fd:close()
return newname, path, export_path, filename
end
local Upload = Model:extend {
__name = 'Upload';
__primarykey = "path";
__fields = {
['name'] = {},
['path'] = {unique=true},
['size'] = {},
['timestamp'] = {},
['desc'] = {},
};
__decorators = {
del = function (odel)
return function (self, ...)
I_AM_INSTANCE_OR_QUERY_SET(self)
-- if self is query set
if isQuerySet(self) then
for _, v in ipairs(self) do
-- remove file from disk
os.execute('rm ' + v.path)
end
else
-- remove file from disk
os.execute('rm ' + self.path)
end
return odel(self, ...)
end
end
};
init = function (self, t)
if not t then return self end
self.oldname = t.oldname
self.name = t.name
self.path = t.export_path
self.size = posix.stat(t.path).size
self.timestamp = os.time()
-- according the current design, desc field is nil
self.desc = t.desc or ''
return self
end;
--- For traditional Html4 form upload
--
batch = function (self, req, params, dest_dir, prefix, postfix, rename_func)
I_AM_CLASS(self)
local file_objs = List()
-- file data are stored as arraies in params
for i, v in ipairs(params) do
local name, path, export_path = savefile { req = req, file_obj = v, dest_dir = dest_dir, prefix = prefix, postfix = postfix, rename_func = rename_func }
if not path or not name then return nil end
-- create file instance
local file_instance = self { name = name, path = path, export_path = export_path }
if file_instance then
-- store to db
-- file_instance:save()
-- fix the id sequence
-- file_instance.id = file_instance.id + i - 1
file_objs:append(file_instance)
end
end
-- a file object list
return file_objs
end;
process = function (self, web, req, dest_dir, prefix, postfix, rename_func)
I_AM_CLASS(self)
assert(web, '[Error] Upload input parameter: "web" must be not nil.')
assert(req, '[Error] Upload input parameter: "req" must be not nil.')
-- current scheme: for those larger than PRESIZE, send a ABORT signal, and abort immediately
if req.headers['x-mongrel2-upload-start'] then
print('return blank to abort upload.')
web.conn:reply(req, '')
return nil, 'Uploading file is too large.'
end
-- if upload in html5 way
if req.headers['x-requested-with'] then
-- stored to disk
local name, path, export_path, oldname = savefile { req = req, dest_dir = dest_dir, prefix = prefix, postfix = postfix, rename_func = rename_func }
if not path or not name then return nil, '[Error] empty file.' end
local file_instance = self { name = name, path = path, export_path = export_path, oldname = oldname }
if file_instance then
-- file_instance:save()
return file_instance, 'single'
end
else
-- for uploading in html4 way
-- here, in formal html4 form, req.POST always has value in,
local params = req.POST -- or Form:parse(req)
assert(#params > 0, '[Error] No valid file data contained.')
local files = self:batch ( req, params, dest_dir, prefix, postfix, rename_func )
if files:isEmpty() then return nil, '[Error] empty file.' end
if #files == 1 then
-- even only one file upload, batch function will return a list
return files[1], 'single'
else
return files, 'multiple'
end
end
end;
calcNewFilename = function (self, dest_dir, oldname)
return calcNewFilename(dest_dir, oldname)
end;
-- this function, encorage override by child model, to execute their own delete action
-- specDelete = function (self)
-- I_AM_INSTANCE(self)
-- -- remove file from disk
-- os.execute('rm ' + self.path)
-- return self
-- end;
}
return Upload
|
fix a bug in export path.
|
fix a bug in export path.
Signed-off-by: Daogang Tang <[email protected]>
|
Lua
|
bsd-3-clause
|
daogangtang/bamboo,daogangtang/bamboo
|
42a7ef1f6a5c3b850ba323e4d9d390a1bec42e9e
|
lib/hpcpf.lua
|
lib/hpcpf.lua
|
--- for detection platform (return "Windows", "Darwin" or "Linux")
function getPlatform()
--- command capture
function captureRedirectErr(cmd)
local f = assert(io.popen(cmd .. ' 2>&1' , 'r'))
local s = assert(f:read('*a'))
f:close()
s = string.gsub(s, '^%s+', '')
s = string.gsub(s, '%s+$', '')
s = string.gsub(s, '[\n\r]+', ' ')
return s
end
if package.config:sub(1,1) == "\\" then
return 'Windows'
else
local plf = captureRedirectErr('uname')
return plf -- 'Darwin', 'Linux'
end
end
-- force buffer flush function
if getPlatform() == 'Windows' then
orgPrint = print
print = function(...) orgPrint(...) io.stdout:flush() end
end
function errorlog(msg)
io.stderr:write(msg .. '\n')
end
-- File/Dir Utility fuctions
function compressFile(srcname, tarname, verbose, opt)
local tarcmd
local optcmd = opt and opt or ''
local option = (verbose == true) and '-czvf' or '-czf'
if (getPlatform() == 'Windows') then
local TAR_CMD = HPCPF_BIN_DIR .. '/tar.exe'
tarcmd = TAR_CMD .. ' ' .. optcmd .. ' ' .. option .. ' ' .. tarname .. ' ' .. srcname
else
local TAR_CMD = 'tar'
tarcmd = TAR_CMD .. ' ' .. optcmd .. ' ' .. option .. ' ' .. tarname .. ' ' .. srcname
end
print(tarcmd)
local handle = io.popen(tarcmd)
local result = handle:read("*a")
handle:close()
return result
end
function extractFile(tarname, verbose, opt)
local tarcmd
local optcmd = opt and opt or ''
local option = verbose and '-xvf' or '-xf'
if (getPlatform() == 'Windows') then
local TAR_CMD = HPCPF_BIN_DIR .. '/tar.exe'
tarcmd = TAR_CMD .. ' ' .. optcmd .. ' '.. option .. ' ' .. tarname
else
local TAR_CMD = 'tar'
tarcmd = TAR_CMD .. ' ' .. optcmd .. ' '.. option .. ' ' .. tarname
end
print(tarcmd)
local handle = io.popen(tarcmd)
local result = handle:read("*a")
handle:close()
return result
end
function deleteFile(filename)
local rmcmd
if (getPlatform() == 'Windows') then
rmcmd = 'del /Q'
else
rmcmd = 'rm '
end
local cmd = rmcmd .. ' ' .. filename
local handle = io.popen(cmd)
local result = handle:read("*a")
handle:close()
return result
end
function deleteDir(dirname)
local rmcmd
if (getPlatform() == 'Windows') then
rmcmd = 'rd /q /s'
else
rmcmd = 'rm -rf'
end
local cmd = rmcmd .. ' ' .. dirname
local handle = io.popen(cmd)
local result = handle:read("*a")
handle:close()
return result
end
function moveFile(fromFile, toFile)
local mvcmd
if (getPlatform() == 'Windows') then
mvcmd = 'move'
else
mvcmd = 'mv'
end
local cmd = mvcmd .. ' ' .. fromFile .. ' ' .. toFile
local handle = io.popen(cmd)
local result = handle:read("*a")
handle:close()
return result
end
function copyFile(fromFile, toFile)
local cpcmd
if (getPlatform() == 'Windows') then
cpcmd = 'copy'
else
cpcmd = 'cp'
end
local cmd = cpcmd .. ' ' .. fromFile .. ' ' .. toFile
local handle = io.popen(cmd)
local result = handle:read("*a")
handle:close()
return result
end
function makeDir(dirpath)
local mkcmd = 'mkdir'
local cmd = mkcmd .. ' ' .. dirpath
local handle = io.popen(cmd)
local result = handle:read("*a")
handle:close()
return result
end
--- Lua Utility
function dumpTable(t,prefix)
if (prefix==nil) then prefix="" end
for i,v in pairs(t) do
print(prefix,i,v)
if (type(v)=='table') then
dumpTable(v,prefix.."-")
end
end
end
--- execution for CASE
local s_base_path=""
function setBasePath(dir)
s_base_path = dir
end
function getBasePath()
return s_base_path
end
function execmd(command)
local handle = io.popen(command,"r")
local content = handle:read("*all")
handle:close()
return content
end
function getCurrentDir()
local pwdcmd
if (getPlatform() == 'Windows') then
pwdcmd = 'cd'
else
pwdcmd = 'pwd'
end
return execmd(pwdcmd):gsub('\n','')
end
function executeCASE(casename,...)
local args_table = {...}
--print("num="..#args_table)
local cf = loadfile('./'..casename..'/cwf.lua');
if (cf == nil) then
print("Can't find Case work flow:"..casename)
print("or can't find " .. casename..'/cwf.lua')
else
print("--- Start CASE: "..casename.." ---")
setBasePath('/' .. casename)
local oldPackagePath = package.path
package.path = "./" .. casename .. "/?.lua;" .. oldPackagePath
cf(args_table)
package.path = oldPackagePath
setBasePath('')
print("--- End CASE: "..casename.." ---")
end
end
--- JSON loader
local json = require('dkjson')
function readJSON(filename)
local filestr = ''
local fp = io.open(s_base_path..filename,'r');
local jst = nil
if (fp) then
filestr = fp:read("*all")
jst = json.decode (filestr, 1, nil)
end
return jst;
end
--- Sleep
function sleep(n)
if getPlatform() == 'Windows' then
--os.execute("timeout /NOBREAK /T " .. math.floor(tonumber(n)) .. ' > nul')
local cmd = HPCPF_BIN_DIR .. '/sleeper.exe ' .. math.floor(n)
os.execute(cmd)
else
os.execute("sleep " .. tonumber(n))
end
end
-- xjob
require('xjob')
|
--- for detection platform (return "Windows", "Darwin" or "Linux")
function getPlatform()
--- command capture
function captureRedirectErr(cmd)
local f = assert(io.popen(cmd .. ' 2>&1' , 'r'))
local s = assert(f:read('*a'))
f:close()
s = string.gsub(s, '^%s+', '')
s = string.gsub(s, '%s+$', '')
s = string.gsub(s, '[\n\r]+', ' ')
return s
end
if package.config:sub(1,1) == "\\" then
return 'Windows'
else
local plf = captureRedirectErr('uname')
return plf -- 'Darwin', 'Linux'
end
end
-- force buffer flush function
orgPrint = print
print = function(...) orgPrint(...) io.stdout:flush() end
function errorlog(msg)
io.stderr:write(msg .. '\n')
end
-- File/Dir Utility fuctions
function compressFile(srcname, tarname, verbose, opt)
local tarcmd
local optcmd = opt and opt or ''
local option = (verbose == true) and '-czvf' or '-czf'
if (getPlatform() == 'Windows') then
local TAR_CMD = HPCPF_BIN_DIR .. '/tar.exe'
tarcmd = TAR_CMD .. ' ' .. optcmd .. ' ' .. option .. ' ' .. tarname .. ' ' .. srcname
else
local TAR_CMD = 'tar'
tarcmd = TAR_CMD .. ' ' .. optcmd .. ' ' .. option .. ' ' .. tarname .. ' ' .. srcname
end
print(tarcmd)
local handle = io.popen(tarcmd)
local result = handle:read("*a")
handle:close()
return result
end
function extractFile(tarname, verbose, opt)
local tarcmd
local optcmd = opt and opt or ''
local option = verbose and '-xvf' or '-xf'
if (getPlatform() == 'Windows') then
local TAR_CMD = HPCPF_BIN_DIR .. '/tar.exe'
tarcmd = TAR_CMD .. ' ' .. optcmd .. ' '.. option .. ' ' .. tarname
else
local TAR_CMD = 'tar'
tarcmd = TAR_CMD .. ' ' .. optcmd .. ' '.. option .. ' ' .. tarname
end
print(tarcmd)
local handle = io.popen(tarcmd)
local result = handle:read("*a")
handle:close()
return result
end
function deleteFile(filename)
local rmcmd
if (getPlatform() == 'Windows') then
rmcmd = 'del /Q'
else
rmcmd = 'rm '
end
local cmd = rmcmd .. ' ' .. filename
local handle = io.popen(cmd)
local result = handle:read("*a")
handle:close()
return result
end
function deleteDir(dirname)
local rmcmd
if (getPlatform() == 'Windows') then
rmcmd = 'rd /q /s'
else
rmcmd = 'rm -rf'
end
local cmd = rmcmd .. ' ' .. dirname
local handle = io.popen(cmd)
local result = handle:read("*a")
handle:close()
return result
end
function moveFile(fromFile, toFile)
local mvcmd
if (getPlatform() == 'Windows') then
mvcmd = 'move'
else
mvcmd = 'mv'
end
local cmd = mvcmd .. ' ' .. fromFile .. ' ' .. toFile
local handle = io.popen(cmd)
local result = handle:read("*a")
handle:close()
return result
end
function copyFile(fromFile, toFile)
local cpcmd
if (getPlatform() == 'Windows') then
cpcmd = 'copy'
else
cpcmd = 'cp'
end
local cmd = cpcmd .. ' ' .. fromFile .. ' ' .. toFile
local handle = io.popen(cmd)
local result = handle:read("*a")
handle:close()
return result
end
function makeDir(dirpath)
local mkcmd = 'mkdir'
local cmd = mkcmd .. ' ' .. dirpath
local handle = io.popen(cmd)
local result = handle:read("*a")
handle:close()
return result
end
--- Lua Utility
function dumpTable(t,prefix)
if (prefix==nil) then prefix="" end
for i,v in pairs(t) do
print(prefix,i,v)
if (type(v)=='table') then
dumpTable(v,prefix.."-")
end
end
end
--- execution for CASE
local s_base_path=""
function setBasePath(dir)
s_base_path = dir
end
function getBasePath()
return s_base_path
end
function execmd(command)
local handle = io.popen(command,"r")
local content = handle:read("*all")
handle:close()
return content
end
function getCurrentDir()
local pwdcmd
if (getPlatform() == 'Windows') then
pwdcmd = 'cd'
else
pwdcmd = 'pwd'
end
return execmd(pwdcmd):gsub('\n','')
end
function executeCASE(casename,...)
local args_table = {...}
--print("num="..#args_table)
local cf = loadfile('./'..casename..'/cwf.lua');
if (cf == nil) then
print("Can't find Case work flow:"..casename)
print("or can't find " .. casename..'/cwf.lua')
else
print("--- Start CASE: "..casename.." ---")
setBasePath('/' .. casename)
local oldPackagePath = package.path
package.path = "./" .. casename .. "/?.lua;" .. oldPackagePath
cf(args_table)
package.path = oldPackagePath
setBasePath('')
print("--- End CASE: "..casename.." ---")
end
end
--- JSON loader
local json = require('dkjson')
function readJSON(filename)
local filestr = ''
local fp = io.open(s_base_path..filename,'r');
local jst = nil
if (fp) then
filestr = fp:read("*all")
jst = json.decode (filestr, 1, nil)
end
return jst;
end
--- Sleep
function sleep(n)
if getPlatform() == 'Windows' then
--os.execute("timeout /NOBREAK /T " .. math.floor(tonumber(n)) .. ' > nul')
local cmd = HPCPF_BIN_DIR .. '/sleeper.exe ' .. math.floor(n)
os.execute(cmd)
else
os.execute("sleep " .. tonumber(n))
end
end
-- xjob
require('xjob')
|
fixed for Linux
|
fixed for Linux
|
Lua
|
bsd-2-clause
|
avr-aics-riken/hpcpfGUI,digirea/hpcpfGUI,digirea/hpcpfGUI,digirea/hpcpfGUI,avr-aics-riken/hpcpfGUI,avr-aics-riken/hpcpfGUI
|
d697c2fbbf1b7c6080a77cdb08d1ca263f23c4eb
|
tests/watch/quake.lua
|
tests/watch/quake.lua
|
require "sprite"
require "theme"
require "timer"
local q = std.obj {
{
started = false;
timer = false;
step = 0;
};
max = 3; -- iterations
power = 40; -- power
post = true; -- after action or before it
nam = '@quake';
}
local scr
local cb = timer.callback
function timer:callback(...)
if q.started then
return '@quake'
end
return cb(self, ...)
end
function q.start()
local old = sprite.direct()
sprite.direct(true)
sprite.scr():copy(scr)
sprite.direct(old)
q.timer = timer:get()
q.step = 0
q.started = true
timer:set(50)
if not q.post then
sprite.direct(true)
end
end
std.mod_cmd(function(cmd)
if cmd[1] ~= '@quake' then
return
end
if not sprite.direct() then
sprite.direct(true)
sprite.scr():copy(scr)
end
q.step = q.step + 1
sprite.scr():fill('black')
scr:copy(sprite.scr(), 0, rnd(q.power) - q.power / 2);
if q.step > q.max then
q.started = false
timer:set(q.timer)
sprite.direct(false)
return std.nop()
end
return false
end)
std.mod_start(function()
scr = sprite.new(theme.get 'scr.w', theme.get 'scr.h')
end)
quake = q
|
require "sprite"
require "theme"
require "timer"
local q = std.obj {
{
started = false;
timer = false;
step = 0;
};
max = 5; -- iterations
power = 40; -- power
post = true; -- after action or before it
nam = '@quake';
}
local scr
local cb = timer.callback
function timer:callback(...)
if q.started then
return '@quake'
end
return cb(self, ...)
end
function q.start()
local old = sprite.direct()
sprite.direct(true)
sprite.scr():copy(scr)
sprite.direct(old)
q.timer = timer:get()
q.step = 0
q.started = true
timer:set(50)
if not q.post then
sprite.direct(true)
end
end
std.mod_cmd(function(cmd)
if cmd[1] ~= '@quake' then
return
end
if not sprite.direct() then
sprite.direct(true)
sprite.scr():copy(scr)
end
q.step = q.step + 1
sprite.scr():fill('black')
local dy = q.power - rnd(q.power / 4)
if q.step % 2 == 0 then
dy = dy
else
dy = - dy
end
scr:copy(sprite.scr(), 0, dy);
if q.step > q.max then
q.started = false
timer:set(q.timer)
sprite.direct(false)
return std.nop()
end
return false
end)
std.mod_start(function()
scr = sprite.new(theme.get 'scr.w', theme.get 'scr.h')
end)
quake = q
|
snowball fix
|
snowball fix
|
Lua
|
mit
|
gl00my/stead3
|
c8537c571725257ab200fd8f64ca74ae2eb4f966
|
module/util/groupids.lua
|
module/util/groupids.lua
|
--[[!
\file
\brief Es un módulo que permite crear grupos de ids y comprobar si una id
está en alguno de estos grupos. Los grupos pueden agruparse paara formar grupos
más complejos, con operadores de negación y or.
]]
loadModule("util/class");
loadModule("util/math/range");
loadModule("util/checkutils");
loadModule("util/stringutils");
--[[!
Esta clase representa un conjunto de IDs arbitrarias.
]]
groupIds = class();
--[[!
Inicializador.
@param ... Es un conjunto de rangos de ids e ids que compondrán al grupo
inicialmente.
@note Si se indican tablas como argumentos deberán ser instancias de la clase
range. Por el contrario, deben ser números.
]]
function groupIds:init(...)
self.ranges = {};
for _, ids in ipairs({...}) do
if type(ids) == "table" then
self:addRangeIds(ids);
else
self:addId(ids);
end;
end;
end;
--[[!
Convierte una cadena de caracteres en un grupo de IDs.
@param str Es la cadena de caracteres donde se especifican las IDs o bien rangos de IDs
separados por comas o por punto y coma
@param symbols Por defecto es una tabla vacía. Es una tabla con grupos de IDs. Los índices son símbolos representativos
de estos grupos (pueden especificarse en la cadena de caracteres a analizar y serán interpretados como el grupo de IDs que representan) y los
valores son los grupos de IDs.
\code
local group = groupIds.fromString("3, 4, 5,3,10,20,30, 70-80, -1);
\endcode
]]
function groupIds.fromString(str, symbols)
-- tokenizar la cadena de caracteres.
local tokens = {};
for token in wpairs(str, ",; ") do tokens[#tokens+1] = token; end;
local group = groupIds();
-- analizar cada token
for _, token in ipairs(tokens) do
if token:match("%d+-%d+") then
local lowerBound, upperBound = token:match("(%d+)-(%d+)");
lowerBound, upperBound = tonumber(lowerBound), tonumber(upperBound);
group:addRangeIds(range(lowerBound, upperBound));
elseif token:match("%d+") then
local id = tonumber(token:match("(%d+)"));
group:addId(id);
else
localizedAssert(symbols and symbols[token], "Failed to parse group IDs; " .. token .. " is not a valid ID our group of IDs", 2);
group = group + symbols[token];
end;
end;
return group;
end;
--[[!
Añade un rango de IDs al conjunto.
]]
function groupIds:addRangeIds(rangeIds)
if #self.ranges > 0 then
-- buscar el primer rango que interseccione con el nuevo rango.
local i = 1;
while (i < #self.ranges) and (not rangeIds:intersectsWith(self.ranges[i]:translate(1, 1))) do
i = i + 1;
end;
if rangeIds:intersectsWith(self.ranges[i]:translate(1, 1)) then
if i < #self.ranges then
-- buscar el primer rango después del rango i que no intersecciona
-- con el nuevo rango.
local j = i;
while ((j+1) < #self.ranges) and rangeIds:intersectsWith(self.ranges[j+1]:translate(1, 1)) do
j = j + 1;
end;
if not rangeIds:intersectsWith(self.ranges[j+1]:translate(1, 1)) then
-- Reemplazamos rangos desde el i+1ésimo hasta el jésimo por un
-- nuevo rango.
local aux = rangeIds:getWrapper(self.ranges[i]):getWrapper(self.ranges[j]);
for k=j,i+1,-1 do
table.remove(self.ranges, k);
end;
self.ranges[i] = aux;
else
-- no hay ningún rango después del rango iésimo que no
-- interseccione con el nuevo rango.
local aux = rangeIds:getWrapper(self.ranges[i]):getWrapper(self.ranges[j+1]);
-- eliminamos todos los rangos a partir del iesimo.
for k=j+1,i+1,-1 do
table.remove(self.ranges, k);
end;
-- insertamos el nuevo rango..
self.ranges[i] = aux;
end;
else
local aux = self.ranges[i];
self.ranges[i] = rangeIds:getWrapper(aux);
end;
else
-- no intersecciona con ningún rango, insertar el nuevo rango
-- después del rango cuyo límite superior es inferior al límite
-- inferior del nuevo rango...
-- buscar ese rango...
if #self.ranges > 1 then
i = 1;
while ((i+1) < #self.ranges) and (rangeIds:getUpperBound() > self.ranges[i+1]:getLowerBound()) do
i = i + 1;
end;
if rangeIds:getUpperBound() < self.ranges[i+1]:getLowerBound() then
table.insert(self.ranges, i, rangeIds);
else
table.insert(self.ranges, rangeIds);
end;
else
if rangeIds:getUpperBound() < self.ranges[1]:getLowerBound() then
table.insert(self.ranges, 1, rangeIds);
else
table.insert(self.ranges, rangeIds);
end;
end;
end;
else
table.insert(self.ranges, rangeIds);
end;
end;
--[[!
Añade una id al conjunto.
]]
function groupIds:addId(id)
self:addRangeIds(range(id, id));
end;
--[[!
@return Devuelve todas las IDs que pertenecen a este grupo en una tabla.
@note Las IDs están situadas en la tabla de forma creciente.
]]
function groupIds:getAllIds()
local aux = {};
for _,r in ipairs(self.ranges) do
for i=r:getLowerBound(),r:getUpperBound(),1 do
aux[#aux+1] = i;
end;
end;
return aux;
end;
--[[!
@return Devuelve un valor booleano indicando si una ID está en este conjunto
o no.
]]
function groupIds:isInside(x)
if #self.ranges > 0 then
if #self.ranges > 1 then
-- buscar el rango previo al rango cuyo límite inferior es
-- superior al valor.
if self.ranges[1]:getLowerBound() > x then
return false;
end;
local i = 1;
while ((i+1) < #self.ranges) and (x >= self.ranges[i+1]:getLowerBound()) do
i = i + 1;
end;
if x < self.ranges[i+1]:getLowerBound() then
return x <= self.ranges[i]:getUpperBound();
else
return x <= self.ranges[i+1]:getUpperBound();
end;
end;
return self.ranges[1]:isInside(x);
end;
return false;
end;
--[[!
@return Devuelve not self:isInside(x)
]]
function groupIds:isOutside(x)
return not self:isInside(x);
end;
--[[!
Es un alias de groupIds.isInside
]]
groupIds.has = groupIds.isInside;
--[[!
@return Devuelve un conjunto de IDs que contiene las IDs de dos conjuntos.
(Operación or)
]]
function groupIds.__add(a, b)
local aux = a:clone();
for _, range in ipairs(b.ranges) do
aux:addRangeIds(range);
end;
return aux;
end;
--[[!
@return Devuelve una representación en forma de cadena de caracteres
de este grupo.
]]
function groupIds.__tostring(g)
return "[" .. table.concat(g:getAllIds(), ",") .. "]";
end;
-- Es un grupo que no contiene ninguna ID
groupIds.empty = groupIds();
|
--[[!
\file
\brief Es un módulo que permite crear grupos de ids y comprobar si una id
está en alguno de estos grupos. Los grupos pueden agruparse paara formar grupos
más complejos, con operadores de negación y or.
]]
loadModule("util/class");
loadModule("util/math/range");
loadModule("util/checkutils");
loadModule("util/stringutils");
--[[!
Esta clase representa un conjunto de IDs arbitrarias.
]]
groupIds = class();
--[[!
Inicializador.
@param ... Es un conjunto de rangos de ids e ids que compondrán al grupo
inicialmente.
@note Si se indican tablas como argumentos deberán ser instancias de la clase
range. Por el contrario, deben ser números.
]]
function groupIds:init(...)
self.ranges = {};
for _, ids in ipairs({...}) do
if type(ids) == "table" then
self:addRangeIds(ids);
else
self:addId(ids);
end;
end;
end;
--[[!
Convierte una cadena de caracteres en un grupo de IDs.
@param str Es la cadena de caracteres donde se especifican las IDs o bien rangos de IDs
separados por comas o por punto y coma
@param symbols Por defecto es una tabla vacía. Es una tabla con grupos de IDs. Los índices son símbolos representativos
de estos grupos (pueden especificarse en la cadena de caracteres a analizar y serán interpretados como el grupo de IDs que representan) y los
valores son los grupos de IDs.
\code
local group = groupIds.fromString("3, 4, 5,3,10,20,30, 70-80, -1);
\endcode
]]
function groupIds.fromString(str, symbols)
-- tokenizar la cadena de caracteres.
local tokens = {};
for token in wpairs(str, ",; ") do tokens[#tokens+1] = token; end;
local group = groupIds();
-- analizar cada token
for _, token in ipairs(tokens) do
if token:match("%d+-%d+") then
local lowerBound, upperBound = token:match("(%d+)-(%d+)");
lowerBound, upperBound = tonumber(lowerBound), tonumber(upperBound);
group:addRangeIds(range(lowerBound, upperBound));
elseif token:match("%d+") then
local id = tonumber(token:match("(%d+)"));
group:addId(id);
else
localizedAssert(symbols and symbols[token], "Failed to parse group IDs; " .. token .. " is not a valid ID our group of IDs", 2);
group = group + symbols[token];
end;
end;
return group;
end;
--[[!
Añade un rango de IDs al conjunto.
]]
function groupIds:addRangeIds(rangeIds)
if #self.ranges > 0 then
-- buscar el primer rango que interseccione con el nuevo rango.
local i = 1;
while (i < #self.ranges) and (not rangeIds:intersectsWith(self.ranges[i]:translate(1, 1))) do
i = i + 1;
end;
if rangeIds:intersectsWith(self.ranges[i]:translate(1, 1)) then
if i < #self.ranges then
-- buscar el primer rango después del rango i que no intersecciona
-- con el nuevo rango.
local j = i;
while ((j+1) < #self.ranges) and rangeIds:intersectsWith(self.ranges[j+1]:translate(1, 1)) do
j = j + 1;
end;
if not rangeIds:intersectsWith(self.ranges[j+1]:translate(1, 1)) then
-- Reemplazamos rangos desde el i+1ésimo hasta el jésimo por un
-- nuevo rango.
local aux = rangeIds:getWrapper(self.ranges[i]):getWrapper(self.ranges[j]);
for k=j,i+1,-1 do
table.remove(self.ranges, k);
end;
self.ranges[i] = aux;
else
-- no hay ningún rango después del rango iésimo que no
-- interseccione con el nuevo rango.
local aux = rangeIds:getWrapper(self.ranges[i]):getWrapper(self.ranges[#self.ranges]);
-- eliminamos todos los rangos a partir del iesimo.
for k=j+1,i+1,-1 do
table.remove(self.ranges, k);
end;
-- insertamos el nuevo rango..
self.ranges[i] = aux;
end;
else
local aux = self.ranges[i];
self.ranges[i] = rangeIds:getWrapper(aux);
end;
else
-- no intersecciona con ningún rango, insertar el nuevo rango
-- después del rango cuyo límite superior es inferior al límite
-- inferior del nuevo rango...
-- buscar ese rango...
if #self.ranges > 1 then
if rangeIds:getUpperBound() < self.ranges[1]:getLowerBound() then
-- añadir al principio.
table.insert(self.ranges, 1, rangeIds);
else
i = 1;
while ((i+1) < #self.ranges) and (rangeIds:getUpperBound() > self.ranges[i+1]:getLowerBound()) do
i = i + 1;
end;
if rangeIds:getUpperBound() < self.ranges[i+1]:getLowerBound() then
table.insert(self.ranges, i+1, rangeIds);
else
table.insert(self.ranges, rangeIds);
end;
end;
else
if rangeIds:getUpperBound() < self.ranges[1]:getLowerBound() then
table.insert(self.ranges, 1, rangeIds);
else
table.insert(self.ranges, rangeIds);
end;
end;
end;
else
table.insert(self.ranges, rangeIds);
end;
end;
--[[!
Añade una id al conjunto.
]]
function groupIds:addId(id)
self:addRangeIds(range(id, id));
end;
--[[!
@return Devuelve todas las IDs que pertenecen a este grupo en una tabla.
@note Las IDs están situadas en la tabla de forma creciente.
]]
function groupIds:getAllIds()
local aux = {};
for _,r in ipairs(self.ranges) do
for i=r:getLowerBound(),r:getUpperBound(),1 do
aux[#aux+1] = i;
end;
end;
return aux;
end;
--[[!
@return Devuelve un valor booleano indicando si una ID está en este conjunto
o no.
]]
function groupIds:isInside(x)
if #self.ranges > 0 then
if #self.ranges > 1 then
-- buscar el rango previo al rango cuyo límite inferior es
-- superior al valor.
if self.ranges[1]:getLowerBound() > x then
return false;
end;
local i = 1;
while ((i+1) < #self.ranges) and (x >= self.ranges[i+1]:getLowerBound()) do
i = i + 1;
end;
if x < self.ranges[i+1]:getLowerBound() then
return x <= self.ranges[i]:getUpperBound();
else
return x <= self.ranges[i+1]:getUpperBound();
end;
end;
return self.ranges[1]:isInside(x);
end;
return false;
end;
--[[!
@return Devuelve not self:isInside(x)
]]
function groupIds:isOutside(x)
return not self:isInside(x);
end;
--[[!
Es un alias de groupIds.isInside
]]
groupIds.has = groupIds.isInside;
--[[!
@return Devuelve un conjunto de IDs que contiene las IDs de dos conjuntos.
(Operación or)
]]
function groupIds.__add(a, b)
local aux = a:clone();
for _, range in ipairs(b.ranges) do
aux:addRangeIds(range);
end;
return aux;
end;
--[[!
@return Devuelve una representación en forma de cadena de caracteres
de este grupo.
]]
function groupIds.__tostring(g)
return "[" .. table.concat(g:getAllIds(), ",") .. "]";
end;
-- Es un grupo que no contiene ninguna ID
groupIds.empty = groupIds();
|
Bugfix en el módulo util/groupids
|
Bugfix en el módulo util/groupids
|
Lua
|
mit
|
morfeo642/mta_plr_server
|
09b439e8d0bda87238ddf535832c97f0bf4af64a
|
prosody/mod_auth_wordpress.lua
|
prosody/mod_auth_wordpress.lua
|
-- Prosody Wordpress Authentication
local datamanager = require "util.datamanager";
local base64 = require "util.encodings".base64;
local md5 = require "util.hashes".md5;
local new_sasl = require "util.sasl".new;
local nodeprep = require "util.encodings".stringprep.nodeprep;
local log = require "util.logger".init("auth_wordpress");
local db = require 'luasql.mysql'
local hosts = hosts;
local mysql_server = module:get_option("wordpress_mysql_host") or "localhost";
local mysql_port = module:get_option("wordpress_mysql_port") or 3306;
local mysql_database = module:get_option("wordpress_mysql_database") or "wordpress";
local mysql_username = module:get_option("wordpress_mysql_username") or "root";
local mysql_password = module:get_option("wordpress_mysql_password") or "";
local mysql_prefix = module:get_option("wordpress_mysql_prefix") or "wp_";
local env = assert(db.mysql())
function new_wordpress_provider(host)
local provider = { name = "wordpress" };
log("debug", "initializing wordpress authentication provider for host '%s'", host);
function provider.test_password(username, password)
local pass = false;
local query = string.format("select user_pass from %susers where `user_login` = '%s'", mysql_prefix, username);
local connection = assert(env:connect(mysql_database, mysql_username, mysql_password, mysql_server, mysql_port));
local cursor = assert (connection:execute (query));
if cursor:numrows() > 0 then
user_pass = cursor:fetch();
md5_pass = md5(password, true);
pass = md5_pass == user_pass;
end
cursor:close();
connection:close();
if pass then
return true;
else
return nil, "Auth failed. Invalid username or password.";
end
end
function provider.get_password(username) return nil, "Password unavailable for Wordpress."; end
function provider.set_password(username, password) return nil, "Password unavailable for Wordpress."; end
function provider.create_user(username, password) return nil, "Account creation/modification not available with Wordpress."; end
function provider.user_exists(username)
log("debug", "Exists %s", username);
local pass = false;
local query = string.format("select id from %susers where `user_login` = '%s'", mysql_prefix, username);
local connection = assert(env:connect(mysql_database, mysql_username, mysql_password, mysql_server, mysql_port));
local cursor = assert (connection:execute (query));
if cursor:numrows() > 0 then
pass = true;
end
cursor:close();
connection:close();
if not pass then
log("debug", "Account not found for username '%s' at host '%s'", username, module.host);
return nil, "Auth failed. Invalid username";
end
return true;
end
function provider.get_sasl_handler()
local realm = module:get_option("sasl_realm") or module.host;
local realm = module:get_option("sasl_realm") or module.host;
local testpass_authentication_profile = {
plain_test = function(sasl, username, password, realm)
local prepped_username = nodeprep(username);
if not prepped_username then
log("debug", "NODEprep failed on username: %s", username);
return "", nil;
end
return provider.test_password(prepped_username, password), true;
end
};
return new_sasl(realm, testpass_authentication_profile);
end
return provider;
end
module:add_item("auth-provider", new_wordpress_provider(module.host));
|
-- Prosody Wordpress Authentication
local md5 = require "util.hashes".md5;
local new_sasl = require "util.sasl".new;
local nodeprep = require "util.encodings".stringprep.nodeprep;
local log = require "util.logger".init("auth_wordpress");
local DBI;
local connection;
local params = module:get_option("wordpress");
function new_wordpress_provider(host)
local provider = { name = "wordpress" };
log("debug", "initializing wordpress authentication provider for host '%s'", host);
function provider.test_password(username, password)
local pass = false;
local get_password_sql = string.format("select user_pass from `%susers` where `user_login` = ?;", params.prefix);
local stmt = connection:prepare(get_password_sql);
if stmt then
stmt:execute(username);
if stmt:rowcount() > 0 then
local row = stmt:fetch(true);
local user_pass = row.user_pass;
local md5_pass = md5(password, true);
pass = md5_pass == user_pass;
end
stmt:close();
end
if pass then
return true;
else
return nil, "Auth failed. Invalid username or password.";
end
end
function provider.get_password(username) return nil, "Password unavailable for Wordpress."; end
function provider.set_password(username, password) return nil, "Password unavailable for Wordpress."; end
function provider.create_user(username, password) return nil, "Account creation/modification not available with Wordpress."; end
function provider.user_exists(username)
log("debug", "Exists %s", username);
local pass = false;
local get_user_sql = string.format("select id from `%susers` where `user_login` = ?;", params.prefix);
local stmt = connection:prepare(get_user_sql);
if stmt then
stmt:execute(username);
if stmt:rowcount() > 0 then
pass = true;
end
stmt:close();
end
if not pass then
log("debug", "Account not found for username '%s' at host '%s'", username, module.host);
return nil, "Auth failed. Invalid username";
end
return true;
end
function provider.get_sasl_handler()
local realm = module:get_option("sasl_realm") or module.host;
local realm = module:get_option("sasl_realm") or module.host;
local testpass_authentication_profile = {
plain_test = function(sasl, username, password, realm)
local prepped_username = nodeprep(username);
if not prepped_username then
log("debug", "NODEprep failed on username: %s", username);
return "", nil;
end
return provider.test_password(prepped_username, password), true;
end
};
return new_sasl(realm, testpass_authentication_profile);
end
return provider;
end
-- database methods from mod_storage_sql.lua
local function test_connection()
if not connection then return nil; end
if connection:ping() then
return true;
else
module:log("debug", "Database connection closed");
connection = nil;
end
end
local function connect()
if not test_connection() then
prosody.unlock_globals();
local dbh, err = DBI.Connect(
"MySQL", params.database,
params.username, params.password,
params.host, params.port
);
prosody.lock_globals();
if not dbh then
module:log("debug", "Database connection failed: %s", tostring(err));
return nil, err;
end
module:log("debug", "Successfully connected to database");
dbh:autocommit(false); -- don't commit automatically
connection = dbh;
return connection;
end
end
do -- process options to get a db connection
local ok;
prosody.unlock_globals();
ok, DBI = pcall(require, "DBI");
if not ok then
package.loaded["DBI"] = {};
module:log("error", "Failed to load the LuaDBI library for accessing SQL databases: %s", DBI);
module:log("error", "More information on installing LuaDBI can be found at http://prosody.im/doc/depends#luadbi");
end
prosody.lock_globals();
if not ok or not DBI.Connect then
return; -- Halt loading of this module
end
params = params or {};
params.host = params.host or "localhost";
params.port = params.port or 3306;
params.database = params.database or "wordpress";
params.username = params.username or "root";
params.password = params.password or "";
params.prefix = params.prefix or "wp_";
assert(connect());
end
module:add_item("auth-provider", new_wordpress_provider(module.host));
|
Removed unuse variable and change database library to LuaDBI. fixes #4 fixes #3 fixes #1
|
Removed unuse variable and change database library to LuaDBI. fixes #4 fixes #3 fixes #1
|
Lua
|
mit
|
llun/wordpress-authenticator
|
6765359c156615f482612e3eb4b3655623c76a8c
|
convert.lua
|
convert.lua
|
-- modules that can be converted to nn seamlessly
local layer_list = {
'SpatialConvolution',
'SpatialCrossMapLRN',
'SpatialMaxPooling',
'SpatialAveragePooling',
'ReLU',
'Tanh',
'Sigmoid',
'SoftMax',
'LogSoftMax',
'VolumetricConvolution',
'VolumetricMaxPooling',
'VolumetricAveragePooling',
}
-- similar to nn.Module.apply
-- goes over a net and recursively replaces modules
-- using callback function
local function replace(self, callback)
local out = callback(self)
if self.modules then
for i, module in ipairs(self.modules) do
self.modules[i] = replace(module, callback)
end
end
return out
end
-- goes over a given net and converts all layers to dst backend
-- for example: net = cudnn.convert(net, cudnn)
function cudnn.convert(net, dst)
return replace(net, function(x)
local y = 0
local src = dst == nn and cudnn or nn
local src_prefix = src == nn and 'nn.' or 'cudnn.'
local dst_prefix = dst == nn and 'nn.' or 'cudnn.'
local function convert(v)
local y = {}
torch.setmetatable(y, dst_prefix..v)
if v == 'ReLU' then y = dst.ReLU() end -- because parameters
for k,u in pairs(x) do y[k] = u end
if src == cudnn and x.clearDesc then x:clearDesc() end
return y
end
local t = torch.typename(x)
if t == 'nn.SpatialConvolutionMM' then
y = convert('SpatialConvolution')
elseif t == 'inn.SpatialCrossResponseNormalization' then
y = convert('SpatialCrossMapLRN')
else
for i,v in ipairs(layer_list) do
if torch.typename(x) == src_prefix..v then
y = convert(v)
end
end
end
return y == 0 and x or y
end)
end
|
-- modules that can be converted to nn seamlessly
local layer_list = {
'SpatialConvolution',
'SpatialCrossMapLRN',
'SpatialMaxPooling',
'SpatialAveragePooling',
'ReLU',
'Tanh',
'Sigmoid',
'SoftMax',
'LogSoftMax',
'VolumetricConvolution',
'VolumetricMaxPooling',
'VolumetricAveragePooling',
}
-- similar to nn.Module.apply
-- goes over a net and recursively replaces modules
-- using callback function
local function replace(self, callback)
local out = callback(self)
if self.modules then
for i, module in ipairs(self.modules) do
self.modules[i] = replace(module, callback)
end
end
return out
end
-- goes over a given net and converts all layers to dst backend
-- for example: net = cudnn.convert(net, cudnn)
function cudnn.convert(net, dst)
return replace(net, function(x)
local y = 0
local src = dst == nn and cudnn or nn
local src_prefix = src == nn and 'nn.' or 'cudnn.'
local dst_prefix = dst == nn and 'nn.' or 'cudnn.'
local function convert(v)
local y = {}
torch.setmetatable(y, dst_prefix..v)
if v == 'ReLU' then y = dst.ReLU() end -- because parameters
for k,u in pairs(x) do y[k] = u end
if src == cudnn and x.clearDesc then x:clearDesc() end
if src == cudnn and v == 'SpatialAveragePooling' then y.divide = true end
return y
end
local t = torch.typename(x)
if t == 'nn.SpatialConvolutionMM' then
y = convert('SpatialConvolution')
elseif t == 'inn.SpatialCrossResponseNormalization' then
y = convert('SpatialCrossMapLRN')
else
for i,v in ipairs(layer_list) do
if torch.typename(x) == src_prefix..v then
y = convert(v)
end
end
end
return y == 0 and x or y
end)
end
|
fix cudnn -> nn avg-pooling conversion
|
fix cudnn -> nn avg-pooling conversion
|
Lua
|
bsd-3-clause
|
phunghx/phnn.torch,phunghx/phnn.torch,phunghx/phnn.torch
|
44b56f71bdb7813503261fbae599bbe6f8c61423
|
modules/luci-mod-admin-full/luasrc/model/cbi/admin_network/wifi_add.lua
|
modules/luci-mod-admin-full/luasrc/model/cbi/admin_network/wifi_add.lua
|
-- Copyright 2009 Jo-Philipp Wich <[email protected]>
-- Licensed to the public under the Apache License 2.0.
local fs = require "nixio.fs"
local nw = require "luci.model.network"
local fw = require "luci.model.firewall"
local uci = require "luci.model.uci".cursor()
local http = require "luci.http"
local iw = luci.sys.wifi.getiwinfo(http.formvalue("device"))
local has_firewall = fs.access("/etc/config/firewall")
if not iw then
luci.http.redirect(luci.dispatcher.build_url("admin/network/wireless"))
return
end
m = SimpleForm("network", translate("Joining Network: %q", http.formvalue("join")))
m.cancel = translate("Back to scan results")
m.reset = false
function m.on_cancel()
local dev = http.formvalue("device")
http.redirect(luci.dispatcher.build_url(
dev and "admin/network/wireless_join?device=" .. dev
or "admin/network/wireless"
))
end
nw.init(uci)
fw.init(uci)
m.hidden = {
device = http.formvalue("device"),
join = http.formvalue("join"),
channel = http.formvalue("channel"),
mode = http.formvalue("mode"),
bssid = http.formvalue("bssid"),
wep = http.formvalue("wep"),
wpa_suites = http.formvalue("wpa_suites"),
wpa_version = http.formvalue("wpa_version")
}
if iw and iw.mbssid_support then
replace = m:field(Flag, "replace", translate("Replace wireless configuration"),
translate("An additional network will be created if you leave this checked."))
function replace.cfgvalue() return "0" end
else
replace = m:field(DummyValue, "replace", translate("Replace wireless configuration"))
replace.default = translate("The hardware is not multi-SSID capable and the existing " ..
"configuration will be replaced if you proceed.")
function replace.formvalue() return "1" end
end
if http.formvalue("wep") == "1" then
key = m:field(Value, "key", translate("WEP passphrase"),
translate("Specify the secret encryption key here."))
key.password = true
key.datatype = "wepkey"
elseif (tonumber(m.hidden.wpa_version) or 0) > 0 and
(m.hidden.wpa_suites == "PSK" or m.hidden.wpa_suites == "PSK2")
then
key = m:field(Value, "key", translate("WPA passphrase"),
translate("Specify the secret encryption key here."))
key.password = true
key.datatype = "wpakey"
--m.hidden.wpa_suite = (tonumber(http.formvalue("wpa_version")) or 0) >= 2 and "psk2" or "psk"
end
newnet = m:field(Value, "_netname_new", translate("Name of the new network"),
translate("The allowed characters are: <code>A-Z</code>, <code>a-z</code>, " ..
"<code>0-9</code> and <code>_</code>"
))
newnet.default = m.hidden.mode == "Ad-Hoc" and "mesh" or "wwan"
newnet.datatype = "uciname"
if has_firewall then
fwzone = m:field(Value, "_fwzone",
translate("Create / Assign firewall-zone"),
translate("Choose the firewall zone you want to assign to this interface. Select <em>unspecified</em> to remove the interface from the associated zone or fill out the <em>create</em> field to define a new zone and attach the interface to it."))
fwzone.template = "cbi/firewall_zonelist"
fwzone.default = m.hidden.mode == "Ad-Hoc" and "mesh" or "wan"
end
function newnet.parse(self, section)
local net, zone
if has_firewall then
local zval = fwzone:formvalue(section)
zone = fw:get_zone(zval)
if not zone and zval == '-' then
zval = m:formvalue(fwzone:cbid(section) .. ".newzone")
if zval and #zval > 0 then
zone = fw:add_zone(zval)
end
end
end
local wdev = nw:get_wifidev(m.hidden.device)
wdev:set("disabled", false)
wdev:set("channel", m.hidden.channel)
if replace:formvalue(section) then
local n
for _, n in ipairs(wdev:get_wifinets()) do
wdev:del_wifinet(n)
end
end
local wconf = {
device = m.hidden.device,
ssid = m.hidden.join,
mode = (m.hidden.mode == "Ad-Hoc" and "adhoc" or "sta")
}
if m.hidden.wep == "1" then
wconf.encryption = "wep-open"
wconf.key = "1"
wconf.key1 = key and key:formvalue(section) or ""
elseif (tonumber(m.hidden.wpa_version) or 0) > 0 then
wconf.encryption = (tonumber(m.hidden.wpa_version) or 0) >= 2 and "psk2" or "psk"
wconf.key = key and key:formvalue(section) or ""
else
wconf.encryption = "none"
end
if wconf.mode == "adhoc" or wconf.mode == "sta" then
wconf.bssid = m.hidden.bssid
end
local value = self:formvalue(section)
net = nw:add_network(value, { proto = "dhcp" })
if not net then
self.error = { [section] = "missing" }
else
wconf.network = net:name()
local wnet = wdev:add_wifinet(wconf)
if wnet then
if zone then
fw:del_network(net:name())
zone:add_network(net:name())
end
uci:save("wireless")
uci:save("network")
uci:save("firewall")
luci.http.redirect(wnet:adminlink())
end
end
end
if has_firewall then
function fwzone.cfgvalue(self, section)
self.iface = section
local z = fw:get_zone_by_network(section)
return z and z:name()
end
end
return m
|
-- Copyright 2009 Jo-Philipp Wich <[email protected]>
-- Licensed to the public under the Apache License 2.0.
local fs = require "nixio.fs"
local nw = require "luci.model.network"
local fw = require "luci.model.firewall"
local uci = require "luci.model.uci".cursor()
local http = require "luci.http"
local iw = luci.sys.wifi.getiwinfo(http.formvalue("device"))
local has_firewall = fs.access("/etc/config/firewall")
if not iw then
luci.http.redirect(luci.dispatcher.build_url("admin/network/wireless"))
return
end
m = SimpleForm("network", translate("Joining Network: %q", http.formvalue("join")))
m.cancel = translate("Back to scan results")
m.reset = false
function m.on_cancel()
local dev = http.formvalue("device")
http.redirect(luci.dispatcher.build_url(
dev and "admin/network/wireless_join?device=" .. dev
or "admin/network/wireless"
))
end
nw.init(uci)
fw.init(uci)
m.hidden = {
device = http.formvalue("device"),
join = http.formvalue("join"),
channel = http.formvalue("channel"),
mode = http.formvalue("mode"),
bssid = http.formvalue("bssid"),
wep = http.formvalue("wep"),
wpa_suites = http.formvalue("wpa_suites"),
wpa_version = http.formvalue("wpa_version")
}
if iw and iw.mbssid_support then
replace = m:field(Flag, "replace", translate("Replace wireless configuration"),
translate("Check this option to delete the existing networks from this radio."))
function replace.cfgvalue() return "0" end
else
replace = m:field(DummyValue, "replace", translate("Replace wireless configuration"))
replace.default = translate("The hardware is not multi-SSID capable and the existing " ..
"configuration will be replaced if you proceed.")
function replace.formvalue() return "1" end
end
if http.formvalue("wep") == "1" then
key = m:field(Value, "key", translate("WEP passphrase"),
translate("Specify the secret encryption key here."))
key.password = true
key.datatype = "wepkey"
elseif (tonumber(m.hidden.wpa_version) or 0) > 0 and
(m.hidden.wpa_suites == "PSK" or m.hidden.wpa_suites == "PSK2")
then
key = m:field(Value, "key", translate("WPA passphrase"),
translate("Specify the secret encryption key here."))
key.password = true
key.datatype = "wpakey"
--m.hidden.wpa_suite = (tonumber(http.formvalue("wpa_version")) or 0) >= 2 and "psk2" or "psk"
end
newnet = m:field(Value, "_netname_new", translate("Name of the new network"),
translate("The allowed characters are: <code>A-Z</code>, <code>a-z</code>, " ..
"<code>0-9</code> and <code>_</code>"
))
newnet.default = m.hidden.mode == "Ad-Hoc" and "mesh" or "wwan"
newnet.datatype = "uciname"
if has_firewall then
fwzone = m:field(Value, "_fwzone",
translate("Create / Assign firewall-zone"),
translate("Choose the firewall zone you want to assign to this interface. Select <em>unspecified</em> to remove the interface from the associated zone or fill out the <em>create</em> field to define a new zone and attach the interface to it."))
fwzone.template = "cbi/firewall_zonelist"
fwzone.default = m.hidden.mode == "Ad-Hoc" and "mesh" or "wan"
end
function newnet.parse(self, section)
local net, zone
if has_firewall then
local zval = fwzone:formvalue(section)
zone = fw:get_zone(zval)
if not zone and zval == '-' then
zval = m:formvalue(fwzone:cbid(section) .. ".newzone")
if zval and #zval > 0 then
zone = fw:add_zone(zval)
end
end
end
local wdev = nw:get_wifidev(m.hidden.device)
wdev:set("disabled", false)
wdev:set("channel", m.hidden.channel)
if replace:formvalue(section) then
local n
for _, n in ipairs(wdev:get_wifinets()) do
wdev:del_wifinet(n)
end
end
local wconf = {
device = m.hidden.device,
ssid = m.hidden.join,
mode = (m.hidden.mode == "Ad-Hoc" and "adhoc" or "sta")
}
if m.hidden.wep == "1" then
wconf.encryption = "wep-open"
wconf.key = "1"
wconf.key1 = key and key:formvalue(section) or ""
elseif (tonumber(m.hidden.wpa_version) or 0) > 0 then
wconf.encryption = (tonumber(m.hidden.wpa_version) or 0) >= 2 and "psk2" or "psk"
wconf.key = key and key:formvalue(section) or ""
else
wconf.encryption = "none"
end
if wconf.mode == "adhoc" or wconf.mode == "sta" then
wconf.bssid = m.hidden.bssid
end
local value = self:formvalue(section)
net = nw:add_network(value, { proto = "dhcp" })
if not net then
self.error = { [section] = "missing" }
else
wconf.network = net:name()
local wnet = wdev:add_wifinet(wconf)
if wnet then
if zone then
fw:del_network(net:name())
zone:add_network(net:name())
end
uci:save("wireless")
uci:save("network")
uci:save("firewall")
luci.http.redirect(wnet:adminlink())
end
end
end
if has_firewall then
function fwzone.cfgvalue(self, section)
self.iface = section
local z = fw:get_zone_by_network(section)
return z and z:name()
end
end
return m
|
luci-mod-admin-full: fix help text for wifi join options
|
luci-mod-admin-full: fix help text for wifi join options
Clarify the help text in the wifi join dialog.
Reference to #793, #876, #897
Signed-off-by: Hannu Nyman <[email protected]>
|
Lua
|
apache-2.0
|
Wedmer/luci,cshore-firmware/openwrt-luci,tobiaswaldvogel/luci,Wedmer/luci,hnyman/luci,lbthomsen/openwrt-luci,LuttyYang/luci,artynet/luci,Noltari/luci,remakeelectric/luci,lbthomsen/openwrt-luci,oneru/luci,lbthomsen/openwrt-luci,wongsyrone/luci-1,981213/luci-1,openwrt-es/openwrt-luci,rogerpueyo/luci,taiha/luci,kuoruan/luci,chris5560/openwrt-luci,daofeng2015/luci,openwrt-es/openwrt-luci,openwrt-es/openwrt-luci,LuttyYang/luci,nmav/luci,Wedmer/luci,shangjiyu/luci-with-extra,kuoruan/lede-luci,lbthomsen/openwrt-luci,openwrt/luci,nmav/luci,wongsyrone/luci-1,rogerpueyo/luci,artynet/luci,rogerpueyo/luci,kuoruan/lede-luci,cshore/luci,Noltari/luci,LuttyYang/luci,cshore-firmware/openwrt-luci,hnyman/luci,cshore-firmware/openwrt-luci,daofeng2015/luci,wongsyrone/luci-1,chris5560/openwrt-luci,tobiaswaldvogel/luci,981213/luci-1,tobiaswaldvogel/luci,Noltari/luci,aa65535/luci,daofeng2015/luci,rogerpueyo/luci,shangjiyu/luci-with-extra,kuoruan/luci,Noltari/luci,wongsyrone/luci-1,aa65535/luci,cshore/luci,hnyman/luci,openwrt/luci,openwrt-es/openwrt-luci,Wedmer/luci,openwrt/luci,kuoruan/lede-luci,rogerpueyo/luci,kuoruan/lede-luci,openwrt-es/openwrt-luci,nmav/luci,lbthomsen/openwrt-luci,taiha/luci,oneru/luci,LuttyYang/luci,LuttyYang/luci,kuoruan/luci,nmav/luci,rogerpueyo/luci,openwrt/luci,cshore-firmware/openwrt-luci,cshore-firmware/openwrt-luci,wongsyrone/luci-1,aa65535/luci,LuttyYang/luci,tobiaswaldvogel/luci,chris5560/openwrt-luci,remakeelectric/luci,aa65535/luci,cshore/luci,981213/luci-1,Wedmer/luci,rogerpueyo/luci,Wedmer/luci,artynet/luci,artynet/luci,artynet/luci,nmav/luci,cshore-firmware/openwrt-luci,taiha/luci,oneru/luci,shangjiyu/luci-with-extra,hnyman/luci,981213/luci-1,wongsyrone/luci-1,rogerpueyo/luci,daofeng2015/luci,981213/luci-1,kuoruan/lede-luci,artynet/luci,cshore/luci,lbthomsen/openwrt-luci,taiha/luci,cshore/luci,Wedmer/luci,kuoruan/lede-luci,openwrt/luci,Noltari/luci,LuttyYang/luci,taiha/luci,cshore/luci,Wedmer/luci,taiha/luci,wongsyrone/luci-1,oneru/luci,hnyman/luci,nmav/luci,kuoruan/luci,hnyman/luci,openwrt-es/openwrt-luci,wongsyrone/luci-1,shangjiyu/luci-with-extra,aa65535/luci,daofeng2015/luci,kuoruan/luci,chris5560/openwrt-luci,openwrt-es/openwrt-luci,remakeelectric/luci,kuoruan/lede-luci,tobiaswaldvogel/luci,hnyman/luci,tobiaswaldvogel/luci,lbthomsen/openwrt-luci,daofeng2015/luci,remakeelectric/luci,kuoruan/lede-luci,openwrt/luci,Noltari/luci,shangjiyu/luci-with-extra,aa65535/luci,kuoruan/luci,chris5560/openwrt-luci,remakeelectric/luci,Noltari/luci,aa65535/luci,chris5560/openwrt-luci,981213/luci-1,LuttyYang/luci,taiha/luci,openwrt/luci,nmav/luci,shangjiyu/luci-with-extra,cshore/luci,tobiaswaldvogel/luci,openwrt-es/openwrt-luci,oneru/luci,artynet/luci,kuoruan/luci,oneru/luci,kuoruan/luci,remakeelectric/luci,981213/luci-1,nmav/luci,chris5560/openwrt-luci,daofeng2015/luci,taiha/luci,oneru/luci,oneru/luci,Noltari/luci,artynet/luci,shangjiyu/luci-with-extra,cshore-firmware/openwrt-luci,tobiaswaldvogel/luci,openwrt/luci,shangjiyu/luci-with-extra,remakeelectric/luci,chris5560/openwrt-luci,hnyman/luci,cshore-firmware/openwrt-luci,artynet/luci,Noltari/luci,lbthomsen/openwrt-luci,remakeelectric/luci,daofeng2015/luci,cshore/luci,aa65535/luci,nmav/luci
|
317b331f7b430337202463dd7c52a4e6fa29b8fd
|
LookupTable.lua
|
LookupTable.lua
|
local LookupTable, parent = torch.class('nn.LookupTable', 'nn.Module')
LookupTable.__version = 3
function LookupTable:__init(nIndex, ...)
parent.__init(self)
local arg = {...}
if select('#', ...) == 1 and type(arg[1]) ~= "number" then
local size = arg[1]
self.size = torch.LongStorage(#size + 1)
for i=1,#size do
self.size[i+1] = size[i]
end
else
self.size = torch.LongStorage(select('#', ...)+1)
for i=1,select('#',...) do
self.size[i+1] = arg[i]
end
end
self.size[1] = nIndex
batchSize = torch.LongTensor(#self.size + 1)
batchSize:narrow(1, 2,#self.size):copy(self.size)
batchSize[1] = 1
self.batchSize = batchSize:storage()
self.weight = torch.Tensor(self.size)
self.gradWeight = torch.Tensor(self.size):zero()
self.inputs = {}
self:reset()
end
function LookupTable:reset(stdv)
stdv = stdv or 1
if nn.oldSeed then
self.weight:apply(function()
return torch.normal(0, stdv)
end)
else
self.weight:normal(0, stdv)
end
end
function LookupTable:updateOutput(input)
if input:dim() == 1 then
local nIndex = input:size(1)
self.size[1] = nIndex
self.output:resize(self.size)
for i=1,nIndex do
self.output:select(1, i):copy(self.weight:select(1, input[i]))
end
elseif input:dim() == 2 then
local nExample = input:size(1)
local nIndex = input:size(2)
self.batchSize[1] = nExample
self.batchSize[2] = nIndex
self.output:resize(self.batchSize)
for i=1,nExample do
local output = self.output:select(1, i)
for j=1,nIndex do
output:select(1, j):copy(self.weight:select(1, input[j]))
end
end
end
return self.output
end
function LookupTable:zeroGradParameters()
for k,_ in pairs(self.inputs) do
self.gradWeight:select(1, k):zero()
end
self.inputs = {}
end
function LookupTable:accGradParameters(input, gradOutput, scale)
if input:dim() == 1 then
for i=1,input:size(1) do
local k = input[i]
self.inputs[k] = true
self.gradWeight:select(1, k):add(scale, gradOutput:select(1, i))
end
elseif input:dim() == 2 then
for i=1,input:size(1) do
local input = input:select(1, i)
local gradOutput = gradOutput:select(1, i)
for j=1,input:size(1) do
local k = input[j]
self.input[k] = true
self.gradWeight:select(1, k):add(scale, gradOutput:select(1, j))
end
end
end
end
function LookupTable:accUpdateGradParameters(input, gradOutput, lr)
if input:dim() == 1 then
for i=1,input:size(1) do
self.weight:select(1, input[i]):add(-lr, gradOutput:select(1, i))
end
elseif input:dim() == 2 then
for i=1,input:size(1) do
local input = input:select(1, i)
local gradOutput = gradOutput:select(1, i)
for j=1,input:size(2) do
self.weight:select(1, input[j]):add(-lr, gradOutput:select(1, j))
end
end
end
end
function LookupTable:updateParameters(learningRate)
for k,_ in pairs(self.inputs) do
self.weight:select(1, k):add(-learningRate, self.gradWeight:select(1, k))
end
end
-- we do not need to accumulate parameters when sharing
LookupTable.sharedAccUpdateGradParameters = LookupTable.accUpdateGradParameters
|
local LookupTable, parent = torch.class('nn.LookupTable', 'nn.Module')
LookupTable.__version = 3
function LookupTable:__init(nIndex, ...)
parent.__init(self)
local arg = {...}
if select('#', ...) == 1 and type(arg[1]) ~= "number" then
local size = arg[1]
self.size = torch.LongStorage(#size + 1)
for i=1,#size do
self.size[i+1] = size[i]
end
else
self.size = torch.LongStorage(select('#', ...)+1)
for i=1,select('#',...) do
self.size[i+1] = arg[i]
end
end
self.size[1] = nIndex
batchSize = torch.LongTensor(#self.size + 1)
batchSize:narrow(1, 2,#self.size):copy(self.size)
batchSize[1] = 1
self.batchSize = batchSize:storage()
-- set to true to scale updates inverse-proportionally to
-- number of times each index was used since last update.
-- less forward/backwards --> higher learning rate (because these are
-- downscaled proportionally to batch size using scale, in criterion,
-- or learning rate))
self.fairScale = false
-- when this is true, assumes that learningRate, scale or criterion
-- already scales the resulting update doing the equivalent of
-- dividing it by the number of examples in the batch.
self.batchScaled = true
self.weight = torch.Tensor(self.size)
self.gradWeight = torch.Tensor(self.size):zero()
self.inputs = {}
self:reset()
end
function LookupTable:reset(stdv)
stdv = stdv or 1
if nn.oldSeed then
self.weight:apply(function()
return torch.normal(0, stdv)
end)
else
self.weight:normal(0, stdv)
end
end
function LookupTable:updateOutput(input)
if input:dim() == 1 then
local nIndex = input:size(1)
self.size[1] = nIndex
self.output:resize(self.size)
for i=1,nIndex do
self.output:select(1, i):copy(self.weight:select(1, input[i]))
end
elseif input:dim() == 2 then
local nExample = input:size(1)
local nIndex = input:size(2)
self.batchSize[1] = nExample
self.batchSize[2] = nIndex
self.output:resize(self.batchSize)
for i=1,nExample do
local output = self.output:select(1, i)
for j=1,nIndex do
output:select(1, j):copy(self.weight:select(1, input[j]))
end
end
end
return self.output
end
function LookupTable:zeroGradParameters()
for k,_ in pairs(self.inputs) do
self.gradWeight:select(1, k):zero()
end
self.inputs = {}
self.nBackward = 0
end
function LookupTable:accGradParameters(input, gradOutput, scale)
if input:dim() == 1 then
self.nBackward = self.nBackward + 1
for i=1,input:size(1) do
local k = input[i]
self.inputs[k] = (self.inputs[k] or 0) + 1
self.gradWeight:select(1, k):add(scale, gradOutput:select(1, i))
end
elseif input:dim() == 2 then
self.nBackward = self.nBackward + input:size(1)
for i=1,input:size(1) do
local input = input:select(1, i)
local gradOutput = gradOutput:select(1, i)
for j=1,input:size(1) do
local k = input[j]
self.input[k] = (self.inputs[k] or 0) + 1
self.gradWeight:select(1, k):add(scale, gradOutput:select(1, j))
end
end
end
end
function LookupTable:accUpdateGradParameters(input, gradOutput, lr)
if input:dim() == 1 then
for i=1,input:size(1) do
self.weight:select(1, input[i]):add(-lr, gradOutput:select(1, i))
end
elseif input:dim() == 2 then
for i=1,input:size(1) do
local input = input:select(1, i)
local gradOutput = gradOutput:select(1, i)
for j=1,input:size(2) do
scale = self:getFairScale(nBackward)
self.weight:select(1, input[j]):add(-lr*scale, gradOutput:select(1, j))
end
end
end
end
function LookupTable:updateParameters(learningRate)
if not self.fairScale then
for k,_ in pairs(self.inputs) do
self.weight:select(1, k):add(-learningRate, self.gradWeight:select(1, k))
end
else
for k,nBackward in pairs(self.inputs) do
scale = self:getFairScale(nBackward)
self.weight:select(1, k):add(-learningRate*scale, self.gradWeight:select(1, k))
end
end
end
function LookupTable:getFairScale(nBackward)
local scale
if self.batchScaled then
scale = self.nBackward/nBackward
else
scale = 1/nBackward
end
return scale
end
-- we do not need to accumulate parameters when sharing
LookupTable.sharedAccUpdateGradParameters = LookupTable.accUpdateGradParameters
|
fixed indentation
|
fixed indentation
|
Lua
|
bsd-3-clause
|
adamlerer/nn,douwekiela/nn,hery/nn,noa/nn,jzbontar/nn,caldweln/nn,jhjin/nn,eriche2016/nn,davidBelanger/nn,abeschneider/nn,PierrotLC/nn,elbamos/nn,rotmanmi/nn,mys007/nn,sbodenstein/nn,Djabbz/nn,clementfarabet/nn,forty-2/nn,eulerreich/nn,hughperkins/nn,vgire/nn,soumith/nn,jonathantompson/nn,Moodstocks/nn,ivendrov/nn,aaiijmrtt/nn,colesbury/nn,mlosch/nn,joeyhng/nn,andreaskoepf/nn,xianjiec/nn,witgo/nn,Aysegul/nn,zchengquan/nn,diz-vara/nn,LinusU/nn,fmassa/nn,Jeffyrao/nn,GregSatre/nn,bartvm/nn,zhangxiangxiao/nn,EnjoyHacking/nn,lvdmaaten/nn,sagarwaghmare69/nn,nicholas-leonard/nn,ominux/nn,lukasc-ch/nn,boknilev/nn,PraveerSINGH/nn,kmul00/nn,karpathy/nn,szagoruyko/nn,rickyHong/nn_lib_torch,apaszke/nn
|
f87b80ada3b45861f0bcd6b3ff858e4d87b920f7
|
_Out/NFDataCfg/ScriptModule/NFScriptSystem.lua
|
_Out/NFDataCfg/ScriptModule/NFScriptSystem.lua
|
package.path = '../NFDataCfg/ScriptModule/?.lua;../NFDataCfg/ScriptModule/game/?.lua;../NFDataCfg/ScriptModule/world/?.lua;../NFDataCfg/ScriptModule/proxy/?.lua;../NFDataCfg/ScriptModule/master/?.lua;../NFDataCfg/ScriptModule/login/?.lua;'
require("NFScriptEnum");
script_module = nil;
function init_script_system(xLuaScriptModule)
script_module = xLuaScriptModule;
print("Hello Lua script_module");
local app_id = script_module:app_id();
local app_type = script_module:app_type();
if NF_SERVER_TYPES.NF_ST_GAME == app_type then
print("Hello NF_ST_GAME");
require("./game/script_list");
elseif NF_SERVER_TYPES.NF_ST_WORLD == app_type then
print("Hello NF_ST_WORLD");
elseif NF_SERVER_TYPES.NF_ST_PROXY == app_type then
print("Hello NF_ST_PROXY");
elseif NF_SERVER_TYPES.NF_ST_LOGIN == app_type then
print("Hello NF_ST_LOGIN");
elseif NF_SERVER_TYPES.NF_ST_MASTER == app_type then
print("Hello NF_ST_MASTER");
else
end
end
function load_script_file(fileList)
for i=1, #(fileList) do
if package.loaded[fileList[i].tblName] then
package.loaded[fileList[i].tblName] = nil
end
print("start to load " .. fileList[i].tblName);
local oldTbl =_G[fileList[i].tblName];
local object = require(fileList[i].tblName);
if true == object then
local newTbl =_G[fileList[i].tblName];
register_module(newTbl, fileList[i].tblName);
if oldTbl ~= nil then
print("reload_script_file " .. fileList[i].tblName .. " successed");
end
else
print("load_script_file " .. fileList[i].tblName .. " failed");
end
end
end
--[[
if you write code under the rule of NF, then you don't need these functions that show below,
but if you write code with free style and want to hot fix feature then you need these functions below.
function reload_script_file( tblName )
local old_module = _G[tblName]
package.loaded[tblName] = nil
local object = require(tblName);
if nil == object then
print(" reload_script_file " .. tblName .. " failed\n");
else
print(" reload_script_file " .. tblName .. " successed\n");
end
local new_module = _G[tblName]
for k, v in pairs(new_module) do
old_module[k] = v
end
end
function reload_script_table( nameList )
io.write("----Begin reload lua list----\n");
local ret = 0;
for i=1, #(nameList) do
ret = 1;
print("reload script : " .. tostring(nameList[i].tblName) .. "\n");
reload_script_file(nameList[i].tblName)
end
io.write("----End reload lua list----\n");
if ret == 1 then
for i=1, #(ScriptList) do
ScriptList[i].tbl.reload();
end
end
end
--]]
function register_module(tbl, name)
script_module:register_module(name, tbl);
if ScriptList then
for i=1, #(ScriptList) do
if ScriptList[i].tblName == name then
ScriptList[i].tbl = tbl;
io.write("----register_module ".. name .. " successed\n");
end
end
for i=1, #(ScriptList) do
if ScriptList[i].tbl ~= nil then
ScriptList[i].tbl.reload();
end
end
end
end
function find_module(name)
if ScriptList then
for i=1, #(ScriptList) do
if ScriptList[i].tblName == name then
return ScriptList[i].tbl;
end
end
end
end
---------------------------------------------
function module_awake(...)
for i=1, #(ScriptList) do
ScriptList[i].tbl:awake(...);
end
end
function module_init(...)
for i=1, #(ScriptList) do
ScriptList[i].tbl:init(...);
end
end
function module_after_init(...)
for i=1, #(ScriptList) do
ScriptList[i].tbl:after_init(...);
end
end
function module_ready_execute(...)
for i=1, #(ScriptList) do
ScriptList[i].tbl:ready_execute(...);
end
end
function module_before_shut(...)
for i=1, #(ScriptList) do
ScriptList[i].tbl:before_shut(...);
end
end
function module_shut(...)
for i=1, #(ScriptList) do
ScriptList[i].tbl:shut(...);
end
end
function print_table(table, level)
if table == nil then
print("the table is nil");
return;
end
local key = ""
level = level or 1
local indent = ""
for i = 1, level do
indent = indent.." "
end
if key ~= "" then
print(indent..key.." ".."=".." ".."{")
else
print(indent .. "{")
end
key = ""
for k,v in pairs(table) do
if type(v) == "table" then
key = k
print(indent .. key .. " =")
print_table(v, level + 1)
else
local content = string.format("%s%s = %s", indent .. " ",tostring(k), tostring(v))
print(content..";")
end
end
print(indent .. "}")
end
----------------------------------------------
|
package.path = '../NFDataCfg/ScriptModule/?.lua;../NFDataCfg/ScriptModule/game/?.lua;../NFDataCfg/ScriptModule/world/?.lua;../NFDataCfg/ScriptModule/proxy/?.lua;../NFDataCfg/ScriptModule/master/?.lua;../NFDataCfg/ScriptModule/login/?.lua;'
require("NFScriptEnum");
script_module = nil;
function init_script_system(xLuaScriptModule)
script_module = xLuaScriptModule;
print("Hello Lua script_module");
local app_id = script_module:app_id();
local app_type = script_module:app_type();
if NF_SERVER_TYPES.NF_ST_GAME == app_type then
print("Hello NF_ST_GAME");
require("./game/script_list");
elseif NF_SERVER_TYPES.NF_ST_WORLD == app_type then
print("Hello NF_ST_WORLD");
elseif NF_SERVER_TYPES.NF_ST_PROXY == app_type then
print("Hello NF_ST_PROXY");
elseif NF_SERVER_TYPES.NF_ST_LOGIN == app_type then
print("Hello NF_ST_LOGIN");
elseif NF_SERVER_TYPES.NF_ST_MASTER == app_type then
print("Hello NF_ST_MASTER");
else
end
end
function load_script_file(fileList)
for i=1, #(fileList) do
if package.loaded[fileList[i].tblName] then
package.loaded[fileList[i].tblName] = nil
end
print("start to load " .. fileList[i].tblName);
local oldTbl =_G[fileList[i].tblName];
local object = require(fileList[i].tblName);
if true == object then
local newTbl =_G[fileList[i].tblName];
register_module(newTbl, fileList[i].tblName);
if oldTbl ~= nil then
print("reload_script_file " .. fileList[i].tblName .. " successed");
end
else
print("load_script_file " .. fileList[i].tblName .. " failed");
end
end
end
--[[
if you write code under the rule of NF, then you don't need these functions that show below,
but if you write code with free style and want to hot fix feature then you need these functions below.
function reload_script_file( tblName )
local old_module = _G[tblName]
package.loaded[tblName] = nil
local object = require(tblName);
if nil == object then
print(" reload_script_file " .. tblName .. " failed\n");
else
print(" reload_script_file " .. tblName .. " successed\n");
end
local new_module = _G[tblName]
for k, v in pairs(new_module) do
old_module[k] = v
end
end
function reload_script_table( nameList )
io.write("----Begin reload lua list----\n");
local ret = 0;
for i=1, #(nameList) do
ret = 1;
print("reload script : " .. tostring(nameList[i].tblName) .. "\n");
reload_script_file(nameList[i].tblName)
end
io.write("----End reload lua list----\n");
if ret == 1 then
for i=1, #(ScriptList) do
ScriptList[i].tbl.reload();
end
end
end
--]]
function register_module(tbl, name)
script_module:register_module(name, tbl);
if ScriptList then
for i=1, #(ScriptList) do
if ScriptList[i].tblName == name then
ScriptList[i].tbl = tbl;
io.write("----register_module ".. name .. " successed\n");
end
end
for i=1, #(ScriptList) do
if ScriptList[i].tbl ~= nil then
ScriptList[i].tbl.reload();
end
end
end
end
function find_module(name)
if ScriptList then
for i=1, #(ScriptList) do
if ScriptList[i].tblName == name then
return ScriptList[i].tbl;
end
end
end
end
---------------------------------------------
function module_awake(...)
if ScriptList then
for i=1, #(ScriptList) do
ScriptList[i].tbl:awake(...);
end
end
end
function module_init(...)
if ScriptList then
for i=1, #(ScriptList) do
ScriptList[i].tbl:init(...);
end
end
end
function module_after_init(...)
if ScriptList then
for i=1, #(ScriptList) do
ScriptList[i].tbl:after_init(...);
end
end
end
function module_ready_execute(...)
if ScriptList then
for i=1, #(ScriptList) do
ScriptList[i].tbl:ready_execute(...);
end
end
end
function module_before_shut(...)
if ScriptList then
for i=1, #(ScriptList) do
ScriptList[i].tbl:before_shut(...);
end
end
end
function module_shut(...)
if ScriptList then
for i=1, #(ScriptList) do
ScriptList[i].tbl:shut(...);
end
end
end
function print_table(table, level)
if table == nil then
print("the table is nil");
return;
end
local key = ""
level = level or 1
local indent = ""
for i = 1, level do
indent = indent.." "
end
if key ~= "" then
print(indent..key.." ".."=".." ".."{")
else
print(indent .. "{")
end
key = ""
for k,v in pairs(table) do
if type(v) == "table" then
key = k
print(indent .. key .. " =")
print_table(v, level + 1)
else
local content = string.format("%s%s = %s", indent .. " ",tostring(k), tostring(v))
print(content..";")
end
end
print(indent .. "}")
end
----------------------------------------------
|
fix bugs
|
fix bugs
|
Lua
|
apache-2.0
|
ketoo/NoahGameFrame,ketoo/NoahGameFrame,zh423328/NoahGameFrame,zh423328/NoahGameFrame,ketoo/NoahGameFrame,ketoo/NoahGameFrame,ketoo/NoahGameFrame,zh423328/NoahGameFrame,zh423328/NoahGameFrame,ketoo/NoahGameFrame,ketoo/NoahGameFrame,zh423328/NoahGameFrame,zh423328/NoahGameFrame,zh423328/NoahGameFrame,zh423328/NoahGameFrame
|
82c489d5c2d6378ba7df964a0837d832f17a518c
|
kong/dao/schemas/upstreams.lua
|
kong/dao/schemas/upstreams.lua
|
local Errors = require "kong.dao.errors"
local utils = require "kong.tools.utils"
local DEFAULT_SLOTS = 100
local SLOTS_MIN, SLOTS_MAX = 10, 2^16
local SLOTS_MSG = "number of slots must be between " .. SLOTS_MIN .. " and " .. SLOTS_MAX
return {
table = "upstreams",
primary_key = {"id"},
fields = {
id = {
type = "id",
dao_insert_value = true,
required = true,
},
created_at = {
type = "timestamp",
immutable = true,
dao_insert_value = true,
required = true,
},
name = {
-- name is a hostname like name that can be referenced in an `upstream_url` field
type = "string",
unique = true,
required = true,
},
hash_on = {
-- primary hash-key
type = "string",
default = "none",
enum = {
"none",
"consumer",
"ip",
"header",
},
},
hash_fallback = {
-- secondary key, if primary fails
type = "string",
default = "none",
enum = {
"none",
"consumer",
"ip",
"header",
},
},
hash_on_header = {
-- header name, if `hash_on == "header"`
type = "string",
},
hash_fallback_header = {
-- header name, if `hash_fallback == "header"`
type = "string",
},
slots = {
-- the number of slots in the loadbalancer algorithm
type = "number",
default = DEFAULT_SLOTS,
},
},
self_check = function(schema, config, dao, is_updating)
-- check the name
local p = utils.normalize_ip(config.name)
if not p then
return false, Errors.schema("Invalid name; must be a valid hostname")
end
if p.type ~= "name" then
return false, Errors.schema("Invalid name; no ip addresses allowed")
end
if p.port then
return false, Errors.schema("Invalid name; no port allowed")
end
if config.hash_on_header then
local ok, err = utils.validate_header_name(config.hash_on_header)
if not ok then
return false, Errors.schema("Header: " .. err)
end
end
if config.hash_fallback_header then
local ok, err = utils.validate_header_name(config.hash_fallback_header)
if not ok then
return false, Errors.schema("Header: " .. err)
end
end
if (config.hash_on == "header"
and not config.hash_on_header) or
(config.hash_fallback == "header"
and not config.hash_fallback_header) then
return false, Errors.schema("Hashing on 'header', " ..
"but no header name provided")
end
if config.hash_on == "none" then
if config.hash_fallback ~= "none" then
return false, Errors.schema("Cannot set fallback if primary " ..
"'hash_on' is not set")
end
else
if config.hash_on == config.hash_fallback then
if config.hash_on ~= "header" then
return false, Errors.schema("Cannot set fallback and primary " ..
"hashes to the same value")
else
local upper_hash_on = config.hash_on_header:upper()
local upper_hash_fallback = config.hash_fallback_header:upper()
if upper_hash_on == upper_hash_fallback then
return false, Errors.schema("Cannot set fallback and primary "..
"hashes to the same value")
end
end
end
end
-- check the slots number
if config.slots < SLOTS_MIN or config.slots > SLOTS_MAX then
return false, Errors.schema(SLOTS_MSG)
end
return true
end,
}
|
local Errors = require "kong.dao.errors"
local utils = require "kong.tools.utils"
local DEFAULT_SLOTS = 100
local SLOTS_MIN, SLOTS_MAX = 10, 2^16
local SLOTS_MSG = "number of slots must be between " .. SLOTS_MIN .. " and " .. SLOTS_MAX
return {
table = "upstreams",
primary_key = {"id"},
fields = {
id = {
type = "id",
dao_insert_value = true,
required = true,
},
created_at = {
type = "timestamp",
immutable = true,
dao_insert_value = true,
required = true,
},
name = {
-- name is a hostname like name that can be referenced in an `upstream_url` field
type = "string",
unique = true,
required = true,
},
hash_on = {
-- primary hash-key
type = "string",
default = "none",
enum = {
"none",
"consumer",
"ip",
"header",
},
},
hash_fallback = {
-- secondary key, if primary fails
type = "string",
default = "none",
enum = {
"none",
"consumer",
"ip",
"header",
},
},
hash_on_header = {
-- header name, if `hash_on == "header"`
type = "string",
},
hash_fallback_header = {
-- header name, if `hash_fallback == "header"`
type = "string",
},
slots = {
-- the number of slots in the loadbalancer algorithm
type = "number",
default = DEFAULT_SLOTS,
},
},
self_check = function(schema, config, dao, is_updating)
-- check the name
if config.name then
local p = utils.normalize_ip(config.name)
if not p then
return false, Errors.schema("Invalid name; must be a valid hostname")
end
if p.type ~= "name" then
return false, Errors.schema("Invalid name; no ip addresses allowed")
end
if p.port then
return false, Errors.schema("Invalid name; no port allowed")
end
end
if config.hash_on_header then
local ok, err = utils.validate_header_name(config.hash_on_header)
if not ok then
return false, Errors.schema("Header: " .. err)
end
end
if config.hash_fallback_header then
local ok, err = utils.validate_header_name(config.hash_fallback_header)
if not ok then
return false, Errors.schema("Header: " .. err)
end
end
if (config.hash_on == "header"
and not config.hash_on_header) or
(config.hash_fallback == "header"
and not config.hash_fallback_header) then
return false, Errors.schema("Hashing on 'header', " ..
"but no header name provided")
end
if config.hash_on and config.hash_fallback then
if config.hash_on == "none" then
if config.hash_fallback ~= "none" then
return false, Errors.schema("Cannot set fallback if primary " ..
"'hash_on' is not set")
end
else
if config.hash_on == config.hash_fallback then
if config.hash_on ~= "header" then
return false, Errors.schema("Cannot set fallback and primary " ..
"hashes to the same value")
else
local upper_hash_on = config.hash_on_header:upper()
local upper_hash_fallback = config.hash_fallback_header:upper()
if upper_hash_on == upper_hash_fallback then
return false, Errors.schema("Cannot set fallback and primary "..
"hashes to the same value")
end
end
end
end
end
if config.slots then
-- check the slots number
if config.slots < SLOTS_MIN or config.slots > SLOTS_MAX then
return false, Errors.schema(SLOTS_MSG)
end
end
return true
end,
}
|
fix(dao) support self_check() on incomplete upstream objects
|
fix(dao) support self_check() on incomplete upstream objects
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong,jebenexer/kong,Mashape/kong
|
18d7fa7597fec82ac794500db4a3c02464d090b7
|
minetestforfun_game/mods/dye/init.lua
|
minetestforfun_game/mods/dye/init.lua
|
-- minetest/dye/init.lua
-- 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"}
-- 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
})
if name == "black" then
minetest.register_craft({
type = "shapeless",
output = item_name.." 4",
recipe = {"group:flower,color_"..name},
})
end
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", "light_grey"}
dyelocal.mixes = {
-- magenta, red, orange, brown, yellow, green, dark_green, cyan, blue, violet, black, dark_grey, grey, white, light_grey
white = {"pink", "pink", "orange", "orange", "yellow", "green", "green", "grey", "cyan", "violet", "grey", "grey", "light_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"},
}
minetest.after(1, function()
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
end)
|
-- minetest/dye/init.lua
-- 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"}
-- 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}, true},
{"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}, true},
{"blue", "Blue dye", {dye=1, basecolor_blue=1, excolor_blue=1, unicolor_blue=1}, true},
{"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}, true},
{"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}, true},
{"red", "Red dye", {dye=1, basecolor_red=1, excolor_red=1, unicolor_red=1}, true},
{"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 flower = row[4]
local item_name = "dye:"..name
local item_image = "dye_"..name..".png"
minetest.register_craftitem(item_name, {
inventory_image = item_image,
description = description,
groups = groups
})
if flower then
minetest.register_craft({
type = "shapeless",
output = item_name.." 4",
recipe = {"group:flower,color_"..name},
})
end
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", "light_grey"}
dyelocal.mixes = {
-- magenta, red, orange, brown, yellow, green, dark_green, cyan, blue, violet, black, dark_grey, grey, white, light_grey
white = {"pink", "pink", "orange", "orange", "yellow", "green", "green", "grey", "cyan", "violet", "grey", "grey", "light_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"},
}
minetest.after(1, function()
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
end)
|
Fix flowers to dyes crafts
|
Fix flowers to dyes crafts
|
Lua
|
unlicense
|
sys4-fr/server-minetestforfun,sys4-fr/server-minetestforfun,MinetestForFun/server-minetestforfun,crabman77/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Coethium/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Coethium/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,Coethium/server-minetestforfun,MinetestForFun/server-minetestforfun,Ombridride/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun
|
fade00e91f2a8db9723b85ddbfd4fc63fcdc0ff6
|
turbovisor.lua
|
turbovisor.lua
|
--- Turbo.lua Turbovisor, auto-reload of application on file changes.
--
-- Copyright 2013 John Abrahamsen, Deyuan Deng
--
-- 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 ffi = require "ffi"
local bit = require "bit"
local turbo = require "turbo"
local fs = require "turbo.fs"
--- Parsing arguments for turbovisor
-- @param arg All command line input. Note arg[0] is 'turbovisor', arg[1] is
-- application name; so user-defined argument starts from arg[2]
-- @return a table containing option/value pair, options including:
-- 'watch': set of files or directories to watch
-- 'ignore': set of files or directories that turbovisor shouldn't watch
local function get_param(arg)
local arg_opt
local arg_tbl = {}
for i = 2, #arg, 1 do
if arg[i] == '--watch' or arg[i] == '-w' then
arg_tbl.watch = {}
arg_opt = 'watch'
elseif arg[i] == '--ignore' or arg[i] == '-i' then
arg_tbl.ignore = {}
arg_opt = 'ignore'
else
if string.sub(arg[i], 1, 2) == "./" then
arg[i] = string.sub(arg[i], 3) -- pass './'
end
local files = fs.glob(arg[i])
-- insert glob expanded result into table
if files then
for _,v in ipairs(files) do
table.insert(arg_tbl[arg_opt], v)
end
end
end
end
-- Deal with default parameters
if arg_tbl.watch == nil then arg_tbl.watch = {'.'} end
return arg_tbl;
end
--- Kill all descendants for a given pid
local function kill_tree(pid)
local status = ffi.new("int[1]")
local cpids = io.popen('pgrep -P ' .. pid)
for cpid in cpids:lines() do
kill_tree(cpid)
ffi.C.kill(tonumber(cpid), 9)
ffi.C.waitpid(tonumber(cpid), status, 0)
assert(status[0] == 9 or bit.band(status[0], 0x7f) == 0,
"Child process " .. cpid .. " not killed.")
end
cpids:close()
end
--- The turbovisor class is a supervisor for detecting file changes
-- and restart supervised application.
local turbovisor = class("turbovisor", turbo.ioloop.IOLoop)
--- Start supervising.
function turbovisor:supervise()
-- Get command line parameters
self.arg_tbl = get_param(arg)
-- Create a new inotify
self.i_fd = turbo.inotify:new()
-- Create a buffer for reading event in callback handler
self.buf = ffi.gc(ffi.C.malloc(turbo.fs.PATH_MAX), ffi.C.free)
-- Initialize ioloop, add inotify handler
self:initialize()
self:add_handler(self.i_fd, turbo.ioloop.READ, self.restart, self)
-- Set watch on target file or directory
for i, target in pairs(self.arg_tbl.watch) do
if turbo.fs.is_dir(target) then
turbo.inotify:watch_all(target, self.arg_tbl.ignore)
else
turbo.inotify:watch_file(target)
end
end
-- Parameters for starting application
local para = ffi.new("const char *[?]", 3)
para[0] = "luajit"
para[1] = arg[1]
para[2] = nil
self.para = ffi.cast("char *const*", para)
-- Run application and supervisor
local cpid = ffi.C.fork()
if cpid == 0 then
turbo.inotify:close()
ffi.C.execvp("luajit", self.para)
error(ffi.string(ffi.C.strerror(ffi.errno())))
else
self:start()
end
end
--- Callback handler when files changed
-- For now, just restart the only one application
function turbovisor.restart(self, fd, events)
-- Read out event
ffi.C.read(fd, self.buf, turbo.fs.PATH_MAX);
self.buf = ffi.cast("struct inotify_event*", self.buf)
local full_path
if self.buf.len == 0 then -- 'len = 0' if we watch on file directly
full_path = turbo.inotify:get_watched_file(self.buf.wd)
else
local path = turbo.inotify:get_watched_file(self.buf.wd)
full_path = path .. '/' .. ffi.string(self.buf.name)
if path == '.' then full_path = ffi.string(self.buf.name) end
end
-- Simply return if we need to ignore the file
if turbo.util.is_in(full_path, self.arg_tbl.ignore) then
return
end
turbo.log.notice("[turbovisor.lua] File '" .. full_path ..
"' changed, application restarted!")
-- Restart application
kill_tree(ffi.C.getpid())
local cpid = ffi.C.fork()
if cpid == 0 then
turbo.inotify:close()
ffi.C.execvp("luajit", self.para)
error(ffi.string(ffi.C.strerror(ffi.errno())))
end
end
return turbovisor
|
--- Turbo.lua Turbovisor, auto-reload of application on file changes.
--
-- Copyright 2013 John Abrahamsen, Deyuan Deng
--
-- 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 ffi = require "ffi"
local bit = require "bit"
local turbo = require "turbo"
local fs = require "turbo.fs"
--- Parsing arguments for turbovisor
-- @param arg All command line input. Note arg[0] is 'turbovisor', arg[1] is
-- application name; so user-defined argument starts from arg[2]
-- @return a table containing option/value pair, options including:
-- 'watch': set of files or directories to watch
-- 'ignore': set of files or directories that turbovisor shouldn't watch
local function get_param(arg)
local arg_opt
local arg_tbl = {}
for i = 2, #arg, 1 do
if arg[i] == '--watch' or arg[i] == '-w' then
arg_tbl.watch = {}
arg_opt = 'watch'
elseif arg[i] == '--ignore' or arg[i] == '-i' then
arg_tbl.ignore = {}
arg_opt = 'ignore'
else
if string.sub(arg[i], 1, 2) == "./" then
arg[i] = string.sub(arg[i], 3) -- pass './'
end
local files = fs.glob(arg[i])
-- insert glob expanded result into table
if files then
for _,v in ipairs(files) do
table.insert(arg_tbl[arg_opt], v)
end
end
end
end
-- Deal with default parameters
if arg_tbl.watch == nil then arg_tbl.watch = {'.'} end
return arg_tbl;
end
--- Kill all descendants for a given pid
local function kill_tree(pid)
local status = ffi.new("int[1]")
local cpids = io.popen('pgrep -P ' .. pid)
for cpid in cpids:lines() do
kill_tree(cpid)
ffi.C.kill(tonumber(cpid), 9)
ffi.C.waitpid(tonumber(cpid), status, 0)
assert(status[0] == 9 or bit.band(status[0], 0x7f) == 0,
"Child process " .. cpid .. " not killed.")
end
cpids:close()
end
--- The turbovisor class is a supervisor for detecting file changes
-- and restart supervised application.
local turbovisor = class("turbovisor", turbo.ioloop.IOLoop)
--- Start supervising.
function turbovisor:supervise()
-- Get command line parameters
self.arg_tbl = get_param(arg)
-- Create a new inotify
self.i_fd = turbo.inotify:new()
-- Create a buffer for reading event in callback handler
self.buf = ffi.gc(ffi.C.malloc(turbo.fs.PATH_MAX), ffi.C.free)
-- Initialize ioloop, add inotify handler
self:initialize()
self:add_handler(self.i_fd, turbo.ioloop.READ, self.restart, self)
-- Set watch on target file or directory
for i, target in pairs(self.arg_tbl.watch) do
if turbo.fs.is_dir(target) then
turbo.inotify:watch_all(target, self.arg_tbl.ignore)
else
turbo.inotify:watch_file(target)
end
end
-- Parameters for starting application
local para = ffi.new("const char *[?]", 3)
para[0] = "luajit"
para[1] = arg[1]
para[2] = nil
self.para = ffi.cast("char *const*", para)
-- Run application and supervisor
local cpid = ffi.C.fork()
if cpid == 0 then
turbo.inotify:close()
ffi.C.execvp("luajit", self.para)
error(ffi.string(ffi.C.strerror(ffi.errno())))
else
self:start()
end
end
--- Callback handler when files changed
-- For now, just restart the only one application
function turbovisor.restart(self, fd, events)
-- Read out event
ffi.C.read(fd, self.buf, turbo.fs.PATH_MAX);
self.buf = ffi.cast("struct inotify_event*", self.buf)
local full_path
if self.buf.len == 0 then -- 'len = 0' if we watch on file directly
full_path = turbo.inotify:get_watched_file(self.buf.wd)
else
local path = turbo.inotify:get_watched_file(self.buf.wd)
full_path = path .. '/' .. ffi.string(self.buf.name)
if path == '.' then full_path = ffi.string(self.buf.name) end
end
turbo.inotify:rewatch_if_ignored(self.buf, full_path)
-- Simply return if we need to ignore the file
if turbo.util.is_in(full_path, self.arg_tbl.ignore) then
return
end
turbo.log.notice("[turbovisor.lua] File '" .. full_path ..
"' changed, application restarted!")
-- Restart application
kill_tree(ffi.C.getpid())
local cpid = ffi.C.fork()
if cpid == 0 then
turbo.inotify:close()
ffi.C.execvp("luajit", self.para)
error(ffi.string(ffi.C.strerror(ffi.errno())))
end
end
return turbovisor
|
turbovisor: Fix case where kernel might stop delivering inotify notifications
|
turbovisor: Fix case where kernel might stop delivering inotify notifications
Test case:
$ turbovisor api.lua -w somefile.lua
And the inotify modify event is only triggered once for somefile.lua and never
again.
Signed-off-by: Petr Štetiar <[email protected]>
|
Lua
|
apache-2.0
|
mniestroj/turbo,zcsteele/turbo,luastoned/turbo,YuanPeir-Chen/turbo-support-mipsel,YuanPeir-Chen/turbo-support-mipsel,zcsteele/turbo,kernelsauce/turbo,ddysher/turbo,luastoned/turbo,ddysher/turbo
|
e5f45dd994d191ccceba5409242fe4033cb2b2ed
|
kong/plugins/jwt/handler.lua
|
kong/plugins/jwt/handler.lua
|
local singletons = require "kong.singletons"
local BasePlugin = require "kong.plugins.base_plugin"
local responses = require "kong.tools.responses"
local constants = require "kong.constants"
local jwt_decoder = require "kong.plugins.jwt.jwt_parser"
local string_format = string.format
local ngx_re_gmatch = ngx.re.gmatch
local ngx_set_header = ngx.req.set_header
local get_method = ngx.req.get_method
local JwtHandler = BasePlugin:extend()
JwtHandler.PRIORITY = 1005
--- Retrieve a JWT in a request.
-- Checks for the JWT in URI parameters, then in the `Authorization` header.
-- @param request ngx request object
-- @param conf Plugin configuration
-- @return token JWT token contained in request (can be a table) or nil
-- @return err
local function retrieve_token(request, conf)
local uri_parameters = request.get_uri_args()
for _, v in ipairs(conf.uri_param_names) do
if uri_parameters[v] then
return uri_parameters[v]
end
end
local authorization_header
authorization_header = ngx.unescape_uri(ngx.var["cookie_authorization"])
if authorization_header == "" then
authorization_header = request.get_headers()["authorization"]
end
if authorization_header then
local iterator, iter_err = ngx_re_gmatch(authorization_header, "\\s*[Bb]earer\\s+(.+)")
if not iterator then
return nil, iter_err
end
local m, err = iterator()
if err then
return nil, err
end
if m and #m > 0 then
return m[1]
end
end
end
function JwtHandler:new()
JwtHandler.super.new(self, "jwt")
end
local function load_credential(jwt_secret_key)
local rows, err = singletons.dao.jwt_secrets:find_all {key = jwt_secret_key}
if err then
return nil, err
end
return rows[1]
end
local function load_consumer(consumer_id, anonymous)
local result, err = singletons.dao.consumers:find { id = consumer_id }
if not result then
if anonymous and not err then
err = 'anonymous consumer "' .. consumer_id .. '" not found'
end
return nil, err
end
return result
end
local function set_consumer(consumer, jwt_secret)
ngx_set_header(constants.HEADERS.CONSUMER_ID, consumer.id)
ngx_set_header(constants.HEADERS.CONSUMER_CUSTOM_ID, consumer.custom_id)
ngx_set_header(constants.HEADERS.CONSUMER_USERNAME, consumer.username)
ngx.ctx.authenticated_consumer = consumer
if jwt_secret then
ngx.ctx.authenticated_credential = jwt_secret
ngx_set_header(constants.HEADERS.ANONYMOUS, nil) -- in case of auth plugins concatenation
else
ngx_set_header(constants.HEADERS.ANONYMOUS, true)
end
end
local function do_authentication(conf)
local token, err = retrieve_token(ngx.req, conf)
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
end
local ttype = type(token)
if ttype ~= "string" then
if ttype == "nil" then
return false, {status = 401}
elseif ttype == "table" then
return false, {status = 401, message = "Multiple tokens provided"}
else
return false, {status = 401, message = "Unrecognizable token"}
end
end
-- Decode token to find out who the consumer is
local jwt, err = jwt_decoder:new(token)
if err then
return false, {status = 401, message = "Bad token; " .. tostring(err)}
end
local claims = jwt.claims
local jwt_secret_key = claims[conf.key_claim_name]
if not jwt_secret_key then
return false, {status = 401, message = "No mandatory '" .. conf.key_claim_name .. "' in claims"}
end
-- Retrieve the secret
local jwt_secret_cache_key = singletons.dao.jwt_secrets:cache_key(jwt_secret_key)
local jwt_secret, err = singletons.cache:get(jwt_secret_cache_key, nil,
load_credential, jwt_secret_key)
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
end
if not jwt_secret then
return false, {status = 403, message = "No credentials found for given '" .. conf.key_claim_name .. "'"}
end
local algorithm = jwt_secret.algorithm or "HS256"
-- Verify "alg"
if jwt.header.alg ~= algorithm then
return false, {status = 403, message = "Invalid algorithm"}
end
local jwt_secret_value = algorithm == "HS256" and jwt_secret.secret or jwt_secret.rsa_public_key
if conf.secret_is_base64 then
jwt_secret_value = jwt:b64_decode(jwt_secret_value)
end
if not jwt_secret_value then
return false, {status = 403, message = "Invalid key/secret"}
end
-- Now verify the JWT signature
if not jwt:verify_signature(jwt_secret_value) then
return false, {status = 403, message = "Invalid signature"}
end
-- Verify the JWT registered claims
local ok_claims, errors = jwt:verify_registered_claims(conf.claims_to_verify)
if not ok_claims then
return false, {status = 401, message = errors}
end
-- Retrieve the consumer
local consumer_cache_key = singletons.dao.consumers:cache_key(jwt_secret.consumer_id)
local consumer, err = singletons.cache:get(consumer_cache_key, nil,
load_consumer,
jwt_secret.consumer_id, true)
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
end
-- However this should not happen
if not consumer then
return false, {status = 403, message = string_format("Could not find consumer for '%s=%s'", conf.key_claim_name, jwt_secret_key)}
end
set_consumer(consumer, jwt_secret)
return true
end
function JwtHandler:access(conf)
JwtHandler.super.access(self)
-- check if preflight request and whether it should be authenticated
if conf.run_on_preflight == false and get_method() == "OPTIONS" then
-- FIXME: the above `== false` test is because existing entries in the db will
-- have `nil` and hence will by default start passing the preflight request
-- This should be fixed by a migration to update the actual entries
-- in the datastore
return
end
if ngx.ctx.authenticated_credential and conf.anonymous ~= "" then
-- we're already authenticated, and we're configured for using anonymous,
-- hence we're in a logical OR between auth methods and we're already done.
return
end
local ok, err = do_authentication(conf)
if not ok then
if conf.anonymous ~= "" then
-- get anonymous user
local consumer_cache_key = singletons.dao.consumers:cache_key(conf.anonymous)
local consumer, err = singletons.cache:get(consumer_cache_key, nil,
load_consumer,
conf.anonymous, true)
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
end
set_consumer(consumer, nil)
else
return responses.send(err.status, err.message)
end
end
end
return JwtHandler
|
local singletons = require "kong.singletons"
local BasePlugin = require "kong.plugins.base_plugin"
local responses = require "kong.tools.responses"
local constants = require "kong.constants"
local jwt_decoder = require "kong.plugins.jwt.jwt_parser"
local string_format = string.format
local ngx_re_gmatch = ngx.re.gmatch
local ngx_set_header = ngx.req.set_header
local get_method = ngx.req.get_method
local JwtHandler = BasePlugin:extend()
JwtHandler.PRIORITY = 1005
--- Retrieve a JWT in a request.
-- Checks for the JWT in URI parameters, then in the `Authorization` header.
-- @param request ngx request object
-- @param conf Plugin configuration
-- @return token JWT token contained in request (can be a table) or nil
-- @return err
local function retrieve_token(request, conf)
local uri_parameters = request.get_uri_args()
for _, v in ipairs(conf.uri_param_names) do
if uri_parameters[v] then
return uri_parameters[v]
end
end
local authorization_cookie
local authorization_header = ngx.unescape_uri(ngx.var["cookie_authorization"])
if authorization_header == "" then
authorization_cookie = request.get_headers()["authorization"]
end
if authorization_header then
local iterator, iter_err = ngx_re_gmatch(authorization_header, "\\s*[Bb]earer\\s+(.+)")
if not iterator then
return nil, iter_err
end
local m, err = iterator()
if err then
return nil, err
end
if m and #m > 0 then
return m[1]
end
elseif authorization_cookie then
return authorization_cookie
end
end
function JwtHandler:new()
JwtHandler.super.new(self, "jwt")
end
local function load_credential(jwt_secret_key)
local rows, err = singletons.dao.jwt_secrets:find_all {key = jwt_secret_key}
if err then
return nil, err
end
return rows[1]
end
local function load_consumer(consumer_id, anonymous)
local result, err = singletons.dao.consumers:find { id = consumer_id }
if not result then
if anonymous and not err then
err = 'anonymous consumer "' .. consumer_id .. '" not found'
end
return nil, err
end
return result
end
local function set_consumer(consumer, jwt_secret)
ngx_set_header(constants.HEADERS.CONSUMER_ID, consumer.id)
ngx_set_header(constants.HEADERS.CONSUMER_CUSTOM_ID, consumer.custom_id)
ngx_set_header(constants.HEADERS.CONSUMER_USERNAME, consumer.username)
ngx.ctx.authenticated_consumer = consumer
if jwt_secret then
ngx.ctx.authenticated_credential = jwt_secret
ngx_set_header(constants.HEADERS.ANONYMOUS, nil) -- in case of auth plugins concatenation
else
ngx_set_header(constants.HEADERS.ANONYMOUS, true)
end
end
local function do_authentication(conf)
local token, err = retrieve_token(ngx.req, conf)
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
end
local ttype = type(token)
if ttype ~= "string" then
if ttype == "nil" then
return false, {status = 401}
elseif ttype == "table" then
return false, {status = 401, message = "Multiple tokens provided"}
else
return false, {status = 401, message = "Unrecognizable token"}
end
end
-- Decode token to find out who the consumer is
local jwt, err = jwt_decoder:new(token)
if err then
return false, {status = 401, message = "Bad token; " .. tostring(err)}
end
local claims = jwt.claims
local jwt_secret_key = claims[conf.key_claim_name]
if not jwt_secret_key then
return false, {status = 401, message = "No mandatory '" .. conf.key_claim_name .. "' in claims"}
end
-- Retrieve the secret
local jwt_secret_cache_key = singletons.dao.jwt_secrets:cache_key(jwt_secret_key)
local jwt_secret, err = singletons.cache:get(jwt_secret_cache_key, nil,
load_credential, jwt_secret_key)
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
end
if not jwt_secret then
return false, {status = 403, message = "No credentials found for given '" .. conf.key_claim_name .. "'"}
end
local algorithm = jwt_secret.algorithm or "HS256"
-- Verify "alg"
if jwt.header.alg ~= algorithm then
return false, {status = 403, message = "Invalid algorithm"}
end
local jwt_secret_value = algorithm == "HS256" and jwt_secret.secret or jwt_secret.rsa_public_key
if conf.secret_is_base64 then
jwt_secret_value = jwt:b64_decode(jwt_secret_value)
end
if not jwt_secret_value then
return false, {status = 403, message = "Invalid key/secret"}
end
-- Now verify the JWT signature
if not jwt:verify_signature(jwt_secret_value) then
return false, {status = 403, message = "Invalid signature"}
end
-- Verify the JWT registered claims
local ok_claims, errors = jwt:verify_registered_claims(conf.claims_to_verify)
if not ok_claims then
return false, {status = 401, message = errors}
end
-- Retrieve the consumer
local consumer_cache_key = singletons.dao.consumers:cache_key(jwt_secret.consumer_id)
local consumer, err = singletons.cache:get(consumer_cache_key, nil,
load_consumer,
jwt_secret.consumer_id, true)
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
end
-- However this should not happen
if not consumer then
return false, {status = 403, message = string_format("Could not find consumer for '%s=%s'", conf.key_claim_name, jwt_secret_key)}
end
set_consumer(consumer, jwt_secret)
return true
end
function JwtHandler:access(conf)
JwtHandler.super.access(self)
-- check if preflight request and whether it should be authenticated
if conf.run_on_preflight == false and get_method() == "OPTIONS" then
-- FIXME: the above `== false` test is because existing entries in the db will
-- have `nil` and hence will by default start passing the preflight request
-- This should be fixed by a migration to update the actual entries
-- in the datastore
return
end
if ngx.ctx.authenticated_credential and conf.anonymous ~= "" then
-- we're already authenticated, and we're configured for using anonymous,
-- hence we're in a logical OR between auth methods and we're already done.
return
end
local ok, err = do_authentication(conf)
if not ok then
if conf.anonymous ~= "" then
-- get anonymous user
local consumer_cache_key = singletons.dao.consumers:cache_key(conf.anonymous)
local consumer, err = singletons.cache:get(consumer_cache_key, nil,
load_consumer,
conf.anonymous, true)
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
end
set_consumer(consumer, nil)
else
return responses.send(err.status, err.message)
end
end
end
return JwtHandler
|
remove the jwt 'bearer ' prefix from cookie
|
remove the jwt 'bearer ' prefix from cookie
|
Lua
|
apache-2.0
|
icyxp/kong
|
621b4840bc93b03f9321e5101ec9976f9325a215
|
util/debug.lua
|
util/debug.lua
|
-- Variables ending with these names will not
-- have their values printed ('password' includes
-- 'new_password', etc.)
local censored_names = {
password = true;
passwd = true;
pass = true;
pwd = true;
};
local optimal_line_length = 65;
local termcolours = require "util.termcolours";
local getstring = termcolours.getstring;
local styles;
do
_ = termcolours.getstyle;
styles = {
boundary_padding = _("bright");
filename = _("bright", "blue");
level_num = _("green");
funcname = _("yellow");
location = _("yellow");
};
end
module("debugx", package.seeall);
function get_locals_table(thread, level)
if not thread then
level = level + 1; -- Skip this function itself
end
local locals = {};
for local_num = 1, math.huge do
local name, value = debug.getlocal(thread, level, local_num);
if not name then break; end
table.insert(locals, { name = name, value = value });
end
return locals;
end
function get_upvalues_table(func)
local upvalues = {};
if func then
for upvalue_num = 1, math.huge do
local name, value = debug.getupvalue(func, upvalue_num);
if not name then break; end
table.insert(upvalues, { name = name, value = value });
end
end
return upvalues;
end
function string_from_var_table(var_table, max_line_len, indent_str)
local var_string = {};
local col_pos = 0;
max_line_len = max_line_len or math.huge;
indent_str = "\n"..(indent_str or "");
for _, var in ipairs(var_table) do
local name, value = var.name, var.value;
if name:sub(1,1) ~= "(" then
if type(value) == "string" then
if censored_names[name:match("%a+$")] then
value = "<hidden>";
else
value = ("%q"):format(value);
end
else
value = tostring(value);
end
if #value > max_line_len then
value = value:sub(1, max_line_len-3).."…";
end
local str = ("%s = %s"):format(name, tostring(value));
col_pos = col_pos + #str;
if col_pos > max_line_len then
table.insert(var_string, indent_str);
col_pos = 0;
end
table.insert(var_string, str);
end
end
if #var_string == 0 then
return nil;
else
return "{ "..table.concat(var_string, ", "):gsub(indent_str..", ", indent_str).." }";
end
end
function get_traceback_table(thread, start_level)
local levels = {};
for level = start_level, math.huge do
local info;
if thread then
info = debug.getinfo(thread, level);
else
info = debug.getinfo(level+1);
end
if not info then break; end
levels[(level-start_level)+1] = {
level = level;
info = info;
locals = get_locals_table(thread, level+(thread and 0 or 1));
upvalues = get_upvalues_table(info.func);
};
end
return levels;
end
function traceback(...)
local ok, ret = pcall(_traceback, ...);
if not ok then
return "Error in error handling: "..ret;
end
return ret;
end
local function build_source_boundary_marker(last_source_desc)
local padding = string.rep("-", math.floor(((optimal_line_length - 6) - #last_source_desc)/2));
return getstring(styles.boundary_padding, "v"..padding).." "..getstring(styles.filename, last_source_desc).." "..getstring(styles.boundary_padding, padding..(#last_source_desc%2==0 and "-v" or "v "));
end
function _traceback(thread, message, level)
-- Lua manual says: debug.traceback ([thread,] [message [, level]])
-- I fathom this to mean one of:
-- ()
-- (thread)
-- (message, level)
-- (thread, message, level)
if thread == nil then -- Defaults
thread, message, level = coroutine.running(), message, level;
elseif type(thread) == "string" then
thread, message, level = coroutine.running(), thread, message;
elseif type(thread) ~= "thread" then
return nil; -- debug.traceback() does this
end
level = level or 0;
message = message and (message.."\n") or "";
-- +3 counts for this function, and the pcall() and wrapper above us, the +1... I don't know.
local levels = get_traceback_table(thread, level+(thread == nil and 4 or 0));
local last_source_desc;
local lines = {};
for nlevel, level in ipairs(levels) do
local info = level.info;
local line = "...";
local func_type = info.namewhat.." ";
local source_desc = (info.short_src == "[C]" and "C code") or info.short_src or "Unknown";
if func_type == " " then func_type = ""; end;
if info.short_src == "[C]" then
line = "[ C ] "..func_type.."C function "..getstring(styles.location, (info.name and ("%q"):format(info.name) or "(unknown name)"));
elseif info.what == "main" then
line = "[Lua] "..getstring(styles.location, info.short_src.." line "..info.currentline);
else
local name = info.name or " ";
if name ~= " " then
name = ("%q"):format(name);
end
if func_type == "global " or func_type == "local " then
func_type = func_type.."function ";
end
line = "[Lua] "..getstring(styles.location, info.short_src.." line "..info.currentline).." in "..func_type..getstring(styles.funcname, name).." (defined on line "..info.linedefined..")";
end
if source_desc ~= last_source_desc then -- Venturing into a new source, add marker for previous
last_source_desc = source_desc;
table.insert(lines, "\t "..build_source_boundary_marker(last_source_desc));
end
nlevel = nlevel-1;
table.insert(lines, "\t"..(nlevel==0 and ">" or " ")..getstring(styles.level_num, "("..nlevel..") ")..line);
local npadding = (" "):rep(#tostring(nlevel));
if level.locals then
local locals_str = string_from_var_table(level.locals, optimal_line_length, "\t "..npadding);
if locals_str then
table.insert(lines, "\t "..npadding.."Locals: "..locals_str);
end
end
local upvalues_str = string_from_var_table(level.upvalues, optimal_line_length, "\t "..npadding);
if upvalues_str then
table.insert(lines, "\t "..npadding.."Upvals: "..upvalues_str);
end
end
-- table.insert(lines, "\t "..build_source_boundary_marker(last_source_desc));
return message.."stack traceback:\n"..table.concat(lines, "\n");
end
function use()
debug.traceback = traceback;
end
return _M;
|
-- Variables ending with these names will not
-- have their values printed ('password' includes
-- 'new_password', etc.)
local censored_names = {
password = true;
passwd = true;
pass = true;
pwd = true;
};
local optimal_line_length = 65;
local termcolours = require "util.termcolours";
local getstring = termcolours.getstring;
local styles;
do
_ = termcolours.getstyle;
styles = {
boundary_padding = _("bright");
filename = _("bright", "blue");
level_num = _("green");
funcname = _("yellow");
location = _("yellow");
};
end
module("debugx", package.seeall);
function get_locals_table(thread, level)
local locals = {};
for local_num = 1, math.huge do
local name, value;
if thread then
name, value = debug.getlocal(thread, level, local_num);
else
name, value = debug.getlocal(level+1, local_num);
end
if not name then break; end
table.insert(locals, { name = name, value = value });
end
return locals;
end
function get_upvalues_table(func)
local upvalues = {};
if func then
for upvalue_num = 1, math.huge do
local name, value = debug.getupvalue(func, upvalue_num);
if not name then break; end
table.insert(upvalues, { name = name, value = value });
end
end
return upvalues;
end
function string_from_var_table(var_table, max_line_len, indent_str)
local var_string = {};
local col_pos = 0;
max_line_len = max_line_len or math.huge;
indent_str = "\n"..(indent_str or "");
for _, var in ipairs(var_table) do
local name, value = var.name, var.value;
if name:sub(1,1) ~= "(" then
if type(value) == "string" then
if censored_names[name:match("%a+$")] then
value = "<hidden>";
else
value = ("%q"):format(value);
end
else
value = tostring(value);
end
if #value > max_line_len then
value = value:sub(1, max_line_len-3).."…";
end
local str = ("%s = %s"):format(name, tostring(value));
col_pos = col_pos + #str;
if col_pos > max_line_len then
table.insert(var_string, indent_str);
col_pos = 0;
end
table.insert(var_string, str);
end
end
if #var_string == 0 then
return nil;
else
return "{ "..table.concat(var_string, ", "):gsub(indent_str..", ", indent_str).." }";
end
end
function get_traceback_table(thread, start_level)
local levels = {};
for level = start_level, math.huge do
local info;
if thread then
info = debug.getinfo(thread, level);
else
info = debug.getinfo(level+1);
end
if not info then break; end
levels[(level-start_level)+1] = {
level = level;
info = info;
locals = get_locals_table(thread, level+(thread and 0 or 1));
upvalues = get_upvalues_table(info.func);
};
end
return levels;
end
function traceback(...)
local ok, ret = pcall(_traceback, ...);
if not ok then
return "Error in error handling: "..ret;
end
return ret;
end
local function build_source_boundary_marker(last_source_desc)
local padding = string.rep("-", math.floor(((optimal_line_length - 6) - #last_source_desc)/2));
return getstring(styles.boundary_padding, "v"..padding).." "..getstring(styles.filename, last_source_desc).." "..getstring(styles.boundary_padding, padding..(#last_source_desc%2==0 and "-v" or "v "));
end
function _traceback(thread, message, level)
-- Lua manual says: debug.traceback ([thread,] [message [, level]])
-- I fathom this to mean one of:
-- ()
-- (thread)
-- (message, level)
-- (thread, message, level)
if thread == nil then -- Defaults
thread, message, level = coroutine.running(), message, level;
elseif type(thread) == "string" then
thread, message, level = coroutine.running(), thread, message;
elseif type(thread) ~= "thread" then
return nil; -- debug.traceback() does this
end
level = level or 0;
message = message and (message.."\n") or "";
-- +3 counts for this function, and the pcall() and wrapper above us, the +1... I don't know.
local levels = get_traceback_table(thread, level+(thread == nil and 4 or 0));
local last_source_desc;
local lines = {};
for nlevel, level in ipairs(levels) do
local info = level.info;
local line = "...";
local func_type = info.namewhat.." ";
local source_desc = (info.short_src == "[C]" and "C code") or info.short_src or "Unknown";
if func_type == " " then func_type = ""; end;
if info.short_src == "[C]" then
line = "[ C ] "..func_type.."C function "..getstring(styles.location, (info.name and ("%q"):format(info.name) or "(unknown name)"));
elseif info.what == "main" then
line = "[Lua] "..getstring(styles.location, info.short_src.." line "..info.currentline);
else
local name = info.name or " ";
if name ~= " " then
name = ("%q"):format(name);
end
if func_type == "global " or func_type == "local " then
func_type = func_type.."function ";
end
line = "[Lua] "..getstring(styles.location, info.short_src.." line "..info.currentline).." in "..func_type..getstring(styles.funcname, name).." (defined on line "..info.linedefined..")";
end
if source_desc ~= last_source_desc then -- Venturing into a new source, add marker for previous
last_source_desc = source_desc;
table.insert(lines, "\t "..build_source_boundary_marker(last_source_desc));
end
nlevel = nlevel-1;
table.insert(lines, "\t"..(nlevel==0 and ">" or " ")..getstring(styles.level_num, "("..nlevel..") ")..line);
local npadding = (" "):rep(#tostring(nlevel));
if level.locals then
local locals_str = string_from_var_table(level.locals, optimal_line_length, "\t "..npadding);
if locals_str then
table.insert(lines, "\t "..npadding.."Locals: "..locals_str);
end
end
local upvalues_str = string_from_var_table(level.upvalues, optimal_line_length, "\t "..npadding);
if upvalues_str then
table.insert(lines, "\t "..npadding.."Upvals: "..upvalues_str);
end
end
-- table.insert(lines, "\t "..build_source_boundary_marker(last_source_desc));
return message.."stack traceback:\n"..table.concat(lines, "\n");
end
function use()
debug.traceback = traceback;
end
return _M;
|
util.debug: Fix level of locals when inspecting a coroutine
|
util.debug: Fix level of locals when inspecting a coroutine
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
4e29570511da781651ee20a33ccf0176f20e0210
|
test_scripts/Smoke/Resumption/ATF_Resumption_heartbeat_disconnect.lua
|
test_scripts/Smoke/Resumption/ATF_Resumption_heartbeat_disconnect.lua
|
-- Requirement summary:
-- [Data Resumption]: Data resumption on Unexpected Disconnect
--
-- Description:
-- Check that SDL perform resumption after heartbeat disconnect.
-- 1. Used precondition
-- In smartDeviceLink.ini file HeartBeatTimeout parameter is:
-- HeartBeatTimeout = 7000.
-- App is registerer and activated on HMI.
-- App has added 1 sub menu, 1 command and 1 choice set.
--
-- 2. Performed steps
-- Wait 20 seconds.
-- Register App with hashId.
--
-- Expected behavior:
-- 1. SDL sends OnAppUnregistered to HMI.
-- 2. App is registered and SDL resumes all App data, sends BC.ActivateApp to HMI, app gets FULL HMI level.
---------------------------------------------------------------------------------------------------
--[[ General Precondition before ATF start ]]
config.defaultProtocolVersion = 3
config.application1.registerAppInterfaceParams.isMediaApplication = true
-- [[ Required Shared Libraries ]]
local commonFunctions = require('user_modules/shared_testcases/commonFunctions')
local commonSteps = require('user_modules/shared_testcases/commonSteps')
local commonStepsResumption = require('user_modules/shared_testcases/commonStepsResumption')
local mobile_session = require('mobile_session')
--[[ General Settings for configuration ]]
Test = require('user_modules/dummy_connecttest')
require('cardinalities')
require('user_modules/AppTypes')
-- [[Local variables]]
local default_app_params = config.application1.registerAppInterfaceParams
-- [[Local functions]]
local function connectMobile(self)
self.mobileConnection:Connect()
return EXPECT_EVENT(events.connectedEvent, "Connected")
end
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
commonSteps:DeletePolicyTable()
commonSteps:DeleteLogsFiles()
function Test:StartSDL_With_One_Activated_App()
self:runSDL()
commonFunctions:waitForSDLStart(self):Do(function()
self:initHMI():Do(function()
commonFunctions:userPrint(35, "HMI initialized")
self:initHMI_onReady():Do(function ()
commonFunctions:userPrint(35, "HMI is ready")
connectMobile(self):Do(function ()
commonFunctions:userPrint(35, "Mobile Connected")
self:startSession():Do(function ()
commonFunctions:userPrint(35, "App is registered")
commonSteps:ActivateAppInSpecificLevel(self, self.applications[default_app_params.appName])
EXPECT_NOTIFICATION("OnHMIStatus", {hmiLevel = "FULL",audioStreamingState = "AUDIBLE", systemContext = "MAIN"})
commonFunctions:userPrint(35, "App is activated")
end)
end)
end)
end)
end)
end
function Test.AddCommand()
commonStepsResumption:AddCommand()
end
function Test.AddSubMenu()
commonStepsResumption:AddSubMenu()
end
function Test.AddChoiceSet()
commonStepsResumption:AddChoiceSet()
end
--[[ Test ]]
commonFunctions:newTestCasesGroup("Check that SDL perform resumption after heartbeat disconnect")
function Test:Wait_20_sec()
self.mobileSession:StopHeartbeat()
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppUnregistered", {appID = self.applications[default_app_params], unexpectedDisconnect = true })
:Timeout(20000)
EXPECT_EVENT(events.disconnectedEvent, "Disconnected")
:Do(function()
print("Disconnected!!!")
end)
:Timeout(20000)
end
function Test:Connect_Mobile()
connectMobile(self)
end
function Test:Register_And_Resume_App_And_Data()
local mobileSession = mobile_session.MobileSession(self, self.mobileConnection)
local on_rpc_service_started = mobileSession:StartRPC()
on_rpc_service_started:Do(function()
default_app_params.hashID = self.currentHashID
commonStepsResumption:Expect_Resumption_Data(default_app_params)
commonStepsResumption:RegisterApp(default_app_params, commonStepsResumption.ExpectResumeAppFULL, true)
end)
end
-- [[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postcondition")
function Test.Stop_SDL()
StopSDL()
end
return Test
|
-- Requirement summary:
-- [Data Resumption]: Data resumption on Unexpected Disconnect
--
-- Description:
-- Check that SDL perform resumption after heartbeat disconnect.
-- 1. Used precondition
-- In smartDeviceLink.ini file HeartBeatTimeout parameter is:
-- HeartBeatTimeout = 7000.
-- App is registerer and activated on HMI.
-- App has added 1 sub menu, 1 command and 1 choice set.
--
-- 2. Performed steps
-- Wait 20 seconds.
-- Register App with hashId.
--
-- Expected behavior:
-- 1. SDL sends OnAppUnregistered to HMI.
-- 2. App is registered and SDL resumes all App data, sends BC.ActivateApp to HMI, app gets FULL HMI level.
---------------------------------------------------------------------------------------------------
--[[ General Precondition before ATF start ]]
config.defaultProtocolVersion = 3
config.application1.registerAppInterfaceParams.isMediaApplication = true
-- [[ Required Shared Libraries ]]
local commonFunctions = require('user_modules/shared_testcases/commonFunctions')
local commonSteps = require('user_modules/shared_testcases/commonSteps')
local commonStepsResumption = require('user_modules/shared_testcases/commonStepsResumption')
local mobile_session = require('mobile_session')
--[[ General Settings for configuration ]]
Test = require('user_modules/dummy_connecttest')
require('cardinalities')
require('user_modules/AppTypes')
-- [[Local variables]]
local default_app_params = config.application1.registerAppInterfaceParams
-- [[Local functions]]
local function connectMobile(self)
self.mobileConnection:Connect()
return EXPECT_EVENT(events.connectedEvent, "Connected")
end
local function delayedExp(pTime, self)
local event = events.Event()
event.matches = function(e1, e2) return e1 == e2 end
EXPECT_HMIEVENT(event, "Delayed event")
:Timeout(pTime + 5000)
local function toRun()
event_dispatcher:RaiseEvent(self.hmiConnection, event)
end
RUN_AFTER(toRun, pTime)
end
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
commonSteps:DeletePolicyTable()
commonSteps:DeleteLogsFiles()
function Test:StartSDL_With_One_Activated_App()
self:runSDL()
commonFunctions:waitForSDLStart(self):Do(function()
self:initHMI():Do(function()
commonFunctions:userPrint(35, "HMI initialized")
self:initHMI_onReady():Do(function ()
commonFunctions:userPrint(35, "HMI is ready")
connectMobile(self):Do(function ()
commonFunctions:userPrint(35, "Mobile Connected")
self:startSession():Do(function ()
commonFunctions:userPrint(35, "App is registered")
commonSteps:ActivateAppInSpecificLevel(self, self.applications[default_app_params.appName])
EXPECT_NOTIFICATION("OnHMIStatus", {hmiLevel = "FULL",audioStreamingState = "AUDIBLE", systemContext = "MAIN"})
commonFunctions:userPrint(35, "App is activated")
end)
end)
end)
end)
end)
end
function Test.AddCommand()
commonStepsResumption:AddCommand()
end
function Test.AddSubMenu()
commonStepsResumption:AddSubMenu()
end
function Test.AddChoiceSet()
commonStepsResumption:AddChoiceSet()
end
--[[ Test ]]
commonFunctions:newTestCasesGroup("Check that SDL perform resumption after heartbeat disconnect")
function Test:Wait_20_sec()
self.mobileSession:StopHeartbeat()
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppUnregistered", {appID = self.applications[default_app_params], unexpectedDisconnect = true })
:Timeout(20000)
EXPECT_EVENT(events.disconnectedEvent, "Disconnected")
:Times(0)
delayedExp(20000, self)
end
function Test:Register_And_Resume_App_And_Data()
local mobileSession = mobile_session.MobileSession(self, self.mobileConnection)
local on_rpc_service_started = mobileSession:StartRPC()
on_rpc_service_started:Do(function()
default_app_params.hashID = self.currentHashID
commonStepsResumption:Expect_Resumption_Data(default_app_params)
commonStepsResumption:RegisterApp(default_app_params, commonStepsResumption.ExpectResumeAppFULL, true)
end)
end
-- [[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postcondition")
function Test.Stop_SDL()
StopSDL()
end
return Test
|
Fix test script due to issue 1893
|
Fix test script due to issue 1893
|
Lua
|
bsd-3-clause
|
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
|
9745755e0874aeed417590bed6cbca4cb5c27ccd
|
packages/lime-proto-bmx6/src/bmx6.lua
|
packages/lime-proto-bmx6/src/bmx6.lua
|
#!/usr/bin/lua
local network = require("lime.network")
local config = require("lime.config")
local fs = require("nixio.fs")
local libuci = require("uci")
bmx6 = {}
function bmx6.setup_interface(ifname, args)
local interface = network.limeIfNamePrefix..ifname.."_bmx6"
local owrtFullIfname = ifname
if args[2] then owrtFullIfname = owrtFullIfname..network.vlanSeparator..args[2] end
local uci = libuci:cursor()
uci:set("bmx6", interface, "dev")
uci:set("bmx6", interface, "dev", owrtFullIfname)
uci:save("bmx6")
uci:set("network", interface, "interface")
uci:set("network", interface, "ifname", owrtFullIfname)
uci:set("network", interface, "proto", "none")
uci:set("network", interface, "auto", "1")
uci:set("network", interface, "mtu", "1398")
uci:save("network")
end
function bmx6.clean()
print("Clearing bmx6 config...")
fs.writefile("/etc/config/bmx6", "")
end
function bmx6.configure(args)
bmx6.clean()
local ipv4, ipv6 = network.primary_address()
local uci = libuci:cursor()
uci:set("bmx6", "general", "bmx6")
uci:set("bmx6", "general", "dbgMuteTimeout", "1000000")
uci:set("bmx6", "main", "tunDev")
uci:set("bmx6", "main", "tunDev", "main")
uci:set("bmx6", "main", "tun4Address", ipv4:string())
uci:set("bmx6", "main", "tun6Address", ipv6:string())
-- Enable bmx6 uci config plugin
uci:set("bmx6", "config", "plugin")
uci:set("bmx6", "config", "plugin", "bmx6_config.so")
-- Enable JSON plugin to get bmx6 information in json format
uci:set("bmx6", "json", "plugin")
uci:set("bmx6", "json", "plugin", "bmx6_json.so")
-- Disable ThrowRules because they are broken in IPv6 with current Linux Kernel
uci:set("bmx6", "ipVersion", "ipVersion")
uci:set("bmx6", "ipVersion", "ipVersion", "6")
-- Search for networks in 172.16.0.0/12
uci:set("bmx6", "nodes", "tunOut")
uci:set("bmx6", "nodes", "tunOut", "nodes")
uci:set("bmx6", "nodes", "network", "172.16.0.0/12")
-- Search for networks in 10.0.0.0/8
uci:set("bmx6", "clouds", "tunOut")
uci:set("bmx6", "clouds", "tunOut", "clouds")
uci:set("bmx6", "clouds", "network", "10.0.0.0/8")
-- Search for internet in the mesh cloud
uci:set("bmx6", "inet4", "tunOut")
uci:set("bmx6", "inet4", "tunOut", "inet4")
uci:set("bmx6", "inet4", "network", "0.0.0.0/0")
uci:set("bmx6", "inet4", "maxPrefixLen", "0")
-- Search for internet IPv6 gateways in the mesh cloud
uci:set("bmx6", "inet6", "tunOut")
uci:set("bmx6", "inet6", "tunOut", "inet6")
uci:set("bmx6", "inet6", "network", "::/0")
uci:set("bmx6", "inet6", "maxPrefixLen", "0")
-- Search for other mesh cloud announcements that have public ipv6
uci:set("bmx6", "publicv6", "tunOut")
uci:set("bmx6", "publicv6", "tunOut", "publicv6")
uci:set("bmx6", "publicv6", "network", "2000::/3")
uci:set("bmx6", "publicv6", "maxPrefixLen", "64")
-- Announce local ipv4 cloud
uci:set("bmx6", "local4", "tunIn")
uci:set("bmx6", "local4", "tunIn", "local4")
uci:set("bmx6", "local4", "network", ipv4:network():string().."/"..ipv4:prefix())
-- Announce local ipv6 cloud
uci:set("bmx6", "local6", "tunIn")
uci:set("bmx6", "local6", "tunIn", "local6")
uci:set("bmx6", "local6", "network", ipv6:network():string().."/"..ipv6:prefix())
if config.get_bool("network", "bmx6_over_batman") then
for _,protoArgs in pairs(config.get("network", "protocols")) do
if(utils.split(protoArgs, network.protoParamsSeparator)[1] == "batadv") then bmx6.setup_interface("bat0", args) end
end
end
uci:save("bmx6")
-- BEGIN
-- Workaround to http://www.libre-mesh.org/issues/28
fs.writefile(
"/etc/lime-init.d/65-bmx6_dumb_workaround.start",
[[!/bin/sh
((sleep 45s && /etc/init.d/bmx6 restart))
]])
-- END
end
function bmx6.apply()
os.execute("killall bmx6 ; sleep 2 ; killall -9 bmx6")
os.execute("bmx6")
end
return bmx6
|
#!/usr/bin/lua
local network = require("lime.network")
local config = require("lime.config")
local fs = require("nixio.fs")
local libuci = require("uci")
bmx6 = {}
function bmx6.setup_interface(ifname, args)
local interface = network.limeIfNamePrefix..ifname.."_bmx6"
local owrtFullIfname = ifname
if args[2] then owrtFullIfname = owrtFullIfname..network.vlanSeparator..args[2] end
local uci = libuci:cursor()
uci:set("bmx6", interface, "dev")
uci:set("bmx6", interface, "dev", owrtFullIfname)
uci:save("bmx6")
-- This must go here because @ notation is not supported by bmx6 but is needed by netifd
if ifname:match("^wlan") then owrtFullIfname = "@lm_"..owrtFullIfname end
uci:set("network", interface, "interface")
uci:set("network", interface, "ifname", owrtFullIfname)
uci:set("network", interface, "proto", "none")
uci:set("network", interface, "auto", "1")
uci:set("network", interface, "mtu", "1398")
uci:save("network")
end
function bmx6.clean()
print("Clearing bmx6 config...")
fs.writefile("/etc/config/bmx6", "")
end
function bmx6.configure(args)
bmx6.clean()
local ipv4, ipv6 = network.primary_address()
local uci = libuci:cursor()
uci:set("bmx6", "general", "bmx6")
uci:set("bmx6", "general", "dbgMuteTimeout", "1000000")
uci:set("bmx6", "main", "tunDev")
uci:set("bmx6", "main", "tunDev", "main")
uci:set("bmx6", "main", "tun4Address", ipv4:string())
uci:set("bmx6", "main", "tun6Address", ipv6:string())
-- Enable bmx6 uci config plugin
uci:set("bmx6", "config", "plugin")
uci:set("bmx6", "config", "plugin", "bmx6_config.so")
-- Enable JSON plugin to get bmx6 information in json format
uci:set("bmx6", "json", "plugin")
uci:set("bmx6", "json", "plugin", "bmx6_json.so")
-- Disable ThrowRules because they are broken in IPv6 with current Linux Kernel
uci:set("bmx6", "ipVersion", "ipVersion")
uci:set("bmx6", "ipVersion", "ipVersion", "6")
-- Search for networks in 172.16.0.0/12
uci:set("bmx6", "nodes", "tunOut")
uci:set("bmx6", "nodes", "tunOut", "nodes")
uci:set("bmx6", "nodes", "network", "172.16.0.0/12")
-- Search for networks in 10.0.0.0/8
uci:set("bmx6", "clouds", "tunOut")
uci:set("bmx6", "clouds", "tunOut", "clouds")
uci:set("bmx6", "clouds", "network", "10.0.0.0/8")
-- Search for internet in the mesh cloud
uci:set("bmx6", "inet4", "tunOut")
uci:set("bmx6", "inet4", "tunOut", "inet4")
uci:set("bmx6", "inet4", "network", "0.0.0.0/0")
uci:set("bmx6", "inet4", "maxPrefixLen", "0")
-- Search for internet IPv6 gateways in the mesh cloud
uci:set("bmx6", "inet6", "tunOut")
uci:set("bmx6", "inet6", "tunOut", "inet6")
uci:set("bmx6", "inet6", "network", "::/0")
uci:set("bmx6", "inet6", "maxPrefixLen", "0")
-- Search for other mesh cloud announcements that have public ipv6
uci:set("bmx6", "publicv6", "tunOut")
uci:set("bmx6", "publicv6", "tunOut", "publicv6")
uci:set("bmx6", "publicv6", "network", "2000::/3")
uci:set("bmx6", "publicv6", "maxPrefixLen", "64")
-- Announce local ipv4 cloud
uci:set("bmx6", "local4", "tunIn")
uci:set("bmx6", "local4", "tunIn", "local4")
uci:set("bmx6", "local4", "network", ipv4:network():string().."/"..ipv4:prefix())
-- Announce local ipv6 cloud
uci:set("bmx6", "local6", "tunIn")
uci:set("bmx6", "local6", "tunIn", "local6")
uci:set("bmx6", "local6", "network", ipv6:network():string().."/"..ipv6:prefix())
if config.get_bool("network", "bmx6_over_batman") then
for _,protoArgs in pairs(config.get("network", "protocols")) do
if(utils.split(protoArgs, network.protoParamsSeparator)[1] == "batadv") then bmx6.setup_interface("bat0", args) end
end
end
uci:save("bmx6")
-- BEGIN
-- Workaround to http://www.libre-mesh.org/issues/28
fs.writefile(
"/etc/lime-init.d/65-bmx6_dumb_workaround.start",
[[!/bin/sh
((sleep 45s && /etc/init.d/bmx6 restart))
]])
-- END
end
function bmx6.apply()
os.execute("killall bmx6 ; sleep 2 ; killall -9 bmx6")
os.execute("bmx6")
end
return bmx6
|
fix missing @lm_ prefix for bmx interfaces
|
fix missing @lm_ prefix for bmx interfaces
|
Lua
|
agpl-3.0
|
libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages,p4u/lime-packages,p4u/lime-packages,p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages
|
be31b82f17134624df698089e23b2d5652f95df9
|
strictness.lua
|
strictness.lua
|
-- ================================================================
-- "strictness" tracks declaration and assignment of globals in Lua
-- Copyright (c) 2013 Roland Y., MIT License
-- v0.1.0 - compatible Lua 5.1, 5.2
-- ================================================================
local setmetatable = setmetatable
local getmetatable = getmetatable
local type = type
local assert = assert
local rawget = rawget
local rawset = rawset
local unpack = unpack
local error = error
-- ===================
-- Private helpers
-- ===================
-- Lua reserved keywords
local luaKeyword = {
['and'] = true, ['break'] = true, ['do'] = true,
['else'] = true, ['elseif'] = true, ['end'] = true ,
['false'] = true, ['for'] = true, ['function'] = true,
['if'] = true, ['in'] = true, ['local'] = true ,
['nil'] = true, ['not'] = true , ['or'] = true,
['repeat'] = true, ['return'] = true, ['then'] = true ,
['true'] = true , ['until'] = true , ['while'] = true,
}
-- Register for declared globals, defined as a table
-- with weak values.
local declared_globals = setmetatable({},{__mode = 'v'})
-- The global env _G metatable
local _G_mt
-- A custom error function
local function err(msg) return error(msg, 3) end
-- Custom argument type assertion helper
local function assert_type(var, expected_type, argn)
local var_type = type(var)
assert(var_type == expected_type,
('Bad argument #%d to global (%s expected, got %s)')
:format(argn or 1, expected_type, var_type))
end
-- Checks in the register if the given global was declared
local function is_declared(varname)
return declared_globals[varname]
end
-- Checks if the passed-in string can be a valid Lua identifier
local function is_valid_identifier(iden)
return iden:match('^[%a_]+[%w_]*$') and not luaKeyword[iden]
end
-- ==========================
-- Module functions
-- ==========================
-- Allows the declaration of passed in varnames
local function declare_global(...)
local vars = {...}
assert(#vars > 0,
'bad argument #1 to global (expected strings, got nil)')
for i,varname in ipairs({...}) do
assert_type(varname, 'string',i)
assert(is_valid_identifier(varname),
('bad argument #%d to global. %s is not a valid Lua identifier')
:format(i, varname))
declared_globals[varname] = true
end
end
-- Allows the given function to write globals
local function declare_global_func(f)
assert_type(f, 'function')
return function(...)
local old_index, old_newindex = _G_mt.__index, _G_mt.__newindex
_G_mt.__index, _G_mt.__newindex = nil, nil
local results = {f(...)}
_G_mt.__index, _G_mt.__newindex = old_index, old_newindex
return unpack(results)
end
end
-- ==========================
-- Locking the global env _G
-- ==========================
do
-- Catches the current env
local ENV = getfenv()
-- Preserves a possible existing metatable for the current env
_G_mt = getmetatable(ENV)
if not _G_mt then
_G_mt = {}
setmetatable(ENV,_G_mt)
end
-- Locks access to undeclared globals
_G_mt.__index = function(env, varname)
if not is_declared(varname) then
err(('Attempt to read undeclared global variable "%s"')
:format(varname))
end
return rawget(env, varname)
end
-- Locks assignment of undeclared globals
_G_mt.__newindex = function(env, varname, value)
if not is_declared(varname) then
err(('Attempt to assign undeclared global variable "%s"')
:format(varname))
end
rawset(env, varname, value)
end
rawset(ENV, 'global', declare_global)
rawset(ENV, 'globalize', declare_global_func)
end
|
-- ================================================================
-- "strictness" tracks declaration and assignment of globals in Lua
-- Copyright (c) 2013 Roland Y., MIT License
-- v0.1.0 - compatible Lua 5.1, 5.2
-- ================================================================
local setmetatable = setmetatable
local getmetatable = getmetatable
local type = type
local assert = assert
local rawget = rawget
local rawset = rawset
local unpack = unpack
local error = error
local getfenv = getfenv
-- ===================
-- Private helpers
-- ===================
-- Lua reserved keywords
local luaKeyword = {
['and'] = true, ['break'] = true, ['do'] = true,
['else'] = true, ['elseif'] = true, ['end'] = true ,
['false'] = true, ['for'] = true, ['function'] = true,
['if'] = true, ['in'] = true, ['local'] = true ,
['nil'] = true, ['not'] = true , ['or'] = true,
['repeat'] = true, ['return'] = true, ['then'] = true ,
['true'] = true , ['until'] = true , ['while'] = true,
}
-- Register for declared globals, defined as a table
-- with weak values.
local declared_globals = setmetatable({},{__mode = 'v'})
-- The global env _G metatable
local _G_mt
-- A custom error function
local function err(msg) return error(msg, 3) end
-- Custom argument type assertion helper
local function assert_type(var, expected_type, argn)
local var_type = type(var)
assert(var_type == expected_type,
('Bad argument #%d to global (%s expected, got %s)')
:format(argn or 1, expected_type, var_type))
end
-- Checks in the register if the given global was declared
local function is_declared(varname)
return declared_globals[varname]
end
-- Checks if the passed-in string can be a valid Lua identifier
local function is_valid_identifier(iden)
return iden:match('^[%a_]+[%w_]*$') and not luaKeyword[iden]
end
-- ==========================
-- Module functions
-- ==========================
-- Allows the declaration of passed in varnames
local function declare_global(...)
local vars = {...}
assert(#vars > 0,
'bad argument #1 to global (expected strings, got nil)')
for i,varname in ipairs({...}) do
assert_type(varname, 'string',i)
assert(is_valid_identifier(varname),
('bad argument #%d to global. %s is not a valid Lua identifier')
:format(i, varname))
declared_globals[varname] = true
end
end
-- Allows the given function to write globals
local function declare_global_func(f)
assert_type(f, 'function')
return function(...)
local old_index, old_newindex = _G_mt.__index, _G_mt.__newindex
_G_mt.__index, _G_mt.__newindex = nil, nil
local results = {f(...)}
_G_mt.__index, _G_mt.__newindex = old_index, old_newindex
return unpack(results)
end
end
-- ==========================
-- Locking the global env _G
-- ==========================
do
-- Catches the current env
local ENV = _VERSION:match('5.2') and _G or getfenv()
-- Preserves a possible existing metatable for the current env
_G_mt = getmetatable(ENV)
if not _G_mt then
_G_mt = {}
setmetatable(ENV,_G_mt)
end
-- Locks access to undeclared globals
_G_mt.__index = function(env, varname)
if not is_declared(varname) then
err(('Attempt to read undeclared global variable "%s"')
:format(varname))
end
return rawget(env, varname)
end
-- Locks assignment of undeclared globals
_G_mt.__newindex = function(env, varname, value)
if not is_declared(varname) then
err(('Attempt to assign undeclared global variable "%s"')
:format(varname))
end
rawset(env, varname, value)
end
rawset(ENV, 'global', declare_global)
rawset(ENV, 'globalize', declare_global_func)
end
|
Fixed Lua 5.2 getfenv compat
|
Fixed Lua 5.2 getfenv compat
|
Lua
|
mit
|
Yonaba/strictness
|
fd6654acea837372c18781047a9925de7ad02284
|
redis/change_track_order.lua
|
redis/change_track_order.lua
|
local room_id = ARGV[1]
local track_id = ARGV[2]
local destination_track_num = tonumber(ARGV[3])
local raw_track_order = redis.call('hgetall', 'room:' .. room_id .. ':track-order')
local function index_of(arr, item)
for i=1, #arr, 1 do
if arr[i] == item then
return i
end
end
end
local function get_track_num_from_id (id, track_order)
return tonumber(track_order[index_of(track_order, id)-1])
end
local track_num = get_track_num_from_id(track_id, raw_track_order)
if track_num > destination_track_num then
-- increment all from destination_track_num
for i=1, #raw_track_order-1, 2 do
local n = tonumber(raw_track_order[i])
if n <= track_num and n >= destination_track_num then
raw_track_order[i] = tostring(n+1)
end
end
else
-- decrement all from destination_track_num
for i=1, #raw_track_order-1, 2 do
local n = tonumber(raw_track_order[i])
if n >= track_num and n <= destination_track_num then
raw_track_order[i] = tostring(n-1)
end
end
end
-- set track_id to destination_track_num
raw_track_order[index_of(raw_track_order, track_id)-1] = tostring(destination_track_num)
redis.call('del', 'room:' .. room_id .. ':track-order')
for i=1, #raw_track_order-1, 2 do
local num = raw_track_order[i]
local id = raw_track_order[i+1]
redis.call('hset', 'room:' .. room_id .. ':track-order', num, id)
end
return "A"
|
local room_id = ARGV[1]
local track_id = ARGV[2]
local destination_track_num = tonumber(ARGV[3])
local raw_track_order = redis.call('hgetall', 'room:' .. room_id .. ':track-order')
local current_track_num = tonumber(redis.call('get', 'room:' .. room_id .. ':current-track'))
local function index_of(arr, item)
for i=1, #arr, 1 do
if arr[i] == item then
return i
end
end
end
local function get_track_num_from_id (id, track_order)
return tonumber(track_order[index_of(track_order, id)-1])
end
local track_num = get_track_num_from_id(track_id, raw_track_order)
if track_num > destination_track_num then
-- increment all from destination_track_num
for i=1, #raw_track_order-1, 2 do
local n = tonumber(raw_track_order[i])
if n <= track_num and n >= destination_track_num then
raw_track_order[i] = tostring(n+1)
if n == current_track_num then
redis.call('set', 'room:' .. room_id .. ':current-track', tostring(n+1))
end
end
end
else
-- decrement all from destination_track_num
for i=1, #raw_track_order-1, 2 do
local n = tonumber(raw_track_order[i])
if n >= track_num and n <= destination_track_num then
raw_track_order[i] = tostring(n-1)
if n == current_track_num then
redis.call('set', 'room:' .. room_id .. ':current-track', tostring(n-1))
end
end
end
end
-- set track_id to destination_track_num
raw_track_order[index_of(raw_track_order, track_id)-1] = tostring(destination_track_num)
redis.call('del', 'room:' .. room_id .. ':track-order')
for i=1, #raw_track_order-1, 2 do
local num = raw_track_order[i]
local id = raw_track_order[i+1]
redis.call('hset', 'room:' .. room_id .. ':track-order', num, id)
end
return "A"
|
fixed bug when current track num changes
|
fixed bug when current track num changes
|
Lua
|
agpl-3.0
|
vheuken/moomoo
|
598292ee8bc732527a09fdbaee9ede8599179b4d
|
src/luarocks/build/builtin.lua
|
src/luarocks/build/builtin.lua
|
--- A builtin build system: back-end to provide a portable way of building C-based Lua modules.
module("luarocks.build.builtin", package.seeall)
local fs = require("luarocks.fs")
local path = require("luarocks.path")
local util = require("luarocks.util")
local cfg = require("luarocks.cfg")
local dir = require("luarocks.dir")
--- Check if platform was detected
-- @param query string: The platform name to check.
-- @return boolean: true if LuaRocks is currently running on queried platform.
local function is_platform(query)
assert(type(query) == "string")
for _, platform in ipairs(cfg.platforms) do
if platform == query then
return true
end
end
end
--- Run a command displaying its execution on standard output.
-- @return boolean: true if command succeeds (status code 0), false
-- otherwise.
local function execute(...)
io.stdout:write(table.concat({...}, " ").."\n")
return fs.execute(...)
end
--- Driver function for the builtin build back-end.
-- @param rockspec table: the loaded rockspec.
-- @return boolean or (nil, string): true if no errors ocurred,
-- nil and an error message otherwise.
function run(rockspec)
assert(type(rockspec) == "table")
local compile_object, compile_library
local build = rockspec.build
local variables = rockspec.variables
local function add_flags(extras, flag, flags)
if flags then
if type(flags) ~= "table" then
flags = { tostring(flags) }
end
util.variable_substitutions(flags, variables)
for _, v in ipairs(flags) do
table.insert(extras, flag:format(v))
end
end
end
if is_platform("win32") then
compile_object = function(object, source, defines, incdirs)
local extras = {}
add_flags(extras, "-D%s", defines)
add_flags(extras, "-I%s", incdirs)
return execute(variables.CC.." "..variables.CFLAGS, "-c", "-Fo"..object, "-I"..variables.LUA_INCDIR, source, unpack(extras))
end
compile_library = function(library, objects, libraries, libdirs, name)
local extras = { unpack(objects) }
add_flags(extras, "-libpath:%s", libdirs)
add_flags(extras, "%s.lib", libraries)
local basename = dir.base_name(library):gsub(".[^.]*$", "")
local deffile = basename .. ".def"
local def = io.open(dir.path(fs.current_dir(), deffile), "w+")
def:write("EXPORTS\n")
def:write("luaopen_"..name:gsub("%.", "_").."\n")
def:close()
local ok = execute(variables.LD, "-dll", "-def:"..deffile, "-out:"..library, dir.path(variables.LUA_LIBDIR, "lua5.1.lib"), unpack(extras))
local manifestfile = basename..".dll.manifest"
if ok and fs.exists(manifestfile) then
ok = execute(variables.MT, "-manifest", manifestfile, "-outputresource:"..basename..".dll;2")
end
return ok
end
else
compile_object = function(object, source, defines, incdirs)
local extras = {}
add_flags(extras, "-D%s", defines)
add_flags(extras, "-I%s", incdirs)
return execute(variables.CC.." "..variables.CFLAGS, "-I"..variables.LUA_INCDIR, "-c", source, "-o", object, unpack(extras))
end
compile_library = function (library, objects, libraries, libdirs)
local extras = { unpack(objects) }
add_flags(extras, "-L%s", libdirs)
add_flags(extras, "-l%s", libraries)
if is_platform("cygwin") then
add_flags(extras, "-l%s", {"lua"})
end
return execute(variables.LD.." "..variables.LIBFLAG, "-o", library, "-L"..variables.LUA_LIBDIR, unpack(extras))
end
end
local ok = true
local built_modules = {}
local luadir = path.lua_dir(rockspec.name, rockspec.version)
local libdir = path.lib_dir(rockspec.name, rockspec.version)
local docdir = path.doc_dir(rockspec.name, rockspec.version)
for name, info in pairs(build.modules) do
local moddir = path.module_to_path(name)
if type(info) == "string" then
local ext = info:match(".([^.]+)$")
if ext == "lua" then
local dest = dir.path(luadir, moddir)
built_modules[info] = dest
else
info = {info}
end
end
if type(info) == "table" then
local objects = {}
local sources = info.sources
if info[1] then sources = info end
if type(sources) == "string" then sources = {sources} end
for _, source in ipairs(sources) do
local object = source:gsub(".[^.]*$", "."..cfg.obj_extension)
if not object then
object = source.."."..cfg.obj_extension
end
ok = compile_object(object, source, info.defines, info.incdirs)
if not ok then break end
table.insert(objects, object)
end
if not ok then break end
local module_name = dir.path(moddir, name:match("([^.]*)$").."."..cfg.lib_extension):gsub("//", "/")
if moddir ~= "" then
fs.make_dir(moddir)
end
local dest = dir.path(libdir, moddir)
built_modules[module_name] = dest
ok = compile_library(module_name, objects, info.libraries, info.libdirs, name)
if not ok then break end
end
end
for name, dest in pairs(built_modules) do
fs.make_dir(dest)
ok = fs.copy(name, dest)
if not ok then break end
end
if ok then
if fs.is_dir("lua") then
ok = fs.copy_contents("lua", luadir)
end
end
if ok then
return true
else
return nil, "Build error"
end
end
|
--- A builtin build system: back-end to provide a portable way of building C-based Lua modules.
module("luarocks.build.builtin", package.seeall)
local fs = require("luarocks.fs")
local path = require("luarocks.path")
local util = require("luarocks.util")
local cfg = require("luarocks.cfg")
local dir = require("luarocks.dir")
--- Check if platform was detected
-- @param query string: The platform name to check.
-- @return boolean: true if LuaRocks is currently running on queried platform.
local function is_platform(query)
assert(type(query) == "string")
for _, platform in ipairs(cfg.platforms) do
if platform == query then
return true
end
end
end
--- Run a command displaying its execution on standard output.
-- @return boolean: true if command succeeds (status code 0), false
-- otherwise.
local function execute(...)
io.stdout:write(table.concat({...}, " ").."\n")
return fs.execute(...)
end
--- Driver function for the builtin build back-end.
-- @param rockspec table: the loaded rockspec.
-- @return boolean or (nil, string): true if no errors ocurred,
-- nil and an error message otherwise.
function run(rockspec)
assert(type(rockspec) == "table")
local compile_object, compile_library
local build = rockspec.build
local variables = rockspec.variables
local function add_flags(extras, flag, flags)
if flags then
if type(flags) ~= "table" then
flags = { tostring(flags) }
end
util.variable_substitutions(flags, variables)
for _, v in ipairs(flags) do
table.insert(extras, flag:format(v))
end
end
end
if is_platform("win32") then
compile_object = function(object, source, defines, incdirs)
local extras = {}
add_flags(extras, "-D%s", defines)
add_flags(extras, "-I%s", incdirs)
return execute(variables.CC.." "..variables.CFLAGS, "-c", "-Fo"..object, "-I"..variables.LUA_INCDIR, source, unpack(extras))
end
compile_library = function(library, objects, libraries, libdirs, name)
local extras = { unpack(objects) }
add_flags(extras, "-libpath:%s", libdirs)
add_flags(extras, "%s.lib", libraries)
local basename = dir.base_name(library):gsub(".[^.]*$", "")
local deffile = basename .. ".def"
local def = io.open(dir.path(fs.current_dir(), deffile), "w+")
def:write("EXPORTS\n")
def:write("luaopen_"..name:gsub("%.", "_").."\n")
def:close()
local ok = execute(variables.LD, "-dll", "-def:"..deffile, "-out:"..library, dir.path(variables.LUA_LIBDIR, "lua5.1.lib"), unpack(extras))
local manifestfile = basename..".dll.manifest"
if ok and fs.exists(manifestfile) then
ok = execute(variables.MT, "-manifest", manifestfile, "-outputresource:"..basename..".dll;2")
end
return ok
end
else
compile_object = function(object, source, defines, incdirs)
local extras = {}
add_flags(extras, "-D%s", defines)
add_flags(extras, "-I%s", incdirs)
return execute(variables.CC.." "..variables.CFLAGS, "-I"..variables.LUA_INCDIR, "-c", source, "-o", object, unpack(extras))
end
compile_library = function (library, objects, libraries, libdirs)
local extras = { unpack(objects) }
add_flags(extras, "-L%s", libdirs)
add_flags(extras, "-l%s", libraries)
if is_platform("cygwin") then
add_flags(extras, "-l%s", {"lua"})
end
return execute(variables.LD.." "..variables.LIBFLAG, "-o", library, "-L"..variables.LUA_LIBDIR, unpack(extras))
end
end
local ok = true
local built_modules = {}
local luadir = path.lua_dir(rockspec.name, rockspec.version)
local libdir = path.lib_dir(rockspec.name, rockspec.version)
local docdir = path.doc_dir(rockspec.name, rockspec.version)
for name, info in pairs(build.modules) do
local moddir = path.module_to_path(name)
if type(info) == "string" then
local ext = info:match(".([^.]+)$")
if ext == "lua" then
if info:match("init.lua$") then
moddir = path.module_to_path(name..".init")
end
local dest = dir.path(luadir, moddir)
built_modules[info] = dest
else
info = {info}
end
end
if type(info) == "table" then
local objects = {}
local sources = info.sources
if info[1] then sources = info end
if type(sources) == "string" then sources = {sources} end
for _, source in ipairs(sources) do
local object = source:gsub(".[^.]*$", "."..cfg.obj_extension)
if not object then
object = source.."."..cfg.obj_extension
end
ok = compile_object(object, source, info.defines, info.incdirs)
if not ok then break end
table.insert(objects, object)
end
if not ok then break end
local module_name = dir.path(moddir, name:match("([^.]*)$").."."..cfg.lib_extension):gsub("//", "/")
if moddir ~= "" then
fs.make_dir(moddir)
end
local dest = dir.path(libdir, moddir)
built_modules[module_name] = dest
ok = compile_library(module_name, objects, info.libraries, info.libdirs, name)
if not ok then break end
end
end
for name, dest in pairs(built_modules) do
fs.make_dir(dest)
ok = fs.copy(name, dest)
if not ok then break end
end
if ok then
if fs.is_dir("lua") then
ok = fs.copy_contents("lua", luadir)
end
end
if ok then
return true
else
return nil, "Build error"
end
end
|
Fix installation of modules installed as init.lua files
|
Fix installation of modules installed as init.lua files
git-svn-id: b90ab2797f6146e3ba3e3d8b20782c4c2887e809@126 9ca3f7c1-7366-0410-b1a3-b5c78f85698c
|
Lua
|
mit
|
aryajur/luarocks,usstwxy/luarocks,starius/luarocks,keplerproject/luarocks,lxbgit/luarocks,rrthomas/luarocks,tst2005/luarocks,luarocks/luarocks,rrthomas/luarocks,ignacio/luarocks,lxbgit/luarocks,starius/luarocks,keplerproject/luarocks,xiaq/luarocks,xpol/luainstaller,xpol/luavm,usstwxy/luarocks,keplerproject/luarocks,xpol/luainstaller,lxbgit/luarocks,xpol/luarocks,xpol/luarocks,xpol/luavm,aryajur/luarocks,xpol/luarocks,usstwxy/luarocks,keplerproject/luarocks,xiaq/luarocks,robooo/luarocks,aryajur/luarocks,xpol/luavm,ignacio/luarocks,xpol/luainstaller,robooo/luarocks,rrthomas/luarocks,coderstudy/luarocks,xiaq/luarocks,luarocks/luarocks,leafo/luarocks,tst2005/luarocks,luarocks/luarocks,ignacio/luarocks,xiaq/luarocks,xpol/luarocks,coderstudy/luarocks,robooo/luarocks,ignacio/luarocks,robooo/luarocks,tst2005/luarocks,tarantool/luarocks,tst2005/luarocks,starius/luarocks,coderstudy/luarocks,xpol/luainstaller,starius/luarocks,rrthomas/luarocks,leafo/luarocks,tarantool/luarocks,usstwxy/luarocks,aryajur/luarocks,xpol/luavm,coderstudy/luarocks,xpol/luavm,tarantool/luarocks,leafo/luarocks,lxbgit/luarocks
|
baa750af6b88d840706743d1ee98a5d58037223d
|
plugins/lotteria.lua
|
plugins/lotteria.lua
|
local function estrai(t, chat_id, msg_id, n)
local hash = 'lotteria:' .. chat_id
local tab = { }
if n == false then
for k, v in pairs(t) do
table.insert(tab, v)
redis:hdel(hash, k)
end
if #tab > 0 then
reply_msg(msg_id, 'Ci sono ' .. #tab .. ' partecipanti.\nIl vincitore è... ' .. tab[math.random(#tab)] .. '!\nQuesta era l\'ultima estrazione :)', ok_cb, false)
else
reply_msg(msg.id, 'Non ci sono partecipanti o la biglietteria non è stata aperta.', ok_cb, false)
end
else
for k, v in pairs(t) do
table.insert(tab, v)
end
local rnd = math.random(#tab)
local i = 0
for k, v in pairs(t) do
i = i + 1
if i == rnd then
reply_msg(msg_id, 'Ci sono ' .. #tab .. ' partecipanti.\nIl vincitore è... ' .. v .. '!\nProseguiamo con la prossima estrazione :)', ok_cb, false)
redis:hdel(hash, k)
return
end
end
end
end
local function randomChoice(extra, success, result)
local user_data = serpent.block(database['users'][tostring(result[math.random(#result)].peer_id)], { sortkeys = false, comment = false })
if user_data then
send_large_msg('channel#id' .. extra.chat_id, 'ℹ️ ' .. user_data)
else
send_large_msg('channel#id' .. extra.chat_id, 'ℹ️ ' .. result[math.random(#result)].peer_id)
end
end
-- id 1078810985
local function run(msg, matches)
if msg.to.id == 1078810985 then
if matches[1]:lower() == 'estrazionerandom' then
if is_momod(msg) then
return channel_get_users(get_receiver(msg), randomChoice, { chat_id = msg.to.id })
else
return langs[msg.lang].require_mod
end
end
local n
local hash = 'lotteria:' .. msg.to.id
local hash2 = 'lotteria:' .. msg.to.id .. ':attiva'
if matches[1]:lower() == 'ticket' then
if redis:get(hash2) then
if redis:hget(hash, msg.from.id) then
reply_msg(msg.id, 'Hai già preso il biglietto!', ok_cb, false)
else
if msg.from.username then
redis:hset(hash, msg.from.id, '@' .. msg.from.username)
reply_msg(msg.id, 'Hai preso un biglietto!', ok_cb, false)
else
reply_msg(msg.id, 'Devi avere un username per partecipare alla lotteria! Vai in impostazioni e settalo.', ok_cb, false)
end
end
else
reply_msg(msg.id, 'La biglietteria è chiusa :(', ok_cb, false)
end
elseif matches[1]:lower() == 'startlotteria' then
if is_momod(msg) then
if redis:get(hash2) then
reply_msg(msg.id, 'La biglietteria è già aperta!', ok_cb, false)
else
redis:set(hash2, '1')
reply_msg(msg.id, 'La biglietteria è aperta, prendete un biglietto con /ticket :)', ok_cb, false)
end
else
return langs[msg.lang].require_mod
end
elseif matches[1]:lower() == 'stoplotteria' then
if is_momod(msg) then
if redis:get(hash2) then
redis:del(hash2)
reply_msg(msg.id, 'Ho chiuso la biglietteria!', ok_cb, false)
else
reply_msg(msg.id, 'La biglietteria è già chiusa!', ok_cb, false)
end
else
return langs[msg.lang].require_mod
end
elseif matches[1]:lower() == 'infolotteria' then
if is_momod(msg) then
local t = { }
for k, v in pairs(redis:hgetall(hash)) do
table.insert(t, v)
end
reply_msg(msg.id, 'Sono stati presi ' .. #t .. ' biglietti.', ok_cb, false)
else
return langs[msg.lang].require_mod
end
elseif matches[1]:lower() == 'estrazione' then
if is_momod(msg) then
if msg.text:match('%d$') then
n = true
else
n = false
end
if redis:get(hash2) then
redis:del(hash2)
estrai(redis:hgetall(hash), msg.to.id, msg.id, n)
else
estrai(redis:hgetall(hash), msg.to.id, msg.id, n)
end
else
return langs[msg.lang].require_mod
end
end
end
end
return {
description = "LOTTERIA",
patterns =
{
"^[#!/]([Tt][Ii][Cc][Kk][Ee][Tt])$",
"^[#!/]([Ss][Tt][Aa][Rr][Tt][Ll][Oo][Tt][Tt][Ee][Rr][Ii][Aa])$",
"^[#!/]([Ss][Tt][Oo][Pp][Ll][Oo][Tt][Tt][Ee][Rr][Ii][Aa])$",
"^[#!/]([Ii][Nn][Ff][Oo][Ll][Oo][Tt][Tt][Ee][Rr][Ii][Aa])$",
"^[#!/]([Ee][Ss][Tt][Rr][Aa][Zz][Ii][Oo][Nn][Ee][Rr][Aa][Nn][Dd][Oo][Mm])$",
"^[#!/]([Ee][Ss][Tt][Rr][Aa][Zz][Ii][Oo][Nn][Ee])%d*$",
},
run = run,
min_rank = 0,
syntax =
{
"USER",
"#ticket",
"MOD",
"#estrazionerandom",
"#startlotteria",
"#stoplotteria",
"#infolotteria",
"#estrazione<numero>",
},
}
|
local function estrai(t, chat_id, msg_id, n)
local hash = 'lotteria:' .. chat_id
local tab = { }
if n == false then
for k, v in pairs(t) do
table.insert(tab, v)
redis:hdel(hash, k)
end
if #tab > 0 then
reply_msg(msg_id, 'Ci sono ' .. #tab .. ' partecipanti.\nIl vincitore è... ' .. tab[math.random(#tab)] .. '!\nQuesta era l\'ultima estrazione :)', ok_cb, false)
else
reply_msg(msg.id, 'Non ci sono partecipanti o la biglietteria non è stata aperta.', ok_cb, false)
end
else
for k, v in pairs(t) do
table.insert(tab, v)
end
local rnd = math.random(#tab)
local i = 0
for k, v in pairs(t) do
i = i + 1
if i == rnd then
reply_msg(msg_id, 'Ci sono ' .. #tab .. ' partecipanti.\nIl vincitore è... ' .. v .. '!\nProseguiamo con la prossima estrazione :)', ok_cb, false)
redis:hdel(hash, k)
return
end
end
end
end
local function randomChoice(extra, success, result)
local id = result[math.random(#result)].peer_id
local user_data = serpent.block(database['users'][tostring(id)], { sortkeys = false, comment = false })
if user_data then
send_large_msg('channel#id' .. extra.chat_id, 'ℹ️ ' .. user_data.username .. ' ID: ' .. id)
else
send_large_msg('channel#id' .. extra.chat_id, 'ℹ️ ' .. id)
end
end
-- id 1078810985
local function run(msg, matches)
if msg.to.id == 1078810985 then
if matches[1]:lower() == 'estrazionerandom' then
if is_momod(msg) then
return channel_get_users(get_receiver(msg), randomChoice, { chat_id = msg.to.id })
else
return langs[msg.lang].require_mod
end
end
local n
local hash = 'lotteria:' .. msg.to.id
local hash2 = 'lotteria:' .. msg.to.id .. ':attiva'
if matches[1]:lower() == 'ticket' then
if redis:get(hash2) then
if redis:hget(hash, msg.from.id) then
reply_msg(msg.id, 'Hai già preso il biglietto!', ok_cb, false)
else
if msg.from.username then
redis:hset(hash, msg.from.id, '@' .. msg.from.username)
reply_msg(msg.id, 'Hai preso un biglietto!', ok_cb, false)
else
reply_msg(msg.id, 'Devi avere un username per partecipare alla lotteria! Vai in impostazioni e settalo.', ok_cb, false)
end
end
else
reply_msg(msg.id, 'La biglietteria è chiusa :(', ok_cb, false)
end
elseif matches[1]:lower() == 'startlotteria' then
if is_momod(msg) then
if redis:get(hash2) then
reply_msg(msg.id, 'La biglietteria è già aperta!', ok_cb, false)
else
redis:set(hash2, '1')
reply_msg(msg.id, 'La biglietteria è aperta, prendete un biglietto con /ticket :)', ok_cb, false)
end
else
return langs[msg.lang].require_mod
end
elseif matches[1]:lower() == 'stoplotteria' then
if is_momod(msg) then
if redis:get(hash2) then
redis:del(hash2)
reply_msg(msg.id, 'Ho chiuso la biglietteria!', ok_cb, false)
else
reply_msg(msg.id, 'La biglietteria è già chiusa!', ok_cb, false)
end
else
return langs[msg.lang].require_mod
end
elseif matches[1]:lower() == 'infolotteria' then
if is_momod(msg) then
local t = { }
for k, v in pairs(redis:hgetall(hash)) do
table.insert(t, v)
end
reply_msg(msg.id, 'Sono stati presi ' .. #t .. ' biglietti.', ok_cb, false)
else
return langs[msg.lang].require_mod
end
elseif matches[1]:lower() == 'estrazione' then
if is_momod(msg) then
if msg.text:match('%d$') then
n = true
else
n = false
end
if redis:get(hash2) then
redis:del(hash2)
estrai(redis:hgetall(hash), msg.to.id, msg.id, n)
else
estrai(redis:hgetall(hash), msg.to.id, msg.id, n)
end
else
return langs[msg.lang].require_mod
end
end
end
end
return {
description = "LOTTERIA",
patterns =
{
"^[#!/]([Tt][Ii][Cc][Kk][Ee][Tt])$",
"^[#!/]([Ss][Tt][Aa][Rr][Tt][Ll][Oo][Tt][Tt][Ee][Rr][Ii][Aa])$",
"^[#!/]([Ss][Tt][Oo][Pp][Ll][Oo][Tt][Tt][Ee][Rr][Ii][Aa])$",
"^[#!/]([Ii][Nn][Ff][Oo][Ll][Oo][Tt][Tt][Ee][Rr][Ii][Aa])$",
"^[#!/]([Ee][Ss][Tt][Rr][Aa][Zz][Ii][Oo][Nn][Ee][Rr][Aa][Nn][Dd][Oo][Mm])$",
"^[#!/]([Ee][Ss][Tt][Rr][Aa][Zz][Ii][Oo][Nn][Ee])%d*$",
},
run = run,
min_rank = 0,
syntax =
{
"USER",
"#ticket",
"MOD",
"#estrazionerandom",
"#startlotteria",
"#stoplotteria",
"#infolotteria",
"#estrazione<numero>",
},
}
|
fix adhoc
|
fix adhoc
|
Lua
|
agpl-3.0
|
xsolinsx/AISasha
|
21eab960d7fb51c4b48aa8b9bba53c85e422cde1
|
agents/monitoring/default/protocol/request.lua
|
agents/monitoring/default/protocol/request.lua
|
--[[
Copyright 2012 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local table = require('table')
local https = require('https')
local fs = require('fs')
local logging = require('logging')
local errors = require('../errors')
local Error = require('core').Error
local misc = require('../util/misc')
local fmt = require('string').format
local Object = require('core').Object
local exports = {}
local Request = Object:extend()
--[[
Attempts to upload or download a file over https to options.host:options.port OR
for endpoints in options.endpoints. Will try options.attempts number of times, or
for each endpoint if not specified.
options = {
host/port OR endpoints [{Endpoint1, Endpoint2, ...}]
path = "string",
method = "METHOD"
upload = nil or '/some/path'
download = nil or '/some/path'
attempts = int or #endpoints
}
]]--
local function makeRequest(...)
local req = Request:new(...)
req:set_headers()
req:request()
return req
end
function Request:initialize(options, callback)
self.callback = misc.fireOnce(callback)
if not options.method then
return self.callback(Error:new('I need a http method'))
end
if options.endpoints then
self.endpoints = misc.merge({}, options.endpoints)
else
self.endpoints = {{host=options.host, port=options.port}}
end
self.attempts = options.attempts or #self.endpoints
self.download = options.download
self.upload = options.upload
options.endpoints = nil
options.attempts = nil
options.download = nil
options.upload = nil
self.options = options
if not self:_cycle_endpoint() then
return self.callback(Error:new('call with options.port and options.host or options.endpoints'))
end
end
function Request:request()
logging.debugf('sending request to %s:%s', self.options.host, self.options.port)
local options = misc.merge({}, self.options)
local req = https.request(options, function(res)
self:_handle_response(res)
end)
req:on('error', function(err)
self:_ensure_retries(err)
end)
if not self.upload then
return req:done()
end
local data = fs.createReadStream(self.upload)
data:on('data', function(chunk)
req:write(chunk)
end)
data:on('end', function(d)
req:done(d)
end)
data:on('error', function(err)
req:done()
self._ensure_retries(err)
end)
end
function Request:_cycle_endpoint()
local position, endpoint
while self.attempts > 0 do
position = #self.endpoints % self.attempts
endpoint = self.endpoints[position+1]
self.attempts = self.attempts - 1
if endpoint and endpoint.host and endpoint.port then
self.options.host = endpoint.host
self.options.port = endpoint.port
return true
end
end
return false
end
function Request:set_headers(callback)
local method = self.options.method:upper()
local headers = {}
-- set defaults
headers['Content-Length'] = 0
headers["Content-Type"] = "application/text"
self.options.headers = misc.merge(headers, self.options.headers)
end
function Request:_write_stream(res)
logging.debugf('writing stream to disk: %s.', self.download)
local stream = fs.createWriteStream(self.download)
stream:on('end', function()
self:_ensure_retries(nil, res)
end)
stream:on('error', function(err)
self:_ensure_retries(err, res)
end)
res:on('end', function(d)
stream:finish(d)
end)
res:pipe(stream)
end
function Request:_ensure_retries(err, res)
if not err then
self.callback(err, res)
return
end
local status = res and res.status_code or "?"
local msg = fmt('%s to %s:%s failed for %s with status: %s and error: %s.', (self.options.method or "?"),
self.options.host, self.options.port, (self.download or self.upload or "?"), status, tostring(err))
logging.warn(msg)
if not self:_cycle_endpoint() then
return self.callback(err)
end
logging.debugf('retrying download %d more times.', self.attempts)
self:request()
end
function Request:_handle_response(res)
if self.download and res.status_code >= 200 and res.status_code < 300 then
return self:_write_stream(res)
end
local buf = ""
res:on('data', function(d)
buf = buf .. d
end)
res:on('end', function()
if res.status_code >= 400 then
return self:_ensure_retries(Error:new(buf), res)
end
self:_ensure_retries(nil, res)
end)
end
local exports = {makeRequest=makeRequest, Request=Request}
return exports
|
--[[
Copyright 2012 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local table = require('table')
local https = require('https')
local fs = require('fs')
local logging = require('logging')
local errors = require('../errors')
local Error = require('core').Error
local misc = require('../util/misc')
local fmt = require('string').format
local Object = require('core').Object
local exports = {}
local Request = Object:extend()
--[[
Attempts to upload or download a file over https to options.host:options.port OR
for endpoints in options.endpoints. Will try options.attempts number of times, or
for each endpoint if not specified.
options = {
host/port OR endpoints [{Endpoint1, Endpoint2, ...}]
path = "string",
method = "METHOD"
upload = nil or '/some/path'
download = nil or '/some/path'
attempts = int or #endpoints
}
]]--
local function makeRequest(...)
local req = Request:new(...)
req:set_headers()
req:request()
return req
end
function Request:initialize(options, callback)
self.callback = misc.fireOnce(callback)
if not options.method then
return self.callback(Error:new('I need a http method'))
end
if options.endpoints then
self.endpoints = misc.merge({}, options.endpoints)
else
self.endpoints = {{host=options.host, port=options.port}}
end
self.attempts = options.attempts or #self.endpoints
self.download = options.download
self.upload = options.upload
options.endpoints = nil
options.attempts = nil
options.download = nil
options.upload = nil
self.options = options
if not self:_cycle_endpoint() then
return self.callback(Error:new('call with options.port and options.host or options.endpoints'))
end
end
function Request:request()
logging.debugf('sending request to %s:%s', self.options.host, self.options.port)
local options = misc.merge({}, self.options)
local req = https.request(options, function(res)
self:_handle_response(res)
end)
req:on('error', function(err)
self:_ensure_retries(err)
end)
if not self.upload then
return req:done()
end
local data = fs.createReadStream(self.upload)
data:on('data', function(chunk)
req:write(chunk)
end)
data:on('end', function(d)
req:done(d)
end)
data:on('error', function(err)
req:done()
self._ensure_retries(err)
end)
end
function Request:_cycle_endpoint()
local position, endpoint
while self.attempts > 0 do
position = #self.endpoints % self.attempts
endpoint = self.endpoints[position+1]
self.attempts = self.attempts - 1
if endpoint and endpoint.host and endpoint.port then
self.options.host = endpoint.host
self.options.port = endpoint.port
return true
end
end
return false
end
function Request:set_headers(callback)
local method = self.options.method:upper()
local headers = {}
-- set defaults
headers['Content-Length'] = 0
headers["Content-Type"] = "application/text"
self.options.headers = misc.merge(headers, self.options.headers)
end
function Request:_write_stream(res)
logging.debugf('writing stream to disk: %s.', self.download)
local ok, stream = pcall(function()
return fs.createWriteStream(self.download)
end)
if not ok then
-- can't make the file because the dir doens't exist
if stream.code and stream.code == "ENOENT" then
return self.callback(stream)
end
return self:_ensure_retries(err, res)
end
stream:on('end', function()
self:_ensure_retries(nil, res)
end)
stream:on('error', function(err)
self:_ensure_retries(err, res)
end)
res:on('end', function(d)
stream:finish(d)
end)
res:pipe(stream)
end
function Request:_ensure_retries(err, res)
if not err then
self.callback(err, res)
return
end
local status = res and res.status_code or "?"
local msg = fmt('%s to %s:%s failed for %s with status: %s and error: %s.', (self.options.method or "?"),
self.options.host, self.options.port, (self.download or self.upload or "?"), status, tostring(err))
logging.warn(msg)
if not self:_cycle_endpoint() then
return self.callback(err)
end
logging.debugf('retrying download %d more times.', self.attempts)
self:request()
end
function Request:_handle_response(res)
if self.download and res.status_code >= 200 and res.status_code < 300 then
return self:_write_stream(res)
end
local buf = ""
res:on('data', function(d)
buf = buf .. d
end)
res:on('end', function()
if res.status_code >= 400 then
return self:_ensure_retries(Error:new(buf), res)
end
self:_ensure_retries(nil, res)
end)
end
local exports = {makeRequest=makeRequest, Request=Request}
return exports
|
Fix request.lua to handle trying to open a stupid file
|
Fix request.lua to handle trying to open a stupid file
|
Lua
|
apache-2.0
|
kans/zirgo,kans/zirgo,kans/zirgo
|
5fa9299cde20a865ffaf9fbf66c37e9b11d0a642
|
Interface/AddOns/RayUI/libs/oUF_Plugins/TotemBar.lua
|
Interface/AddOns/RayUI/libs/oUF_Plugins/TotemBar.lua
|
--[[
Documentation:
Element handled:
.TotemBar (must be a table with statusbar inside)
.TotemBar only:
.delay : The interval for updates (Default: 0.1)
.colors : The colors for the statusbar, depending on the totem
.Name : The totem name
.Destroy (boolean): Enables/Disable the totem destruction on right click
NOT YET IMPLEMENTED
.Icon (boolean): If true an icon will be added to the left or right of the bar
.IconSize : If the Icon is enabled then changed the IconSize (default: 8)
.IconJustify : any anchor like "TOPLEFT", "BOTTOMRIGHT", "TOP", etc
.TotemBar.bg only:
.multiplier : Sets the multiplier for the text or the background (can be two differents multipliers)
--]]
local R, C, L, DB = unpack(select(2, ...))
local _, ns = ...
local oUF = RayUF or oUF
if not oUF then return end
local _, pClass = UnitClass("player")
local total = 0
local delay = 0.01
-- In the order, fire, earth, water, air
local colors = {
[1] = {0.752,0.172,0.02},
[2] = {0.741,0.580,0.04},
[3] = {0,0.443,0.631},
[4] = {0.6,1,0.945},
}
local GetTotemInfo, SetValue, GetTime = GetTotemInfo, SetValue, GetTime
local Abbrev = function(name)
return (string.len(name) > 10) and string.gsub(name, "%s*(.)%S*%s*", "%1. ") or name
end
local function TotemOnClick(self,...)
local id = self.ID
local mouse = ...
--~ print(id, mouse)
if IsShiftKeyDown() then
for j = 1,4 do
DestroyTotem(j)
end
else
DestroyTotem(id)
end
end
local function InitDestroy(self)
local totem = self.TotemBar
for i = 1 , 4 do
local Destroy = CreateFrame("Button",nil, totem[i])
Destroy:SetAllPoints(totem[i])
Destroy:RegisterForClicks("LeftButtonUp", "RightButtonUp")
Destroy.ID = i
Destroy:SetScript("OnClick", TotemOnClick)
end
end
local function UpdateSlot(self, slot)
local totem = self.TotemBar
haveTotem, name, startTime, duration, totemIcon = GetTotemInfo(slot)
totem[slot]:SetStatusBarColor(unpack(totem.colors[slot]))
totem[slot]:SetValue(0)
-- Multipliers
if (totem[slot].bg.multiplier) then
local mu = totem[slot].bg.multiplier
local r, g, b = totem[slot]:GetStatusBarColor()
r, g, b = r*mu, g*mu, b*mu
totem[slot].bg:SetVertexColor(r, g, b)
end
totem[slot].ID = slot
-- If we have a totem then set his value
if(haveTotem) then
if totem[slot].Name then
totem[slot].Name:SetText(Abbrev(name))
end
if(duration >= 0) then
totem[slot]:SetValue(1 - ((GetTime() - startTime) / duration))
-- Status bar update
totem[slot]:SetScript("OnUpdate",function(self,elapsed)
total = total + elapsed
if total >= delay then
total = 0
haveTotem, name, startTime, duration, totemIcon = GetTotemInfo(self.ID)
if ((GetTime() - startTime) == 0) then
self:SetValue(0)
else
self:SetValue(1 - ((GetTime() - startTime) / duration))
end
end
end)
else
-- There's no need to update because it doesn't have any duration
totem[slot]:SetScript("OnUpdate",nil)
totem[slot]:SetValue(0)
end
else
-- No totem = no time
if totem[slot].Name then
totem[slot].Name:SetText(" ")
end
totem[slot]:SetValue(0)
end
end
local function Update(self, unit)
-- Update every slot on login, still have issues with it
for i = 1, 4 do
UpdateSlot(self, i)
end
end
local function Event(self,event,...)
if event == "PLAYER_TOTEM_UPDATE" then
UpdateSlot(self, ...)
end
end
local function Enable(self, unit)
local totem = self.TotemBar
if(totem) then
self:RegisterEvent("PLAYER_TOTEM_UPDATE" ,Event)
totem.colors = setmetatable(totem.colors or {}, {__index = colors})
delay = totem.delay or delay
if totem.Destroy then
InitDestroy(self)
end
TotemFrame:UnregisterAllEvents()
return true
end
end
local function Disable(self,unit)
local totem = self.TotemBar
if(totem) then
self:UnregisterEvent("PLAYER_TOTEM_UPDATE", Event)
TotemFrame:Show()
end
end
oUF:AddElement("TotemBar",Update,Enable,Disable)
|
--[[
Documentation:
Element handled:
.TotemBar (must be a table with statusbar inside)
.TotemBar only:
.delay : The interval for updates (Default: 0.1)
.colors : The colors for the statusbar, depending on the totem
.Name : The totem name
.Destroy (boolean): Enables/Disable the totem destruction on right click
NOT YET IMPLEMENTED
.Icon (boolean): If true an icon will be added to the left or right of the bar
.IconSize : If the Icon is enabled then changed the IconSize (default: 8)
.IconJustify : any anchor like "TOPLEFT", "BOTTOMRIGHT", "TOP", etc
.TotemBar.bg only:
.multiplier : Sets the multiplier for the text or the background (can be two differents multipliers)
--]]
local R, C, L, DB = unpack(select(2, ...))
local _, ns = ...
local oUF = ns.oUF or oUF or RayUF
if not oUF then return end
if select(2, UnitClass('player')) ~= "SHAMAN" then return end
local _, pClass = UnitClass("player")
local total = 0
local delay = 0.01
-- In the order, fire, earth, water, air
local colors = {
[1] = {0.752,0.172,0.02},
[2] = {0.741,0.580,0.04},
[3] = {0,0.443,0.631},
[4] = {0.6,1,0.945},
}
local GetTotemInfo, SetValue, GetTime = GetTotemInfo, SetValue, GetTime
local Abbrev = function(name)
return (string.len(name) > 10) and string.gsub(name, "%s*(.)%S*%s*", "%1. ") or name
end
local function TotemOnClick(self,...)
local id = self.ID
local mouse = ...
--~ print(id, mouse)
if IsShiftKeyDown() then
for j = 1,4 do
DestroyTotem(j)
end
else
DestroyTotem(id)
end
end
local function InitDestroy(self)
local totem = self.TotemBar
for i = 1 , 4 do
local Destroy = CreateFrame("Button",nil, totem[i])
Destroy:SetAllPoints(totem[i])
Destroy:RegisterForClicks("LeftButtonUp", "RightButtonUp")
Destroy.ID = i
Destroy:SetScript("OnClick", TotemOnClick)
end
end
local function UpdateSlot(self, slot)
local totem = self.TotemBar
haveTotem, name, startTime, duration, totemIcon = GetTotemInfo(slot)
totem[slot]:SetStatusBarColor(unpack(totem.colors[slot]))
totem[slot]:SetValue(0)
-- Multipliers
if (totem[slot].bg.multiplier) then
local mu = totem[slot].bg.multiplier
local r, g, b = totem[slot]:GetStatusBarColor()
r, g, b = r*mu, g*mu, b*mu
totem[slot].bg:SetVertexColor(r, g, b)
end
totem[slot].ID = slot
-- If we have a totem then set his value
if(haveTotem) then
if totem[slot].Name then
totem[slot].Name:SetText(Abbrev(name))
end
if(duration >= 0) then
if duration == 0 then
totem[slot]:SetValue(0)
else
totem[slot]:SetValue(1 - ((GetTime() - startTime) / duration))
end
-- Status bar update
totem[slot]:SetScript("OnUpdate",function(self,elapsed)
total = total + elapsed
if total >= delay then
total = 0
haveTotem, name, startTime, duration, totemIcon = GetTotemInfo(self.ID)
if duration == 0 then
self:SetValue(0)
else
self:SetValue(1 - ((GetTime() - startTime) / duration))
end
end
end)
else
-- There's no need to update because it doesn't have any duration
totem[slot]:SetScript("OnUpdate",nil)
totem[slot]:SetValue(0)
end
else
-- No totem = no time
if totem[slot].Name then
totem[slot].Name:SetText(" ")
end
totem[slot]:SetValue(0)
end
end
local function Update(self, unit)
-- Update every slot on login, still have issues with it
for i = 1, 4 do
UpdateSlot(self, i)
end
end
local function Event(self,event,...)
if event == "PLAYER_TOTEM_UPDATE" then
UpdateSlot(self, ...)
end
end
local function Enable(self, unit)
local totem = self.TotemBar
if(totem) then
self:RegisterEvent("PLAYER_TOTEM_UPDATE" ,Event, true)
totem.colors = setmetatable(totem.colors or {}, {__index = colors})
delay = totem.delay or delay
if totem.Destroy then
InitDestroy(self)
end
TotemFrame:UnregisterAllEvents()
return true
end
end
local function Disable(self,unit)
local totem = self.TotemBar
if(totem) then
self:UnregisterEvent("PLAYER_TOTEM_UPDATE", Event)
TotemFrame:Show()
end
end
oUF:AddElement("TotemBar",Update,Enable,Disable)
|
fix totem bar
|
fix totem bar
|
Lua
|
mit
|
fgprodigal/RayUI
|
2576e298ca0bbe99ad46fdaf395b43eb0c1dc63c
|
share/lua/website/ted.lua
|
share/lua/website/ted.lua
|
-- libquvi-scripts
-- Copyright (C) 2012 Toni Gundogdu <[email protected]>
-- Copyright (C) 2011 Bastien Nocera <[email protected]>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-- 02110-1301 USA
--
local Ted = {} -- Utility functions unique to this script
-- Identify the script.
function ident(self)
package.path = self.script_dir .. '/?.lua'
local C = require 'quvi/const'
local r = {}
r.domain = "ted%.com"
r.formats = "default|best"
r.categories = C.proto_http
local U = require 'quvi/util'
r.handles = U.handles(self.page_url, {r.domain}, {"/talks/.+$"})
return r
end
-- Query available formats.
function query_formats(self)
self.formats = "default"
Ted.is_external(self, quvi.fetch(self.page_url))
return self
end
-- Parse video URL.
function parse(self)
self.host_id = "ted"
local p = quvi.fetch(self.page_url)
if Ted.is_external(self, p) then
return self
end
self.id = p:match('ti:"(%d+)"')
or error("no match: media ID")
self.title = p:match('<title>(.-)%s+|')
or error("no match: media title")
self.thumbnail_url = p:match('rel="image_src" href="(.-)"') or ''
self.url = {p:match('(http://download.-)"')
or error("no match: media stream URL")}
return self
end
--
-- Utility functions
--
function Ted.is_external(self, page)
-- Some of the videos are hosted elsewhere.
self.redirect_url = page:match('name="movie"%s+value="(.-)"') or ''
return #self.redirect_url > 0
end
-- vim: set ts=4 sw=4 tw=72 expandtab:
|
-- libquvi-scripts
-- Copyright (C) 2012,2013 Toni Gundogdu <[email protected]>
-- Copyright (C) 2011 Bastien Nocera <[email protected]>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-- 02110-1301 USA
--
local Ted = {} -- Utility functions unique to this script
-- Identify the script.
function ident(self)
package.path = self.script_dir .. '/?.lua'
local C = require 'quvi/const'
local r = {}
r.domain = "ted%.com"
r.formats = "default|best"
r.categories = C.proto_http
local U = require 'quvi/util'
r.handles = U.handles(self.page_url, {r.domain}, {"/talks/.+$"})
return r
end
-- Query available formats.
function query_formats(self)
self.formats = "default"
Ted.is_external(self, quvi.fetch(self.page_url))
return self
end
-- Parse video URL.
function parse(self)
self.host_id = "ted"
local p = quvi.fetch(self.page_url)
if Ted.is_external(self, p) then return self end
self.id = p:match('ti:"(%d+)"') or error("no match: media ID")
self.title = p:match('<title>(.-)%s+|') or error("no match: media title")
self.thumbnail_url = p:match('"og:image" content="(.-)"') or ''
return self
end
--
-- Utility functions
--
function Ted.is_external(self, p)
self.url = {p:match('(http://download.-)"') or ''}
if #self.url[1] ==0 then -- Try the first iframe
self.redirect_url = p:match('<iframe src="(.-)"') or ''
if #self.redirect_url >0 then
return true
else
error('no match: media stream URL')
end
end
return false
end
-- vim: set ts=4 sw=4 tw=72 expandtab:
|
FIX: website/ted.lua: Check for extern media
|
FIX: website/ted.lua: Check for extern media
* Rewrite `Ted.is_external' func using a new embed URL pattern
* Revise `parse' function for minor style changes
* Update thumbnail_url pattern
Signed-off-by: Toni Gundogdu <[email protected]>
|
Lua
|
agpl-3.0
|
alech/libquvi-scripts,legatvs/libquvi-scripts,alech/libquvi-scripts,legatvs/libquvi-scripts
|
1b1425ea5958fe089b80c47066d45620a830b3aa
|
applications/luci-statistics/luasrc/controller/luci_statistics/luci_statistics.lua
|
applications/luci-statistics/luasrc/controller/luci_statistics/luci_statistics.lua
|
--[[
Luci statistics - statistics controller module
(c) 2008 Freifunk Leipzig / 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$
]]--
module("luci.controller.luci_statistics.luci_statistics", package.seeall)
function index()
require("nixio.fs")
require("luci.util")
require("luci.statistics.datatree")
-- get rrd data tree
local tree = luci.statistics.datatree.Instance()
-- override entry(): check for existance <plugin>.so where <plugin> is derived from the called path
function _entry( path, ... )
local file = path[5] or path[4]
if nixio.fs.access( "/usr/lib/collectd/" .. file .. ".so" ) then
entry( path, ... )
end
end
local labels = {
s_output = _("Output plugins"),
s_system = _("System plugins"),
s_network = _("Network plugins"),
rrdtool = _("RRDTool"),
network = _("Network"),
unixsock = _("UnixSock"),
csv = _("CSV Output"),
exec = _("Exec"),
email = _("Email"),
cpu = _("Processor"),
df = _("Disk Space Usage"),
disk = _("Disk Usage"),
irq = _("Interrupts"),
processes = _("Processes"),
load = _("System Load"),
interface = _("Interfaces"),
netlink = _("Netlink"),
iptables = _("Firewall"),
tcpconns = _("TCP Connections"),
ping = _("Ping"),
dns = _("DNS"),
wireless = _("Wireless")
}
-- our collectd menu
local collectd_menu = {
output = { "rrdtool", "network", "unixsock", "csv" },
system = { "exec", "email", "cpu", "df", "disk", "irq", "processes", "load" },
network = { "interface", "netlink", "iptables", "tcpconns", "ping", "dns", "wireless" }
}
-- create toplevel menu nodes
local st = entry({"admin", "statistics"}, call("statistics_index"), _("Statistics"), 80)
st.i18n = "statistics"
st.index = true
entry({"admin", "statistics", "collectd"}, cbi("luci_statistics/collectd"), _("Collectd"), 10).subindex = true
-- populate collectd plugin menu
local index = 1
for section, plugins in luci.util.kspairs( collectd_menu ) do
local e = entry(
{ "admin", "statistics", "collectd", section },
call( "statistics_" .. section .. "plugins" ),
labels["s_"..section], index * 10
)
e.index = true
e.i18n = "rrdtool"
for j, plugin in luci.util.vspairs( plugins ) do
_entry(
{ "admin", "statistics", "collectd", section, plugin },
cbi("luci_statistics/" .. plugin ),
labels[plugin], j * 10
)
end
index = index + 1
end
-- output views
local page = entry( { "admin", "statistics", "graph" }, call("statistics_index"), _("Graphs"), 80)
page.i18n = "statistics"
page.setuser = "nobody"
page.setgroup = "nogroup"
local vars = luci.http.formvalue(nil, true)
local span = vars.timespan or nil
for i, plugin in luci.util.vspairs( tree:plugins() ) do
-- get plugin instances
local instances = tree:plugin_instances( plugin )
-- plugin menu entry
entry(
{ "admin", "statistics", "graph", plugin },
call("statistics_render"), labels[plugin], i
).query = { timespan = span }
-- if more then one instance is found then generate submenu
if #instances > 1 then
for j, inst in luci.util.vspairs(instances) do
-- instance menu entry
entry(
{ "admin", "statistics", "graph", plugin, inst },
call("statistics_render"), inst, j
).query = { timespan = span }
end
end
end
end
function statistics_index()
luci.template.render("admin_statistics/index")
end
function statistics_outputplugins()
local translate = luci.i18n.translate
local plugins = {
rrdtool = _("RRDTool"),
network = _("Network"),
unixsock = _("UnixSock"),
csv = _("CSV Output")
}
luci.template.render("admin_statistics/outputplugins", {plugins=plugins})
end
function statistics_systemplugins()
local translate = luci.i18n.translate
local plugins = {
exec = _("Exec"),
email = _("Email"),
cpu = _("Processor"),
df = _("Disk Space Usage"),
disk = _("Disk Usage"),
irq = _("Interrupts"),
processes = _("Processes"),
load = _("System Load"),
}
luci.template.render("admin_statistics/systemplugins", {plugins=plugins})
end
function statistics_networkplugins()
local translate = luci.i18n.translate
local plugins = {
interface = _("Interfaces"),
netlink = _("Netlink"),
iptables = _("Firewall"),
tcpconns = _("TCP Connections"),
ping = _("Ping"),
dns = _("DNS"),
wireless = _("Wireless")
}
luci.template.render("admin_statistics/networkplugins", {plugins=plugins})
end
function statistics_render()
require("luci.statistics.rrdtool")
require("luci.template")
require("luci.model.uci")
local vars = luci.http.formvalue()
local req = luci.dispatcher.context.request
local path = luci.dispatcher.context.path
local uci = luci.model.uci.cursor()
local spans = luci.util.split( uci:get( "luci_statistics", "collectd_rrdtool", "RRATimespans" ), "%s+", nil, true )
local span = vars.timespan or uci:get( "luci_statistics", "rrdtool", "default_timespan" ) or spans[1]
local graph = luci.statistics.rrdtool.Graph( luci.util.parse_units( span ) )
-- deliver image
if vars.img then
local l12 = require "luci.ltn12"
local png = io.open(graph.opts.imgpath .. "/" .. vars.img:gsub("%.+", "."), "r")
if png then
luci.http.prepare_content("image/png")
l12.pump.all(l12.source.file(png), luci.http.write)
png:close()
end
return
end
local plugin, instances
local images = { }
-- find requested plugin and instance
for i, p in ipairs( luci.dispatcher.context.path ) do
if luci.dispatcher.context.path[i] == "graph" then
plugin = luci.dispatcher.context.path[i+1]
instances = { luci.dispatcher.context.path[i+2] }
end
end
-- no instance requested, find all instances
if #instances == 0 then
instances = { graph.tree:plugin_instances( plugin )[1] }
-- index instance requested
elseif instances[1] == "-" then
instances[1] = ""
end
-- render graphs
for i, inst in ipairs( instances ) do
for i, img in ipairs( graph:render( plugin, inst ) ) do
table.insert( images, graph:strippngpath( img ) )
end
end
luci.template.render( "public_statistics/graph", {
images = images,
plugin = plugin,
timespans = spans,
current_timespan = span
} )
end
|
--[[
Luci statistics - statistics controller module
(c) 2008 Freifunk Leipzig / 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$
]]--
module("luci.controller.luci_statistics.luci_statistics", package.seeall)
function index()
require("nixio.fs")
require("luci.util")
require("luci.statistics.datatree")
-- get rrd data tree
local tree = luci.statistics.datatree.Instance()
-- override entry(): check for existance <plugin>.so where <plugin> is derived from the called path
function _entry( path, ... )
local file = path[5] or path[4]
if nixio.fs.access( "/usr/lib/collectd/" .. file .. ".so" ) then
entry( path, ... )
end
end
local labels = {
s_output = _("Output plugins"),
s_system = _("System plugins"),
s_network = _("Network plugins"),
rrdtool = _("RRDTool"),
network = _("Network"),
unixsock = _("UnixSock"),
csv = _("CSV Output"),
exec = _("Exec"),
email = _("Email"),
cpu = _("Processor"),
df = _("Disk Space Usage"),
disk = _("Disk Usage"),
irq = _("Interrupts"),
processes = _("Processes"),
load = _("System Load"),
interface = _("Interfaces"),
netlink = _("Netlink"),
iptables = _("Firewall"),
tcpconns = _("TCP Connections"),
ping = _("Ping"),
dns = _("DNS"),
wireless = _("Wireless")
}
-- our collectd menu
local collectd_menu = {
output = { "rrdtool", "network", "unixsock", "csv" },
system = { "exec", "email", "cpu", "df", "disk", "irq", "processes", "load" },
network = { "interface", "netlink", "iptables", "tcpconns", "ping", "dns", "wireless" }
}
-- create toplevel menu nodes
local st = entry({"admin", "statistics"}, call("statistics_index"), _("Statistics"), 80)
st.i18n = "statistics"
st.index = true
entry({"admin", "statistics", "collectd"}, cbi("luci_statistics/collectd"), _("Collectd"), 10).subindex = true
-- populate collectd plugin menu
local index = 1
for section, plugins in luci.util.kspairs( collectd_menu ) do
local e = entry(
{ "admin", "statistics", "collectd", section },
call( "statistics_" .. section .. "plugins" ),
labels["s_"..section], index * 10
)
e.index = true
e.i18n = "rrdtool"
for j, plugin in luci.util.vspairs( plugins ) do
_entry(
{ "admin", "statistics", "collectd", section, plugin },
cbi("luci_statistics/" .. plugin ),
labels[plugin], j * 10
)
end
index = index + 1
end
-- output views
local page = entry( { "admin", "statistics", "graph" }, call("statistics_index"), _("Graphs"), 80)
page.i18n = "statistics"
page.setuser = "nobody"
page.setgroup = "nogroup"
local vars = luci.http.formvalue(nil, true)
local span = vars.timespan or nil
for i, plugin in luci.util.vspairs( tree:plugins() ) do
-- get plugin instances
local instances = tree:plugin_instances( plugin )
-- plugin menu entry
entry(
{ "admin", "statistics", "graph", plugin },
call("statistics_render"), labels[plugin], i
).query = { timespan = span }
-- if more then one instance is found then generate submenu
if #instances > 1 then
for j, inst in luci.util.vspairs(instances) do
-- instance menu entry
entry(
{ "admin", "statistics", "graph", plugin, inst },
call("statistics_render"), inst, j
).query = { timespan = span }
end
end
end
end
function statistics_index()
luci.template.render("admin_statistics/index")
end
function statistics_outputplugins()
local translate = luci.i18n.translate
local plugins = {
rrdtool = translate("RRDTool"),
network = translate("Network"),
unixsock = translate("UnixSock"),
csv = translate("CSV Output")
}
luci.template.render("admin_statistics/outputplugins", {plugins=plugins})
end
function statistics_systemplugins()
local translate = luci.i18n.translate
local plugins = {
exec = translate("Exec"),
email = translate("Email"),
cpu = translate("Processor"),
df = translate("Disk Space Usage"),
disk = translate("Disk Usage"),
irq = translate("Interrupts"),
processes = translate("Processes"),
load = translate("System Load"),
}
luci.template.render("admin_statistics/systemplugins", {plugins=plugins})
end
function statistics_networkplugins()
local translate = luci.i18n.translate
local plugins = {
interface = translate("Interfaces"),
netlink = translate("Netlink"),
iptables = translate("Firewall"),
tcpconns = translate("TCP Connections"),
ping = translate("Ping"),
dns = translate("DNS"),
wireless = translate("Wireless")
}
luci.template.render("admin_statistics/networkplugins", {plugins=plugins})
end
function statistics_render()
require("luci.statistics.rrdtool")
require("luci.template")
require("luci.model.uci")
local vars = luci.http.formvalue()
local req = luci.dispatcher.context.request
local path = luci.dispatcher.context.path
local uci = luci.model.uci.cursor()
local spans = luci.util.split( uci:get( "luci_statistics", "collectd_rrdtool", "RRATimespans" ), "%s+", nil, true )
local span = vars.timespan or uci:get( "luci_statistics", "rrdtool", "default_timespan" ) or spans[1]
local graph = luci.statistics.rrdtool.Graph( luci.util.parse_units( span ) )
-- deliver image
if vars.img then
local l12 = require "luci.ltn12"
local png = io.open(graph.opts.imgpath .. "/" .. vars.img:gsub("%.+", "."), "r")
if png then
luci.http.prepare_content("image/png")
l12.pump.all(l12.source.file(png), luci.http.write)
png:close()
end
return
end
local plugin, instances
local images = { }
-- find requested plugin and instance
for i, p in ipairs( luci.dispatcher.context.path ) do
if luci.dispatcher.context.path[i] == "graph" then
plugin = luci.dispatcher.context.path[i+1]
instances = { luci.dispatcher.context.path[i+2] }
end
end
-- no instance requested, find all instances
if #instances == 0 then
instances = { graph.tree:plugin_instances( plugin )[1] }
-- index instance requested
elseif instances[1] == "-" then
instances[1] = ""
end
-- render graphs
for i, inst in ipairs( instances ) do
for i, img in ipairs( graph:render( plugin, inst ) ) do
table.insert( images, graph:strippngpath( img ) )
end
end
luci.template.render( "public_statistics/graph", {
images = images,
plugin = plugin,
timespans = spans,
current_timespan = span
} )
end
|
applications/luci-statistics: fix translation issues in controller
|
applications/luci-statistics: fix translation issues in controller
|
Lua
|
apache-2.0
|
8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci
|
c2a1c9130cd93513c4429e7e86b5b93f9fb638d8
|
Hydra/hydra.lua
|
Hydra/hydra.lua
|
doc.hydra.resourcesdir = {"hydra.resourcesdir -> string", "The path of the built-in lua source files, with no trailing slash."}
doc.hydra.userfile = {"hydra.userfile(name)", "Returns the full path to the file ~/.hydra/{name}.lua"}
function hydra.userfile(name)
return os.getenv("HOME") .. "/.hydra/" .. name .. ".lua"
end
doc.hydra.douserfile = {"hydra.douserfile(name)", "Convenience wrapper around dofile() and hydra.userfile(name)"}
function hydra.douserfile(name)
local userfile = hydra.userfile(name)
local exists, isdir = hydra.fileexists(userfile)
if exists and not isdir then
dofile(userfile)
else
notify.show("Hydra user-file missing", "", "Can't find file: " .. tostring(name), "")
end
end
local function load_default_config()
local fallbackinit = dofile(hydra.resourcesdir .. "/fallback_init.lua")
fallbackinit.run()
end
local function clear_old_state()
hotkey.disableall()
menu.hide()
pathwatcher.stopall()
timer.stopall()
textgrid.closeall()
notify.unregisterall()
end
doc.hydra.reload = {"hydra.reload()", "Reloads your init-file. Makes sure to clear any state that makes sense to clear (hotkeys, pathwatchers, etc)."}
function hydra.reload()
clear_old_state()
local userfile = os.getenv("HOME") .. "/.hydra/init.lua"
local exists, isdir = hydra.fileexists(userfile)
if exists and not isdir then
local ok, err = pcall(function() dofile(userfile) end)
if not ok then
notify.show("Hydra config error", "", tostring(err) .. " -- Falling back to sample config.", "")
load_default_config()
end
else
-- don't say (via alert) anything more than what the default config already says
load_default_config()
end
end
doc.hydra.errorhandler = {"hydra.errorhandler = function(err)", "Error handler for hydra.call; intended for you to set, not for third party libs"}
function hydra.errorhandler(err)
print("Error: " .. err)
notify.show("Hydra Error", "", tostring(err), "error")
end
function hydra.tryhandlingerror(firsterr)
local ok, seconderr = pcall(function()
hydra.errorhandler(firsterr)
end)
if not ok then
notify.show("Hydra error", "", "Error while handling error: " .. tostring(seconderr) .. " -- Original error: " .. tostring(firsterr), "")
end
end
doc.hydra.call = {"hydra.call(fn, ...) -> ...", "Just like pcall, except that failures are handled using hydra.errorhandler"}
function hydra.call(fn, ...)
local results = table.pack(pcall(fn, ...))
if not results[1] then
-- print(debug.traceback())
hydra.tryhandlingerror(results[2])
end
return table.unpack(results)
end
local function trimstring(s)
return s:gsub("^%s+", ""):gsub("%s+$", "")
end
doc.hydra.exec = {"hydra.exec(command) -> string", "Runs a shell function and returns stdout as a string (without trailing newline)."}
function hydra.exec(command)
local f = io.popen(command)
local str = f:read("*a")
f:close()
return trimstring(str)
end
doc.hydra.uuid = {"hydra.uuid() -> string", "Returns a UUID as a string"}
function hydra.uuid()
return hydra.exec("uuidgen")
end
-- swizzle! this is necessary so hydra.settings can save keys on exit
os.exit = hydra.exit
|
doc.hydra.resourcesdir = {"hydra.resourcesdir -> string", "The path of the built-in lua source files, with no trailing slash."}
doc.hydra.userfile = {"hydra.userfile(name)", "Returns the full path to the file ~/.hydra/{name}.lua"}
function hydra.userfile(name)
return os.getenv("HOME") .. "/.hydra/" .. name .. ".lua"
end
doc.hydra.douserfile = {"hydra.douserfile(name)", "Convenience wrapper around dofile() and hydra.userfile(name)"}
function hydra.douserfile(name)
local userfile = hydra.userfile(name)
local exists, isdir = hydra.fileexists(userfile)
if exists and not isdir then
dofile(userfile)
else
notify.show("Hydra user-file missing", "", "Can't find file: " .. tostring(name), "")
end
end
local function clear_old_state()
hotkey.disableall()
menu.hide()
pathwatcher.stopall()
timer.stopall()
textgrid.closeall()
notify.unregisterall()
end
local function load_default_config()
clear_old_state()
local fallbackinit = dofile(hydra.resourcesdir .. "/fallback_init.lua")
fallbackinit.run()
end
doc.hydra.reload = {"hydra.reload()", "Reloads your init-file. Makes sure to clear any state that makes sense to clear (hotkeys, pathwatchers, etc)."}
function hydra.reload()
local userfile = os.getenv("HOME") .. "/.hydra/init.lua"
local exists, isdir = hydra.fileexists(userfile)
if exists and not isdir then
local fn, err = loadfile(userfile)
if fn then
clear_old_state()
local ok, err = pcall(fn)
if not ok then
notify.show("Hydra config runtime error", "", tostring(err) .. " -- Falling back to sample config.", "")
load_default_config()
end
else
notify.show("Hydra config syntax error", "", tostring(err) .. " -- Doing nothing.", "")
end
else
-- don't say (via alert) anything more than what the default config already says
load_default_config()
end
end
doc.hydra.errorhandler = {"hydra.errorhandler = function(err)", "Error handler for hydra.call; intended for you to set, not for third party libs"}
function hydra.errorhandler(err)
print("Error: " .. err)
notify.show("Hydra Error", "", tostring(err), "error")
end
function hydra.tryhandlingerror(firsterr)
local ok, seconderr = pcall(function()
hydra.errorhandler(firsterr)
end)
if not ok then
notify.show("Hydra error", "", "Error while handling error: " .. tostring(seconderr) .. " -- Original error: " .. tostring(firsterr), "")
end
end
doc.hydra.call = {"hydra.call(fn, ...) -> ...", "Just like pcall, except that failures are handled using hydra.errorhandler"}
function hydra.call(fn, ...)
local results = table.pack(pcall(fn, ...))
if not results[1] then
-- print(debug.traceback())
hydra.tryhandlingerror(results[2])
end
return table.unpack(results)
end
local function trimstring(s)
return s:gsub("^%s+", ""):gsub("%s+$", "")
end
doc.hydra.exec = {"hydra.exec(command) -> string", "Runs a shell function and returns stdout as a string (without trailing newline)."}
function hydra.exec(command)
local f = io.popen(command)
local str = f:read("*a")
f:close()
return trimstring(str)
end
doc.hydra.uuid = {"hydra.uuid() -> string", "Returns a UUID as a string"}
function hydra.uuid()
return hydra.exec("uuidgen")
end
-- swizzle! this is necessary so hydra.settings can save keys on exit
os.exit = hydra.exit
|
Do nothing if hydra.reload fails due to user syntax errors; fixes #119.
|
Do nothing if hydra.reload fails due to user syntax errors; fixes #119.
|
Lua
|
mit
|
heptal/hammerspoon,Hammerspoon/hammerspoon,cmsj/hammerspoon,wvierber/hammerspoon,bradparks/hammerspoon,Stimim/hammerspoon,chrisjbray/hammerspoon,kkamdooong/hammerspoon,ocurr/hammerspoon,heptal/hammerspoon,emoses/hammerspoon,nkgm/hammerspoon,cmsj/hammerspoon,chrisjbray/hammerspoon,latenitefilms/hammerspoon,peterhajas/hammerspoon,heptal/hammerspoon,CommandPost/CommandPost-App,zzamboni/hammerspoon,cmsj/hammerspoon,zzamboni/hammerspoon,latenitefilms/hammerspoon,wsmith323/hammerspoon,wsmith323/hammerspoon,peterhajas/hammerspoon,asmagill/hammerspoon,heptal/hammerspoon,lowne/hammerspoon,TimVonsee/hammerspoon,joehanchoi/hammerspoon,chrisjbray/hammerspoon,TimVonsee/hammerspoon,cmsj/hammerspoon,zzamboni/hammerspoon,peterhajas/hammerspoon,ocurr/hammerspoon,asmagill/hammerspoon,trishume/hammerspoon,junkblocker/hammerspoon,hypebeast/hammerspoon,Habbie/hammerspoon,kkamdooong/hammerspoon,chrisjbray/hammerspoon,dopcn/hammerspoon,knu/hammerspoon,knu/hammerspoon,wsmith323/hammerspoon,knu/hammerspoon,kkamdooong/hammerspoon,junkblocker/hammerspoon,dopcn/hammerspoon,emoses/hammerspoon,tmandry/hammerspoon,ocurr/hammerspoon,cmsj/hammerspoon,bradparks/hammerspoon,knu/hammerspoon,asmagill/hammerspoon,wvierber/hammerspoon,asmagill/hammerspoon,nkgm/hammerspoon,kkamdooong/hammerspoon,lowne/hammerspoon,joehanchoi/hammerspoon,heptal/hammerspoon,lowne/hammerspoon,junkblocker/hammerspoon,tmandry/hammerspoon,emoses/hammerspoon,dopcn/hammerspoon,Habbie/hammerspoon,CommandPost/CommandPost-App,knu/hammerspoon,asmagill/hammerspoon,joehanchoi/hammerspoon,joehanchoi/hammerspoon,TimVonsee/hammerspoon,latenitefilms/hammerspoon,CommandPost/CommandPost-App,bradparks/hammerspoon,latenitefilms/hammerspoon,lowne/hammerspoon,trishume/hammerspoon,ocurr/hammerspoon,Stimim/hammerspoon,ocurr/hammerspoon,wsmith323/hammerspoon,knl/hammerspoon,hypebeast/hammerspoon,bradparks/hammerspoon,hypebeast/hammerspoon,wvierber/hammerspoon,zzamboni/hammerspoon,Hammerspoon/hammerspoon,knl/hammerspoon,joehanchoi/hammerspoon,Habbie/hammerspoon,Hammerspoon/hammerspoon,cmsj/hammerspoon,peterhajas/hammerspoon,latenitefilms/hammerspoon,TimVonsee/hammerspoon,hypebeast/hammerspoon,chrisjbray/hammerspoon,knl/hammerspoon,latenitefilms/hammerspoon,Habbie/hammerspoon,nkgm/hammerspoon,hypebeast/hammerspoon,emoses/hammerspoon,knu/hammerspoon,Hammerspoon/hammerspoon,junkblocker/hammerspoon,Hammerspoon/hammerspoon,kkamdooong/hammerspoon,knl/hammerspoon,peterhajas/hammerspoon,wvierber/hammerspoon,Stimim/hammerspoon,zzamboni/hammerspoon,tmandry/hammerspoon,Habbie/hammerspoon,wvierber/hammerspoon,wsmith323/hammerspoon,Stimim/hammerspoon,zzamboni/hammerspoon,knl/hammerspoon,CommandPost/CommandPost-App,nkgm/hammerspoon,Stimim/hammerspoon,lowne/hammerspoon,junkblocker/hammerspoon,TimVonsee/hammerspoon,bradparks/hammerspoon,Hammerspoon/hammerspoon,CommandPost/CommandPost-App,asmagill/hammerspoon,nkgm/hammerspoon,trishume/hammerspoon,emoses/hammerspoon,Habbie/hammerspoon,CommandPost/CommandPost-App,dopcn/hammerspoon,chrisjbray/hammerspoon,dopcn/hammerspoon
|
93073b3fe61d00ec66877f93ec270989aacb2928
|
config/nvim/lua/plugins/init.lua
|
config/nvim/lua/plugins/init.lua
|
local g = vim.g
local fn = vim.fn
local utils = require("utils")
local nmap = utils.nmap
local env = vim.env
local plugLoad = fn["functions#PlugLoad"]
local plugBegin = fn["plug#begin"]
local plugEnd = fn["plug#end"]
local Plug = fn["plug#"]
plugLoad()
plugBegin("~/.config/nvim/plugged")
-- NOTE: the argument passed to Plug has to be wrapped with single-quotes
-- a set of lua helpers that are used by other plugins
Plug "nvim-lua/plenary.nvim"
-- easy commenting
Plug "tpope/vim-commentary"
Plug "JoosepAlviste/nvim-ts-context-commentstring"
-- bracket mappings for moving between buffers, quickfix items, etc.
Plug "tpope/vim-unimpaired"
-- mappings to easily delete, change and add such surroundings in pairs, such as quotes, parens, etc.
Plug "tpope/vim-surround"
-- endings for html, xml, etc. - ehances surround
Plug "tpope/vim-ragtag"
-- substitution and abbreviation helpers
Plug "tpope/vim-abolish"
-- enables repeating other supported plugins with the . command
Plug "tpope/vim-repeat"
-- single/multi line code handler: gS - split one line into multiple, gJ - combine multiple lines into one
Plug "AndrewRadev/splitjoin.vim"
-- detect indent style (tabs vs. spaces)
Plug "tpope/vim-sleuth"
-- setup editorconfig
Plug "editorconfig/editorconfig-vim"
-- fugitive
Plug "tpope/vim-fugitive"
Plug "tpope/vim-rhubarb"
nmap("<leader>gr", ":Gread<cr>")
nmap("<leader>gb", ":G blame<cr>")
-- general plugins
-- emmet support for vim - easily create markdup wth CSS-like syntax
Plug "mattn/emmet-vim"
-- match tags in html, similar to paren support
Plug("gregsexton/MatchTag", {["for"] = "html"})
-- html5 support
Plug("othree/html5.vim", {["for"] = "html"})
-- mustache support
Plug "mustache/vim-mustache-handlebars"
-- pug / jade support
Plug("digitaltoad/vim-pug", {["for"] = {"jade", "pug"}})
-- nunjucks support
-- Plug "niftylettuce/vim-jinja"
-- edit quickfix list
Plug "itchyny/vim-qfedit"
-- liquid support
Plug "tpope/vim-liquid"
Plug("othree/yajs.vim", {["for"] = {"javascript", "javascript.jsx", "html"}})
-- Plug 'pangloss/vim-javascript', { 'for': ['javascript', 'javascript.jsx', 'html'] }
Plug("moll/vim-node", {["for"] = "javascript"})
Plug "MaxMEllon/vim-jsx-pretty"
g.vim_jsx_pretty_highlight_close_tag = 1
Plug("leafgarland/typescript-vim", {["for"] = {"typescript", "typescript.tsx"}})
Plug("wavded/vim-stylus", {["for"] = {"stylus", "markdown"}})
Plug("groenewege/vim-less", {["for"] = "less"})
Plug("hail2u/vim-css3-syntax", {["for"] = "css"})
Plug("cakebaker/scss-syntax.vim", {["for"] = "scss"})
Plug("stephenway/postcss.vim", {["for"] = "css"})
Plug "udalov/kotlin-vim"
-- Open markdown files in Marked.app - mapped to <leader>m
Plug("itspriddle/vim-marked", {["for"] = "markdown", on = "MarkedOpen"})
nmap("<leader>m", ":MarkedOpen!<cr>")
nmap("<leader>mq", ":MarkedQuit<cr>")
nmap("<leader>*", "*<c-o>:%s///gn<cr>")
Plug("elzr/vim-json", {["for"] = "json"})
g.vim_json_syntax_conceal = 0
Plug "ekalinin/Dockerfile.vim"
Plug "jparise/vim-graphql"
Plug "hrsh7th/cmp-vsnip"
Plug "hrsh7th/vim-vsnip"
Plug "hrsh7th/vim-vsnip-integ"
local snippet_dir = os.getenv("DOTFILES") .. "/config/nvim/snippets"
g.vsnip_snippet_dir = snippet_dir
g.vsnip_filetypes = {
javascriptreact = {"javascript"},
typescriptreact = {"typescript"},
["typescript.tsx"] = {"typescript"}
}
-- add color highlighting to hex values
Plug "norcalli/nvim-colorizer.lua"
-- use devicons for filetypes
Plug "kyazdani42/nvim-web-devicons"
-- fast lau file drawer
Plug "kyazdani42/nvim-tree.lua"
-- Show git information in the gutter
Plug "lewis6991/gitsigns.nvim"
-- Helpers to configure the built-in Neovim LSP client
Plug "neovim/nvim-lspconfig"
-- Helpers to install LSPs and maintain them
Plug "williamboman/nvim-lsp-installer"
-- neovim completion
Plug "hrsh7th/cmp-nvim-lsp"
Plug "hrsh7th/cmp-nvim-lua"
Plug "hrsh7th/cmp-buffer"
Plug "hrsh7th/cmp-path"
Plug "hrsh7th/nvim-cmp"
-- treesitter enables an AST-like understanding of files
Plug("nvim-treesitter/nvim-treesitter", {["do"] = ":TSUpdate"})
-- show treesitter nodes
Plug "nvim-treesitter/playground"
-- enable more advanced treesitter-aware text objects
Plug "nvim-treesitter/nvim-treesitter-textobjects"
-- add rainbow highlighting to parens and brackets
Plug "p00f/nvim-ts-rainbow"
-- show nerd font icons for LSP types in completion menu
Plug "onsails/lspkind-nvim"
-- base16 syntax themes that are neovim/treesitter-aware
Plug "RRethy/nvim-base16"
-- status line plugin
Plug "feline-nvim/feline.nvim"
-- automatically complete brackets/parens/quotes
Plug "windwp/nvim-autopairs"
-- Run prettier and other formatters on save
Plug "mhartington/formatter.nvim"
-- Style the tabline without taking over how tabs and buffers work in Neovim
Plug "alvarosevilla95/luatab.nvim"
-- enable copilot support for Neovim
Plug "github/copilot.vim"
-- if a copilot-aliased version of node exists from fnm, use that
local copilot_node_path = env.FNM_DIR .. "/aliases/copilot/bin/node"
if utils.file_exists(copilot_node_path) then
g.copilot_node_path = copilot_node_path
end
-- improve the default neovim interfaces, such as refactoring
Plug "stevearc/dressing.nvim"
-- Navigate a code base with a really slick UI
Plug "nvim-telescope/telescope.nvim"
Plug "nvim-telescope/telescope-rg.nvim"
-- Startup screen for Neovim
Plug "startup-nvim/startup.nvim"
-- fzf
Plug "$HOMEBREW_PREFIX/opt/fzf"
Plug "junegunn/fzf.vim"
-- Power telescope with FZF
Plug("nvim-telescope/telescope-fzf-native.nvim", {["do"] = "make"})
Plug "folke/trouble.nvim"
plugEnd()
-- Once the plugins have been loaded, Lua-based plugins need to be required and started up
-- For plugins with their own configuration file, that file is loaded and is responsible for
-- starting them. Otherwise, the plugin itself is required and its `setup` method is called.
require("nvim-autopairs").setup()
require("colorizer").setup()
require("plugins.telescope")
require("plugins.gitsigns")
require("plugins.trouble")
require("plugins.fzf")
require("plugins.lspconfig")
require("plugins.completion")
require("plugins.treesitter")
require("plugins.nvimtree")
require("plugins.formatter")
require("plugins.tabline")
require("plugins.feline")
require("plugins.startup")
|
local g = vim.g
local fn = vim.fn
local utils = require("utils")
local nmap = utils.nmap
local env = vim.env
local cmd = vim.cmd
local plugLoad = fn["functions#PlugLoad"]
local plugBegin = fn["plug#begin"]
local plugEnd = fn["plug#end"]
local Plug = fn["plug#"]
plugLoad()
plugBegin("~/.config/nvim/plugged")
-- NOTE: the argument passed to Plug has to be wrapped with single-quotes
-- a set of lua helpers that are used by other plugins
Plug "nvim-lua/plenary.nvim"
-- easy commenting
Plug "tpope/vim-commentary"
Plug "JoosepAlviste/nvim-ts-context-commentstring"
-- bracket mappings for moving between buffers, quickfix items, etc.
Plug "tpope/vim-unimpaired"
-- mappings to easily delete, change and add such surroundings in pairs, such as quotes, parens, etc.
Plug "tpope/vim-surround"
-- endings for html, xml, etc. - ehances surround
Plug "tpope/vim-ragtag"
-- substitution and abbreviation helpers
Plug "tpope/vim-abolish"
-- enables repeating other supported plugins with the . command
Plug "tpope/vim-repeat"
-- single/multi line code handler: gS - split one line into multiple, gJ - combine multiple lines into one
Plug "AndrewRadev/splitjoin.vim"
-- detect indent style (tabs vs. spaces)
Plug "tpope/vim-sleuth"
-- setup editorconfig
Plug "editorconfig/editorconfig-vim"
-- fugitive
Plug "tpope/vim-fugitive"
Plug "tpope/vim-rhubarb"
nmap("<leader>gr", ":Gread<cr>")
nmap("<leader>gb", ":G blame<cr>")
-- general plugins
-- emmet support for vim - easily create markdup wth CSS-like syntax
Plug "mattn/emmet-vim"
-- match tags in html, similar to paren support
Plug("gregsexton/MatchTag", {["for"] = "html"})
-- html5 support
Plug("othree/html5.vim", {["for"] = "html"})
-- mustache support
Plug "mustache/vim-mustache-handlebars"
-- pug / jade support
Plug("digitaltoad/vim-pug", {["for"] = {"jade", "pug"}})
-- nunjucks support
-- Plug "niftylettuce/vim-jinja"
-- edit quickfix list
Plug "itchyny/vim-qfedit"
-- liquid support
Plug "tpope/vim-liquid"
Plug("othree/yajs.vim", {["for"] = {"javascript", "javascript.jsx", "html"}})
-- Plug 'pangloss/vim-javascript', { 'for': ['javascript', 'javascript.jsx', 'html'] }
Plug("moll/vim-node", {["for"] = "javascript"})
Plug "MaxMEllon/vim-jsx-pretty"
g.vim_jsx_pretty_highlight_close_tag = 1
Plug("leafgarland/typescript-vim", {["for"] = {"typescript", "typescript.tsx"}})
Plug("wavded/vim-stylus", {["for"] = {"stylus", "markdown"}})
Plug("groenewege/vim-less", {["for"] = "less"})
Plug("hail2u/vim-css3-syntax", {["for"] = "css"})
Plug("cakebaker/scss-syntax.vim", {["for"] = "scss"})
Plug("stephenway/postcss.vim", {["for"] = "css"})
Plug "udalov/kotlin-vim"
-- Open markdown files in Marked.app - mapped to <leader>m
Plug("itspriddle/vim-marked", {["for"] = "markdown", on = "MarkedOpen"})
nmap("<leader>m", ":MarkedOpen!<cr>")
nmap("<leader>mq", ":MarkedQuit<cr>")
nmap("<leader>*", "*<c-o>:%s///gn<cr>")
Plug("elzr/vim-json", {["for"] = "json"})
g.vim_json_syntax_conceal = 0
Plug "ekalinin/Dockerfile.vim"
Plug "jparise/vim-graphql"
Plug "hrsh7th/cmp-vsnip"
Plug "hrsh7th/vim-vsnip"
Plug "hrsh7th/vim-vsnip-integ"
local snippet_dir = os.getenv("DOTFILES") .. "/config/nvim/snippets"
g.vsnip_snippet_dir = snippet_dir
g.vsnip_filetypes = {
javascriptreact = {"javascript"},
typescriptreact = {"typescript"},
["typescript.tsx"] = {"typescript"}
}
-- add color highlighting to hex values
Plug "norcalli/nvim-colorizer.lua"
-- use devicons for filetypes
Plug "kyazdani42/nvim-web-devicons"
-- fast lau file drawer
Plug "kyazdani42/nvim-tree.lua"
-- Show git information in the gutter
Plug "lewis6991/gitsigns.nvim"
-- Helpers to configure the built-in Neovim LSP client
Plug "neovim/nvim-lspconfig"
-- Helpers to install LSPs and maintain them
Plug "williamboman/nvim-lsp-installer"
-- neovim completion
Plug "hrsh7th/cmp-nvim-lsp"
Plug "hrsh7th/cmp-nvim-lua"
Plug "hrsh7th/cmp-buffer"
Plug "hrsh7th/cmp-path"
Plug "hrsh7th/nvim-cmp"
-- treesitter enables an AST-like understanding of files
Plug("nvim-treesitter/nvim-treesitter", {["do"] = ":TSUpdate"})
-- show treesitter nodes
Plug "nvim-treesitter/playground"
-- enable more advanced treesitter-aware text objects
Plug "nvim-treesitter/nvim-treesitter-textobjects"
-- add rainbow highlighting to parens and brackets
Plug "p00f/nvim-ts-rainbow"
-- show nerd font icons for LSP types in completion menu
Plug "onsails/lspkind-nvim"
-- base16 syntax themes that are neovim/treesitter-aware
Plug "RRethy/nvim-base16"
-- status line plugin
Plug "feline-nvim/feline.nvim"
-- automatically complete brackets/parens/quotes
Plug "windwp/nvim-autopairs"
-- Run prettier and other formatters on save
Plug "mhartington/formatter.nvim"
-- Style the tabline without taking over how tabs and buffers work in Neovim
Plug "alvarosevilla95/luatab.nvim"
-- enable copilot support for Neovim
Plug "github/copilot.vim"
-- if a copilot-aliased version of node exists from fnm, use that
local copilot_node_command = env.FNM_DIR .. "/aliases/copilot/bin/node"
if utils.file_exists(copilot_node_command) then
-- vim.g.copilot_node_command = copilot_node_path
-- for some reason, this works but the above line does not
cmd('let g:copilot_node_command = "' .. copilot_node_command .. '"')
end
-- improve the default neovim interfaces, such as refactoring
Plug "stevearc/dressing.nvim"
-- Navigate a code base with a really slick UI
Plug "nvim-telescope/telescope.nvim"
Plug "nvim-telescope/telescope-rg.nvim"
-- Startup screen for Neovim
Plug "startup-nvim/startup.nvim"
-- fzf
Plug "$HOMEBREW_PREFIX/opt/fzf"
Plug "junegunn/fzf.vim"
-- Power telescope with FZF
Plug("nvim-telescope/telescope-fzf-native.nvim", {["do"] = "make"})
Plug "folke/trouble.nvim"
plugEnd()
-- Once the plugins have been loaded, Lua-based plugins need to be required and started up
-- For plugins with their own configuration file, that file is loaded and is responsible for
-- starting them. Otherwise, the plugin itself is required and its `setup` method is called.
require("nvim-autopairs").setup()
require("colorizer").setup()
require("plugins.telescope")
require("plugins.gitsigns")
require("plugins.trouble")
require("plugins.fzf")
require("plugins.lspconfig")
require("plugins.completion")
require("plugins.treesitter")
require("plugins.nvimtree")
require("plugins.formatter")
require("plugins.tabline")
require("plugins.feline")
require("plugins.startup")
|
fix(vim): copilot locked node version
|
fix(vim): copilot locked node version
use copilot aliased version of node for Apple Silicon
|
Lua
|
mit
|
nicknisi/dotfiles,nicknisi/dotfiles,nicknisi/dotfiles
|
537cd7359131e22a62ce99d3685da49913995d24
|
src/_premake_main.lua
|
src/_premake_main.lua
|
--
-- _premake_main.lua
-- Script-side entry point for the main program logic.
-- Copyright (c) 2002-2014 Jason Perkins and the Premake project
--
local shorthelp = "Type 'premake5 --help' for help"
local versionhelp = "premake5 (Premake Build Script Generator) %s"
_WORKING_DIR = os.getcwd()
--
-- Script-side program entry point.
--
function _premake_main()
-- Clear out any configuration scoping left over from initialization
filter {}
-- Seed the random number generator so actions don't have to do it themselves
math.randomseed(os.time())
-- Look for and run the system-wide configuration script; make sure any
-- configuration scoping gets cleared before continuing
dofileopt(_OPTIONS["systemscript"] or { "premake5-system.lua", "premake-system.lua" })
filter {}
-- The "next-gen" actions have now replaced their deprecated counterparts.
-- Provide a warning for a little while before I remove them entirely.
if _ACTION and _ACTION:endswith("ng") then
premake.warnOnce(_ACTION, "'%s' has been deprecated; use '%s' instead", _ACTION, _ACTION:sub(1, -3))
end
-- Set up the environment for the chosen action early, so side-effects
-- can be picked up by the scripts.
premake.action.set(_ACTION)
local action = premake.action.current()
-- If there is a project script available, run it to get the
-- project information, available options and actions, etc.
local hasScript = dofileopt(_OPTIONS["file"] or { "premake5.lua", "premake4.lua" })
-- Process special options
if (_OPTIONS["version"]) then
printf(versionhelp, _PREMAKE_VERSION)
return 1
end
if (_OPTIONS["help"]) then
premake.showhelp()
return 1
end
-- Validate the command-line arguments. This has to happen after the
-- script has run to allow for project-specific options
ok, err = premake.option.validate(_OPTIONS)
if not ok then
print("Error: " .. err)
return 1
end
-- If no further action is possible, show a short help message
if not _OPTIONS.interactive then
if not _ACTION then
print(shorthelp)
return 1
end
if not action then
print("Error: no such action '" .. _ACTION .. "'")
return 1
end
if not hasScript then
print("No Premake script (premake5.lua) found!")
return 1
end
end
-- "Bake" the project information, preparing it for use by the action
if action then
print("Building configurations...")
premake.oven.bake()
end
-- Run the interactive prompt, if requested
if _OPTIONS.interactive then
debug.prompt()
end
-- Sanity check the current project setup
premake.validate()
-- Hand over control to the action
printf("Running action '%s'...", action.trigger)
premake.action.call(action.trigger)
print("Done.")
return 0
end
|
--
-- _premake_main.lua
-- Script-side entry point for the main program logic.
-- Copyright (c) 2002-2014 Jason Perkins and the Premake project
--
local shorthelp = "Type 'premake5 --help' for help"
local versionhelp = "premake5 (Premake Build Script Generator) %s"
_WORKING_DIR = os.getcwd()
--
-- Script-side program entry point.
--
function _premake_main()
-- Clear out any configuration scoping left over from initialization
filter {}
-- Seed the random number generator so actions don't have to do it themselves
math.randomseed(os.time())
-- Look for and run the system-wide configuration script; make sure any
-- configuration scoping gets cleared before continuing
dofileopt(_OPTIONS["systemscript"] or { "premake5-system.lua", "premake-system.lua" })
filter {}
-- The "next-gen" actions have now replaced their deprecated counterparts.
-- Provide a warning for a little while before I remove them entirely.
if _ACTION and _ACTION:endswith("ng") then
premake.warnOnce(_ACTION, "'%s' has been deprecated; use '%s' instead", _ACTION, _ACTION:sub(1, -3))
end
-- Set up the environment for the chosen action early, so side-effects
-- can be picked up by the scripts.
premake.action.set(_ACTION)
-- If there is a project script available, run it to get the
-- project information, available options and actions, etc.
local hasScript = dofileopt(_OPTIONS["file"] or { "premake5.lua", "premake4.lua" })
-- Process special options
local action = premake.action.current()
if (_OPTIONS["version"]) then
printf(versionhelp, _PREMAKE_VERSION)
return 1
end
if (_OPTIONS["help"]) then
premake.showhelp()
return 1
end
-- Validate the command-line arguments. This has to happen after the
-- script has run to allow for project-specific options
ok, err = premake.option.validate(_OPTIONS)
if not ok then
print("Error: " .. err)
return 1
end
-- If no further action is possible, show a short help message
if not _OPTIONS.interactive then
if not _ACTION then
print(shorthelp)
return 1
end
if not action then
print("Error: no such action '" .. _ACTION .. "'")
return 1
end
if not hasScript then
print("No Premake script (premake5.lua) found!")
return 1
end
end
-- "Bake" the project information, preparing it for use by the action
if action then
print("Building configurations...")
premake.oven.bake()
end
-- Run the interactive prompt, if requested
if _OPTIONS.interactive then
debug.prompt()
end
-- Sanity check the current project setup
premake.validate()
-- Hand over control to the action
printf("Running action '%s'...", action.trigger)
premake.action.call(action.trigger)
print("Done.")
return 0
end
|
Fix action check to work with new interactive prompt
|
Fix action check to work with new interactive prompt
|
Lua
|
bsd-3-clause
|
jstewart-amd/premake-core,Blizzard/premake-core,bravnsgaard/premake-core,dcourtois/premake-core,TurkeyMan/premake-core,premake/premake-core,Blizzard/premake-core,tritao/premake-core,Zefiros-Software/premake-core,felipeprov/premake-core,sleepingwit/premake-core,Meoo/premake-core,dcourtois/premake-core,starkos/premake-core,starkos/premake-core,LORgames/premake-core,aleksijuvani/premake-core,jsfdez/premake-core,bravnsgaard/premake-core,mendsley/premake-core,CodeAnxiety/premake-core,tvandijck/premake-core,starkos/premake-core,jstewart-amd/premake-core,grbd/premake-core,noresources/premake-core,CodeAnxiety/premake-core,CodeAnxiety/premake-core,Yhgenomics/premake-core,TurkeyMan/premake-core,premake/premake-core,mandersan/premake-core,jsfdez/premake-core,dcourtois/premake-core,jsfdez/premake-core,martin-traverse/premake-core,martin-traverse/premake-core,LORgames/premake-core,saberhawk/premake-core,mandersan/premake-core,bravnsgaard/premake-core,PlexChat/premake-core,Yhgenomics/premake-core,martin-traverse/premake-core,aleksijuvani/premake-core,aleksijuvani/premake-core,soundsrc/premake-core,Tiger66639/premake-core,lizh06/premake-core,mendsley/premake-core,saberhawk/premake-core,jstewart-amd/premake-core,starkos/premake-core,xriss/premake-core,mandersan/premake-core,LORgames/premake-core,lizh06/premake-core,kankaristo/premake-core,alarouche/premake-core,starkos/premake-core,premake/premake-core,Tiger66639/premake-core,felipeprov/premake-core,PlexChat/premake-core,soundsrc/premake-core,tvandijck/premake-core,felipeprov/premake-core,Zefiros-Software/premake-core,alarouche/premake-core,Blizzard/premake-core,tvandijck/premake-core,tritao/premake-core,CodeAnxiety/premake-core,Blizzard/premake-core,xriss/premake-core,Meoo/premake-core,resetnow/premake-core,prapin/premake-core,mandersan/premake-core,tritao/premake-core,noresources/premake-core,tvandijck/premake-core,PlexChat/premake-core,resetnow/premake-core,TurkeyMan/premake-core,premake/premake-core,sleepingwit/premake-core,soundsrc/premake-core,TurkeyMan/premake-core,dcourtois/premake-core,Meoo/premake-core,prapin/premake-core,LORgames/premake-core,xriss/premake-core,tritao/premake-core,felipeprov/premake-core,LORgames/premake-core,aleksijuvani/premake-core,PlexChat/premake-core,saberhawk/premake-core,tvandijck/premake-core,Blizzard/premake-core,soundsrc/premake-core,akaStiX/premake-core,jstewart-amd/premake-core,grbd/premake-core,aleksijuvani/premake-core,noresources/premake-core,saberhawk/premake-core,jstewart-amd/premake-core,dcourtois/premake-core,mandersan/premake-core,kankaristo/premake-core,Yhgenomics/premake-core,sleepingwit/premake-core,premake/premake-core,soundsrc/premake-core,Zefiros-Software/premake-core,grbd/premake-core,Zefiros-Software/premake-core,CodeAnxiety/premake-core,mendsley/premake-core,Tiger66639/premake-core,martin-traverse/premake-core,prapin/premake-core,akaStiX/premake-core,akaStiX/premake-core,dcourtois/premake-core,noresources/premake-core,Meoo/premake-core,resetnow/premake-core,premake/premake-core,starkos/premake-core,TurkeyMan/premake-core,kankaristo/premake-core,lizh06/premake-core,Tiger66639/premake-core,noresources/premake-core,dcourtois/premake-core,xriss/premake-core,noresources/premake-core,akaStiX/premake-core,sleepingwit/premake-core,xriss/premake-core,resetnow/premake-core,mendsley/premake-core,starkos/premake-core,alarouche/premake-core,bravnsgaard/premake-core,grbd/premake-core,sleepingwit/premake-core,bravnsgaard/premake-core,Zefiros-Software/premake-core,resetnow/premake-core,noresources/premake-core,mendsley/premake-core,lizh06/premake-core,Yhgenomics/premake-core,premake/premake-core,prapin/premake-core,kankaristo/premake-core,alarouche/premake-core,jsfdez/premake-core,Blizzard/premake-core
|
a06a691ea39e61ac1a266c67bdf383996f50e6cf
|
openwrt/package/linkmeter/luasrc/model/cbi/linkmeter/alarm-scripts.lua
|
openwrt/package/linkmeter/luasrc/model/cbi/linkmeter/alarm-scripts.lua
|
require "luci.fs"
require "luci.sys"
require "lmclient"
local SCRIPT_PATH = "/usr/share/linkmeter/alarm-"
local function isexec_cfgvalue(self)
return luci.fs.access(SCRIPT_PATH .. self.config, "x") and "1"
end
local function isexec_write(self, section, value)
self.value = value
local curmode = luci.fs.stat(SCRIPT_PATH .. self.config)
value = value == "1" and 755 or 644
if curmode and curmode.modedec ~= value then
luci.fs.chmod(SCRIPT_PATH .. self.config, value)
end
end
local function script_cfgvalue(self)
return luci.fs.readfile(SCRIPT_PATH .. self.config) or ""
end
local function script_write(self, section, value)
-- BRY: Note to self. If you make one big form out of the page,
-- value becomes an indexed table with a string entry for each textbox
local old = self:cfgvalue()
value = value:gsub("\r\n", "\n")
if old ~= value then
luci.fs.writefile(SCRIPT_PATH .. self.config, value)
-- If there was no file previously re-call the isexec handler
-- as it executes before this handler and there was not a file then
if old == "" then self.isexec:write(section, self.isexec.value) end
end
end
local scriptitems = {
{ fname = "all", title = "All Alarm Script", desc =
[[This script is run when HeaterMeter signals any alarm before any
specific script below is executed. If the 'All' script returns non-zero
the alarm-specific script will not be run.
<a href="https://github.com/CapnBry/HeaterMeter/wiki/Alarm-Script-Recipes"
target="wiki">
Example scripts</a>
can be found in the HeaterMeter wiki.
If using sendmail in your scripts, make sure your <a href="]] ..
luci.dispatcher.build_url("admin/services/msmtp") ..
[[">SMTP Client</a> is configured as well.]] },
}
-- Get the probe names (separated by newline) and split into an array
local pnamestr = LmClient():query("$LMGT,pn0,,pn1,,pn2,,pn3") or ""
local pnames = {}
for p in pnamestr:gmatch("([^\n]+)\n?") do
pnames[#pnames+1] = p
end
for i = 0, 3 do
local pname = pnames[i+1] or "Probe " .. i
for _, j in pairs({ "Low", "High" }) do
scriptitems[#scriptitems+1] = { fname = i..j:sub(1,1),
title = pname .. " " .. j }
end
end
local retVal = {}
for i, item in pairs(scriptitems) do
local f = SimpleForm(item.fname, item.title, item.desc)
local isexec = f:field(Flag, "isexec", "Execute on alarm")
isexec.default = "0"
isexec.rmempty = nil
isexec.cfgvalue = isexec_cfgvalue
isexec.write = isexec_write
local fld = f:field(TextValue, "script")
fld.isexec = isexec
fld.rmempty = nil
fld.optional = true
fld.rows = 10
fld.cfgvalue = script_cfgvalue
fld.write = script_write
retVal[#retVal+1] = f
end -- for file
return unpack(retVal)
|
require "luci.fs"
require "luci.sys"
require "lmclient"
local SCRIPT_PATH = "/usr/share/linkmeter/alarm-"
local function isexec_cfgvalue(self)
return luci.fs.access(SCRIPT_PATH .. self.config, "x") and "1"
end
local function isexec_write(self, section, value)
self.value = value
local curmode = luci.fs.stat(SCRIPT_PATH .. self.config)
value = value == "1" and 755 or 644
if curmode and curmode.modedec ~= value then
luci.fs.chmod(SCRIPT_PATH .. self.config, value)
end
end
local function script_cfgvalue(self)
return luci.fs.readfile(SCRIPT_PATH .. self.config) or ""
end
local function script_write(self, section, value)
-- BRY: Note to self. If you make one big form out of the page,
-- value becomes an indexed table with a string entry for each textbox
local old = self:cfgvalue()
value = value:gsub("\r\n", "\n")
if old ~= value then
luci.fs.writefile(SCRIPT_PATH .. self.config, value)
-- If there was no file previously re-call the isexec handler
-- as it executes before this handler and there was not a file then
if old == "" then self.isexec:write(section, self.isexec.value) end
end
end
local function script_remove(self, section)
luci.fs.unlink(SCRIPT_PATH .. self.config)
end
local scriptitems = {
{ fname = "all", title = "All Alarm Script", desc =
[[This script is run when HeaterMeter signals any alarm before any
specific script below is executed. If the 'All' script returns non-zero
the alarm-specific script will not be run.
<a href="https://github.com/CapnBry/HeaterMeter/wiki/Alarm-Script-Recipes"
target="wiki">
Example scripts</a>
can be found in the HeaterMeter wiki.
If using sendmail in your scripts, make sure your <a href="]] ..
luci.dispatcher.build_url("admin/services/msmtp") ..
[[">SMTP Client</a> is configured as well.]] },
}
-- Get the probe names (separated by newline) and split into an array
local pnamestr = LmClient():query("$LMGT,pn0,,pn1,,pn2,,pn3") or ""
local pnames = {}
for p in pnamestr:gmatch("([^\n]+)\n?") do
pnames[#pnames+1] = p
end
for i = 0, 3 do
local pname = pnames[i+1] or "Probe " .. i
for _, j in pairs({ "Low", "High" }) do
scriptitems[#scriptitems+1] = { fname = i..j:sub(1,1),
title = pname .. " " .. j }
end
end
local retVal = {}
for i, item in pairs(scriptitems) do
local f = SimpleForm(item.fname, item.title, item.desc)
local isexec = f:field(Flag, "isexec", "Execute on alarm")
isexec.default = "0"
isexec.rmempty = nil
isexec.cfgvalue = isexec_cfgvalue
isexec.write = isexec_write
local fld = f:field(TextValue, "script")
fld.isexec = isexec
fld.optional = true
fld.rows = 10
fld.cfgvalue = script_cfgvalue
fld.write = script_write
fld.remove = script_remove
retVal[#retVal+1] = f
end -- for file
return unpack(retVal)
|
[lm] Fix inabilty to fully remove an alarm script
|
[lm] Fix inabilty to fully remove an alarm script
|
Lua
|
mit
|
CapnBry/HeaterMeter,shmick/HeaterMeter,CapnBry/HeaterMeter,CapnBry/HeaterMeter,dwright134/HeaterMeter,CapnBry/HeaterMeter,kdakers80/HeaterMeter,shmick/HeaterMeter,dwright134/HeaterMeter,CapnBry/HeaterMeter,kdakers80/HeaterMeter,kdakers80/HeaterMeter,shmick/HeaterMeter,shmick/HeaterMeter,dwright134/HeaterMeter,CapnBry/HeaterMeter,dwright134/HeaterMeter,kdakers80/HeaterMeter,shmick/HeaterMeter,dwright134/HeaterMeter,shmick/HeaterMeter,dwright134/HeaterMeter,kdakers80/HeaterMeter,shmick/HeaterMeter,CapnBry/HeaterMeter,kdakers80/HeaterMeter
|
f415273b50e655e2945d6a7c2fb50c48c7e65efc
|
premake5.lua
|
premake5.lua
|
local build_dir = "build/" .. _ACTION
--------------------------------------------------------------------------------
solution "Format"
configurations { "release", "debug" }
architecture "x64"
location (build_dir)
objdir (build_dir .. "/obj")
warnings "Extra"
exceptionhandling "Off"
rtti "Off"
configuration { "debug" }
targetdir (build_dir .. "/bin/debug")
configuration { "release" }
targetdir (build_dir .. "/bin/release")
configuration { "debug" }
defines { "_DEBUG" }
symbols "On"
configuration { "release" }
defines { "NDEBUG" }
symbols "On"
optimize "Full"
-- On ==> -O2
-- Full ==> -O3
configuration { "gmake" }
buildoptions {
"-march=native",
"-std=c++11",
"-Wformat",
-- "-Wsign-compare",
-- "-Wsign-conversion",
-- "-pedantic",
-- "-fvisibility=hidden",
-- "-fno-omit-frame-pointer",
-- "-ftime-report",
}
configuration { "gmake", "debug", "linux" }
buildoptions {
-- "-fno-omit-frame-pointer",
-- "-fsanitize=undefined",
-- "-fsanitize=address",
-- "-fsanitize=memory",
-- "-fsanitize-memory-track-origins",
}
linkoptions {
-- "-fsanitize=undefined",
-- "-fsanitize=address",
-- "-fsanitize=memory",
}
configuration { "vs*" }
buildoptions {
-- "/std:c++latest",
"/EHsc",
-- "/arch:AVX2",
-- "/GR-",
}
defines {
-- "_CRT_SECURE_NO_WARNINGS=1",
-- "_SCL_SECURE_NO_WARNINGS=1",
"_HAS_EXCEPTIONS=0",
}
configuration { "windows" }
characterset "Unicode"
--------------------------------------------------------------------------------
group "Libs"
project "fmtxx"
language "C++"
kind "SharedLib"
files {
"src/**.h",
"src/**.cc",
}
defines {
"FMTXX_SHARED=1",
"FMTXX_EXPORT=1",
}
includedirs {
"src/",
}
configuration { "gmake" }
buildoptions {
"-Wsign-compare",
"-Wsign-conversion",
"-Wold-style-cast",
"-pedantic",
"-fvisibility=hidden",
}
project "gtest"
language "C++"
kind "StaticLib"
files {
"test/ext/googletest/googletest/src/*.cc",
"test/ext/googletest/googletest/src/*.h",
}
excludes {
"test/ext/googletest/googletest/src/gtest_main.cc",
}
includedirs {
"test/ext/googletest/googletest/",
"test/ext/googletest/googletest/include/",
}
project "gtest_main"
language "C++"
kind "StaticLib"
files {
"test/ext/googletest/googletest/src/gtest_main.cc",
}
includedirs {
"test/ext/googletest/googletest/include/",
}
links {
"gtest",
}
project "fmt"
language "C++"
kind "SharedLib"
files {
"ext/fmt/**.h",
"ext/fmt/**.cc",
}
defines {
"FMT_SHARED=1",
"FMT_EXPORT=1",
}
includedirs {
"ext/",
}
--------------------------------------------------------------------------------
group "Tests"
project "Test"
language "C++"
kind "ConsoleApp"
files {
"test/Test.cc",
}
defines {
"FMTXX_SHARED=1",
}
includedirs {
"src/",
"test/ext/googletest/googletest/include/",
}
links {
"fmtxx",
"gtest",
"gtest_main",
}
function AddExampleProject(name)
project (name)
language "C++"
kind "ConsoleApp"
files {
"test/" .. name .. ".cc",
}
defines {
"FMTXX_SHARED=1",
}
includedirs {
"src/",
}
links {
"fmtxx",
}
end
AddExampleProject("Example1")
AddExampleProject("Example2")
AddExampleProject("Example3")
AddExampleProject("Example4")
AddExampleProject("Example5")
-- Doesn't work with MinGW (std::condition_variable not implemented...)
-- project "Benchmark"
-- language "C++"
-- kind "ConsoleApp"
-- files {
-- "test/Bench.cc",
-- "test/ext/benchmark/include/benchmark/*.h",
-- "test/ext/benchmark/src/*.cc",
-- }
-- defines {
-- "HAVE_STD_REGEX=1",
-- "FMTXX_SHARED=1",
-- }
-- includedirs {
-- "src/",
-- "test/ext/",
-- "test/ext/benchmark/include/",
-- }
-- links {
-- "fmtxx",
-- }
-- configuration { "vs*" }
-- links {
-- "shlwapi",
-- }
-- configuration { "not vs*" }
-- links {
-- "pthread",
-- }
|
local build_dir = "build/" .. _ACTION
--------------------------------------------------------------------------------
solution "Format"
configurations { "release", "debug" }
architecture "x64"
location (build_dir)
objdir (build_dir .. "/obj")
warnings "Extra"
exceptionhandling "Off"
rtti "Off"
configuration { "debug" }
targetdir (build_dir .. "/bin/debug")
configuration { "release" }
targetdir (build_dir .. "/bin/release")
configuration { "debug" }
defines { "_DEBUG" }
symbols "On"
configuration { "release" }
defines { "NDEBUG" }
symbols "On"
optimize "Full"
-- On ==> -O2
-- Full ==> -O3
configuration { "gmake" }
buildoptions {
"-march=native",
"-std=c++11",
"-Wformat",
-- "-Wsign-compare",
-- "-Wsign-conversion",
-- "-pedantic",
-- "-fvisibility=hidden",
-- "-fno-omit-frame-pointer",
-- "-ftime-report",
}
configuration { "gmake", "debug", "linux" }
buildoptions {
-- "-fno-omit-frame-pointer",
-- "-fsanitize=undefined",
-- "-fsanitize=address",
-- "-fsanitize=memory",
-- "-fsanitize-memory-track-origins",
}
linkoptions {
-- "-fsanitize=undefined",
-- "-fsanitize=address",
-- "-fsanitize=memory",
}
configuration { "vs*" }
buildoptions {
-- "/std:c++latest",
"/EHsc",
-- "/arch:AVX2",
-- "/GR-",
}
defines {
-- "_CRT_SECURE_NO_WARNINGS=1",
-- "_SCL_SECURE_NO_WARNINGS=1",
"_HAS_EXCEPTIONS=0",
}
configuration { "windows" }
characterset "Unicode"
--------------------------------------------------------------------------------
group "Libs"
project "fmtxx"
language "C++"
kind "SharedLib"
files {
"src/**.h",
"src/**.cc",
}
defines {
"FMTXX_SHARED=1",
"FMTXX_EXPORT=1",
}
includedirs {
"src/",
}
configuration { "gmake" }
buildoptions {
"-Wsign-compare",
"-Wsign-conversion",
"-Wold-style-cast",
"-pedantic",
"-fvisibility=hidden",
}
project "gtest"
language "C++"
kind "StaticLib"
files {
"test/ext/googletest/googletest/src/gtest-all.cc",
}
includedirs {
"test/ext/googletest/googletest/",
"test/ext/googletest/googletest/include/",
}
project "gtest_main"
language "C++"
kind "StaticLib"
files {
"test/ext/googletest/googletest/src/gtest_main.cc",
}
includedirs {
"test/ext/googletest/googletest/include/",
}
links {
"gtest",
}
-- project "fmt"
-- language "C++"
-- kind "SharedLib"
-- files {
-- "ext/fmt/**.h",
-- "ext/fmt/**.cc",
-- }
-- defines {
-- "FMT_SHARED=1",
-- "FMT_EXPORT=1",
-- }
-- includedirs {
-- "ext/",
-- }
--------------------------------------------------------------------------------
group "Tests"
project "Test"
language "C++"
kind "ConsoleApp"
files {
"test/Test.cc",
}
defines {
"FMTXX_SHARED=1",
}
includedirs {
"src/",
"test/ext/googletest/googletest/include/",
}
links {
"fmtxx",
"gtest",
"gtest_main",
}
function AddExampleProject(name)
project (name)
language "C++"
kind "ConsoleApp"
files {
"test/" .. name .. ".cc",
}
defines {
"FMTXX_SHARED=1",
}
includedirs {
"src/",
}
links {
"fmtxx",
}
end
AddExampleProject("Example1")
AddExampleProject("Example2")
AddExampleProject("Example3")
AddExampleProject("Example4")
AddExampleProject("Example5")
-- Doesn't work with MinGW (std::condition_variable not implemented...)
-- project "Benchmark"
-- language "C++"
-- kind "ConsoleApp"
-- files {
-- "test/Bench.cc",
-- "test/ext/benchmark/include/benchmark/*.h",
-- "test/ext/benchmark/src/*.cc",
-- }
-- defines {
-- "HAVE_STD_REGEX=1",
-- "FMTXX_SHARED=1",
-- }
-- includedirs {
-- "src/",
-- "test/ext/",
-- "test/ext/benchmark/include/",
-- }
-- links {
-- "fmtxx",
-- }
-- configuration { "vs*" }
-- links {
-- "shlwapi",
-- }
-- configuration { "not vs*" }
-- links {
-- "pthread",
-- }
|
Fix build script
|
Fix build script
|
Lua
|
mit
|
abolz/Format
|
9c7a9cf059bda9011bdb96158875be53b369a646
|
src/extensions/cp/apple/finalcutpro/browser/AppearanceAndFiltering.lua
|
src/extensions/cp/apple/finalcutpro/browser/AppearanceAndFiltering.lua
|
--- === cp.apple.finalcutpro.browser.AppearanceAndFiltering ===
---
--- Clip Appearance & Filtering Menu Popover
local require = require
--local log = require("hs.logger").new("appearanceAndFiltering")
local axutils = require "cp.ui.axutils"
local Button = require "cp.ui.Button"
local CheckBox = require "cp.ui.CheckBox"
local Popover = require "cp.ui.Popover"
local PopUpButton = require "cp.ui.PopUpButton"
local Slider = require "cp.ui.Slider"
local cache = axutils.cache
local childFromRight = axutils.childFromRight
local childFromTop = axutils.childFromTop
local childMatching = axutils.childMatching
local childrenWithRole = axutils.childrenWithRole
local AppearanceAndFiltering = Popover:subclass("cp.apple.finalcutpro.browser.AppearanceAndFiltering")
--- cp.apple.finalcutpro.browser.AppearanceAndFiltering.matches(element) -> boolean
--- Function
--- Checks to see if a GUI element is the "Clip Appearance & Filtering Menu" popover or not.
---
--- Parameters:
--- * element - The element you want to check
---
--- Returns:
--- * `true` if the `element` is the "Clip Appearance & Filtering Menu" popover otherwise `false`
function AppearanceAndFiltering.static.matches(element)
return Popover.matches(element)
end
--- cp.apple.finalcutpro.browser.AppearanceAndFiltering(parent) -> AppearanceAndFiltering
--- Constructor
--- Constructs a new "Clip Appearance & Filtering Menu" popover.
---
--- Parameters:
--- * parent - The parent object
---
--- Returns:
--- * The new `AppearanceAndFiltering` instance.
function AppearanceAndFiltering:initialize(parent)
local UI = parent.UI:mutate(function(original)
return cache(self, "_ui", function()
return childMatching(original(), AppearanceAndFiltering.matches)
end,
AppearanceAndFiltering.matches)
end)
Popover.initialize(self, parent, UI)
end
--- cp.apple.finalcutpro.browser.AppearanceAndFiltering.DURATION -> table
--- Constant
--- A lookup table of the duration values.
AppearanceAndFiltering.DURATION = {
["All"] = 0,
["30min"] = 1,
["10min"] = 2,
["5min"] = 3,
["2min"] = 4,
["1min"] = 5,
["30sec"] = 6,
["10sec"] = 7,
["5sec"] = 8,
["2sec"] = 9,
["1sec"] = 10,
["1/2sec"] = 11,
}
-- Local wrapper for `isWindowAnimationEnabled`.
function AppearanceAndFiltering.lazy.prop:_windowAnimation()
return self:app().isWindowAnimationEnabled
end
--- cp.apple.finalcutpro.browser.AppearanceAndFiltering:show() -> self
--- Method
--- Shows the "Clip Appearance & Filtering Menu" Popover
---
--- Parameters:
--- * None
---
--- Returns:
--- * Self
function AppearanceAndFiltering:show()
if not self:isShowing() then
local originalAnimation = self._windowAnimation:get()
self._windowAnimation:set(false)
self.button:press()
self._windowAnimation:set(originalAnimation)
end
return self
end
--- cp.apple.finalcutpro.browser.AppearanceAndFiltering:doShow() -> cp.rx.go.Statement
--- Method
--- A `Statement` that shows the Browser's "Clip Appearance & Filtering" popover.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `Statement`.
function AppearanceAndFiltering.lazy.method:doShow()
return If(self.isShowing):Is(false)
:Then(
SetProp(self._windowAnimation):To(false)
:Then(self.button:doPress())
:Then(WaitUntil(self.isShowing))
:ThenReset()
)
end
--- cp.apple.finalcutpro.browser.AppearanceAndFiltering.button <cp.ui.Button>
--- Field
--- The "Clip Appearance & Filtering Menu" button.
function AppearanceAndFiltering.lazy.value:button()
local parent = self:parent()
return Button(parent, parent.UI:mutate(function(original)
return childFromRight(childrenWithRole(original(), "AXButton"), 2)
end))
end
--- cp.apple.finalcutpro.browser.AppearanceAndFiltering.clipHeight <cp.ui.Slider>
--- Field
--- The Clip Height Slider.
function AppearanceAndFiltering.lazy.value:clipHeight()
return Slider(self, self.UI:mutate(function(original)
return childFromTop(childrenWithRole(original(), "AXSlider"), 2)
end))
end
--- cp.apple.finalcutpro.browser.AppearanceAndFiltering.duration <cp.ui.Slider>
--- Field
--- The Duration Slider.
function AppearanceAndFiltering.lazy.value:duration()
return Slider(self, self.UI:mutate(function(original)
return childFromTop(childrenWithRole(original(), "AXSlider"), 3)
end))
end
--- cp.apple.finalcutpro.browser.AppearanceAndFiltering.groupBy <cp.ui.PopUpButton>
--- Field
--- The "Group By" popup button.
function AppearanceAndFiltering.lazy.value:groupBy()
return PopUpButton(self, self.UI:mutate(function(original)
return childFromTop(childrenWithRole(original(), "AXPopUpButton"), 1)
end))
end
--- cp.apple.finalcutpro.browser.AppearanceAndFiltering.sortBy <cp.ui.PopUpButton>
--- Field
--- The "Sort By" popup button.
function AppearanceAndFiltering.lazy.value:sortBy()
return PopUpButton(self, self.UI:mutate(function(original)
return childFromTop(childrenWithRole(original(), "AXPopUpButton"), 2)
end))
end
--- cp.apple.finalcutpro.browser.AppearanceAndFiltering.waveforms <cp.ui.CheckBox>
--- Field
--- The Waveforms checkbox.
function AppearanceAndFiltering.lazy.value:waveforms()
return CheckBox(self, self.UI:mutate(function(original)
return childFromTop(childrenWithRole(original(), "AXCheckBox"), 1)
end))
end
--- cp.apple.finalcutpro.browser.AppearanceAndFiltering.continuousPlayback <cp.ui.CheckBox>
--- Field
--- The Continuous Playback checkbox.
function AppearanceAndFiltering.lazy.value:continuousPlayback()
return CheckBox(self, self.UI:mutate(function(original)
return childFromTop(childrenWithRole(original(), "AXCheckBox"), 2)
end))
end
return AppearanceAndFiltering
|
--- === cp.apple.finalcutpro.browser.AppearanceAndFiltering ===
---
--- Clip Appearance & Filtering Menu Popover
local require = require
--local log = require("hs.logger").new("appearanceAndFiltering")
local axutils = require "cp.ui.axutils"
local Button = require "cp.ui.Button"
local CheckBox = require "cp.ui.CheckBox"
local Popover = require "cp.ui.Popover"
local PopUpButton = require "cp.ui.PopUpButton"
local Slider = require "cp.ui.Slider"
local go = require "cp.rx.go"
local If = go.If
local SetProp = go.SetProp
local WaitUntil = go.WaitUntil
local cache = axutils.cache
local childFromRight = axutils.childFromRight
local childFromTop = axutils.childFromTop
local childMatching = axutils.childMatching
local childrenWithRole = axutils.childrenWithRole
local AppearanceAndFiltering = Popover:subclass("cp.apple.finalcutpro.browser.AppearanceAndFiltering")
--- cp.apple.finalcutpro.browser.AppearanceAndFiltering.matches(element) -> boolean
--- Function
--- Checks to see if a GUI element is the "Clip Appearance & Filtering Menu" popover or not.
---
--- Parameters:
--- * element - The element you want to check
---
--- Returns:
--- * `true` if the `element` is the "Clip Appearance & Filtering Menu" popover otherwise `false`
function AppearanceAndFiltering.static.matches(element)
return Popover.matches(element)
end
--- cp.apple.finalcutpro.browser.AppearanceAndFiltering(parent) -> AppearanceAndFiltering
--- Constructor
--- Constructs a new "Clip Appearance & Filtering Menu" popover.
---
--- Parameters:
--- * parent - The parent object
---
--- Returns:
--- * The new `AppearanceAndFiltering` instance.
function AppearanceAndFiltering:initialize(parent)
local UI = parent.UI:mutate(function(original)
return cache(self, "_ui", function()
return childMatching(original(), AppearanceAndFiltering.matches)
end,
AppearanceAndFiltering.matches)
end)
Popover.initialize(self, parent, UI)
end
--- cp.apple.finalcutpro.browser.AppearanceAndFiltering.DURATION -> table
--- Constant
--- A lookup table of the duration values.
AppearanceAndFiltering.DURATION = {
["All"] = 0,
["30min"] = 1,
["10min"] = 2,
["5min"] = 3,
["2min"] = 4,
["1min"] = 5,
["30sec"] = 6,
["10sec"] = 7,
["5sec"] = 8,
["2sec"] = 9,
["1sec"] = 10,
["1/2sec"] = 11,
}
-- Local wrapper for `isWindowAnimationEnabled`.
function AppearanceAndFiltering.lazy.prop:_windowAnimation()
return self:app().isWindowAnimationEnabled
end
--- cp.apple.finalcutpro.browser.AppearanceAndFiltering:show() -> self
--- Method
--- Shows the "Clip Appearance & Filtering Menu" Popover
---
--- Parameters:
--- * None
---
--- Returns:
--- * Self
function AppearanceAndFiltering:show()
if not self:isShowing() then
local originalAnimation = self._windowAnimation:get()
self._windowAnimation:set(false)
self.button:press()
self._windowAnimation:set(originalAnimation)
end
return self
end
--- cp.apple.finalcutpro.browser.AppearanceAndFiltering:doShow() -> cp.rx.go.Statement
--- Method
--- A `Statement` that shows the Browser's "Clip Appearance & Filtering" popover.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `Statement`.
function AppearanceAndFiltering.lazy.method:doShow()
return If(self.isShowing):Is(false)
:Then(
SetProp(self._windowAnimation):To(false)
:Then(self.button:doPress())
:Then(WaitUntil(self.isShowing))
:ThenReset()
)
end
--- cp.apple.finalcutpro.browser.AppearanceAndFiltering.button <cp.ui.Button>
--- Field
--- The "Clip Appearance & Filtering Menu" button.
function AppearanceAndFiltering.lazy.value:button()
local parent = self:parent()
return Button(parent, parent.UI:mutate(function(original)
return childFromRight(childrenWithRole(original(), "AXButton"), 2)
end))
end
--- cp.apple.finalcutpro.browser.AppearanceAndFiltering.clipHeight <cp.ui.Slider>
--- Field
--- The Clip Height Slider.
function AppearanceAndFiltering.lazy.value:clipHeight()
return Slider(self, self.UI:mutate(function(original)
return childFromTop(childrenWithRole(original(), "AXSlider"), 2)
end))
end
--- cp.apple.finalcutpro.browser.AppearanceAndFiltering.duration <cp.ui.Slider>
--- Field
--- The Duration Slider.
function AppearanceAndFiltering.lazy.value:duration()
return Slider(self, self.UI:mutate(function(original)
return childFromTop(childrenWithRole(original(), "AXSlider"), 3)
end))
end
--- cp.apple.finalcutpro.browser.AppearanceAndFiltering.groupBy <cp.ui.PopUpButton>
--- Field
--- The "Group By" popup button.
function AppearanceAndFiltering.lazy.value:groupBy()
return PopUpButton(self, self.UI:mutate(function(original)
return childFromTop(childrenWithRole(original(), "AXPopUpButton"), 1)
end))
end
--- cp.apple.finalcutpro.browser.AppearanceAndFiltering.sortBy <cp.ui.PopUpButton>
--- Field
--- The "Sort By" popup button.
function AppearanceAndFiltering.lazy.value:sortBy()
return PopUpButton(self, self.UI:mutate(function(original)
return childFromTop(childrenWithRole(original(), "AXPopUpButton"), 2)
end))
end
--- cp.apple.finalcutpro.browser.AppearanceAndFiltering.waveforms <cp.ui.CheckBox>
--- Field
--- The Waveforms checkbox.
function AppearanceAndFiltering.lazy.value:waveforms()
return CheckBox(self, self.UI:mutate(function(original)
return childFromTop(childrenWithRole(original(), "AXCheckBox"), 1)
end))
end
--- cp.apple.finalcutpro.browser.AppearanceAndFiltering.continuousPlayback <cp.ui.CheckBox>
--- Field
--- The Continuous Playback checkbox.
function AppearanceAndFiltering.lazy.value:continuousPlayback()
return CheckBox(self, self.UI:mutate(function(original)
return childFromTop(childrenWithRole(original(), "AXCheckBox"), 2)
end))
end
return AppearanceAndFiltering
|
Fixed missing modules in Appearance & Filtering
|
Fixed missing modules in Appearance & Filtering
|
Lua
|
mit
|
CommandPost/CommandPost,CommandPost/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost,fcpxhacks/fcpxhacks
|
36bf7d8b882523b5365dab449cbd0699e05857a2
|
.config/awesome/widgets/mpd.lua
|
.config/awesome/widgets/mpd.lua
|
local awful = require("awful")
local utils = require("utils")
local lain = require("lain")
local wibox = require("wibox")
local icons = require("icons")
local BaseWidget = require("widgets.base").BaseWidget
local MPDWidget = BaseWidget.derive()
local mpdmenu = awful.menu({
items = {
{ "Play/Pause", "mpc toggle" },
{ "Stop", "mpc stop" },
{ "Next", "mpc next" },
{ "Previous", "mpc prev" },
{ "Toggle random", "mpc random" },
{ "Toggle repeat", "mpc repeat" },
{ "Toggle single", "mpc single" },
},
theme = { width = 120 }
})
-- Strips the path part from the filename
local function getFilename(fname)
-- The '/' at the beginning of the filename ensures that the regex will
-- also work for files in the root of the music directory (which don't
-- have any '/' inside their filename).
return ("/" .. fname):match(".*/(.*)")
end
local function prettyTime(seconds)
if not seconds then
return -1
end
local sec = (seconds % 60)
return math.floor(seconds / 60) .. ":" .. (sec < 10 and "0" or "") .. sec
end
function MPDWidget:create(args)
args = args or {}
args.settings = function() self:updateText() end
self.lainwidget = lain.widgets.mpd(args)
local widget = wibox.container.constraint(self.lainwidget.widget, "max", 125, nil)
widget.widget:set_align("right")
local box = self:init(widget, args.icon or icons.mpd)
self:attach(box)
end
function MPDWidget:update()
self.lainwidget.update()
end
function MPDWidget:updateText()
self.data = mpd_now
if mpd_now.state == "stop" then
widget:set_markup("")
return
elseif mpd_now.title == "N/A" then
widget:set_markup(getFilename(self.data.file))
else
widget:set_markup(mpd_now.title)
end
end
function MPDWidget:attach(box)
box:buttons(awful.util.table.join(
awful.button({}, 1, function() utils.toggle_run_term("ncmpcpp -s visualizer") end),
awful.button({}, 3, function() mpdmenu:toggle() end),
awful.button({}, 4, function() awful.spawn("mpc volume +2") end),
awful.button({}, 5, function() awful.spawn("mpc volume -2") end)
))
utils.registerPopupNotify(box, "MPD", function(w)
return "Title:\t\t" .. self.data.title ..
"\nAlbum:\t" .. self.data.album ..
"\nArtist:\t" .. self.data.artist ..
"\nGenre:\t" .. self.data.genre ..
"\nFile:\t\t" .. getFilename(self.data.file) ..
"\nState:\t" .. self.data.state ..
"\nLength:\t" .. prettyTime(tonumber(self.data.time))
end)
end
return MPDWidget
|
local awful = require("awful")
local utils = require("utils")
local lain = require("lain")
local wibox = require("wibox")
local icons = require("icons")
local BaseWidget = require("widgets.base").BaseWidget
local MPDWidget = BaseWidget.derive()
local mpdmenu = awful.menu({
items = {
{ "Play/Pause", "mpc toggle" },
{ "Stop", "mpc stop" },
{ "Next", "mpc next" },
{ "Previous", "mpc prev" },
{ "Toggle random", "mpc random" },
{ "Toggle repeat", "mpc repeat" },
{ "Toggle single", "mpc single" },
},
theme = { width = 120 }
})
-- Strips the path part from the filename
local function getFilename(fname)
-- The '/' at the beginning of the filename ensures that the regex will
-- also work for files in the root of the music directory (which don't
-- have any '/' inside their filename).
return ("/" .. fname):match(".*/(.*)")
end
local function prettyTime(seconds)
if not seconds then
return -1
end
local sec = (seconds % 60)
return math.floor(seconds / 60) .. ":" .. (sec < 10 and "0" or "") .. sec
end
function MPDWidget:create(args)
args = args or {}
args.settings = function() self:updateText() end
self.lainwidget = lain.widgets.mpd(args)
local widget = wibox.container.constraint(self.lainwidget.widget, "max", 125, nil)
widget.widget:set_align("right")
local box = self:init(widget, args.icon or icons.mpd)
self:attach(box)
end
function MPDWidget:update()
self.lainwidget.update()
end
function MPDWidget:updateText()
self.data = mpd_now
if mpd_now.state == "stop" then
widget:set_text("")
elseif mpd_now.title == "N/A" then
widget:set_text(getFilename(self.data.file))
else
widget:set_text(mpd_now.title)
end
end
function MPDWidget:attach(box)
box:buttons(awful.util.table.join(
awful.button({}, 1, function() utils.toggle_run_term("ncmpcpp -s visualizer") end),
awful.button({}, 3, function() mpdmenu:toggle() end),
awful.button({}, 4, function() awful.spawn("mpc volume +2") end),
awful.button({}, 5, function() awful.spawn("mpc volume -2") end)
))
utils.registerPopupNotify(box, "MPD", function(w)
return "Title:\t\t" .. self.data.title ..
"\nAlbum:\t" .. self.data.album ..
"\nArtist:\t" .. self.data.artist ..
"\nGenre:\t" .. self.data.genre ..
"\nFile:\t\t" .. getFilename(self.data.file) ..
"\nState:\t" .. self.data.state ..
"\nLength:\t" .. prettyTime(tonumber(self.data.time))
end)
end
return MPDWidget
|
[Awesome] Fix MPD widget text not updating
|
[Awesome] Fix MPD widget text not updating
widget:set_markup(...) sometiems failed because the string contains
characters that need to be escaped.
|
Lua
|
mit
|
mphe/dotfiles,mall0c/dotfiles,mphe/dotfiles,mphe/dotfiles,mphe/dotfiles,mphe/dotfiles,mphe/dotfiles,mall0c/dotfiles
|
ffb4cf164449e029aeb4269c501366e2eb483798
|
src/core/shm.lua
|
src/core/shm.lua
|
-- shm.lua -- shared memory alternative to ffi.new()
-- API:
-- shm.map(name, type[, readonly]) => ptr
-- Map a shared object into memory via a heirarchical name.
-- shm.unmap(ptr)
-- Delete a memory mapping.
-- shm.unlink(path)
-- Unlink a subtree of objects from the filesystem.
--
-- (See NAME SYNTAX below for recognized name formats.)
--
-- Example:
-- local freelist = shm.map("engine/freelist/packet", "struct freelist")
--
-- This is like ffi.new() except that separate calls to map() for the
-- same name will each return a new mapping of the same shared
-- memory. Different processes can share memory by mapping an object
-- with the same name (and type). Each process can map any object any
-- number of times.
--
-- Mappings are deleted on process termination or with an explicit unmap:
-- shm.unmap(freelist)
--
-- Names are unlinked from objects that are no longer needed:
-- shm.unlink("engine/freelist/packet")
-- shm.unlink("engine")
--
-- Object memory is freed when the name is unlinked and all mappings
-- have been deleted.
--
-- Behind the scenes the objects are backed by files on ram disk:
-- /var/run/snabb/$pid/engine/freelist/packet
--
-- and accessed with the equivalent of POSIX shared memory (shm_overview(7)).
--
-- The practical limit on the number of objects that can be mapped
-- will depend on the operating system limit for memory mappings.
-- On Linux the default limit is 65,530 mappings:
-- $ sysctl vm.max_map_count
-- vm.max_map_count = 65530
-- NAME SYNTAX:
--
-- Names can be fully qualified, abbreviated to be within the current
-- process, or further abbreviated to be relative to the current value
-- of the 'path' variable. Here are examples of names and how they are
-- resolved:
-- Fully qualified:
-- //snabb/1234/foo/bar => /var/run/snabb/1234/foo/bar
-- Path qualified:
-- /foo/bar => /var/run/snabb/$pid/foo/bar
-- Local:
-- bar => /var/run/snabb/$pid/$path/bar
-- .. where $pid is the PID of this process and $path is the current
-- value of the 'path' variable in this module.
module(..., package.seeall)
local ffi = require("ffi")
local lib = require("core.lib")
local S = require("syscall")
-- Root directory where the object tree is created.
root = "/var/run/snabb"
path = ""
-- Table (address->size) of all currently mapped objects.
mappings = {}
-- Map an object into memory.
function map (name, type, readonly)
local path = resolve(name)
local mapmode = readonly and 'read' or 'read, write'
local ctype = ffi.typeof(type)
local size = ffi.sizeof(ctype)
local stat = S.stat(root..'/'..path)
if stat and stat.size ~= size then
print(("shm warning: resizing %s from %d to %d bytes")
:format(path, stat.size, size))
end
-- Create the parent directories. If this fails then so will the open().
mkdir(path)
local fd, err = S.open(root..'/'..path, "creat, rdwr", "rwxu")
if not fd then error("shm open error ("..path.."):"..tostring(err)) end
assert(fd:ftruncate(size), "shm: ftruncate failed")
local mem, err = S.mmap(nil, size, mapmode, "shared", fd, 0)
fd:close()
if mem == nil then error("mmap failed: " .. tostring(err)) end
mappings[pointer_to_number(mem)] = size
return ffi.cast(ffi.typeof("$&", ctype), mem)
end
function resolve (name)
local result = name
-- q is qualifier ("", "/", "//")
local q, p = name:match("^(/*)(.*)")
-- Add path, if name is related and path is defined
if q == '' and path ~= '' then result = path.."/"..result end
-- Add process qualifier, unless name is fully qualified
if q ~= '//' then result = tostring(S.getpid()).."/"..result end
return result
end
-- Make directories needed for a named object.
-- Given the name "foo/bar/baz" create /var/run/foo and /var/run/foo/bar.
function mkdir (name)
local dir = root
name:gsub("([^/]+)",
function (x) S.mkdir(dir, "rwxu") dir = dir.."/"..x end)
end
-- Delete a shared object memory mapping.
-- The pointer must have been returned by map().
function unmap (ptr)
local size = mappings[pointer_to_number(ptr)]
assert(size, "shm mapping not found")
S.munmap(ptr, size)
mappings[pointer_to_number(ptr)] = nil
end
function pointer_to_number (ptr)
return tonumber(ffi.cast("uint64_t", ffi.cast("void*", ptr)))
end
-- Unlink names from their objects.
function unlink (name)
local path = resolve(name)
-- Note: Recursive delete is dangerous, important it is under $root!
return S.util.rm(root..'/'..path) -- recursive rm of file or directory
end
function selftest ()
print("selftest: shm")
print("checking paths..")
path = 'foo/bar'
pid = tostring(S.getpid())
local p1 = resolve("//"..pid.."/foo/bar/baz/beer")
local p2 = resolve("/foo/bar/baz/beer")
local p3 = resolve("baz/beer")
assert(p1 == p2, p1.." ~= "..p2)
assert(p1 == p3, p1.." ~= "..p3)
print("checking shared memory..")
path = 'shm/selftest'
local name = "obj"
print("create "..name)
local p1 = map(name, "struct { int x, y, z; }")
local p2 = map(name, "struct { int x, y, z; }")
assert(p1 ~= p2)
assert(p1.x == p2.x)
p1.x = 42
assert(p1.x == p2.x)
assert(unlink(name))
unmap(p1)
unmap(p2)
-- Test that we can open and cleanup many objects
print("checking many objects..")
path = 'shm/selftest/manyobj'
local n = 10000
local objs = {}
for i = 1, n do
table.insert(objs, map("obj/"..i, "uint64_t[1]"))
end
print(n.." objects created")
for i = 1, n do unmap(objs[i]) end
print(n.." objects unmapped")
assert(unlink("/"))
print("selftest ok")
end
|
-- shm.lua -- shared memory alternative to ffi.new()
-- API:
-- shm.map(name, type[, readonly]) => ptr
-- Map a shared object into memory via a heirarchical name.
-- shm.unmap(ptr)
-- Delete a memory mapping.
-- shm.unlink(path)
-- Unlink a subtree of objects from the filesystem.
--
-- (See NAME SYNTAX below for recognized name formats.)
--
-- Example:
-- local freelist = shm.map("engine/freelist/packet", "struct freelist")
--
-- This is like ffi.new() except that separate calls to map() for the
-- same name will each return a new mapping of the same shared
-- memory. Different processes can share memory by mapping an object
-- with the same name (and type). Each process can map any object any
-- number of times.
--
-- Mappings are deleted on process termination or with an explicit unmap:
-- shm.unmap(freelist)
--
-- Names are unlinked from objects that are no longer needed:
-- shm.unlink("engine/freelist/packet")
-- shm.unlink("engine")
--
-- Object memory is freed when the name is unlinked and all mappings
-- have been deleted.
--
-- Behind the scenes the objects are backed by files on ram disk:
-- /var/run/snabb/$pid/engine/freelist/packet
--
-- and accessed with the equivalent of POSIX shared memory (shm_overview(7)).
--
-- The practical limit on the number of objects that can be mapped
-- will depend on the operating system limit for memory mappings.
-- On Linux the default limit is 65,530 mappings:
-- $ sysctl vm.max_map_count
-- vm.max_map_count = 65530
-- NAME SYNTAX:
--
-- Names can be fully qualified, abbreviated to be within the current
-- process, or further abbreviated to be relative to the current value
-- of the 'path' variable. Here are examples of names and how they are
-- resolved:
-- Fully qualified:
-- //snabb/1234/foo/bar => /var/run/snabb/1234/foo/bar
-- Path qualified:
-- /foo/bar => /var/run/snabb/$pid/foo/bar
-- Local:
-- bar => /var/run/snabb/$pid/$path/bar
-- .. where $pid is the PID of this process and $path is the current
-- value of the 'path' variable in this module.
module(..., package.seeall)
local ffi = require("ffi")
local lib = require("core.lib")
local S = require("syscall")
-- Root directory where the object tree is created.
root = "/var/run/snabb"
path = ""
-- Table (address->size) of all currently mapped objects.
mappings = {}
-- Map an object into memory.
function map (name, type, readonly)
local path = resolve(name)
local mapmode = readonly and 'read' or 'read, write'
local ctype = ffi.typeof(type)
local size = ffi.sizeof(ctype)
local stat = S.stat(root..'/'..path)
if stat and stat.size ~= size then
print(("shm warning: resizing %s from %d to %d bytes")
:format(path, stat.size, size))
end
-- Create the parent directories. If this fails then so will the open().
mkdir(path)
local fd, err = S.open(root..'/'..path, "creat, rdwr", "rwxu")
if not fd then error("shm open error ("..path.."):"..tostring(err)) end
assert(fd:ftruncate(size), "shm: ftruncate failed")
local mem, err = S.mmap(nil, size, mapmode, "shared", fd, 0)
fd:close()
if mem == nil then error("mmap failed: " .. tostring(err)) end
mappings[pointer_to_number(mem)] = size
return ffi.cast(ffi.typeof("$&", ctype), mem)
end
function resolve (name)
local q, p = name:match("^(/*)(.*)") -- split qualifier (/ or //)
local result = p
if q == '' and path ~= '' then result = path.."/"..result end
if q ~= '//' then result = tostring(S.getpid()).."/"..result end
return result
end
-- Make directories needed for a named object.
-- Given the name "foo/bar/baz" create /var/run/foo and /var/run/foo/bar.
function mkdir (name)
local dir = root
name:gsub("([^/]+)",
function (x) S.mkdir(dir, "rwxu") dir = dir.."/"..x end)
end
-- Delete a shared object memory mapping.
-- The pointer must have been returned by map().
function unmap (ptr)
local size = mappings[pointer_to_number(ptr)]
assert(size, "shm mapping not found")
S.munmap(ptr, size)
mappings[pointer_to_number(ptr)] = nil
end
function pointer_to_number (ptr)
return tonumber(ffi.cast("uint64_t", ffi.cast("void*", ptr)))
end
-- Unlink names from their objects.
function unlink (name)
local path = resolve(name)
-- Note: Recursive delete is dangerous, important it is under $root!
return S.util.rm(root..'/'..path) -- recursive rm of file or directory
end
function selftest ()
print("selftest: shm")
print("checking paths..")
path = 'foo/bar'
pid = tostring(S.getpid())
local p1 = resolve("//"..pid.."/foo/bar/baz/beer")
local p2 = resolve("/foo/bar/baz/beer")
local p3 = resolve("baz/beer")
assert(p1 == p2, p1.." ~= "..p2)
assert(p1 == p3, p1.." ~= "..p3)
print("checking shared memory..")
path = 'shm/selftest'
local name = "obj"
print("create "..name)
local p1 = map(name, "struct { int x, y, z; }")
local p2 = map(name, "struct { int x, y, z; }")
assert(p1 ~= p2)
assert(p1.x == p2.x)
p1.x = 42
assert(p1.x == p2.x)
assert(unlink(name))
unmap(p1)
unmap(p2)
-- Test that we can open and cleanup many objects
print("checking many objects..")
path = 'shm/selftest/manyobj'
local n = 10000
local objs = {}
for i = 1, n do
table.insert(objs, map("obj/"..i, "uint64_t[1]"))
end
print(n.." objects created")
for i = 1, n do unmap(objs[i]) end
print(n.." objects unmapped")
assert(unlink("/"))
print("selftest ok")
end
|
core.shm: Fix bug in resolve()
|
core.shm: Fix bug in resolve()
Corrected bug caught by SnabbBot and selftest(). resolve() was broken.
|
Lua
|
apache-2.0
|
plajjan/snabbswitch,SnabbCo/snabbswitch,lukego/snabbswitch,pirate/snabbswitch,andywingo/snabbswitch,pirate/snabbswitch,kbara/snabb,aperezdc/snabbswitch,snabbnfv-goodies/snabbswitch,pavel-odintsov/snabbswitch,hb9cwp/snabbswitch,Igalia/snabb,eugeneia/snabbswitch,pavel-odintsov/snabbswitch,eugeneia/snabbswitch,aperezdc/snabbswitch,aperezdc/snabbswitch,dpino/snabbswitch,virtualopensystems/snabbswitch,wingo/snabbswitch,dpino/snabbswitch,alexandergall/snabbswitch,fhanik/snabbswitch,kbara/snabb,snabbco/snabb,pavel-odintsov/snabbswitch,eugeneia/snabbswitch,wingo/snabb,dwdm/snabbswitch,mixflowtech/logsensor,alexandergall/snabbswitch,Igalia/snabbswitch,justincormack/snabbswitch,dpino/snabb,snabbco/snabb,dpino/snabb,kbara/snabb,andywingo/snabbswitch,hb9cwp/snabbswitch,Igalia/snabb,Igalia/snabb,eugeneia/snabb,lukego/snabb,fhanik/snabbswitch,eugeneia/snabb,wingo/snabbswitch,plajjan/snabbswitch,kellabyte/snabbswitch,dpino/snabb,xdel/snabbswitch,heryii/snabb,snabbco/snabb,dpino/snabb,heryii/snabb,aperezdc/snabbswitch,Igalia/snabbswitch,alexandergall/snabbswitch,snabbnfv-goodies/snabbswitch,lukego/snabbswitch,Igalia/snabb,Igalia/snabb,dpino/snabb,fhanik/snabbswitch,wingo/snabb,wingo/snabb,Igalia/snabb,eugeneia/snabb,mixflowtech/logsensor,eugeneia/snabb,justincormack/snabbswitch,andywingo/snabbswitch,snabbco/snabb,wingo/snabbswitch,kbara/snabb,heryii/snabb,Igalia/snabbswitch,mixflowtech/logsensor,kellabyte/snabbswitch,SnabbCo/snabbswitch,snabbnfv-goodies/snabbswitch,pirate/snabbswitch,heryii/snabb,dpino/snabb,snabbco/snabb,alexandergall/snabbswitch,eugeneia/snabb,hb9cwp/snabbswitch,eugeneia/snabbswitch,justincormack/snabbswitch,kbara/snabb,xdel/snabbswitch,eugeneia/snabb,dpino/snabbswitch,plajjan/snabbswitch,wingo/snabbswitch,andywingo/snabbswitch,alexandergall/snabbswitch,Igalia/snabbswitch,eugeneia/snabb,wingo/snabb,plajjan/snabbswitch,heryii/snabb,alexandergall/snabbswitch,justincormack/snabbswitch,lukego/snabbswitch,mixflowtech/logsensor,snabbco/snabb,kellabyte/snabbswitch,Igalia/snabbswitch,wingo/snabb,Igalia/snabb,Igalia/snabb,eugeneia/snabb,hb9cwp/snabbswitch,xdel/snabbswitch,lukego/snabb,alexandergall/snabbswitch,SnabbCo/snabbswitch,dwdm/snabbswitch,heryii/snabb,lukego/snabb,dpino/snabbswitch,virtualopensystems/snabbswitch,wingo/snabb,snabbco/snabb,virtualopensystems/snabbswitch,lukego/snabbswitch,kbara/snabb,dpino/snabb,lukego/snabb,dwdm/snabbswitch,SnabbCo/snabbswitch,snabbnfv-goodies/snabbswitch,snabbco/snabb,mixflowtech/logsensor,alexandergall/snabbswitch
|
3af8ac2ec6602ed839cae962c334b72aecaaea31
|
tests/test_gmake_cpp.lua
|
tests/test_gmake_cpp.lua
|
--
-- tests/test_gmake_cpp.lua
-- Automated test suite for GNU Make C/C++ project generation.
-- Copyright (c) 2009 Jason Perkins and the Premake project
--
T.gmake_cpp = { }
--
-- Configure a solution for testing
--
local sln, prj
function T.gmake_cpp.setup()
_ACTION = "gmake"
_OPTIONS.os = "linux"
sln = solution "MySolution"
configurations { "Debug", "Release" }
platforms { "native" }
prj = project "MyProject"
language "C++"
kind "ConsoleApp"
end
local function prepare()
io.capture()
premake.buildconfigs()
end
--
-- Test the header
--
function T.gmake_cpp.BasicHeader()
prepare()
premake.gmake_cpp_header(prj, premake.gcc, sln.platforms)
test.capture [[
# GNU Make project makefile autogenerated by Premake
ifndef config
config=debug
endif
ifndef verbose
SILENT = @
endif
ifndef CC
CC = gcc
endif
ifndef CXX
CXX = g++
endif
ifndef AR
AR = ar
endif
]]
end
--
-- Test configuration blocks
--
function T.gmake_cpp.BasicCfgBlock()
prepare()
local cfg = premake.getconfig(prj, "Debug")
premake.gmake_cpp_config(cfg, premake.gcc)
test.capture [[
ifeq ($(config),debug)
OBJDIR = obj/Debug
TARGETDIR = .
TARGET = $(TARGETDIR)/MyProject
DEFINES +=
INCLUDES +=
CPPFLAGS += -MMD $(DEFINES) $(INCLUDES)
CFLAGS += $(CPPFLAGS) $(ARCH)
CXXFLAGS += $(CFLAGS)
LDFLAGS += -s
LIBS +=
RESFLAGS += $(DEFINES) $(INCLUDES)
LDDEPS +=
LINKCMD = $(CXX) -o $(TARGET) $(LDFLAGS) $(OBJECTS) $(RESOURCES) $(ARCH) $(LIBS)
define PREBUILDCMDS
endef
define PRELINKCMDS
endef
define POSTBUILDCMDS
endef
endif
]]
end
function T.gmake_cpp.BasicCfgBlockWithPlatformCc()
platforms { "ps3" }
prepare()
local cfg = premake.getconfig(prj, "Debug", "PS3")
premake.gmake_cpp_config(cfg, premake.gcc)
test.capture [[
ifeq ($(config),debugps3)
CC = ppu-lv2-g++
CXX = ppu-lv2-g++
AR = ppu-lv2-ar
OBJDIR = obj/PS3/Debug
TARGETDIR = .
TARGET = $(TARGETDIR)/MyProject.elf
DEFINES +=
INCLUDES +=
CPPFLAGS += -MMD $(DEFINES) $(INCLUDES)
CFLAGS += $(CPPFLAGS) $(ARCH)
CXXFLAGS += $(CFLAGS)
LDFLAGS += -s
LIBS +=
RESFLAGS += $(DEFINES) $(INCLUDES)
LDDEPS +=
LINKCMD = $(CXX) -o $(TARGET) $(LDFLAGS) $(OBJECTS) $(RESOURCES) $(ARCH) $(LIBS)
define PREBUILDCMDS
endef
define PRELINKCMDS
endef
define POSTBUILDCMDS
endef
endif
]]
end
function T.gmake_cpp.PlatformSpecificBlock()
platforms { "x64" }
prepare()
local cfg = premake.getconfig(prj, "Debug", "x64")
premake.gmake_cpp_config(cfg, premake.gcc)
test.capture [[
ifeq ($(config),debug64)
OBJDIR = obj/x64/Debug
TARGETDIR = .
TARGET = $(TARGETDIR)/MyProject
DEFINES +=
INCLUDES +=
CPPFLAGS += -MMD $(DEFINES) $(INCLUDES)
CFLAGS += $(CPPFLAGS) $(ARCH) -m64
CXXFLAGS += $(CFLAGS)
LDFLAGS += -s -m64 -L/usr/lib64
LIBS +=
RESFLAGS += $(DEFINES) $(INCLUDES)
LDDEPS +=
LINKCMD = $(CXX) -o $(TARGET) $(LDFLAGS) $(OBJECTS) $(RESOURCES) $(ARCH) $(LIBS)
define PREBUILDCMDS
endef
define PRELINKCMDS
endef
define POSTBUILDCMDS
endef
endif
]]
end
function T.gmake_cpp.UniversalStaticLibBlock()
kind "StaticLib"
platforms { "universal32" }
prepare()
local cfg = premake.getconfig(prj, "Debug", "Universal32")
premake.gmake_cpp_config(cfg, premake.gcc)
test.capture [[
ifeq ($(config),debuguniv32)
OBJDIR = obj/Universal32/Debug
TARGETDIR = .
TARGET = $(TARGETDIR)/libMyProject.a
DEFINES +=
INCLUDES +=
CPPFLAGS += $(DEFINES) $(INCLUDES)
CFLAGS += $(CPPFLAGS) $(ARCH) -arch i386 -arch ppc
CXXFLAGS += $(CFLAGS)
LDFLAGS += -s -arch i386 -arch ppc
LIBS +=
RESFLAGS += $(DEFINES) $(INCLUDES)
LDDEPS +=
LINKCMD = libtool -o $(TARGET) $(OBJECTS)
define PREBUILDCMDS
endef
define PRELINKCMDS
endef
define POSTBUILDCMDS
endef
endif
]]
end
|
--
-- tests/test_gmake_cpp.lua
-- Automated test suite for GNU Make C/C++ project generation.
-- Copyright (c) 2009 Jason Perkins and the Premake project
--
T.gmake_cpp = { }
--
-- Configure a solution for testing
--
local sln, prj
function T.gmake_cpp.setup()
_ACTION = "gmake"
_OPTIONS.os = "linux"
sln = solution "MySolution"
configurations { "Debug", "Release" }
platforms { "native" }
prj = project "MyProject"
language "C++"
kind "ConsoleApp"
end
local function prepare()
io.capture()
premake.buildconfigs()
end
--
-- Test the header
--
function T.gmake_cpp.BasicHeader()
prepare()
premake.gmake_cpp_header(prj, premake.gcc, sln.platforms)
test.capture [[
# GNU Make project makefile autogenerated by Premake
ifndef config
config=debug
endif
ifndef verbose
SILENT = @
endif
ifndef CC
CC = gcc
endif
ifndef CXX
CXX = g++
endif
ifndef AR
AR = ar
endif
]]
end
--
-- Test configuration blocks
--
function T.gmake_cpp.BasicCfgBlock()
prepare()
local cfg = premake.getconfig(prj, "Debug")
premake.gmake_cpp_config(cfg, premake.gcc)
test.capture [[
ifeq ($(config),debug)
OBJDIR = obj/Debug
TARGETDIR = .
TARGET = $(TARGETDIR)/MyProject
DEFINES +=
INCLUDES +=
CPPFLAGS += -MMD $(DEFINES) $(INCLUDES)
CFLAGS += $(CPPFLAGS) $(ARCH)
CXXFLAGS += $(CFLAGS)
LDFLAGS += -s
LIBS +=
RESFLAGS += $(DEFINES) $(INCLUDES)
LDDEPS +=
LINKCMD = $(CXX) -o $(TARGET) $(OBJECTS) $(LDFLAGS) $(RESOURCES) $(ARCH) $(LIBS)
define PREBUILDCMDS
endef
define PRELINKCMDS
endef
define POSTBUILDCMDS
endef
endif
]]
end
function T.gmake_cpp.BasicCfgBlockWithPlatformCc()
platforms { "ps3" }
prepare()
local cfg = premake.getconfig(prj, "Debug", "PS3")
premake.gmake_cpp_config(cfg, premake.gcc)
test.capture [[
ifeq ($(config),debugps3)
CC = ppu-lv2-g++
CXX = ppu-lv2-g++
AR = ppu-lv2-ar
OBJDIR = obj/PS3/Debug
TARGETDIR = .
TARGET = $(TARGETDIR)/MyProject.elf
DEFINES +=
INCLUDES +=
CPPFLAGS += -MMD $(DEFINES) $(INCLUDES)
CFLAGS += $(CPPFLAGS) $(ARCH)
CXXFLAGS += $(CFLAGS)
LDFLAGS += -s
LIBS +=
RESFLAGS += $(DEFINES) $(INCLUDES)
LDDEPS +=
LINKCMD = $(CXX) -o $(TARGET) $(OBJECTS) $(LDFLAGS) $(RESOURCES) $(ARCH) $(LIBS)
define PREBUILDCMDS
endef
define PRELINKCMDS
endef
define POSTBUILDCMDS
endef
endif
]]
end
function T.gmake_cpp.PlatformSpecificBlock()
platforms { "x64" }
prepare()
local cfg = premake.getconfig(prj, "Debug", "x64")
premake.gmake_cpp_config(cfg, premake.gcc)
test.capture [[
ifeq ($(config),debug64)
OBJDIR = obj/x64/Debug
TARGETDIR = .
TARGET = $(TARGETDIR)/MyProject
DEFINES +=
INCLUDES +=
CPPFLAGS += -MMD $(DEFINES) $(INCLUDES)
CFLAGS += $(CPPFLAGS) $(ARCH) -m64
CXXFLAGS += $(CFLAGS)
LDFLAGS += -s -m64 -L/usr/lib64
LIBS +=
RESFLAGS += $(DEFINES) $(INCLUDES)
LDDEPS +=
LINKCMD = $(CXX) -o $(TARGET) $(OBJECTS) $(LDFLAGS) $(RESOURCES) $(ARCH) $(LIBS)
define PREBUILDCMDS
endef
define PRELINKCMDS
endef
define POSTBUILDCMDS
endef
endif
]]
end
function T.gmake_cpp.UniversalStaticLibBlock()
kind "StaticLib"
platforms { "universal32" }
prepare()
local cfg = premake.getconfig(prj, "Debug", "Universal32")
premake.gmake_cpp_config(cfg, premake.gcc)
test.capture [[
ifeq ($(config),debuguniv32)
OBJDIR = obj/Universal32/Debug
TARGETDIR = .
TARGET = $(TARGETDIR)/libMyProject.a
DEFINES +=
INCLUDES +=
CPPFLAGS += $(DEFINES) $(INCLUDES)
CFLAGS += $(CPPFLAGS) $(ARCH) -arch i386 -arch ppc
CXXFLAGS += $(CFLAGS)
LDFLAGS += -s -arch i386 -arch ppc
LIBS +=
RESFLAGS += $(DEFINES) $(INCLUDES)
LDDEPS +=
LINKCMD = libtool -o $(TARGET) $(OBJECTS)
define PREBUILDCMDS
endef
define PRELINKCMDS
endef
define POSTBUILDCMDS
endef
endif
]]
end
|
Fixed failing GMake C++ tests
|
Fixed failing GMake C++ tests
--HG--
extra : convert_revision : svn%3A644ed5ae-bb15-0410-aa60-99f397bbb77a/trunk%40927
|
Lua
|
bsd-3-clause
|
annulen/premake-annulen,annulen/premake-annulen,annulen/premake-dev-rgeary,warrenseine/premake,annulen/premake,Lusito/premake,annulen/premake,annulen/premake-dev-rgeary,annulen/premake-dev-rgeary,annulen/premake-annulen,Lusito/premake,annulen/premake-annulen,Lusito/premake,annulen/premake,annulen/premake,warrenseine/premake,warrenseine/premake,Lusito/premake
|
bd0b476dce5f3fe745f645757a5b3436900d1263
|
Framework/BuildTools/protoc.lua
|
Framework/BuildTools/protoc.lua
|
local function checkRecompileNeeded(file, cppOut, javaOut, pythonOut)
local file_info = os.stat(file)
local name = path.getbasename(file)
if file_info == nil then
print ("ERROR: conld not get the stats from file " .. file)
return false
end
local cpp_info = os.stat(path.join(cppOut, name..".pb.cc"))
local hpp_info = os.stat(path.join(cppOut, name..".pb.h"))
--local java_info = os.stat(path.join(javaOut, name..".java"))
local python_info = os.stat(path.join(pythonOut, name:gsub("-", "_").."_pb2.py"))
if python_info == nil then
print(path.join(pythonOut, name.."_pb2.py"))
end
return (cpp_info == nil or file_info.mtime > cpp_info.mtime) or
(hpp_info == nil or file_info.mtime > cpp_info.mtime) or
--(java_info == nil or file_info.mtime > java_info.mtime) or
(python_info == nil or file_info.mtime > python_info.mtime)
end
local function protocCompileAll(inputFiles, cppOut, javaOut, pythonOut, ipaths)
-- get the protobuf compiler from the EXTERN_PATH
compiler = os.ishost("windows") and "protoc.exe" or "protoc"
-- TODO: should we search on additional locations?
compilerPath = os.pathsearch(compiler, EXTERN_PATH .. "/bin/") or os.pathsearch(compiler, EXTERN_PATH_NATIVE .. "/bin/")
if compilerPath == nil then
print ("ERROR: could not find protoc compiler executable in \"" .. EXTERN_PATH .. "/bin/" .. "\"")
return false
end
local args = ""
if(pythonOut ~= nil) then
args = args .. "--python_out=\"" .. pythonOut .. "\" " -- always mind the space at the end
os.mkdir(pythonOut) -- create the output directory if needed
end
if(cppOut ~= nil) then
args = args .. "--cpp_out=\"" .. cppOut .. "\" " -- always mind the space at the end
os.mkdir(cppOut) -- create the output directory if needed
end
if(javaOut ~= nil) then
args = args .. "--java_out=\"" .. javaOut .. "\" " -- always mind the space at the end
os.mkdir(javaOut) -- create the output directory if needed
end
if(ipaths ~= nil) then
for i=1,#ipaths do
args = args .. "--proto_path=\"" .. ipaths[i] .. "\" " -- always mind the space at the end
end
end
-- add files to compile
args = args .. table.concat(inputFiles, " ")
local cmd = "\"" .. compilerPath .. "/" .. compiler .. "\" " .. args
if os.ishost("windows") then
cmd = "\"" .. cmd .. "\""
end
-- TODO. why is this necessary?
-- delete the generated cpp files
print("Try to remove the pb.cc and .pb.h files ")
for i,file in ipairs(inputFiles) do
local name = path.getbasename(file)
ok, err = os.remove (path.join(cppOut, name..".pb.cc"))
ok, err = os.remove (path.join(cppOut, name..".pb.h"))
end
print("Removed all generated message files")
-- generate the message files
print("INFO: (Protbuf) executing " .. cmd)
local succ, status, returnCode = os.execute(cmd)
if returnCode == 0 then
print("NOTE: (Protbuf) supressing warnings in " .. cppOut)
-- add few lines to suppress the conversion warnings to each of the generated *.cc files
add_gcc_ignore_pragmas(os.matchfiles(path.join(cppOut,"**.pb.cc")))
add_gcc_ignore_pragmas(os.matchfiles(path.join(cppOut,"**.pb.h")))
end
return returnCode == 0
end
-- adds some content at the beginning and and the end of the file.
-- the new content looks like this: <prefix><original content><suffix>
-- TODO: it was used to add some warning pragmas. check if it still necessarey
function file_add_prefix_sufix(file_name, prefix, suffix)
local f = io.open(file_name, "r")
if (f == nil) then
print ("ERROR: (Protbuf) could not open file \"" .. file_name)
end
local content = f:read("*all")
f:close()
local f = io.open(file_name, "w+")
f:write(prefix);
f:write(content);
f:write(suffix);
f:close()
end
function add_gcc_ignore_pragmas(files)
-- add GCC pragmas: declare the auto generated files as system headers to prevent any warnings
--[[
local prefix = "// added by NaoTH \n" ..
"#if defined(__GNUC__)\n" ..
"#pragma GCC system_header\n" ..
"#endif\n\n"
]]--
-- add gcc pragma to suppress the conversion warnings to each of the generated *.cc files
-- NOTE: we assume GCC version >= 4.9
local prefix = "// added by NaoTH \n" ..
"#if defined(__GNUC__)\n" ..
"#pragma GCC diagnostic push\n" ..
"#pragma GCC diagnostic ignored \"-Wconversion\"\n" ..
"#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n" ..
"#endif\n\n"
-- restore the previous state at the end
local suffix = "\n\n// added by NaoTH \n" ..
"#if defined(__GNUC__)\n" ..
"#pragma GCC diagnostic pop\n" ..
"#endif\n\n"
numberFiles = 0
for i,file in ipairs(files) do
print("NOTE: process " .. file)
file_add_prefix_sufix(file, prefix, suffix)
numberFiles = numberFiles + 1
end
if numberFiles == 0 then
print("WARNING: (Protbuf) no message files were processed")
end
end
-- a wrapper for an easier access with names parameters
-- e.g., makeprotoc{inputFiles = {""}, ...}
function makeprotoc(arg)
invokeprotoc(arg.inputFiles, arg.cppOut, arg.javaOut, arg.pythonOut, arg.includeDirs)
end
function invokeprotoc(inputFiles, cppOut, javaOut, pythonOut, includeDirs)
-- check if protobuf compile is explicitely requested
local compileAll = (_OPTIONS["protoc"] ~= nil)
-- remember the time in case it is needed for the shadow file
local time = os.time()
local filesToCompile = {}
-- collect the files that need to be compiled
for i = 1, #inputFiles do
if checkRecompileNeeded(inputFiles[i], cppOut, javaOut, pythonOut) then
table.insert(filesToCompile, inputFiles[i])
end
end
-- filesToCompile is not empty
if next(filesToCompile) ~= nil then
protocCompileAll(filesToCompile, cppOut, javaOut, pythonOut, includeDirs)
end
end
newoption {
trigger = "protoc",
description = "Force to recompile the protbuf messages"
}
newoption {
trigger = "protoc-ipath",
value = "INCLUDE-DIRS",
description = "Include paths seperated by a \":\""
}
newoption {
trigger = "protoc-cpp",
value = "OUT-DIR",
description = "Output directory for the C++ classes generated by protoc"
}
newoption {
trigger = "protoc-java",
value = "OUT-DIR",
description = "Output directory for the Java classes generated by protoc"
}
newoption {
trigger = "protoc-python",
value = "OUT-DIR",
description = "Output directory for the Python classes generated by protoc"
}
|
local function checkRecompileNeeded(file, cppOut, javaOut, pythonOut)
local file_info = os.stat(file)
local name = path.getbasename(file)
if file_info == nil then
print ("ERROR: conld not get the stats from file " .. file)
return false
end
local cpp_info = os.stat(path.join(cppOut, name..".pb.cc"))
local hpp_info = os.stat(path.join(cppOut, name..".pb.h"))
--local java_info = os.stat(path.join(javaOut, name..".java"))
local python_info = os.stat(path.join(pythonOut, name:gsub("-", "_").."_pb2.py"))
if python_info == nil then
print(path.join(pythonOut, name.."_pb2.py"))
end
return (cpp_info == nil or file_info.mtime > cpp_info.mtime) or
(hpp_info == nil or file_info.mtime > cpp_info.mtime) or
--(java_info == nil or file_info.mtime > java_info.mtime) or
(python_info == nil or file_info.mtime > python_info.mtime)
end
local function protocCompileAll(inputFiles, cppOut, javaOut, pythonOut, ipaths)
-- get the protobuf compiler from the EXTERN_PATH
compiler = os.ishost("windows") and "protoc.exe" or "protoc"
-- TODO: should we search on additional locations?
compilerPath = os.pathsearch(compiler, EXTERN_PATH .. "/bin/") or os.pathsearch(compiler, EXTERN_PATH_NATIVE .. "/bin/")
if compilerPath == nil then
print ("ERROR: could not find protoc compiler executable in \"" .. EXTERN_PATH .. "/bin/" .. "\"")
return false
end
local args = ""
if(pythonOut ~= nil) then
args = args .. "--python_out=\"" .. pythonOut .. "\" " -- always mind the space at the end
os.mkdir(pythonOut) -- create the output directory if needed
end
if(cppOut ~= nil) then
args = args .. "--cpp_out=\"" .. cppOut .. "\" " -- always mind the space at the end
os.mkdir(cppOut) -- create the output directory if needed
end
if(javaOut ~= nil) then
args = args .. "--java_out=\"" .. javaOut .. "\" " -- always mind the space at the end
os.mkdir(javaOut) -- create the output directory if needed
end
if(ipaths ~= nil) then
for i=1,#ipaths do
args = args .. "--proto_path=\"" .. ipaths[i] .. "\" " -- always mind the space at the end
end
end
-- add files to compile
args = args .. table.concat(inputFiles, " ")
local cmd = "\"" .. compilerPath .. "/" .. compiler .. "\" " .. args
if os.ishost("windows") then
cmd = "\"" .. cmd .. "\""
end
-- TODO. why is this necessary?
-- delete the generated cpp files
print("Try to remove the pb.cc and .pb.h files ")
for i,file in ipairs(inputFiles) do
local name = path.getbasename(file)
ok, err = os.remove(path.join(cppOut, name..".pb.cc"))
ok, err = os.remove(path.join(cppOut, name..".pb.h"))
end
print("Removed all generated message files")
-- generate the message files
print("INFO: (Protbuf) executing " .. cmd)
local succ, status, returnCode = os.execute(cmd)
if returnCode == 0 then
for i,file in ipairs(inputFiles) do
print("NOTE: (Protbuf) supressing warnings in " .. cppOut)
-- add few lines to suppress the conversion warnings to each of the generated *.cc files
local name = path.getbasename(file)
add_gcc_ignore_pragmas(path.join(cppOut, name..".pb.cc"))
add_gcc_ignore_pragmas(path.join(cppOut, name..".pb.h"))
end
end
return returnCode == 0
end
-- adds some content at the beginning and and the end of the file.
-- the new content looks like this: <prefix><original content><suffix>
-- TODO: it was used to add some warning pragmas. check if it still necessarey
function file_add_prefix_sufix(file_name, prefix, suffix)
local f = io.open(file_name, "r")
if (f == nil) then
print ("ERROR: (Protbuf) could not open file \"" .. file_name)
end
local content = f:read("*all")
f:close()
local f = io.open(file_name, "w+")
f:write(prefix);
f:write(content);
f:write(suffix);
f:close()
end
function add_gcc_ignore_pragmas(files)
-- add GCC pragmas: declare the auto generated files as system headers to prevent any warnings
--[[
local prefix = "// added by NaoTH \n" ..
"#if defined(__GNUC__)\n" ..
"#pragma GCC system_header\n" ..
"#endif\n\n"
]]--
-- add gcc pragma to suppress the conversion warnings to each of the generated *.cc files
-- NOTE: we assume GCC version >= 4.9
local prefix = "// added by NaoTH \n" ..
"#if defined(__GNUC__)\n" ..
"#pragma GCC diagnostic push\n" ..
"#pragma GCC diagnostic ignored \"-Wconversion\"\n" ..
"#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n" ..
"#endif\n\n"
-- restore the previous state at the end
local suffix = "\n\n// added by NaoTH \n" ..
"#if defined(__GNUC__)\n" ..
"#pragma GCC diagnostic pop\n" ..
"#endif\n\n"
numberFiles = 0
for i,file in ipairs(files) do
print("NOTE: process " .. file)
file_add_prefix_sufix(file, prefix, suffix)
numberFiles = numberFiles + 1
end
if numberFiles == 0 then
print("WARNING: (Protbuf) no message files were processed")
end
end
-- a wrapper for an easier access with names parameters
-- e.g., makeprotoc{inputFiles = {""}, ...}
function makeprotoc(arg)
invokeprotoc(arg.inputFiles, arg.cppOut, arg.javaOut, arg.pythonOut, arg.includeDirs)
end
function invokeprotoc(inputFiles, cppOut, javaOut, pythonOut, includeDirs)
-- check if protobuf compile is explicitely requested
local compileAll = (_OPTIONS["protoc"] ~= nil)
-- remember the time in case it is needed for the shadow file
local time = os.time()
local filesToCompile = {}
-- collect the files that need to be compiled
for i = 1, #inputFiles do
if checkRecompileNeeded(inputFiles[i], cppOut, javaOut, pythonOut) then
table.insert(filesToCompile, inputFiles[i])
end
end
-- filesToCompile is not empty
if next(filesToCompile) ~= nil then
protocCompileAll(filesToCompile, cppOut, javaOut, pythonOut, includeDirs)
end
end
newoption {
trigger = "protoc",
description = "Force to recompile the protbuf messages"
}
newoption {
trigger = "protoc-ipath",
value = "INCLUDE-DIRS",
description = "Include paths seperated by a \":\""
}
newoption {
trigger = "protoc-cpp",
value = "OUT-DIR",
description = "Output directory for the C++ classes generated by protoc"
}
newoption {
trigger = "protoc-java",
value = "OUT-DIR",
description = "Output directory for the Java classes generated by protoc"
}
newoption {
trigger = "protoc-python",
value = "OUT-DIR",
description = "Output directory for the Python classes generated by protoc"
}
|
bugfix: only modify the file which had been rebuilt
|
bugfix: only modify the file which had been rebuilt
|
Lua
|
apache-2.0
|
BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH
|
91eac1bd7cea45c05a74239fe45c8703d3a3701d
|
turttlebot2_v4_turtlebot.lua
|
turttlebot2_v4_turtlebot.lua
|
function setVels_cb(msg)
-- not sure if a scale factor is must be applied
local linVel = msg.linear.x/2 -- in m/s
local rotVel = msg.angular.z*wheelAxis/2 -- in rad/s
velocityRight = linVel+rotVel
velocityLeft = linVel-rotVel
if simulationIsKinematic then
-- Simulation is kinematic
p=sim.boolOr32(sim.getModelProperty(objHandle),sim.modelproperty_not_dynamic)
sim.setModelProperty(objHandle,p)
dt=sim.getSimulationTimeStep()
p=sim.getJointPosition(leftJoint)
sim.setJointPosition(leftJoint,p+velocityLeft*dt*2/wheelDiameter)
p=sim.getJointPosition(rightJoint)
sim.setJointPosition(rightJoint,p+velocityRight*dt*2/wheelDiameter)
linMov=dt*(velocityLeft+velocityRight)/2.0
rotMov=dt*math.atan((velocityRight-velocityLeft)/interWheelDistance)
position=sim.getObjectPosition(objHandle,sim.handle_parent)
orientation=sim.getObjectOrientation(objHandle,sim.handle_parent)
xDir={math.cos(orientation[3]),math.sin(orientation[3]),0.0}
position[1]=position[1]+xDir[1]*linMov
position[2]=position[2]+xDir[2]*linMov
orientation[3]=orientation[3]+rotMov
sim.setObjectPosition(objHandle,sim.handle_parent,position)
sim.setObjectOrientation(objHandle,sim.handle_parent,orientation)
else
-- Simulation is dynamic
p=sim.boolOr32(sim.getModelProperty(objHandle),sim.modelproperty_not_dynamic)-sim.modelproperty_not_dynamic
sim.setModelProperty(objHandle,p)
velocityRight = linVel + math.Rad2Deg(rotVel)
velocityLeft = linVel - math.Rad2Deg(rotVel)
sim.setJointTargetVelocity(leftJoint,velocityLeft*2/wheelDiameter)
sim.setJointTargetVelocity(rightJoint,velocityRight*2/wheelDiameter)
end
end
if (sim_call_type==sim.childscriptcall_initialization) then
objHandle=sim.getObjectAssociatedWithScript(sim.handle_self)
modelBaseName = sim.getObjectName(objHandle)
leftJoint=sim.getObjectHandle("turtlebot_leftWheelJoint_")
rightJoint=sim.getObjectHandle("turtlebot_rightWheelJoint_")
simulationIsKinematic=false -- we want a dynamic simulation here!
-- Braitenberg weights:
brait_left={0,-0.5,-1.25,-1,-0.2}
t_frontBumper = sim.getObjectHandle('bumper_front_joint')
t_rightBumper = sim.getObjectHandle('bumper_right_joint')
t_leftBumper = sim.getObjectHandle('bumper_left_joint')
originMatrix = sim.getObjectMatrix(objHandle,-1)
invOriginMatrix = simGetInvertedMatrix(originMatrix)
----------------------------- ROS STUFF --------------------------------
-- Odometry
pubPose = simROS.advertise(modelBaseName..'/pose','nav_msgs/Odometry')
simROS.publisherTreatUInt8ArrayAsString(pubPose)
-- Commands
subCmdVel = simROS.subscribe(modelBaseName..'/cmd_vel','geometry_msgs/Twist','setVels_cb')
end
if (sim_call_type == sim.childscriptcall_sensing) then
-- Front Bumper
front_bumper_pos = sim.getJointPosition(t_frontBumper)
if(front_bumper_pos < -0.001) then
-- print("F. COLLISION!")
front_collision=true
bumperCenterState = 1
else
-- print("F. No Collision")
front_collision=false
bumperCenterState = 0
end
-- Right Bumper
right_bumper_pos = sim.getJointPosition(t_rightBumper)
if(right_bumper_pos < -0.001) then
-- print("R. COLLISION!")
right_collision=true
bumperRightState = 1
else
--print("R. No Collision")
right_collision=false
bumperRightState = 0
end
-- Left Bumper
left_bumper_pos = sim.getJointPosition(t_leftBumper)
if(left_bumper_pos < -0.001) then
-- print("L. COLLISION!")
left_collision=true
bumperLeftState = 1
else
--print("L. No Collision")
left_collision=false
bumperLeftState = 0
end
-- Odometry
local transformNow = sim.getObjectMatrix(objHandle,-1)
pose_orientationNow = sim.multiplyMatrices(invOriginMatrix, transformNow)
r_quaternion = simGetQuaternionFromMatrix(pose_orientationNow)
r_position = {pose_orientationNow[3], pose_orientationNow[7], pose_orientationNow[11]}
r_linear_velocity, r_angular_velocity = simGetObjectVelocity(objHandle)
-- ROSing
ros_pose = {}
ros_pose['header'] = {seq=0,stamp=simROS.getTime(), frame_id="/robot"..modelBaseName}
cov = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
quaternion_ros = {}
quaternion_ros["x"] = r_quaternion[1]
quaternion_ros["y"] = r_quaternion[2]
quaternion_ros["z"] = r_quaternion[3]
quaternion_ros["w"] = r_quaternion[4]
position_ros = {}
position_ros["x"] = r_position[1]
position_ros["y"] = r_position[2]
position_ros["z"] = r_position[3]
pose_r = {position=position_ros, orientation=quaternion_ros}
ros_pose['pose'] = {pose=pose_r, covariance = cov}
linear_speed = {}
linear_speed["x"] = r_linear_velocity[1]
linear_speed["y"] = r_linear_velocity[2]
linear_speed["z"] = r_linear_velocity[3]
angular_speed = {}
angular_speed["x"] = r_angular_velocity[1]
angular_speed["y"] = r_angular_velocity[2]
angular_speed["z"] = r_angular_velocity[3]
ros_pose['twist'] = {twist={linear=linear_speed, angular=angular_speed}, covariance=cov}
ros_pose['child_frame_id'] = "kinect"
simROS.publish(pubPose, ros_pose)
end
if (sim_call_type==sim.childscriptcall_cleanup) then
-- ROS Shutdown
simROS.shutdownPublisher(pubPose)
simROS.shutdownSubscriber(subCmdVel)
end
if (sim_call_type==sim.childscriptcall_actuation) then
s=sim.getObjectSizeFactor(objHandle) -- make sure that if we scale the robot during simulation, other values are scaled too!
v0=0.4*s
wheelDiameter=0.085*s
interWheelDistance=0.254*s
noDetectionDistance=0.4*s
end
|
function setVels_cb(msg)
-- not sure if a scale factor must be applied
local linVel = msg.linear.x/2 -- in m/s
local rotVel = msg.angular.z*interWheelDistance/2 -- in rad/s
velocityRight = linVel+rotVel
velocityLeft = linVel-rotVel
if simulationIsKinematic then
-- Simulation is kinematic
p=sim.boolOr32(sim.getModelProperty(objHandle),sim.modelproperty_not_dynamic)
sim.setModelProperty(objHandle,p)
dt=sim.getSimulationTimeStep()
p=sim.getJointPosition(leftJoint)
sim.setJointPosition(leftJoint,p+velocityLeft*dt*2/wheelDiameter)
p=sim.getJointPosition(rightJoint)
sim.setJointPosition(rightJoint,p+velocityRight*dt*2/wheelDiameter)
linMov=dt*(velocityLeft+velocityRight)/2.0
rotMov=dt*math.atan((velocityRight-velocityLeft)/interWheelDistance)
position=sim.getObjectPosition(objHandle,sim.handle_parent)
orientation=sim.getObjectOrientation(objHandle,sim.handle_parent)
xDir={math.cos(orientation[3]),math.sin(orientation[3]),0.0}
position[1]=position[1]+xDir[1]*linMov
position[2]=position[2]+xDir[2]*linMov
orientation[3]=orientation[3]+rotMov
sim.setObjectPosition(objHandle,sim.handle_parent,position)
sim.setObjectOrientation(objHandle,sim.handle_parent,orientation)
else
-- Simulation is dynamic
p=sim.boolOr32(sim.getModelProperty(objHandle),sim.modelproperty_not_dynamic)-sim.modelproperty_not_dynamic
sim.setModelProperty(objHandle,p)
velocityRight = linVel + rotVel
velocityLeft = linVel - rotVel
sim.setJointTargetVelocity(leftJoint,velocityLeft*2/wheelDiameter*180/math.pi)
sim.setJointTargetVelocity(rightJoint,velocityRight*2/wheelDiameter*180/math.pi)
end
end
if (sim_call_type==sim.childscriptcall_initialization) then
objHandle=sim.getObjectAssociatedWithScript(sim.handle_self)
modelBaseName = sim.getObjectName(objHandle)
mainBodyHandle = sim.getObjectHandle("turtlebot_body_visual")
leftJoint=sim.getObjectHandle("turtlebot_leftWheelJoint_")
rightJoint=sim.getObjectHandle("turtlebot_rightWheelJoint_")
simulationIsKinematic=false -- we want a dynamic simulation here!
-- Braitenberg weights:
brait_left={0,-0.5,-1.25,-1,-0.2}
t_frontBumper = sim.getObjectHandle('bumper_front_joint')
t_rightBumper = sim.getObjectHandle('bumper_right_joint')
t_leftBumper = sim.getObjectHandle('bumper_left_joint')
originMatrix = sim.getObjectMatrix(mainBodyHandle,-1)
invOriginMatrix = simGetInvertedMatrix(originMatrix)
----------------------------- ROS STUFF --------------------------------
-- Odometry
pubPose = simROS.advertise(modelBaseName..'/pose','nav_msgs/Odometry')
simROS.publisherTreatUInt8ArrayAsString(pubPose)
-- Commands
subCmdVel = simROS.subscribe(modelBaseName..'/cmd_vel','geometry_msgs/Twist','setVels_cb')
end
if (sim_call_type == sim.childscriptcall_sensing) then
-- Front Bumper
front_bumper_pos = sim.getJointPosition(t_frontBumper)
if(front_bumper_pos < -0.001) then
-- print("F. COLLISION!")
front_collision=true
bumperCenterState = 1
else
-- print("F. No Collision")
front_collision=false
bumperCenterState = 0
end
-- Right Bumper
right_bumper_pos = sim.getJointPosition(t_rightBumper)
if(right_bumper_pos < -0.001) then
-- print("R. COLLISION!")
right_collision=true
bumperRightState = 1
else
--print("R. No Collision")
right_collision=false
bumperRightState = 0
end
-- Left Bumper
left_bumper_pos = sim.getJointPosition(t_leftBumper)
if(left_bumper_pos < -0.001) then
-- print("L. COLLISION!")
left_collision=true
bumperLeftState = 1
else
--print("L. No Collision")
left_collision=false
bumperLeftState = 0
end
-- Odometry
local transformNow = sim.getObjectMatrix(mainBodyHandle,-1)
local pose_orientationNow = sim.multiplyMatrices(invOriginMatrix, transformNow)
local r_quaternion = simGetQuaternionFromMatrix(pose_orientationNow)
local r_position = {pose_orientationNow[4], pose_orientationNow[8], pose_orientationNow[12]}
local r_linear_velocity, r_angular_velocity = 0,0
r_linear_velocity, r_angular_velocity = simGetObjectVelocity(mainBodyHandle)
-- ROSing
local ros_pose = {}
ros_pose['header'] = {seq=0,stamp=simROS.getTime(), frame_id="/robot"..modelBaseName}
local cov = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
local quaternion_ros = {}
quaternion_ros["x"] = r_quaternion[1]
quaternion_ros["y"] = r_quaternion[2]
quaternion_ros["z"] = r_quaternion[3]
quaternion_ros["w"] = r_quaternion[4]
local position_ros = {}
position_ros["x"] = r_position[1]
position_ros["y"] = r_position[2]
position_ros["z"] = r_position[3]
local pose_r = {position=position_ros, orientation=quaternion_ros}
ros_pose['pose'] = {pose=pose_r, covariance = cov}
local linear_speed = {}
linear_speed["x"] = r_linear_velocity[1]
linear_speed["y"] = r_linear_velocity[2]
linear_speed["z"] = r_linear_velocity[3]
local angular_speed = {}
angular_speed["x"] = r_angular_velocity[1]
angular_speed["y"] = r_angular_velocity[2]
angular_speed["z"] = r_angular_velocity[3]
ros_pose['twist'] = {twist={linear=linear_speed, angular=angular_speed}, covariance=cov}
ros_pose['child_frame_id'] = "kinect"
simROS.publish(pubPose, ros_pose)
end
if (sim_call_type==sim.childscriptcall_cleanup) then
-- ROS Shutdown
simROS.shutdownPublisher(pubPose)
simROS.shutdownSubscriber(subCmdVel)
end
if (sim_call_type==sim.childscriptcall_actuation) then
s=sim.getObjectSizeFactor(objHandle) -- make sure that if we scale the robot during simulation, other values are scaled too!
v0=0.4*s
wheelDiameter=0.085*s
interWheelDistance=0.254*s
noDetectionDistance=0.4*s
end
|
Bug-fix: robot position]
|
Bug-fix: robot position]
|
Lua
|
apache-2.0
|
EricssonResearch/scott-eu,EricssonResearch/scott-eu,EricssonResearch/scott-eu,EricssonResearch/scott-eu,EricssonResearch/scott-eu,EricssonResearch/scott-eu,EricssonResearch/scott-eu,EricssonResearch/scott-eu,EricssonResearch/scott-eu,EricssonResearch/scott-eu
|
5abd0ffd1ee7db8da318a79fe2af888bc46c5698
|
tcpdns.lua
|
tcpdns.lua
|
local socket = require("socket")
local struct = require("struct")
-----------------------------------------
-- LRU cache function
-----------------------------------------
local function LRU(size)
local keys, dict = {}, {}
local function get(key)
local value = dict[key]
if value and keys[1] ~= key then
for i, k in ipairs(keys) do
if k == key then
table.insert(keys, 1, table.remove(keys, i))
break
end
end
end
return value
end
local function set(key, value)
if not get(key) then
if #keys == size then
dict[keys[size]] = nil
table.remove(keys)
end
table.insert(keys, 1, key)
end
dict[key] = value
end
return {set = set, get = get}
end
-----------------------------------------
-- task package
-----------------------------------------
do
local pool = {}
local mutex = {}
local num = 0
local function go(f, ...)
local co = coroutine.create(f)
assert(coroutine.resume(co, ...))
if coroutine.status(co) ~= "dead" then
pool[co] = pool[co] or os.clock()
num = num + 1
end
end
local function sleep(n)
n = n or 0
pool[coroutine.running()] = os.clock() + n
coroutine.yield()
end
local function step()
for co, wt in pairs(pool) do
if os.clock() >= wt and not mutex[mutex[co]] then
assert(coroutine.resume(co))
if coroutine.status(co) == "dead" then
pool[co] = nil
num = num - 1
end
end
end
return num
end
local function loop(n)
n = n or 0.001
local sleep = ps.sleep or socket.sleep
while step() ~= 0 do sleep(n) end
end
local function lock(o)
local co = coroutine.running()
if mutex[o] then
mutex[co] = o
coroutine.yield()
end
mutex[co] = nil
mutex[o] = true
end
local function unlock(o)
mutex[o] = nil
end
local function count()
return num
end
task = {
go = go, sleep = sleep,
step = step, loop = loop,
lock = lock, unlock = unlock,
count = count
}
end
-----------------------------------------
-- TCP DNS proxy
-----------------------------------------
local cache = LRU(20)
local task = task
local hosts = {
"8.8.8.8", "8.8.4.4",
"208.67.222.222", "208.67.220.220"
}
local function queryDNS(host, data)
local sock = socket.tcp()
sock:settimeout(1)
local ret = sock:connect(host, 53)
if not ret then task.sleep(1) end
ret = ""
if sock:send(struct.pack(">h", #data)..data) then
repeat
task.sleep(0.02)
local s, status, partial = sock:receive(1024)
ret = ret..(s or partial)
until #ret > 0 or status == "closed"
end
sock:close()
return ret
end
local function transfer(skt, data, ip, port)
local domain = (data:sub(14, -6):gsub("[^%w]", "."))
print("domain: "..domain, "thread: "..task.count())
task.lock(domain)
if cache.get(domain) then
skt:sendto(data:sub(1, 2)..cache.get(domain), ip, port)
else
for _, host in ipairs(hosts) do
data = queryDNS(host, data)
if #data > 0 then break end
end
if #data > 0 then
data = data:sub(3)
cache.set(domain, data:sub(3))
skt:sendto(data, ip, port)
end
end
task.unlock(domain)
end
local function udpserver()
local udp = socket.udp()
udp:settimeout(0)
udp:setsockname('*', 53)
while true do
local data, ip, port = udp:receivefrom()
if data and #data > 0 then
task.go(transfer, udp, data, ip, port)
end
task.sleep(0)
end
end
task.go(udpserver)
task.loop()
|
local socket = require("socket")
local struct = require("struct")
-----------------------------------------
-- LRU cache function
-----------------------------------------
local function LRU(size)
local keys, dict = {}, {}
local function get(key)
local value = dict[key]
if value and keys[1] ~= key then
for i, k in ipairs(keys) do
if k == key then
table.insert(keys, 1, table.remove(keys, i))
break
end
end
end
return value
end
local function set(key, value)
if not get(key) then
if #keys == size then
dict[keys[size]] = nil
table.remove(keys)
end
table.insert(keys, 1, key)
end
dict[key] = value
end
return {set = set, get = get}
end
-----------------------------------------
-- task package
-----------------------------------------
do
local pool = {}
local mutex = {}
local num = 0
local function go(f, ...)
local co = coroutine.create(f)
assert(coroutine.resume(co, ...))
if coroutine.status(co) ~= "dead" then
pool[co] = pool[co] or os.clock()
num = num + 1
end
end
local function sleep(n)
n = n or 0
pool[coroutine.running()] = os.clock() + n
coroutine.yield()
end
local function step()
for co, wt in pairs(pool) do
if os.clock() >= wt and not mutex[mutex[co]] then
assert(coroutine.resume(co))
if coroutine.status(co) == "dead" then
pool[co] = nil
num = num - 1
end
end
end
return num
end
local function loop(n)
n = n or 0.001
local sleep = ps.sleep or socket.sleep
while step() ~= 0 do sleep(n) end
end
local function lock(o)
local co = coroutine.running()
if mutex[o] then
mutex[co] = o
coroutine.yield()
end
mutex[co] = nil
mutex[o] = true
end
local function unlock(o)
mutex[o] = nil
end
local function count()
return num
end
task = {
go = go, sleep = sleep,
step = step, loop = loop,
lock = lock, unlock = unlock,
count = count
}
end
-----------------------------------------
-- TCP DNS proxy
-----------------------------------------
local cache = LRU(20)
local task = task
local hosts = {
"8.8.8.8", "8.8.4.4",
"208.67.222.222", "208.67.220.220"
}
local function queryDNS(host, data)
local sock = socket.tcp()
sock:settimeout(1)
local ret = sock:connect(host, 53)
if not ret then task.sleep(1) end
ret = ""
if sock:send(struct.pack(">h", #data)..data) then
sock:settimeout(0)
repeat
task.sleep(0.02)
local s, status, partial = sock:receive(1024)
ret = ret..(s or partial)
until #ret > 0 or status == "closed"
end
sock:close()
return ret
end
local function transfer(skt, data, ip, port)
local domain = (data:sub(14, -6):gsub("[^%w]", "."))
print("domain: "..domain, "thread: "..task.count())
local ID, key = data:sub(1, 2), data:sub(3)
task.lock(key)
if cache.get(key) then
skt:sendto(ID..cache.get(key):sub(5), ip, port)
else
for _, host in ipairs(hosts) do
data = queryDNS(host, data)
if #data > 0 then break end
end
if #data > 0 then
cache.set(key, data)
skt:sendto(data:sub(3), ip, port)
end
end
task.unlock(key)
end
local function udpserver()
local udp = socket.udp()
udp:settimeout(0)
udp:setsockname('*', 53)
while true do
local data, ip, port = udp:receivefrom()
if data and #data > 0 then
task.go(transfer, udp, data, ip, port)
end
task.sleep(0)
end
end
task.go(udpserver)
task.loop()
|
fix wrong cache response
|
fix wrong cache response
|
Lua
|
mit
|
uleelx/dnsforwarder
|
c78a2e68ddccdcd26d8c2566a105f8c863fadfd5
|
src/extensions/cp/apple/finalcutpro/inspector/audio/AudioConfiguration.lua
|
src/extensions/cp/apple/finalcutpro/inspector/audio/AudioConfiguration.lua
|
--- === cp.apple.finalcutpro.inspector.audio.AudioConfiguration ===
---
--- The Audio Configuration section of the Audio Inspector.
local require = require
local log = require("hs.logger").new("audioConfiguration")
local axutils = require("cp.ui.axutils")
local CheckBox = require("cp.ui.CheckBox")
local just = require("cp.just")
local MenuButton = require("cp.ui.MenuButton")
local ScrollArea = require("cp.ui.ScrollArea")
local Do = require("cp.rx.go.Do")
local If = require("cp.rx.go.If")
local Throw = require("cp.rx.go.Throw")
local Require = require("cp.rx.go.Require")
local sort = table.sort
--------------------------------------------------------------------------------
--
-- THE MODULE:
--
--------------------------------------------------------------------------------
local AudioConfiguration = ScrollArea:subclass("cp.apple.finalcutpro.inspector.audio.AudioConfiguration")
--- cp.apple.finalcutpro.inspector.audio.AudioConfiguration.matches(element) -> boolean
--- Function
--- Checks to see if an element matches what we think it should be.
---
--- Parameters:
--- * element - An `axuielementObject` to check.
---
--- Returns:
--- * `true` if matches otherwise `false`
function AudioConfiguration.static.matches(element)
return ScrollArea.matches(element)
end
--- cp.apple.finalcutpro.inspector.audio.AudioConfiguration(parent) -> AudioConfiguration
--- Function
--- Creates a new Media Import object.
---
--- Parameters:
--- * parent - The parent object.
---
--- Returns:
--- * A new AudioConfiguration object.
function AudioConfiguration:initialize(parent)
local UI = parent.UI:mutate(function(original)
return axutils.cache(self, "_ui",
function()
local ui = original()
if ui then
local splitGroup = ui[1]
local scrollArea = splitGroup and axutils.childWithRole(splitGroup, "AXScrollArea")
return AudioConfiguration.matches(scrollArea) and scrollArea or nil
else
return nil
end
end,
AudioConfiguration.matches
)
end)
ScrollArea.initialize(self, parent, UI)
end
--- cp.apple.finalcutpro.inspector.audio.AudioConfiguration:enableCheckboxes() -> table
--- Method
--- Returns a table of `hs._asm.axuielement` objects for each enable/disable toggle.
---
--- Parameters:
--- * None
---
--- Returns:
--- * A table containing `hs._asm.axuielement` objects.
function AudioConfiguration.lazy.prop:enableCheckboxes()
return self.UI:mutate(function(original)
local ui = original()
local children = ui and ui:children()
local firstElement = true
local result = {}
local firstElementFrame = nil
for _, child in pairs(children) do
if firstElement then
if child:attributeValue("AXRole") == "AXButton" then
table.insert(result, child)
firstElementFrame = child:attributeValue("AXFrame")
firstElement = false
end
else
local childFrame = child:attributeValue("AXFrame")
if child:attributeValue("AXRole") == "AXButton" and childFrame.w == firstElementFrame.w and childFrame.h == firstElementFrame.h then
table.insert(result, child)
end
end
end
return result
end)
end
--- cp.apple.finalcutpro.inspector.audio.AudioConfiguration:show() -> self
--- Method
--- Attempts to show the bar.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `AudioConfiguration` instance.
function AudioConfiguration:show()
self:parent():show()
just.doUntil(self.isShowing, 5)
return self
end
--- cp.apple.finalcutpro.inspector.audio.AudioConfiguration:doShow() -> cp.rx.go.Statement
--- Method
--- A Statement that will attempt to show the bar.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `Statement`, which will resolve to `true` if successful, or send an `error` if not.
function AudioConfiguration.lazy.method:doShow()
return self:parent():doShow():Label("AudioConfiguration:doShow")
end
return AudioConfiguration
|
--- === cp.apple.finalcutpro.inspector.audio.AudioConfiguration ===
---
--- The Audio Configuration section of the Audio Inspector.
local require = require
--local log = require("hs.logger").new("audioConfiguration")
local axutils = require("cp.ui.axutils")
local just = require("cp.just")
local ScrollArea = require("cp.ui.ScrollArea")
--------------------------------------------------------------------------------
--
-- THE MODULE:
--
--------------------------------------------------------------------------------
local AudioConfiguration = ScrollArea:subclass("cp.apple.finalcutpro.inspector.audio.AudioConfiguration")
--- cp.apple.finalcutpro.inspector.audio.AudioConfiguration.matches(element) -> boolean
--- Function
--- Checks to see if an element matches what we think it should be.
---
--- Parameters:
--- * element - An `axuielementObject` to check.
---
--- Returns:
--- * `true` if matches otherwise `false`
function AudioConfiguration.static.matches(element)
return ScrollArea.matches(element)
end
--- cp.apple.finalcutpro.inspector.audio.AudioConfiguration(parent) -> AudioConfiguration
--- Function
--- Creates a new Media Import object.
---
--- Parameters:
--- * parent - The parent object.
---
--- Returns:
--- * A new AudioConfiguration object.
function AudioConfiguration:initialize(parent)
local UI = parent.UI:mutate(function(original)
return axutils.cache(self, "_ui",
function()
local ui = original()
if ui then
local splitGroup = ui[1]
local scrollArea = splitGroup and axutils.childWithRole(splitGroup, "AXScrollArea")
return AudioConfiguration.matches(scrollArea) and scrollArea or nil
else
return nil
end
end,
AudioConfiguration.matches
)
end)
ScrollArea.initialize(self, parent, UI)
end
--- cp.apple.finalcutpro.inspector.audio.AudioConfiguration:enableCheckboxes() -> table
--- Method
--- Returns a table of `hs._asm.axuielement` objects for each enable/disable toggle.
---
--- Parameters:
--- * None
---
--- Returns:
--- * A table containing `hs._asm.axuielement` objects.
function AudioConfiguration.lazy.prop:enableCheckboxes()
return self.UI:mutate(function(original)
local ui = original()
local children = ui and ui:children()
local firstElement = true
local result = {}
local firstElementFrame = nil
for _, child in pairs(children) do
if firstElement then
if child:attributeValue("AXRole") == "AXButton" then
table.insert(result, child)
firstElementFrame = child:attributeValue("AXFrame")
firstElement = false
end
else
local childFrame = child:attributeValue("AXFrame")
if child:attributeValue("AXRole") == "AXButton" and childFrame.w == firstElementFrame.w and childFrame.h == firstElementFrame.h then
table.insert(result, child)
end
end
end
return result
end)
end
--- cp.apple.finalcutpro.inspector.audio.AudioConfiguration:show() -> self
--- Method
--- Attempts to show the bar.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `AudioConfiguration` instance.
function AudioConfiguration:show()
self:parent():show()
just.doUntil(self.isShowing, 5)
return self
end
--- cp.apple.finalcutpro.inspector.audio.AudioConfiguration:doShow() -> cp.rx.go.Statement
--- Method
--- A Statement that will attempt to show the bar.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `Statement`, which will resolve to `true` if successful, or send an `error` if not.
function AudioConfiguration.lazy.method:doShow()
return self:parent():doShow():Label("AudioConfiguration:doShow")
end
return AudioConfiguration
|
#1747
|
#1747
- Fixed @stickler-ci errors
|
Lua
|
mit
|
CommandPost/CommandPost,fcpxhacks/fcpxhacks,fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost
|
498d060da9c60732eb3c4a465b798f355e84c676
|
Interface/AddOns/RayUI/modules/map/worldmap.lua
|
Interface/AddOns/RayUI/modules/map/worldmap.lua
|
local R, L, P, G = unpack(select(2, ...)) --Import: Engine, Locales, ProfileDB, GlobalDB
local WM = R:NewModule("WorldMap", "AceEvent-3.0", "AceHook-3.0", "AceTimer-3.0")
--Cache global variables
--Lua functions
local _G = _G
local select, unpack = select, unpack
--WoW API / Variables
local CreateFrame = CreateFrame
local InCombatLockdown = InCombatLockdown
local SetUIPanelAttribute = SetUIPanelAttribute
local IsInInstance = IsInInstance
local GetPlayerMapPosition = GetPlayerMapPosition
local GetCursorPosition = GetCursorPosition
--Global variables that we don't cache, list them here for the mikk's Find Globals script
-- GLOBALS: WorldMapFrame, WorldMapFrameSizeUpButton, WorldMapFrameSizeDownButton, CoordsHolder, PLAYER
-- GLOBALS: WorldMapDetailFrame, MOUSE_LABEL, DropDownList1, NumberFontNormal, BlackoutWorld
-- GLOBALS: WORLDMAP_SETTINGS, WORLDMAP_FULLMAP_SIZE, WORLDMAP_WINDOWED_SIZE
WM.modName = L["世界地图"]
function WM:SetLargeWorldMap()
if InCombatLockdown() then return end
WorldMapFrame:SetParent(R.UIParent)
WorldMapFrame:EnableKeyboard(false)
WorldMapFrame:SetScale(1)
WorldMapFrame:EnableMouse(true)
if WorldMapFrame:GetAttribute("UIPanelLayout-area") ~= "center" then
SetUIPanelAttribute(WorldMapFrame, "area", "center");
end
if WorldMapFrame:GetAttribute("UIPanelLayout-allowOtherPanels") ~= true then
SetUIPanelAttribute(WorldMapFrame, "allowOtherPanels", true)
end
WorldMapFrameSizeUpButton:Hide()
WorldMapFrameSizeDownButton:Show()
WorldMapFrame:ClearAllPoints()
WorldMapFrame:SetPoint("CENTER", R.UIParent, "CENTER", 0, 100)
WorldMapFrame:SetSize(1002, 668)
end
function WM:SetSmallWorldMap()
if InCombatLockdown() then return; end
WorldMapFrameSizeUpButton:Show()
WorldMapFrameSizeDownButton:Hide()
end
function WM:PLAYER_REGEN_ENABLED()
WorldMapFrameSizeDownButton:Enable()
WorldMapFrameSizeUpButton:Enable()
end
function WM:PLAYER_REGEN_DISABLED()
WorldMapFrameSizeDownButton:Disable()
WorldMapFrameSizeUpButton:Disable()
end
function WM:UpdateCoords()
if not WorldMapFrame:IsShown() then return end
local inInstance, _ = IsInInstance()
local x, y = GetPlayerMapPosition("player")
x = R:Round(100 * x, 2)
y = R:Round(100 * y, 2)
if x ~= 0 and y ~= 0 then
CoordsHolder.playerCoords:SetText(PLAYER..": "..x..", "..y)
else
CoordsHolder.playerCoords:SetText(nil)
end
local scale = WorldMapDetailFrame:GetEffectiveScale()
local width = WorldMapDetailFrame:GetWidth()
local height = WorldMapDetailFrame:GetHeight()
local centerX, centerY = WorldMapDetailFrame:GetCenter()
local x, y = GetCursorPosition()
local adjustedX = (x / scale - (centerX - (width/2))) / width
local adjustedY = (centerY + (height/2) - y / scale) / height
if (adjustedX >= 0 and adjustedY >= 0 and adjustedX <= 1 and adjustedY <= 1) then
adjustedX = R:Round(100 * adjustedX, 2)
adjustedY = R:Round(100 * adjustedY, 2)
CoordsHolder.mouseCoords:SetText(MOUSE_LABEL..": "..adjustedX..", "..adjustedY)
else
CoordsHolder.mouseCoords:SetText(nil)
end
end
function WM:ResetDropDownListPosition(frame)
DropDownList1:ClearAllPoints()
DropDownList1:Point("TOPRIGHT", frame, "BOTTOMRIGHT", -17, -4)
end
function WM:Initialize()
local CoordsHolder = CreateFrame("Frame", "CoordsHolder", WorldMapFrame)
CoordsHolder:SetFrameLevel(WorldMapDetailFrame:GetFrameLevel() + 1)
CoordsHolder:SetFrameStrata(WorldMapDetailFrame:GetFrameStrata())
CoordsHolder.playerCoords = CoordsHolder:CreateFontString(nil, "OVERLAY")
CoordsHolder.mouseCoords = CoordsHolder:CreateFontString(nil, "OVERLAY")
CoordsHolder.playerCoords:SetFontObject(NumberFontNormal)
CoordsHolder.mouseCoords:SetFontObject(NumberFontNormal)
CoordsHolder.playerCoords:SetText(PLAYER..": 0, 0")
CoordsHolder.mouseCoords:SetText(MOUSE_LABEL..": 0, 0")
CoordsHolder.playerCoords:SetPoint("BOTTOMLEFT", WorldMapFrame.UIElementsFrame, "BOTTOMLEFT", 5, 5)
CoordsHolder.mouseCoords:SetPoint("BOTTOMLEFT", CoordsHolder.playerCoords, "TOPLEFT")
self:ScheduleRepeatingTimer("UpdateCoords", 0.05)
BlackoutWorld:SetTexture(nil)
self:SecureHook("WorldMap_ToggleSizeDown", "SetSmallWorldMap")
self:SecureHook("WorldMap_ToggleSizeUp", "SetLargeWorldMap")
self:RegisterEvent("PLAYER_REGEN_ENABLED")
self:RegisterEvent("PLAYER_REGEN_DISABLED")
if WORLDMAP_SETTINGS.size == WORLDMAP_FULLMAP_SIZE then
self:SetLargeWorldMap()
elseif WORLDMAP_SETTINGS.size == WORLDMAP_WINDOWED_SIZE then
self:SetSmallWorldMap()
end
end
function WM:Info()
return L["|cff7aa6d6Ray|r|cffff0000U|r|cff7aa6d6I|r世界地图模块."]
end
R:RegisterModule(WM:GetName())
|
local R, L, P, G = unpack(select(2, ...)) --Import: Engine, Locales, ProfileDB, GlobalDB
local WM = R:NewModule("WorldMap", "AceEvent-3.0", "AceHook-3.0", "AceTimer-3.0")
--Cache global variables
--Lua functions
local _G = _G
local select, unpack = select, unpack
--WoW API / Variables
local CreateFrame = CreateFrame
local InCombatLockdown = InCombatLockdown
local SetUIPanelAttribute = SetUIPanelAttribute
local IsInInstance = IsInInstance
local GetPlayerMapPosition = GetPlayerMapPosition
local GetCursorPosition = GetCursorPosition
--Global variables that we don't cache, list them here for the mikk's Find Globals script
-- GLOBALS: WorldMapFrame, WorldMapFrameSizeUpButton, WorldMapFrameSizeDownButton, CoordsHolder, PLAYER
-- GLOBALS: WorldMapDetailFrame, MOUSE_LABEL, DropDownList1, NumberFontNormal, BlackoutWorld
-- GLOBALS: WORLDMAP_SETTINGS, WORLDMAP_FULLMAP_SIZE, WORLDMAP_WINDOWED_SIZE
WM.modName = L["世界地图"]
function WM:SetLargeWorldMap()
if InCombatLockdown() then return end
WorldMapFrame:SetParent(R.UIParent)
WorldMapFrame:EnableKeyboard(false)
WorldMapFrame:SetScale(1)
WorldMapFrame:EnableMouse(true)
if WorldMapFrame:GetAttribute("UIPanelLayout-area") ~= "center" then
SetUIPanelAttribute(WorldMapFrame, "area", "center");
end
if WorldMapFrame:GetAttribute("UIPanelLayout-allowOtherPanels") ~= true then
SetUIPanelAttribute(WorldMapFrame, "allowOtherPanels", true)
end
WorldMapFrameSizeUpButton:Hide()
WorldMapFrameSizeDownButton:Show()
WorldMapFrame:ClearAllPoints()
WorldMapFrame:SetPoint("CENTER", R.UIParent, "CENTER", 0, 100)
WorldMapFrame:SetSize(1002, 668)
end
function WM:SetSmallWorldMap()
if InCombatLockdown() then return; end
WorldMapFrameSizeUpButton:Show()
WorldMapFrameSizeDownButton:Hide()
end
function WM:PLAYER_REGEN_ENABLED()
WorldMapFrameSizeDownButton:Enable()
WorldMapFrameSizeUpButton:Enable()
end
function WM:PLAYER_REGEN_DISABLED()
WorldMapFrameSizeDownButton:Disable()
WorldMapFrameSizeUpButton:Disable()
end
function WM:ResetDropDownListPosition(frame)
DropDownList1:ClearAllPoints()
DropDownList1:Point("TOPRIGHT", frame, "BOTTOMRIGHT", -17, -4)
end
local inRestrictedArea = false
function WM:PLAYER_ENTERING_WORLD()
local x = GetPlayerMapPosition("player")
if not x then
inRestrictedArea = true
self:CancelTimer(self.CoordsTimer)
self.CoordsTimer = nil
CoordsHolder.playerCoords:SetText("")
CoordsHolder.mouseCoords:SetText("")
elseif not self.CoordsTimer then
inRestrictedArea = false
self.CoordsTimer = self:ScheduleRepeatingTimer("UpdateCoords", 0.05)
end
end
function WM:UpdateCoords()
if not WorldMapFrame:IsShown() then return end
local inInstance, _ = IsInInstance()
local x, y = GetPlayerMapPosition("player")
x = R:Round(100 * x, 2)
y = R:Round(100 * y, 2)
if x ~= 0 and y ~= 0 then
CoordsHolder.playerCoords:SetText(PLAYER..": "..x..", "..y)
else
CoordsHolder.playerCoords:SetText(nil)
end
local scale = WorldMapDetailFrame:GetEffectiveScale()
local width = WorldMapDetailFrame:GetWidth()
local height = WorldMapDetailFrame:GetHeight()
local centerX, centerY = WorldMapDetailFrame:GetCenter()
local x, y = GetCursorPosition()
local adjustedX = (x / scale - (centerX - (width/2))) / width
local adjustedY = (centerY + (height/2) - y / scale) / height
if (adjustedX >= 0 and adjustedY >= 0 and adjustedX <= 1 and adjustedY <= 1) then
adjustedX = R:Round(100 * adjustedX, 2)
adjustedY = R:Round(100 * adjustedY, 2)
CoordsHolder.mouseCoords:SetText(MOUSE_LABEL..": "..adjustedX..", "..adjustedY)
else
CoordsHolder.mouseCoords:SetText(nil)
end
end
function WM:Initialize()
local CoordsHolder = CreateFrame("Frame", "CoordsHolder", WorldMapFrame)
CoordsHolder:SetFrameLevel(WorldMapDetailFrame:GetFrameLevel() + 1)
CoordsHolder:SetFrameStrata(WorldMapDetailFrame:GetFrameStrata())
CoordsHolder.playerCoords = CoordsHolder:CreateFontString(nil, "OVERLAY")
CoordsHolder.mouseCoords = CoordsHolder:CreateFontString(nil, "OVERLAY")
CoordsHolder.playerCoords:SetFontObject(NumberFontNormal)
CoordsHolder.mouseCoords:SetFontObject(NumberFontNormal)
CoordsHolder.playerCoords:SetText(PLAYER..": 0, 0")
CoordsHolder.mouseCoords:SetText(MOUSE_LABEL..": 0, 0")
CoordsHolder.playerCoords:SetPoint("BOTTOMLEFT", WorldMapFrame.UIElementsFrame, "BOTTOMLEFT", 5, 5)
CoordsHolder.mouseCoords:SetPoint("BOTTOMLEFT", CoordsHolder.playerCoords, "TOPLEFT")
self.CoordsTimer = self:ScheduleRepeatingTimer("UpdateCoords", 0.05)
self:RegisterEvent("PLAYER_ENTERING_WORLD")
BlackoutWorld:SetTexture(nil)
self:SecureHook("WorldMap_ToggleSizeDown", "SetSmallWorldMap")
self:SecureHook("WorldMap_ToggleSizeUp", "SetLargeWorldMap")
self:RegisterEvent("PLAYER_REGEN_ENABLED")
self:RegisterEvent("PLAYER_REGEN_DISABLED")
if WORLDMAP_SETTINGS.size == WORLDMAP_FULLMAP_SIZE then
self:SetLargeWorldMap()
elseif WORLDMAP_SETTINGS.size == WORLDMAP_WINDOWED_SIZE then
self:SetSmallWorldMap()
end
end
function WM:Info()
return L["|cff7aa6d6Ray|r|cffff0000U|r|cff7aa6d6I|r世界地图模块."]
end
R:RegisterModule(WM:GetName())
|
fix #4.
|
fix #4.
|
Lua
|
mit
|
fgprodigal/RayUI
|
2049f5badbd3be66ee6cbff76cf219825bff4aab
|
lua/parse/char/utf8/tools.lua
|
lua/parse/char/utf8/tools.lua
|
local strbyte, strchar = string.byte, string.char
local strsub = string.sub
local contiguous_byte_ranges = require 'parse.char.utf8.data.contiguous_byte_ranges'
local blob_tools = require 'parse.blob.tools'
local next_blob = blob_tools.next
local previous_blob = blob_tools.previous
local special_next = {}
local special_previous = {}
for i = 2, #contiguous_byte_ranges do
local current = contiguous_byte_ranges[i]
local previous = contiguous_byte_ranges[i - 1]
special_next[previous.max] = current.min
special_previous[current.min] = previous.max
end
local tools = {}
local function next_80_BF(v)
local last_byte = strbyte(v, -1)
local rest = strsub(v, 1, -2)
if last_byte == 0xBF then
return next_80_BF(rest) .. '\x80'
end
return rest .. strchar(last_byte + 1)
end
local function next_char(v)
if v < '\x80' then
return next_blob(v)
end
local last_byte = strbyte(v, -1)
if last_byte ~= 0xBF then
return next_blob(v)
end
local special = special_next[v]
if special then
return special
end
return next_80_BF(strsub(v,1,-2)) .. '\x80'
end
tools.next = next_char
local function previous_80_BF(v)
local last_byte = strbyte(v, -1)
local rest = strsub(v, 1, -2)
if last_byte == 0x80 then
return previous_80_BF(rest) .. '\xBF'
end
return rest .. strchar(last_byte - 1)
end
local function previous_char(v)
if v < '\x80' then
return previous_blob(v)
end
local last_byte = strbyte(v, -1)
if last_byte ~= 0x80 then
return previous_blob(v)
end
local special = special_previous[v]
if special then
return special
end
return previous_80_BF(strsub(v,1,-2)) .. '\xBF'
end
tools.previous = previous_char
local function range_aux(final_char, ref_char)
local char = next_char(ref_char)
if char > final_char then
return nil
end
return char
end
function tools.range(from_char, to_char)
return range_aux, to_char, previous_char(from_char)
end
return tools
|
local strbyte, strchar = string.byte, string.char
local strsub = string.sub
local contiguous_byte_ranges = require 'parse.char.utf8.data.contiguous_byte_ranges'
local blob_tools = require 'parse.blob.tools'
local next_blob = blob_tools.next
local previous_blob = blob_tools.previous
local special_next = {}
local special_previous = {}
for i = 2, #contiguous_byte_ranges do
local current = contiguous_byte_ranges[i]
local previous = contiguous_byte_ranges[i - 1]
special_next[previous.max] = current.min
special_previous[current.min] = previous.max
end
local tools = {}
local function next_80_BF(v)
local last_byte = strbyte(v, -1)
local rest = strsub(v, 1, -2)
if last_byte == 0xBF then
return next_80_BF(rest) .. '\x80'
end
return rest .. strchar(last_byte + 1)
end
local function next_char(v)
if v == '\x7F' then
return '\u{80}'
elseif v < '\x7F' then
return next_blob(v)
end
local last_byte = strbyte(v, -1)
if last_byte ~= 0xBF then
return next_blob(v)
end
local special = special_next[v]
if special then
return special
end
return next_80_BF(strsub(v,1,-2)) .. '\x80'
end
tools.next = next_char
local function previous_80_BF(v)
local last_byte = strbyte(v, -1)
local rest = strsub(v, 1, -2)
if last_byte == 0x80 then
return previous_80_BF(rest) .. '\xBF'
end
return rest .. strchar(last_byte - 1)
end
local function previous_char(v)
if v == '\u{80}' then
return '\x7F'
elseif v < '\u{80}' then
return previous_blob(v)
end
local last_byte = strbyte(v, -1)
if last_byte ~= 0x80 then
return previous_blob(v)
end
local special = special_previous[v]
if special then
return special
end
return previous_80_BF(strsub(v,1,-2)) .. '\xBF'
end
tools.previous = previous_char
local function range_aux(final_char, ref_char)
local char = next_char(ref_char)
if char > final_char then
return nil
end
return char
end
function tools.range(from_char, to_char)
return range_aux, to_char, previous_char(from_char)
end
return tools
|
More next/previous char edge case fixing
|
More next/previous char edge case fixing
|
Lua
|
mit
|
taxler/radish,taxler/radish,taxler/radish,taxler/radish,taxler/radish,taxler/radish
|
364c1b5c0bca6b81cd4bf90290cc6663889a33b2
|
worker.lua
|
worker.lua
|
#!/usr/bin/luajit
local io = require("io")
local os = require("os")
local string = require("string")
local http = require("socket.http")
local json = require("dkjson")
local memcache = require("memcached")
local nonblock = require("nonblock")
-- check effective uid
if io.popen("whoami"):read("*l") ~= "root" then
print("Need to be root.")
os.exit(1)
end
-- retrieve url from environment
local meeci_host = os.getenv("MEECI_HOST")
if not meeci_host then
print("MEECI_HOST is not defined.")
os.exit(2)
end
local meeci_http = "http://" .. meeci_host
local meeci_ftp = "ftp://" .. meeci_host .. "/meeci"
local mc = memcache.connect(meeci_host, 11211)
--< function definitions
function fwrite(fmt, ...)
return io.write(string.format(fmt, ...))
end
function sleep(n)
os.execute("sleep " .. tonumber(n))
end
-- luajit os.execute returns only the exit status
function execute(cmd)
print(cmd)
if _G.jit then
return os.execute(cmd) == 0
else
return os.execute(cmd)
end
end
-- return content of a file
function cat(file)
local stream = io.popen("cat " .. file)
local result = stream:read("*a")
stream:close()
return result
end
-- receive a task from meeci-web
function receive()
local body, code = http.request(meeci_http .. "/task")
if code == 200 then
return json.decode(body)
end
end
function log(task)
fwrite("[%s] %s %d: ", os.date(), task.type, task.id)
if task.type == "build" then
io.write(task.url .. '\n')
else
io.write(task.container .. '\n')
end
end
-- download files in /meeci/container
function wget(file)
local cmd = "wget -N " .. meeci_ftp .. "/containers/" .. file
return execute(cmd)
end
-- extract a container into 'container' directory
-- [args] container: container name with suffix .bz2
function tarx(container)
execute("rm -rf container && mkdir container")
return execute("tar xf " .. container .. " -C container")
end
-- download a shallow repository and its build script
function gitclone(task)
local dir = "container/opt/" .. task.repository
if not execute("mkdir -p " .. dir) then
return false
end
local cmd = "git clone --depth 30 -b %s %s %s"
cmd = string.format(cmd, task.branch, task.url, dir)
if not execute(cmd) then
return false
end
cmd = "cd " .. dir .. "; git checkout " .. task.commit
if not execute(cmd) then
return false
end
local url = meeci_http .. "/scripts/" .. task.id
cmd = "wget -O " .. dir .. "/meeci_build.sh " .. url
return execute(cmd)
end
-- inform meeci-web the result
function report(task, start, stop, code)
local str = json.encode({
type = task.type,
id = task.id,
start = start,
stop = stop,
exit = code
})
mc:set(string.sub(task.type, 1, 1) .. ":" .. task.id, str)
local path = string.format(
"/finish/%s/%d", task.type, task.id
)
http.request(meeci_http .. path, tostring(code))
end
-- compress and upload a new container
-- [args] container: container name with suffix .bz2
function upload(container)
execute("rm -f container/meeci_exit_status")
if execute("tar jcf container.bz2 -C container .") then
local url = meeci_ftp .. "/containers/" .. container
if execute("wput container.bz2 " .. url) then
os.remove("container.bz2")
return true
end
end
end
-- run a build task or create a container
function build(task)
local dir, script
if task.type == "build" then
dir = "/opt/" .. task.repository
script = "meeci_build.sh"
else
dir = "/root"
script = task.container .. ".sh"
end
local cmd = "cd %s; bash %s; echo -n $? > /meeci_exit_status"
cmd = string.format(cmd, dir, script)
cmd = string.format("systemd-nspawn -D ./container bash -c '%s'", cmd)
-- file log
local logdir = "/var/lib/meeci/worker/logs"
local log = string.format("%s/%s/%d.log", logdir, task.type, task.id)
log = io.open(log, 'a')
-- memcache log
local key = string.sub(task.type, 1, 1) .. "#" .. tostring(task.id)
mc:set(key, "")
local start = os.time()
local stream, fd = nonblock:popen(cmd)
while true do
local n, line = nonblock:read(fd)
if n == 0 then break end
log:write(line)
mc:append(key, line)
if n < 1000 then sleep(1) end
-- TODO: 10min and 60min limit
end
log:close()
nonblock:pclose(stream)
local stop = os.time()
local code = tonumber(cat("container/meeci_exit_status"))
report(task, start, stop, code)
if task.type == "build" then
return true
else
return upload(task.user .. "/" .. task.container .. ".bz2")
end
end
-->
local test = os.getenv("TEST") and true or false
if not test and not wget("meeci-minbase.bz2") then
print("Cannot wget meeci-minbase.bz2")
os.exit(3)
end
-- main loop --
local failure, idle = 0, os.time()
while not test do
local done = false
local task = receive()
if task then
log(task)
if task.type == "build" then
if not wget(task.user .. "/" .. task.container .. ".bz2") then
goto END_TASK
end
if not tarx(task.container .. ".bz2") then
goto END_TASK
end
os.remove(task.container .. ".bz2")
if not gitclone(task) then
goto END_TASK
end
else
if not tarx("meeci-minbase.bz2") then
goto END_TASK
end
local script = task.container .. ".sh"
if not wget(task.user .. "/" .. script) then
goto END_TASK
end
os.rename(script, "container/root/" .. script)
end
done = build(task)
::END_TASK::
execute("rm -rf container")
if done then
fwrite("[%s] succeed\n", os.date())
if failure > 0 then
failure = failure - 1
end
else
fwrite("[%s] fail\n", os.date())
failure = failure + 1
if failure == 10 then
fwrite("Worker stopped because of too many failures.\n")
os.exit(10)
end
end
idle = os.time()
end
-- TODO: sleep(1)
sleep(10)
if (os.time() - idle) % 60 == 0 then
local m = math.floor((os.time() - idle) / 60)
fwrite("[%s] idle for %d min\n", os.date(), m)
end
end
|
#!/usr/bin/luajit
local io = require("io")
local os = require("os")
local string = require("string")
local http = require("socket.http")
local json = require("dkjson")
local memcache = require("memcached")
local nonblock = require("nonblock")
-- check effective uid
if io.popen("whoami"):read("*l") ~= "root" then
print("Need to be root.")
os.exit(1)
end
-- retrieve url from environment
local meeci_host = os.getenv("MEECI_HOST")
if not meeci_host then
print("MEECI_HOST is not defined.")
os.exit(2)
end
local meeci_http = "http://" .. meeci_host
local meeci_ftp = "ftp://" .. meeci_host .. "/meeci"
local mc = memcache.connect(meeci_host, 11211)
--< function definitions
function fwrite(fmt, ...)
return io.write(string.format(fmt, ...))
end
function sleep(n)
os.execute("sleep " .. tonumber(n))
end
-- luajit os.execute returns only the exit status
function execute(cmd)
print(cmd)
if _G.jit then
return os.execute(cmd) == 0
else
return os.execute(cmd)
end
end
-- return content of a file
function cat(file)
local stream = io.popen("cat " .. file)
local result = stream:read("*a")
stream:close()
return result
end
-- receive a task from meeci-web
function receive()
local body, code = http.request(meeci_http .. "/task")
if code == 200 then
return json.decode(body)
end
end
function log(task)
fwrite("[%s] %s %d: ", os.date(), task.type, task.id)
if task.type == "build" then
io.write(task.url .. '\n')
else
io.write(task.container .. '\n')
end
end
-- download files in /meeci/container
function wget(file)
local cmd = "wget -N " .. meeci_ftp .. "/containers/" .. file
return execute(cmd)
end
-- extract a container into 'container' directory
-- [args] container: container name with suffix .bz2
function tarx(container)
execute("rm -rf container")
return execute("tar xf " .. container)
end
-- download a shallow repository and its build script
function gitclone(task)
local dir = "container/opt/" .. task.repository
if not execute("mkdir -p " .. dir) then
return false
end
local cmd = "git clone --depth 30 -b %s %s %s"
cmd = string.format(cmd, task.branch, task.url, dir)
if not execute(cmd) then
return false
end
cmd = "cd " .. dir .. "; git checkout " .. task.commit
if not execute(cmd) then
return false
end
local url = meeci_http .. "/scripts/" .. task.id
cmd = "wget -O " .. dir .. "/meeci_build.sh " .. url
return execute(cmd)
end
-- inform meeci-web the result
function report(task, start, stop, code)
local cmd = string.format(
"wput /var/lib/meeci/worker/logs/%s/%d.log " ..
meeci_ftp .. "/logs/%s/%d.log",
task.type, task.id, task.type, task.id
)
execute(cmd);
local str = json.encode({
user = task.user,
type = task.type,
id = task.id,
start = start,
stop = stop,
exit = code,
container = task.container
})
mc:set(string.sub(task.type, 1, 1) .. ":" .. task.id, str)
local path = string.format(
"/finish/%s/%d", task.type, task.id
)
http.request(meeci_http .. path, tostring(code))
print("POST " .. meeci_http .. path)
end
-- compress and upload a new container
-- [args] container: container name with suffix .bz2
function upload(container)
execute("rm -f container/meeci_exit_status")
-- TODO: file changed as we read it
execute("tar jcf container.bz2 container")
local url = meeci_ftp .. "/containers/" .. container
if execute("wput container.bz2 " .. url) then
os.remove("container.bz2")
return true
end
end
-- run a build task or create a container
function build(task)
local dir, script
if task.type == "build" then
dir = "/opt/" .. task.repository
script = "meeci_build.sh"
else
dir = "/root"
script = task.container .. ".sh"
end
local cmd = "cd %s; bash %s; echo -n $? > /meeci_exit_status"
cmd = string.format(cmd, dir, script)
cmd = string.format("systemd-nspawn -D ./container bash -c '%s'", cmd)
-- file log
local logdir = "/var/lib/meeci/worker/logs"
local log = string.format("%s/%s/%d.log", logdir, task.type, task.id)
log = io.open(log, 'a')
-- memcache log
local key = string.sub(task.type, 1, 1) .. "#" .. tostring(task.id)
mc:set(key, "")
local start = os.time()
local stream, fd = nonblock:popen(cmd)
while true do
local n, line = nonblock:read(fd)
if n == 0 then break end
log:write(line)
mc:append(key, line)
if n < 1000 then sleep(1) end
-- TODO: 10min and 60min limit
end
log:close()
nonblock:pclose(stream)
local stop = os.time()
local code = tonumber(cat("container/meeci_exit_status"))
if task.type == "build" then
report(task, start, stop, code)
return true
else
if (not upload(task.user .. "/" .. task.container .. ".bz2")) then
code = 21
end
report(task, start, stop, code)
return code == 0
end
end
-->
local test = os.getenv("TEST") and true or false
if not test and not wget("meeci-minbase.bz2") then
print("Cannot wget meeci-minbase.bz2")
os.exit(3)
end
-- main loop --
local failure, idle = 0, os.time()
while not test do
local done = false
local task = receive()
if task then
log(task)
if task.type == "build" then
if not wget(task.user .. "/" .. task.container .. ".bz2") then
goto END_TASK
end
if not tarx(task.container .. ".bz2") then
goto END_TASK
end
os.remove(task.container .. ".bz2")
if not gitclone(task) then
goto END_TASK
end
else
if not tarx("meeci-minbase.bz2") then
goto END_TASK
end
local script = task.container .. ".sh"
if not wget(task.user .. "/" .. script) then
goto END_TASK
end
os.rename(script, "container/root/" .. script)
end
done = build(task)
::END_TASK::
execute("rm -rf container")
if done then
fwrite("[%s] SUCCESS\n", os.date())
if failure > 0 then
failure = failure - 1
end
else
fwrite("[%s] ERROR\n", os.date())
failure = failure + 1
if failure == 10 then
fwrite("Worker stopped because of too many failures.\n")
os.exit(10)
end
end
idle = os.time()
end
-- TODO: sleep(1)
sleep(10)
if (os.time() - idle) % 600 == 0 then
local m = math.floor((os.time() - idle) / 60)
fwrite("[%s] idle for %d min\n", os.date(), m)
end
end
|
to fix: tar file changed as we read it
|
to fix: tar file changed as we read it
|
Lua
|
mit
|
wizawu/meeci-worker
|
0d0c65524c086a80c07b0a3fd0f22daf272fecea
|
nova/object.lua
|
nova/object.lua
|
--- LuaNova's object module.
-- This module is used to create objects from prototypes, through the use of
-- the nova.object:new() method. It also defines a reference to a nil object,
-- which may be acquired with nova.object.nilref().
module ("nova.object", package.seeall) do
--- Local instance of the "nil object".
local nilref_ = {}
--- Returns the representation of the nil object.
-- @return An object reference to the nil object.
function nilref()
return nilref_
end
-- Recursive initialization.
local function init (obj, super)
if not super then return end
init(obj, super:__super())
if super.__init then
local init_type = type(super.__init)
if init_type == "function" then
super.__init(obj)
elseif init_type == "table" then
for k,v in pairs(super.__init) do
if not obj[k] then
obj[k] = clone(v)
end
end
end
end
end
--- Creates a new object from a prototype.
-- If the self object has an <code>__init</code> field as a function, it will
-- be applied to the new object. If it has an <code>__init</code> field as a
-- table, its contents will be cloned into the new object.
-- @param prototype A table containing the object's methods and the default
-- values of its attributes.
function nova.object:new (prototype)
prototype = prototype or {}
self.__index = rawget(self, "__index") or self
setmetatable(prototype, self)
init(prototype, self)
return prototype;
end
--- Clones an object.
-- @return A clone of this object.
function nova.object:clone ()
if type(self) ~= "table" then return self end
print "cloning..."
table.foreach(self, print)
local cloned = {}
for k,v in pairs(self) do
cloned[k] = clone(v)
end
local super = __super(self)
return super and super.new and super:new(cloned) or cloned
end
--- Returns the super class of an object.
-- @return The super class of an object.
function nova.object:__super ()
return self ~= nova.object and getmetatable(self) or nil
end
--- Makes a class module inherit from a table.
-- This function is to be used only when declaring modules, like this:
-- <p><code>
-- module ("my.module", nova.object.inherit(some_table))
-- </code></p>
-- This essentially makes the module inherit everything indexable from the
-- given table. It also turns the module into an object.
-- @param super A table from which the module will inherit.
function inherit (super)
return function (class)
class.__index = super
nova.object:new(class)
end
end
end
|
--- LuaNova's object module.
-- This module is used to create objects from prototypes, through the use of
-- the nova.object:new() method. It also defines a reference to a nil object,
-- which may be acquired with nova.object.nilref().
module ("nova.object", package.seeall) do
--- Local instance of the "nil object".
local nilref_ = {}
local base_object = {}
--- Returns the representation of the nil object.
-- @return An object reference to the nil object.
function nilref()
return nilref_
end
-- Recursive initialization.
local function init (obj, super)
if not super then return end
init(obj, super:__super())
if super.__init then
local init_type = type(super.__init)
if init_type == "function" then
super.__init(obj)
elseif init_type == "table" then
for k,v in pairs(super.__init) do
if not obj[k] then
obj[k] = clone(v)
end
end
end
end
end
--- Creates a new object from a prototype.
-- If the self object has an <code>__init</code> field as a function, it will
-- be applied to the new object. If it has an <code>__init</code> field as a
-- table, its contents will be cloned into the new object.
-- @param prototype A table containing the object's methods and the default
-- values of its attributes.
function base_object:new (prototype)
prototype = prototype or {}
self.__index = rawget(self, "__index") or self
setmetatable(prototype, self)
init(prototype, self)
return prototype;
end
function new (prototype, prototype2)
return prototype2
and base_object:new(prototype2)
or base_object:new(prototype)
end
--- Clones an object.
-- @return A clone of this object.
function base_object:clone ()
if type(self) ~= "table" then return self end
print "cloning..."
table.foreach(self, print)
local cloned = {}
for k,v in pairs(self) do
cloned[k] = clone(v)
end
local super = base_object.__super(self)
return super and super.new and super:new(cloned) or cloned
end
function clone (obj)
return base_object.clone(obj)
end
--- Returns the super class of an object.
-- @return The super class of an object.
function base_object:__super ()
return self ~= nova.object and getmetatable(self) or nil
end
--- Makes a class module inherit from a table.
-- This function is to be used only when declaring modules, like this:
-- <p><code>
-- module ("my.module", nova.object.inherit(some_table))
-- </code></p>
-- This essentially makes the module inherit everything indexable from the
-- given table. It also turns the module into an object.
-- @param super A table from which the module will inherit.
function inherit (super)
return function (class)
class.__index = super
nova.object:new(class)
end
end
end
|
Fixed nova.object visibility bug. Supposedly.
|
Fixed nova.object visibility bug. Supposedly.
|
Lua
|
mit
|
Kazuo256/luxproject
|
2e434cc4612cee2627717537f2895dc117edeabf
|
pages/library/support/get.lua
|
pages/library/support/get.lua
|
function get()
local data = {}
local groups = xml:unmarshalFile(serverPath .. "/data/XML/groups.xml")
data.list = {}
for _, group in pairs(groups.groups.group) do
if tonumber(group["-access"]) >= 1 then
data.list[group["-name"]] = db:query("SELECT name, lastlogin FROM players WHERE group_id = ?", group["-id"])
for _, player in pairs(data.list[group["-name"]]) do
player.lastlogin = time:parseUnix(player.lastlogin)
end
end
end
http:render("support.html", data)
end
|
function get()
local data = {}
local groups = xml:unmarshalFile(serverPath .. "/data/XML/groups.xml")
data.list = {}
for _, group in pairs(groups.groups.group) do
if tonumber(group["-access"]) >= 1 then
data.list[group["-name"]] = db:query("SELECT name, lastlogin FROM players WHERE group_id = ?", group["-id"])
if data.list[group["-name"]] then
for _, player in pairs(data.list[group["-name"]]) do
player.lastlogin = time:parseUnix(player.lastlogin)
end
end
end
end
http:render("support.html", data)
end
|
Fix support page when a group has no players
|
Fix support page when a group has no players
|
Lua
|
mit
|
Raggaer/castro,Raggaer/castro,Raggaer/castro
|
35691ffbc44f13236469628d2dba56a53484e6fb
|
modules/title/sites/komplett.lua
|
modules/title/sites/komplett.lua
|
local simplehttp = require'simplehttp'
local html2unicode = require'html'
local trim = function(s)
if(not s) then return end
return (string.gsub(s, "^%s*(.-)%s*$", "%1"))
end
local handler = function(queue, info)
local query = info.query
local path = info.path
if((query and query:match('sku=%d+')) or (path and path:match('/[^/]+/%d+'))) then
simplehttp(
info.url,
function(data, url, response)
local ins = function(out, fmt, ...)
for i=1, select('#', ...) do
local val = select(i, ...)
if(type(val) == 'nil' or val == -1) then
return
end
end
table.insert(
out,
string.format(fmt, ...)
)
end
local out = {}
local name = data:match('<h1 class="main%-header" itemprop="name">([^<]+)</h1>')
local desc = data:match('<h3 class="secondary%-header" itemprop="description">([^<]+)</h3>')
local price = data:match('<span itemprop="price"[^>]+>([^<]+)</span>')
local storage = data:match('<span class="stock%-details">(.-)</span>')
local bomb = data:match('<div class="bomb">.-<div class="value">([^<]+)</div>')
ins(out, '\002%s\002: ', html2unicode(name))
if(desc) then
ins(out, '%s ,', html2unicode(desc))
end
if(price) then
ins(out, '\002%s\002 ', trim(price))
end
local extra = {}
if(bomb) then
bomb = trim(bomb)
if(bomb:sub(1, 1) == '-') then
bomb = bomb:sub(2)
end
ins(extra, '%s off', bomb)
end
if(storage) then
storage = html2unicode(storage)
storage = trim(storage:gsub('<%/?[%w:]+.-%/?>', ''))
if(storage:sub(-1) == '.') then
storage = storage:sub(1, -2)
end
ins(extra, '%s', storage)
end
if(#extra > 0) then
ins(out, '(%s)', table.concat(extra, ', '))
end
queue:done(table.concat(out, ''))
end
)
return true
end
end
customHosts['komplett%.no'] = handler
customHosts['komplett%.dk'] = handler
customHosts['komplett%.se'] = handler
customHosts['inwarehouse%.se'] = handler
customHosts['mpx%.no'] = handler
|
local simplehttp = require'simplehttp'
local html2unicode = require'html'
local trim = function(s)
if(not s) then return end
return (string.gsub(s, "^%s*(.-)%s*$", "%1"))
end
local handler = function(queue, info)
local query = info.query
local path = info.path
if((query and query:match('sku=%d+')) or (path and path:match('/[^/]+/%d+'))) then
simplehttp(
info.url,
function(data, url, response)
local ins = function(out, fmt, ...)
for i=1, select('#', ...) do
local val = select(i, ...)
if(type(val) == 'nil' or val == -1) then
return
end
end
table.insert(
out,
string.format(fmt, ...)
)
end
local out = {}
local name = data:match('<h1 class="product%-main%-info%-webtext1" itemprop="name">([^<]+)</h1>')
local desc = data:match('<h2 class="product%-main%-info%-webtext2" itemprop="description">([^<]+)</h2>')
local price = data:match('<span class="product%-price%-now" itemprop=price content=.->([^<]+)</span>')
local storage = data:match('<span class="stockstatus%-stock%-details">([^<]+)</span>')
local bomb = data:match('<span.-class="prodpage-discount-label".->([^<]+)</span>')
ins(out, '\002%s\002: ', html2unicode(trim(name)))
if(desc) then
ins(out, '%s ,', html2unicode(trim(desc)))
end
if(price) then
ins(out, '\002%s\002 ', trim(price))
end
local extra = {}
if(bomb) then
bomb = trim(bomb)
if(bomb:sub(1, 1) == '-') then
bomb = bomb:sub(2)
end
ins(extra, '%s off', bomb)
end
if(storage) then
storage = html2unicode(storage)
storage = trim(storage:gsub('<%/?[%w:]+.-%/?>', ''))
if(storage:sub(-1) == '.') then
storage = storage:sub(1, -2)
end
ins(extra, '%s', storage)
end
if(#extra > 0) then
ins(out, '(%s)', table.concat(extra, ', '))
end
queue:done(table.concat(out, ''))
end
)
return true
end
end
customHosts['komplett%.no'] = handler
customHosts['komplett%.dk'] = handler
customHosts['komplett%.se'] = handler
customHosts['inwarehouse%.se'] = handler
customHosts['mpx%.no'] = handler
|
title/komplett: fix site plugin
|
title/komplett: fix site plugin
Former-commit-id: c13af0a9186ba7c47e4b1b072f3d8be7da43b45f [formerly daee3ecf69d0f83e8f58fd1fb2a2e989cd79a807]
Former-commit-id: 0577e5080bbc333fa882e723f578c498a21baa09
|
Lua
|
mit
|
torhve/ivar2,torhve/ivar2,torhve/ivar2,haste/ivar2
|
779480a50e424528c448cc7fcf6dcab51577149a
|
scen_edit/command/abstract_terrain_modify_command.lua
|
scen_edit/command/abstract_terrain_modify_command.lua
|
AbstractTerrainModifyCommand = Command:extends{}
AbstractTerrainModifyCommand.className = "AbstractTerrainModifyCommand"
Math = Math or {}
function Math.RoundInt(x, step)
x = math.round(x)
return x - x % step
end
local function rotate(x, y, rotation)
return x * math.cos(rotation) - y * math.sin(rotation),
x * math.sin(rotation) + y * math.cos(rotation)
end
local function GetRotatedSize(size, rotation)
return size * (
math.abs(math.sin(rotation)) +
math.abs(math.cos(rotation))
)
end
local once = true
local function generateMap(size, delta, shapeName, rotation, origSize)
local greyscale = SB.model.terrainManager:getShape(shapeName)
local sizeX, sizeZ = greyscale.sizeX, greyscale.sizeZ
local map = { sizeX = sizeX, sizeZ = sizeZ }
local res = greyscale.res
local scaleX = sizeX / (size)
local scaleZ = sizeZ / (size)
local parts = size / Game.squareSize + 1
local diffSize = size - origSize
local function getIndex(x, z)
local rx = math.min(sizeX-1, math.max(0, math.floor(scaleX * x)))
local rz = math.min(sizeZ-1, math.max(0, math.floor(scaleZ * z)))
local indx = rx * sizeX + rz
return indx
end
-- interpolates between four nearest points based on their distance
local function interpolate(x, z)
local rxRaw = scaleX * x
local rzRaw = scaleZ * z
local rx = math.floor(rxRaw)
local rz = math.floor(rzRaw)
local indx = rx * sizeX + rz
local i = (rxRaw > rx) and 1 or -1
local j = (rzRaw > rz) and 1 or -1
local dx = 1 - (rxRaw - rx)
local dz = 1 - (rzRaw - rz)
local value = res[indx] * dx * dz
+ res[indx + i * sizeX] * (1 - dx) * dz
+ res[indx + j] * dx * (1 - dz)
+ res[indx + i * sizeX + j] * (1 - dx) * (1 - dz)
local w = dx * dx + (1 - dx) * dz + dx * (1 - dz) + (1 - dx) * (1 - dz)
return value
end
Spring.Echo("diffSize", diffSize)
for x = 0, size, Game.squareSize do
for z = 0, size, Game.squareSize do
-- local rx, rz = x, z
local rx, rz = x - size, z - size
rx, rz = rotate(rx, rz, rotation)
rx, rz = rx + size, rz + size
-- rx, rz = rx + diffSize, rz + diffSize
if once then
Spring.Echo(("%d:%d, %d:%d"):format(x, z, rx, rz))
end
local diff
local indx = getIndex(rx, rz)
if indx > sizeX + 1 and indx < sizeX * (sizeX - 1) - 1 then
diff = interpolate(rx, rz)
else
diff = res[indx]
end
map[x + z * parts] = diff * delta
end
end
once = true
return map
end
local maps = {}
-- FIXME: ugly, rework
local function getMap(size, delta, shapeName, rotation, origSize)
local map = nil
local mapsByShape = maps[shapeName]
if not mapsByShape then
mapsByShape = {}
maps[shapeName] = mapsByShape
end
local mapsBySize = mapsByShape[size]
if not mapsBySize then
mapsBySize = {}
mapsByShape[size] = mapsBySize
end
local mapsByRotation = mapsBySize[rotation]
if not mapsByRotation then
mapsByRotation = {}
mapsBySize[rotation] = mapsByRotation
end
local map = mapsByRotation[delta]
if not map then
map = generateMap(size, delta, shapeName, rotation, origSize)
mapsByRotation[delta] = map
end
return map
end
function AbstractTerrainModifyCommand:GetHeightMapFunc(isUndo)
return function()
local rotation = math.rad(self.opts.rotation)
local size = self.opts.size
local rotatedSize = GetRotatedSize(size, rotation)
size = Math.RoundInt(size, Game.squareSize)
rotatedSize = Math.RoundInt(rotatedSize, Game.squareSize)
local origSize = size
size = rotatedSize
local map = getMap(size, self.opts.strength, self.opts.shapeName, rotation, origSize)
local centerX = self.opts.x
local centerZ = self.opts.z
local parts = size / Game.squareSize + 1
local dsh = Math.RoundInt((size - origSize) / 2, Game.squareSize)
local startX = Math.RoundInt(centerX - size + dsh, Game.squareSize)
local startZ = Math.RoundInt(centerZ - size + dsh, Game.squareSize)
if not isUndo then
-- calculate the changes only once so redoing the command is faster
if self.changes == nil then
self.changes = self:GenerateChanges({
startX = startX,
startZ = startZ,
parts = parts,
size = size,
isUndo = isUndo,
map = map,
})
end
for x = 0, size, Game.squareSize do
for z = 0, size, Game.squareSize do
local delta = self.changes[x + z * parts]
if delta ~= nil then
Spring.AddHeightMap(
x + startX,
z + startZ,
delta
)
end
end
end
else
for x = 0, size, Game.squareSize do
for z = 0, size, Game.squareSize do
local delta = self.changes[x + z * parts]
if delta ~= nil then
Spring.AddHeightMap(
x + startX,
z + startZ,
-delta
)
end
end
end
end
end
end
function AbstractTerrainModifyCommand:execute()
-- set it only once
if self.canExecute == nil then
-- check if shape is available
self.canExecute = SB.model.terrainManager:getShape(self.opts.shapeName) ~= nil
end
if self.canExecute then
Spring.SetHeightMapFunc(self:GetHeightMapFunc(false))
end
end
function AbstractTerrainModifyCommand:unexecute()
if self.canExecute then
Spring.SetHeightMapFunc(self:GetHeightMapFunc(true))
end
end
|
AbstractTerrainModifyCommand = Command:extends{}
AbstractTerrainModifyCommand.className = "AbstractTerrainModifyCommand"
Math = Math or {}
function Math.RoundInt(x, step)
x = math.round(x)
return x - x % step
end
local function rotate(x, y, rotation)
return x * math.cos(rotation) - y * math.sin(rotation),
x * math.sin(rotation) + y * math.cos(rotation)
end
local function GetRotatedSize(size, rotation)
return size * (
math.abs(math.sin(rotation)) +
math.abs(math.cos(rotation))
)
end
local function generateMap(size, delta, shapeName, rotation, origSize)
local greyscale = SB.model.terrainManager:getShape(shapeName)
local sizeX, sizeZ = greyscale.sizeX, greyscale.sizeZ
local map = { sizeX = sizeX, sizeZ = sizeZ }
local res = greyscale.res
local scaleX = sizeX / (size)
local scaleZ = sizeZ / (size)
local parts = size / Game.squareSize + 1
local function getIndex(x, z)
local rx = math.min(sizeX-1, math.max(0, math.floor(scaleX * x)))
local rz = math.min(sizeZ-1, math.max(0, math.floor(scaleZ * z)))
local indx = rx * sizeX + rz
return indx
end
-- interpolates between four nearest points based on their distance
local function interpolate(x, z)
local rxRaw = scaleX * x
local rzRaw = scaleZ * z
local rx = math.floor(rxRaw)
local rz = math.floor(rzRaw)
local indx = rx * sizeX + rz
local i = (rxRaw > rx) and 1 or -1
local j = (rzRaw > rz) and 1 or -1
local dx = 1 - (rxRaw - rx)
local dz = 1 - (rzRaw - rz)
local value = res[indx] * dx * dz
+ res[indx + i * sizeX] * (1 - dx) * dz
+ res[indx + j] * dx * (1 - dz)
+ res[indx + i * sizeX + j] * (1 - dx) * (1 - dz)
local w = dx * dx + (1 - dx) * dz + dx * (1 - dz) + (1 - dx) * (1 - dz)
return value
end
local sizeRatio = size / origSize
local dsh = (size - origSize) / 2
local sh = size / 2
for x = 0, size, Game.squareSize do
for z = 0, size, Game.squareSize do
local rx, rz = x, z
rx, rz = rx - sh, rz - sh
rx, rz = rotate(rx, rz, rotation)
rx, rz = rx + sh, rz + sh
rx, rz = rx * sizeRatio, rz * sizeRatio
rx, rz = rx - dsh, rz - dsh
local diff
-- we ignore points that fall outside of the original image (when rotated)
if rx < 0 or rz < 0 or scaleX * rx > sizeX-1 or scaleZ * rz > sizeZ-1 then
diff = 0
else
local indx = getIndex(rx, rz)
if indx > sizeX + 1 and indx < sizeX * (sizeX - 1) - 1 then
diff = interpolate(rx, rz)
else
diff = res[indx]
end
end
map[x + z * parts] = diff * delta
end
end
return map
end
local maps = {}
-- FIXME: ugly, rework
local function getMap(size, delta, shapeName, rotation, origSize)
local map = nil
local mapsByShape = maps[shapeName]
if not mapsByShape then
mapsByShape = {}
maps[shapeName] = mapsByShape
end
local mapsBySize = mapsByShape[size]
if not mapsBySize then
mapsBySize = {}
mapsByShape[size] = mapsBySize
end
local mapsByRotation = mapsBySize[rotation]
if not mapsByRotation then
mapsByRotation = {}
mapsBySize[rotation] = mapsByRotation
end
local map = mapsByRotation[delta]
if not map then
map = generateMap(size, delta, shapeName, rotation, origSize)
mapsByRotation[delta] = map
end
return map
end
function AbstractTerrainModifyCommand:GetHeightMapFunc(isUndo)
return function()
local rotation = math.rad(self.opts.rotation)
local size = self.opts.size
local rotatedSize = GetRotatedSize(size, rotation)
size = Math.RoundInt(size, Game.squareSize)
rotatedSize = Math.RoundInt(rotatedSize, Game.squareSize)
local origSize = size
size = rotatedSize
local map = getMap(size, self.opts.strength, self.opts.shapeName, rotation, origSize)
local centerX = self.opts.x
local centerZ = self.opts.z
local parts = size / Game.squareSize + 1
local dsh = Math.RoundInt((size - origSize) / 2, Game.squareSize)
local startX = Math.RoundInt(centerX - size + dsh, Game.squareSize)
local startZ = Math.RoundInt(centerZ - size + dsh, Game.squareSize)
if not isUndo then
-- calculate the changes only once so redoing the command is faster
if self.changes == nil then
self.changes = self:GenerateChanges({
startX = startX,
startZ = startZ,
parts = parts,
size = size,
isUndo = isUndo,
map = map,
})
end
for x = 0, size, Game.squareSize do
for z = 0, size, Game.squareSize do
local delta = self.changes[x + z * parts]
if delta ~= nil then
Spring.AddHeightMap(
x + startX,
z + startZ,
delta
)
end
end
end
else
for x = 0, size, Game.squareSize do
for z = 0, size, Game.squareSize do
local delta = self.changes[x + z * parts]
if delta ~= nil then
Spring.AddHeightMap(
x + startX,
z + startZ,
-delta
)
end
end
end
end
end
end
function AbstractTerrainModifyCommand:execute()
-- set it only once
if self.canExecute == nil then
-- check if shape is available
self.canExecute = SB.model.terrainManager:getShape(self.opts.shapeName) ~= nil
end
if self.canExecute then
Spring.SetHeightMapFunc(self:GetHeightMapFunc(false))
end
end
function AbstractTerrainModifyCommand:unexecute()
if self.canExecute then
Spring.SetHeightMapFunc(self:GetHeightMapFunc(true))
end
end
|
fix rotating brush patterns for synced operations; close #178
|
fix rotating brush patterns for synced operations; close #178
|
Lua
|
mit
|
Spring-SpringBoard/SpringBoard-Core,Spring-SpringBoard/SpringBoard-Core
|
413f4b7482a9b7dabaf3ac4e20d3cfb245357cf0
|
src/c3_spec.lua
|
src/c3_spec.lua
|
require "busted.runner" ()
local assert = require "luassert"
describe ("c3 algorithm implementation", function ()
it ("can be required", function()
assert.has.no.errors (function ()
require "c3"
end)
end)
it ("linearizes correctly a hierarchy", function ()
local c3 = require "c3"
local o = {}
local a = { o, }
local b = { o, }
local c = { o, }
local d = { o, }
local e = { o, }
local k1 = { c, b, a, }
local k2 = { e, b, d, }
local k3 = { d, a, }
local z = { k3, k2, k1, }
assert.are.same (c3 (o ), { o, })
assert.are.same (c3 (a ), { o, a, })
assert.are.same (c3 (b ), { o, b, })
assert.are.same (c3 (c ), { o, c, })
assert.are.same (c3 (d ), { o, d, })
assert.are.same (c3 (e ), { o, e, })
assert.are.same (c3 (k1), { o, c, b, a, k1, })
assert.are.same (c3 (k2), { o, e, b, d, k2, })
assert.are.same (c3 (k3), { o, a, d, k3, })
assert.are.same (c3 (z ), { o, e, c, b, a, d, k3, k2, k1, z, })
end)
it ("handles cycles", function ()
local c3 = require "c3"
local a, b = {}, {}
a [1] = b
b [1] = a
assert.are.same (c3 (a), { b, a, })
assert.are.same (c3 (b), { a, b, })
end)
it ("raises an error when linearization is not possible", function ()
local c3 = require "c3"
local a, b = {}, {}
a [1] = b
b [1] = a
local c = { a, b, }
local ok, err = pcall (c3, c)
assert.is_falsy (ok)
assert.is_truthy (err:match "linearization failed")
end)
end)
|
require "busted.runner" ()
local assert = require "luassert"
describe ("c3 algorithm implementation", function ()
it ("can be required", function()
assert.has.no.errors (function ()
require "c3"
end)
end)
it ("linearizes correctly a hierarchy", function ()
local C3 = require "c3"
local c3 = C3.new {
superclass = function (x) return x end,
}
local o = {}
local a = { o, }
local b = { o, }
local c = { o, }
local d = { o, }
local e = { o, }
local k1 = { c, b, a, }
local k2 = { e, b, d, }
local k3 = { d, a, }
local z = { k3, k2, k1, }
assert.are.same (c3 (o ), { o, })
assert.are.same (c3 (a ), { o, a, })
assert.are.same (c3 (b ), { o, b, })
assert.are.same (c3 (c ), { o, c, })
assert.are.same (c3 (d ), { o, d, })
assert.are.same (c3 (e ), { o, e, })
assert.are.same (c3 (k1), { o, c, b, a, k1, })
assert.are.same (c3 (k2), { o, e, b, d, k2, })
assert.are.same (c3 (k3), { o, a, d, k3, })
assert.are.same (c3 (z ), { o, e, c, b, a, d, k3, k2, k1, z, })
end)
it ("handles cycles", function ()
local C3 = require "c3"
local c3 = C3.new {
superclass = function (x) return x end,
}
local a, b = {}, {}
a [1] = b
b [1] = a
assert.are.same (c3 (a), { b, a, })
assert.are.same (c3 (b), { a, b, })
end)
it ("raises an error when linearization is not possible", function ()
local C3 = require "c3"
local c3 = C3.new {
superclass = function (x) return x end,
}
local a, b = {}, {}
a [1] = b
b [1] = a
local c = { a, b, }
local ok, err = pcall (c3, c)
assert.is_falsy (ok)
assert.is_truthy (err:match "linearization failed")
end)
end)
|
Fix tests.
|
Fix tests.
|
Lua
|
mit
|
saucisson/lua-c3
|
6587bd94be20707b017ae79905fcc5a68ed13d18
|
src/spy.lua
|
src/spy.lua
|
-- module will return spy table, and register its assertions with the main assert engine
local assert = require('luassert.assert')
local util = require('luassert.util')
-- Spy metatable
local spy_mt = {
__call = function(self, ...)
local arguments = {...}
arguments.n = select('#',...) -- add argument count for trailing nils
table.insert(self.calls, arguments)
return self.callback(...)
end }
local spy -- must make local before defining table, because table contents refers to the table (recursion)
spy = {
_ = {"don't care"},
new = function(callback)
if not util.callable(callback) then
error("Cannot spy on type '" .. type(callback) .. "', only on functions or callable elements", 2)
end
local s = setmetatable(
{
calls = {},
callback = callback,
target_table = nil, -- these will be set when using 'spy.on'
target_key = nil,
revert = function(self)
if not self.reverted then
if self.target_table and self.target_key then
self.target_table[self.target_key] = self.callback
end
self.reverted = true
end
return self.callback
end,
called = function(self, times, compare)
if times or compare then
local compare = compare or function(count, expected) return count == expected end
return compare(#self.calls, times), #self.calls
end
return (#self.calls > 0), #self.calls
end,
called_with = function(self, args)
local function deepcompare(t1, t2)
for k1,v1 in pairs(t1) do
local v2 = t2[k1]
if v2 == nil or v2 ~= spy._ and not util.deepcompare(v1,v2) then
return false
end
end
for k2,_ in pairs(t2) do
if t1[k2] == nil then return false end
end
return true
end
for _,v in ipairs(self.calls) do
if deepcompare(v, args) then
return true
end
end
return false
end
}, spy_mt)
assert:add_spy(s) -- register with the current state
return s
end,
is_spy = function(object)
return type(object) == "table" and getmetatable(object) == spy_mt
end,
on = function(target_table, target_key)
local s = spy.new(target_table[target_key])
target_table[target_key] = s
-- store original data
s.target_table = target_table
s.target_key = target_key
return s
end
}
local function set_spy(state)
end
local function called_with(state, arguments)
if rawget(state, "payload") and rawget(state, "payload").called_with then
return state.payload:called_with(arguments)
else
error("'called_with' must be chained after 'spy(aspy)'")
end
end
local function called(state, arguments, compare)
local num_times = arguments[1]
if not num_times and not state.mod then
state.mod = true
num_times = 0
end
if state.payload and type(state.payload) == "table" and state.payload.called then
local result, count = state.payload:called(num_times, compare)
arguments[1] = tostring(num_times or ">0")
table.insert(arguments, 2, tostring(count))
arguments.n = arguments.n + 1
arguments.nofmt = arguments.nofmt or {}
arguments.nofmt[1] = true
arguments.nofmt[2] = true
return result
elseif state.payload and type(state.payload) == "function" then
error("When calling 'spy(aspy)', 'aspy' must not be the original function, but the spy function replacing the original")
else
error("'called' must be chained after 'spy(aspy)'")
end
end
local function called_at_least(state, arguments)
return called(state, arguments, function(count, expected) return count >= expected end)
end
local function called_at_most(state, arguments)
return called(state, arguments, function(count, expected) return count <= expected end)
end
local function called_more_than(state, arguments)
return called(state, arguments, function(count, expected) return count > expected end)
end
local function called_less_than(state, arguments)
return called(state, arguments, function(count, expected) return count < expected end)
end
assert:register("modifier", "spy", set_spy)
assert:register("assertion", "called_with", called_with, "assertion.called_with.positive", "assertion.called_with.negative")
assert:register("assertion", "called", called, "assertion.called.positive", "assertion.called.negative")
assert:register("assertion", "called_at_least", called_at_least, "assertion.called_at_least.positive", "assertion.called_at_least.negative")
assert:register("assertion", "called_at_most", called_at_most, "assertion.called_at_most.positive", "assertion.called_at_most.negative")
assert:register("assertion", "called_more_than", called_more_than, "assertion.called_more_than.positive", "assertion.called_more_than.negative")
assert:register("assertion", "called_less_than", called_less_than, "assertion.called_less_than.positive", "assertion.called_less_than.negative")
return setmetatable(spy, {
__call = function(self, ...)
return spy.new(...)
end
})
|
-- module will return spy table, and register its assertions with the main assert engine
local assert = require('luassert.assert')
local util = require('luassert.util')
-- Spy metatable
local spy_mt = {
__call = function(self, ...)
local arguments = {...}
arguments.n = select('#',...) -- add argument count for trailing nils
table.insert(self.calls, arguments)
return self.callback(...)
end }
local spy -- must make local before defining table, because table contents refers to the table (recursion)
spy = {
_ = {"don't care"},
new = function(callback)
if not util.callable(callback) then
error("Cannot spy on type '" .. type(callback) .. "', only on functions or callable elements", 2)
end
local s = setmetatable(
{
calls = {},
callback = callback,
target_table = nil, -- these will be set when using 'spy.on'
target_key = nil,
revert = function(self)
if not self.reverted then
if self.target_table and self.target_key then
self.target_table[self.target_key] = self.callback
end
self.reverted = true
end
return self.callback
end,
called = function(self, times, compare)
if times or compare then
local compare = compare or function(count, expected) return count == expected end
return compare(#self.calls, times), #self.calls
end
return (#self.calls > 0), #self.calls
end,
called_with = function(self, args)
local function deepcompare(t1, t2)
for k1,v1 in pairs(t1) do
local v2 = t2[k1]
if v2 == nil or v2 ~= spy._ and not util.deepcompare(v1,v2) then
return false
end
end
for k2,_ in pairs(t2) do
if t1[k2] == nil then return false end
end
return true
end
for _,v in ipairs(self.calls) do
if deepcompare(v, args) then
return true
end
end
return false
end
}, spy_mt)
assert:add_spy(s) -- register with the current state
return s
end,
is_spy = function(object)
return type(object) == "table" and getmetatable(object) == spy_mt
end,
on = function(target_table, target_key)
local s = spy.new(target_table[target_key])
target_table[target_key] = s
-- store original data
s.target_table = target_table
s.target_key = target_key
return s
end
}
local function set_spy(state)
end
local function called_with(state, arguments)
local payload = rawget(state, "payload")
if payload and payload.called_with then
return state.payload:called_with(arguments)
else
error("'called_with' must be chained after 'spy(aspy)'")
end
end
local function called(state, arguments, compare)
local num_times = arguments[1]
if not num_times and not state.mod then
state.mod = true
num_times = 0
end
local payload = rawget(state, "payload")
if payload and type(payload) == "table" and payload.called then
local result, count = state.payload:called(num_times, compare)
arguments[1] = tostring(num_times or ">0")
util.tinsert(arguments, 2, tostring(count))
arguments.n = arguments.n + 1
arguments.nofmt = arguments.nofmt or {}
arguments.nofmt[1] = true
arguments.nofmt[2] = true
return result
elseif payload and type(payload) == "function" then
error("When calling 'spy(aspy)', 'aspy' must not be the original function, but the spy function replacing the original")
else
error("'called' must be chained after 'spy(aspy)'")
end
end
local function called_at_least(state, arguments)
return called(state, arguments, function(count, expected) return count >= expected end)
end
local function called_at_most(state, arguments)
return called(state, arguments, function(count, expected) return count <= expected end)
end
local function called_more_than(state, arguments)
return called(state, arguments, function(count, expected) return count > expected end)
end
local function called_less_than(state, arguments)
return called(state, arguments, function(count, expected) return count < expected end)
end
assert:register("modifier", "spy", set_spy)
assert:register("assertion", "called_with", called_with, "assertion.called_with.positive", "assertion.called_with.negative")
assert:register("assertion", "called", called, "assertion.called.positive", "assertion.called.negative")
assert:register("assertion", "called_at_least", called_at_least, "assertion.called_at_least.positive", "assertion.called_at_least.negative")
assert:register("assertion", "called_at_most", called_at_most, "assertion.called_at_most.positive", "assertion.called_at_most.negative")
assert:register("assertion", "called_more_than", called_more_than, "assertion.called_more_than.positive", "assertion.called_more_than.negative")
assert:register("assertion", "called_less_than", called_less_than, "assertion.called_less_than.positive", "assertion.called_less_than.negative")
return setmetatable(spy, {
__call = function(self, ...)
return spy.new(...)
end
})
|
Fix called and called_with assertions
|
Fix called and called_with assertions
Need to use `rawget(state, "payload")` instead of `state.payload`
since `state.payload` will never return `nil`. Also use `util.tinsert`
instead of `table.insert` to respect `nil` values.
|
Lua
|
mit
|
mpeterv/luassert,ZyX-I/luassert,o-lim/luassert
|
e5890bab7fd36dfb553935413b97c3a87ac1ddad
|
util/datamanager.lua
|
util/datamanager.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 format = string.format;
local setmetatable, type = setmetatable, type;
local pairs, ipairs = pairs, ipairs;
local char = string.char;
local loadfile, setfenv, pcall = loadfile, setfenv, pcall;
local log = require "util.logger".init("datamanager");
local io_open = io.open;
local os_remove = os.remove;
local io_popen = io.popen;
local tostring, tonumber = tostring, tonumber;
local error = error;
local next = next;
local t_insert = table.insert;
local append = require "util.serialization".append;
local path_separator = "/"; if os.getenv("WINDIR") then path_separator = "\\" end
module "datamanager"
---- utils -----
local encode, decode;
do
local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end });
decode = function (s)
return s and (s:gsub("+", " "):gsub("%%([a-fA-F0-9][a-fA-F0-9])", urlcodes));
end
encode = function (s)
return s and (s:gsub("%W", function (c) return format("%%%02x", c:byte()); end));
end
end
local _mkdir = {};
local function mkdir(path)
path = path:gsub("/", path_separator); -- TODO as an optimization, do this during path creation rather than here
if not _mkdir[path] then
local x = io_popen("mkdir \""..path.."\" 2>&1"):read("*a");
_mkdir[path] = true;
end
return path;
end
local data_path = "data";
------- API -------------
function set_data_path(path)
log("info", "Setting data path to: %s", path);
data_path = path;
end
function getpath(username, host, datastore, ext, create)
ext = ext or "dat";
host = host and encode(host);
username = username and encode(username);
if username then
if create then mkdir(mkdir(mkdir(data_path).."/"..host).."/"..datastore); end
return format("%s/%s/%s/%s.%s", data_path, host, datastore, username, ext);
elseif host then
if create then mkdir(mkdir(data_path).."/"..host); end
return format("%s/%s/%s.%s", data_path, host, datastore, ext);
else
if create then mkdir(data_path); end
return format("%s/%s.%s", data_path, datastore, ext);
end
end
function load(username, host, datastore)
local data, ret = loadfile(getpath(username, host, datastore));
if not data then
log("debug", "Failed to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
return nil;
end
setfenv(data, {});
local success, ret = pcall(data);
if not success then
log("error", "Unable to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
return nil;
end
return ret;
end
function store(username, host, datastore, data)
if not data then
data = {};
end
-- save the datastore
local f, msg = io_open(getpath(username, host, datastore, nil, true), "w+");
if not f then
log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil"));
return;
end
f:write("return ");
append(f, data);
f:close();
if not next(data) then -- try to delete empty datastore
os_remove(getpath(username, host, datastore));
end
-- we write data even when we are deleting because lua doesn't have a
-- platform independent way of checking for non-exisitng files
return true;
end
function list_append(username, host, datastore, data)
if not data then return; end
-- save the datastore
local f, msg = io_open(getpath(username, host, datastore, "list", true), "a+");
if not f then
log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil"));
return;
end
f:write("item(");
append(f, data);
f:write(");\n");
f:close();
return true;
end
function list_store(username, host, datastore, data)
if not data then
data = {};
end
-- save the datastore
local f, msg = io_open(getpath(username, host, datastore, "list", true), "w+");
if not f then
log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil"));
return;
end
for _, d in ipairs(data) do
f:write("item(");
append(f, d);
f:write(");\n");
end
f:close();
if not next(data) then -- try to delete empty datastore
os_remove(getpath(username, host, datastore, "list"));
end
-- we write data even when we are deleting because lua doesn't have a
-- platform independent way of checking for non-exisitng files
return true;
end
function list_load(username, host, datastore)
local data, ret = loadfile(getpath(username, host, datastore, "list"));
if not data then
log("debug", "Failed to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
return nil;
end
local items = {};
setfenv(data, {item = function(i) t_insert(items, i); end});
local success, ret = pcall(data);
if not success then
log("error", "Unable to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
return nil;
end
return items;
end
return _M;
|
-- 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 format = string.format;
local setmetatable, type = setmetatable, type;
local pairs, ipairs = pairs, ipairs;
local char = string.char;
local loadfile, setfenv, pcall = loadfile, setfenv, pcall;
local log = require "util.logger".init("datamanager");
local io_open = io.open;
local os_remove = os.remove;
local io_popen = io.popen;
local tostring, tonumber = tostring, tonumber;
local error = error;
local next = next;
local t_insert = table.insert;
local append = require "util.serialization".append;
local path_separator = "/"; if os.getenv("WINDIR") then path_separator = "\\" end
module "datamanager"
---- utils -----
local encode, decode;
do
local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end });
decode = function (s)
return s and (s:gsub("+", " "):gsub("%%([a-fA-F0-9][a-fA-F0-9])", urlcodes));
end
encode = function (s)
return s and (s:gsub("%W", function (c) return format("%%%02x", c:byte()); end));
end
end
local _mkdir = {};
local function mkdir(path)
path = path:gsub("/", path_separator); -- TODO as an optimization, do this during path creation rather than here
if not _mkdir[path] then
local x = io_popen("mkdir \""..path.."\" 2>&1"):read("*a");
_mkdir[path] = true;
end
return path;
end
local data_path = "data";
------- API -------------
function set_data_path(path)
log("info", "Setting data path to: %s", path);
data_path = path;
end
function getpath(username, host, datastore, ext, create)
ext = ext or "dat";
host = host and encode(host);
username = username and encode(username);
if username then
if create then mkdir(mkdir(mkdir(data_path).."/"..host).."/"..datastore); end
return format("%s/%s/%s/%s.%s", data_path, host, datastore, username, ext);
elseif host then
if create then mkdir(mkdir(data_path).."/"..host); end
return format("%s/%s/%s.%s", data_path, host, datastore, ext);
else
if create then mkdir(data_path); end
return format("%s/%s.%s", data_path, datastore, ext);
end
end
function load(username, host, datastore)
local data, ret = loadfile(getpath(username, host, datastore));
if not data then
log("debug", "Failed to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
return nil;
end
setfenv(data, {});
local success, ret = pcall(data);
if not success then
log("error", "Unable to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
return nil;
end
return ret;
end
function store(username, host, datastore, data)
if not data then
data = {};
end
-- save the datastore
local f, msg = io_open(getpath(username, host, datastore, nil, true), "w+");
if not f then
log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil"));
return;
end
f:write("return ");
append(f, data);
f:close();
if next(data) == nil then -- try to delete empty datastore
log("debug", "Removing empty %s datastore for user %s@%s", datastore, username, host);
os_remove(getpath(username, host, datastore));
end
-- we write data even when we are deleting because lua doesn't have a
-- platform independent way of checking for non-exisitng files
return true;
end
function list_append(username, host, datastore, data)
if not data then return; end
-- save the datastore
local f, msg = io_open(getpath(username, host, datastore, "list", true), "a+");
if not f then
log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil"));
return;
end
f:write("item(");
append(f, data);
f:write(");\n");
f:close();
return true;
end
function list_store(username, host, datastore, data)
if not data then
data = {};
end
-- save the datastore
local f, msg = io_open(getpath(username, host, datastore, "list", true), "w+");
if not f then
log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil"));
return;
end
for _, d in ipairs(data) do
f:write("item(");
append(f, d);
f:write(");\n");
end
f:close();
if next(data) == nil then -- try to delete empty datastore
log("debug", "Removing empty %s datastore for user %s@%s", datastore, username, host);
os_remove(getpath(username, host, datastore, "list"));
end
-- we write data even when we are deleting because lua doesn't have a
-- platform independent way of checking for non-exisitng files
return true;
end
function list_load(username, host, datastore)
local data, ret = loadfile(getpath(username, host, datastore, "list"));
if not data then
log("debug", "Failed to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
return nil;
end
local items = {};
setfenv(data, {item = function(i) t_insert(items, i); end});
local success, ret = pcall(data);
if not success then
log("error", "Unable to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
return nil;
end
return items;
end
return _M;
|
util.datamanager: Don't delete data when first entry in table is 'false'. My favourite bug so far.
|
util.datamanager: Don't delete data when first entry in table is 'false'. My favourite bug so far.
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
4bcb891c5c628cda37b9ce1080d488d482079f8e
|
board.lua
|
board.lua
|
T = require("tictaclib")
local Board = {} -- 9x9 board
local SBoard = {} -- 3x3 board
SBoard.tostring = function(self)
local ret = T.StringBuffer()
for x = 1, 3 do
for y = 1, 3 do
ret = ret .. (self[x][y] == nil and "-" or self[x][y]) .. " "
end
ret = ret .. "\n"
end
return tostring(ret)
end
SBoard.new = function()
local sboard = {
{nil, nil, nil},
{nil, nil, nil},
{nil, nil, nil}
}
setmetatable(sboard, {__tostring=SBoard.tostring})
return sboard
end
Board.tostring = function(self)
local ret = T.StringBuffer()
for y1 = 1, 3 do
for y2 = 1, 3 do
for x1 = 1, 3 do
for x2 = 1, 3 do
local i = self[y1][x1][y2][x2]
ret = ret .. (i == nil and "-" or i) .. " "
end
ret = ret .. " "
end
ret = ret .. "\n"
end
ret = ret .. "\n"
end
return tostring(ret)
end
Board.new = function()
local board = {
{SBoard.new(), SBoard.new(), SBoard.new()},
{SBoard.new(), SBoard.new(), SBoard.new()},
{SBoard.new(), SBoard.new(), SBoard.new()}
}
setmetatable(board, {__tostring=Board.tostring})
return board
end
Board.copy = function(self)
local board = Board.new()
for x1 = 1, 3 do
for y1 = 1, 3 do
for x2 = 1, 3 do
for y2 = 1, 3 do
board[x1][y1][x2][y2] = self[x1][y1][x2][y2]
end
end
end
end
return board
end
-- Check state of a 3x3 board. Possible return values:
-- "draw", "x", "o", nil (continue)
SBoard.state = function(self)
local choices = { -- diagonals
{self[1][1], self[2][2], self[3][3]}, -- \
{self[1][3], self[2][2], self[3][1]} -- /
}
for x in 1, 3 do
table.insert(choices, {self[x][1], self[x][2], self[x][3]}) -- rows
table.insert(choices, {self[1][x], self[2][x], self[3][x]}) -- cols
end
local draw = true
for set in choices do
local a, b, c = set[1], set[2], set[3]
if a == b and b == c and (b == "x" or b == "o") then
return b
elseif a == nil or b == nil or c == nil then
draw = false
end
end
return draw and "draw" or nil
end
-- Check state of 9x9 board. Possible return values:
-- "draw", "x", "o", nil (continue)
Board.state = function(self)
local sboard = SBoard.new()
for x in 1, 3 do
for y in 1, 3 do
sboard[x][y] = SBoard.state(self[x][y])
end
end
return SBoard.state(sboard)
end
return Board
|
T = require("tictaclib")
local Board = {} -- 9x9 board
local SBoard = {} -- 3x3 board
SBoard.tostring = function(self)
local ret = T.StringBuffer()
for x = 1, 3 do
for y = 1, 3 do
ret = ret .. (self[x][y] == nil and "-" or self[x][y]) .. " "
end
ret = ret .. "\n"
end
return tostring(ret)
end
SBoard.new = function()
local sboard = {
{nil, nil, nil},
{nil, nil, nil},
{nil, nil, nil}
}
setmetatable(sboard, {__tostring=SBoard.tostring, __index=SBoard})
return sboard
end
Board.tostring = function(self)
local ret = T.StringBuffer()
for y1 = 1, 3 do
for y2 = 1, 3 do
for x1 = 1, 3 do
for x2 = 1, 3 do
local i = self[y1][x1][y2][x2]
ret = ret .. (i == nil and "-" or i) .. " "
end
ret = ret .. " "
end
ret = ret .. "\n"
end
ret = ret .. "\n"
end
return tostring(ret)
end
Board.new = function()
local board = {
{SBoard.new(), SBoard.new(), SBoard.new()},
{SBoard.new(), SBoard.new(), SBoard.new()},
{SBoard.new(), SBoard.new(), SBoard.new()}
}
setmetatable(board, {__tostring=Board.tostring, __index=Board})
return board
end
Board.copy = function(self)
local board = Board.new()
for x1 = 1, 3 do
for y1 = 1, 3 do
for x2 = 1, 3 do
for y2 = 1, 3 do
board[x1][y1][x2][y2] = self[x1][y1][x2][y2]
end
end
end
end
return board
end
-- Check state of a 3x3 board. Possible return values:
-- "draw", "x", "o", nil (continue)
SBoard.state = function(self)
local choices = { -- diagonals
{self[1][1], self[2][2], self[3][3]}, -- \
{self[1][3], self[2][2], self[3][1]} -- /
}
for x = 1, 3 do
table.insert(choices, {self[x][1], self[x][2], self[x][3]}) -- rows
table.insert(choices, {self[1][x], self[2][x], self[3][x]}) -- cols
end
local draw = true
for _, set in ipairs(choices) do
local a, b, c = set[1], set[2], set[3]
if a == b and b == c and b ~= nil then
return b
elseif a == nil or b == nil or c == nil then
draw = false
end
end
return draw and "draw" or nil
end
-- Check state of 9x9 board. Possible return values:
-- "draw", "x", "o", nil (continue)
Board.state = function(self)
local sboard = SBoard.new()
for x = 1, 3 do
for y = 1, 3 do
sboard[x][y] = SBoard.state(self[x][y])
end
end
return SBoard.state(sboard)
end
return Board
|
Fix algorithm bugs
|
Fix algorithm bugs
|
Lua
|
apache-2.0
|
Motiejus/tictactoelib,Motiejus/tictactoelib
|
8e9d893b8febade76c5057aba4afc1fe439c331f
|
OS/DiskOS/Programs/run.lua
|
OS/DiskOS/Programs/run.lua
|
--This file loads a lk12 disk and execute it
--First we will start by obtaining the disk data
--We will run the current code in the editor
print("")
local eapi = require("C://Editors")
local sprid = "spritesheet"
local codeid = "luacode"
local diskdata = eapi:export()
diskdata = loadstring(diskdata)()
--Load the spritesheet
local SpriteMap, FlagsData
if diskdata[sprid] then
local sheetData = diskdata[sprid]
local w,h,imgdata = string.match(sheetData,"LK12;GPUIMG;(%d+)x(%d+);(.+)")
local sheetW, sheetH = w/8, h/8
FlagsData = imgdata:sub(w*h+1,-1)
if FlagsData:len() < sheetW*sheetH then
local missing = sheetW*sheetH
local zerochar = string.char(0)
for i=1,missing do
FlagsData = FlagsData..zerochar
end
end
imgdata = imgdata:sub(0,w*h)
imgdata = "LK12;GPUIMG;"..w.."x"..h..";"..imgdata
SpriteMap = SpriteSheet(imagedata(imgdata):image(),sheetW,sheetH)
end
--Load the code
local luacode = diskdata[codeid]:sub(2,-1) --Remove the first empty line
local diskchunk, err = loadstring(luacode)
if not diskchunk then
local err = tostring(err)
local pos = string.find(err,":")
err = err:sub(pos+1,-1)
color(9) print("Compile ERR: "..err )
return
end
--Create the sandboxed global variables
local glob = _FreshGlobals()
glob._G = glob --Magic ;)
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(chunk)
--if type(chunk) == "function" then setfenv(chunk,glob) end
local ok,co = pcall(coroutine.create,chunk)
if not ok then return error(co) end
return co
end
--Add peripherals api
local blocklist = { HDD = true }
local _,perlist = coroutine.yield("BIOS:listPeripherals")
for k, v in pairs(blocklist) do perlist[v] = nil end
for peripheral,funcs in pairs(perlist) do
for _,func in ipairs(funcs) do
local command = peripheral..":"..func
glob[func] = function(...)
local args = {coroutine.yield(command,...)}
if not args[1] then return error(args[2]) end
local nargs = {}
for k,v in ipairs(args) do
if k >1 then table.insert(nargs,k-1,v) end
end
return unpack(nargs)
end
end
end
local apiloader = loadstring(fs.read("C://api.lua"))
setfenv(apiloader,glob) apiloader()
--Add special disk api
glob.SpriteMap = SpriteMap
glob.SheetFlagsData = FlagsData
local helpersloader, err = loadstring(fs.read("C://Libraries/diskHelpers.lua"))
if not helpersloader then error(err) end
setfenv(helpersloader,glob) helpersloader()
--Apply the sandbox
setfenv(diskchunk,glob)
--Create the coroutine
local co = coroutine.create(diskchunk)
--Too Long Without Yielding
local checkclock = true
local eventclock = os.clock()
local lastclock = os.clock()
coroutine.sethook(co,function()
if os.clock() > lastclock + 3.5 and checkclock then
error("Too Long Without Yielding",2)
end
end,"",10000)
--Run the thing !
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
local lastArgs = {}
while true do
if coroutine.status(co) == "dead" then break end
--[[local name, key = rawPullEvent()
if name == "keypressed" and key == "escape" then
break
end]]
if os.clock() > eventclock + 3.5 then
color(9) print("Too Long Without Pulling Event / Flipping") break
end
local args = {coroutine.resume(co,unpack(lastArgs))}
checkclock = false
if not args[1] then
local err = tostring(args[2])
local pos = string.find(err,":")
err = err:sub(pos+1,-1); color(9) print("ERR: "..err ); break
end
if args[2] then
lastArgs = {coroutine.yield(args[2],unpack(extractArgs(args,2)))}
if args[2] == "CPU:pullEvent" or args[2] == "CPU:rawPullEvent" or args[2] == "GPU:flip" then
eventclock = os.clock()
if args[2] == "GPU:flip" then
local name, key = rawPullEvent()
if name == "keypressed" and key == "escape" then
break
end
else
if lastArgs[1] and lastArgs[2] == "keypressed" and lastArgs[3] == "escape" then
break
end
end
end
lastclock = os.clock()
checkclock = true
--lastclock = os.clock()
end
end
coroutine.sethook(co)
clearEStack()
print("")
|
--This file loads a lk12 disk and execute it
--First we will start by obtaining the disk data
--We will run the current code in the editor
print("")
local eapi = require("C://Editors")
local sprid = "spritesheet"
local codeid = "luacode"
local diskdata = eapi:export()
diskdata = loadstring(diskdata)()
--Load the spritesheet
local SpriteMap, FlagsData
if diskdata[sprid] then
local sheetData = diskdata[sprid]
local w,h,imgdata = string.match(sheetData,"LK12;GPUIMG;(%d+)x(%d+);(.+)")
local sheetW, sheetH = w/8, h/8
FlagsData = imgdata:sub(w*h+1,-1)
if FlagsData:len() < sheetW*sheetH then
local missing = sheetW*sheetH
local zerochar = string.char(0)
for i=1,missing do
FlagsData = FlagsData..zerochar
end
end
imgdata = imgdata:sub(0,w*h)
imgdata = "LK12;GPUIMG;"..w.."x"..h..";"..imgdata
SpriteMap = SpriteSheet(imagedata(imgdata):image(),sheetW,sheetH)
end
--Load the code
local luacode = diskdata[codeid]:sub(2,-1) --Remove the first empty line
local diskchunk, err = loadstring(luacode)
if not diskchunk then
local err = tostring(err)
local pos = string.find(err,":")
err = err:sub(pos+1,-1)
color(9) print("Compile ERR: "..err )
return
end
--Create the sandboxed global variables
local glob = _FreshGlobals()
glob._G = glob --Magic ;)
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(chunk)
--if type(chunk) == "function" then setfenv(chunk,glob) end
local ok,co = pcall(coroutine.create,chunk)
if not ok then return error(co) end
return co
end
--Add peripherals api
local blocklist = { HDD = true }
local _,perlist = coroutine.yield("BIOS:listPeripherals")
for k, v in pairs(blocklist) do perlist[v] = nil end
for peripheral,funcs in pairs(perlist) do
for _,func in ipairs(funcs) do
local command = peripheral..":"..func
glob[func] = function(...)
local args = {coroutine.yield(command,...)}
if not args[1] then return error(args[2]) end
local nargs = {}
for k,v in ipairs(args) do
if k >1 then table.insert(nargs,k-1,v) end
end
return unpack(nargs)
end
end
end
local apiloader = loadstring(fs.read("C://api.lua"))
setfenv(apiloader,glob) apiloader()
--Add special disk api
glob.SpriteMap = SpriteMap
glob.SheetFlagsData = FlagsData
local helpersloader, err = loadstring(fs.read("C://Libraries/diskHelpers.lua"))
if not helpersloader then error(err) end
setfenv(helpersloader,glob) helpersloader()
--Apply the sandbox
setfenv(diskchunk,glob)
--Create the coroutine
local co = coroutine.create(diskchunk)
--Too Long Without Yielding
local checkclock = true
local eventclock = os.clock()
local lastclock = os.clock()
coroutine.sethook(co,function()
if os.clock() > lastclock + 3.5 and checkclock then
error("Too Long Without Yielding",2)
end
end,"",10000)
--Run the thing !
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
local lastArgs = {}
while true do
if coroutine.status(co) == "dead" then break end
--[[local name, key = rawPullEvent()
if name == "keypressed" and key == "escape" then
break
end]]
if os.clock() > eventclock + 3.5 then
color(9) print("Too Long Without Pulling Event / Flipping") break
end
local args = {coroutine.resume(co,unpack(lastArgs))}
checkclock = false
if not args[1] then
local err = tostring(args[2])
local pos = string.find(err,":")
err = err:sub(pos+1,-1); color(9) print("ERR: "..err ); break
end
if args[2] then
lastArgs = {coroutine.yield(args[2],unpack(extractArgs(args,2)))}
if args[2] == "CPU:pullEvent" or args[2] == "CPU:rawPullEvent" or args[2] == "GPU:flip" or args[2] == "CPU:sleep" then
eventclock = os.clock()
if args[2] == "GPU:flip" or args[2] == "CPU:sleep" then
local name, key = rawPullEvent()
if name == "keypressed" and key == "escape" then
break
end
else
if lastArgs[1] and lastArgs[2] == "keypressed" and lastArgs[3] == "escape" then
break
end
end
end
lastclock = os.clock()
checkclock = true
--lastclock = os.clock()
end
end
coroutine.sethook(co)
clearEStack()
print("")
|
Bugfix
|
Bugfix
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
034c5364e87f4acef941582f095e0169a71ed941
|
premake5.lua
|
premake5.lua
|
function CommonConfig()
language "C++"
if os.get() ~= "windows" then
buildoptions "-std=c++11"
else
links { "ws2_32" }
end
configuration "Debug"
defines { "DEBUG" }
flags { "Symbols" }
configuration "Release"
defines { "NDEBUG" }
flags { "Optimize" }
end
solution "lib-lifx"
configurations { "Debug", "Release" }
warnings "Extra"
location "build"
project "lifx-cli"
kind "ConsoleApp"
targetname "lifx-cli"
files { "./include/**.h", "./src/cli/*.h", "./src/cli/*.cpp" }
dependson { "lib-lifx" }
links { "lib-lifx" }
includedirs { "./include/", "./src/cli/" }
CommonConfig()
project "lib-lifx"
kind "StaticLib"
targetname "liblifx"
files { "./src/lib/*.cpp" }
includedirs { "./include/" }
CommonConfig()
|
function CommonConfig()
language "C++"
if os.get() ~= "windows" then
buildoptions "-std=c++11"
else
links { "ws2_32" }
end
configuration "Debug"
defines { "DEBUG" }
flags { "Symbols" }
configuration "Release"
defines { "NDEBUG" }
flags { "Optimize" }
end
solution "lib-lifx"
configurations { "Debug", "Release" }
warnings "Extra"
location "build"
project "lifx-cli"
kind "ConsoleApp"
targetname "lifx-cli"
files { "./include/**.h", "./src/cli/*.h", "./src/cli/*.cpp" }
dependson { "lib-lifx" }
links { "lib-lifx" }
includedirs { "./include/", "./src/cli/" }
if os.get() == 'macosx' then
buildoptions
{
'-Wno-c++14-extensions',
}
end
CommonConfig()
project "lib-lifx"
kind "StaticLib"
targetname "lifx"
files { "./src/lib/*.cpp" }
includedirs { "./include/" }
CommonConfig()
|
Fixed C++14 warning. Fixed library name.
|
Fixed C++14 warning. Fixed library name.
|
Lua
|
mit
|
sanyaade-iot/lib-lifx,codemaster/lib-lifx
|
334643cefb329fd068a856da118af1c05aa1c6f2
|
MMOCoreORB/bin/scripts/managers/loot_manager.lua
|
MMOCoreORB/bin/scripts/managers/loot_manager.lua
|
--Copyright (C) 2007 <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
--which carries forward this exception.
--Determines how often exceptional and legendary items can drop.
exceptionalChance = 100000 --1 in 100,000
legendaryChance = 1000000 --1 in 1,000,000
--exceptionalChance = 100 --1 in 100 for testing
--legendaryChance = 1000 --1 in 1000 for testing
--Determines how much of an increase in the base stats will be applied to the object.
exceptionalModifier = 2.5
legendaryModifier = 5.0
lootableStatMods = {
"aim",
"alert",
"armor_assembly",
"armor_experimentation",
"armor_repair",
"berserk",
"blind_defense",
"block",
"camouflage",
"carbine_accuracy",
"carbine_aim",
"carbine_hit_while_moving",
"carbine_speed",
"clothing_assembly",
"clothing_experimentation",
"clothing_repair",
"combat_bleeding_defense",
"combat_healing_ability",
"combat_medicine_assembly",
"combat_medicine_experimentation",
"counterattack",
"cover",
"dizzy_defense",
"dodge",
"droid_assembly",
"droid_complexity",
"droid_customization",
"droid_experimentation",
"droid_find_chance",
"droid_find_speed",
"droid_track_chance",
"droid_track_speed",
"food_assembly",
"food_experimentation",
"foraging",
"general_assembly",
"general_experimentation",
"grenade_assembly",
"grenade_experimentation",
"group_slope_move",
"healing_ability",
"healing_dance_mind",
"healing_dance_shock",
"healing_dance_wound",
"healing_injury_speed",
"healing_injury_treatment",
"healing_music_mind",
"healing_music_shock",
"healing_music_wound",
"healing_range",
"healing_range",
"healing_range_speed",
"healing_wound_speed",
"healing_wound_treatment",
"heavyweapon_accuracy",
"heavyweapon_speed",
"instrument_assembly",
"intimidate",
"intimidate_defense",
"keep_creature",
"knockdown_defense",
"light_lightning_cannon_accuracy",
"light_lightning_cannon_speed",
"knockdown_defense",
"medical_foraging",
"medicine_assembly",
"medicine_experimentation",
"melee_defense",
"onehandmelee_accuracy",
"onehandmelee_damage",
"onehandmelee_speed",
"pistol_accuracy",
"pistol_aim",
"pistol_hit_while_moving",
"pistol_speed",
"pistol_standing",
"polearm_accuracy",
"polearm_speed",
"posture_change_down_defense",
"posture_change_up_defense",
"ranged_defense",
"rescue",
"resistance_bleeding",
"resistance_disease",
"resistance_fire",
"resistance_poison",
"rifle_accuracy",
"rifle_aim",
"rifle_hit_while_moving",
"rifle_prone",
"rifle_speed",
"slope_move",
"steadyaim",
"stored_pets",
"structure_assembly",
"structure_complexity",
"structure_experimentation",
"stun_defense",
"stun_defense",
"surveying",
"take_cover",
"tame_bonus",
"thrown_accuracy",
"thrown_speed",
"twohandmelee_accuracy",
"twohandmelee_damage",
"twohandmelee_speed",
"unarmed_accuracy",
"unarmed_damage",
"unarmed_speed",
"volley",
"warcry",
"weapon_assembly",
"weapon_experimentation",
"weapon_repair"
}
|
--Copyright (C) 2007 <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
--which carries forward this exception.
--Determines how often exceptional and legendary items can drop.
exceptionalChance = 100000 --1 in 100,000
legendaryChance = 1000000 --1 in 1,000,000
--exceptionalChance = 100 --1 in 100 for testing
--legendaryChance = 1000 --1 in 1000 for testing
--Determines how much of an increase in the base stats will be applied to the object.
exceptionalModifier = 2.5
legendaryModifier = 5.0
lootableStatMods = {
"aim",
"alert",
"armor_assembly",
"armor_experimentation",
"armor_repair",
"berserk",
"blind_defense",
"block",
"camouflage",
"carbine_accuracy",
"carbine_aim",
"carbine_hit_while_moving",
"carbine_speed",
"clothing_assembly",
"clothing_experimentation",
"clothing_repair",
"combat_bleeding_defense",
"combat_healing_ability",
"combat_medicine_assembly",
"combat_medicine_experimentation",
"counterattack",
"cover",
"dizzy_defense",
"dodge",
"droid_assembly",
"droid_complexity",
"droid_customization",
"droid_experimentation",
"droid_find_chance",
"droid_find_speed",
"droid_track_chance",
"droid_track_speed",
"food_assembly",
"food_experimentation",
"foraging",
"general_assembly",
"general_experimentation",
"grenade_assembly",
"grenade_experimentation",
"group_slope_move",
"healing_ability",
"healing_dance_mind",
"healing_dance_shock",
"healing_dance_wound",
"healing_injury_speed",
"healing_injury_treatment",
"healing_music_mind",
"healing_music_shock",
"healing_music_wound",
"healing_range",
"healing_range",
"healing_range_speed",
"healing_wound_speed",
"healing_wound_treatment",
"heavy_rifle_lightning_accuracy",
"heavy_rifle_lightning_speed",
"heavyweapon_accuracy",
"heavyweapon_speed",
"instrument_assembly",
"intimidate",
"intimidate_defense",
"keep_creature",
"knockdown_defense",
"knockdown_defense",
"medical_foraging",
"medicine_assembly",
"medicine_experimentation",
"melee_defense",
"onehandmelee_accuracy",
"onehandmelee_damage",
"onehandmelee_speed",
"pistol_accuracy",
"pistol_aim",
"pistol_hit_while_moving",
"pistol_speed",
"pistol_standing",
"polearm_accuracy",
"polearm_speed",
"posture_change_down_defense",
"posture_change_up_defense",
"ranged_defense",
"rescue",
"resistance_bleeding",
"resistance_disease",
"resistance_fire",
"resistance_poison",
"rifle_accuracy",
"rifle_aim",
"rifle_hit_while_moving",
"rifle_prone",
"rifle_speed",
"slope_move",
"steadyaim",
"stored_pets",
"structure_assembly",
"structure_complexity",
"structure_experimentation",
"stun_defense",
"stun_defense",
"surveying",
"take_cover",
"tame_bonus",
"thrown_accuracy",
"thrown_speed",
"twohandmelee_accuracy",
"twohandmelee_damage",
"twohandmelee_speed",
"unarmed_accuracy",
"unarmed_damage",
"unarmed_speed",
"volley",
"warcry",
"weapon_assembly",
"weapon_experimentation",
"weapon_repair"
}
|
(unstable) [fixed] fixed LLC sea's to use the correct string. Mantis 2719. Patch by Ivojedi.
|
(unstable) [fixed] fixed LLC sea's to use the correct string. Mantis 2719. Patch by Ivojedi.
git-svn-id: e4cf3396f21da4a5d638eecf7e3b4dd52b27f938@6559 c3d1530f-68f5-4bd0-87dc-8ef779617e40
|
Lua
|
agpl-3.0
|
Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo
|
3588da93d8a3c07826814212a69d817280ce4457
|
libremap-agent/luasrc/libremap/plugins/wireless.lua
|
libremap-agent/luasrc/libremap/plugins/wireless.lua
|
--[[
Copyright 2013 Nicolás Echániz <[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
]]--
local netm = require "luci.model.network"
-- TODO: this hardcoded values could be set in the config for the plugin
-- the current chosen thresholds are Ubiquiti's default for led signal indicator
local function link_quality(signal)
if signal >= -65 then
return 1
elseif signal >= -73 then
return 0.75
elseif signal >= -80 then
return 0.5
elseif signal >= -90 then
return 0.25
else
return 0.1
end
end
local function clean_aliases(doc)
if doc.aliases ~= nil then
for i, alias in ipairs(doc.aliases) do
if alias.type == "wifi" then
table.remove(doc.aliases, i)
end
end
end
end
local function read_wifilinks()
local ntm = netm.init()
local wifidevs = ntm:get_wifidevs()
local wifilinks = {}
local macs = {}
for _, dev in ipairs(wifidevs) do
for _, net in ipairs(dev:get_wifinets()) do
local local_mac = string.upper(ntm:get_interface(net.iwdata.ifname).dev.macaddr)
local channel = net:channel()
local assoclist = net.iwinfo.assoclist or {}
for station_mac, link_data in pairs(assoclist) do
local wifilink = {
type = "wifi",
alias_local = local_mac,
alias_remote = station_mac,
quality = link_quality(link_data.signal),
attributes = {
interface = net.iwdata.ifname,
local_mac = local_mac,
station_mac = station_mac,
channel = channel,
signal = link_data.signal
}
}
table.insert(wifilinks, wifilink)
end
table.insert(macs, local_mac)
end
end
return macs, wifilinks
end
function insert(doc)
local macs, wifilinks
macs, wifilinks = read_wifilinks()
-- clean the existing wifi aliases from the document
clean_aliases(doc)
local aliases = {}
for _, mac in ipairs(macs) do
table.insert(aliases, {type = "wifi", alias = mac})
end
-- if aliases is not empty, insert aliases and wifilinks data in the doc
if next(aliases) ~= nil then
doc.links = wifilinks
doc.aliases = aliases
end
end
return {
insert = insert
}
|
--[[
Copyright 2013-2015 Nicolás Echániz <[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
]]--
local netm = require "luci.model.network"
function concat_tables(t1,t2)
for i=1,#t2 do
t1[#t1+1] = t2[i]
end
return t1
end
-- TODO: this hardcoded values could be set in the config for the plugin
-- the current chosen thresholds are Ubiquiti's default for led signal indicator
local function link_quality(signal)
if signal >= -65 then
return 1
elseif signal >= -73 then
return 0.75
elseif signal >= -80 then
return 0.5
elseif signal >= -90 then
return 0.25
else
return 0.1
end
end
local function clean_aliases(doc)
if doc.aliases ~= nil then
for i, alias in ipairs(doc.aliases) do
if alias.type == "wifi" then
table.remove(doc.aliases, i)
end
end
end
end
local function read_wifilinks()
local ntm = netm.init()
local wifidevs = ntm:get_wifidevs()
local wifilinks = {}
local macs = {}
for _, dev in ipairs(wifidevs) do
for _, net in ipairs(dev:get_wifinets()) do
local local_mac = string.upper(ntm:get_interface(net.iwdata.ifname).dev.macaddr)
local channel = net:channel()
local assoclist = net.iwinfo.assoclist or {}
for station_mac, link_data in pairs(assoclist) do
local wifilink = {
type = "wifi",
alias_local = local_mac,
alias_remote = station_mac,
quality = link_quality(link_data.signal),
attributes = {
interface = net.iwdata.ifname,
local_mac = local_mac,
station_mac = station_mac,
channel = channel,
signal = link_data.signal
}
}
table.insert(wifilinks, wifilink)
end
table.insert(macs, local_mac)
end
end
return macs, wifilinks
end
function insert(doc)
local macs, wifilinks
macs, wifilinks = read_wifilinks()
-- clean the existing wifi aliases from the document
clean_aliases(doc)
local aliases = {}
for _, mac in ipairs(macs) do
table.insert(aliases, {type = "wifi", alias = mac})
end
-- if aliases is not empty, insert aliases and wifilinks data in the doc
if next(aliases) ~= nil then
if doc["links"] ~= nil then
concat_tables(doc.links, wifilinks)
else
doc.links = wifilinks
end
if doc["aliases"] ~= nil then
concat_tables(doc.aliases, aliases)
else
doc.aliases = aliases
end
end
end
return {
insert = insert
}
|
fixed wireless plugin
|
fixed wireless plugin
|
Lua
|
apache-2.0
|
libre-mesh/libremap-agent,rogerpueyo/libremap-agent-openwrt,libremap/libremap-agent-openwrt
|
0d34af972e57f8171df6ffc1a3db8c5b1b0c5d46
|
modules/game_ruleviolation/ruleviolation.lua
|
modules/game_ruleviolation/ruleviolation.lua
|
RuleViolation = {}
-- private variables
local rvreasons = {}
rvreasons[0] = tr("1a) Offensive Name")
rvreasons[1] = tr("1b) Invalid Name Format")
rvreasons[2] = tr("1c) Unsuitable Name")
rvreasons[3] = tr("1d) Name Inciting Rule Violation")
rvreasons[4] = tr("2a) Offensive Statement")
rvreasons[5] = tr("2b) Spamming")
rvreasons[6] = tr("2c) Illegal Advertising")
rvreasons[7] = tr("2d) Off-Topic Public Statement")
rvreasons[8] = tr("2e) Non-English Public Statement")
rvreasons[9] = tr("2f) Inciting Rule Violation")
rvreasons[10] = tr("3a) Bug Abuse")
rvreasons[11] = tr("3b) Game Weakness Abuse")
rvreasons[12] = tr("3c) Using Unofficial Software to Play")
rvreasons[13] = tr("3d) Hacking")
rvreasons[14] = tr("3e) Multi-Clienting")
rvreasons[15] = tr("3f) Account Trading or Sharing")
rvreasons[16] = tr("4a) Threatening Gamemaster")
rvreasons[17] = tr("4b) Pretending to Have Influence on Rule Enforcement")
rvreasons[18] = tr("4c) False Report to Gamemaster")
rvreasons[19] = tr("Destructive Behaviour")
rvreasons[20] = tr("Excessive Unjustified Player Killing")
local rvactions = {}
rvactions[0] = tr("Notation")
rvactions[1] = tr("Name Report")
rvactions[2] = tr("Banishment")
rvactions[3] = tr("Name Report + Banishment")
rvactions[4] = tr("Banishment + Final Warning")
rvactions[5] = tr("Name Report + Banishment + Final Warning")
rvactions[6] = tr("Statement Report")
local ruleViolationWindow
local reasonsTextList
local actionsTextList
-- public functions
function RuleViolation.hasWindowAccess()
return reasonsTextList:getChildCount() > 0
end
function RuleViolation.loadReasons()
reasonsTextList:destroyChildren()
local actions = g_game.getGMActions()
for reason, actionFlags in pairs(actions) do
local label = createWidget('RVListLabel', reasonsTextList)
label:setText(rvreasons[reason])
label.reasonId = reason
label.actionFlags = actionFlags
end
if not RuleViolation.hasWindowAccess() and ruleViolationWindow:isVisible() then RuleViolation.hide() end
end
function RuleViolation.init()
connect(g_game, { onGMActions = RuleViolation.loadReasons })
ruleViolationWindow = displayUI('ruleviolation.otui')
ruleViolationWindow:setVisible(false)
reasonsTextList = ruleViolationWindow:getChildById('reasonList')
actionsTextList = ruleViolationWindow:getChildById('actionList')
Keyboard.bindKeyDown('Ctrl+Y', RuleViolation.show)
if g_game.isOnline() then
RuleViolation.loadReasons()
end
end
function RuleViolation.terminate()
disconnect(g_game, { onGMActions = RuleViolation.loadReasons })
ruleViolationWindow:destroy()
ruleViolationWindow = nil
reasonsTextList = nil
actionsTextList = nil
end
function RuleViolation.show(target, statement)
if g_game.isOnline() and RuleViolation.hasWindowAccess() then
if target then
ruleViolationWindow:getChildById('nameText'):setText(target)
end
if statement then
ruleViolationWindow:getChildById('statementText'):setText(statement)
end
ruleViolationWindow:show()
ruleViolationWindow:raise()
end
end
function RuleViolation.hide()
ruleViolationWindow:hide()
RuleViolation.clearForm()
end
function RuleViolation.onSelectReason(reasonLabel, focused)
if reasonLabel.actionFlags and focused then
actionsTextList:destroyChildren()
for actionBaseFlag = 0, #rvactions do
actionFlagString = rvactions[actionBaseFlag]
if bit32.band(reasonLabel.actionFlags, math.pow(2, actionBaseFlag)) > 0 then
local label = createWidget('RVListLabel', actionsTextList)
label:setText(actionFlagString)
label.actionId = actionBaseFlag
end
end
end
end
function RuleViolation.report()
local target = ruleViolationWindow:getChildById('nameText'):getText()
local reason = reasonsTextList:getFocusedChild().reasonId
local action = actionsTextList:getFocusedChild().actionId
local comment = ruleViolationWindow:getChildById('commentText'):getText()
local statement = ruleViolationWindow:getChildById('statementText'):getText()
local statementId = 0 -- TODO: message unique id ?
local ipBanishment = ruleViolationWindow:getChildById('ipBanCheckBox'):isChecked()
if action == 6 and statement == "" then
displayErrorBox(tr("Error"), tr("No statement has been selected."))
elseif comment == "" then
displayErrorBox(tr("Error"), tr("You must enter a comment."))
else
g_game.reportRuleVilation(target, reason, action, comment, statement, statementId, ipBanishment)
RuleViolation.hide()
end
end
function RuleViolation.clearForm()
ruleViolationWindow:getChildById('nameText'):clearText()
ruleViolationWindow:getChildById('commentText'):clearText()
ruleViolationWindow:getChildById('statementText'):clearText()
ruleViolationWindow:getChildById('ipBanCheckBox'):setChecked(false)
end
|
RuleViolation = {}
-- private variables
local rvreasons = {}
rvreasons[1] = tr("1a) Offensive Name")
rvreasons[2] = tr("1b) Invalid Name Format")
rvreasons[3] = tr("1c) Unsuitable Name")
rvreasons[4] = tr("1d) Name Inciting Rule Violation")
rvreasons[5] = tr("2a) Offensive Statement")
rvreasons[6] = tr("2b) Spamming")
rvreasons[7] = tr("2c) Illegal Advertising")
rvreasons[8] = tr("2d) Off-Topic Public Statement")
rvreasons[9] = tr("2e) Non-English Public Statement")
rvreasons[10] = tr("2f) Inciting Rule Violation")
rvreasons[11] = tr("3a) Bug Abuse")
rvreasons[12] = tr("3b) Game Weakness Abuse")
rvreasons[13] = tr("3c) Using Unofficial Software to Play")
rvreasons[14] = tr("3d) Hacking")
rvreasons[15] = tr("3e) Multi-Clienting")
rvreasons[16] = tr("3f) Account Trading or Sharing")
rvreasons[17] = tr("4a) Threatening Gamemaster")
rvreasons[18] = tr("4b) Pretending to Have Influence on Rule Enforcement")
rvreasons[19] = tr("4c) False Report to Gamemaster")
rvreasons[20] = tr("Destructive Behaviour")
rvreasons[21] = tr("Excessive Unjustified Player Killing")
local rvactions = {}
rvactions[0] = tr("Notation")
rvactions[1] = tr("Name Report")
rvactions[2] = tr("Banishment")
rvactions[3] = tr("Name Report + Banishment")
rvactions[4] = tr("Banishment + Final Warning")
rvactions[5] = tr("Name Report + Banishment + Final Warning")
rvactions[6] = tr("Statement Report")
local ruleViolationWindow
local reasonsTextList
local actionsTextList
-- public functions
function RuleViolation.hasWindowAccess()
return reasonsTextList:getChildCount() > 0
end
function RuleViolation.loadReasons()
reasonsTextList:destroyChildren()
local actions = g_game.getGMActions()
for reason, actionFlags in pairs(actions) do
local label = createWidget('RVListLabel', reasonsTextList)
print("LOAD REASON: " .. tostring(reason) .. " " .. tostring(actionFlags))
label:setText(rvreasons[reason])
label.reasonId = reason
label.actionFlags = actionFlags
end
if not RuleViolation.hasWindowAccess() and ruleViolationWindow:isVisible() then RuleViolation.hide() end
end
function RuleViolation.init()
connect(g_game, { onGMActions = RuleViolation.loadReasons })
ruleViolationWindow = displayUI('ruleviolation.otui')
ruleViolationWindow:setVisible(false)
reasonsTextList = ruleViolationWindow:getChildById('reasonList')
actionsTextList = ruleViolationWindow:getChildById('actionList')
Keyboard.bindKeyDown('Ctrl+Y', RuleViolation.show)
if g_game.isOnline() then
RuleViolation.loadReasons()
end
end
function RuleViolation.terminate()
disconnect(g_game, { onGMActions = RuleViolation.loadReasons })
ruleViolationWindow:destroy()
ruleViolationWindow = nil
reasonsTextList = nil
actionsTextList = nil
end
function RuleViolation.show(target, statement)
if g_game.isOnline() and RuleViolation.hasWindowAccess() then
if target then
ruleViolationWindow:getChildById('nameText'):setText(target)
end
if statement then
ruleViolationWindow:getChildById('statementText'):setText(statement)
end
ruleViolationWindow:show()
ruleViolationWindow:raise()
end
end
function RuleViolation.hide()
ruleViolationWindow:hide()
RuleViolation.clearForm()
end
function RuleViolation.onSelectReason(reasonLabel, focused)
if reasonLabel.actionFlags and focused then
actionsTextList:destroyChildren()
for actionBaseFlag = 0, #rvactions do
actionFlagString = rvactions[actionBaseFlag]
if bit32.band(reasonLabel.actionFlags, math.pow(2, actionBaseFlag)) > 0 then
local label = createWidget('RVListLabel', actionsTextList)
label:setText(actionFlagString)
label.actionId = actionBaseFlag
end
end
end
end
function RuleViolation.report()
local target = ruleViolationWindow:getChildById('nameText'):getText()
local reason = reasonsTextList:getFocusedChild().reasonId
local action = actionsTextList:getFocusedChild().actionId
local comment = ruleViolationWindow:getChildById('commentText'):getText()
local statement = ruleViolationWindow:getChildById('statementText'):getText()
local statementId = 0 -- TODO: message unique id ?
local ipBanishment = ruleViolationWindow:getChildById('ipBanCheckBox'):isChecked()
if action == 6 and statement == "" then
displayErrorBox(tr("Error"), tr("No statement has been selected."))
elseif comment == "" then
displayErrorBox(tr("Error"), tr("You must enter a comment."))
else
g_game.reportRuleVilation(target, reason, action, comment, statement, statementId, ipBanishment)
RuleViolation.hide()
end
end
function RuleViolation.clearForm()
ruleViolationWindow:getChildById('nameText'):clearText()
ruleViolationWindow:getChildById('commentText'):clearText()
ruleViolationWindow:getChildById('statementText'):clearText()
ruleViolationWindow:getChildById('ipBanCheckBox'):setChecked(false)
end
|
fix on ruleviolation reason indexes
|
fix on ruleviolation reason indexes
|
Lua
|
mit
|
dreamsxin/otclient,kwketh/otclient,EvilHero90/otclient,gpedro/otclient,Cavitt/otclient_mapgen,Radseq/otclient,EvilHero90/otclient,kwketh/otclient,dreamsxin/otclient,Cavitt/otclient_mapgen,gpedro/otclient,dreamsxin/otclient,gpedro/otclient,Radseq/otclient
|
0f8bd011f21fc6c9c77b448287d35cfa269b9a22
|
Happy_Number/Lua/Yonaba/happy.lua
|
Happy_Number/Lua/Yonaba/happy.lua
|
-- Happy Number implementation
-- See: http://en.wikipedia.org/wiki/Happy_number
-- Utility function
-- Returns the sums of squares of the digits of a number n
local function sumsq(n)
local ssq = 0
for d in tostring(n):gmatch('%d') do
local num_d = tonumber(d)
ssq = ssq + num_d * num_d
end
return ssq
end
-- Checks if the given number is a happy number
-- n : a number
-- returns : true if n is a happy number, false otherwise
return function(n)
while n > 9 do
n = sumsq(n)
end
return n==1
end
|
-- Happy Number implementation
-- See: http://en.wikipedia.org/wiki/Happy_number
-- Utility function
-- Returns the sums of squares of the digits of a number n
local function sumsq(n)
local ssq = 0
for d in tostring(n):gmatch('%d') do
local num_d = tonumber(d)
ssq = ssq + num_d * num_d
end
return ssq
end
-- Checks if the given number is a happy number
-- Note, it loops endlessly when n is not happy (i.e, n is a sad number)
-- n : a number
-- returns : true if n is a happy number, false otherwise
return function(n)
while n > 1 do
n = sumsq(n)
end
return n==1
end
|
Fixed implementation
|
Fixed implementation
|
Lua
|
mit
|
imanmafi/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,Yonaba/Algorithm-Implementations,girishramnani/Algorithm-Implementations,warreee/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,Yonaba/Algorithm-Implementations,Yonaba/Algorithm-Implementations,isalnikov/Algorithm-Implementations,vikas17a/Algorithm-Implementations,isalnikov/Algorithm-Implementations,Etiene/Algorithm-Implementations,pravsingh/Algorithm-Implementations,jiang42/Algorithm-Implementations,kennyledet/Algorithm-Implementations,jb1717/Algorithm-Implementations,mishin/Algorithm-Implementations,pravsingh/Algorithm-Implementations,warreee/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,isalnikov/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,warreee/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,Yonaba/Algorithm-Implementations,warreee/Algorithm-Implementations,jiang42/Algorithm-Implementations,Etiene/Algorithm-Implementations,rohanp/Algorithm-Implementations,jb1717/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,jb1717/Algorithm-Implementations,rohanp/Algorithm-Implementations,jiang42/Algorithm-Implementations,mishin/Algorithm-Implementations,vikas17a/Algorithm-Implementations,Endika/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,kidaa/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,joshimoo/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,Yonaba/Algorithm-Implementations,jiang42/Algorithm-Implementations,vikas17a/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,joshimoo/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,mishin/Algorithm-Implementations,Etiene/Algorithm-Implementations,Endika/Algorithm-Implementations,vikas17a/Algorithm-Implementations,kidaa/Algorithm-Implementations,girishramnani/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,movb/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,joshimoo/Algorithm-Implementations,imanmafi/Algorithm-Implementations,isalnikov/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,Etiene/Algorithm-Implementations,pravsingh/Algorithm-Implementations,kidaa/Algorithm-Implementations,isalnikov/Algorithm-Implementations,Endika/Algorithm-Implementations,rohanp/Algorithm-Implementations,jb1717/Algorithm-Implementations,mishin/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,kidaa/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,imanmafi/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,vikas17a/Algorithm-Implementations,imanmafi/Algorithm-Implementations,kennyledet/Algorithm-Implementations,isalnikov/Algorithm-Implementations,mishin/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,Endika/Algorithm-Implementations,rohanp/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,pravsingh/Algorithm-Implementations,girishramnani/Algorithm-Implementations,Yonaba/Algorithm-Implementations,jb1717/Algorithm-Implementations,warreee/Algorithm-Implementations,movb/Algorithm-Implementations,imanmafi/Algorithm-Implementations,pravsingh/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,Endika/Algorithm-Implementations,isalnikov/Algorithm-Implementations,kennyledet/Algorithm-Implementations,kidaa/Algorithm-Implementations,rohanp/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,kennyledet/Algorithm-Implementations,movb/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,jiang42/Algorithm-Implementations,movb/Algorithm-Implementations,Yonaba/Algorithm-Implementations,Endika/Algorithm-Implementations,jb1717/Algorithm-Implementations,vikas17a/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,warreee/Algorithm-Implementations,girishramnani/Algorithm-Implementations,kennyledet/Algorithm-Implementations,jb1717/Algorithm-Implementations,vikas17a/Algorithm-Implementations,pravsingh/Algorithm-Implementations,joshimoo/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,kidaa/Algorithm-Implementations,imanmafi/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,kidaa/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,Etiene/Algorithm-Implementations,rohanp/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,jb1717/Algorithm-Implementations,kidaa/Algorithm-Implementations,movb/Algorithm-Implementations,Yonaba/Algorithm-Implementations,jiang42/Algorithm-Implementations,Endika/Algorithm-Implementations,movb/Algorithm-Implementations,jiang42/Algorithm-Implementations,mishin/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,kidaa/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,joshimoo/Algorithm-Implementations,Endika/Algorithm-Implementations,warreee/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,movb/Algorithm-Implementations,jiang42/Algorithm-Implementations,jb1717/Algorithm-Implementations,joshimoo/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,Etiene/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,movb/Algorithm-Implementations,joshimoo/Algorithm-Implementations,Etiene/Algorithm-Implementations,mishin/Algorithm-Implementations,girishramnani/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,imanmafi/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,warreee/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,pravsingh/Algorithm-Implementations,movb/Algorithm-Implementations,jiang42/Algorithm-Implementations,warreee/Algorithm-Implementations,imanmafi/Algorithm-Implementations,joshimoo/Algorithm-Implementations,warreee/Algorithm-Implementations,warreee/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,kennyledet/Algorithm-Implementations,kidaa/Algorithm-Implementations,mishin/Algorithm-Implementations,pravsingh/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,mishin/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,joshimoo/Algorithm-Implementations,jiang42/Algorithm-Implementations,isalnikov/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,Endika/Algorithm-Implementations,isalnikov/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,Etiene/Algorithm-Implementations,imanmafi/Algorithm-Implementations,Endika/Algorithm-Implementations,girishramnani/Algorithm-Implementations,imanmafi/Algorithm-Implementations,jiang42/Algorithm-Implementations,vikas17a/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,vikas17a/Algorithm-Implementations,kennyledet/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,pravsingh/Algorithm-Implementations,warreee/Algorithm-Implementations,mishin/Algorithm-Implementations,vikas17a/Algorithm-Implementations,joshimoo/Algorithm-Implementations,girishramnani/Algorithm-Implementations,vikas17a/Algorithm-Implementations,Endika/Algorithm-Implementations,jb1717/Algorithm-Implementations,rohanp/Algorithm-Implementations,kidaa/Algorithm-Implementations,isalnikov/Algorithm-Implementations,mishin/Algorithm-Implementations,imanmafi/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,rohanp/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,kennyledet/Algorithm-Implementations,warreee/Algorithm-Implementations,rohanp/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,Endika/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,isalnikov/Algorithm-Implementations,pravsingh/Algorithm-Implementations,Etiene/Algorithm-Implementations,movb/Algorithm-Implementations,kennyledet/Algorithm-Implementations,girishramnani/Algorithm-Implementations,Etiene/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,rohanp/Algorithm-Implementations,rohanp/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,Etiene/Algorithm-Implementations,isalnikov/Algorithm-Implementations,joshimoo/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,warreee/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,jiang42/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,jiang42/Algorithm-Implementations,imanmafi/Algorithm-Implementations,pravsingh/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,Etiene/Algorithm-Implementations,kidaa/Algorithm-Implementations,jiang42/Algorithm-Implementations,kennyledet/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,joshimoo/Algorithm-Implementations,movb/Algorithm-Implementations,movb/Algorithm-Implementations,pravsingh/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,joshimoo/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,isalnikov/Algorithm-Implementations,pravsingh/Algorithm-Implementations,joshimoo/Algorithm-Implementations,pravsingh/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,Yonaba/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,joshimoo/Algorithm-Implementations,mishin/Algorithm-Implementations,rohanp/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,jb1717/Algorithm-Implementations,kennyledet/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,jb1717/Algorithm-Implementations,Yonaba/Algorithm-Implementations,isalnikov/Algorithm-Implementations,warreee/Algorithm-Implementations,rohanp/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,Endika/Algorithm-Implementations,mishin/Algorithm-Implementations,girishramnani/Algorithm-Implementations,movb/Algorithm-Implementations,kidaa/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,girishramnani/Algorithm-Implementations,rohanp/Algorithm-Implementations,rohanp/Algorithm-Implementations,jb1717/Algorithm-Implementations,Yonaba/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,imanmafi/Algorithm-Implementations,vikas17a/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,isalnikov/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,Endika/Algorithm-Implementations,pravsingh/Algorithm-Implementations,jiang42/Algorithm-Implementations,movb/Algorithm-Implementations,kidaa/Algorithm-Implementations,vikas17a/Algorithm-Implementations,girishramnani/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,Yonaba/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,girishramnani/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,kennyledet/Algorithm-Implementations,Yonaba/Algorithm-Implementations,kidaa/Algorithm-Implementations,jb1717/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,Endika/Algorithm-Implementations,jb1717/Algorithm-Implementations,mishin/Algorithm-Implementations,vikas17a/Algorithm-Implementations,Etiene/Algorithm-Implementations,warreee/Algorithm-Implementations,Yonaba/Algorithm-Implementations,kennyledet/Algorithm-Implementations,imanmafi/Algorithm-Implementations,vikas17a/Algorithm-Implementations,kennyledet/Algorithm-Implementations,Etiene/Algorithm-Implementations,mishin/Algorithm-Implementations,imanmafi/Algorithm-Implementations,kennyledet/Algorithm-Implementations,movb/Algorithm-Implementations,Yonaba/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations
|
e4473b66fbbb48ec96761d74e592e4a73df55ee6
|
plugins/why.lua
|
plugins/why.lua
|
do
local function is_banned(user_id, chat_id)
local hash = 'banned:'..chat_id..':'..user_id
local banned = redis:get(hash)
return banned or false
end
local function is_super_banned(user_id)
local hash = 'superbanned:'..user_id
local superbanned = redis:get(hash)
return superbanned or false
end
function why_real(user, receiver)
local chat_id = string.gsub(receiver, "chat#id", "")
chat_id = string.gsub(receiver, "channel#id", "")
local banned = is_banned(user.peer_id, chat_id)
local superbanned = is_super_banned(user.peer_id)
local text = str2emoji(':information_source:').." User "
if user.username ~= nil then
text = text.."@"..user.username
else
text = text..user.print_name
end
text = text.." ["..user.peer_id.."]\n"
if banned then
text = text..str2emoji(":exclamation:").." Is currently banned from this group.\n"
if superbanned then
text = text..str2emoji(":no_entry_sign:").." This ID is also superbanned.\n\n"
text = text..str2emoji(":point_right:").." You can let this user in by disabling the superban list with the !superban disable command"
text = text.."and then by unbanning with !ban delete "..user.peer_id
else
text = text.."\n"..str2emoji(":point_right:").." You can unban the user with !ban delete "..user.peer_id
end
else
if superbanned then
text = text..str2emoji(":no_entry_sign:").." This ID is currently superbanned.\n\n"
text = text..str2emoji(":point_right:").." You can let this user in by disabling the superban list with the !superban disable command."
else
text = text..str2emoji(":thumbsup:").." This ID is nor banned nor superbanned.\n"
end
end
send_large_msg(receiver, text)
end
function why_id(peer_id, chat_id)
local banned = is_banned(peer_id, chat_id)
local superbanned = is_super_banned(peer_id)
local text = str2emoji(':information_source:').." User with ID "..peer_id.."\n"
if banned then
text = text..str2emoji(":exclamation:").." Is currently banned from this group.\n"
if superbanned then
text = text..str2emoji(":no_entry_sign:").." This ID is also superbanned.\n\n"
text = text..str2emoji(":point_right:").." You can let this user in by disabling the superban list with the !superban disable command"
text = text.."and then by unbanning with !ban delete "..peer_id
else
text = text.."\n"..str2emoji(":point_right:").." You can unban the user with !ban delete "..peer_id
end
else
if superbanned then
text = text..str2emoji(":no_entry_sign:").." Is currently superbanned.\n\n"
text = text..str2emoji(":point_right:").." You can let this user in by disabling the superban list with the !superban disable command."
else
text = text..str2emoji(":thumbsup:").." This ID is nor banned nor superbanned.\n"
end
end
return text
end
function why(extra, success, result)
if result.from ~= nil then
why_real(result.from, extra.from)
else
why_real(result, extra.from)
end
end
function run(msg, matches)
if matches[1] == '!why' then
if matches[2] == '@' then
return resolve_username(matches[3], why, {from=get_receiver(msg)})
end
return why_id(matches[2], msg.from.peer_id)
end
if matches[1] == '#why' then
if msg.reply_id then
get_message(msg.reply_id, why, {from=get_receiver(msg)})
else
return str2emoji(":point_right:").." You must reply to a message to get informations about that."
end
end
end
return {
description = "Get informations about a username/ID",
usage = {
"!why <@username>/<user_id> : Returns informations about that user",
"#why (by reply) : Returns informations about that user",
},
patterns = {
"^(!why) (%d+)$",
"^(!why) (@)(.*)$",
"^(#why)$"
},
run = run
}
end
|
local function is_banned(user_id, chat_id)
local hash = 'banned:'..chat_id..':'..user_id
local banned = redis:get(hash)
return banned or false
end
local function is_super_banned(user_id)
local hash = 'superbanned:'..user_id
local superbanned = redis:get(hash)
return superbanned or false
end
local function why_real(user, receiver)
local chat_id = string.gsub(receiver, "chat#id", "")
chat_id = string.gsub(receiver, "channel#id", "")
local banned = is_banned(user.peer_id, chat_id)
local superbanned = is_super_banned(user.peer_id)
local text = str2emoji(':information_source:').." User "
if user.username ~= nil then
text = text.."@"..user.username
else
text = text..user.print_name
end
text = text.." ["..user.peer_id.."]\n"
if banned then
text = text..str2emoji(":exclamation:").." Is currently banned from this group.\n"
if superbanned then
text = text..str2emoji(":no_entry_sign:").." This ID is also superbanned.\n\n"
text = text..str2emoji(":point_right:").." You can let this user in by disabling the superban list with the !superban disable command"
text = text.."and then by unbanning with !ban delete "..user.peer_id
else
text = text.."\n"..str2emoji(":point_right:").." You can unban the user with !ban delete "..user.peer_id
end
else
if superbanned then
text = text..str2emoji(":no_entry_sign:").." This ID is currently superbanned.\n\n"
text = text..str2emoji(":point_right:").." You can let this user in by disabling the superban list with the !superban disable command."
else
text = text..str2emoji(":thumbsup:").." This ID is nor banned nor superbanned.\n"
end
end
send_large_msg(receiver, text)
end
local function why_id(peer_id, chat_id)
local banned = is_banned(peer_id, chat_id)
local superbanned = is_super_banned(peer_id)
local text = str2emoji(':information_source:').." User with ID "..peer_id.."\n"
if banned then
text = text..str2emoji(":exclamation:").." Is currently banned from this group.\n"
if superbanned then
text = text..str2emoji(":no_entry_sign:").." This ID is also superbanned.\n\n"
text = text..str2emoji(":point_right:").." You can let this user in by disabling the superban list with the !superban disable command"
text = text.."and then by unbanning with !ban delete "..peer_id
else
text = text.."\n"..str2emoji(":point_right:").." You can unban the user with !ban delete "..peer_id
end
else
if superbanned then
text = text..str2emoji(":no_entry_sign:").." Is currently superbanned.\n\n"
text = text..str2emoji(":point_right:").." You can let this user in by disabling the superban list with the !superban disable command."
else
text = text..str2emoji(":thumbsup:").." This ID is nor banned nor superbanned.\n"
end
end
return text
end
local function why(cb_extra, success, result)
if result.from ~= nil then
why_real(result.from, cb_extra.receiver)
else
why_real(result, cb_extra.receiver)
end
end
local function run(msg, matches)
local receiver = get_receiver(msg)
if msg.reply_id then
get_message(msg.reply_id, why, {receiver=receiver})
return nil
end
if matches[1] == '#why' then
return str2emoji(":point_right:").." You must reply to a message to get informations about that."
end
if matches[1]:match("^%d+$") then
return why_id(matches[1], msg.to.id)
else
return resolve_username(matches[1]:gsub("@", ""), why, {receiver=receiver})
end
end
return {
description = "Get informations about a username/ID",
usage = {
"!why <username>/<user_id> : Returns informations about that user",
"#why (by reply) : Returns informations about that user",
},
patterns = {
"^!why (%d+)$",
"^!why (@?%a%S+)$",
"^#why$"
},
run = run
}
|
Fixed plugin why
|
Fixed plugin why
command !why <id> didn't work for local gruoup ban, just for superban,
fixed
now !why <username> don't need the @
unified plugin style
|
Lua
|
mit
|
KevinGuarnati/controllore,KevinGuarnati/controllore
|
e7863543489de790fbafbbfc1c0dfb9dd78fe733
|
util/events.lua
|
util/events.lua
|
-- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local pairs = pairs;
local t_insert = table.insert;
local t_sort = table.sort;
module "events"
function new()
local handlers = {};
local event_map = {};
local function _rebuild_index(event) -- TODO optimize index rebuilding
local _handlers = event_map[event];
local index = handlers[event];
if index then
for i=#index,1,-1 do index[i] = nil; end
else index = {}; handlers[event] = index; end
for handler in pairs(_handlers) do
t_insert(index, handler);
end
t_sort(index, function(a, b) return _handlers[a] > _handlers[b]; end);
end;
local function add_handler(event, handler, priority)
local map = event_map[event];
if map then
map[handler] = priority or 0;
else
map = {[handler] = priority or 0};
event_map[event] = map;
end
_rebuild_index(event);
end;
local function remove_handler(event, handler)
local map = event_map[event];
if map then
map[handler] = nil;
_rebuild_index(event);
end
end;
local function add_handlers(handlers)
for event, handler in pairs(handlers) do
add_handler(event, handler);
end
end;
local function remove_handlers(handlers)
for event, handler in pairs(handlers) do
remove_handler(event, handler);
end
end;
local function fire_event(event, ...)
local h = handlers[event];
if h then
for i=1,#h do
local ret = h[i](...);
if ret ~= nil then return ret; end
end
end
end;
return {
add_handler = add_handler;
remove_handler = remove_handler;
add_plugin = add_plugin;
remove_plugin = remove_plugin;
fire_event = fire_event;
_handlers = handlers;
_event_map = event_map;
};
end
return _M;
|
-- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local pairs = pairs;
local t_insert = table.insert;
local t_sort = table.sort;
module "events"
function new()
local handlers = {};
local event_map = {};
local function _rebuild_index(event) -- TODO optimize index rebuilding
local _handlers = event_map[event];
local index = handlers[event];
if index then
for i=#index,1,-1 do index[i] = nil; end
else index = {}; handlers[event] = index; end
for handler in pairs(_handlers) do
t_insert(index, handler);
end
t_sort(index, function(a, b) return _handlers[a] > _handlers[b]; end);
end;
local function add_handler(event, handler, priority)
local map = event_map[event];
if map then
map[handler] = priority or 0;
else
map = {[handler] = priority or 0};
event_map[event] = map;
end
_rebuild_index(event);
end;
local function remove_handler(event, handler)
local map = event_map[event];
if map then
map[handler] = nil;
_rebuild_index(event);
end
end;
local function add_handlers(handlers)
for event, handler in pairs(handlers) do
add_handler(event, handler);
end
end;
local function remove_handlers(handlers)
for event, handler in pairs(handlers) do
remove_handler(event, handler);
end
end;
local function fire_event(event, ...)
local h = handlers[event];
if h then
for i=1,#h do
local ret = h[i](...);
if ret ~= nil then return ret; end
end
end
end;
return {
add_handler = add_handler;
remove_handler = remove_handler;
add_handlers = add_handlers;
remove_handlers = remove_handlers;
fire_event = fire_event;
_handlers = handlers;
_event_map = event_map;
};
end
return _M;
|
util.events: Fixed the exposed API for adding/removing sets of event handlers.
|
util.events: Fixed the exposed API for adding/removing sets of event handlers.
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
64c91c5543de0d458bea69b78763b12f5155aff2
|
durden/atypes/wayland-x11.lua
|
durden/atypes/wayland-x11.lua
|
--
-- Simplified policy/mutation rules for X11 surfaces allocated via
-- wayland->x11-bridge. These are slightly special in that they can
-- possibly change role/behavior as they go along, and current
-- behavior as to visibility etc. is based on that.
--
-- The corresponding low-level implementation is in waybridge/
-- arcan_xwm.
--
local x11_menu = {
-- nothing atm.
};
local function viewport(wnd, status)
-- the behavior for this varies with type
wayland_debug(string.format(
"name=%s:type=%s:x=%d:y=%d:parent=%d",
wnd.name, wnd.surface_type, status.rel_x, status.rel_y, status.parent)
);
end
local function resize(wnd, status)
wnd:resize_effective(status.width, status.height, true, true);
end
-- In principle, an x11 surface can request a display global coordinate
-- for reparenting and positioning popups and other 'override_redirect'
-- surfaces with a grab.
local function popup_handler(wnd, source, status, wtype)
if (status.kind == "viewport") then
local pid = wayland_wndcookie(status.parent);
if (not pid) then
wayland_debug(string.format(
"x11-%s:viewport:name=%s:parent_id=%d:x=%d:y=%d",
wtype, wnd.name, status.parent, status.rel_x, status.rel_y)
);
link_image(source, active_display().order_anchor);
order_image(source, 1);
else
wayland_debug(string.format(
"x11-%s:viewport:name=%s:parent=%s:x=%d:y=%d",
wtype, wnd.name, pid.name, status.rel_x, status.rel_y)
);
link_image(source, pid.canvas);
order_image(source, 1);
end
move_image(source, status.rel_x, status.rel_y);
elseif (status.kind == "terminated") then
wayland_debug(string.format(
"x11-%s:destroy:name=%s", wtype, wnd.name));
wayland_lostwnd(source);
delete_image(source);
elseif (status.kind == "resized") then
wayland_debug(string.format(
"x11-%s:resized:name=%s:w=%d:h=%d",
wtype, wnd.name, status.width, status.height)
);
resize_image(source, status.width, status.height);
order_image(source, 2);
show_image(source);
local mx, my = mouse_xy();
move_image(source, mx, my);
end
end
local function apply_type_size(wnd, status)
if (wnd.surface_type == "popup" or
wnd.surface_type == "tooltip" or
wnd.surface_type == "menu") then
-- destroy the 'container', won't be needed with popup, uncertain
-- what the 'rules' say about the same surface mutating in type, but
-- assume for now that it doesn't.
wayland_debug(string.format(
"x11:type=%s:name=%s", wnd.surface_type, wnd.name));
local newwnd = {name = wnd.name, surface_type = wnd.surface_type};
local newvid = wnd.external;
image_inherit_order(newvid, true);
image_mask_set(newvid, MASK_UNPICKABLE);
wayland_debug("switch-handler:" .. tostring(newvid));
target_updatehandler(newvid, function(source, status)
popup_handler(newwnd, source, status, newwnd.surface_type);
end);
-- register and apply deferred viewport
wayland_gotwnd(newvid, newwnd);
if (wnd.last_viewport) then
popup_handler(newwnd, source, wnd.last_viewport, newwnd.surface_type);
end
-- forward any possible incoming 'resize' event as well
if (status) then
popup_handler(newwnd, source, status, newwnd.surface_type);
end
wnd.external = nil;
wnd:destroy();
-- normal? then we just attach as any old window
else
if (wnd.ws_attach) then
wnd:ws_attach();
end
if (status) then
resize(wnd, status);
end
end
end
function x11_event_handler(wnd, source, status)
wayland_debug(string.format(
"status=event:event=%s:name=%s", status.kind, wnd.name));
if (status.kind == "terminated") then
wayland_lostwnd(source);
wnd:destroy();
elseif (status.kind == "registered") then
wnd:set_guid(status.guid);
elseif (status.kind == "viewport") then
if (wnd.surface_type) then
viewport(wnd, status);
else
wnd.last_viewport = status;
end
elseif (status.kind == "message") then
-- our regular dispatch table of 'special hacks'
local opts = string.split(status.message, ":");
if (not opts or not opts[1]) then
wayland_debug(string.format(
"x11:error_message=unknown:name=%s:raw=%s", wnd.name, status.message));
end
if (opts[1] == "type" and opts[2]) then
wayland_debug(string.format("x11:set_type=%s:name=%s", opts[2], wnd.name));
wnd.surface_type = opts[2];
apply_type_size(wnd, wnd.defer_resize);
wnd.defer_size = nil;
else
wayland_debug(string.format(
"x11:error_message=unknown:command=%s:name=%s", opts[1], wnd.name));
end
elseif (status.kind == "segment_requested") then
wayland_debug("x11:error_message=subsegment_request");
elseif (status.kind == "resized") then
-- we actually only attach on the first buffer delivery when we also know
-- the intended purpose of the mapped window as we don't get that information
-- during the segment allocation stage for wayland/x11
if (wnd.ws_attach) then
if (wnd.surface_type) then
apply_type_size(wnd, status);
else
wayland_debug("x11:kind=status:message=no type defer_attach");
wnd.defer_resize = status;
return;
end
else
resize(wnd, status);
end
else
wayland_debug("x11:error_message=unhandled:event=" .. status.kind);
end
end
return {
atype = "x11surface",
actions = {
name = "x11surface",
label = "Xsurface",
description = "Surfaces that comes from an X server",
submenu = true,
eval = function() return false; end,
handler = x11_menu,
},
init = function(atype, wnd, source)
wnd:add_handler("resize", function(wnd, neww, newh, efw, efh)
target_displayhint(wnd.external, neww, newh);
end);
end,
props = {
kbd_period = 0,
kbd_delay = 0,
centered = true,
scalemode = "client",
filtermode = FILTER_NONE,
rate_unlimited = true,
clipboard_block = true,
font_block = true,
block_rz_hint = false,
-- all allocations come via the parent bridge
allowed_segments = {}
},
dispatch = {}
};
|
--
-- Simplified policy/mutation rules for X11 surfaces allocated via
-- wayland->x11-bridge. These are slightly special in that they can
-- possibly change role/behavior as they go along, and current
-- behavior as to visibility etc. is based on that.
--
-- The corresponding low-level implementation is in waybridge/
-- arcan_xwm.
--
local x11_menu = {
-- nothing atm.
};
local function viewport(wnd, status)
-- the behavior for this varies with type
wayland_debug(string.format(
"name=%s:type=%s:x=%d:y=%d:parent=%d",
wnd.name, wnd.surface_type, status.rel_x, status.rel_y, status.parent)
);
end
local function resize(wnd, status)
wnd:resize_effective(status.width, status.height, true, true);
end
-- In principle, an x11 surface can request a display global coordinate
-- for reparenting and positioning popups and other 'override_redirect'
-- surfaces with a grab.
--
-- Since this can be used for UI- redressing style nastyness, it should
-- be an option if the user wants this or not.
--
local function popup_handler(wnd, source, status, wtype)
if (status.kind == "viewport") then
local pid = wayland_wndcookie(status.parent);
if (not pid) then
wayland_debug(string.format(
"x11-%s:viewport:name=%s:parent_id=%d:x=%d:y=%d:anchor=global",
wtype, wnd.name, status.parent, status.rel_x, status.rel_y)
);
link_image(source, active_display().order_anchor);
order_image(source, 1);
else
wayland_debug(string.format(
"x11-%s:viewport:name=%s:parent=%s:x=%d:y=%d:anchor=parent",
wtype, wnd.name, pid.name, status.rel_x, status.rel_y)
);
link_image(source, pid.canvas);
order_image(source, 1);
end
move_image(source, status.rel_x, status.rel_y);
elseif (status.kind == "terminated") then
wayland_debug(string.format(
"x11-%s:destroy:name=%s", wtype, wnd.name));
wayland_lostwnd(source);
delete_image(source);
elseif (status.kind == "resized") then
wayland_debug(string.format(
"x11-%s:resized:name=%s:w=%d:h=%d",
wtype, wnd.name, status.width, status.height)
);
resize_image(source, status.width, status.height);
order_image(source, 2);
show_image(source);
end
end
-- tray-icons are also a bit special, a separate window for
-- _NET_SYSTEM_TRAY_S0 are needed along with a SYSTEM_TRAY_REQUEST_DOCK,
-- then the icon itself comes from _NET_WM_ICON, and notifications go
-- as 'balloon messages'.
local function apply_type_size(wnd, status)
if (wnd.surface_type == "popup" or
wnd.surface_type == "dropdown" or
wnd.surface_type == "tooltip" or
wnd.surface_type == "menu") then
-- destroy the 'container', won't be needed with popup, uncertain
-- what the 'rules' say about the same surface mutating in type, but
-- assume for now that it doesn't. Likely need different positioning
-- constraints based on the different types
wayland_debug(string.format(
"x11:type=%s:name=%s", wnd.surface_type, wnd.name));
local newwnd = {name = wnd.name, surface_type = wnd.surface_type};
local newvid = wnd.external;
image_inherit_order(newvid, true);
image_mask_set(newvid, MASK_UNPICKABLE);
wayland_debug("switch-handler:" .. tostring(newvid));
target_updatehandler(newvid, function(source, status)
popup_handler(newwnd, source, status, newwnd.surface_type);
end);
-- register and apply deferred viewport
wayland_gotwnd(newvid, newwnd);
if (wnd.last_viewport) then
popup_handler(newwnd, source, wnd.last_viewport, newwnd.surface_type);
end
-- forward any possible incoming 'resize' event as well
if (status) then
popup_handler(newwnd, source, status, newwnd.surface_type);
end
wnd.external = nil;
wnd:destroy();
elseif (wnd.surface_type == "icon") then
-- treat the rest as normal windows
else
if (wnd.ws_attach) then
wnd:ws_attach();
end
if (status) then
resize(wnd, status);
end
end
end
function x11_event_handler(wnd, source, status)
wayland_debug(string.format(
"status=event:event=%s:name=%s", status.kind, wnd.name));
if (status.kind == "terminated") then
wayland_lostwnd(source);
wnd:destroy();
elseif (status.kind == "registered") then
wnd:set_guid(status.guid);
elseif (status.kind == "viewport") then
if (wnd.surface_type) then
viewport(wnd, status);
else
wayland_debug(string.format(
"status=deferred:event=%s:name=%s", status.kind, wnd.name));
wnd.last_viewport = status;
end
elseif (status.kind == "message") then
-- our regular dispatch table of 'special hacks'
local opts = string.split(status.message, ":");
if (not opts or not opts[1]) then
wayland_debug(string.format(
"x11:error_message=unknown:name=%s:raw=%s", wnd.name, status.message));
end
if (opts[1] == "type" and opts[2]) then
wayland_debug(string.format("x11:set_type=%s:name=%s", opts[2], wnd.name));
wnd.surface_type = opts[2];
apply_type_size(wnd, wnd.defer_resize);
wnd.defer_size = nil;
else
wayland_debug(string.format(
"x11:error_message=unknown:command=%s:name=%s", opts[1], wnd.name));
end
elseif (status.kind == "segment_requested") then
wayland_debug("x11:error_message=subsegment_request");
elseif (status.kind == "resized") then
-- we actually only attach on the first buffer delivery when we also know
-- the intended purpose of the mapped window as we don't get that information
-- during the segment allocation stage for wayland/x11
if (wnd.ws_attach) then
if (wnd.surface_type) then
apply_type_size(wnd, status);
else
wayland_debug("x11:kind=status:message=no type defer_attach");
wnd.defer_resize = status;
return;
end
else
resize(wnd, status);
end
else
wayland_debug("x11:error_message=unhandled:event=" .. status.kind);
end
end
return {
atype = "x11surface",
actions = {
name = "x11surface",
label = "Xsurface",
description = "Surfaces that comes from an X server",
submenu = true,
eval = function() return false; end,
handler = x11_menu,
},
init = function(atype, wnd, source)
wnd:add_handler("resize", function(wnd, neww, newh, efw, efh)
target_displayhint(wnd.external, neww, newh);
end);
end,
props = {
kbd_period = 0,
kbd_delay = 0,
centered = true,
scalemode = "client",
filtermode = FILTER_NONE,
rate_unlimited = true,
clipboard_block = true,
font_block = true,
block_rz_hint = false,
-- all allocations come via the parent bridge
allowed_segments = {}
},
dispatch = {}
};
|
xwayland, support more window types, popup pos fix
|
xwayland, support more window types, popup pos fix
|
Lua
|
bsd-3-clause
|
letoram/durden
|
b242f6dba354ec80d9fcc0fb9472a65146573a2b
|
test_scripts/Polices/Policy_Table_Update/ATF_PTU_request_after_N_ignition_cycles.lua
|
test_scripts/Polices/Policy_Table_Update/ATF_PTU_request_after_N_ignition_cycles.lua
|
---------------------------------------------------------------------------------------------
-- Requirement summary:
-- [PolicyTableUpdate] Request to update PT - after "N" ignition cycles
--
-- Description:
-- Triggering PTU on reaching 'ignition_cycles_since_last_exchange' value
-- 1. Used preconditions:
-- Delete log file and policy table if any
-- Register app and update policy
-- Stop SDL
-- Set ignition_cycles_since_last_exchange less on 1 from exchange_after_x_ignition_cycles
-- Start SDL
-- Register app
--
-- 2. Performed steps
-- Preform IGNOF
--
-- Expected result:
-- HMI->SDL:BasicCommunication.OnIgnitionCycleOver->
-- SDL must trigger a PolicyTableUpdate sequence
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
config.application1.registerAppInterfaceParams.appHMIType = {"DEFAULT"}
--[ToDo: should be removed when fixed: "ATF does not stop HB timers by closing session and connection"
config.defaultProtocolVersion = 2
--[[ Required Shared libraries ]]
local commonFunctions = require ('user_modules/shared_testcases/commonFunctions')
local commonSteps = require('user_modules/shared_testcases/commonSteps')
--[[ General Precondition before ATF start ]]
commonSteps:DeleteLogsFiles()
commonSteps:DeletePolicyTable()
--[[ General Settings for configuration ]]
Test = require('connecttest')
require('cardinalities')
local mobile_session = require('mobile_session')
require('user_modules/AppTypes')
--[[ Local functions ]]
local function SetIgnitionCyclesSinceLastExchange()
local pathToDB = config.pathToSDL .. "storage/policy.sqlite"
local sql_query = 'select exchange_after_x_ignition_cycles from module_config where rowid=1;'
local exchange_after_x_ignition_cycles = commonFunctions:get_data_policy_sql(pathToDB, sql_query)
local DBQuery = 'sqlite3 ' .. pathToDB .. ' \"UPDATE module_meta SET ignition_cycles_since_last_exchange = ' .. tonumber(exchange_after_x_ignition_cycles[1]) - 1 .. ' WHERE rowid = 1;\"'
os.execute(DBQuery)
os.execute(" sleep 1 ")
end
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test:Precondition_Activate_App_Consent_Device_And_Update_Policy()
local RequestId = self.hmiConnection:SendRequest("SDL.ActivateApp", {appID = self.applications["Test Application"]})
EXPECT_HMIRESPONSE(RequestId, {result = {code = 0, isSDLAllowed = false}, method = "SDL.ActivateApp"})
:Do(function(_,_)
local RequestIdGetUserFriendlyMessage = self.hmiConnection:SendRequest("SDL.GetUserFriendlyMessage", {language = "EN-US", messageCodes = {"DataConsent"}})
EXPECT_HMIRESPONSE(RequestIdGetUserFriendlyMessage,{result = {code = 0, method = "SDL.GetUserFriendlyMessage"}})
:Do(function(_,_)
self.hmiConnection:SendNotification("SDL.OnAllowSDLFunctionality", {allowed = true, source = "GUI", device = {id = config.deviceMAC, name = "127.0.0.1"}})
-- GetCurrentTimeStampDeviceConsent()
EXPECT_HMICALL("BasicCommunication.ActivateApp")
:Do(function(_,data1)
self.hmiConnection:SendResponse(data1.id,"BasicCommunication.ActivateApp", "SUCCESS", {})
EXPECT_NOTIFICATION("OnHMIStatus", {hmiLevel = "FULL", systemContext = "MAIN"})
:Do(function()
end)
end)
end)
end)
EXPECT_HMICALL("BasicCommunication.PolicyUpdate")
:Do(function(_,data)
pathToSnapshot = data.params.file
local RequestIdGetURLS = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 })
EXPECT_HMIRESPONSE(RequestIdGetURLS,{result = {code = 0, method = "SDL.GetURLS", urls = {{url = "http://policies.telematics.ford.com/api/policies"}}}})
:Do(function()
self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest",{requestType = "PROPRIETARY", fileName = "filename"})
EXPECT_NOTIFICATION("OnSystemRequest", { requestType = "PROPRIETARY" })
:Do(function()
local CorIdSystemRequest = self.mobileSession:SendRPC("SystemRequest", {fileName = "PolicyTableUpdate", requestType = "PROPRIETARY"}, "files/ptu_general.json")
local systemRequestId
EXPECT_HMICALL("BasicCommunication.SystemRequest")
:Do(function(_,data1)
systemRequestId = data1.id
self.hmiConnection:SendNotification("SDL.OnReceivedPolicyUpdate",
{
policyfile = "/tmp/fs/mp/images/ivsu_cache/PolicyTableUpdate"
})
self.hmiConnection:SendResponse(systemRequestId, "BasicCommunication.SystemRequest", "SUCCESS", {})
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UP_TO_DATE"}):Timeout(500)
self.mobileSession:ExpectResponse(CorIdSystemRequest, {success = true, resultCode = "SUCCESS"})
end)
end)
end)
end)
end
function Test:Precondition_StopSDL()
StopSDL()
end
function Test:Precondition_SetIgnitionCyclesSinceLastExchange()
SetIgnitionCyclesSinceLastExchange()
end
function Test:Precondition_StartSDL()
StartSDL(config.pathToSDL, config.ExitOnCrash)
end
function Test:Precondition_InitHMI()
self:initHMI()
end
function Test:Precondition_InitHMI_onReady()
self:initHMI_onReady()
end
function Test:Precondition_Register_app()
self:connectMobile()
self.mobileSession = mobile_session.MobileSession(self, self.mobileConnection)
self.mobileSession:StartService(7)
:Do(function()
local correlationId = self.mobileSession:SendRPC("RegisterAppInterface", config.application1.registerAppInterfaceParams)
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered")
:Do(function(_,data)
self.HMIAppID = data.params.application.appID
end)
self.mobileSession:ExpectResponse(correlationId, { success = true, resultCode = "SUCCESS" })
self.mobileSession:ExpectNotification("OnHMIStatus", {hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE", systemContext = "MAIN"})
end)
end
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:Check_PTU_triggered_on_IGNOFF()
StopSDL()
self.hmiConnection:SendNotification("BasicCommunication.OnIgnitionCycleOver")
EXPECT_HMICALL("SDL.PolicyUpdate")
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATE_NEEDED"})
:Timeout(500)
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test.Postcondition_SDLStop()
StopSDL()
end
|
---------------------------------------------------------------------------------------------
-- Requirement summary:
-- [PolicyTableUpdate] Request to update PT - after "N" ignition cycles
--
-- Description:
-- Triggering PTU on reaching 'ignition_cycles_since_last_exchange' value
-- 1. Used preconditions:
-- Delete log file and policy table if any
-- Register app and update policy
-- Stop SDL
-- Set ignition_cycles_since_last_exchange less on 1 from exchange_after_x_ignition_cycles
-- Start SDL
-- Register app
--
-- 2. Performed steps
-- Preform IGNOF
--
-- Expected result:
-- HMI->SDL:BasicCommunication.OnIgnitionCycleOver->
-- SDL must trigger a PolicyTableUpdate sequence
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
config.application1.registerAppInterfaceParams.appHMIType = {"DEFAULT"}
--[ToDo: should be removed when fixed: "ATF does not stop HB timers by closing session and connection"
config.defaultProtocolVersion = 2
--[[ Required Shared libraries ]]
local commonFunctions = require ('user_modules/shared_testcases/commonFunctions')
local commonSteps = require('user_modules/shared_testcases/commonSteps')
--[[ General Precondition before ATF start ]]
commonSteps:DeleteLogsFiles()
commonSteps:DeletePolicyTable()
--[[ General Settings for configuration ]]
Test = require('connecttest')
require('cardinalities')
local mobile_session = require('mobile_session')
require('user_modules/AppTypes')
--[[ Local functions ]]
local function SetIgnitionCyclesSinceLastExchange()
local pathToDB = config.pathToSDL .. "storage/policy.sqlite"
local sql_query = 'select exchange_after_x_ignition_cycles from module_config where rowid=1;'
local exchange_after_x_ignition_cycles = commonFunctions:get_data_policy_sql(pathToDB, sql_query)
local DBQuery = 'sqlite3 ' .. pathToDB .. ' \"UPDATE module_meta SET ignition_cycles_since_last_exchange = ' .. tonumber(exchange_after_x_ignition_cycles[1]) - 1 .. ' WHERE rowid = 1;\"'
os.execute(DBQuery)
os.execute(" sleep 1 ")
end
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test:Precondition_Activate_App_Consent_Device_And_Update_Policy()
local RequestId = self.hmiConnection:SendRequest("SDL.ActivateApp", {appID = self.applications["Test Application"]})
EXPECT_HMIRESPONSE(RequestId, {result = {code = 0, isSDLAllowed = false}, method = "SDL.ActivateApp"})
:Do(function(_,_)
local RequestIdGetUserFriendlyMessage = self.hmiConnection:SendRequest("SDL.GetUserFriendlyMessage", {language = "EN-US", messageCodes = {"DataConsent"}})
EXPECT_HMIRESPONSE(RequestIdGetUserFriendlyMessage,{result = {code = 0, method = "SDL.GetUserFriendlyMessage"}})
:Do(function(_,_)
self.hmiConnection:SendNotification("SDL.OnAllowSDLFunctionality", {allowed = true, source = "GUI", device = {id = config.deviceMAC, name = "127.0.0.1"}})
-- GetCurrentTimeStampDeviceConsent()
EXPECT_HMICALL("BasicCommunication.ActivateApp")
:Do(function(_,data1)
self.hmiConnection:SendResponse(data1.id,"BasicCommunication.ActivateApp", "SUCCESS", {})
EXPECT_NOTIFICATION("OnHMIStatus", {hmiLevel = "FULL", systemContext = "MAIN"})
:Do(function()
end)
end)
end)
end)
EXPECT_HMICALL("BasicCommunication.PolicyUpdate")
:Do(function(_,data)
pathToSnapshot = data.params.file
local RequestIdGetURLS = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 })
EXPECT_HMIRESPONSE(RequestIdGetURLS,{result = {code = 0, method = "SDL.GetURLS", urls = {{url = "http://policies.telematics.ford.com/api/policies"}}}})
:Do(function()
self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest",{requestType = "PROPRIETARY", fileName = "filename"})
EXPECT_NOTIFICATION("OnSystemRequest", { requestType = "PROPRIETARY" })
:Do(function()
local CorIdSystemRequest = self.mobileSession:SendRPC("SystemRequest", {fileName = "PolicyTableUpdate", requestType = "PROPRIETARY"}, "files/ptu_general.json")
local systemRequestId
EXPECT_HMICALL("BasicCommunication.SystemRequest")
:Do(function(_,data1)
systemRequestId = data1.id
self.hmiConnection:SendNotification("SDL.OnReceivedPolicyUpdate",
{
policyfile = "/tmp/fs/mp/images/ivsu_cache/PolicyTableUpdate"
})
self.hmiConnection:SendResponse(systemRequestId, "BasicCommunication.SystemRequest", "SUCCESS", {})
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UP_TO_DATE"}):Timeout(500)
self.mobileSession:ExpectResponse(CorIdSystemRequest, {success = true, resultCode = "SUCCESS"})
end)
end)
end)
end)
end
function Test:Precondition_StopSDL()
StopSDL()
end
function Test:Precondition_SetIgnitionCyclesSinceLastExchange()
SetIgnitionCyclesSinceLastExchange()
end
function Test:Precondition_StartSDL()
StartSDL(config.pathToSDL, config.ExitOnCrash)
end
function Test:Precondition_InitHMI()
self:initHMI()
end
function Test:Precondition_InitHMI_onReady()
self:initHMI_onReady()
end
function Test:Precondition_Register_app()
self:connectMobile()
self.mobileSession = mobile_session.MobileSession(self, self.mobileConnection)
self.mobileSession:StartService(7)
:Do(function()
local correlationId = self.mobileSession:SendRPC("RegisterAppInterface", config.application1.registerAppInterfaceParams)
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered")
:Do(function(_,data)
self.HMIAppID = data.params.application.appID
end)
self.mobileSession:ExpectResponse(correlationId, { success = true, resultCode = "SUCCESS" })
self.mobileSession:ExpectNotification("OnHMIStatus", {hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE", systemContext = "MAIN"})
end)
end
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:Check_PTU_triggered_on_IGNOFF()
StopSDL()
self.hmiConnection:SendNotification("BasicCommunication.OnIgnitionCycleOver")
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATE_NEEDED"})
:Timeout(500)
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test.Postcondition_SDLStop()
StopSDL()
end
|
Add fix after clarification requirements
|
Add fix after clarification requirements
|
Lua
|
bsd-3-clause
|
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
|
f09a0b78eb95ebdb1e426c3d668b4eeabf01a1c8
|
applications/luci-statistics/luasrc/statistics/i18n.lua
|
applications/luci-statistics/luasrc/statistics/i18n.lua
|
--[[
Luci statistics - diagram i18n helper
(c) 2008 Freifunk Leipzig / 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$
]]--
module("luci.statistics.i18n", package.seeall)
require("luci.util")
require("luci.i18n")
Instance = luci.util.class()
function Instance.__init__( self, graph )
self.i18n = luci.i18n
self.graph = graph
self.i18n.loadc("rrdtool")
self.i18n.loadc("statistics")
end
function Instance._subst( self, str, val )
str = str:gsub( "%%H", self.graph.opts.host or "" )
str = str:gsub( "%%pn", val.plugin or "" )
str = str:gsub( "%%pi", val.pinst or "" )
str = str:gsub( "%%dt", val.dtype or "" )
str = str:gsub( "%%di", val.dinst or "" )
str = str:gsub( "%%ds", val.dsrc or "" )
return str
end
function Instance.title( self, plugin, pinst, dtype, dinst )
local title = self.i18n.translate(
string.format( "stat_dg_title_%s_%s_%s", plugin, pinst, dtype ),
self.i18n.translate(
string.format( "stat_dg_title_%s_%s", plugin, pinst ),
self.i18n.translate(
string.format( "stat_dg_title_%s__%s", plugin, dtype ),
self.i18n.translate(
string.format( "stat_dg_title_%s", plugin ),
self.graph:_mkpath( plugin, pinst, dtype )
)
)
)
)
return self:_subst( title, {
plugin = plugin,
pinst = pinst,
dtype = dtype,
dinst = dinst
} )
end
function Instance.label( self, plugin, pinst, dtype, dinst )
local label = self.i18n.translate(
string.format( "stat_dg_label_%s_%s_%s", plugin, pinst, dtype ),
self.i18n.translate(
string.format( "stat_dg_label_%s_%s", plugin, pinst ),
self.i18n.translate(
string.format( "stat_dg_label_%s__%s", plugin, dtype ),
self.i18n.translate(
string.format( "stat_dg_label_%s", plugin ),
self.graph:_mkpath( plugin, pinst, dtype )
)
)
)
)
return self:_subst( label, {
plugin = plugin,
pinst = pinst,
dtype = dtype,
dinst = dinst
} )
end
function Instance.ds( self, source )
local label = self.i18n.translate(
string.format( "stat_ds_%s_%s_%s", source.type, source.instance, source.ds ),
self.i18n.translate(
string.format( "stat_ds_%s_%s", source.type, source.instance ),
self.i18n.translate(
string.format( "stat_ds_label_%s__%s", source.type, source.ds ),
self.i18n.translate(
string.format( "stat_ds_%s", source.type ),
source.type .. "_" .. source.instance:gsub("[^%w]","_") .. "_" .. source.ds
)
)
)
)
return self:_subst( label, {
dtype = source.type,
dinst = source.instance,
dsrc = source.ds
} )
end
|
--[[
Luci statistics - diagram i18n helper
(c) 2008 Freifunk Leipzig / 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$
]]--
module("luci.statistics.i18n", package.seeall)
require("luci.util")
require("luci.i18n")
Instance = luci.util.class()
function Instance.__init__( self, graph )
self.i18n = luci.i18n
self.graph = graph
self.i18n.loadc("rrdtool")
self.i18n.loadc("statistics")
end
function Instance._subst( self, str, val )
str = str:gsub( "%%H", self.graph.opts.host or "" )
str = str:gsub( "%%pn", val.plugin or "" )
str = str:gsub( "%%pi", val.pinst or "" )
str = str:gsub( "%%dt", val.dtype or "" )
str = str:gsub( "%%di", val.dinst or "" )
str = str:gsub( "%%ds", val.dsrc or "" )
return str
end
function Instance.title( self, plugin, pinst, dtype, dinst )
local title = self.i18n.string(
string.format( "stat_dg_title_%s_%s_%s", plugin, pinst, dtype ),
self.i18n.string(
string.format( "stat_dg_title_%s_%s", plugin, pinst ),
self.i18n.string(
string.format( "stat_dg_title_%s__%s", plugin, dtype ),
self.i18n.string(
string.format( "stat_dg_title_%s", plugin ),
self.graph:_mkpath( plugin, pinst, dtype )
)
)
)
)
return self:_subst( title, {
plugin = plugin,
pinst = pinst,
dtype = dtype,
dinst = dinst
} )
end
function Instance.label( self, plugin, pinst, dtype, dinst )
local label = self.i18n.string(
string.format( "stat_dg_label_%s_%s_%s", plugin, pinst, dtype ),
self.i18n.string(
string.format( "stat_dg_label_%s_%s", plugin, pinst ),
self.i18n.string(
string.format( "stat_dg_label_%s__%s", plugin, dtype ),
self.i18n.string(
string.format( "stat_dg_label_%s", plugin ),
self.graph:_mkpath( plugin, pinst, dtype )
)
)
)
)
return self:_subst( label, {
plugin = plugin,
pinst = pinst,
dtype = dtype,
dinst = dinst
} )
end
function Instance.ds( self, source )
local label = self.i18n.string(
string.format( "stat_ds_%s_%s_%s", source.type, source.instance, source.ds ),
self.i18n.string(
string.format( "stat_ds_%s_%s", source.type, source.instance ),
self.i18n.string(
string.format( "stat_ds_label_%s__%s", source.type, source.ds ),
self.i18n.string(
string.format( "stat_ds_%s", source.type ),
source.type .. "_" .. source.instance:gsub("[^%w]","_") .. "_" .. source.ds
)
)
)
)
return self:_subst( label, {
dtype = source.type,
dinst = source.instance,
dsrc = source.ds
} )
end
|
application/luci-statistics: fix i18n binding, use string() instead of translate
|
application/luci-statistics: fix i18n binding, use string() instead of translate
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@5181 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci
|
47a5341b064120fd85cae7d8e0ade5a103fdfdb5
|
testserver/item/id_74_axe.lua
|
testserver/item/id_74_axe.lua
|
-- lumberjacking
-- UPDATE common SET com_script='item.id_74_axe' WHERE com_itemid IN (74,2946);
require("base.common")
require("item.general.metal")
require("content.gathering")
module("item.id_74_axe", package.seeall)
function UseItem( User, SourceItem, TargetItem, Counter, Param, ltstate )
content.gathering.InitGathering();
InitTreeItems();
local woodchopping = content.gathering.woodchopping;
base.common.ResetInterruption( User, ltstate );
if ( ltstate == Action.abort ) then -- work interrupted
if (User:increaseAttrib("sex",0) == 0) then
gText = "seine";
eText = "his";
else
gText = "ihre";
eText = "her";
end
User:talkLanguage(Character.say, Player.german, "#me unterbricht "..gText.." Arbeit.");
User:talkLanguage(Character.say, Player.english,"#me interrupts "..eText.." work.");
return
end
if not base.common.CheckItem( User, SourceItem ) then -- security check
return
end
if (SourceItem:getType() ~= 4) then -- tool in Hand
base.common.HighInformNLS( User,
"Du musst das Beil in der Hand haben!",
"You have to hold the hatchet in your hand!" );
return
end
if not base.common.FitForWork( User ) then -- check minimal food points
return
end
-- check for tree
local TargetItem = base.common.GetFrontItem(User);
if ( TargetItem == nil ) then -- if there is no front item, check for nearby tree
for x=-1,1 do
for y=-1,1 do
local pos = position(User.pos.x+x,User.pos.y+y,User.pos.z);
if ( world:isItemOnField(pos) ) then
TargetItem = world:getItemOnField(pos);
if ( TreeItems[TargetItem.id] ~= nil) then
break;
end
TargetItem = nil;
end
end
if ( TargetItem ~= nil and TreeItems[TargetItem.id] ~= nil) then
break;
end
end
end
if ( TargetItem == nil ) then
base.common.HighInformNLS( User,
"Um Holz zu hacken musst du zu einem Baum gehen.",
"For chopping wood you have to go to a tree." );
return;
end
if not base.common.IsLookingAt( User, TargetItem.pos ) then -- check looking direction
base.common.TurnTo( User, TargetItem.pos ); -- turn if necessary
end
local tree = TreeItems[TargetItem.id];
-- any other checks?
local changeItem = false;
local amount = TargetItem:getData("wood_amount");
if ( amount == "" ) then
amount = tree.Amount;
TargetItem:setData("wood_amount", "" .. amount);
changeItem = true;
else
amount = tonumber(amount);
end
if ( amount <= 0 ) then
-- should never happen, but handle it nevertheless
world:erase(TargetItem, TargetItem.number);
world:createItemFromId(tree.TrunkId, 1, TargetItem.pos, true, 333, nil);
base.common.HighInformNLS( User,
"Hier gibt es kein Holz mehr zu holen. Gib dem Baum Zeit um nachzuwachsen.",
"There is no wood anymore that you can chop. Give the tree time to grow again." );
return;
end
if ( ltstate == Action.none ) then -- currently not working -> let's go
woodchopping.SavedWorkTime[User.id] = woodchopping:GenWorkTime(User,SourceItem);
User:startAction( woodchopping.SavedWorkTime[User.id], 0, 0, 6, 0);
User:talkLanguage( Character.say, Player.german, "#me beginnt Holz zu hacken.");
User:talkLanguage( Character.say, Player.english, "#me starts to chop wood.");
if ( changeItem ) then
world:changeItem(TargetItem);
end
return;
end
-- since we're here, we're working
if woodchopping:FindRandomItem(User) then
if ( changeItem ) then
world:changeItem(TargetItem);
end
return
end
User:learn( woodchopping.LeadSkill, woodchopping.SavedWorkTime[User.id], 100 );
amount = amount - 1;
TargetItem:setData("wood_amount", "" .. amount);
local producedItemId = tree.LogId;
if (math.random() <= tree.BoughProbability ) then
producedItemId = tree.BoughId;
end
local notCreated = User:createItem( producedItemId, 1, 333, nil ); -- create the new produced items
if ( notCreated > 0 ) then -- too many items -> character can't carry anymore
world:createItemFromId( producedItemId, notCreated, User.pos, true, 333, nil );
base.common.HighInformNLS(User,
"Du kannst nichts mehr halten und der Rest fllt zu Boden.",
"You can't carry any more and the rest drops to the ground.");
else -- character can still carry something
if (amount>0) then -- there are still items we can work on
woodchopping.SavedWorkTime[User.id] = woodchopping:GenWorkTime(User,SourceItem);
User:startAction( woodchopping.SavedWorkTime[User.id], 0, 0, 6, 0);
end
end
if base.common.ToolBreaks( User, SourceItem, false ) then -- damage and possibly break the tool
base.common.HighInformNLS(User,
"Dein altes Beil zerbricht.",
"Your old hatchet breaks.");
end
if ( amount <= 0 ) then
world:erase(TargetItem, TargetItem.number);
world:createItemFromId(tree.TrunkId, 1, TargetItem.pos, true, 333, nil);
base.common.HighInformNLS( User,
"Hier gibt es kein Holz mehr zu holen. Gib dem Baum Zeit um nachzuwachsen.",
"There is no wood anymore that you can chop. Give the tree time to grow again." );
return;
end
TargetItem:setData("wood_amount","" .. amount);
world:changeItem(TargetItem);
end
function InitTreeItems()
if ( TreeItems ~= nil ) then
return;
end
TreeItems = {};
AddTree( 11,125,2560, 56,10,0.4); -- apple tree
AddTree( 14,125,2560, 56,10,0.4); -- apple tree
AddTree( 299,541, 543,2786,15,0.4); -- cherry tree
AddTree( 300,541, 543,2786,15,0.4); -- cherry tree
AddTree( 308,309, 3, 0,12,-1); -- fir tree
AddTree( 586,587, 544, 56,10,0.4); -- cachdern tree
AddTree(1804,542, 544, 56,15,0.4); -- naldor tree
AddTree(1809,584, 544, 56,24,0.4); -- eldan oak
AddTree(1817,585, 3, 0,19,-1); -- scandrel pine
end
function AddTree(TreeId, TrunkId, LogId, BoughId, Amount, BoughProbability)
local treeTable = {};
treeTable.TrunkId = TrunkId;
treeTable.LogId = LogId;
treeTable.BoughId = BoughId;
treeTable.Amount = Amount;
treeTable.BoughProbability = BoughProbability;
table.insert(TreeItems, TreeId, treeTable);
end
--[[ old lists
function initLists( )
-- Initialisierung der Listen
if (trees ~= nil) then
return
end
trees = { };
logs = { };
AddTree( 11,125,560,561,562,563,2560,10, 56); -- Apfelbaum
AddTree( 14,125,560,561,562,563,2560,10, 56); -- Apfelbaum
AddTree( 299,541,564,565,566,567, 543,15,2786); -- Kirschbaum
AddTree( 300,541,564,565,566,567, 543,15,2786); -- Kirschbaum
AddTree( 308,309,572,573,574,575, 3,12, 0); -- Tanne
AddTree( 586,587,592,593,594,595, 544,10, 56); -- Cachdern-Baum
AddTree(1804,542,568,569,570,571, 544,15, 56); -- Naldorbaum
AddTree(1809,584,576,577,578,579, 544,24, 56); -- Alter Naldorbaum
AddTree(1817,585,580,581,582,583, 3,19, 0); -- Nadelbaum
end -- function initLists
function AddTree(TreeID,StumpID,NLog,OLog,SLog,WLog,Logs,maxLogs,bough)
trees[ TreeID ] = { StumpID, NLog, OLog, SLog, WLog, maxLogs };
logs[ NLog ] = {Logs,bough};
logs[ OLog ] = {Logs,bough};
logs[ SLog ] = {Logs,bough};
logs[ WLog ] = {Logs,bough};
end
--]]
function LookAtItem(User,Item)
item.general.metal.LookAtItem(User,Item)
end
|
-- lumberjacking
-- UPDATE common SET com_script='item.id_74_axe' WHERE com_itemid IN (74,2946);
require("base.common")
require("item.general.metal")
require("content.gathering")
module("item.id_74_axe", package.seeall)
function UseItem( User, SourceItem, TargetItem, Counter, Param, ltstate )
content.gathering.InitGathering();
InitTreeItems();
local woodchopping = content.gathering.woodchopping;
base.common.ResetInterruption( User, ltstate );
if ( ltstate == Action.abort ) then -- work interrupted
if (User:increaseAttrib("sex",0) == 0) then
gText = "seine";
eText = "his";
else
gText = "ihre";
eText = "her";
end
User:talkLanguage(Character.say, Player.german, "#me unterbricht "..gText.." Arbeit.");
User:talkLanguage(Character.say, Player.english,"#me interrupts "..eText.." work.");
return
end
if not base.common.CheckItem( User, SourceItem ) then -- security check
return
end
if (SourceItem:getType() ~= 4) then -- tool in Hand
base.common.HighInformNLS( User,
"Du musst das Beil in der Hand haben!",
"You have to hold the hatchet in your hand!" );
return
end
if not base.common.FitForWork( User ) then -- check minimal food points
return
end
-- check for tree
local TargetItem = base.common.GetFrontItem(User);
if ( TargetItem == nil ) then -- if there is no front item, check for nearby tree
for x=-1,1 do
for y=-1,1 do
local pos = position(User.pos.x+x,User.pos.y+y,User.pos.z);
if ( world:isItemOnField(pos) ) then
TargetItem = world:getItemOnField(pos);
if ( TreeItems[TargetItem.id] ~= nil) then
break;
end
TargetItem = nil;
end
end
if ( TargetItem ~= nil and TreeItems[TargetItem.id] ~= nil) then
break;
end
end
end
if ( TargetItem == nil ) then
base.common.HighInformNLS( User,
"Um Holz zu hacken musst du zu einem Baum gehen.",
"For chopping wood you have to go to a tree." );
return;
end
if not base.common.IsLookingAt( User, TargetItem.pos ) then -- check looking direction
base.common.TurnTo( User, TargetItem.pos ); -- turn if necessary
end
local tree = TreeItems[TargetItem.id];
if tree == nil then
return;
end;
-- any other checks?
local changeItem = false;
local amount = TargetItem:getData("wood_amount");
if ( amount == "" ) then
amount = tree.Amount;
TargetItem:setData("wood_amount", "" .. amount);
changeItem = true;
else
amount = tonumber(amount);
end
if ( amount <= 0 ) then
-- should never happen, but handle it nevertheless
world:erase(TargetItem, TargetItem.number);
world:createItemFromId(tree.TrunkId, 1, TargetItem.pos, true, 333, nil);
base.common.HighInformNLS( User,
"Hier gibt es kein Holz mehr zu holen. Gib dem Baum Zeit um nachzuwachsen.",
"There is no wood anymore that you can chop. Give the tree time to grow again." );
return;
end
if ( ltstate == Action.none ) then -- currently not working -> let's go
woodchopping.SavedWorkTime[User.id] = woodchopping:GenWorkTime(User,SourceItem);
User:startAction( woodchopping.SavedWorkTime[User.id], 0, 0, 6, 0);
User:talkLanguage( Character.say, Player.german, "#me beginnt Holz zu hacken.");
User:talkLanguage( Character.say, Player.english, "#me starts to chop wood.");
if ( changeItem ) then
world:changeItem(TargetItem);
end
return;
end
-- since we're here, we're working
if woodchopping:FindRandomItem(User) then
if ( changeItem ) then
world:changeItem(TargetItem);
end
return
end
User:learn( woodchopping.LeadSkill, woodchopping.SavedWorkTime[User.id], 100 );
amount = amount - 1;
TargetItem:setData("wood_amount", "" .. amount);
local producedItemId = tree.LogId;
if (math.random() <= tree.BoughProbability ) then
producedItemId = tree.BoughId;
end
local notCreated = User:createItem( producedItemId, 1, 333, nil ); -- create the new produced items
if ( notCreated > 0 ) then -- too many items -> character can't carry anymore
world:createItemFromId( producedItemId, notCreated, User.pos, true, 333, nil );
base.common.HighInformNLS(User,
"Du kannst nichts mehr halten und der Rest fllt zu Boden.",
"You can't carry any more and the rest drops to the ground.");
else -- character can still carry something
if (amount>0) then -- there are still items we can work on
woodchopping.SavedWorkTime[User.id] = woodchopping:GenWorkTime(User,SourceItem);
User:startAction( woodchopping.SavedWorkTime[User.id], 0, 0, 6, 0);
end
end
if base.common.ToolBreaks( User, SourceItem, false ) then -- damage and possibly break the tool
base.common.HighInformNLS(User,
"Dein altes Beil zerbricht.",
"Your old hatchet breaks.");
end
if ( amount <= 0 ) then
world:erase(TargetItem, TargetItem.number);
world:createItemFromId(tree.TrunkId, 1, TargetItem.pos, true, 333, nil);
base.common.HighInformNLS( User,
"Hier gibt es kein Holz mehr zu holen. Gib dem Baum Zeit um nachzuwachsen.",
"There is no wood anymore that you can chop. Give the tree time to grow again." );
return;
end
TargetItem:setData("wood_amount","" .. amount);
world:changeItem(TargetItem);
end
function InitTreeItems()
if ( TreeItems ~= nil ) then
return;
end
TreeItems = {};
AddTree( 11,125,2560, 56,10,0.4); -- apple tree
AddTree( 14,125,2560, 56,10,0.4); -- apple tree
AddTree( 299,541, 543,2786,15,0.4); -- cherry tree
AddTree( 300,541, 543,2786,15,0.4); -- cherry tree
AddTree( 308,309, 3, 0,12,-1); -- fir tree
AddTree( 586,587, 544, 56,10,0.4); -- cachdern tree
AddTree(1804,542, 544, 56,15,0.4); -- naldor tree
AddTree(1809,584, 544, 56,24,0.4); -- eldan oak
AddTree(1817,585, 3, 0,19,-1); -- scandrel pine
end
function AddTree(TreeId, TrunkId, LogId, BoughId, Amount, BoughProbability)
local treeTable = {};
treeTable.TrunkId = TrunkId;
treeTable.LogId = LogId;
treeTable.BoughId = BoughId;
treeTable.Amount = Amount;
treeTable.BoughProbability = BoughProbability;
table.insert(TreeItems, TreeId, treeTable);
end
--[[ old lists
function initLists( )
-- Initialisierung der Listen
if (trees ~= nil) then
return
end
trees = { };
logs = { };
AddTree( 11,125,560,561,562,563,2560,10, 56); -- Apfelbaum
AddTree( 14,125,560,561,562,563,2560,10, 56); -- Apfelbaum
AddTree( 299,541,564,565,566,567, 543,15,2786); -- Kirschbaum
AddTree( 300,541,564,565,566,567, 543,15,2786); -- Kirschbaum
AddTree( 308,309,572,573,574,575, 3,12, 0); -- Tanne
AddTree( 586,587,592,593,594,595, 544,10, 56); -- Cachdern-Baum
AddTree(1804,542,568,569,570,571, 544,15, 56); -- Naldorbaum
AddTree(1809,584,576,577,578,579, 544,24, 56); -- Alter Naldorbaum
AddTree(1817,585,580,581,582,583, 3,19, 0); -- Nadelbaum
end -- function initLists
function AddTree(TreeID,StumpID,NLog,OLog,SLog,WLog,Logs,maxLogs,bough)
trees[ TreeID ] = { StumpID, NLog, OLog, SLog, WLog, maxLogs };
logs[ NLog ] = {Logs,bough};
logs[ OLog ] = {Logs,bough};
logs[ SLog ] = {Logs,bough};
logs[ WLog ] = {Logs,bough};
end
--]]
function LookAtItem(User,Item)
item.general.metal.LookAtItem(User,Item)
end
|
Nil value fix
|
Nil value fix
|
Lua
|
agpl-3.0
|
Illarion-eV/Illarion-Content,vilarion/Illarion-Content,LaFamiglia/Illarion-Content,KayMD/Illarion-Content,Baylamon/Illarion-Content
|
387ada5bd9a2d435362a0dc0a9af6c1b59401323
|
ferre/updates.lua
|
ferre/updates.lua
|
#!/usr/local/bin/lua
local sql = require'carlos.sqlite'
local fd = require'carlos.fold'
local aux = require'ferre.aux'
local mx = require'ferre.timezone'
local hd = require'ferre.header'
local week = os.date('W%U', mx())
local QRY = 'SELECT * FROM updates %s'
local function push(week, vers, ret)
local conn = assert( sql.connect(string.format('/db/%s.db', week)) )
local clause = string.format('WHERE vers > %d', vers)
local function into(w)
local clave = w.clave
if not ret[clave] then ret[clave] = {clave=clave, store='PRICE'} end
local z = ret[clave]
z[w.campo] = w.valor
end
if conn.count('updates', clause) > 0 then
fd.reduce(conn.query(string.format(QRY, clause)), into)
end
return conn.count'updates'
end
local function records(w)
local ret = {}
local vers = w.vers
if w.week < week then -- XXX should NOT be valid for more than a week old | can define a new variable holding one week ago
push( w.week, vers, ret )
vers = 0
end
vers = push( week, vers, ret )
ret.VERS = {store='VERS', week=week, vers=vers}
ret = fd.reduce(fd.keys( ret ), fd.map( hd.asJSON ), fd.into, {})
return string.format('Content-Type: text/plain; charset=utf-8\r\n\r\n[%s]\n', table.concat(ret, ', '))
end
aux( records )
|
#!/usr/local/bin/lua
local sql = require'carlos.sqlite'
local fd = require'carlos.fold'
local aux = require'ferre.aux'
local mx = require'ferre.timezone'
local hd = require'ferre.header'
local week = os.date('W%U', mx())
local QRY = 'SELECT * FROM updates %s'
local function push(week, vers, ret)
local conn = assert( sql.connect(string.format('/db/%s.db', week)) )
local clause = string.format('WHERE vers > %d', vers)
local function into(w)
local clave = w.clave
if not ret[clave] then ret[clave] = {clave=clave, store='PRICE'} end
local z = ret[clave]
z[w.campo] = w.valor or ''
end
if conn.count('updates', clause) > 0 then
fd.reduce(conn.query(string.format(QRY, clause)), into)
local nvers = conn.count'updates'
ret.VERS = {store='VERS', week=week, vers=nvers}
end
end
local function records(w)
local ret = {}
local vers = w.vers
--[[
local wk = w.week
repeat
push( wk, vers, ret )
vers = 0
until wk == week
--]]
if w.week < week then
push( w.week, vers, ret )
vers = 0
end
push(week, vers, ret)
ret = fd.reduce(fd.keys( ret ), fd.map( hd.asJSON ), fd.into, {})
return string.format('Content-Type: text/plain; charset=utf-8\r\n\r\n[%s]\n', table.concat(ret, ', '))
end
aux( records )
|
Fixing the LOOP
|
Fixing the LOOP
|
Lua
|
bsd-2-clause
|
CAAP/ferre
|
22ba36cf60163369971e9b71b7ba7e7951b7de46
|
utils.lua
|
utils.lua
|
require('nn')
require('image')
local utils = {}
function utils.center2Corners(g, delta, N, dim_size)
local p1 = math.max(math.floor(g + (1 - N/ 2 - 0.5) * delta), 1)
local p2 = math.min(math.ceil(g + (N / 2 - 0.5) * delta), dim_size)
return p1, p2
end
function utils.toRGB(batch)
local output = torch.Tensor():typeAs(batch):resizeAs(batch)
output:copy(batch)
if #batch:size() <= 3 then
-- Batch Input
if #batch:size() > 2 then
local batch_size, height, width = table.unpack(batch:size():totable())
output = output:resize(batch_size, 1, height, width):repeatTensor(1, 3, 1, 1)
else
local height, width = table.unpack(batch:size():totable())
output = output:resize(1, height, width):repeatTensor(3, 1, 1)
end
end
return output
end
function utils.storeSeq(folder, img_seq)
for t = 1, #img_seq do
local img_name = paths.concat(folder, 'seq' .. t .. '.png')
image.save(img_name, img_seq[t])
end
end
function utils.drawReadSeq(T, N, input, att_params, line_color)
local batch = utils.toRGB(input)
if batch:type() == 'torch.CudaTensor' then
batch = batch:float()
end
local img_seq = {}
for t = 1, T do
img_seq[t] = utils.drawAttentionRect(N, batch, att_params[t], line_color)
end
return img_seq
end
function utils.drawWriteSeq(T, N, input, att_params, line_color)
local img_seq = {}
for t = 1, T do
local batch = utils.toRGB(input[t])
if batch:type() == 'torch.CudaTensor' then
batch = batch:float()
end
img_seq[t] = utils.drawAttentionRect(N, batch, att_params[t], line_color)
end
return img_seq
end
function utils.drawAttentionRect(N, input, att_params, line_color)
local batch_size, _, height, width = table.unpack(input:size():totable())
local output = torch.Tensor():typeAs(input):resizeAs(input)
output:copy(input)
local gx, gy, var, delta = table.unpack(att_params)
local rectOptions = {color = line_color, inplace = true}
for i = 1, batch_size do
local x1, x2 = utils.center2Corners(gx[i]:squeeze(), delta[i]:squeeze(), N, width)
local y1, y2 = utils.center2Corners(gy[i]:squeeze(), delta[i]:squeeze(), N, height)
image.drawRect(output[i], x1, y1, x2, y2, rectOptions)
end
return output
end
return utils
|
require('nn')
require('image')
local utils = {}
function utils.center2Corners(g, delta, N, dim_size)
local p1 = math.floor(g + (1 - N/ 2 - 0.5) * delta)
p1 = math.max(math.min(p1, dim_size), 1)
local p2 = math.ceil(g + (N / 2 - 0.5) * delta)
p2 = math.max(math.min(p2, dim_size), 1)
return p1, p2
end
function utils.toRGB(batch)
local output = torch.Tensor():typeAs(batch):resizeAs(batch)
output:copy(batch)
if #batch:size() <= 3 then
-- Batch Input
if #batch:size() > 2 then
local batch_size, height, width = table.unpack(batch:size():totable())
output = output:resize(batch_size, 1, height, width):repeatTensor(1, 3, 1, 1)
else
local height, width = table.unpack(batch:size():totable())
output = output:resize(1, height, width):repeatTensor(3, 1, 1)
end
end
return output
end
function utils.storeSeq(folder, img_seq)
for t = 1, #img_seq do
local img_name = paths.concat(folder, 'seq' .. t .. '.png')
image.save(img_name, img_seq[t])
end
end
function utils.drawReadSeq(T, N, input, att_params, line_color)
local batch = utils.toRGB(input)
if batch:type() == 'torch.CudaTensor' then
batch = batch:float()
end
local img_seq = {}
for t = 1, T do
img_seq[t] = utils.drawAttentionRect(N, batch, att_params[t], line_color)
end
return img_seq
end
function utils.drawWriteSeq(T, N, input, att_params, line_color)
local img_seq = {}
for t = 1, T do
local batch = utils.toRGB(input[t])
if batch:type() == 'torch.CudaTensor' then
batch = batch:float()
end
img_seq[t] = utils.drawAttentionRect(N, batch, att_params[t], line_color)
end
return img_seq
end
function utils.drawAttentionRect(N, input, att_params, line_color)
local batch_size, _, height, width = table.unpack(input:size():totable())
local output = torch.Tensor():typeAs(input):resizeAs(input)
output:copy(input)
local gx, gy, var, delta = table.unpack(att_params)
local rectOptions = {color = line_color, inplace = true}
for i = 1, batch_size do
local x1, x2 = utils.center2Corners(gx[i]:squeeze(), delta[i]:squeeze(), N, width)
local y1, y2 = utils.center2Corners(gy[i]:squeeze(), delta[i]:squeeze(), N, height)
image.drawRect(output[i], x1, y1, x2, y2, rectOptions)
end
return output
end
return utils
|
Fix rectangle coordinate clipping
|
Fix rectangle coordinate clipping
|
Lua
|
mit
|
vasilish/torch-draw
|
58cf56bb8dd03b215d5508c1fda18be05c57b9ef
|
item/id_271_scythe.lua
|
item/id_271_scythe.lua
|
-- scythe ( 271 )
-- (fully grown) grain (248) --> bundle of grain (249)
-- UPDATE common SET com_script='item.id_271_scythe' WHERE com_itemid IN (271);
require("base.common")
require("item.general.metal")
require("content.gathering")
module("item.id_271_scythe", package.seeall, package.seeall(item.general.metal))
LookAtItem = item.general.metal.LookAtItem
function UseItem(User, SourceItem, ltstate)
content.gathering.InitGathering();
local grainharvesting = content.gathering.grainharvesting;
base.common.ResetInterruption( User, ltstate );
if ( ltstate == Action.abort ) then -- work interrupted
if (User:increaseAttrib("sex",0) == 0) then
gText = "seine";
eText = "his";
else
gText = "ihre";
eText = "her";
end
User:talk(Character.say, "#me unterbricht "..gText.." Arbeit.", "#me interrupts "..eText.." work.")
return
end
if not base.common.CheckItem( User, SourceItem ) then -- security check
return
end
if (SourceItem:getType() ~= 4) then -- tool in Hand
base.common.HighInformNLS( User,
"Du musst die Sense in der Hand haben!",
"You have to hold the scythe in your hand!" );
return
end
if not base.common.FitForWork( User ) then -- check minimal food points
return
end
-- first check front position for grain
local TargetItem = base.common.GetFrontItem(User);
if ( TargetItem ~= nil and TargetItem ~= 248 ) then
TargetItem = nil; -- there is an item, but not fully grown grain
end
if ( TargetItem == nil ) then -- only check surroundings if no grain is at the front position
local foundYoungGrain = false; -- check if we only find not fully grown grain
TargetItem, foundYoungGrain = GetNearbyGrain(User);
if ( TargetItem == nil ) then
-- since we're here, there is no fully grown grain
if ( foundYoungGrain ) then
base.common.HighInformNLS( User,
"Das Getreide ist noch nicht reif fr den Schnitt.",
"The grain is not ready for harvest yet." );
else
base.common.HighInformNLS( User,
"Du brauchst Getriede um es mit der Sense zu schneiden.",
"You need grain for harvesting it with the scythe." );
end
return;
end
end
-- since we're here, there is some fully grown grain
if not base.common.IsLookingAt( User, TargetItem.pos ) then -- check looking direction
base.common.TurnTo( User, TargetItem.pos ); -- turn if necessary
end
if ( ltstate == Action.none ) then -- currently not working -> let's go
grainharvesting.SavedWorkTime[User.id] = grainharvesting:GenWorkTime(User,SourceItem);
User:startAction( grainharvesting.SavedWorkTime[User.id], 0, 0, 0, 0);
-- this is no batch action => no emote message, only inform player
if grainharvesting.SavedWorkTime[User.id] > 15 then
base.common.InformNLS(User,
"Du schneidest das Getreide mit der Sense.",
"You harvest the grain with the scythe.");
end
return
end
-- since we're here, we're working
if grainharvesting:FindRandomItem(User) then
return
end
User:learn( grainharvesting.LeadSkill, grainharvesting.SavedWorkTime[User.id], grainharvesting.LearnLimit);
local amount = TargetItem:getData("amount");
if ( amount == "" ) then
-- this should never happen...
User:inform("[ERROR] Grain has no amount set. Please inform a developer.");
-- but continue anyway, just set the amount
amount = 1;
else
amount = tonumber(amount);
end
world:erase(TargetItem, TargetItem.number); -- erase the item we're working on
local notCreated = User:createItem( 249, amount, 333, nil ); -- create the new produced items
if ( notCreated > 0 ) then -- too many items -> character can't carry anymore
world:createItemFromId( 249, notCreated, User.pos, true, 333, nil );
base.common.HighInformNLS(User,
"Du kannst nichts mehr halten und der Rest fllt zu Boden.",
"You can't carry any more and the rest drops to the ground.");
else -- character can still carry something
local a,b = GetNearbyGrain(User);
if (a~=nil) then -- there are still items we can work on
grainharvesting.SavedWorkTime[User.id] = grainharvesting:GenWorkTime(User,SourceItem);
User:startAction( grainharvesting.SavedWorkTime[User.id], 0, 0, 0, 0);
end
end
if base.common.GatheringToolBreaks( User, SourceItem ) then -- damage and possibly break the tool
base.common.HighInformNLS(User,
"Deine alte Sense zerbricht.",
"Your old scythe breaks.");
return
end
end
-- @return TargetItem The fully grown grain or nil if nothing was found
-- @return foundYoungGrain True if not fully grown grain was found (not reliable if TargetItem~=nil !!!)
function GetNearbyGrain(User)
local TargetItem = nil;
local foundYoungGrain = false; -- check if we only find not fully grown grain
for x=-1,1 do
for y=-1,1 do
local pos = position(User.pos.x+x,User.pos.y+y,User.pos.z);
if ( world:isItemOnField(pos) ) then
TargetItem = world:getItemOnField(pos);
if ( TargetItem.id == 248 ) then
-- got it!
break;
elseif ( TargetItem.id == 246 or TargetItem.id == 247 ) then
foundYoungGrain = true;
end
TargetItem = nil;
end
end
end
return TargetItem, foundYoungGrain;
end
|
-- scythe ( 271 )
-- (fully grown) grain (248) --> bundle of grain (249)
-- UPDATE common SET com_script='item.id_271_scythe' WHERE com_itemid IN (271);
require("base.common")
require("item.general.metal")
require("content.gathering")
module("item.id_271_scythe", package.seeall, package.seeall(item.general.metal))
LookAtItem = item.general.metal.LookAtItem
function UseItem(User, SourceItem, ltstate)
content.gathering.InitGathering();
local grainharvesting = content.gathering.grainharvesting;
base.common.ResetInterruption( User, ltstate );
if ( ltstate == Action.abort ) then -- work interrupted
if (User:increaseAttrib("sex",0) == 0) then
gText = "seine";
eText = "his";
else
gText = "ihre";
eText = "her";
end
User:talk(Character.say, "#me unterbricht "..gText.." Arbeit.", "#me interrupts "..eText.." work.")
return
end
if not base.common.CheckItem( User, SourceItem ) then -- security check
return
end
if (SourceItem:getType() ~= 4) then -- tool in Hand
base.common.HighInformNLS( User,
"Du musst die Sense in der Hand haben!",
"You have to hold the scythe in your hand!" );
return
end
if not base.common.FitForWork( User ) then -- check minimal food points
return
end
-- first check front position for grain
local TargetItem = base.common.GetFrontItem(User);
if ( TargetItem ~= nil and TargetItem.id ~= 248 ) then
TargetItem = nil; -- there is an item, but not fully grown grain
end
if ( TargetItem == nil ) then -- only check surroundings if no grain is at the front position
local foundYoungGrain = false; -- check if we only find not fully grown grain
TargetItem, foundYoungGrain = GetNearbyGrain(User);
if ( TargetItem == nil ) then
-- since we're here, there is no fully grown grain
if ( foundYoungGrain ) then
base.common.HighInformNLS( User,
"Das Getreide ist noch nicht reif fr den Schnitt.",
"The grain is not ready for harvest yet." );
else
base.common.HighInformNLS( User,
"Du brauchst Getriede um es mit der Sense zu schneiden.",
"You need grain for harvesting it with the scythe." );
end
return;
end
end
-- since we're here, there is some fully grown grain
if not base.common.IsLookingAt( User, TargetItem.pos ) then -- check looking direction
base.common.TurnTo( User, TargetItem.pos ); -- turn if necessary
end
if ( ltstate == Action.none ) then -- currently not working -> let's go
grainharvesting.SavedWorkTime[User.id] = grainharvesting:GenWorkTime(User,SourceItem);
User:startAction( grainharvesting.SavedWorkTime[User.id], 0, 0, 0, 0);
-- this is no batch action => no emote message, only inform player
if grainharvesting.SavedWorkTime[User.id] > 15 then
base.common.InformNLS(User,
"Du schneidest das Getreide mit der Sense.",
"You harvest the grain with the scythe.");
end
return
end
-- since we're here, we're working
if grainharvesting:FindRandomItem(User) then
return
end
User:learn( grainharvesting.LeadSkill, grainharvesting.SavedWorkTime[User.id], grainharvesting.LearnLimit);
local amount = TargetItem:getData("amount");
if ( amount == "" ) then
-- this should never happen...
User:inform("[ERROR] Grain has no amount set. Please inform a developer.");
-- but continue anyway, just set the amount
amount = 1;
else
amount = tonumber(amount);
end
world:erase(TargetItem, TargetItem.number); -- erase the item we're working on
local notCreated = User:createItem( 249, amount, 333, nil ); -- create the new produced items
if ( notCreated > 0 ) then -- too many items -> character can't carry anymore
world:createItemFromId( 249, notCreated, User.pos, true, 333, nil );
base.common.HighInformNLS(User,
"Du kannst nichts mehr halten und der Rest fllt zu Boden.",
"You can't carry any more and the rest drops to the ground.");
else -- character can still carry something
local a,b = GetNearbyGrain(User);
if (a~=nil) then -- there are still items we can work on
grainharvesting.SavedWorkTime[User.id] = grainharvesting:GenWorkTime(User,SourceItem);
User:startAction( grainharvesting.SavedWorkTime[User.id], 0, 0, 0, 0);
end
end
if base.common.GatheringToolBreaks( User, SourceItem ) then -- damage and possibly break the tool
base.common.HighInformNLS(User,
"Deine alte Sense zerbricht.",
"Your old scythe breaks.");
return
end
end
-- @return TargetItem The fully grown grain or nil if nothing was found
-- @return foundYoungGrain True if not fully grown grain was found (not reliable if TargetItem~=nil !!!)
function GetNearbyGrain(User)
local TargetItem = nil;
local foundYoungGrain = false; -- check if we only find not fully grown grain
for x=-1,1 do
for y=-1,1 do
local pos = position(User.pos.x+x,User.pos.y+y,User.pos.z);
if ( world:isItemOnField(pos) ) then
TargetItem = world:getItemOnField(pos);
if ( TargetItem.id == 248 ) then
-- got it!
return TargetItem, foundYoungGrain;
elseif ( TargetItem.id == 246 or TargetItem.id == 247 ) then
foundYoungGrain = true;
end
TargetItem = nil;
end
end
end
return TargetItem, foundYoungGrain;
end
|
fix search for (fully grown) grain (Mantis 0009436)
|
fix search for (fully grown) grain (Mantis 0009436)
|
Lua
|
agpl-3.0
|
Baylamon/Illarion-Content,KayMD/Illarion-Content,vilarion/Illarion-Content,LaFamiglia/Illarion-Content,Illarion-eV/Illarion-Content
|
eb6e61fc11f8ef2375ad8715cb57518b9201ebc9
|
src/screens/SelectionScreen.lua
|
src/screens/SelectionScreen.lua
|
--==================================================================================================
-- Copyright (C) 2014 - 2015 by Robert Machmer =
-- =
-- Permission is hereby granted, free of charge, to any person obtaining a copy =
-- of this software and associated documentation files (the "Software"), to deal =
-- in the Software without restriction, including without limitation the rights =
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell =
-- copies of the Software, and to permit persons to whom the Software is =
-- furnished to do so, subject to the following conditions: =
-- =
-- The above copyright notice and this permission notice shall be included in =
-- all copies or substantial portions of the Software. =
-- =
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR =
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, =
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE =
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER =
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, =
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN =
-- THE SOFTWARE. =
--==================================================================================================
local Screen = require('lib.screenmanager.Screen');
local LogLoader = require('src.logfactory.LogLoader');
local ButtonList = require('src.ui.ButtonList');
local InfoPanel = require('src.ui.InfoPanel');
local ConfigReader = require('src.conf.ConfigReader');
local InputHandler = require('src.InputHandler');
-- ------------------------------------------------
-- Module
-- ------------------------------------------------
local SelectionScreen = {};
-- ------------------------------------------------
-- Constructor
-- ------------------------------------------------
function SelectionScreen.new()
local self = Screen.new();
local config;
local logList;
local buttonList;
local infoPanel;
local uiElementPadding = 20;
local uiElementMargin = 5;
-- ------------------------------------------------
-- Private Functions
-- ------------------------------------------------
---
-- Updates the project's window settings based on the config file.
-- @param options
--
local function setWindowMode(options)
local _, _, flags = love.window.getMode();
flags.fullscreen = options.fullscreen;
flags.fullscreentype = options.fullscreenType;
flags.vsync = options.vsync;
flags.msaa = options.msaa;
flags.display = options.display;
love.window.setMode(options.screenWidth, options.screenHeight, flags);
local sw, sh = love.window.getDesktopDimensions();
love.window.setPosition(sw * 0.5 - love.graphics.getWidth() * 0.5, sh * 0.5 - love.graphics.getHeight() * 0.5);
end
-- ------------------------------------------------
-- Public Functions
-- ------------------------------------------------
function self:init()
config = ConfigReader.init();
-- Set the background color based on the option in the config file.
love.graphics.setBackgroundColor(config.options.backgroundColor);
setWindowMode(config.options);
-- Intitialise LogLoader.
logList = LogLoader.init();
-- A scrollable list of buttons which can be used to select a certain log.
buttonList = ButtonList.new(uiElementPadding, uiElementPadding, uiElementMargin);
buttonList:init(logList);
-- The info panel which displays more information about a selected log.
infoPanel = InfoPanel.new(uiElementPadding + (2 * uiElementMargin) + buttonList:getButtonWidth(), uiElementPadding);
infoPanel:setInfo(logList[1].name);
end
function self:update(dt)
buttonList:update(dt);
infoPanel:update(dt);
end
function self:resize(x, y)
infoPanel:resize(x, y);
end
function self:draw()
buttonList:draw();
infoPanel:draw();
love.graphics.print('Work in Progress (v' .. getVersion() .. ')', uiElementPadding, love.graphics.getHeight() - uiElementPadding);
end
function self:mousepressed(x, y, b)
infoPanel:pressed(x, y, b);
local logId = buttonList:pressed(x, y, b);
if logId then
infoPanel:setInfo(logId);
end
end
function self:keypressed(key)
if InputHandler.isPressed(key, config.keyBindings.exit) then
love.event.quit();
elseif InputHandler.isPressed(key, config.keyBindings.toggleFullscreen) then
love.window.setFullscreen(not love.window.getFullscreen());
end
end
return self;
end
return SelectionScreen;
|
--==================================================================================================
-- Copyright (C) 2014 - 2015 by Robert Machmer =
-- =
-- Permission is hereby granted, free of charge, to any person obtaining a copy =
-- of this software and associated documentation files (the "Software"), to deal =
-- in the Software without restriction, including without limitation the rights =
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell =
-- copies of the Software, and to permit persons to whom the Software is =
-- furnished to do so, subject to the following conditions: =
-- =
-- The above copyright notice and this permission notice shall be included in =
-- all copies or substantial portions of the Software. =
-- =
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR =
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, =
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE =
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER =
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, =
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN =
-- THE SOFTWARE. =
--==================================================================================================
local Screen = require('lib.screenmanager.Screen');
local LogLoader = require('src.logfactory.LogLoader');
local ButtonList = require('src.ui.ButtonList');
local InfoPanel = require('src.ui.InfoPanel');
local ConfigReader = require('src.conf.ConfigReader');
local InputHandler = require('src.InputHandler');
-- ------------------------------------------------
-- Module
-- ------------------------------------------------
local SelectionScreen = {};
-- ------------------------------------------------
-- Constructor
-- ------------------------------------------------
function SelectionScreen.new()
local self = Screen.new();
local config;
local logList;
local buttonList;
local infoPanel;
local uiElementPadding = 20;
local uiElementMargin = 5;
-- ------------------------------------------------
-- Private Functions
-- ------------------------------------------------
---
-- Updates the project's window settings based on the config file.
-- @param options
--
local function setWindowMode(options)
local _, _, flags = love.window.getMode();
flags.fullscreen = options.fullscreen;
flags.fullscreentype = options.fullscreenType;
flags.vsync = options.vsync;
flags.msaa = options.msaa;
flags.display = options.display;
love.window.setMode(options.screenWidth, options.screenHeight, flags);
local sw, sh = love.window.getDesktopDimensions();
love.window.setPosition(sw * 0.5 - love.graphics.getWidth() * 0.5, sh * 0.5 - love.graphics.getHeight() * 0.5);
end
-- ------------------------------------------------
-- Public Functions
-- ------------------------------------------------
function self:init()
config = ConfigReader.init();
-- Set the background color based on the option in the config file.
love.graphics.setBackgroundColor(config.options.backgroundColor);
setWindowMode(config.options);
-- Intitialise LogLoader.
logList = LogLoader.init();
-- A scrollable list of buttons which can be used to select a certain log.
buttonList = ButtonList.new(uiElementPadding, uiElementPadding, uiElementMargin);
buttonList:init(logList);
-- The info panel which displays more information about a selected log.
infoPanel = InfoPanel.new(uiElementPadding + (2 * uiElementMargin) + buttonList:getButtonWidth(), uiElementPadding);
infoPanel:setInfo(logList[1].name);
end
function self:update(dt)
buttonList:update(dt);
infoPanel:update(dt);
end
function self:resize(x, y)
infoPanel:resize(x, y);
end
function self:draw()
buttonList:draw();
infoPanel:draw();
love.graphics.print('Work in Progress (v' .. getVersion() .. ')', uiElementPadding, love.graphics.getHeight() - uiElementPadding);
end
function self:mousepressed(x, y, b)
infoPanel:pressed(x, y, b);
local logId = buttonList:pressed(x, y, b);
if logId then
infoPanel:setInfo(logId);
end
end
function self:keypressed(key)
if InputHandler.isPressed(key, config.keyBindings.exit) then
love.event.quit();
elseif InputHandler.isPressed(key, config.keyBindings.toggleFullscreen) then
love.window.setFullscreen(not love.window.getFullscreen());
end
end
function self:quit()
if ConfigReader.getConfig('options').removeTmpFiles then
ConfigReader.removeTmpFiles();
end
end
return self;
end
return SelectionScreen;
|
Fix deletion of temporary files when exiting from the selection menu
|
Fix deletion of temporary files when exiting from the selection menu
|
Lua
|
mit
|
rm-code/logivi
|
36d7318ebb2bf5b6d84af626c70aea4d1b3ae7cf
|
lua/tcp.lua
|
lua/tcp.lua
|
local internet = require('internet');
local JSON = require("json");
local config = require('config');
local conf = config.get(config.path);
local handle = internet.open(conf.serverIP, tonumber(conf.tcpPort));
handle:setvbuf('line');
-- handle:setTimeout('10');
local M = {};
function M.read()
-- reads delimited by newlines
return JSON:decode(handle:read());
end
function M.write(data)
-- without the newline the write will wait in the buffer
return handle:write(JSON:encode(data)..'\r\n');
end
M.write({id={account=conf.accountName, robot=conf.robotName}});
return M;
|
local internet = require('internet');
local JSON = require("json");
local config = require('config');
local conf = config.get(config.path);
local handle = internet.open(conf.serverIP, tonumber(conf.tcpPort));
handle:setvbuf('line');
-- handle:setTimeout('10');
local M = {};
function M.read()
-- reads delimited by newlines
return JSON:decode(handle:read());
end
function M.write(data)
local status, result = pcall(function()
-- without the newline the write will wait in the buffer
handle:write(JSON:encode(data)..'\r\n');
end);
if not status then
local errorMessage = {'message' = 'Failed to serialize result!'};
handle:write(JSON:encode(errorMessage)..'\r\n');
end
return result;
end
M.write({id={account=conf.accountName, robot=conf.robotName}});
return M;
|
tcp crash from failure to serialize functions fixed maybe
|
tcp crash from failure to serialize functions fixed maybe
|
Lua
|
mit
|
dunstad/roboserver,dunstad/roboserver
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.