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
|
|---|---|---|---|---|---|---|---|---|---|
b3b27bf5b482b1be3a0d7777a817cb87f6b1a38e
|
spec/integration/api/api_spec.lua
|
spec/integration/api/api_spec.lua
|
local spec_helper = require "spec.spec_helpers"
local http_client = require "kong.tools.http_client"
local cjson = require "cjson"
local env = spec_helper.get_env()
local created_ids = {}
local kWebURL = spec_helper.API_URL
local ENDPOINTS = {
{
collection = "apis",
total = table.getn(env.faker.FIXTURES.api) + 1,
entity = {
public_dns = "api.mockbin.com",
name = "mockbin",
target_url = "http://mockbin.com"
},
update_fields = {
public_dns = "newapi.mockbin.com"
},
error_message = '{"public_dns":"public_dns is required","name":"name is required","target_url":"target_url is required"}'
},
{
collection = "consumers",
total = table.getn(env.faker.FIXTURES.consumer) + 1,
entity = {
custom_id = "123456789"
},
update_fields = {
custom_id = "ABC_custom_ID"
},
error_message = nil
},
{
collection = "basicauth_credentials",
total = table.getn(env.faker.FIXTURES.basicauth_credential) + 1,
entity = {
username = "username5555",
password = "password5555",
consumer_id = function()
return created_ids.consumers
end
},
update_fields = {
username = "upd_username5555",
password = "upd_password5555"
},
error_message = '{"username":"username is required","consumer_id":"consumer_id is required"}'
},
{
collection = "keyauth_credentials",
total = table.getn(env.faker.FIXTURES.keyauth_credential) + 1,
entity = {
key = "apikey5555",
consumer_id = function()
return created_ids.consumers
end
},
update_fields = {
key = "upd_apikey5555",
},
error_message = '{"key":"key is required","consumer_id":"consumer_id is required"}'
},
{
collection = "plugins_configurations",
total = table.getn(env.faker.FIXTURES.plugin_configuration) + 1,
entity = {
name = "ratelimiting",
api_id = function()
return created_ids.apis
end,
consumer_id = function()
return created_ids.consumers
end,
["value.period"] = "second",
["value.limit"] = 10
},
update_fields = {
enabled = false
},
error_message = '{"name":"name is required","api_id":"api_id is required","value":"value is required"}'
}
}
describe("Web API #web", function()
setup(function()
spec_helper.prepare_db()
spec_helper.start_kong()
end)
teardown(function()
spec_helper.stop_kong()
spec_helper.reset_db()
end)
describe("/", function()
it("should return Kong's version and a welcome message", function()
local response, status, headers = http_client.get(kWebURL)
local body = cjson.decode(response)
assert.are.equal(200, status)
assert.truthy(body.version)
assert.truthy(body.tagline)
end)
end)
for i, v in ipairs(ENDPOINTS) do
describe("#"..v.collection, function()
it("should not create on POST with invalid parameters", function()
if v.collection ~= "consumers" then
local response, status, headers = http_client.post(kWebURL.."/"..v.collection.."/", {})
assert.are.equal(400, status)
assert.are.equal(v.error_message, response)
end
end)
it("should create an entity from valid paremeters", function()
-- Replace the IDs
for k, p in pairs(v.entity) do
if type(p) == "function" then
v.entity[k] = p()
end
end
local response, status, headers = http_client.post(kWebURL.."/"..v.collection.."/", v.entity)
local body = cjson.decode(response)
assert.are.equal(201, status)
assert.truthy(body)
-- Save the ID for later use
created_ids[v.collection] = body.id
end)
it("should GET all entities", function()
local response, status, headers = http_client.get(kWebURL.."/"..v.collection.."/")
local body = cjson.decode(response)
assert.are.equal(200, status)
assert.truthy(body.data)
--assert.truthy(body.total)
--assert.are.equal(v.total, body.total)
assert.are.equal(v.total, table.getn(body.data))
end)
it("should GET one entity", function()
local response, status, headers = http_client.get(kWebURL.."/"..v.collection.."/"..created_ids[v.collection])
local body = cjson.decode(response)
assert.are.equal(200, status)
assert.truthy(body)
assert.are.equal(created_ids[v.collection], body.id)
end)
it("should return not found on GET", function()
local response, status, headers = http_client.get(kWebURL.."/"..v.collection.."/"..created_ids[v.collection].."blah")
local body = cjson.decode(response)
assert.are.equal(404, status)
assert.truthy(body)
assert.are.equal('{"id":"'..created_ids[v.collection]..'blah is an invalid uuid"}', response)
end)
it("should update a created entity on PUT", function()
local data = http_client.get(kWebURL.."/"..v.collection.."/"..created_ids[v.collection])
local body = cjson.decode(data)
-- Create new body
for k,v in pairs(v.update_fields) do
body[k] = v
end
local response, status, headers = http_client.put(kWebURL.."/"..v.collection.."/"..created_ids[v.collection], body)
local new_body = cjson.decode(response)
assert.are.equal(200, status)
assert.truthy(new_body)
assert.are.equal(created_ids[v.collection], new_body.id)
for k,v in pairs(v.update_fields) do
assert.are.equal(v, new_body[k])
end
assert.are.same(body, new_body)
end)
it("should not update when the content-type is wrong", function()
local response, status, headers = http_client.put(kWebURL.."/"..v.collection.."/"..created_ids[v.collection], body, { ["content-type"] = "application/x-www-form-urlencoded"})
assert.are.equal(415, status)
assert.are.equal("{\"message\":\"Unsupported Content-Type. Use \\\"application\\\/json\\\"\"}", response)
end)
it("should not save when the content-type is wrong", function()
local response, status, headers = http_client.post(kWebURL.."/"..v.collection.."/", v.entity, { ["content-type"] = "application/json"})
assert.are.equal(415, status)
assert.are.equal("{\"message\":\"Unsupported Content-Type. Use \\\"application\\\/x-www-form-urlencoded\\\"\"}", response)
end)
end)
end
for i,v in ipairs(ENDPOINTS) do
describe("#"..v.collection, function()
it("should delete an entity on DELETE", function()
local response, status, headers = http_client.delete(kWebURL.."/"..v.collection.."/"..created_ids[v.collection])
assert.are.equal(204, status)
end)
end)
end
end)
|
local spec_helper = require "spec.spec_helpers"
local http_client = require "kong.tools.http_client"
local cjson = require "cjson"
local env = spec_helper.get_env()
local created_ids = {}
local kWebURL = spec_helper.API_URL
local ENDPOINTS = {
{
collection = "apis",
total = table.getn(env.faker.FIXTURES.api) + 1,
entity = {
public_dns = "api.mockbin.com",
name = "mockbin",
target_url = "http://mockbin.com"
},
update_fields = {
public_dns = "newapi.mockbin.com"
},
error_message = '{"public_dns":"public_dns is required","name":"name is required","target_url":"target_url is required"}'
},
{
collection = "consumers",
total = table.getn(env.faker.FIXTURES.consumer) + 1,
entity = {
custom_id = "123456789"
},
update_fields = {
custom_id = "ABC_custom_ID"
},
error_message = nil
},
{
collection = "basicauth_credentials",
total = table.getn(env.faker.FIXTURES.basicauth_credential) + 1,
entity = {
username = "username5555",
password = "password5555",
consumer_id = function()
return created_ids.consumers
end
},
update_fields = {
username = "upd_username5555",
password = "upd_password5555"
},
error_message = '{"username":"username is required","consumer_id":"consumer_id is required"}'
},
{
collection = "keyauth_credentials",
total = table.getn(env.faker.FIXTURES.keyauth_credential) + 1,
entity = {
key = "apikey5555",
consumer_id = function()
return created_ids.consumers
end
},
update_fields = {
key = "upd_apikey5555",
},
error_message = '{"key":"key is required","consumer_id":"consumer_id is required"}'
},
{
collection = "plugins_configurations",
total = table.getn(env.faker.FIXTURES.plugin_configuration) + 1,
entity = {
name = "ratelimiting",
api_id = function()
return created_ids.apis
end,
consumer_id = function()
return created_ids.consumers
end,
["value.period"] = "second",
["value.limit"] = 10
},
update_fields = {
enabled = false
},
error_message = '{"name":"name is required","api_id":"api_id is required","value":"value is required"}'
}
}
describe("API", function()
setup(function()
spec_helper.prepare_db()
spec_helper.start_kong()
end)
teardown(function()
spec_helper.stop_kong()
spec_helper.reset_db()
end)
describe("/", function()
it("should return Kong's version and a welcome message", function()
local response, status, headers = http_client.get(kWebURL)
local body = cjson.decode(response)
assert.are.equal(200, status)
assert.truthy(body.version)
assert.truthy(body.tagline)
end)
end)
for i, v in ipairs(ENDPOINTS) do
describe("#"..v.collection.." entity", function()
it("should not create on POST with invalid parameters", function()
if v.collection ~= "consumers" then
local response, status, headers = http_client.post(kWebURL.."/"..v.collection.."/", {})
assert.are.equal(400, status)
assert.are.equal(v.error_message, response)
end
end)
it("should create an entity from valid paremeters", function()
-- Replace the IDs
for k, p in pairs(v.entity) do
if type(p) == "function" then
v.entity[k] = p()
end
end
local response, status, headers = http_client.post(kWebURL.."/"..v.collection.."/", v.entity)
local body = cjson.decode(response)
assert.are.equal(201, status)
assert.truthy(body)
-- Save the ID for later use
created_ids[v.collection] = body.id
end)
it("should GET all entities", function()
local response, status, headers = http_client.get(kWebURL.."/"..v.collection.."/")
local body = cjson.decode(response)
local inspect = require "inspect"
assert.are.equal(200, status)
assert.truthy(body.data)
--assert.truthy(body.total)
--assert.are.equal(v.total, body.total)
assert.are.equal(v.total, table.getn(body.data))
end)
it("should GET one entity", function()
local response, status, headers = http_client.get(kWebURL.."/"..v.collection.."/"..created_ids[v.collection])
local body = cjson.decode(response)
assert.are.equal(200, status)
assert.truthy(body)
assert.are.equal(created_ids[v.collection], body.id)
end)
it("should return not found on GET", function()
local response, status, headers = http_client.get(kWebURL.."/"..v.collection.."/"..created_ids[v.collection].."blah")
local body = cjson.decode(response)
assert.are.equal(404, status)
assert.truthy(body)
assert.are.equal('{"id":"'..created_ids[v.collection]..'blah is an invalid uuid"}', response)
end)
it("should update a created entity on PUT", function()
local data = http_client.get(kWebURL.."/"..v.collection.."/"..created_ids[v.collection])
local body = cjson.decode(data)
-- Create new body
for k,v in pairs(v.update_fields) do
body[k] = v
end
local response, status, headers = http_client.put(kWebURL.."/"..v.collection.."/"..created_ids[v.collection], body)
local new_body = cjson.decode(response)
assert.are.equal(200, status)
assert.truthy(new_body)
assert.are.equal(created_ids[v.collection], new_body.id)
for k,v in pairs(v.update_fields) do
assert.are.equal(v, new_body[k])
end
assert.are.same(body, new_body)
end)
it("should not update when the content-type is wrong", function()
local response, status, headers = http_client.put(kWebURL.."/"..v.collection.."/"..created_ids[v.collection], body, { ["content-type"] = "application/x-www-form-urlencoded"})
assert.are.equal(415, status)
assert.are.equal("{\"message\":\"Unsupported Content-Type. Use \\\"application\\/json\\\"\"}", response)
end)
it("should not save when the content-type is wrong", function()
local response, status, headers = http_client.post(kWebURL.."/"..v.collection.."/", v.entity, { ["content-type"] = "application/json"})
assert.are.equal(415, status)
assert.are.equal("{\"message\":\"Unsupported Content-Type. Use \\\"application\\/x-www-form-urlencoded\\\"\"}", response)
end)
end)
end
for i,v in ipairs(ENDPOINTS) do
describe("#"..v.collection, function()
it("should delete an entity on DELETE", function()
local response, status, headers = http_client.delete(kWebURL.."/"..v.collection.."/"..created_ids[v.collection])
assert.are.equal(204, status)
end)
end)
end
end)
|
fix: api tests. Escaping was erroring.
|
fix: api tests. Escaping was erroring.
|
Lua
|
apache-2.0
|
AnsonSmith/kong,bbalu/kong,wakermahmud/kong,puug/kong,ropik/kong,ChristopherBiscardi/kong,skynet/kong,paritoshmmmec/kong,Skyscanner/kong,vmercierfr/kong,chourobin/kong,sbuettner/kong,peterayeni/kong
|
ec3350f9c78a87208b03ba30139f54deb978a724
|
lua_scripts/display_hitboxes.lua
|
lua_scripts/display_hitboxes.lua
|
-- Renders all currently active hitboxes, with the color depending on the type of hitbox.
game_id = memory.readdword(0x023FFE0C)
if game_id == 0x45564341 then -- ACVE, US DoS
entity_list_start = 0x020CA3F0
entity_list_end = 0x020F6DEF
entity_size = 0x2A0
hitbox_list_start = 0x0210AF18
screen_x_ptr = 0x020F7070
screen_y_ptr = 0x020F7074
elseif game_id == 0x45424341 then -- ACBE, US PoR
entity_list_start = 0x020FC500
entity_list_end = 0x0211173F
entity_size = 0x160
hitbox_list_start = 0x0213291C
screen_x_ptr = 0x021119FC
screen_y_ptr = 0x02111A00
elseif game_id == 0x45395259 then -- YR9E, US OoE
entity_list_start = 0x021092A0
entity_list_end = 0x0211DF5F
entity_size = 0x160
hitbox_list_start = 0x02128BDC
screen_x_ptr = 0x021000BC
screen_y_ptr = 0x021000C0
else
print("Error: Unsupported game")
return
end
local function display_weapon_hitboxes()
entity_ptr = entity_list_start
screen_x = memory.readdwordsigned(screen_x_ptr)/0x1000
screen_y = memory.readdwordsigned(screen_y_ptr)/0x1000
while entity_ptr < entity_list_end do
entity_code_pointer = memory.readdword(entity_ptr)
entity_hitbox_is_active = memory.readbyte(entity_ptr+0xA6)
if entity_code_pointer ~= 0 and entity_hitbox_is_active ~= 0 then
hitbox_index = memory.readbyte(entity_ptr+0xA7)
for i=0,1 do
hitbox_ptr = hitbox_list_start + hitbox_index*0x14 + i*0xA
htype = memory.readword(hitbox_ptr)
left = memory.readwordsigned(hitbox_ptr + 2)
top = memory.readwordsigned(hitbox_ptr + 4)
right = memory.readwordsigned(hitbox_ptr + 6)
bottom = memory.readwordsigned(hitbox_ptr + 8)
if htype == 0 then -- Deleted hitbox.
-- We won't render these.
fillcolor = 0xFFFFFF3F
linecolor = 0xFFFFFFFF
elseif htype == 1 then -- Can deal damage but not take it.
-- Blue.
fillcolor = 0x0000FF3F
linecolor = 0x0000FFFF
elseif htype == 2 then -- Can take damage from player.
-- Yellow.
fillcolor = 0xFFFF003F
linecolor = 0xFFFF00FF
elseif htype == 3 then -- Can take damage from player, can deal damage to player.
-- Red.
--print(string.format("%08X", entity_ptr))
fillcolor = 0xFF00003F
linecolor = 0xFF0000FF
elseif htype == 4 then -- Can't deal or take damage.
-- Purple.
fillcolor = 0xFF00FF3F
linecolor = 0xFF00FFFF
elseif htype == 6 then -- Can take damage from enemies.
-- Green.
fillcolor = 0x00FF003F
linecolor = 0x00FF00FF
else
print("Unknown hitbox type " .. htype .. " at " .. string.format("%08X", hitbox_ptr))
fillcolor = 0x0000003F
linecolor = 0x000000FF
end
left = left-screen_x
top = top-screen_y
right = right-screen_x
bottom = bottom-screen_y
-- Negative y pos is interpreted as on the top screen by Desmume.
top = math.max(top, 0)
if htype ~= 0 and bottom >= 0 then
gui.drawbox(left, top, right, bottom, fillcolor, linecolor)
end
end
end
entity_ptr = entity_ptr + entity_size
end
end
gui.register(display_weapon_hitboxes)
|
-- Renders all currently active hitboxes, with the color depending on the type of hitbox.
identifier = memory.readword(0x0200000E)
if identifier == 0xFDE3 then -- US DoS
entity_list_start = 0x020CA3F0
entity_list_end = 0x020F6DEF
entity_size = 0x2A0
hitbox_list_start = 0x0210AF18
screen_x_ptr = 0x020F7070
screen_y_ptr = 0x020F7074
game_state_location = 0x020C07E8
elseif identifier == 0x94BA then -- US PoR
entity_list_start = 0x020FC500
entity_list_end = 0x0211173F
entity_size = 0x160
hitbox_list_start = 0x0213291C
screen_x_ptr = 0x021119FC
screen_y_ptr = 0x02111A00
game_state_location = 0x020F6284
elseif identifier == 0xC73B then -- US OoE
entity_list_start = 0x021092A0
entity_list_end = 0x0211DF5F
entity_size = 0x160
hitbox_list_start = 0x02128BDC
screen_x_ptr = 0x021000BC
screen_y_ptr = 0x021000C0
game_state_location = 0x0211D723 -- hack, that's not really the game state location. might be at 0x021516D0 but that doesn't work perfectly
else
-- 62F2 for JP DoS
-- 446B for JP PoR
-- EC90 for JP OoE
print("Error: Unsupported game")
return
end
local function display_hitboxes()
if memory.readbyte(game_state_location) ~= 2 then
-- Not ingame
return
end
entity_ptr = entity_list_start
screen_x = memory.readdwordsigned(screen_x_ptr)/0x1000
screen_y = memory.readdwordsigned(screen_y_ptr)/0x1000
while entity_ptr < entity_list_end do
entity_code_pointer = memory.readdword(entity_ptr)
entity_hitbox_is_active = memory.readbyte(entity_ptr+0xA6)
if entity_code_pointer ~= 0 and entity_hitbox_is_active ~= 0 then
hitbox_index = memory.readbyte(entity_ptr+0xA7)
for i=0,1 do
hitbox_ptr = hitbox_list_start + hitbox_index*0x14 + i*0xA
htype = memory.readword(hitbox_ptr)
left = memory.readwordsigned(hitbox_ptr + 2)
top = memory.readwordsigned(hitbox_ptr + 4)
right = memory.readwordsigned(hitbox_ptr + 6)
bottom = memory.readwordsigned(hitbox_ptr + 8)
if htype == 0 then -- Deleted hitbox.
-- We won't render these.
fillcolor = "#FFFFFF3F"
linecolor = "#FFFFFFFF"
elseif htype == 1 then -- Can deal damage but not take it.
-- Blue.
fillcolor = "#0000FF3F"
linecolor = "#0000FFFF"
elseif htype == 2 then -- Can take damage from player.
-- Yellow.
fillcolor = "#FFFF003F"
linecolor = "#FFFF00FF"
elseif htype == 3 then -- Can take damage from player, can deal damage to player.
-- Red.
fillcolor = "#FF00003F"
linecolor = "#FF0000FF"
elseif htype == 4 then -- Can't deal or take damage.
-- Purple.
fillcolor = "#FF00FF3F"
linecolor = "#FF00FFFF"
elseif htype == 6 then -- Can take damage from enemies.
-- Green.
fillcolor = "#00FF003F"
linecolor = "#00FF00FF"
else
print("Unknown hitbox type " .. htype .. " at " .. string.format("%08X", hitbox_ptr))
fillcolor = "#0000003F"
linecolor = "#000000FF"
end
left = left-screen_x
top = top-screen_y
right = right-screen_x
bottom = bottom-screen_y
-- Negative y pos is interpreted as on the top screen by Desmume.
top = math.max(top, 0)
if htype ~= 0 and bottom >= 0 then
gui.drawbox(left, top, right, bottom, fillcolor, linecolor)
end
end
end
entity_ptr = entity_ptr + entity_size
end
end
gui.register(display_hitboxes)
|
Fix some bugs with display hitboxes lua script
|
Fix some bugs with display hitboxes lua script
|
Lua
|
mit
|
LagoLunatic/DSVEdit
|
53efac47d2e04a3961c4f7d089d4c4f44bb20fb8
|
Mjolnir/setup.lua
|
Mjolnir/setup.lua
|
os.exit = mj._exit
local function pack(...)
return {n = select("#", ...), ...}
end
function mj.runstring(s)
local fn, err = loadstring("return " .. s)
if not fn then fn, err = loadstring(s) end
if not fn then return tostring(err) end
local str = ""
local results = pack(pcall(fn))
for i = 2,results.n do
if i > 2 then str = str .. "\t" end
str = str .. tostring(results[i])
end
return str
end
function mj.errorhandler(err)
mj._notify("Mjolnir error occurred")
print(err)
print(debug.traceback())
return err
end
function mj.pcall(f, ...)
return xpcall(f, mj.errorhandler, ...)
end
local rawprint = print
function print(...)
rawprint(...)
local vals = pack(...)
for k = 1, vals.n do
vals[k] = tostring(vals[k])
end
local str = table.concat(vals, "\t") .. "\n"
mj._logmessage(str)
end
--- mj.print = print
--- The original print function, before Mjolnir overrides it.
mj.print = rawprint
-- load user's init-file
local fn, err = loadfile "init.lua"
if fn then
if mj.pcall(fn) then
print "-- Load user settings: success."
end
elseif err:find "No such file or directory" then
print "-- Load personal settings: cannot find ~/.mjolnir/init.lua; skipping."
print "-- See the documentation for more info about init.lua"
else
print(tostring(err))
mj._notify("Syntax error in ~/.mjolnir/init.lua")
end
|
os.exit = mj._exit
local function pack(...)
return {n = select("#", ...), ...}
end
function mj.runstring(s)
local fn, err = loadstring("return " .. s)
if not fn then fn, err = loadstring(s) end
if not fn then return tostring(err) end
local str = ""
local results = pack(pcall(fn))
for i = 2,results.n do
if i > 2 then str = str .. "\t" end
str = str .. tostring(results[i])
end
return str
end
function mj.errorhandler(err)
mj._notify("Mjolnir error occurred")
print(err)
print(debug.traceback())
return err
end
function mj.pcall(f, ...)
return xpcall(f, mj.errorhandler, ...)
end
local rawprint = print
function print(...)
rawprint(...)
local vals = pack(...)
for k = 1, vals.n do
vals[k] = tostring(vals[k])
end
local str = table.concat(vals, "\t") .. "\n"
mj._logmessage(str)
end
--- mj.print = print
--- The original print function, before Mjolnir overrides it.
mj.print = rawprint
-- load user's init-file
local fn, err = loadfile "init.lua"
if fn then
if mj.pcall(fn) then
print "-- Loading ~/.mjolnir/init.lua; success."
end
elseif err:find "No such file or directory" then
print "-- Loading ~/.mjolnir/init.lua; file not found, skipping."
else
print(tostring(err))
mj._notify("Syntax error in ~/.mjolnir/init.lua")
end
|
Fixing wording.
|
Fixing wording.
|
Lua
|
mit
|
knl/hammerspoon,asmagill/hammerspoon,emoses/hammerspoon,zzamboni/hammerspoon,kkamdooong/hammerspoon,lowne/hammerspoon,hypebeast/hammerspoon,zzamboni/hammerspoon,CommandPost/CommandPost-App,peterhajas/hammerspoon,cmsj/hammerspoon,asmagill/hammerspoon,hypebeast/hammerspoon,Hammerspoon/hammerspoon,TimVonsee/hammerspoon,chrisjbray/hammerspoon,knu/hammerspoon,trishume/hammerspoon,TimVonsee/hammerspoon,Habbie/hammerspoon,latenitefilms/hammerspoon,cmsj/hammerspoon,wsmith323/hammerspoon,Habbie/hammerspoon,knl/hammerspoon,emoses/hammerspoon,latenitefilms/hammerspoon,joehanchoi/hammerspoon,chrisjbray/hammerspoon,ocurr/hammerspoon,heptal/hammerspoon,Hammerspoon/hammerspoon,cmsj/hammerspoon,latenitefilms/hammerspoon,joehanchoi/hammerspoon,peterhajas/hammerspoon,nkgm/hammerspoon,chrisjbray/hammerspoon,asmagill/hammerspoon,chrisjbray/hammerspoon,Habbie/hammerspoon,CommandPost/CommandPost-App,bradparks/hammerspoon,TimVonsee/hammerspoon,lowne/hammerspoon,Stimim/hammerspoon,emoses/hammerspoon,asmagill/hammerspoon,tmandry/hammerspoon,heptal/hammerspoon,dopcn/hammerspoon,knu/hammerspoon,peterhajas/hammerspoon,cmsj/hammerspoon,hypebeast/hammerspoon,kkamdooong/hammerspoon,dopcn/hammerspoon,emoses/hammerspoon,TimVonsee/hammerspoon,zzamboni/hammerspoon,knu/hammerspoon,zzamboni/hammerspoon,heptal/hammerspoon,bradparks/hammerspoon,wvierber/hammerspoon,TimVonsee/hammerspoon,ocurr/hammerspoon,peterhajas/hammerspoon,cmsj/hammerspoon,bradparks/hammerspoon,kkamdooong/hammerspoon,latenitefilms/hammerspoon,wvierber/hammerspoon,asmagill/hammerspoon,joehanchoi/hammerspoon,nkgm/hammerspoon,hypebeast/hammerspoon,CommandPost/CommandPost-App,knu/hammerspoon,junkblocker/hammerspoon,CommandPost/CommandPost-App,joehanchoi/hammerspoon,chrisjbray/hammerspoon,wvierber/hammerspoon,asmagill/hammerspoon,latenitefilms/hammerspoon,zzamboni/hammerspoon,emoses/hammerspoon,CommandPost/CommandPost-App,junkblocker/hammerspoon,trishume/hammerspoon,cmsj/hammerspoon,Hammerspoon/hammerspoon,Stimim/hammerspoon,wsmith323/hammerspoon,ocurr/hammerspoon,tmandry/hammerspoon,nkgm/hammerspoon,trishume/hammerspoon,junkblocker/hammerspoon,Habbie/hammerspoon,kkamdooong/hammerspoon,bradparks/hammerspoon,lowne/hammerspoon,lowne/hammerspoon,latenitefilms/hammerspoon,dopcn/hammerspoon,wsmith323/hammerspoon,Stimim/hammerspoon,knl/hammerspoon,junkblocker/hammerspoon,heptal/hammerspoon,Stimim/hammerspoon,Hammerspoon/hammerspoon,wsmith323/hammerspoon,wsmith323/hammerspoon,kkamdooong/hammerspoon,bradparks/hammerspoon,knl/hammerspoon,knu/hammerspoon,joehanchoi/hammerspoon,Hammerspoon/hammerspoon,peterhajas/hammerspoon,CommandPost/CommandPost-App,nkgm/hammerspoon,tmandry/hammerspoon,wvierber/hammerspoon,dopcn/hammerspoon,junkblocker/hammerspoon,ocurr/hammerspoon,ocurr/hammerspoon,Hammerspoon/hammerspoon,dopcn/hammerspoon,heptal/hammerspoon,hypebeast/hammerspoon,Habbie/hammerspoon,nkgm/hammerspoon,wvierber/hammerspoon,knu/hammerspoon,lowne/hammerspoon,chrisjbray/hammerspoon,zzamboni/hammerspoon,Stimim/hammerspoon,Habbie/hammerspoon,knl/hammerspoon
|
b1bb1b3f9f20d274fe089e4d8529716f1fa6d039
|
Tester.lua
|
Tester.lua
|
local Tester = torch.class('torch.Tester')
function Tester:__init()
self.errors = {}
self.tests = {}
self.testnames = {}
self.curtestname = ''
end
function Tester:assert_sub (condition, message)
self.countasserts = self.countasserts + 1
if not condition then
local ss = debug.traceback('tester',2)
--print(ss)
ss = ss:match('[^\n]+\n[^\n]+\n([^\n]+\n[^\n]+)\n')
self.errors[#self.errors+1] = self.curtestname .. '\n' .. message .. '\n' .. ss .. '\n'
end
end
function Tester:assert (condition, message)
self:assert_sub(condition,string.format('%s\n%s condition=%s',message,' BOOL violation ', tostring(condition)))
end
function Tester:assertlt (val, condition, message)
self:assert_sub(val<condition,string.format('%s\n%s val=%s, condition=%s',message,' LT(<) violation ', tostring(val), tostring(condition)))
end
function Tester:assertgt (val, condition, message)
self:assert_sub(val>condition,string.format('%s\n%s val=%s, condition=%s',message,' GT(>) violation ', tostring(val), tostring(condition)))
end
function Tester:assertle (val, condition, message)
self:assert_sub(val<=condition,string.format('%s\n%s val=%s, condition=%s',message,' LE(<=) violation ', tostring(val), tostring(condition)))
end
function Tester:assertge (val, condition, message)
self:assert_sub(val>=condition,string.format('%s\n%s val=%s, condition=%s',message,' GE(>=) violation ', tostring(val), tostring(condition)))
end
function Tester:asserteq (val, condition, message)
self:assert_sub(val==condition,string.format('%s\n%s val=%s, condition=%s',message,' EQ(==) violation ', tostring(val), tostring(condition)))
end
function Tester:assertne (val, condition, message)
self:assert_sub(val~=condition,string.format('%s\n%s val=%s, condition=%s',message,' NE(~=) violation ', tostring(val), tostring(condition)))
end
function Tester:assertTensorEq(ta, tb, condition, message)
local diff = ta-tb
local err = diff:abs():max()
self:assert_sub(err<condition,string.format('%s\n%s val=%s, condition=%s',message,' TensorEQ(==) violation ', tostring(err), tostring(condition)))
end
function Tester:assertTensorNe(ta, tb, condition, message)
local diff = ta-tb
local err = diff:abs():max()
self:assert_sub(err>=condition,string.format('%s\n%s val=%s, condition=%s',message,' TensorNE(~=) violation ', tostring(err), tostring(condition)))
end
local function areTablesEqual(ta, tb)
local function isIncludedIn(ta, tb)
if type(ta) ~= 'table' or type(tb) ~= 'table' then
return ta == tb
end
for k, v in pairs(tb) do
if not areTablesEqual(ta[k], v) then return false end
end
return true
end
return isIncludedIn(ta, tb) and isIncludedIn(tb, ta)
end
function Tester:assertTableEq(ta, tb, message)
self:assert_sub(areTablesEqual(ta, tb), string.format('%s\n%s val=%s, condition=%s',message,' TableEQ(==) violation ', tostring(err), tostring(condition)))
end
function Tester:assertTableNe(ta, tb, message)
self:assert_sub(not areTablesEqual(ta, tb), string.format('%s\n%s val=%s, condition=%s',message,' TableEQ(==) violation ', tostring(err), tostring(condition)))
end
function Tester:assertError(f, message)
status, err = pcall(f)
self:assert_sub(status == false, string.format('%s\n%s condition=%s',message,' ERROR violation ', 'should have errored'))
end
function Tester:pcall(f)
local nerr = #self.errors
-- local res = f()
local stat, result = xpcall(f, debug.traceback)
if not stat then
self.errors[#self.errors+1] = self.curtestname .. '\n Function call failed \n' .. result .. '\n'
end
return stat, result, stat and (nerr == #self.errors)
-- return true, res, nerr == #self.errors
end
function Tester:report(tests)
if not tests then
tests = self.tests
end
print('Completed ' .. self.countasserts .. ' asserts in ' .. #tests .. ' tests with ' .. #self.errors .. ' errors')
print()
print(string.rep('-',80))
for i,v in ipairs(self.errors) do
print(v)
print(string.rep('-',80))
end
end
function Tester:run(run_tests)
local tests, testnames
self.countasserts = 0
tests = self.tests
testnames = self.testnames
if type(run_tests) == 'string' then
run_tests = {run_tests}
end
if type(run_tests) == 'table' then
tests = {}
testnames = {}
for i,fun in ipairs(self.tests) do
for j,name in ipairs(run_tests) do
if self.testnames[i] == name then
tests[#tests+1] = self.tests[i]
testnames[#testnames+1] = self.testnames[i]
end
end
end
end
print('Running ' .. #tests .. ' tests')
local statstr = string.rep('_',#tests)
local pstr = ''
io.write(statstr .. '\r')
for i,v in ipairs(tests) do
self.curtestname = testnames[i]
--clear
io.write('\r' .. string.rep(' ', pstr:len()))
io.flush()
--write
pstr = statstr:sub(1,i-1) .. '|' .. statstr:sub(i+1) .. ' ==> ' .. self.curtestname
io.write('\r' .. pstr)
io.flush()
local stat, message, pass = self:pcall(v)
if pass then
--io.write(string.format('\b_'))
statstr = statstr:sub(1,i-1) .. '_' .. statstr:sub(i+1)
else
statstr = statstr:sub(1,i-1) .. '*' .. statstr:sub(i+1)
--io.write(string.format('\b*'))
end
if not stat then
-- print()
-- print('Function call failed: Test No ' .. i .. ' ' .. testnames[i])
-- print(message)
end
collectgarbage()
end
--clear
io.write('\r' .. string.rep(' ', pstr:len()))
io.flush()
-- write finish
pstr = statstr .. ' ==> Done '
io.write('\r' .. pstr)
io.flush()
print()
print()
self:report(tests)
end
function Tester:add(f,name)
name = name or 'unknown'
if type(f) == "table" then
for i,v in pairs(f) do
self:add(v,i)
end
elseif type(f) == "function" then
self.tests[#self.tests+1] = f
self.testnames[#self.tests] = name
else
error('Tester:add(f) expects a function or a table of functions')
end
end
|
local Tester = torch.class('torch.Tester')
function Tester:__init()
self.errors = {}
self.tests = {}
self.testnames = {}
self.curtestname = ''
end
function Tester:assert_sub (condition, message)
self.countasserts = self.countasserts + 1
if not condition then
local ss = debug.traceback('tester',2)
--print(ss)
ss = ss:match('[^\n]+\n[^\n]+\n([^\n]+\n[^\n]+)\n')
self.errors[#self.errors+1] = self.curtestname .. '\n' .. message .. '\n' .. ss .. '\n'
end
end
function Tester:assert (condition, message)
self:assert_sub(condition,string.format('%s\n%s condition=%s',message,' BOOL violation ', tostring(condition)))
end
function Tester:assertlt (val, condition, message)
self:assert_sub(val<condition,string.format('%s\n%s val=%s, condition=%s',message,' LT(<) violation ', tostring(val), tostring(condition)))
end
function Tester:assertgt (val, condition, message)
self:assert_sub(val>condition,string.format('%s\n%s val=%s, condition=%s',message,' GT(>) violation ', tostring(val), tostring(condition)))
end
function Tester:assertle (val, condition, message)
self:assert_sub(val<=condition,string.format('%s\n%s val=%s, condition=%s',message,' LE(<=) violation ', tostring(val), tostring(condition)))
end
function Tester:assertge (val, condition, message)
self:assert_sub(val>=condition,string.format('%s\n%s val=%s, condition=%s',message,' GE(>=) violation ', tostring(val), tostring(condition)))
end
function Tester:asserteq (val, condition, message)
self:assert_sub(val==condition,string.format('%s\n%s val=%s, condition=%s',message,' EQ(==) violation ', tostring(val), tostring(condition)))
end
function Tester:assertne (val, condition, message)
self:assert_sub(val~=condition,string.format('%s\n%s val=%s, condition=%s',message,' NE(~=) violation ', tostring(val), tostring(condition)))
end
function Tester:assertTensorEq(ta, tb, condition, message)
local diff = ta-tb
local err = diff:abs():max()
self:assert_sub(err<condition,string.format('%s\n%s val=%s, condition=%s',message,' TensorEQ(==) violation ', tostring(err), tostring(condition)))
end
function Tester:assertTensorNe(ta, tb, condition, message)
local diff = ta-tb
local err = diff:abs():max()
self:assert_sub(err>=condition,string.format('%s\n%s val=%s, condition=%s',message,' TensorNE(~=) violation ', tostring(err), tostring(condition)))
end
local function areTablesEqual(ta, tb)
local function isIncludedIn(ta, tb)
if type(ta) ~= 'table' or type(tb) ~= 'table' then
return ta == tb
end
for k, v in pairs(tb) do
if not areTablesEqual(ta[k], v) then return false end
end
return true
end
return isIncludedIn(ta, tb) and isIncludedIn(tb, ta)
end
function Tester:assertTableEq(ta, tb, message)
self:assert_sub(areTablesEqual(ta, tb), string.format('%s\n%s val=%s, condition=%s',message,' TableEQ(==) violation ', tostring(err), tostring(condition)))
end
function Tester:assertTableNe(ta, tb, message)
self:assert_sub(not areTablesEqual(ta, tb), string.format('%s\n%s val=%s, condition=%s',message,' TableEQ(==) violation ', tostring(err), tostring(condition)))
end
function Tester:assertError(f, message)
return self:assertErrorObj(f, function(err) return true end, message)
end
function Tester:assertErrorMsg(f, errmsg, message)
return self:assertErrorObj(f, function(err) return err == errmsg end, message)
end
function Tester:assertErrorObj(f, errcomp, message)
-- errcomp must be a function that compares the error object to its expected value
local status, err = pcall(f)
self:assert_sub(status == false and errcomp(err), string.format('%s\n%s condition=%s',message,' ERROR violation ', 'should have errored'))
end
function Tester:pcall(f)
local nerr = #self.errors
-- local res = f()
local stat, result = xpcall(f, debug.traceback)
if not stat then
self.errors[#self.errors+1] = self.curtestname .. '\n Function call failed \n' .. result .. '\n'
end
return stat, result, stat and (nerr == #self.errors)
-- return true, res, nerr == #self.errors
end
function Tester:report(tests)
if not tests then
tests = self.tests
end
print('Completed ' .. self.countasserts .. ' asserts in ' .. #tests .. ' tests with ' .. #self.errors .. ' errors')
print()
print(string.rep('-',80))
for i,v in ipairs(self.errors) do
print(v)
print(string.rep('-',80))
end
end
function Tester:run(run_tests)
local tests, testnames
self.countasserts = 0
tests = self.tests
testnames = self.testnames
if type(run_tests) == 'string' then
run_tests = {run_tests}
end
if type(run_tests) == 'table' then
tests = {}
testnames = {}
for i,fun in ipairs(self.tests) do
for j,name in ipairs(run_tests) do
if self.testnames[i] == name then
tests[#tests+1] = self.tests[i]
testnames[#testnames+1] = self.testnames[i]
end
end
end
end
print('Running ' .. #tests .. ' tests')
local statstr = string.rep('_',#tests)
local pstr = ''
io.write(statstr .. '\r')
for i,v in ipairs(tests) do
self.curtestname = testnames[i]
--clear
io.write('\r' .. string.rep(' ', pstr:len()))
io.flush()
--write
pstr = statstr:sub(1,i-1) .. '|' .. statstr:sub(i+1) .. ' ==> ' .. self.curtestname
io.write('\r' .. pstr)
io.flush()
local stat, message, pass = self:pcall(v)
if pass then
--io.write(string.format('\b_'))
statstr = statstr:sub(1,i-1) .. '_' .. statstr:sub(i+1)
else
statstr = statstr:sub(1,i-1) .. '*' .. statstr:sub(i+1)
--io.write(string.format('\b*'))
end
if not stat then
-- print()
-- print('Function call failed: Test No ' .. i .. ' ' .. testnames[i])
-- print(message)
end
collectgarbage()
end
--clear
io.write('\r' .. string.rep(' ', pstr:len()))
io.flush()
-- write finish
pstr = statstr .. ' ==> Done '
io.write('\r' .. pstr)
io.flush()
print()
print()
self:report(tests)
end
function Tester:add(f,name)
name = name or 'unknown'
if type(f) == "table" then
for i,v in pairs(f) do
self:add(v,i)
end
elseif type(f) == "function" then
self.tests[#self.tests+1] = f
self.testnames[#self.tests] = name
else
error('Tester:add(f) expects a function or a table of functions')
end
end
|
Extend assertError and fix global
|
Extend assertError and fix global
Two new asserts: assertErrorMsg and assertErroObj,
to compare the actual error message or object returned.
|
Lua
|
bsd-3-clause
|
syhw/torch7,jlegendary/torch7,WangHong-yang/torch7,dhruvparamhans/torch7,akhti/torch7,voidException/torch7,Moodstocks/torch7,massimobernava/torch7,ujjwalkarn/torch7,wickedfoo/torch7,ominux/torch7,bnk-iitb/torch7,kidaa/torch7,stein2013/torch7,Peilong/torch7,szagoruyko/torch7,ominux/torch7,iamtrask/torch7,hughperkins/torch7,kod3r/torch7,yt752/torch7,MOUlili/torch7,Srisai85/torch7,xindaya/torch7,douwekiela/torch7,alexbw/torch7,fmassa/torch7,breakds/torch7,ninjin/torch7,Cadene/torch7,ninjin/torch7,Moodstocks/torch7,u20024804/torch7,breakds/torch7,hmandal/torch7,PrajitR/torch7,adamlerer/torch7,clementfarabet/torch7,hechenfon/torch7,Jai-Chaudhary/torch7,dhruvparamhans/torch7,xindaya/torch7,yaolubrain/torch7,kirangonella/torch7,chenfsjz/torch7,LinusU/torch7,rickyHong/torchPlusDQN,Atcold/torch7,fmassa/torch7,pushups/torch7,eriche2016/torch7,PierrotLC/torch7,voidException/torch7,kod3r/torch7,yt752/torch7,clementfarabet/torch7,colesbury/torch7,szagoruyko/torch7,akhti/torch7,hechenfon/torch7,Cadene/torch7,jaak-s/torch7,0wu/torch7,massimobernava/torch7,jibaro/torch7,chenfsjz/torch7,wangg12/torch7,wangg12/torch7,nicholas-leonard/torch7,jbeich/torch7,dominikgrewe/torch7,wgapl/torch7,stein2013/torch7,dariosena/torch7,wheatwaves/torch7,hughperkins/torch7,Peilong/torch7,bartvm/torch7,nkhuyu/torch7,bartvm/torch7,jibaro/torch7,waitwaitforget/torch7,kirangonella/torch7,jaak-s/torch7,yaolubrain/torch7,waitwaitforget/torch7,yozw/torch7,Jai-Chaudhary/torch7,wgapl/torch7,mr-justin/torch7,kaustubhcs/torch7,colesbury/torch7,syhw/torch7,golden1232004/torch7,diz-vara/torch7,0wu/torch7,dominikgrewe/torch7,rickyHong/torchPlusDQN,eriche2016/torch7,iamtrask/torch7,eulerreich/torch7,diz-vara/torch7,nicholas-leonard/torch7,bnk-iitb/torch7,MOUlili/torch7,redbill/torch7,jlegendary/torch7,dariosena/torch7,ilovecv/torch7,golden1232004/torch7,yozw/torch7,WangHong-yang/torch7,eulerreich/torch7,alexbw/torch7,rotmanmi/torch7,PrajitR/torch7,kidaa/torch7,Atcold/torch7,adamlerer/torch7,Srisai85/torch7,redbill/torch7,mr-justin/torch7,nkhuyu/torch7,rotmanmi/torch7,PierrotLC/torch7,kaustubhcs/torch7,ilovecv/torch7,jbeich/torch7,pushups/torch7,LinusU/torch7,wheatwaves/torch7,ujjwalkarn/torch7,hmandal/torch7,u20024804/torch7,wickedfoo/torch7,douwekiela/torch7
|
26080c2f04e967071fa19a4e9fd3dd1fe87cbfe0
|
test.lua
|
test.lua
|
--
-- Copyright (C) 2012-2014 Arseny Vakhrushev <arseny.vakhrushev at gmail dot com>
-- Please read the LICENSE file for license details
--
math.randomseed(os.time())
local amf3 = require 'amf3'
local amf3_encode = amf3.encode
local amf3_decode = amf3.decode
local error = error
local pairs = pairs
local print = print
local type = type
local unpack = unpack
local io_flush = io.flush
local io_write = io.write
local math_random = math.random
local string_char = string.char
local table_insert = table.insert
local vals = {
function () return nil end, -- Undefined
function () return math_random() < 0.5 end, -- Boolean
function () return math_random(-268435456, 268435455) end, -- Integer
function () return (math_random() - 0.5) * 1234567890 end, -- Double
function () -- String
local t = {}
for i = 1, math_random(0, 30) do
t[i] = math_random(0, 10)
end
return string_char(unpack(t))
end,
}
local refs, any
local objs = {
function () -- Reference
local n = #refs
return n > 0 and refs[math_random(n)] or nil
end,
function (d) -- Dense array
local t = {}
for i = 1, math_random(0, 10) do
local v = any(d + 1)
if v ~= nil then
table_insert(t, v)
end
end
table_insert(refs, t)
return t
end,
function (d) -- Associative array
local t = {}
for i = 1, math_random(0, 10) do
local k = vals[5]() -- Random string key
local v = any(d + 1)
if #k > 0 and v ~= nil then
t[k] = v
end
end
table_insert(refs, t)
return t
end,
}
any = function (d)
if d < 4 and math_random() < 0.7 then
return objs[math_random(#objs)](d)
end
return vals[math_random(#vals)]()
end
local function spawn()
refs = {}
return any(0)
end
local function compare(v1, v2)
local r = {}
local function compare(v1, v2)
if type(v1) ~= 'table' or type(v2) ~= 'table' then
return v1 == v2
end
if r[v1] and r[v2] then
return true
end
r[v1] = true
r[v2] = true
for k, v in pairs(v1) do
if not compare(v, v2[k]) then
return false
end
end
for k, v in pairs(v2) do
if not compare(v, v1[k]) then
return false
end
end
return true
end
return compare(v1, v2)
end
local function stdout(...)
io_write(...)
io_flush()
end
local function printf(fmt, ...)
print(fmt:format(...))
end
local function check(cond)
if not cond then
stdout '\n'
error('check failed!', 2)
end
end
-- Stress test
local total = 0
local cnt = 0
local max = 0
local sizes = {}
for i = 1, 50 do
for j = 1, 20 do
local obj = spawn()
local str = amf3_encode(obj)
local size = #str
local _obj, _size = amf3_decode(str)
check(size == _size)
check(compare(obj, _obj))
total = total + size
cnt = cnt + 1
if max < size then
max = size
end
table_insert(sizes, size)
-- Additional decoder's robustness test
for pos = 1, size - 1 do
pcall(amf3_decode, str, pos)
end
end
stdout '.'
end
stdout '\n'
printf('Processed %d bytes in %d chunks', total, cnt)
printf('Max chunk size: %d bytes', max)
print 'Size distribution:'
print '% of max size\t% of chunks'
for i = 1, 10 do
local a = (i - 1) / 10 * max
local b = i / 10 * max
local c = 0
for _, size in ipairs(sizes) do
if size > a and size <= b then
c = c + 1
end
end
printf('%2d...%d \t%5.1f', (i - 1) * 10, i * 10, c / cnt * 100)
end
-- Compliance test
local strs = {
-- Date, XML, XMLDoc, ByteArray
string_char(
0x09, 0x11, 0x01, -- Array (length 8)
0x08, 0x01, 0x3f, 0xb9, 0x99, 0x99, 0x99, 0x99, 0x99, 0x9a, -- Date (0.1)
0x0b, 0x07, 0x41, 0x42, 0x43, -- XML ("ABC")
0x07, 0x07, 0x44, 0x45, 0x46, -- XMLDoc ("DEF")
0x0c, 0x07, 0x11, 0x22, 0x33, -- ByteArray (11 22 33)
0x08, 0x02, -- Date (reference 1)
0x0b, 0x04, -- XML (reference 2)
0x0b, 0x06, -- XMLDoc (reference 3)
0x0c, 0x08 -- ByteArray (reference 4)
),
-- Mixed array
string_char(
0x09, 0x07, -- Array (length 3)
0x03, 0x41, 0x04, 0x01, 0x03, 0x42, 0x04, 0x02, -- Associative part: A:1, B:2
0x01, -- End of associative part
0x06, 0x01, 0x03, 0x02 -- Dense part: ["", true, false]
),
-- Object
string_char(
0x09, 0x09, 0x01, -- Array (length 4)
0x0a, 0x3b, 0x07, 0x41, 0x42, 0x43, 0x03, 0x41, 0x03, 0x42, 0x03, 0x43, -- Dynamic class ABC with static members A, B, C
0x04, 0x01, 0x04, 0x02, 0x04, 0x03, -- Static member values: A:1, B:2, C:3
0x03, 0x44, 0x04, 0x04, 0x03, 0x45, 0x04, 0x05, -- Dynamic members: D:4, E:5
0x01, -- End of dymanic part
0x0a, 0x01, -- Object (class reference 0)
0x01, 0x02, 0x03, -- Static member values: A:null, B:false, C:true
0x03, 0x46, 0x02, 0x03, 0x46, 0x03, -- Dynamic members: F:false, F:true (same name!!!)
0x01, -- End of dymanic part
0x0a, 0x07, 0x07, 0x44, 0x45, 0x46, -- Externalizable class DEF
0x02, -- _data:false
0x0a, 0x05, -- Object (class reference 1)
0x03 -- _data:true
),
}
local ba = string_char(0x11, 0x22, 0x33)
local objs = {
{ 0.1, "ABC", "DEF", ba, 0.1, "ABC", "DEF", ba },
{ A = 1, B = 2, [1] = '', [2] = true, [3] = false },
{
{ A = 1, B = 2, C = 3, D = 4, E = 5, _class = 'ABC' },
{ A = nil, B = false, C = true, F = true, _class = 'ABC' },
{ _data = false, _class = 'DEF' },
{ _data = true, _class = 'DEF' },
}
}
for i = 1, #strs do
local str, obj = strs[i], objs[i]
local size = #str
local _obj, _size = amf3_decode(str)
check(size == _size)
check(compare(obj, _obj))
end
|
--
-- Copyright (C) 2012-2014 Arseny Vakhrushev <arseny.vakhrushev at gmail dot com>
-- Please read the LICENSE file for license details
--
math.randomseed(os.time())
local amf3 = require 'amf3'
local amf3_encode = amf3.encode
local amf3_decode = amf3.decode
local error = error
local pairs = pairs
local print = print
local type = type
local unpack = unpack
local io_flush = io.flush
local io_write = io.write
local math_random = math.random
local string_char = string.char
local table_insert = table.insert
local vals = {
function () return nil end, -- Undefined
function () return math_random() < 0.5 end, -- Boolean
function () return math_random(-268435456, 268435455) end, -- Integer
function () return (math_random() - 0.5) * 1234567890 end, -- Double
function () -- String
local t = {}
for i = 1, math_random(0, 30) do
t[i] = math_random(0, 10)
end
return string_char(unpack(t))
end,
}
local refs, any
local objs = {
function () -- Reference
local n = #refs
return n > 0 and refs[math_random(n)] or nil
end,
function (d) -- Dense array
local t = {}
for i = 1, math_random(0, 10) do
local v = any(d + 1)
if v ~= nil then
table_insert(t, v)
end
end
table_insert(refs, t)
return t
end,
function (d) -- Associative array
local t = {}
for i = 1, math_random(0, 10) do
local k = vals[5]() -- Random string key
local v = any(d + 1)
if #k > 0 and v ~= nil then
t[k] = v
end
end
table_insert(refs, t)
return t
end,
}
any = function (d)
if d < 4 and math_random() < 0.7 then
return objs[math_random(#objs)](d)
end
return vals[math_random(#vals)]()
end
local function spawn()
refs = {}
return any(0)
end
local function compare(v1, v2)
local r = {}
local function compare(v1, v2)
if type(v1) ~= 'table' or type(v2) ~= 'table' then
return v1 == v2
end
if r[v1] and r[v2] then
return true
end
r[v1] = true
r[v2] = true
for k, v in pairs(v1) do
if not compare(v, v2[k]) then
return false
end
end
for k, v in pairs(v2) do
if not compare(v, v1[k]) then
return false
end
end
return true
end
return compare(v1, v2)
end
local function stdout(...)
io_write(...)
io_flush()
end
local function printf(fmt, ...)
print(fmt:format(...))
end
local function check(cond)
if not cond then
stdout '\n'
error('check failed!', 2)
end
end
-- Stress test
local total = 0
local cnt = 0
local max = 0
local sizes = {}
for i = 1, 50 do
for j = 1, 20 do
local obj = spawn()
local str = amf3_encode(obj)
local size = #str
local _obj, _size = amf3_decode(str)
check(size == _size)
check(compare(obj, _obj))
total = total + size
cnt = cnt + 1
if max < size then
max = size
end
table_insert(sizes, size)
-- Additional decoder's robustness test
for pos = 1, size - 1 do
pcall(amf3_decode, str, pos)
end
end
stdout '.'
end
stdout '\n'
printf('Processed %d bytes in %d chunks', total, cnt)
printf('Max chunk size: %d bytes', max)
print 'Size distribution:'
print '% of max size\t% of chunks'
for i = 1, 10 do
local a = (i - 1) / 10 * max
local b = i / 10 * max
local c = 0
for _, size in ipairs(sizes) do
if size > a and size <= b then
c = c + 1
end
end
printf('%2d...%d \t%5.1f', (i - 1) * 10, i * 10, c / cnt * 100)
end
-- Compliance test
local strs = {
-- Date, XML, XMLDoc, ByteArray
string_char(
0x09, 0x11, 0x01, -- Array (length 8)
0x08, 0x01, 0x3f, 0xb9, 0x99, 0x99, 0x99, 0x99, 0x99, 0x9a, -- Date (0.1)
0x0b, 0x07, 0x41, 0x42, 0x43, -- XML ('ABC')
0x07, 0x07, 0x44, 0x45, 0x46, -- XMLDoc ('DEF')
0x0c, 0x07, 0x11, 0x22, 0x33, -- ByteArray (11 22 33)
0x08, 0x02, -- Date (reference 1)
0x0b, 0x04, -- XML (reference 2)
0x0b, 0x06, -- XMLDoc (reference 3)
0x0c, 0x08 -- ByteArray (reference 4)
),
-- Mixed array
string_char(
0x09, 0x07, -- Array (length 3)
0x03, 0x41, 0x04, 0x01, 0x03, 0x42, 0x04, 0x02, -- Associative part: A:1, B:2
0x01, -- End of associative part
0x06, 0x01, 0x03, 0x02 -- Dense part: ['', true, false]
),
-- Object
string_char(
0x09, 0x09, 0x01, -- Array (length 4)
0x0a, 0x3b, 0x07, 0x41, 0x42, 0x43, 0x03, 0x41, 0x03, 0x42, 0x03, 0x43, -- Dynamic class ABC with static members A, B, C
0x04, 0x01, 0x04, 0x02, 0x04, 0x03, -- Static member values: A:1, B:2, C:3
0x03, 0x44, 0x04, 0x04, 0x03, 0x45, 0x04, 0x05, -- Dynamic members: D:4, E:5
0x01, -- End of dymanic part
0x0a, 0x01, -- Object (class reference 0)
0x01, 0x02, 0x03, -- Static member values: A:null, B:false, C:true
0x03, 0x46, 0x02, 0x03, 0x46, 0x03, -- Dynamic members: F:false, F:true (same name!!!)
0x01, -- End of dymanic part
0x0a, 0x07, 0x07, 0x44, 0x45, 0x46, -- Externalizable class DEF
0x02, -- _data:false
0x0a, 0x05, -- Object (class reference 1)
0x03 -- _data:true
),
}
local ba = string_char(0x11, 0x22, 0x33)
local objs = {
{ 0.1, 'ABC', 'DEF', ba, 0.1, 'ABC', 'DEF', ba },
{ A = 1, B = 2, [1] = '', [2] = true, [3] = false },
{
{ A = 1, B = 2, C = 3, D = 4, E = 5, _class = 'ABC' },
{ A = nil, B = false, C = true, F = true, _class = 'ABC' },
{ _data = false, _class = 'DEF' },
{ _data = true, _class = 'DEF' },
}
}
for i = 1, #strs do
local str, obj = strs[i], objs[i]
local size = #str
local _obj, _size = amf3_decode(str)
check(size == _size)
check(compare(obj, _obj))
end
print 'Test completed!'
|
+ Fixes to the test
|
+ Fixes to the test
|
Lua
|
mit
|
neoxic/lua-amf3
|
168dffc6bd6aa21ef8ac32ea6987c9dd64a98101
|
packages/svg.lua
|
packages/svg.lua
|
local svg = require("svg")
local pdf = require("justenoughlibtexpdf")
local parser = require("core/opentype-parser")
local pushSVG = function (string, desiredHeight, em, drop)
local figure, width, height = svg.svg_to_ps(string,em)
local scalefactor = 1
if desiredHeight then
scalefactor = desiredHeight / height
height = desiredHeight
width = width * scalefactor
end
scalefactor = scalefactor * em / 72
SILE.typesetter:pushHbox({
value = nil,
height = height,
width = width,
depth = 0,
outputYourself= function (self, typesetter)
pdf.add_content("q")
SILE.outputter.moveTo(typesetter.frame.state.cursorX, typesetter.frame.state.cursorY)
local x,y = SILE.outputter.cursor()
y = y - SILE.documentState.paperSize[2] + (drop and 0 or height)
pdf.add_content(scalefactor.." 0 0 "..-(scalefactor).." "..x.." "..y.." cm")
pdf.add_content(figure)
pdf.add_content("Q")
typesetter.frame:advanceWritingDirection(self.width)
end
})
end
SILE.registerCommand("include-svg-file", function (options, _)
local fn = SU.required(options, "src", "filename")
local height = options.height and SU.cast("measurement", options.height):absolute() or nil
local density = options.density or 72
local fh = io.open(fn)
local inp = fh:read("*all")
pushSVG(inp, height, density)
end)
SILE.registerCommand("svg-glyph", function(_, content)
local fontoptions = SILE.font.loadDefaults({})
local items = SILE.shaper:shapeToken(content[1], fontoptions)
local face = SILE.shaper.getFace(fontoptions)
parser.parseFont(face)
if not face.font.svg then return SILE.process(content) end
for i = 1, #items do
local svg_data = parser.getSVG(face, items[i].gid)
if svg_data then pushSVG(svg_data, fontoptions.size, 72, true) end
end
end)
return {
documentation = [[\begin{document}
This experimental package provides two commands.
The first is \code{\\include-svg-file[src=...,height=...,[density=...]{}]}.
This loads and parses an SVG file and attempts to render it in the current
document with the given height and density (which defaults to 72 ppi). For
example, the command \code{\\include-svg-file[src=examples/packages/smiley.svg,\goodbreak{}height=12pt]}
produces the following:
\include-svg-file[src=examples/packages/smiley.svg,height=12pt]
The second is \code{\\svg-glyph}. When the current font is set to an SVG font,
SILE does not currently render the SVG glyphs automatically. This command is
intended to be used as a means of eventually implementing SVG fonts; it retrieves
the SVG glyph provided and renders it.
The rendering is done with our own SVG drawing library; it is currently
very minimal, only handling lines, curves, strokes and fills. For a fuller
implementation, consider using a \code{converters} registration to render
your SVG file to PDF and include it on the fly.
\end{document}]]
}
|
local svg = require("svg")
local pdf = require("justenoughlibtexpdf")
local parser = require("core/opentype-parser")
local pushSVG = function (string, desiredHeight, em, drop)
local figure, width, height = svg.svg_to_ps(string,em)
local scalefactor = 1
if desiredHeight then
scalefactor = desiredHeight / height
height = desiredHeight
width = width * scalefactor
end
scalefactor = scalefactor * em / 72
SILE.typesetter:pushHbox({
value = nil,
height = height,
width = width,
depth = 0,
outputYourself= function (self, typesetter)
pdf.add_content("q")
SILE.outputter.moveTo(typesetter.frame.state.cursorX, typesetter.frame.state.cursorY)
local x,y = SILE.outputter.cursor()
y = y - SILE.documentState.paperSize[2] + (drop and 0 or height)
pdf.add_content(scalefactor:tonumber() .." 0 0 "..-(scalefactor:tonumber()).." "..x.." "..(y:tonumber()).." cm")
pdf.add_content(figure)
pdf.add_content("Q")
typesetter.frame:advanceWritingDirection(self.width)
end
})
end
SILE.registerCommand("include-svg-file", function (options, _)
local fn = SU.required(options, "src", "filename")
local height = options.height and SU.cast("measurement", options.height):absolute() or nil
local density = options.density or 72
local fh = io.open(fn)
local inp = fh:read("*all")
pushSVG(inp, height, density)
end)
SILE.registerCommand("svg-glyph", function(_, content)
local fontoptions = SILE.font.loadDefaults({})
local items = SILE.shaper:shapeToken(content[1], fontoptions)
local face = SILE.shaper.getFace(fontoptions)
parser.parseFont(face)
if not face.font.svg then return SILE.process(content) end
for i = 1, #items do
local svg_data = parser.getSVG(face, items[i].gid)
if svg_data then pushSVG(svg_data, fontoptions.size, 72, true) end
end
end)
return {
documentation = [[\begin{document}
This experimental package provides two commands.
The first is \code{\\include-svg-file[src=...,height=...,[density=...]{}]}.
This loads and parses an SVG file and attempts to render it in the current
document with the given height and density (which defaults to 72 ppi). For
example, the command \code{\\include-svg-file[src=examples/packages/smiley.svg,\goodbreak{}height=12pt]}
produces the following:
\include-svg-file[src=examples/packages/smiley.svg,height=12pt]
The second is \code{\\svg-glyph}. When the current font is set to an SVG font,
SILE does not currently render the SVG glyphs automatically. This command is
intended to be used as a means of eventually implementing SVG fonts; it retrieves
the SVG glyph provided and renders it.
The rendering is done with our own SVG drawing library; it is currently
very minimal, only handling lines, curves, strokes and fills. For a fuller
implementation, consider using a \code{converters} registration to render
your SVG file to PDF and include it on the fly.
\end{document}]]
}
|
fix(packages): Fix measurement-to-number issue in SVG
|
fix(packages): Fix measurement-to-number issue in SVG
|
Lua
|
mit
|
alerque/sile,alerque/sile,alerque/sile,alerque/sile
|
92d9d9195418706e4abdd0eb7f36b79d93da1a11
|
lua/entities/gmod_wire_egp/lib/egplib/queuesystem.lua
|
lua/entities/gmod_wire_egp/lib/egplib/queuesystem.lua
|
--------------------------------------------------------
-- EGP Queue System
--------------------------------------------------------
local EGP = EGP
EGP.Queue = {}
function EGP:AddQueueObject( Ent, ply, Function, Object )
if (!self.Queue[ply]) then self.Queue[ply] = {} end
local n = #self.Queue[ply]
if (n > 0) then
local LastItem = self.Queue[ply][n]
if (LastItem.Ent == Ent and LastItem.Action == "Object") then
local found = false
for k,v in ipairs( LastItem.Args[1] ) do
if (v.index == Object.index) then
found = true
--self:EditObject( v, Object )
if (v.ID != Object.ID) then -- Not the same kind of object, create new
if (v.OnRemove) then v:OnRemove() end
local Obj = self:GetObjectByID( Object.ID )
self:EditObject( Obj, Object:DataStreamInfo() )
Obj.index = v.index
if (Obj.OnCreate) then Obj:OnCreate() end
LastItem.Args[1][k] = Obj
else -- Edit
self:EditObject( v, Object:DataStreamInfo() )
end
break
end
end
if (!found) then
LastItem.Args[1][#LastItem.Args[1]+1] = Object
end
else
self:AddQueue( Ent, ply, Function, "Object", { Object } )
end
else
self:AddQueue( Ent, ply, Function, "Object", { Object } )
end
end
function EGP:AddQueue( Ent, ply, Function, Action, ... )
if (!self.Queue[ply]) then self.Queue[ply] = {} end
local n = #self.Queue[ply]
if (n > 0) then
local LastItem = self.Queue[ply][n]
if (LastItem.Ent == Ent and LastItem.Action == Action) then -- Same item, no point in sending it again
return
end
end
self.Queue[ply][n+1] = { Action = Action, Function = Function, Ent = Ent, Args = {...} }
end
function EGP:InsertQueueObjects( Ent, ply, Function, Objects )
if (!self.Queue[ply]) then self.Queue[ply] = {} end
local n = #self.Queue[ply]
if (n > 0) then
local FirstItem = self.Queue[ply][1]
if (FirstItem.Ent == Ent and FirstItem.Action == "Object") then
local Args = FirstItem.Args
for k,v in ipairs( Objects ) do
table.insert( Args, v )
end
else
self:InsertQueue( Ent, ply, Function, "Object", Objects )
end
else
self:InsertQueue( Ent, ply, Function, "Object", Objects )
end
end
function EGP:InsertQueue( Ent, ply, Function, Action, ... )
if (!self.Queue[ply]) then self.Queue[ply] = {} end
table.insert( self.Queue[ply], 1, { Action = Action, Function = Function, Ent = Ent, Args = {...} } )
end
function EGP:GetNextItem( ply )
if (!self.Queue[ply]) then return false end
if (#self.Queue[ply] <= 0) then return false end
return table.remove( self.Queue[ply], 1 )
end
local AlreadyChecking = 0
function EGP:SendQueueItem( ply )
if (!ply or !ply:IsValid()) then self:StopQueueTimer() end
local NextAction = self:GetNextItem( ply )
if (NextAction == false) then
self:StopQueueTimer( ply )
else
local Func = NextAction.Function
local Ent = NextAction.Ent
local Args = NextAction.Args
if (Args and #Args>0) then
Func( Ent, ply, unpack(Args) )
else
Func( Ent, ply )
end
if (CurTime() != AlreadyChecking) then -- Had to use this hacky way of checking, because the E2 triggered 4 times for some strange reason. If anyone can figure out why, go ahead and tell me.
AlreadyChecking = CurTime()
-- Check if the queue has no more items for this screen
local Items = self:GetQueueItemsForScreen( ply, Ent )
if (Items and #Items == 0) then
EGP.RunByEGPQueue = 1
EGP.RunByEGPQueue_Ent = Ent
EGP.RunByEGPQueue_ply = ply
for k,v in ipairs( ents.FindByClass( "gmod_wire_expression2" ) ) do -- Find all E2s
local context = v.context
if (context) then
local owner = context.player
-- Check if friends, whether or not the E2 is already executing, and if the E2 wants to be triggered by the queue system regarding the screen in question.
if (E2Lib.isFriend( ply, owner ) and context.data and context.data.EGP and context.data.EGP.RunOnEGP and context.data.EGP.RunOnEGP[Ent] == true) then
v:Execute()
end
end
end
EGP.RunByEGPQueue_ply = nil
EGP.RunByEGPQueue_Ent = nil
EGP.RunByEGPQueue = nil
end
end
end
end
EGP.Queue.Timers = {} -- Table used to fix player leaving errors
function EGP:StartQueueTimer( ply )
local TimerName = "EGP_Queue_"..ply:UniqueID()
if (!timer.IsTimer(TimerName)) then
self.Queue.Timers[#self.Queue.Timers+1] = { ply, ply:UniqueID() } -- Fix for players who leave while their queue is sending
timer.Create( TimerName, 1, 0, function( ply )
self:SendQueueItem( ply )
end, ply)
end
end
function EGP:StopQueueTimer( ply )
-- If a player left the server while their queue was sending
if (!ply or !ply:IsValid()) then -- If the argument is invalid
local removetable = {}
for k,v in ipairs( self.Queue.Timers ) do -- Loop through all timers
if (!v[1] or !v[1]:IsValid()) then -- Check if the player no longer exists
local TimerName = "EGP_Queue_"..v[2]
if (timer.IsTimer( TimerName )) then
timer.Destroy( TimerName ) -- Stop the timer
end
removetable[#removetable+1] = k -- Add to remove table
end
end
for k,v in ipairs( removetable ) do table.remove( self.Queue.Timers, v ) end -- Remove all stopped timers from the table
else -- If the player is still here, go ahead as usual
local TimerName = "EGP_Queue_"..ply:UniqueID()
if (timer.IsTimer( TimerName )) then
timer.Destroy( TimerName )
for k,v in ipairs( self.Queue.Timers ) do
if (v[1] == ply) then
table.remove( self.Queue.Timers, k )
break
end
end
end
end
end
function EGP:GetQueueItemsForScreen( ply, Ent )
if (!self.Queue[ply]) then return {} end
local ret = {}
for k,v in ipairs( self.Queue[ply] ) do
if (v.Ent == Ent) then
table.insert( ret, v )
end
end
return ret
end
|
--------------------------------------------------------
-- EGP Queue System
--------------------------------------------------------
local EGP = EGP
EGP.Queue = {}
function EGP:AddQueueObject( Ent, ply, Function, Object )
if (!self.Queue[ply]) then self.Queue[ply] = {} end
local n = #self.Queue[ply]
if (n > 0) then
local LastItem = self.Queue[ply][n]
if (LastItem.Ent == Ent and LastItem.Action == "Object") then
local found = false
for k,v in ipairs( LastItem.Args[1] ) do
if (v.index == Object.index) then
found = true
--self:EditObject( v, Object )
if (Object.remove) then -- The object has been removed
table.remove( LastItem.Args[1], k )
elseif (v.ID != Object.ID) then -- Not the same kind of object, create new
if (v.OnRemove) then v:OnRemove() end
local Obj = self:GetObjectByID( Object.ID )
self:EditObject( Obj, Object:DataStreamInfo() )
Obj.index = v.index
if (Obj.OnCreate) then Obj:OnCreate() end
LastItem.Args[1][k] = Obj
else -- Edit
self:EditObject( v, Object:DataStreamInfo() )
end
break
end
end
if (!found) then
LastItem.Args[1][#LastItem.Args[1]+1] = Object
end
else
self:AddQueue( Ent, ply, Function, "Object", { Object } )
end
else
self:AddQueue( Ent, ply, Function, "Object", { Object } )
end
end
function EGP:AddQueue( Ent, ply, Function, Action, ... )
if (!self.Queue[ply]) then self.Queue[ply] = {} end
local n = #self.Queue[ply]
if (n > 0) then
local LastItem = self.Queue[ply][n]
if (LastItem.Ent == Ent and LastItem.Action == Action) then -- Same item, no point in sending it again
return
end
end
self.Queue[ply][n+1] = { Action = Action, Function = Function, Ent = Ent, Args = {...} }
end
function EGP:InsertQueueObjects( Ent, ply, Function, Objects )
if (!self.Queue[ply]) then self.Queue[ply] = {} end
local n = #self.Queue[ply]
if (n > 0) then
local FirstItem = self.Queue[ply][1]
if (FirstItem.Ent == Ent and FirstItem.Action == "Object") then
local Args = FirstItem.Args
for k,v in ipairs( Objects ) do
table.insert( Args, v )
end
else
self:InsertQueue( Ent, ply, Function, "Object", Objects )
end
else
self:InsertQueue( Ent, ply, Function, "Object", Objects )
end
end
function EGP:InsertQueue( Ent, ply, Function, Action, ... )
if (!self.Queue[ply]) then self.Queue[ply] = {} end
table.insert( self.Queue[ply], 1, { Action = Action, Function = Function, Ent = Ent, Args = {...} } )
end
function EGP:GetNextItem( ply )
if (!self.Queue[ply]) then return false end
if (#self.Queue[ply] <= 0) then return false end
return table.remove( self.Queue[ply], 1 )
end
local AlreadyChecking = 0
function EGP:SendQueueItem( ply )
if (!ply or !ply:IsValid()) then self:StopQueueTimer() end
local NextAction = self:GetNextItem( ply )
if (NextAction == false) then
self:StopQueueTimer( ply )
else
local Func = NextAction.Function
local Ent = NextAction.Ent
local Args = NextAction.Args
if (Args and #Args>0) then
Func( Ent, ply, unpack(Args) )
else
Func( Ent, ply )
end
if (CurTime() != AlreadyChecking) then -- Had to use this hacky way of checking, because the E2 triggered 4 times for some strange reason. If anyone can figure out why, go ahead and tell me.
AlreadyChecking = CurTime()
-- Check if the queue has no more items for this screen
local Items = self:GetQueueItemsForScreen( ply, Ent )
if (Items and #Items == 0) then
EGP.RunByEGPQueue = 1
EGP.RunByEGPQueue_Ent = Ent
EGP.RunByEGPQueue_ply = ply
for k,v in ipairs( ents.FindByClass( "gmod_wire_expression2" ) ) do -- Find all E2s
local context = v.context
if (context) then
local owner = context.player
-- Check if friends, whether or not the E2 is already executing, and if the E2 wants to be triggered by the queue system regarding the screen in question.
if (E2Lib.isFriend( ply, owner ) and context.data and context.data.EGP and context.data.EGP.RunOnEGP and context.data.EGP.RunOnEGP[Ent] == true) then
v:Execute()
end
end
end
EGP.RunByEGPQueue_ply = nil
EGP.RunByEGPQueue_Ent = nil
EGP.RunByEGPQueue = nil
end
end
end
end
EGP.Queue.Timers = {} -- Table used to fix player leaving errors
function EGP:StartQueueTimer( ply )
local TimerName = "EGP_Queue_"..ply:UniqueID()
if (!timer.IsTimer(TimerName)) then
self.Queue.Timers[#self.Queue.Timers+1] = { ply, ply:UniqueID() } -- Fix for players who leave while their queue is sending
timer.Create( TimerName, 1, 0, function( ply )
self:SendQueueItem( ply )
end, ply)
end
end
function EGP:StopQueueTimer( ply )
-- If a player left the server while their queue was sending
if (!ply or !ply:IsValid()) then -- If the argument is invalid
local removetable = {}
for k,v in ipairs( self.Queue.Timers ) do -- Loop through all timers
if (!v[1] or !v[1]:IsValid()) then -- Check if the player no longer exists
local TimerName = "EGP_Queue_"..v[2]
if (timer.IsTimer( TimerName )) then
timer.Destroy( TimerName ) -- Stop the timer
end
removetable[#removetable+1] = k -- Add to remove table
end
end
for k,v in ipairs( removetable ) do table.remove( self.Queue.Timers, v ) end -- Remove all stopped timers from the table
else -- If the player is still here, go ahead as usual
local TimerName = "EGP_Queue_"..ply:UniqueID()
if (timer.IsTimer( TimerName )) then
timer.Destroy( TimerName )
for k,v in ipairs( self.Queue.Timers ) do
if (v[1] == ply) then
table.remove( self.Queue.Timers, k )
break
end
end
end
end
end
function EGP:GetQueueItemsForScreen( ply, Ent )
if (!self.Queue[ply]) then return {} end
local ret = {}
for k,v in ipairs( self.Queue[ply] ) do
if (v.Ent == Ent) then
table.insert( ret, v )
end
end
return ret
end
|
[EGP] Fixed an error with appeared if you removed and created an object too fast.
|
[EGP] Fixed an error with appeared if you removed and created an object too fast.
|
Lua
|
apache-2.0
|
plinkopenguin/wiremod,notcake/wire,bigdogmat/wire,Grocel/wire,dvdvideo1234/wire,mitterdoo/wire,wiremod/wire,mms92/wire,sammyt291/wire,rafradek/wire,immibis/wiremod,thegrb93/wire,CaptainPRICE/wire,Python1320/wire,garrysmodlua/wire,NezzKryptic/Wire
|
e92f12a6b7aa720133e73a0d2f20cb3afb21434e
|
MMOCoreORB/bin/scripts/loot/items/nightsister_bicep_r.lua
|
MMOCoreORB/bin/scripts/loot/items/nightsister_bicep_r.lua
|
--Automatically generated by SWGEmu Spawn Tool v0.12 loot editor.
nightsister_bicep_r = {
minimumLevel = 0,
maximumLevel = -1,
customObjectName = "",
directObjectTemplate = "object/tangible/wearables/armor/nightsister/armor_nightsister_bicep_r_s01.iff",
craftingValues = {
},
customizationStringNames = {},
customizationValues = {},
junkDealerTypeNeeded = JUNKGENERIC,
junkMinValue = 20,
junkMaxValue = 40
}
addLootItemTemplate("nightsister_bicep_r", nightsister_bicep_r)
|
--Automatically generated by SWGEmu Spawn Tool v0.12 loot editor.
nightsister_bicep_r = {
minimumLevel = 0,
maximumLevel = -1,
customObjectName = "Nightsister Melee Armguard",
directObjectTemplate = "object/tangible/wearables/armor/nightsister/armor_nightsister_bicep_r_s01.iff",
craftingValues = {
{"armor_rating",1,1,0},
{"armor_effectiveness",0,0,0},
{"kineticeffectiveness",0,0,0},
{"energyeffectiveness",0,0,0},
{"heateffectiveness",0,0,0},
{"coldeffectiveness",0,0,0},
{"acideffectiveness",0,0,0},
{"armor_integrity",20000,70000,0},
{"armor_health_encumbrance",25,15,0},
{"armor_action_encumbrance",22,13,0},
{"armor_mind_encumbrance",25,15,0},
},
customizationStringNames = {},
customizationValues = {},
junkDealerTypeNeeded = JUNKGENERIC,
junkMinValue = 20,
junkMaxValue = 40
}
addLootItemTemplate("nightsister_bicep_r", nightsister_bicep_r)
|
[fixed] NS Bracer displayname and stats
|
[fixed] NS Bracer displayname and stats
Change-Id: I3fce4fef6f4146ba98ba484bdd9667507b68fedc
|
Lua
|
agpl-3.0
|
Tatwi/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,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo
|
6c18897b20cd409bbf1599c2e57f50b2f8720987
|
examples/moonsniff/traffic-gen.lua
|
examples/moonsniff/traffic-gen.lua
|
--- Generates MoonSniff traffic, i.e. packets contain an identifier and a fixed bit pattern
--- Live mode and MSCAP mode require this type of traffic
local lm = require "libmoon"
local device = require "device"
local memory = require "memory"
local ts = require "timestamping"
local hist = require "histogram"
local timer = require "timer"
local log = require "log"
local stats = require "stats"
local bit = require "bit"
local limiter = require "software-ratecontrol"
local MS_TYPE = 0b01010101
local band = bit.band
function configure(parser)
parser:description("Generate traffic which can be used by moonsniff to establish latencies induced by a device under test.")
parser:argument("dev", "Devices to use."):args(2):convert(tonumber)
parser:option("-v --fix-packetrate", "Approximate send rate in pps."):convert(tonumber):default(10000):target('fixedPacketRate')
parser:option("-s --src-mac", "Overwrite source MAC address of every sent packet"):default(''):target("srcMAC")
parser:option("-d --dst-mac", "Overwrite destination MAC address of every sent packet"):default(''):target("dstMAC")
parser:option("-p --packets", "Send only the number of packets specified"):default(100000):convert(tonumber):target("numberOfPackets")
parser:option("-x --size", "Packet size in bytes."):convert(tonumber):default(100):target('packetSize')
return parser:parse()
end
function master(args)
args.dev[1] = device.config { port = args.dev[1], txQueues = 1 }
args.dev[2] = device.config { port = args.dev[2], rxQueues = 1 }
device.waitForLinks()
local dev0tx = args.dev[1]:getTxQueue(0)
local dev1rx = args.dev[2]:getRxQueue(0)
stats.startStatsTask { txDevices = { args.dev[1] }, rxDevices = { args.dev[2] } }
rateLimiter = limiter:new(dev0tx, "custom")
local sender0 = lm.startTask("generateTraffic", dev0tx, args, rateLimiter)
sender0:wait()
lm.stop()
lm.waitForTasks()
end
function generateTraffic(queue, args, rateLimiter)
log:info("Trying to enable rx timestamping of all packets, this isn't supported by most nics")
local pkt_id = 0
local numberOfPackets = args.numberOfPackets
local runtime = timer:new(args.time)
local mempool = memory.createMemPool(function(buf)
buf:getUdpPacket():fill {
pktLength = args.packetSize;
}
end)
local bufs = mempool:bufArray()
counter = 0
while lm.running() do
bufs:alloc(args.packetSize)
for i, buf in ipairs(bufs) do
if dstMAC ~= nil then
local pkt = buf:getEthernetPacket()
pkt.eth:setDst(dstMAC)
end
if srcMAC ~= nil then
local pkt = buf:getEthernetPacket()
pkt.eth:setSrc(srcMAC)
end
local pkt = buf:getUdpPacket()
-- for setters to work correctly, the number is not allowed to exceed 16 bit
pkt.ip4:setID(band(pkt_id, 0xFFFF))
pkt.payload.uint32[0] = pkt_id
pkt.payload.uint8[4] = MS_TYPE
pkt_id = pkt_id + 1
numberOfPackets = numberOfPackets - 1
delay = 10000000000 / args.fixedPacketRate / 8 - (args.packetSize + 4)
buf:setDelay(delay)
counter = counter + 1
if numberOfPackets <= 0 then
print(i)
rateLimiter:sendN(bufs, i)
lm.sleepMillis(1500)
print(counter)
lm.stop()
lm.sleepMillis(1500)
os.exit(0)
return
end
end
rateLimiter:send(bufs)
end
end
|
--- Generates MoonSniff traffic, i.e. packets contain an identifier and a fixed bit pattern
--- Live mode and MSCAP mode require this type of traffic
local lm = require "libmoon"
local device = require "device"
local memory = require "memory"
local ts = require "timestamping"
local hist = require "histogram"
local timer = require "timer"
local log = require "log"
local stats = require "stats"
local bit = require "bit"
local limiter = require "software-ratecontrol"
local MS_TYPE = 0b01010101
local band = bit.band
function configure(parser)
parser:description("Generate traffic which can be used by moonsniff to establish latencies induced by a device under test.")
parser:argument("dev", "Devices to use."):args(2):convert(tonumber)
parser:option("-v --fix-packetrate", "Approximate send rate in pps."):convert(tonumber):default(10000):target('fixedPacketRate')
parser:option("-s --src-mac", "Overwrite source MAC address of every sent packet"):default(''):target("srcMAC")
parser:option("-d --dst-mac", "Overwrite destination MAC address of every sent packet"):default(''):target("dstMAC")
parser:option("-p --packets", "Send only the number of packets specified"):default(100000):convert(tonumber):target("numberOfPackets")
parser:option("-x --size", "Packet size in bytes."):convert(tonumber):default(100):target('packetSize')
return parser:parse()
end
function master(args)
args.dev[1] = device.config { port = args.dev[1], txQueues = 1 }
args.dev[2] = device.config { port = args.dev[2], rxQueues = 1 }
device.waitForLinks()
local dev0tx = args.dev[1]:getTxQueue(0)
local dev1rx = args.dev[2]:getRxQueue(0)
stats.startStatsTask { txDevices = { args.dev[1] }, rxDevices = { args.dev[2] } }
dstmc = parseMacAddress(args.dstMAC, 0)
srcmc = parseMacAddress(args.srcMAC, 0)
rateLimiter = limiter:new(dev0tx, "custom")
local sender0 = lm.startTask("generateTraffic", dev0tx, args, rateLimiter, dstmc, srcmc)
sender0:wait()
lm.stop()
lm.waitForTasks()
end
function generateTraffic(queue, args, rateLimiter, dstMAC, srcMAC)
log:info("Trying to enable rx timestamping of all packets, this isn't supported by most nics")
local pkt_id = 0
local numberOfPackets = args.numberOfPackets
local runtime = timer:new(args.time)
local mempool = memory.createMemPool(function(buf)
buf:getUdpPacket():fill {
pktLength = args.packetSize;
}
end)
local bufs = mempool:bufArray()
counter = 0
while lm.running() do
bufs:alloc(args.packetSize)
for i, buf in ipairs(bufs) do
local pkt = buf:getUdpPacket()
if dstMAC ~= nil then
pkt.eth:setDst(dstMAC)
end
if srcMAC ~= nil then
pkt.eth:setSrc(srcMAC)
end
-- for setters to work correctly, the number is not allowed to exceed 16 bit
pkt.ip4:setID(band(pkt_id, 0xFFFF))
pkt.payload.uint32[0] = pkt_id
pkt.payload.uint8[4] = MS_TYPE
pkt_id = pkt_id + 1
numberOfPackets = numberOfPackets - 1
delay = 10000000000 / args.fixedPacketRate / 8 - (args.packetSize + 4)
buf:setDelay(delay)
counter = counter + 1
if numberOfPackets <= 0 then
print(i)
rateLimiter:sendN(bufs, i)
lm.sleepMillis(1500)
print(counter)
lm.stop()
lm.sleepMillis(1500)
os.exit(0)
return
end
end
rateLimiter:send(bufs)
end
end
|
fix mac address setting in moonsniff gen
|
fix mac address setting in moonsniff gen
|
Lua
|
mit
|
gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen
|
35cf4de6bede3204c62485f764c0449c8047f235
|
mod_mam/rsm.lib.lua
|
mod_mam/rsm.lib.lua
|
local stanza = require"util.stanza".stanza;
local tostring, tonumber = tostring, tonumber;
local type = type;
local pairs = pairs;
local xmlns_rsm = 'http://jabber.org/protocol/rsm';
local element_parsers;
do
local function xs_int(st)
return tonumber((st:get_text()));
end
local function xs_string(st)
return st:get_text();
end
element_parsers = {
after = xs_string;
before = function(st)
return st:get_text() or true;
end;
max = xs_int;
index = xs_int;
first = function(st)
return { index = tonumber(st.attr.index); st:get_text() };
end;
last = xs_string;
count = xs_int;
}
end
local element_generators = setmetatable({
first = function(st, data)
if type(data) == "table" then
st:tag("first", { index = data.index }):text(data[1]):up();
else
st:tag("first"):text(tostring(data)):up();
end
end;
}, {
__index = function(_, name)
return function(st, data)
st:tag(name):text(tostring(data)):up();
end
end;
});
local function parse(stanza)
local rs = {};
for tag in stanza:childtags() do
local name = tag.name;
local parser = name and element_parsers[name];
if parser then
rs[name] = parser(tag);
end
end
return rs;
end
local function generate(t)
local st = stanza("set", { xmlns = xmlns_rsm });
for k,v in pairs(t) do
if element_parsers[k] then
element_generators[k](st, v);
end
end
return st;
end
local function get(st)
local set = st:get_child("set", xmlns_rsm);
if set and #set.tags > 0 then
return parse(set);
else
module:log("debug", "RSM parse failed, %s", tostring(st));
end
end
return { parse = parse, generate = generate, get = get };
|
local stanza = require"util.stanza".stanza;
local tostring, tonumber = tostring, tonumber;
local type = type;
local pairs = pairs;
local xmlns_rsm = 'http://jabber.org/protocol/rsm';
local element_parsers;
do
local function xs_int(st)
return tonumber((st:get_text()));
end
local function xs_string(st)
return st:get_text();
end
element_parsers = {
after = xs_string;
before = function(st)
return st:get_text() or true;
end;
max = xs_int;
index = xs_int;
first = function(st)
return { index = tonumber(st.attr.index); st:get_text() };
end;
last = xs_string;
count = xs_int;
}
end
local element_generators = setmetatable({
first = function(st, data)
if type(data) == "table" then
st:tag("first", { index = data.index }):text(data[1]):up();
else
st:tag("first"):text(tostring(data)):up();
end
end;
}, {
__index = function(_, name)
return function(st, data)
st:tag(name):text(tostring(data)):up();
end
end;
});
local function parse(stanza)
local rs = {};
for tag in stanza:childtags() do
local name = tag.name;
local parser = name and element_parsers[name];
if parser then
rs[name] = parser(tag);
end
end
return rs;
end
local function generate(t)
local st = stanza("set", { xmlns = xmlns_rsm });
for k,v in pairs(t) do
if element_parsers[k] then
element_generators[k](st, v);
end
end
return st;
end
local function get(st)
local set = st:get_child("set", xmlns_rsm);
if set and #set.tags > 0 then
return parse(set);
end
end
return { parse = parse, generate = generate, get = get };
|
mod_mam/rsm.lib: Remove log statement (fixes usage in verse)
|
mod_mam/rsm.lib: Remove log statement (fixes usage in verse)
|
Lua
|
mit
|
stephen322/prosody-modules,1st8/prosody-modules,BurmistrovJ/prosody-modules,iamliqiang/prosody-modules,dhotson/prosody-modules,guilhem/prosody-modules,softer/prosody-modules,vince06fr/prosody-modules,obelisk21/prosody-modules,softer/prosody-modules,BurmistrovJ/prosody-modules,brahmi2/prosody-modules,vfedoroff/prosody-modules,mmusial/prosody-modules,amenophis1er/prosody-modules,BurmistrovJ/prosody-modules,dhotson/prosody-modules,crunchuser/prosody-modules,NSAKEY/prosody-modules,heysion/prosody-modules,apung/prosody-modules,either1/prosody-modules,NSAKEY/prosody-modules,guilhem/prosody-modules,apung/prosody-modules,LanceJenkinZA/prosody-modules,syntafin/prosody-modules,olax/prosody-modules,stephen322/prosody-modules,prosody-modules/import,jkprg/prosody-modules,apung/prosody-modules,mardraze/prosody-modules,guilhem/prosody-modules,heysion/prosody-modules,prosody-modules/import,syntafin/prosody-modules,drdownload/prosody-modules,stephen322/prosody-modules,dhotson/prosody-modules,syntafin/prosody-modules,mardraze/prosody-modules,Craige/prosody-modules,1st8/prosody-modules,iamliqiang/prosody-modules,prosody-modules/import,obelisk21/prosody-modules,LanceJenkinZA/prosody-modules,obelisk21/prosody-modules,jkprg/prosody-modules,crunchuser/prosody-modules,crunchuser/prosody-modules,iamliqiang/prosody-modules,heysion/prosody-modules,mmusial/prosody-modules,softer/prosody-modules,vince06fr/prosody-modules,LanceJenkinZA/prosody-modules,NSAKEY/prosody-modules,mmusial/prosody-modules,mardraze/prosody-modules,brahmi2/prosody-modules,asdofindia/prosody-modules,softer/prosody-modules,drdownload/prosody-modules,either1/prosody-modules,obelisk21/prosody-modules,NSAKEY/prosody-modules,mmusial/prosody-modules,crunchuser/prosody-modules,cryptotoad/prosody-modules,guilhem/prosody-modules,either1/prosody-modules,Craige/prosody-modules,amenophis1er/prosody-modules,olax/prosody-modules,olax/prosody-modules,jkprg/prosody-modules,olax/prosody-modules,brahmi2/prosody-modules,BurmistrovJ/prosody-modules,joewalker/prosody-modules,mardraze/prosody-modules,apung/prosody-modules,vfedoroff/prosody-modules,asdofindia/prosody-modules,iamliqiang/prosody-modules,BurmistrovJ/prosody-modules,drdownload/prosody-modules,stephen322/prosody-modules,mmusial/prosody-modules,Craige/prosody-modules,Craige/prosody-modules,NSAKEY/prosody-modules,drdownload/prosody-modules,heysion/prosody-modules,drdownload/prosody-modules,vfedoroff/prosody-modules,brahmi2/prosody-modules,joewalker/prosody-modules,1st8/prosody-modules,LanceJenkinZA/prosody-modules,joewalker/prosody-modules,Craige/prosody-modules,cryptotoad/prosody-modules,brahmi2/prosody-modules,olax/prosody-modules,vince06fr/prosody-modules,jkprg/prosody-modules,softer/prosody-modules,amenophis1er/prosody-modules,prosody-modules/import,syntafin/prosody-modules,amenophis1er/prosody-modules,mardraze/prosody-modules,iamliqiang/prosody-modules,cryptotoad/prosody-modules,vince06fr/prosody-modules,joewalker/prosody-modules,syntafin/prosody-modules,cryptotoad/prosody-modules,asdofindia/prosody-modules,crunchuser/prosody-modules,stephen322/prosody-modules,vince06fr/prosody-modules,asdofindia/prosody-modules,joewalker/prosody-modules,jkprg/prosody-modules,LanceJenkinZA/prosody-modules,either1/prosody-modules,vfedoroff/prosody-modules,cryptotoad/prosody-modules,guilhem/prosody-modules,heysion/prosody-modules,dhotson/prosody-modules,1st8/prosody-modules,1st8/prosody-modules,asdofindia/prosody-modules,vfedoroff/prosody-modules,apung/prosody-modules,obelisk21/prosody-modules,prosody-modules/import,either1/prosody-modules,dhotson/prosody-modules,amenophis1er/prosody-modules
|
fc50621f0bcc4e1bfda47f00126bced78132151e
|
share/lua/playlist/dailymotion.lua
|
share/lua/playlist/dailymotion.lua
|
--[[
Translate Daily Motion video webpages URLs to the corresponding
FLV URL.
$Id$
Copyright © 2007-2011 the VideoLAN team
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
function get_prefres()
local prefres = -1
if vlc.var and vlc.var.inherit then
prefres = vlc.var.inherit(nil, "preferred-resolution")
if prefres == nil then
prefres = -1
end
end
return prefres
end
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "dailymotion." )
and string.match( vlc.peek( 2048 ), "<!DOCTYPE.*video_type" )
end
function find( haystack, needle )
local _,_,ret = string.find( haystack, needle )
return ret
end
-- Parse function.
function parse()
prefres = get_prefres()
while true
do
line = vlc.readline()
if not line then
break
end
if string.match( line, "\"sequence\"")
then
line = vlc.strings.decode_uri(line):gsub("\\/", "/")
arturl = find( line, "\"videoPreviewURL\":\"([^\"]*)\"")
name = find( line, "\"videoTitle\":\"([^\"]*)\"")
if name then
name = string.gsub( name, "+", " " )
end
description = find( line, "\"videoDescription\":\"([^\"]*)\"")
if description then
description = string.gsub( description, "+", " " )
end
for _,param in ipairs({ "hd1080URL", "hd720URL", "hqURL", "sdURL" }) do
path = string.match( line, "\""..param.."\":\"([^\"]*)\"" )
if path then
if prefres < 0 then
break
end
height = string.match( path, "/cdn/%w+%-%d+x(%d+)/video/" )
if not height then
height = string.match( param, "(%d+)" )
end
if not height or tonumber(height) <= prefres then
break
end
end
end
if not path then
break
end
return { { path = path; name = name; description = description; url = vlc.path; arturl = arturl } }
end
end
vlc.msg.err("Couldn't extract the video URL from dailymotion")
return { }
end
|
--[[
Translate Daily Motion video webpages URLs to the corresponding
FLV URL.
$Id$
Copyright © 2007-2011 the VideoLAN team
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
function get_prefres()
local prefres = -1
if vlc.var and vlc.var.inherit then
prefres = vlc.var.inherit(nil, "preferred-resolution")
if prefres == nil then
prefres = -1
end
end
return prefres
end
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "www.dailymotion.com/video" )
end
function find( haystack, needle )
local _,_,ret = string.find( haystack, needle )
return ret
end
-- Parse function.
function parse()
prefres = get_prefres()
while true
do
line = vlc.readline()
if not line then
break
end
if string.match( line, "sequence=")
then
line = vlc.strings.decode_uri(line):gsub("\\/", "/")
arturl = find( line, "\"videoPreviewURL\":\"([^\"]*)\"")
name = find( line, "\"videoTitle\":\"([^\"]*)\"")
if name then
name = string.gsub( name, "+", " " )
end
description = find( line, "\"videoDescription\":\"([^\"]*)\"")
if description then
description = string.gsub( description, "+", " " )
end
for _,param in ipairs({ "hd1080URL", "hd720URL", "hqURL", "sdURL", "video_url" }) do
path = string.match( line, "\""..param.."\":\"([^\"]*)\"" )
if path then
path = vlc.strings.decode_uri(path)
if prefres < 0 then
break
end
height = string.match( path, "/cdn/%w+%-%d+x(%d+)/video/" )
if not height then
height = string.match( param, "(%d+)" )
end
if not height or tonumber(height) <= prefres then
break
end
end
end
if not path then
break
end
return { { path = path; name = name; description = description; url = vlc.path; arturl = arturl } }
end
end
vlc.msg.err("Couldn't extract the video URL from dailymotion")
return { }
end
|
dailymotion.lua: fix page parsing
|
dailymotion.lua: fix page parsing
(cherry picked from commit 2fe62d4008bef9698641a5453dea70db80a8803f)
Signed-off-by: Jean-Baptiste Kempf <[email protected]>
|
Lua
|
lgpl-2.1
|
vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1
|
611a5311b69b0633ed6dfc7202244f42f93a7d33
|
frontend/device/android/powerd.lua
|
frontend/device/android/powerd.lua
|
local BasePowerD = require("device/generic/powerd")
local _, android = pcall(require, "android")
local AndroidPowerD = BasePowerD:new{
fl_min = 0,
fl_max = 100,
}
-- Let the footer know of the change
local function broadcastLightChanges()
if package.loaded["ui/uimanager"] ~= nil then
local Event = require("ui/event")
local UIManager = require("ui/uimanager")
UIManager:broadcastEvent(Event:new("FrontlightStateChanged"))
end
end
function AndroidPowerD:frontlightIntensityHW()
return math.floor(android.getScreenBrightness() / self.bright_diff * self.fl_max)
end
function AndroidPowerD:setIntensityHW(intensity)
-- if frontlight switch was toggled of, turn it on
android.enableFrontlightSwitch()
self.fl_intensity = intensity
android.setScreenBrightness(math.floor(intensity * self.bright_diff / self.fl_max))
end
function AndroidPowerD:init()
local min_bright = android.getScreenMinBrightness()
self.bright_diff = android.getScreenMaxBrightness() - min_bright
-- if necessary scale fl_min:
-- do not use fl_min==0 if getScreenMinBrightness!=0,
-- because intenstiy==0 would mean to use system intensity
if min_bright ~= self.fl_min then
self.fl_min = math.ceil(min_bright * self.bright_diff / self.fl_max)
end
if self.device:hasNaturalLight() then
self.fl_warmth_min = android.getScreenMinWarmth()
self.fl_warmth_max = android.getScreenMaxWarmth()
self.warm_diff = self.fl_warmth_max - self.fl_warmth_min
self.fl_warmth = self:getWarmth()
end
end
function AndroidPowerD:setWarmth(warmth)
self.fl_warmth = warmth
android.setScreenWarmth(warmth / self.warm_diff)
end
function AndroidPowerD:getWarmth()
return android.getScreenWarmth() * self.warm_diff
end
function AndroidPowerD:getCapacityHW()
return android.getBatteryLevel()
end
function AndroidPowerD:isChargingHW()
return android.isCharging()
end
function AndroidPowerD:turnOffFrontlightHW()
if not self:isFrontlightOnHW() then
return
end
android.setScreenBrightness(self.fl_min)
self.is_fl_on = false
broadcastLightChanges()
end
function AndroidPowerD:turnOnFrontlightHW()
if self:isFrontlightOn() and self:isFrontlightOnHW() then
return
end
-- on devices with a software frontlight switch (e.g Tolinos), enable it
android.enableFrontlightSwitch()
android.setScreenBrightness(math.floor(self.fl_intensity * self.bright_diff / self.fl_max))
self.is_fl_on = true
broadcastLightChanges()
end
return AndroidPowerD
|
local BasePowerD = require("device/generic/powerd")
local _, android = pcall(require, "android")
local AndroidPowerD = BasePowerD:new{
fl_min = 0,
fl_max = 100,
}
-- Let the footer know of the change
local function broadcastLightChanges()
if package.loaded["ui/uimanager"] ~= nil then
local Event = require("ui/event")
local UIManager = require("ui/uimanager")
UIManager:broadcastEvent(Event:new("FrontlightStateChanged"))
end
end
function AndroidPowerD:frontlightIntensityHW()
return math.floor(android.getScreenBrightness() / self.bright_diff * self.fl_max)
end
function AndroidPowerD:setIntensityHW(intensity)
-- if frontlight switch was toggled of, turn it on
android.enableFrontlightSwitch()
self.fl_intensity = intensity
android.setScreenBrightness(math.floor(intensity * self.bright_diff / self.fl_max))
end
function AndroidPowerD:init()
local min_bright = android.getScreenMinBrightness()
self.bright_diff = android.getScreenMaxBrightness() - min_bright
-- if necessary scale fl_min:
-- do not use fl_min==0 if getScreenMinBrightness!=0,
-- because intenstiy==0 would mean to use system intensity
if min_bright ~= self.fl_min then
self.fl_min = math.ceil(min_bright * self.bright_diff / self.fl_max)
end
if self.device:hasNaturalLight() then
self.fl_warmth_min = android.getScreenMinWarmth()
self.fl_warmth_max = android.getScreenMaxWarmth()
self.warm_diff = self.fl_warmth_max - self.fl_warmth_min
self.fl_warmth = self:getWarmth()
end
end
function AndroidPowerD:setWarmth(warmth)
self.fl_warmth = warmth
local new_warmth = math.floor(warmth * self.fl_warmth_max / 100)
android.setScreenWarmth(new_warmth)
end
function AndroidPowerD:getWarmth()
return android.getScreenWarmth() * self.warm_diff
end
function AndroidPowerD:getCapacityHW()
return android.getBatteryLevel()
end
function AndroidPowerD:isChargingHW()
return android.isCharging()
end
function AndroidPowerD:turnOffFrontlightHW()
if not self:isFrontlightOnHW() then
return
end
android.setScreenBrightness(self.fl_min)
self.is_fl_on = false
broadcastLightChanges()
end
function AndroidPowerD:turnOnFrontlightHW()
if self:isFrontlightOn() and self:isFrontlightOnHW() then
return
end
-- on devices with a software frontlight switch (e.g Tolinos), enable it
android.enableFrontlightSwitch()
android.setScreenBrightness(math.floor(self.fl_intensity * self.bright_diff / self.fl_max))
self.is_fl_on = true
broadcastLightChanges()
end
return AndroidPowerD
|
Fix warmth settings on some android devices (#8104)
|
Fix warmth settings on some android devices (#8104)
|
Lua
|
agpl-3.0
|
Frenzie/koreader,poire-z/koreader,Frenzie/koreader,NiLuJe/koreader,NiLuJe/koreader,koreader/koreader,poire-z/koreader,koreader/koreader
|
69b6ca0bf6a188e4905542ed933afb4ba9ecb9e1
|
spec/alignment/goodSlices_spec.lua
|
spec/alignment/goodSlices_spec.lua
|
-- lua-npge, Nucleotide PanGenome explorer (Lua module)
-- Copyright (C) 2014-2015 Boris Nagaev
-- See the LICENSE file for terms of use.
describe("npge.alignment.goodSlices", function()
it("finds good slices", function()
local goodSlices = require 'npge.alignment.goodSlices'
assert.same(goodSlices({true, false, true, true, true,
false, false, false, false, true, true, true},
3, 1, 0.6), {
{start = 0, length = 5},
{start = 9, length = 3},
})
assert.same(goodSlices({true, false, true, true, true,
false, false, false, false, true, true, true, true},
3, 2, 0.6), {
{start = 9, length = 4},
{start = 2, length = 3},
})
end)
local function bools(row)
row = row:gsub('%s', '')
local array = {}
for i = 1, #row do
table.insert(array, row:sub(i, i) ~= '-')
end
return array
end
it("finds good slices (rows)", function()
local goodSlices = require 'npge.alignment.goodSlices'
assert.same(goodSlices(bools("+-+++----++++"),
3, 1, 0.6), {
{start = 0, length = 5},
{start = 9, length = 4},
})
assert.same(goodSlices(bools("+-+++----++++"),
3, 2, 0.6), {
{start = 9, length = 4},
{start = 2, length = 3},
})
end)
it("finds good slices (long rows)", function()
local goodSlices = require 'npge.alignment.goodSlices'
local row = [[
++++++++++++++++++++-+++++++++++++++++++++++++++-++-++++--+-
+++++++++++-++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++-+-+++++++++-++--+++++-++++++-+--+++++++
+++++-++++++++-++++++++++++++-++++++++-++++++++++++++++-++++
+++++++-+++++++++++++++++-+++-+++++++++++-++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++-+++++-++++++++++++
+++++++++++++-++++++-++++++--+++++--++++++++++++++++++++--++
+++++++++-+++++++++++++++++++++-+++++++++++++-+++++++++++--+
++++--++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++-+++++++-++++++++-+++++++--++++++++++++++++++++++++++++
++++++++++++++++++++++-+++-+-+++++++++++++++++++++++++++++++
+++-+++++++-++++++++-+++++-++++++++-+++++++++++-+++++-++-+++
+++++++++++++-++++++++++++++++-+++++++++-+++++++++---++++++-
+++--+++-++++++-++++-++++++-+++++-++++++++++-+++++++++++++-+
++++++-+++-+++++--+++++++++++++++++-+++++++++++++-++++++++++
+++++++++++++++++++++++++-+++++-+++++++++++++++++++-++++++++
++++++++++++-++++++-++++++++++++++++++++]]
assert.same(goodSlices(bools(row), 100, 3, 0.9), {
{start = 396, length = 317},
{start = 157, length = 237},
{start = 801, length = 199},
{start = 0, length = 152},
})
end)
end)
|
-- lua-npge, Nucleotide PanGenome explorer (Lua module)
-- Copyright (C) 2014-2015 Boris Nagaev
-- See the LICENSE file for terms of use.
describe("npge.alignment.goodSlices", function()
it("finds good slices", function()
local goodSlices = require 'npge.alignment.goodSlices'
assert.same(goodSlices({true, false, true, true, true,
false, false, false, false, true, true, true},
3, 1, 0.6), {
{start = 0, length = 5},
{start = 9, length = 3},
})
assert.same(goodSlices({true, false, true, true, true,
false, false, false, false, true, true, true, true},
3, 2, 0.6), {
{start = 9, length = 4},
{start = 2, length = 3},
})
end)
local function bools(row)
row = row:gsub('%s', '')
local array = {}
for i = 1, #row do
table.insert(array, row:sub(i, i) ~= '-')
end
return array
end
it("finds good slices (rows)", function()
local goodSlices = require 'npge.alignment.goodSlices'
assert.same(goodSlices(bools("+-+++----++++"),
3, 1, 0.6), {
{start = 0, length = 5},
{start = 9, length = 4},
})
assert.same(goodSlices(bools("+-+++----++++"),
3, 2, 0.6), {
{start = 9, length = 4},
{start = 2, length = 3},
})
end)
pending("finds good slices (local is good, #global is bad)",
function()
local goodSlices = require 'npge.alignment.goodSlices'
assert.same(goodSlices(bools("++-+++++++++-+"),
10, 1, 0.9), {
{start = 0, length = 12},
-- not {start = 0, length = 14}
})
end)
it("finds good slices (long rows)", function()
local goodSlices = require 'npge.alignment.goodSlices'
local row = [[
++++++++++++++++++++-+++++++++++++++++++++++++++-++-++++--+-
+++++++++++-++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++-+-+++++++++-++--+++++-++++++-+--+++++++
+++++-++++++++-++++++++++++++-++++++++-++++++++++++++++-++++
+++++++-+++++++++++++++++-+++-+++++++++++-++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++-+++++-++++++++++++
+++++++++++++-++++++-++++++--+++++--++++++++++++++++++++--++
+++++++++-+++++++++++++++++++++-+++++++++++++-+++++++++++--+
++++--++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++-+++++++-++++++++-+++++++--++++++++++++++++++++++++++++
++++++++++++++++++++++-+++-+-+++++++++++++++++++++++++++++++
+++-+++++++-++++++++-+++++-++++++++-+++++++++++-+++++-++-+++
+++++++++++++-++++++++++++++++-+++++++++-+++++++++---++++++-
+++--+++-++++++-++++-++++++-+++++-++++++++++-+++++++++++++-+
++++++-+++-+++++--+++++++++++++++++-+++++++++++++-++++++++++
+++++++++++++++++++++++++-+++++-+++++++++++++++++++-++++++++
++++++++++++-++++++-++++++++++++++++++++]]
assert.same(goodSlices(bools(row), 100, 3, 0.9), {
{start = 396, length = 317},
{start = 157, length = 237},
{start = 801, length = 199},
{start = 0, length = 152},
})
end)
end)
|
add shorter example of bug in goodSlices
|
add shorter example of bug in goodSlices
|
Lua
|
mit
|
npge/lua-npge,starius/lua-npge,starius/lua-npge,starius/lua-npge,npge/lua-npge,npge/lua-npge
|
06f083be701c4aea3c9b8a09c07a635767730e8b
|
mod_mam/rsm.lib.lua
|
mod_mam/rsm.lib.lua
|
local stanza = require"util.stanza".stanza;
local tostring, tonumber = tostring, tonumber;
local type = type;
local pairs = pairs;
local xmlns_rsm = 'http://jabber.org/protocol/rsm';
local element_parsers;
do
local function xs_int(st)
return tonumber((st:get_text()));
end
local function xs_string(st)
return st:get_text();
end
element_parsers = {
after = xs_string;
before = function(st)
return st:get_text() or true;
end;
max = xs_int;
index = xs_int;
first = function(st)
return { index = tonumber(st.attr.index); st:get_text() };
end;
last = xs_string;
count = xs_int;
}
end
local element_generators = setmetatable({
first = function(st, data)
if type(data) == "table" then
st:tag("first", { index = data.index }):text(data[1]):up();
else
st:tag("first"):text(tostring(data)):up();
end
end;
before = function(st, data)
if data == true then
st:tag("before"):up();
else
st:tag("before"):text(tostring(data)):up();
end
end
}, {
__index = function(_, name)
return function(st, data)
st:tag(name):text(tostring(data)):up();
end
end;
});
local function parse(stanza)
local rs = {};
for tag in stanza:childtags() do
local name = tag.name;
local parser = name and element_parsers[name];
if parser then
rs[name] = parser(tag);
end
end
return rs;
end
local function generate(t)
local st = stanza("set", { xmlns = xmlns_rsm });
for k,v in pairs(t) do
if element_parsers[k] then
element_generators[k](st, v);
end
end
return st;
end
local function get(st)
local set = st:get_child("set", xmlns_rsm);
if set and #set.tags > 0 then
return parse(set);
end
end
return { parse = parse, generate = generate, get = get };
|
local stanza = require"util.stanza".stanza;
local tostring, tonumber = tostring, tonumber;
local type = type;
local pairs = pairs;
local xmlns_rsm = 'http://jabber.org/protocol/rsm';
local element_parsers;
do
local function xs_int(st)
return tonumber((st:get_text()));
end
local function xs_string(st)
return st:get_text();
end
element_parsers = {
after = xs_string;
before = function(st)
local text = st:get_text();
return text == "" or text;
end;
max = xs_int;
index = xs_int;
first = function(st)
return { index = tonumber(st.attr.index); st:get_text() };
end;
last = xs_string;
count = xs_int;
}
end
local element_generators = setmetatable({
first = function(st, data)
if type(data) == "table" then
st:tag("first", { index = data.index }):text(data[1]):up();
else
st:tag("first"):text(tostring(data)):up();
end
end;
before = function(st, data)
if data == true then
st:tag("before"):up();
else
st:tag("before"):text(tostring(data)):up();
end
end
}, {
__index = function(_, name)
return function(st, data)
st:tag(name):text(tostring(data)):up();
end
end;
});
local function parse(stanza)
local rs = {};
for tag in stanza:childtags() do
local name = tag.name;
local parser = name and element_parsers[name];
if parser then
rs[name] = parser(tag);
end
end
return rs;
end
local function generate(t)
local st = stanza("set", { xmlns = xmlns_rsm });
for k,v in pairs(t) do
if element_parsers[k] then
element_generators[k](st, v);
end
end
return st;
end
local function get(st)
local set = st:get_child("set", xmlns_rsm);
if set and #set.tags > 0 then
return parse(set);
end
end
return { parse = parse, generate = generate, get = get };
|
mod_mam/rsm.lib: Fix parsing of empty before tag
|
mod_mam/rsm.lib: Fix parsing of empty before tag
|
Lua
|
mit
|
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
|
3ee63626139ddc42a9954687db3bbcd3b6e9a540
|
devel/emotion-table.lua
|
devel/emotion-table.lua
|
-- Generate a wikitext table of emotions
VERSION = '1.0'
utils = require 'utils'
args = utils.processArgs({...}, utils.invert{'file', 'overwrite'})
f = nil
if args.file ~= nil then
if dfhack.filesystem.exists(args.file) and not args.overwrite then
qerror('File exists, -overwrite not specified')
end
f, err = io.open(args.file, 'w')
if f == nil then
qerror('Could not open file: ' .. err)
end
write = function(...) f:write(...) end
else
write = dfhack.print
end
write([[{| class="wikitable sortable"
|-
! ID !! Emotion !! Divider
]])
for id, emotion in ipairs(df.emotion_type) do
if emotion ~= nil and id >= 0 then
attrs = df.emotion_type.attrs[id]
if attrs.color >= 8 then
color = (attrs.color - 8) .. ':1'
else
color = attrs.color .. ':0'
end
write('|-\n')
write(('|| %i || {{DFtext|%s|%s}} || %i\n'):format(id, emotion, color, attrs.divider))
end
end
write('|}\n')
if f ~= nil then
f:close()
end
|
-- Generate a wikitext table of emotions
VERSION = '1.1'
utils = require 'utils'
args = utils.processArgs({...}, utils.invert{'file', 'overwrite'})
f = nil
if args.file ~= nil then
if dfhack.filesystem.exists(args.file) and not args.overwrite then
qerror('File exists, -overwrite not specified')
end
f, err = io.open(args.file, 'w')
if f == nil then
qerror('Could not open file: ' .. err)
end
write = function(...) f:write(...) end
else
write = dfhack.print
end
write([[{| class="wikitable sortable"
|-
! ID !! Emotion !! Strength
]])
for id, emotion in ipairs(df.emotion_type) do
if emotion ~= nil and id >= 0 then
attrs = df.emotion_type.attrs[id]
if attrs.color >= 8 then
color = (attrs.color - 8) .. ':1'
else
color = attrs.color .. ':0'
end
strength = attrs.divider
if strength ~= 0 then
strength = -8 / strength
if strength >= 0 then
strength = '+' .. strength
end
strength = tostring(strength)
end
emotion = emotion:gsub('[A-Z]', ' %1'):sub(2)
write('|-\n')
write(('| %i || {{DFtext|%s|%s}} || %s\n'):format(id, emotion, color, strength))
end
end
write('|}\n')
if f ~= nil then
f:close()
end
|
Update devel/emotion-table
|
Update devel/emotion-table
* divider -> strength
* Fix table markup
* Add spaces to multiple-word emotions
|
Lua
|
unlicense
|
lethosor/dfhack-scripts,PeridexisErrant/lethosor-scripts,DFHack/lethosor-scripts
|
e172926af5338435d14c722d56a48c5ecdd9e837
|
frontend/ui/widget/logindialog.lua
|
frontend/ui/widget/logindialog.lua
|
--[[--
This widget displays a login dialog with a username and password.
]]
local Blitbuffer = require("ffi/blitbuffer")
local CenterContainer = require("ui/widget/container/centercontainer")
local FrameContainer = require("ui/widget/container/framecontainer")
local Geom = require("ui/geometry")
local InputDialog = require("ui/widget/inputdialog")
local InputText = require("ui/widget/inputtext")
local Size = require("ui/size")
local UIManager = require("ui/uimanager")
local VerticalGroup = require("ui/widget/verticalgroup")
local _ = require("gettext")
local Screen = require("device").screen
local LoginDialog = InputDialog:extend{
username = "",
username_hint = "username",
password = "",
password_hint = "password",
}
function LoginDialog:init()
-- init title and buttons in base class
InputDialog.init(self)
self.input_username = InputText:new{
text = self.username,
hint = self.username_hint,
face = self.input_face,
width = self.width * 0.9,
focused = true,
scroll = false,
parent = self,
}
self.input_password = InputText:new{
text = self.password,
hint = self.password_hint,
face = self.input_face,
width = self.width * 0.9,
text_type = "password",
focused = false,
scroll = false,
parent = self,
}
self.dialog_frame = FrameContainer:new{
radius = Size.radius.window,
padding = 0,
margin = 0,
background = Blitbuffer.COLOR_WHITE,
VerticalGroup:new{
align = "left",
self.title_widget,
self.title_bar,
-- username input
CenterContainer:new{
dimen = Geom:new{
w = self.title_bar:getSize().w,
h = self.input_username:getSize().h,
},
self.input_username,
},
-- password input
CenterContainer:new{
dimen = Geom:new{
w = self.title_bar:getSize().w,
h = self.input_password:getSize().h,
},
self.input_password,
},
-- buttons
CenterContainer:new{
dimen = Geom:new{
w = self.title_bar:getSize().w,
h = self.button_table:getSize().h,
},
self.button_table,
}
}
}
self._input_widget = self.input_username
self[1] = CenterContainer:new{
dimen = Geom:new{
w = Screen:getWidth(),
h = Screen:getHeight() - self._input_widget:getKeyboardDimen().h,
},
self.dialog_frame,
}
end
function LoginDialog:getCredential()
local username = self.input_username:getText()
local password = self.input_password:getText()
return username, password
end
function LoginDialog:onSwitchFocus(inputbox)
-- unfocus current inputbox
self._input_widget:unfocus()
self._input_widget:onCloseKeyboard()
UIManager:close(self)
-- focus new inputbox
self._input_widget = inputbox
self._input_widget:focus()
self._input_widget:onShowKeyboard()
UIManager:show(self)
end
return LoginDialog
|
--[[--
This widget displays a login dialog with a username and password.
]]
local Blitbuffer = require("ffi/blitbuffer")
local CenterContainer = require("ui/widget/container/centercontainer")
local FrameContainer = require("ui/widget/container/framecontainer")
local Geom = require("ui/geometry")
local InputDialog = require("ui/widget/inputdialog")
local InputText = require("ui/widget/inputtext")
local Size = require("ui/size")
local UIManager = require("ui/uimanager")
local VerticalGroup = require("ui/widget/verticalgroup")
local _ = require("gettext")
local Screen = require("device").screen
local LoginDialog = InputDialog:extend{
username = "",
username_hint = "username",
password = "",
password_hint = "password",
}
function LoginDialog:init()
-- init title and buttons in base class
InputDialog.init(self)
self.input_username = InputText:new{
text = self.username,
hint = self.username_hint,
face = self.input_face,
width = self.width * 0.9,
focused = true,
scroll = false,
parent = self,
}
self.input_password = InputText:new{
text = self.password,
hint = self.password_hint,
face = self.input_face,
width = self.width * 0.9,
text_type = "password",
focused = false,
scroll = false,
parent = self,
}
self.dialog_frame = FrameContainer:new{
radius = Size.radius.window,
padding = 0,
margin = 0,
background = Blitbuffer.COLOR_WHITE,
VerticalGroup:new{
align = "left",
self.title_widget,
self.title_bar,
-- username input
CenterContainer:new{
dimen = Geom:new{
w = self.title_bar:getSize().w,
h = self.input_username:getSize().h,
},
self.input_username,
},
-- password input
CenterContainer:new{
dimen = Geom:new{
w = self.title_bar:getSize().w,
h = self.input_password:getSize().h,
},
self.input_password,
},
-- buttons
CenterContainer:new{
dimen = Geom:new{
w = self.title_bar:getSize().w,
h = self.button_table:getSize().h,
},
self.button_table,
}
}
}
self._input_widget = self.input_username
self[1] = CenterContainer:new{
dimen = Geom:new{
w = Screen:getWidth(),
h = Screen:getHeight() - self._input_widget:getKeyboardDimen().h,
},
self.dialog_frame,
}
end
function LoginDialog:getCredential()
local username = self.input_username:getText()
local password = self.input_password:getText()
return username, password
end
function LoginDialog:onSwitchFocus(inputbox)
-- unfocus current inputbox
self._input_widget:unfocus()
self._input_widget:onCloseKeyboard()
-- focus new inputbox
self._input_widget = inputbox
self._input_widget:focus()
self._input_widget:onShowKeyboard()
UIManager:setDirty(self, "ui")
end
return LoginDialog
|
LoginDialog: fix crash on focus switch (#5749)
|
LoginDialog: fix crash on focus switch (#5749)
|
Lua
|
agpl-3.0
|
koreader/koreader,NiLuJe/koreader,mwoz123/koreader,koreader/koreader,poire-z/koreader,Markismus/koreader,Frenzie/koreader,pazos/koreader,Frenzie/koreader,NiLuJe/koreader,mihailim/koreader,poire-z/koreader,Hzj-jie/koreader
|
0cad8af1d9c527e8b6c12f5d9571d86d8af98908
|
src/analytics/uvedelete.lua
|
src/analytics/uvedelete.lua
|
--
-- Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
--
local function sub_del(_values)
local lres = redis.call('hgetall',_values)
local iter = 1
while iter <= #lres do
local attr = lres[iter]
local val = lres[iter+1]
if string.byte(val,1) ~= 60 then
local descs = cjson.decode(val)
for k,desc in pairs(descs) do
if desc.href ~= nil then
redis.call('del',desc.href)
redis.log(redis.LOG_NOTICE,"Deleting for "..desc.href)
end
end
redis.call('hdel', _values, attr)
end
iter = iter + 2
end
end
local sm = ARGV[1]..":"..ARGV[2]..":"..ARGV[3]..":"..ARGV[4]
local typ = ARGV[5]
local key = ARGV[6]
local db = tonumber(ARGV[7])
local is_alarm = tonumber(ARGV[8])
local _del = KEYS[1]
local _values = KEYS[2]
local _uves = KEYS[3]
local _origins = KEYS[4]
local _table = KEYS[5]
local _deleted = KEYS[6]
redis.call('select',db)
if is_alarm == 1 then
redis.log(redis.LOG_NOTICE,"DelAlarm on "..sm.." for "..key)
else
local part = redis.call('hget',"KEY2PART:"..sm..":"..typ, key)
if part == false then
part = "NULL"
else
redis.call('hdel', "KEY2PART:"..sm..":"..typ, key)
redis.call('srem', "PART2KEY:"..part, sm..":"..typ..":"..key)
redis.log(redis.LOG_NOTICE,"DelUVE on "..sm.." for "..key.." part "..part)
end
end
sub_del(_values)
redis.call('rename', _values, _del)
redis.call('zrem', _uves, key)
redis.call('srem', _origins, sm..":"..typ)
redis.call('srem', _table, key..":"..sm..":"..typ)
redis.call('lpush',_deleted, _del)
return true
|
--
-- Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
--
local function sub_del(_values)
local lres = redis.call('hgetall',_values)
local iter = 1
while iter <= #lres do
local attr = lres[iter]
local val = lres[iter+1]
if string.byte(val,1) ~= 60 then
local descs = cjson.decode(val)
for k,desc in pairs(descs) do
if desc.href ~= nil then
redis.call('del',desc.href)
redis.log(redis.LOG_NOTICE,"Deleting for "..desc.href)
end
end
redis.call('hdel', _values, attr)
end
iter = iter + 2
end
end
local sm = ARGV[1]..":"..ARGV[2]..":"..ARGV[3]..":"..ARGV[4]
local typ = ARGV[5]
local key = ARGV[6]
local db = tonumber(ARGV[7])
local is_alarm = tonumber(ARGV[8])
local _del = KEYS[1]
local _values = KEYS[2]
local _uves = KEYS[3]
local _origins = KEYS[4]
local _table = KEYS[5]
local _deleted = KEYS[6]
redis.call('select',db)
if is_alarm == 1 then
redis.log(redis.LOG_NOTICE,"DelAlarm on "..sm.." for "..key)
else
local part = redis.call('hget',"KEY2PART:"..sm..":"..typ, key)
if part == false then
part = "NULL"
else
redis.call('hdel', "KEY2PART:"..sm..":"..typ, key)
redis.call('srem', "PART2KEY:"..part, sm..":"..typ..":"..key)
redis.log(redis.LOG_NOTICE,"DelUVE on "..sm.." for "..key.." part "..part)
end
end
sub_del(_values)
redis.call('zrem', _uves, key)
redis.call('srem', _origins, sm..":"..typ)
redis.call('srem', _table, key..":"..sm..":"..typ)
local lttt = redis.call('exists', _values)
if lttt == 1 then
redis.call('rename', _values, _del)
redis.call('lpush',_deleted, _del)
end
return true
|
When deleting a UVE, check if the VALUES hashset exists before enqueing it for post-processing
|
When deleting a UVE, check if the VALUES hashset exists before
enqueing it for post-processing
Change-Id: I7ae54fa707f820ee11cf6facaf38b445c69151f2
Closes-Bug: 1434670
|
Lua
|
apache-2.0
|
DreamLab/contrail-controller,reiaaoyama/contrail-controller,codilime/contrail-controller,eonpatapon/contrail-controller,hthompson6/contrail-controller,facetothefate/contrail-controller,tcpcloud/contrail-controller,eonpatapon/contrail-controller,reiaaoyama/contrail-controller,nischalsheth/contrail-controller,rombie/contrail-controller,rombie/contrail-controller,reiaaoyama/contrail-controller,DreamLab/contrail-controller,hthompson6/contrail-controller,hthompson6/contrail-controller,numansiddique/contrail-controller,numansiddique/contrail-controller,codilime/contrail-controller,eonpatapon/contrail-controller,sajuptpm/contrail-controller,vmahuli/contrail-controller,codilime/contrail-controller,tcpcloud/contrail-controller,vmahuli/contrail-controller,tcpcloud/contrail-controller,eonpatapon/contrail-controller,reiaaoyama/contrail-controller,reiaaoyama/contrail-controller,vmahuli/contrail-controller,DreamLab/contrail-controller,codilime/contrail-controller,eonpatapon/contrail-controller,nischalsheth/contrail-controller,eonpatapon/contrail-controller,nischalsheth/contrail-controller,facetothefate/contrail-controller,vpramo/contrail-controller,sajuptpm/contrail-controller,sajuptpm/contrail-controller,codilime/contrail-controller,tcpcloud/contrail-controller,hthompson6/contrail-controller,rombie/contrail-controller,facetothefate/contrail-controller,facetothefate/contrail-controller,vmahuli/contrail-controller,numansiddique/contrail-controller,eonpatapon/contrail-controller,vmahuli/contrail-controller,DreamLab/contrail-controller,tcpcloud/contrail-controller,numansiddique/contrail-controller,vpramo/contrail-controller,sajuptpm/contrail-controller,nischalsheth/contrail-controller,vpramo/contrail-controller,facetothefate/contrail-controller,nischalsheth/contrail-controller,vpramo/contrail-controller,rombie/contrail-controller,rombie/contrail-controller,rombie/contrail-controller,rombie/contrail-controller,numansiddique/contrail-controller,sajuptpm/contrail-controller,vpramo/contrail-controller,sajuptpm/contrail-controller,tcpcloud/contrail-controller,codilime/contrail-controller,nischalsheth/contrail-controller,hthompson6/contrail-controller,nischalsheth/contrail-controller,DreamLab/contrail-controller,nischalsheth/contrail-controller
|
1ba552c92e431aac5cb4de329ab9bccc170469f6
|
spec/async_spec.lua
|
spec/async_spec.lua
|
describe('testing the done callback with tokens', function()
it('Tests done call back ordered', function()
async()
stub(done, 'done_cb') -- create a stub to prevent actually calling 'done'
done:wait_ordered('1', '2', '3')
assert.has_no_error(function() done('1') end)
assert.has_error(function() done('1') end) -- was already done
assert.has_error(function() done('3') end) -- bad order
assert.has_no_error(function() done('2') end)
assert.has_error(function() done('this is no valid token') end)
assert.has_no_error(function() done('3') end)
assert.has_error(function() done('3') end) -- tokenlist empty by now
assert.stub(done.done_cb).was.called(1)
done.done_cb:revert() -- revert so test can complete
end)
it('Tests done call back unordered', function()
async()
stub(done, 'done_cb') -- create a stub to prevent actually calling 'done'
done:wait_unordered('1', '2', '3')
assert.has_no_error(function() done('1') end)
assert.has_error(function() done('1') end) -- was already done
assert.has_no_error(function() done('3') end) -- different order
assert.has_no_error(function() done('2') end)
assert.has_error(function() done('this is no valid token') end)
assert.has_error(function() done('3') end) -- tokenlist empty by now
assert.stub(done.done_cb).was.called(1)
done.done_cb:revert() -- revert so test can complete
end)
it('Tests done call back defaulting to ordered', function()
async()
stub(done, 'done_cb') -- create a stub to prevent actually calling 'done'
done:wait('1', '2')
assert.has_error(function() done('2') end) -- different order
assert.has_no_error(function() done('1') end)
assert.has_no_error(function() done('2') end)
done.done_cb:revert() -- revert so test can complete
end)
end)
describe('testing done callbacks being provided for async tests', function()
setup(function()
async()
assert.is_table(done)
assert.is_function(done.wait)
end)
before_each(function()
async()
assert.is_table(done)
assert.is_function(done.wait)
end)
after_each(function()
async()
assert.is_table(done)
assert.is_function(done.wait)
end)
teardown(function()
async()
assert.is_table(done)
assert.is_function(done.wait)
end)
it('Tests done callbacks being provided for async tests', function()
async()
assert.is_table(done)
assert.is_function(done.wait)
end)
end)
|
describe('testing the done callback with tokens', function()
it('Tests done call back ordered', function()
async()
stub(done, 'done_cb') -- create a stub to prevent actually calling 'done'
done:wait_ordered('1', '2', '3')
assert.has_no_error(function() done('1') end)
assert.has_error(function() done('1') end) -- was already done
assert.has_error(function() done('3') end) -- bad order
assert.has_no_error(function() done('2') end)
assert.has_error(function() done('this is no valid token') end)
assert.has_no_error(function() done('3') end)
assert.has_error(function() done('3') end) -- tokenlist empty by now
assert.stub(done.done_cb).was.called(1)
done.done_cb:revert() -- revert so test can complete
done()
end)
it('Tests done call back unordered', function()
async()
stub(done, 'done_cb') -- create a stub to prevent actually calling 'done'
done:wait_unordered('1', '2', '3')
assert.has_no_error(function() done('1') end)
assert.has_error(function() done('1') end) -- was already done
assert.has_no_error(function() done('3') end) -- different order
assert.has_no_error(function() done('2') end)
assert.has_error(function() done('this is no valid token') end)
assert.has_error(function() done('3') end) -- tokenlist empty by now
assert.stub(done.done_cb).was.called(1)
done.done_cb:revert() -- revert so test can complete
done()
end)
it('Tests done call back defaulting to ordered', function()
async()
stub(done, 'done_cb') -- create a stub to prevent actually calling 'done'
done:wait('1', '2')
assert.has_error(function() done('2') end) -- different order
assert.has_no_error(function() done('1') end)
assert.has_no_error(function() done('2') end)
done.done_cb:revert() -- revert so test can complete
done()
end)
end)
describe('testing done callbacks being provided for async tests', function()
setup(function()
async()
assert.is_table(done)
assert.is_function(done.wait)
done()
end)
before_each(function()
async()
assert.is_table(done)
assert.is_function(done.wait)
done()
end)
after_each(function()
async()
assert.is_table(done)
assert.is_function(done.wait)
done()
end)
teardown(function()
async()
assert.is_table(done)
assert.is_function(done.wait)
done()
end)
it('Tests done callbacks being provided for async tests', function()
async()
assert.is_table(done)
assert.is_function(done.wait)
done()
end)
end)
|
fix async spec
|
fix async spec
|
Lua
|
mit
|
o-lim/busted,Olivine-Labs/busted,nehz/busted,xyliuke/busted,DorianGray/busted,leafo/busted,mpeterv/busted,ryanplusplus/busted,istr/busted,sobrinho/busted
|
dc8e1807f04afcd8100d44b50ced1eda1cae782d
|
kong/plugins/request-transformer/schema.lua
|
kong/plugins/request-transformer/schema.lua
|
local pl_template = require "pl.template"
local tx = require "pl.tablex"
local typedefs = require "kong.db.schema.typedefs"
local validate_header_name = require("kong.tools.utils").validate_header_name
-- entries must have colons to set the key and value apart
local function check_for_value(entry)
local name, value = entry:match("^([^:]+):*(.-)$")
if not name or not value or value == "" then
return false, "key '" ..name.. "' has no value"
end
local status, res, err = pcall(pl_template.compile, value)
if not status or err then
return false, "value '" .. value ..
"' is not in supported format, error:" ..
(status and res or err)
end
return true
end
local function validate_headers(pair, validate_value)
local name, value = pair:match("^([^:]+):*(.-)$")
print("validating header: " .. name .. ": " .. value)
if validate_header_name(name) == nil then
return nil, string.format("'%s' is not a valid header", tostring(name))
end
if validate_value then
if validate_header_name(value) == nil then
return nil, string.format("'%s' is not a valid header", tostring(value))
end
end
return true
end
local function validate_colon_headers(pair)
return validate_headers(pair, true)
end
local strings_array = {
type = "array",
default = {},
elements = { type = "string" },
}
local headers_array = {
type = "array",
default = {},
elements = { type = "string", custom_validator = validate_headers },
}
local strings_array_record = {
type = "record",
fields = {
{ body = strings_array },
{ headers = headers_array },
{ querystring = strings_array },
},
}
local colon_strings_array = {
type = "array",
default = {},
elements = { type = "string", custom_validator = check_for_value }
}
local colon_header_value_array = {
type = "array",
default = {},
elements = { type = "string", match = "^[^:]+:.*$", custom_validator = validate_headers },
}
local colon_strings_array_record = {
type = "record",
fields = {
{ body = colon_strings_array },
{ headers = colon_header_value_array },
{ querystring = colon_strings_array },
},
}
local colon_headers_array = {
type = "array",
default = {},
elements = { type = "string", match = "^[^:]+:.*$", custom_validator = validate_colon_headers },
}
local colon_rename_strings_array_record = {
type = "record",
fields = {
{ body = colon_strings_array },
{ headers = colon_headers_array },
{ querystring = colon_strings_array },
},
}
local colon_strings_array_record_plus_uri = tx.deepcopy(colon_strings_array_record)
local uri = { uri = { type = "string" } }
table.insert(colon_strings_array_record_plus_uri.fields, uri)
return {
name = "request-transformer",
fields = {
{ run_on = typedefs.run_on_first },
{ config = {
type = "record",
fields = {
{ http_method = typedefs.http_method },
{ remove = strings_array_record },
{ rename = colon_rename_strings_array_record },
{ replace = colon_strings_array_record_plus_uri },
{ add = colon_strings_array_record },
{ append = colon_strings_array_record },
}
},
},
}
}
|
local pl_template = require "pl.template"
local tx = require "pl.tablex"
local typedefs = require "kong.db.schema.typedefs"
local validate_header_name = require("kong.tools.utils").validate_header_name
-- entries must have colons to set the key and value apart
local function check_for_value(entry)
local name, value = entry:match("^([^:]+):*(.-)$")
if not name or not value or value == "" then
return false, "key '" ..name.. "' has no value"
end
local status, res, err = pcall(pl_template.compile, value)
if not status or err then
return false, "value '" .. value ..
"' is not in supported format, error:" ..
(status and res or err)
end
return true
end
local function validate_headers(pair, validate_value)
local name, value = pair:match("^([^:]+):*(.-)$")
if validate_header_name(name) == nil then
return nil, string.format("'%s' is not a valid header", tostring(name))
end
if validate_value then
if validate_header_name(value) == nil then
return nil, string.format("'%s' is not a valid header", tostring(value))
end
end
return true
end
local function validate_colon_headers(pair)
return validate_headers(pair, true)
end
local strings_array = {
type = "array",
default = {},
elements = { type = "string" },
}
local headers_array = {
type = "array",
default = {},
elements = { type = "string", custom_validator = validate_headers },
}
local strings_array_record = {
type = "record",
fields = {
{ body = strings_array },
{ headers = headers_array },
{ querystring = strings_array },
},
}
local colon_strings_array = {
type = "array",
default = {},
elements = { type = "string", custom_validator = check_for_value }
}
local colon_header_value_array = {
type = "array",
default = {},
elements = { type = "string", match = "^[^:]+:.*$", custom_validator = validate_headers },
}
local colon_strings_array_record = {
type = "record",
fields = {
{ body = colon_strings_array },
{ headers = colon_header_value_array },
{ querystring = colon_strings_array },
},
}
local colon_headers_array = {
type = "array",
default = {},
elements = { type = "string", match = "^[^:]+:.*$", custom_validator = validate_colon_headers },
}
local colon_rename_strings_array_record = {
type = "record",
fields = {
{ body = colon_strings_array },
{ headers = colon_headers_array },
{ querystring = colon_strings_array },
},
}
local colon_strings_array_record_plus_uri = tx.deepcopy(colon_strings_array_record)
local uri = { uri = { type = "string" } }
table.insert(colon_strings_array_record_plus_uri.fields, uri)
return {
name = "request-transformer",
fields = {
{ run_on = typedefs.run_on_first },
{ config = {
type = "record",
fields = {
{ http_method = typedefs.http_method },
{ remove = strings_array_record },
{ rename = colon_rename_strings_array_record },
{ replace = colon_strings_array_record_plus_uri },
{ add = colon_strings_array_record },
{ append = colon_strings_array_record },
}
},
},
}
}
|
fix: change log level from notice to debug for a leftover line
|
fix: change log level from notice to debug for a leftover line
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
7266c074c37996a5dffc1368db0c737c575ac0e3
|
scripts/genie.lua
|
scripts/genie.lua
|
--
-- Copyright 2010-2014 Branimir Karadzic. All rights reserved.
-- License: http://www.opensource.org/licenses/BSD-2-Clause
--
newoption {
trigger = "with-tools",
description = "Enable building tools.",
}
newoption {
trigger = "with-shared-lib",
description = "Enable building shared library.",
}
newoption {
trigger = "with-sdl",
description = "Enable SDL entry.",
}
solution "bgfx"
configurations {
"Debug",
"Release",
}
platforms {
"x32",
"x64",
-- "Xbox360",
"Native", -- for targets where bitness is not specified
}
language "C++"
startproject "example-00-helloworld"
BGFX_DIR = (path.getabsolute("..") .. "/")
local BGFX_BUILD_DIR = (BGFX_DIR .. ".build/")
local BGFX_THIRD_PARTY_DIR = (BGFX_DIR .. "3rdparty/")
BX_DIR = (BGFX_DIR .. "../bx/")
defines {
"BX_CONFIG_ENABLE_MSVC_LEVEL4_WARNINGS=1"
}
dofile (BX_DIR .. "scripts/toolchain.lua")
toolchain(BGFX_BUILD_DIR, BGFX_THIRD_PARTY_DIR)
function copyLib()
end
if _OPTIONS["with-sdl"] then
if os.is("windows") then
if not os.getenv("SDL2_DIR") then
print("Set SDL2_DIR enviroment variable.")
end
end
end
function exampleProject(_name)
project ("example-" .. _name)
uuid (os.uuid("example-" .. _name))
kind "WindowedApp"
configuration {}
debugdir (BGFX_DIR .. "examples/runtime/")
includedirs {
BX_DIR .. "include",
BGFX_DIR .. "include",
BGFX_DIR .. "3rdparty",
BGFX_DIR .. "examples/common",
}
files {
BGFX_DIR .. "examples/" .. _name .. "/**.cpp",
BGFX_DIR .. "examples/" .. _name .. "/**.h",
}
links {
"bgfx",
"example-common",
}
if _OPTIONS["with-sdl"] then
defines { "ENTRY_CONFIG_USE_SDL=1" }
links { "SDL2" }
configuration { "x32", "windows" }
libdirs { "$(SDL2_DIR)/lib/x86" }
configuration { "x64", "windows" }
libdirs { "$(SDL2_DIR)/lib/x64" }
configuration {}
end
configuration { "vs*" }
linkoptions {
"/ignore:4199", -- LNK4199: /DELAYLOAD:*.dll ignored; no imports found from *.dll
}
links { -- this is needed only for testing with GLES2/3 on Windows with VS2008
"DelayImp",
}
configuration { "vs201*" }
linkoptions { -- this is needed only for testing with GLES2/3 on Windows with VS201x
"/DELAYLOAD:\"libEGL.dll\"",
"/DELAYLOAD:\"libGLESv2.dll\"",
}
configuration { "windows" }
links {
"gdi32",
"psapi",
}
configuration { "android*" }
kind "ConsoleApp"
targetextension ".so"
linkoptions {
"-shared",
}
links {
"EGL",
"GLESv2",
}
configuration { "nacl or nacl-arm" }
kind "ConsoleApp"
targetextension ".nexe"
links {
"ppapi",
"ppapi_gles2",
"pthread",
}
configuration { "pnacl" }
kind "ConsoleApp"
targetextension ".pexe"
links {
"ppapi",
"ppapi_gles2",
"pthread",
}
configuration { "asmjs" }
kind "ConsoleApp"
targetextension ".bc"
configuration { "linux-*" }
links {
"X11",
"GL",
"pthread",
}
configuration { "rpi" }
links {
"X11",
"GLESv2",
"EGL",
"bcm_host",
"vcos",
"vchiq_arm",
"pthread",
}
configuration { "osx" }
files {
BGFX_DIR .. "examples/common/**.mm",
}
links {
"Cocoa.framework",
"OpenGL.framework",
}
configuration { "xcode4" }
platforms {
"Universal"
}
files {
BGFX_DIR .. "examples/common/**.mm",
}
links {
"Cocoa.framework",
"Foundation.framework",
"OpenGL.framework",
}
configuration { "ios*" }
kind "ConsoleApp"
files {
BGFX_DIR .. "examples/common/**.mm",
}
linkoptions {
"-framework CoreFoundation",
"-framework Foundation",
"-framework OpenGLES",
"-framework UIKit",
"-framework QuartzCore",
}
configuration { "qnx*" }
targetextension ""
links {
"EGL",
"GLESv2",
}
configuration {}
strip()
end
dofile "bgfx.lua"
dofile "example-common.lua"
bgfxProject("", "StaticLib", {})
exampleProject("00-helloworld")
exampleProject("01-cubes")
exampleProject("02-metaballs")
exampleProject("03-raymarch")
exampleProject("04-mesh")
exampleProject("05-instancing")
exampleProject("06-bump")
exampleProject("07-callback")
exampleProject("08-update")
exampleProject("09-hdr")
exampleProject("10-font")
exampleProject("11-fontsdf")
exampleProject("12-lod")
exampleProject("13-stencil")
exampleProject("14-shadowvolumes")
exampleProject("15-shadowmaps-simple")
exampleProject("16-shadowmaps")
exampleProject("17-drawstress")
exampleProject("18-ibl")
exampleProject("19-oit")
exampleProject("20-nanovg")
exampleProject("21-deferred")
exampleProject("22-windows")
if _OPTIONS["with-shared-lib"] then
bgfxProject("-shared-lib", "SharedLib", {})
end
if _OPTIONS["with-tools"] then
dofile "makedisttex.lua"
dofile "shaderc.lua"
dofile "texturec.lua"
dofile "geometryc.lua"
end
|
--
-- Copyright 2010-2014 Branimir Karadzic. All rights reserved.
-- License: http://www.opensource.org/licenses/BSD-2-Clause
--
newoption {
trigger = "with-tools",
description = "Enable building tools.",
}
newoption {
trigger = "with-shared-lib",
description = "Enable building shared library.",
}
newoption {
trigger = "with-sdl",
description = "Enable SDL entry.",
}
solution "bgfx"
configurations {
"Debug",
"Release",
}
platforms {
"x32",
"x64",
-- "Xbox360",
"Native", -- for targets where bitness is not specified
}
language "C++"
startproject "example-00-helloworld"
BGFX_DIR = (path.getabsolute("..") .. "/")
local BGFX_BUILD_DIR = (BGFX_DIR .. ".build/")
local BGFX_THIRD_PARTY_DIR = (BGFX_DIR .. "3rdparty/")
BX_DIR = (BGFX_DIR .. "../bx/")
defines {
"BX_CONFIG_ENABLE_MSVC_LEVEL4_WARNINGS=1"
}
dofile (BX_DIR .. "scripts/toolchain.lua")
toolchain(BGFX_BUILD_DIR, BGFX_THIRD_PARTY_DIR)
function copyLib()
end
if _OPTIONS["with-sdl"] then
if os.is("windows") then
if not os.getenv("SDL2_DIR") then
print("Set SDL2_DIR enviroment variable.")
end
end
end
function exampleProject(_name)
project ("example-" .. _name)
uuid (os.uuid("example-" .. _name))
kind "WindowedApp"
configuration {}
debugdir (BGFX_DIR .. "examples/runtime/")
includedirs {
BX_DIR .. "include",
BGFX_DIR .. "include",
BGFX_DIR .. "3rdparty",
BGFX_DIR .. "examples/common",
}
files {
BGFX_DIR .. "examples/" .. _name .. "/**.cpp",
BGFX_DIR .. "examples/" .. _name .. "/**.h",
}
links {
"bgfx",
"example-common",
}
if _OPTIONS["with-sdl"] then
defines { "ENTRY_CONFIG_USE_SDL=1" }
links { "SDL2" }
configuration { "x32", "windows" }
libdirs { "$(SDL2_DIR)/lib/x86" }
configuration { "x64", "windows" }
libdirs { "$(SDL2_DIR)/lib/x64" }
configuration {}
end
configuration { "vs*" }
linkoptions {
"/ignore:4199", -- LNK4199: /DELAYLOAD:*.dll ignored; no imports found from *.dll
}
links { -- this is needed only for testing with GLES2/3 on Windows with VS2008
"DelayImp",
}
configuration { "vs201*" }
linkoptions { -- this is needed only for testing with GLES2/3 on Windows with VS201x
"/DELAYLOAD:\"libEGL.dll\"",
"/DELAYLOAD:\"libGLESv2.dll\"",
}
configuration { "windows" }
links {
"gdi32",
"psapi",
}
configuration { "mingw-clang" }
kind "ConsoleApp"
configuration { "android*" }
kind "ConsoleApp"
targetextension ".so"
linkoptions {
"-shared",
}
links {
"EGL",
"GLESv2",
}
configuration { "nacl or nacl-arm" }
kind "ConsoleApp"
targetextension ".nexe"
links {
"ppapi",
"ppapi_gles2",
"pthread",
}
configuration { "pnacl" }
kind "ConsoleApp"
targetextension ".pexe"
links {
"ppapi",
"ppapi_gles2",
"pthread",
}
configuration { "asmjs" }
kind "ConsoleApp"
targetextension ".bc"
configuration { "linux-*" }
links {
"X11",
"GL",
"pthread",
}
configuration { "rpi" }
links {
"X11",
"GLESv2",
"EGL",
"bcm_host",
"vcos",
"vchiq_arm",
"pthread",
}
configuration { "osx" }
files {
BGFX_DIR .. "examples/common/**.mm",
}
links {
"Cocoa.framework",
"OpenGL.framework",
}
configuration { "xcode4" }
platforms {
"Universal"
}
files {
BGFX_DIR .. "examples/common/**.mm",
}
links {
"Cocoa.framework",
"Foundation.framework",
"OpenGL.framework",
}
configuration { "ios*" }
kind "ConsoleApp"
files {
BGFX_DIR .. "examples/common/**.mm",
}
linkoptions {
"-framework CoreFoundation",
"-framework Foundation",
"-framework OpenGLES",
"-framework UIKit",
"-framework QuartzCore",
}
configuration { "qnx*" }
targetextension ""
links {
"EGL",
"GLESv2",
}
configuration {}
strip()
end
dofile "bgfx.lua"
dofile "example-common.lua"
bgfxProject("", "StaticLib", {})
exampleProject("00-helloworld")
exampleProject("01-cubes")
exampleProject("02-metaballs")
exampleProject("03-raymarch")
exampleProject("04-mesh")
exampleProject("05-instancing")
exampleProject("06-bump")
exampleProject("07-callback")
exampleProject("08-update")
exampleProject("09-hdr")
exampleProject("10-font")
exampleProject("11-fontsdf")
exampleProject("12-lod")
exampleProject("13-stencil")
exampleProject("14-shadowvolumes")
exampleProject("15-shadowmaps-simple")
exampleProject("16-shadowmaps")
exampleProject("17-drawstress")
exampleProject("18-ibl")
exampleProject("19-oit")
exampleProject("20-nanovg")
exampleProject("21-deferred")
exampleProject("22-windows")
if _OPTIONS["with-shared-lib"] then
bgfxProject("-shared-lib", "SharedLib", {})
end
if _OPTIONS["with-tools"] then
dofile "makedisttex.lua"
dofile "shaderc.lua"
dofile "texturec.lua"
dofile "geometryc.lua"
end
|
Fixed mingw-clang.
|
Fixed mingw-clang.
|
Lua
|
bsd-2-clause
|
LSBOSS/bgfx,ming4883/bgfx,elmindreda/bgfx,cyndis/bgfx,ming4883/bgfx,attilaz/bgfx,LSBOSS/bgfx,bkaradzic/bgfx,fluffyfreak/bgfx,jpcy/bgfx,mmicko/bgfx,marco-we/bgfx,Extrawurst/bgfx,jdryg/bgfx,mendsley/bgfx,kondrak/bgfx,mcanthony/bgfx,sergeScherbakov/bgfx,elmindreda/bgfx,bkaradzic/bgfx,bkaradzic/bgfx,mendsley/bgfx,fluffyfreak/bgfx,cyndis/bgfx,janstk/bgfx,jpcy/bgfx,LWJGL-CI/bgfx,LSBOSS/bgfx,mmicko/bgfx,ktotheoz/bgfx,darkimage/bgfx,ktotheoz/bgfx,septag/bgfx,septag/bgfx,aonorin/bgfx,andr3wmac/bgfx,BlueCrystalLabs/bgfx,sergeScherbakov/bgfx,janstk/bgfx,MikePopoloski/bgfx,fluffyfreak/bgfx,BlueCrystalLabs/bgfx,0-wiz-0/bgfx,0-wiz-0/bgfx,attilaz/bgfx,Extrawurst/bgfx,fluffyfreak/bgfx,kondrak/bgfx,marco-we/bgfx,LWJGL-CI/bgfx,0-wiz-0/bgfx,Synxis/bgfx,v3n/bgfx,BlueCrystalLabs/bgfx,Extrawurst/bgfx,ming4883/bgfx,aonorin/bgfx,Synxis/bgfx,mcanthony/bgfx,jpcy/bgfx,jdryg/bgfx,MikePopoloski/bgfx,jdryg/bgfx,darkimage/bgfx,cyndis/bgfx,v3n/bgfx,MikePopoloski/bgfx,jdryg/bgfx,andr3wmac/bgfx,cuavas/bgfx,andr3wmac/bgfx,LWJGL-CI/bgfx,marco-we/bgfx,sergeScherbakov/bgfx,ktotheoz/bgfx,Vertexwahn/bgfx,kondrak/bgfx,jpcy/bgfx,mcanthony/bgfx,cuavas/bgfx,emoon/bgfx,mendsley/bgfx,emoon/bgfx,cuavas/bgfx,septag/bgfx,emoon/bgfx,mmicko/bgfx,v3n/bgfx,ocornut/bgfx,attilaz/bgfx,elmindreda/bgfx,LWJGL-CI/bgfx,ocornut/bgfx,bkaradzic/bgfx,darkimage/bgfx,aonorin/bgfx,Vertexwahn/bgfx,janstk/bgfx,ocornut/bgfx,Synxis/bgfx,Vertexwahn/bgfx
|
f39e8eebe273075ebcd297801a58c365298c64c5
|
net/http/parser.lua
|
net/http/parser.lua
|
local tonumber = tonumber;
local assert = assert;
local url_parse = require "socket.url".parse;
local urldecode = require "net.http".urldecode;
local function preprocess_path(path)
path = urldecode((path:gsub("//+", "/")));
if path:sub(1,1) ~= "/" then
path = "/"..path;
end
local level = 0;
for component in path:gmatch("([^/]+)/") do
if component == ".." then
level = level - 1;
elseif component ~= "." then
level = level + 1;
end
if level < 0 then
return nil;
end
end
return path;
end
local httpstream = {};
function httpstream.new(success_cb, error_cb, parser_type, options_cb)
local client = true;
if not parser_type or parser_type == "server" then client = false; else assert(parser_type == "client", "Invalid parser type"); end
local buf = "";
local chunked;
local state = nil;
local packet;
local len;
local have_body;
local error;
return {
feed = function(self, data)
if error then return nil, "parse has failed"; end
if not data then -- EOF
if state and client and not len then -- reading client body until EOF
packet.body = buf;
success_cb(packet);
elseif buf ~= "" then -- unexpected EOF
error = true; return error_cb();
end
return;
end
buf = buf..data;
while #buf > 0 do
if state == nil then -- read request
local index = buf:find("\r\n\r\n", nil, true);
if not index then return; end -- not enough data
local method, path, httpversion, status_code, reason_phrase;
local first_line;
local headers = {};
for line in buf:sub(1,index+1):gmatch("([^\r\n]+)\r\n") do -- parse request
if first_line then
local key, val = line:match("^([^%s:]+): *(.*)$");
if not key then error = true; return error_cb("invalid-header-line"); end -- TODO handle multi-line and invalid headers
key = key:lower();
headers[key] = headers[key] and headers[key]..","..val or val;
else
first_line = line;
if client then
httpversion, status_code, reason_phrase = line:match("^HTTP/(1%.[01]) (%d%d%d) (.*)$");
if not status_code then error = true; return error_cb("invalid-status-line"); end
have_body = not
( (options_cb and options_cb().method == "HEAD")
or (status_code == 204 or status_code == 304 or status_code == 301)
or (status_code >= 100 and status_code < 200) );
chunked = have_body and headers["transfer-encoding"] == "chunked";
else
method, path, httpversion = line:match("^(%w+) (%S+) HTTP/(1%.[01])$");
if not method then error = true; return error_cb("invalid-status-line"); end
end
end
end
len = tonumber(headers["content-length"]); -- TODO check for invalid len
if client then
-- FIXME handle '100 Continue' response (by skipping it)
if not have_body then len = 0; end
packet = {
code = status_code;
httpversion = httpversion;
headers = headers;
body = have_body and "" or nil;
-- COMPAT the properties below are deprecated
responseversion = httpversion;
responseheaders = headers;
};
else
local parsed_url = url_parse(path);
path = preprocess_path(parsed_url.path);
headers.host = parsed_url.host or headers.host;
len = len or 0;
packet = {
method = method;
url = parsed_url;
path = path;
httpversion = httpversion;
headers = headers;
body = nil;
};
end
buf = buf:sub(index + 4);
state = true;
end
if state then -- read body
if client then
if chunked then
local index = buf:find("\r\n", nil, true);
if not index then return; end -- not enough data
local chunk_size = buf:match("^%x+");
if not chunk_size then error = true; return error_cb("invalid-chunk-size"); end
chunk_size = tonumber(chunk_size, 16);
index = index + 2;
if chunk_size == 0 then
state = nil; success_cb(packet);
elseif #buf - index + 1 >= chunk_size then -- we have a chunk
packet.body = packet.body..buf:sub(index, index + chunk_size - 1);
buf = buf:sub(index + chunk_size);
end
error("trailers"); -- FIXME MUST read trailers
elseif len and #buf >= len then
packet.body, buf = buf:sub(1, len), buf:sub(len + 1);
state = nil; success_cb(packet);
end
elseif #buf >= len then
packet.body, buf = buf:sub(1, len), buf:sub(len + 1);
state = nil; success_cb(packet);
else
break;
end
end
end
end;
};
end
return httpstream;
|
local tonumber = tonumber;
local assert = assert;
local url_parse = require "socket.url".parse;
local urldecode = require "net.http".urldecode;
local function preprocess_path(path)
path = urldecode((path:gsub("//+", "/")));
if path:sub(1,1) ~= "/" then
path = "/"..path;
end
local level = 0;
for component in path:gmatch("([^/]+)/") do
if component == ".." then
level = level - 1;
elseif component ~= "." then
level = level + 1;
end
if level < 0 then
return nil;
end
end
return path;
end
local httpstream = {};
function httpstream.new(success_cb, error_cb, parser_type, options_cb)
local client = true;
if not parser_type or parser_type == "server" then client = false; else assert(parser_type == "client", "Invalid parser type"); end
local buf = "";
local chunked;
local state = nil;
local packet;
local len;
local have_body;
local error;
return {
feed = function(self, data)
if error then return nil, "parse has failed"; end
if not data then -- EOF
if state and client and not len then -- reading client body until EOF
packet.body = buf;
success_cb(packet);
elseif buf ~= "" then -- unexpected EOF
error = true; return error_cb();
end
return;
end
buf = buf..data;
while #buf > 0 do
if state == nil then -- read request
local index = buf:find("\r\n\r\n", nil, true);
if not index then return; end -- not enough data
local method, path, httpversion, status_code, reason_phrase;
local first_line;
local headers = {};
for line in buf:sub(1,index+1):gmatch("([^\r\n]+)\r\n") do -- parse request
if first_line then
local key, val = line:match("^([^%s:]+): *(.*)$");
if not key then error = true; return error_cb("invalid-header-line"); end -- TODO handle multi-line and invalid headers
key = key:lower();
headers[key] = headers[key] and headers[key]..","..val or val;
else
first_line = line;
if client then
httpversion, status_code, reason_phrase = line:match("^HTTP/(1%.[01]) (%d%d%d) (.*)$");
if not status_code then error = true; return error_cb("invalid-status-line"); end
have_body = not
( (options_cb and options_cb().method == "HEAD")
or (status_code == 204 or status_code == 304 or status_code == 301)
or (status_code >= 100 and status_code < 200) );
chunked = have_body and headers["transfer-encoding"] == "chunked";
else
method, path, httpversion = line:match("^(%w+) (%S+) HTTP/(1%.[01])$");
if not method then error = true; return error_cb("invalid-status-line"); end
end
end
end
len = tonumber(headers["content-length"]); -- TODO check for invalid len
if client then
-- FIXME handle '100 Continue' response (by skipping it)
if not have_body then len = 0; end
packet = {
code = status_code;
httpversion = httpversion;
headers = headers;
body = have_body and "" or nil;
-- COMPAT the properties below are deprecated
responseversion = httpversion;
responseheaders = headers;
};
else
local parsed_url;
if path:byte() == 47 then -- starts with /
local _path, _query = path:match("([^?]*).?(.*)");
if _query == "" then _query = nil; end
parsed_url = { path = _path, query = _query };
else
parsed_url = url_parse(path);
end
path = preprocess_path(parsed_url.path);
headers.host = parsed_url.host or headers.host;
len = len or 0;
packet = {
method = method;
url = parsed_url;
path = path;
httpversion = httpversion;
headers = headers;
body = nil;
};
end
buf = buf:sub(index + 4);
state = true;
end
if state then -- read body
if client then
if chunked then
local index = buf:find("\r\n", nil, true);
if not index then return; end -- not enough data
local chunk_size = buf:match("^%x+");
if not chunk_size then error = true; return error_cb("invalid-chunk-size"); end
chunk_size = tonumber(chunk_size, 16);
index = index + 2;
if chunk_size == 0 then
state = nil; success_cb(packet);
elseif #buf - index + 1 >= chunk_size then -- we have a chunk
packet.body = packet.body..buf:sub(index, index + chunk_size - 1);
buf = buf:sub(index + chunk_size);
end
error("trailers"); -- FIXME MUST read trailers
elseif len and #buf >= len then
packet.body, buf = buf:sub(1, len), buf:sub(len + 1);
state = nil; success_cb(packet);
end
elseif #buf >= len then
packet.body, buf = buf:sub(1, len), buf:sub(len + 1);
state = nil; success_cb(packet);
else
break;
end
end
end
end;
};
end
return httpstream;
|
net.http.parser: Skip url.parse when we don't have a full URL (also fixes traceback on paths starting with '//').
|
net.http.parser: Skip url.parse when we don't have a full URL (also fixes traceback on paths starting with '//').
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
5fc7de3fed5fa17ffad85392e53be65982ad4bed
|
lua/wire/flir.lua
|
lua/wire/flir.lua
|
--[[
Simulation of FLIR (forward-looking infrared) vision.
Possible future ideas:
* Different materials have different emissivities:
aluminium is about 20%, wherease asphalt is 95%.
maybe we could use the physical properties to simulate this?
* the luminance of a texture contributes *negatively* to its emissivity
* IR sensors often have auto gain control that we might simulate with auto-exposure
* players are drawn fullbright but NPCs aren't.
--]]
if not FLIR then FLIR = { enabled = false } end
if CLIENT then
FLIR.living = CreateMaterial("flir_living", "UnlitGeneric", {
["$basetexture"] = "color/white",
["$model"] = 1,
})
FLIR.normal = CreateMaterial("flir_normal", "VertexLitGeneric", {
["$basetexture"] = "color/white",
["$model"] = 1,
["$halflambert"] = 1 -- causes the diffuse lighting to 'wrap around' more
})
FLIR.colmod = {
[ "$pp_colour_addr" ] = 0.4,
[ "$pp_colour_addg" ] = -.5,
[ "$pp_colour_addb" ] = -.5,
[ "$pp_colour_brightness" ] = .1,
[ "$pp_colour_contrast" ] = 1.2,
[ "$pp_colour_colour" ] = 0,
[ "$pp_colour_mulr" ] = 0,
[ "$pp_colour_mulg" ] = 0,
[ "$pp_colour_mulb" ] = 0
}
local materialOverrides = {
PlayerDraw = { FLIR.living, FLIR.normal },
DrawOpaqueRenderables = { FLIR.normal, nil },
DrawTranslucentRenderables = { FLIR.normal, nil },
DrawSkybox = { FLIR.normal, nil }
}
function FLIR.start()
if FLIR.enabled then return else FLIR.enabled = true end
for hookName, materials in pairs(materialOverrides) do
hook.Add("Pre" .. hookName, "flir", function() render.MaterialOverride(materials[1]) end)
hook.Add("Post" .. hookName, "flir", function() render.MaterialOverride(materials[2]) end)
end
hook.Add("RenderScreenspaceEffects", "flir", function()
DrawColorModify(FLIR.colmod)
DrawBloom(0,100,5,5,3,0.1,0,0,0)
DrawSharpen(1,0.5)
end)
end
function FLIR.stop()
if FLIR.enabled then FLIR.enabled = false else return end
for hookName, materials in pairs(materialOverrides) do
hook.Remove("Pre" .. hookName, "flir")
hook.Remove("Post" .. hookName, "flir")
end
hook.Remove("RenderScreenspaceEffects", "flir")
render.MaterialOverride(nil)
end
function FLIR.enable(enabled)
if enabled then FLIR.start() else FLIR.stop() end
end
usermessage.Hook("flir.enable",function(um)
FLIR.enable(um:ReadBool())
end)
concommand.Add("flir_enable", function(player, command, args)
FLIR.enable(tobool(args[1]))
end)
else
function FLIR.start(player) FLIR.enable(player, true) end
function FLIR.stop(player) FLIR.enable(player, false) end
function FLIR.enable(player, enabled)
umsg.Start( "flir.enable", player)
umsg.Bool( enabled )
umsg.End()
end
end
|
--[[
Simulation of FLIR (forward-looking infrared) vision.
Possible future ideas:
* Different materials have different emissivities:
aluminium is about 20%, wherease asphalt is 95%.
maybe we could use the physical properties to simulate this?
* the luminance of a texture contributes *negatively* to its emissivity
* IR sensors often have auto gain control that we might simulate with auto-exposure
* players are drawn fullbright but NPCs aren't.
--]]
if not FLIR then FLIR = { enabled = false } end
if CLIENT then
FLIR.normal = CreateMaterial("flir_normal", "VertexLitGeneric", {
["$basetexture"] = "color/white",
["$model"] = 1,
["$halflambert"] = 1, -- causes the diffuse lighting to 'wrap around' more
["$color2"] = "[10.0 10.0 10.0]"
})
FLIR.entcol = {
["$pp_colour_colour" ] = 0,
["$pp_colour_brightness"] = -0.00,
["$pp_colour_contrast"] = 4
}
FLIR.mapcol = {
[ "$pp_colour_brightness" ] = 0,
[ "$pp_colour_contrast" ] = 0.2
}
FLIR.skycol = {
[ "$pp_colour_contrast" ] = 0.2,
[ "$pp_colour_brightness" ] = 1
}
local function SetFLIRMat(ent)
if not IsValid(ent) then return end
if ent:GetMoveType() == MOVETYPE_VPHYSICS or IsValid(ent:GetParent()) or ent:IsPlayer() or ent:IsNPC() or ent:IsRagdoll() then
ent.FLIRMat = ent:GetMaterial()
ent:SetMaterial("!flir_normal")
end
end
function FLIR.start()
if FLIR.enabled then return else FLIR.enabled = true end
bright = false
hook.Add("PreRender", "wire_flir", function() --lighting mode 1 = fullbright
render.SetLightingMode(1)
end)
hook.Add("PostDraw2DSkyBox", "wire_flir", function() --overrides 2d skybox to be gray, as it normally becomes white
DrawColorModify(FLIR.skycol)
end)
hook.Add("PostDrawTranslucentRenderables", "wire_flir", function(_a, _b, sky)
if not sky then
render.SetLightingMode(0)
DrawColorModify(FLIR.mapcol)
end
end)
hook.Add("RenderScreenspaceEffects", "wire_flir", function()
DrawColorModify(FLIR.entcol)
DrawBloom(0.5,1.0,2,2,2,1, 1, 1, 1)
DrawBokehDOF(1, 0.1, 0.1)
end)
hook.Add("OnEntityCreated", "wire_flir", function(ent)
if FLIR.enabled then
SetFLIRMat(ent)
end
end)
hook.Add("CreateClientsideRagdoll", "wire_flir", function(ent, rag)
if FLIR.enabled then
SetFLIRMat(rag)
end
end)
for k, v in pairs(ents.GetAll()) do
SetFLIRMat(v)
end
end
function FLIR.stop()
if FLIR.enabled then FLIR.enabled = false else return end
render.SetLightingMode(0)
hook.Remove("PostDrawTranslucentRenderables", "wire_flir")
hook.Remove("RenderScreenspaceEffects", "wire_flir")
hook.Remove("PostDraw2DSkyBox", "wire_flir")
hook.Remove("PreRender", "wire_flir")
hook.Remove("OnEntityCreated", "wire_flir")
hook.Remove("CreateClientsideRagdoll", "wire_flir")
render.MaterialOverride(nil)
for k, v in pairs(ents.GetAll()) do
if v.FLIRMat then
v:SetMaterial(v.FLIRMat)
v.FLIRMat = nil
end
end
end
function FLIR.enable(enabled)
if enabled then FLIR.start() else FLIR.stop() end
end
usermessage.Hook("flir.enable",function(um)
FLIR.enable(um:ReadBool())
end)
concommand.Add("flir_enable", function(player, command, args)
FLIR.enable(tobool(args[1]))
end)
else
function FLIR.start(player) FLIR.enable(player, true) end
function FLIR.stop(player) FLIR.enable(player, false) end
function FLIR.enable(player, enabled)
umsg.Start( "flir.enable", player)
umsg.Bool( enabled )
umsg.End()
end
end
|
Reworked FLIR visual behaviour (#2216)
|
Reworked FLIR visual behaviour (#2216)
* Reworked FLIR visual behaviour
* added hook removals, fixed 3d skybox color
* adjusted color modifies, streamlined hooks, removed old material system
* client ragdoll hook -> flir.Start() to fix no heat on bodies
* removed print(test) from function
* removed flir.living material, renamed hooks flir -> wire_flir
|
Lua
|
apache-2.0
|
wiremod/wire,dvdvideo1234/wire,Grocel/wire
|
4b4b549697b339619e48bb1132197f2a52465bcf
|
src/cosy/webclient/main.lua
|
src/cosy/webclient/main.lua
|
local js = _G.js
local location = js.global.location
local loader = require (location.origin .. "/lua/cosy.loader")
_G.client = {}
local function screen ()
local result,err = _G.client.server.filter({
iterator = "return function (yield, store)\
for k in pairs (store.user) do\
yield {lat = store.user [k].position.latitude , lng = store.user [k].position.longitude}\
end\
end"
})
if result then
local iframe = js.global.document:getElementById("map").contentWindow
for _,value in pairs(result) do
if value.lat and value.lng then
iframe.cluster (nil,value.lat,value.lng)
end
end
iframe.groupcluster ()
else
print(err.message)
end
end
local function main()
local lib = require "cosy.library"
_G.client = lib.connect (js.global.location.origin)
local storage = js.global.sessionStorage
local token = storage:getItem("cosytoken")
local user = storage:getItem("cosyuser")
local connected = false
local connection, err = _G.client.user.is_authentified {
authentication = token
}
if connection then
if user == connection.username and token ~= js.null then
connected = true
end
else
print(err.message)
end
js.global.document:getElementById("content-wrapper").innerHTML = loader.loadhttp ( "/html/main.html")
if connected then
js.global.document:getElementById("navbar-login").innerHTML = loader.loadhttp ( "/html/logoutnavbar.html")
js.global.document:getElementById("user-in").innerHTML = user
local result = _G.client.user.update {
authentication = token
}
if result.name then
js.global.document:getElementById("user-name").innerHTML = result.name
end
if result.lastseen then
js.global.document:getElementById("user-last").innerHTML = os.date('%d/%m/%Y %H:%M:%S', result.lastseen)
end
if result.avatar then
js.global.document:getElementById("user-image-s").src = 'data:image/png;base64,'..result.avatar
js.global.document:getElementById("user-image-b").src = 'data:image/png;base64,'..result.avatar
else
js.global.document:getElementById("user-image-s").src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAACklEQVQYV2P4DwABAQEAWk1v8QAAAABJRU5ErkJggg=="
js.global.document:getElementById("user-image-b").src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAACklEQVQYV2P4DwABAQEAWk1v8QAAAABJRU5ErkJggg=="
end
js.global.document:getElementById("logout-button").onclick = function()
storage:removeItem("cosytoken")
storage:removeItem("cosyuser")
js.global.location.href = "/"
return false
end
js.global.document:getElementById("profile-button").onclick = function()
require ("cosy.webclient.profile")
return false
end
else
local auth = require ("cosy.webclient.auth")
js.global.document:getElementById("navbar-login").innerHTML = loader.loadhttp ( "/html/loginnavbar.html")
js.global.document:getElementById("login-button").onclick = function()
coroutine.wrap(auth.login) ()
return false
end
js.global.document:getElementById("signup-button").onclick = function()
coroutine.wrap(auth.register) ()
return false
end
end
local map = js.global.document:getElementById("map")
if map.contentWindow.cluster == nil then
map.onload = function ()
local co = coroutine.create (screen)
coroutine.resume (co)
end
else
screen()
end
end
local co = coroutine.create (main)
coroutine.resume (co)
|
return function (loader)
local Value = loader.load "cosy.value"
local Main = {}
local function show_users ()
local result, err = loader.client.server.filter {
iterator = [[
return function (coroutine, store)
for user in store / "data" * ".*" do
if user.position then
coroutine.yield {
latitude = user.position.latitude,
longitude = user.position.longitude,
}
end
end
end
]]
}
if result then
local iframe = loader.document:getElementById "map".contentWindow
for value in result do
iframe.cluster (nil, value.latitude, value.longitude)
end
iframe.groupcluster ()
else
print (err.message, Value.encode (err))
end
end
function Main.init ()
local serverinfo = assert (loader.client.server.information ())
local userinfo = assert (loader.client.user.authentified_as {})
local username = userinfo and userinfo.username
loader.document:getElementById "content-wrapper".innerHTML = (loader.request "/html/main.html") % serverinfo
if username then
loader.document:getElementById "navbar-login".innerHTML = loader.request "/html/logoutnavbar.html"
loader.document:getElementById "user-in".innerHTML = username
userinfo = loader.client.user.update {}
if userinfo.name then
loader.document:getElementById "user-name".innerHTML = userinfo.name
end
if userinfo.lastseen then
loader.document:getElementById "user-last".innerHTML = os.date ("%d/%m/%Y %H:%M:%S", userinfo.lastseen)
end
if userinfo.avatar then
loader.document:getElementById "user-image-s".src = "data:image/png;base64," .. userinfo.avatar
loader.document:getElementById "user-image-b".src = "data:image/png;base64," .. userinfo.avatar
else
loader.document:getElementById "user-image-s".src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAACklEQVQYV2P4DwABAQEAWk1v8QAAAABJRU5ErkJggg=="
loader.document:getElementById "user-image-b".src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAACklEQVQYV2P4DwABAQEAWk1v8QAAAABJRU5ErkJggg=="
end
loader.document:getElementById "logout-button".onclick = function ()
loader.storage:removeItem "cosy:client"
loader.window.location.href = "/"
return false
end
loader.document:getElementById "profile-button".onclick = function ()
loader.load "cosy.webclient.profile"
return false
end
else
local auth = loader.load "cosy.webclient.auth"
loader.document:getElementById "navbar-login".innerHTML = loader.request "/html/loginnavbar.html"
loader.document:getElementById "login-button".onclick = function ()
loader.coroutine.wrap (auth.login) ()
return false
end
loader.document:getElementById "signup-button".onclick = function ()
loader.coroutine.wrap (auth.register) ()
return false
end
end
local map = loader.document:getElementById "map"
if map.contentWindow.cluster == nil then
map.onload = function ()
loader.scheduler.addthread (show_users)
end
else
loader.scheduler.addthread (show_users)
end
end
Main.init ()
-- Update server information regularly:
loader.scheduler.addthread (function ()
while true do
loader.scheduler.sleep (10)
local serverinfo = assert (loader.client.server.information ())
for k, v in pairs (serverinfo) do
if k:match "^#" then
local part = loader.document:getElementById (k)
if part ~= loader.js.null then
part.innerHTML = tostring (v)
end
end
end
end
end)
end
|
Fix HTML main lua code.
|
Fix HTML main lua code.
|
Lua
|
mit
|
CosyVerif/library,CosyVerif/library,CosyVerif/library
|
2db20944f3122323bcfc40963d84bea7f53ea372
|
link/config/nvim/plug-config/nvim-cmp.lua
|
link/config/nvim/plug-config/nvim-cmp.lua
|
-- nvim-cmp is a super flexible and powerful completion plugin for Neovim.
-- It even completes in the command entry area.
local cmp = require "cmp"
-- Use VSCode-like pictograms
local lspkind = require "lspkind"
cmp.setup(
{
-- This plugin is currently broken. Wait for fix.
--[[ formatting = {
-- Use VSCode-like pictograms in completions
format = lspkind.cmp_format({with_text = false, maxwidth = 50})
}, ]]
snippet = {
expand = function(args)
vim.fn["vsnip#anonymous"](args.body) -- For `vsnip` users.
-- require('luasnip').lsp_expand(args.body) -- For `luasnip` users.
-- vim.fn["UltiSnips#Anon"](args.body) -- For `ultisnips` users.
-- require'snippy'.expand_snippet(args.body) -- For `snippy` users.
end
},
mapping = {
["<C-l>"] = cmp.mapping.confirm({select = true}),
["<Tab>"] = cmp.mapping(cmp.mapping.select_next_item(), {"i", "s"}),
-- Use C-j and C-k to cycle forward or backward through completion
-- candidates.
["<C-j>"] = cmp.mapping(cmp.mapping.select_next_item(), {"i", "s"}),
["<C-k>"] = cmp.mapping(cmp.mapping.select_prev_item(), {"i", "s"}),
["<C-d>"] = cmp.mapping(cmp.mapping.scroll_docs(-4), {"i", "c"}),
["<C-f>"] = cmp.mapping(cmp.mapping.scroll_docs(4), {"i", "c"}),
["<C-Space>"] = cmp.mapping(cmp.mapping.complete(), {"i", "c"}),
["<C-y>"] = cmp.config.disable, -- If you want to remove the default `<C-y>` mapping, You can specify `cmp.config.disable` value.
["<C-e>"] = cmp.mapping(
{
i = cmp.mapping.abort(),
c = cmp.mapping.close()
}
),
["<CR>"] = cmp.mapping.confirm({select = true})
},
sources = cmp.config.sources(
{
{name = "nvim_lsp"},
{name = "vsnip"} -- For vsnip users.
-- { name = 'luasnip' }, -- For luasnip users.
-- { name = 'ultisnips' }, -- For ultisnips users.
-- { name = 'snippy' }, -- For snippy users.
},
{
{name = "buffer"}
}
)
}
)
-- Use buffer source for `/`.
cmp.setup.cmdline(
"/",
{
sources = {
{name = "buffer"}
}
}
)
-- Use cmdline & path source for ':'.
cmp.setup.cmdline(
":",
{
sources = cmp.config.sources(
{
{name = "path"}
},
{
{name = "cmdline"}
}
)
}
)
-- vim:foldenable:foldmethod=marker:foldlevel=0
|
-- nvim-cmp is a super flexible and powerful completion plugin for Neovim.
-- It even completes in the command entry area.
local cmp = require "cmp"
-- Use VSCode-like pictograms
local lspkind = require "lspkind"
cmp.setup(
{
formatting = {
-- Use VSCode-like pictograms in completions
format = lspkind.cmp_format({with_text = false, maxwidth = 50})
},
snippet = {
expand = function(args)
-- Choose your snippets provider. vsnip will be awesome once it gets
-- more snippets in the friendly-snippets repo.
-- vim.fn["vsnip#anonymous"](args.body) -- For `vsnip` users.
-- require('luasnip').lsp_expand(args.body) -- For `luasnip` users.
vim.fn["UltiSnips#Anon"](args.body) -- For `ultisnips` users.
-- require'snippy'.expand_snippet(args.body) -- For `snippy` users.
end
},
mapping = {
["<C-l>"] = cmp.mapping.confirm({select = true}),
["<Tab>"] = cmp.mapping(cmp.mapping.select_next_item(), {"i", "s"}),
-- Use C-j and C-k to cycle forward or backward through completion
-- candidates.
["<C-j>"] = cmp.mapping(cmp.mapping.select_next_item(), {"i", "s"}),
["<C-k>"] = cmp.mapping(cmp.mapping.select_prev_item(), {"i", "s"}),
["<C-d>"] = cmp.mapping(cmp.mapping.scroll_docs(-4), {"i", "c"}),
["<C-f>"] = cmp.mapping(cmp.mapping.scroll_docs(4), {"i", "c"}),
["<C-Space>"] = cmp.mapping(cmp.mapping.complete(), {"i", "c"}),
["<C-y>"] = cmp.config.disable, -- If you want to remove the default `<C-y>` mapping, You can specify `cmp.config.disable` value.
["<C-e>"] = cmp.mapping(
{
i = cmp.mapping.abort(),
c = cmp.mapping.close()
}
),
["<CR>"] = cmp.mapping.confirm({select = true})
},
sources = cmp.config.sources(
{
{name = "nvim_lsp"},
-- {name = "vsnip"} -- For vsnip users.
-- { name = 'luasnip' }, -- For luasnip users.
{name = "ultisnips"} -- For ultisnips users.
-- { name = 'snippy' }, -- For snippy users.
},
{
{name = "buffer"}
}
)
}
)
-- Use buffer source for `/`.
cmp.setup.cmdline(
"/",
{
sources = {
{name = "buffer"}
}
}
)
-- Use cmdline & path source for ':'.
cmp.setup.cmdline(
":",
{
sources = cmp.config.sources(
{
{name = "path"}
},
{
{name = "cmdline"}
}
)
}
)
-- vim:foldenable:foldmethod=marker:foldlevel=0
|
Re-added lspkind after fix was submitted
|
Re-added lspkind after fix was submitted
|
Lua
|
mit
|
tjtrabue/dotfiles,tjtrabue/dotfiles,tjtrabue/dotfiles,tjtrabue/dotfiles,tjtrabue/dotfiles
|
c934f12eb75ad7593b31232ce9dc24d8c9b2d640
|
mod_admin_web/admin_web/mod_admin_web.lua
|
mod_admin_web/admin_web/mod_admin_web.lua
|
-- Copyright (C) 2010 Florian Zeitz
--
-- This file is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
-- <session xmlns="http://prosody.im/streams/c2s" jid="[email protected]/brussels">
-- <encrypted/>
-- <compressed/>
-- </session>
-- <session xmlns="http://prosody.im/streams/s2s" jid="example.com">
-- <encrypted/>
-- <compressed/>
-- <in/> / <out/>
-- </session>
local stanza = require "util.stanza";
local uuid_generate = require "util.uuid".generate;
local httpserver = require "net.httpserver";
local lfs = require "lfs";
local open = io.open;
local stat = lfs.attributes;
local host = module:get_host();
local service = config.get("*", "core", "webadmin_pubsub_host") or ("pubsub." .. host);
local http_base = (prosody.paths.plugins or "./plugins/") .. "admin_web/www_files";
local xmlns_c2s_session = "http://prosody.im/streams/c2s";
local xmlns_s2s_session = "http://prosody.im/streams/s2s";
local response_400 = { status = "400 Bad Request", body = "<h1>Bad Request</h1>Sorry, we didn't understand your request :(" };
local response_403 = { status = "403 Forbidden", body = "<h1>Forbidden</h1>You don't have permission to view the contents of this directory :(" };
local response_404 = { status = "404 Not Found", body = "<h1>Page Not Found</h1>Sorry, we couldn't find what you were looking for :(" };
local mime_map = {
html = "text/html";
xml = "text/xml";
js = "text/javascript";
css = "text/css";
};
local idmap = {};
function add_client(session)
local name = session.full_jid;
local id = idmap[name];
if not id then
id = uuid_generate();
idmap[name] = id;
end
local item = stanza.stanza("item", { id = id }):tag("session", {xmlns = xmlns_c2s_session, jid = name}):up();
if session.secure then
item:tag("encrypted"):up();
end
if session.compressed then
item:tag("compressed"):up();
end
hosts[service].modules.pubsub.service:publish(xmlns_c2s_session, service, id, item);
module:log("debug", "Added client " .. name);
end
function del_client(session)
local name = session.full_jid;
local id = idmap[name];
if id then
local notifier = stanza.stanza("retract", { id = id });
hosts[service].modules.pubsub.service:retract(xmlns_c2s_session, service, id, notifier);
end
end
function add_host(session, type)
local name = (type == "out" and session.to_host) or (type == "in" and session.from_host);
local id = idmap[name.."_"..type];
if not id then
id = uuid_generate();
idmap[name.."_"..type] = id;
end
local item = stanza.stanza("item", { id = id }):tag("session", {xmlns = xmlns_s2s_session, jid = name})
:tag(type):up();
if session.secure then
item:tag("encrypted"):up();
end
if session.compressed then
item:tag("compressed"):up();
end
hosts[service].modules.pubsub.service:publish(xmlns_s2s_session, service, id, item);
module:log("debug", "Added host " .. name .. " s2s" .. type);
end
function del_host(session, type)
local name = (type == "out" and session.to_host) or (type == "in" and session.from_host);
local id = idmap[name.."_"..type];
if id then
local notifier = stanza.stanza("retract", { id = id });
hosts[service].modules.pubsub.service:retract(xmlns_s2s_session, service, id, notifier);
end
end
local function preprocess_path(path)
if path:sub(1,1) ~= "/" then
path = "/"..path;
end
local level = 0;
for component in path:gmatch("([^/]+)/") do
if component == ".." then
level = level - 1;
elseif component ~= "." then
level = level + 1;
end
if level < 0 then
return nil;
end
end
return path;
end
function serve_file(path)
local full_path = http_base..path;
if stat(full_path, "mode") == "directory" then
if stat(full_path.."/index.html", "mode") == "file" then
return serve_file(path.."/index.html");
end
return response_403;
end
local f, err = open(full_path, "rb");
if not f then return response_404; end
local data = f:read("*a");
data = data:gsub("%%PUBSUBHOST%%", service);
f:close();
if not data then
return response_403;
end
local ext = path:match("%.([^.]*)$");
local mime = mime_map[ext]; -- Content-Type should be nil when not known
return {
headers = { ["Content-Type"] = mime; };
body = data;
};
end
local function handle_file_request(method, body, request)
local path = preprocess_path(request.url.path);
if not path then return response_400; end
path = path:gsub("^/[^/]+", ""); -- Strip /admin/
return serve_file(path);
end
function module.load()
local host_session = prosody.hosts[host];
local http_conf = config.get("*", "core", "webadmin_http_ports");
httpserver.new_from_config(http_conf, handle_file_request, { base = "admin" });
end
module:hook("server-started", function ()
if not select(2, hosts[service].modules.pubsub.service:get_nodes(service))[xmlns_s2s_session] then
local ok, errmsg = hosts[service].modules.pubsub.service:create(xmlns_s2s_session, service);
if not ok then
module:log("warn", "Could not create node " .. xmlns_s2s_session .. ": " .. tostring(errmsg));
end
end
for remotehost, session in pairs(host_session.s2sout) do
if session.type ~= "s2sout_unauthed" then
add_host(session, "out");
end
end
for session in pairs(incoming_s2s) do
if session.to_host == host then
add_host(session, "in");
end
end
if not select(2, hosts[service].modules.pubsub.service:get_nodes(service))[xmlns_c2s_session] then
local ok, errmsg = hosts[service].modules.pubsub.service:create(xmlns_c2s_session, service);
if not ok then
module:log("warn", "Could not create node " .. xmlns_c2s_session .. ": " .. tostring(errmsg));
end
end
for username, user in pairs(host_session.sessions or {}) do
for resource, session in pairs(user.sessions or {}) do
add_client(session);
end
end
end);
module:hook("resource-bind", function(event)
add_client(event.session);
end);
module:hook("resource-unbind", function(event)
del_client(event.session);
end);
module:hook("s2sout-established", function(event)
add_host(event.session, "out");
end);
module:hook("s2sin-established", function(event)
add_host(event.session, "in");
end);
module:hook("s2sout-destroyed", function(event)
del_host(event.session, "out");
end);
module:hook("s2sin-destroyed", function(event)
del_host(event.session, "in");
end);
|
-- Copyright (C) 2010 Florian Zeitz
--
-- This file is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
-- <session xmlns="http://prosody.im/streams/c2s" jid="[email protected]/brussels">
-- <encrypted/>
-- <compressed/>
-- </session>
-- <session xmlns="http://prosody.im/streams/s2s" jid="example.com">
-- <encrypted/>
-- <compressed/>
-- <in/> / <out/>
-- </session>
local stanza = require "util.stanza";
local uuid_generate = require "util.uuid".generate;
local httpserver = require "net.httpserver";
local lfs = require "lfs";
local open = io.open;
local stat = lfs.attributes;
local host = module:get_host();
local service = config.get("*", "core", "webadmin_pubsub_host") or ("pubsub." .. host);
local http_base = (prosody.paths.plugins or "./plugins/") .. "admin_web/www_files";
local xmlns_c2s_session = "http://prosody.im/streams/c2s";
local xmlns_s2s_session = "http://prosody.im/streams/s2s";
local response_400 = { status = "400 Bad Request", body = "<h1>Bad Request</h1>Sorry, we didn't understand your request :(" };
local response_403 = { status = "403 Forbidden", body = "<h1>Forbidden</h1>You don't have permission to view the contents of this directory :(" };
local response_404 = { status = "404 Not Found", body = "<h1>Page Not Found</h1>Sorry, we couldn't find what you were looking for :(" };
local mime_map = {
html = "text/html";
xml = "text/xml";
js = "text/javascript";
css = "text/css";
};
local idmap = {};
function add_client(session)
local name = session.full_jid;
local id = idmap[name];
if not id then
id = uuid_generate();
idmap[name] = id;
end
local item = stanza.stanza("item", { id = id }):tag("session", {xmlns = xmlns_c2s_session, jid = name}):up();
if session.secure then
item:tag("encrypted"):up();
end
if session.compressed then
item:tag("compressed"):up();
end
hosts[service].modules.pubsub.service:publish(xmlns_c2s_session, service, id, item);
module:log("debug", "Added client " .. name);
end
function del_client(session)
local name = session.full_jid;
local id = idmap[name];
if id then
local notifier = stanza.stanza("retract", { id = id });
hosts[service].modules.pubsub.service:retract(xmlns_c2s_session, service, id, notifier);
end
end
function add_host(session, type)
local name = (type == "out" and session.to_host) or (type == "in" and session.from_host);
local id = idmap[name.."_"..type];
if not id then
id = uuid_generate();
idmap[name.."_"..type] = id;
end
local item = stanza.stanza("item", { id = id }):tag("session", {xmlns = xmlns_s2s_session, jid = name})
:tag(type):up();
if session.secure then
item:tag("encrypted"):up();
end
if session.compressed then
item:tag("compressed"):up();
end
hosts[service].modules.pubsub.service:publish(xmlns_s2s_session, service, id, item);
module:log("debug", "Added host " .. name .. " s2s" .. type);
end
function del_host(session, type)
local name = (type == "out" and session.to_host) or (type == "in" and session.from_host);
local id = idmap[name.."_"..type];
if id then
local notifier = stanza.stanza("retract", { id = id });
hosts[service].modules.pubsub.service:retract(xmlns_s2s_session, service, id, notifier);
end
end
local function preprocess_path(path)
if path:sub(1,1) ~= "/" then
path = "/"..path;
end
local level = 0;
for component in path:gmatch("([^/]+)/") do
if component == ".." then
level = level - 1;
elseif component ~= "." then
level = level + 1;
end
if level < 0 then
return nil;
end
end
return path;
end
function serve_file(path)
local full_path = http_base..path;
if stat(full_path, "mode") == "directory" then
if stat(full_path.."/index.html", "mode") == "file" then
return serve_file(path.."/index.html");
end
return response_403;
end
local f, err = open(full_path, "rb");
if not f then return response_404; end
local data = f:read("*a");
data = data:gsub("%%PUBSUBHOST%%", service);
f:close();
if not data then
return response_403;
end
local ext = path:match("%.([^.]*)$");
local mime = mime_map[ext]; -- Content-Type should be nil when not known
return {
headers = { ["Content-Type"] = mime; };
body = data;
};
end
local function handle_file_request(method, body, request)
local path = preprocess_path(request.url.path);
if not path then return response_400; end
path = path:gsub("^/[^/]+", ""); -- Strip /admin/
return serve_file(path);
end
function module.load()
local http_conf = config.get("*", "core", "webadmin_http_ports");
httpserver.new_from_config(http_conf, handle_file_request, { base = "admin" });
end
prosody.events.add_handler("server-started", function ()
local host_session = prosody.hosts[host];
if not select(2, hosts[service].modules.pubsub.service:get_nodes(service))[xmlns_s2s_session] then
local ok, errmsg = hosts[service].modules.pubsub.service:create(xmlns_s2s_session, service);
if not ok then
module:log("warn", "Could not create node " .. xmlns_s2s_session .. ": " .. tostring(errmsg));
end
end
for remotehost, session in pairs(host_session.s2sout) do
if session.type ~= "s2sout_unauthed" then
add_host(session, "out");
end
end
for session in pairs(incoming_s2s) do
if session.to_host == host then
add_host(session, "in");
end
end
if not select(2, hosts[service].modules.pubsub.service:get_nodes(service))[xmlns_c2s_session] then
local ok, errmsg = hosts[service].modules.pubsub.service:create(xmlns_c2s_session, service);
if not ok then
module:log("warn", "Could not create node " .. xmlns_c2s_session .. ": " .. tostring(errmsg));
end
end
for username, user in pairs(host_session.sessions or {}) do
for resource, session in pairs(user.sessions or {}) do
add_client(session);
end
end
end);
module:hook("resource-bind", function(event)
add_client(event.session);
end);
module:hook("resource-unbind", function(event)
del_client(event.session);
end);
module:hook("s2sout-established", function(event)
add_host(event.session, "out");
end);
module:hook("s2sin-established", function(event)
add_host(event.session, "in");
end);
module:hook("s2sout-destroyed", function(event)
del_host(event.session, "out");
end);
module:hook("s2sin-destroyed", function(event)
del_host(event.session, "in");
end);
|
mod_admin_web: Fix initialisation code, undeclared variable and wrong event scope
|
mod_admin_web: Fix initialisation code, undeclared variable and wrong event scope
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
6b077afbcbce2e700fae01f5a1d7f4135c34ba51
|
src/cosy/server.lua
|
src/cosy/server.lua
|
local loader = require "cosy.loader"
local hotswap = loader.hotswap
hotswap "cosy.string"
local Server = {}
function Server.get (http)
if http.request.method == "POST"
and http.request.headers.user_agent:match "GitHub-Hookshot/"
and http.request.headers.x_github_event == "push"
and loader.configuration.debug.update then
loader.logger.info {
_ = "github:push",
}
os.execute "git pull --quiet --force"
return
elseif http.request.headers ["upgrade"] == "websocket" then
http () -- send response
return Server.wsloop (http)
elseif http.request.method ~= "GET" then
http.response.status = 405
http.response.message = "Method Not Allowed"
end
assert (http.request.method == "GET")
if http.request.method == "GET"
and http.request.path:sub (-1) == "/" then
http.request.path = http.request.path .. "index.html"
end
local lua_module = http.request.path:match "/lua/(.*)"
if lua_module then
lua_module = lua_module:gsub ("/", ".")
local path = package.searchpath (lua_module, package.path)
if path then
local file = io.open (path, "r")
http.response.status = 200
http.response.message = "OK"
http.response.body = file:read "*all"
file:close ()
return
end
end
local file = io.open ("%{root}/%{path}" % {
root = loader.configuration.www.root._,
path = http.request.path
})
if file then
http.response.status = 200
http.response.message = "OK"
http.response.body = file:read "*all"
file:close ()
return
end
http.response.status = 404
http.response.message = "Not Found"
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
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
function Server.www_dependencies ()
local scheduler = loader.scheduler
scheduler.blocking (false)
local directories = {
loader.configuration.www.root._,
loader.configuration.www.root._ .. "/css",
loader.configuration.www.root._ .. "/font",
loader.configuration.www.root._ .. "/html",
loader.configuration.www.root._ .. "/js",
}
local continue = true
local lfs = loader.hotswap "lfs"
for i = 1, #directories do
local directory = directories [i]
local attributes = lfs.attributes (directory)
if attributes and attributes.mode ~= "directory" then
loader.logger.error {
_ = "directory:not-directory",
directory = directory,
mode = attributes.mode,
}
return
end
if not attributes then
local ok, err = lfs.mkdir (directory)
if ok then
loader.logger.info {
_ = "directory:created",
directory = directory,
}
else
loader.logger.error {
_ = "directory:not-created",
directory = directory,
reason = err,
}
continue = false
end
end
end
if continue then
local request = (loader.hotswap "copas.http").request
for target, source in pairs (loader.configuration.dependencies) do
source = source._
local content, status = request (source)
if math.floor (status / 100) == 2 then
local file = io.open (loader.configuration.www.root._ .. "/" .. target, "w")
file:write (content)
file:close ()
loader.logger.info {
_ = "dependency:success",
source = source,
target = target,
}
else
loader.logger.warning {
_ = "dependency:failure",
source = source,
target = target,
}
end
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.addthread (Server.www_dependencies)
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.info {
_ = "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
hotswap "cosy.string"
local Server = {}
function Server.get (http)
if http.request.method == "POST"
and http.request.headers.user_agent:match "GitHub%-Hookshot/"
and http.request.headers.x_github_event == "push"
and loader.configuration.debug.update._ then
loader.logger.info {
_ = "github:push",
}
os.execute "git pull --quiet --force"
http.response.status = 200
http.response.message = "OK"
return
elseif http.request.headers ["upgrade"] == "websocket" then
http () -- send response
return Server.wsloop (http)
elseif http.request.method ~= "GET" then
http.response.status = 405
http.response.message = "Method Not Allowed"
end
assert (http.request.method == "GET")
if http.request.method == "GET"
and http.request.path:sub (-1) == "/" then
http.request.path = http.request.path .. "index.html"
end
local lua_module = http.request.path:match "/lua/(.*)"
if lua_module then
lua_module = lua_module:gsub ("/", ".")
local path = package.searchpath (lua_module, package.path)
if path then
local file = io.open (path, "r")
http.response.status = 200
http.response.message = "OK"
http.response.body = file:read "*all"
file:close ()
return
end
end
local file = io.open ("%{root}/%{path}" % {
root = loader.configuration.www.root._,
path = http.request.path
})
if file then
http.response.status = 200
http.response.message = "OK"
http.response.body = file:read "*all"
file:close ()
return
end
http.response.status = 404
http.response.message = "Not Found"
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
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
function Server.www_dependencies ()
local scheduler = loader.scheduler
scheduler.blocking (false)
local directories = {
loader.configuration.www.root._,
loader.configuration.www.root._ .. "/css",
loader.configuration.www.root._ .. "/font",
loader.configuration.www.root._ .. "/html",
loader.configuration.www.root._ .. "/js",
}
local continue = true
local lfs = loader.hotswap "lfs"
for i = 1, #directories do
local directory = directories [i]
local attributes = lfs.attributes (directory)
if attributes and attributes.mode ~= "directory" then
loader.logger.error {
_ = "directory:not-directory",
directory = directory,
mode = attributes.mode,
}
return
end
if not attributes then
local ok, err = lfs.mkdir (directory)
if ok then
loader.logger.info {
_ = "directory:created",
directory = directory,
}
else
loader.logger.error {
_ = "directory:not-created",
directory = directory,
reason = err,
}
continue = false
end
end
end
if continue then
local request = (loader.hotswap "copas.http").request
for target, source in pairs (loader.configuration.dependencies) do
source = source._
local content, status = request (source)
if math.floor (status / 100) == 2 then
local file = io.open (loader.configuration.www.root._ .. "/" .. target, "w")
file:write (content)
file:close ()
loader.logger.info {
_ = "dependency:success",
source = source,
target = target,
}
else
loader.logger.warning {
_ = "dependency:failure",
source = source,
target = target,
}
end
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.addthread (Server.www_dependencies)
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.info {
_ = "server:listening",
host = host,
port = port,
}
-- local profiler = require "ProFi"
-- profiler:start ()
scheduler.loop ()
-- profiler:stop ()
-- profiler:writeReport "profiler.txt"
end
|
Fix github hook.
|
Fix github hook.
|
Lua
|
mit
|
CosyVerif/library,CosyVerif/library,CosyVerif/library
|
c48cd9380b80fe5491391e83a76ccedf58ac6b9c
|
minionmaster/minion.lua
|
minionmaster/minion.lua
|
local Unit = require "shared.unit"
local Entity = require "shared.entity"
local state = require "minionmaster.state"
local content = require "minionmaster.content"
local state = require "minionmaster.state"
local Minion = Unit:subclass("Minion")
local function findNearestEnemy(position, range)
local nearest
local minDist = range * range
for id, entity in pairs(state.entityManager.entities) do
if entity.type == "enemy" then
local dist = (entity.position - position):sqLength()
if dist < minDist then
minDist = dist
nearest = entity
end
end
end
return nearest
end
-- speed: pixels/second
function Minion:initialize(entityStatics, master)
Unit.initialize(self, entityStatics, state.player)
self.master = master
-- self:setAnimation("images/minion/frost/attack.png", 0.175)
-- self.attackAnim = self.animation:clone()
-- self:setAnimation("images/minion/frost/walk.png", 0.175)
-- self.walkAnim = self.animation:clone()
self.attack = false
end
function Minion:update(dt)
if not self.target or self.target == self.master or self.target.health <= 0 then
self.target = findNearestEnemy(self.position, self.attackRange) or self.master
end
self:moveTo(self.target.position.x, self.target.position.y, self.target.spriteSize)
Unit.update(self, dt)
local direction = (self.targetPosition - self.position)
local length = direction:length()
if length < self.target.spriteSize then
self.attack = true
if not self.attack then
self:setAnimation("images/minion/frost/attack.png", 0.175)
end
self.target.health = self.target.health - 1
elseif self.attack then
self.attack = false
self:setAnimation("images/minion/frost/walk.png", 0.175)
end
end
function Minion:draw(dt)
love.graphics.setColor(255, 255, 255, 255)
Entity.draw(self, dt)
end
return Minion
|
local Unit = require "shared.unit"
local Entity = require "shared.entity"
local state = require "minionmaster.state"
local content = require "minionmaster.content"
local state = require "minionmaster.state"
local Minion = Unit:subclass("Minion")
local function findNearestEnemy(position, range)
local nearest
local minDist = range * range
for id, entity in pairs(state.entityManager.entities) do
if entity.type == "enemy" then
local dist = (entity.position - position):sqLength()
if dist < minDist then
minDist = dist
nearest = entity
end
end
end
return nearest
end
-- speed: pixels/second
function Minion:initialize(entityStatics, master)
Unit.initialize(self, entityStatics, state.player)
self.master = master
-- self:setAnimation("images/minion/frost/attack.png", 0.175)
-- self.attackAnim = self.animation:clone()
self:setAnimation("images/minion/frost/walk.png", 0.175)
-- self.walkAnim = self.animation:clone()
self.attack = false
end
function Minion:update(dt)
if not self.target or self.target == self.master or self.target.health <= 0 then
self.target = findNearestEnemy(self.position, self.attackRange) or self.master
end
self:moveTo(self.target.position.x, self.target.position.y, self.target.spriteSize)
Unit.update(self, dt)
local direction = (self.targetPosition - self.position)
local length = direction:length()
if length < self.target.spriteSize then
if not self.attack then
self:setAnimation("images/minion/frost/attack.png", 0.175)
self.attack = true
end
self.target.health = self.target.health - 1
elseif self.attack then
self.attack = false
self:setAnimation("images/minion/frost/walk.png", 0.175)
end
end
function Minion:draw(dt)
love.graphics.setColor(255, 255, 255, 255)
Entity.draw(self, dt)
end
return Minion
|
fixed attack animation
|
fixed attack animation
|
Lua
|
mit
|
ExcelF/project-navel
|
dda4fc1a50b95c51110830a7c9d1823421f4d300
|
kong/concurrency.lua
|
kong/concurrency.lua
|
local resty_lock = require "resty.lock"
local ngx_semaphore = require "ngx.semaphore"
local get_phase = ngx.get_phase
local concurrency = {}
-- these must remain for the lifetime of the process
local semaphores = {}
function concurrency.with_worker_mutex(opts, fn)
if type(opts) ~= "table" then
error("opts must be a table", 2)
end
if type(opts.name) ~= "string" then
error("opts.name is required and must be a string", 2)
end
if opts.timeout and type(opts.timeout) ~= "number" then
error("opts.timeout must be a number", 2)
end
local timeout = opts.timeout or 60
local rlock, err = resty_lock:new("kong_locks", {
exptime = timeout,
timeout = timeout,
})
if not rlock then
return nil, "failed to create worker lock: " .. err
end
-- acquire lock
local elapsed, err = rlock:lock(opts.name)
if not elapsed then
if err == "timeout" then
return nil, err
end
return nil, "failed to acquire worker lock: " .. err
end
local pok, ok, err = pcall(fn, elapsed)
if not pok then
err = ok
ok = nil
end
-- release lock
rlock:unlock(opts.name)
return ok, err
end
function concurrency.with_coroutine_mutex(opts, fn)
if type(opts) ~= "table" then
error("opts must be a table", 2)
end
if type(opts.name) ~= "string" then
error("opts.name is required and must be a string", 2)
end
if opts.timeout and type(opts.timeout) ~= "number" then
error("opts.timeout must be a number", 2)
end
if opts.on_timeout and
opts.on_timeout ~= "run_unlocked" and
opts.on_timeout ~= "return_true" then
error("invalid value for opts.on_timeout", 2)
end
if get_phase() == "init_worker" then
return fn()
end
local timeout = opts.timeout or 60
local semaphore = semaphores[opts.name]
-- the following `if` block must not yield:
if not semaphore then
local err
semaphore, err = ngx_semaphore.new()
if err then
kong.log.crit("failed to create ", opts.name, " lock: ", err)
return nil, "critical error"
end
semaphores[opts.name] = semaphore
semaphore:post(1)
end
-- acquire lock
local lok, err = semaphore:wait(timeout)
if not lok then
if err ~= "timeout" then
return nil, "error attempting to acquire " .. opts.name .. " lock: " .. err
end
if opts.on_timeout == "run_unlocked" then
kong.log.warn("bypassing ", opts.name, " lock: timeout")
elseif opts.on_timeout == "return_true" then
return true
else
return nil, "timeout acquiring " .. opts.name .. " lock"
end
end
local pok, ok, err = pcall(fn)
if lok then
-- release lock
semaphore:post(1)
end
if not pok then
return nil, ok
end
return ok, err
end
return concurrency
|
local resty_lock = require "resty.lock"
local ngx_semaphore = require "ngx.semaphore"
local get_phase = ngx.get_phase
local concurrency = {}
-- these must remain for the lifetime of the process
local semaphores = {}
function concurrency.with_worker_mutex(opts, fn)
if type(opts) ~= "table" then
error("opts must be a table", 2)
end
if type(opts.name) ~= "string" then
error("opts.name is required and must be a string", 2)
end
if opts.timeout and type(opts.timeout) ~= "number" then
error("opts.timeout must be a number", 2)
end
local timeout = opts.timeout or 60
local rlock, err = resty_lock:new("kong_locks", {
exptime = timeout,
timeout = timeout,
})
if not rlock then
return nil, "failed to create worker lock: " .. err
end
-- acquire lock
local elapsed, err = rlock:lock(opts.name)
if not elapsed then
if err == "timeout" then
return nil, err
end
return nil, "failed to acquire worker lock: " .. err
end
local pok, ok, err = pcall(fn, elapsed)
if not pok then
err = ok
ok = nil
end
-- release lock
rlock:unlock(opts.name)
return ok, err
end
function concurrency.with_coroutine_mutex(opts, fn)
if type(opts) ~= "table" then
error("opts must be a table", 2)
end
if type(opts.name) ~= "string" then
error("opts.name is required and must be a string", 2)
end
if opts.timeout and type(opts.timeout) ~= "number" then
error("opts.timeout must be a number", 2)
end
if opts.on_timeout and
opts.on_timeout ~= "run_unlocked" and
opts.on_timeout ~= "return_true" then
error("invalid value for opts.on_timeout", 2)
end
if get_phase() == "init_worker" then
return fn()
end
local timeout = opts.timeout or 60
local semaphore = semaphores[opts.name]
-- the following `if` block must not yield:
if not semaphore then
local err
semaphore, err = ngx_semaphore.new()
if err then
return nil, "failed to create " .. opts.name .. " lock: " .. err
end
semaphores[opts.name] = semaphore
semaphore:post(1)
end
-- acquire lock
local lok, err = semaphore:wait(timeout)
if not lok then
if err ~= "timeout" then
return nil, "error attempting to acquire " .. opts.name .. " lock: " .. err
end
if opts.on_timeout == "run_unlocked" then
kong.log.warn("bypassing ", opts.name, " lock: timeout")
elseif opts.on_timeout == "return_true" then
return true
else
return nil, "timeout acquiring " .. opts.name .. " lock"
end
end
local pok, ok, err = pcall(fn)
if lok then
-- release lock
semaphore:post(1)
end
if not pok then
return nil, ok
end
return ok, err
end
return concurrency
|
fix(concurrency) return error on failure to instantiate semaphore
|
fix(concurrency) return error on failure to instantiate semaphore
Callers of this module should be given the choice as to how to handle
the error. They should also have visibility into what the error was.
As of this patch, the only user of this function is already logging
failures with the appropriate logging level, so this path would create
duplicated logs.
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Mashape/kong,Kong/kong
|
c11cce2d3b32198618bc74957beaaa8ef34a0373
|
src/xenia/ui/vulkan/premake5.lua
|
src/xenia/ui/vulkan/premake5.lua
|
project_root = "../../../.."
include(project_root.."/tools/build")
group("src")
project("xenia-ui-vulkan")
uuid("4933d81e-1c2c-4d5d-b104-3c0eb9dc2f00")
kind("StaticLib")
language("C++")
links({
"xenia-base",
"xenia-ui",
"xenia-ui-spirv",
})
defines({
})
includedirs({
project_root.."/third_party/gflags/src",
project_root.."/third_party/vulkan/",
})
local_platform_files()
files({
"shaders/bin/*.h",
})
removefiles({"*_demo.cc"})
group("demos")
project("xenia-ui-window-vulkan-demo")
uuid("97598f13-3177-454c-8e58-c59e2b6ede27")
kind("WindowedApp")
language("C++")
links({
"gflags",
"imgui",
"volk",
"xenia-base",
"xenia-ui",
"xenia-ui-spirv",
"xenia-ui-vulkan",
})
flags({
"WinMain", -- Use WinMain instead of main.
})
defines({
})
includedirs({
project_root.."/third_party/gflags/src",
project_root.."/third_party/vulkan/",
})
files({
"../window_demo.cc",
"vulkan_window_demo.cc",
project_root.."/src/xenia/base/main_"..platform_suffix..".cc",
})
resincludedirs({
project_root,
})
|
project_root = "../../../.."
include(project_root.."/tools/build")
group("src")
project("xenia-ui-vulkan")
uuid("4933d81e-1c2c-4d5d-b104-3c0eb9dc2f00")
kind("StaticLib")
language("C++")
links({
"xenia-base",
"xenia-ui",
"xenia-ui-spirv",
})
defines({
})
includedirs({
project_root.."/third_party/gflags/src",
project_root.."/third_party/vulkan/",
})
local_platform_files()
files({
"shaders/bin/*.h",
})
removefiles({"*_demo.cc"})
group("demos")
project("xenia-ui-window-vulkan-demo")
uuid("97598f13-3177-454c-8e58-c59e2b6ede27")
kind("WindowedApp")
language("C++")
links({
"gflags",
"imgui",
"volk",
"xenia-base",
"xenia-ui",
"xenia-ui-spirv",
"xenia-ui-vulkan",
})
flags({
"WinMain", -- Use WinMain instead of main.
})
defines({
})
includedirs({
project_root.."/third_party/gflags/src",
project_root.."/third_party/vulkan/",
})
files({
"../window_demo.cc",
"vulkan_window_demo.cc",
project_root.."/src/xenia/base/main_"..platform_suffix..".cc",
})
resincludedirs({
project_root,
})
filter("platforms:Linux")
links({
"X11",
"xcb",
"X11-xcb",
"GL",
"vulkan",
})
|
Oops. Fix premake for xenia-ui-window-vulkan-demo.
|
Oops. Fix premake for xenia-ui-window-vulkan-demo.
|
Lua
|
bsd-3-clause
|
sephiroth99/xenia,sephiroth99/xenia,sephiroth99/xenia
|
a7c30b41afb796492db5861fe0bca0e4799b64d6
|
lib/acid/cluster.lua
|
lib/acid/cluster.lua
|
local acid_paxos = require( "acid.paxos" )
local paxoshelper = require( "acid.paxoshelper" )
local paxosserver = require( "acid.paxosserver" )
local _M = {
_VERSION="0.1",
dead_wait = 60*20,
dead_timeout = 86400,
admin_lease = 60*2,
max_dead = 4,
_dead = {},
}
local _mt = { __index = _M }
local function _true() return true, nil, nil end
function _M.new(impl, opt)
opt = opt or {}
local cluster = {
impl = impl,
dead_wait = opt.dead_wait,
dead_timeout = opt.dead_timeout,
admin_lease = opt.admin_lease,
max_dead = opt.max_dead,
}
setmetatable( cluster, _mt )
assert( cluster.admin_lease > 4, "lease must be long enough: > 4" )
cluster.repair_timeout = math.floor(cluster.admin_lease / 2)
cluster.server = paxosserver.new(impl, {
handlers = opt.handlers,
})
return cluster
end
function _M:member_check(member_id)
local paxos, err, errmes = acid_paxos.new(member_id, self.impl)
if err then
paxos:logerr("new paxos error:", err, errmes)
return nil, err, errmes
end
local _, err, errmes = self:data_check(paxos)
if err then
return nil, err, errmes
end
local rst, err, errmes = paxoshelper.get_or_elect_leader(paxos, self.admin_lease)
if err then
paxos:logerr( "get_or_elect_leader:", err, errmes, paxos.member_id )
-- Incomplete view change might cause it to be unable to form a quorum
-- in either previous or next view, thus it stalls leader election.
--
-- Push view to consistent state by finishing unfinished view change.
local _, err, errmes = paxoshelper.change_view( paxos, {} )
if err then
paxos:logerr( "change_view with {}:", err, errmes )
end
return
end
local leader = rst.val
-- start to track version change. if version changed, paxos stops any write
-- operation.
paxos.ver = rst.ver
if leader.ident == member_id.ident then
if self:extend_lease(paxos, leader) then
local _, err, errmes = paxos.impl:wait_run(
self.repair_timeout*0.9,
self.repair_cluster, self, paxos)
if err then
paxos:logerr( 'repair_cluster', paxos.member_id, err, errmes )
end
end
end
end
function _M:data_check(paxos)
-- For leader or not:
-- Local storage checking does not require version tracking for paxos.
--
-- If it is not a member of any view, it is definitely correct to destory
-- this member with all data removed.
--
-- Race condition happens if:
--
-- While new version of view has this member and someone else has been
-- initiating this member.
--
-- While timer triggered routine has been removing data of this
-- member.
--
-- But it does not matter. Data will be re-built in next checking.
local _mem, err, errmes = paxos:local_get_mem()
if err then
paxos:logerr("local_get_mem err:", err, errmes)
return nil, err, errmes
end
if _mem.val ~= nil then
self.impl:restore(paxos, _mem.val)
return
end
paxos:logerr("i am no longer a member of cluster:", paxos.member_id)
local _, err, errmes = self.impl:destory(paxos)
if err then
paxos:logerr("destory err:", err, errmes)
else
local acc, err, errmes = paxos:new_acceptor()
if err then
return nil, err, errmes
end
local rst, err, errmes = acc:destory(_mem.ver)
paxos:logerr("after destory acceptor:", rst, err, errmes)
end
end
function _M:extend_lease(paxos, leader)
if leader.__lease < self.repair_timeout then
local rst, err, errmes = paxoshelper.elect_leader(paxos, self.admin_lease)
if err then
paxos:logerr( "failure extend lease:", leader )
return nil, err, errmes
end
end
return true, nil, nil
end
function _M:repair_cluster(paxos)
local dead_members, err, errmes = self:find_dead(paxos)
if err then
return nil, err, errmes
end
local nr_dead = #dead_members
if nr_dead > 0 then
paxos:logerr( "dead members confirmed:", dead_members )
end
if nr_dead > self.max_dead then
paxos:logerr( nr_dead, " members down, too many, can not repair" )
return
end
for _, _m in ipairs( dead_members ) do
local ident, member = _m[1], _m[2]
self:replace_dead( paxos, ident, member )
-- fix only one each time
return
end
end
function _M:find_dead(paxos)
local _members, err, errmes = paxos:local_get_members()
if err then
return nil, err, errmes
end
local dead_members = {}
for ident, member in pairs(_members.val) do
if self:is_confirmed_dead(paxos, ident, member) then
table.insert( dead_members, { ident, member } )
end
end
return dead_members, nil, nil
end
function _M:is_confirmed_dead(paxos, ident, member)
local cluster_id = paxos.member_id.cluster_id
if self:is_member_alive(paxos, ident) then
self:record_dead(cluster_id, ident, nil)
return false
end
paxos:logerr("dead detected:", ident, member)
local now = paxos.impl:time()
local dead_time = self:record_dead(cluster_id, ident, now)
if dead_time > self.dead_wait then
return true
end
return false
end
function _M:replace_dead(paxos, dead_ident, dead_mem)
local _members, err, errmes = paxos:local_get_members()
if err then
return nil, err, errmes
end
local new_mem, err, errmes = self.impl:new_member(paxos, dead_ident, _members.val )
if err then
return nil, err, errmes
end
local changes = {
add = new_mem,
del = { [dead_ident]=dead_mem },
}
local rst, err, errmes = paxoshelper.change_view( paxos, changes )
paxos:logerr( "view changed: ", rst, err, errmes )
return rst, err, errmes
end
function _M:record_dead(cluster_id, ident, time)
local cd = self._dead
cd[cluster_id] = cd[cluster_id] or {}
local d = cd[cluster_id]
if time == nil then
d[ident] = nil
return nil
end
local prev = d[ident] or time
-- Discard record that is too old, which might be caused by leader
-- switching
if prev < time - self.dead_timeout then
d[ident] = nil
end
d[ident] = d[ident] or time
return time - d[ident]
end
function _M:is_member_alive(paxos, ident)
local rst, err, errmes = paxos:send_req(ident, { cmd = "isalive", })
return (err == nil and rst.err == nil), nil, nil
end
return _M
|
local acid_paxos = require( "acid.paxos" )
local paxoshelper = require( "acid.paxoshelper" )
local paxosserver = require( "acid.paxosserver" )
local _M = {
_VERSION="0.1",
dead_wait = 60*20,
dead_timeout = 86400,
admin_lease = 60*2,
max_dead = 4,
_dead = {},
}
local _mt = { __index = _M }
function _M.new(impl, opt)
opt = opt or {}
local cluster = {
impl = impl,
dead_wait = opt.dead_wait,
dead_timeout = opt.dead_timeout,
admin_lease = opt.admin_lease,
max_dead = opt.max_dead,
}
setmetatable( cluster, _mt )
assert( cluster.admin_lease > 4, "lease must be long enough: > 4" )
cluster.repair_timeout = math.floor(cluster.admin_lease / 2)
cluster.server = paxosserver.new(impl, {
handlers = opt.handlers,
})
return cluster
end
function _M:member_check(member_id)
local paxos, err, errmes = acid_paxos.new(member_id, self.impl)
if err then
paxos:logerr("new paxos error:", err, errmes)
return nil, err, errmes
end
local _, err, errmes = self:data_check(paxos)
if err then
return nil, err, errmes
end
local rst, err, errmes = paxoshelper.get_or_elect_leader(paxos, self.admin_lease)
if err then
paxos:logerr( "get_or_elect_leader:", err, errmes, paxos.member_id )
-- Incomplete view change might cause it to be unable to form a quorum
-- in either previous or next view, thus it stalls leader election.
--
-- Push view to consistent state by finishing unfinished view change.
local _, err, errmes = paxoshelper.change_view( paxos, {} )
if err then
paxos:logerr( "change_view with {}:", err, errmes )
end
return
end
local leader = rst.val
-- start to track version change. if version changed, paxos stops any write
-- operation.
paxos.ver = rst.ver
if leader.ident == member_id.ident then
if self:extend_lease(paxos, leader) then
local _, err, errmes = paxos.impl:wait_run(
self.repair_timeout*0.9,
self.repair_cluster, self, paxos)
if err then
paxos:logerr( 'repair_cluster', paxos.member_id, err, errmes )
end
end
end
end
function _M:data_check(paxos)
-- For leader or not:
-- Local storage checking does not require version tracking for paxos.
--
-- If it is not a member of any view, it is definitely correct to destory
-- this member with all data removed.
--
-- Race condition happens if:
--
-- While new version of view has this member and someone else has been
-- initiating this member.
--
-- While timer triggered routine has been removing data of this
-- member.
--
-- But it does not matter. Data will be re-built in next checking.
local _mem, err, errmes = paxos:local_get_mem()
if err then
paxos:logerr("local_get_mem err:", err, errmes)
return nil, err, errmes
end
if _mem.val ~= nil then
self.impl:restore(paxos, _mem.val)
return
end
paxos:logerr("i am no longer a member of cluster:", paxos.member_id)
local _, err, errmes = self.impl:destory(paxos)
if err then
paxos:logerr("destory err:", err, errmes)
else
local acc, err, errmes = paxos:new_acceptor()
if err then
return nil, err, errmes
end
local rst, err, errmes = acc:destory(_mem.ver)
paxos:logerr("after destory acceptor:", rst, err, errmes)
end
end
function _M:extend_lease(paxos, leader)
if leader.__lease < self.repair_timeout then
local rst, err, errmes = paxoshelper.elect_leader(paxos, self.admin_lease)
if err then
paxos:logerr( "failure extend lease:", leader )
return nil, err, errmes
end
end
return true, nil, nil
end
function _M:repair_cluster(paxos)
local dead_members, err, errmes = self:find_dead(paxos)
if err then
return nil, err, errmes
end
local nr_dead = #dead_members
if nr_dead > 0 then
paxos:logerr( "dead members confirmed:", dead_members )
end
if nr_dead > self.max_dead then
paxos:logerr( nr_dead, " members down, too many, can not repair" )
return
end
for _, _m in ipairs( dead_members ) do
local ident, member = _m[1], _m[2]
self:replace_dead( paxos, ident, member )
-- fix only one each time
return
end
end
function _M:find_dead(paxos)
local _members, err, errmes = paxos:local_get_members()
if err then
return nil, err, errmes
end
local dead_members = {}
for ident, member in pairs(_members.val) do
if self:is_confirmed_dead(paxos, ident, member) then
table.insert( dead_members, { ident, member } )
end
end
return dead_members, nil, nil
end
function _M:is_confirmed_dead(paxos, ident, member)
local cluster_id = paxos.member_id.cluster_id
if self:is_member_alive(paxos, ident) then
self:record_dead(cluster_id, ident, nil)
return false
end
paxos:logerr("dead detected:", ident, member)
local now = paxos.impl:time()
local dead_time = self:record_dead(cluster_id, ident, now)
if dead_time > self.dead_wait then
return true
end
return false
end
function _M:replace_dead(paxos, dead_ident, dead_mem)
local _members, err, errmes = paxos:local_get_members()
if err then
return nil, err, errmes
end
local new_mem, err, errmes = self.impl:new_member(paxos, dead_ident, _members.val )
if err then
return nil, err, errmes
end
local changes = {
add = new_mem,
del = { [dead_ident]=dead_mem },
}
local rst, err, errmes = paxoshelper.change_view( paxos, changes )
paxos:logerr( "view changed: ", rst, err, errmes )
return rst, err, errmes
end
function _M:record_dead(cluster_id, ident, time)
local cd = self._dead
cd[cluster_id] = cd[cluster_id] or {}
local d = cd[cluster_id]
if time == nil then
d[ident] = nil
return nil
end
local prev = d[ident] or time
-- Discard record that is too old, which might be caused by leader
-- switching
if prev < time - self.dead_timeout then
d[ident] = nil
end
d[ident] = d[ident] or time
return time - d[ident]
end
function _M:is_member_alive(paxos, ident)
local rst, err, errmes = paxos:send_req(ident, { cmd = "isalive", })
return (err == nil and rst.err == nil), nil, nil
end
return _M
|
fixup
|
fixup
|
Lua
|
mit
|
baishancloud/lua-acid,baishancloud/lua-acid,baishancloud/lua-acid
|
92f1645146c22699f4e2b567451f87fb0dbf2fc6
|
xmake/modules/detect/tools/find_vswhere.lua
|
xmake/modules/detect/tools/find_vswhere.lua
|
--!A cross-platform build utility based on Lua
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2018, TBOOX Open Source Group.
--
-- @author ruki
-- @file find_vswhere.lua
--
-- imports
import("lib.detect.find_program")
import("lib.detect.find_programver")
-- find vswhere
--
-- @param opt the argument options, .e.g {version = true, program = "c:\xxx\vswhere.exe"}
--
-- @return program, version
--
-- @code
--
-- local vswhere = find_vswhere()
-- local vswhere, version = find_vswhere({version = true})
-- local vswhere, version = find_vswhere({version = true, program = "c:\xxx\vswhere.exe"})
--
-- @endcode
--
function main(opt)
-- not on windows?
if not is_host("windows") then
return
end
-- init options
opt = opt or {}
-- find program
opt.pathes = opt.pathes or
{
path.join(os.getenv("ProgramFiles(x86)"), "Microsoft Visual Studio", "Installer", "vswhere.exe"),
path.join(os.getenv("ProgramFiles"), "Microsoft Visual Studio", "Installer", "vswhere.exe"),
}
local program = find_program(opt.program or "vswhere.exe", opt)
-- find program version
local version = nil
if program and opt and opt.version then
version = find_programver(program, opt)
end
-- ok?
return program, version
end
|
--!A cross-platform build utility based on Lua
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2018, TBOOX Open Source Group.
--
-- @author ruki
-- @file find_vswhere.lua
--
-- imports
import("lib.detect.find_program")
import("lib.detect.find_programver")
-- find vswhere
--
-- @param opt the argument options, .e.g {version = true, program = "c:\xxx\vswhere.exe"}
--
-- @return program, version
--
-- @code
--
-- local vswhere = find_vswhere()
-- local vswhere, version = find_vswhere({version = true})
-- local vswhere, version = find_vswhere({version = true, program = "c:\xxx\vswhere.exe"})
--
-- @endcode
--
function main(opt)
-- not on windows?
if not is_host("windows") then
return
end
-- init options
opt = opt or {}
-- find program
opt.check = "-?"
opt.command = "-?"
opt.pathes = opt.pathes or
{
path.join(os.getenv("ProgramFiles(x86)"), "Microsoft Visual Studio", "Installer", "vswhere.exe"),
path.join(os.getenv("ProgramFiles"), "Microsoft Visual Studio", "Installer", "vswhere.exe"),
}
local program = find_program(opt.program or "vswhere.exe", opt)
-- find program version
local version = nil
if program and opt and opt.version then
version = find_programver(program, opt)
end
-- ok?
return program, version
end
|
fix `vswhere` detection in find_vswhere
|
fix `vswhere` detection in find_vswhere
|
Lua
|
apache-2.0
|
waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake
|
2199da1713e658126d0611f72b146ef9eed263ff
|
frontend/ui/widget/filechooser.lua
|
frontend/ui/widget/filechooser.lua
|
local lfs = require("libs/libkoreader-lfs")
local Menu = require("ui/widget/menu")
local Screen = require("ui/screen")
local UIManager = require("ui/uimanager")
local DEBUG = require("dbg")
local util = require("ffi/util")
local ffi = require("ffi")
ffi.cdef[[
int strcoll (char *str1, char *str2);
]]
-- string sort function respecting LC_COLLATE
local function strcoll(str1, str2)
return ffi.C.strcoll(ffi.cast("char*", str1), ffi.cast("char*", str2)) <= 0
end
local FileChooser = Menu:extend{
height = Screen:getHeight(),
width = Screen:getWidth(),
no_title = true,
path = lfs.currentdir(),
parent = nil,
show_hidden = nil,
show_filesize = DSHOWFILESIZE,
filter = function(filename) return true end,
}
function FileChooser:init()
self.item_table = self:genItemTableFromPath(self.path)
Menu.init(self) -- call parent's init()
end
function FileChooser:genItemTableFromPath(path)
local dirs = {}
local files = {}
-- lfs.dir directory without permission will give error
if pcall(lfs.dir, self.path) then
for f in lfs.dir(self.path) do
if self.show_hidden or not string.match(f, "^%.[^.]") then
local filename = self.path.."/"..f
local filemode = lfs.attributes(filename, "mode")
if filemode == "directory" and f ~= "." and f~=".." then
if self.dir_filter(filename) then
table.insert(dirs, f)
end
elseif filemode == "file" then
if self.file_filter(filename) then
table.insert(files, f)
end
end
end
end
end
table.sort(dirs, strcoll)
if path ~= "/" then table.insert(dirs, 1, "..") end
table.sort(files, strcoll)
local item_table = {}
for _, dir in ipairs(dirs) do
table.insert(item_table, { text = dir.."/", path = self.path.."/"..dir })
end
for _, file in ipairs(files) do
local full_path = self.path.."/"..file
if self.show_filesize then
local sstr = string.format("%4.1fM",lfs.attributes(full_path, "size")/1024/1024)
table.insert(item_table, { text = file, mandatory = sstr, path = full_path })
else
table.insert(item_table, { text = file, path = full_path })
end
end
return item_table
end
function FileChooser:changeToPath(path)
path = util.realpath(path)
self.path = path
self:refreshPath()
end
function FileChooser:refreshPath()
self:swithItemTable(nil, self:genItemTableFromPath(self.path))
end
function FileChooser:toggleHiddenFiles()
self.show_hidden = not self.show_hidden
self:swithItemTable(nil, self:genItemTableFromPath(self.path))
end
function FileChooser:onMenuSelect(item)
-- parent directory of dir without permission get nil mode
-- we need to change to parent path in this case
if lfs.attributes(item.path, "mode") == "file" then
self:onFileSelect(item.path)
else
self:changeToPath(item.path)
end
return true
end
function FileChooser:onMenuHold(item)
self:onFileHold(item.path)
return true
end
function FileChooser:onFileSelect(file)
UIManager:close(self)
return true
end
function FileChooser:onFileHold(file)
return true
end
return FileChooser
|
local lfs = require("libs/libkoreader-lfs")
local UIManager = require("ui/uimanager")
local Menu = require("ui/widget/menu")
local Screen = require("ui/screen")
local Device = require("ui/device")
local util = require("ffi/util")
local DEBUG = require("dbg")
local ffi = require("ffi")
ffi.cdef[[
int strcoll (char *str1, char *str2);
]]
-- string sort function respecting LC_COLLATE
local function strcoll(str1, str2)
return ffi.C.strcoll(ffi.cast("char*", str1), ffi.cast("char*", str2)) <= 0
end
local FileChooser = Menu:extend{
height = Screen:getHeight(),
width = Screen:getWidth(),
no_title = true,
path = lfs.currentdir(),
parent = nil,
show_hidden = nil,
show_filesize = DSHOWFILESIZE,
filter = function(filename) return true end,
collate = strcoll,
}
function FileChooser:init()
-- disable string collating in Kobo devices. See issue koreader/koreader#686
if Device:isKobo() then self.collate = nil end
self.item_table = self:genItemTableFromPath(self.path)
Menu.init(self) -- call parent's init()
end
function FileChooser:genItemTableFromPath(path)
local dirs = {}
local files = {}
-- lfs.dir directory without permission will give error
if pcall(lfs.dir, self.path) then
for f in lfs.dir(self.path) do
if self.show_hidden or not string.match(f, "^%.[^.]") then
local filename = self.path.."/"..f
local filemode = lfs.attributes(filename, "mode")
if filemode == "directory" and f ~= "." and f~=".." then
if self.dir_filter(filename) then
table.insert(dirs, f)
end
elseif filemode == "file" then
if self.file_filter(filename) then
table.insert(files, f)
end
end
end
end
end
table.sort(dirs, self.collate)
if path ~= "/" then table.insert(dirs, 1, "..") end
table.sort(files, self.collate)
local item_table = {}
for _, dir in ipairs(dirs) do
table.insert(item_table, { text = dir.."/", path = self.path.."/"..dir })
end
for _, file in ipairs(files) do
local full_path = self.path.."/"..file
if self.show_filesize then
local sstr = string.format("%4.1fM",lfs.attributes(full_path, "size")/1024/1024)
table.insert(item_table, { text = file, mandatory = sstr, path = full_path })
else
table.insert(item_table, { text = file, path = full_path })
end
end
return item_table
end
function FileChooser:changeToPath(path)
path = util.realpath(path)
self.path = path
self:refreshPath()
end
function FileChooser:refreshPath()
self:swithItemTable(nil, self:genItemTableFromPath(self.path))
end
function FileChooser:toggleHiddenFiles()
self.show_hidden = not self.show_hidden
self:swithItemTable(nil, self:genItemTableFromPath(self.path))
end
function FileChooser:onMenuSelect(item)
-- parent directory of dir without permission get nil mode
-- we need to change to parent path in this case
if lfs.attributes(item.path, "mode") == "file" then
self:onFileSelect(item.path)
else
self:changeToPath(item.path)
end
return true
end
function FileChooser:onMenuHold(item)
self:onFileHold(item.path)
return true
end
function FileChooser:onFileSelect(file)
UIManager:close(self)
return true
end
function FileChooser:onFileHold(file)
return true
end
return FileChooser
|
disable string collating in Kobo devices This should fix #686.
|
disable string collating in Kobo devices
This should fix #686.
|
Lua
|
agpl-3.0
|
NickSavage/koreader,mwoz123/koreader,Frenzie/koreader,NiLuJe/koreader,koreader/koreader,noname007/koreader,Hzj-jie/koreader,lgeek/koreader,ashang/koreader,NiLuJe/koreader,chrox/koreader,poire-z/koreader,apletnev/koreader,houqp/koreader,mihailim/koreader,frankyifei/koreader,poire-z/koreader,chihyang/koreader,Markismus/koreader,ashhher3/koreader,koreader/koreader,Frenzie/koreader,robert00s/koreader,pazos/koreader
|
8c8a9c0cf8180ba8b766f06b5937c45a824c511a
|
shared/cm/config.lua
|
shared/cm/config.lua
|
-- This is a partly implemented next step in the channel manager to
-- make an object which can load and save a configuration file so that
-- we don't need to edit the source code of the channel manager to show
-- the configuration directory.
-- We're using some fancy parts of Lua called metatables which give us
-- the hooks to do object orientated programming in Lua.
if not cm then cm = {} end
if not cm.config then cm.config = {} end
local function ConfigName()
return iguana.workingDir()..'/IguanaRepo.cfg'
end
local function DefaultRepoLocation()
if os.isWindows() then
return "C:/iguana-web-apps/"
else
return "~/iguana-web-apps/"
end
end
local function ConfigDefault()
return {repo={DefaultRepoLocation()}}
end
local method = {}
local meta={__index=method}
function method.load(S)
local Name = ConfigName()
if not os.fs.access(Name) then
S.config = ConfigDefault()
return
end
local Json = os.fs.readFile(Name)
if #Json == 0 then
S.config = ConfigDefault();
return
end
S.config = json.parse{data=Json}
end
function method.addRepo(S, Name, Path)
S.config.repo[#S.config.locations+1] = {name=Name, path=Path}
end
function method.save(S)
local Content = json.serialize{data=S.config}
os.fs.writeFile(ConfigName(), Content)
end
function method.clear(S)
S.config.locations = {}
end
function method.repoList(S)
if not S.config.locations then
S.config.locations = {}
end
local Result = S.config.locations
if(S.config.repo)then
for i=1, #S.config.repo do
local Temp = {}
Temp.Name = ""
Temp.Dir = os.fs.name.toNative(S.config.repo[i])
Result.locations[i + #S.config.locations] = Temp
end
end
return S.config.locations
end
function cm.config.open()
local T = {}
setmetatable(T, meta)
T:load()
return T
end
|
-- This is a partly implemented next step in the channel manager to
-- make an object which can load and save a configuration file so that
-- we don't need to edit the source code of the channel manager to show
-- the configuration directory.
-- We're using some fancy parts of Lua called metatables which give us
-- the hooks to do object orientated programming in Lua.
if not cm then cm = {} end
if not cm.config then cm.config = {} end
local function ConfigName()
return iguana.workingDir()..'/IguanaRepo.cfg'
end
local function DefaultRepoLocation()
if os.isWindows() then
return "C:/iguana-web-apps/"
else
return "~/iguana-web-apps/"
end
end
local function ConfigDefault()
return {repo={DefaultRepoLocation()}}
end
local method = {}
local meta={__index=method}
local function ConvertOldFormat(S)
if(S.config.repo)then
for i=1, #S.config.repo do
local Temp = {}
Temp.Name = "Repository "..i
Temp.Dir = os.fs.name.toNative(S.config.repo[i])
S.config.locations[#S.config.locations +1] = Temp
end
S.config.repo = nil
end
return S
end
function method.load(S)
local Name = ConfigName()
if not os.fs.access(Name) then
S.config = ConfigDefault()
return
end
local Json = os.fs.readFile(Name)
if #Json == 0 then
S.config = ConfigDefault();
return
end
S.config = json.parse{data=Json}
if not S.config.locations then
S.config.locations = {}
end
ConvertOldFormat(S)
end
function method.addRepo(S, Name, Path)
S.config.repo[#S.config.locations+1] = {name=Name, path=Path}
end
function method.save(S)
local Content = json.serialize{data=S.config}
os.fs.writeFile(ConfigName(), Content)
end
function method.clear(S)
S.config.locations = {}
end
function method.repoList(S)
return S.config.locations
end
function cm.config.open()
local T = {}
setmetatable(T, meta)
T:load()
return T
end
|
Fixed up readng old config file.
|
Fixed up readng old config file.
|
Lua
|
mit
|
interfaceware/iguana-web-apps,interfaceware/iguana-web-apps
|
eb93614df762f4650ad6677d05d6552a401c4a68
|
site/api/compose.lua
|
site/api/compose.lua
|
--[[
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
-- This is compose.lua - a script for sending replies or new topics to lists
local JSON = require 'cjson'
local elastic = require 'lib/elastic'
local user = require 'lib/user'
local config = require 'lib/config'
local smtp = require 'socket.smtp'
local cross = require 'lib/cross'
function handle(r)
local account = user.get(r)
cross.contentType(r, "application/json")
-- make sure the user is logged in
if account and account.cid then
-- parse response, up to 1MB of it. if >1MB, we're gonna pretend we never saw anything ;)
local post = r:parsebody(1024*1024)
-- check that recipient, subject and body exists
if post.to and post.subject and post.body then
-- validate recipient
local to = ("<%s>"):format(post.to)
local fp, lp = post.to:match("([^@]+)@([^@]+)")
local domainIsOkay = false
-- check that recipient is whitelisted in config.lua
if type(config.accepted_domains) == "string" then
if r.strcmp_match(lp, config.accepted_domains) or config.accepted_domains == "*" then
domainIsOkay = true
end
elseif type(config.accepted_domains) == "table" then
for k, ad in pairs(config.accepted_domains) do
if r.strcmp_match(lp, ad) or ad == "*" then
domainIsOkay = true
break
end
end
end
-- if we can send, then...
if domainIsOkay then
-- find user's full name
local fname = nil
if account.preferences then
fname = account.preferences.fullname
end
-- construct sender name+address
local fr = ([["%s"<%s>]]):format(fname or account.credentials.fullname, account.credentials.email)
-- Using alt email??
if account.credentials.altemail and post.alt then
for k, v in pairs(account.credentials.altemail) do
if v.email == post.alt then
fr = ([["%s"<%s>]]):format(fname or account.credentials.fullname, v.email)
break
end
end
end
-- standard headers + headers we need ourselves for parsing in the archiver (notifications etc)
local headers = {
['X-PonyMail-Sender'] = r:sha1(account.cid),
['X-PonyMail-Agent'] = "PonyMail Composer/0.2",
['message-id'] = ("<pony-%s-%s@%s>"):format(r:sha1(account.cid), r:sha1(r:clock() .. os.time() .. r.useragent_ip), post.to:gsub("@", ".")),
to = to,
subject = post.subject,
from = fr,
}
-- set references and IRT if need be
if post['references'] then
headers['references'] = post['references']
end
if post['in-reply-to'] then
headers['in-reply-to'] = post['in-reply-to']
end
local msgbody = post.body
-- set an email footer if specified in config.lua
if config.email_footer then
local subs = {
list = to:gsub("[<>]", ""),
domain = r.hostname,
port = r.port,
msgid = headers['message-id']
}
msgbody = msgbody .. "\n" .. config.email_footer:gsub("$([a-z]+)", function(a) return subs[a] or a end)
end
-- construct the smtp object
local source = smtp.message{
headers = headers,
body = msgbody
}
-- send email!
local rv, er = smtp.send{
from = fr,
rcpt = to,
source = source,
server = config.mailserver
}
-- let the user know what happened
r:puts(JSON.encode{
result = rv,
error = er,
src = headers
})
else
r:puts(JSON.encode{
error = "Invalid recipient specified."
})
end
else
r:puts(JSON.encode{
error = "Invalid or missing headers",
headers = post
})
end
else
r:puts[[{"error": "You need to be logged in before you can send emails"}]]
end
return cross.OK
end
cross.start(handle)
|
--[[
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
-- This is compose.lua - a script for sending replies or new topics to lists
local JSON = require 'cjson'
local elastic = require 'lib/elastic'
local user = require 'lib/user'
local config = require 'lib/config'
local smtp = require 'socket.smtp'
local cross = require 'lib/cross'
function handle(r)
local account = user.get(r)
cross.contentType(r, "application/json")
-- make sure the user is logged in
if account and account.cid then
-- parse response, up to 1MB of it. if >1MB, we're gonna pretend we never saw anything ;)
local post = r:parsebody(1024*1024)
-- check that recipient, subject and body exists
if post.to and post.subject and post.body then
-- validate recipient
local to = ("<%s>"):format(post.to)
local fp, lp = post.to:match("([^@]+)@([^@]+)")
local domainIsOkay = false
-- check that recipient is whitelisted in config.lua
if type(config.accepted_domains) == "string" then
if r.strcmp_match(lp, config.accepted_domains) or config.accepted_domains == "*" then
domainIsOkay = true
end
elseif type(config.accepted_domains) == "table" then
for k, ad in pairs(config.accepted_domains) do
if r.strcmp_match(lp, ad) or ad == "*" then
domainIsOkay = true
break
end
end
end
-- if we can send, then...
if domainIsOkay then
-- find user's full name
local fname = nil
if account.preferences then
fname = account.preferences.fullname
end
-- construct sender name+address
local fr = ([["%s"<%s>]]):format(fname or account.credentials.fullname, account.credentials.email)
-- Using alt email??
if account.credentials.altemail and post.alt then
for k, v in pairs(account.credentials.altemail) do
if v.email == post.alt then
fr = ([["%s"<%s>]]):format(fname or account.credentials.fullname, v.email)
break
end
end
end
-- standard headers + headers we need ourselves for parsing in the archiver (notifications etc)
local headers = {
['Content-Type'] = 'text/plain; charset=utf-8',
['X-PonyMail-Sender'] = r:sha1(account.cid),
['X-PonyMail-Agent'] = "PonyMail Composer/0.2",
['message-id'] = ("<pony-%s-%s@%s>"):format(r:sha1(account.cid), r:sha1(r:clock() .. os.time() .. r.useragent_ip), post.to:gsub("@", ".")),
to = to,
subject = post.subject,
from = fr,
}
-- set references and IRT if need be
if post['references'] then
headers['references'] = post['references']
end
if post['in-reply-to'] then
headers['in-reply-to'] = post['in-reply-to']
end
local msgbody = post.body
-- set an email footer if specified in config.lua
if config.email_footer then
local subs = {
list = to:gsub("[<>]", ""),
domain = r.hostname,
port = r.port,
msgid = headers['message-id']
}
msgbody = msgbody .. "\n" .. config.email_footer:gsub("$([a-z]+)", function(a) return subs[a] or a end)
end
-- construct the smtp object
local source = smtp.message{
headers = headers,
body = msgbody
}
-- send email!
local rv, er = smtp.send{
from = fr,
rcpt = to,
source = source,
server = config.mailserver
}
-- let the user know what happened
r:puts(JSON.encode{
result = rv,
error = er,
src = headers
})
else
r:puts(JSON.encode{
error = "Invalid recipient specified."
})
end
else
r:puts(JSON.encode{
error = "Invalid or missing headers",
headers = post
})
end
else
r:puts[[{"error": "You need to be logged in before you can send emails"}]]
end
return cross.OK
end
cross.start(handle)
|
compuser body should be unicode
|
compuser body should be unicode
This addresses #445 (though not a complete fix yet)
|
Lua
|
apache-2.0
|
quenda/ponymail,quenda/ponymail,Humbedooh/ponymail,Humbedooh/ponymail,quenda/ponymail,Humbedooh/ponymail,jimjag/ponymail,jimjag/ponymail,jimjag/ponymail,jimjag/ponymail
|
7a74cb0b7624143ef5cd81659185cedb6bb1c0bc
|
build/Tests.lua
|
build/Tests.lua
|
-- Tests/examples helpers
function SetupTestProject(name, extraFiles)
SetupTestGeneratorProject(name)
SetupTestNativeProject(name)
SetupTestProjectsCSharp(name, nil, extraFiles)
end
function SetupManagedTestProject()
kind "SharedLib"
language "C#"
flags { "Unsafe" }
SetupManagedProject()
end
function SetupTestGeneratorProject(name, depends)
project(name .. ".Gen")
SetupManagedTestProject()
kind "ConsoleApp"
files { name .. ".Gen.cs" }
dependson { name .. ".Managed" }
linktable = {
"System.Core",
"native-binder",
}
if depends ~= nil then
table.insert(linktable, depends .. ".Gen")
end
links(linktable)
end
function SetupTestGeneratorBuildEvent(name)
local runtimeExe = os.is("windows") and "" or "mono --debug "
if string.starts(action, "vs") then
local exePath = SafePath("$(TargetDir)" .. name .. ".Gen.exe")
prebuildcommands { runtimeExe .. exePath }
else
local exePath = SafePath("%{cfg.buildtarget.directory}/" .. name .. ".Gen.exe")
prebuildcommands { runtimeExe .. exePath }
end
end
local function SetupMono()
local monoDir = ''
-- Find system-specific Mono include/library paths.
-- For Windows, first search the default Mono install location.
local monoDefaultWindowsDir = "C:\\Program Files (x86)\\Mono"
if os.isdir(monoDefaultWindowsDir) then
monoDir = monoDefaultWindowsDir
end
if not os.isdir(monoDir) then
error("Could not find Mono install location, please specify it manually")
end
includedirs { path.join(monoDir, "include", "mono-2.0") }
libdirs { path.join(monoDir, "lib") }
links { "monosgen-2.0" }
end
function SetupTestNativeProject(name, depends)
if string.starts(action, "vs") and not os.is("windows") then
return
end
project(name .. ".C")
SetupNativeProject()
kind "SharedLib"
language "C"
defines { "MONO_DLL_EXPORT" }
flags { common_flags }
files
{
path.join(gendir, name, name .. ".h"),
path.join(gendir, name, name .. ".c")
}
dependson { name .. ".Gen" }
if depends ~= nil then
links { depends .. ".C" }
end
SetupTestGeneratorBuildEvent(name)
SetupMono()
end
function SetupTestProjectsCSharp(name, depends, extraFiles)
project(name .. ".Managed")
SetupManagedTestProject()
files
{
files { name .. ".cs" }
}
if extraFiles ~= nil then
for _, file in pairs(extraFiles) do
files { file .. ".cs" }
end
end
linktable = { }
if depends ~= nil then
table.insert(linktable, depends .. ".Managed")
end
links(linktable)
project(name .. ".Tests")
SetupNativeProject()
language "C++"
kind "ConsoleApp"
includedirs
{
path.join(gendir, name),
path.join(depsdir, "../catch/include")
}
files { name .. ".Tests.cpp" }
links { name .. ".C" }
dependson { name .. ".Managed" }
end
|
-- Tests/examples helpers
function SetupTestProject(name, extraFiles)
SetupTestGeneratorProject(name)
SetupTestNativeProject(name)
SetupTestProjectsCSharp(name, nil, extraFiles)
end
function SetupManagedTestProject()
kind "SharedLib"
language "C#"
flags { "Unsafe" }
SetupManagedProject()
end
function SetupTestGeneratorProject(name, depends)
project(name .. ".Gen")
SetupManagedTestProject()
kind "ConsoleApp"
files { name .. ".Gen.cs" }
dependson { name .. ".Managed" }
linktable = {
"System.Core",
"native-binder",
}
if depends ~= nil then
table.insert(linktable, depends .. ".Gen")
end
links(linktable)
end
function SetupTestGeneratorBuildEvent(name)
local runtimeExe = os.is("windows") and "" or "mono --debug "
if string.starts(action, "vs") then
local exePath = SafePath("$(TargetDir)" .. name .. ".Gen.exe")
prebuildcommands { runtimeExe .. exePath }
else
local exePath = SafePath("%{cfg.buildtarget.directory}/" .. name .. ".Gen.exe")
prebuildcommands { runtimeExe .. exePath }
end
end
local function SetupMono()
local monoDir = nil
-- Find system-specific Mono include/library paths.
-- For Windows, first search the default Mono install location.
local monoDefaultWindowsDir = "C:\\Program Files (x86)\\Mono"
if os.isdir(monoDefaultWindowsDir) then
monoDir = monoDefaultWindowsDir
end
local monoDefaultOSXDir = "/Library/Frameworks/Mono.framework/Versions/Current/"
if os.isdir(monoDefaultOSXDir) then
monoDir = monoDefaultOSXDir
end
-- TODO: Use premake-pkgconfig for Linux
if not monoDir or not os.isdir(monoDir) then
error("Could not find Mono install location, please specify it manually")
end
includedirs { path.join(monoDir, "include", "mono-2.0") }
libdirs { path.join(monoDir, "lib") }
links { "monosgen-2.0" }
end
function SetupTestNativeProject(name, depends)
if string.starts(action, "vs") and not os.is("windows") then
return
end
project(name .. ".C")
SetupNativeProject()
kind "SharedLib"
language "C"
defines { "MONO_DLL_EXPORT" }
flags { common_flags }
files
{
path.join(gendir, name, name .. ".h"),
path.join(gendir, name, name .. ".c")
}
dependson { name .. ".Gen" }
if depends ~= nil then
links { depends .. ".C" }
end
SetupTestGeneratorBuildEvent(name)
SetupMono()
end
function SetupTestProjectsCSharp(name, depends, extraFiles)
project(name .. ".Managed")
SetupManagedTestProject()
files
{
files { name .. ".cs" }
}
if extraFiles ~= nil then
for _, file in pairs(extraFiles) do
files { file .. ".cs" }
end
end
linktable = { }
if depends ~= nil then
table.insert(linktable, depends .. ".Managed")
end
links(linktable)
project(name .. ".Tests")
SetupNativeProject()
language "C++"
kind "ConsoleApp"
includedirs
{
path.join(gendir, name),
path.join(depsdir, "../catch/include")
}
files { name .. ".Tests.cpp" }
links { name .. ".C" }
dependson { name .. ".Managed" }
end
|
Fixed Mono build dirs lookup in OSX.
|
Fixed Mono build dirs lookup in OSX.
|
Lua
|
mit
|
tritao/MonoManagedToNative,tritao/MonoManagedToNative,jonathanpeppers/Embeddinator-4000,mono/Embeddinator-4000,mono/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,mono/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,mono/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,mono/Embeddinator-4000,tritao/MonoManagedToNative,mono/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,mono/Embeddinator-4000,jonathanpeppers/Embeddinator-4000
|
38b447466c19adbece629507acf6100d90520bbd
|
PausableLinear.lua
|
PausableLinear.lua
|
local PausableLinear, Parent = torch.class('nn.PausableLinear', 'nn.Linear')
function PausableLinear:__init(inputSize, outputSize)
Parent.__init(self, inputSize, outputSize)
self.pause = 0 -- pos value to prevent accGradParameters/updateParameters
end
function PausableLinear:pause()
self.pause = 1
end
function PausableLinear:resume()
self.pause = 0
end
function PausableLinear:accGradParameters(input, gradOutput, scale)
if self.pause > 0 then return end -- do nothing
Parent.accGradParameters(input, gradOutput, scale)
end
function PausableLinear:updateParameters(learningRate)
if self.pause > 0 then return end -- do nothing
Parent.updateParameters(self, learningRate)
end
|
local PausableLinear, Parent = torch.class('nn.PausableLinear', 'nn.Linear')
function PausableLinear:__init(inputSize, outputSize)
Parent.__init(self, inputSize, outputSize)
self.pause = 0 -- pos value to prevent accGradParameters/updateParameters
end
function PausableLinear:accGradParameters(input, gradOutput, scale)
if self.pause > 0 then return end -- do nothing
Parent.accGradParameters(self, input, gradOutput, scale)
end
function PausableLinear:updateParameters(learningRate)
if self.pause > 0 then return end -- do nothing
Parent.updateParameters(self, learningRate)
end
function PausableLinear:__tostring__()
local pauseStr = ''
if self.pause > 0 then pauseStr = ' paused' end
return torch.type(self) ..
string.format('(%d -> %d)'..pauseStr, self.weight:size(2), self.weight:size(1))
end
|
fix: pass self to Parent call
|
fix: pass self to Parent call
|
Lua
|
bsd-3-clause
|
caldweln/nn
|
571e04d7c0c9a94c666f5b8994ff7f7384720210
|
premake4.lua
|
premake4.lua
|
--
-- Premake4 build script (http://industriousone.com/premake/download)
--
solution 'luazmq'
configurations {'Debug', 'Release'}
--flags {'ExtraWarnings'}
targetdir 'bin'
platforms {'x32', 'x64'}
configuration 'Debug'
defines { 'DEBUG' }
flags { 'Symbols' }
configuration 'Release'
defines { 'NDEBUG' }
flags { 'Symbols', 'Optimize' }
configuration 'vs*'
defines
{
'WIN32',
'_WIN32_WINNT=0x0600',
'_CRT_SECURE_NO_WARNINGS',
'_SCL_SECURE_NO_WARNINGS',
'NOMINMAX',
}
links 'ws2_32'
project 'lua'
language 'C'
kind 'ConsoleApp'
location 'build'
uuid '9C08AC41-18D8-4FB9-80F2-01F603917025'
files
{
'deps/lua/src/lua.c',
}
includedirs
{
'deps/lua/src',
}
links 'lua52'
project 'luazmq'
language 'C'
kind 'SharedLib'
location 'build'
uuid '86C52891-A665-47BF-9107-8EA58606C41A'
if os.get() == 'windows' then
defines 'inline=__inline'
end
files
{
'src/*.c',
}
includedirs
{
'deps/lua/src',
'deps/libzmq/include',
}
libdirs 'bin'
links
{
'lua52',
'zmq',
'sodium',
}
project 'lua52'
language 'C'
kind 'SharedLib'
location 'build'
uuid 'C9A112FB-08C0-4503-9AFD-8EBAB5B3C204'
if os.get() == 'windows' then
defines 'LUA_BUILD_AS_DLL'
end
files
{
'deps/lua/src/*.h',
'deps/lua/src/*.c',
}
excludes
{
'deps/lua/src/lua.c',
'deps/lua/src/luac.c',
}
project 'sodium'
language 'C'
kind 'SharedLib'
location 'build'
uuid 'CB19F7EE-55D6-4C40-849D-64E2D3849041'
if os.get() == 'windows' then
defines
{
'SODIUM_DLL_EXPORT',
'inline=__inline',
}
end
files
{
'deps/libsodium/src/**.h',
'deps/libsodium/src/**.c',
}
includedirs
{
'deps/libsodium/src/libsodium/include',
'deps/libsodium/src/libsodium/include/sodium',
}
project 'zmq'
language 'C++'
kind 'SharedLib'
location 'build'
uuid 'A75AF625-DDF0-4E60-97D8-A2FDC6229AF7'
if os.get() == 'windows' then
defines
{
'DLL_EXPORT',
'FD_SETSIZE=1024',
}
end
defines 'HAVE_LIBSODIUM'
files
{
'deps/libzmq/include/*.h',
'deps/libzmq/src/*.hpp',
'deps/libzmq/src/*.cpp',
}
includedirs
{
'deps/libsodium/src/libsodium/include',
'deps/libzmq/include',
'deps/libzmq/builds/msvc',
}
links 'sodium'
|
--
-- Premake4 build script (http://industriousone.com/premake/download)
--
solution 'luazmq'
configurations {'Debug', 'Release'}
--flags {'ExtraWarnings'}
targetdir 'bin'
platforms {'x32', 'x64'}
configuration 'Debug'
defines { 'DEBUG' }
flags { 'Symbols' }
configuration 'Release'
defines { 'NDEBUG' }
flags { 'Symbols', 'Optimize' }
configuration 'vs*'
defines
{
'WIN32',
'_WIN32_WINNT=0x0600',
'_CRT_SECURE_NO_WARNINGS',
'_SCL_SECURE_NO_WARNINGS',
'NOMINMAX',
}
links 'ws2_32'
configuration 'gmake'
buildoptions '-rdynamic'
defines
{
'__STDC_LIMIT_MACROS',
}
links
{
'm',
'rt',
'dl',
}
project 'lua'
language 'C'
kind 'ConsoleApp'
location 'build'
uuid '9C08AC41-18D8-4FB9-80F2-01F603917025'
files
{
'deps/lua/src/lua.c',
}
includedirs
{
'deps/lua/src',
}
links 'lua52'
project 'luazmq'
language 'C'
kind 'SharedLib'
location 'build'
uuid '86C52891-A665-47BF-9107-8EA58606C41A'
if os.get() == 'windows' then
defines 'inline=__inline'
end
files
{
'src/*.c',
}
includedirs
{
'deps/lua/src',
'deps/libzmq/include',
}
libdirs 'bin'
links
{
'lua52',
'zmq',
'sodium',
}
project 'lua52'
language 'C'
kind 'SharedLib'
location 'build'
uuid 'C9A112FB-08C0-4503-9AFD-8EBAB5B3C204'
if os.get() == 'windows' then
defines 'LUA_BUILD_AS_DLL'
end
files
{
'deps/lua/src/*.h',
'deps/lua/src/*.c',
}
excludes
{
'deps/lua/src/lua.c',
'deps/lua/src/luac.c',
}
if os.get() == 'linux' then
defines 'LUA_USE_LINUX'
links 'readline'
end
project 'sodium'
language 'C'
kind 'SharedLib'
location 'build'
uuid 'CB19F7EE-55D6-4C40-849D-64E2D3849041'
if os.get() == 'windows' then
defines
{
'SODIUM_DLL_EXPORT',
'inline=__inline',
}
end
files
{
'deps/libsodium/src/**.h',
'deps/libsodium/src/**.c',
}
includedirs
{
'deps/libsodium/src/libsodium/include',
'deps/libsodium/src/libsodium/include/sodium',
}
project 'zmq'
language 'C++'
kind 'SharedLib'
location 'build'
uuid 'A75AF625-DDF0-4E60-97D8-A2FDC6229AF7'
if os.get() == 'windows' then
defines
{
'DLL_EXPORT',
'FD_SETSIZE=1024',
}
end
defines 'HAVE_LIBSODIUM'
files
{
'deps/libzmq/include/*.h',
'deps/libzmq/src/*.hpp',
'deps/libzmq/src/*.cpp',
}
includedirs
{
'deps/libsodium/src/libsodium/include',
'deps/libzmq/include',
'deps/libzmq/builds/msvc',
}
links 'sodium'
|
fix gcc compiling error
|
fix gcc compiling error
|
Lua
|
apache-2.0
|
ichenq/lua-zmq
|
60c5b6a34e70daf7dde6d96f35203bb14bd57ea1
|
CTCCriterion.lua
|
CTCCriterion.lua
|
------------------------------------------------------------------------
--[[ CTCCriterion ]]--
-- CTC Alignment for sequence data where input and labels do not align.
-- Useful for speech recognition on a phoneme/character level basis.
-- Inputs assumed are in the form of batch x time x inputdim.
-- Targets assumed in the form of {{1,2},{3,4}} where {1,2} is for the first
-- element.
------------------------------------------------------------------------
local CTCCriterion, parent = torch.class('nn.CTCCriterion', 'nn.Criterion')
CTCCriterion.dim = 3
function CTCCriterion:__init()
parent.__init(self)
require 'warp_ctc'
self.acts = torch.Tensor()
self.convertedGradients = torch.Tensor()
end
function CTCCriterion:updateOutput(output, labels)
assert(output:nDimension() == CTCCriterion.dim, "Output must be a tensor of (batch x time x inputdim), recieved " .. output:nDimension() .. " dimensions")
local tensorSizes = output:size()
local acts = self:createCTCBatch(output, tensorSizes)
local sizes = {} -- For each batch we state the number of time steps.
for x = 1, tensorSizes[1] do
table.insert(sizes, tensorSizes[2])
end
if (output:type() == 'torch.CudaTensor') then
local grads = torch.CudaTensor()
self.output = sumCosts(gpu_ctc(acts, grads, labels, sizes))
else
local grads = torch.Tensor()
self.output = sumCosts(cpu_ctc(acts:float(), grads:float(), labels, sizes))
end
return self.output
end
function CTCCriterion:updateGradInput(output, labels)
local tensorSizes = output:size()
local acts = self:createCTCBatch(output, tensorSizes)
local sizes = {}
for x = 1, tensorSizes[1] do
table.insert(sizes, tensorSizes[2])
end
local grads = acts:clone():zero()
if (output:type() == 'torch.CudaTensor') then
gpu_ctc(acts, grads, labels, sizes)
else
cpu_ctc(acts:float(), grads:float(), labels, sizes)
end
self.gradInput = self:revertBatching(grads, tensorSizes):typeAs(output)
return self.gradInput
end
--If batching occurs multiple costs are returned. We sum the costs and return.
function sumCosts(list)
local acc
for k, v in ipairs(list) do
if 1 == k then
acc = v
else
acc = acc + v
end
end
return acc
end
--[[
-- Converts the outputs into batch warp-ctc format seen at the end of the README here:
-- https://github.com/baidu-research/warp-ctc/blob/master/torch_binding/TUTORIAL.md
]]
function CTCCriterion:createCTCBatch(output, sizes)
self.acts:resize(sizes[1] * sizes[2], sizes[3]):zero()
local counter = 1
for i = 1, sizes[2] do
for j = 1, sizes[1] do
self.acts[counter] = output[j][i]
counter = counter + 1
end
end
return self.acts
end
function CTCCriterion:revertBatching(gradients, sizes)
self.convertedGradients:resize(sizes[1], sizes[2], sizes[3]):zero()
local counter = 1
for i = 1, sizes[2] do
for j = 1, sizes[1] do
self.convertedGradients[j][i] = gradients[counter]
counter = counter + 1
end
end
return self.convertedGradients
end
|
------------------------------------------------------------------------
--[[ CTCCriterion ]]--
-- CTC Alignment for sequence data where input and labels do not align.
-- Useful for speech recognition on a phoneme/character level basis.
-- Inputs assumed are in the form of batch x time x inputdim.
-- Targets assumed in the form of {{1,2},{3,4}} where {1,2} is for the first
-- element.
------------------------------------------------------------------------
local CTCCriterion, parent = torch.class('nn.CTCCriterion', 'nn.Criterion')
CTCCriterion.dim = 3
function CTCCriterion:__init()
parent.__init(self)
require 'warp_ctc'
self.acts = torch.Tensor()
self.convertedGradients = torch.Tensor()
end
function CTCCriterion:updateOutput(output, labels)
assert(output:nDimension() == CTCCriterion.dim, "Output must be a tensor of (batch x time x inputdim), recieved " .. output:nDimension() .. " dimensions")
local tensorSizes = output:size()
local acts = self:createCTCBatch(output, tensorSizes)
local sizes = {} -- For each batch we state the number of time steps.
for x = 1, tensorSizes[1] do
table.insert(sizes, tensorSizes[2])
end
if (output:type() == 'torch.CudaTensor') then
local grads = torch.CudaTensor()
self.output = sumCosts(gpu_ctc(acts, grads, labels, sizes))
else
local grads = torch.Tensor()
self.output = sumCosts(cpu_ctc(acts:float(), grads:float(), labels, sizes))
end
return self.output
end
function CTCCriterion:updateGradInput(output, labels)
local tensorSizes = output:size()
local acts = self:createCTCBatch(output, tensorSizes)
local sizes = {}
for x = 1, tensorSizes[1] do
table.insert(sizes, tensorSizes[2])
end
local grads = acts:clone():zero()
if (output:type() == 'torch.CudaTensor') then
gpu_ctc(acts, grads, labels, sizes)
else
grads = grads:float()
cpu_ctc(acts:float(), grads:float(), labels, sizes)
end
self.gradInput = self:revertBatching(grads, tensorSizes):typeAs(output)
return self.gradInput
end
--If batching occurs multiple costs are returned. We sum the costs and return.
function sumCosts(list)
local acc
for k, v in ipairs(list) do
if 1 == k then
acc = v
else
acc = acc + v
end
end
return acc
end
--[[
-- Converts the outputs into batch warp-ctc format seen at the end of the README here:
-- https://github.com/baidu-research/warp-ctc/blob/master/torch_binding/TUTORIAL.md
]]
function CTCCriterion:createCTCBatch(output, sizes)
self.acts:resize(sizes[1] * sizes[2], sizes[3]):zero()
local counter = 1
for i = 1, sizes[2] do
for j = 1, sizes[1] do
self.acts[counter] = output[j][i]
counter = counter + 1
end
end
return self.acts
end
function CTCCriterion:revertBatching(gradients, sizes)
self.convertedGradients:resize(sizes[1], sizes[2], sizes[3]):zero()
local counter = 1
for i = 1, sizes[2] do
for j = 1, sizes[1] do
self.convertedGradients[j][i] = gradients[counter]
counter = counter + 1
end
end
return self.convertedGradients
end
|
Fixed CPU gradInputs float error
|
Fixed CPU gradInputs float error
|
Lua
|
mit
|
clementfarabet/lua---nnx
|
9d2c922444ad6874d34ef5bfed40f4cee9d02115
|
xmake.lua
|
xmake.lua
|
set_xmakever("2.1.3")
set_languages("gnu++14")
if is_mode("debug") then
set_symbols("debug")
set_optimize("none")
set_warnings("all", "error")
add_defines("DEBUG")
add_undefines("NDEBUG")
end
if is_mode("release") then
set_symbols("hidden")
set_optimize("fastest")
set_strip("all")
set_warnings("none")
add_defines("NDEBUG")
add_undefines("DEBUG")
end
target("factorio-mod-info")
set_kind("shared")
add_files("src/*.cpp")
add_headers("src/**.hpp")
before_build(function (target)
if not os.exists("/usr/include/boost") then
if io.stderr == nil then
io.stderr = io.open("/dev/stderr", "a")
end
io.stderr:print("Need boost");
io.stderr:print("Install it with package manager")
io.stderr:print("Or http://www.boost.org/")
os.exit(1);
end
if not (os.exists("/usr/include/avhttp") and os.exists("/usr/include/avhttp.hpp")) then
if io.stderr == nil then
io.stderr = io.open("/dev/stderr", "a")
end
io.stderr:print("Need avhttp");
io.stderr:print("Install it with package manager")
io.stderr:print("Or https://avplayer.org/avhttp.html")
os.exit(1);
end
if not os.exists("/usr/include/DA/exception.hpp") then
os.exec("sh -c \'cd $(scriptdir)/DA-exception && sudo ./install\'")
end
end)
|
set_xmakever("2.1.3")
set_languages("gnu++14")
if is_mode("debug") then
set_symbols("debug")
set_optimize("none")
set_warnings("all", "error")
add_defines("DEBUG")
add_undefines("NDEBUG")
end
if is_mode("release") then
set_optimize("fastest")
set_strip("all")
set_warnings("none")
add_defines("NDEBUG")
add_undefines("DEBUG")
end
target("factorio-mod-info")
set_kind("shared")
add_files("src/*.cpp")
add_headers("src/**.hpp")
add_links("ssl", "pthread", "boost_date_time", "boost_system", "boost_filesystem")
before_build(function (target)
if not os.exists("/usr/include/boost") then
if io.stderr == nil then
io.stderr = io.open("/dev/stderr", "a")
end
io.stderr:print("Need boost");
io.stderr:print("Install it with package manager")
io.stderr:print("Or http://www.boost.org/")
os.exit(1);
end
if not (os.exists("/usr/include/avhttp") and os.exists("/usr/include/avhttp.hpp")) then
if io.stderr == nil then
io.stderr = io.open("/dev/stderr", "a")
end
io.stderr:print("Need avhttp");
io.stderr:print("Install it with package manager")
io.stderr:print("Or https://avplayer.org/avhttp.html")
os.exit(1);
end
if not os.exists("/usr/include/DA/exception.hpp") then
os.exec("sh -c \'cd $(scriptdir)/DA-exception && sudo ./install\'")
end
end)
|
fix caused by set_symbols
|
fix caused by set_symbols
|
Lua
|
agpl-3.0
|
745275633/Factorio-Mod-info
|
feaea1737788d0836cf000de411f93f4dd692959
|
spec/cap_spec.lua
|
spec/cap_spec.lua
|
describe("lpjit", function()
it("captures parts of pattern", function()
local lpeg = require 'lpeg'
local lpjit = require 'lpjit'
local pattern = lpeg.P 'a' * lpeg.C('b') * lpeg.P('c')
local pattern2 = lpjit.compile(pattern)
assert.equal('b', pattern2:match('abc'))
assert.falsy(pattern2:match('ff'))
end)
local allchar = {}
for i = 0, 255 do
allchar[i + 1] = i
end
allchar = string.char(unpack(allchar))
assert(#allchar == 256)
pending("can grow list of captures", function()
local lpeg = require 'lpeg'
local lpjit = require 'lpjit'
local pattern = lpeg.Cs((lpeg.R'09' + lpeg.P(1)/"")^0)
lpeg.pcode(pattern)
local pattern2 = lpjit.compile(pattern)
for i = 1, 1000 do
assert.equal('0123456789', pattern2:match(allchar))
end
end)
end)
|
describe("lpjit", function()
it("captures parts of pattern", function()
local lpeg = require 'lpeg'
local lpjit = require 'lpjit'
local pattern = lpeg.P 'a' * lpeg.C('b') * lpeg.P('c')
local pattern2 = lpjit.compile(pattern)
assert.equal('b', pattern2:match('abc'))
assert.falsy(pattern2:match('ff'))
end)
local allchar = {}
for i = 0, 255 do
allchar[i + 1] = i
end
local unpack = unpack or table.unpack
allchar = string.char(unpack(allchar))
assert(#allchar == 256)
pending("can grow list of captures", function()
local lpeg = require 'lpeg'
local lpjit = require 'lpjit'
local pattern = lpeg.Cs((lpeg.R'09' + lpeg.P(1)/"")^0)
lpeg.pcode(pattern)
local pattern2 = lpjit.compile(pattern)
for i = 1, 1000 do
assert.equal('0123456789', pattern2:match(allchar))
end
end)
end)
|
fix error in test
|
fix error in test
see https://travis-ci.org/starius/lpjit/jobs/65168418#L652
|
Lua
|
mit
|
starius/lpjit,starius/lpjit
|
e9629367a6ab816603e35e56bb65b0d18dc66196
|
kong/cmd/quit.lua
|
kong/cmd/quit.lua
|
local nginx_signals = require "kong.cmd.utils.nginx_signals"
local conf_loader = require "kong.conf_loader"
local pl_path = require "pl.path"
local kill = require "kong.cmd.utils.kill"
local log = require "kong.cmd.utils.log"
local function execute(args)
log.disable()
-- retrieve default prefix or use given one
local default_conf = assert(conf_loader(nil, {
prefix = args.prefix
}))
log.enable()
assert(pl_path.exists(default_conf.prefix),
"no such prefix: " .. default_conf.prefix)
-- load <PREFIX>/kong.conf containing running node's config
local conf = assert(conf_loader(default_conf.kong_env))
-- try graceful shutdown (QUIT)
assert(nginx_signals.quit(conf))
log.verbose("waiting for nginx to finish processing requests")
local tstart = ngx.time()
local texp, running = tstart + math.max(args.timeout, 1) -- min 1s timeout
repeat
ngx.sleep(0.2)
running = kill.is_running(conf.nginx_pid)
until not running or ngx.time() >= texp
if running then
log.verbose("nginx is still running at %s, forcing shutdown", conf.prefix)
assert(nginx_signals.stop(conf))
end
log("Kong stopped (gracefully)")
end
local lapp = [[
Usage: kong quit [OPTIONS]
Gracefully quit a running Kong node (Nginx and other
configured services) in given prefix directory.
This command sends a SIGQUIT signal to Nginx, meaning all
requests will finish processing before shutting down.
If the timeout delay is reached, the node will be forcefully
stopped (SIGTERM).
Options:
-p,--prefix (optional string) prefix Kong is running at
-t,--timeout (default 10) timeout before forced shutdown
]]
return {
lapp = lapp,
execute = execute
}
|
local nginx_signals = require "kong.cmd.utils.nginx_signals"
local conf_loader = require "kong.conf_loader"
local pl_path = require "pl.path"
local kill = require "kong.cmd.utils.kill"
local log = require "kong.cmd.utils.log"
local function execute(args)
log.disable()
-- retrieve default prefix or use given one
local default_conf = assert(conf_loader(nil, {
prefix = args.prefix
}))
log.enable()
assert(pl_path.exists(default_conf.prefix),
"no such prefix: " .. default_conf.prefix)
-- load <PREFIX>/kong.conf containing running node's config
local conf = assert(conf_loader(default_conf.kong_env))
-- try graceful shutdown (QUIT)
assert(nginx_signals.quit(conf))
log.verbose("waiting for nginx to finish processing requests")
local tstart = ngx.time()
local texp, running = tstart + math.max(args.timeout, 1) -- min 1s timeout
repeat
ngx.sleep(0.2)
running = kill.is_running(conf.nginx_pid)
until not running or ngx.time() >= texp
if running then
log.verbose("nginx is still running at %s, forcing shutdown", conf.prefix)
assert(nginx_signals.stop(conf))
log("Timeout, Kong stopped forcefully")
return
end
log("Kong stopped (gracefully)")
end
local lapp = [[
Usage: kong quit [OPTIONS]
Gracefully quit a running Kong node (Nginx and other
configured services) in given prefix directory.
This command sends a SIGQUIT signal to Nginx, meaning all
requests will finish processing before shutting down.
If the timeout delay is reached, the node will be forcefully
stopped (SIGTERM).
Options:
-p,--prefix (optional string) prefix Kong is running at
-t,--timeout (default 10) timeout before forced shutdown
]]
return {
lapp = lapp,
execute = execute
}
|
fix(cli) log forceful shutdown message upon SIGQUIT timeout
|
fix(cli) log forceful shutdown message upon SIGQUIT timeout
The CLI `quit` command would even on a forceful exit still
print a 'graceful shutdown' message.
From #3061
|
Lua
|
apache-2.0
|
Kong/kong,Mashape/kong,Kong/kong,Kong/kong,jebenexer/kong
|
1fcddf12cd592b11255495ff739cb9ec5f255867
|
kong/constants.lua
|
kong/constants.lua
|
local plugins = {
"jwt",
"acl",
"correlation-id",
"cors",
"oauth2",
"tcp-log",
"udp-log",
"file-log",
"http-log",
"key-auth",
"hmac-auth",
"basic-auth",
"ip-restriction",
"request-transformer",
"response-transformer",
"request-size-limiting",
"rate-limiting",
"response-ratelimiting",
"syslog",
"loggly",
"datadog",
"ldap-auth",
"statsd",
"bot-detection",
"aws-lambda",
"request-termination",
-- external plugins
"azure-functions",
"zipkin",
"pre-function",
"post-function",
"prometheus",
"proxy-cache",
"session",
"acme",
}
local plugin_map = {}
for i = 1, #plugins do
plugin_map[plugins[i]] = true
end
local deprecated_plugins = {} -- no currently deprecated plugin
local deprecated_plugin_map = {}
for _, plugin in ipairs(deprecated_plugins) do
deprecated_plugin_map[plugin] = true
end
local protocols_with_subsystem = {
http = "http",
https = "http",
tcp = "stream",
tls = "stream",
grpc = "http",
grpcs = "http",
}
local protocols = {}
for p,_ in pairs(protocols_with_subsystem) do
protocols[#protocols + 1] = p
end
table.sort(protocols)
return {
BUNDLED_PLUGINS = plugin_map,
DEPRECATED_PLUGINS = deprecated_plugin_map,
-- non-standard headers, specific to Kong
HEADERS = {
HOST_OVERRIDE = "X-Host-Override",
PROXY_LATENCY = "X-Kong-Proxy-Latency",
RESPONSE_LATENCY = "X-Kong-Response-Latency",
ADMIN_LATENCY = "X-Kong-Admin-Latency",
UPSTREAM_LATENCY = "X-Kong-Upstream-Latency",
UPSTREAM_STATUS = "X-Kong-Upstream-Status",
CONSUMER_ID = "X-Consumer-ID",
CONSUMER_CUSTOM_ID = "X-Consumer-Custom-ID",
CONSUMER_USERNAME = "X-Consumer-Username",
CREDENTIAL_USERNAME = "X-Credential-Username", -- TODO: deprecated, use CREDENTIAL_IDENTIFIER instead
CREDENTIAL_IDENTIFIER = "X-Credential-Identifier",
RATELIMIT_LIMIT = "X-RateLimit-Limit",
RATELIMIT_REMAINING = "X-RateLimit-Remaining",
CONSUMER_GROUPS = "X-Consumer-Groups",
AUTHENTICATED_GROUPS = "X-Authenticated-Groups",
FORWARDED_HOST = "X-Forwarded-Host",
FORWARDED_PREFIX = "X-Forwarded-Prefix",
ANONYMOUS = "X-Anonymous-Consumer",
VIA = "Via",
SERVER = "Server"
},
-- Notice that the order in which they are listed is important:
-- schemas of dependencies need to be loaded first.
CORE_ENTITIES = {
"consumers",
"certificates",
"services",
"routes",
"snis",
"upstreams",
"targets",
"plugins",
"tags",
"ca_certificates",
consumers = true,
certificates = true,
services = true,
routes = true,
snis = true,
upstreams = true,
targets = true,
plugins = true,
tags = true,
ca_certificates = true,
},
ENTITY_CACHE_STORE = setmetatable({
consumers = "cache",
certificates = "core_cache",
services = "core_cache",
routes = "core_cache",
snis = "core_cache",
upstreams = "core_cache",
targets = "core_cache",
plugins = "core_cache",
tags = "cache",
ca_certificates = "core_cache",
}, {
__index = function()
return "cache"
end
}),
RATELIMIT = {
PERIODS = {
"second",
"minute",
"hour",
"day",
"month",
"year"
}
},
REPORTS = {
ADDRESS = "kong-hf.konghq.com",
STATS_PORT = 61830
},
DICTS = {
"kong",
"kong_locks",
"kong_db_cache",
"kong_db_cache_miss",
"kong_process_events",
"kong_cluster_events",
"kong_healthchecks",
"kong_rate_limiting_counters",
},
DATABASE = {
POSTGRES = {
MIN = "9.5",
-- also accepts a DEPRECATED key, i.e. DEPRECATED = "9.4"
},
CASSANDRA = {
MIN = "2.2",
-- also accepts a DEPRECATED key
}
},
PROTOCOLS = protocols,
PROTOCOLS_WITH_SUBSYSTEM = protocols_with_subsystem,
}
|
local plugins = {
"jwt",
"acl",
"correlation-id",
"cors",
"oauth2",
"tcp-log",
"udp-log",
"file-log",
"http-log",
"key-auth",
"hmac-auth",
"basic-auth",
"ip-restriction",
"request-transformer",
"response-transformer",
"request-size-limiting",
"rate-limiting",
"response-ratelimiting",
"syslog",
"loggly",
"datadog",
"ldap-auth",
"statsd",
"bot-detection",
"aws-lambda",
"request-termination",
-- external plugins
"azure-functions",
"zipkin",
"pre-function",
"post-function",
"prometheus",
"proxy-cache",
"session",
"acme",
"grpc-web",
"grpc-gateway",
}
local plugin_map = {}
for i = 1, #plugins do
plugin_map[plugins[i]] = true
end
local deprecated_plugins = {} -- no currently deprecated plugin
local deprecated_plugin_map = {}
for _, plugin in ipairs(deprecated_plugins) do
deprecated_plugin_map[plugin] = true
end
local protocols_with_subsystem = {
http = "http",
https = "http",
tcp = "stream",
tls = "stream",
grpc = "http",
grpcs = "http",
}
local protocols = {}
for p,_ in pairs(protocols_with_subsystem) do
protocols[#protocols + 1] = p
end
table.sort(protocols)
return {
BUNDLED_PLUGINS = plugin_map,
DEPRECATED_PLUGINS = deprecated_plugin_map,
-- non-standard headers, specific to Kong
HEADERS = {
HOST_OVERRIDE = "X-Host-Override",
PROXY_LATENCY = "X-Kong-Proxy-Latency",
RESPONSE_LATENCY = "X-Kong-Response-Latency",
ADMIN_LATENCY = "X-Kong-Admin-Latency",
UPSTREAM_LATENCY = "X-Kong-Upstream-Latency",
UPSTREAM_STATUS = "X-Kong-Upstream-Status",
CONSUMER_ID = "X-Consumer-ID",
CONSUMER_CUSTOM_ID = "X-Consumer-Custom-ID",
CONSUMER_USERNAME = "X-Consumer-Username",
CREDENTIAL_USERNAME = "X-Credential-Username", -- TODO: deprecated, use CREDENTIAL_IDENTIFIER instead
CREDENTIAL_IDENTIFIER = "X-Credential-Identifier",
RATELIMIT_LIMIT = "X-RateLimit-Limit",
RATELIMIT_REMAINING = "X-RateLimit-Remaining",
CONSUMER_GROUPS = "X-Consumer-Groups",
AUTHENTICATED_GROUPS = "X-Authenticated-Groups",
FORWARDED_HOST = "X-Forwarded-Host",
FORWARDED_PREFIX = "X-Forwarded-Prefix",
ANONYMOUS = "X-Anonymous-Consumer",
VIA = "Via",
SERVER = "Server"
},
-- Notice that the order in which they are listed is important:
-- schemas of dependencies need to be loaded first.
CORE_ENTITIES = {
"consumers",
"certificates",
"services",
"routes",
"snis",
"upstreams",
"targets",
"plugins",
"tags",
"ca_certificates",
consumers = true,
certificates = true,
services = true,
routes = true,
snis = true,
upstreams = true,
targets = true,
plugins = true,
tags = true,
ca_certificates = true,
},
ENTITY_CACHE_STORE = setmetatable({
consumers = "cache",
certificates = "core_cache",
services = "core_cache",
routes = "core_cache",
snis = "core_cache",
upstreams = "core_cache",
targets = "core_cache",
plugins = "core_cache",
tags = "cache",
ca_certificates = "core_cache",
}, {
__index = function()
return "cache"
end
}),
RATELIMIT = {
PERIODS = {
"second",
"minute",
"hour",
"day",
"month",
"year"
}
},
REPORTS = {
ADDRESS = "kong-hf.konghq.com",
STATS_PORT = 61830
},
DICTS = {
"kong",
"kong_locks",
"kong_db_cache",
"kong_db_cache_miss",
"kong_process_events",
"kong_cluster_events",
"kong_healthchecks",
"kong_rate_limiting_counters",
},
DATABASE = {
POSTGRES = {
MIN = "9.5",
-- also accepts a DEPRECATED key, i.e. DEPRECATED = "9.4"
},
CASSANDRA = {
MIN = "2.2",
-- also accepts a DEPRECATED key
}
},
PROTOCOLS = protocols,
PROTOCOLS_WITH_SUBSYSTEM = protocols_with_subsystem,
}
|
fix(plugins) enable grpc-web and grpc-gateway plugins by default
|
fix(plugins) enable grpc-web and grpc-gateway plugins by default
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
a6e6f1c7830a4dbe43e2292fe71c52d5c47a8de3
|
core/baseclass.lua
|
core/baseclass.lua
|
SILE.Commands = {}
function SILE.registerCommand (name, f) SILE.Commands[name] = f end
SILE.baseClass = {
registerCommands = (function()
local commandStack = {};
SILE.registerCommand("define", function (options, content)
SILE.registerCommand(options["command"], function(o,c)
local prevState = SILE.documentState;
SILE.documentState = SU.deepCopy( prevState )
table.insert(commandStack, c)
SILE.process(content)
SILE.documentState = prevState
end)
end)
SILE.registerCommand("comment", function(o,c) end);
SILE.registerCommand("process", function()
SILE.process(table.remove(commandStack));
end)
SILE.registerCommand("script", function(options, content)
if (options["src"]) then dofile(options["src"]..".lua") else loadstring(content) end
end)
SILE.registerCommand("include", function(options, content)
SILE.readFile(options["src"]);
end)
SILE.registerCommand("pagetemplate", function (options, content)
SILE.documentState.thisPageTemplate = { frames = {} };
SILE.process(content);
SILE.documentState.thisPageTemplate.firstContentFrame = SILE.getFrame(options["first-content-frame"]);
SILE.typesetter.initFrame(SILE.documentState.thisPageTemplate.firstContentFrame);
end)
SILE.registerCommand("frame", function (options, content)
local spec = {
id = options.id,
next = options.next,
balanced = (options.balanced or 0),
top = options.top and function() return SILE.parseComplexFrameDimension(options.top, "h") end,
bottom = options.bottom and function() return SILE.parseComplexFrameDimension(options.bottom, "h") end,
left = options.left and function() return SILE.parseComplexFrameDimension(options.left, "w") end,
right = options.right and function() return SILE.parseComplexFrameDimension(options.right, "w") end,
width = options.width and function() return SILE.parseComplexFrameDimension(options.width, "w") end,
height = options.height and function() return SILE.parseComplexFrameDimension(options.height, "h") end,
};
SILE.documentState.thisPageTemplate.frames[id] = SILE.newFrame(spec);
end)
SILE.registerCommand("font", function(options, content)
local prevState = SILE.documentState;
if (content[1]) then
SILE.documentState = SU.deepCopy( prevState )
end
if (options.family) then SILE.documentState.fontFamily = options.family end
if (options.size) then SILE.documentState.fontSize = options.size end
if (options.weight) then SILE.documentState.fontWeight = options.weight end
if (options.style) then SILE.documentState.fontStyle = options.style end
if (options.language) then SILE.documentState.language = options.language end
if (content[1]) then
SILE.process(content)
SILE.documentState = prevState
end
end)
SILE.registerCommand("penalty", function(options, content)
SILE.typesetter:pushPenalty({ flagged= tonumber(options.flagged), penalty = tonumber(options.penalty) })
end)
SILE.registerCommand("glue", function(options, content)
SILE.typesetter:pushGlue({
width = SILE.length.new({ length = tonumber(options.width), stretch = tonumber(options.stretch), shrink = tonumber(options.shrink) })
})
end)
SILE.registerCommand("skip", function(options, content)
SILE.typesetter:leaveHmode();
SILE.typesetter:pushVglue({ height = SILE.length.new({ length = tonumber(options.height), stretch = tonumber(options.stretch) or 0, shrink = tonumber(options.shrink) or 0 }) })
end)
end),
settings = { widowPenalty= 5000, clubPenalty= 5000 },
pageTemplate = { frames= {}, firstContentFrame= nil },
state = {
parindent = SILE.nodefactory.newGlue({ width= SILE.length.new({length = 11, stretch= 0, shrink= 0})}),
baselineSkip = SILE.nodefactory.newVglue({ height= SILE.length.new({length = 13, stretch= 2, shrink= 0})}),
lineSkip = SILE.nodefactory.newVglue({ height= SILE.length.new({length = 2, stretch= 0, shrink= 0}) }),
},
init = function(self)
SILE.outputter.init(self);
self:registerCommands();
SILE.documentState.fontFamily = "Gentium";
SILE.documentState.fontSize = 10;
SILE.documentState.fontWeight = 200;
SILE.documentState.fontStyle = "normal";
SILE.documentState.language = "en";
return self:initialFrame();
end,
initialFrame= function(self)
SILE.documentState.thisPageTemplate = self.pageTemplate;
return SILE.documentState.thisPageTemplate.firstContentFrame;
end,
declareFrame = function (self, id, spec)
local fW = function (val) return function() return SILE.parseComplexFrameDimension(val, "w"); end end
local fH = function (val) return function() return SILE.parseComplexFrameDimension(val, "h"); end end
self.pageTemplate.frames[id] = SILE.newFrame({
id= id, next= spec.next,
left= fW(spec.left),
right= fW(spec.right),
top= fH(spec.top),
bottom= fH(spec.bottom)
});
end,
newPage = function(self)
SILE.outputter:newPage();
-- Any other output-routiney things will be done here by inheritors
return self:initialFrame();
end,
endPage= function()
SILE.typesetter:leaveHmode();
-- Any other output-routiney things will be done here by inheritors
end,
finish = function(self)
self:endPage();
SILE.typesetter:shipOut(0);
SILE.outputter:finish()
end,
newPar = function(typesetter)
--typesetter:pushVglue(SILE.documentState.documentClass.state.lineSkip);
typesetter:pushGlue( SILE.documentState.documentClass.state.parindent );
end,
options= {
papersize= function(size)
_, _, x, y = string.find(size, "(.+)%s+x%s+(.+)")
if x then
SILE.documentState.paperSize ={ SILE.toPoints(x), SILE.toPoints(y) };
elseif (SILE.paperSizes[size]) then
SILE.documentState.paperSize = SILE.paperSizes[size];
else
SU.error("Unknown paper size "+size);
end
end
}
}
|
SILE.Commands = {}
function SILE.registerCommand (name, f) SILE.Commands[name] = f end
SILE.baseClass = {
registerCommands = (function()
local commandStack = {};
SILE.registerCommand("define", function (options, content)
SILE.registerCommand(options["command"], function(o,c)
local prevState = SILE.documentState;
SILE.documentState = SU.deepCopy( prevState )
table.insert(commandStack, c)
SILE.process(content)
SILE.documentState = prevState
end)
end)
SILE.registerCommand("comment", function(o,c) end);
SILE.registerCommand("process", function()
SILE.process(table.remove(commandStack));
end)
SILE.registerCommand("script", function(options, content)
if (options["src"]) then
dofile(options["src"]..".lua")
else
p = loadstring(content[1])
p()
end
end)
SILE.registerCommand("include", function(options, content)
SILE.readFile(options["src"]);
end)
SILE.registerCommand("pagetemplate", function (options, content)
SILE.documentState.thisPageTemplate = { frames = {} };
SILE.process(content);
SILE.documentState.thisPageTemplate.firstContentFrame = SILE.getFrame(options["first-content-frame"]);
SILE.typesetter:initFrame(SILE.documentState.thisPageTemplate.firstContentFrame);
end)
SILE.registerCommand("frame", function (options, content)
local spec = {
id = options.id,
next = options.next,
balanced = (options.balanced or 0),
top = options.top and function() return SILE.parseComplexFrameDimension(options.top, "h") end,
bottom = options.bottom and function() return SILE.parseComplexFrameDimension(options.bottom, "h") end,
left = options.left and function() return SILE.parseComplexFrameDimension(options.left, "w") end,
right = options.right and function() return SILE.parseComplexFrameDimension(options.right, "w") end,
width = options.width and function() return SILE.parseComplexFrameDimension(options.width, "w") end,
height = options.height and function() return SILE.parseComplexFrameDimension(options.height, "h") end,
};
SILE.documentState.thisPageTemplate.frames[options.id] = SILE.newFrame(spec);
end)
SILE.registerCommand("font", function(options, content)
local prevState = SILE.documentState;
if (content[1]) then
SILE.documentState = SU.deepCopy( prevState )
end
if (options.family) then SILE.documentState.fontFamily = options.family end
if (options.size) then SILE.documentState.fontSize = options.size end
if (options.weight) then SILE.documentState.fontWeight = options.weight end
if (options.style) then SILE.documentState.fontStyle = options.style end
if (options.language) then SILE.documentState.language = options.language end
if (content[1]) then
SILE.process(content)
SILE.documentState = prevState
end
end)
SILE.registerCommand("penalty", function(options, content)
SILE.typesetter:pushPenalty({ flagged= tonumber(options.flagged), penalty = tonumber(options.penalty) })
end)
SILE.registerCommand("glue", function(options, content)
SILE.typesetter:pushGlue({
width = SILE.length.new({ length = tonumber(options.width), stretch = tonumber(options.stretch), shrink = tonumber(options.shrink) })
})
end)
SILE.registerCommand("skip", function(options, content)
SILE.typesetter:leaveHmode();
SILE.typesetter:pushVglue({ height = SILE.length.new({ length = tonumber(options.height), stretch = tonumber(options.stretch) or 0, shrink = tonumber(options.shrink) or 0 }) })
end)
end),
settings = { widowPenalty= 5000, clubPenalty= 5000 },
pageTemplate = { frames= {}, firstContentFrame= nil },
state = {
parindent = SILE.nodefactory.newGlue({ width= SILE.length.new({length = 11, stretch= 0, shrink= 0})}),
baselineSkip = SILE.nodefactory.newVglue({ height= SILE.length.new({length = 13, stretch= 2, shrink= 0})}),
lineSkip = SILE.nodefactory.newVglue({ height= SILE.length.new({length = 2, stretch= 0, shrink= 0}) }),
},
init = function(self)
SILE.outputter.init(self);
self:registerCommands();
SILE.documentState.fontFamily = "Gentium";
SILE.documentState.fontSize = 10;
SILE.documentState.fontWeight = 200;
SILE.documentState.fontStyle = "normal";
SILE.documentState.language = "en";
return self:initialFrame();
end,
initialFrame= function(self)
SILE.documentState.thisPageTemplate = self.pageTemplate;
return SILE.documentState.thisPageTemplate.firstContentFrame;
end,
declareFrame = function (self, id, spec)
local fW = function (val) return function() return SILE.parseComplexFrameDimension(val, "w"); end end
local fH = function (val) return function() return SILE.parseComplexFrameDimension(val, "h"); end end
self.pageTemplate.frames[id] = SILE.newFrame({
next= spec.next,
left= fW(spec.left),
right= fW(spec.right),
top= fH(spec.top),
bottom= fH(spec.bottom)
});
end,
newPage = function(self)
SILE.outputter:newPage();
-- Any other output-routiney things will be done here by inheritors
return self:initialFrame();
end,
endPage= function()
SILE.typesetter:leaveHmode();
-- Any other output-routiney things will be done here by inheritors
end,
finish = function(self)
self:endPage();
SILE.typesetter:shipOut(0);
SILE.outputter:finish()
end,
newPar = function(typesetter)
--typesetter:pushVglue(SILE.documentState.documentClass.state.lineSkip);
typesetter:pushGlue( SILE.documentState.documentClass.state.parindent );
end,
options= {
papersize= function(size)
_, _, x, y = string.find(size, "(.+)%s+x%s+(.+)")
if x then
SILE.documentState.paperSize ={ SILE.toPoints(x), SILE.toPoints(y) };
elseif (SILE.paperSizes[size]) then
SILE.documentState.paperSize = SILE.paperSizes[size];
else
SU.error("Unknown paper size "+size);
end
end
}
}
|
Various fixes.
|
Various fixes.
|
Lua
|
mit
|
anthrotype/sile,simoncozens/sile,shirat74/sile,shirat74/sile,neofob/sile,Nathan22Miles/sile,WAKAMAZU/sile_fe,alerque/sile,alerque/sile,alerque/sile,Nathan22Miles/sile,neofob/sile,alerque/sile,WAKAMAZU/sile_fe,simoncozens/sile,simoncozens/sile,anthrotype/sile,shirat74/sile,simoncozens/sile,Nathan22Miles/sile,anthrotype/sile,neofob/sile,Nathan22Miles/sile,Nathan22Miles/sile,WAKAMAZU/sile_fe,WAKAMAZU/sile_fe,anthrotype/sile,shirat74/sile,neofob/sile
|
00a14b1b2367dc112aee3e512c2632d54678faf2
|
src/logging/logging.lua
|
src/logging/logging.lua
|
-------------------------------------------------------------------------------
-- includes a new tostring function that handles tables recursively
--
-- @author Danilo Tuler ([email protected])
-- @author Andre Carregal ([email protected])
-- @author Thiago Costa Ponte ([email protected])
--
-- @copyright 2004-2007 Kepler Project
-- @release $Id: logging.lua,v 1.12 2007-10-30 19:57:59 carregal Exp $
-------------------------------------------------------------------------------
local type, table, string, assert, _tostring = type, table, string, assert, tostring
module("logging")
-- Meta information
_COPYRIGHT = "Copyright (C) 2004-2007 Kepler Project"
_DESCRIPTION = "A simple API to use logging features in Lua"
_VERSION = "LuaLogging 1.1.4"
-- The DEBUG Level designates fine-grained instring.formational events that are most
-- useful to debug an application
DEBUG = "DEBUG"
-- The INFO level designates instring.formational messages that highlight the
-- progress of the application at coarse-grained level
INFO = "INFO"
-- The WARN level designates potentially harmful situations
WARN = "WARN"
-- The ERROR level designates error events that might still allow the
-- application to continue running
ERROR = "ERROR"
-- The FATAL level designates very severe error events that will presumably
-- lead the application to abort
FATAL = "FATAL"
local LEVEL = {
[DEBUG] = 1,
[INFO] = 2,
[WARN] = 3,
[ERROR] = 4,
[FATAL] = 5,
}
-------------------------------------------------------------------------------
-- Creates a new logger object
-- @param append Function used by the logger to append a message with a
-- log-level to the log stream.
-- @return Table representing the new logger object.
-------------------------------------------------------------------------------
function new(append)
if type(append) ~= "function" then
return nil, "Appender must be a function."
end
local logger = {}
logger.level = DEBUG
logger.append = append
logger.setLevel = function (self, level)
assert(LEVEL[level], string.format("undefined level `%s'", tostring(level)))
self.level = level
end
logger.log = function (self, level, message)
assert(LEVEL[level], string.format("undefined level `%s'", tostring(level)))
if LEVEL[level] < LEVEL[self.level] then
return
end
if type(message) ~= "string" then
message = tostring(message)
end
return logger:append(level, message)
end
logger.debug = function (logger, message) return logger:log(DEBUG, message) end
logger.info = function (logger, message) return logger:log(INFO, message) end
logger.warn = function (logger, message) return logger:log(WARN, message) end
logger.error = function (logger, message) return logger:log(ERROR, message) end
logger.fatal = function (logger, message) return logger:log(FATAL, message) end
return logger
end
-------------------------------------------------------------------------------
-- Prepares the log message
-------------------------------------------------------------------------------
function prepareLogMsg(pattern, dt, level, message)
local logMsg = pattern or "%date %level %message\n"
message = string.gsub(message, "%%", "%%%%")
logMsg = string.gsub(logMsg, "%%date", dt)
logMsg = string.gsub(logMsg, "%%level", level)
logMsg = string.gsub(logMsg, "%%message", message)
return logMsg
end
-------------------------------------------------------------------------------
-- Converts a Lua value to a string
--
-- Converts Table fields in alphabetical order
-------------------------------------------------------------------------------
function tostring(value)
local str = ''
if (type(value) ~= 'table') then
if (type(value) == 'string') then
str = string.format("%q", value)
else
str = _tostring(value)
end
else
local auxTable = {}
table.foreach(value, function(i, v)
if (tonumber(i) ~= i) then
table.insert(auxTable, i)
else
table.insert(auxTable, tostring(i))
end
end)
table.sort(auxTable)
str = str..'{'
local separator = ""
local entry = ""
table.foreachi (auxTable, function (i, fieldName)
if ((tonumber(fieldName)) and (tonumber(fieldName) > 0)) then
entry = tostring(value[tonumber(fieldName)])
else
entry = fieldName.." = "..tostring(value[fieldName])
end
str = str..separator..entry
separator = ", "
end)
str = str..'}'
end
return str
end
|
-------------------------------------------------------------------------------
-- includes a new tostring function that handles tables recursively
--
-- @author Danilo Tuler ([email protected])
-- @author Andre Carregal ([email protected])
-- @author Thiago Costa Ponte ([email protected])
--
-- @copyright 2004-2007 Kepler Project
-- @release $Id: logging.lua,v 1.13 2008-07-24 20:17:39 alessandrohc Exp $
-------------------------------------------------------------------------------
local type, table, string, assert, _tostring, tonumber = type, table, string, assert, tostring, tonumber
module("logging")
-- Meta information
_COPYRIGHT = "Copyright (C) 2004-2007 Kepler Project"
_DESCRIPTION = "A simple API to use logging features in Lua"
_VERSION = "LuaLogging 1.1.4"
-- The DEBUG Level designates fine-grained instring.formational events that are most
-- useful to debug an application
DEBUG = "DEBUG"
-- The INFO level designates instring.formational messages that highlight the
-- progress of the application at coarse-grained level
INFO = "INFO"
-- The WARN level designates potentially harmful situations
WARN = "WARN"
-- The ERROR level designates error events that might still allow the
-- application to continue running
ERROR = "ERROR"
-- The FATAL level designates very severe error events that will presumably
-- lead the application to abort
FATAL = "FATAL"
local LEVEL = {
[DEBUG] = 1,
[INFO] = 2,
[WARN] = 3,
[ERROR] = 4,
[FATAL] = 5,
}
-------------------------------------------------------------------------------
-- Creates a new logger object
-- @param append Function used by the logger to append a message with a
-- log-level to the log stream.
-- @return Table representing the new logger object.
-------------------------------------------------------------------------------
function new(append)
if type(append) ~= "function" then
return nil, "Appender must be a function."
end
local logger = {}
logger.level = DEBUG
logger.append = append
logger.setLevel = function (self, level)
assert(LEVEL[level], string.format("undefined level `%s'", tostring(level)))
self.level = level
end
logger.log = function (self, level, message)
assert(LEVEL[level], string.format("undefined level `%s'", tostring(level)))
if LEVEL[level] < LEVEL[self.level] then
return
end
if type(message) ~= "string" then
message = tostring(message)
end
return logger:append(level, message)
end
logger.debug = function (logger, message) return logger:log(DEBUG, message) end
logger.info = function (logger, message) return logger:log(INFO, message) end
logger.warn = function (logger, message) return logger:log(WARN, message) end
logger.error = function (logger, message) return logger:log(ERROR, message) end
logger.fatal = function (logger, message) return logger:log(FATAL, message) end
return logger
end
-------------------------------------------------------------------------------
-- Prepares the log message
-------------------------------------------------------------------------------
function prepareLogMsg(pattern, dt, level, message)
local logMsg = pattern or "%date %level %message\n"
message = string.gsub(message, "%%", "%%%%")
logMsg = string.gsub(logMsg, "%%date", dt)
logMsg = string.gsub(logMsg, "%%level", level)
logMsg = string.gsub(logMsg, "%%message", message)
return logMsg
end
-------------------------------------------------------------------------------
-- Converts a Lua value to a string
--
-- Converts Table fields in alphabetical order
-------------------------------------------------------------------------------
function tostring(value)
local str = ''
if (type(value) ~= 'table') then
if (type(value) == 'string') then
str = string.format("%q", value)
else
str = _tostring(value)
end
else
local auxTable = {}
table.foreach(value, function(i, v)
if (tonumber(i) ~= i) then
table.insert(auxTable, i)
else
table.insert(auxTable, tostring(i))
end
end)
table.sort(auxTable)
str = str..'{'
local separator = ""
local entry = ""
table.foreachi (auxTable, function (i, fieldName)
if ((tonumber(fieldName)) and (tonumber(fieldName) > 0)) then
entry = tostring(value[tonumber(fieldName)])
else
entry = fieldName.." = "..tostring(value[fieldName])
end
str = str..separator..entry
separator = ", "
end)
str = str..'}'
end
return str
end
|
fix #1 bug relative to logging.file
|
fix #1
bug relative to logging.file
|
Lua
|
mit
|
mwchase/log4l,Neopallium/lualogging,StoneDot/lualogging
|
46538722da861a22b69abe7229ee410c6ee5639f
|
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,
GetWndButtonStyleName = D.GetWndButtonStyleName,
GetWndButtonStyleConfig = D.GetWndButtonStyleConfig,
},
},
},
}
_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 = PLUGIN_ROOT .. '/img/WndButton.UITex',
nNormalGroup = 8,
nMouseOverGroup = 9,
nMouseDownGroup = 10,
nDisableGroup = 11,
}),
FLAT_LACE_BORDER = LIB.SetmetaReadonly({
nWidth = 148,
nHeight = 33,
szImage = PLUGIN_ROOT .. '/img/WndButton.UITex',
nNormalGroup = 0,
nMouseOverGroup = 1,
nMouseDownGroup = 2,
nDisableGroup = 3,
}),
SKEUOMORPHISM = LIB.SetmetaReadonly({
nWidth = 148,
nHeight = 33,
szImage = PLUGIN_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 = PLUGIN_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
|
cde4cc5f4b610d18a923ef61d6708da6dbc7c35c
|
api-gateway-config/scripts/lua/routing.lua
|
api-gateway-config/scripts/lua/routing.lua
|
-- Copyright (c) 2016 IBM. All rights reserved.
--
-- 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.
--- @module Routing
-- Used to dynamically handle nginx routing based on an object containing implementation details
-- @author Cody Walker (cmwalker), Alex Song (songs)
local utils = require "lib/utils"
local request = require "lib/request"
local url = require "url"
-- load policies
local security = require "policies/security"
local mapping = require "policies/mapping"
local rateLimit = require "policies/rateLimit"
local _M = {}
--- Main function that handles parsing of invocation details and carries out implementation
-- @param obj Lua table object containing implementation details for the given resource
-- {
-- {{GatewayMethod (GET / PUT / POST / DELETE)}} = {
-- "backendMethod": (GET / PUT / POST / DELETE) - Method to use for invocation (if different from gatewayMethod),
-- "backendUrl": STRING - fully composed url of backend invocation,
-- "policies": LIST - list of table objects containing type and value fields
-- }, ...
-- }
function processCall(obj)
local found = false
for verb, opFields in pairs(obj.operations) do
if string.upper(verb) == ngx.req.get_method() then
-- Check if auth is required
local apiKey
if (opFields.security and string.lower(opFields.security.type) == 'apikey') then
apiKey = security.processAPIKey(opFields.security)
end
-- Set nginx conf values
local u = url.parse(opFields.backendUrl)
ngx.req.set_uri(u.path)
ngx.var.upstream = utils.concatStrings({u.scheme, '://', u.host})
if opFields.backendMethod ~= nil then
setVerb(opFields.backendMethod)
end
-- Parse policies
if opFields.policies ~= nil then
parsePolicies(opFields.policies, apiKey)
end
found = true
break
end
end
if found == false then
request.err(404, 'Whoops. Verb not supported.')
end
end
--- Function to read the list of policies and send implementation to the correct backend
-- @param obj List of policies containing a type and value field. This function reads the type field and routes it appropriately.
-- @param apiKey optional subscription api key
function parsePolicies(obj, apiKey)
for k, v in pairs (obj) do
if v.type == 'reqMapping' then
mapping.processMap(v.value)
elseif v.type == 'rateLimit' then
rateLimit.limit(v.value, apiKey)
end
end
end
--- Given a verb, transforms the backend request to use that method
-- @param v Verb to set on the backend request
function setVerb(v)
if (string.lower(v) == 'post') then
ngx.req.set_method(ngx.HTTP_POST)
elseif (string.lower(v) == 'put') then
ngx.req.set_method(ngx.HTTP_PUT)
elseif (string.lower(v) == 'delete') then
ngx.req.set_method(ngx.HTTP_DELETE)
else
ngx.req.set_method(ngx.HTTP_GET)
end
end
_M.processCall = processCall
return _M
|
-- Copyright (c) 2016 IBM. All rights reserved.
--
-- 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.
--- @module Routing
-- Used to dynamically handle nginx routing based on an object containing implementation details
-- @author Cody Walker (cmwalker), Alex Song (songs)
local utils = require "lib/utils"
local request = require "lib/request"
local url = require "url"
-- load policies
local security = require "policies/security"
local mapping = require "policies/mapping"
local rateLimit = require "policies/rateLimit"
local _M = {}
--- Main function that handles parsing of invocation details and carries out implementation
-- @param obj Lua table object containing implementation details for the given resource
-- {
-- {{GatewayMethod (GET / PUT / POST / DELETE)}} = {
-- "backendMethod": (GET / PUT / POST / DELETE) - Method to use for invocation (if different from gatewayMethod),
-- "backendUrl": STRING - fully composed url of backend invocation,
-- "policies": LIST - list of table objects containing type and value fields
-- }, ...
-- }
function processCall(obj)
local found = false
for verb, opFields in pairs(obj.operations) do
if string.upper(verb) == ngx.req.get_method() then
-- Check if auth is required
local apiKey
if (opFields.security and string.lower(opFields.security.type) == 'apikey') then
apiKey = security.processAPIKey(opFields.security)
end
-- Parse backend url
local u = url.parse(opFields.backendUrl)
-- Check for path
if u.path == nil or u.path == '' then
u.path = '/'
end
ngx.req.set_uri(u.path)
-- Set upstream - add port if it's in the backendURL
local upstream = utils.concatStrings({u.scheme, '://', u.host})
if u.port ~= nil and u.port ~= '' then
upstream = utils.concatStrings({upstream, ':', u.port})
end
ngx.var.upstream = upstream
-- Set backend method
if opFields.backendMethod ~= nil then
setVerb(opFields.backendMethod)
end
-- Parse policies
if opFields.policies ~= nil then
parsePolicies(opFields.policies, apiKey)
end
found = true
break
end
end
if found == false then
request.err(404, 'Whoops. Verb not supported.')
end
end
--- Function to read the list of policies and send implementation to the correct backend
-- @param obj List of policies containing a type and value field. This function reads the type field and routes it appropriately.
-- @param apiKey optional subscription api key
function parsePolicies(obj, apiKey)
for k, v in pairs (obj) do
if v.type == 'reqMapping' then
mapping.processMap(v.value)
elseif v.type == 'rateLimit' then
rateLimit.limit(v.value, apiKey)
end
end
end
--- Given a verb, transforms the backend request to use that method
-- @param v Verb to set on the backend request
function setVerb(v)
if (string.lower(v) == 'post') then
ngx.req.set_method(ngx.HTTP_POST)
elseif (string.lower(v) == 'put') then
ngx.req.set_method(ngx.HTTP_PUT)
elseif (string.lower(v) == 'delete') then
ngx.req.set_method(ngx.HTTP_DELETE)
else
ngx.req.set_method(ngx.HTTP_GET)
end
end
_M.processCall = processCall
return _M
|
Fix upstream ignoring port for backendUrl
|
Fix upstream ignoring port for backendUrl
|
Lua
|
apache-2.0
|
LukeFarrell/incubator-openwhisk-apigateway,alexsong93/openwhisk-apigateway,taylorking/apigateway,openwhisk/apigateway,LukeFarrell/incubator-openwhisk-apigateway,alexsong93/openwhisk-apigateway,taylorking/apigateway,openwhisk/openwhisk-apigateway,openwhisk/openwhisk-apigateway,openwhisk/apigateway,openwhisk/apigateway,alexsong93/openwhisk-apigateway,openwhisk/openwhisk-apigateway,taylorking/apigateway,LukeFarrell/incubator-openwhisk-apigateway
|
fe410459ac5c03b95435224a88d9289cfa5829e8
|
lua/wire/wire_paths.lua
|
lua/wire/wire_paths.lua
|
-- wire_paths.lua
--
-- This file implements syncing of wire paths, which are the visual
-- component of wires.
--
-- Conceptually, a wire path has a material, a color, and a non-zero width, as
-- well as as a non-empty polyline along the wire. (Each point in the line
-- has both a parent entity, and a local offset from that entity.)
--
if not WireLib then return end
if CLIENT then
net.Receive("WireLib.Paths.TransmitPath", function(length)
local path = {
Path = {}
}
path.Entity = net.ReadEntity()
if not path.Entity:IsValid() then return end
path.Name = net.ReadString()
path.Width = net.ReadFloat()
if path.Width<=0 then
if path.Entity.WirePaths then
path.Entity.WirePaths[path.Name] = nil
if not next(path.Entity.WirePaths) then path.Entity.WirePaths = nil end
end
return
end
path.StartPos = net.ReadVector()
path.Material = net.ReadString()
path.Color = net.ReadColor()
local num_points = net.ReadUInt(16)
for i = 1, num_points do
path.Path[i] = { Entity = net.ReadEntity(), Pos = net.ReadVector() }
end
if path.Entity.WirePaths == nil then path.Entity.WirePaths = {} end
path.Entity.WirePaths[path.Name] = path
end)
return
end
WireLib.Paths = {}
local transmit_queues = setmetatable({}, { __index = function(t,p) t[p] = {} return t[p] end })
util.AddNetworkString("WireLib.Paths.RequestPaths")
util.AddNetworkString("WireLib.Paths.TransmitPath")
net.Receive("WireLib.Paths.RequestPaths", function(length, ply)
local ent = net.ReadEntity()
if ent:IsValid() and ent.Inputs then
for name, input in pairs(ent.Inputs) do
if input.Src then
WireLib.Paths.Add(input, ply)
end
end
end
end)
local function TransmitPath(input, ply)
net.Start("WireLib.Paths.TransmitPath")
local color = input.Color
net.WriteEntity(input.Entity)
net.WriteString(input.Name)
if not input.Src or input.Width<=0 then
net.WriteFloat(0)
else
net.WriteFloat(input.Width)
net.WriteVector(input.StartPos)
net.WriteString(input.Material)
net.WriteColor(Color(color.r or 255, color.g or 255, color.b or 255, color.a or 255))
net.WriteUInt(#input.Path, 16)
for _, point in ipairs(input.Path) do
net.WriteEntity(point.Entity)
net.WriteVector(point.Pos)
end
end
net.Send(ply)
end
local function ProcessQueue()
for ply, queue in pairs(transmit_queues) do
if not ply:IsValid() then transmit_queues[ply] = nil continue end
local nextinqueue = table.remove(queue, 1)
if nextinqueue then
TransmitPath(nextinqueue, ply)
else
transmit_queues[ply] = nil
end
end
if not next(transmit_queues) then
timer.Remove("WireLib.Paths.ProcessQueue")
end
end
-- Add a path to every player's transmit queue
function WireLib.Paths.Add(input, ply)
if ply then
table.insert(transmit_queues[ply], input)
else
for _, player in pairs(player.GetAll()) do
table.insert(transmit_queues[player], input)
end
end
if not timer.Exists("WireLib.Paths.ProcessQueue") then
timer.Create("WireLib.Paths.ProcessQueue", 0, 0, ProcessQueue)
end
end
|
-- wire_paths.lua
--
-- This file implements syncing of wire paths, which are the visual
-- component of wires.
--
-- Conceptually, a wire path has a material, a color, and a non-zero width, as
-- well as as a non-empty polyline along the wire. (Each point in the line
-- has both a parent entity, and a local offset from that entity.)
--
if not WireLib then return end
if CLIENT then
net.Receive("WireLib.Paths.TransmitPath", function(length)
local path = {
Path = {}
}
path.Entity = net.ReadEntity()
if not path.Entity:IsValid() then return end
path.Name = net.ReadString()
path.Width = net.ReadFloat()
if path.Width<=0 then
if path.Entity.WirePaths then
path.Entity.WirePaths[path.Name] = nil
end
return
end
path.StartPos = net.ReadVector()
path.Material = net.ReadString()
path.Color = net.ReadColor()
local num_points = net.ReadUInt(16)
for i = 1, num_points do
path.Path[i] = { Entity = net.ReadEntity(), Pos = net.ReadVector() }
end
if path.Entity.WirePaths == nil then path.Entity.WirePaths = {} end
path.Entity.WirePaths[path.Name] = path
end)
return
end
WireLib.Paths = {}
local transmit_queues = setmetatable({}, { __index = function(t,p) t[p] = {} return t[p] end })
util.AddNetworkString("WireLib.Paths.RequestPaths")
util.AddNetworkString("WireLib.Paths.TransmitPath")
net.Receive("WireLib.Paths.RequestPaths", function(length, ply)
local ent = net.ReadEntity()
if ent:IsValid() and ent.Inputs then
for name, input in pairs(ent.Inputs) do
if input.Src then
WireLib.Paths.Add(input, ply)
end
end
end
end)
local function TransmitPath(input, ply)
net.Start("WireLib.Paths.TransmitPath")
local color = input.Color
net.WriteEntity(input.Entity)
net.WriteString(input.Name)
if not input.Src or input.Width<=0 then
net.WriteFloat(0)
else
net.WriteFloat(input.Width)
net.WriteVector(input.StartPos)
net.WriteString(input.Material)
net.WriteColor(Color(color.r or 255, color.g or 255, color.b or 255, color.a or 255))
net.WriteUInt(#input.Path, 16)
for _, point in ipairs(input.Path) do
net.WriteEntity(point.Entity)
net.WriteVector(point.Pos)
end
end
net.Send(ply)
end
local function ProcessQueue()
for ply, queue in pairs(transmit_queues) do
if not ply:IsValid() then transmit_queues[ply] = nil continue end
local nextinqueue = table.remove(queue, 1)
if nextinqueue then
TransmitPath(nextinqueue, ply)
else
transmit_queues[ply] = nil
end
end
if not next(transmit_queues) then
timer.Remove("WireLib.Paths.ProcessQueue")
end
end
-- Add a path to every player's transmit queue
function WireLib.Paths.Add(input, ply)
if ply then
table.insert(transmit_queues[ply], input)
else
for _, player in pairs(player.GetAll()) do
table.insert(transmit_queues[player], input)
end
end
if not timer.Exists("WireLib.Paths.ProcessQueue") then
timer.Create("WireLib.Paths.ProcessQueue", 0, 0, ProcessQueue)
end
end
|
Fix net spam caused by setting WirePaths to nil
|
Fix net spam caused by setting WirePaths to nil
|
Lua
|
apache-2.0
|
dvdvideo1234/wire,wiremod/wire,sammyt291/wire,NezzKryptic/Wire,Grocel/wire
|
8e7c5dbb18dff0c0ef4fe1e07103b20944d8466a
|
Phoenix/phoenix_init.lua
|
Phoenix/phoenix_init.lua
|
-- print(__api)
-- print(__api.app_running_apps)
-- for k, v in pairs(__api.app_running_apps()) do
-- print(k, __api.app_title(v))
-- end
for k, pid in pairs(__api.app_running_apps()) do
local x = __api.app_get_windows(pid)
print(__api.app_title(pid))
for k, v in pairs(x) do
print(k, v)
end
end
print("done")
-- local x, y = __api.mouse_get()
-- __api.hotkey_setup(function(uid)
-- __api.mouse_set(x, y)
-- print("got: " .. tostring(uid))
-- end)
-- local uid, carbonkey = __api.hotkey_register(true, true, true, false, "s")
-- print(uid, carbonkey)
|
-- print(__api)
-- print(__api.app_running_apps)
-- for k, v in pairs(__api.app_running_apps()) do
-- print(k, __api.app_title(v))
-- end
if false then
-- TODO: fix this!
for k, pid in pairs(__api.app_running_apps()) do
local x = __api.app_get_windows(pid)
print(__api.app_title(pid))
for k, v in pairs(x) do
print(k, v)
end
end
end
print("done")
-- local x, y = __api.mouse_get()
-- __api.hotkey_setup(function(uid)
-- __api.mouse_set(x, y)
-- print("got: " .. tostring(uid))
-- end)
-- local uid, carbonkey = __api.hotkey_register(true, true, true, false, "s")
-- print(uid, carbonkey)
|
Adding TODO to fix boring code
|
Adding TODO to fix boring code
|
Lua
|
mit
|
emoses/hammerspoon,Hammerspoon/hammerspoon,wsmith323/hammerspoon,dopcn/hammerspoon,dopcn/hammerspoon,joehanchoi/hammerspoon,knu/hammerspoon,CommandPost/CommandPost-App,wsmith323/hammerspoon,Stimim/hammerspoon,junkblocker/hammerspoon,emoses/hammerspoon,tmandry/hammerspoon,TimVonsee/hammerspoon,chrisjbray/hammerspoon,peterhajas/hammerspoon,lowne/hammerspoon,Habbie/hammerspoon,Hammerspoon/hammerspoon,hypebeast/hammerspoon,knl/hammerspoon,zzamboni/hammerspoon,nkgm/hammerspoon,Hammerspoon/hammerspoon,latenitefilms/hammerspoon,TimVonsee/hammerspoon,zzamboni/hammerspoon,bradparks/hammerspoon,CommandPost/CommandPost-App,chrisjbray/hammerspoon,nkgm/hammerspoon,emoses/hammerspoon,kkamdooong/hammerspoon,Habbie/hammerspoon,kkamdooong/hammerspoon,dopcn/hammerspoon,hypebeast/hammerspoon,knu/hammerspoon,cmsj/hammerspoon,zzamboni/hammerspoon,latenitefilms/hammerspoon,zzamboni/hammerspoon,knu/hammerspoon,Habbie/hammerspoon,peterhajas/hammerspoon,lowne/hammerspoon,peterhajas/hammerspoon,TimVonsee/hammerspoon,asmagill/hammerspoon,latenitefilms/hammerspoon,hypebeast/hammerspoon,knl/hammerspoon,wvierber/hammerspoon,wvierber/hammerspoon,knu/hammerspoon,Stimim/hammerspoon,latenitefilms/hammerspoon,asmagill/hammerspoon,ocurr/hammerspoon,joehanchoi/hammerspoon,lowne/hammerspoon,CommandPost/CommandPost-App,kkamdooong/hammerspoon,wvierber/hammerspoon,bradparks/hammerspoon,asmagill/hammerspoon,trishume/hammerspoon,hypebeast/hammerspoon,chrisjbray/hammerspoon,CommandPost/CommandPost-App,Habbie/hammerspoon,junkblocker/hammerspoon,emoses/hammerspoon,knu/hammerspoon,chrisjbray/hammerspoon,tmandry/hammerspoon,CommandPost/CommandPost-App,Stimim/hammerspoon,zzamboni/hammerspoon,Stimim/hammerspoon,joehanchoi/hammerspoon,nkgm/hammerspoon,wvierber/hammerspoon,trishume/hammerspoon,knl/hammerspoon,peterhajas/hammerspoon,cmsj/hammerspoon,asmagill/hammerspoon,junkblocker/hammerspoon,Hammerspoon/hammerspoon,cmsj/hammerspoon,heptal/hammerspoon,heptal/hammerspoon,heptal/hammerspoon,latenitefilms/hammerspoon,cmsj/hammerspoon,bradparks/hammerspoon,cmsj/hammerspoon,nkgm/hammerspoon,lowne/hammerspoon,kkamdooong/hammerspoon,Habbie/hammerspoon,peterhajas/hammerspoon,emoses/hammerspoon,ocurr/hammerspoon,bradparks/hammerspoon,wsmith323/hammerspoon,trishume/hammerspoon,Stimim/hammerspoon,cmsj/hammerspoon,knl/hammerspoon,dopcn/hammerspoon,lowne/hammerspoon,bradparks/hammerspoon,joehanchoi/hammerspoon,zzamboni/hammerspoon,knu/hammerspoon,Habbie/hammerspoon,junkblocker/hammerspoon,tmandry/hammerspoon,chrisjbray/hammerspoon,ocurr/hammerspoon,chrisjbray/hammerspoon,kkamdooong/hammerspoon,heptal/hammerspoon,dopcn/hammerspoon,Hammerspoon/hammerspoon,junkblocker/hammerspoon,asmagill/hammerspoon,TimVonsee/hammerspoon,hypebeast/hammerspoon,Hammerspoon/hammerspoon,CommandPost/CommandPost-App,wsmith323/hammerspoon,asmagill/hammerspoon,ocurr/hammerspoon,heptal/hammerspoon,TimVonsee/hammerspoon,ocurr/hammerspoon,joehanchoi/hammerspoon,knl/hammerspoon,latenitefilms/hammerspoon,wsmith323/hammerspoon,wvierber/hammerspoon,nkgm/hammerspoon
|
049bf07063b18ea1c61bcd92cf707a0e7bdc5eae
|
app/modules/repl.lua
|
app/modules/repl.lua
|
--[[
Copyright 2014 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local uv = require('uv')
local utils = require('utils')
local pathJoin = require('luvi').path.join
return function (stdin, stdout, greeting)
local global = setmetatable({
require = require('luvit-require')()(pathJoin(uv.cwd(), "repl"))
}, {
__index = _G
})
if greeting then print(greeting) end
local c = utils.color
local function gatherResults(success, ...)
local n = select('#', ...)
return success, { n = n, ... }
end
local function printResults(results)
for i = 1, results.n do
results[i] = utils.dump(results[i])
end
print(table.concat(results, '\t'))
end
local buffer = ''
local function evaluateLine(line)
if line == "<3\n" or line == "♥\n" then
print("I " .. c("Bred") .. "♥" .. c() .. " you too!")
return '>'
end
local chunk = buffer .. line
local f, err = loadstring('return ' .. chunk, 'REPL') -- first we prefix return
if not f then
f, err = loadstring(chunk, 'REPL') -- try again without return
end
setfenv(f, global)
if f then
buffer = ''
local success, results = gatherResults(xpcall(f, debug.traceback))
if success then
-- successful call
if results.n > 0 then
printResults(results)
end
else
-- error
print(results[1])
end
else
if err:match "'<eof>'$" then
-- Lua expects some more input; stow it away for next time
buffer = chunk .. '\n'
return '>>'
else
print(err)
buffer = ''
end
end
return '>'
end
local function displayPrompt(prompt)
uv.write(stdout, prompt .. ' ')
end
local function start()
displayPrompt '>'
uv.read_start(stdin, function (err, line)
assert(not err, err)
if line then
local prompt = evaluateLine(line)
displayPrompt(prompt)
else
uv.write(stdout, "\n")
end
end)
end
return {
start = start,
evaluateLine = evaluateLine,
}
end
|
--[[
Copyright 2014 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local uv = require('uv')
local utils = require('utils')
local pathJoin = require('luvi').path.join
return function (stdin, stdout, greeting)
local global = setmetatable({
require = require('luvit-require')()(pathJoin(uv.cwd(), "repl"))
}, {
__index = _G
})
if greeting then print(greeting) end
local c = utils.color
local function gatherResults(success, ...)
local n = select('#', ...)
return success, { n = n, ... }
end
local function printResults(results)
for i = 1, results.n do
results[i] = utils.dump(results[i])
end
print(table.concat(results, '\t'))
end
local buffer = ''
local function evaluateLine(line)
if line == "<3\n" or line == "♥\n" then
print("I " .. c("Bred") .. "♥" .. c() .. " you too!")
return '>'
end
local chunk = buffer .. line
local f, err = loadstring('return ' .. chunk, 'REPL') -- first we prefix return
if not f then
f, err = loadstring(chunk, 'REPL') -- try again without return
end
if f then
setfenv(f, global)
buffer = ''
local success, results = gatherResults(xpcall(f, debug.traceback))
if success then
-- successful call
if results.n > 0 then
printResults(results)
end
else
-- error
print(results[1])
end
else
if err:match "'<eof>'$" then
-- Lua expects some more input; stow it away for next time
buffer = chunk .. '\n'
return '>>'
else
print(err)
buffer = ''
end
end
return '>'
end
local function displayPrompt(prompt)
uv.write(stdout, prompt .. ' ')
end
local function start()
displayPrompt '>'
uv.read_start(stdin, function (err, line)
assert(not err, err)
if line then
local prompt = evaluateLine(line)
displayPrompt(prompt)
else
uv.write(stdout, "\n")
end
end)
end
return {
start = start,
evaluateLine = evaluateLine,
}
end
|
Fix error handling in repl
|
Fix error handling in repl
|
Lua
|
apache-2.0
|
bsn069/luvit,GabrielNicolasAvellaneda/luvit-upstream,GabrielNicolasAvellaneda/luvit-upstream,luvit/luvit,DBarney/luvit,GabrielNicolasAvellaneda/luvit-upstream,bsn069/luvit,luvit/luvit,kaustavha/luvit,GabrielNicolasAvellaneda/luvit-upstream,DBarney/luvit,kaustavha/luvit,bsn069/luvit,zhaozg/luvit,DBarney/luvit,rjeli/luvit,DBarney/luvit,zhaozg/luvit,rjeli/luvit,rjeli/luvit,rjeli/luvit,kaustavha/luvit
|
e711a5069b9579bdc977b76489e35650a5fa2826
|
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 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"
|
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
local new_track_num = n + 1
raw_track_order[i] = tostring(new_track_num)
if n == current_track_num then
redis.call('set', 'room:' .. room_id .. ':current-track', tostring(new_track_num))
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
local new_track_num = n - 1
raw_track_order[i] = tostring(new_track_num)
if n == current_track_num then
redis.call('set', 'room:' .. room_id .. ':current-track', tostring(new_track_num))
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)
if track_num == current_track_num then
redis.call('set', 'room:' .. room_id .. ':current-track', tostring(destination_track_num))
end
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 #75
|
fixed #75
|
Lua
|
agpl-3.0
|
vheuken/moomoo
|
0231e27f6b11f811c989a1daa0c4ef2ae19cfbe4
|
onmt/utils/Parallel.lua
|
onmt/utils/Parallel.lua
|
--[[
This file provides generic parallel class - allowing to run functions
in different threads and on different GPU
]]--
local Parallel = {
_pool = nil,
count = 1,
gradBuffer = torch.Tensor()
}
-- Synchronizes the current stream on dst device with src device. This is only
-- necessary if we are not on the default stream
local function waitForDevice(dst, src)
local stream = cutorch.getStream()
if stream ~= 0 then
cutorch.streamWaitForMultiDevice(dst, stream, { [src] = {stream} })
end
end
function Parallel.getCounter()
local atomic = Parallel._tds.AtomicCounter()
atomic:inc()
return atomic
end
function Parallel.gmutexId()
return Parallel._gmutex:id()
end
function Parallel.init(opt)
if onmt.utils.Cuda.activated then
Parallel.count = onmt.utils.Cuda.gpuCount()
Parallel.gradBuffer = onmt.utils.Cuda.convert(Parallel.gradBuffer)
Parallel._tds = require('tds')
if Parallel.count > 1 then
local globalLogger = _G.logger
local threads = require('threads')
threads.Threads.serialization('threads.sharedserialize')
Parallel._gmutex = threads.Mutex()
Parallel._pool = threads.Threads(
Parallel.count,
function()
require('cunn')
require('nngraph')
require('onmt.init')
_G.threads = require('threads')
end,
function(threadid)
_G.logger = globalLogger
onmt.utils.Cuda.init(opt, threadid)
end
) -- dedicate threads to GPUs
Parallel._pool:specific(true)
end
if Parallel.count > 1 and not opt.no_nccl and not opt.async_parallel then
-- check if we have nccl installed
local ret
ret, Parallel.usenccl = pcall(require, 'nccl')
if not ret then
_G.logger:warning("For improved efficiency with multiple GPUs, consider installing nccl")
Parallel.usenccl = nil
elseif os.getenv('CUDA_LAUNCH_BLOCKING') == '1' then
_G.logger:warning("CUDA_LAUNCH_BLOCKING set - cannot use nccl")
Parallel.usenccl = nil
end
end
end
end
--[[ Launch function in parallel on different threads. ]]
function Parallel.launch(closure, endCallback)
endCallback = endCallback or function() end
for j = 1, Parallel.count do
if Parallel._pool == nil then
endCallback(closure(j))
else
Parallel._pool:addjob(j, function() return closure(j) end, endCallback)
end
end
if Parallel._pool then
Parallel._pool:synchronize()
end
end
--[[ Accumulate the gradient parameters from the different parallel threads. ]]
function Parallel.accGradParams(gradParams, batches)
if Parallel.count > 1 then
for h = 1, #gradParams[1] do
local inputs = { gradParams[1][h] }
for j = 2, #batches do
if not Parallel.usenccl then
-- TODO - this is memory costly since we need to clone full parameters from one GPU to another
-- to avoid out-of-memory, we can copy/add by batch
-- Synchronize before and after copy to ensure that it doesn't overlap
-- with this add or previous adds
waitForDevice(onmt.utils.Cuda.gpuIds[j], onmt.utils.Cuda.gpuIds[1])
local remoteGrads = onmt.utils.Tensor.reuseTensor(Parallel.gradBuffer, gradParams[j][h]:size())
remoteGrads:copy(gradParams[j][h])
waitForDevice(onmt.utils.Cuda.gpuIds[1], onmt.utils.Cuda.gpuIds[j])
gradParams[1][h]:add(remoteGrads)
else
table.insert(inputs, gradParams[j][h])
end
end
if Parallel.usenccl then
Parallel.usenccl.reduce(inputs, nil, true)
end
end
end
end
-- [[ In async mode, sync the parameters from all replica to master replica. ]]
function Parallel.updateAndSync(masterParams, replicaGradParams, replicaParams, gradBuffer, masterGPU, gmutexId)
-- Add a mutex to avoid competition while accessing shared buffer and while updating parameters.
local mutex = _G.threads.Mutex(gmutexId)
mutex:lock()
local device = cutorch.getDevice()
cutorch.setDevice(masterGPU)
for h = 1, #replicaGradParams do
waitForDevice(device, masterGPU)
local remoteGrads = onmt.utils.Tensor.reuseTensor(gradBuffer, replicaGradParams[h]:size())
remoteGrads:copy(replicaGradParams[h])
waitForDevice(masterGPU, device)
masterParams[h]:add(remoteGrads)
end
cutorch.setDevice(device)
for h = 1, #replicaGradParams do
replicaParams[h]:copy(masterParams[h])
waitForDevice(device, masterGPU)
end
mutex:unlock()
end
--[[ Sync parameters from main model to different parallel threads. ]]
function Parallel.syncParams(params)
if Parallel.count > 1 then
if not Parallel.usenccl then
for j = 2, Parallel.count do
for h = 1, #params[1] do
params[j][h]:copy(params[1][h])
end
waitForDevice(onmt.utils.Cuda.gpuIds[j], onmt.utils.Cuda.gpuIds[1])
end
else
for h = 1, #params[1] do
local inputs = { params[1][h] }
for j = 2, Parallel.count do
table.insert(inputs, params[j][h])
end
Parallel.usenccl.bcast(inputs, true, 1)
end
end
end
end
return Parallel
|
--[[
This file provides generic parallel class - allowing to run functions
in different threads and on different GPU
]]--
local Parallel = {
_pool = nil,
count = 1,
gradBuffer = torch.Tensor()
}
-- Synchronizes the current stream on dst device with src device. This is only
-- necessary if we are not on the default stream
local function waitForDevice(dst, src)
local stream = cutorch.getStream()
if stream ~= 0 then
cutorch.streamWaitForMultiDevice(dst, stream, { [src] = {stream} })
end
end
function Parallel.getCounter()
local atomic = Parallel._tds.AtomicCounter()
atomic:inc()
return atomic
end
function Parallel.gmutexId()
return Parallel._gmutex:id()
end
function Parallel.init(opt)
if onmt.utils.Cuda.activated then
Parallel.count = onmt.utils.Cuda.gpuCount()
Parallel.gradBuffer = onmt.utils.Cuda.convert(Parallel.gradBuffer)
Parallel._tds = require('tds')
if Parallel.count > 1 then
local globalLogger = _G.logger
local globalProfiler = _G.profiler
local threads = require('threads')
threads.Threads.serialization('threads.sharedserialize')
Parallel._gmutex = threads.Mutex()
Parallel._pool = threads.Threads(
Parallel.count,
function()
require('cunn')
require('nngraph')
require('onmt.init')
_G.threads = require('threads')
end,
function(threadid)
_G.logger = globalLogger
_G.profiler = globalProfiler
onmt.utils.Cuda.init(opt, threadid)
end
) -- dedicate threads to GPUs
Parallel._pool:specific(true)
end
if Parallel.count > 1 and not opt.no_nccl and not opt.async_parallel then
-- check if we have nccl installed
local ret
ret, Parallel.usenccl = pcall(require, 'nccl')
if not ret then
_G.logger:warning("For improved efficiency with multiple GPUs, consider installing nccl")
Parallel.usenccl = nil
elseif os.getenv('CUDA_LAUNCH_BLOCKING') == '1' then
_G.logger:warning("CUDA_LAUNCH_BLOCKING set - cannot use nccl")
Parallel.usenccl = nil
end
end
end
end
--[[ Launch function in parallel on different threads. ]]
function Parallel.launch(closure, endCallback)
endCallback = endCallback or function() end
for j = 1, Parallel.count do
if Parallel._pool == nil then
endCallback(closure(j))
else
Parallel._pool:addjob(j, function() return closure(j) end, endCallback)
end
end
if Parallel._pool then
Parallel._pool:synchronize()
end
end
--[[ Accumulate the gradient parameters from the different parallel threads. ]]
function Parallel.accGradParams(gradParams, batches)
if Parallel.count > 1 then
for h = 1, #gradParams[1] do
local inputs = { gradParams[1][h] }
for j = 2, #batches do
if not Parallel.usenccl then
-- TODO - this is memory costly since we need to clone full parameters from one GPU to another
-- to avoid out-of-memory, we can copy/add by batch
-- Synchronize before and after copy to ensure that it doesn't overlap
-- with this add or previous adds
waitForDevice(onmt.utils.Cuda.gpuIds[j], onmt.utils.Cuda.gpuIds[1])
local remoteGrads = onmt.utils.Tensor.reuseTensor(Parallel.gradBuffer, gradParams[j][h]:size())
remoteGrads:copy(gradParams[j][h])
waitForDevice(onmt.utils.Cuda.gpuIds[1], onmt.utils.Cuda.gpuIds[j])
gradParams[1][h]:add(remoteGrads)
else
table.insert(inputs, gradParams[j][h])
end
end
if Parallel.usenccl then
Parallel.usenccl.reduce(inputs, nil, true)
end
end
end
end
-- [[ In async mode, sync the parameters from all replica to master replica. ]]
function Parallel.updateAndSync(masterParams, replicaGradParams, replicaParams, gradBuffer, masterGPU, gmutexId)
-- Add a mutex to avoid competition while accessing shared buffer and while updating parameters.
local mutex = _G.threads.Mutex(gmutexId)
mutex:lock()
local device = cutorch.getDevice()
cutorch.setDevice(masterGPU)
for h = 1, #replicaGradParams do
waitForDevice(device, masterGPU)
local remoteGrads = onmt.utils.Tensor.reuseTensor(gradBuffer, replicaGradParams[h]:size())
remoteGrads:copy(replicaGradParams[h])
waitForDevice(masterGPU, device)
masterParams[h]:add(remoteGrads)
end
cutorch.setDevice(device)
for h = 1, #replicaGradParams do
replicaParams[h]:copy(masterParams[h])
waitForDevice(device, masterGPU)
end
mutex:unlock()
end
--[[ Sync parameters from main model to different parallel threads. ]]
function Parallel.syncParams(params)
if Parallel.count > 1 then
if not Parallel.usenccl then
for j = 2, Parallel.count do
for h = 1, #params[1] do
params[j][h]:copy(params[1][h])
end
waitForDevice(onmt.utils.Cuda.gpuIds[j], onmt.utils.Cuda.gpuIds[1])
end
else
for h = 1, #params[1] do
local inputs = { params[1][h] }
for j = 2, Parallel.count do
table.insert(inputs, params[j][h])
end
Parallel.usenccl.bcast(inputs, true, 1)
end
end
end
end
return Parallel
|
Fix crash when using multiple GPU
|
Fix crash when using multiple GPU
|
Lua
|
mit
|
jsenellart-systran/OpenNMT,jsenellart/OpenNMT,jungikim/OpenNMT,da03/OpenNMT,monsieurzhang/OpenNMT,jsenellart-systran/OpenNMT,monsieurzhang/OpenNMT,jungikim/OpenNMT,jsenellart/OpenNMT,jungikim/OpenNMT,jsenellart-systran/OpenNMT,OpenNMT/OpenNMT,OpenNMT/OpenNMT,jsenellart/OpenNMT,da03/OpenNMT,da03/OpenNMT,OpenNMT/OpenNMT,monsieurzhang/OpenNMT
|
90cca4b79f17de44a131106d6dae14dfcfed8e88
|
binding/lua/util.lua
|
binding/lua/util.lua
|
#!/usr/bin/env lua
util = {}
ffi = require('ffi')
util.tensor_type = {
['unsigned char'] = 'torch.ByteTensor',
['char'] = 'torch.CharTensor',
['short'] = 'torch.ShortTensor',
['int'] = 'torch.IntTensor',
['long'] = 'torch.LongTensor',
['float'] ='torch.FloatTensor',
['double'] = 'torch.DoubleTensor'
}
function util.tensor2cdata(data, data_type)
data_type = data_type or 'float'
tensor_type = util.tensor_type[data_type]
return torch.Tensor(data):contiguous():type(tensor_type):data()
end
function util.cdata2tensor(cdata, sizes, data_type)
data_type = data_type or 'float'
tensor_type = util.tensor_type[data_type]
data = torch.Tensor(sizes):type(tensor_type)
ffi.copy(data:data(), cdata, data:nElement() * ffi.sizeof(data_type))
return data
end
function util.Set(list)
local set = {}
for _, l in ipairs(list) do set[l] = true end
return set
end
return util
|
#!/usr/bin/env lua
util = {}
ffi = require('ffi')
util.tensor_type = {
['unsigned char'] = 'torch.ByteTensor',
['char'] = 'torch.CharTensor',
['short'] = 'torch.ShortTensor',
['int'] = 'torch.IntTensor',
['long'] = 'torch.LongTensor',
['float'] ='torch.FloatTensor',
['double'] = 'torch.DoubleTensor'
}
function util.tensor2cdata(data, data_type)
if type(data) == 'table' then
data = torch.Tensor(data)
end
data_type = data_type or 'float'
tensor_type = util.tensor_type[data_type]
return data:contiguous():type(tensor_type):data()
end
function util.cdata2tensor(cdata, sizes, data_type)
data_type = data_type or 'float'
tensor_type = util.tensor_type[data_type]
data = torch.Tensor(sizes):type(tensor_type)
ffi.copy(data:data(), cdata, data:nElement() * ffi.sizeof(data_type))
return data
end
function util.Set(list)
local set = {}
for _, l in ipairs(list) do set[l] = true end
return set
end
return util
|
Bug fix for lua binding util.
|
Bug fix for lua binding util.
|
Lua
|
mit
|
Microsoft/multiverso,Microsoft/multiverso,zhengsx/multiverso,you-n-g/multiverso,liming-vie/multiverso,you-n-g/multiverso,liming-vie/multiverso,you-n-g/multiverso,zhengsx/multiverso,zhengsx/multiverso,Microsoft/multiverso,Microsoft/multiverso,liming-vie/multiverso,liming-vie/multiverso,zhengsx/multiverso,you-n-g/multiverso
|
5a629e429752c5f99d1233cb133bdf614fb7d7c0
|
lua_modules/ds18b20/ds18b20.lua
|
lua_modules/ds18b20/ds18b20.lua
|
--------------------------------------------------------------------------------
-- DS18B20 one wire module for NODEMCU
-- NODEMCU TEAM
-- LICENCE: http://opensource.org/licenses/MIT
-- Vowstar <[email protected]>
--------------------------------------------------------------------------------
-- Set module name as parameter of require
local modname = ...
local M = {}
_G[modname] = M
--------------------------------------------------------------------------------
-- Local used variables
--------------------------------------------------------------------------------
-- DS18B20 dq pin
local pin = nil
-- DS18B20 default pin
local defaultPin = 9
--------------------------------------------------------------------------------
-- Local used modules
--------------------------------------------------------------------------------
-- Table module
local table = table
-- String module
local string = string
-- One wire module
local ow = ow
-- Timer module
local tmr = tmr
-- Limited to local environment
setfenv(1,M)
--------------------------------------------------------------------------------
-- Implementation
--------------------------------------------------------------------------------
C = 0
F = 1
K = 2
function setup(dq)
pin = dq
if(pin == nil) then
pin = defaultPin
end
ow.setup(pin)
end
function addrs()
setup(pin)
tbl = {}
ow.reset_search(pin)
repeat
addr = ow.search(pin)
if(addr ~= nil) then
table.insert(tbl, addr)
end
tmr.wdclr()
until (addr == nil)
ow.reset_search(pin)
return tbl
end
function readNumber(addr, unit)
result = nil
setup(pin)
flag = false
if(addr == nil) then
ow.reset_search(pin)
count = 0
repeat
count = count + 1
addr = ow.search(pin)
tmr.wdclr()
until((addr ~= nil) or (count > 100))
ow.reset_search(pin)
end
if(addr == nil) then
return result
end
crc = ow.crc8(string.sub(addr,1,7))
if (crc == addr:byte(8)) then
if ((addr:byte(1) == 0x10) or (addr:byte(1) == 0x28)) then
-- print("Device is a DS18S20 family device.")
ow.reset(pin)
ow.select(pin, addr)
ow.write(pin, 0x44, 1)
-- tmr.delay(1000000)
present = ow.reset(pin)
ow.select(pin, addr)
ow.write(pin,0xBE,1)
-- print("P="..present)
data = nil
data = string.char(ow.read(pin))
for i = 1, 8 do
data = data .. string.char(ow.read(pin))
end
-- print(data:byte(1,9))
crc = ow.crc8(string.sub(data,1,8))
-- print("CRC="..crc)
if (crc == data:byte(9)) then
if(unit == nil or unit == C) then
t = (data:byte(1) + data:byte(2) * 256) * 625
elseif(unit == F) then
t = (data:byte(1) + data:byte(2) * 256) * 1125 + 320000
elseif(unit == K) then
t = (data:byte(1) + data:byte(2) * 256) * 625 + 2731500
else
return nil
end
t = t / 10000
-- print("Temperature="..t1.."."..t2.." Centigrade")
-- result = t1.."."..t2
return t
end
tmr.wdclr()
else
-- print("Device family is not recognized.")
end
else
-- print("CRC is not valid!")
end
return result
end
function read(addr, unit)
t = readNumber(addr, unit)
if (t == nil) then
return nil
else
return t
end
end
-- Return module table
return M
|
--------------------------------------------------------------------------------
-- DS18B20 one wire module for NODEMCU
-- NODEMCU TEAM
-- LICENCE: http://opensource.org/licenses/MIT
-- Vowstar <[email protected]>
-- 2015/02/14 sza2 <[email protected]> Fix for negative values
--------------------------------------------------------------------------------
-- Set module name as parameter of require
local modname = ...
local M = {}
_G[modname] = M
--------------------------------------------------------------------------------
-- Local used variables
--------------------------------------------------------------------------------
-- DS18B20 dq pin
local pin = nil
-- DS18B20 default pin
local defaultPin = 9
--------------------------------------------------------------------------------
-- Local used modules
--------------------------------------------------------------------------------
-- Table module
local table = table
-- String module
local string = string
-- One wire module
local ow = ow
-- Timer module
local tmr = tmr
-- Limited to local environment
setfenv(1,M)
--------------------------------------------------------------------------------
-- Implementation
--------------------------------------------------------------------------------
C = 0
F = 1
K = 2
function setup(dq)
pin = dq
if(pin == nil) then
pin = defaultPin
end
ow.setup(pin)
end
function addrs()
setup(pin)
tbl = {}
ow.reset_search(pin)
repeat
addr = ow.search(pin)
if(addr ~= nil) then
table.insert(tbl, addr)
end
tmr.wdclr()
until (addr == nil)
ow.reset_search(pin)
return tbl
end
function readNumber(addr, unit)
result = nil
setup(pin)
flag = false
if(addr == nil) then
ow.reset_search(pin)
count = 0
repeat
count = count + 1
addr = ow.search(pin)
tmr.wdclr()
until((addr ~= nil) or (count > 100))
ow.reset_search(pin)
end
if(addr == nil) then
return result
end
crc = ow.crc8(string.sub(addr,1,7))
if (crc == addr:byte(8)) then
if ((addr:byte(1) == 0x10) or (addr:byte(1) == 0x28)) then
-- print("Device is a DS18S20 family device.")
ow.reset(pin)
ow.select(pin, addr)
ow.write(pin, 0x44, 1)
-- tmr.delay(1000000)
present = ow.reset(pin)
ow.select(pin, addr)
ow.write(pin,0xBE,1)
-- print("P="..present)
data = nil
data = string.char(ow.read(pin))
for i = 1, 8 do
data = data .. string.char(ow.read(pin))
end
-- print(data:byte(1,9))
crc = ow.crc8(string.sub(data,1,8))
-- print("CRC="..crc)
if (crc == data:byte(9)) then
t = (data:byte(1) + data:byte(2) * 256)
if (t > 32767) then
t = -(65536 - t)
end
if(unit == nil or unit == C) then
t = t * 625
elseif(unit == F) then
t = t * 1125 + 320000
elseif(unit == K) then
t = t * 625 + 2731500
else
return nil
end
t = t / 10000
-- print("Temperature="..t1.."."..t2.." Centigrade")
-- result = t1.."."..t2
return t
end
tmr.wdclr()
else
-- print("Device family is not recognized.")
end
else
-- print("CRC is not valid!")
end
return result
end
function read(addr, unit)
t = readNumber(addr, unit)
if (t == nil) then
return nil
else
return t
end
end
-- Return module table
return M
|
Fix for negative values
|
Fix for negative values
|
Lua
|
mit
|
zhujunsan/nodemcu-firmware,iotcafe/nodemcu-firmware,vowstar/nodemcu-firmware,remspoor/nodemcu-firmware,funshine/nodemcu-firmware,HEYAHONG/nodemcu-firmware,cal101/nodemcu-firmware,karrots/nodemcu-firmware,HEYAHONG/nodemcu-firmware,marcelstoer/nodemcu-firmware,bogvak/nodemcu-firmware,luizfeliperj/nodemcu-firmware,raburton/nodemcu-firmware,christakahashi/nodemcu-firmware,klukonin/nodemcu-firmware,karrots/nodemcu-firmware,dnc40085/nodemcu-firmware,digitalloggers/nodemcu-firmware,flexiti/nodemcu-firmware,dscoolx6/MyESP8266,marktsai0316/nodemcu-firmware,fetchbot/nodemcu-firmware,nodemcu/nodemcu-firmware,ktosiu/nodemcu-firmware,Audumla/audiot-nodemcu-firmware,devsaurus/nodemcu-firmware,rickvanbodegraven/nodemcu-firmware,karrots/nodemcu-firmware,shangwudong/MyNodeMcu,fetchbot/nodemcu-firmware,Alkorin/nodemcu-firmware,shangwudong/MyNodeMcu,filug/nodemcu-firmware,SmartArduino/nodemcu-firmware,radiojam11/nodemcu-firmware,benwolfe/nodemcu-firmware,rowellx68/nodemcu-firmware-custom,klukonin/nodemcu-firmware,Andrew-Collins/nodemcu-firmware,chadouming/nodemcu-firmware,christakahashi/nodemcu-firmware,shangwudong/MyNodeMcu,weera00/nodemcu-firmware,HEYAHONG/nodemcu-firmware,weera00/nodemcu-firmware,anusornc/nodemcu-firmware,devsaurus/nodemcu-firmware,filug/nodemcu-firmware,nwf/nodemcu-firmware,christakahashi/nodemcu-firmware,petrkr/nodemcu-firmware,TerryE/nodemcu-firmware,fetchbot/nodemcu-firmware,ciufciuf57/nodemcu-firmware,danronco/nodemcu-firmware,cs8425/nodemcu-firmware,eku/nodemcu-firmware,marcelstoer/nodemcu-firmware,oyooyo/nodemcu-firmware,abgoyal/nodemcu-firmware,xatanais/nodemcu-firmware,bogvak/nodemcu-firmware,christakahashi/nodemcu-firmware,dan-cleinmark/nodemcu-firmware,oyooyo/nodemcu-firmware,londry/nodemcu-firmware,FelixPe/nodemcu-firmware,raburton/nodemcu-firmware,TerryE/nodemcu-firmware,weera00/nodemcu-firmware,radiojam11/nodemcu-firmware,vsky279/nodemcu-firmware,flexiti/nodemcu-firmware,christakahashi/nodemcu-firmware,Andrew-Collins/nodemcu-firmware,ojahan/node-mcu-firmware,abgoyal/nodemcu-firmware,ruisebastiao/nodemcu-firmware,djphoenix/nodemcu-firmware,londry/nodemcu-firmware,FelixPe/nodemcu-firmware,bhrt/nodeMCU,danronco/nodemcu-firmware,FrankX0/nodemcu-firmware,chadouming/nodemcu-firmware,remspoor/nodemcu-firmware,makefu/nodemcu-firmware,dnc40085/nodemcu-firmware,yurenyong123/nodemcu-firmware,kbeckmann/nodemcu-firmware,marcelstoer/nodemcu-firmware,robertfoss/nodemcu-firmware,jmattsson/nodemcu-firmware,natetrue/nodemcu-firmware,FrankX0/nodemcu-firmware,jmattsson/nodemcu-firmware,zhujunsan/nodemcu-firmware,borromeotlhs/nodemcu-firmware,ciufciuf57/nodemcu-firmware,Andrew-Collins/nodemcu-firmware,filug/nodemcu-firmware,devsaurus/nodemcu-firmware,jmattsson/nodemcu-firmware,benwolfe/nodemcu-firmware,digitalloggers/nodemcu-firmware,nwf/nodemcu-firmware,ojahan/node-mcu-firmware,Audumla/audiot-nodemcu-firmware,Audumla/audiot-nodemcu-firmware,petrkr/nodemcu-firmware,anusornc/nodemcu-firmware,Alkorin/nodemcu-firmware,TerryE/nodemcu-firmware,zhujunsan/nodemcu-firmware,iotcafe/nodemcu-firmware,anusornc/nodemcu-firmware,Alkorin/nodemcu-firmware,bhrt/nodeMCU,noahchense/nodemcu-firmware,iotcafe/nodemcu-firmware,marcelstoer/nodemcu-firmware,kbeckmann/nodemcu-firmware,daned33/nodemcu-firmware,Kisaua/nodemcu-firmware,TerryE/nodemcu-firmware,romanchyla/nodemcu-firmware,luizfeliperj/nodemcu-firmware,vowstar/nodemcu-firmware,romanchyla/nodemcu-firmware,creationix/nodemcu-firmware,borromeotlhs/nodemcu-firmware,robertfoss/nodemcu-firmware,dscoolx6/MyESP8266,vowstar/nodemcu-firmware,zerog2k/nodemcu-firmware,digitalloggers/nodemcu-firmware,vsky279/nodemcu-firmware,bogvak/nodemcu-firmware,TerryE/nodemcu-firmware,cal101/nodemcu-firmware,marktsai0316/nodemcu-firmware,abgoyal/nodemcu-firmware,petrkr/nodemcu-firmware,borromeotlhs/nodemcu-firmware,FelixPe/nodemcu-firmware,Alkorin/nodemcu-firmware,nodemcu/nodemcu-firmware,yurenyong123/nodemcu-firmware,remspoor/nodemcu-firmware,makefu/nodemcu-firmware,remspoor/nodemcu-firmware,kbeckmann/nodemcu-firmware,chadouming/nodemcu-firmware,noahchense/nodemcu-firmware,klukonin/nodemcu-firmware,luizfeliperj/nodemcu-firmware,flexiti/nodemcu-firmware,AllAboutEE/nodemcu-firmware,fetchbot/nodemcu-firmware,zerog2k/nodemcu-firmware,radiojam11/nodemcu-firmware,vsky279/nodemcu-firmware,raburton/nodemcu-firmware,funshine/nodemcu-firmware,vsky279/nodemcu-firmware,vsky279/nodemcu-firmware,yurenyong123/nodemcu-firmware,oyooyo/nodemcu-firmware,londry/nodemcu-firmware,zerog2k/nodemcu-firmware,karrots/nodemcu-firmware,dan-cleinmark/nodemcu-firmware,eku/nodemcu-firmware,cs8425/nodemcu-firmware,rickvanbodegraven/nodemcu-firmware,ruisebastiao/nodemcu-firmware,chadouming/nodemcu-firmware,dnc40085/nodemcu-firmware,funshine/nodemcu-firmware,kbeckmann/nodemcu-firmware,nodemcu/nodemcu-firmware,benwolfe/nodemcu-firmware,nwf/nodemcu-firmware,dscoolx6/MyESP8266,cs8425/nodemcu-firmware,bhrt/nodeMCU,orlando3d/nodemcu-firmware,dnc40085/nodemcu-firmware,ktosiu/nodemcu-firmware,robertfoss/nodemcu-firmware,funshine/nodemcu-firmware,rowellx68/nodemcu-firmware-custom,natetrue/nodemcu-firmware,natetrue/nodemcu-firmware,HEYAHONG/nodemcu-firmware,ciufciuf57/nodemcu-firmware,ojahan/node-mcu-firmware,nodemcu/nodemcu-firmware,FelixPe/nodemcu-firmware,bhrt/nodeMCU,creationix/nodemcu-firmware,romanchyla/nodemcu-firmware,rickvanbodegraven/nodemcu-firmware,Kisaua/nodemcu-firmware,shangwudong/MyNodeMcu,orlando3d/nodemcu-firmware,cal101/nodemcu-firmware,jmattsson/nodemcu-firmware,eku/nodemcu-firmware,mikeller/nodemcu-firmware,devsaurus/nodemcu-firmware,HEYAHONG/nodemcu-firmware,xatanais/nodemcu-firmware,ruisebastiao/nodemcu-firmware,ktosiu/nodemcu-firmware,luizfeliperj/nodemcu-firmware,marcelstoer/nodemcu-firmware,djphoenix/nodemcu-firmware,xatanais/nodemcu-firmware,mikeller/nodemcu-firmware,noahchense/nodemcu-firmware,dnc40085/nodemcu-firmware,sowbug/nodemcu-firmware,FrankX0/nodemcu-firmware,karrots/nodemcu-firmware,daned33/nodemcu-firmware,remspoor/nodemcu-firmware,SmartArduino/nodemcu-firmware,djphoenix/nodemcu-firmware,oyooyo/nodemcu-firmware,marktsai0316/nodemcu-firmware,AllAboutEE/nodemcu-firmware,kbeckmann/nodemcu-firmware,orlando3d/nodemcu-firmware,nwf/nodemcu-firmware,makefu/nodemcu-firmware,FrankX0/nodemcu-firmware,SmartArduino/nodemcu-firmware,petrkr/nodemcu-firmware,shangwudong/MyNodeMcu,eku/nodemcu-firmware,petrkr/nodemcu-firmware,daned33/nodemcu-firmware,bhrt/nodeMCU,AllAboutEE/nodemcu-firmware,djphoenix/nodemcu-firmware,Kisaua/nodemcu-firmware,sowbug/nodemcu-firmware,mikeller/nodemcu-firmware,creationix/nodemcu-firmware,devsaurus/nodemcu-firmware,nodemcu/nodemcu-firmware,sowbug/nodemcu-firmware,nwf/nodemcu-firmware,rowellx68/nodemcu-firmware-custom,danronco/nodemcu-firmware,FelixPe/nodemcu-firmware,funshine/nodemcu-firmware,Alkorin/nodemcu-firmware,dan-cleinmark/nodemcu-firmware,jmattsson/nodemcu-firmware,FrankX0/nodemcu-firmware
|
e1f0688b5ff0a4aaaca7ba681c8e94039a45d9bf
|
search-engine_0.0.1/v2/main.lua
|
search-engine_0.0.1/v2/main.lua
|
local events = require("__flib__.event")
local gui = require("__flib__.gui-beta")
local gui_generic = require("v2/gui/gui_generic")
local gui_step1 = require("v2/gui/step_1_search_spec")
local search_results = require("v2/gui/search_results")
local search = require("v2/search/searcher")
local filters = require("v2/plugins/filters/filters")
local migration = require("__flib__.migration")
local function handle_action(msg, e)
-- game.print("HANDLE ACTION " .. game.tick)
-- game.print(serpent.block(e))
-- game.print(serpent.block(msg))
if msg == "close_window" then
local element = e.element
while element.parent and element.parent.parent do
element = element.parent
end
local tags = gui.get_tags(element)
if tags and tags.search_id then
global.searches[tags.search_id] = nil
end
element.destroy()
end
if type(msg) == "table" then
if msg.gui == 1 then
gui_step1.handle_action(msg, e)
end
if msg.type == "result" or msg.type == "results_batch" then
search_results.handle_action(msg, e)
end
if msg.type == "filters" then
filters.handle_action(msg, e)
end
end
end
gui.hook_events(function(e)
local msg = gui.read_action(e)
if msg then
handle_action(msg, e)
end
end)
events.on_lua_shortcut(function(event)
if event.prototype_name == "search-engine" then
gui_step1.open_small_gui(game.players[event.player_index])
end
end)
events.register("search-engine-open-search", function(event)
gui_step1.open_small_gui(game.players[event.player_index])
end)
events.on_tick(function (e) search.on_tick(e) end)
events.on_configuration_changed(function(e)
if migration.on_config_changed(e, {}) then
for _, player in pairs(game.players) do
gui_generic.create_mod_gui_button(player)
end
end
end)
|
local events = require("__flib__.event")
local gui = require("__flib__.gui-beta")
local gui_generic = require("v2/gui/gui_generic")
local gui_step1 = require("v2/gui/step_1_search_spec")
local search_results = require("v2/gui/search_results")
local search = require("v2/search/searcher")
local filters = require("v2/plugins/filters/filters")
local migration = require("__flib__.migration")
local function handle_action(msg, e)
-- game.print("HANDLE ACTION " .. game.tick)
-- game.print(serpent.block(e))
-- game.print(serpent.block(msg))
if msg == "close_window" then
local element = e.element
while element.parent and element.parent.parent do
element = element.parent
end
local tags = gui.get_tags(element)
if tags and tags.search_id then
global.searches[tags.search_id] = nil
end
element.destroy()
end
if type(msg) == "table" then
if msg.gui == 1 then
gui_step1.handle_action(msg, e)
end
if msg.type == "result" or msg.type == "results_batch" then
search_results.handle_action(msg, e)
end
if msg.type == "filters" then
filters.handle_action(msg, e)
end
end
end
gui.hook_events(function(e)
local msg = gui.read_action(e)
if msg then
handle_action(msg, e)
end
end)
events.on_lua_shortcut(function(event)
if event.prototype_name == "search-engine" then
gui_step1.open_small_gui(game.players[event.player_index])
end
end)
events.register("search-engine-open-search", function(event)
gui_step1.open_small_gui(game.players[event.player_index])
end)
events.on_tick(function (e) search.on_tick(e) end)
events.on_configuration_changed(function(e)
if migration.on_config_changed(e, {}) then
for _, player in pairs(game.players) do
gui_generic.create_mod_gui_button(player)
end
end
end)
|
Search Engine: Fix indentation inconsistency
|
Search Engine: Fix indentation inconsistency
|
Lua
|
mit
|
Zomis/FactorioMods
|
a86e122b15e915f73523c14fb4e93023088a8112
|
scripts/kettle_full.lua
|
scripts/kettle_full.lua
|
-- kettle_full v1.1 by Bardoth. Revised by Tallow
--
-- Automatically runs many kettles, stoking as necessary.
--
dofile("common.inc");
askText = singleLine([[
Kettles v1.1 (by Bardoth, revised by Tallow) --
Automatically runs many kettles, stoking as necessary. Make sure the
VT window is in the TOP-RIGHT corner of the screen.
]])
wmText = "Tap control on kettles to open and pin.";
actions = {
{
label = "Potash",
buttonPos = makePoint(30, 10);
stoked = true,
menuImage = "Kettle_Potash.png",
output = 5,
matLabels = {"Ash", "Water", "Wood"},
matCounts = {5, 25, 28}
},
{
label = "Flower Fert",
buttonPos = makePoint(30, 40);
stoked = false,
menuImage = "Kettle_Flower_Fert.png",
output = 50,
matLabels = {"Rotten Fish", "Water", "Wood"},
matCounts = {3, 5, 5}
},
{
label = "Grain Fert",
buttonPos = makePoint(30, 70);
stoked = false,
menuImage = "Kettle_Grain_Fert.png",
output = 50,
matLabels = {"Rotten Fish", "Dung", "Water", "Wood"},
matCounts = {1, 1, 5, 5}
},
{
label = "Weed Killer",
buttonPos = makePoint(30, 100);
stoked = false,
menuImage = "Kettle_Weed_Killer.png",
output = 50,
matLabels = {"Toad Skin Mushrooms", "Water", "Wood"},
matCounts = {1, 5, 5}
},
{
label = "Sulfur",
buttonPos = makePoint(30, 130);
stoked = true,
menuImage = "Kettle_Sulfur.png",
output = 25,
matLabels = {"Sulphurous Water", "Wood"},
matCounts = {25, 28}
},
{
label = "Salt",
buttonPos = makePoint(30, 160);
stoked = true,
menuImage = "Kettle_Salt.png",
output = 3,
matLabels = {"Coconut Water", "Wood"},
matCounts = {25, 28}
},
{
label = "Acid",
buttonPos = makePoint(30, 190);
stoked = true,
menuImage = "Kettle_Acid.png",
output = 3,
matLabels = {"Sulphurous Water", "Salt", "Wood"},
matCounts = {25, 1, 28}
},
{
label = "Arsenic",
buttonPos = makePoint(30, 220);
stoked = false,
menuImage = "Kettle_Arsenic.png",
output = 8,
matLabels = {"Razor's Edge Mushrooms", "Scorpion's Brood Mushrooms",
"Oil", "Wood"},
matCounts = {1, 1, 5, 5}
},
{
label = "Geb's Tears",
buttonPos = makePoint(30, 250);
stoked = false,
menuImage = "Kettle_Gebs_Tears.png",
output = 1,
matLabels = {"Flower Bulbs", "Water", "Wood"},
matCounts = {30, 20, 20}
}
};
function runKettles(num_loops, action)
for i=1, num_loops do
drawWater();
refreshAll();
clickAllImages(action.menuImage);
lsSleep(200);
clickAllImages("Kettle_Begin.png");
lsSleep(200);
local message = "(" .. i .. "/" .. num_loops .. ") Making "
.. action.label;
waitForKettles(message, action.stoked);
clickAllImages("kettle_take.png");
lsSleep(200);
end
end
function refreshAll()
clickAllImages("ThisIs.png");
lsSleep(200);
end
function waitForKettles(message, stoked)
local done = false;
while not done do
if stoked then
igniteAll();
end
srReadScreen();
local anchors = findAllImages("ThisIs.png");
done = true;
for i=1,#anchors do
if not stokeWindow(anchors[i], stoked) then
done = false;
end
end
sleepWithStatus(5000, message);
end
end
function igniteAll()
srReadScreen();
local ignite = findAllImages("Ignite.png");
for i=1,#ignite do
srClickMouseNoMove(ignite[i][0] + 5, ignite[i][1] + 5);
local maxButton = waitForImage("Kettle_Max.png", 500,
"Waiting for Max button");
if maxButton then
safeClick(maxButton[0], maxButton[1])
else
error("Timed out waiting for max button.");
end
lsSleep(50);
end
if #ignite > 0 then
--The lag is causing the refresh to not show "stoke max". Need a bit of a pause.
sleepWithStatus(2000, "Waiting for refresh");
refreshAll();
end
end
function stokeWindow(anchor, stoked)
local done = true;
local bounds = srGetWindowBorders(anchor[0], anchor[1]);
local takePos = findImageInWindow("kettle_take.png", anchor[0], anchor[1],
bounds);
if not takePos then
done = false;
if stoked then
local wood = nil;
local water = nil;
local woodPos = findImageInWindow("Kettle_wood.png", anchor[0], anchor[1],
bounds);
if woodPos then
wood = ocrNumber(woodPos[0] + 34, woodPos[1], SMALL_SET);
end
local waterPos = findImageInWindow("Kettle_water.png", anchor[0],
anchor[1], bounds);
if waterPos then
water = ocrNumber(waterPos[0] + 34, waterPos[1], SMALL_SET);
end
if wood and water
and ((wood < 2 and water > 6)
or (water <= 6 and wood < water - 1))
then
local stoke = findImageInWindow("StokeMax.png", anchor[0], anchor[1],
bounds);
if stoke then
safeClick(stoke[0] + 5, stoke[1] + 5);
end
elseif not woodPos and not waterPos then
done = true;
end
end
end
return done;
end
function doit()
askForWindow(askText);
windowManager("Kettle Setup", wmText, false, true, 215, 298);
askForFocus();
unpinOnExit(menuKettles);
end
function menuKettles()
-- Ask for which button
local selected = nil;
while not selected do
for i=1, #actions do
if lsButtonText(actions[i].buttonPos[0], actions[i].buttonPos[1],
0, 250, 0x80D080ff, actions[i].label) then
selected = actions[i];
end
end
if lsButtonText(lsScreenX - 110, lsScreenY - 30, z, 100, 0xFFFFFFff,
"End script")
then
selected = nil;
break;
end
lsDoFrame();
lsSleep(tick_delay);
end
if selected then
srReadScreen();
local kettles = #(findAllImages("ThisIs.png"));
local num_loops = promptNumber("How many passes ?", 10);
local message = "Making " .. selected.label .. " requires:\n";
for i=1,#(selected.matLabels) do
message = message .. " " .. selected.matCounts[i]*num_loops*kettles
.. " " .. selected.matLabels[i] .. "\n";
end
askForWindow(message);
runKettles(num_loops, selected);
end
end
|
-- kettle_full v1.1 by Bardoth. Revised by Tallow
--
-- Automatically runs many kettles, stoking as necessary.
--
dofile("common.inc");
askText = singleLine([[
Kettles v1.1 (by Bardoth, revised by Tallow) --
Automatically runs many kettles, stoking as necessary. Make sure the
VT window is in the TOP-RIGHT corner of the screen.
]])
wmText = "Tap Ctrl on kettles to open and pin.\nTap Alt on kettles to open, pin and stash.";
actions = {
{
label = "Potash",
buttonPos = makePoint(30, 10);
stoked = true,
menuImage = "Kettle_Potash.png",
output = 5,
matLabels = {"Ash", "Water", "Wood"},
matCounts = {5, 25, 28}
},
{
label = "Flower Fert",
buttonPos = makePoint(30, 40);
stoked = false,
menuImage = "Kettle_Flower_Fert.png",
output = 50,
matLabels = {"Rotten Fish", "Water", "Wood"},
matCounts = {3, 5, 5}
},
{
label = "Grain Fert",
buttonPos = makePoint(30, 70);
stoked = false,
menuImage = "Kettle_Grain_Fert.png",
output = 50,
matLabels = {"Rotten Fish", "Dung", "Water", "Wood"},
matCounts = {1, 1, 5, 5}
},
{
label = "Weed Killer",
buttonPos = makePoint(30, 100);
stoked = false,
menuImage = "Kettle_Weed_Killer.png",
output = 50,
matLabels = {"Toad Skin Mushrooms", "Water", "Wood"},
matCounts = {1, 5, 5}
},
{
label = "Sulfur",
buttonPos = makePoint(30, 130);
stoked = true,
menuImage = "Kettle_Sulfur.png",
output = 25,
matLabels = {"Sulphurous Water", "Wood"},
matCounts = {25, 28}
},
{
label = "Salt",
buttonPos = makePoint(30, 160);
stoked = true,
menuImage = "Kettle_Salt.png",
output = 3,
matLabels = {"Coconut Water", "Wood"},
matCounts = {25, 28}
},
{
label = "Acid",
buttonPos = makePoint(30, 190);
stoked = true,
menuImage = "Kettle_Acid.png",
output = 3,
matLabels = {"Sulphurous Water", "Salt", "Wood"},
matCounts = {25, 1, 28}
},
{
label = "Arsenic",
buttonPos = makePoint(30, 220);
stoked = false,
menuImage = "Kettle_Arsenic.png",
output = 8,
matLabels = {"Razor's Edge Mushrooms", "Scorpion's Brood Mushrooms",
"Oil", "Wood"},
matCounts = {1, 1, 5, 5}
},
{
label = "Geb's Tears",
buttonPos = makePoint(30, 250);
stoked = false,
menuImage = "Kettle_Gebs_Tears.png",
output = 1,
matLabels = {"Flower Bulbs", "Water", "Wood"},
matCounts = {30, 20, 20}
}
};
function runKettles(num_loops, action)
for i=1, num_loops do
drawWater();
refreshAll();
clickAllImages(action.menuImage);
lsSleep(200);
clickAllImages("Kettle_Begin.png");
lsSleep(200);
local message = "(" .. i .. "/" .. num_loops .. ") Making "
.. action.label;
waitForKettles(message, action.stoked);
clickAllImages("kettle_take.png");
lsSleep(200);
end
end
function refreshAll()
clickAllImages("ThisIs.png");
lsSleep(200);
end
function waitForKettles(message, stoked)
local done = false;
while not done do
if stoked then
igniteAll();
end
srReadScreen();
local anchors = findAllImages("ThisIs.png");
done = true;
for i=1,#anchors do
if not stokeWindow(anchors[i], stoked) then
done = false;
end
end
sleepWithStatus(5000, message);
end
end
function igniteAll()
srReadScreen();
local ignite = findAllImages("Ignite.png");
for i=1,#ignite do
srClickMouseNoMove(ignite[i][0] + 5, ignite[i][1] + 5);
local maxButton = waitForImage("Kettle_Max.png", 500,
"Waiting for Max button");
if maxButton then
safeClick(maxButton[0], maxButton[1])
else
error("Timed out waiting for max button.");
end
lsSleep(50);
end
if #ignite > 0 then
--The lag is causing the refresh to not show "stoke max". Need a bit of a pause.
sleepWithStatus(2000, "Waiting for refresh");
refreshAll();
end
end
function stokeWindow(anchor, stoked)
local done = true;
local bounds = srGetWindowBorders(anchor[0], anchor[1]);
local takePos = findImageInWindow("kettle_take.png", anchor[0], anchor[1],
bounds);
if not takePos then
done = false;
if stoked then
local wood = nil;
local water = nil;
local woodPos = findImageInWindow("Kettle_wood.png", anchor[0], anchor[1],
bounds);
if woodPos then
wood = ocrNumber(woodPos[0] + 34, woodPos[1], SMALL_SET);
end
local waterPos = findImageInWindow("Kettle_water.png", anchor[0],
anchor[1], bounds);
if waterPos then
water = ocrNumber(waterPos[0] + 34, waterPos[1], SMALL_SET);
end
if wood and water
and ((wood < 2 and water > 6)
or (water <= 6 and wood < water - 1))
then
local stoke = findImageInWindow("StokeMax.png", anchor[0], anchor[1],
bounds);
if stoke then
safeClick(stoke[0] + 5, stoke[1] + 5);
end
elseif not woodPos and not waterPos then
done = true;
end
end
end
return done;
end
function doit()
askForWindow(askText);
windowManager("Kettle Setup", wmText, false, true, 215, 288);
askForFocus();
unpinOnExit(menuKettles);
end
function menuKettles()
-- Ask for which button
local selected = nil;
while not selected do
for i=1, #actions do
if lsButtonText(actions[i].buttonPos[0], actions[i].buttonPos[1],
0, 250, 0x80D080ff, actions[i].label) then
selected = actions[i];
end
end
if lsButtonText(lsScreenX - 110, lsScreenY - 30, z, 100, 0xFFFFFFff,
"End script")
then
selected = nil;
break;
end
lsDoFrame();
lsSleep(tick_delay);
end
if selected then
srReadScreen();
local kettles = #(findAllImages("ThisIs.png"));
local num_loops = promptNumber("How many passes ?", 10);
local message = "Making " .. selected.label .. " requires:\n";
for i=1,#(selected.matLabels) do
message = message .. " " .. selected.matCounts[i]*num_loops*kettles
.. " " .. selected.matLabels[i] .. "\n";
end
askForWindow(message);
runKettles(num_loops, selected);
end
end
|
kettle_full.lua -- Reduce y by 10, Update wmText
|
kettle_full.lua -- Reduce y by 10, Update wmText
Undo the y update from
https://github.com/DashingStrike/Automato-ATITD/commit/61c9332e17b8a5a9fcee1c361ea48971da51c9cf
commit . This didn't fix the issue with kettle, instead
https://github.com/DashingStrike/Automato-ATITD/commit/092b3c15130d39077a817329062b4e2023df057b
was the fix.
|
Lua
|
mit
|
wzydhek/Automato-ATITD,DashingStrike/Automato-ATITD,wzydhek/Automato-ATITD,DashingStrike/Automato-ATITD
|
fe66d43370869ee24fda825988184ad7834d712b
|
modules/exchange.lua
|
modules/exchange.lua
|
local simplehttp = require'simplehttp'
local html2unicode = require'html'
local cc = {
["AED"] = "United Arab Emirates Dirham (AED)",
["ANG"] = "Netherlands Antillean Guilder (ANG)",
["ARS"] = "Argentine Peso (ARS)",
["AUD"] = "Australian Dollar (AUD)",
["BDT"] = "Bangladeshi Taka (BDT)",
["BGN"] = "Bulgarian Lev (BGN)",
["BHD"] = "Bahraini Dinar (BHD)",
["BND"] = "Brunei Dollar (BND)",
["BOB"] = "Bolivian Boliviano (BOB)",
["BRL"] = "Brazilian Real (BRL)",
["BWP"] = "Botswanan Pula (BWP)",
["CAD"] = "Canadian Dollar (CAD)",
["CHF"] = "Swiss Franc (CHF)",
["CLP"] = "Chilean Peso (CLP)",
["CNY"] = "Chinese Yuan (CNY)",
["COP"] = "Colombian Peso (COP)",
["CRC"] = "Costa Rican Colón (CRC)",
["CZK"] = "Czech Republic Koruna (CZK)",
["DKK"] = "Danish Krone (DKK)",
["DOP"] = "Dominican Peso (DOP)",
["DZD"] = "Algerian Dinar (DZD)",
["EEK"] = "Estonian Kroon (EEK)",
["EGP"] = "Egyptian Pound (EGP)",
["EUR"] = "Euro (EUR)",
["FJD"] = "Fijian Dollar (FJD)",
["GBP"] = "British Pound Sterling (GBP)",
["HKD"] = "Hong Kong Dollar (HKD)",
["HNL"] = "Honduran Lempira (HNL)",
["HRK"] = "Croatian Kuna (HRK)",
["HUF"] = "Hungarian Forint (HUF)",
["IDR"] = "Indonesian Rupiah (IDR)",
["ILS"] = "Israeli New Sheqel (ILS)",
["INR"] = "Indian Rupee (INR)",
["JMD"] = "Jamaican Dollar (JMD)",
["JOD"] = "Jordanian Dinar (JOD)",
["JPY"] = "Japanese Yen (JPY)",
["KES"] = "Kenyan Shilling (KES)",
["KRW"] = "South Korean Won (KRW)",
["KWD"] = "Kuwaiti Dinar (KWD)",
["KYD"] = "Cayman Islands Dollar (KYD)",
["KZT"] = "Kazakhstani Tenge (KZT)",
["LBP"] = "Lebanese Pound (LBP)",
["LKR"] = "Sri Lankan Rupee (LKR)",
["LTL"] = "Lithuanian Litas (LTL)",
["LVL"] = "Latvian Lats (LVL)",
["MAD"] = "Moroccan Dirham (MAD)",
["MDL"] = "Moldovan Leu (MDL)",
["MKD"] = "Macedonian Denar (MKD)",
["MUR"] = "Mauritian Rupee (MUR)",
["MVR"] = "Maldivian Rufiyaa (MVR)",
["MXN"] = "Mexican Peso (MXN)",
["MYR"] = "Malaysian Ringgit (MYR)",
["NAD"] = "Namibian Dollar (NAD)",
["NGN"] = "Nigerian Naira (NGN)",
["NIO"] = "Nicaraguan Córdoba (NIO)",
["NOK"] = "Norwegian Krone (NOK)",
["NPR"] = "Nepalese Rupee (NPR)",
["NZD"] = "New Zealand Dollar (NZD)",
["OMR"] = "Omani Rial (OMR)",
["PEN"] = "Peruvian Nuevo Sol (PEN)",
["PGK"] = "Papua New Guinean Kina (PGK)",
["PHP"] = "Philippine Peso (PHP)",
["PKR"] = "Pakistani Rupee (PKR)",
["PLN"] = "Polish Zloty (PLN)",
["PYG"] = "Paraguayan Guarani (PYG)",
["QAR"] = "Qatari Rial (QAR)",
["RON"] = "Romanian Leu (RON)",
["RSD"] = "Serbian Dinar (RSD)",
["RUB"] = "Russian Ruble (RUB)",
["SAR"] = "Saudi Riyal (SAR)",
["SCR"] = "Seychellois Rupee (SCR)",
["SEK"] = "Swedish Krona (SEK)",
["SGD"] = "Singapore Dollar (SGD)",
["SKK"] = "Slovak Koruna (SKK)",
["SLL"] = "Sierra Leonean Leone (SLL)",
["SVC"] = "Salvadoran Colón (SVC)",
["THB"] = "Thai Baht (THB)",
["TND"] = "Tunisian Dinar (TND)",
["TRY"] = "Turkish Lira (TRY)",
["TTD"] = "Trinidad and Tobago Dollar (TTD)",
["TWD"] = "New Taiwan Dollar (TWD)",
["TZS"] = "Tanzanian Shilling (TZS)",
["UAH"] = "Ukrainian Hryvnia (UAH)",
["UGX"] = "Ugandan Shilling (UGX)",
["USD"] = "US Dollar (USD)",
["UYU"] = "Uruguayan Peso (UYU)",
["UZS"] = "Uzbekistan Som (UZS)",
["VEF"] = "Venezuelan Bolívar (VEF)",
["VND"] = "Vietnamese Dong (VND)",
["XOF"] = "CFA Franc BCEAO (XOF)",
["YER"] = "Yemeni Rial (YER)",
["ZAR"] = "South African Rand (ZAR)",
["ZMK"] = "Zambian Kwacha (ZMK)",
}
local conv = {
['euro'] = 'eur',
['bux'] = 'usd',
}
-- make environment
local _X = setmetatable({
math = math,
print = function(val) if(val and tonumber(val)) then return tonumber(val) end end
}, {__index = math})
-- run code under environment
local function run(untrusted_code)
local untrusted_function, message = loadstring(untrusted_code)
if not untrusted_function then return nil, message end
setfenv(untrusted_function, _X)
return pcall(untrusted_function)
end
local parseData = function(data)
local data = data:match'<div id=currency_converter_result>(.-)</span>'
if(not data) then
return 'Some currency died? No exchange rates returned.'
end
return html2unicode(data:gsub('<.->', '')):gsub(' ', ' '):gsub('%w+', cc)
end
local checkInput = function(value, from, to)
if(not (cc[from] and cc[to])) then
return nil, string.format('Invalid currency: %s.', (not cc[from] and from) or (not cc[to] and to))
end
-- Control the input.
value = value:gsub(',', '.')
local success, value, err = run('return ' .. value)
if(err) then
return nil, string.format('Parsing of input failed: %s', err)
end
-- Number validation, serious business!
if(type(value) ~= 'number' or value <= 0 or value == math.huge or value ~= value) then
return nil, string.format('Invalid number provided: %s', tonumber(value))
end
return true, value
end
local handleExchange = function(self, source, destination, value, from, to)
-- Strip away to/in and spaces.
to = to:lower():gsub('[toin ]+ ', '')
from = from:lower()
-- Default to NOK.
if(to == '') then to = 'NOK' end
from = (conv[from] or from):upper()
to = (conv[to] or to):upper()
if(from == to) then
return self:Msg('privmsg', destination, source, 'wat ar u dewn... %s! STAHP!', source.nick)
end
local success, value = checkInput(value, from, to)
if(not success) then
self:Msg('privmsg', destination, source, '%s: %s', source.nick, value)
else
simplehttp(
('http://www.google.com/finance/converter?a=%s&from=%s&to=%s'):format(value, from, to),
function(data)
local message = parseData(data)
if(message) then
self:Msg('privmsg', destination, source, '%s: %s', source.nick, message)
end
end
)
end
end
return {
PRIVMSG = {
['^.xe (%S+) (%S+) ?(.*)$'] = handleExchange,
['^.cur (%S+) (%S+) ?(.*)$'] = handleExchange,
['^.jpy'] = function(self, source, destination)
handleExchange(self, source, destination, '100', 'JPY', 'NOK')
end
},
}
|
local simplehttp = require'simplehttp'
local html2unicode = require'html'
local cc = {
["AED"] = "United Arab Emirates Dirham (AED)",
["ANG"] = "Netherlands Antillean Guilder (ANG)",
["ARS"] = "Argentine Peso (ARS)",
["AUD"] = "Australian Dollar (AUD)",
["BDT"] = "Bangladeshi Taka (BDT)",
["BGN"] = "Bulgarian Lev (BGN)",
["BHD"] = "Bahraini Dinar (BHD)",
["BND"] = "Brunei Dollar (BND)",
["BOB"] = "Bolivian Boliviano (BOB)",
["BRL"] = "Brazilian Real (BRL)",
["BWP"] = "Botswanan Pula (BWP)",
["CAD"] = "Canadian Dollar (CAD)",
["CHF"] = "Swiss Franc (CHF)",
["CLP"] = "Chilean Peso (CLP)",
["CNY"] = "Chinese Yuan (CNY)",
["COP"] = "Colombian Peso (COP)",
["CRC"] = "Costa Rican Colón (CRC)",
["CZK"] = "Czech Republic Koruna (CZK)",
["DKK"] = "Danish Krone (DKK)",
["DOP"] = "Dominican Peso (DOP)",
["DZD"] = "Algerian Dinar (DZD)",
["EEK"] = "Estonian Kroon (EEK)",
["EGP"] = "Egyptian Pound (EGP)",
["EUR"] = "Euro (EUR)",
["FJD"] = "Fijian Dollar (FJD)",
["GBP"] = "British Pound Sterling (GBP)",
["HKD"] = "Hong Kong Dollar (HKD)",
["HNL"] = "Honduran Lempira (HNL)",
["HRK"] = "Croatian Kuna (HRK)",
["HUF"] = "Hungarian Forint (HUF)",
["IDR"] = "Indonesian Rupiah (IDR)",
["ILS"] = "Israeli New Sheqel (ILS)",
["INR"] = "Indian Rupee (INR)",
["JMD"] = "Jamaican Dollar (JMD)",
["JOD"] = "Jordanian Dinar (JOD)",
["JPY"] = "Japanese Yen (JPY)",
["KES"] = "Kenyan Shilling (KES)",
["KRW"] = "South Korean Won (KRW)",
["KWD"] = "Kuwaiti Dinar (KWD)",
["KYD"] = "Cayman Islands Dollar (KYD)",
["KZT"] = "Kazakhstani Tenge (KZT)",
["LBP"] = "Lebanese Pound (LBP)",
["LKR"] = "Sri Lankan Rupee (LKR)",
["LTL"] = "Lithuanian Litas (LTL)",
["LVL"] = "Latvian Lats (LVL)",
["MAD"] = "Moroccan Dirham (MAD)",
["MDL"] = "Moldovan Leu (MDL)",
["MKD"] = "Macedonian Denar (MKD)",
["MUR"] = "Mauritian Rupee (MUR)",
["MVR"] = "Maldivian Rufiyaa (MVR)",
["MXN"] = "Mexican Peso (MXN)",
["MYR"] = "Malaysian Ringgit (MYR)",
["NAD"] = "Namibian Dollar (NAD)",
["NGN"] = "Nigerian Naira (NGN)",
["NIO"] = "Nicaraguan Córdoba (NIO)",
["NOK"] = "Norwegian Krone (NOK)",
["NPR"] = "Nepalese Rupee (NPR)",
["NZD"] = "New Zealand Dollar (NZD)",
["OMR"] = "Omani Rial (OMR)",
["PEN"] = "Peruvian Nuevo Sol (PEN)",
["PGK"] = "Papua New Guinean Kina (PGK)",
["PHP"] = "Philippine Peso (PHP)",
["PKR"] = "Pakistani Rupee (PKR)",
["PLN"] = "Polish Zloty (PLN)",
["PYG"] = "Paraguayan Guarani (PYG)",
["QAR"] = "Qatari Rial (QAR)",
["RON"] = "Romanian Leu (RON)",
["RSD"] = "Serbian Dinar (RSD)",
["RUB"] = "Russian Ruble (RUB)",
["SAR"] = "Saudi Riyal (SAR)",
["SCR"] = "Seychellois Rupee (SCR)",
["SEK"] = "Swedish Krona (SEK)",
["SGD"] = "Singapore Dollar (SGD)",
["SKK"] = "Slovak Koruna (SKK)",
["SLL"] = "Sierra Leonean Leone (SLL)",
["SVC"] = "Salvadoran Colón (SVC)",
["THB"] = "Thai Baht (THB)",
["TND"] = "Tunisian Dinar (TND)",
["TRY"] = "Turkish Lira (TRY)",
["TTD"] = "Trinidad and Tobago Dollar (TTD)",
["TWD"] = "New Taiwan Dollar (TWD)",
["TZS"] = "Tanzanian Shilling (TZS)",
["UAH"] = "Ukrainian Hryvnia (UAH)",
["UGX"] = "Ugandan Shilling (UGX)",
["USD"] = "US Dollar (USD)",
["UYU"] = "Uruguayan Peso (UYU)",
["UZS"] = "Uzbekistan Som (UZS)",
["VEF"] = "Venezuelan Bolívar (VEF)",
["VND"] = "Vietnamese Dong (VND)",
["XOF"] = "CFA Franc BCEAO (XOF)",
["YER"] = "Yemeni Rial (YER)",
["ZAR"] = "South African Rand (ZAR)",
["ZMK"] = "Zambian Kwacha (ZMK)",
}
local conv = {
['euro'] = 'eur',
['bux'] = 'usd',
}
-- make environment
local _X = setmetatable({
math = math,
print = function(val) if(val and tonumber(val)) then return tonumber(val) end end
}, {__index = math})
-- run code under environment
local function run(untrusted_code)
local untrusted_function, message = loadstring(untrusted_code)
if not untrusted_function then return nil, message end
setfenv(untrusted_function, _X)
return pcall(untrusted_function)
end
local parseData = function(data)
local data = data:match'<div id=currency_converter_result>(.-)</span>'
if(not data) then
return 'Some currency died? No exchange rates returned.'
end
return html2unicode(data:gsub('<.->', '')):gsub(' ', ' '):gsub('%w+', cc)
end
local checkInput = function(value, from, to)
if(not (cc[from] and cc[to])) then
return nil, string.format('Invalid currency: %s.', (not cc[from] and from) or (not cc[to] and to))
end
-- Control the input.
value = value:gsub(',', '.')
local success, value, err = run('return ' .. value)
if(err) then
return nil, string.format('Parsing of input failed: %s', err)
end
-- Number validation, serious business!
if(type(value) ~= 'number' or value <= 0 or value == math.huge or value ~= value) then
return nil, string.format('Invalid number provided: %s', tonumber(value))
end
return true, value
end
local handleExchange = function(self, source, destination, value, from, to)
-- Strip away to/in and spaces.
to = to:lower():gsub('[toin ]+ ', '')
from = from:lower()
-- Default to NOK.
if(to == '') then to = 'NOK' end
from = (conv[from] or from):upper()
to = (conv[to] or to):upper()
if(from == to) then
return self:Msg('privmsg', destination, source, 'wat ar u dewn... %s! STAHP!', source.nick)
end
local success, value = checkInput(value, from, to)
if(not success) then
self:Msg('privmsg', destination, source, '%s: %s', source.nick, value)
else
simplehttp(
('http://www.google.com/finance/converter?a=%s&from=%s&to=%s'):format(value, from, to),
function(data)
local message = parseData(data)
if(message) then
self:Msg('privmsg', destination, source, '%s: %s', source.nick, message)
end
end
)
end
end
return {
PRIVMSG = {
['^%pxe (%S+) (%S+) ?(.*)$'] = handleExchange,
['^%pcur (%S+) (%S+) ?(.*)$'] = handleExchange,
['^%pusd'] = function(self, source, destination)
handleExchange(self, source, destination, '1', 'USD', 'NOK')
end,
['^%peur'] = function(self, source, destination)
handleExchange(self, source, destination, '1', 'EUR', 'NOK')
end,
['^%pjpy'] = function(self, source, destination)
handleExchange(self, source, destination, '100', 'JPY', 'NOK')
end
},
}
|
fix syntax error
|
fix syntax error
Former-commit-id: 7a7f478280aa8faccfafd4c75152a55c9294340d [formerly 2624985e452d7ba55cd30f762ca62c4d82f50178]
Former-commit-id: db52d54ff7c9fac2b96060cf4ac4e379946c31e2
|
Lua
|
mit
|
torhve/ivar2,torhve/ivar2,haste/ivar2,torhve/ivar2
|
94b601cbbaf3ac89a92aff3b72e273f1f9ee72f2
|
src/api-umbrella/utils/interval_lock.lua
|
src/api-umbrella/utils/interval_lock.lua
|
local lock = require "resty.lock"
local _M = {}
--- Only one thread can execute fn through its execution duration
-- A lock (mutex) is held while the function executes and released at the end.
-- Logs errors; no return value
-- @param name - a unique identifier for this lock (automatically namespaced)
-- @param fn - function to execute if the lock can be held
_M.mutex_exec = function(name, fn)
local check_lock = lock:new("locks", {["timeout"] = 0})
local _, lock_err = check_lock:lock("mutex_exec:" .. name)
if not lock_err then
local pcall_ok, pcall_err = pcall(fn)
-- always attempt to unlock, even if the call failed
local unlock_ok, unlock_err = check_lock:unlock()
if not pcall_ok then
ngx.log(ngx.ERR, "mutex exec pcall failed: ", pcall_err)
end
if not unlock_ok then
ngx.log(ngx.ERR, "failed to unlock: ", unlock_err)
end
end
end
--- Only allow a function to be executed once in a given interval
-- A lock (mutex) is set to expire after an interval of time. If the mutex is
-- present, execution won't take place. Logs errors, no return value
-- @param name - a unique identifier for this lock (automatically namespaced)
-- @param interval - the length of time until expiry (seconds)
-- @param fn - function to execute within the interval
_M.timeout_exec = function(name, interval, fn)
local mem_ok, mem_err = ngx.shared.interval_locks:add(name, true, interval)
if not mem_ok and mem_err ~= "exists" then
ngx.log(ngx.ERR, "failed to allocate inverval_locks: ", mem_err)
-- if not mem_ok and mem_err == "exists" is an acceptable scenario; it means
-- that the mutex hasn't expired yet. NOOP in this situation
elseif mem_ok then
local pcall_ok, pcall_err = pcall(fn)
if not pcall_ok then
ngx.log(ngx.ERR, "timeout exec pcall failed: ", pcall_err)
end
end
end
--- Call a function every `interval` amount of time
-- Set a timeout for next execution and run the provided function. Note that,
-- should the function execution take more time than the `interval`, this will
-- quickly backup. Combine with the mutexes above via `repeat_with_mutex`.
-- Logs errors, no return value
-- @param interval - the length of time until repeated (seconds)
-- @param fn - function to execute when the next timeout occurs
_M.repeat_exec = function(interval, fn)
-- schedule the next call
local ok, err = ngx.timer.at(interval, function(premature)
if not premature then
_M.repeat_exec(interval, fn)
end
end)
if not ok and err ~= "process exiting" then
ngx.log(ngx.ERR, "failed to create timer: ", err)
else
-- execute fn now (may tie down this thread)
local pcall_ok, pcall_err = pcall(fn)
if not pcall_ok then
ngx.log(ngx.ERR, "repeat exec pcall failed: ", pcall_err)
end
end
end
--- Call a function once (or less) per time interval, across all threads
-- If execution takes longer than the interval to complete, execution of the
-- next cycle will start on the following expiry
-- @param name - a unique identifier for the relevant locks
-- @param interval - minimum time in between executions (seconds)
-- @param fn - function to execute
_M.repeat_with_mutex = function(name, interval, fn)
_M.repeat_exec(interval, function()
_M.mutex_exec(name, function()
-- here we subtract the lock expiration time by 1ms to prevent
-- a race condition with the next timer event.
_M.timeout_exec(name, interval - 0.001, fn)
end)
end)
end
return _M
|
local lock = require "resty.lock"
local _M = {}
--- Only one thread can execute fn through its execution duration
-- A lock (mutex) is held while the function executes and released at the end.
-- Logs errors; no return value
-- @param name - a unique identifier for this lock (automatically namespaced)
-- @param fn - function to execute if the lock can be held
_M.mutex_exec = function(name, fn)
local check_lock = lock:new("locks", {["timeout"] = 0})
local _, lock_err = check_lock:lock("mutex_exec:" .. name)
if not lock_err then
local pcall_ok, pcall_err = pcall(fn)
-- always attempt to unlock, even if the call failed
local unlock_ok, unlock_err = check_lock:unlock()
if not pcall_ok then
ngx.log(ngx.ERR, "mutex exec pcall failed: ", pcall_err)
end
if not unlock_ok then
ngx.log(ngx.ERR, "failed to unlock: ", unlock_err)
end
end
end
--- Only allow a function to be executed once in a given interval
-- A lock (mutex) is set to expire after an interval of time. If the mutex is
-- present, execution won't take place. Logs errors, no return value
-- @param name - a unique identifier for this lock (automatically namespaced)
-- @param interval - the length of time until expiry (seconds)
-- @param fn - function to execute within the interval
_M.timeout_exec = function(name, interval, fn)
local mem_ok, mem_err = ngx.shared.interval_locks:add(name, true, interval)
if not mem_ok and mem_err ~= "exists" then
ngx.log(ngx.ERR, "failed to allocate inverval_locks: ", mem_err)
-- if not mem_ok and mem_err == "exists" is an acceptable scenario; it means
-- that the mutex hasn't expired yet. NOOP in this situation
elseif mem_ok then
local pcall_ok, pcall_err = pcall(fn)
if not pcall_ok then
ngx.log(ngx.ERR, "timeout exec pcall failed: ", pcall_err)
end
end
end
--- Call a function every `interval` amount of time
-- Set a timeout for next execution and run the provided function. Note that,
-- should the function execution take more time than the `interval`, this will
-- quickly backup. Combine with the mutexes above via `repeat_with_mutex`.
-- Logs errors, no return value
-- @param interval - the length of time until repeated (seconds)
-- @param fn - function to execute when the next timeout occurs
_M.repeat_exec = function(interval, fn)
-- schedule the next call
local ok, err = ngx.timer.at(interval, function(premature)
if not premature then
_M.repeat_exec(interval, fn)
end
end)
if not ok and err ~= "process exiting" then
ngx.log(ngx.ERR, "failed to create timer: ", err)
else
-- execute fn now (may tie down this thread)
local pcall_ok, pcall_err = pcall(fn)
if not pcall_ok then
ngx.log(ngx.ERR, "repeat exec pcall failed: ", pcall_err)
end
end
end
--- Call a function once (or less) per time interval, across all threads
-- If execution takes longer than the interval to complete, execution of the
-- next cycle will start on the following expiry
-- @param name - a unique identifier for the relevant locks
-- @param interval - minimum time in between executions (seconds)
-- @param fn - function to execute
_M.repeat_with_mutex = function(name, interval, fn)
-- Wrap the initial call in an immediate timer, so we know we're always
-- executing fn() within the context of a timer (since some nginx APIs may
-- not be available in other contexts, like init_worker_by_lua).
local ok, err = ngx.timer.at(0, function(premature)
if premature then
return
end
_M.repeat_exec(interval, function()
_M.mutex_exec(name, function()
-- here we subtract the lock expiration time by 1ms to prevent
-- a race condition with the next timer event.
_M.timeout_exec(name, interval - 0.001, fn)
end)
end)
end)
if not ok and err ~= "process exiting" then
ngx.log(ngx.ERR, "failed to create timer: ", err)
end
end
return _M
|
Fix the health check never getting to green with the new interval locks.
|
Fix the health check never getting to green with the new interval locks.
The elasticsearch setup was never completing successfully since the HTTP
calls it was making on the initial pass were done directly in the
init_worker_by_lua context. Since HTTP APIs are disabled in this
context, things were failing. To fix, we'll wrap all of our interval
lock calls in an immediately executing timer to shift things into the
timer context. This enables the HTTP APIs, and also makes the context
for the function consistent between the first call and subsequently
schedules calls. This is how we previously scheduled the first wrapper
call to check() instead our spawn() functions.
|
Lua
|
mit
|
apinf/api-umbrella,NREL/api-umbrella,apinf/api-umbrella,apinf/api-umbrella,apinf/api-umbrella,NREL/api-umbrella,NREL/api-umbrella,NREL/api-umbrella,apinf/api-umbrella
|
8761976b54769e381b79e8268b9abbdc47c1518d
|
script/c80600054.lua
|
script/c80600054.lua
|
--零鳥姫リオート・ハルピュイア
function c80600054.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,aux.XyzFilterFunctionF(c,aux.FilterBoolFunction(Card.IsRace,RACE_ZOMBIE),5),2)
c:EnableReviveLimit()
--Special Summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(80600054,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCost(c80600054.cost)
e1:SetTarget(c80600054.target)
e1:SetOperation(c80600054.operation)
c:RegisterEffect(e1)
--
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e2:SetCode(EVENT_BATTLE_DESTROYED)
e2:SetCondition(c80600054.regcon)
e2:SetOperation(c80600054.regop)
c:RegisterEffect(e2)
end
function c80600054.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetFlagEffect(tp,80600054)==0 and e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end
e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST)
Duel.RegisterFlagEffect(tp,80600054,RESET_PHASE+PHASE_END,0,1)
end
function c80600054.filter(c,e)
return c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c80600054.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(1-tp) and c75162696.filter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c80600054.filter,tp,0,LOCATION_GRAVE,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c80600054.filter,tp,0,LOCATION_GRAVE,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c80600054.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)
end
end
function c80600054.regcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsReason(REASON_DESTROY) and e:GetHandler():GetReasonPlayer()~=tp
and e:GetHandler():GetPreviousControler()==tp
end
function c80600054.regop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(80600054,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e1:SetRange(LOCATION_GRAVE)
e1:SetCountLimit(1)
e1:SetCode(EVENT_PHASE+PHASE_STANDBY)
e1:SetCondition(c80600054.spcon)
e1:SetTarget(c80600054.sptg)
e1:SetOperation(c80600054.spop)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_STANDBY+RESET_SELF_TURN,1)
c:RegisterEffect(e1)
end
function c80600054.spcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()==tp
end
function c80600054.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
local c=e:GetHandler()
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,c,1,0,0)
end
function c80600054.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) then
Duel.SpecialSummon(c,1,tp,tp,false,false,POS_FACEUP_DEFENCE)
end
end
|
--零鳥姫リオート・ハルピュイア
function c80600054.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,aux.XyzFilterFunctionF(c,aux.FilterBoolFunction(Card.IsRace,RACE_ZOMBIE),5),2)
c:EnableReviveLimit()
--Special Summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(80600054,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCondition(c80600054.condition)
e1:SetCost(c80600054.cost)
e1:SetTarget(c80600054.target)
e1:SetOperation(c80600054.operation)
c:RegisterEffect(e1)
--
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e2:SetCode(EVENT_DESTROYED)
e2:SetCondition(c80600054.regcon)
e2:SetOperation(c80600054.regop)
c:RegisterEffect(e2)
end
function c80600054.condition(e,tp,eg,ep,ev,re,r,rp)
return not Duel.CheckAttackActivity(tp)
end
function c80600054.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetFlagEffect(tp,80600054)==0 and e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end
e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST)
Duel.RegisterFlagEffect(tp,80600054,RESET_PHASE+PHASE_END,0,1)
end
function c80600054.filter(c,e)
return c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c80600054.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(1-tp) and c75162696.filter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c80600054.filter,tp,0,LOCATION_GRAVE,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c80600054.filter,tp,0,LOCATION_GRAVE,1,1,nil,e,tp)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_ATTACK)
e1:SetProperty(EFFECT_FLAG_OATH)
e1:SetTargetRange(LOCATION_MZONE,0)
e1:SetTarget(c80600054.ftarget)
e1:SetLabelObject(g:GetFirst())
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c80600054.ftarget(e,c)
return e:GetLabelObject()~=c
end
function c80600054.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)
end
end
function c80600054.regcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:IsPreviousLocation(LOCATION_ONFIELD)
and rp~=tp
and c:GetPreviousControler()==tp
end
function c80600054.regop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(80600054,1))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e1:SetRange(LOCATION_GRAVE)
e1:SetCountLimit(1)
e1:SetCode(EVENT_PHASE+PHASE_STANDBY)
e1:SetTarget(c80600054.sptg)
e1:SetOperation(c80600054.spop)
e1:SetReset(RESET_EVENT+0x1fc0000+RESET_PHASE+PHASE_STANDBY)
c:RegisterEffect(e1)
end
function c80600054.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
local c=e:GetHandler()
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,c,1,0,0)
end
function c80600054.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) then
Duel.SpecialSummon(c,1,tp,tp,false,false,POS_FACEUP_DEFENCE)
end
end
|
fix
|
fix
fixed being able to attack after using 1. effect.
fixed not reviving when destroyed by card effect
changed special Summon to next standby phase
|
Lua
|
mit
|
SuperAndroid17/DevProLauncher,sidschingis/DevProLauncher,Tic-Tac-Toc/DevProLauncher
|
18479cd4bd40a264e00e666faa267b4da8374403
|
modules/admin-full/luasrc/model/cbi/admin_system/system.lua
|
modules/admin-full/luasrc/model/cbi/admin_system/system.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2011 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.sys")
require("luci.sys.zoneinfo")
require("luci.tools.webadmin")
require("luci.fs")
require("luci.config")
m = Map("system", translate("System"), translate("Here you can configure the basic aspects of your device like its hostname or the timezone."))
m:chain("luci")
local has_rdate = false
m.uci:foreach("system", "rdate",
function()
has_rdate = true
return false
end)
s = m:section(TypedSection, "system", translate("System Properties"))
s.anonymous = true
s.addremove = false
s:tab("general", translate("General Settings"))
s:tab("logging", translate("Logging"))
s:tab("language", translate("Language and Style"))
--
-- System Properties
--
local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo()
local uptime = luci.sys.uptime()
s:taboption("general", DummyValue, "_system", translate("System")).value = system
s:taboption("general", DummyValue, "_cpu", translate("Processor")).value = model
s:taboption("general", DummyValue, "_kernel", translate("Kernel")).value =
luci.util.exec("uname -r") or "?"
local load1, load5, load15 = luci.sys.loadavg()
s:taboption("general", DummyValue, "_la", translate("Load")).value =
string.format("%.2f, %.2f, %.2f", load1, load5, load15)
s:taboption("general", DummyValue, "_memtotal", translate("Memory")).value =
string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)",
tonumber(memtotal) / 1024,
100 * memcached / memtotal,
tostring(translate("cached")),
100 * membuffers / memtotal,
tostring(translate("buffered")),
100 * memfree / memtotal,
tostring(translate("free"))
)
s:taboption("general", DummyValue, "_systime", translate("Local Time")).value =
os.date("%c")
s:taboption("general", DummyValue, "_uptime", translate("Uptime")).value =
luci.tools.webadmin.date_format(tonumber(uptime))
hn = s:taboption("general", Value, "hostname", translate("Hostname"))
hn.datatype = "hostname"
function hn.write(self, section, value)
Value.write(self, section, value)
luci.sys.hostname(value)
end
tz = s:taboption("general", ListValue, "zonename", translate("Timezone"))
tz:value("UTC")
for i, zone in ipairs(luci.sys.zoneinfo.TZ) do
tz:value(zone[1])
end
function tz.write(self, section, value)
local function lookup_zone(title)
for _, zone in ipairs(luci.sys.zoneinfo.TZ) do
if zone[1] == title then return zone[2] end
end
end
AbstractValue.write(self, section, value)
local timezone = lookup_zone(value) or "GMT0"
self.map.uci:set("system", section, "timezone", timezone)
luci.fs.writefile("/etc/TZ", timezone .. "\n")
end
--
-- Logging
--
o = s:taboption("logging", Value, "log_size", translate("System log buffer size"), "kiB")
o.optional = true
o.placeholder = 16
o.datatype = "uinteger"
o = s:taboption("logging", Value, "log_ip", translate("External system log server"))
o.optional = true
o.placeholder = "0.0.0.0"
o.datatype = "ip4addr"
o = s:taboption("logging", Value, "log_port", translate("External system log server port"))
o.optional = true
o.placeholder = 514
o.datatype = "port"
o = s:taboption("logging", ListValue, "conloglevel", translate("Log output level"))
o:value(7, translate("Debug"))
o:value(6, translate("Info"))
o:value(5, translate("Notice"))
o:value(4, translate("Warning"))
o:value(3, translate("Error"))
o:value(2, translate("Critical"))
o:value(1, translate("Alert"))
o:value(0, translate("Emergency"))
o = s:taboption("logging", ListValue, "cronloglevel", translate("Cron Log Level"))
o.default = 8
o:value(5, translate("Debug"))
o:value(8, translate("Normal"))
o:value(9, translate("Warning"))
--
-- Langauge & Style
--
o = s:taboption("language", ListValue, "_lang", translate("Language"))
o:value("auto")
local i18ndir = luci.i18n.i18ndir .. "base."
for k, v in luci.util.kspairs(luci.config.languages) do
local file = i18ndir .. k:gsub("_", "-")
if k:sub(1, 1) ~= "." and luci.fs.access(file .. ".lmo") then
o:value(k, v)
end
end
function o.cfgvalue(...)
return m.uci:get("luci", "main", "lang")
end
function o.write(self, section, value)
m.uci:set("luci", "main", "lang", value)
end
o = s:taboption("language", ListValue, "_mediaurlbase", translate("Design"))
for k, v in pairs(luci.config.themes) do
if k:sub(1, 1) ~= "." then
o:value(v, k)
end
end
function o.cfgvalue(...)
return m.uci:get("luci", "main", "mediaurlbase")
end
function o.write(self, section, value)
m.uci:set("luci", "main", "mediaurlbase", value)
end
--
-- Rdate
--
if has_rdate then
m3= Map("timeserver", translate("Time Server (rdate)"))
s = m3:section(TypedSection, "timeserver")
s.anonymous = true
s.addremove = true
s.template = "cbi/tblsection"
s.rmempty = true
s:option(Value, "hostname", translate("Name"))
i = s:option(ListValue, "interface", translate("Interface"))
i:value("", translate("Default"))
m3.uci:foreach("network", "interface",
function (section)
local ifc = section[".name"]
if ifc ~= "loopback" then
i:value(ifc)
end
end
)
end
m2 = Map("luci")
f = m2:section(NamedSection, "main", "core", translate("Files to be kept when flashing a new firmware"))
f:tab("detected", translate("Detected Files"),
translate("The following files are detected by the system and will be kept automatically during sysupgrade"))
f:tab("custom", translate("Custom Files"),
translate("This is a list of shell glob patterns for matching files and directories to include during sysupgrade"))
d = f:taboption("detected", DummyValue, "_detected", translate("Detected files"))
d.rawhtml = true
d.cfgvalue = function(s)
local list = io.popen(
"( find $(sed -ne '/^[[:space:]]*$/d; /^#/d; p' /etc/sysupgrade.conf " ..
"/lib/upgrade/keep.d/* 2>/dev/null) -type f 2>/dev/null; " ..
"opkg list-changed-conffiles ) | sort -u"
)
if list then
local files = { "<ul>" }
while true do
local ln = list:read("*l")
if not ln then
break
else
files[#files+1] = "<li>"
files[#files+1] = luci.util.pcdata(ln)
files[#files+1] = "</li>"
end
end
list:close()
files[#files+1] = "</ul>"
return table.concat(files, "")
end
return "<em>" .. translate("No files found") .. "</em>"
end
c = f:taboption("custom", TextValue, "_custom", translate("Custom files"))
c.rmempty = false
c.cols = 70
c.rows = 30
c.cfgvalue = function(self, section)
return nixio.fs.readfile("/etc/sysupgrade.conf")
end
c.write = function(self, section, value)
value = value:gsub("\r\n?", "\n")
return nixio.fs.writefile("/etc/sysupgrade.conf", value)
end
return m, m3, m2
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2011 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.sys")
require("luci.sys.zoneinfo")
require("luci.tools.webadmin")
require("luci.fs")
require("luci.config")
m = Map("system", translate("System"), translate("Here you can configure the basic aspects of your device like its hostname or the timezone."))
m:chain("luci")
local has_rdate = false
m.uci:foreach("system", "rdate",
function()
has_rdate = true
return false
end)
s = m:section(TypedSection, "system", translate("System Properties"))
s.anonymous = true
s.addremove = false
s:tab("general", translate("General Settings"))
s:tab("logging", translate("Logging"))
s:tab("language", translate("Language and Style"))
--
-- System Properties
--
local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo()
local uptime = luci.sys.uptime()
s:taboption("general", DummyValue, "_system", translate("System")).value = system
s:taboption("general", DummyValue, "_cpu", translate("Processor")).value = model
s:taboption("general", DummyValue, "_kernel", translate("Kernel")).value =
luci.util.exec("uname -r") or "?"
local load1, load5, load15 = luci.sys.loadavg()
s:taboption("general", DummyValue, "_la", translate("Load")).value =
string.format("%.2f, %.2f, %.2f", load1, load5, load15)
s:taboption("general", DummyValue, "_memtotal", translate("Memory")).value =
string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)",
tonumber(memtotal) / 1024,
100 * memcached / memtotal,
tostring(translate("cached")),
100 * membuffers / memtotal,
tostring(translate("buffered")),
100 * memfree / memtotal,
tostring(translate("free"))
)
s:taboption("general", DummyValue, "_systime", translate("Local Time")).value =
os.date("%c")
s:taboption("general", DummyValue, "_uptime", translate("Uptime")).value =
luci.tools.webadmin.date_format(tonumber(uptime))
hn = s:taboption("general", Value, "hostname", translate("Hostname"))
hn.datatype = "hostname"
function hn.write(self, section, value)
Value.write(self, section, value)
luci.sys.hostname(value)
end
tz = s:taboption("general", ListValue, "zonename", translate("Timezone"))
tz:value("UTC")
for i, zone in ipairs(luci.sys.zoneinfo.TZ) do
tz:value(zone[1])
end
function tz.write(self, section, value)
local function lookup_zone(title)
for _, zone in ipairs(luci.sys.zoneinfo.TZ) do
if zone[1] == title then return zone[2] end
end
end
AbstractValue.write(self, section, value)
local timezone = lookup_zone(value) or "GMT0"
self.map.uci:set("system", section, "timezone", timezone)
luci.fs.writefile("/etc/TZ", timezone .. "\n")
end
--
-- Logging
--
o = s:taboption("logging", Value, "log_size", translate("System log buffer size"), "kiB")
o.optional = true
o.placeholder = 16
o.datatype = "uinteger"
o = s:taboption("logging", Value, "log_ip", translate("External system log server"))
o.optional = true
o.placeholder = "0.0.0.0"
o.datatype = "ip4addr"
o = s:taboption("logging", Value, "log_port", translate("External system log server port"))
o.optional = true
o.placeholder = 514
o.datatype = "port"
o = s:taboption("logging", ListValue, "conloglevel", translate("Log output level"))
o:value(7, translate("Debug"))
o:value(6, translate("Info"))
o:value(5, translate("Notice"))
o:value(4, translate("Warning"))
o:value(3, translate("Error"))
o:value(2, translate("Critical"))
o:value(1, translate("Alert"))
o:value(0, translate("Emergency"))
o = s:taboption("logging", ListValue, "cronloglevel", translate("Cron Log Level"))
o.default = 8
o:value(5, translate("Debug"))
o:value(8, translate("Normal"))
o:value(9, translate("Warning"))
--
-- Langauge & Style
--
o = s:taboption("language", ListValue, "_lang", translate("Language"))
o:value("auto")
local i18ndir = luci.i18n.i18ndir .. "base."
for k, v in luci.util.kspairs(luci.config.languages) do
local file = i18ndir .. k:gsub("_", "-")
if k:sub(1, 1) ~= "." and luci.fs.access(file .. ".lmo") then
o:value(k, v)
end
end
function o.cfgvalue(...)
return m.uci:get("luci", "main", "lang")
end
function o.write(self, section, value)
m.uci:set("luci", "main", "lang", value)
end
o = s:taboption("language", ListValue, "_mediaurlbase", translate("Design"))
for k, v in pairs(luci.config.themes) do
if k:sub(1, 1) ~= "." then
o:value(v, k)
end
end
function o.cfgvalue(...)
return m.uci:get("luci", "main", "mediaurlbase")
end
function o.write(self, section, value)
m.uci:set("luci", "main", "mediaurlbase", value)
end
--
-- Rdate
--
if has_rdate then
m3= Map("timeserver", translate("Time Server (rdate)"))
s = m3:section(TypedSection, "timeserver")
s.anonymous = true
s.addremove = true
s.template = "cbi/tblsection"
h = s:option(Value, "hostname", translate("Name"))
h.rmempty = true
h.datatype = host
i = s:option(ListValue, "interface", translate("Interface"))
i.rmempty = true
i:value("", translate("Default"))
m3.uci:foreach("network", "interface",
function (section)
local ifc = section[".name"]
if ifc ~= "loopback" then
i:value(ifc)
end
end
)
end
m2 = Map("luci")
f = m2:section(NamedSection, "main", "core", translate("Files to be kept when flashing a new firmware"))
f:tab("detected", translate("Detected Files"),
translate("The following files are detected by the system and will be kept automatically during sysupgrade"))
f:tab("custom", translate("Custom Files"),
translate("This is a list of shell glob patterns for matching files and directories to include during sysupgrade"))
d = f:taboption("detected", DummyValue, "_detected", translate("Detected files"))
d.rawhtml = true
d.cfgvalue = function(s)
local list = io.popen(
"( find $(sed -ne '/^[[:space:]]*$/d; /^#/d; p' /etc/sysupgrade.conf " ..
"/lib/upgrade/keep.d/* 2>/dev/null) -type f 2>/dev/null; " ..
"opkg list-changed-conffiles ) | sort -u"
)
if list then
local files = { "<ul>" }
while true do
local ln = list:read("*l")
if not ln then
break
else
files[#files+1] = "<li>"
files[#files+1] = luci.util.pcdata(ln)
files[#files+1] = "</li>"
end
end
list:close()
files[#files+1] = "</ul>"
return table.concat(files, "")
end
return "<em>" .. translate("No files found") .. "</em>"
end
c = f:taboption("custom", TextValue, "_custom", translate("Custom files"))
c.rmempty = false
c.cols = 70
c.rows = 30
c.cfgvalue = function(self, section)
return nixio.fs.readfile("/etc/sysupgrade.conf")
end
c.write = function(self, section, value)
value = value:gsub("\r\n?", "\n")
return nixio.fs.writefile("/etc/sysupgrade.conf", value)
end
return m, m3, m2
|
modules/admin-full: Fixes for rdate config
|
modules/admin-full: Fixes for rdate config
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@6884 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
zwhfly/openwrt-luci,zwhfly/openwrt-luci,dtaht/cerowrt-luci-3.3,phi-psi/luci,8devices/carambola2-luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,Flexibity/luci,phi-psi/luci,phi-psi/luci,vhpham80/luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,yeewang/openwrt-luci,eugenesan/openwrt-luci,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci,eugenesan/openwrt-luci,vhpham80/luci,saraedum/luci-packages-old,ThingMesh/openwrt-luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,ch3n2k/luci,vhpham80/luci,phi-psi/luci,stephank/luci,freifunk-gluon/luci,jschmidlapp/luci,phi-psi/luci,saraedum/luci-packages-old,jschmidlapp/luci,Flexibity/luci,projectbismark/luci-bismark,Flexibity/luci,jschmidlapp/luci,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,projectbismark/luci-bismark,gwlim/luci,Flexibity/luci,gwlim/luci,zwhfly/openwrt-luci,phi-psi/luci,projectbismark/luci-bismark,8devices/carambola2-luci,dtaht/cerowrt-luci-3.3,jschmidlapp/luci,stephank/luci,saraedum/luci-packages-old,projectbismark/luci-bismark,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,freifunk-gluon/luci,zwhfly/openwrt-luci,Flexibity/luci,Canaan-Creative/luci,Canaan-Creative/luci,eugenesan/openwrt-luci,projectbismark/luci-bismark,saraedum/luci-packages-old,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,vhpham80/luci,jschmidlapp/luci,yeewang/openwrt-luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,dtaht/cerowrt-luci-3.3,jschmidlapp/luci,jschmidlapp/luci,8devices/carambola2-luci,gwlim/luci,ch3n2k/luci,gwlim/luci,yeewang/openwrt-luci,Flexibity/luci,freifunk-gluon/luci,dtaht/cerowrt-luci-3.3,8devices/carambola2-luci,zwhfly/openwrt-luci,gwlim/luci,yeewang/openwrt-luci,saraedum/luci-packages-old,Canaan-Creative/luci,ch3n2k/luci,eugenesan/openwrt-luci,ReclaimYourPrivacy/cloak-luci,dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,stephank/luci,stephank/luci,vhpham80/luci,ThingMesh/openwrt-luci,saraedum/luci-packages-old,yeewang/openwrt-luci,ThingMesh/openwrt-luci,phi-psi/luci,jschmidlapp/luci,gwlim/luci,ch3n2k/luci,zwhfly/openwrt-luci,projectbismark/luci-bismark,8devices/carambola2-luci,Canaan-Creative/luci,stephank/luci,freifunk-gluon/luci,vhpham80/luci,stephank/luci,8devices/carambola2-luci,Flexibity/luci,freifunk-gluon/luci,projectbismark/luci-bismark,gwlim/luci,ThingMesh/openwrt-luci,Canaan-Creative/luci,yeewang/openwrt-luci,ch3n2k/luci,freifunk-gluon/luci,Flexibity/luci,ch3n2k/luci,Canaan-Creative/luci,dtaht/cerowrt-luci-3.3
|
4ea06b1debf344a7933329b6d23940c1f5ec9b85
|
esp/OTAUpdater.lua
|
esp/OTAUpdater.lua
|
ota_updater = {}
ota_updater.write_base64_to_file = function(base64_string, filename)
update = encoder.fromBase64(base64_string)
file.open(filename, 'w+') then
file.write(update)
file.close()
end
end
ota_updater.verify_checksum = function(file_name, encrypted_checksum)
file.open(filename, 'r') then
conent = file.read()
file.close()
end
-- TODO get iv from headers/request body
iv = 'iv needs to come here'
file_hash = crypto.toBase64(crypto.hash("sha1", content))
encrypted_file_hash = p_crypto.p_encrypt(file_hash, iv)
if encrypted_file_hash == encrypted_checksum
return true
else
return false
end
end
ota_updater.apply_update = function(file_name)
file.rename('init.lua', 'init.lua.old')
file.rename(file_name, 'init.lua')
node.restart()
end
ota_updater.check_for_update = function(server_hostname, device_id)
http.get('http://' .. server_hostname .. '/api/v1/firmwares',
'Content-Type: text/plain\r\nuid: '..deviceid..'\r\n',
function(code, data)
if (code == 204) then
return false
else
return data
end
end
)
end
|
ota_updater = {}
ota_updater.write_base64_to_file = function(base64_string, filename)
update = encoder.fromBase64(base64_string)
if file.open(filename, 'w+') then
file.write(update)
file.close()
end
end
ota_updater.verify_checksum = function(file_name, encrypted_checksum)
if file.open(filename, 'r') then
conent = file.read()
file.close()
end
-- TODO get iv from headers/request body
iv = 'iv needs to come here'
file_hash = crypto.toBase64(crypto.hash("sha1", content))
encrypted_file_hash = p_crypto.p_encrypt(file_hash, iv)
if encrypted_file_hash == encrypted_checksum then
return true
else
return false
end
end
ota_updater.apply_update = function(file_name)
file.rename('init.lua', 'init.lua.old')
file.rename(file_name, 'init.lua')
node.restart()
end
|
changed OTAUpdater to fix syntax
|
changed OTAUpdater to fix syntax
|
Lua
|
mit
|
jaspervandenberg/roselabs_project1,jaspervandenberg/roselabs_project1,jaspervandenberg/roselabs_project1
|
a1329f11771ac0182a9ce7f2ce4098dfb38875d7
|
game_view.lua
|
game_view.lua
|
-- imports
grid_state = require 'grid_state'
glitch_gen = require 'glitchGen'
directions = require 'directions'
glider = require 'glider'
watcher = require 'watcher'
background_color = {240, 240, 240}
grid_normal_color = {180, 230, 255}
grid_block_color = {100, 200, 250}
grid_line_width = 0.5
grid_unit_size = 32
grid_big_border = 5
-- mouse variables
mouse_x = 0;
mouse_y = 0;
mouseClicked = false;
lastFrameMouseClicked = false;
-- glider variables
rectanglesToDraw = {}
numberOfGliders = 0
gliderPlaced = false
lastGliderX = 0
lastGliderY = 0
-- grid state
-- visual glitch state
glitchUpdateTimer = 0.5
function draw_line(grid_num, x1, y1, x2, y2)
local is_main = grid_num % grid_big_border == 0
local color = is_main and grid_block_color or grid_normal_color
local width = grid_line_width
love.graphics.setLineWidth(width)
love.graphics.setColor(color[1], color[2], color[3])
love.graphics.line(x1, y1, x2, y2)
end
function gliderClicked(grid_state)
local gliderObject = nil
if gliderPlaced then
gliderObject = grid_state:get_object_at(lastGliderX, lastGliderY)
gliderObject.direction = directions.rotate_clockwise(gliderObject.direction)
end
end
function processGoButtonClicked(grid_state)
grid_state:update_objects()
gliderPlaced = false;
end
function exports()
local instance = {}
local block_size = grid_unit_size * grid_big_border
local xoffsets = 1280 % block_size
if xoffsets == 0 then
xoffsets = block_size
end
local xoffset = xoffsets / 2
local xcount = (1280 - xoffsets) / grid_unit_size
local yoffsets = 720 % block_size
local yoffset = yoffsets / 2
local ycount = (720 - yoffsets) / grid_unit_size
instance.grid_state = grid_state(xcount, ycount)
instance.grid_state:add_object(glider(5, 5, directions.UP))
for watcherI=1,10 do
instance.grid_state:add_object(watcher(math.random(0,xcount), math.random(0,ycount), directions.DOWN))
end
instance.goButtonImage = love.graphics.newImage( "placeholders/goButton.png" )
local goButtonX = (xcount - 2) * grid_unit_size + xoffset
local goButtonY = (ycount + 1.4) * grid_unit_size
local goButtonWidth = 64
local goButtonHeight = 32
function instance:draw()
love.graphics.setColor(background_color[1], background_color[2], background_color[3])
love.graphics.rectangle('fill', 0, 0, 1280, 720)
-- Draw Grid
local current_x = xoffset
local grid_num = 0
-- glider
local drawGliderX = -1
local drawGliderY = -1
while grid_num <= xcount do
draw_line(grid_num, current_x, yoffset, current_x, 720 - yoffset)
if mouse_x >= current_x and mouse_x < current_x + grid_unit_size then
drawGliderX = grid_num
end
current_x = current_x + grid_unit_size
grid_num = grid_num + 1
end
local current_y = yoffset
grid_num = 0
while grid_num <= ycount do
draw_line(grid_num, xoffset, current_y, 1280 - xoffset, current_y)
if mouse_y >= current_y and mouse_y < current_y + grid_unit_size then
drawGliderY = grid_num
end
current_y = current_y + grid_unit_size
grid_num = grid_num + 1
end
if mouseClicked and drawGliderX >= 0 and drawGliderY >= 0 and drawGliderX < xcount and drawGliderY < ycount and
not self.grid_state:get_space_at(drawGliderX+1, drawGliderY+1) and not gliderPlaced then
lastGliderX = drawGliderX + 1
lastGliderY = drawGliderY + 1
self.grid_state:add_object(glider(lastGliderX, lastGliderY, directions.DOWN))
gliderPlaced = true
end
if glitchUpdateTimer > 0.2 then
glitchUpdate = true
glitchUpdateTimer = glitchUpdateTimer - 0.2
end
for i,rect in ipairs(rectanglesToDraw) do
glitch_gen.drawGlich(rect["x"], rect["y"], xcount, glitchUpdate)
end
for x = 1, xcount, 1 do
for y = 1, ycount, 1 do
if self.grid_state:get_space_at(x, y) then
glitch_gen.drawGlich( (x-1) * grid_unit_size + xoffset, (y-1) * grid_unit_size + yoffset, xcount, glitchUpdate)
end
end
end
self.grid_state:draw_objects(xoffset, yoffset)
glitchUpdate = false
-- Button Go to Evolution mode
love.graphics.setColor(background_color[1], background_color[2], background_color[3])
love.graphics.draw(self.goButtonImage, goButtonX, goButtonY)
end
function instance:update()
mouse_x, mouse_y = love.mouse.getPosition()
lastFrameMouseClicked = mouseClicked
mouseClicked = love.mouse.isDown("l")
if mouseClicked and not lastFrameMouseClicked then
if mouse_x > goButtonX and mouse_x <= goButtonX + goButtonWidth and mouse_y > goButtonY and mouse_y <= goButtonY + goButtonHeight then
processGoButtonClicked(self.grid_state)
else if gliderPlaced then
local posX = (lastGliderX-1) * grid_unit_size + xoffset
local posY = (lastGliderY-1) * grid_unit_size + yoffset
if mouse_x > posX and mouse_x <= posX + grid_unit_size and mouse_y > posY and mouse_y <= posY + grid_unit_size then
gliderClicked(self.grid_state)
end
end
end
end
glitchUpdateTimer = glitchUpdateTimer + 1/60
end
return instance
end
return exports
|
-- imports
grid_state = require 'grid_state'
glitch_gen = require 'glitchGen'
directions = require 'directions'
glider = require 'glider'
watcher = require 'watcher'
background_color = {240, 240, 240}
grid_normal_color = {180, 230, 255}
grid_block_color = {100, 200, 250}
grid_line_width = 0.5
grid_unit_size = 32
grid_big_border = 5
-- mouse variables
mouse_x = 0;
mouse_y = 0;
mouseClicked = false;
lastFrameMouseClicked = false;
-- glider variables
rectanglesToDraw = {}
numberOfGliders = 0
gliderPlaced = false
lastGliderX = 0
lastGliderY = 0
-- grid state
-- visual glitch state
glitchUpdateTimer = 0.5
function draw_line(grid_num, x1, y1, x2, y2)
local is_main = grid_num % grid_big_border == 0
local color = is_main and grid_block_color or grid_normal_color
local width = grid_line_width
love.graphics.setLineWidth(width)
love.graphics.setColor(color[1], color[2], color[3])
love.graphics.line(x1, y1, x2, y2)
end
function gliderClicked(grid_state)
local gliderObject = nil
if gliderPlaced then
gliderObject = grid_state:get_object_at(lastGliderX, lastGliderY)
gliderObject.direction = directions.rotate_clockwise(gliderObject.direction)
end
end
function processGoButtonClicked(grid_state)
grid_state:update_objects()
gliderPlaced = false;
end
function exports()
local instance = {}
local block_size = grid_unit_size * grid_big_border
local xoffsets = 1280 % block_size
if xoffsets == 0 then
xoffsets = block_size
end
local xoffset = xoffsets / 2
local xcount = (1280 - xoffsets) / grid_unit_size
local yoffsets = 720 % block_size
local yoffset = yoffsets / 2
local ycount = (720 - yoffsets) / grid_unit_size
instance.grid_state = grid_state(xcount, ycount)
instance.grid_state:add_object(glider(5, 5, directions.UP))
for watcherI=1,10 do
instance.grid_state:add_object(watcher(math.random(0,xcount), math.random(0,ycount), directions.DOWN))
end
instance.goButtonImage = love.graphics.newImage( "placeholders/goButton.png" )
local goButtonX = (xcount - 2) * grid_unit_size + xoffset
local goButtonY = (ycount + 1.4) * grid_unit_size
local goButtonWidth = 64
local goButtonHeight = 32
function instance:draw()
love.graphics.setColor(background_color[1], background_color[2], background_color[3])
love.graphics.rectangle('fill', 0, 0, 1280, 720)
-- Draw Grid
local current_x = xoffset
local grid_num = 0
-- glider
local drawGliderX = -1
local drawGliderY = -1
while grid_num <= xcount do
draw_line(grid_num, current_x, yoffset, current_x, 720 - yoffset)
if mouse_x >= current_x and mouse_x < current_x + grid_unit_size then
drawGliderX = grid_num
end
current_x = current_x + grid_unit_size
grid_num = grid_num + 1
end
local current_y = yoffset
grid_num = 0
while grid_num <= ycount do
draw_line(grid_num, xoffset, current_y, 1280 - xoffset, current_y)
if mouse_y >= current_y and mouse_y < current_y + grid_unit_size then
drawGliderY = grid_num
end
current_y = current_y + grid_unit_size
grid_num = grid_num + 1
end
if mouseClicked and drawGliderX >= 0 and drawGliderY >= 0 and drawGliderX < xcount and drawGliderY < ycount and
not self.grid_state:get_space_at(drawGliderX+1, drawGliderY+1) and not gliderPlaced and self.grid_state:get_object_at(drawGliderX+1, drawGliderY+1) == nil then
lastGliderX = drawGliderX + 1
lastGliderY = drawGliderY + 1
self.grid_state:add_object(glider(lastGliderX, lastGliderY, directions.DOWN))
gliderPlaced = true
end
if glitchUpdateTimer > 0.2 then
glitchUpdate = true
glitchUpdateTimer = glitchUpdateTimer - 0.2
end
for i,rect in ipairs(rectanglesToDraw) do
glitch_gen.drawGlich(rect["x"], rect["y"], xcount, glitchUpdate)
end
for x = 1, xcount, 1 do
for y = 1, ycount, 1 do
if self.grid_state:get_space_at(x, y) then
glitch_gen.drawGlich( (x-1) * grid_unit_size + xoffset, (y-1) * grid_unit_size + yoffset, xcount, glitchUpdate)
end
end
end
self.grid_state:draw_objects(xoffset, yoffset)
glitchUpdate = false
-- Button Go to Evolution mode
love.graphics.setColor(background_color[1], background_color[2], background_color[3])
love.graphics.draw(self.goButtonImage, goButtonX, goButtonY)
end
function instance:update()
mouse_x, mouse_y = love.mouse.getPosition()
lastFrameMouseClicked = mouseClicked
mouseClicked = love.mouse.isDown("l")
if mouseClicked and not lastFrameMouseClicked then
if mouse_x > goButtonX and mouse_x <= goButtonX + goButtonWidth and mouse_y > goButtonY and mouse_y <= goButtonY + goButtonHeight then
processGoButtonClicked(self.grid_state)
else if gliderPlaced then
local posX = (lastGliderX-1) * grid_unit_size + xoffset
local posY = (lastGliderY-1) * grid_unit_size + yoffset
if mouse_x > posX and mouse_x <= posX + grid_unit_size and mouse_y > posY and mouse_y <= posY + grid_unit_size then
gliderClicked(self.grid_state)
end
end
end
end
glitchUpdateTimer = glitchUpdateTimer + 1/60
end
return instance
end
return exports
|
bug in placing glider corrected and rotate by user done
|
bug in placing glider corrected and rotate by user done
|
Lua
|
mit
|
NamefulTeam/PortoGameJam2015
|
e107d4225ebbc520abbe6412b2573335f2032194
|
script/c81907872.lua
|
script/c81907872.lua
|
--ゴーストリック・スペクター
function c81907872.initial_effect(c)
--summon limit
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CANNOT_SUMMON)
e1:SetCondition(c81907872.sumcon)
c:RegisterEffect(e1)
--turn set
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(81907872,0))
e2:SetCategory(CATEGORY_POSITION)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_MZONE)
e2:SetTarget(c81907872.postg)
e2:SetOperation(c81907872.posop)
c:RegisterEffect(e2)
--spsummon
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(81907872,1))
e3:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_DRAW)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e3:SetProperty(EFFECT_FLAG_DAMAGE_STEP)
e3:SetCode(EVENT_TO_GRAVE)
e3:SetRange(LOCATION_HAND)
e3:SetCondition(c81907872.spcon)
e3:SetTarget(c81907872.sptg)
e3:SetOperation(c81907872.spop)
c:RegisterEffect(e3)
end
function c81907872.sfilter(c)
return c:IsFaceup() and c:IsSetCard(0x8d)
end
function c81907872.sumcon(e)
return not Duel.IsExistingMatchingCard(c81907872.sfilter,e:GetHandlerPlayer(),LOCATION_MZONE,0,1,nil)
end
function c81907872.postg(e,tp,eg,ep,ev,re,r,rp,chk)
local c=e:GetHandler()
if chk==0 then return c:IsCanTurnSet() and c:GetFlagEffect(81907872)==0 end
c:RegisterFlagEffect(81907872,RESET_EVENT+0x1fc0000+RESET_PHASE+PHASE_END,0,1)
Duel.SetOperationInfo(0,CATEGORY_POSITION,c,1,0,0)
end
function c81907872.posop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) and c:IsFaceup() then
Duel.ChangePosition(c,POS_FACEDOWN_DEFENCE)
end
end
function c81907872.cfilter(c,tp)
return c:IsControler(tp) and c:IsSetCard(0x8d) and c:IsReason(REASON_DESTROY)
and (not c:IsReason(REASON_BATTLE) or c==Duel.GetAttackTarget())
end
function c81907872.spcon(e,tp,eg,ep,ev,re,r,rp)
return rp~=tp and eg:IsExists(c81907872.cfilter,1,nil,tp)
end
function c81907872.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false,POS_FACEDOWN)
and Duel.IsPlayerCanDraw(tp,1) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1)
end
function c81907872.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) and Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEDOWN_DEFENCE) then
Duel.ConfirmCards(1-tp,c)
Duel.Draw(tp,1,REASON_EFFECT)
end
end
|
--ゴーストリック・スペクター
function c81907872.initial_effect(c)
--summon limit
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CANNOT_SUMMON)
e1:SetCondition(c81907872.sumcon)
c:RegisterEffect(e1)
--turn set
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(81907872,0))
e2:SetCategory(CATEGORY_POSITION)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_MZONE)
e2:SetTarget(c81907872.postg)
e2:SetOperation(c81907872.posop)
c:RegisterEffect(e2)
--spsummon
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(81907872,1))
e3:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_DRAW)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e3:SetProperty(EFFECT_FLAG_DAMAGE_STEP)
e3:SetCode(EVENT_TO_GRAVE)
e3:SetRange(LOCATION_HAND)
e3:SetCondition(c81907872.spcon)
e3:SetTarget(c81907872.sptg)
e3:SetOperation(c81907872.spop)
c:RegisterEffect(e3)
end
function c81907872.sfilter(c)
return c:IsFaceup() and c:IsSetCard(0x8d)
end
function c81907872.sumcon(e)
return not Duel.IsExistingMatchingCard(c81907872.sfilter,e:GetHandlerPlayer(),LOCATION_MZONE,0,1,nil)
end
function c81907872.postg(e,tp,eg,ep,ev,re,r,rp,chk)
local c=e:GetHandler()
if chk==0 then return c:IsCanTurnSet() and c:GetFlagEffect(81907872)==0 end
c:RegisterFlagEffect(81907872,RESET_EVENT+0x1fc0000+RESET_PHASE+PHASE_END,0,1)
Duel.SetOperationInfo(0,CATEGORY_POSITION,c,1,0,0)
end
function c81907872.posop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) and c:IsFaceup() then
Duel.ChangePosition(c,POS_FACEDOWN_DEFENCE)
end
end
function c81907872.cfilter(c,tp)
return c:GetPreviousControler()==tp and c:IsSetCard(0x8d) and c:IsReason(REASON_DESTROY)
and c:IsType(TYPE_MONSTER)
end
function c81907872.spcon(e,tp,eg,ep,ev,re,r,rp)
return rp~=tp and eg:IsExists(c81907872.cfilter,1,nil,tp)
end
function c81907872.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false,POS_FACEDOWN)
and Duel.IsPlayerCanDraw(tp,1) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1)
end
function c81907872.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) and Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEDOWN_DEFENCE) then
Duel.ConfirmCards(1-tp,c)
Duel.Draw(tp,1,REASON_EFFECT)
end
end
|
fix condition
|
fix condition
|
Lua
|
mit
|
Tic-Tac-Toc/DevProLauncher,SuperAndroid17/DevProLauncher,sidschingis/DevProLauncher
|
6b7e154d3ba8fa7912a801b3cc087a4b1e73853f
|
src/lua-factory/sources/grl-euronews.lua
|
src/lua-factory/sources/grl-euronews.lua
|
--[[
* Copyright (C) 2014 Bastien Nocera
*
* Contact: Bastien Nocera <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; version 2.1 of
* the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
--]]
EURONEWS_URL = 'http://euronews.hexaglobe.com/json/'
---------------------------
-- Source initialization --
---------------------------
source = {
id = "grl-euronews-lua",
name = "Euronews",
description = "A source for watching Euronews online",
supported_keys = { "id", "title", "url" },
supported_media = 'video',
icon = 'resource:///org/gnome/grilo/plugins/euronews/euronews.svg',
tags = { 'news', 'tv', 'net:internet', 'net:plaintext' }
}
------------------
-- Source utils --
------------------
function grl_source_browse(media, options, callback)
if options.skip > 0 then
callback()
else
grl.fetch(EURONEWS_URL, euronews_fetch_cb, callback)
end
end
------------------------
-- Callback functions --
------------------------
-- return all the media found
function euronews_fetch_cb(results, callback)
local json = {}
json = grl.lua.json.string_to_table(results)
if not json or json.stat == "fail" or not json.primary then
callback()
return
end
for index, item in pairs(json.primary) do
local media = create_media(index, item)
if media ~= nil then
callback(media, -1)
end
end
callback()
end
-------------
-- Helpers --
-------------
function get_lang(id)
local langs = {}
langs.ru = "Russian"
langs.hu = "Hungarian"
langs.de = "German"
langs.fa = "Persian"
langs.ua = "Ukrainian"
langs.ar = "Arabic"
langs.es = "Spanish; Castilian"
langs.gr = "Greek, Modern (1453-)"
langs.tr = "Turkish"
langs.pe = "Persian" -- Duplicate?
langs.en = "English"
langs.it = "Italian"
langs.fr = "French"
langs.pt = "Portuguese"
if not langs[id] then
grl.warning('Could not find language ' .. id)
return id
end
return grl.dgettext('iso_639', langs[id])
end
function create_media(lang, item)
local media = {}
if item.rtmp_flash["750"].name == 'UNAVAILABLE' then
return nil
end
media.type = "video"
media.id = lang
media.title = "Euronews " .. get_lang(lang)
media.url = item.rtmp_flash["750"].server ..
item.rtmp_flash["750"].name ..
" playpath=" .. item.rtmp_flash["750"].name ..
" swfVfy=1 " ..
"swfUrl=http://euronews.com/media/player_live_1_14.swf "..
"live=1"
return media
end
|
--[[
* Copyright (C) 2014 Bastien Nocera
*
* Contact: Bastien Nocera <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; version 2.1 of
* the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
--]]
EURONEWS_URL = 'http://euronews.hexaglobe.com/json/'
---------------------------
-- Source initialization --
---------------------------
source = {
id = "grl-euronews-lua",
name = "Euronews",
description = "A source for watching Euronews online",
supported_keys = { "id", "title", "url" },
supported_media = 'video',
icon = 'resource:///org/gnome/grilo/plugins/euronews/euronews.svg',
tags = { 'news', 'tv', 'net:internet', 'net:plaintext' }
}
------------------
-- Source utils --
------------------
function grl_source_browse(media_id)
if grl.get_options("skip") > 0 then
grl.callback()
else
grl.fetch(EURONEWS_URL, euronews_fetch_cb)
end
end
------------------------
-- Callback functions --
------------------------
-- return all the media found
function euronews_fetch_cb(results)
local json = {}
json = grl.lua.json.string_to_table(results)
if not json or json.stat == "fail" or not json.primary then
grl.callback()
return
end
for index, item in pairs(json.primary) do
local media = create_media(index, item)
if media ~= nil then
grl.callback(media, -1)
end
end
grl.callback()
end
-------------
-- Helpers --
-------------
function get_lang(id)
local langs = {}
langs.ru = "Russian"
langs.hu = "Hungarian"
langs.de = "German"
langs.fa = "Persian"
langs.ua = "Ukrainian"
langs.ar = "Arabic"
langs.es = "Spanish; Castilian"
langs.gr = "Greek, Modern (1453-)"
langs.tr = "Turkish"
langs.pe = "Persian" -- Duplicate?
langs.en = "English"
langs.it = "Italian"
langs.fr = "French"
langs.pt = "Portuguese"
if not langs[id] then
grl.warning('Could not find language ' .. id)
return id
end
return grl.dgettext('iso_639', langs[id])
end
function create_media(lang, item)
local media = {}
if item.rtmp_flash["750"].name == 'UNAVAILABLE' then
return nil
end
media.type = "video"
media.id = lang
media.title = "Euronews " .. get_lang(lang)
media.url = item.rtmp_flash["750"].server ..
item.rtmp_flash["750"].name ..
" playpath=" .. item.rtmp_flash["750"].name ..
" swfVfy=1 " ..
"swfUrl=http://euronews.com/media/player_live_1_14.swf "..
"live=1"
return media
end
|
Revert "lua-factory: port grl-euronews.lua to the new lua system"
|
Revert "lua-factory: port grl-euronews.lua to the new lua system"
This reverts commit 592bb1c7a5315e4f2582dad415e03e42f5a43cad.
But keeps grl.fetch callback as function instead of string
https://bugzilla.gnome.org/show_bug.cgi?id=763046
|
Lua
|
lgpl-2.1
|
jasuarez/grilo-plugins,MikePetullo/grilo-plugins,GNOME/grilo-plugins,grilofw/grilo-plugins,MikePetullo/grilo-plugins,grilofw/grilo-plugins,MikePetullo/grilo-plugins,GNOME/grilo-plugins,jasuarez/grilo-plugins
|
31d48808fc1e4f1517d570a3a0dfe33d4c8de4a5
|
scripts/tundra/tools/dotnet.lua
|
scripts/tundra/tools/dotnet.lua
|
module(..., package.seeall)
local frameworkDir = "c:\\Windows\\Microsoft.NET\\Framework"
local defaultFrameworkVersion = "v3.5"
function apply(env, options)
tundra.unitgen.load_toolset("generic-dotnet", env)
local version = options and assert(options.Version) or defaultFrameworkVersion
env:set_external_env_var('FrameworkDir', frameworkDir)
env:set_external_env_var('FrameworkVersion', version)
local binPath = frameworkDir .. "\\" .. version
env:set_external_env_var('PATH', binPath .. ";" .. env:get_external_env_var('PATH'))
-- C# support
env:set_many {
["CSC"] = "csc.exe",
["CSPROGSUFFIX"] = ".exe",
["CSLIBSUFFIX"] = ".dll",
["CSRESGEN"] = "resgen $(<) $(@)",
["_CSC_COMMON"] = "-warn:$(CSC_WARNING_LEVEL) /nologo $(CSLIBPATH:b:p/lib\\:) $(CSRESOURCES:b:p/resource\\:) $(CSLIBS:p/reference\\::A.dll)",
["CSCLIBCOM"] = "$(CSC) $(_CSC_COMMON) $(CSCOPTS) -target:library -out:$(@:b) $(<:b)",
["CSCEXECOM"] = "$(CSC) $(_CSC_COMMON) $(CSCOPTS) -target:exe -out:$(@:b) $(<:b)",
}
end
|
module(..., package.seeall)
local frameworkDir = "c:\\Windows\\Microsoft.NET\\Framework"
local defaultFrameworkVersion = "v3.5"
function apply(env, options)
tundra.unitgen.load_toolset("generic-dotnet", env)
local version = options and assert(options.Version) or defaultFrameworkVersion
env:set_external_env_var('FrameworkDir', frameworkDir)
env:set_external_env_var('FrameworkVersion', version)
local binPath = frameworkDir .. "\\" .. version
env:set_external_env_var('PATH', binPath .. ";" .. env:get_external_env_var('PATH'))
-- C# support
env:set_many {
["DOTNET_SUFFIXES"] = { ".cs" },
["DOTNET_SUFFIXES_RESOURCE"] = { ".resource" },
["CSC"] = "csc.exe",
["CSPROGSUFFIX"] = ".exe",
["CSLIBSUFFIX"] = ".dll",
["CSRESGEN"] = "resgen $(<) $(@)",
["_CSC_COMMON"] = "-warn:$(CSC_WARNING_LEVEL) /nologo $(CSLIBPATH:b:p/lib\\:) $(CSRESOURCES:b:p/resource\\:) $(CSLIBS:p/reference\\::A.dll)",
["CSCLIBCOM"] = "$(CSC) $(_CSC_COMMON) $(CSCOPTS) -target:library -out:$(@:b) $(<:b)",
["CSCEXECOM"] = "$(CSC) $(_CSC_COMMON) $(CSCOPTS) -target:exe -out:$(@:b) $(<:b)",
}
end
|
Added DOTNET_SUFFIXES(_RESOURCE) to dotnet.lua
|
Added DOTNET_SUFFIXES(_RESOURCE) to dotnet.lua
|
Lua
|
mit
|
bmharper/tundra,deplinenoise/tundra,bmharper/tundra,deplinenoise/tundra,bmharper/tundra,bmharper/tundra,deplinenoise/tundra
|
2dc8b0a2537c4ae66d3ddd8de66867e7fd930ac8
|
premake5.lua
|
premake5.lua
|
solution "SuperMatch5DX"
configurations { "Debug", "Release" }
flags { "FatalWarnings", "NoRTTI", "Unicode" }
warnings "Extra"
floatingpoint "Fast"
vectorextensions "SSE2"
targetdir "bin"
configuration "Debug"
defines { "DEBUG" }
flags { "Symbols" }
optimize "Off"
configuration "Release"
defines { "NDEBUG" }
optimize "On"
configuration "vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
project "libyuriks"
kind "StaticLib"
language "C++"
files { "libyuriks/**.cpp", "libyuriks/**.hpp", "libyuriks/**.c", "libyuriks/**.h" }
includedirs { "libyuriks" }
project "SuperMatch5DX"
kind "ConsoleApp"
language "C++"
files { "src/**.cpp", "src/**.hpp", "src/**.c", "src/**.h" }
includedirs { "src", "libyuriks" }
links { "SDL2", "SDL2main", "libyuriks" }
configuration "Windows"
linkoptions { "/NODEFAULTLIB:msvcrt" }
links { "OpenGL32" }
|
solution "SuperMatch5DX"
configurations { "Debug", "Release" }
flags { "FatalWarnings", "NoRTTI", "Unicode" }
warnings "Extra"
floatingpoint "Fast"
vectorextensions "SSE2"
targetdir "bin"
configuration "Debug"
defines { "DEBUG" }
flags { "Symbols" }
optimize "Off"
configuration "Release"
defines { "NDEBUG" }
optimize "On"
configuration "vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
project "libyuriks"
kind "StaticLib"
language "C++"
files { "libyuriks/**.cpp", "libyuriks/**.hpp", "libyuriks/**.c", "libyuriks/**.h" }
includedirs { "libyuriks" }
project "SuperMatch5DX"
kind "ConsoleApp"
language "C++"
files { "src/**.cpp", "src/**.hpp", "src/**.c", "src/**.h" }
includedirs { "src", "libyuriks" }
links { "SDL2", "SDL2main", "libyuriks" }
configuration "Windows"
links { "OpenGL32" }
configuration { "Windows", "Debug" }
linkoptions { "/NODEFAULTLIB:msvcrt" }
|
Fix compilation in Release mode
|
Fix compilation in Release mode
|
Lua
|
apache-2.0
|
yuriks/super-match-5-dx,yuriks/super-match-5-dx
|
c907334f9ad14f786b3716b4b37925ac0090f549
|
packages/footnotes.lua
|
packages/footnotes.lua
|
-- Footnotes class
-- Exports: The \footnote command
-- outputInsertions (call this in endPage)
SILE.require("packages/counters")
SILE.require("packages/raiselower")
local insertions = SILE.require("packages/insertions")
SILE.scratch.counters.footnote = { value= 1, display= "arabic" };
SILE.registerCommand("footnotemark", function(options, content)
SILE.Commands["raise"]({height = "0.7ex"}, function()
SILE.Commands["font"]({ size = "1.5ex" }, function()
SILE.typesetter:typeset(SILE.formatCounter(SILE.scratch.counters.footnote))
end)
end)
end)
SILE.registerCommand("footnote:separator", function(options, content)
SILE.settings.pushState()
local material = SILE.Commands["vbox"]({}, content)
SILE.scratch.insertions.classes.footnote.topBox = material
SILE.settings.popState()
end)
SILE.registerCommand("footnote:options", function(options, content)
if options["max-height"] then
SILE.scratch.insertions.classes.footnote.maxHeight = SILE.length.parse(options["max-height"])
end
if options["inter-insertion-skip"] then
SILE.scratch.insertions.classes.footnote.interInsertionSkip = SILE.length.parse(options["inter-insertion-skip"])
end
end)
SILE.registerCommand("footnote", function(options, content)
SILE.call("footnotemark")
local opts = SILE.scratch.insertions.classes.footnote
local f = SILE.getFrame(opts["insertInto"])
local oldT = SILE.typesetter
SILE.typesetter = SILE.typesetter {}
SILE.typesetter:init(f)
SILE.typesetter.pageTarget = function () return 0xFFFFFF end
SILE.settings.reset()
local material = SILE.Commands["vbox"]({}, function()
SILE.Commands["font"]({size = "9pt"}, function()
SILE.call("footnote:atstart")
SILE.call("footnote:counter")
SILE.process(content)
end)
end
)
SILE.typesetter = oldT
insertions.exports:insert("footnote", material)
SILE.scratch.counters.footnote.value = SILE.scratch.counters.footnote.value + 1
end)
SILE.registerCommand("footnote:atstart", function(o,c)
end)
SILE.registerCommand("footnote:counter", function(o,c)
SILE.call("noindent")
SILE.typesetter:typeset(SILE.formatCounter(SILE.scratch.counters.footnote)..".")
SILE.call("qquad")
end)
return {
init = function (class, args)
insertions.exports:initInsertionClass("footnote", {
insertInto = args.insertInto,
stealFrom = args.stealFrom,
maxHeight = SILE.length.new({length = SILE.toPoints("75", "%","h") }),
topBox = SILE.nodefactory.newVbox({height = SILE.length.parse("2ex") }),
interInsertionSkip = SILE.length.parse("1ex"),
})
end,
exports = {
outputInsertions = insertions.exports.outputInsertions
}
}
|
-- Footnotes class
-- Exports: The \footnote command
-- outputInsertions (call this in endPage)
SILE.require("packages/counters")
SILE.require("packages/raiselower")
local insertions = SILE.require("packages/insertions")
SILE.scratch.counters.footnote = { value= 1, display= "arabic" };
SILE.registerCommand("footnotemark", function(options, content)
SILE.Commands["raise"]({height = "0.7ex"}, function()
SILE.Commands["font"]({ size = "1.5ex" }, function()
SILE.typesetter:typeset(SILE.formatCounter(SILE.scratch.counters.footnote))
end)
end)
end)
SILE.registerCommand("footnote:separator", function(options, content)
SILE.settings.pushState()
local material = SILE.Commands["vbox"]({}, content)
SILE.scratch.insertions.classes.footnote.topBox = material
SILE.settings.popState()
end)
SILE.registerCommand("footnote:options", function(options, content)
if options["max-height"] then
SILE.scratch.insertions.classes.footnote.maxHeight = SILE.length.parse(options["max-height"])
end
if options["inter-insertion-skip"] then
SILE.scratch.insertions.classes.footnote.interInsertionSkip = SILE.length.parse(options["inter-insertion-skip"])
end
end)
SILE.registerCommand("footnote", function(options, content)
SILE.call("footnotemark")
local opts = SILE.scratch.insertions.classes.footnote
local f = SILE.getFrame(opts["insertInto"])
local oldT = SILE.typesetter
SILE.typesetter = SILE.typesetter {}
SILE.typesetter:init(f)
SILE.typesetter.pageTarget = function () return 0xFFFFFF end
SILE.settings.pushState()
SILE.settings.reset()
local material = SILE.Commands["vbox"]({}, function()
SILE.Commands["font"]({size = "9pt"}, function()
SILE.call("footnote:atstart")
SILE.call("footnote:counter")
SILE.process(content)
end)
end)
SILE.settings.popState()
SILE.typesetter = oldT
insertions.exports:insert("footnote", material)
SILE.scratch.counters.footnote.value = SILE.scratch.counters.footnote.value + 1
end)
SILE.registerCommand("footnote:atstart", function(o,c)
end)
SILE.registerCommand("footnote:counter", function(o,c)
SILE.call("noindent")
SILE.typesetter:typeset(SILE.formatCounter(SILE.scratch.counters.footnote)..".")
SILE.call("qquad")
end)
return {
init = function (class, args)
insertions.exports:initInsertionClass("footnote", {
insertInto = args.insertInto,
stealFrom = args.stealFrom,
maxHeight = SILE.length.new({length = SILE.toPoints("75", "%","h") }),
topBox = SILE.nodefactory.newVbox({height = SILE.length.parse("2ex") }),
interInsertionSkip = SILE.length.parse("1ex"),
})
end,
exports = {
outputInsertions = insertions.exports.outputInsertions
}
}
|
Add push/pop state back to footnote typesetter
|
Add push/pop state back to footnote typesetter
Fixes issue #231
See commit b3072fa for where this issue was introduced.
|
Lua
|
mit
|
alerque/sile,alerque/sile,simoncozens/sile,simoncozens/sile,alerque/sile,neofob/sile,alerque/sile,simoncozens/sile,neofob/sile,simoncozens/sile,neofob/sile,neofob/sile
|
8c826f3940e2af2001bd666febe69173792ee065
|
share/lua/playlist/koreus.lua
|
share/lua/playlist/koreus.lua
|
--[[
Copyright 2009 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()
if vlc.access ~= "http" then
return false
end
koreus_site = string.match( vlc.path, "koreus" )
if not koreus_site then
return false
end
return ( string.match( vlc.path, "video" ) ) -- http://www.koreus.com/video/pouet.html
end
-- Parse function.
function parse()
while true do
line = vlc.readline()
if not line then break end
if string.match( line, "<meta name=\"title\"" ) then
_,_,name = string.find( line, "content=\"(.-)\"" )
end
if string.match( line, "<meta name=\"description\"" ) then
_,_,description = string.find( line, "content=\"(.-)\"" )
end
if string.match( line, "<meta name=\"author\"" ) then
_,_,artist = string.find( line, "content=\"(.-)\"" )
end
if string.match( line, "link rel=\"image_src\"" ) then
_,_,arturl = string.find( line, "href=\"(.-)\"" )
end
if string.match( line, "videoDiv\"%)%.innerHTML" ) then
vid_url = string.match( line, '(http://media%d?%.koreus%.com/%d+/%d+/[%w-]*%.mp4)' )
if vid_url then
return { { path = vid_url; name = name; description = description; artist = artist; arturl = arturl } }
end
end
end
end
|
--[[
Copyright 2009 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()
if vlc.access ~= "http" then
return false
end
koreus_site = string.match( vlc.path, "koreus" )
if not koreus_site then
return false
end
return ( string.match( vlc.path, "video" ) ) -- http://www.koreus.com/video/pouet.html
end
-- Parse function.
function parse()
while true do
line = vlc.readline()
if not line then break end
if string.match( line, "<meta name=\"title\"" ) then
_,_,name = string.find( line, "content=\"(.-)\"" )
end
if string.match( line, "<meta name=\"description\"" ) then
_,_,description = string.find( line, "content=\"(.-)\"" )
end
if string.match( line, "<meta name=\"author\"" ) then
_,_,artist = string.find( line, "content=\"(.-)\"" )
end
if string.match( line, "link rel=\"image_src\"" ) then
_,_,arturl = string.find( line, "href=\"(.-)\"" )
end
vid_url = string.match( line, '(http://media%d?%.koreus%.com/%d+/%d+/[%w-]*%.mp4)' )
if vid_url then
return { { path = vid_url; name = name; description = description; artist = artist; arturl = arturl } }
end
end
end
|
lua: fix koreus parsing.
|
lua: fix koreus parsing.
|
Lua
|
lgpl-2.1
|
krichter722/vlc,vlc-mirror/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,xkfz007/vlc,xkfz007/vlc,jomanmuk/vlc-2.1,krichter722/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc,jomanmuk/vlc-2.1,shyamalschandra/vlc,xkfz007/vlc,krichter722/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,krichter722/vlc,xkfz007/vlc,vlc-mirror/vlc,vlc-mirror/vlc,vlc-mirror/vlc,shyamalschandra/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,shyamalschandra/vlc,jomanmuk/vlc-2.1,xkfz007/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,shyamalschandra/vlc,vlc-mirror/vlc-2.1,xkfz007/vlc,jomanmuk/vlc-2.2,krichter722/vlc,krichter722/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.2,xkfz007/vlc,vlc-mirror/vlc,krichter722/vlc,shyamalschandra/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2
|
7e1ef7bd21eee0dc60a3acaac377387c7f963d72
|
libs/util.lua
|
libs/util.lua
|
-- ivar2 IRC utilities and more
-- vim: set noexpandtab:
local reset = function(s)
return '\015'
end
local bold = function(s)
return string.format("\002%s\002", s)
end
local underline = function(s)
return string.format("\031%s\031", s)
end
local italic = function(s)
return string.format("\029%s\029", s)
end
local reverse = function(s)
return string.format("\018%s\018", s)
end
local rot13 = function(s)
local byte_a, byte_A = string.byte('a'), string.byte('A')
return (string.gsub((s or ''), "[%a]",
function (char)
local offset = (char < 'a') and byte_A or byte_a
local b = string.byte(char) - offset -- 0 to 25
b = ((b + 13) % 26) + offset -- Rotate
return string.char(b)
end
))
end
local color = function(s, color)
return string.format("\03%02d%s%s", color, s, reset())
end
local urlEncode = function(str)
return str:gsub(
'([^%w ])',
function (c)
return string.format ("%%%02X", string.byte(c))
end
):gsub(' ', '+')
end
local trim = function(s)
return (string.gsub(s, "^%s*(.-)%s*$", "%1"))
end
local split = function(str, delim)
if str == "" or str == nil then
return { }
end
str = str .. delim
local _accum_0 = { }
local _len_0 = 1
for m in str:gmatch("(.-)" .. delim) do
_accum_0[_len_0] = m
_len_0 = _len_0 + 1
end
return _accum_0
end
local translateWords = function(str, callback, fixCase, nickpat)
-- Usage: etc.translateWords(s ,callback) the callback can return new word, false to skip, or nil to keep the same word.
local str = assert(str)
local callback = assert(callback, "Callback expected")
local fixCase = fixCase == nil or fixCase == true
local nickpat = nickpat
local prev = 1
local result = ""
local pat = "()([%w'%-]+)()"
if nickpat then
pat = "()([%w_'%-%{%}%[%]`%^]+)()"
end
for wpos, w, wposEnd in str:gmatch(pat) do
local wnew = callback(w)
if wnew ~= false then
result = result .. str:sub(prev, wpos - 1)
if wnew then
if fixCase then
if w == w:lower() then
elseif w == w:upper() then
wnew = wnew:upper()
elseif w:sub(1, 1) == w:sub(1, 1):upper() then
wnew = wnew:sub(1, 1):upper() .. wnew:sub(2)
end
end
result = result .. wnew
else
result = result .. w
end
if not wnew then
wnew = w
end
end
prev = wposEnd
end
result = result .. str:sub(prev)
return result
end
local nonickalert = function(nicklist, str)
-- U+200B, ZERO WIDTH SPACE: "\226\128\139"
local s = str or ''
local nl = nicklist -- nicklist
local zwsp = "\226\128\142" -- LTR
nl = nl or {}
local nlkeys = {}
for nick, t in pairs(nicklist) do
nlkeys[nick:lower()] = true
end
return translateWords(s, function(x)
if nlkeys[x:lower()] then
return x:sub(1, 1) .. zwsp .. x:sub(2)
end
end, nil, true)
end
return {
bold=bold,
underline=underline,
italic=italic,
reverse=reverse,
color=color,
reset=reset,
urlEncode=urlEncode,
trim=trim,
split=split,
rot13=rot13,
json = require'cjson',
simplehttp = require'simplehttp',
white=function(s)
return color(s, 0)
end,
black=function(s)
return color(s, 1)
end,
blue=function(s)
return color(s, 2)
end,
green=function(s)
return color(s, 3)
end,
red=function(s)
return color(s, 4)
end,
maroon=function(s)
return color(s, 5)
end,
purple=function(s)
return color(s, 6)
end,
orange=function(s)
return color(s, 7)
end,
yellow=function(s)
return color(s, 8)
end,
lightgreen=function(s)
return color(s, 9)
end,
teal=function(s)
return color(s, 10)
end,
cyan=function(s)
return color(s, 11)
end,
lightblue=function(s)
return color(s, 12)
end,
fuchsia=function(s)
return color(s, 13)
end,
gray=function(s)
return color(s, 14)
end,
lightgray=function(s)
return color(s, 15)
end,
nonickalert=nonickalert,
translateWords=translateWords,
}
|
-- ivar2 IRC utilities and more
-- vim: set noexpandtab:
local reset = function(s)
return '\015'
end
local bold = function(s)
return string.format("\002%s\002", s)
end
local underline = function(s)
return string.format("\031%s\031", s)
end
local italic = function(s)
return string.format("\029%s\029", s)
end
local reverse = function(s)
return string.format("\018%s\018", s)
end
local rot13 = function(s)
local byte_a, byte_A = string.byte('a'), string.byte('A')
return (string.gsub((s or ''), "[%a]",
function (char)
local offset = (char < 'a') and byte_A or byte_a
local b = string.byte(char) - offset -- 0 to 25
b = ((b + 13) % 26) + offset -- Rotate
return string.char(b)
end
))
end
local color = function(s, color)
return string.format("\03%02d%s%s", color, s, reset())
end
local urlEncode = function(str)
return str:gsub(
'([^%w ])',
function (c)
return string.format ("%%%02X", string.byte(c))
end
):gsub(' ', '+')
end
local trim = function(s)
return (string.gsub(s, "^%s*(.-)%s*$", "%1"))
end
local split = function(str, delim)
if str == "" or str == nil then
return { }
end
str = str .. delim
local _accum_0 = { }
local _len_0 = 1
for m in str:gmatch("(.-)" .. delim) do
_accum_0[_len_0] = m
_len_0 = _len_0 + 1
end
return _accum_0
end
local translateWords = function(str, callback, fixCase, nickpat)
-- Usage: etc.translateWords(s ,callback) the callback can return new word, false to skip, or nil to keep the same word.
local str = assert(str)
local callback = assert(callback, "Callback expected")
local fixCase = fixCase == nil or fixCase == true
local nickpat = nickpat
local prev = 1
local result = ""
local pat = "()([%w'%-]+)()"
if nickpat then
pat = "()([%w_'%-%{%}%[%]`%^]+)()"
end
for wpos, w, wposEnd in str:gmatch(pat) do
local wnew = callback(w)
if wnew ~= false then
result = result .. str:sub(prev, wpos - 1)
if wnew then
if fixCase then
if w == w:lower() then
elseif w == w:upper() then
wnew = wnew:upper()
elseif w:sub(1, 1) == w:sub(1, 1):upper() then
wnew = wnew:sub(1, 1):upper() .. wnew:sub(2)
end
end
result = result .. wnew
else
result = result .. w
end
if not wnew then
wnew = w
end
end
prev = wposEnd
end
result = result .. str:sub(prev)
return result
end
local nonickalert = function(nicklist, str)
-- U+200B, ZERO WIDTH SPACE: "\226\128\139"
local s = str or ''
local nl = nicklist -- nicklist
local zwsp = "\226\128\142" -- LTR
nl = nl or {}
local nlkeys = {}
for nick, t in pairs(nicklist) do
nlkeys[nick:lower()] = true
end
return translateWords(s, function(x)
if nlkeys[x:lower()] then
return x:sub(1, 1) .. zwsp .. x:sub(2)
end
end, nil, true)
end
return {
bold=bold,
underline=underline,
italic=italic,
reverse=reverse,
color=color,
reset=reset,
urlEncode=urlEncode,
trim=trim,
split=split,
rot13=rot13,
json = require'cjson',
simplehttp = require'simplehttp',
white=function(s)
return color(s, 0)
end,
black=function(s)
return color(s, 1)
end,
blue=function(s)
return color(s, 2)
end,
green=function(s)
return color(s, 3)
end,
red=function(s)
return color(s, 4)
end,
maroon=function(s)
return color(s, 5)
end,
purple=function(s)
return color(s, 6)
end,
orange=function(s)
return color(s, 7)
end,
yellow=function(s)
return color(s, 8)
end,
lightgreen=function(s)
return color(s, 9)
end,
teal=function(s)
return color(s, 10)
end,
cyan=function(s)
return color(s, 11)
end,
lightblue=function(s)
return color(s, 12)
end,
fuchsia=function(s)
return color(s, 13)
end,
gray=function(s)
return color(s, 14)
end,
lightgray=function(s)
return color(s, 15)
end,
nonickalert=nonickalert,
translateWords=translateWords,
}
|
util: Fix mixed indent.
|
util: Fix mixed indent.
|
Lua
|
mit
|
haste/ivar2,torhve/ivar2,torhve/ivar2,torhve/ivar2
|
e9d1602eebd66ed250250461ac4c115a7ba31f65
|
lib/log_player.lua
|
lib/log_player.lua
|
package.cpath = "/usr/local/openresty/lualib/?.so;" .. package.cpath
local logFilePath = arg[1]
local MON={Jan=1,Feb=2,Mar=3,Apr=4,May=5,Jun=6,Jul=7,Aug=8,Sep=9,Oct=10,Nov=11,Dec=12}
local geoip = require "geoip";
local geoip_country = require "geoip.country"
local geoip_file = "/usr/share/GeoIP/GeoIP.dat"
local geoip_country_filename = geoip_file
geodb = geoip.country.open(geoip_country_filename)
function parseDate(date)
-- 28/Oct/2013:10:41:15 +0000
local p ="(%d+)/(%a+)/(%d+):(%d+):(%d+):(%d+)"
local day,month,year,hour,min,sec = date:match(p)
month=MON[month]
return os.time({day=day,month=month,year=year,hour=hour,min=min,sec=sec})
end
function getCountry(ip)
local country = geodb:query_by_addr(ip, "id")
return geoip.code_by_id(country)
end
function parseQueryArgs(queryArgs)
params = {}
for k,v in queryArgs:gmatch("(%w+%[?%]?)=(*)%&?") do
if k:match("[[]]") then
local key = k:gsub("[[]]", "")
if params[key] then
table.insert(params[key], v)
else
params[key] = {v}
end
else
params[k] = v
end
end
return params
end
function parseArgs(line)
args = parseQueryArgs(line)
ip, request_time, query_args = line:match("^([^%s]+).*%[(.*)].*GET%s*(.*)%s*HTTP")
parseQueryArgs(query_args)
args["action"] = query_args:match("%/(.*)%?")
date = parseDate(request_time)
args["day"] = os.date("%d", date)
args["week"] = os.date("%W", date)
args["month"] = os.date("%m", date)
args["year"] = os.date("%Y", date)
args["country"] = getCountry(ip)
if args["week"] == "00" then
args["week"] = "52"
args["year"] = tostring( tonumber(args["year"]) - 1 )
end
return args
end
local cjson = require "cjson"
for line in io.lines(logFilePath) do
args = parseArgs(line)
args_json = "'" .. cjson.encode(args) .. "'"
print(args_json)
os.execute("redis-cli evalsha 66063b195459196a03132c0c89b95efd6c17aa77 2 args mode " .. args_json .. " record")
end
|
package.cpath = "/usr/local/openresty/lualib/?.so;" .. package.cpath
local logFilePath = arg[1]
local MON={Jan=1,Feb=2,Mar=3,Apr=4,May=5,Jun=6,Jul=7,Aug=8,Sep=9,Oct=10,Nov=11,Dec=12}
local geoip = require "geoip";
local geoip_country = require "geoip.country"
local geoip_file = "/usr/share/GeoIP/GeoIP.dat"
local geoip_country_filename = geoip_file
geodb = geoip.country.open(geoip_country_filename)
function parseDate(date)
-- 28/Oct/2013:10:41:15 +0000
local p ="(%d+)/(%a+)/(%d+):(%d+):(%d+):(%d+)"
local day,month,year,hour,min,sec = date:match(p)
month=MON[month]
return os.time({day=day,month=month,year=year,hour=hour,min=min,sec=sec})
end
function getCountry(ip)
local country = geodb:query_by_addr(ip, "id")
return geoip.code_by_id(country)
end
function parseQueryArgs(queryArgs)
params = {}
for k,v in queryArgs:gmatch("(%w+%[?%]?)=([^&]+)") do
if k:match("[[]]") then
local key = k:gsub("[[]]", "")
if params[key] then
table.insert(params[key], v)
else
params[key] = {v}
end
else
params[k] = v
end
end
return params
end
function parseArgs(line)
ip, request_time, query_args = line:match("^([^%s]+).*%[(.*)].*GET%s*(.*)%s*HTTP")
args = parseQueryArgs(query_args)
args["action"] = query_args:match("%/(.*)%?")
date = parseDate(request_time)
args["day"] = os.date("%d", date)
args["week"] = os.date("%W", date)
args["month"] = os.date("%m", date)
args["year"] = os.date("%Y", date)
args["country"] = getCountry(ip)
if args["week"] == "00" then
args["week"] = "52"
args["year"] = tostring( tonumber(args["year"]) - 1 )
end
return args
end
local cjson = require "cjson"
for line in io.lines(logFilePath) do
args = parseArgs(line)
args_json = "'" .. cjson.encode(args) .. "'"
print(args_json)
os.execute("redis-cli evalsha 66063b195459196a03132c0c89b95efd6c17aa77 2 args mode " .. args_json .. " record")
end
|
fixed bug in log player
|
fixed bug in log player
|
Lua
|
mit
|
FTBpro/count-von-count,FTBpro/count-von-count
|
6b4acf85575025375f414371c749d9bab1dc6cf8
|
snippets.lua
|
snippets.lua
|
-- Snippets
--- # Global Snippets
usersnippets = {
['file'] = '%<buffer.filename>',
['beh'] = 'Behindertenpädagogik',
['FAB']= 'Fachkraft zur Arbeits- und Berufsförderung',
['FABs'] = 'Fachkräfte zur Arbeits- und Berufsförderung',
['FFK'] = 'Fähigkeiten, Fertigkeiten, Kenntnisse',
['SQ'] = 'Schlüsselqualifikation',
['HO'] = 'Handlungsorientierung',
['ho'] = 'handlungsorientiert',
['Reha'] = 'Rehabilitation',
['anfuu'] = '„',
['anfuo'] = '“',
}
-- Add user defined snippets to the preconfigured ones, overwriting, if
-- necessary
for k,v in pairs(usersnippets) do snippets[k] = v end
--- # Markdown Snippets
snippets.markdown = {
-- Headers.
['1'] = '# ',
['2'] = '## ',
['3'] = '### ',
['4'] = '#### ',
['5'] = '##### ',
['6'] = '###### ',
--Links
link = '[%1(Link)](%2(http://example.net/))',
--Clickable link.
clink = '<%1(http://example.com/)>',
--Reference-style link.
rlink = '[%1(example)][%2(ref)]',
id = '[%1(ref)]: %2(http://example.com/)',
-- Code.
c = '`%0`',
-- Codeblock
cb = '```%0\n```',
-- Image.
i = ')',
}
--- # LaTeX Snippets
snippets.latex = {
-- Sections etc.
['chap'] = '\\chapter{%1(title)}\\label{chap:%2(label)}',
['sec'] = '\\section{%1(title)}\\label{sec:%2(label)}',
['sub'] = '\\subsection{%1(title)\\label{subsec:%2(label)}',
['subsub'] = '\\subsubsection{%1(title)}\\label{subsubsec:%2(label)}',
['par'] = '\\paragraph{%1(title)} ~\\',
-- Environments
--- first, generics
['begin'] = '\\begin{%1(type)}\n\t%3( )\n\\end{%2(type)}\n%4( )',
['item'] = '\\item %0',
['desitem'] = '\\item[%1(des)] %2(item)',
['ditem'] = '\\item[%1(des)] %2(item)',
--- next, the classics
['itemize'] = '\\begin{itemize}\n\t\\item %1(item)\n\\end{itemize}\n%2( )',
['enum'] = '\\begin{enumerate}\n\t\\item %1(item)\n\\end{enumerate}\n%2( )',
['enumerate'] = '\\begin{enumerate}\n\t\\item %1(item)\n\\end{enumerate}\n%2( )',
['description'] = '\\begin{description}\n\t\\item[%1(des)] %2(item)\n\\end{description}\n%3( )',
['des'] = '\\begin{description}\n\t\\item[%1(des)] %2(item)\n\\end{description}\n%3( )',
['desindent'] = '\\begin{itemize}[style=multiline,leftmargin=2.5cm,font=\\normalfont]\n\t\\item[%1(des)] %2(item)\n\\end{itemize}\n%3( )',
['frame'] = '\\begin{frame}\n\t\\item %1( )\n\\end{frame}\n%2( )',
--- skeleton of my most frequently used table
['table'] = '\\begin{table}[hb]\n\t\\begin{tabularx}{\\textwidth}{|l|X|}\n\t\\hline\n\t\\rowcolor{lightgray}\n\t%1(Header Column1) & %2(Header Column2)\\\\ \\hline\n\t%5(Row1Col1)& %6(Row1Col2)\\\\ \\hline\n\t%7(Row2Col1) & %8(Row2Col2)\\\\ \\hline\n\t\\end{tabularx}\n\t\\caption {%3(Caption)}\n\t\\label{tab:%4(label)}\n\\end{table}',
-- Arrows
['uparrow'] = '$\\uparrow $',
['Uparrow'] = '$\\Uparrow $',
['downarrow'] = '$\\downarrow $',
['Downarrow'] = '$\\Downarrow $',
['rightarrow'] = '$\\rightarrow $',
['Rightarrow'] = '$\\Rightarrow $',
['leftarrow'] = '$\\leftarrow $',
['Leftarrow'] = '$\\Leftarrow $',
-- In-Document References
['ref'] = '\\ref{%0}',
['page'] = '\\pageref{%0}',
['name'] = '\\nameref{%0}',
-- Quoting, using csquotes
['enq'] = '\\enquote{%0}',
--- blockquotes
['zit'] = '\\begin{quote}\n\t\\enquote{%1(Quote)}\n\t\\parencite[S.\\,%3(page)]{%2(source)}\n\\end{quote}',
--- blockquotes for laws
['rzit'] = '\\begin{quote}\n\t\\enquote{%1(Quote)}\n\t(§\\,%2(source))\n\\citereset{}\n\\end{quote}',
-- Biblatex citation commands
--- \cite [ prenote ][ postnote ]{ key }
['citepre'] = '\\cite[%3(prenote)][S.\\,%2(page){%1(source)}',
--- \cite [ postnote ]{ key }
['cite'] = '\\cite[S.\\,%2(page)]{%1(source)}',
--- \parencite [ prenote ][ postnote ]{ key }
['parencitepre'] = '\\parencite[%3(prenote)][S.\\,%2(page){%1(source)}',
--- \parencite [ postnote ]{ key }
['parencite'] = '\\parencite[S.\\,%2(page)]{%1(source)}',
--- \textcite [ prenote ][ postnote ]{ key }
['textcitepre'] = '\\textcite[%3(prenote)][S.\\,%2(page){%1(source)}',
--- \parencite [ postnote ]{ key }
['textcite'] = '\\textcite[S.\\,%2(page)]{%1(source)}',
--- \citeauthor{key}
['aut'] = '\\citeauthor{%0}',
--- \citetitle{key}
['citetitle'] = '\\citetitle{%0}',
--- \citetitle* [ prenote ][ postnote ]{ key }
['citefulltitle'] = '\\citetitle*{%0}',
['citetitle*'] = '\\citetitle*{%0}',
--- \citeyear [ prenote ][ postnote ]{ key }
['citeyear'] = '\\citeyear{%0}',
--- \fullcite{ key}
['fullcite'] = '\\fullcite{%0}',
--- \citereset{}
['citereset'] = '\\citereset{}',
['cr'] = '\\citereset{}',
-- Some abbreviations frequently used in German academia
['oä'] = 'o.\\,ä. ',
['uä'] = 'u.\\,ä. ',
['ua'] = 'u.\\,a. ',
['va'] = 'v.\\,a. ',
['zb'] = 'z.\\,B. ',
['dh'] = 'd.\\,h. ',
--- one of them usually followed by a citation.
['vgl'] = '(vgl. \\cite[S.\\,%2(page)]{%1(source)})',
-- Misc
['emph'] = '\\emph{%0}',
['bs'] = '\\bigskip{}',
['fn'] = '\\footnote{%0}',
['ma'] = '\\marginpar{%0}',
['rn'] = '\\marginpar{%0}',
-- a Comment Box I use in my excerpts
['anm'] = '\\begin{mdframed}[backgroundcolor=gray!20,roundcorner=8pt,shadow=true]\n\tAnm. ' .. user_initials .. ':\\\\\n\t%0\n\\end{mdframed}',
}
|
-- Snippets
--- # Global Snippets
usersnippets = {
['file'] = '%<buffer.filename>',
-- Specific stuff I frequently use in my German academic texts
['beh'] = 'Behindertenpädagogik',
['FAB'] = 'Fachkraft zur Arbeits- und Berufsförderung',
['FABs'] = 'Fachkräfte zur Arbeits- und Berufsförderung',
['FFK'] = 'Fähigkeiten, Fertigkeiten, Kenntnisse',
['SQ'] = 'Schlüsselqualifikation',
['HO'] = 'Handlungsorientierung',
['ho'] = 'handlungsorientiert',
['Reha'] = 'Rehabilitation',
['anfuu'] = '„',
['anfuo'] = '“',
['mmb'] = 'Menschen mit Behinderung',
['sozr'] = 'sozialraumorientiert',
['Sozr'] = 'Sozialraumorientierung',
}
-- Add user defined snippets to the preconfigured ones, overwriting, if
-- necessary
for k,v in pairs(usersnippets) do snippets[k] = v end
--- # Markdown Snippets
snippets.markdown = {
-- Headers.
['1'] = '# ',
['2'] = '## ',
['3'] = '### ',
['4'] = '#### ',
['5'] = '##### ',
['6'] = '###### ',
--Links
link = '[%1(Link)](%2(http://example.net/))',
--Clickable link.
clink = '<%1(http://example.com/)>',
--Reference-style link.
rlink = '[%1(example)][%2(ref)]',
id = '[%1(ref)]: %2(http://example.com/)',
-- Code.
c = '`%0`',
-- Codeblock
cb = '```%0\n```',
-- Image.
i = ')',
}
--- # LaTeX Snippets
snippets.latex = {
-- Sections etc.
['chap'] = '\\chapter{%1(title)}\\label{chap:%2(label)}',
['sec'] = '\\section{%1(title)}\\label{sec:%2(label)}',
['sub'] = '\\subsection{%1(title)}\\label{subsec:%2(label)}',
['subsub'] = '\\subsubsection{%1(title)}\\label{subsubsec:%2(label)}',
['par'] = '\\paragraph{%1(title)} ~\\',
-- Environments
--- first, generics
['begin'] = '\\begin{%1(type)}\n\t%3( )\n\\end{%2(type)}\n%4( )',
['item'] = '\\item %0',
['desitem'] = '\\item[%1(des)] %2(item)',
['ditem'] = '\\item[%1(des)] %2(item)',
--- next, the classics
['itemize'] = '\\begin{itemize}\n\t\\item %1(item)\n\\end{itemize}\n%2( )',
['enum'] = '\\begin{enumerate}\n\t\\item %1(item)\n\\end{enumerate}\n%2( )',
['enumerate'] = '\\begin{enumerate}\n\t\\item %1(item)\n\\end{enumerate}\n%2( )',
['description'] = '\\begin{description}\n\t\\item[%1(des)] %2(item)\n\\end{description}\n%3( )',
['des'] = '\\begin{description}\n\t\\item[%1(des)] %2(item)\n\\end{description}\n%3( )',
['desindent'] = '\\begin{itemize}[style=multiline,leftmargin=2.5cm,font=\\normalfont]\n\t\\item[%1(des)] %2(item)\n\\end{itemize}\n%3( )',
['frame'] = '\\begin{frame}\n\t\\item %1( )\n\\end{frame}\n%2( )',
--- skeleton of my most frequently used table
['table'] = '\\begin{table}[hb]\n\t\\begin{tabularx}{\\textwidth}{|l|X|}\n\t\\hline\n\t\\rowcolor{lightgray}\n\t%1(Header Column1) & %2(Header Column2)\\\\ \\hline\n\t%5(Row1Col1)& %6(Row1Col2)\\\\ \\hline\n\t%7(Row2Col1) & %8(Row2Col2)\\\\ \\hline\n\t\\end{tabularx}\n\t\\caption {%3(Caption)}\n\t\\label{tab:%4(label)}\n\\end{table}',
-- Figure
['fig'] = '\\begin{figure}[h]\n\t\\centering\n\t\\includegraphics[width=\\textwidth]{%1(file)}\n\t\\caption{%2(caption)}\n\t\\label{fig:%3(label)}\n\\end{figure}\n',
['abb'] = '\\begin{figure}[h]\n\t\\centering\n\t\\includegraphics[width=\\textwidth]{%1(file)}\n\t\\caption{%2(caption)}\n\t\\label{fig:%3(label)}\n\\end{figure}\n',
-- Arrows
['uparrow'] = '$\\uparrow $',
['Uparrow'] = '$\\Uparrow $',
['downarrow'] = '$\\downarrow $',
['Downarrow'] = '$\\Downarrow $',
['rightarrow'] = '$\\rightarrow $',
['Rightarrow'] = '$\\Rightarrow $',
['leftarrow'] = '$\\leftarrow $',
['Leftarrow'] = '$\\Leftarrow $',
-- In-Document References
['ref'] = '\\ref{%0}',
['page'] = '\\pageref{%0}',
['name'] = '\\nameref{%0}',
-- Quoting, using csquotes
['enq'] = '\\enquote{%0}',
--- blockquotes
['zit'] = '\\begin{quote}\n\t\\enquote{%1(Quote)}\n\t\\parencite[S.\\,%3(page)]{%2(source)}\n\\end{quote}',
--- blockquotes for laws
['rzit'] = '\\begin{quote}\n\t\\enquote{%1(Quote)}\n\t(§\\,%2(source))\n\\citereset{}\n\\end{quote}',
-- Biblatex citation commands
--- \cite [ prenote ][ postnote ]{ key }
['citepre'] = '\\cite[%3(prenote)][S.\\,%2(page){%1(source)}',
--- \cite [ postnote ]{ key }
['cite'] = '\\cite[S.\\,%2(page)]{%1(source)}',
--- \parencite [ prenote ][ postnote ]{ key }
['parencitepre'] = '\\parencite[%3(prenote)][S.\\,%2(page){%1(source)}',
--- \parencite [ postnote ]{ key }
['parencite'] = '\\parencite[S.\\,%2(page)]{%1(source)}',
--- \textcite [ prenote ][ postnote ]{ key }
['textcitepre'] = '\\textcite[%3(prenote)][S.\\,%2(page){%1(source)}',
--- \parencite [ postnote ]{ key }
['textcite'] = '\\textcite[S.\\,%2(page)]{%1(source)}',
--- \citeauthor{key}
['aut'] = '\\citeauthor{%0}',
--- \citetitle{key}
['citetitle'] = '\\citetitle{%0}',
--- \citetitle* [ prenote ][ postnote ]{ key }
['citefulltitle'] = '\\citetitle*{%0}',
['citetitle*'] = '\\citetitle*{%0}',
--- \citeyear [ prenote ][ postnote ]{ key }
['citeyear'] = '\\citeyear{%0}',
--- \fullcite{ key}
['fullcite'] = '\\fullcite{%0}',
--- \citereset{}
['citereset'] = '\\citereset{}',
['cr'] = '\\citereset{}',
-- Some abbreviations frequently used in German academia
['oä'] = 'o.\\,ä. ',
['uä'] = 'u.\\,ä. ',
['ua'] = 'u.\\,a. ',
['va'] = 'v.\\,a. ',
['zb'] = 'z.\\,B. ',
['dh'] = 'd.\\,h. ',
['uu'] = 'u.\\,U. ',
['me'] = 'm.\\,E. ',
['mE'] = 'm.\\,E. ',
--- one of them usually followed by a citation.
['vgl'] = '(vgl. \\cite[S.\\,%2(page)]{%1(source)})',
-- Misc
['emph'] = '\\emph{%0}',
['bs'] = '\\bigskip{}',
['fn'] = '\\footnote{%0}',
['ma'] = '\\marginpar{%0}',
['rn'] = '\\marginpar{%0}',
-- a Comment Box I use in my excerpts
['anm'] = '\\begin{mdframed}[backgroundcolor=gray!20,roundcorner=8pt,shadow=true]\n\tAnm. ' .. user_initials .. ':\\\\\n\t%0\n\\end{mdframed}',
}
|
Bugfixes
|
Bugfixes
|
Lua
|
mit
|
sthesing/.textadept,sthesing/.textadept,sthesing/.textadept
|
9ef9cc7698ee63fc0a61207da3a77433b71daaef
|
scripts/lmkbuild.lua
|
scripts/lmkbuild.lua
|
require "lmk"
require "lmkutil"
require "lmkbase"
local assert = assert
local error = error
local io = io
local ipairs = ipairs
local lmk = lmk
local lmkbase = lmkbase
local lmkutil = lmkutil
local os = os
local print = print
local tostring = tostring
local type = type
module (...)
add_files = lmk.add_files_local
append_global = lmk.append_global
append_local = lmk.append_local
get_var = lmk.get_var
resolve = lmk.resolve
set_local = lmk.set_local
set_global = lmk.set_global
system = lmk.system
is_dir = lmkbase.is_dir
directories = lmkbase.directories
files = lmkbase.files
function print_success (msg)
print (lmk.ConsoleGreen .. msg .. lmk.ConsoleDefault)
end
function print_fail (msg)
print (lmk.ConsoleRed .. msg .. lmk.ConsoleDefault)
end
function verbose () return lmk.IsVerbose end
local buildPart1 = nil
local buildPart2 = nil
function get_build_number ()
if not buildPart1 or not buildPart2 then
buildPart1 = os.date ("!%y%m%d")
buildPart2 = os.date ("!%H%M%S")
end
return
tostring (buildPart1) .. "-" .. tostring (buildPart2),
tostring (buildPart1),
tostring (buildPart2)
end
function append_table (target, add)
if type (target) ~= "table" then
error ("Expect table but was given: " .. type (target)) end
local size = #target
if type (add) ~= "table" then target[size + 1] = add
else for ix = 1, #add do target[size + ix] = add[ix] end
end
end
function set_persist (name, value) set_global (name, value, true) end
function rm (path)
path = lmkutil.clean_path (lmk.resolve (path))
local result, msg = true, nil
if lmkbase.is_valid (path) then
print ("Removing: " .. path)
result, msg = lmkutil.raw_rm (path)
end
return result, msg
end
function mkdir (path)
path = lmkutil.clean_path (lmk.resolve (path))
local result, msg = true, nil
assert (path ~= "", "Path not defined for lmkbuild.mkdir")
if path then result, msg = lmkutil.raw_mkdir (path) end
return result, msg
end
function split (path)
path = lmkutil.clean_path (lmk.resolve (path))
local file, ext = nil, nil
if path then path, file, ext = lmkutil.raw_split (path) end
return path, file, ext
end
function split_path_and_file (path)
local file, ext = nil, nil
path, file, ext = split (path)
if ext and file then file = file .. "." .. ext end
return path, file
end
function abs_path (path)
return lmkutil.raw_abs_path (lmk.resolve (path))
end
local function copy_file (src, target)
local result = false
local inp = io.open (src, "rb")
local out = io.open (target, "wb")
if inp and out then
local data = inp:read ("*all")
out:write (data)
io.close (inp)
io.close (out)
result = true
end
return result
end
function cp (fileList, target)
local result = true
target = lmkutil.clean_path (lmk.resolve (target))
if type (fileList) ~= "table" then fileList = { fileList } end
if lmkbase.is_dir (target) then
for index, file in ipairs (fileList) do
file = lmkutil.clean_path (lmk.resolve (file))
if lmkbase.is_valid (file) then
local path = nil
path, file = split_path_and_file (file)
if not copy_file (file, target .. "/" .. file) then
result = false
end
end
end
else
if #fileList == 1 then
local file = lmk.resolve (fileList[1])
if (lmkbase.is_valid (file)) then
result = copy_file (file, target)
else result = false;
end
else
result = false
msg = "Unable to copy multiple files to single file"
end
end
return result
end
function is_valid (path)
return lmkbase.is_valid (lmk.resolve (path))
end
function file_newer (src, target)
local result, msg = false, nil
if type (src) ~= "table" then src = { src } end
target = lmkutil.clean_path (lmk.resolve (target))
if lmkbase.is_valid (target) then
for index, file in ipairs (src) do
file = lmkutil.clean_path (lmk.resolve (file))
if lmkbase.is_valid (file) then
result = lmkbase.file_newer (file, target)
if result then break end
else
print ("Warning: source file: " .. file ..
" does not exist for target file: " .. target)
end
end
else result = true
end
return result, msg
end
function exec (list)
if type (list) ~= "table" then list = { list } end
for index, item in ipairs (list) do
local todo = resolve (item)
assert (todo and todo ~= "", "Empty exec string from: " .. item)
if lmk.IsVerbose then
print (todo)
local result = os.execute (todo)
assert (result == 0, "Build faild in " .. lmkbase.pwd ())
else
local result = os.execute (todo)
if result ~= 0 then
print (todo)
error ("Build failded in " .. lmkbase.pwd ())
end
end
end
end
function find_file (item, paths)
local file = lmk.resolve (item)
if is_valid (file) then file = abs_path (file)
elseif paths then
local p, f, e = split (file)
file = nil
for ix = 1, #paths do
local testPath = resolve (paths[ix] .. "/" .. item)
if is_valid (testPath) then file = abs_path (testPath); break
else
testPath = resolve (paths[ix]) .. f .. (e and ("." .. e) or "")
if is_valid (testPath) then file = abs_path (testPath); break end
end
end
end
return file
end
|
require "lmk"
require "lmkutil"
require "lmkbase"
local assert = assert
local error = error
local io = io
local ipairs = ipairs
local lmk = lmk
local lmkbase = lmkbase
local lmkutil = lmkutil
local os = os
local print = print
local tostring = tostring
local type = type
module (...)
add_files = lmk.add_files_local
append_global = lmk.append_global
append_local = lmk.append_local
get_var = lmk.get_var
resolve = lmk.resolve
set_local = lmk.set_local
set_global = lmk.set_global
system = lmk.system
is_dir = lmkbase.is_dir
directories = lmkbase.directories
files = lmkbase.files
function print_success (msg)
print (lmk.ConsoleGreen .. msg .. lmk.ConsoleDefault)
end
function print_fail (msg)
print (lmk.ConsoleRed .. msg .. lmk.ConsoleDefault)
end
function verbose () return lmk.IsVerbose end
local buildPart1 = nil
local buildPart2 = nil
function get_build_number ()
if not buildPart1 or not buildPart2 then
buildPart1 = os.date ("!%y%m%d")
buildPart2 = os.date ("!%H%M%S")
end
return
tostring (buildPart1) .. "-" .. tostring (buildPart2),
tostring (buildPart1),
tostring (buildPart2)
end
function append_table (target, add)
if type (target) ~= "table" then
error ("Expect table but was given: " .. type (target)) end
local size = #target
if type (add) ~= "table" then target[size + 1] = add
else for ix = 1, #add do target[size + ix] = add[ix] end
end
end
function set_persist (name, value) set_global (name, value, true) end
function rm (path)
path = lmkutil.clean_path (lmk.resolve (path))
local result, msg = true, nil
if lmkbase.is_valid (path) then
print ("Removing: " .. path)
result, msg = lmkutil.raw_rm (path)
end
return result, msg
end
function mkdir (path)
path = lmkutil.clean_path (lmk.resolve (path))
local result, msg = true, nil
assert (path ~= "", "Path not defined for lmkbuild.mkdir")
if path then result, msg = lmkutil.raw_mkdir (path) end
return result, msg
end
function split (path)
path = lmkutil.clean_path (lmk.resolve (path))
local file, ext = nil, nil
if path then path, file, ext = lmkutil.raw_split (path) end
return path, file, ext
end
function split_path_and_file (path)
local file, ext = nil, nil
path, file, ext = split (path)
if ext and file then file = file .. "." .. ext end
return path, file
end
function abs_path (path)
return lmkutil.raw_abs_path (lmk.resolve (path))
end
local function copy_file (src, target)
local result = false
local inp = io.open (src, "rb")
local out = io.open (target, "wb")
if inp and out then
local data = inp:read ("*all")
out:write (data)
io.close (inp)
io.close (out)
result = true
end
return result
end
function cp (fileList, target)
local result = true
target = lmkutil.clean_path (lmk.resolve (target))
if type (fileList) ~= "table" then fileList = { fileList } end
if lmkbase.is_dir (target) then
for index, file in ipairs (fileList) do
file = lmkutil.clean_path (lmk.resolve (file))
if lmkbase.is_valid (file) then
local path = nil
path, file = split_path_and_file (file)
if not copy_file (file, target .. "/" .. file) then
result = false
end
end
end
else
if #fileList == 1 then
local file = lmk.resolve (fileList[1])
if (lmkbase.is_valid (file)) then
result = copy_file (file, target)
else result = false;
end
else
result = false
msg = "Unable to copy multiple files to single file"
end
end
return result
end
function is_valid (path)
return lmkbase.is_valid (lmk.resolve (path))
end
function file_newer (src, target)
local result, msg = false, nil
if type (src) ~= "table" then src = { src } end
target = lmkutil.clean_path (lmk.resolve (target))
if lmkbase.is_valid (target) then
for index, file in ipairs (src) do
file = lmkutil.clean_path (lmk.resolve (file))
if lmkbase.is_valid (file) then
result = lmkbase.file_newer (file, target)
if result then break end
else
result = true
print ("Warning: source file: " .. file ..
" does not exist for target file: " .. target)
break
end
end
else result = true
end
return result, msg
end
function exec (list)
if type (list) ~= "table" then list = { list } end
for index, item in ipairs (list) do
local todo = resolve (item)
assert (todo and todo ~= "", "Empty exec string from: " .. item)
if lmk.IsVerbose then
print (todo)
local result = os.execute (todo)
assert (result == 0, "Build faild in " .. lmkbase.pwd ())
else
local result = os.execute (todo)
if result ~= 0 then
print (todo)
error ("Build failded in " .. lmkbase.pwd ())
end
end
end
end
function find_file (item, paths)
local file = lmk.resolve (item)
if is_valid (file) then file = abs_path (file)
elseif paths then
local p, f, e = split (file)
file = nil
for ix = 1, #paths do
local testPath = resolve (paths[ix] .. "/" .. item)
if is_valid (testPath) then file = abs_path (testPath); break
else
testPath = resolve (paths[ix]) .. f .. (e and ("." .. e) or "")
if is_valid (testPath) then file = abs_path (testPath); break end
end
end
end
return file
end
|
Bugfix: missing header files were not being evaluated correctly in depend.
|
Bugfix: missing header files were not being evaluated correctly in depend.
|
Lua
|
mit
|
shillcock/lmk,dmzgroup/lmk
|
623d8182eb93c2cb0cb1ea81ecec926da2ce9849
|
service/launcher.lua
|
service/launcher.lua
|
local skynet = require "skynet"
local core = require "skynet.core"
require "skynet.manager" -- import manager apis
local string = string
local services = {}
local command = {}
local instance = {} -- for confirm (function command.LAUNCH / command.ERROR / command.LAUNCHOK)
local launch_session = {} -- for command.QUERY, service_address -> session
local function handle_to_address(handle)
return tonumber("0x" .. string.sub(handle , 2))
end
local NORET = {}
function command.LIST()
local list = {}
for k,v in pairs(services) do
list[skynet.address(k)] = v
end
return list
end
local function list_srv(ti, fmt_func, ...)
local list = {}
local sessions = {}
local req = skynet.request()
for addr in pairs(services) do
local r = { addr, "debug", ... }
req:add(r)
sessions[r] = addr
end
for resp, req in req:select(ti) do
local stat = resp[1]
local addr = req[1]
if resp.ok then
list[skynet.address(addr)] = fmt_func(stat, addr)
else
list[skynet.address(addr)] = fmt_func("ERROR", addr)
end
sessions[req] = nil
end
for session, addr in pairs(sessions) do
list[skynet.address(addr)] = fmt_func("TIMEOUT", addr)
end
return list
end
function command.STAT(addr, ti)
return list_srv(ti, function(v) return v end, "STAT")
end
function command.KILL(_, handle)
handle = handle_to_address(handle)
skynet.kill(handle)
local ret = { [skynet.address(handle)] = tostring(services[handle]) }
services[handle] = nil
return ret
end
function command.MEM(addr, ti)
return list_srv(ti, function(kb, addr)
local v = services[addr]
if kb == "TIMEOUT" then
return string.format("TIMEOUT (%s)",v)
else
return string.format("%.2f Kb (%s)",kb,v)
end
end, "MEM")
end
function command.GC(addr, ti)
for k,v in pairs(services) do
skynet.send(k,"debug","GC")
end
return command.MEM(ti)
end
function command.REMOVE(_, handle, kill)
services[handle] = nil
local response = instance[handle]
if response then
-- instance is dead
response(not kill) -- return nil to caller of newservice, when kill == false
instance[handle] = nil
launch_session[handle] = nil
end
-- don't return (skynet.ret) because the handle may exit
return NORET
end
local function launch_service(service, ...)
local param = table.concat({...}, " ")
local inst = skynet.launch(service, param)
local session = skynet.context()
local response = skynet.response()
if inst then
services[inst] = service .. " " .. param
instance[inst] = response
launch_session[inst] = session
else
response(false)
return
end
return inst
end
function command.LAUNCH(_, service, ...)
launch_service(service, ...)
return NORET
end
function command.LOGLAUNCH(_, service, ...)
local inst = launch_service(service, ...)
if inst then
core.command("LOGON", skynet.address(inst))
end
return NORET
end
function command.ERROR(address)
-- see serivce-src/service_lua.c
-- init failed
local response = instance[address]
if response then
response(false)
launch_session[address] = nil
instance[address] = nil
end
services[address] = nil
return NORET
end
function command.LAUNCHOK(address)
-- init notice
local response = instance[address]
if response then
response(true, address)
instance[address] = nil
launch_session[address] = nil
end
return NORET
end
function command.QUERY(_, request_session)
for address, session in pairs(launch_session) do
if session == request_session then
return address
end
end
end
-- for historical reasons, launcher support text command (for C service)
skynet.register_protocol {
name = "text",
id = skynet.PTYPE_TEXT,
unpack = skynet.tostring,
dispatch = function(session, address , cmd)
if cmd == "" then
command.LAUNCHOK(address)
elseif cmd == "ERROR" then
command.ERROR(address)
else
error ("Invalid text command " .. cmd)
end
end,
}
skynet.dispatch("lua", function(session, address, cmd , ...)
cmd = string.upper(cmd)
local f = command[cmd]
if f then
local ret = f(address, ...)
if ret ~= NORET then
skynet.ret(skynet.pack(ret))
end
else
skynet.ret(skynet.pack {"Unknown command"} )
end
end)
skynet.start(function() end)
|
local skynet = require "skynet"
local core = require "skynet.core"
require "skynet.manager" -- import manager apis
local string = string
local services = {}
local command = {}
local instance = {} -- for confirm (function command.LAUNCH / command.ERROR / command.LAUNCHOK)
local launch_session = {} -- for command.QUERY, service_address -> session
local function handle_to_address(handle)
return tonumber("0x" .. string.sub(handle , 2))
end
local NORET = {}
function command.LIST()
local list = {}
for k,v in pairs(services) do
list[skynet.address(k)] = v
end
return list
end
local function list_srv(ti, fmt_func, ...)
local list = {}
local sessions = {}
local req = skynet.request()
for addr in pairs(services) do
local r = { addr, "debug", ... }
req:add(r)
sessions[r] = addr
end
for req, resp in req:select(ti) do
local stat = resp[1]
local addr = req[1]
if resp then
list[skynet.address(addr)] = fmt_func(stat, addr)
else
list[skynet.address(addr)] = fmt_func("ERROR", addr)
end
sessions[req] = nil
end
for session, addr in pairs(sessions) do
list[skynet.address(addr)] = fmt_func("TIMEOUT", addr)
end
return list
end
function command.STAT(addr, ti)
return list_srv(ti, function(v) return v end, "STAT")
end
function command.KILL(_, handle)
handle = handle_to_address(handle)
skynet.kill(handle)
local ret = { [skynet.address(handle)] = tostring(services[handle]) }
services[handle] = nil
return ret
end
function command.MEM(addr, ti)
return list_srv(ti, function(kb, addr)
local v = services[addr]
if type(kb) == "string" then
return string.format("%s (%s)", kb, v)
else
return string.format("%.2f Kb (%s)",kb,v)
end
end, "MEM")
end
function command.GC(addr, ti)
for k,v in pairs(services) do
skynet.send(k,"debug","GC")
end
return command.MEM(addr, ti)
end
function command.REMOVE(_, handle, kill)
services[handle] = nil
local response = instance[handle]
if response then
-- instance is dead
response(not kill) -- return nil to caller of newservice, when kill == false
instance[handle] = nil
launch_session[handle] = nil
end
-- don't return (skynet.ret) because the handle may exit
return NORET
end
local function launch_service(service, ...)
local param = table.concat({...}, " ")
local inst = skynet.launch(service, param)
local session = skynet.context()
local response = skynet.response()
if inst then
services[inst] = service .. " " .. param
instance[inst] = response
launch_session[inst] = session
else
response(false)
return
end
return inst
end
function command.LAUNCH(_, service, ...)
launch_service(service, ...)
return NORET
end
function command.LOGLAUNCH(_, service, ...)
local inst = launch_service(service, ...)
if inst then
core.command("LOGON", skynet.address(inst))
end
return NORET
end
function command.ERROR(address)
-- see serivce-src/service_lua.c
-- init failed
local response = instance[address]
if response then
response(false)
launch_session[address] = nil
instance[address] = nil
end
services[address] = nil
return NORET
end
function command.LAUNCHOK(address)
-- init notice
local response = instance[address]
if response then
response(true, address)
instance[address] = nil
launch_session[address] = nil
end
return NORET
end
function command.QUERY(_, request_session)
for address, session in pairs(launch_session) do
if session == request_session then
return address
end
end
end
-- for historical reasons, launcher support text command (for C service)
skynet.register_protocol {
name = "text",
id = skynet.PTYPE_TEXT,
unpack = skynet.tostring,
dispatch = function(session, address , cmd)
if cmd == "" then
command.LAUNCHOK(address)
elseif cmd == "ERROR" then
command.ERROR(address)
else
error ("Invalid text command " .. cmd)
end
end,
}
skynet.dispatch("lua", function(session, address, cmd , ...)
cmd = string.upper(cmd)
local f = command[cmd]
if f then
local ret = f(address, ...)
if ret ~= NORET then
skynet.ret(skynet.pack(ret))
end
else
skynet.ret(skynet.pack {"Unknown command"} )
end
end)
skynet.start(function() end)
|
fix #1246
|
fix #1246
|
Lua
|
mit
|
JiessieDawn/skynet,sanikoyes/skynet,sanikoyes/skynet,wangyi0226/skynet,hongling0/skynet,xjdrew/skynet,pigparadise/skynet,xcjmine/skynet,xcjmine/skynet,korialuo/skynet,pigparadise/skynet,icetoggle/skynet,icetoggle/skynet,wangyi0226/skynet,hongling0/skynet,sanikoyes/skynet,xjdrew/skynet,pigparadise/skynet,korialuo/skynet,JiessieDawn/skynet,korialuo/skynet,cloudwu/skynet,cloudwu/skynet,JiessieDawn/skynet,icetoggle/skynet,xcjmine/skynet,xjdrew/skynet,hongling0/skynet,wangyi0226/skynet,cloudwu/skynet
|
53e0c654af685b46a38548cca6d5df7bad30a7dc
|
src/luarocks/command_line.lua
|
src/luarocks/command_line.lua
|
--- Functions for command-line scripts.
--module("luarocks.command_line", package.seeall)
local command_line = {}
local unpack = unpack or table.unpack
local util = require("luarocks.util")
local cfg = require("luarocks.cfg")
local path = require("luarocks.path")
local dir = require("luarocks.dir")
local deps = require("luarocks.deps")
local program = util.this_program("luarocks")
--- Display an error message and exit.
-- @param message string: The error message.
-- @param exitcode number: the exitcode to use
local function die(message, exitcode)
assert(type(message) == "string")
local ok, err = pcall(util.run_scheduled_functions)
if not ok then
util.printerr("\nLuaRocks "..cfg.program_version.." internal bug (please report at [email protected]):\n"..err)
end
util.printerr("\nError: "..message)
os.exit(exitcode or cfg.errorcodes.UNSPECIFIED)
end
local function replace_tree(flags, args, tree)
tree = dir.normalize(tree)
flags["tree"] = tree
for i = 1, #args do
if args[i]:match("%-%-tree=") then
args[i] = "--tree="..tree
break
end
end
path.use_tree(tree)
end
--- Main command-line processor.
-- Parses input arguments and calls the appropriate driver function
-- to execute the action requested on the command-line, forwarding
-- to it any additional arguments passed by the user.
-- Uses the global table "commands", which contains
-- the loaded modules representing commands.
-- @param ... string: Arguments given on the command-line.
function command_line.run_command(...)
local args = {...}
local cmdline_vars = {}
for i = #args, 1, -1 do
local arg = args[i]
if arg:match("^[^-][^=]*=") then
local var, val = arg:match("^([A-Z_][A-Z0-9_]*)=(.*)")
if val then
cmdline_vars[var] = val
table.remove(args, i)
else
die("Invalid assignment: "..arg)
end
end
end
local nonflags = { util.parse_flags(unpack(args)) }
local flags = table.remove(nonflags, 1)
if flags["from"] then flags["server"] = flags["from"] end
if flags["only-from"] then flags["only-server"] = flags["only-from"] end
if flags["only-sources-from"] then flags["only-sources"] = flags["only-sources-from"] end
if flags["to"] then flags["tree"] = flags["to"] end
if flags["nodeps"] then
flags["deps-mode"] = "none"
table.insert(args, "--deps-mode=none")
end
cfg.flags = flags
local command
if flags["verbose"] then -- setting it in the config file will kick-in earlier in the process
cfg.verbose = true
local fs = require("luarocks.fs")
fs.verbose()
end
if flags["timeout"] then -- setting it in the config file will kick-in earlier in the process
local timeout = tonumber(flags["timeout"])
if timeout then
cfg.connection_timeout = timeout
else
die "Argument error: --timeout expects a numeric argument."
end
end
if flags["version"] then
util.printout(program.." "..cfg.program_version)
util.printout(program_description)
util.printout()
os.exit(cfg.errorcodes.OK)
elseif flags["help"] or #nonflags == 0 then
command = "help"
args = nonflags
else
command = nonflags[1]
for i, arg in ipairs(args) do
if arg == command then
table.remove(args, i)
break
end
end
end
command = command:gsub("-", "_")
if flags["extensions"] then
cfg.use_extensions = true
local type_check = require("luarocks.type_check")
type_check.load_extensions()
end
if cfg.local_by_default then
flags["local"] = true
end
if flags["deps-mode"] and not deps.check_deps_mode_flag(flags["deps-mode"]) then
die("Invalid entry for --deps-mode.")
end
if flags["branch"] then
if flags["branch"] == true or flags["branch"] == "" then
die("Argument error: use --branch=<branch-name>")
end
cfg.branch = flags["branch"]
end
if flags["tree"] then
if flags["tree"] == true or flags["tree"] == "" then
die("Argument error: use --tree=<path>")
end
local named = false
for _, tree in ipairs(cfg.rocks_trees) do
if type(tree) == "table" and flags["tree"] == tree.name then
if not tree.root then
die("Configuration error: tree '"..tree.name.."' has no 'root' field.")
end
replace_tree(flags, args, tree.root)
named = true
break
end
end
if not named then
local fs = require("luarocks.fs")
local root_dir = fs.absolute_name(flags["tree"])
replace_tree(flags, args, root_dir)
end
elseif flags["local"] then
replace_tree(flags, args, cfg.home_tree)
else
local trees = cfg.rocks_trees
path.use_tree(trees[#trees])
end
if type(cfg.root_dir) == "string" then
cfg.root_dir = cfg.root_dir:gsub("/+$", "")
else
cfg.root_dir.root = cfg.root_dir.root:gsub("/+$", "")
end
cfg.rocks_dir = cfg.rocks_dir:gsub("/+$", "")
cfg.deploy_bin_dir = cfg.deploy_bin_dir:gsub("/+$", "")
cfg.deploy_lua_dir = cfg.deploy_lua_dir:gsub("/+$", "")
cfg.deploy_lib_dir = cfg.deploy_lib_dir:gsub("/+$", "")
cfg.variables.ROCKS_TREE = cfg.rocks_dir
cfg.variables.SCRIPTS_DIR = cfg.deploy_bin_dir
if flags["server"] then
if flags["server"] == true then
die("Argument error: use --server=<url>")
end
local protocol, path = dir.split_url(flags["server"])
table.insert(cfg.rocks_servers, 1, protocol.."://"..path)
end
if flags["only-server"] then
if flags["only-server"] == true then
die("Argument error: use --only-server=<url>")
end
cfg.rocks_servers = { flags["only-server"] }
end
if flags["only-sources"] then
cfg.only_sources_from = flags["only-sources"]
end
if command ~= "help" then
for k, v in pairs(cmdline_vars) do
cfg.variables[k] = v
end
end
if commands[command] then
-- TODO the interface of run should be modified, to receive the
-- flags table and the (possibly unpacked) nonflags arguments.
-- This would remove redundant parsing of arguments.
-- I'm not changing this now to avoid messing with the run()
-- interface, which I know some people use (even though
-- I never published it as a public API...)
local cmd = require(commands[command])
local xp, ok, err, exitcode = xpcall(function() return cmd.run(unpack(args)) end, function(err)
die(debug.traceback("LuaRocks "..cfg.program_version
.." bug (please report at [email protected]).\n"
..err, 2), cfg.errorcodes.CRASH)
end)
if xp and (not ok) then
die(err, exitcode)
end
else
die("Unknown command: "..command)
end
util.run_scheduled_functions()
end
return command_line
|
--- Functions for command-line scripts.
--module("luarocks.command_line", package.seeall)
local command_line = {}
local unpack = unpack or table.unpack
local util = require("luarocks.util")
local cfg = require("luarocks.cfg")
local path = require("luarocks.path")
local dir = require("luarocks.dir")
local deps = require("luarocks.deps")
local program = util.this_program("luarocks")
--- Display an error message and exit.
-- @param message string: The error message.
-- @param exitcode number: the exitcode to use
local function die(message, exitcode)
assert(type(message) == "string")
local ok, err = pcall(util.run_scheduled_functions)
if not ok then
util.printerr("\nLuaRocks "..cfg.program_version.." internal bug (please report at https://github.com/keplerproject/luarocks/issues):\n"..err)
end
util.printerr("\nError: "..message)
os.exit(exitcode or cfg.errorcodes.UNSPECIFIED)
end
local function replace_tree(flags, args, tree)
tree = dir.normalize(tree)
flags["tree"] = tree
for i = 1, #args do
if args[i]:match("%-%-tree=") then
args[i] = "--tree="..tree
break
end
end
path.use_tree(tree)
end
--- Main command-line processor.
-- Parses input arguments and calls the appropriate driver function
-- to execute the action requested on the command-line, forwarding
-- to it any additional arguments passed by the user.
-- Uses the global table "commands", which contains
-- the loaded modules representing commands.
-- @param ... string: Arguments given on the command-line.
function command_line.run_command(...)
local args = {...}
local cmdline_vars = {}
for i = #args, 1, -1 do
local arg = args[i]
if arg:match("^[^-][^=]*=") then
local var, val = arg:match("^([A-Z_][A-Z0-9_]*)=(.*)")
if val then
cmdline_vars[var] = val
table.remove(args, i)
else
die("Invalid assignment: "..arg)
end
end
end
local nonflags = { util.parse_flags(unpack(args)) }
local flags = table.remove(nonflags, 1)
if flags["from"] then flags["server"] = flags["from"] end
if flags["only-from"] then flags["only-server"] = flags["only-from"] end
if flags["only-sources-from"] then flags["only-sources"] = flags["only-sources-from"] end
if flags["to"] then flags["tree"] = flags["to"] end
if flags["nodeps"] then
flags["deps-mode"] = "none"
table.insert(args, "--deps-mode=none")
end
cfg.flags = flags
local command
if flags["verbose"] then -- setting it in the config file will kick-in earlier in the process
cfg.verbose = true
local fs = require("luarocks.fs")
fs.verbose()
end
if flags["timeout"] then -- setting it in the config file will kick-in earlier in the process
local timeout = tonumber(flags["timeout"])
if timeout then
cfg.connection_timeout = timeout
else
die "Argument error: --timeout expects a numeric argument."
end
end
if flags["version"] then
util.printout(program.." "..cfg.program_version)
util.printout(program_description)
util.printout()
os.exit(cfg.errorcodes.OK)
elseif flags["help"] or #nonflags == 0 then
command = "help"
args = nonflags
else
command = nonflags[1]
for i, arg in ipairs(args) do
if arg == command then
table.remove(args, i)
break
end
end
end
command = command:gsub("-", "_")
if flags["extensions"] then
cfg.use_extensions = true
local type_check = require("luarocks.type_check")
type_check.load_extensions()
end
if cfg.local_by_default then
flags["local"] = true
end
if flags["deps-mode"] and not deps.check_deps_mode_flag(flags["deps-mode"]) then
die("Invalid entry for --deps-mode.")
end
if flags["branch"] then
if flags["branch"] == true or flags["branch"] == "" then
die("Argument error: use --branch=<branch-name>")
end
cfg.branch = flags["branch"]
end
if flags["tree"] then
if flags["tree"] == true or flags["tree"] == "" then
die("Argument error: use --tree=<path>")
end
local named = false
for _, tree in ipairs(cfg.rocks_trees) do
if type(tree) == "table" and flags["tree"] == tree.name then
if not tree.root then
die("Configuration error: tree '"..tree.name.."' has no 'root' field.")
end
replace_tree(flags, args, tree.root)
named = true
break
end
end
if not named then
local fs = require("luarocks.fs")
local root_dir = fs.absolute_name(flags["tree"])
replace_tree(flags, args, root_dir)
end
elseif flags["local"] then
replace_tree(flags, args, cfg.home_tree)
else
local trees = cfg.rocks_trees
path.use_tree(trees[#trees])
end
if type(cfg.root_dir) == "string" then
cfg.root_dir = cfg.root_dir:gsub("/+$", "")
else
cfg.root_dir.root = cfg.root_dir.root:gsub("/+$", "")
end
cfg.rocks_dir = cfg.rocks_dir:gsub("/+$", "")
cfg.deploy_bin_dir = cfg.deploy_bin_dir:gsub("/+$", "")
cfg.deploy_lua_dir = cfg.deploy_lua_dir:gsub("/+$", "")
cfg.deploy_lib_dir = cfg.deploy_lib_dir:gsub("/+$", "")
cfg.variables.ROCKS_TREE = cfg.rocks_dir
cfg.variables.SCRIPTS_DIR = cfg.deploy_bin_dir
if flags["server"] then
if flags["server"] == true then
die("Argument error: use --server=<url>")
end
local protocol, path = dir.split_url(flags["server"])
table.insert(cfg.rocks_servers, 1, protocol.."://"..path)
end
if flags["only-server"] then
if flags["only-server"] == true then
die("Argument error: use --only-server=<url>")
end
cfg.rocks_servers = { flags["only-server"] }
end
if flags["only-sources"] then
cfg.only_sources_from = flags["only-sources"]
end
if command ~= "help" then
for k, v in pairs(cmdline_vars) do
cfg.variables[k] = v
end
end
if commands[command] then
-- TODO the interface of run should be modified, to receive the
-- flags table and the (possibly unpacked) nonflags arguments.
-- This would remove redundant parsing of arguments.
-- I'm not changing this now to avoid messing with the run()
-- interface, which I know some people use (even though
-- I never published it as a public API...)
local cmd = require(commands[command])
local xp, ok, err, exitcode = xpcall(function() return cmd.run(unpack(args)) end, function(err)
die(debug.traceback("LuaRocks "..cfg.program_version
.." bug (please report at [email protected]).\n"
..err, 2), cfg.errorcodes.CRASH)
end)
if xp and (not ok) then
die(err, exitcode)
end
else
die("Unknown command: "..command)
end
util.run_scheduled_functions()
end
return command_line
|
Direct users to the bug tracker
|
Direct users to the bug tracker
|
Lua
|
mit
|
keplerproject/luarocks,aryajur/luarocks,rrthomas/luarocks,keplerproject/luarocks,tst2005/luarocks,usstwxy/luarocks,tarantool/luarocks,xpol/luarocks,rrthomas/luarocks,lxbgit/luarocks,tst2005/luarocks,lxbgit/luarocks,starius/luarocks,lxbgit/luarocks,xpol/luavm,starius/luarocks,xpol/luainstaller,xpol/luainstaller,xpol/luavm,luarocks/luarocks,keplerproject/luarocks,luarocks/luarocks,coderstudy/luarocks,xpol/luarocks,robooo/luarocks,xpol/luavm,coderstudy/luarocks,aryajur/luarocks,luarocks/luarocks,xiaq/luarocks,coderstudy/luarocks,tst2005/luarocks,xpol/luainstaller,ignacio/luarocks,aryajur/luarocks,xpol/luarocks,ignacio/luarocks,xiaq/luarocks,lxbgit/luarocks,ignacio/luarocks,tarantool/luarocks,xpol/luainstaller,tst2005/luarocks,coderstudy/luarocks,keplerproject/luarocks,xpol/luarocks,robooo/luarocks,starius/luarocks,xiaq/luarocks,usstwxy/luarocks,usstwxy/luarocks,robooo/luarocks,xiaq/luarocks,xpol/luavm,rrthomas/luarocks,aryajur/luarocks,tarantool/luarocks,starius/luarocks,robooo/luarocks,rrthomas/luarocks,xpol/luavm,usstwxy/luarocks,ignacio/luarocks
|
dcdd3e1229a4ed53fe85fcf77ba2bcfb834a913e
|
MMOCoreORB/bin/scripts/commands/rally.lua
|
MMOCoreORB/bin/scripts/commands/rally.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.
--true = 1, false = 0
RallyCommand = {
name = "rally",
action = "rally",
--actionCRC = action.hashCode(),
combatSpam = "rally",
}
AddCommand(RallyCommand)
|
--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.
--true = 1, false = 0
RallyCommand = {
name = "rally",
action = "rally",
combatSpam = "rally_success_single",
}
AddCommand(RallyCommand)
|
[Fixed] SL Rally combatspam.
|
[Fixed] SL Rally combatspam.
Change-Id: I1652d9c040493d7fdaca8ae1503a920c9c8ac316
|
Lua
|
agpl-3.0
|
Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/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,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo
|
57dcc86db6761cc3bcf64ef372b914465037b5ff
|
scripts/lib/getopt.lua
|
scripts/lib/getopt.lua
|
local api = {}
api.noArgument = 0
api.requiredArgument = 1
api.optionalArgument = 2
api.notOpt = {}
--[[
longOpts format:
{
name = {
hasArg = 0|1|2,
val = <something>
}...
}
]]
function api.getopt(argTbl, optString, longOpts, noErrors)
local printerrors = not noErrors
longOpts = longOpts or {}
local toParse = {}
for i = 1, #argTbl do
toParse[i] = argTbl[i]
end
local parseMode
local shortOpts = {}
parseMode, optString = optString:match("^([-+]?)(.+)")
while #optString > 0 do
local char, args
char, args, optString = optString:match("^(.)([:]?[:]?)(.*)")
if not char then
error("Malformed optString", 2)
end
shortOpts[char] = {
hasArg = (args == ":" and api.requiredArgument) or
(args == "::" and api.optionalArgument) or api.noArgument
}
end
local instance = {}
instance.notOptions = {}
function instance.evalNext()
local opt = table.remove(toParse, 1)
if opt == "--" then
return -1
end
if opt:sub(1, 1) == "-" then
if opt:sub(2, 2) == "-" then
-- Long option
opt = opt:sub(3)
local optParams = longOpts[opt]
if optParams then
if optParams.hasArg == api.noArgument then
return optParams.val or opt, nil
else
local nextElm = toParse[1]
if optParams.hasArg == api.optionalArgument then
if nextElm:sub(1, 1) == "-" then
return optParams.val or opt, nil
else
table.remove(toParse, 1)
return optParams.val or opt, nextElm
end
elseif optParams.hasArg == api.requiredArgument then
if nextElm:sub(1, 1) == "-" then
error(("Option '--%s' requires an argument"):format(opt), 0)
else
table.remove(toParse, 1)
return optParams.val or opt, nextElm
end
else
error(("Option Parameter 'hasArg' for '--%s' is invalid"):format(opt), 0)
end
end
else
if printerrors then
print(("Unknown option '--%s'"):format(opt), 8)
end
return "?", opt
end
else
if opt == "-" then
return api.notOpt
end
-- Short option
opt = opt:sub(2)
local char
char, opt = opt:match("^(.)(.*)")
table.insert(toParse, 1, "-" .. opt)
local optParams = shortOpts[char]
if optParams then
if optParams.hasArg == api.noArgument then
return char, nil
else
local nextElm = toParse[2]
if optParams.hasArg == api.optionalArgument then
if #opt == 0 then
if nextElm:sub(1, 1) == "-" then
return char, nil
else
table.remove(toParse, 2)
return char, nextElm
end
else
return char, nil
end
elseif optParams.hasArg == api.requiredArgument then
if #opt == 0 then
if nextElm:sub(1, 1) == "-" then
error(("Option '--%s' requires an argument"):format(opt), 0)
else
table.remove(toParse, 2)
return char, nextElm
end
else
local arg = opt
table.remove(toParse, 1)
return char, arg
end
else
error(("Option Parameter 'hasArg' for '--%s' is invalid"):format(opt), 0)
end
end
else
if printerrors then
print(("Unknown option '-%s'"):format(char), 8)
end
return "?", char
end
end
else
if parseMode == "+" then
return -1, opt
elseif parseMode == "-" then
return 1, opt
else
instance.notOptions[#instance.notOptions + 1] = opt
return api.notOpt
end
end
end
setmetatable(instance, {
__call = function(self, switchTable)
local val, arg = 0
while #toParse > 0 and val ~= -1 do
val, arg = instance.evalNext()
if val ~= api.notOpt then
if switchTable[val] then
switchTable[val](arg)
elseif switchTable.default then
switchTable.default(val, arg)
end
end
end
for i = 1, #toParse do
instance.notOptions[#instance.notOptions + 1] = toParse[i]
end
return instance
end
})
return instance
end
setmetatable(api, {__call = function(self, ...) return api.getopt(...) end})
return api
|
local api = {}
api.noArgument = 0
api.requiredArgument = 1
api.optionalArgument = 2
api.notOpt = {}
--[[
longOpts format:
{
name = {
hasArg = 0|1|2,
val = <something>
argumentLabel = "label" -- Required for printHelp when hasArg ~= 0
description = "text", -- Optional, used for printHelp
section = "sectionTitle", -- Optional, used for printHelp
}...
}
config:
{
description = "text"
sections = {
{
title = "sectionTitle",
description = "text"
}
}
}
]]
function api.getopt(argTbl, optString, longOpts, config)
config = config or {}
config.sections = config.sections or {}
local printErrors = config.printErrors or (not config.noErrors)
longOpts = longOpts or {}
local toParse = {}
for i = 1, #argTbl do
toParse[i] = argTbl[i]
end
local parseMode
local shortOpts = {}
parseMode, optString = optString:match("^([-+]?)(.*)")
while #optString > 0 do
local char, args
char, args, optString = optString:match("^(.)([:]?[:]?)(.*)")
if not char then
error("Malformed optString", 2)
end
shortOpts[char] = {
hasArg = (args == ":" and api.requiredArgument) or
(args == "::" and api.optionalArgument) or api.noArgument
}
end
local instance = {}
instance.notOptions = {}
function instance.evalNext()
local opt = table.remove(toParse, 1)
if opt == "--" then
return -1
end
if opt:sub(1, 1) == "-" then
if opt:sub(2, 2) == "-" then
-- Long option
opt = opt:sub(3)
local optParams = longOpts[opt]
if optParams then
if optParams.hasArg == api.noArgument then
return optParams.val or opt, nil
else
local nextElm = toParse[1]
if optParams.hasArg == api.optionalArgument then
if nextElm:sub(1, 1) == "-" then
return optParams.val or opt, nil
else
table.remove(toParse, 1)
return optParams.val or opt, nextElm
end
elseif optParams.hasArg == api.requiredArgument then
if nextElm:sub(1, 1) == "-" then
error(("Option '--%s' requires an argument"):format(opt), 0)
else
table.remove(toParse, 1)
return optParams.val or opt, nextElm
end
else
error(("Option Parameter 'hasArg' for '--%s' is invalid"):format(opt), 0)
end
end
else
if printErrors then
print(("Unknown option '--%s'"):format(opt), 8)
end
return "?", opt
end
else
if opt == "-" then
return api.notOpt
end
-- Short option
opt = opt:sub(2)
local char
char, opt = opt:match("^(.)(.*)")
table.insert(toParse, 1, "-" .. opt)
local optParams = shortOpts[char]
if optParams then
if optParams.hasArg == api.noArgument then
return char, nil
else
local nextElm = toParse[2]
if optParams.hasArg == api.optionalArgument then
if #opt == 0 then
if nextElm:sub(1, 1) == "-" then
return char, nil
else
table.remove(toParse, 2)
return char, nextElm
end
else
return char, nil
end
elseif optParams.hasArg == api.requiredArgument then
if #opt == 0 then
if nextElm:sub(1, 1) == "-" then
error(("Option '--%s' requires an argument"):format(opt), 0)
else
table.remove(toParse, 2)
return char, nextElm
end
else
local arg = opt
table.remove(toParse, 1)
return char, arg
end
else
error(("Option Parameter 'hasArg' for '--%s' is invalid"):format(opt), 0)
end
end
else
if printErrors then
print(("Unknown option '-%s'"):format(char), 8)
end
return "?", char
end
end
else
if parseMode == "+" then
return -1, opt
elseif parseMode == "-" then
return 1, opt
else
instance.notOptions[#instance.notOptions + 1] = opt
return api.notOpt
end
end
end
function instance.printHelp(usageStr)
local sections = {{
title = "Options"
}}
for i = 1, #config.sections do
sections[i + 1] = config.sections[i]
sections[i + 1].elements = {}
end
for k, v in pairs(shortOpts) do
end
if usageStr then
print(usageStr)
end
print(config.description)
end
setmetatable(instance, {
__call = function(self, switchTable)
local val, arg = 0
while #toParse > 0 and val ~= -1 do
val, arg = instance.evalNext()
if val ~= api.notOpt then
if switchTable[val] then
switchTable[val](arg)
elseif switchTable.default then
switchTable.default(val, arg)
end
end
end
for i = 1, #toParse do
instance.notOptions[#instance.notOptions + 1] = toParse[i]
end
return instance
end
})
return instance
end
setmetatable(api, {__call = function(self, ...) return api.getopt(...) end})
return api
|
Fix getopt parsemode
|
Fix getopt parsemode
|
Lua
|
mit
|
incinirate/Riko4,incinirate/Riko4,incinirate/Riko4
|
23ebe39031eff118b9748f096ea7d464d316731d
|
frontend/apps/cloudstorage/webdavapi.lua
|
frontend/apps/cloudstorage/webdavapi.lua
|
local DocumentRegistry = require("document/documentregistry")
local FFIUtil = require("ffi/util")
local http = require('socket.http')
local https = require('ssl.https')
local ltn12 = require('ltn12')
local mime = require('mime')
local socket = require('socket')
local url = require('socket.url')
local util = require("util")
local _ = require("gettext")
local WebDavApi = {
}
function WebDavApi:isCurrentDirectory( current_item, address, path )
local is_home, is_parent
local home_path
-- find first occurence of / after http(s)://
local start = string.find( address, "/", 9 )
if not start then
home_path = "/"
else
home_path = string.sub( address, start )
end
local item
if string.sub( current_item, -1 ) == "/" then
item = string.sub( current_item, 1, -2 )
else
item = current_item
end
if item == home_path then
is_home = true
else
local temp_path = string.sub( item, string.len(home_path) + 1 )
if temp_path == path then
is_parent = true
end
end
return is_home or is_parent
end
-- version of urlEncode that doesn't encode the /
function WebDavApi:urlEncode(url_data)
local char_to_hex = function(c)
return string.format("%%%02X", string.byte(c))
end
if url_data == nil then
return
end
url_data = url_data:gsub("([^%w%/%-%.%_%~%!%*%'%(%)])", char_to_hex)
return url_data
end
function WebDavApi:listFolder(address, user, pass, folder_path)
local path = self:urlEncode( folder_path )
local webdav_list = {}
local webdav_file = {}
local has_trailing_slash = false
local has_leading_slash = false
if string.sub( address, -1 ) ~= "/" then has_trailing_slash = true end
if path == nil or path == "/" then
path = ""
elseif string.sub( path, 1, 2 ) == "/" then
if has_trailing_slash then
-- too many slashes, remove one
path = string.sub( path, 1 )
end
has_leading_slash = true
end
if not has_trailing_slash and not has_leading_slash then
address = address .. "/"
end
local webdav_url = address .. path
local request, sink = {}, {}
local parsed = url.parse(webdav_url)
local data = [[<?xml version="1.0"?><a:propfind xmlns:a="DAV:"><a:prop><a:resourcetype/></a:prop></a:propfind>]]
local auth = string.format("%s:%s", user, pass)
local headers = { ["Authorization"] = "Basic " .. mime.b64( auth ),
["Content-Type"] = "application/xml",
["Depth"] = "1",
["Content-Length"] = #data}
request["url"] = webdav_url
request["method"] = "PROPFIND"
request["headers"] = headers
request["source"] = ltn12.source.string(data)
request["sink"] = ltn12.sink.table(sink)
http.TIMEOUT = 5
https.TIMEOUT = 5
local httpRequest = parsed.scheme == "http" and http.request or https.request
local headers_request = socket.skip(1, httpRequest(request))
if headers_request == nil then
return nil
end
local res_data = table.concat(sink)
if res_data ~= "" then
-- iterate through the <d:response> tags, each containing an entry
for item in res_data:gmatch("<d:response>(.-)</d:response>") do
--logger.dbg("WebDav catalog item=", item)
-- <d:href> is the path and filename of the entry.
local item_fullpath = item:match("<d:href>(.*)</d:href>")
if string.sub( item_fullpath, -1 ) == "/" then
item_fullpath = string.sub( item_fullpath, 1, -2 )
end
local is_current_dir = self:isCurrentDirectory( item_fullpath, address, path )
local item_name = util.urlDecode( FFIUtil.basename( item_fullpath ) )
local item_path = path .. "/" .. item_name
if item:find("<d:collection/>") then
item_name = item_name .. "/"
if not is_current_dir then
table.insert(webdav_list, {
text = item_name,
url = util.urlDecode( item_path ),
type = "folder",
})
end
elseif item:find("<d:resourcetype/>") and (DocumentRegistry:hasProvider(item_name)
or G_reader_settings:isTrue("show_unsupported")) then
table.insert(webdav_file, {
text = item_name,
url = util.urlDecode( item_path ),
type = "file",
})
end
end
else
return nil
end
--sort
table.sort(webdav_list, function(v1,v2)
return v1.text < v2.text
end)
table.sort(webdav_file, function(v1,v2)
return v1.text < v2.text
end)
for _, files in ipairs(webdav_file) do
table.insert(webdav_list, {
text = files.text,
url = files.url,
type = files.type,
})
end
return webdav_list
end
function WebDavApi:downloadFile(file_url, user, pass, local_path)
local parsed = url.parse(file_url)
local auth = string.format("%s:%s", user, pass)
local headers = { ["Authorization"] = "Basic " .. mime.b64( auth ) }
http.TIMEOUT = 5
https.TIMEOUT = 5
local httpRequest = parsed.scheme == "http" and http.request or https.request
local _, code_return, _ = httpRequest{
url = file_url,
method = "GET",
headers = headers,
sink = ltn12.sink.file(io.open(local_path, "w"))
}
return code_return
end
return WebDavApi
|
local DocumentRegistry = require("document/documentregistry")
local FFIUtil = require("ffi/util")
local http = require('socket.http')
local https = require('ssl.https')
local ltn12 = require('ltn12')
local mime = require('mime')
local socket = require('socket')
local url = require('socket.url')
local util = require("util")
local _ = require("gettext")
local WebDavApi = {
}
function WebDavApi:isCurrentDirectory( current_item, address, path )
local is_home, is_parent
local home_path
-- find first occurence of / after http(s)://
local start = string.find( address, "/", 9 )
if not start then
home_path = "/"
else
home_path = string.sub( address, start )
end
local item
if string.sub( current_item, -1 ) == "/" then
item = string.sub( current_item, 1, -2 )
else
item = current_item
end
if item == home_path then
is_home = true
else
local temp_path = string.sub( item, string.len(home_path) + 1 )
if temp_path == path then
is_parent = true
end
end
return is_home or is_parent
end
-- version of urlEncode that doesn't encode the /
function WebDavApi:urlEncode(url_data)
local char_to_hex = function(c)
return string.format("%%%02X", string.byte(c))
end
if url_data == nil then
return
end
url_data = url_data:gsub("([^%w%/%-%.%_%~%!%*%'%(%)])", char_to_hex)
return url_data
end
function WebDavApi:listFolder(address, user, pass, folder_path)
local path = self:urlEncode( folder_path )
local webdav_list = {}
local webdav_file = {}
local has_trailing_slash = false
local has_leading_slash = false
if string.sub( address, -1 ) == "/" then has_trailing_slash = true end
if path == nil or path == "/" then
path = ""
elseif string.sub( path, 1, 2 ) == "/" then
if has_trailing_slash then
-- too many slashes, remove one
path = string.sub( path, 1 )
end
has_leading_slash = true
end
if not has_trailing_slash and not has_leading_slash then
address = address .. "/"
end
local webdav_url = address .. path
if not has_trailing_slash then
webdav_url = webdav_url .. "/"
end
local request, sink = {}, {}
local parsed = url.parse(webdav_url)
local data = [[<?xml version="1.0"?><a:propfind xmlns:a="DAV:"><a:prop><a:resourcetype/></a:prop></a:propfind>]]
local auth = string.format("%s:%s", user, pass)
local headers = { ["Authorization"] = "Basic " .. mime.b64( auth ),
["Content-Type"] = "application/xml",
["Depth"] = "1",
["Content-Length"] = #data}
request["url"] = webdav_url
request["method"] = "PROPFIND"
request["headers"] = headers
request["source"] = ltn12.source.string(data)
request["sink"] = ltn12.sink.table(sink)
http.TIMEOUT = 5
https.TIMEOUT = 5
local httpRequest = parsed.scheme == "http" and http.request or https.request
local headers_request = socket.skip(1, httpRequest(request))
if headers_request == nil then
return nil
end
local res_data = table.concat(sink)
if res_data ~= "" then
-- iterate through the <d:response> tags, each containing an entry
for item in res_data:gmatch("<[^:]*:response[^>]*>(.-)</[^:]*:response>") do
--logger.dbg("WebDav catalog item=", item)
-- <d:href> is the path and filename of the entry.
local item_fullpath = item:match("<[^:]*:href[^>]*>(.*)</[^:]*:href>")
if string.sub( item_fullpath, -1 ) == "/" then
item_fullpath = string.sub( item_fullpath, 1, -2 )
end
local is_current_dir = self:isCurrentDirectory( item_fullpath, address, path )
local item_name = util.urlDecode( FFIUtil.basename( item_fullpath ) )
local item_path = path .. "/" .. item_name
if item:find("<[^:]*:collection/>") then
item_name = item_name .. "/"
if not is_current_dir then
table.insert(webdav_list, {
text = item_name,
url = util.urlDecode( item_path ),
type = "folder",
})
end
elseif item:find("<[^:]*:resourcetype/>") and (DocumentRegistry:hasProvider(item_name)
or G_reader_settings:isTrue("show_unsupported")) then
table.insert(webdav_file, {
text = item_name,
url = util.urlDecode( item_path ),
type = "file",
})
end
end
else
return nil
end
--sort
table.sort(webdav_list, function(v1,v2)
return v1.text < v2.text
end)
table.sort(webdav_file, function(v1,v2)
return v1.text < v2.text
end)
for _, files in ipairs(webdav_file) do
table.insert(webdav_list, {
text = files.text,
url = files.url,
type = files.type,
})
end
return webdav_list
end
function WebDavApi:downloadFile(file_url, user, pass, local_path)
local parsed = url.parse(file_url)
local auth = string.format("%s:%s", user, pass)
local headers = { ["Authorization"] = "Basic " .. mime.b64( auth ) }
http.TIMEOUT = 5
https.TIMEOUT = 5
local httpRequest = parsed.scheme == "http" and http.request or https.request
local _, code_return, _ = httpRequest{
url = file_url,
method = "GET",
headers = headers,
sink = ltn12.sink.file(io.open(local_path, "w"))
}
return code_return
end
return WebDavApi
|
Support for Apache WebDAV module (#6510)
|
Support for Apache WebDAV module (#6510)
This change to the parser in `cloudstorage.lua` adds support for the [Apache WebDAV module][1]
It was manually tested using the [bytemark/webdav][2] docker container.
I developed this in Windows, with a docker container that hosted an extracted AppImage and a VNC server that I viewed using a VNC client.
I will write up my work flow at a later point.
Changes have not been tested against other webdav servers (what was this originally tested against?). Please could someone test against other webdav servers?
I also noticed a logic inversion error where we were looking for a slash at the end of the URL and if it exists, then we explicitly set `has_trailing_slash=false` - so I fixed it to set to `true`. I had to do this so that we weren't visiting the URL without a trailing slash - apache sends back a 301 redirect with a `location` header with a trailing slash, if you don't put a trailing slash.
As a side note, I think we should consider replacing this regexp pattern matching parser with the [XML parser in the newsreader plugin[3]
[1]: https://httpd.apache.org/docs/2.4/mod/mod_dav.html
[2]: https://github.com/BytemarkHosting/docker-webdav
[3]: https://github.com/koreader/koreader/blob/master/plugins/newsdownloader.koplugin/lib/xml.lua
|
Lua
|
agpl-3.0
|
NiLuJe/koreader,Frenzie/koreader,Hzj-jie/koreader,poire-z/koreader,koreader/koreader,mwoz123/koreader,pazos/koreader,Markismus/koreader,NiLuJe/koreader,Frenzie/koreader,poire-z/koreader,koreader/koreader
|
bba336f827152b4499872ade61b335ba45ac3c63
|
feedback/topcrop.lua
|
feedback/topcrop.lua
|
------------------------------------------------------------------------
--[[ TopCrop ]]--
-- Feedback for use with ImageNet-like dataset.
------------------------------------------------------------------------
local TopCrop, parent = torch.class("dp.TopCrop", "dp.Feedback")
function TopCrop:__init(config)
config = config or {}
assert(torch.type(config) == 'table' and not config[1],
"Constructor requires key-value arguments")
local args, n_top, n_crop, center, name = xlua.unpack(
{config},
'TopCrop',
'Measures top-n classification accuracy for m-crops taken from '..
'the same image (which therefore have the same target class).',
{arg='n_top', type='number | table',
help='the accuracy is measured by looking for the target class'..
' in the n_top predictions with highest log-likelihood. '..
' Defaults to {1,5} ,i.e. top-1 and top-5'},
{arg='n_crop', type='number', default=10,
help='The number of crops taken from each sample. The assumption'..
' is that the input performs n_crop propagations of each image'..
' such that their predictions can be averaged'},
{arg='center', type='number', default=2,
help='The number of first crops to be considered center patches for '..
'which performance will also be reported separately. '..
'This means that you should put center crops first.'},
{arg='name', type='string', default='topcrop',
help='name identifying Feedback in reports'}
)
require 'torchx'
config.name = name
self._n_top = n_top or {1,5}
self._n_top = (torch.type(n_top) == 'number') and {self._n_top} or self._n_top
_.sort(self._n_top)
self._n_crop = n_crop
assert(center >= 1)
self._center = center
parent.__init(self, config)
self:reset()
end
function TopCrop:setup(config)
parent.setup(self, config)
self._mediator:subscribe("doneEpoch", self, "doneEpoch")
end
function TopCrop:doneEpoch(report)
if report.epoch > 0 then
local msg = self._id:toString().." accuracy top ("..table.concat(self._n_top,",")..") :"
local centerTops = {}
local allTops = {}
local nSample = self._n_sample / self._n_crop
for i,top in ipairs(self._n_top) do
table.insert(centerTops, string.format("%g", self.topCounts.center[top]/nSample*100))
table.insert(allTops, string.format("%g", self.topCounts.all[top]/nSample*100))
end
msg = msg .. "center ("..table.concat(centerTops, ",").."); "
msg = msg .. "all ("..table.concat(allTops,",")..")"
print(msg)
end
end
function TopCrop:topstats(preds, targets, ns)
-- sort each sample's prediction in descending order of activation
self._sorted = self._sorted or preds.new()
self._indices = self._indices or torch.LongTensor()
self._sorted:sort(self._indices, preds, 2, true)
local topClasses = self._indices:narrow(2,1,self._n_top[#self._n_top])
for i=1,preds:size(1) do
local p,g = topClasses[i], targets[i]
-- torch.find is from torchx (in case you are wondering)
local idx = torch.find(p,g)[1]
for top, count in pairs(self.topCounts[ns]) do
if idx and idx <= top then
self.topCounts[ns][top] = count + 1
end
end
end
end
function TopCrop:_add(batch, output, carry, report)
local preds = output:forward('bf', 'torch.FloatTensor')
local labels = batch:targets():forward('b')
assert(preds:isContiguous())
assert(labels:isContiguous())
if math.fmod(preds:size(1), self._n_crop) ~= 0 then
error("TopCrop: the number of samples should be a multiple of n_crop")
end
local predView = preds:view(preds:size(1)/self._n_crop, self._n_crop, preds:size(2))
local labelView = labels:view(labels:size(1)/self._n_crop, self._n_crop)
-- check that each images n_crops have the same label
self._labels = self._labels or torch.FloatTensor()
self._labels:resize(labelView:size()):copy(labelView)
self._labelStd = self._labelStd or torch.FloatTensor()
if self._labelStd:std(self._labels, 2):max() ~= 0 then
print(labelView)
error"TopCrop: The n_crops per image should all have the same target label"
end
local targets = labelView:select(2,1)
-- center(s)
local center = predView:narrow(2,1,self._center)
self._sum = self._sum or preds.new()
self._sum:sum(center, 2)
self:topstats(self._sum:select(2,1), targets, 'center')
-- all crops
self._sum:sum(predView, 2)
self:topstats(self._sum:select(2,1), targets, 'all')
end
function TopCrop:_reset()
self.topCounts = {all={}, center={}}
for j,top in ipairs(self._n_top) do
self.topCounts.all[top] = 0
self.topCounts.center[top] = 0
end
end
function TopCrop:report()
local centerTops = {}
local allTops = {}
local nSample = self._n_sample / self._n_crop
for i,top in ipairs(self._n_top) do
centerTops[top] = self.topCounts.center[top]/nSample*100
allTops[top] = self.topCounts.all[top]/nSample*100
end
return {
[self:name()] = {
center=centerTops, all=allTops, n_crop=self._n_crop
},
n_sample = nSample
}
end
|
------------------------------------------------------------------------
--[[ TopCrop ]]--
-- Feedback for use with ImageNet-like dataset.
------------------------------------------------------------------------
local TopCrop, parent = torch.class("dp.TopCrop", "dp.Feedback")
function TopCrop:__init(config)
config = config or {}
assert(torch.type(config) == 'table' and not config[1],
"Constructor requires key-value arguments")
local args, n_top, n_crop, center, name = xlua.unpack(
{config},
'TopCrop',
'Measures top-n classification accuracy for m-crops taken from '..
'the same image (which therefore have the same target class).',
{arg='n_top', type='number | table',
help='the accuracy is measured by looking for the target class'..
' in the n_top predictions with highest log-likelihood. '..
' Defaults to {1,5} ,i.e. top-1 and top-5'},
{arg='n_crop', type='number', default=10,
help='The number of crops taken from each sample. The assumption'..
' is that the input performs n_crop propagations of each image'..
' such that their predictions can be averaged'},
{arg='center', type='number', default=2,
help='The number of first crops to be considered center patches for '..
'which performance will also be reported separately. '..
'This means that you should put center crops first.'},
{arg='name', type='string', default='topcrop',
help='name identifying Feedback in reports'}
)
require 'torchx'
config.name = name
self._n_top = n_top or {1,5}
self._n_top = (torch.type(n_top) == 'number') and {self._n_top} or self._n_top
_.sort(self._n_top)
self._n_crop = n_crop
assert(center >= 1)
self._center = center
parent.__init(self, config)
self:reset()
end
function TopCrop:setup(config)
parent.setup(self, config)
self._mediator:subscribe("doneEpoch", self, "doneEpoch")
end
function TopCrop:doneEpoch(report)
if report.epoch > 0 then
local msg = self._id:toString().." accuracy top ("..table.concat(self._n_top,",")..") :"
local centerTops = {}
local allTops = {}
local nSample = self._n_sample / self._n_crop
for i,top in ipairs(self._n_top) do
table.insert(centerTops, string.format("%g", self.topCounts.center[top]/nSample*100))
table.insert(allTops, string.format("%g", self.topCounts.all[top]/nSample*100))
end
msg = msg .. "center ("..table.concat(centerTops, ",").."); "
msg = msg .. "all ("..table.concat(allTops,",")..")"
print(msg)
end
end
function TopCrop:topstats(preds, targets, ns)
-- sort each sample's prediction in descending order of activation
self._sorted = self._sorted or preds.new()
self._indices = self._indices or torch.LongTensor()
self._sorted:sort(self._indices, preds, 2, true)
local topClasses = self._indices:narrow(2,1,self._n_top[#self._n_top])
for i=1,preds:size(1) do
local p,g = topClasses[i], targets[i]
-- torch.find is from torchx (in case you are wondering)
local idx = torch.find(p,g)[1]
for top, count in pairs(self.topCounts[ns]) do
if idx and idx <= top then
self.topCounts[ns][top] = count + 1
end
end
end
end
function TopCrop:add(batch, output, carry, report)
local preds = output:forward('bf', 'torch.FloatTensor')
local labels = batch:targets():forward('b')
assert(preds:isContiguous())
assert(labels:isContiguous())
if math.fmod(preds:size(1), self._n_crop) ~= 0 then
error("TopCrop: the number of samples should be a multiple of n_crop")
end
local predView = preds:view(preds:size(1)/self._n_crop, self._n_crop, preds:size(2))
local labelView = labels:view(labels:size(1)/self._n_crop, self._n_crop)
self._n_sample = self._n_sample + predView:size(1)
-- check that each images n_crops have the same label
self._labels = self._labels or torch.FloatTensor()
self._labels:resize(labelView:size()):copy(labelView)
self._labelStd = self._labelStd or torch.FloatTensor()
if self._labelStd:std(self._labels, 2):max() ~= 0 then
print(labelView)
error"TopCrop: The n_crops per image should all have the same target label"
end
local targets = labelView:select(2,1)
-- center(s)
local center = predView:narrow(2,1,self._center)
self._sum = self._sum or preds.new()
self._sum:sum(center, 2)
self:topstats(self._sum:select(2,1), targets, 'center')
-- all crops
self._sum:sum(predView, 2)
self:topstats(self._sum:select(2,1), targets, 'all')
end
function TopCrop:_reset()
self.topCounts = {all={}, center={}}
for j,top in ipairs(self._n_top) do
self.topCounts.all[top] = 0
self.topCounts.center[top] = 0
end
end
function TopCrop:report()
local centerTops = {}
local allTops = {}
local nSample = self._n_sample / self._n_crop
for i,top in ipairs(self._n_top) do
centerTops[top] = self.topCounts.center[top]/nSample*100
allTops[top] = self.topCounts.all[top]/nSample*100
end
return {
[self:name()] = {
center=centerTops, all=allTops, n_crop=self._n_crop
},
n_sample = nSample
}
end
|
topcrop n_sample fix
|
topcrop n_sample fix
|
Lua
|
bsd-3-clause
|
fiskio/dp,jnhwkim/dp,rickyHong/dptorchLib,kracwarlock/dp,sagarwaghmare69/dp,nicholas-leonard/dp,eulerreich/dp
|
da3d385b6835ef75f774a47aee972e22dd653f98
|
src/cosy/email.lua
|
src/cosy/email.lua
|
local loader = require "cosy.loader"
local ssl = require "ssl"
local smtp = loader.hotswap "socket.smtp"
if _G.js then
error "Not available"
end
local Email = {}
-- First case: detection, using blocking sockets
-- Second case: email sending, using non-blocking sockets
local make_socket = {}
function make_socket.sync ()
local socket = loader.hotswap "socket"
local result = socket.tcp ()
result:settimeout (1)
result:setoption ("keepalive", true)
result:setoption ("reuseaddr", true)
result:setoption ("tcp-nodelay", true)
return result
end
function make_socket.async ()
local socket = loader.hotswap "cosy.platform.socket"
local result = socket ()
result:settimeout (0)
result:setoption ("keepalive", true)
result:setoption ("reuseaddr", true)
result:setoption ("tcp-nodelay", true)
return result
end
-- http://lua-users.org/wiki/StringRecipes
local email_pattern = "<[A-Za-z0-9%.%%%+%-]+@[A-Za-z0-9%.%%%+%-]+%.%w%w%w?%w?>"
local tls_alias = {
["TLS v1.2"] = "tlsv1_2",
["TLS v1.1"] = "tlsv1_1",
["TLS v1.0"] = "tlsv1",
["SSL v3" ] = "sslv3",
["SSL v2" ] = "sslv23",
}
-- http://stackoverflow.com/questions/11070623/lua-send-mail-with-gmail-account
local Tcp = {}
local function forward__index (self, key)
return getmetatable (self) [key]
or function (_, ...)
return self.socket [key] (self.socket, ...)
end
end
local function dohandshake (self)
while true do
local ok, err = self.socket:dohandshake ()
if ok then
return true
elseif err == "wantread"
or err == "wantwrite"
or err == "timeout" then
-- loop
else
error (err)
end
end
end
function Tcp.PLAINTEXT ()
return function (_, make)
return make ()
end
end
local TLS_mt = {
__index = forward__index,
dohandshake = dohandshake,
}
function TLS_mt:connect (host, port)
self.socket = self.make ()
if not self.socket:connect (host, port) then
return false
end
self.socket = ssl.wrap (self.socket, {
mode = "client",
protocol = tls_alias [self.protocol],
})
return self:dohandshake ()
end
function Tcp.TLS (protocol, make)
return function ()
return setmetatable ({
socket = make (),
protocol = protocol,
make = make,
}, TLS_mt)
end
end
local STARTTLS_mt = {
__index = forward__index,
dohandshake = dohandshake,
}
function STARTTLS_mt:connect (host, port)
self.socket = self.make ()
if not self.socket:connect (host, port) then
return false
end
self.socket:receive "*l"
self.socket:send ("EHLO cosy\r\n")
repeat
local line = self.socket:receive "*l"
until line == nil
self.socket:send "STARTTLS\r\n"
self.socket:receive "*l"
self.socket = ssl.wrap (self.socket, {
mode = "client",
protocol = tls_alias [self.protocol],
})
local result = self:dohandshake ()
self.socket:send ("EHLO cosy\r\n")
return result
end
function Tcp.STARTTLS (protocol, make)
return function ()
return setmetatable ({
socket = make (),
protocol = protocol,
make = make,
}, STARTTLS_mt)
end
end
function Email.discover ()
local logger = loader.logger
local configuration = loader.configuration
local domain = configuration.server.root._
local host = configuration.smtp.host._
local username = configuration.smtp.username._
local password = configuration.smtp.password._
local methods = { configuration.smtp.method._ }
if #methods == 0 then
methods = {
"STARTTLS",
"TLS",
"PLAINTEXT",
}
end
local protocols = { configuration.smtp.protocol._ }
if #protocols == 0 then
protocols = {
"TLS v1.2",
"TLS v1.1",
"TLS v1.0",
"SSL v3",
"SSL v2",
}
end
local ports = { configuration.smtp.port._ }
if #ports == 0 then
ports = {
25,
587,
465
}
end
for _, method in ipairs (methods) do
local protos = (method == "PLAIN") and { "nothing" } or protocols
for _, protocol in ipairs (protos) do
for _, port in ipairs (ports) do
logger.debug {
_ = "smtp:discover",
host = host,
port = port,
method = method,
protocol = protocol,
}
local ok, s = pcall (smtp.open, host, port, Tcp [method] (protocol, make_socket.sync))
if ok then
local ok = pcall (s.auth, s, username, password, s:greet (domain))
if ok then
configuration.smtp.port = port
configuration.smtp.method = method
configuration.smtp.protocol = protocol
return true
else
s:close ()
end
end
end
end
end
end
function Email.send (message)
local i18n = loader.i18n
local configuration = loader.configuration
local locale = message.locale or configuration.locale.default._
message.from .locale = locale
message.to .locale = locale
message.subject.locale = locale
message.body .locale = locale
-- FIXME: fix calls to i18n
message.from = i18n (message.from [1], message.from )
message.to = i18n (message.to [1], message.to )
message.subject = i18n (message.subject [1], message.subject)
message.body = i18n (message.body [1], message.body )
return smtp.send {
from = message.from:match (email_pattern),
rcpt = message.to :match (email_pattern),
source = smtp.message {
headers = {
from = message.from,
to = message.to,
subject = message.subject,
},
body = message.body
},
user = configuration.smtp.username._,
password = configuration.smtp.password._,
server = configuration.smtp.host._,
port = configuration.smtp.port._,
create = Tcp [configuration.smtp.method._]
(configuration.smtp.protocol._, make_socket.async),
}
end
do
local logger = loader.logger
local configuration = loader.configuration
if not Email.discover () then
logger.warning {
_ = "smtp:not-available",
}
else
logger.info {
_ = "smtp:available",
host = configuration.smtp.host._,
port = configuration.smtp.port._,
method = configuration.smtp.method._,
protocol = configuration.smtp.protocol._,
}
end
end
return Email
|
local loader = require "cosy.loader"
local ssl = require "ssl"
local smtp = loader.hotswap "socket.smtp"
if _G.js then
error "Not available"
end
local Email = {}
-- First case: detection, using blocking sockets
-- Second case: email sending, using non-blocking sockets
local make_socket = {}
function make_socket.sync ()
local socket = loader.hotswap "socket"
local result = socket.tcp ()
result:settimeout (loader.configuration.smtp.timeout._)
result:setoption ("keepalive", true)
result:setoption ("reuseaddr", true)
result:setoption ("tcp-nodelay", true)
return result
end
function make_socket.async ()
local result = loader.socket ()
result:settimeout (loader.configuration.smtp.timeout._)
result:setoption ("keepalive", true)
result:setoption ("reuseaddr", true)
result:setoption ("tcp-nodelay", true)
return result
end
-- http://lua-users.org/wiki/StringRecipes
local email_pattern = "<[A-Za-z0-9%.%%%+%-]+@[A-Za-z0-9%.%%%+%-]+%.%w%w%w?%w?>"
local tls_alias = {
["TLS v1.2"] = "tlsv1_2",
["TLS v1.1"] = "tlsv1_1",
["TLS v1.0"] = "tlsv1",
["SSL v3" ] = "sslv3",
["SSL v2" ] = "sslv23",
}
-- http://stackoverflow.com/questions/11070623/lua-send-mail-with-gmail-account
local Tcp = {}
local function forward__index (self, key)
return getmetatable (self) [key]
or function (_, ...)
return self.socket [key] (self.socket, ...)
end
end
function Tcp.PLAINTEXT ()
return function (_, make)
return make ()
end
end
local TLS_mt = {
__index = forward__index,
dohandshake = dohandshake,
}
function TLS_mt:connect (host, port)
self.socket = self.make ()
if not self.socket:connect (host, port) then
return false
end
self.socket = ssl.wrap (self.socket, {
mode = "client",
protocol = tls_alias [self.protocol],
})
return self.socket:dohandshake ()
end
function Tcp.TLS (protocol, make)
return function ()
return setmetatable ({
socket = make (),
protocol = protocol,
make = make,
}, TLS_mt)
end
end
local STARTTLS_mt = {
__index = forward__index,
dohandshake = dohandshake,
}
function STARTTLS_mt:connect (host, port)
self.socket = self.make ()
if not self.socket:connect (host, port) then
print "connection failed"
return nil, "connection failed"
end
self.socket:send ("EHLO cosy\r\n")
repeat
local line = self.socket:receive "*l"
until line == nil
self.socket:send "STARTTLS\r\n"
self.socket:receive "*l"
self.socket = ssl.wrap (self.socket, {
mode = "client",
protocol = tls_alias [self.protocol],
})
local result = self.socket:dohandshake ()
self.socket:send ("EHLO cosy\r\n")
return result
end
function Tcp.STARTTLS (protocol, make)
return function ()
return setmetatable ({
socket = make (),
protocol = protocol,
make = make,
}, STARTTLS_mt)
end
end
function Email.discover ()
local logger = loader.logger
local configuration = loader.configuration
local domain = configuration.server.root._
local host = configuration.smtp.host._
local username = configuration.smtp.username._
local password = configuration.smtp.password._
local methods = { configuration.smtp.method._ }
if #methods == 0 then
methods = {
"STARTTLS",
"TLS",
"PLAINTEXT",
}
end
local protocols = { configuration.smtp.protocol._ }
if #protocols == 0 then
protocols = {
"TLS v1.2",
"TLS v1.1",
"TLS v1.0",
"SSL v3",
"SSL v2",
}
end
local ports = { configuration.smtp.port._ }
if #ports == 0 then
ports = {
25,
587,
465
}
end
for _, method in ipairs (methods) do
local protos = (method == "PLAIN") and { "nothing" } or protocols
for _, protocol in ipairs (protos) do
for _, port in ipairs (ports) do
logger.debug {
_ = "smtp:discover",
host = host,
port = port,
method = method,
protocol = protocol,
}
local ok, s = pcall (smtp.open, host, port, Tcp [method] (protocol, make_socket.sync))
if ok then
local ok = pcall (s.auth, s, username, password, s:greet (domain))
if ok then
configuration.smtp.port = port
configuration.smtp.method = method
configuration.smtp.protocol = protocol
return true
else
s:close ()
end
end
end
end
end
end
function Email.send (message)
local i18n = loader.i18n
local configuration = loader.configuration
local locale = message.locale or configuration.locale.default._
message.from .locale = locale
message.to .locale = locale
message.subject.locale = locale
message.body .locale = locale
message.from = i18n (message.from )
message.to = i18n (message.to )
message.subject = i18n (message.subject)
message.body = i18n (message.body )
return smtp.send {
from = message.from:match (email_pattern),
rcpt = message.to :match (email_pattern),
source = smtp.message {
headers = {
from = message.from,
to = message.to,
subject = message.subject,
},
body = message.body
},
user = configuration.smtp.username._,
password = configuration.smtp.password._,
server = configuration.smtp.host._,
port = configuration.smtp.port._,
create = Tcp [configuration.smtp.method._]
(configuration.smtp.protocol._, make_socket.async),
}
end
do
local logger = loader.logger
local configuration = loader.configuration
if not Email.discover () then
logger.warning {
_ = "smtp:not-available",
}
else
logger.info {
_ = "smtp:available",
host = configuration.smtp.host._,
port = configuration.smtp.port._,
method = configuration.smtp.method._,
protocol = configuration.smtp.protocol._,
}
end
end
return Email
|
Fix things in email sending, but still buggy...
|
Fix things in email sending, but still buggy...
|
Lua
|
mit
|
CosyVerif/library,CosyVerif/library,CosyVerif/library
|
3a99429aa32eab7e3335873c664e02e57c8380b3
|
agents/monitoring/tests/schedule/init.lua
|
agents/monitoring/tests/schedule/init.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 path = require('path')
local async = require('async')
local utils = require('utils')
local timer = require('timer')
local StateScanner = require('monitoring/lib/schedule').StateScanner
local Scheduler = require('monitoring/lib/schedule').Scheduler
local BaseCheck = require('monitoring/lib/check/base').BaseCheck
local tmp = path.join('tests', 'tmp')
local exports = {}
local checks = {
BaseCheck:new({id='ch0001', state='OK', period=30, path=path.join(tmp, '0001.chk')}),
BaseCheck:new({id='ch0002', state='OK', period=35, path=path.join(tmp, '0002.chk')}),
BaseCheck:new({id='ch0003', state='OK', period=40, path=path.join(tmp, '0003.chk')}),
BaseCheck:new({id='ch0004', state='OK', period=45, path=path.join(tmp, '0004.chk')}),
}
exports['test_scheduler_scan'] = function(test, asserts)
local s = StateScanner:new(process.cwd()..'/agents/monitoring/tests/data/sample.state')
local count = 0
s:on('check_scheduled', function(details)
count = count + 1
if count >= 3 then
test.done()
end
end)
s:scanStates()
end
exports['test_scheduler_initialize'] = function(test, asserts)
local testFile = path.join(tmp, 'test_scheduler_initialize.state')
async.waterfall({
-- write a scan file. the scheduler does this.
function(callback)
Scheduler:new(testFile, checks, callback)
end,
-- load with scanner.
function(callback)
local count = 0
local s = StateScanner:new(testFile)
s:on('check_scheduled', function(details)
count = count + 1
if count >= #checks then
callback()
end
end)
s:scanStates()
end
}, function(err)
asserts.ok(err == nil)
test.done()
end)
end
exports['test_scheduler_scans'] = function(test, asserts)
local testFile = path.join(tmp, 'test_scheduler_initialize.state')
local scheduler
async.waterfall({
function(callback)
scheduler = Scheduler:new(testFile, checks, callback)
end,
function(callback)
scheduler:start()
local timeout = timer.setTimeout(5000, function()
-- they all should have run.
asserts.equals(scheduler._runCount, #checks)
callback()
end)
end
}, function(err)
asserts.ok(err == nil)
test.done()
end)
end
exports['test_scheduler_adds'] = function(test, asserts)
local testFile = path.join(tmp, 'test_scheduler_adds.state')
local scheduler
local checks2 = {
BaseCheck:new({id='ch0001', state='OK', period=1, path=path.join(tmp, '0001.chk')}),
}
local checks3 = {
BaseCheck:new({id='ch0001', state='OK', period=1, path=path.join(tmp, '0001.chk')}),
BaseCheck:new({id='ch0002', state='OK', period=1, path=path.join(tmp, '0002.chk')}),
}
local checks4 = {
BaseCheck:new({id='ch0002', state='OK', period=1, path=path.join(tmp, '0002.chk')}),
}
async.waterfall({
function(callback)
scheduler = Scheduler:new(testFile, checks2, callback)
end,
function(callback)
scheduler:rebuild(checks3, callback);
end,
function(callback)
scheduler:start()
local timeout = timer.setTimeout(5000, function()
-- they all should have run.
asserts.equals(scheduler._runCount, 10)
print('rebuild');
scheduler:rebuild(checks4, callback);
end)
end,
function(callback)
scheduler:start()
local timeout = timer.setTimeout(5000, function()
-- they all should have run.
asserts.ok(scheduler._runCount > 15)
asserts.ok(scheduler._runCount < 18)
callback()
end)
end
}, function(err)
asserts.ok(err == nil)
test.done()
end)
end
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 path = require('path')
local async = require('async')
local utils = require('utils')
local timer = require('timer')
local StateScanner = require('monitoring/lib/schedule').StateScanner
local Scheduler = require('monitoring/lib/schedule').Scheduler
local BaseCheck = require('monitoring/lib/check/base').BaseCheck
local tmp = path.join('tests', 'tmp')
local exports = {}
local checks = {
BaseCheck:new({id='ch0001', state='OK', period=30, path=path.join(tmp, '0001.chk')}),
BaseCheck:new({id='ch0002', state='OK', period=35, path=path.join(tmp, '0002.chk')}),
BaseCheck:new({id='ch0003', state='OK', period=40, path=path.join(tmp, '0003.chk')}),
BaseCheck:new({id='ch0004', state='OK', period=45, path=path.join(tmp, '0004.chk')}),
}
exports['test_scheduler_scan'] = function(test, asserts)
local s = StateScanner:new(process.cwd()..'/agents/monitoring/tests/data/sample.state')
local count = 0
s:on('check_scheduled', function(details)
count = count + 1
if count >= 3 then
test.done()
end
end)
s:scanStates()
end
exports['test_scheduler_initialize'] = function(test, asserts)
local testFile = path.join(tmp, 'test_scheduler_initialize.state')
async.waterfall({
-- write a scan file. the scheduler does this.
function(callback)
Scheduler:new(testFile, checks, callback)
end,
-- load with scanner.
function(callback)
local count = 0
local s = StateScanner:new(testFile)
s:on('check_scheduled', function(details)
count = count + 1
if count >= #checks then
callback()
end
end)
s:scanStates()
end
}, function(err)
asserts.ok(err == nil)
test.done()
end)
end
exports['test_scheduler_scans'] = function(test, asserts)
local testFile = path.join(tmp, 'test_scheduler_scans.state')
local scheduler
async.waterfall({
function(callback)
scheduler = Scheduler:new(testFile, checks, callback)
end,
function(callback)
scheduler:start()
local timeout = timer.setTimeout(5000, function()
-- they all should have run.
asserts.equals(scheduler._runCount, #checks)
callback()
end)
end
}, function(err)
asserts.ok(err == nil)
test.done()
end)
end
exports['test_scheduler_adds'] = function(test, asserts)
local testFile = path.join(tmp, 'test_scheduler_adds.state')
local scheduler
local checks2 = {
BaseCheck:new({id='ch0001', state='OK', period=1, path=path.join(tmp, '0001.chk')}),
}
local checks3 = {
BaseCheck:new({id='ch0001', state='OK', period=1, path=path.join(tmp, '0001.chk')}),
BaseCheck:new({id='ch0002', state='OK', period=1, path=path.join(tmp, '0002.chk')}),
}
local checks4 = {
BaseCheck:new({id='ch0002', state='OK', period=1, path=path.join(tmp, '0002.chk')}),
}
async.waterfall({
function(callback)
scheduler = Scheduler:new(testFile, checks2, callback)
end,
function(callback)
scheduler:rebuild(checks3, callback);
end,
function(callback)
scheduler:start()
local timeout = timer.setTimeout(5000, function()
-- they all should have run.
asserts.equals(scheduler._runCount, 10)
print('rebuild');
scheduler:rebuild(checks4, callback);
end)
end,
function(callback)
scheduler:start()
local timeout = timer.setTimeout(5000, function()
-- tests are a bit dicey at this point depending on exactly where in the clock we are..
asserts.ok(scheduler._runCount >= 15)
asserts.ok(scheduler._runCount <= 18)
callback()
end)
end
}, function(err)
asserts.ok(err == nil)
test.done()
end)
end
return exports
|
fix race condition in test, improve general test stability
|
fix race condition in test, improve general test stability
|
Lua
|
apache-2.0
|
cp16net/virgo-base,cp16net/virgo-base,christopherjwang/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,cp16net/virgo-base,cp16net/virgo-base,virgo-agent-toolkit/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,cp16net/virgo-base
|
7630e9cd9d74d9969e0138b8ba11ec6ca78648eb
|
app/lua/main.lua
|
app/lua/main.lua
|
--local rx = require('rx')
--local u = require('tableutil')
--editor bootstrap
local windowWidth = MOAIEnvironment.horizontalResolution or 300
local windowHeight = MOAIEnvironment.verticalResolution or 300
MOAISim.openWindow ( "test", windowWidth, windowHeight ) --needed but doesn't do anything now
local Editor = require('editor')
local Scene = require('scene')
local scene = Scene.create()
-- one main gui viewport
function refreshViewport()
print("resizing", MOAIEnvironment.verticalResolution, MOAIEnvironment.horizontalResolution)
Editor:resize(windowWidth, windowHeight)
end
refreshViewport()
MOAIRenderMgr.setRenderTable({
scene.layers,
Editor.layer
})
local gfxQuad = MOAIGfxQuad2D.new ()
gfxQuad:setTexture ( "moai.png" )
gfxQuad:setRect ( -64, -64, 64, 64 )
gfxQuad.name = "TestQuad"
scene:addDeck(gfxQuad)
local sceneViewport = MOAIViewport.new()
sceneViewport:setSize (windowWidth, windowHeight )
sceneViewport:setScale ( windowWidth , windowHeight)
scene:addViewport(sceneViewport)
local layer = MOAILayer2D.new ()
layer.name = "Main"
layer:setViewport ( sceneViewport )
layer:setCamera( Editor.camera )
scene:addLayer(layer)
local prop = MOAIProp2D.new ()
prop:setDeck ( gfxQuad )
prop.name = "prop1"
prop.parent = layer
layer:insertProp ( prop )
scene:addProp(prop)
rx = require('rx')
--rx setup
local Scheduler = rx.CooperativeScheduler.create(0)
local schedulerThread = MOAICoroutine:new()
local lastStep = MOAISim:getElapsedTime()
schedulerThread:run(function()
local now = MOAISim:getElapsedTime()
local delta = now - lastStep
Scheduler:update(delta)
end)
LeftMouse = rx.Subject.create()
function onMouseLeftEvent ( down )
local x, y = MOAIInputMgr.device.pointer:getLoc()
LeftMouse:onNext( down, x, y )
end
MOAIInputMgr.device.mouseLeft:setCallback ( onMouseLeftEvent )
RightMouse = rx.Subject.create()
function onMouseRightEvent ( down )
local x, y = MOAIInputMgr.device.pointer:getLoc()
RightMouse:onNext( down, x, y )
end
MOAIInputMgr.device.mouseRight:setCallback ( onMouseRightEvent )
RightMouse:subscribe(function(down,x,y)
print("right mouse",down,x,y)
end)
MousePos = rx.Subject.create()
function onMouseMoveEvent( x, y )
MousePos:onNext( x, y )
end
MOAIInputMgr.device.pointer:setCallback( onMouseMoveEvent )
LeftMouseDown = LeftMouse:filter(function(down) return down end)
LeftMouseUp = LeftMouse:filter(function(down) return not down end)
RightMouseDown = RightMouse:filter(function(down) return down end)
RightMouseUp = RightMouse:filter(function(up) return not down end)
MouseDeltas = MousePos:pack():skip(1):zip(MousePos:pack()):map(function(newpos, oldpos) return newpos[1] - oldpos[1], newpos[2] - oldpos[2] end)
local RightMouseDrag = RightMouseDown:flatMap(function() return MouseDeltas:takeUntil(RightMouseUp) end)
RightMouseDrag:subscribe(function(dx,dy)
Editor:panView(dx,dy)
end)
local function checkKey ( key )
return MOAIInputMgr.device.keyboard:keyIsDown( key )
end
MOAIInputMgr.device.keyboard:setKeyCallback(function(keycode,down) print("keycall",keycode,down) end)
local PropClick = LeftMouseDown:map(function(down, x, y)
return scene:propForPoint(x,y)
end):compact()
local Drags = LeftMouseDown:flatMap(function() return MouseDeltas:takeUntil(LeftMouseUp) end)
PropClick:subscribe(function(prop, layer)
print("gotpropclick", prop, layer)
print("prop",scene:resolveName(prop))
print("layer",scene:resolveName(layer))
print("selected",scene:resolveName(prop),scene:resolveName(layer))
Editor:select(prop, layer)
prop:moveRot(45,3)
prop:moveScl(0.5,0.5,3)
end,
function(err)
print("error in propclick",err)
end
)
print("hello from editor")
|
--local rx = require('rx')
--local u = require('tableutil')
--editor bootstrap
local windowWidth = MOAIEnvironment.horizontalResolution or 300
local windowHeight = MOAIEnvironment.verticalResolution or 300
MOAISim.openWindow ( "test", windowWidth, windowHeight ) --needed but doesn't do anything now
local Editor = require('editor')
local Scene = require('scene')
local scene = Scene.create()
-- one main gui viewport
function refreshViewport()
print("resizing",MOAIEnvironment.verticalResolution, MOAIEnvironment.horizontalResolution )
Editor:resize(MOAIEnvironment.horizontalResolution, MOAIEnvironment.verticalResolution)
end
refreshViewport()
MOAIRenderMgr.setRenderTable({
scene.layers,
Editor.layer
})
local gfxQuad = MOAIGfxQuad2D.new ()
gfxQuad:setTexture ( "moai.png" )
gfxQuad:setRect ( -64, -64, 64, 64 )
gfxQuad.name = "TestQuad"
scene:addDeck(gfxQuad)
local sceneViewport = MOAIViewport.new()
sceneViewport:setSize (windowWidth, windowHeight )
sceneViewport:setScale ( windowWidth , windowHeight)
scene:addViewport(sceneViewport)
local layer = MOAILayer2D.new ()
layer.name = "Main"
layer:setViewport ( sceneViewport )
layer:setCamera( Editor.camera )
scene:addLayer(layer)
local prop = MOAIProp2D.new ()
prop:setDeck ( gfxQuad )
prop.name = "prop1"
prop.parent = layer
layer:insertProp ( prop )
scene:addProp(prop)
rx = require('rx')
--rx setup
local Scheduler = rx.CooperativeScheduler.create(0)
local schedulerThread = MOAICoroutine:new()
local lastStep = MOAISim:getElapsedTime()
schedulerThread:run(function()
local now = MOAISim:getElapsedTime()
local delta = now - lastStep
Scheduler:update(delta)
end)
LeftMouse = rx.Subject.create()
function onMouseLeftEvent ( down )
local x, y = MOAIInputMgr.device.pointer:getLoc()
LeftMouse:onNext( down, x, y )
end
MOAIInputMgr.device.mouseLeft:setCallback ( onMouseLeftEvent )
RightMouse = rx.Subject.create()
function onMouseRightEvent ( down )
local x, y = MOAIInputMgr.device.pointer:getLoc()
RightMouse:onNext( down, x, y )
end
MOAIInputMgr.device.mouseRight:setCallback ( onMouseRightEvent )
RightMouse:subscribe(function(down,x,y)
print("right mouse",down,x,y)
end)
MousePos = rx.Subject.create()
function onMouseMoveEvent( x, y )
MousePos:onNext( x, y )
end
MOAIInputMgr.device.pointer:setCallback( onMouseMoveEvent )
LeftMouseDown = LeftMouse:filter(function(down) return down end)
LeftMouseUp = LeftMouse:filter(function(down) return not down end)
RightMouseDown = RightMouse:filter(function(down) return down end)
RightMouseUp = RightMouse:filter(function(up) return not down end)
MouseDeltas = MousePos:pack():skip(1):zip(MousePos:pack()):map(function(newpos, oldpos) return newpos[1] - oldpos[1], newpos[2] - oldpos[2] end)
local RightMouseDrag = RightMouseDown:flatMap(function() return MouseDeltas:takeUntil(RightMouseUp) end)
RightMouseDrag:subscribe(function(dx,dy)
Editor:panView(dx,dy)
end)
local function checkKey ( key )
return MOAIInputMgr.device.keyboard:keyIsDown( key )
end
MOAIInputMgr.device.keyboard:setKeyCallback(function(keycode,down) print("keycall",keycode,down) end)
local PropClick = LeftMouseDown:map(function(down, x, y)
return scene:propForPoint(x,y)
end):compact()
local Drags = LeftMouseDown:flatMap(function() return MouseDeltas:takeUntil(LeftMouseUp) end)
PropClick:subscribe(function(prop, layer)
print("gotpropclick", prop, layer)
print("prop",scene:resolveName(prop))
print("layer",scene:resolveName(layer))
print("selected",scene:resolveName(prop),scene:resolveName(layer))
Editor:select(prop, layer)
prop:moveRot(45,3)
prop:moveScl(0.5,0.5,3)
end,
function(err)
print("error in propclick",err)
end
)
print("hello from editor")
|
fix some resize issues, prop still clips
|
fix some resize issues, prop still clips
|
Lua
|
mit
|
halfnelson/moaiscene,halfnelson/moaiscene,halfnelson/moaiscene
|
f078bcbe32243691eb2de74591fe7b31e4f08f95
|
src/lib/yang/state.lua
|
src/lib/yang/state.lua
|
-- Use of this source code is governed by the Apache 2.0 license; see COPYING.
module(..., package.seeall)
local lib = require("core.lib")
local shm = require("core.shm")
local xpath = require("lib.yang.path")
local yang = require("lib.yang.yang")
local yang_data = require("lib.yang.data")
local counter = require("core.counter")
local counter_directory = "/apps"
local function flatten(val)
local rtn = {}
for k, v in pairs(val) do
if type(v) == "table" then
v = flatten(v)
for k1, v1 in pairs(v) do rtn[k1] = v1 end
else
rtn[k] = v
end
end
return rtn
end
local function find_counters(pid)
local path = shm.root.."/"..pid..counter_directory
local counters = {}
for _, c in pairs(lib.files_in_directory(path)) do
local counterdir = "/"..pid..counter_directory.."/"..c
counters[c] = shm.open_frame(counterdir)
end
return counters
end
function collect_state_leaves(schema)
-- Iterate over schema looking fo state leaves at a specific path into the
-- schema. This should return a dictionary of leaf to lua path.
local function collection(scm, path)
local function newpath(oldpath)
return lib.deepcopy(oldpath)
end
if path == nil then path = {} end
table.insert(path, scm.id)
if scm.kind == "container" then
-- Iterate over the body and recursively call self on all children.
local rtn = {}
for _, child in pairs(scm.body) do
local leaves = collection(child, newpath(path))
table.insert(rtn, leaves)
end
return rtn
elseif scm.kind == "leaf" then
if scm.config == false then
local rtn = {}
rtn[path] = scm.id
return rtn
end
elseif scm.kind == "module" then
local rtn = {}
for _, v in pairs(scm.body) do
-- We deliberately don't want to include the module in the path.
table.insert(rtn, collection(v, {}))
end
return rtn
end
return {}
end
local leaves = collection(schema)
if leaves == nil then return {} end
leaves = flatten(leaves)
return function () return leaves end
end
local function set_data_value(data, path, value)
local head = yang_data.normalize_id(table.remove(path, 1))
if #path == 0 then
data[head] = value
return
end
if data[head] == nil then data[head] = {} end
set_data_value(data[head], path, value)
end
function show_state(scm, pid, raw_path)
local schema = yang.load_schema_by_name(scm)
local grammar = yang_data.data_grammar_from_schema(schema)
local counters = find_counters(pid)
local path = xpath.convert_path(grammar, raw_path)
-- Lookup the specific schema element that's being addressed by the path
local leaves = collect_state_leaves(schema)()
local data = {}
for leaf_path, leaf in pairs(leaves) do
for _, counter in pairs(counters) do
if counter[leaf] then
set_data_value(data, leaf_path, counter[leaf])
end
end
end
return data
end
function selftest ()
print("selftest: lib.yang.state")
local simple_router_schema_src = [[module snabb-simple-router {
namespace snabb:simple-router;
prefix simple-router;
import ietf-inet-types {prefix inet;}
leaf active { type boolean; default true; }
leaf-list blocked-ips { type inet:ipv4-address; }
container routes {
presence true;
list route {
key addr;
leaf addr { type inet:ipv4-address; mandatory true; }
leaf port { type uint8 { range 0..11; } mandatory true; }
}
}
container state {
presence true;
config false;
leaf total-packets {
type uint64 {
default 0;
}
}
leaf dropped-packets {
type uint64 {
default 0;
}
}
}
grouping detailed-counters {
leaf dropped-wrong-route {
type uint64 { default 0; }
}
leaf dropped-not-permitted {
type uint64 { default 0; }
}
}
container detailed-state {
presence true;
config false;
uses "detailed-counters";
}
}]]
local function table_length(tbl)
local rtn = 0
for k,v in pairs(tbl) do rtn = rtn + 1 end
return rtn
end
local function in_array(needle, haystack)
for _, i in pairs(haystack) do if needle == i then return true end end
return false
end
local simple_router_schema = yang.load_schema(simple_router_schema_src,
"state-test")
local leaves = collect_state_leaves(simple_router_schema)()
-- Check the correct number of leaves have been found
assert(table_length(leaves) == 4)
-- Check it's found every state path.
local state_leaves = {
"total-packets",
"dropped-packets",
"dropped-wrong-route",
"dropped-not-permitted"
}
for _, leaf in pairs(leaves) do
assert(in_array(leaf, state_leaves))
end
-- Check flatten produces a single dimentional table with all the elements.
local multi_dimentional = {{hello="hello"}, {world="world"}}
assert(flatten(multi_dimentional), {hello="hello", world="world"})
print("selftest: ok")
end
|
-- Use of this source code is governed by the Apache 2.0 license; see COPYING.
module(..., package.seeall)
local lib = require("core.lib")
local shm = require("core.shm")
local xpath = require("lib.yang.path")
local yang = require("lib.yang.yang")
local yang_data = require("lib.yang.data")
local counter = require("core.counter")
local counter_directory = "/apps"
local function flatten(val)
local rtn = {}
for k, v in pairs(val) do
if type(v) == "table" then
v = flatten(v)
for k1, v1 in pairs(v) do rtn[k1] = v1 end
else
rtn[k] = v
end
end
return rtn
end
function find_counters(pid)
local path = shm.root.."/"..pid..counter_directory
local apps = {}
for _, c in pairs(lib.files_in_directory(path)) do
local counters = {}
local counterdir = "/"..pid..counter_directory.."/"..c
for k,v in pairs(shm.open_frame(counterdir)) do
if type(v) == "cdata" then
counters[k] = v.c
end
end
apps[c] = counters
end
return apps
end
function collect_state_leaves(schema)
-- Iterate over schema looking fo state leaves at a specific path into the
-- schema. This should return a dictionary of leaf to lua path.
local function collection(scm, path)
local function newpath(oldpath)
return lib.deepcopy(oldpath)
end
if path == nil then path = {} end
table.insert(path, scm.id)
if scm.kind == "container" then
-- Iterate over the body and recursively call self on all children.
local rtn = {}
for _, child in pairs(scm.body) do
local leaves = collection(child, newpath(path))
table.insert(rtn, leaves)
end
return rtn
elseif scm.kind == "leaf" then
if scm.config == false then
local rtn = {}
rtn[path] = scm.id
return rtn
end
elseif scm.kind == "module" then
local rtn = {}
for _, v in pairs(scm.body) do
-- We deliberately don't want to include the module in the path.
table.insert(rtn, collection(v, {}))
end
return rtn
end
return {}
end
local leaves = collection(schema)
if leaves == nil then return {} end
leaves = flatten(leaves)
return function () return leaves end
end
local function set_data_value(data, path, value)
local head = yang_data.normalize_id(table.remove(path, 1))
if #path == 0 then
data[head] = value
return
end
if data[head] == nil then data[head] = {} end
set_data_value(data[head], path, value)
end
function show_state(scm, pid, raw_path)
local schema = yang.load_schema_by_name(scm)
local grammar = yang_data.data_grammar_from_schema(schema)
local counters = find_counters(pid)
local path = xpath.convert_path(grammar, raw_path)
-- Lookup the specific schema element that's being addressed by the path
local leaves = collect_state_leaves(schema)()
local data = {}
for leaf_path, leaf in pairs(leaves) do
for _, counter in pairs(counters) do
if counter[leaf] then
set_data_value(data, leaf_path, counter[leaf])
end
end
end
return data
end
function selftest ()
print("selftest: lib.yang.state")
local simple_router_schema_src = [[module snabb-simple-router {
namespace snabb:simple-router;
prefix simple-router;
import ietf-inet-types {prefix inet;}
leaf active { type boolean; default true; }
leaf-list blocked-ips { type inet:ipv4-address; }
container routes {
presence true;
list route {
key addr;
leaf addr { type inet:ipv4-address; mandatory true; }
leaf port { type uint8 { range 0..11; } mandatory true; }
}
}
container state {
presence true;
config false;
leaf total-packets {
type uint64 {
default 0;
}
}
leaf dropped-packets {
type uint64 {
default 0;
}
}
}
grouping detailed-counters {
leaf dropped-wrong-route {
type uint64 { default 0; }
}
leaf dropped-not-permitted {
type uint64 { default 0; }
}
}
container detailed-state {
presence true;
config false;
uses "detailed-counters";
}
}]]
local function table_length(tbl)
local rtn = 0
for k,v in pairs(tbl) do rtn = rtn + 1 end
return rtn
end
local function in_array(needle, haystack)
for _, i in pairs(haystack) do if needle == i then return true end end
return false
end
local simple_router_schema = yang.load_schema(simple_router_schema_src,
"state-test")
local leaves = collect_state_leaves(simple_router_schema)()
-- Check the correct number of leaves have been found
assert(table_length(leaves) == 4)
-- Check it's found every state path.
local state_leaves = {
"total-packets",
"dropped-packets",
"dropped-wrong-route",
"dropped-not-permitted"
}
for _, leaf in pairs(leaves) do
assert(in_array(leaf, state_leaves))
end
-- Check flatten produces a single dimentional table with all the elements.
local multi_dimentional = {{hello="hello"}, {world="world"}}
assert(flatten(multi_dimentional), {hello="hello", world="world"})
print("selftest: ok")
end
|
Fix problem in get-state causing number formatting issues
|
Fix problem in get-state causing number formatting issues
There was a problem where the numbers where formatted with commas in to
denote groups of three numbers. This was caused by the counters being
wrapped in the core.counters_h struct. This fixe ensures they're unwrapped
uint64 values.
|
Lua
|
apache-2.0
|
Igalia/snabbswitch,dpino/snabb,alexandergall/snabbswitch,dpino/snabb,eugeneia/snabb,Igalia/snabb,snabbco/snabb,snabbco/snabb,heryii/snabb,eugeneia/snabb,eugeneia/snabb,eugeneia/snabb,snabbco/snabb,SnabbCo/snabbswitch,eugeneia/snabb,snabbco/snabb,alexandergall/snabbswitch,dpino/snabb,heryii/snabb,eugeneia/snabb,snabbco/snabb,heryii/snabb,Igalia/snabbswitch,eugeneia/snabbswitch,alexandergall/snabbswitch,dpino/snabbswitch,dpino/snabb,dpino/snabb,alexandergall/snabbswitch,alexandergall/snabbswitch,Igalia/snabb,Igalia/snabb,SnabbCo/snabbswitch,snabbco/snabb,alexandergall/snabbswitch,heryii/snabb,snabbco/snabb,heryii/snabb,Igalia/snabb,Igalia/snabb,Igalia/snabbswitch,Igalia/snabb,eugeneia/snabbswitch,dpino/snabbswitch,eugeneia/snabbswitch,dpino/snabb,Igalia/snabb,eugeneia/snabbswitch,dpino/snabbswitch,eugeneia/snabb,dpino/snabbswitch,Igalia/snabb,Igalia/snabbswitch,eugeneia/snabb,Igalia/snabbswitch,snabbco/snabb,dpino/snabb,heryii/snabb,alexandergall/snabbswitch,SnabbCo/snabbswitch,SnabbCo/snabbswitch,alexandergall/snabbswitch
|
7849eaf80f2c99bba3f69f952baf9713bade28d6
|
build/scripts/actions/package.lua
|
build/scripts/actions/package.lua
|
newoption({
trigger = "pack-libdir",
description = "Specifiy the subdirectory in lib/ to be used when packaging the project"
})
ACTION.Name = "Package"
ACTION.Description = "Pack Nazara binaries/include/lib together"
ACTION.Function = function ()
local libDir = _OPTIONS["pack-libdir"]
if (not libDir or #libDir == 0) then
local libDirs = os.matchdirs("../lib/*")
if (#libDirs > 1) then
error("More than one subdirectory was found in the lib directory, please use the --pack-libdir command to clarify which directory should be used")
elseif (#libDirs == 0) then
error("No subdirectory was found in the lib directory, have you built the engine yet?")
else
libDir = libDirs[1] .. "/"
print("No directory was set by the --pack-libdir command, \"" .. libDir .. "\" will be used")
end
else
libDir = "../lib/" .. libDir .. "/"
end
if (not os.isdir(libDir)) then
error(string.format("\"%s\" doesn't seem to be an existing directory", libDir))
end
local packageDir = "../package/"
local copyTargets = {
{ -- Engine headers
Masks = {"**.hpp", "**.inl"},
Source = "../include/",
Target = "include/"
},
{ -- SDK headers
Masks = {"**.hpp", "**.inl"},
Source = "../SDK/include/",
Target = "include/"
},
{ -- Examples files
Masks = {"**.hpp", "**.inl", "**.cpp"},
Source = "../examples/",
Target = "examples/"
},
{ -- Demo resources
Masks = {"**.*"},
Source = "../examples/bin/resources/",
Target = "examples/bin/resources/"
},
-- Unit test sources
{
Masks = {"**.hpp", "**.inl", "**.cpp"},
Source = "../tests/",
Target = "tests/src/"
},
-- Unit test resources
{
Masks = {"**.*"},
Source = "../tests/resources/",
Target = "tests/resources/"
}
}
if (os.is("windows")) then
-- Engine/SDK binaries
table.insert(copyTargets, {
Masks = {"**.dll"},
Source = libDir,
Target = "bin/"
})
-- Engine/SDK libraries
table.insert(copyTargets, {
Masks = {"**.lib"},
Source = libDir,
Target = "lib/"
})
-- 3rd party binary dep
table.insert(copyTargets, {
Masks = {"**.dll"},
Source = "../extlibs/lib/common/",
Target = "bin/"
})
-- Demo executable (Windows)
table.insert(copyTargets, {
Masks = {"Demo*.exe"},
Source = "../examples/bin/",
Target = "examples/bin/"
})
-- Unit test (Windows)
table.insert(copyTargets, {
Masks = {"*.exe"},
Source = "../tests/",
Target = "tests/"
})
elseif (os.is("macosx")) then
-- Engine/SDK binaries
table.insert(copyTargets, {
Masks = {"**.dynlib"},
Source = libDir,
Target = "bin/"
})
-- Engine/SDK libraries
table.insert(copyTargets, {
Masks = {"**.a"},
Source = libDir,
Target = "lib/"
})
-- 3rd party binary dep
table.insert(copyTargets, {
Masks = {"**.dynlib"},
Source = "../extlibs/lib/common/",
Target = "bin/"
})
-- Demo executable (OS X)
table.insert(copyTargets, {
Masks = {"Demo*"},
Filter = function (path) return path.getextension(path) == "" end,
Source = "../examples/bin/",
Target = "examples/bin/"
})
-- Unit test (OS X)
table.insert(copyTargets, {
Masks = {"*.*"},
Filter = function (path) return path.getextension(path) == "" end,
Source = "../tests/",
Target = "tests/"
})
else
-- Engine/SDK binaries
table.insert(copyTargets, {
Masks = {"**.so"},
Source = libDir,
Target = "bin/"
})
-- Engine/SDK libraries
table.insert(copyTargets, {
Masks = {"**.a"},
Source = libDir,
Target = "lib/"
})
-- 3rd party binary dep
table.insert(copyTargets, {
Masks = {"**.so"},
Source = "../extlibs/lib/common/",
Target = "bin/"
})
-- Demo executable (Linux)
table.insert(copyTargets, {
Masks = {"Demo*"},
Filter = function (path) return path.getextension(path) == "" end,
Source = "../examples/bin/",
Target = "examples/bin/"
})
-- Unit test (Linux)
table.insert(copyTargets, {
Masks = {"*.*"},
Filter = function (path) return path.getextension(path) == "" end,
Source = "../tests/",
Target = "tests/"
})
end
-- Processing
os.mkdir(packageDir)
local size = 0
for k,v in pairs(copyTargets) do
local target = packageDir .. v.Target
local includePrefix = v.Source
local targetFiles = {}
for k, mask in pairs(v.Masks) do
print(includePrefix .. mask .. " => " .. target)
local files = os.matchfiles(includePrefix .. mask)
if (v.Filter) then
for k,path in pairs(files) do
if (not v.Filter(v)) then
files[k] = nil
end
end
end
targetFiles = table.join(targetFiles, files)
end
for k,v in pairs(targetFiles) do
local relPath = v:sub(#includePrefix + 1)
local targetPath = target .. relPath
local targetDir = path.getdirectory(targetPath)
if (not os.isdir(targetDir)) then
local ok, err = os.mkdir(targetDir)
if (not ok) then
print("Failed to create directory \"" .. targetDir .. "\": " .. err)
end
end
local ok, err = os.copyfile(v, targetPath)
if (not ok) then
print("Failed to copy \"" .. v .. "\" to \"" .. targetPath .. "\": " .. err)
end
local stat = os.stat(targetPath)
if (stat) then
size = size + stat.size
end
end
end
print(string.format("Package successfully created at \"%s\" (%u MB, %s)", packageDir, size / (1024 * 1024), libDir))
end
|
newoption({
trigger = "pack-libdir",
description = "Specifiy the subdirectory in lib/ to be used when packaging the project"
})
ACTION.Name = "Package"
ACTION.Description = "Pack Nazara binaries/include/lib together"
ACTION.Function = function ()
local libDir = _OPTIONS["pack-libdir"]
if (not libDir or #libDir == 0) then
local libDirs = os.matchdirs("../lib/*")
if (#libDirs > 1) then
error("More than one subdirectory was found in the lib directory, please use the --pack-libdir command to clarify which directory should be used")
elseif (#libDirs == 0) then
error("No subdirectory was found in the lib directory, have you built the engine yet?")
else
libDir = libDirs[1] .. "/"
print("No directory was set by the --pack-libdir command, \"" .. libDir .. "\" will be used")
end
else
libDir = "../lib/" .. libDir .. "/"
end
if (not os.isdir(libDir)) then
error(string.format("\"%s\" doesn't seem to be an existing directory", libDir))
end
local packageDir = "../package/"
local copyTargets = {
{ -- Engine headers
Masks = {"**.hpp", "**.inl"},
Source = "../include/",
Target = "include/"
},
{ -- SDK headers
Masks = {"**.hpp", "**.inl"},
Source = "../SDK/include/",
Target = "include/"
},
{ -- Examples files
Masks = {"**.hpp", "**.inl", "**.cpp"},
Source = "../examples/",
Target = "examples/"
},
{ -- Demo resources
Masks = {"**.*"},
Source = "../examples/bin/resources/",
Target = "examples/bin/resources/"
},
-- Unit test sources
{
Masks = {"**.hpp", "**.inl", "**.cpp"},
Source = "../tests/",
Target = "tests/src/"
},
-- Unit test resources
{
Masks = {"**.*"},
Source = "../tests/resources/",
Target = "tests/resources/"
}
}
if (os.is("windows")) then
-- Engine/SDK binaries
table.insert(copyTargets, {
Masks = {"**.dll"},
Source = libDir,
Target = "bin/"
})
-- Engine/SDK libraries
table.insert(copyTargets, {
Masks = {"**.lib"},
Source = libDir,
Target = "lib/"
})
-- 3rd party binary dep
table.insert(copyTargets, {
Masks = {"**.dll"},
Source = "../extlibs/lib/common/",
Target = "bin/"
})
-- Demo executable (Windows)
table.insert(copyTargets, {
Masks = {"Demo*.exe"},
Source = "../examples/bin/",
Target = "examples/bin/"
})
-- Unit test (Windows)
table.insert(copyTargets, {
Masks = {"*.exe"},
Source = "../tests/",
Target = "tests/"
})
elseif (os.is("macosx")) then
-- Engine/SDK binaries
table.insert(copyTargets, {
Masks = {"**.dynlib"},
Source = libDir,
Target = "bin/"
})
-- Engine/SDK libraries
table.insert(copyTargets, {
Masks = {"**.a"},
Source = libDir,
Target = "lib/"
})
-- 3rd party binary dep
table.insert(copyTargets, {
Masks = {"**.dynlib"},
Source = "../extlibs/lib/common/",
Target = "bin/"
})
-- Demo executable (OS X)
table.insert(copyTargets, {
Masks = {"Demo*"},
Filter = function (filePath) return path.getextension(filePath) == "" end,
Source = "../examples/bin/",
Target = "examples/bin/"
})
-- Unit test (OS X)
table.insert(copyTargets, {
Masks = {"*.*"},
Filter = function (filePath) return path.getextension(filePath) == "" end,
Source = "../tests/",
Target = "tests/"
})
else
-- Engine/SDK binaries
table.insert(copyTargets, {
Masks = {"**.so"},
Source = libDir,
Target = "bin/"
})
-- Engine/SDK libraries
table.insert(copyTargets, {
Masks = {"**.a"},
Source = libDir,
Target = "lib/"
})
-- 3rd party binary dep
table.insert(copyTargets, {
Masks = {"**.so"},
Source = "../extlibs/lib/common/",
Target = "bin/"
})
-- Demo executable (Linux)
table.insert(copyTargets, {
Masks = {"Demo*"},
Filter = function (filePath) return path.getextension(filePath) == "" end,
Source = "../examples/bin/",
Target = "examples/bin/"
})
-- Unit test (Linux)
table.insert(copyTargets, {
Masks = {"*.*"},
Filter = function (filePath) return path.getextension(filePath) == "" end,
Source = "../tests/",
Target = "tests/"
})
end
-- Processing
os.mkdir(packageDir)
local size = 0
for k,v in pairs(copyTargets) do
local target = packageDir .. v.Target
local includePrefix = v.Source
local targetFiles = {}
for k, mask in pairs(v.Masks) do
print(includePrefix .. mask .. " => " .. target)
local files = os.matchfiles(includePrefix .. mask)
if (v.Filter) then
for k,path in pairs(files) do
if (not v.Filter(path)) then
files[k] = nil
end
end
end
targetFiles = table.join(targetFiles, files)
end
for k,v in pairs(targetFiles) do
local relPath = v:sub(#includePrefix + 1)
local targetPath = target .. relPath
local targetDir = path.getdirectory(targetPath)
if (not os.isdir(targetDir)) then
local ok, err = os.mkdir(targetDir)
if (not ok) then
print("Failed to create directory \"" .. targetDir .. "\": " .. err)
end
end
local ok, err
if (os.is("windows")) then
ok, err = os.copyfile(v, targetPath)
else
-- Workaround: As premake is translating this to "cp %s %s", it fails if there are space in the paths.
ok, err = os.copyfile(string.format("\"%s\"", v), string.format("\"%s\"", targetPath))
end
if (not ok) then
print("Failed to copy \"" .. v .. "\" to \"" .. targetPath .. "\": " .. err)
end
local stat = os.stat(targetPath)
if (stat) then
size = size + stat.size
end
end
end
print(string.format("Package successfully created at \"%s\" (%u MB, %s)", packageDir, size / (1024 * 1024), libDir))
end
|
Build: Fix package on Linux/OS X
|
Build: Fix package on Linux/OS X
Former-commit-id: af859279daff0a3277885a129dbe0a3b64b670ee [formerly 9b5c746de0092b15a3a6b22e7b62c0d786511f74] [formerly c0deb3f2282e65eced2a847bfe96fade40000e0d [formerly 778655003cf7af0d129e08cf1241c0e7062cbc02]]
Former-commit-id: 1c43974f748ac73fb001ed826e33e6d65fa6be5a [formerly 860aaa09c8659b40712ecfbde1503098cb18d26f]
Former-commit-id: e13892bcca0dac59917554a6236ff53015c7cb2c
|
Lua
|
mit
|
DigitalPulseSoftware/NazaraEngine
|
bb9e5788c94b4fbd2a413d07286080d3b24b1433
|
Spr.lua
|
Spr.lua
|
-- Modulo per il Template Spr
local s = {}
local mw = require('mw')
local tab = require('Wikilib-tables')
local w = require('Wikilib')
local gens = require('Wikilib-gens')
--[[
Table che mantiene le associazioni tra il
secondo parametro in lowercase e le sigle
dei giochi negli sprite
--]]
local gamesAbbr = {
verde = 'verde',
['rosso e blu'] = 'rb',
giallo = 'gia',
oro = 'or',
argento = 'ar',
cristallo = 'cr',
['rubino e zaffiro'] = 'rz',
['rosso fuoco e verde foglia'] = 'rfvf',
smeraldo = 'sme',
['diamante e perla'] = 'dp',
platino = 'pt',
['heartgold e soulsilver'] = 'hgss',
['nero e bianco'] = 'nb',
['nero 2 e bianco 2'] = 'nb2',
['x e y'] = 'xy',
['rubino omega e zaffiro alpha'] = 'roza',
colosseum = 'colo',
-- XD is not necessary
stadium = 'stad',
['stadium 2'] = 'stad2'
}
-- Alias per la table di cui sopra
table.tableKeysAlias(gamesAbbr,
{'verde', 'rosso e blu', 'oro', 'cristallo',
'rubino e zaffiro', 'rosso fuoco e verde foglia',
'smeraldo', 'diamante e perla',
'heartgold e soulsilver', 'nero e bianco',
'nero 2 e bianco 2', 'x e y',
'rubino omega e zaffiro alpha', 'stadium 2'},
{{'rosso e verde', 'rv', 'v'}, {'rosso', 'blu', 'r', 'b'},
{'oro e argento', 'oa'}, {'c'}, {'rubino', 'zaffiro', 'ru',
'za', 'z'},
{'rosso fuoco', 'verde foglia', 'rf', 'vf'}, {'s'},
{'diamante', 'perla', 'd', 'p'}, {'oro heartgold e argento soulsilver',
'heartgold', 'oro heartgold', 'soulsilver', 'argento soulsilver',
'hg', 'ss'},
{'nero', 'bianco', 'n', 'bi'}, {'nero 2', 'bianco 2',
'n2', 'b2', 'n2b2'},
{'x', 'y', 'xy'}, {'rubino omega', 'zaffiro alpha', 'ro', 'za'},
{'stad 2'}})
--[[
Table per convertire dalle sigle usate
negli sprite a quelle usate nella funzione
getGen.games del modulo Wikilib/gens
--]]
local gamesAbbrGen = {
verde = 'rb',
gia = 'g',
stad = 'st',
ar = 'oa',
cr = 'c',
stad2 = 'st2',
sme = 's',
nb2 = 'n2b2'
}
gamesAbbrGen['or'] = gamesAbbrGen.ar
--[[
Table usata per ordinare le parole che
compongono la variante dello sprite.
L'ordine relativo di 'male' e 'female'
è irrilevante, poiché non possono coesistere.
--]]
local variantPiecesOrder = {'female', 'male', 'back', 'shiny'}
-- Sigle per le varianti sesso/shiny/dietro degli sprite
local variants = {
male = 'm',
female = 'f',
shiny = 'sh',
back = 'd',
['male shiny'] = 'msh',
['female shiny'] = 'fsh',
['back shiny'] = 'dsh',
['male back'] = 'md',
['female back'] = 'fd',
['male back shiny'] = 'mdsh',
['female back shiny'] = 'fdsh'
}
-- Table per i giochi che hanno gli sprite in .gif
local gifs = {'cr', 'sme', 'xy', 'roza'}
-- Table per le dimensioni degli sprite
local sizes = {
stad = '|120px',
stad2 = '|120px',
xy = '|192px',
roza = '|192px'
}
--[[
Ritorna gif se il gioco è presente nella table
gifs, con l'unica eccezione degli sprite shiny
e restrostanti di smeraldo che sono in png.
Negli altri casi png.
--]]
local getExtension = function(game, variant)
if game == 'sme' and variant:find('[dsh]')
or not table.search(gifs, game) then
return 'png'
end
return 'gif'
end
--[[
Link agli sprite, chiamata da lua.
La variante è obbligatoria per i giochi dalla
quarta generazione in poi, mentre la dimensione
è sempre opzionale.
La variante può contenere le parole 'female',
'male', 'back' e 'shiny' in qualsiasi ordine
e in qualsiasi numero, con la sola restrizione
che 'male' e 'female' non possono coesistere
--]]
s.sprLua = function(ndex, game, variant, size)
game = string.lower(game or 'current')
variant = string.lower(variant or '')
game = gamesAbbr[game] or game
local gen = gens.getGen.game(gamesAbbrGen[game] or game)
--[[
I giochi di seconda generazione hanno
'oac' come gioco negli sprite posteriori
--]]
if gen == 2 and variant:find('back') then
game = 'oac'
end
variant = table.unique(mw.text.split(variant, '%s+'))
table.sort(variant, function(a, b)
return table.search(variantPiecesOrder, a)
< table.search(variantPiecesOrder, b)
end)
variant = table.concat(variant, ' ')
--[[
Prima della quarta generazione non c'erano
differenze di genere negli sprite.
NB: la stringa 'male' è trovata sia in
'male' che in 'female'
--]]
if gen < 4 and variant:find('male') then
-- Elimina il genere dalla variante
variant = variant:match('male%s+([%w%s]+)')
end
variant = variants[variant] or ''
return game == 'current' and
table.concat{'[[File:', ndex, '.png]]'} or
w.interp('[[File:Spr${game}${variant}${ndex}.${ext}${size}]]',
{
game = game,
variant = variant,
ndex = ndex or '001',
ext = getExtension(game, variant),
size = size and '|' .. size or sizes[game] or ''
})
end
s.spr_lua = s.sprLua
--[[
Link agli sprite, chiamata da Wikicode (adapter per lua)
- Primo argomento: numero di dex nazionale, con
eventuale sigla della forma alternativa
- Secondo argomento: gioco
- Terzo argomento: variante (sesso, retro, shiny)
- Quarto argomento (opzionale): dimensione
Esempio: {{#invoke: Spr | spr | 479L | Platino | shiny back | 30px}}
--]]
s.spr = function(frame)
local p = w.trimAll(mw.clone(frame.args))
return s.sprLua(p[1], p[2], p[3], p[4])
end
s.Spr = s.spr
return s
|
-- Modulo per il Template Spr
local s = {}
local mw = require('mw')
local tab = require('Wikilib-tables')
local w = require('Wikilib')
local gens = require('Wikilib-gens')
--[[
Table che mantiene le associazioni tra il
secondo parametro in lowercase e le sigle
dei giochi negli sprite
--]]
local gamesAbbr = {
verde = 'verde',
['rosso e blu'] = 'rb',
giallo = 'gia',
oro = 'or',
argento = 'ar',
cristallo = 'cr',
['rubino e zaffiro'] = 'rz',
['rosso fuoco e verde foglia'] = 'rfvf',
smeraldo = 'sme',
['diamante e perla'] = 'dp',
platino = 'pt',
['heartgold e soulsilver'] = 'hgss',
['nero e bianco'] = 'nb',
['nero 2 e bianco 2'] = 'nb2',
['x e y'] = 'xy',
['rubino omega e zaffiro alpha'] = 'roza',
colosseum = 'colo',
-- XD is not necessary
stadium = 'stad',
['stadium 2'] = 'stad2'
}
-- Alias per la table di cui sopra
table.tableKeysAlias(gamesAbbr,
{'verde', 'rosso e blu', 'oro', 'cristallo',
'rubino e zaffiro', 'rosso fuoco e verde foglia',
'smeraldo', 'diamante e perla',
'heartgold e soulsilver', 'nero e bianco',
'nero 2 e bianco 2', 'x e y',
'rubino omega e zaffiro alpha', 'stadium 2'},
{{'rosso e verde', 'rv', 'v'}, {'rosso', 'blu', 'r', 'b'},
{'oro e argento', 'oa'}, {'c'}, {'rubino', 'zaffiro', 'ru',
'za', 'z'},
{'rosso fuoco', 'verde foglia', 'rf', 'vf'}, {'s'},
{'diamante', 'perla', 'd', 'p'}, {'oro heartgold e argento soulsilver',
'heartgold', 'oro heartgold', 'soulsilver', 'argento soulsilver',
'hg', 'ss'},
{'nero', 'bianco', 'n', 'bi'}, {'nero 2', 'bianco 2',
'n2', 'b2', 'n2b2'},
{'x', 'y', 'xy'}, {'rubino omega', 'zaffiro alpha', 'ro', 'za'},
{'stad 2'}})
--[[
Table per convertire dalle sigle usate
negli sprite a quelle usate nella funzione
getGen.games del modulo Wikilib/gens
--]]
local gamesAbbrGen = {
verde = 'rb',
gia = 'g',
stad = 'st',
ar = 'oa',
cr = 'c',
stad2 = 'st2',
sme = 's',
nb2 = 'n2b2'
}
gamesAbbrGen['or'] = gamesAbbrGen.ar
--[[
Table usata per ordinare le parole che
compongono la variante dello sprite.
L'ordine relativo di 'male' e 'female'
è irrilevante, poiché non possono coesistere.
--]]
local variantPiecesOrder = {'female', 'male', 'back', 'shiny'}
-- Sigle per le varianti sesso/shiny/dietro degli sprite
local variants = {
male = 'm',
female = 'f',
shiny = 'sh',
back = 'd',
['male shiny'] = 'msh',
['female shiny'] = 'fsh',
['back shiny'] = 'dsh',
['male back'] = 'md',
['female back'] = 'fd',
['male back shiny'] = 'mdsh',
['female back shiny'] = 'fdsh'
}
-- Table per i giochi che hanno gli sprite in .gif
local gifs = {'cr', 'sme', 'xy', 'roza'}
-- Table per le dimensioni degli sprite
local sizes = {
stad = '|120px',
stad2 = '|120px',
xy = '|192px',
roza = '|192px'
}
--[[
Ritorna gif se il gioco è presente nella table
gifs, con l'unica eccezione degli sprite shiny
e restrostanti di smeraldo che sono in png.
Negli altri casi png.
--]]
local getExtension = function(game, variant)
if game == 'sme' and variant:find('[dsh]')
or not table.search(gifs, game) then
return 'png'
end
return 'gif'
end
--[[
Link agli sprite, chiamata da lua.
La variante è obbligatoria per i giochi dalla
quarta generazione in poi, mentre la dimensione
è sempre opzionale.
La variante può contenere le parole 'female',
'male', 'back' e 'shiny' in qualsiasi ordine
e in qualsiasi numero, con la sola restrizione
che 'male' e 'female' non possono coesistere
--]]
s.sprLua = function(ndex, game, variant, size)
game = string.lower(game or 'current')
if game == 'current' then
return table.concat{'[[File:', ndex, '.png]]'}
end
variant = string.lower(variant or '')
game = gamesAbbr[game] or game
local gen = gens.getGen.game(gamesAbbrGen[game] or game)
--[[
I giochi di seconda generazione hanno
'oac' come gioco negli sprite posteriori
--]]
if gen == 2 and variant:find('back') then
game = 'oac'
end
variant = table.unique(mw.text.split(variant, '%s+'))
table.sort(variant, function(a, b)
return table.search(variantPiecesOrder, a)
< table.search(variantPiecesOrder, b)
end)
variant = table.concat(variant, ' ')
--[[
Prima della quarta generazione non c'erano
differenze di genere negli sprite.
NB: la stringa 'male' è trovata sia in
'male' che in 'female'
--]]
if gen < 4 and variant:find('male') then
-- Elimina il genere dalla variante
variant = variant:match('male%s+([%w%s]+)')
end
variant = variants[variant] or ''
return w.interp('[[File:Spr${game}${variant}${ndex}.${ext}${size}]]',
{
game = game,
variant = variant,
ndex = ndex or '001',
ext = getExtension(game, variant),
size = size and '|' .. size or sizes[game] or ''
})
end
s.spr_lua = s.sprLua
--[[
Link agli sprite, chiamata da Wikicode (adapter per lua)
- Primo argomento: numero di dex nazionale, con
eventuale sigla della forma alternativa
- Secondo argomento: gioco
- Terzo argomento: variante (sesso, retro, shiny)
- Quarto argomento (opzionale): dimensione
Esempio: {{#invoke: Spr | spr | 479L | Platino | shiny back | 30px}}
--]]
s.spr = function(frame)
local p = w.trimAll(mw.clone(frame.args))
return s.sprLua(p[1], p[2], p[3], p[4])
end
s.Spr = s.spr
return s
|
Sor: Early management of current game, since it avoids lots of bugs and computation.
|
Sor: Early management of current game, since it avoids lots of bugs and computation.
|
Lua
|
cc0-1.0
|
pokemoncentral/wiki-lua-modules
|
6957dd91a31a9e51873abbcc601b449c31050877
|
example/gatedNegationRanking.lua
|
example/gatedNegationRanking.lua
|
local cutorch = require "cutorch"
local cunn = require "cunn"
local nn = require "nn"
local nngraph = require "nngraph"
local optim = require "optim"
-- set gated network hyperparameters
local opt = {}
opt.embedSize = 300
opt.gateSize = 300
opt.hiddenSize = 600
opt.jackknifeSize = 10
opt.numEpochs = 1
opt.batchSize = 8
opt.useGPU = true -- use CUDA_VISIBLE_DEVICES to set the GPU you want to use
opt.predFile = "predict.out"
-- define gated network graph
---- declare inputs
print("Constructing input layers")
local word_vector = nn.Identity()()
local gate_vector = nn.Identity()()
local targ_vector = nn.Identity()()
local sample_vector = nn.Identity()()
---- define hidden layer
print("Constructing hidden state")
local h = nn.Sigmoid()(nn.Bilinear(opt.embedSize, opt.gateSize, opt.hiddenSize)({word_vector, gate_vector}))
---- define output layer
print("Constructing output")
local output = nn.Bilinear(opt.hiddenSize, opt.gateSize, opt.embedSize)({h, gate_vector})
---- Construct model
print("Constructing module")
local ged = nn.gModule({word_vector, gate_vector}, {output})
-- define loss function
print("Defining loss function")
local out_vec = nn.Identity()()
local targ_vec = nn.Identity()()
local sample_vec = nn.Identity()()
local rank = nn.Identity()()
local cos1 = nn.CosineDistance()({out_vec, targ_vec})
local cos2 = nn.CosineDistance()({out_vec, sample_vec})
local loss = nn.MarginRankingCriterion()({nn.ParallelTable()
:add(nn.Identity())
:add(nn.Identity())({cos1, cos2}), rank})
local loss_module = nn.gModule({out_vec, targ_vec, sample_vec, rank}, {loss})
-- GPU mode
if opt.useGPU then
ged:cuda()
loss_module:cuda()
end
-- read training and test data
print("Reading training data")
traindata = torch.Tensor(19578, 4*opt.embedSize)
io.input('data.top10nns.raw.ranking.train')
linecount = 0
for line in io.lines() do
linecount = linecount + 1
valcount = 0
for num in string.gmatch(line, "%S+") do
valcount = valcount + 1
if valcount > 1 then
traindata[linecount][valcount - 1] = tonumber(num)
end
end
end
print("Reading test data")
testdata = torch.Tensor(225, 4*opt.embedSize)
testwords = {}
io.input('data.top10nns.raw.ranking.test')
linecount = 0
for line in io.lines() do
linecount = linecount + 1
valcount = 0
for num in string.gmatch(line, "%S+") do
valcount = valcount + 1
if valcount == 1 then
testwords[linecount] = num
else
testdata[linecount][valcount - 1] = tonumber(num)
end
end
end
-- train model
local x, gradParameters = ged:getParameters()
for epoch = 1, opt.numEpochs do
print("Training epoch", epoch)
shuffle = torch.randperm(traindata:size()[1])
current_loss = 0
for t = 1, traindata:size()[1], opt.batchSize do
local inputs = {}
local gates = {}
local targets = {}
local samples = {}
for j = t, math.min(t + opt.batchSize - 1, traindata:size()[1]) do
local input = traindata[shuffle[j]]:narrow(1, 1, opt.embedSize):resize(1, opt.embedSize)
local gate = traindata[shuffle[j]]:narrow(1, opt.embedSize + 1, opt.embedSize):resize(1, opt.embedSize)
local target = traindata[shuffle[j]]:narrow(1, 2*opt.embedSize + 1, opt.embedSize):resize(1, opt.embedSize)
local sample = traindata[shuffle[j]]:narrow(1, 3*opt.embedSize + 1, opt.embedSize):resize(1,opt.embedSize)
if opt.useGPU then
input = input:cuda()
gate = gate:cuda()
target = target:cuda()
sample = sample:cuda()
end
table.insert(inputs, input:clone())
table.insert(gates, gate:clone())
table.insert(targets, target:clone())
table.insert(samples, sample:clone())
end
local feval = function(w) -- w = weight vector. returns loss, dloss_dw
gradParameters:zero()
local f = 0 -- for averaging error
for k = 1, #inputs do
local result = ged:forward({inputs[k], gates[k]})
local err = loss_module:forward({result, targets[k], samples[k], 1})
f = f + err
local gradErr = loss_module:backward({result, targets[k], samples[k], 1})
ged:backward({inputs[k], gates[k]}, gradErr)
end -- for k = 1, #inputs
-- normalize gradients and f(X)
gradParameters:div(#inputs)
f = f/(#inputs)
return f, gradParameters
end -- local feval
_, fs = optim.adadelta(feval, x, {rho = 0.9})
current_loss = current_loss + fs[1]
end -- for t = 1, traindata:size()[1], opt.batchSize
current_loss = current_loss / traindata:size()[1]
print("... Current loss", current_loss)
end -- for epoch = 1, opt.numEpochs
-- predict
print "Predicting"
-- module with the first half of the network
for t = 1, testdata:size()[1] do
local input_word = testwords[t]
local input = traindata[shuffle[j]]:narrow(1, 1, opt.embedSize):resize(1, opt.embedSize)
local gate = traindata[shuffle[j]]:narrow(1, opt.embedSize + 1, opt.embedSize):resize(1, opt.embedSize)
if opt.useGPU then
input = input:cuda()
gate = gate:cuda()
end
local output = ged:forward({input, gate})
opt.predfile:write(input_word .. "\t[")
for k = 1, output:size()[2] do
opt.predfile:write(output[t][k] .. ", ")
end
opt.predfile:write("]\n")
end
print("Saving model")
torch.save("model.net", ged)
|
local cutorch = require "cutorch"
local cunn = require "cunn"
local nn = require "nn"
local nngraph = require "nngraph"
local optim = require "optim"
-- set gated network hyperparameters
local opt = {}
opt.embedSize = 300
opt.gateSize = 300
opt.hiddenSize = 600
opt.jackknifeSize = 10
opt.numEpochs = 1
opt.batchSize = 8
opt.useGPU = true -- use CUDA_VISIBLE_DEVICES to set the GPU you want to use
opt.predFile = "predict.out"
-- define gated network graph
---- declare inputs
print("Constructing input layers")
local word_vector = nn.Identity()()
local gate_vector = nn.Identity()()
local targ_vector = nn.Identity()()
local sample_vector = nn.Identity()()
---- define hidden layer
print("Constructing hidden state")
local h = nn.Sigmoid()(nn.Bilinear(opt.embedSize, opt.gateSize, opt.hiddenSize)({word_vector, gate_vector}))
---- define output layer
print("Constructing output")
local output = nn.Bilinear(opt.hiddenSize, opt.gateSize, opt.embedSize)({h, gate_vector})
---- Construct model
print("Constructing module")
local ged = nn.gModule({word_vector, gate_vector}, {output})
-- define loss function
print("Defining loss function")
local out_vec = nn.Identity()()
local targ_vec = nn.Identity()()
local sample_vec = nn.Identity()()
local rank = nn.Identity()()
local cos1 = nn.CosineDistance()({out_vec, targ_vec})
local cos2 = nn.CosineDistance()({out_vec, sample_vec})
local parInput = nn.ParallelTable()
:add(nn.Identity())
:add(nn.Identity())
local loss = nn.MarginRankingCriterion()({parInput({cos1, cos2}), rank})
local loss_module = nn.gModule({out_vec, targ_vec, sample_vec, rank}, {loss})
-- GPU mode
if opt.useGPU then
ged:cuda()
loss_module:cuda()
end
-- read training and test data
print("Reading training data")
traindata = torch.Tensor(19578, 4*opt.embedSize)
io.input('data.top10nns.raw.ranking.train')
linecount = 0
for line in io.lines() do
linecount = linecount + 1
valcount = 0
for num in string.gmatch(line, "%S+") do
valcount = valcount + 1
if valcount > 1 then
traindata[linecount][valcount - 1] = tonumber(num)
end
end
end
print("Reading test data")
testdata = torch.Tensor(225, 4*opt.embedSize)
testwords = {}
io.input('data.top10nns.raw.ranking.test')
linecount = 0
for line in io.lines() do
linecount = linecount + 1
valcount = 0
for num in string.gmatch(line, "%S+") do
valcount = valcount + 1
if valcount == 1 then
testwords[linecount] = num
else
testdata[linecount][valcount - 1] = tonumber(num)
end
end
end
-- train model
local x, gradParameters = ged:getParameters()
for epoch = 1, opt.numEpochs do
print("Training epoch", epoch)
shuffle = torch.randperm(traindata:size()[1])
current_loss = 0
for t = 1, traindata:size()[1], opt.batchSize do
local inputs = {}
local gates = {}
local targets = {}
local samples = {}
for j = t, math.min(t + opt.batchSize - 1, traindata:size()[1]) do
local input = traindata[shuffle[j]]:narrow(1, 1, opt.embedSize):resize(1, opt.embedSize)
local gate = traindata[shuffle[j]]:narrow(1, opt.embedSize + 1, opt.embedSize):resize(1, opt.embedSize)
local target = traindata[shuffle[j]]:narrow(1, 2*opt.embedSize + 1, opt.embedSize):resize(1, opt.embedSize)
local sample = traindata[shuffle[j]]:narrow(1, 3*opt.embedSize + 1, opt.embedSize):resize(1,opt.embedSize)
if opt.useGPU then
input = input:cuda()
gate = gate:cuda()
target = target:cuda()
sample = sample:cuda()
end
table.insert(inputs, input:clone())
table.insert(gates, gate:clone())
table.insert(targets, target:clone())
table.insert(samples, sample:clone())
end
local feval = function(w) -- w = weight vector. returns loss, dloss_dw
gradParameters:zero()
local f = 0 -- for averaging error
for k = 1, #inputs do
local result = ged:forward({inputs[k], gates[k]})
local err = loss_module:forward({result, targets[k], samples[k], 1})
f = f + err
local gradErr = loss_module:backward({result, targets[k], samples[k], 1})
ged:backward({inputs[k], gates[k]}, gradErr)
end -- for k = 1, #inputs
-- normalize gradients and f(X)
gradParameters:div(#inputs)
f = f/(#inputs)
return f, gradParameters
end -- local feval
_, fs = optim.adadelta(feval, x, {rho = 0.9})
current_loss = current_loss + fs[1]
end -- for t = 1, traindata:size()[1], opt.batchSize
current_loss = current_loss / traindata:size()[1]
print("... Current loss", current_loss)
end -- for epoch = 1, opt.numEpochs
-- predict
print "Predicting"
-- module with the first half of the network
for t = 1, testdata:size()[1] do
local input_word = testwords[t]
local input = traindata[shuffle[j]]:narrow(1, 1, opt.embedSize):resize(1, opt.embedSize)
local gate = traindata[shuffle[j]]:narrow(1, opt.embedSize + 1, opt.embedSize):resize(1, opt.embedSize)
if opt.useGPU then
input = input:cuda()
gate = gate:cuda()
end
local output = ged:forward({input, gate})
opt.predfile:write(input_word .. "\t[")
for k = 1, output:size()[2] do
opt.predfile:write(output[t][k] .. ", ")
end
opt.predfile:write("]\n")
end
print("Saving model")
torch.save("model.net", ged)
|
Fix Paralleltable input for ranking criterion.
|
Fix Paralleltable input for ranking criterion.
|
Lua
|
mit
|
douwekiela/nncg-negation
|
b47d76b93bee333fc62f982075d84c73d7aa282a
|
pud/ui/TextEntry.lua
|
pud/ui/TextEntry.lua
|
local Class = require 'lib.hump.class'
local Text = getClass 'pud.ui.Text'
local KeyboardEvent = getClass 'pud.event.KeyboardEvent'
local string_len = string.len
local string_sub = string.sub
local format = string.format
-- TextEntry
-- A text frame that gathers keyboard input.
local TextEntry = Class{name='TextEntry',
inherits=Text,
function(self, ...)
Text.construct(self, ...)
InputEvents:register(self, KeyboardEvent)
end
}
-- destructor
function TextEntry:destroy()
self._isEnteringText = nil
-- Frame will unregister all InputEvents
Text.destroy(self)
end
-- override Frame:onRelease()
function TextEntry:onRelease(button, mods, wasInside)
if wasInside and 'l' == button then
self._isEnteringText = not self._isEnteringText
end
if self._isEnteringText then
self._curStyle = self._activeStyle or self._hoverStyle or self._normalStyle
elseif self._hovered then
self._curStyle = self._hoverStyle or self._normalStyle
else
self._curStyle = self._normalStyle
end
self:_drawFB()
end
-- override Frame:onHoverIn()
function TextEntry:onHoverIn(x, y)
if self._isEnteringText then return end
Text.onHoverIn(self, x, y)
end
-- override TextEntry:onHoverOut()
function TextEntry:onHoverOut(x, y)
if self._isEnteringText then return end
Text.onHoverOut(self, x, y)
end
-- capture text input if in editing mode
function TextEntry:KeyboardEvent(e)
if not self._isEnteringText then return end
if self._text then
-- copy the entire text
local text = {}
local numLines = #self._text
for i=1,numLines do text[i] = self._text[i] end
local line
local lineNum = numLines + 1
repeat
lineNum = lineNum - 1
line = text[lineNum]
until string.len(line) ~= 0 or lineNum < 1
if lineNum < 1 then lineNum = 1 end
line = line or text[lineNum]
local key = e:getKey()
switch(key) {
backspace = function() line = string_sub(line, 1, -2) end,
escape = function()
self._isEnteringText = false
self:onRelease()
end,
default = function()
local unicode = e:getUnicode()
if unicode then
line = format('%s%s', line, unicode)
end
end,
}
text[lineNum] = line
self:setText(text)
self:_drawFB()
else
warning('Text is missing!')
end
end
-- the class
return TextEntry
|
local Class = require 'lib.hump.class'
local Text = getClass 'pud.ui.Text'
local KeyboardEvent = getClass 'pud.event.KeyboardEvent'
local string_len = string.len
local string_sub = string.sub
local format = string.format
-- TextEntry
-- A text frame that gathers keyboard input.
local TextEntry = Class{name='TextEntry',
inherits=Text,
function(self, ...)
Text.construct(self, ...)
InputEvents:register(self, KeyboardEvent)
end
}
-- destructor
function TextEntry:destroy()
self._isEnteringText = nil
-- Frame will unregister all InputEvents
Text.destroy(self)
end
-- override Frame:onRelease()
function TextEntry:onRelease(button, mods, wasInside)
if wasInside and 'l' == button then
self._isEnteringText = not self._isEnteringText
end
if self._isEnteringText then
self._curStyle = self._activeStyle or self._hoverStyle or self._normalStyle
elseif self._hovered then
self._curStyle = self._hoverStyle or self._normalStyle
else
self._curStyle = self._normalStyle
end
self:_drawFB()
end
-- override Frame:onHoverIn()
function TextEntry:onHoverIn(x, y)
if self._isEnteringText then return end
Text.onHoverIn(self, x, y)
end
-- override TextEntry:onHoverOut()
function TextEntry:onHoverOut(x, y)
if self._isEnteringText then return end
Text.onHoverOut(self, x, y)
end
-- capture text input if in editing mode
function TextEntry:KeyboardEvent(e)
if not self._isEnteringText then return end
if self._text then
-- copy the entire text
local text = {}
local numLines = #self._text
for i=1,numLines do text[i] = self._text[i] end
local lineNum = numLines
if lineNum < 1 then lineNum = 1 end
local line = text[lineNum] or ''
local key = e:getKey()
switch(key) {
backspace = function()
line = string_sub(line, 1, -2)
if string.len(line) < 1 then
text[lineNum] = nil
lineNum = lineNum - 1
if lineNum < 1 then lineNum = 1 end
line = text[lineNum] or ''
end
end,
['return'] = function()
local nextLine = lineNum + 1
if nextLine > self._maxLines then nextLine = self._maxLines end
text[nextLine] = text[nextLine] or ''
end,
escape = function()
self._isEnteringText = false
self:onRelease()
end,
default = function()
local unicode = e:getUnicode()
if unicode then
line = format('%s%s', line, unicode)
end
end,
}
text[lineNum] = line
self:setText(text)
self:_drawFB()
else
warning('Text is missing!')
end
end
-- the class
return TextEntry
|
fix backspace to delete to prev line and return to add line
|
fix backspace to delete to prev line and return to add line
|
Lua
|
mit
|
scottcs/wyx
|
e536eaf2f9e647a845781366598c79a3c4d683ee
|
packages/nn/Copy.lua
|
packages/nn/Copy.lua
|
local Copy, parent = torch.class('nn.Copy', 'nn.Module')
function Copy:__init(intype, outtype)
intype = intype or torch.getmetatable(torch.Tensor.__typename)
outtype = outtype or torch.getmetatable(torch.Tensor.__typename)
parent.__init(self)
self.gradInput = torch.getmetatable(intype).new()
self.output = torch.getmetatable(outtype).new()
if intype == outtype then
self.forward = function(self, input)
return input
end
self.backward = function(self, input, gradOutput)
self.gradInput = gradOutput
return gradOutput
end
end
end
function Copy:forward(input)
self.output:resize(input:size()):copy(input)
return self.output
end
function Copy:backward(input, gradOutput)
self.gradInput:resize(gradOutput:size()):copy(gradOutput)
return self.gradInput
end
|
local Copy, parent = torch.class('nn.Copy', 'nn.Module')
function Copy:__init(intype, outtype)
intype = intype or torch.getmetatable(torch.Tensor.__typename)
outtype = outtype or torch.getmetatable(torch.Tensor.__typename)
parent.__init(self)
self.gradInput = torch.getmetatable(intype).new()
self.output = torch.getmetatable(outtype).new()
if intype == outtype then
self.forward = function(self, input)
self.output = input
return input
end
self.backward = function(self, input, gradOutput)
self.gradInput = gradOutput
return gradOutput
end
end
end
function Copy:forward(input)
self.output:resize(input:size()):copy(input)
return self.output
end
function Copy:backward(input, gradOutput)
self.gradInput:resize(gradOutput:size()):copy(gradOutput)
return self.gradInput
end
|
oops, corrected bug just introduced in Copy
|
oops, corrected bug just introduced in Copy
|
Lua
|
bsd-3-clause
|
soumith/TH,soumith/TH,soumith/TH,soumith/TH
|
0ce42f55750179aef5ed6b60cf0e7387346cb603
|
test/test_jacobian.lua
|
test/test_jacobian.lua
|
require 'inn'
local mytester = torch.Tester()
local jac
local precision = 1e-3
local inntest = torch.TestSuite()
-- disabled test because of stochastic nature
-- to do it properly testJacobian needs to reset seed before every forward
--[[
function inntest.SpatialStochasticPooling()
local from = math.random(1,5)
local ki = math.random(1,4)
local kj = math.random(1,4)
local si = math.random(1,3)
local sj = math.random(1,3)
local outi = math.random(4,5)
local outj = math.random(4,5)
local ini = (outi-1)*si+ki
local inj = (outj-1)*sj+kj
local module = inn.SpatialStochasticPooling(ki,kj,si,sj):cuda()
local input = torch.rand(from,ini,inj):cuda()
local err = jac.testJacobian(module, input, nil, nil, 1e-3)
mytester:assertlt(err, precision, 'error on state ')
local ferr, berr = jac.testIO(module, input)
mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ')
mytester:assertlt(berr, 1e-6, torch.typename(module) .. ' - i/o backward err ')
-- batch
local nbatch = math.random(2,5)
input = torch.rand(nbatch,from,ini,inj):cuda()
module = inn.SpatialStochasticPooling(ki,kj,si,sj):cuda()
local err = jac.testJacobian(module, input, nil, nil, 1e-3)
mytester:assertlt(err, precision, 'error on state (Batch) ')
local ferr, berr = jac.testIO(module, input)
mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err (Batch) ')
mytester:assertlt(berr, 1e-6, torch.typename(module) .. ' - i/o backward err (Batch) ')
end
]]--
function inntest.SpatialPyramidPooling()
local from = math.random(1,5)
local ki = math.random(1,4)
local kj = math.random(1,4)
local si = math.random(1,3)
local sj = math.random(1,3)
local outi = math.random(4,5)
local outj = math.random(4,5)
local ini = (outi-1)*si+ki
local inj = (outj-1)*sj+kj
local module = inn.SpatialPyramidPooling({4,4},{3,3})
local input = torch.rand(from,ini,inj)
local err = jac.testJacobian(module, input, nil, nil, 1e-3)
mytester:assertlt(err, precision, 'error on state ')
local ferr, berr = jac.testIO(module, input)
mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ')
mytester:assertlt(berr, 1e-6, torch.typename(module) .. ' - i/o backward err ')
-- batch
local nbatch = math.random(2,5)
input = torch.rand(nbatch,from,ini,inj)
module = inn.SpatialPyramidPooling({4,4},{3,3})
local err = jac.testJacobian(module, input, nil, nil, 1e-3)
mytester:assertlt(err, precision, 'error on state (Batch) ')
local ferr, berr = jac.testIO(module, input)
mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err (Batch) ')
mytester:assertlt(berr, 1e-6, torch.typename(module) .. ' - i/o backward err (Batch) ')
end
function inntest.SpatialSameResponseNormalization()
local from = 16
local inj = 2
local ini = inj
local module = inn.SpatialSameResponseNormalization(3, 5e-5, 0.75)
local input = torch.randn(from,inj,ini)
local err = jac.testJacobian(module,input,nil,nil,1e-3)
mytester:assertlt(err, precision, 'error on state ')
-- batch
local bs = 32
local input = torch.randn(bs,from,inj,ini)
local module = inn.SpatialSameResponseNormalization(3, 5e-5, 0.75)
local err = jac.testJacobian(module, input, nil, nil, 1e-3)
mytester:assertlt(err, precision, 'error on state (Batch) ')
end
function randROI(sz, n)
assert(sz:size()==4, "need 4d size")
local roi=torch.Tensor(n,5)
for i=1,n do
idx=torch.randperm(sz[1])[1]
y=torch.randperm(sz[3])[{{1,2}}]:sort()
x=torch.randperm(sz[4])[{{1,2}}]:sort()
roi[{i,{}}] = torch.Tensor({idx,x[1],y[1],x[2],y[2]})
end
return roi
end
function testJacobianWithRandomROI(cls, v2)
--pooling grid size
local w=4;
local h=4;
--input size
local W=w*2;
local H=h*2;
local batchSize = 3
local numRoi = batchSize
local numRepeat = 3
torch.manualSeed(0)
for i=1,numRepeat do
local input = torch.rand(batchSize, 1, H, W);
local roi = randROI(input:size(), numRoi)
local module = cls.new(h, w, 1, roi)
module.v2 = v2
local err = jac.testJacobian(module, input, nil, nil, 1e-3)
mytester:assertlt(err, precision, 'error on ROIPooling '..(v2 and 'v2' or 'v1'))
end
end
function inntest.ROIPooling()
local FixedROIPooling, parent = torch.class('FixedROIPooling', 'inn.ROIPooling')
function FixedROIPooling:__init(W, H, s, roi)
self.roi = roi
parent.__init(self, W, H, s)
self:cuda()
end
function FixedROIPooling:updateOutput(input)
return parent.updateOutput(self,{input:cuda(), self.roi})
end
function FixedROIPooling:updateGradInput(input, gradOutput)
return parent.updateGradInput(self,{input:cuda(), self.roi}, gradOutput)[1]
end
testJacobianWithRandomROI(FixedROIPooling, true)
end
jac = nn.Jacobian
mytester:add(inntest)
mytester:run()
|
require 'inn'
local mytester = torch.Tester()
local jac
local precision = 1e-3
local inntest = torch.TestSuite()
function inntest.SpatialStochasticPooling()
local from = math.random(1,5)
local ki = math.random(1,4)
local kj = math.random(1,4)
local si = math.random(1,3)
local sj = math.random(1,3)
local outi = math.random(4,5)
local outj = math.random(4,5)
local ini = (outi-1)*si+ki
local inj = (outj-1)*sj+kj
local input = torch.rand(from,ini,inj):cuda()
local module = inn.SpatialStochasticPooling(ki,kj,si,sj):cuda()
module.updateOutput = function(...)
cutorch.manualSeed(11)
return inn.SpatialStochasticPooling.updateOutput(...)
end
local err = jac.testJacobian(module, input, nil, nil, 1e-3)
mytester:assertlt(err, precision, 'error on state ')
local ferr, berr = jac.testIO(module, input)
mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ')
mytester:assertlt(berr, 1e-6, torch.typename(module) .. ' - i/o backward err ')
-- batch
local nbatch = math.random(2,5)
input = torch.rand(nbatch,from,ini,inj):cuda()
local err = jac.testJacobian(module, input, nil, nil, 1e-3)
mytester:assertlt(err, precision, 'error on state (Batch) ')
local ferr, berr = jac.testIO(module, input)
mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err (Batch) ')
mytester:assertlt(berr, 1e-6, torch.typename(module) .. ' - i/o backward err (Batch) ')
end
function inntest.SpatialPyramidPooling()
local from = math.random(1,5)
local ki = math.random(1,4)
local kj = math.random(1,4)
local si = math.random(1,3)
local sj = math.random(1,3)
local outi = math.random(4,5)
local outj = math.random(4,5)
local ini = (outi-1)*si+ki
local inj = (outj-1)*sj+kj
local module = inn.SpatialPyramidPooling({4,4},{3,3})
local input = torch.rand(from,ini,inj)
local err = jac.testJacobian(module, input, nil, nil, 1e-3)
mytester:assertlt(err, precision, 'error on state ')
local ferr, berr = jac.testIO(module, input)
mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ')
mytester:assertlt(berr, 1e-6, torch.typename(module) .. ' - i/o backward err ')
-- batch
local nbatch = math.random(2,5)
input = torch.rand(nbatch,from,ini,inj)
module = inn.SpatialPyramidPooling({4,4},{3,3})
local err = jac.testJacobian(module, input, nil, nil, 1e-3)
mytester:assertlt(err, precision, 'error on state (Batch) ')
local ferr, berr = jac.testIO(module, input)
mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err (Batch) ')
mytester:assertlt(berr, 1e-6, torch.typename(module) .. ' - i/o backward err (Batch) ')
end
function inntest.SpatialSameResponseNormalization()
local from = 16
local inj = 2
local ini = inj
local module = inn.SpatialSameResponseNormalization(3, 5e-5, 0.75)
local input = torch.randn(from,inj,ini)
local err = jac.testJacobian(module,input,nil,nil,1e-3)
mytester:assertlt(err, precision, 'error on state ')
-- batch
local bs = 32
local input = torch.randn(bs,from,inj,ini)
local module = inn.SpatialSameResponseNormalization(3, 5e-5, 0.75)
local err = jac.testJacobian(module, input, nil, nil, 1e-3)
mytester:assertlt(err, precision, 'error on state (Batch) ')
end
function randROI(sz, n)
assert(sz:size()==4, "need 4d size")
local roi=torch.Tensor(n,5)
for i=1,n do
idx=torch.randperm(sz[1])[1]
y=torch.randperm(sz[3])[{{1,2}}]:sort()
x=torch.randperm(sz[4])[{{1,2}}]:sort()
roi[{i,{}}] = torch.Tensor({idx,x[1],y[1],x[2],y[2]})
end
return roi
end
function testJacobianWithRandomROI(cls, v2)
--pooling grid size
local w=4;
local h=4;
--input size
local W=w*2;
local H=h*2;
local batchSize = 3
local numRoi = batchSize
local numRepeat = 3
torch.manualSeed(0)
for i=1,numRepeat do
local input = torch.rand(batchSize, 1, H, W);
local roi = randROI(input:size(), numRoi)
local module = cls.new(h, w, 1, roi)
module.v2 = v2
local err = jac.testJacobian(module, input, nil, nil, 1e-3)
mytester:assertlt(err, precision, 'error on ROIPooling '..(v2 and 'v2' or 'v1'))
end
end
function inntest.ROIPooling()
local FixedROIPooling, parent = torch.class('FixedROIPooling', 'inn.ROIPooling')
function FixedROIPooling:__init(W, H, s, roi)
self.roi = roi
parent.__init(self, W, H, s)
self:cuda()
end
function FixedROIPooling:updateOutput(input)
return parent.updateOutput(self,{input:cuda(), self.roi})
end
function FixedROIPooling:updateGradInput(input, gradOutput)
return parent.updateGradInput(self,{input:cuda(), self.roi}, gradOutput)[1]
end
testJacobianWithRandomROI(FixedROIPooling, true)
end
jac = nn.Jacobian
mytester:add(inntest)
mytester:run()
|
fix stochastic pooling test
|
fix stochastic pooling test
|
Lua
|
bsd-3-clause
|
szagoruyko/imagine-nn
|
3c1b12820d9e15af28f4888c2bfe7852ce8d6a76
|
spec/config_spec.lua
|
spec/config_spec.lua
|
local config = require "luacheck.config"
local fs = require "luacheck.fs"
local cur_dir = fs.has_lfs and fs.lfs.currentdir()
local function nest(dir, func)
if fs.has_lfs then
local backed = false
local function back()
if not backed then
fs.lfs.chdir(cur_dir)
backed = true
end
end
finally(back)
fs.lfs.chdir(dir)
func()
back()
end
end
describe("config", function()
it("has default path", function()
assert.is_string(config.default_path)
end)
it("loads default config", function()
local conf = config.load_config()
assert.is_table(conf)
nest("spec/configs", function()
local nested_conf = config.load_config()
assert.is_table(nested_conf)
assert.same(config.get_top_options(conf), config.get_top_options(nested_conf))
assert.same(config.get_options(conf, "spec/foo.lua"), config.get_options(nested_conf, "../foo.lua"))
assert.equal("../../bar.lua", config.relative_path(nested_conf, "bar.lua"))
end)
assert.not_same(config.get_options(conf, "spec/foo_spec.lua"), config.get_options(conf, "foo_spec.lua"))
assert.equal("bar.lua", config.relative_path(conf, "bar.lua"))
end)
it("works with empty config", function()
local conf = config.empty_config
assert.is_table(conf)
assert.same({}, config.get_top_options(conf))
assert.same({}, config.get_options(conf, "bar.lua"))
assert.equal("bar.lua", config.relative_path(conf, "bar.lua"))
end)
it("loads config from path", function()
local conf = config.load_config("spec/configs/override_config.luacheckrc")
assert.is_table(conf)
nest("spec/configs/project", function()
local nested_conf = config.load_config("spec/configs/override_config.luacheckrc")
assert.is_table(nested_conf)
assert.same(config.get_top_options(conf), config.get_top_options(nested_conf))
assert.same(config.get_options(conf, "spec/samples/bad_code.lua"), config.get_options(nested_conf, "../../samples/bad_code.lua"))
assert.equal("../../../bar.lua", config.relative_path(nested_conf, "bar.lua"))
end)
assert.not_same(config.get_options(conf, "spec/samples/bad_code.lua"), config.get_options(conf, "spec/samples/unused_code.lua"))
assert.equal("bar.lua", config.relative_path(conf, "bar.lua"))
end)
it("returns nil, error on missing config", function()
local conf, err = config.load_config("spec/configs/config_404.luacheckrc")
assert.is_nil(conf)
assert.equal("Couldn't find configuration file spec/configs/config_404.luacheckrc", err)
end)
it("returns nil, error on config with bad syntax", function()
local conf, err = config.load_config("spec/configs/bad_config.luacheckrc")
assert.is_nil(conf)
assert.matches("Couldn't load configuration from spec/configs/bad_config.luacheckrc: syntax error %(line 2: .*%)", err)
nest("spec/configs/project", function()
local nested_conf, nested_err = config.load_config("spec/configs/bad_config.luacheckrc")
assert.is_nil(nested_conf)
assert.matches("Couldn't load configuration from ../../../spec/configs/bad_config.luacheckrc: syntax error %(line 2: .*%)", nested_err)
end)
end)
it("returns nil, error on config with runtime issues", function()
local conf, err = config.load_config("spec/configs/runtime_bad_config.luacheckrc")
assert.is_nil(conf)
assert.equal("Couldn't load configuration from spec/configs/runtime_bad_config.luacheckrc: runtime error (line 1: attempt to call a nil value)", err)
nest("spec/configs/project", function()
local nested_conf, nested_err = config.load_config("spec/configs/runtime_bad_config.luacheckrc")
assert.is_nil(nested_conf)
assert.equal("Couldn't load configuration from ../../../spec/configs/runtime_bad_config.luacheckrc: runtime error (line 1: attempt to call a nil value)", nested_err)
end)
end)
it("returns nil, error on invalid config", function()
local conf, err = config.load_config("spec/configs/invalid_config.luacheckrc")
assert.is_nil(conf)
assert.equal("Couldn't load configuration from spec/configs/invalid_config.luacheckrc: invalid value of option 'ignore'", err)
nest("spec/configs/project", function()
local nested_conf, nested_err = config.load_config("spec/configs/invalid_config.luacheckrc")
assert.is_nil(nested_conf)
assert.equal("Couldn't load configuration from ../../../spec/configs/invalid_config.luacheckrc: invalid value of option 'ignore'", nested_err)
end)
end)
it("returns nil, error on config with invalid override", function()
local conf, err = config.load_config("spec/configs/invalid_override_config.luacheckrc")
assert.is_nil(conf)
assert.equal("Couldn't load configuration from spec/configs/invalid_override_config.luacheckrc: invalid value of option 'enable' in options for path 'spec/foo.lua'", err)
nest("spec/configs/project", function()
local nested_conf, nested_err = config.load_config("spec/configs/invalid_override_config.luacheckrc")
assert.is_nil(nested_conf)
assert.equal("Couldn't load configuration from ../../../spec/configs/invalid_override_config.luacheckrc: invalid value of option 'enable' in options for path 'spec/foo.lua'", nested_err)
end)
end)
end)
|
local config = require "luacheck.config"
local fs = require "luacheck.fs"
local P = fs.normalize
local cur_dir = fs.has_lfs and fs.lfs.currentdir()
local function nest(dir, func)
if not fs.has_lfs then
pending("uses lfs")
end
local backed = false
local function back()
if not backed then
fs.lfs.chdir(cur_dir)
backed = true
end
end
finally(back)
fs.lfs.chdir(dir)
func()
back()
end
describe("config", function()
it("has default path", function()
assert.is_string(config.default_path)
end)
it("loads default config", function()
local conf = config.load_config()
assert.is_table(conf)
nest("spec/configs", function()
local nested_conf = config.load_config()
assert.is_table(nested_conf)
assert.same(config.get_top_options(conf), config.get_top_options(nested_conf))
assert.same(config.get_options(conf, P"spec/foo.lua"), config.get_options(nested_conf, P"../foo.lua"))
assert.equal(P"../../bar.lua", config.relative_path(nested_conf, "bar.lua"))
end)
assert.not_same(config.get_options(conf, P"spec/foo_spec.lua"), config.get_options(conf, "foo_spec.lua"))
assert.equal("bar.lua", config.relative_path(conf, "bar.lua"))
end)
it("works with empty config", function()
local conf = config.empty_config
assert.is_table(conf)
assert.same({}, config.get_top_options(conf))
assert.same({}, config.get_options(conf, "bar.lua"))
assert.equal("bar.lua", config.relative_path(conf, "bar.lua"))
end)
it("loads config from path", function()
local conf = config.load_config(P"spec/configs/override_config.luacheckrc")
assert.is_table(conf)
nest("spec/configs/project", function()
local nested_conf = config.load_config(P"spec/configs/override_config.luacheckrc")
assert.is_table(nested_conf)
assert.same(config.get_top_options(conf), config.get_top_options(nested_conf))
assert.same(
config.get_options(conf, P"spec/samples/bad_code.lua"),
config.get_options(nested_conf, P"../../samples/bad_code.lua")
)
assert.equal(P"../../../bar.lua", config.relative_path(nested_conf, "bar.lua"))
end)
assert.not_same(
config.get_options(conf, P"spec/samples/bad_code.lua"),
config.get_options(conf, P"spec/samples/unused_code.lua")
)
assert.equal("bar.lua", config.relative_path(conf, "bar.lua"))
end)
it("returns nil, error on missing config", function()
local conf, err = config.load_config(P"spec/configs/config_404.luacheckrc")
assert.is_nil(conf)
assert.equal("Couldn't find configuration file "..P"spec/configs/config_404.luacheckrc", err)
end)
it("returns nil, error on config with bad syntax", function()
local conf, err = config.load_config(P"spec/configs/bad_config.luacheckrc")
assert.is_nil(conf)
assert.matches("Couldn't load configuration from "..P"spec/configs/bad_config.luacheckrc"..
": syntax error %(line 2: .*%)", err)
nest("spec/configs/project", function()
local nested_conf, nested_err = config.load_config(P"spec/configs/bad_config.luacheckrc")
assert.is_nil(nested_conf)
assert.matches("Couldn't load configuration from "..P"../../../spec/configs/bad_config.luacheckrc"..
": syntax error %(line 2: .*%)", nested_err)
end)
end)
it("returns nil, error on config with runtime issues", function()
local conf, err = config.load_config(P"spec/configs/runtime_bad_config.luacheckrc")
assert.is_nil(conf)
assert.equal("Couldn't load configuration from "..P"spec/configs/runtime_bad_config.luacheckrc"..
": runtime error (line 1: attempt to call a nil value)", err)
nest("spec/configs/project", function()
local nested_conf, nested_err = config.load_config(P"spec/configs/runtime_bad_config.luacheckrc")
assert.is_nil(nested_conf)
assert.equal("Couldn't load configuration from "..P"../../../spec/configs/runtime_bad_config.luacheckrc"..
": runtime error (line 1: attempt to call a nil value)", nested_err)
end)
end)
it("returns nil, error on invalid config", function()
local conf, err = config.load_config(P"spec/configs/invalid_config.luacheckrc")
assert.is_nil(conf)
assert.equal("Couldn't load configuration from "..P"spec/configs/invalid_config.luacheckrc"..
": invalid value of option 'ignore'", err)
nest("spec/configs/project", function()
local nested_conf, nested_err = config.load_config(P"spec/configs/invalid_config.luacheckrc")
assert.is_nil(nested_conf)
assert.equal("Couldn't load configuration from "..P"../../../spec/configs/invalid_config.luacheckrc"..
": invalid value of option 'ignore'", nested_err)
end)
end)
it("returns nil, error on config with invalid override", function()
local conf, err = config.load_config(P"spec/configs/invalid_override_config.luacheckrc")
assert.is_nil(conf)
assert.equal("Couldn't load configuration from "..P"spec/configs/invalid_override_config.luacheckrc"..
": invalid value of option 'enable' in options for path 'spec/foo.lua'", err)
nest("spec/configs/project", function()
local nested_conf, nested_err = config.load_config(P"spec/configs/invalid_override_config.luacheckrc")
assert.is_nil(nested_conf)
assert.equal("Couldn't load configuration from "..P"../../../spec/configs/invalid_override_config.luacheckrc"..
": invalid value of option 'enable' in options for path 'spec/foo.lua'", nested_err)
end)
end)
end)
|
Windows compat fixes for config tests
|
Windows compat fixes for config tests
|
Lua
|
mit
|
linuxmaniac/luacheck,xpol/luacheck,linuxmaniac/luacheck,xpol/luacheck,xpol/luacheck,mpeterv/luacheck,mpeterv/luacheck,mpeterv/luacheck
|
e1eb96b01846674645cc882fb71cb9fd8b7b88b7
|
init.lua
|
init.lua
|
-- Alias various helper variables.
local opt = vim.opt -- Options.
local cmd = vim.cmd -- Vim commands.
-- Enable relative line numbers.
opt.number = true
opt.relativenumber = true
opt.scrolloff = 3
-- Highlight current line.
opt.cursorline = true
-- Ignore case in searches.
opt.ignorecase = true
-- Show the filename in the window titlebar.
opt.title = true
-- Tabs configuration.
opt.tabstop = 2
opt.shiftwidth = 2
opt.expandtab = true
-- Use smart indentation.
opt.smartindent = true
-- Load packages.
require('packer').startup(function()
use 'wbthomason/packer.nvim' -- package manager
use 'connorholyday/vim-snazzy' -- theme
use 'lukas-reineke/indent-blankline.nvim' -- indentation guides
use 'tpope/vim-fugitive' -- git
use 'airblade/vim-gitgutter' -- git gutter
use 'bling/vim-airline' -- status line
use 'vim-airline/vim-airline-themes' -- status line themes
end)
-- Configure theme.
cmd 'colorscheme snazzy'
-- Fix color scheme search highlight colors
cmd 'autocmd ColorScheme * highlight Search guibg=#ff6ac1'
cmd 'autocmd ColorScheme * highlight IncSearch guibg=#ff6ac1'
-- Configure indentation guides.
vim.g.indent_blankline_char = '│'
-- Configure status line.
opt.laststatus = 2
cmd([[
let g:airline_theme='base16_snazzy'
let g:airline_left_sep = ''
let g:airline_right_sep = ''
let g:airline_section_z = airline#section#create(['%3p%%', 'linenr', 'maxlinenr'])
if !exists('g:airline_symbols')
let g:airline_symbols = {}
endif
let g:airline_symbols.branch = ''
let g:airline_symbols.readonly = ''
let g:airline_symbols.linenr = ' Ξ '
let g:airline_symbols.notexists = '!'
let g:airline_symbols.maxlinenr = ' ¶'
]])
|
-- Alias various helper variables.
local opt = vim.opt -- Options.
local cmd = vim.cmd -- Vim commands.
-- Enable relative line numbers.
opt.number = true
opt.relativenumber = true
opt.scrolloff = 3
-- Highlight current line.
opt.cursorline = true
-- Ignore case in searches.
opt.ignorecase = true
-- Show the filename in the window titlebar.
opt.title = true
-- Tabs configuration.
opt.tabstop = 2
opt.shiftwidth = 2
opt.expandtab = true
-- Use smart indentation.
opt.smartindent = true
-- Load packages.
require('packer').startup(function()
use 'wbthomason/packer.nvim' -- package manager
use 'connorholyday/vim-snazzy' -- theme
use 'lukas-reineke/indent-blankline.nvim' -- indentation guides
use 'tpope/vim-fugitive' -- git
use 'airblade/vim-gitgutter' -- git gutter
use 'bling/vim-airline' -- status line
use 'vim-airline/vim-airline-themes' -- status line themes
end)
-- Configure theme.
cmd 'colorscheme snazzy'
cmd([[
hi Normal ctermbg=16 guibg=#121212
hi LineNr ctermbg=16 guibg=#121212 guifg=#383837
]])
-- Fix color scheme search highlight colors
cmd 'autocmd ColorScheme * highlight Search guibg=#ff6ac1'
cmd 'autocmd ColorScheme * highlight IncSearch guibg=#ff6ac1'
-- Configure indentation guides.
vim.g.indent_blankline_char = '│'
-- Configure status line.
opt.laststatus = 2
cmd([[
let g:airline_theme='base16_snazzy'
let g:airline_left_sep = ''
let g:airline_right_sep = ''
let g:airline_section_z = airline#section#create(['%3p%%', 'linenr', 'maxlinenr'])
if !exists('g:airline_symbols')
let g:airline_symbols = {}
endif
let g:airline_symbols.branch = ''
let g:airline_symbols.readonly = ''
let g:airline_symbols.linenr = ' Ξ '
let g:airline_symbols.notexists = '!'
let g:airline_symbols.maxlinenr = ' ¶'
]])
|
Fix neovim background color
|
Fix neovim background color
|
Lua
|
mit
|
HiDeoo/dotfiles
|
edbdbdfc5bacd861f51ad80e7e44a93d850267d5
|
vrp/client/admin.lua
|
vrp/client/admin.lua
|
-- https://github.com/ImagicTheCat/vRP
-- MIT license (see LICENSE or vrp/vRPShared.lua)
if not vRP.modules.admin then return end
local Admin = class("Admin", vRP.Extension)
-- METHODS
function Admin:__construct()
vRP.Extension.__construct(self)
self.noclip = false
self.noclip_speed = 1.0
-- noclip task
Citizen.CreateThread(function()
local Base = vRP.EXT.Base
while true do
Citizen.Wait(0)
if self.noclip then
local ped = GetPlayerPed(-1)
local x,y,z = Base:getPosition()
local dx,dy,dz = Base:getCamDirection()
local speed = self.noclip_speed
-- reset velocity
SetEntityVelocity(ped, 0.0001, 0.0001, 0.0001)
-- forward
if IsControlPressed(0,32) then -- MOVE UP
x = x+speed*dx
y = y+speed*dy
z = z+speed*dz
end
-- backward
if IsControlPressed(0,269) then -- MOVE DOWN
x = x-speed*dx
y = y-speed*dy
z = z-speed*dz
end
SetEntityCoordsNoOffset(ped,x,y,z,true,true,true)
end
end
end)
end
function Admin:toggleNoclip()
self.noclip = not self.noclip
local ped = GetPlayerPed(-1)
if self.noclip then -- set
SetEntityInvincible(ped, true)
SetEntityVisible(ped, false, false)
else -- unset
SetEntityInvincible(ped, false)
SetEntityVisible(ped, true, false)
end
end
-- ref: https://github.com/citizenfx/project-lambdamenu/blob/master/LambdaMenu/teleportation.cpp#L301
function Admin:teleportToMarker()
local ped = GetPlayerPed(-1)
-- find GPS blip
local it = GetBlipInfoIdIterator()
local blip = GetFirstBlipInfoId(it)
local ok, done
repeat
ok = DoesBlipExist(blip)
if ok then
if GetBlipInfoIdType(blip) == 4 then
ok = false
done = true
else
blip = GetNextBlipInfoId(it)
end
end
until not ok
if done then
local x,y = table.unpack(Citizen.InvokeNative(0xFA7C7F0AADF25D09, blip, Citizen.ResultAsVector())) -- GetBlipInfoIdCoord fix
local gz, ground = 0, false
for z=0,800,50 do
SetEntityCoordsNoOffset(ped, x+0.001, y+0.001, z+0.001, 0, 0, 1);
ground, gz = GetGroundZFor_3dCoord(x,y,z+0.001)
if ground then break end
end
if ground then
vRP.EXT.Base:teleport(x,y,gz+3)
else
vRP.EXT.Base:teleport(x,y,1000)
GiveDelayedWeaponToPed(ped, 0xFBAB5776, 1, 0)
end
end
end
-- TUNNEL
Admin.tunnel = {}
Admin.tunnel.toggleNoclip = Admin.toggleNoclip
Admin.tunnel.teleportToMarker = Admin.teleportToMarker
vRP:registerExtension(Admin)
|
-- https://github.com/ImagicTheCat/vRP
-- MIT license (see LICENSE or vrp/vRPShared.lua)
if not vRP.modules.admin then return end
local Admin = class("Admin", vRP.Extension)
-- METHODS
function Admin:__construct()
vRP.Extension.__construct(self)
self.noclip = false
self.noclip_speed = 1.0
-- noclip task
Citizen.CreateThread(function()
local Base = vRP.EXT.Base
while true do
Citizen.Wait(0)
if self.noclip then
local ped = GetPlayerPed(-1)
local x,y,z = Base:getPosition()
local dx,dy,dz = Base:getCamDirection()
local speed = self.noclip_speed
-- reset velocity
SetEntityVelocity(ped, 0.0001, 0.0001, 0.0001)
-- forward
if IsControlPressed(0,32) then -- MOVE UP
x = x+speed*dx
y = y+speed*dy
z = z+speed*dz
end
-- backward
if IsControlPressed(0,269) then -- MOVE DOWN
x = x-speed*dx
y = y-speed*dy
z = z-speed*dz
end
SetEntityCoordsNoOffset(ped,x,y,z,true,true,true)
end
end
end)
end
function Admin:toggleNoclip()
self.noclip = not self.noclip
local ped = GetPlayerPed(-1)
if self.noclip then -- set
SetEntityInvincible(ped, true)
SetEntityVisible(ped, false, false)
else -- unset
SetEntityInvincible(ped, false)
SetEntityVisible(ped, true, false)
end
end
-- ref: https://github.com/citizenfx/project-lambdamenu/blob/master/LambdaMenu/teleportation.cpp#L301
function Admin:teleportToMarker()
local ped = GetPlayerPed(-1)
-- find GPS blip
local it = GetBlipInfoIdIterator()
local blip = GetFirstBlipInfoId(it)
local ok, done
repeat
ok = DoesBlipExist(blip)
if ok then
if GetBlipInfoIdType(blip) == 4 then
ok = false
done = true
else
blip = GetNextBlipInfoId(it)
end
end
until not ok
if done then
local x,y = table.unpack(Citizen.InvokeNative(0xFA7C7F0AADF25D09, blip, Citizen.ResultAsVector())) -- GetBlipInfoIdCoord fix
local gz, ground = 0.0, false
for z=0,1000,5 do
SetEntityCoords(ped, x+0.0, y+0.0, z+0.0, 1,0,0,1)
Citizen.Wait(5)
ground, gz = GetGroundZFor_3dCoord(x + 0.0,y + 0.0,z + 0.0)
if ground then break end
end
if ground then
vRP.EXT.Base:teleport(x,y,gz+1.5)
else
vRP.EXT.Base:teleport(x,y,1000)
GiveDelayedWeaponToPed(ped, 0xFBAB5776, 1, 0)
end
end
end
-- TUNNEL
Admin.tunnel = {}
Admin.tunnel.toggleNoclip = Admin.toggleNoclip
Admin.tunnel.teleportToMarker = Admin.teleportToMarker
vRP:registerExtension(Admin)
|
Update admin.lua
|
Update admin.lua
Fix TpTopMarker socorrectly find ground
|
Lua
|
mit
|
ImagicTheCat/vRP,ImagicTheCat/vRP
|
8db5579f84e06b0f4eb278a72e58d052d807d768
|
Core.lua
|
Core.lua
|
local L = EPGPGlobalStrings
EPGP = AceLibrary("AceAddon-2.0"):new("AceConsole-2.0", "AceDB-2.0", "AceDebug-2.0", "AceEvent-2.0", "AceModuleCore-2.0")
-------------------------------------------------------------------------------
-- DB defaults
-------------------------------------------------------------------------------
EPGP:RegisterDB("EPGP_Core_DB", "EPGP_Core_PerCharDB")
EPGP:RegisterDefaults("profile", {
report_channel = "GUILD",
current_listing = "GUILD",
RAID = {
show_alts = true,
},
GUILD = {
show_alts = false,
},
GUILD_ONLINE_LABEL = {
show_alts = true,
},
gp_in_tooltips = true,
boss_tracking = true,
loot_tracking = true,
loot_tracking_quality_threshold = 4, -- Epic and above
loot_announce = true,
reason_award_cache = {},
alts = {},
outsiders = {},
dummies = {},
data = {},
info = {},
base_gp = 0,
flat_credentials = false,
min_eps = 1000,
decay_percent = 10,
backup_notes = {},
recurring_ep_period = 15 * 60,
})
function EPGP:OnInitialize()
local backend = self:GetModule("EPGP_Backend")
EPGPFrameTitleText:SetText(GetAddOnMetadata("epgp", "Title").." "..GetAddOnMetadata("epgp", "Version"))
self:RegisterChatCommand({ "/epgp" }, {
type = "group",
desc = L["EPGP Options"],
args = {
["show"] = {
type = "execute",
name = L["Show UI"],
desc = L["Shows the EPGP UI"],
disabled = function() return EPGPFrame:IsShown() end,
func = function() ShowUIPanel(EPGPFrame) end,
order = 1,
},
["decay"] = {
type = "execute",
name = L["Decay EP and GP"],
desc = string.format(L["Decay EP and GP by %d%%"], EPGP.db.profile.decay_percent),
disabled = function() return not backend:CanLogRaids() end,
func = function() StaticPopup_Show("EPGP_DECAY_EPGP", EPGP.db.profile.decay_percent) end,
order = 4,
},
["reset"] = {
type = "execute",
name = L["Reset EPGP"],
desc = L["Reset all EP and GP to 0 and make officer notes readable by all."],
guiHidden = true,
disabled = function() return not backend:CanChangeRules() end,
func = function() StaticPopup_Show("EPGP_RESET_EPGP") end,
order = 11,
},
},
},
"EPGP")
end
function EPGP:OnEnable()
--EPGP:SetDebugging(true)
BINDING_HEADER_EPGP = L["EPGP Options"]
BINDING_NAME_EPGP = L["Toggle EPGP UI"]
-- Set shift-E as the toggle button if it is not bound
if #GetBindingAction("J") == 0 then
SetBinding("J", "EPGP")
end
end
|
local L = EPGPGlobalStrings
EPGP = AceLibrary("AceAddon-2.0"):new("AceConsole-2.0", "AceDB-2.0", "AceDebug-2.0", "AceEvent-2.0", "AceModuleCore-2.0")
-------------------------------------------------------------------------------
-- DB defaults
-------------------------------------------------------------------------------
EPGP:RegisterDB("EPGP_Core_DB", "EPGP_Core_PerCharDB")
EPGP:RegisterDefaults("profile", {
report_channel = "GUILD",
current_listing = "GUILD",
RAID = {
show_alts = true,
},
GUILD = {
show_alts = false,
},
GUILD_ONLINE_LABEL = {
show_alts = true,
},
gp_in_tooltips = true,
boss_tracking = true,
loot_tracking = true,
loot_tracking_quality_threshold = 4, -- Epic and above
loot_announce = true,
reason_award_cache = {},
alts = {},
outsiders = {},
dummies = {},
data = {},
info = {},
base_gp = 0,
flat_credentials = false,
min_eps = 1000,
decay_percent = 10,
backup_notes = {},
recurring_ep_period = 15 * 60,
})
function EPGP:OnInitialize()
local backend = self:GetModule("EPGP_Backend")
EPGPFrameTitleText:SetText(GetAddOnMetadata("epgp", "Title").." "..GetAddOnMetadata("epgp", "Version"))
self:RegisterChatCommand({ "/epgp" }, {
type = "group",
desc = L["EPGP Options"],
args = {
["show"] = {
type = "execute",
name = L["Show UI"],
desc = L["Shows the EPGP UI"],
disabled = function() return EPGPFrame:IsShown() end,
func = function() ShowUIPanel(EPGPFrame) end,
order = 1,
},
["decay"] = {
type = "execute",
name = L["Decay EP and GP"],
desc = string.format(L["Decay EP and GP by %d%%"], EPGP.db.profile.decay_percent),
disabled = function() return not backend:CanLogRaids() end,
func = function() StaticPopup_Show("EPGP_DECAY_EPGP", EPGP.db.profile.decay_percent) end,
order = 4,
},
["reset"] = {
type = "execute",
name = L["Reset EPGP"],
desc = L["Reset all EP and GP to 0 and make officer notes readable by all."],
guiHidden = true,
disabled = function() return not backend:CanChangeRules() end,
func = function() StaticPopup_Show("EPGP_RESET_EPGP") end,
order = 11,
},
},
},
"EPGP")
end
function EPGP:OnEnable()
--EPGP:SetDebugging(true)
BINDING_HEADER_EPGP = L["EPGP Options"]
BINDING_NAME_EPGP = L["Toggle EPGP UI"]
-- Set shift-E as the toggle button if it is not bound
if #GetBindingAction("J") == 0 then
SetBinding("J", "EPGP")
end
end
|
Fix indentation.
|
Fix indentation.
|
Lua
|
bsd-3-clause
|
sheldon/epgp,protomech/epgp-dkp-reloaded,hayword/tfatf_epgp,protomech/epgp-dkp-reloaded,hayword/tfatf_epgp,sheldon/epgp,ceason/epgp-tfatf,ceason/epgp-tfatf
|
5510c0e87d5fbef5512b42473ecb6ce255737424
|
script/c80600029.lua
|
script/c80600029.lua
|
--ヴァンパイア・ソーサラー
function c80600029.initial_effect(c)
--to grave
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_DELAY+EFFECT_FLAG_DAMAGE_STEP)
e1:SetCode(EVENT_TO_GRAVE)
e1:SetCondition(c80600029.condition)
e1:SetTarget(c80600029.target)
e1:SetOperation(c80600029.operation)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(80600029,0))
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_GRAVE)
e2:SetCost(c80600029.ntcost)
e2:SetOperation(c80600029.ntop)
c:RegisterEffect(e2)
end
function c80600029.condition(e,tp,eg,ep,ev,re,r,rp)
return rp~=tp
end
function c80600029.filter(c)
return (
c:IsAttribute(ATTRIBUTE_DARK) or
c:IsType(TYPE_SPELL) or
c:IsType(TYPE_TRAP)
)
and c:IsAbleToHand() and c:IsSetCard(0x92)
end
function c80600029.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c80600029.filter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c80600029.operation(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c80600029.filter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
function c80600029.ntcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsAbleToRemoveAsCost() end
Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_COST)
end
function c80600029.ntop(e,tp,eg,ep,ev,re,r,rp)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_DECREASE_TRIBUTE)
e1:SetTargetRange(LOCATION_HAND,0)
e1:SetTarget(c80600029.rfilter)
e1:SetCountLimit(1)
e1:SetValue(0x2)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
end
function c80600029.rfilter(e,c)
return c:IsSetCard(0x92)
end
|
--ヴァンパイア・ソーサラー
function c80600029.initial_effect(c)
--to grave
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_DELAY+EFFECT_FLAG_DAMAGE_STEP)
e1:SetCode(EVENT_TO_GRAVE)
e1:SetCondition(c80600029.condition)
e1:SetTarget(c80600029.target)
e1:SetOperation(c80600029.operation)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(80600029,0))
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_GRAVE)
e2:SetCost(c80600029.ntcost)
e2:SetOperation(c80600029.ntop)
c:RegisterEffect(e2)
end
function c80600029.condition(e,tp,eg,ep,ev,re,r,rp)
return rp~=tp and (r==REASON_EFFECT or r==REASON_BATTLE)
end
function c80600029.filter(c)
return (
c:IsAttribute(ATTRIBUTE_DARK) or
c:IsType(TYPE_SPELL) or
c:IsType(TYPE_TRAP)
)
and c:IsAbleToHand() and c:IsSetCard(0x92)
end
function c80600029.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c80600029.filter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c80600029.operation(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c80600029.filter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
function c80600029.ntcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsAbleToRemoveAsCost() end
Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_COST)
end
function c80600029.ntop(e,tp,eg,ep,ev,re,r,rp)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_DECREASE_TRIBUTE)
e1:SetTargetRange(LOCATION_HAND,0)
e1:SetTarget(c80600029.rfilter)
e1:SetCountLimit(1)
e1:SetValue(0x2)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
end
function c80600029.rfilter(e,c)
return c:IsSetCard(0x92)
end
|
fix
|
fix
fixed lava golem interaction
|
Lua
|
mit
|
sidschingis/DevProLauncher,Tic-Tac-Toc/DevProLauncher,SuperAndroid17/DevProLauncher
|
49e8863450ff5fc23333ae23a8c25bc93954ecbd
|
src/sounds/src/Shared/SoundUtils.lua
|
src/sounds/src/Shared/SoundUtils.lua
|
--[=[
Helps plays back sounds in the Roblox engine.
```lua
SoundUtils.playFromId("rbxassetid://4255432837") -- Plays a wooshing sound
```
@class SoundUtils
]=]
local require = require(script.Parent.loader).load(script)
local SoundService = game:GetService("SoundService")
local RunService = game:GetService("RunService")
local SoundPromiseUtils = require("SoundPromiseUtils")
local SoundUtils = {}
--[=[
Plays back a template given asset id.
```lua
SoundUtils.playFromId("rbxassetid://4255432837") -- Plays a wooshing sound
```
:::tip
The sound will be automatically cleaned up after the sound is played.
:::
@param id string | number
@return Sound
]=]
function SoundUtils.playFromId(id)
local soundId = SoundUtils.toRbxAssetId(id)
assert(type(soundId) == "string", "Bad id")
local sound = Instance.new("Sound")
sound.Name = ("Sound_%s"):format(soundId)
sound.SoundId = soundId
sound.Volume = 0.25
sound.Archivable = false
if RunService:IsClient() then
SoundService:PlayLocalSound(sound)
else
sound:Play()
end
SoundUtils.removeAfterTimeLength(sound)
return sound
end
--[=[
Plays back a template given asset id in the parent
@param id string | number
@param parent Instance
@return Sound
]=]
function SoundUtils.playFromIdInParent(id, parent)
assert(typeof(parent) == "Instance", "Bad parent")
local soundId = SoundUtils.toRbxAssetId(id)
assert(type(soundId) == "string", "Bad id")
local sound = Instance.new("Sound")
sound.Name = ("Sound_%s"):format(soundId)
sound.SoundId = soundId
sound.Volume = 0.25
sound.Archivable = false
sound.Parent = parent
if not RunService:IsRunning() then
SoundService:PlayLocalSound(sound)
else
sound:Play()
end
SoundUtils.removeAfterTimeLength(sound)
return sound
end
--[=[
Loads the sound and then cleans up the sound after load.
@param sound Sound
]=]
function SoundUtils.removeAfterTimeLength(sound)
-- TODO: clean up on destroying
SoundPromiseUtils.promiseLoaded(sound):Then(function()
task.delay(sound.TimeLength + 0.05, function()
sound:Destroy()
end)
end, function()
sound:Destroy()
end)
end
--[=[
Plays back a template given the templateName.
:::tip
The sound will be automatically cleaned up after the sound is played.
:::
@param templates TemplateProvider
@param templateName string
@return Sound
]=]
function SoundUtils.playTemplate(templates, templateName)
assert(type(templates) == "table", "Bad templates")
assert(type(templateName) == "string", "Bad templateName")
local sound = templates:Clone(templateName)
sound.Archivable = false
SoundService:PlayLocalSound(sound)
SoundUtils.removeAfterTimeLength(sound)
return sound
end
--[=[
Converts a string or number to a string for playback.
@param id string | number
@return string
]=]
function SoundUtils.toRbxAssetId(id)
if type(id) == "number" then
return ("rbxassetid://%d"):format(id)
else
return id
end
end
--[=[
Plays back a sound template in a specific parent.
:::tip
The sound will be automatically cleaned up after the sound is played.
:::
@param templates TemplateProvider
@param templateName string
@param parent Instance
@return Sound
]=]
function SoundUtils.playTemplateInParent(templates, templateName, parent)
local sound = templates:Clone(templateName)
sound.Archivable = false
sound.Parent = parent
sound:Play()
SoundUtils.removeAfterTimeLength(sound)
return sound
end
return SoundUtils
|
--[=[
Helps plays back sounds in the Roblox engine.
```lua
SoundUtils.playFromId("rbxassetid://4255432837") -- Plays a wooshing sound
```
@class SoundUtils
]=]
local require = require(script.Parent.loader).load(script)
local SoundService = game:GetService("SoundService")
local RunService = game:GetService("RunService")
local SoundPromiseUtils = require("SoundPromiseUtils")
local SoundUtils = {}
--[=[
Plays back a template given asset id.
```lua
SoundUtils.playFromId("rbxassetid://4255432837") -- Plays a wooshing sound
```
:::tip
The sound will be automatically cleaned up after the sound is played.
:::
@param id string | number
@return Sound
]=]
function SoundUtils.playFromId(id)
local soundId = SoundUtils.toRbxAssetId(id)
assert(type(soundId) == "string", "Bad id")
local sound = SoundUtils.createSoundFromId(id)
if RunService:IsClient() then
SoundService:PlayLocalSound(sound)
else
sound:Play()
end
SoundUtils.removeAfterTimeLength(sound)
return sound
end
--[=[
Creates a new sound object from the given id
]=]
function SoundUtils.createSoundFromId(id)
local soundId = SoundUtils.toRbxAssetId(id)
assert(type(soundId) == "string", "Bad id")
local sound = Instance.new("Sound")
sound.Name = ("Sound_%s"):format(soundId)
sound.SoundId = soundId
sound.Volume = 0.25
sound.Archivable = false
return sound
end
--[=[
Plays back a template given asset id in the parent
@param id string | number
@param parent Instance
@return Sound
]=]
function SoundUtils.playFromIdInParent(id, parent)
assert(typeof(parent) == "Instance", "Bad parent")
local sound = SoundUtils.createSoundFromId(id)
sound.Parent = parent
if not RunService:IsRunning() then
SoundService:PlayLocalSound(sound)
else
sound:Play()
end
SoundUtils.removeAfterTimeLength(sound)
return sound
end
--[=[
Loads the sound and then cleans up the sound after load.
@param sound Sound
]=]
function SoundUtils.removeAfterTimeLength(sound)
-- TODO: clean up on destroying
SoundPromiseUtils.promiseLoaded(sound):Then(function()
task.delay(sound.TimeLength + 0.05, function()
sound:Destroy()
end)
end, function()
sound:Destroy()
end)
end
--[=[
Plays back a template given the templateName.
:::tip
The sound will be automatically cleaned up after the sound is played.
:::
@param templates TemplateProvider
@param templateName string
@return Sound
]=]
function SoundUtils.playTemplate(templates, templateName)
assert(type(templates) == "table", "Bad templates")
assert(type(templateName) == "string", "Bad templateName")
local sound = templates:Clone(templateName)
sound.Archivable = false
SoundService:PlayLocalSound(sound)
SoundUtils.removeAfterTimeLength(sound)
return sound
end
--[=[
Converts a string or number to a string for playback.
@param id string | number
@return string
]=]
function SoundUtils.toRbxAssetId(id)
if type(id) == "number" then
return ("rbxassetid://%d"):format(id)
else
return id
end
end
--[=[
Plays back a sound template in a specific parent.
:::tip
The sound will be automatically cleaned up after the sound is played.
:::
@param templates TemplateProvider
@param templateName string
@param parent Instance
@return Sound
]=]
function SoundUtils.playTemplateInParent(templates, templateName, parent)
local sound = templates:Clone(templateName)
sound.Archivable = false
sound.Parent = parent
sound:Play()
SoundUtils.removeAfterTimeLength(sound)
return sound
end
return SoundUtils
|
fix: Sounds can be played back from parents, and we can create sounds without playing them
|
fix: Sounds can be played back from parents, and we can create sounds without playing them
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
884b3a4b0bf719d7ad1756860e02e84a7c10cd2d
|
tests/test-timer.lua
|
tests/test-timer.lua
|
--[[
Copyright 2012 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
require("helper")
local os = require('os')
local timer = require('timer')
local math = require('math')
expect("timeout")
timer.setTimeout(200, function (arg1)
fulfill("timeout")
assert(arg1 == 'test1')
end, "test1")
expect("interval")
local count = 0
local interval
interval = timer.setInterval(200, function(arg1)
count = count + 1
assert(arg1 == 'test2')
if count == 2 then
fulfill("interval")
timer.clearTimer(interval)
end
end, 'test2')
--
-- nextTick
local zeroTimeoutTriggered = false
timer.setTimeout(500, function()
zeroTimeoutTriggered = true
end)
-- nextTick
local zeroTimeoutTriggered2 = false
timer.setTimeout(500, function()
zeroTimeoutTriggered2 = true
end)
-- test cancelled timer
local cancelledTimerTriggered = false
local cancelledTimer = timer.setTimeout(10000, function()
cancelledTimerTriggered = true
end)
timer.clearTimer(cancelledTimer)
-- test recursive timer
function calcJitter(n, jitter)
return math.floor(n + (jitter * math.random()))
end
local recursiveTimerCount = 0
local recursiveTime = 0
local st = 0
function start()
local timeout = 2000
st = os.time()
return timer.setTimeout(timeout, function()
recursiveTimerCount = recursiveTimerCount + 1
recursiveTime = recursiveTime + os.time() - st
if recursiveTimerCount < 3 then
start()
end
end)
end
start()
process:on('exit', function()
assert(zeroTimeoutTriggered == true)
assert(zeroTimeoutTriggered2 == true)
assert(cancelledTimerTriggered == false)
assert(recursiveTimerCount == 3)
assert(recursiveTime >= 6)
end)
|
--[[
Copyright 2012 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
require("helper")
local os = require('os')
local timer = require('timer')
local math = require('math')
expect("timeout")
timer.setTimeout(200, function (arg1)
fulfill("timeout")
assert(arg1 == 'test1')
end, "test1")
expect("interval")
local count = 0
local interval
interval = timer.setInterval(200, function(arg1)
count = count + 1
assert(arg1 == 'test2')
if count == 2 then
fulfill("interval")
timer.clearTimer(interval)
end
end, 'test2')
--
-- nextTick
local zeroTimeoutTriggered = false
timer.setTimeout(500, function()
zeroTimeoutTriggered = true
end)
-- nextTick
local zeroTimeoutTriggered2 = false
timer.setTimeout(500, function()
zeroTimeoutTriggered2 = true
end)
-- test cancelled timer
local cancelledTimerTriggered = false
local cancelledTimer = timer.setTimeout(10000, function()
cancelledTimerTriggered = true
end)
timer.clearTimer(cancelledTimer)
-- test recursive timer
function calcJitter(n, jitter)
return math.floor(n + (jitter * math.random()))
end
local counter = 0
local timeoutId1
local timeoutId2
local timeoutId3
-- Test two timers closing at the same time caused expiration() to call close on
-- the wrong timer
local function schedule()
timeoutId2 = timer.setTimeout(200, function()
end)
timeoutId1 = timer.setTimeout(200, function()
timer.clearTimer(timeoutId2)
counter = counter + 1
if counter < 4 then
schedule()
end
end)
end
schedule()
local recursiveTimerCount = 0
local recursiveTime = 0
local st = 0
function start()
local timeout = 2000
st = os.time()
return timer.setTimeout(timeout, function()
recursiveTimerCount = recursiveTimerCount + 1
recursiveTime = recursiveTime + os.time() - st
if recursiveTimerCount < 3 then
start()
end
end)
end
start()
process:on('exit', function()
assert(zeroTimeoutTriggered == true)
assert(zeroTimeoutTriggered2 == true)
assert(cancelledTimerTriggered == false)
assert(recursiveTimerCount == 3)
assert(recursiveTime >= 6)
end)
|
Add a test which demonstrates the problem and fails before my fix (4a6e25394fc53f572f49300b02bc9335eeeba126).
|
Add a test which demonstrates the problem and fails before my fix
(4a6e25394fc53f572f49300b02bc9335eeeba126).
|
Lua
|
apache-2.0
|
GabrielNicolasAvellaneda/luvit-upstream,boundary/luvit,GabrielNicolasAvellaneda/luvit-upstream,luvit/luvit,kaustavha/luvit,rjeli/luvit,kaustavha/luvit,rjeli/luvit,boundary/luvit,DBarney/luvit,zhaozg/luvit,bsn069/luvit,sousoux/luvit,GabrielNicolasAvellaneda/luvit-upstream,bsn069/luvit,rjeli/luvit,zhaozg/luvit,boundary/luvit,DBarney/luvit,GabrielNicolasAvellaneda/luvit-upstream,kaustavha/luvit,sousoux/luvit,sousoux/luvit,boundary/luvit,boundary/luvit,rjeli/luvit,DBarney/luvit,luvit/luvit,sousoux/luvit,sousoux/luvit,bsn069/luvit,sousoux/luvit,boundary/luvit,DBarney/luvit
|
b37f05d837a1b57cae56955dabd21088e8817c88
|
tests/test_vflip.lua
|
tests/test_vflip.lua
|
require 'totem'
require 'image'
myTests = {}
local tester = totem.Tester()
-- List of all possible tests
local all_tests = {}
function all_tests.test_transformation_largeByteImage(flip)
local x_real = image.fabio():double():mul(255)
local x_byte = x_real:clone():byte()
assert(x_byte:size(1) > 256 and x_byte:size(2) > 256, 'Tricky case only occurs for images larger than 256 px, pick another example')
local f_real, f_byte
f_real = image[flip](x_real)
f_byte = image[flip](x_byte)
tester:assertTensorEq(f_real:byte():double(), f_byte:double(), 1e-16, flip .. ': result for double and byte images do not match')
end
-- Apply all tests to both vflip and hflip
for _, flip in pairs{'vflip', 'hflip'} do
for name, test in pairs(all_tests) do
myTests[name .. '_' .. flip] = function() return test(flip) end
end
end
tester:add(myTests)
return tester:run(myTests)
|
require 'totem'
require 'image'
myTests = {}
local tester = totem.Tester()
-- List of all possible tests
local all_tests = {}
function all_tests.test_transformation_largeByteImage(flip)
local x_real = image.fabio():double():mul(255)
local x_byte = x_real:clone():byte()
assert(x_byte:size(1) > 256 and x_byte:size(2) > 256, 'Tricky case only occurs for images larger than 256 px, pick another example')
local f_real, f_byte
f_real = image[flip](x_real)
f_byte = image[flip](x_byte)
tester:assertTensorEq(f_real:byte():double(), f_byte:double(), 1e-16, flip .. ': result for double and byte images do not match')
end
function all_tests.test_inplace(flip)
local im = image.lena()
local not_inplace = image.hflip(im)
local in_place = im:clone()
image[flip](in_place, in_place)
tester:assertTensorEq(in_place, not_inplace, 1e-16, flip .. ': result in-place does not match result not in-place')
end
-- Apply all tests to both vflip and hflip
for _, flip in pairs{'vflip', 'hflip'} do
for name, test in pairs(all_tests) do
myTests[name .. '_' .. flip] = function() return test(flip) end
end
end
tester:add(myTests)
return tester:run(myTests)
|
Add failing test case for in-place vflip
|
Add failing test case for in-place vflip
Thanks to @jonathantompson for spotting the bug, see issue #27
|
Lua
|
bsd-3-clause
|
jagapiou/image,torch/image,colesbury/image,Moodstocks/image,jonathantompson/image
|
8191a0a8e3a4e00beccace52ed241a6e142d2352
|
modules/more.lua
|
modules/more.lua
|
return {
PRIVMSG = {
['^%pmore$'] = function(self, source, destination, module)
local more = self.more[destination]
if more then
self:Msg('privmsg', destination, source, more)
end
end,
['^%pmore%?$'] = function(self, source, destination, module)
local more = self.more[destination]
if more then
self:Msg('privmsg', destination, source, 'There are %s more bytes.', #more)
else
self:Msg('privmsg', destination, source, 'There is no more!')
end
end,
},
}
|
return {
PRIVMSG = {
['^%pmore$'] = function(self, source, destination, module)
if(destination == self.config.nick) then
destination = source.nick
end
local more = self.more[destination]
if more then
self:Msg('privmsg', destination, source, more)
end
end,
['^%pmore%?$'] = function(self, source, destination, module)
if(destination == self.config.nick) then
destination = source.nick
end
local more = self.more[destination]
if more then
self:Msg('privmsg', destination, source, 'There are %s more bytes.', #more)
else
self:Msg('privmsg', destination, source, 'There is no more!')
end
end,
},
}
|
more: fix module to not only work on channels
|
more: fix module to not only work on channels
Former-commit-id: 462720e4c1ed43262b2dc48373de80cd08fe6e8e [formerly d82319b781e06d69ff0bbfa17239adfe0e31e3d5]
Former-commit-id: e7aef2ec2e0e7fd3ac2380a756fa117945e1a9cd
|
Lua
|
mit
|
haste/ivar2,torhve/ivar2,torhve/ivar2,torhve/ivar2
|
631cdde959180a933a75f73317768009d4348381
|
KSFramework/Product/Lua/UI/UILogin/UILogin.lua
|
KSFramework/Product/Lua/UI/UILogin/UILogin.lua
|
---@type UILogin
local UILogin = {}
extends(UILogin, UIBase)
-- Maybe you have many `UILogin` instance? create a new function!
-- Always write a New function is best practices
function UILogin.New(controller)
local newUILogin = new(UILogin)
newUILogin.Controller = controller
return newUILogin
end
---测试场景数组
local scenes = { "Scene/Scene1001/Scene1001", "Scene/Scene1002/Scene1002" }
-- controller also pass to OnInit function
function UILogin:OnInit(controller)
self.sceneIndex = 1
print("================================ UILogin:OnInit ============================")
---多语言示例,从语言表中读取
-- self.LoginText from LuaOutlet
--self.LoginText.text = I18N.Str("UILogin.LoginDescText")
Tools.SetButton(self.btnSwithScene, function()
self.sceneIndex = self.sceneIndex == 1 and 2 or 1
SceneLoader.Load(scenes[self.sceneIndex], function(isOK)
if not isOK then
return print("SceneLoader.Load faild")
end
print("switch scene success")
end, LoaderMode.Async)
end)
Tools.SetButton(self.btnBillboard, function()
print('Click the button!!!')
UIModule.Instance:OpenWindow("UIBillboard")
end)
Tools.SetButton(self.btnSwithUI, function()
UIModule.Instance:CloseWindow("UILogin")
UIModule.Instance:OpenWindow("UIMain", "user1")
end)
Tools.SetButton(self.btnLoadSprite, function()
UIModule.Instance:OpenWindow("UILoadUISprite")
end)
end
function UILogin:OnOpen(num1)
print("UILogin:OnOpen, arg1: " .. tostring(num1))
UIModule.Instance:OpenWindow("UINavbar")
UIModule.Instance:OpenWindow("UIMain", 888);
if AppSettings then
using("AppSettings") -- namespace all
print("================================ Read settings throught Lua ============================")
for config in foreach(GameConfigSettings.GetAll()) do
print(string.format("Lua Read Setting, Id: %s, Value: %s", config.Id, config.Value))
end
else
print("Not found AppSettings, maybe no static code generate yet")
end
local openCount
openCount = Cookie.Get('UILogin.OpenCount')
if not openCount then
openCount = 0
end
openCount = openCount + 1
Cookie.Set('UILogin.OpenCount', openCount)
self:TestJson()
print('Test cookie, Reload UI use (Ctrl+Alt+Shift+R)... UI Open Count: ' .. tostring(openCount))
end
function UILogin:OnClose()
print(self.btnTest)
print(self.sceneIndex)
end
function UILogin:TestJson()
--table转成json
local lua_table = {
a = "hello",
b = "ksframework",
c = 2020,
d = "2020", }
local json_str = table.table2JsonString(lua_table)
print("lua table to json string ---->"..json_str)
local t = table.jsonStr2Table("{\"name\":\"ksframework\",\"year\":2020}")
print("json string to lua table----> table.name:"..t.name)
t.a = 456
end
return UILogin
|
---@type UILogin
local UILogin = {}
extends(UILogin, UIBase)
-- Maybe you have many `UILogin` instance? create a new function!
-- Always write a New function is best practices
function UILogin.New(controller)
local newUILogin = new(UILogin)
newUILogin.Controller = controller
return newUILogin
end
---测试场景数组
local scenes = { "Scene/Scene1001/Scene1001", "Scene/Scene1002/Scene1002" }
-- controller also pass to OnInit function
function UILogin:OnInit(controller)
self.sceneIndex = 1
print("================================ UILogin:OnInit ============================")
---多语言示例,从语言表中读取
-- self.LoginText from LuaOutlet
--self.LoginText.text = I18N.Str("UILogin.LoginDescText")
Tools.SetButton(self.btnSwithScene, function()
self.sceneIndex = self.sceneIndex == 1 and 2 or 1
SceneLoader.Load(scenes[self.sceneIndex], function(isOK)
if not isOK then
return print("SceneLoader.Load faild")
end
print("switch scene success")
end, LoaderMode.Async)
end)
Tools.SetButton(self.btnBillboard, function()
print('Click the button!!!')
UIModule.Instance:OpenWindow("UIBillboard")
end)
Tools.SetButton(self.btnSwithUI, function()
UIModule.Instance:CloseWindow("UILogin")
UIModule.Instance:OpenWindow("UIMain", "user1")
end)
Tools.SetButton(self.btnLoadSprite, function()
UIModule.Instance:OpenWindow("UILoadUISprite")
end)
end
function UILogin:OnOpen(num1)
print("UILogin:OnOpen, arg1: " .. tostring(num1))
UIModule.Instance:OpenWindow("UINavbar")
UIModule.Instance:OpenWindow("UIMain", 888);
if AppSettings then
using("AppSettings") -- namespace all
print("================================ Read settings throught Lua ============================")
for config in foreach(GameConfigSettings.GetAll()) do
print(string.format("Lua Read Setting, Id: %s, Value: %s", config.Id, config.Value))
end
else
print("Not found AppSettings, maybe no static code generate yet")
end
local openCount
openCount = Cookie.Get('UILogin.OpenCount')
if not openCount then
openCount = 0
end
openCount = openCount + 1
Cookie.Set('UILogin.OpenCount', openCount)
self:TestJson()
print('Test cookie, Reload UI use (Ctrl+Alt+Shift+R)... UI Open Count: ' .. tostring(openCount))
end
function UILogin:OnClose()
print(string.format("btnBillboard=%s ,sceneIndex=%s",self.btnBillboard,self.sceneIndex))
end
function UILogin:TestJson()
--table转成json
local lua_table = {
a = "hello",
b = "ksframework",
c = 2020,
d = "2020", }
local json_str = table.table2JsonString(lua_table)
print("lua table to json string ---->"..json_str)
local t = table.jsonStr2Table("{\"name\":\"ksframework\",\"year\":2020}")
print("json string to lua table----> table.name:"..t.name)
t.a = 456
end
return UILogin
|
fixed lua log
|
fixed lua log
|
Lua
|
apache-2.0
|
mr-kelly/KSFramework,mr-kelly/KSFramework,mr-kelly/KSFramework,mr-kelly/KSFramework
|
8cb5229c14374e35a394e2637e972b21484c6e8a
|
commands/serve.lua
|
commands/serve.lua
|
local args = {...}
return function ()
local createServer = require('coro-net').createServer
local uv = require('uv')
local httpCodec = require('http-codec')
local websocketCodec = require('websocket-codec')
local wrapIo = require('coro-websocket').wrapIo
local log = require('log').log
local makeRemote = require('codec').makeRemote
local core = require('core')()
local handlers = require('handlers')(core)
local handleRequest = require('api')(core.db, args[2])
-- Ignore SIGPIPE if it exists on platform
if uv.constants.SIGPIPE then
uv.new_signal():start("sigpipe")
end
createServer({
host = "0.0.0.0",
port = 4822,
decode = httpCodec.decoder(),
encode = httpCodec.encoder(),
}, function (read, write, socket, updateDecoder, updateEncoder, close)
local function upgrade(res)
write(res)
-- Upgrade the protocol to websocket
updateDecoder(websocketCodec.decode)
updateEncoder(websocketCodec.encode)
read, write = wrapIo(read, write, { mask = false })
-- Log the client connection
local peerName = socket:getpeername()
peerName = peerName.ip .. ':' .. peerName.port
log("client connected", peerName)
-- Proces the client using server handles
local remote = makeRemote(read, write)
local success, err = xpcall(function ()
for command, data in remote.read do
log("client command", peerName .. " - " .. command)
local handler = handlers[command]
if handler then
handler(remote, data)
else
remote.writeAs("error", "no such command " .. command)
end
end
end, debug.traceback)
if not success then
log("client error", err, "err")
remote.writeAs("error", string.match(err, ":%d+: *([^\n]*)"))
remote.close()
end
log("client disconnected", peerName)
end
for req in read do
local body = {}
for chunk in read do
if #chunk == 0 then break end
body[#body + 1] = chunk
end
local res, err = websocketCodec.handleHandshake(req, "lit")
if res then return upgrade(res) end
body = table.concat(body)
if req.method == "GET" or req.method == "HEAD" then
req.body = #body > 0 and body or nil
local now = uv.now()
res, err = handleRequest(req)
local delay = (uv.now() - now) .. "ms"
res[#res + 1] = {"X-Request-Time", delay}
print(req.method .. " " .. req.path .. " " .. res.code .. " " .. delay)
end
if not res then
write({code=400})
write(err or "lit websocket request required")
return write()
end
write(res)
write(res.body)
end
end)
-- Never return so that the command keeps running.
coroutine.yield()
end
|
local args = {...}
return function ()
local createServer = require('coro-net').createServer
local uv = require('uv')
local httpCodec = require('http-codec')
local websocketCodec = require('websocket-codec')
local wrapIo = require('coro-websocket').wrapIo
local log = require('log').log
local makeRemote = require('codec').makeRemote
local core = require('core')()
local handlers = require('handlers')(core)
local handleRequest = require('api')(core.db, args[2])
-- Ignore SIGPIPE if it exists on platform
if uv.constants.SIGPIPE then
uv.new_signal():start("sigpipe")
end
createServer({
host = "0.0.0.0",
port = 4822,
decode = httpCodec.decoder(),
encode = httpCodec.encoder(),
}, function (read, write, socket, updateDecoder, updateEncoder, close)
local function upgrade(res)
write(res)
-- Upgrade the protocol to websocket
updateDecoder(websocketCodec.decode)
updateEncoder(websocketCodec.encode)
read, write = wrapIo(read, write, { mask = false })
-- Log the client connection
local peerName = socket:getpeername()
peerName = peerName.ip .. ':' .. peerName.port
log("client connected", peerName)
-- Proces the client using server handles
local remote = makeRemote(read, write)
local success, err = xpcall(function ()
for command, data in remote.read do
log("client command", peerName .. " - " .. command)
local handler = handlers[command]
if handler then
handler(remote, data)
else
remote.writeAs("error", "no such command " .. command)
end
end
end, debug.traceback)
if not success then
log("client error", err, "err")
remote.writeAs("error", string.match(err, ":%d+: *([^\n]*)"))
remote.close()
end
log("client disconnected", peerName)
end
for req in read do
local body = {}
for chunk in read do
if #chunk == 0 then break end
body[#body + 1] = chunk
end
local res, err = websocketCodec.handleHandshake(req, "lit")
if res then return upgrade(res) end
body = table.concat(body)
if req.method == "GET" or req.method == "HEAD" then
req.body = #body > 0 and body or nil
local now = uv.now()
res, err = handleRequest(req)
local delay = (uv.now() - now) .. "ms"
res[#res + 1] = {"X-Request-Time", delay}
print(req.method .. " " .. req.path .. " " .. res.code .. " " .. delay)
end
if not res then
write({code=400})
write(err or "lit websocket request required")
write()
if not socket:is_closing() then
socket:close()
end
return
end
write(res)
write(res.body)
end
write()
end)
-- Never return so that the command keeps running.
coroutine.yield()
end
|
Fix resource leak in lit server
|
Fix resource leak in lit server
|
Lua
|
apache-2.0
|
luvit/lit,zhaozg/lit,squeek502/lit,james2doyle/lit
|
254e62cfdb8dc453bd2bfb7c6f560a9bdc4a405a
|
packages/ubus-tmate/files/usr/lib/lua/tmate.lua
|
packages/ubus-tmate/files/usr/lib/lua/tmate.lua
|
#!/usr/bin/env lua
--[[ Copyright (C) 2013-2020 LibreMesh.org
This is free software, licensed under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3
]]--
local TMATE_SOCK = "/tmp/tmate.sock"
local TMATE_CONFIG = "/etc/tmate/tmate.conf"
local tmate = {}
function tmate.cmd_as_str(cmd)
final_cmd = "tmate -f "..TMATE_CONFIG.." -S "..TMATE_SOCK.." "..cmd
return utils.unsafe_shell(final_cmd)
end
local function unix_socket_listening(name)
return "" ~= utils.unsafe_shell("netstat -xl | grep "..TMATE_SOCK.." 2>/dev/null")
end
function tmate.session_running()
return unix_socket_listening(TMATE_SOCK)
end
function tmate.get_rw_session()
return tmate.cmd_as_str("display -p '#{tmate_ssh}'"):sub(1, -2)
end
function tmate.get_ro_session()
return tmate.cmd_as_str("display -p '#{tmate_ssh_ro}'"):sub(1, -2)
end
function tmate.get_connected_clients()
return tmate.cmd_as_str("display -p '#{tmate_num_clients}'"):sub(1, -2)
end
function tmate.open_session()
tmate.cmd_as_str("new-session -d")
end
function tmate.wait_session_ready()
tmate.cmd_as_str("wait tmate-ready")
end
function tmate.close_session()
tmate.cmd_as_str("kill-session -t 0")
end
return tmate
|
#!/usr/bin/env lua
--[[ Copyright (C) 2013-2020 LibreMesh.org
This is free software, licensed under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3
]]--
local utils = require 'lime.utils'
local TMATE_SOCK = "/tmp/tmate.sock"
local TMATE_CONFIG = "/etc/tmate/tmate.conf"
local tmate = {}
function tmate.cmd_as_str(cmd)
final_cmd = "tmate -f "..TMATE_CONFIG.." -S "..TMATE_SOCK.." "..cmd
return utils.unsafe_shell(final_cmd)
end
local function unix_socket_listening(name)
return "" ~= utils.unsafe_shell("netstat -xl | grep "..TMATE_SOCK.." 2>/dev/null")
end
function tmate.session_running()
return unix_socket_listening(TMATE_SOCK)
end
function tmate.get_rw_session()
return tmate.cmd_as_str("display -p '#{tmate_ssh}'"):sub(1, -2)
end
function tmate.get_ro_session()
return tmate.cmd_as_str("display -p '#{tmate_ssh_ro}'"):sub(1, -2)
end
function tmate.get_connected_clients()
return tmate.cmd_as_str("display -p '#{tmate_num_clients}'"):sub(1, -2)
end
function tmate.open_session()
tmate.cmd_as_str("new-session -d")
end
function tmate.wait_session_ready()
tmate.cmd_as_str("wait tmate-ready")
end
function tmate.close_session()
tmate.cmd_as_str("kill-session -t 0")
end
return tmate
|
ubus-tmate: fix missing import
|
ubus-tmate: fix missing import
|
Lua
|
agpl-3.0
|
libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages
|
569c48f40ede4a9729aaa7abe78e995acb20f8d9
|
src_trunk/resources/global/zone_globals.lua
|
src_trunk/resources/global/zone_globals.lua
|
gezn = getElementZoneName
-- custom areas
local hospitalcol = createColCuboid( 1520, 1750, 2070, 100, 80, 30 )
setElementInterior( hospitalcol, 4 )
local custommaps =
{
[ hospitalcol ] = { 'All Saints General Hospital', 'Los Santos' }
}
-- caching to improve efficiency
local cache = { [true] = {}, [false] = {} }
function getElementZoneName( element, citiesonly )
if citiesonly ~= true and citiesonly ~= false then citiesonly = false end
-- check for hospital
for col, name in pairs( custommaps ) do
if getElementDimension( element ) == getElementDimension( col ) and getElementInterior( element ) == getElementInterior( col ) and isElementWithinColShape( element, col ) then
return citiesonly and name[2] or name[1]
end
end
if not cache[citiesonly][ getElementDimension( element ) ] then
name = ''
if getElementDimension( element ) > 0 then
if citiesonly then
local parent = exports['interior-system']:findParent( element )
if parent then
name = getElementZoneName( parent, citiesonly, true )
end
else
local dimension, entrance = exports['interior-system']:findProperty( element )
if entrance then
name = getElementData( entrance, 'name' )
end
end
else
name = gezn( element, citiesonly ), gezn( element, not citiesonly )
end
cache[citiesonly][ getElementDimension( element ) ] = name
return name
else
return cache[citiesonly][ getElementDimension( element ) ]
end
end
|
gezn = getElementZoneName
-- custom areas
local hospitalcol = createColCuboid( 1520, 1750, 2070, 100, 80, 30 )
setElementInterior( hospitalcol, 4 )
local custommaps =
{
[ hospitalcol ] = { 'All Saints General Hospital', 'Los Santos' }
}
-- caching to improve efficiency
local cache = { [true] = {}, [false] = {} }
function getElementZoneName( element, citiesonly )
if citiesonly ~= true and citiesonly ~= false then citiesonly = false end
-- check for hospital
for col, name in pairs( custommaps ) do
if getElementDimension( element ) == getElementDimension( col ) and getElementInterior( element ) == getElementInterior( col ) and isElementWithinColShape( element, col ) then
return citiesonly and name[2] or name[1]
end
end
if not cache[citiesonly][ getElementDimension( element ) ] then
name = ''
if getElementDimension( element ) > 0 then
if citiesonly then
local parent = exports['interior-system']:findParent( element )
if parent then
name = getElementZoneName( parent, citiesonly, true )
end
else
local dimension, entrance = exports['interior-system']:findProperty( element )
if entrance then
name = getElementData( entrance, 'name' )
end
end
cache[citiesonly][ getElementDimension( element ) ] = name
else
name = gezn( element, citiesonly ), gezn( element, not citiesonly )
end
return name
else
return cache[citiesonly][ getElementDimension( element ) ]
end
end
|
fixed /district
|
fixed /district
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1929 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.